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
//! LLVM CommandLine — command-line argument parsing for LLVM tool drivers.
//! Clean-room reimplementation of LLVM's cl::opt / cl::list / cl::alias infrastructure.
//!
//! @llvm_behavior: LLVM's CommandLine library provides declarative option
//! registration with automatic parsing, help generation, and type-safe access.
//! This implementation provides the full API surface needed for LLVM tool
//! drivers (opt, llc, lli, etc.) including common LLVM option presets.
//!
//! Key features:
//! - Flag options (boolean switches like -S, -debug)
//! - String options (-o <file>, -mtriple=<triple>)
//! - Integer options (-O<level>)
//! - String list options (accumulating options)
//! - Positional argument tracking
//! - Error collection instead of immediate panics
//! - Help text generation
use std::collections::HashMap;
// ============================================================================
// CommandLine — main argument parser
// ============================================================================
/// A complete command-line argument parser for LLVM tool drivers.
///
/// @llvm_behavior: Equivalent to LLVM's `cl::ParseCommandLineOptions` plus
/// the collection of registered `cl::opt` / `cl::list` descriptors.
#[derive(Debug, Clone)]
pub struct CommandLine {
/// The program name (argv[0]).
pub program_name: String,
/// All registered options, in registration order.
pub options: Vec<ClOption>,
/// Positional (non-option) arguments.
pub positional: Vec<String>,
/// Errors encountered during parsing (non-fatal collection).
pub errors: Vec<String>,
/// Lookup map: option name → index into `options`.
name_to_index: HashMap<String, usize>,
}
/// The stored value of a parsed command-line option.
#[derive(Debug, Clone)]
pub enum ClOptionValue {
/// A boolean flag (present → true, absent → false).
Flag(bool),
/// A string value.
String(String),
/// A signed integer value.
Int(i64),
/// A list of string values (accumulated from multiple occurrences).
Strings(Vec<String>),
}
/// A single registered command-line option.
///
/// @llvm_behavior: Corresponds to an instance of `cl::opt<T>` or `cl::list<T>`.
#[derive(Debug, Clone)]
pub struct ClOption {
/// The option name (without leading dashes), e.g. "o", "S", "debug".
pub name: String,
/// Human-readable description for help output.
pub description: String,
/// The parsed value (or default).
pub value: ClOptionValue,
/// Whether this option was explicitly set on the command line.
pub is_set: bool,
}
impl CommandLine {
/// Create a new CommandLine parser for the given program name.
pub fn new(program_name: &str) -> Self {
Self {
program_name: program_name.to_string(),
options: Vec::new(),
positional: Vec::new(),
errors: Vec::new(),
name_to_index: HashMap::new(),
}
}
/// Register a boolean flag option.
///
/// Returns a mutable reference to the newly registered option so
/// the caller can inspect or modify it before parsing.
///
/// @llvm_behavior: Equivalent to `cl::opt<bool> MyFlag("name", cl::desc("..."))`.
pub fn add_flag(&mut self, name: &str, description: &str) -> &mut ClOption {
self.add_option(name, description, ClOptionValue::Flag(false))
}
/// Register a string option with a default value.
///
/// @llvm_behavior: Equivalent to `cl::opt<std::string> MyOpt("name", cl::desc("..."), cl::init("default"))`.
pub fn add_string_option(
&mut self,
name: &str,
default: &str,
description: &str,
) -> &mut ClOption {
self.add_option(
name,
description,
ClOptionValue::String(default.to_string()),
)
}
/// Register an integer option with a default value.
///
/// @llvm_behavior: Equivalent to `cl::opt<int> MyOpt("name", cl::desc("..."), cl::init(0))`.
pub fn add_int_option(&mut self, name: &str, default: i64, description: &str) -> &mut ClOption {
self.add_option(name, description, ClOptionValue::Int(default))
}
/// Register a string list option (accumulates values from multiple -name=val occurrences).
///
/// @llvm_behavior: Equivalent to `cl::list<std::string> MyList("name", cl::desc("..."))`.
pub fn add_string_list(&mut self, name: &str, description: &str) -> &mut ClOption {
self.add_option(name, description, ClOptionValue::Strings(Vec::new()))
}
/// Internal helper: register an option and return a mutable reference.
fn add_option(&mut self, name: &str, description: &str, value: ClOptionValue) -> &mut ClOption {
let idx = self.options.len();
self.name_to_index.insert(name.to_string(), idx);
self.options.push(ClOption {
name: name.to_string(),
description: description.to_string(),
value,
is_set: false,
});
self.options.last_mut().unwrap()
}
/// Parse the command-line arguments.
///
/// @llvm_behavior: Walks argv[1..], dispatches each token to the
/// matching registered option or collects it as a positional argument.
/// Errors are accumulated in `self.errors` rather than returned
/// immediately, but a summary error is still returned via `Result`.
///
/// Supported formats:
/// - `-name` or `--name` → flag (set to true)
/// - `-name=value` or `--name=value` → string/int/list assignment
/// - `-name value` or `--name value` → string/int assignment (space-separated)
/// - `-O0`, `-O1`, `-O2`, `-O3`, `-Os`, `-Oz` → integer option "O"
/// - Positional arguments have no leading dash.
pub fn parse(&mut self, args: &[String]) -> Result<(), String> {
self.errors.clear();
self.positional.clear();
// Reset all options to unset with defaults
for opt in &mut self.options {
opt.is_set = false;
match &mut opt.value {
ClOptionValue::Flag(v) => *v = false,
ClOptionValue::Strings(v) => v.clear(),
// String and Int keep their defaults
_ => {}
}
}
let mut i = 1; // skip argv[0] (program name)
while i < args.len() {
let arg = &args[i];
if arg == "--" {
// End of options: everything after "--" is positional
i += 1;
while i < args.len() {
self.positional.push(args[i].clone());
i += 1;
}
break;
}
if arg.starts_with("--") {
// Long option: --name or --name=value
let stripped = &arg[2..];
if stripped.is_empty() {
// bare "--" already handled above
i += 1;
continue;
}
if let Some(eq) = stripped.find('=') {
let name = &stripped[..eq];
let value = &stripped[eq + 1..];
self.set_option_value(name, value)?;
} else {
// Check if it's a flag
if self.is_flag_option(stripped) {
self.set_flag(stripped)?;
} else {
// It's a value option expecting a next argument
i += 1;
if i < args.len() {
let value = &args[i];
self.set_option_value(stripped, value)?;
} else {
let msg = format!(
"{}: option '--{}' requires a value",
self.program_name, stripped
);
self.errors.push(msg);
}
}
}
} else if arg.starts_with('-') && arg.len() > 1 {
// Short option: -name, -name=value, or -O<level>
let stripped = &arg[1..];
// Special handling for -O[0123sz] optimization level
if stripped.starts_with('O') && stripped.len() >= 2 {
let level = &stripped[1..];
if let Some(opt_name) = self.resolve_opt_name("O") {
let val: i64 = match level {
"0" => 0,
"1" => 1,
"2" => 2,
"3" => 3,
"s" => 101, // Use special values to distinguish
"z" => 102,
_ => {
let msg = format!(
"{}: unknown optimization level '-{}'",
self.program_name, stripped
);
self.errors.push(msg);
i += 1;
continue;
}
};
let idx = self.name_to_index[opt_name];
self.options[idx].value = ClOptionValue::Int(val);
self.options[idx].is_set = true;
} else {
self.positional.push(arg.clone());
}
i += 1;
continue;
}
if let Some(eq) = stripped.find('=') {
let name = &stripped[..eq];
let value = &stripped[eq + 1..];
self.set_option_value(name, value)?;
} else {
// Check if it's a flag
if self.is_flag_option(stripped) {
self.set_flag(stripped)?;
} else {
// It's a value option expecting a next argument
i += 1;
if i < args.len() {
let value = &args[i];
self.set_option_value(stripped, value)?;
} else {
let msg = format!(
"{}: option '-{}' requires a value",
self.program_name, stripped
);
self.errors.push(msg);
}
}
}
} else {
// Positional argument
self.positional.push(arg.clone());
}
i += 1;
}
if self.errors.is_empty() {
Ok(())
} else {
Err(self.errors.join("\n"))
}
}
/// Get the boolean value of a flag option.
///
/// @llvm_behavior: Returns `false` if the option is not found or is not a flag.
pub fn get_flag(&self, name: &str) -> bool {
self.find_option(name)
.and_then(|opt| match &opt.value {
ClOptionValue::Flag(v) => Some(*v),
_ => None,
})
.unwrap_or(false)
}
/// Get the string value of a string option.
///
/// @llvm_behavior: Returns `""` if the option is not found or is not a string option.
pub fn get_string(&self, name: &str) -> &str {
// We need to return a reference. Since the default is an empty string,
// we can return a static empty str if not found.
self.find_option(name)
.and_then(|opt| match &opt.value {
ClOptionValue::String(s) => Some(s.as_str()),
_ => None,
})
.unwrap_or("")
}
/// Get the integer value of an integer option.
///
/// @llvm_behavior: Returns `0` if the option is not found or is not an integer option.
pub fn get_int(&self, name: &str) -> i64 {
self.find_option(name)
.and_then(|opt| match &opt.value {
ClOptionValue::Int(v) => Some(*v),
_ => None,
})
.unwrap_or(0)
}
/// Get the list of strings for a string-list option.
///
/// @llvm_behavior: Returns an empty slice if the option is not found or is not a string list.
pub fn get_strings(&self, name: &str) -> &[String] {
// Need a static empty vec for the fallback
self.find_option(name)
.and_then(|opt| match &opt.value {
ClOptionValue::Strings(v) => Some(v.as_slice()),
_ => None,
})
.unwrap_or(&[])
}
/// Get a positional argument by index (0-based).
pub fn get_positional(&self, index: usize) -> Option<&str> {
self.positional.get(index).map(|s| s.as_str())
}
/// Print help text to stdout describing all registered options.
///
/// @llvm_behavior: Equivalent to `-help` / `--help` output in LLVM tools.
pub fn print_help(&self) {
println!("Usage: {} [options] [files...]\n", self.program_name);
println!("Options:");
for opt in &self.options {
let flag = match &opt.value {
ClOptionValue::Flag(_) => "",
ClOptionValue::String(s) => &format!(" <string> (default: {})", s),
ClOptionValue::Int(v) => &format!(" <int> (default: {})", v),
ClOptionValue::Strings(_) => " <string>",
};
println!(" -{}{}", opt.name, flag);
if !opt.description.is_empty() {
println!(" {}", opt.description);
}
}
println!();
println!("Common options:");
println!(" -help Display this help message");
println!(" -version Display the version");
}
// ========================================================================
// Private helpers
// ========================================================================
/// Find an option by name. Tries exact match first, then common aliases.
fn find_option(&self, name: &str) -> Option<&ClOption> {
self.resolve_opt_name(name)
.and_then(|resolved| self.options.get(self.name_to_index[resolved]))
}
/// Resolve an option name to its canonical registered name.
fn resolve_opt_name<'a>(&self, name: &'a str) -> Option<&'a str> {
// Exact match
if self.name_to_index.contains_key(name) {
return Some(name);
}
// Common aliases
match name {
"o" | "output" => {
if self.name_to_index.contains_key("o") {
return Some("o");
}
}
"help" => {
if self.name_to_index.contains_key("help") {
return Some("help");
}
}
_ => {}
}
None
}
/// Check if a registered option is a flag type.
fn is_flag_option(&self, name: &str) -> bool {
self.resolve_opt_name(name)
.and_then(|resolved| self.name_to_index.get(resolved))
.and_then(|&idx| self.options.get(idx))
.map(|opt| matches!(opt.value, ClOptionValue::Flag(_)))
.unwrap_or(false)
}
/// Set a flag option to true.
fn set_flag(&mut self, name: &str) -> Result<(), String> {
if let Some(resolved) = self.resolve_opt_name(name) {
let idx = self.name_to_index[resolved];
let opt = &mut self.options[idx];
match &mut opt.value {
ClOptionValue::Flag(v) => {
*v = true;
opt.is_set = true;
Ok(())
}
_ => {
let msg = format!("{}: option '-{}' is not a flag", self.program_name, name);
self.errors.push(msg.clone());
Err(msg)
}
}
} else {
let msg = format!("{}: unknown option '-{}'", self.program_name, name);
self.errors.push(msg.clone());
Err(msg)
}
}
/// Set the value of a non-flag option.
fn set_option_value(&mut self, name: &str, value: &str) -> Result<(), String> {
if let Some(resolved) = self.resolve_opt_name(name) {
let idx = self.name_to_index[resolved];
let opt = &mut self.options[idx];
match &mut opt.value {
ClOptionValue::String(s) => {
*s = value.to_string();
opt.is_set = true;
Ok(())
}
ClOptionValue::Int(v) => match value.parse::<i64>() {
Ok(parsed) => {
*v = parsed;
opt.is_set = true;
Ok(())
}
Err(_) => {
let msg = format!(
"{}: invalid integer value '{}' for option '-{}'",
self.program_name, value, name
);
self.errors.push(msg.clone());
Err(msg)
}
},
ClOptionValue::Strings(list) => {
list.push(value.to_string());
opt.is_set = true;
Ok(())
}
ClOptionValue::Flag(_) => {
// Treat -flag=value as setting flag to true and ignoring value
let opt = &mut self.options[idx];
opt.value = ClOptionValue::Flag(true);
opt.is_set = true;
Ok(())
}
}
} else {
let msg = format!("{}: unknown option '-{}'", self.program_name, name);
self.errors.push(msg.clone());
Err(msg)
}
}
}
// ============================================================================
// Common LLVM option presets
// ============================================================================
/// Register common LLVM tool options on a CommandLine parser.
///
/// Includes: -o, -S, -c, -debug, -time-passes, -stats, -version.
///
/// @llvm_behavior: These are the universally-available options in all LLVM
/// tool drivers (opt, llc, lli, llvm-link, etc.).
pub fn add_common_llvm_options(cl: &mut CommandLine) {
cl.add_string_option("o", "", "Output file");
cl.add_flag("S", "Emit assembly text (default: emit bitcode)");
cl.add_flag("c", "Emit object file (default: emit bitcode)");
cl.add_flag("debug", "Enable debug output");
cl.add_flag("time-passes", "Time each pass and print elapsed time");
cl.add_flag("stats", "Print statistics gathered during execution");
cl.add_flag("version", "Print version information");
cl.add_flag("help", "Display help message");
}
/// Register optimization-level options on a CommandLine parser.
///
/// Includes: -O0, -O1, -O2, -O3, -Os, -Oz.
///
/// @llvm_behavior: These correspond to the standard LLVM optimization
/// pipeline presets. -Os optimizes for size, -Oz optimizes for size
/// more aggressively.
pub fn add_optimization_options(cl: &mut CommandLine) {
cl.add_int_option(
"O",
0,
"Optimization level (0=none, 1=less, 2=default, 3=aggressive, s=size, z=min-size)",
);
}
/// Register target code-generation options on a CommandLine parser.
///
/// Includes: -march, -mtriple, -mcpu, -mattr.
///
/// @llvm_behavior: These options select the target architecture and
/// fine-tune code generation for a specific CPU model with optional
/// feature flags.
pub fn add_codegen_options(cl: &mut CommandLine) {
cl.add_string_option("march", "", "Target architecture to generate code for");
cl.add_string_option(
"mtriple",
"",
"Target triple (e.g. x86_64-unknown-linux-gnu)",
);
cl.add_string_option("mcpu", "", "Target CPU (e.g. skylake, cortex-a72)");
cl.add_string_option("mattr", "", "Target features (+sse2,-avx)");
}
/// Register output-format options on a CommandLine parser.
///
/// Includes: -o, -S, -c, -emit-llvm, -emit-asm, -emit-obj.
///
/// @llvm_behavior: These control the output format of the compilation
/// pipeline: LLVM IR, assembly, or object code.
pub fn add_output_options(cl: &mut CommandLine) {
cl.add_string_option("o", "", "Output filename");
cl.add_flag("S", "Emit assembly (.s) instead of object code");
cl.add_flag("c", "Compile and assemble, but do not link");
cl.add_flag("emit-llvm", "Emit LLVM IR (.ll) instead of object code");
cl.add_flag("emit-asm", "Emit assembly text");
cl.add_flag("emit-obj", "Emit native object file");
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
fn args(slice: &[&str]) -> Vec<String> {
slice.iter().map(|s| s.to_string()).collect()
}
// --- Basic option registration ---
#[test]
fn test_add_flag() {
let mut cl = CommandLine::new("test");
cl.add_flag("verbose", "Enable verbose output");
assert_eq!(cl.options.len(), 1);
assert_eq!(cl.options[0].name, "verbose");
assert!(!cl.get_flag("verbose"));
assert!(matches!(cl.options[0].value, ClOptionValue::Flag(false)));
}
#[test]
fn test_add_string_option() {
let mut cl = CommandLine::new("test");
cl.add_string_option("output", "default.out", "Output filename");
assert_eq!(cl.get_string("output"), "default.out");
assert!(!cl.options[0].is_set);
}
#[test]
fn test_add_int_option() {
let mut cl = CommandLine::new("test");
cl.add_int_option("level", 2, "Optimization level");
assert_eq!(cl.get_int("level"), 2);
assert!(!cl.options[0].is_set);
}
#[test]
fn test_add_string_list() {
let mut cl = CommandLine::new("test");
cl.add_string_list("include", "Include paths");
assert!(cl.get_strings("include").is_empty());
}
// --- Flag parsing ---
#[test]
fn test_parse_flag_short() {
let mut cl = CommandLine::new("test");
cl.add_flag("verbose", "Verbose");
cl.parse(&args(&["test", "-verbose"])).unwrap();
assert!(cl.get_flag("verbose"));
assert!(cl.options[0].is_set);
}
#[test]
fn test_parse_flag_long() {
let mut cl = CommandLine::new("test");
cl.add_flag("debug", "Debug mode");
cl.parse(&args(&["test", "--debug"])).unwrap();
assert!(cl.get_flag("debug"));
}
#[test]
fn test_parse_flag_absent() {
let mut cl = CommandLine::new("test");
cl.add_flag("verbose", "Verbose");
cl.parse(&args(&["test"])).unwrap();
assert!(!cl.get_flag("verbose"));
}
// --- String option parsing ---
#[test]
fn test_parse_string_with_equals() {
let mut cl = CommandLine::new("test");
cl.add_string_option("o", "", "Output file");
cl.parse(&args(&["test", "-o=output.ll"])).unwrap();
assert_eq!(cl.get_string("o"), "output.ll");
assert!(cl.options[0].is_set);
}
#[test]
fn test_parse_string_space_separated() {
let mut cl = CommandLine::new("test");
cl.add_string_option("o", "", "Output file");
cl.parse(&args(&["test", "-o", "output.ll"])).unwrap();
assert_eq!(cl.get_string("o"), "output.ll");
}
#[test]
fn test_parse_string_long_with_equals() {
let mut cl = CommandLine::new("test");
cl.add_string_option("output", "", "Output file");
cl.parse(&args(&["test", "--output=out.bc"])).unwrap();
assert_eq!(cl.get_string("output"), "out.bc");
}
// --- Integer option parsing ---
#[test]
fn test_parse_int_with_equals() {
let mut cl = CommandLine::new("test");
cl.add_int_option("level", 0, "Level");
cl.parse(&args(&["test", "-level=3"])).unwrap();
assert_eq!(cl.get_int("level"), 3);
}
#[test]
fn test_parse_optimization_level() {
let mut cl = CommandLine::new("test");
add_optimization_options(&mut cl);
cl.parse(&args(&["test", "-O2"])).unwrap();
assert_eq!(cl.get_int("O"), 2);
}
#[test]
fn test_parse_optimization_size() {
let mut cl = CommandLine::new("test");
add_optimization_options(&mut cl);
cl.parse(&args(&["test", "-Os"])).unwrap();
// -Os maps to 101 internally
assert_eq!(cl.get_int("O"), 101);
}
// --- String list parsing ---
#[test]
fn test_parse_string_list_multiple() {
let mut cl = CommandLine::new("test");
cl.add_string_list("I", "Include paths");
cl.parse(&args(&["test", "-I=/usr/include", "-I=/opt/include"]))
.unwrap();
let strings = cl.get_strings("I");
assert_eq!(strings.len(), 2);
assert_eq!(strings[0], "/usr/include");
assert_eq!(strings[1], "/opt/include");
}
#[test]
fn test_parse_string_list_clears_on_reparse() {
let mut cl = CommandLine::new("test");
cl.add_string_list("I", "Include paths");
cl.parse(&args(&["test", "-I=/path1"])).unwrap();
assert_eq!(cl.get_strings("I").len(), 1);
// Re-parse: should reset
cl.parse(&args(&["test", "-I=/path2"])).unwrap();
assert_eq!(cl.get_strings("I").len(), 1);
assert_eq!(cl.get_strings("I")[0], "/path2");
}
// --- Positional arguments ---
#[test]
fn test_positional_arguments() {
let mut cl = CommandLine::new("test");
cl.add_flag("verbose", "Verbose");
cl.parse(&args(&["test", "-verbose", "input.ll", "extra.bc"]))
.unwrap();
assert_eq!(cl.positional.len(), 2);
assert_eq!(cl.get_positional(0), Some("input.ll"));
assert_eq!(cl.get_positional(1), Some("extra.bc"));
assert_eq!(cl.get_positional(2), None);
}
#[test]
fn test_positional_after_double_dash() {
let mut cl = CommandLine::new("test");
cl.add_flag("verbose", "Verbose");
cl.parse(&args(&["test", "--", "-verbose", "file.txt"]))
.unwrap();
// After "--", everything is positional, even -verbose
assert_eq!(cl.positional.len(), 2);
assert_eq!(cl.positional[0], "-verbose");
assert!(cl.get_flag("verbose") == false);
}
// --- Error handling ---
#[test]
fn test_unknown_option_error() {
let mut cl = CommandLine::new("test");
cl.add_flag("verbose", "Verbose");
let result = cl.parse(&args(&["test", "-unknown"]));
assert!(result.is_err());
assert!(!cl.errors.is_empty());
}
#[test]
fn test_missing_value_error() {
let mut cl = CommandLine::new("test");
cl.add_string_option("o", "", "Output");
let result = cl.parse(&args(&["test", "-o"]));
assert!(result.is_err());
assert!(cl.errors.iter().any(|e| e.contains("requires a value")));
}
#[test]
fn test_invalid_integer_error() {
let mut cl = CommandLine::new("test");
cl.add_int_option("level", 0, "Level");
let result = cl.parse(&args(&["test", "-level=abc"]));
assert!(result.is_err());
assert!(cl.errors.iter().any(|e| e.contains("invalid integer")));
}
// --- Common option presets ---
#[test]
fn test_common_llvm_options_preset() {
let mut cl = CommandLine::new("opt");
add_common_llvm_options(&mut cl);
// Should have 8 options
assert!(cl.options.len() >= 7);
cl.parse(&args(&["opt", "-S", "-debug", "-stats", "input.bc"]))
.unwrap();
assert!(cl.get_flag("S"));
assert!(cl.get_flag("debug"));
assert!(cl.get_flag("stats"));
assert!(!cl.get_flag("c"));
assert_eq!(cl.positional.len(), 1);
}
#[test]
fn test_codegen_options_preset() {
let mut cl = CommandLine::new("llc");
add_codegen_options(&mut cl);
cl.parse(&args(&[
"llc",
"-mtriple=x86_64-unknown-linux-gnu",
"-mcpu=skylake",
"-mattr=+avx2,+fma",
]))
.unwrap();
assert_eq!(cl.get_string("mtriple"), "x86_64-unknown-linux-gnu");
assert_eq!(cl.get_string("mcpu"), "skylake");
assert_eq!(cl.get_string("mattr"), "+avx2,+fma");
}
#[test]
fn test_reparse_resets_flags() {
let mut cl = CommandLine::new("test");
cl.add_flag("verbose", "Verbose");
cl.parse(&args(&["test", "-verbose"])).unwrap();
assert!(cl.get_flag("verbose"));
// Re-parse without the flag
cl.parse(&args(&["test"])).unwrap();
assert!(!cl.get_flag("verbose"));
}
#[test]
fn test_print_help_does_not_panic() {
let mut cl = CommandLine::new("mytool");
cl.add_flag("verbose", "Enable verbose output");
cl.add_string_option("o", "out.bc", "Output file");
cl.add_int_option("j", 1, "Number of threads");
cl.print_help(); // Should not panic
}
#[test]
fn test_get_nonexistent_option() {
let cl = CommandLine::new("test");
assert!(!cl.get_flag("nonexistent"));
assert_eq!(cl.get_string("nonexistent"), "");
assert_eq!(cl.get_int("nonexistent"), 0);
assert!(cl.get_strings("nonexistent").is_empty());
}
#[test]
fn test_output_options_preset() {
let mut cl = CommandLine::new("clang");
add_output_options(&mut cl);
cl.parse(&args(&["clang", "-S", "-o", "out.s", "input.c"]))
.unwrap();
assert!(cl.get_flag("S"));
assert_eq!(cl.get_string("o"), "out.s");
assert_eq!(cl.positional.len(), 1);
}
}