@@ -525,6 +525,59 @@ TEST(CommandLineTest, LookupFailsInWrongSubCommand) {
525
525
EXPECT_FALSE (Errs.empty ());
526
526
}
527
527
528
+ TEST (CommandLineTest, TopLevelOptInSubcommand) {
529
+ enum LiteralOptionEnum {
530
+ foo,
531
+ bar,
532
+ baz,
533
+ };
534
+
535
+ cl::ResetCommandLineParser ();
536
+
537
+ // This is a top-level option and not associated with a subcommand.
538
+ // A command line using subcommand should parse both subcommand options and
539
+ // top-level options. A valid use case is that users of llvm command line
540
+ // tools should be able to specify top-level options defined in any library.
541
+ cl::opt<std::string> TopLevelOpt (" str" , cl::init (" txt" ),
542
+ cl::desc (" A top-level option." ));
543
+
544
+ StackSubCommand SC (" sc" , " Subcommand" );
545
+ StackOption<std::string> PositionalOpt (
546
+ cl::Positional, cl::desc (" positional argument test coverage" ),
547
+ cl::sub (SC));
548
+ StackOption<LiteralOptionEnum> LiteralOpt (
549
+ cl::desc (" literal argument test coverage" ), cl::sub (SC), cl::init (bar),
550
+ cl::values (clEnumVal (foo, " foo" ), clEnumVal (bar, " bar" ),
551
+ clEnumVal (baz, " baz" )));
552
+ StackOption<bool > EnableOpt (" enable" , cl::sub (SC), cl::init (false ));
553
+ StackOption<int > ThresholdOpt (" threshold" , cl::sub (SC), cl::init (1 ));
554
+
555
+ const char *PositionalOptVal = " input-file" ;
556
+ const char *args[] = {" prog" , " sc" , PositionalOptVal,
557
+ " -enable" , " --str=csv" , " --threshold=2" };
558
+
559
+ // cl::ParseCommandLineOptions returns true on success. Otherwise, it will
560
+ // print the error message to stderr and exit in this setting (`Errs` ostream
561
+ // is not set).
562
+ ASSERT_TRUE (cl::ParseCommandLineOptions (sizeof (args) / sizeof (args[0 ]), args,
563
+ StringRef ()));
564
+ EXPECT_STREQ (PositionalOpt.getValue ().c_str (), PositionalOptVal);
565
+ EXPECT_TRUE (EnableOpt);
566
+ // Tests that the value of `str` option is `csv` as specified.
567
+ EXPECT_STREQ (TopLevelOpt.getValue ().c_str (), " csv" );
568
+ EXPECT_EQ (ThresholdOpt, 2 );
569
+
570
+ for (auto &[LiteralOptVal, WantLiteralOpt] :
571
+ {std::pair{" --bar" , bar}, {" --foo" , foo}, {" --baz" , baz}}) {
572
+ const char *args[] = {" prog" , " sc" , LiteralOptVal};
573
+ ASSERT_TRUE (cl::ParseCommandLineOptions (sizeof (args) / sizeof (args[0 ]),
574
+ args, StringRef ()));
575
+
576
+ // Tests that literal options are parsed correctly.
577
+ EXPECT_EQ (LiteralOpt, WantLiteralOpt);
578
+ }
579
+ }
580
+
528
581
TEST (CommandLineTest, AddToAllSubCommands) {
529
582
cl::ResetCommandLineParser ();
530
583
0 commit comments