-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpp_args.hpp
More file actions
1126 lines (983 loc) · 39.6 KB
/
cpp_args.hpp
File metadata and controls
1126 lines (983 loc) · 39.6 KB
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef ARGUMENT_PARSER_HPP
#define ARGUMENT_PARSER_HPP
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <ostream>
#include <set>
#include <sstream>
#include <string>
#include <vector>
namespace cppargs {
/**
* @brief Parse result status for option parsing
*/
enum class ParseResult {
Success, // Successfully parsed
Failed, // Failed to parse (e.g., invalid value) - option was recognized
NotAnOption // This is not the type of option we're looking for
};
/**
* @brief Option metadata.
*/
struct Option {
int id;
std::string longName; // Raw name from macro (e.g. "log_lvl")
std::string shortName; // e.g. "l"
std::string help;
std::set<std::string> allowed;
// Option feature using bit flags (one-hot encoding):
// - SEPARATE: value separate from option (space or '=')
// - JOINED: value attached directly to option name
// - FLAG: no value required
// - SHORT: long option can be used with single dash (e.g., -help)
// Can be combined: SEPARATE | JOINED = both formats supported
enum Feature {
FEAT_SEPARATE = 1, // Bit 0: separate format support (--option value)
FEAT_FLAG = 2, // Bit 1: flag (no value)
FEAT_JOINED = 4, // Bit 2: joined format support (--optionvalue)
FEAT_HIDDEN = 8, // Bit 3: Hidden option (will not be printed in help)
FEAT_SHORT =
16, // Bit 4: Long option also accepts single dash (e.g., -help)
FEAT_EQ_JOIN = 32 // Bit 5: equals join format support (--option=value)
};
int feature; // Changed to int to support bit combinations
// Helper to check if feature has specific flag
bool HasFeature(int flag) const { return (feature & flag) != 0; }
// Group ID for grouping options in help output
int groupId;
// Helper: Normalize name by converting _ to -
static std::string Normalize(std::string str) {
for (char &c : str)
if (c == '_')
c = '-';
return str;
}
};
using OptionTable = std::vector<Option>;
struct OptionGroup {
int id;
std::string name;
};
using OptionGroupTable = std::vector<OptionGroup>;
/**
* @brief Alias mapping: maps alias names to option IDs
*/
struct AliasEntry {
std::string aliasName; // The long alias name (e.g., "save_temps")
std::string shortAliasName; // The short alias name (e.g., "st"), can be empty
std::string optionName; // The actual option name it maps to (e.g., "keep")
};
using AliasTable = std::vector<AliasEntry>;
/**
* @brief Alias lookup map for efficient runtime lookup
* Maps normalized alias name -> option name
*/
using AliasMap = std::map<std::string, std::string>;
class ArgumentParser {
public:
explicit ArgumentParser(const OptionTable &table)
: optionTable(table), allowUnknown(false) {}
/**
* @brief Constructor with option groups support
* @param table The option table
* @param groups The option group table
*/
ArgumentParser(const OptionTable &table, const OptionGroupTable &groups)
: optionTable(table), optionGroups(groups), allowUnknown(false) {}
/**
* @brief Set alias table for option name aliases
* @param aliasTable The alias table mapping alias names to option IDs
*/
void SetAliasTable(const AliasTable &aliasTable) {
this->aliasTable = aliasTable;
// Build lookup map for efficient runtime lookup
aliasMap.clear();
for (const auto &alias : aliasTable) {
// Map long alias name (normalized)
std::string normLongAlias = Option::Normalize(alias.aliasName);
aliasMap[normLongAlias] = alias.optionName;
// Map short alias name if present
if (!alias.shortAliasName.empty()) {
aliasMap[alias.shortAliasName] = alias.optionName;
}
}
}
/**
* @brief Fuzzy parsing: treats "_" and "-" as identical.
* Supports joined options where value is attached to the option name
* Remaining arguments after known options are treated as inputs
*/
bool Parse(int argc, char *argv[]) {
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
// Check if this looks like an option (starts with - or --)
bool isOption = (arg.size() > 0 && arg[0] == '-');
// If it doesn't look like an option, treat it as input
if (!isOption) {
inputs.push_back(arg);
continue;
}
// Try parsing in order of specificity:
// 1. Flag (no value needed)
ParseResult flagResult = ParseFlag(arg);
if (flagResult == ParseResult::Success) {
continue;
} else if (flagResult == ParseResult::Failed) {
// Option was recognized but failed (e.g., invalid value)
return false;
}
// NotAnOption - continue to next parser
// 2. Separate format (--option value)
ParseResult separateResult = ParseSeparate(arg, i, argc, argv);
if (separateResult == ParseResult::Success) {
continue;
} else if (separateResult == ParseResult::Failed) {
// Option was recognized but failed (e.g., missing/invalid value)
return false;
}
// NotAnOption - continue to next parser
// 3. Equals join format (--option=value)
ParseResult eqJoinResult = ParseEqJoin(arg);
if (eqJoinResult == ParseResult::Success) {
continue;
} else if (eqJoinResult == ParseResult::Failed) {
// Option was recognized but failed (e.g., invalid value)
return false;
}
// NotAnOption - continue to next parser
// 4. Joined format (--optionvalue or -Ivalue)
ParseResult joinedResult = ParseJoined(arg);
if (joinedResult == ParseResult::Success) {
continue;
} else if (joinedResult == ParseResult::Failed) {
// Option was recognized but failed (e.g., invalid value)
return false;
}
// NotAnOption - continue to unknown handling
// Unknown option - not recognized by any parser
unknownArgs.push_back(arg);
if (!allowUnknown) {
std::string suggestion = FindSimilarOption(arg);
if (!suggestion.empty()) {
std::cerr << "Error: Unknown argument '" << arg << "'. Did you mean '"
<< suggestion << "'?" << std::endl;
} else {
std::cerr << "Error: Unknown argument '" << arg << "'" << std::endl;
}
return false;
}
}
return true;
}
bool HasArg(int id) const { return parsedArgs.find(id) != parsedArgs.end(); }
/**
* @brief Get the value of an option (returns last value if specified multiple
* times)
* @param id The option enum ID (e.g., OPT_port)
* @param defaultValue Default value to return if the option is not provided
* @return The option value, or defaultValue if not provided
*/
std::string GetArgValue(int id, const std::string &defaultValue = "") const {
auto it = parsedArgs.find(id);
if (it != parsedArgs.end() && !it->second.empty()) {
return it->second.back(); // Return last value for backward compatibility
}
return defaultValue;
}
/**
* @brief Get all values of an option (if specified multiple times)
* @param id The option enum ID (e.g., OPT_port)
* @return Vector of all values, or empty vector if not provided
*/
const std::vector<std::string> &GetAllArgValues(int id) const {
static const std::vector<std::string> emptyVec;
auto it = parsedArgs.find(id);
return (it != parsedArgs.end()) ? it->second : emptyVec;
}
/**
* @brief Get the list of positional inputs (non-option arguments)
*/
const std::vector<std::string> &GetInputs() const { return inputs; }
/**
* @brief Set whether to allow unknown options without error
* @param allow If true, unknown options are stored but don't cause parse
* failure
*/
void SetAllowUnknown(bool allow) { allowUnknown = allow; }
/**
* @brief Get the list of unknown options
* @return Vector of unknown option strings
*/
const std::vector<std::string> &GetUnknown() const { return unknownArgs; }
/**
* @brief Find the most similar option name to the given input
* @param input The misspelled or unknown option name (e.g. "--verbos" or
* "-vve")
* @return The most similar valid option name with prefix (e.g. "--verbose"),
* or empty string if no similar option found
*/
std::string FindSimilarOption(const std::string &input) const {
if (input.empty())
return "";
// Extract the name part (without prefix and potential value)
std::string cleanInput = input;
// Remove any joined value (after '=' or attached to short option)
size_t eqPos = cleanInput.find('=');
if (eqPos != std::string::npos) {
cleanInput = cleanInput.substr(0, eqPos);
}
std::string normInput = Option::Normalize(cleanInput);
std::string bestMatch;
int minDistance = std::numeric_limits<int>::max();
for (const auto &opt : optionTable) {
int distance;
std::string candidate;
// For long options, compare against normalized long name
std::string normLongName;
if (opt.HasFeature(Option::FEAT_SHORT)) {
normLongName = "-" + Option::Normalize(opt.longName);
} else {
normLongName = "--" + Option::Normalize(opt.longName);
}
distance = LevenshteinDistance(normInput, normLongName);
candidate = normLongName;
// Also consider short name if it exists and might be a better match
if (!opt.shortName.empty()) {
int shortDistance = LevenshteinDistance(normInput, "-" + opt.shortName);
if (shortDistance < distance) {
distance = shortDistance;
candidate = "-" + opt.shortName;
}
}
if (opt.HasFeature(Option::FEAT_EQ_JOIN)) {
candidate += "=";
}
if (distance < minDistance) {
minDistance = distance;
bestMatch = candidate;
}
}
// Only return suggestion if it's reasonably close (threshold based on input
// length)
int threshold = std::max(2, (int)normInput.length() / 2);
return (minDistance <= threshold) ? bestMatch : "";
}
/**
* @brief Get the group ID for a given option ID
* @param optionId The option enum value (e.g., OPT_host)
* @return The group ID, or -1 if not found or no groups defined
*/
int GetGroupId(int optionId) const {
for (const auto &opt : optionTable) {
if (opt.id == optionId) {
return opt.groupId;
}
}
return -1;
}
/**
* @brief Render an option back to command-line format based on parse results
* @param optionId The option enum value to render
* @param renderArgs Output vector to append rendered arguments
*
* This function reconstructs command-line arguments from parsed values.
* Rendering strategy based on option type:
* - SEPARATE (only): Uses space-separated format (--option value)
* - JOINED (only): Uses joined format (--optionvalue)
* - SEPARATE | JOINED: Uses space-separated format by default (--option
* value)
* - FLAG | SHORT: Uses single dash format (-option)
* - SEPARATE | SHORT: Uses single dash format with space-separated value
* (-option value)
* - FLAG (no SHORT): Uses double dash format (--option)
* For options with multiple values, each value is rendered separately.
*/
void Render(int optionId, std::vector<std::string> &renderArgs) const {
// Find the option in the table
const Option *opt = nullptr;
for (const auto &o : optionTable) {
if (o.id == optionId) {
opt = &o;
break;
}
}
if (!opt) {
return; // Option not found
}
// Check if this option was parsed
auto it = parsedArgs.find(optionId);
if (it == parsedArgs.end()) {
return; // Option was not specified
}
const auto &values = it->second;
std::string normalizedName = Option::Normalize(opt->longName);
// Determine rendering format based on option type
bool isFlag = opt->HasFeature(Option::FEAT_FLAG);
bool hasShortFeature = opt->HasFeature(Option::FEAT_SHORT);
bool isJoinedOnly = opt->HasFeature(Option::FEAT_JOINED) &&
!opt->HasFeature(Option::FEAT_SEPARATE) &&
!opt->HasFeature(Option::FEAT_EQ_JOIN);
bool hasEqJoin = opt->HasFeature(Option::FEAT_EQ_JOIN);
bool hasSeparate = opt->HasFeature(Option::FEAT_SEPARATE);
// Rendering priority:
// 1. If has SEPARATE feature, use space-separated format (--option value)
// 2. Else if has EQ_JOIN feature, use equals format (--option=value)
// 3. Else if pure JOINED, use joined format (--optionvalue)
// Render each value occurrence
for (size_t i = 0; i < values.size(); ++i) {
if (isFlag) {
// For flags with SHORT feature, use single dash format (-option)
// For normal flags, use double dash format (--option)
if (hasShortFeature) {
renderArgs.push_back("-" + normalizedName);
} else {
renderArgs.push_back("--" + normalizedName);
}
} else if (hasShortFeature && hasSeparate) {
// For SEPARATE|SHORT options, use single dash with space-separated
// value
renderArgs.push_back("-" + normalizedName);
renderArgs.push_back(values[i]);
} else if (hasShortFeature && hasEqJoin && !hasSeparate) {
// For EQ_JOIN|SHORT (without SEPARATE) options, use single dash with
// equals format
renderArgs.push_back("-" + normalizedName + "=" + values[i]);
} else if (hasShortFeature) {
// Fallback for other SHORT combinations
renderArgs.push_back("-" + normalizedName);
renderArgs.push_back(values[i]);
} else if (isJoinedOnly) {
// For pure JOINED options (not SEPARATE|JOINED or EQ_JOIN|JOINED),
// render as --optionvalue
if (!values[i].empty()) {
renderArgs.push_back("--" + normalizedName + values[i]);
} else {
// Edge case: empty value for joined option
renderArgs.push_back("--" + normalizedName);
}
} else if (hasEqJoin && !hasSeparate) {
// For EQ_JOIN or EQ_JOIN|JOINED options (without SEPARATE), render as
// --option=value
renderArgs.push_back("--" + normalizedName + "=" + values[i]);
} else {
// For SEPARATE or SEPARATE|JOINED or SEPARATE|EQ_JOIN options, render
// as --option value (space-separated)
renderArgs.push_back("--" + normalizedName);
renderArgs.push_back(values[i]);
}
}
}
virtual void PrintHelp(int wrappedWidth = 100) const {
// Check if we have groups defined
if (optionGroups.empty()) {
// Print all options without grouping
for (const auto &opt : optionTable) {
printOption(&opt, wrappedWidth);
}
} else {
// Group options by groupId
std::map<int, std::vector<const Option *>> groupedOptions;
std::vector<const Option *> ungroupedOptions;
for (const auto &opt : optionTable) {
// If the option's group has an empty name, treat it as ungrouped
bool isUngrouped =
(opt.groupId < 0 ||
opt.groupId >= static_cast<int>(optionGroups.size()) ||
optionGroups[opt.groupId].name.empty());
if (!isUngrouped) {
groupedOptions[opt.groupId].push_back(&opt);
} else {
ungroupedOptions.push_back(&opt);
}
}
// Print ungrouped options first
bool hasUngrouped = !ungroupedOptions.empty();
for (const auto *opt : ungroupedOptions) {
printOption(opt, wrappedWidth);
}
// Print grouped options
bool firstGroup = true;
for (const auto &group : groupedOptions) {
int groupId = group.first;
const auto &options = group.second;
// Skip if group ID is out of range
if (groupId >= static_cast<int>(optionGroups.size()))
continue;
// Add separator before each group (except possibly the first)
if (!firstGroup || hasUngrouped) {
std::cout << std::endl;
}
firstGroup = false;
// Print group header if we have a group name
if (!optionGroups[groupId].name.empty()) {
std::cout << optionGroups[groupId].name << ":" << std::endl;
std::cout << std::string(wrappedWidth, '=') << std::endl;
}
for (const auto *opt : options) {
printOption(opt, wrappedWidth);
}
}
}
}
private:
virtual void printOption(const Option *opt, int wrappedWidth = 100) const {
if (opt->HasFeature(Option::FEAT_HIDDEN)) {
return;
}
// brief = longName [kind] [allow values]
// For FEAT_SHORT options, show both --option and -option formats
std::string brief;
if (opt->HasFeature(Option::FEAT_SHORT)) {
brief = "-" + Option::Normalize(opt->longName);
} else {
brief = "--" + Option::Normalize(opt->longName);
}
if (opt->HasFeature(Option::FEAT_FLAG)) {
brief += " [flag]";
}
if (opt->HasFeature(Option::FEAT_EQ_JOIN)) {
brief += "=";
}
if (!opt->allowed.empty()) {
brief += " [Values: ";
for (auto it = opt->allowed.begin(); it != opt->allowed.end(); ++it) {
if (brief.size() >= wrappedWidth / 2) {
brief += "|...";
break;
}
brief += (it == opt->allowed.begin() ? "" : "|");
brief += *it;
}
brief += "]";
}
std::cout << std::left << std::setw(wrappedWidth - 30) << brief;
if (!opt->shortName.empty()) {
std::cout << "(-" << Option::Normalize(opt->shortName) << ")";
}
std::cout << std::endl;
std::istringstream iss(opt->help);
std::string word;
std::string line;
while (iss >> word) {
if (!line.empty() && line.length() + 1 + word.length() >
static_cast<size_t>(wrappedWidth - 4)) {
std::cout << " " << line << std::endl;
line = word;
} else {
if (line.empty()) {
line = word;
} else {
line += " " + word;
}
}
}
if (!line.empty()) {
std::cout << " " << line << std::endl;
}
// print alias
for (const auto &it : aliasTable) {
if (it.optionName == opt->longName) {
if (it.aliasName.empty()) {
// only short alias name
std::cout << std::left << std::setw(wrappedWidth - 30)
<< ("-" + it.shortAliasName);
} else {
std::cout << std::left << std::setw(wrappedWidth - 30)
<< ("--" + it.aliasName);
if (!it.shortAliasName.empty()) {
std::cout << "(-" << it.shortAliasName << ")";
}
}
std::cout << std::endl;
std::cout << " Alias for " << "--"
<< Option::Normalize(opt->longName) << std::endl;
}
}
}
const Option *FindOption(const std::string &input) const {
if (input.empty())
return nullptr;
// Strip prefix (-- or -) and normalize the input
std::string cleanInput = input;
bool isSingleDash = false;
bool isDoubleDash = false;
if (cleanInput.find("--") == 0) {
cleanInput = cleanInput.substr(2);
isDoubleDash = true;
} else if (cleanInput.find("-") == 0) {
cleanInput = cleanInput.substr(1);
isSingleDash = true;
}
std::string normInput = Option::Normalize(cleanInput);
for (const auto &opt : optionTable) {
// Match short name ONLY with single dash format
if (isSingleDash && opt.shortName == normInput)
return &opt;
// For FEAT_SHORT options with single dash, match long name
// This allows -help but NOT --help for FLAG|SHORT options
if (isSingleDash && opt.HasFeature(Option::FEAT_SHORT) &&
Option::Normalize(opt.longName) == normInput) {
return &opt;
}
// For normal options (without FEAT_SHORT), match long name with double
// dash Or match long name regardless of dash type for non-FEAT_SHORT
// options
if (!opt.HasFeature(Option::FEAT_SHORT) &&
Option::Normalize(opt.longName) == normInput) {
return &opt;
}
}
// If not found, check alias map (efficient O(log n) lookup)
auto it = aliasMap.find(normInput);
if (it != aliasMap.end()) {
std::string normOptionName = Option::Normalize(it->second);
// Check if this is a short alias by searching the alias table
bool isShortAlias = false;
bool isLongAlias = false;
for (const auto &alias : aliasTable) {
if (!alias.shortAliasName.empty() &&
alias.shortAliasName == normInput) {
isShortAlias = true;
break;
}
// Check if this matches a long alias
if (Option::Normalize(alias.aliasName) == normInput) {
isLongAlias = true;
break;
}
}
// Short aliases require single dash format
if (isShortAlias && !isSingleDash) {
return nullptr;
}
// Long aliases require double dash format
if (isLongAlias && !isDoubleDash) {
return nullptr;
}
// Find the option by its name (from alias map value)
for (const auto &opt : optionTable) {
if (Option::Normalize(opt.longName) == normOptionName) {
return &opt;
}
}
}
return nullptr;
}
const Option *FindOptionByShortName(const std::string &shortName) const {
for (const auto &opt : optionTable) {
if (opt.shortName == shortName)
return &opt;
}
// Check alias map (efficient O(log n) lookup)
auto it = aliasMap.find(shortName);
if (it != aliasMap.end()) {
std::string normOptionName = Option::Normalize(it->second);
for (const auto &opt : optionTable) {
if (Option::Normalize(opt.longName) == normOptionName ||
opt.shortName == normOptionName) {
return &opt;
}
}
}
return nullptr;
}
const Option *FindOptionByLongName(const std::string &longName) const {
std::string normName = Option::Normalize(longName);
for (const auto &opt : optionTable) {
if (Option::Normalize(opt.longName) == normName)
return &opt;
}
// Check alias map (efficient O(log n) lookup)
auto it = aliasMap.find(normName);
if (it != aliasMap.end()) {
std::string normOptionName = Option::Normalize(it->second);
for (const auto &opt : optionTable) {
if (Option::Normalize(opt.longName) == normOptionName ||
opt.shortName == normOptionName) {
return &opt;
}
}
}
return nullptr;
}
/**
* @brief Parse flag options (--flag or -flag for FEAT_SHORT)
* @param arg The argument string
* @return ParseResult indicating success, failure, or not this type
*/
ParseResult ParseFlag(const std::string &arg) {
const Option *opt = FindOption(arg);
// For FEAT_SHORT options, also check single dash format
if (!opt && arg.find("-") == 0 && arg.find("--") != 0) {
opt = FindOption(arg);
}
if (opt && opt->HasFeature(Option::FEAT_FLAG)) {
parsedArgs[opt->id].push_back("");
return ParseResult::Success;
}
return ParseResult::NotAnOption;
}
/**
* @brief Parse separate format options (--option value or -option value for
* FEAT_SHORT)
* @param arg The argument string
* @param i Current index in argv (will be incremented if value is consumed)
* @param argc Argument count
* @param argv Argument vector
* @return ParseResult indicating success, failure, or not this type
*/
ParseResult ParseSeparate(const std::string &arg, int &i, int argc,
char *argv[]) {
const Option *opt = FindOption(arg);
if (opt && opt->HasFeature(Option::FEAT_SEPARATE)) {
if (i + 1 >= argc) {
std::cerr << "Error: Missing value for " << arg << std::endl;
return ParseResult::Failed;
}
std::string value = argv[++i];
if (!opt->allowed.empty() &&
opt->allowed.find(value) == opt->allowed.end()) {
std::cerr << "Error: Invalid value '" << value << "' for " << arg
<< std::endl;
return ParseResult::Failed;
}
parsedArgs[opt->id].push_back(value);
return ParseResult::Success;
}
return ParseResult::NotAnOption;
}
/**
* @brief Parse equals join format options (--option=value or -option=value
* for FEAT_SHORT)
* @param arg The argument string
* @return ParseResult indicating success, failure, or not this type
*/
ParseResult ParseEqJoin(const std::string &arg) {
size_t eqPos = arg.find('=');
if (eqPos == std::string::npos) {
return ParseResult::NotAnOption;
}
std::string namePart;
std::string value = arg.substr(eqPos + 1);
const Option *opt = nullptr;
if (arg.find("--") == 0) {
// Long format: --option=value
namePart = arg.substr(2, eqPos - 2);
opt = FindOptionByLongName(namePart);
if (!opt) {
// Try with full argument for FEAT_SHORT options
opt = FindOption(arg.substr(0, eqPos));
}
} else if (arg.find("-") == 0) {
// Short format: -option=value (for FEAT_SHORT options)
namePart = arg.substr(1, eqPos - 1);
opt = FindOption(arg.substr(0, eqPos));
}
if (opt && opt->HasFeature(Option::FEAT_EQ_JOIN)) {
if (!opt->allowed.empty() &&
opt->allowed.find(value) == opt->allowed.end()) {
std::cerr << "Error: Invalid value '" << value << "' for " << arg
<< std::endl;
return ParseResult::Failed;
}
parsedArgs[opt->id].push_back(value);
return ParseResult::Success;
}
return ParseResult::NotAnOption;
}
/**
* @brief Parse joined format options (--optionvalue or -lvalue for short
* options)
* @param arg The argument string
* @return ParseResult indicating success, failure, or not this type
*/
ParseResult ParseJoined(const std::string &arg) {
// Try short option format first: -Ivalue, -Lcuda, etc.
if (arg.size() > 2 && arg[0] == '-' && arg[1] != '-') {
std::string shortName = arg.substr(1, 1);
std::string value = arg.substr(2);
const Option *opt = FindOptionByShortName(shortName);
if (opt && opt->HasFeature(Option::FEAT_JOINED)) {
if (!opt->allowed.empty() &&
opt->allowed.find(value) == opt->allowed.end()) {
std::cerr << "Error: Invalid value '" << value << "' for " << arg
<< std::endl;
return ParseResult::Failed;
}
parsedArgs[opt->id].push_back(value);
return ParseResult::Success;
}
}
// Try long option format: --librarycuda, --helpme, etc.
if (arg.size() > 3 && arg.find("--") == 0) {
// Search for JOINED options that match the prefix
for (const auto &option : optionTable) {
if (option.HasFeature(Option::FEAT_JOINED)) {
std::string expectedPrefix = "--" + option.longName;
if (arg.find(expectedPrefix) == 0 &&
arg.size() > expectedPrefix.size()) {
std::string value = arg.substr(expectedPrefix.size());
if (!option.allowed.empty() &&
option.allowed.find(value) == option.allowed.end()) {
std::cerr << "Error: Invalid value '" << value << "' for " << arg
<< std::endl;
return ParseResult::Failed;
}
parsedArgs[option.id].push_back(value);
return ParseResult::Success;
}
// Also try with normalized name
std::string normalizedPrefix =
"--" + Option::Normalize(option.longName);
if (arg.find(normalizedPrefix) == 0 &&
arg.size() > normalizedPrefix.size()) {
std::string value = arg.substr(normalizedPrefix.size());
if (!option.allowed.empty() &&
option.allowed.find(value) == option.allowed.end()) {
std::cerr << "Error: Invalid value '" << value << "' for " << arg
<< std::endl;
return ParseResult::Failed;
}
parsedArgs[option.id].push_back(value);
return ParseResult::Success;
}
}
}
// Try alias names for JOINED options
if (!aliasTable.empty()) {
for (const auto &alias : aliasTable) {
std::string normOptionName = Option::Normalize(alias.optionName);
const Option *targetOpt = nullptr;
for (const auto &opt : optionTable) {
if (Option::Normalize(opt.longName) == normOptionName ||
opt.shortName == normOptionName) {
targetOpt = &opt;
break;
}
}
if (targetOpt && targetOpt->HasFeature(Option::FEAT_JOINED)) {
// Try long alias
std::string expectedPrefix = "--" + alias.aliasName;
if (arg.find(expectedPrefix) == 0 &&
arg.size() > expectedPrefix.size()) {
std::string value = arg.substr(expectedPrefix.size());
if (!targetOpt->allowed.empty() &&
targetOpt->allowed.find(value) == targetOpt->allowed.end()) {
std::cerr << "Error: Invalid value '" << value << "' for "
<< arg << std::endl;
return ParseResult::Failed;
}
parsedArgs[targetOpt->id].push_back(value);
return ParseResult::Success;
}
// Try short alias
if (!alias.shortAliasName.empty()) {
std::string shortPrefix = "-" + alias.shortAliasName;
if (arg.find(shortPrefix) == 0 &&
arg.size() > shortPrefix.size()) {
std::string value = arg.substr(shortPrefix.size());
if (!targetOpt->allowed.empty() &&
targetOpt->allowed.find(value) ==
targetOpt->allowed.end()) {
std::cerr << "Error: Invalid value '" << value << "' for "
<< arg << std::endl;
return ParseResult::Failed;
}
parsedArgs[targetOpt->id].push_back(value);
return ParseResult::Success;
}
}
}
}
}
}
return ParseResult::NotAnOption;
}
/**
* @brief Calculate Levenshtein distance between two strings
* @param s1 First string
* @param s2 Second string
* @return The minimum number of single-character edits required to transform
* s1 into s2
*/
int LevenshteinDistance(const std::string &s1, const std::string &s2) const {
size_t len1 = s1.length();
size_t len2 = s2.length();
// Create a matrix
std::vector<std::vector<int>> matrix(len1 + 1, std::vector<int>(len2 + 1));
// Initialize first column and row
for (size_t i = 0; i <= len1; ++i)
matrix[i][0] = i;
for (size_t j = 0; j <= len2; ++j)
matrix[0][j] = j;
// Compute distances
for (size_t i = 1; i <= len1; ++i) {
for (size_t j = 1; j <= len2; ++j) {
int cost = (s1[i - 1] == s2[j - 1]) ? 0 : 1;
matrix[i][j] = std::min({
matrix[i - 1][j] + 1, // deletion
matrix[i][j - 1] + 1, // insertion
matrix[i - 1][j - 1] + cost // substitution
});
// Check for transposition
if (i > 1 && j > 1 && s1[i - 1] == s2[j - 2] &&
s1[i - 2] == s2[j - 1]) {
matrix[i][j] = std::min(matrix[i][j], matrix[i - 2][j - 2] + cost);
}
}
}
return matrix[len1][len2];
}
OptionTable optionTable;
OptionGroupTable optionGroups;
AliasTable aliasTable; // Alias table for option name aliases (for
// help/introspection)
AliasMap aliasMap; // Alias lookup map for O(log n) runtime lookup
std::map<int, std::vector<std::string>>
parsedArgs; // Support multiple values per option
std::vector<std::string> inputs; // Positional inputs (non-option arguments)
std::vector<std::string> unknownArgs; // Unknown options
bool allowUnknown; // Whether to allow unknown options without error
};
/**
* @brief X-Macros for unified argument definition.
*
* Usage format:
* - For separate options: F(name, short_name, help_text, SEPARATE,
* {allowed_values}) Supports space-separated (-o value) and equals-separated
* (-o=value) formats
* - For flags: F(name, short_name, help_text, FLAG, {}) - no value required
* - For joined options: F(name, short_name, help_text, JOINED,
* {allowed_values}) Value attached directly (-lcuda, --librarycuda)
* - For both separate and joined: F(name, short_name, help_text, SEPARATE |
* JOINED, {allowed_values}) Supports all formats: space, equals, and direct
* attachment
*/
// Kind identifiers for macro usage (using bit flags)
// Using full namespace prefix to avoid conflicts
#define SEPARATE cppargs::Option::FEAT_SEPARATE
#define FLAG cppargs::Option::FEAT_FLAG
#define JOINED cppargs::Option::FEAT_JOINED
#define HIDDEN cppargs::Option::FEAT_HIDDEN
#define SHORT cppargs::Option::FEAT_SHORT
#define EQ_JOIN cppargs::Option::FEAT_EQ_JOIN
// GENERATE_ENUM takes kind and optional allowed values (ignored for enum
// generation)
#define GENERATE_ENUM(name, sh, help, kind, ...) OPT_##name,