1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements a command line argument processor that is useful when
11 // creating a tool. It provides a simple, minimalistic interface that is easily
12 // extensible and supports nonlocal (library) command line options.
14 // Note that rather than trying to figure out what this code does, you could try
15 // reading the library documentation located in docs/CommandLine.html
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Config/config.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/Streams.h"
23 #include "llvm/System/Path.h"
35 //===----------------------------------------------------------------------===//
36 // Template instantiations and anchors.
38 TEMPLATE_INSTANTIATION(class basic_parser
<bool>);
39 TEMPLATE_INSTANTIATION(class basic_parser
<boolOrDefault
>);
40 TEMPLATE_INSTANTIATION(class basic_parser
<int>);
41 TEMPLATE_INSTANTIATION(class basic_parser
<unsigned>);
42 TEMPLATE_INSTANTIATION(class basic_parser
<double>);
43 TEMPLATE_INSTANTIATION(class basic_parser
<float>);
44 TEMPLATE_INSTANTIATION(class basic_parser
<std::string
>);
46 TEMPLATE_INSTANTIATION(class opt
<unsigned>);
47 TEMPLATE_INSTANTIATION(class opt
<int>);
48 TEMPLATE_INSTANTIATION(class opt
<std::string
>);
49 TEMPLATE_INSTANTIATION(class opt
<bool>);
51 void Option::anchor() {}
52 void basic_parser_impl::anchor() {}
53 void parser
<bool>::anchor() {}
54 void parser
<boolOrDefault
>::anchor() {}
55 void parser
<int>::anchor() {}
56 void parser
<unsigned>::anchor() {}
57 void parser
<double>::anchor() {}
58 void parser
<float>::anchor() {}
59 void parser
<std::string
>::anchor() {}
61 //===----------------------------------------------------------------------===//
63 // Globals for name and overview of program. Program name is not a string to
64 // avoid static ctor/dtor issues.
65 static char ProgramName
[80] = "<premain>";
66 static const char *ProgramOverview
= 0;
68 // This collects additional help to be printed.
69 static ManagedStatic
<std::vector
<const char*> > MoreHelp
;
71 extrahelp::extrahelp(const char *Help
)
73 MoreHelp
->push_back(Help
);
76 static bool OptionListChanged
= false;
78 // MarkOptionsChanged - Internal helper function.
79 void cl::MarkOptionsChanged() {
80 OptionListChanged
= true;
83 /// RegisteredOptionList - This is the list of the command line options that
84 /// have statically constructed themselves.
85 static Option
*RegisteredOptionList
= 0;
87 void Option::addArgument() {
88 assert(NextRegistered
== 0 && "argument multiply registered!");
90 NextRegistered
= RegisteredOptionList
;
91 RegisteredOptionList
= this;
96 //===----------------------------------------------------------------------===//
97 // Basic, shared command line option processing machinery.
100 /// GetOptionInfo - Scan the list of registered options, turning them into data
101 /// structures that are easier to handle.
102 static void GetOptionInfo(std::vector
<Option
*> &PositionalOpts
,
103 std::map
<std::string
, Option
*> &OptionsMap
) {
104 std::vector
<const char*> OptionNames
;
105 Option
*CAOpt
= 0; // The ConsumeAfter option if it exists.
106 for (Option
*O
= RegisteredOptionList
; O
; O
= O
->getNextRegisteredOption()) {
107 // If this option wants to handle multiple option names, get the full set.
108 // This handles enum options like "-O1 -O2" etc.
109 O
->getExtraOptionNames(OptionNames
);
111 OptionNames
.push_back(O
->ArgStr
);
113 // Handle named options.
114 for (unsigned i
= 0, e
= OptionNames
.size(); i
!= e
; ++i
) {
115 // Add argument to the argument map!
116 if (!OptionsMap
.insert(std::pair
<std::string
,Option
*>(OptionNames
[i
],
118 cerr
<< ProgramName
<< ": CommandLine Error: Argument '"
119 << OptionNames
[0] << "' defined more than once!\n";
125 // Remember information about positional options.
126 if (O
->getFormattingFlag() == cl::Positional
)
127 PositionalOpts
.push_back(O
);
128 else if (O
->getNumOccurrencesFlag() == cl::ConsumeAfter
) {
130 O
->error("Cannot specify more than one option with cl::ConsumeAfter!");
136 PositionalOpts
.push_back(CAOpt
);
138 // Make sure that they are in order of registration not backwards.
139 std::reverse(PositionalOpts
.begin(), PositionalOpts
.end());
143 /// LookupOption - Lookup the option specified by the specified option on the
144 /// command line. If there is a value specified (after an equal sign) return
146 static Option
*LookupOption(const char *&Arg
, const char *&Value
,
147 std::map
<std::string
, Option
*> &OptionsMap
) {
148 while (*Arg
== '-') ++Arg
; // Eat leading dashes
150 const char *ArgEnd
= Arg
;
151 while (*ArgEnd
&& *ArgEnd
!= '=')
152 ++ArgEnd
; // Scan till end of argument name.
154 if (*ArgEnd
== '=') // If we have an equals sign...
155 Value
= ArgEnd
+1; // Get the value, not the equals
158 if (*Arg
== 0) return 0;
160 // Look up the option.
161 std::map
<std::string
, Option
*>::iterator I
=
162 OptionsMap
.find(std::string(Arg
, ArgEnd
));
163 return I
!= OptionsMap
.end() ? I
->second
: 0;
166 static inline bool ProvideOption(Option
*Handler
, const char *ArgName
,
167 const char *Value
, int argc
, char **argv
,
169 // Enforce value requirements
170 switch (Handler
->getValueExpectedFlag()) {
172 if (Value
== 0) { // No value specified?
173 if (i
+1 < argc
) { // Steal the next argument, like for '-o filename'
176 return Handler
->error(" requires a value!");
180 case ValueDisallowed
:
182 return Handler
->error(" does not allow a value! '" +
183 std::string(Value
) + "' specified.");
189 << ": Bad ValueMask flag! CommandLine usage error:"
190 << Handler
->getValueExpectedFlag() << "\n";
195 // Run the handler now!
196 return Handler
->addOccurrence(i
, ArgName
, Value
? Value
: "");
199 static bool ProvidePositionalOption(Option
*Handler
, const std::string
&Arg
,
202 return ProvideOption(Handler
, Handler
->ArgStr
, Arg
.c_str(), 0, 0, Dummy
);
206 // Option predicates...
207 static inline bool isGrouping(const Option
*O
) {
208 return O
->getFormattingFlag() == cl::Grouping
;
210 static inline bool isPrefixedOrGrouping(const Option
*O
) {
211 return isGrouping(O
) || O
->getFormattingFlag() == cl::Prefix
;
214 // getOptionPred - Check to see if there are any options that satisfy the
215 // specified predicate with names that are the prefixes in Name. This is
216 // checked by progressively stripping characters off of the name, checking to
217 // see if there options that satisfy the predicate. If we find one, return it,
218 // otherwise return null.
220 static Option
*getOptionPred(std::string Name
, unsigned &Length
,
221 bool (*Pred
)(const Option
*),
222 std::map
<std::string
, Option
*> &OptionsMap
) {
224 std::map
<std::string
, Option
*>::iterator OMI
= OptionsMap
.find(Name
);
225 if (OMI
!= OptionsMap
.end() && Pred(OMI
->second
)) {
226 Length
= Name
.length();
230 if (Name
.size() == 1) return 0;
232 Name
.erase(Name
.end()-1, Name
.end()); // Chop off the last character...
233 OMI
= OptionsMap
.find(Name
);
235 // Loop while we haven't found an option and Name still has at least two
236 // characters in it (so that the next iteration will not be the empty
238 } while ((OMI
== OptionsMap
.end() || !Pred(OMI
->second
)) && Name
.size() > 1);
240 if (OMI
!= OptionsMap
.end() && Pred(OMI
->second
)) {
241 Length
= Name
.length();
242 return OMI
->second
; // Found one!
244 return 0; // No option found!
247 static bool RequiresValue(const Option
*O
) {
248 return O
->getNumOccurrencesFlag() == cl::Required
||
249 O
->getNumOccurrencesFlag() == cl::OneOrMore
;
252 static bool EatsUnboundedNumberOfValues(const Option
*O
) {
253 return O
->getNumOccurrencesFlag() == cl::ZeroOrMore
||
254 O
->getNumOccurrencesFlag() == cl::OneOrMore
;
257 /// ParseCStringVector - Break INPUT up wherever one or more
258 /// whitespace characters are found, and store the resulting tokens in
259 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
260 /// using strdup (), so it is the caller's responsibility to free ()
263 static void ParseCStringVector(std::vector
<char *> &output
,
265 // Characters which will be treated as token separators:
266 static const char *delims
= " \v\f\t\r\n";
268 std::string
work (input
);
269 // Skip past any delims at head of input string.
270 size_t pos
= work
.find_first_not_of (delims
);
271 // If the string consists entirely of delims, then exit early.
272 if (pos
== std::string::npos
) return;
273 // Otherwise, jump forward to beginning of first word.
274 work
= work
.substr (pos
);
275 // Find position of first delimiter.
276 pos
= work
.find_first_of (delims
);
278 while (!work
.empty() && pos
!= std::string::npos
) {
279 // Everything from 0 to POS is the next word to copy.
280 output
.push_back (strdup (work
.substr (0,pos
).c_str ()));
281 // Is there another word in the string?
282 size_t nextpos
= work
.find_first_not_of (delims
, pos
+ 1);
283 if (nextpos
!= std::string::npos
) {
284 // Yes? Then remove delims from beginning ...
285 work
= work
.substr (work
.find_first_not_of (delims
, pos
+ 1));
286 // and find the end of the word.
287 pos
= work
.find_first_of (delims
);
289 // No? (Remainder of string is delims.) End the loop.
291 pos
= std::string::npos
;
295 // If `input' ended with non-delim char, then we'll get here with
296 // the last word of `input' in `work'; copy it now.
297 if (!work
.empty ()) {
298 output
.push_back (strdup (work
.c_str ()));
302 /// ParseEnvironmentOptions - An alternative entry point to the
303 /// CommandLine library, which allows you to read the program's name
304 /// from the caller (as PROGNAME) and its command-line arguments from
305 /// an environment variable (whose name is given in ENVVAR).
307 void cl::ParseEnvironmentOptions(const char *progName
, const char *envVar
,
308 const char *Overview
) {
310 assert(progName
&& "Program name not specified");
311 assert(envVar
&& "Environment variable name missing");
313 // Get the environment variable they want us to parse options out of.
314 const char *envValue
= getenv(envVar
);
318 // Get program's "name", which we wouldn't know without the caller
320 std::vector
<char*> newArgv
;
321 newArgv
.push_back(strdup(progName
));
323 // Parse the value of the environment variable into a "command line"
324 // and hand it off to ParseCommandLineOptions().
325 ParseCStringVector(newArgv
, envValue
);
326 int newArgc
= newArgv
.size();
327 ParseCommandLineOptions(newArgc
, &newArgv
[0], Overview
);
329 // Free all the strdup()ed strings.
330 for (std::vector
<char*>::iterator i
= newArgv
.begin(), e
= newArgv
.end();
335 void cl::ParseCommandLineOptions(int &argc
, char **argv
,
336 const char *Overview
) {
337 // Process all registered options.
338 std::vector
<Option
*> PositionalOpts
;
339 std::map
<std::string
, Option
*> Opts
;
340 GetOptionInfo(PositionalOpts
, Opts
);
342 assert((!Opts
.empty() || !PositionalOpts
.empty()) &&
343 "No options specified!");
344 sys::Path
progname(argv
[0]);
346 // Copy the program name into ProgName, making sure not to overflow it.
347 std::string ProgName
= sys::Path(argv
[0]).getLast();
348 if (ProgName
.size() > 79) ProgName
.resize(79);
349 strcpy(ProgramName
, ProgName
.c_str());
351 ProgramOverview
= Overview
;
352 bool ErrorParsing
= false;
354 // Check out the positional arguments to collect information about them.
355 unsigned NumPositionalRequired
= 0;
357 // Determine whether or not there are an unlimited number of positionals
358 bool HasUnlimitedPositionals
= false;
360 Option
*ConsumeAfterOpt
= 0;
361 if (!PositionalOpts
.empty()) {
362 if (PositionalOpts
[0]->getNumOccurrencesFlag() == cl::ConsumeAfter
) {
363 assert(PositionalOpts
.size() > 1 &&
364 "Cannot specify cl::ConsumeAfter without a positional argument!");
365 ConsumeAfterOpt
= PositionalOpts
[0];
368 // Calculate how many positional values are _required_.
369 bool UnboundedFound
= false;
370 for (unsigned i
= ConsumeAfterOpt
!= 0, e
= PositionalOpts
.size();
372 Option
*Opt
= PositionalOpts
[i
];
373 if (RequiresValue(Opt
))
374 ++NumPositionalRequired
;
375 else if (ConsumeAfterOpt
) {
376 // ConsumeAfter cannot be combined with "optional" positional options
377 // unless there is only one positional argument...
378 if (PositionalOpts
.size() > 2)
380 Opt
->error(" error - this positional option will never be matched, "
381 "because it does not Require a value, and a "
382 "cl::ConsumeAfter option is active!");
383 } else if (UnboundedFound
&& !Opt
->ArgStr
[0]) {
384 // This option does not "require" a value... Make sure this option is
385 // not specified after an option that eats all extra arguments, or this
386 // one will never get any!
388 ErrorParsing
|= Opt
->error(" error - option can never match, because "
389 "another positional argument will match an "
390 "unbounded number of values, and this option"
391 " does not require a value!");
393 UnboundedFound
|= EatsUnboundedNumberOfValues(Opt
);
395 HasUnlimitedPositionals
= UnboundedFound
|| ConsumeAfterOpt
;
398 // PositionalVals - A vector of "positional" arguments we accumulate into
399 // the process at the end...
401 std::vector
<std::pair
<std::string
,unsigned> > PositionalVals
;
403 // If the program has named positional arguments, and the name has been run
404 // across, keep track of which positional argument was named. Otherwise put
405 // the positional args into the PositionalVals list...
406 Option
*ActivePositionalArg
= 0;
408 // Loop over all of the arguments... processing them.
409 bool DashDashFound
= false; // Have we read '--'?
410 for (int i
= 1; i
< argc
; ++i
) {
412 const char *Value
= 0;
413 const char *ArgName
= "";
415 // If the option list changed, this means that some command line
416 // option has just been registered or deregistered. This can occur in
417 // response to things like -load, etc. If this happens, rescan the options.
418 if (OptionListChanged
) {
419 PositionalOpts
.clear();
421 GetOptionInfo(PositionalOpts
, Opts
);
422 OptionListChanged
= false;
425 // Check to see if this is a positional argument. This argument is
426 // considered to be positional if it doesn't start with '-', if it is "-"
427 // itself, or if we have seen "--" already.
429 if (argv
[i
][0] != '-' || argv
[i
][1] == 0 || DashDashFound
) {
430 // Positional argument!
431 if (ActivePositionalArg
) {
432 ProvidePositionalOption(ActivePositionalArg
, argv
[i
], i
);
433 continue; // We are done!
434 } else if (!PositionalOpts
.empty()) {
435 PositionalVals
.push_back(std::make_pair(argv
[i
],i
));
437 // All of the positional arguments have been fulfulled, give the rest to
438 // the consume after option... if it's specified...
440 if (PositionalVals
.size() >= NumPositionalRequired
&&
441 ConsumeAfterOpt
!= 0) {
442 for (++i
; i
< argc
; ++i
)
443 PositionalVals
.push_back(std::make_pair(argv
[i
],i
));
444 break; // Handle outside of the argument processing loop...
447 // Delay processing positional arguments until the end...
450 } else if (argv
[i
][0] == '-' && argv
[i
][1] == '-' && argv
[i
][2] == 0 &&
452 DashDashFound
= true; // This is the mythical "--"?
453 continue; // Don't try to process it as an argument itself.
454 } else if (ActivePositionalArg
&&
455 (ActivePositionalArg
->getMiscFlags() & PositionalEatsArgs
)) {
456 // If there is a positional argument eating options, check to see if this
457 // option is another positional argument. If so, treat it as an argument,
458 // otherwise feed it to the eating positional.
460 Handler
= LookupOption(ArgName
, Value
, Opts
);
461 if (!Handler
|| Handler
->getFormattingFlag() != cl::Positional
) {
462 ProvidePositionalOption(ActivePositionalArg
, argv
[i
], i
);
463 continue; // We are done!
466 } else { // We start with a '-', must be an argument...
468 Handler
= LookupOption(ArgName
, Value
, Opts
);
470 // Check to see if this "option" is really a prefixed or grouped argument.
472 std::string
RealName(ArgName
);
473 if (RealName
.size() > 1) {
475 Option
*PGOpt
= getOptionPred(RealName
, Length
, isPrefixedOrGrouping
,
478 // If the option is a prefixed option, then the value is simply the
479 // rest of the name... so fall through to later processing, by
480 // setting up the argument name flags and value fields.
482 if (PGOpt
&& PGOpt
->getFormattingFlag() == cl::Prefix
) {
483 Value
= ArgName
+Length
;
484 assert(Opts
.find(std::string(ArgName
, Value
)) != Opts
.end() &&
485 Opts
.find(std::string(ArgName
, Value
))->second
== PGOpt
);
488 // This must be a grouped option... handle them now.
489 assert(isGrouping(PGOpt
) && "Broken getOptionPred!");
492 // Move current arg name out of RealName into RealArgName...
493 std::string
RealArgName(RealName
.begin(),
494 RealName
.begin() + Length
);
495 RealName
.erase(RealName
.begin(), RealName
.begin() + Length
);
497 // Because ValueRequired is an invalid flag for grouped arguments,
498 // we don't need to pass argc/argv in...
500 assert(PGOpt
->getValueExpectedFlag() != cl::ValueRequired
&&
501 "Option can not be cl::Grouping AND cl::ValueRequired!");
503 ErrorParsing
|= ProvideOption(PGOpt
, RealArgName
.c_str(),
506 // Get the next grouping option...
507 PGOpt
= getOptionPred(RealName
, Length
, isGrouping
, Opts
);
508 } while (PGOpt
&& Length
!= RealName
.size());
510 Handler
= PGOpt
; // Ate all of the options.
517 cerr
<< ProgramName
<< ": Unknown command line argument '"
518 << argv
[i
] << "'. Try: '" << argv
[0] << " --help'\n";
523 // Check to see if this option accepts a comma separated list of values. If
524 // it does, we have to split up the value into multiple values...
525 if (Value
&& Handler
->getMiscFlags() & CommaSeparated
) {
526 std::string
Val(Value
);
527 std::string::size_type Pos
= Val
.find(',');
529 while (Pos
!= std::string::npos
) {
530 // Process the portion before the comma...
531 ErrorParsing
|= ProvideOption(Handler
, ArgName
,
532 std::string(Val
.begin(),
533 Val
.begin()+Pos
).c_str(),
535 // Erase the portion before the comma, AND the comma...
536 Val
.erase(Val
.begin(), Val
.begin()+Pos
+1);
537 Value
+= Pos
+1; // Increment the original value pointer as well...
539 // Check for another comma...
544 // If this is a named positional argument, just remember that it is the
546 if (Handler
->getFormattingFlag() == cl::Positional
)
547 ActivePositionalArg
= Handler
;
549 ErrorParsing
|= ProvideOption(Handler
, ArgName
, Value
, argc
, argv
, i
);
552 // Check and handle positional arguments now...
553 if (NumPositionalRequired
> PositionalVals
.size()) {
555 << ": Not enough positional command line arguments specified!\n"
556 << "Must specify at least " << NumPositionalRequired
557 << " positional arguments: See: " << argv
[0] << " --help\n";
560 } else if (!HasUnlimitedPositionals
561 && PositionalVals
.size() > PositionalOpts
.size()) {
563 << ": Too many positional arguments specified!\n"
564 << "Can specify at most " << PositionalOpts
.size()
565 << " positional arguments: See: " << argv
[0] << " --help\n";
568 } else if (ConsumeAfterOpt
== 0) {
569 // Positional args have already been handled if ConsumeAfter is specified...
570 unsigned ValNo
= 0, NumVals
= PositionalVals
.size();
571 for (unsigned i
= 0, e
= PositionalOpts
.size(); i
!= e
; ++i
) {
572 if (RequiresValue(PositionalOpts
[i
])) {
573 ProvidePositionalOption(PositionalOpts
[i
], PositionalVals
[ValNo
].first
,
574 PositionalVals
[ValNo
].second
);
576 --NumPositionalRequired
; // We fulfilled our duty...
579 // If we _can_ give this option more arguments, do so now, as long as we
580 // do not give it values that others need. 'Done' controls whether the
581 // option even _WANTS_ any more.
583 bool Done
= PositionalOpts
[i
]->getNumOccurrencesFlag() == cl::Required
;
584 while (NumVals
-ValNo
> NumPositionalRequired
&& !Done
) {
585 switch (PositionalOpts
[i
]->getNumOccurrencesFlag()) {
587 Done
= true; // Optional arguments want _at most_ one value
589 case cl::ZeroOrMore
: // Zero or more will take all they can get...
590 case cl::OneOrMore
: // One or more will take all they can get...
591 ProvidePositionalOption(PositionalOpts
[i
],
592 PositionalVals
[ValNo
].first
,
593 PositionalVals
[ValNo
].second
);
597 assert(0 && "Internal error, unexpected NumOccurrences flag in "
598 "positional argument processing!");
603 assert(ConsumeAfterOpt
&& NumPositionalRequired
<= PositionalVals
.size());
605 for (unsigned j
= 1, e
= PositionalOpts
.size(); j
!= e
; ++j
)
606 if (RequiresValue(PositionalOpts
[j
])) {
607 ErrorParsing
|= ProvidePositionalOption(PositionalOpts
[j
],
608 PositionalVals
[ValNo
].first
,
609 PositionalVals
[ValNo
].second
);
613 // Handle the case where there is just one positional option, and it's
614 // optional. In this case, we want to give JUST THE FIRST option to the
615 // positional option and keep the rest for the consume after. The above
616 // loop would have assigned no values to positional options in this case.
618 if (PositionalOpts
.size() == 2 && ValNo
== 0 && !PositionalVals
.empty()) {
619 ErrorParsing
|= ProvidePositionalOption(PositionalOpts
[1],
620 PositionalVals
[ValNo
].first
,
621 PositionalVals
[ValNo
].second
);
625 // Handle over all of the rest of the arguments to the
626 // cl::ConsumeAfter command line option...
627 for (; ValNo
!= PositionalVals
.size(); ++ValNo
)
628 ErrorParsing
|= ProvidePositionalOption(ConsumeAfterOpt
,
629 PositionalVals
[ValNo
].first
,
630 PositionalVals
[ValNo
].second
);
633 // Loop over args and make sure all required args are specified!
634 for (std::map
<std::string
, Option
*>::iterator I
= Opts
.begin(),
635 E
= Opts
.end(); I
!= E
; ++I
) {
636 switch (I
->second
->getNumOccurrencesFlag()) {
639 if (I
->second
->getNumOccurrences() == 0) {
640 I
->second
->error(" must be specified at least once!");
649 // Free all of the memory allocated to the map. Command line options may only
650 // be processed once!
652 PositionalOpts
.clear();
655 // If we had an error processing our arguments, don't let the program execute
656 if (ErrorParsing
) exit(1);
659 //===----------------------------------------------------------------------===//
660 // Option Base class implementation
663 bool Option::error(std::string Message
, const char *ArgName
) {
664 if (ArgName
== 0) ArgName
= ArgStr
;
666 cerr
<< HelpStr
; // Be nice for positional arguments
668 cerr
<< ProgramName
<< ": for the -" << ArgName
;
670 cerr
<< " option: " << Message
<< "\n";
674 bool Option::addOccurrence(unsigned pos
, const char *ArgName
,
675 const std::string
&Value
) {
676 NumOccurrences
++; // Increment the number of times we have been seen
678 switch (getNumOccurrencesFlag()) {
680 if (NumOccurrences
> 1)
681 return error(": may only occur zero or one times!", ArgName
);
684 if (NumOccurrences
> 1)
685 return error(": must occur exactly one time!", ArgName
);
689 case ConsumeAfter
: break;
690 default: return error(": bad num occurrences flag value!");
693 return handleOccurrence(pos
, ArgName
, Value
);
697 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
698 // has been specified yet.
700 static const char *getValueStr(const Option
&O
, const char *DefaultMsg
) {
701 if (O
.ValueStr
[0] == 0) return DefaultMsg
;
705 //===----------------------------------------------------------------------===//
706 // cl::alias class implementation
709 // Return the width of the option tag for printing...
710 unsigned alias::getOptionWidth() const {
711 return std::strlen(ArgStr
)+6;
714 // Print out the option for the alias.
715 void alias::printOptionInfo(unsigned GlobalWidth
) const {
716 unsigned L
= std::strlen(ArgStr
);
717 cout
<< " -" << ArgStr
<< std::string(GlobalWidth
-L
-6, ' ') << " - "
723 //===----------------------------------------------------------------------===//
724 // Parser Implementation code...
727 // basic_parser implementation
730 // Return the width of the option tag for printing...
731 unsigned basic_parser_impl::getOptionWidth(const Option
&O
) const {
732 unsigned Len
= std::strlen(O
.ArgStr
);
733 if (const char *ValName
= getValueName())
734 Len
+= std::strlen(getValueStr(O
, ValName
))+3;
739 // printOptionInfo - Print out information about this option. The
740 // to-be-maintained width is specified.
742 void basic_parser_impl::printOptionInfo(const Option
&O
,
743 unsigned GlobalWidth
) const {
744 cout
<< " -" << O
.ArgStr
;
746 if (const char *ValName
= getValueName())
747 cout
<< "=<" << getValueStr(O
, ValName
) << ">";
749 cout
<< std::string(GlobalWidth
-getOptionWidth(O
), ' ') << " - "
750 << O
.HelpStr
<< "\n";
756 // parser<bool> implementation
758 bool parser
<bool>::parse(Option
&O
, const char *ArgName
,
759 const std::string
&Arg
, bool &Value
) {
760 if (Arg
== "" || Arg
== "true" || Arg
== "TRUE" || Arg
== "True" ||
763 } else if (Arg
== "false" || Arg
== "FALSE" || Arg
== "False" || Arg
== "0") {
766 return O
.error(": '" + Arg
+
767 "' is invalid value for boolean argument! Try 0 or 1");
772 // parser<boolOrDefault> implementation
774 bool parser
<boolOrDefault
>::parse(Option
&O
, const char *ArgName
,
775 const std::string
&Arg
, boolOrDefault
&Value
) {
776 if (Arg
== "" || Arg
== "true" || Arg
== "TRUE" || Arg
== "True" ||
779 } else if (Arg
== "false" || Arg
== "FALSE" || Arg
== "False" || Arg
== "0") {
782 return O
.error(": '" + Arg
+
783 "' is invalid value for boolean argument! Try 0 or 1");
788 // parser<int> implementation
790 bool parser
<int>::parse(Option
&O
, const char *ArgName
,
791 const std::string
&Arg
, int &Value
) {
793 Value
= (int)strtol(Arg
.c_str(), &End
, 0);
795 return O
.error(": '" + Arg
+ "' value invalid for integer argument!");
799 // parser<unsigned> implementation
801 bool parser
<unsigned>::parse(Option
&O
, const char *ArgName
,
802 const std::string
&Arg
, unsigned &Value
) {
805 unsigned long V
= strtoul(Arg
.c_str(), &End
, 0);
807 if (((V
== ULONG_MAX
) && (errno
== ERANGE
))
810 return O
.error(": '" + Arg
+ "' value invalid for uint argument!");
814 // parser<double>/parser<float> implementation
816 static bool parseDouble(Option
&O
, const std::string
&Arg
, double &Value
) {
817 const char *ArgStart
= Arg
.c_str();
819 Value
= strtod(ArgStart
, &End
);
821 return O
.error(": '" +Arg
+ "' value invalid for floating point argument!");
825 bool parser
<double>::parse(Option
&O
, const char *AN
,
826 const std::string
&Arg
, double &Val
) {
827 return parseDouble(O
, Arg
, Val
);
830 bool parser
<float>::parse(Option
&O
, const char *AN
,
831 const std::string
&Arg
, float &Val
) {
833 if (parseDouble(O
, Arg
, dVal
))
841 // generic_parser_base implementation
844 // findOption - Return the option number corresponding to the specified
845 // argument string. If the option is not found, getNumOptions() is returned.
847 unsigned generic_parser_base::findOption(const char *Name
) {
848 unsigned i
= 0, e
= getNumOptions();
852 if (getOption(i
) == N
)
860 // Return the width of the option tag for printing...
861 unsigned generic_parser_base::getOptionWidth(const Option
&O
) const {
863 unsigned Size
= std::strlen(O
.ArgStr
)+6;
864 for (unsigned i
= 0, e
= getNumOptions(); i
!= e
; ++i
)
865 Size
= std::max(Size
, (unsigned)std::strlen(getOption(i
))+8);
868 unsigned BaseSize
= 0;
869 for (unsigned i
= 0, e
= getNumOptions(); i
!= e
; ++i
)
870 BaseSize
= std::max(BaseSize
, (unsigned)std::strlen(getOption(i
))+8);
875 // printOptionInfo - Print out information about this option. The
876 // to-be-maintained width is specified.
878 void generic_parser_base::printOptionInfo(const Option
&O
,
879 unsigned GlobalWidth
) const {
881 unsigned L
= std::strlen(O
.ArgStr
);
882 cout
<< " -" << O
.ArgStr
<< std::string(GlobalWidth
-L
-6, ' ')
883 << " - " << O
.HelpStr
<< "\n";
885 for (unsigned i
= 0, e
= getNumOptions(); i
!= e
; ++i
) {
886 unsigned NumSpaces
= GlobalWidth
-strlen(getOption(i
))-8;
887 cout
<< " =" << getOption(i
) << std::string(NumSpaces
, ' ')
888 << " - " << getDescription(i
) << "\n";
892 cout
<< " " << O
.HelpStr
<< "\n";
893 for (unsigned i
= 0, e
= getNumOptions(); i
!= e
; ++i
) {
894 unsigned L
= std::strlen(getOption(i
));
895 cout
<< " -" << getOption(i
) << std::string(GlobalWidth
-L
-8, ' ')
896 << " - " << getDescription(i
) << "\n";
902 //===----------------------------------------------------------------------===//
903 // --help and --help-hidden option implementation
910 const Option
*EmptyArg
;
911 const bool ShowHidden
;
913 // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
914 inline static bool isHidden(std::pair
<std::string
, Option
*> &OptPair
) {
915 return OptPair
.second
->getOptionHiddenFlag() >= Hidden
;
917 inline static bool isReallyHidden(std::pair
<std::string
, Option
*> &OptPair
) {
918 return OptPair
.second
->getOptionHiddenFlag() == ReallyHidden
;
922 HelpPrinter(bool showHidden
) : ShowHidden(showHidden
) {
926 void operator=(bool Value
) {
927 if (Value
== false) return;
929 // Get all the options.
930 std::vector
<Option
*> PositionalOpts
;
931 std::map
<std::string
, Option
*> OptMap
;
932 GetOptionInfo(PositionalOpts
, OptMap
);
934 // Copy Options into a vector so we can sort them as we like...
935 std::vector
<std::pair
<std::string
, Option
*> > Opts
;
936 copy(OptMap
.begin(), OptMap
.end(), std::back_inserter(Opts
));
938 // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
939 Opts
.erase(std::remove_if(Opts
.begin(), Opts
.end(),
940 std::ptr_fun(ShowHidden
? isReallyHidden
: isHidden
)),
943 // Eliminate duplicate entries in table (from enum flags options, f.e.)
944 { // Give OptionSet a scope
945 std::set
<Option
*> OptionSet
;
946 for (unsigned i
= 0; i
!= Opts
.size(); ++i
)
947 if (OptionSet
.count(Opts
[i
].second
) == 0)
948 OptionSet
.insert(Opts
[i
].second
); // Add new entry to set
950 Opts
.erase(Opts
.begin()+i
--); // Erase duplicate
954 cout
<< "OVERVIEW:" << ProgramOverview
<< "\n";
956 cout
<< "USAGE: " << ProgramName
<< " [options]";
958 // Print out the positional options.
959 Option
*CAOpt
= 0; // The cl::ConsumeAfter option, if it exists...
960 if (!PositionalOpts
.empty() &&
961 PositionalOpts
[0]->getNumOccurrencesFlag() == ConsumeAfter
)
962 CAOpt
= PositionalOpts
[0];
964 for (unsigned i
= CAOpt
!= 0, e
= PositionalOpts
.size(); i
!= e
; ++i
) {
965 if (PositionalOpts
[i
]->ArgStr
[0])
966 cout
<< " --" << PositionalOpts
[i
]->ArgStr
;
967 cout
<< " " << PositionalOpts
[i
]->HelpStr
;
970 // Print the consume after option info if it exists...
971 if (CAOpt
) cout
<< " " << CAOpt
->HelpStr
;
975 // Compute the maximum argument length...
977 for (unsigned i
= 0, e
= Opts
.size(); i
!= e
; ++i
)
978 MaxArgLen
= std::max(MaxArgLen
, Opts
[i
].second
->getOptionWidth());
980 cout
<< "OPTIONS:\n";
981 for (unsigned i
= 0, e
= Opts
.size(); i
!= e
; ++i
)
982 Opts
[i
].second
->printOptionInfo(MaxArgLen
);
984 // Print any extra help the user has declared.
985 for (std::vector
<const char *>::iterator I
= MoreHelp
->begin(),
986 E
= MoreHelp
->end(); I
!= E
; ++I
)
990 // Halt the program since help information was printed
994 } // End anonymous namespace
996 // Define the two HelpPrinter instances that are used to print out help, or
999 static HelpPrinter
NormalPrinter(false);
1000 static HelpPrinter
HiddenPrinter(true);
1002 static cl::opt
<HelpPrinter
, true, parser
<bool> >
1003 HOp("help", cl::desc("Display available options (--help-hidden for more)"),
1004 cl::location(NormalPrinter
), cl::ValueDisallowed
);
1006 static cl::opt
<HelpPrinter
, true, parser
<bool> >
1007 HHOp("help-hidden", cl::desc("Display all available options"),
1008 cl::location(HiddenPrinter
), cl::Hidden
, cl::ValueDisallowed
);
1010 static void (*OverrideVersionPrinter
)() = 0;
1013 class VersionPrinter
{
1016 cout
<< "Low Level Virtual Machine (http://llvm.org/):\n";
1017 cout
<< " " << PACKAGE_NAME
<< " version " << PACKAGE_VERSION
;
1018 #ifdef LLVM_VERSION_INFO
1019 cout
<< LLVM_VERSION_INFO
;
1022 #ifndef __OPTIMIZE__
1023 cout
<< "DEBUG build";
1025 cout
<< "Optimized build";
1028 cout
<< " with assertions";
1032 void operator=(bool OptionWasSpecified
) {
1033 if (OptionWasSpecified
) {
1034 if (OverrideVersionPrinter
== 0) {
1038 (*OverrideVersionPrinter
)();
1044 } // End anonymous namespace
1047 // Define the --version option that prints out the LLVM version for the tool
1048 static VersionPrinter VersionPrinterInstance
;
1050 static cl::opt
<VersionPrinter
, true, parser
<bool> >
1051 VersOp("version", cl::desc("Display the version of this program"),
1052 cl::location(VersionPrinterInstance
), cl::ValueDisallowed
);
1054 // Utility function for printing the help message.
1055 void cl::PrintHelpMessage() {
1056 // This looks weird, but it actually prints the help message. The
1057 // NormalPrinter variable is a HelpPrinter and the help gets printed when
1058 // its operator= is invoked. That's because the "normal" usages of the
1059 // help printer is to be assigned true/false depending on whether the
1060 // --help option was given or not. Since we're circumventing that we have
1061 // to make it look like --help was given, so we assign true.
1062 NormalPrinter
= true;
1065 /// Utility function for printing version number.
1066 void cl::PrintVersionMessage() {
1067 VersionPrinterInstance
.print();
1070 void cl::SetVersionPrinter(void (*func
)()) {
1071 OverrideVersionPrinter
= func
;