Skip to content

Commit b85f74a

Browse files
committed
[CommandLineParser] Add DefaultOption flag
Summary: Add DefaultOption flag to CommandLineParser which provides a default option or alias, but allows users to override it for some other purpose as needed. Also, add `-h` as a default alias to `-help`, which can be seamlessly overridden by applications like llvm-objdump and llvm-readobj which use `-h` as an alias for other options. (relanding after revert, r358414) Added DefaultOptions.clear() to reset(). Reviewers: alexfh, klimek Reviewed By: klimek Subscribers: kristina, MaskRay, mehdi_amini, inglorion, dexonsmith, hiraditya, llvm-commits, jhenderson, arphaman, cfe-commits Tags: #clang, #llvm Differential Revision: https://reviews.llvm.org/D59746 llvm-svn: 358428
1 parent 8e364c6 commit b85f74a

File tree

7 files changed

+145
-17
lines changed

7 files changed

+145
-17
lines changed

clang/lib/Tooling/CommonOptionsParser.cpp

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,6 @@ std::vector<CompileCommand> ArgumentsAdjustingCompilations::adjustCommands(
8383
llvm::Error CommonOptionsParser::init(
8484
int &argc, const char **argv, cl::OptionCategory &Category,
8585
llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
86-
static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden,
87-
cl::sub(*cl::AllSubCommands));
8886

8987
static cl::opt<std::string> BuildPath("p", cl::desc("Build path"),
9088
cl::Optional, cl::cat(Category),

llvm/docs/CommandLine.rst

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ this:
128128
USAGE: compiler [options]
129129

130130
OPTIONS:
131+
-h - Alias for -help
131132
-help - display available options (-help-hidden for more)
132133
-o <filename> - Specify output filename
133134

@@ -194,6 +195,7 @@ declarations above, the ``-help`` option synopsis is now extended to:
194195
USAGE: compiler [options] <input file>
195196

196197
OPTIONS:
198+
-h - Alias for -help
197199
-help - display available options (-help-hidden for more)
198200
-o <filename> - Specify output filename
199201

@@ -1251,6 +1253,14 @@ specify boolean properties that modify the option.
12511253
with ``cl::CommaSeparated``, this modifier only makes sense with a `cl::list`_
12521254
option.
12531255

1256+
.. _cl::DefaultOption:
1257+
1258+
* The **cl::DefaultOption** modifier is used to specify that the option is a
1259+
default that can be overridden by application specific parsers. For example,
1260+
the ``-help`` alias, ``-h``, is registered this way, so it can be overridden
1261+
by applications that need to use the ``-h`` option for another purpose,
1262+
either as a regular option or an alias for another option.
1263+
12541264
.. _response files:
12551265

12561266
Response files

llvm/include/llvm/Support/CommandLine.h

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,10 @@ enum MiscFlags { // Miscellaneous flags to adjust argument
175175
// If this is enabled, multiple letter options are allowed to bunch together
176176
// with only a single hyphen for the whole group. This allows emulation
177177
// of the behavior that ls uses for example: ls -la === ls -l -a
178-
Grouping = 0x08
178+
Grouping = 0x08,
179+
180+
// Default option
181+
DefaultOption = 0x10
179182
};
180183

181184
//===----------------------------------------------------------------------===//
@@ -270,7 +273,7 @@ class Option {
270273
unsigned Value : 2;
271274
unsigned HiddenFlag : 2; // enum OptionHidden
272275
unsigned Formatting : 2; // enum FormattingFlags
273-
unsigned Misc : 4;
276+
unsigned Misc : 5;
274277
unsigned Position = 0; // Position of last occurrence of the option
275278
unsigned AdditionalVals = 0; // Greater than 0 for multi-valued option.
276279

@@ -306,6 +309,7 @@ class Option {
306309
bool hasArgStr() const { return !ArgStr.empty(); }
307310
bool isPositional() const { return getFormattingFlag() == cl::Positional; }
308311
bool isSink() const { return getMiscFlags() & cl::Sink; }
312+
bool isDefaultOption() const { return getMiscFlags() & cl::DefaultOption; }
309313

310314
bool isConsumeAfter() const {
311315
return getNumOccurrencesFlag() == cl::ConsumeAfter;
@@ -382,7 +386,7 @@ class Option {
382386
}
383387

384388
inline int getNumOccurrences() const { return NumOccurrences; }
385-
inline void reset() { NumOccurrences = 0; }
389+
void reset();
386390
};
387391

388392
//===----------------------------------------------------------------------===//
@@ -1732,7 +1736,10 @@ class alias : public Option {
17321736
error("cl::alias must have argument name specified!");
17331737
if (!AliasFor)
17341738
error("cl::alias must have an cl::aliasopt(option) specified!");
1739+
if (!Subs.empty())
1740+
error("cl::alias must not have cl::sub(), aliased option's cl::sub() will be used!");
17351741
Subs = AliasFor->Subs;
1742+
Category = AliasFor->Category;
17361743
addArgument();
17371744
}
17381745

llvm/lib/Support/CommandLine.cpp

Lines changed: 45 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,11 @@ class CommandLineParser {
9898
// This collects additional help to be printed.
9999
std::vector<StringRef> MoreHelp;
100100

101+
// This collects Options added with the cl::DefaultOption flag. Since they can
102+
// be overridden, they are not added to the appropriate SubCommands until
103+
// ParseCommandLineOptions actually runs.
104+
SmallVector<Option*, 4> DefaultOptions;
105+
101106
// This collects the different option categories that have been registered.
102107
SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
103108

@@ -146,6 +151,11 @@ class CommandLineParser {
146151
void addOption(Option *O, SubCommand *SC) {
147152
bool HadErrors = false;
148153
if (O->hasArgStr()) {
154+
// If it's a DefaultOption, check to make sure it isn't already there.
155+
if (O->isDefaultOption() &&
156+
SC->OptionsMap.find(O->ArgStr) != SC->OptionsMap.end())
157+
return;
158+
149159
// Add argument to the argument map!
150160
if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
151161
errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
@@ -185,7 +195,12 @@ class CommandLineParser {
185195
}
186196
}
187197

188-
void addOption(Option *O) {
198+
void addOption(Option *O, bool ProcessDefaultOption = false) {
199+
if (!ProcessDefaultOption && O->isDefaultOption()) {
200+
DefaultOptions.push_back(O);
201+
return;
202+
}
203+
189204
if (O->Subs.empty()) {
190205
addOption(O, &*TopLevelSubCommand);
191206
} else {
@@ -201,8 +216,12 @@ class CommandLineParser {
201216
OptionNames.push_back(O->ArgStr);
202217

203218
SubCommand &Sub = *SC;
204-
for (auto Name : OptionNames)
205-
Sub.OptionsMap.erase(Name);
219+
auto End = Sub.OptionsMap.end();
220+
for (auto Name : OptionNames) {
221+
auto I = Sub.OptionsMap.find(Name);
222+
if (I != End && I->getValue() == O)
223+
Sub.OptionsMap.erase(I);
224+
}
206225

207226
if (O->getFormattingFlag() == cl::Positional)
208227
for (auto Opt = Sub.PositionalOpts.begin();
@@ -266,8 +285,13 @@ class CommandLineParser {
266285
if (O->Subs.empty())
267286
updateArgStr(O, NewName, &*TopLevelSubCommand);
268287
else {
269-
for (auto SC : O->Subs)
270-
updateArgStr(O, NewName, SC);
288+
if (O->isInAllSubCommands()) {
289+
for (auto SC : RegisteredSubCommands)
290+
updateArgStr(O, NewName, SC);
291+
} else {
292+
for (auto SC : O->Subs)
293+
updateArgStr(O, NewName, SC);
294+
}
271295
}
272296
}
273297

@@ -331,6 +355,8 @@ class CommandLineParser {
331355
AllSubCommands->reset();
332356
registerSubCommand(&*TopLevelSubCommand);
333357
registerSubCommand(&*AllSubCommands);
358+
359+
DefaultOptions.clear();
334360
}
335361

336362
private:
@@ -366,6 +392,13 @@ void Option::setArgStr(StringRef S) {
366392
ArgStr = S;
367393
}
368394

395+
void Option::reset() {
396+
NumOccurrences = 0;
397+
setDefault();
398+
if (isDefaultOption())
399+
removeArgument();
400+
}
401+
369402
// Initialise the general option category.
370403
OptionCategory llvm::cl::GeneralCategory("General options");
371404

@@ -1167,6 +1200,10 @@ bool CommandLineParser::ParseCommandLineOptions(int argc,
11671200
auto &SinkOpts = ChosenSubCommand->SinkOpts;
11681201
auto &OptionsMap = ChosenSubCommand->OptionsMap;
11691202

1203+
for (auto O: DefaultOptions) {
1204+
addOption(O, true);
1205+
}
1206+
11701207
if (ConsumeAfterOpt) {
11711208
assert(PositionalOpts.size() > 0 &&
11721209
"Cannot specify cl::ConsumeAfter without a positional argument!");
@@ -2146,6 +2183,9 @@ static cl::opt<HelpPrinterWrapper, true, parser<bool>>
21462183
cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
21472184
cl::cat(GenericCategory), cl::sub(*AllSubCommands));
21482185

2186+
static cl::alias HOpA("h", cl::desc("Alias for -help"), cl::aliasopt(HOp),
2187+
cl::DefaultOption);
2188+
21492189
static cl::opt<HelpPrinterWrapper, true, parser<bool>>
21502190
HHOp("help-hidden", cl::desc("Display all available options"),
21512191
cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# RUN: llvm-objdump -help-hidden %t | FileCheck --check-prefix=CHECK-OBJDUMP %s
2+
# RUN: llvm-readobj -help-hidden %t | FileCheck --check-prefix=CHECK-READOBJ %s
3+
# RUN: llvm-tblgen -help-hidden %t | FileCheck --check-prefix=CHECK-TBLGEN %s
4+
# RUN: llvm-opt-report -help-hidden %t | FileCheck --check-prefix=CHECK-OPT-RPT %s
5+
# RUN: llvm-dwarfdump -help-hidden %t | FileCheck --check-prefix=CHECK-DWARF %s
6+
# RUN: llvm-dwarfdump -h %t | FileCheck --check-prefix=CHECK-DWARF-H %s
7+
8+
9+
# CHECK-OBJDUMP: -h - Alias for --section-headers
10+
# CHECK-READOBJ: -h - Alias for --file-headers
11+
# CHECK-TBLGEN: -h - Alias for -help
12+
# CHECK-OPT-RPT: -h - Alias for -help
13+
# CHECK-DWARF: -h - Alias for -help
14+
15+
# llvm-dwarfdump declares `-h` option and prints special help in that case,
16+
# which is weird, but makes for a good test, i.e., shows the default `-h`
17+
# wasn't used.
18+
# CHECK-DWARF-H-NOT: -help-list - Display list of available options (-help-list-hidden for more)

llvm/tools/llvm-opt-report/OptReport.cpp

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,6 @@
3636
using namespace llvm;
3737
using namespace llvm::yaml;
3838

39-
static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
40-
4139
// Mark all our options with this category, everything else (except for -version
4240
// and -help) will be hidden.
4341
static cl::OptionCategory
@@ -440,11 +438,6 @@ int main(int argc, const char **argv) {
440438
"A tool to generate an optimization report from YAML optimization"
441439
" record files.\n");
442440

443-
if (Help) {
444-
cl::PrintHelpMessage();
445-
return 0;
446-
}
447-
448441
LocationInfoTy LocationInfo;
449442
if (!readLocationInfo(LocationInfo))
450443
return 1;

llvm/unittests/Support/CommandLineTest.cpp

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,68 @@ TEST(CommandLineTest, GetRegisteredSubcommands) {
620620
}
621621
}
622622

623+
TEST(CommandLineTest, DefaultOptions) {
624+
cl::ResetCommandLineParser();
625+
626+
StackOption<std::string> Bar("bar", cl::sub(*cl::AllSubCommands),
627+
cl::DefaultOption);
628+
StackOption<std::string, cl::alias> Bar_Alias(
629+
"b", cl::desc("Alias for -bar"), cl::aliasopt(Bar), cl::DefaultOption);
630+
631+
StackOption<bool> Foo("foo", cl::init(false), cl::sub(*cl::AllSubCommands),
632+
cl::DefaultOption);
633+
StackOption<bool, cl::alias> Foo_Alias("f", cl::desc("Alias for -foo"),
634+
cl::aliasopt(Foo), cl::DefaultOption);
635+
636+
StackSubCommand SC1("sc1", "First Subcommand");
637+
// Override "-b" and change type in sc1 SubCommand.
638+
StackOption<bool> SC1_B("b", cl::sub(SC1), cl::init(false));
639+
StackSubCommand SC2("sc2", "Second subcommand");
640+
// Override "-foo" and change type in sc2 SubCommand. Note that this does not
641+
// affect "-f" alias, which continues to work correctly.
642+
StackOption<std::string> SC2_Foo("foo", cl::sub(SC2));
643+
644+
const char *args0[] = {"prog", "-b", "args0 bar string", "-f"};
645+
EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args0) / sizeof(char *), args0,
646+
StringRef(), &llvm::nulls()));
647+
EXPECT_TRUE(Bar == "args0 bar string");
648+
EXPECT_TRUE(Foo);
649+
EXPECT_FALSE(SC1_B);
650+
EXPECT_TRUE(SC2_Foo.empty());
651+
652+
cl::ResetAllOptionOccurrences();
653+
654+
const char *args1[] = {"prog", "sc1", "-b", "-bar", "args1 bar string", "-f"};
655+
EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args1) / sizeof(char *), args1,
656+
StringRef(), &llvm::nulls()));
657+
EXPECT_TRUE(Bar == "args1 bar string");
658+
EXPECT_TRUE(Foo);
659+
EXPECT_TRUE(SC1_B);
660+
EXPECT_TRUE(SC2_Foo.empty());
661+
for (auto *S : cl::getRegisteredSubcommands()) {
662+
if (*S) {
663+
EXPECT_EQ("sc1", S->getName());
664+
}
665+
}
666+
667+
cl::ResetAllOptionOccurrences();
668+
669+
const char *args2[] = {"prog", "sc2", "-b", "args2 bar string",
670+
"-f", "-foo", "foo string"};
671+
EXPECT_TRUE(cl::ParseCommandLineOptions(sizeof(args2) / sizeof(char *), args2,
672+
StringRef(), &llvm::nulls()));
673+
EXPECT_TRUE(Bar == "args2 bar string");
674+
EXPECT_TRUE(Foo);
675+
EXPECT_FALSE(SC1_B);
676+
EXPECT_TRUE(SC2_Foo == "foo string");
677+
for (auto *S : cl::getRegisteredSubcommands()) {
678+
if (*S) {
679+
EXPECT_EQ("sc2", S->getName());
680+
}
681+
}
682+
cl::ResetCommandLineParser();
683+
}
684+
623685
TEST(CommandLineTest, ArgumentLimit) {
624686
std::string args(32 * 4096, 'a');
625687
EXPECT_FALSE(llvm::sys::commandLineFitsWithinSystemLimits("cl", args.data()));

0 commit comments

Comments
 (0)