CommandLine.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  1. //===-- CommandLine.cpp - Command line parser implementation --------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  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.
  13. //
  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
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/Config/config.h"
  19. #include "llvm/Support/CommandLine.h"
  20. #include "llvm/Support/ManagedStatic.h"
  21. #include "llvm/Support/Streams.h"
  22. #include "llvm/System/Path.h"
  23. #include <algorithm>
  24. #include <functional>
  25. #include <map>
  26. #include <ostream>
  27. #include <set>
  28. #include <cstdlib>
  29. #include <cerrno>
  30. #include <cstring>
  31. #include <climits>
  32. using namespace llvm;
  33. using namespace cl;
  34. //===----------------------------------------------------------------------===//
  35. // Template instantiations and anchors.
  36. //
  37. TEMPLATE_INSTANTIATION(class basic_parser<bool>);
  38. TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
  39. TEMPLATE_INSTANTIATION(class basic_parser<int>);
  40. TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
  41. TEMPLATE_INSTANTIATION(class basic_parser<double>);
  42. TEMPLATE_INSTANTIATION(class basic_parser<float>);
  43. TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
  44. TEMPLATE_INSTANTIATION(class opt<unsigned>);
  45. TEMPLATE_INSTANTIATION(class opt<int>);
  46. TEMPLATE_INSTANTIATION(class opt<std::string>);
  47. TEMPLATE_INSTANTIATION(class opt<bool>);
  48. void Option::anchor() {}
  49. void basic_parser_impl::anchor() {}
  50. void parser<bool>::anchor() {}
  51. void parser<boolOrDefault>::anchor() {}
  52. void parser<int>::anchor() {}
  53. void parser<unsigned>::anchor() {}
  54. void parser<double>::anchor() {}
  55. void parser<float>::anchor() {}
  56. void parser<std::string>::anchor() {}
  57. //===----------------------------------------------------------------------===//
  58. // Globals for name and overview of program. Program name is not a string to
  59. // avoid static ctor/dtor issues.
  60. static char ProgramName[80] = "<premain>";
  61. static const char *ProgramOverview = 0;
  62. // This collects additional help to be printed.
  63. static ManagedStatic<std::vector<const char*> > MoreHelp;
  64. extrahelp::extrahelp(const char *Help)
  65. : morehelp(Help) {
  66. MoreHelp->push_back(Help);
  67. }
  68. static bool OptionListChanged = false;
  69. // MarkOptionsChanged - Internal helper function.
  70. void cl::MarkOptionsChanged() {
  71. OptionListChanged = true;
  72. }
  73. /// RegisteredOptionList - This is the list of the command line options that
  74. /// have statically constructed themselves.
  75. static Option *RegisteredOptionList = 0;
  76. void Option::addArgument() {
  77. assert(NextRegistered == 0 && "argument multiply registered!");
  78. NextRegistered = RegisteredOptionList;
  79. RegisteredOptionList = this;
  80. MarkOptionsChanged();
  81. }
  82. //===----------------------------------------------------------------------===//
  83. // Basic, shared command line option processing machinery.
  84. //
  85. /// GetOptionInfo - Scan the list of registered options, turning them into data
  86. /// structures that are easier to handle.
  87. static void GetOptionInfo(std::vector<Option*> &PositionalOpts,
  88. std::map<std::string, Option*> &OptionsMap) {
  89. std::vector<const char*> OptionNames;
  90. Option *CAOpt = 0; // The ConsumeAfter option if it exists.
  91. for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
  92. // If this option wants to handle multiple option names, get the full set.
  93. // This handles enum options like "-O1 -O2" etc.
  94. O->getExtraOptionNames(OptionNames);
  95. if (O->ArgStr[0])
  96. OptionNames.push_back(O->ArgStr);
  97. // Handle named options.
  98. for (unsigned i = 0, e = OptionNames.size(); i != e; ++i) {
  99. // Add argument to the argument map!
  100. if (!OptionsMap.insert(std::pair<std::string,Option*>(OptionNames[i],
  101. O)).second) {
  102. cerr << ProgramName << ": CommandLine Error: Argument '"
  103. << OptionNames[0] << "' defined more than once!\n";
  104. }
  105. }
  106. OptionNames.clear();
  107. // Remember information about positional options.
  108. if (O->getFormattingFlag() == cl::Positional)
  109. PositionalOpts.push_back(O);
  110. else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
  111. if (CAOpt)
  112. O->error("Cannot specify more than one option with cl::ConsumeAfter!");
  113. CAOpt = O;
  114. }
  115. }
  116. if (CAOpt)
  117. PositionalOpts.push_back(CAOpt);
  118. // Make sure that they are in order of registration not backwards.
  119. std::reverse(PositionalOpts.begin(), PositionalOpts.end());
  120. }
  121. /// LookupOption - Lookup the option specified by the specified option on the
  122. /// command line. If there is a value specified (after an equal sign) return
  123. /// that as well.
  124. static Option *LookupOption(const char *&Arg, const char *&Value,
  125. std::map<std::string, Option*> &OptionsMap) {
  126. while (*Arg == '-') ++Arg; // Eat leading dashes
  127. const char *ArgEnd = Arg;
  128. while (*ArgEnd && *ArgEnd != '=')
  129. ++ArgEnd; // Scan till end of argument name.
  130. if (*ArgEnd == '=') // If we have an equals sign...
  131. Value = ArgEnd+1; // Get the value, not the equals
  132. if (*Arg == 0) return 0;
  133. // Look up the option.
  134. std::map<std::string, Option*>::iterator I =
  135. OptionsMap.find(std::string(Arg, ArgEnd));
  136. return I != OptionsMap.end() ? I->second : 0;
  137. }
  138. static inline bool ProvideOption(Option *Handler, const char *ArgName,
  139. const char *Value, int argc, char **argv,
  140. int &i) {
  141. // Enforce value requirements
  142. switch (Handler->getValueExpectedFlag()) {
  143. case ValueRequired:
  144. if (Value == 0) { // No value specified?
  145. if (i+1 < argc) { // Steal the next argument, like for '-o filename'
  146. Value = argv[++i];
  147. } else {
  148. return Handler->error(" requires a value!");
  149. }
  150. }
  151. break;
  152. case ValueDisallowed:
  153. if (Value)
  154. return Handler->error(" does not allow a value! '" +
  155. std::string(Value) + "' specified.");
  156. break;
  157. case ValueOptional:
  158. break;
  159. default:
  160. cerr << ProgramName
  161. << ": Bad ValueMask flag! CommandLine usage error:"
  162. << Handler->getValueExpectedFlag() << "\n";
  163. abort();
  164. break;
  165. }
  166. // Run the handler now!
  167. return Handler->addOccurrence(i, ArgName, Value ? Value : "");
  168. }
  169. static bool ProvidePositionalOption(Option *Handler, const std::string &Arg,
  170. int i) {
  171. int Dummy = i;
  172. return ProvideOption(Handler, Handler->ArgStr, Arg.c_str(), 0, 0, Dummy);
  173. }
  174. // Option predicates...
  175. static inline bool isGrouping(const Option *O) {
  176. return O->getFormattingFlag() == cl::Grouping;
  177. }
  178. static inline bool isPrefixedOrGrouping(const Option *O) {
  179. return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
  180. }
  181. // getOptionPred - Check to see if there are any options that satisfy the
  182. // specified predicate with names that are the prefixes in Name. This is
  183. // checked by progressively stripping characters off of the name, checking to
  184. // see if there options that satisfy the predicate. If we find one, return it,
  185. // otherwise return null.
  186. //
  187. static Option *getOptionPred(std::string Name, unsigned &Length,
  188. bool (*Pred)(const Option*),
  189. std::map<std::string, Option*> &OptionsMap) {
  190. std::map<std::string, Option*>::iterator OMI = OptionsMap.find(Name);
  191. if (OMI != OptionsMap.end() && Pred(OMI->second)) {
  192. Length = Name.length();
  193. return OMI->second;
  194. }
  195. if (Name.size() == 1) return 0;
  196. do {
  197. Name.erase(Name.end()-1, Name.end()); // Chop off the last character...
  198. OMI = OptionsMap.find(Name);
  199. // Loop while we haven't found an option and Name still has at least two
  200. // characters in it (so that the next iteration will not be the empty
  201. // string...
  202. } while ((OMI == OptionsMap.end() || !Pred(OMI->second)) && Name.size() > 1);
  203. if (OMI != OptionsMap.end() && Pred(OMI->second)) {
  204. Length = Name.length();
  205. return OMI->second; // Found one!
  206. }
  207. return 0; // No option found!
  208. }
  209. static bool RequiresValue(const Option *O) {
  210. return O->getNumOccurrencesFlag() == cl::Required ||
  211. O->getNumOccurrencesFlag() == cl::OneOrMore;
  212. }
  213. static bool EatsUnboundedNumberOfValues(const Option *O) {
  214. return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
  215. O->getNumOccurrencesFlag() == cl::OneOrMore;
  216. }
  217. /// ParseCStringVector - Break INPUT up wherever one or more
  218. /// whitespace characters are found, and store the resulting tokens in
  219. /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
  220. /// using strdup (), so it is the caller's responsibility to free ()
  221. /// them later.
  222. ///
  223. static void ParseCStringVector(std::vector<char *> &output,
  224. const char *input) {
  225. // Characters which will be treated as token separators:
  226. static const char *delims = " \v\f\t\r\n";
  227. std::string work (input);
  228. // Skip past any delims at head of input string.
  229. size_t pos = work.find_first_not_of (delims);
  230. // If the string consists entirely of delims, then exit early.
  231. if (pos == std::string::npos) return;
  232. // Otherwise, jump forward to beginning of first word.
  233. work = work.substr (pos);
  234. // Find position of first delimiter.
  235. pos = work.find_first_of (delims);
  236. while (!work.empty() && pos != std::string::npos) {
  237. // Everything from 0 to POS is the next word to copy.
  238. output.push_back (strdup (work.substr (0,pos).c_str ()));
  239. // Is there another word in the string?
  240. size_t nextpos = work.find_first_not_of (delims, pos + 1);
  241. if (nextpos != std::string::npos) {
  242. // Yes? Then remove delims from beginning ...
  243. work = work.substr (work.find_first_not_of (delims, pos + 1));
  244. // and find the end of the word.
  245. pos = work.find_first_of (delims);
  246. } else {
  247. // No? (Remainder of string is delims.) End the loop.
  248. work = "";
  249. pos = std::string::npos;
  250. }
  251. }
  252. // If `input' ended with non-delim char, then we'll get here with
  253. // the last word of `input' in `work'; copy it now.
  254. if (!work.empty ()) {
  255. output.push_back (strdup (work.c_str ()));
  256. }
  257. }
  258. /// ParseEnvironmentOptions - An alternative entry point to the
  259. /// CommandLine library, which allows you to read the program's name
  260. /// from the caller (as PROGNAME) and its command-line arguments from
  261. /// an environment variable (whose name is given in ENVVAR).
  262. ///
  263. void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
  264. const char *Overview) {
  265. // Check args.
  266. assert(progName && "Program name not specified");
  267. assert(envVar && "Environment variable name missing");
  268. // Get the environment variable they want us to parse options out of.
  269. const char *envValue = getenv(envVar);
  270. if (!envValue)
  271. return;
  272. // Get program's "name", which we wouldn't know without the caller
  273. // telling us.
  274. std::vector<char*> newArgv;
  275. newArgv.push_back(strdup(progName));
  276. // Parse the value of the environment variable into a "command line"
  277. // and hand it off to ParseCommandLineOptions().
  278. ParseCStringVector(newArgv, envValue);
  279. int newArgc = newArgv.size();
  280. ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
  281. // Free all the strdup()ed strings.
  282. for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
  283. i != e; ++i)
  284. free (*i);
  285. }
  286. void cl::ParseCommandLineOptions(int argc, char **argv,
  287. const char *Overview) {
  288. // Process all registered options.
  289. std::vector<Option*> PositionalOpts;
  290. std::map<std::string, Option*> Opts;
  291. GetOptionInfo(PositionalOpts, Opts);
  292. assert((!Opts.empty() || !PositionalOpts.empty()) &&
  293. "No options specified!");
  294. sys::Path progname(argv[0]);
  295. // Copy the program name into ProgName, making sure not to overflow it.
  296. std::string ProgName = sys::Path(argv[0]).getLast();
  297. if (ProgName.size() > 79) ProgName.resize(79);
  298. strcpy(ProgramName, ProgName.c_str());
  299. ProgramOverview = Overview;
  300. bool ErrorParsing = false;
  301. // Check out the positional arguments to collect information about them.
  302. unsigned NumPositionalRequired = 0;
  303. // Determine whether or not there are an unlimited number of positionals
  304. bool HasUnlimitedPositionals = false;
  305. Option *ConsumeAfterOpt = 0;
  306. if (!PositionalOpts.empty()) {
  307. if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
  308. assert(PositionalOpts.size() > 1 &&
  309. "Cannot specify cl::ConsumeAfter without a positional argument!");
  310. ConsumeAfterOpt = PositionalOpts[0];
  311. }
  312. // Calculate how many positional values are _required_.
  313. bool UnboundedFound = false;
  314. for (unsigned i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
  315. i != e; ++i) {
  316. Option *Opt = PositionalOpts[i];
  317. if (RequiresValue(Opt))
  318. ++NumPositionalRequired;
  319. else if (ConsumeAfterOpt) {
  320. // ConsumeAfter cannot be combined with "optional" positional options
  321. // unless there is only one positional argument...
  322. if (PositionalOpts.size() > 2)
  323. ErrorParsing |=
  324. Opt->error(" error - this positional option will never be matched, "
  325. "because it does not Require a value, and a "
  326. "cl::ConsumeAfter option is active!");
  327. } else if (UnboundedFound && !Opt->ArgStr[0]) {
  328. // This option does not "require" a value... Make sure this option is
  329. // not specified after an option that eats all extra arguments, or this
  330. // one will never get any!
  331. //
  332. ErrorParsing |= Opt->error(" error - option can never match, because "
  333. "another positional argument will match an "
  334. "unbounded number of values, and this option"
  335. " does not require a value!");
  336. }
  337. UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
  338. }
  339. HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
  340. }
  341. // PositionalVals - A vector of "positional" arguments we accumulate into
  342. // the process at the end...
  343. //
  344. std::vector<std::pair<std::string,unsigned> > PositionalVals;
  345. // If the program has named positional arguments, and the name has been run
  346. // across, keep track of which positional argument was named. Otherwise put
  347. // the positional args into the PositionalVals list...
  348. Option *ActivePositionalArg = 0;
  349. // Loop over all of the arguments... processing them.
  350. bool DashDashFound = false; // Have we read '--'?
  351. for (int i = 1; i < argc; ++i) {
  352. Option *Handler = 0;
  353. const char *Value = 0;
  354. const char *ArgName = "";
  355. // If the option list changed, this means that some command line
  356. // option has just been registered or deregistered. This can occur in
  357. // response to things like -load, etc. If this happens, rescan the options.
  358. if (OptionListChanged) {
  359. PositionalOpts.clear();
  360. Opts.clear();
  361. GetOptionInfo(PositionalOpts, Opts);
  362. OptionListChanged = false;
  363. }
  364. // Check to see if this is a positional argument. This argument is
  365. // considered to be positional if it doesn't start with '-', if it is "-"
  366. // itself, or if we have seen "--" already.
  367. //
  368. if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
  369. // Positional argument!
  370. if (ActivePositionalArg) {
  371. ProvidePositionalOption(ActivePositionalArg, argv[i], i);
  372. continue; // We are done!
  373. } else if (!PositionalOpts.empty()) {
  374. PositionalVals.push_back(std::make_pair(argv[i],i));
  375. // All of the positional arguments have been fulfulled, give the rest to
  376. // the consume after option... if it's specified...
  377. //
  378. if (PositionalVals.size() >= NumPositionalRequired &&
  379. ConsumeAfterOpt != 0) {
  380. for (++i; i < argc; ++i)
  381. PositionalVals.push_back(std::make_pair(argv[i],i));
  382. break; // Handle outside of the argument processing loop...
  383. }
  384. // Delay processing positional arguments until the end...
  385. continue;
  386. }
  387. } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
  388. !DashDashFound) {
  389. DashDashFound = true; // This is the mythical "--"?
  390. continue; // Don't try to process it as an argument itself.
  391. } else if (ActivePositionalArg &&
  392. (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
  393. // If there is a positional argument eating options, check to see if this
  394. // option is another positional argument. If so, treat it as an argument,
  395. // otherwise feed it to the eating positional.
  396. ArgName = argv[i]+1;
  397. Handler = LookupOption(ArgName, Value, Opts);
  398. if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
  399. ProvidePositionalOption(ActivePositionalArg, argv[i], i);
  400. continue; // We are done!
  401. }
  402. } else { // We start with a '-', must be an argument...
  403. ArgName = argv[i]+1;
  404. Handler = LookupOption(ArgName, Value, Opts);
  405. // Check to see if this "option" is really a prefixed or grouped argument.
  406. if (Handler == 0) {
  407. std::string RealName(ArgName);
  408. if (RealName.size() > 1) {
  409. unsigned Length = 0;
  410. Option *PGOpt = getOptionPred(RealName, Length, isPrefixedOrGrouping,
  411. Opts);
  412. // If the option is a prefixed option, then the value is simply the
  413. // rest of the name... so fall through to later processing, by
  414. // setting up the argument name flags and value fields.
  415. //
  416. if (PGOpt && PGOpt->getFormattingFlag() == cl::Prefix) {
  417. Value = ArgName+Length;
  418. assert(Opts.find(std::string(ArgName, Value)) != Opts.end() &&
  419. Opts.find(std::string(ArgName, Value))->second == PGOpt);
  420. Handler = PGOpt;
  421. } else if (PGOpt) {
  422. // This must be a grouped option... handle them now.
  423. assert(isGrouping(PGOpt) && "Broken getOptionPred!");
  424. do {
  425. // Move current arg name out of RealName into RealArgName...
  426. std::string RealArgName(RealName.begin(),
  427. RealName.begin() + Length);
  428. RealName.erase(RealName.begin(), RealName.begin() + Length);
  429. // Because ValueRequired is an invalid flag for grouped arguments,
  430. // we don't need to pass argc/argv in...
  431. //
  432. assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
  433. "Option can not be cl::Grouping AND cl::ValueRequired!");
  434. int Dummy;
  435. ErrorParsing |= ProvideOption(PGOpt, RealArgName.c_str(),
  436. 0, 0, 0, Dummy);
  437. // Get the next grouping option...
  438. PGOpt = getOptionPred(RealName, Length, isGrouping, Opts);
  439. } while (PGOpt && Length != RealName.size());
  440. Handler = PGOpt; // Ate all of the options.
  441. }
  442. }
  443. }
  444. }
  445. if (Handler == 0) {
  446. cerr << ProgramName << ": Unknown command line argument '"
  447. << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
  448. ErrorParsing = true;
  449. continue;
  450. }
  451. // Check to see if this option accepts a comma separated list of values. If
  452. // it does, we have to split up the value into multiple values...
  453. if (Value && Handler->getMiscFlags() & CommaSeparated) {
  454. std::string Val(Value);
  455. std::string::size_type Pos = Val.find(',');
  456. while (Pos != std::string::npos) {
  457. // Process the portion before the comma...
  458. ErrorParsing |= ProvideOption(Handler, ArgName,
  459. std::string(Val.begin(),
  460. Val.begin()+Pos).c_str(),
  461. argc, argv, i);
  462. // Erase the portion before the comma, AND the comma...
  463. Val.erase(Val.begin(), Val.begin()+Pos+1);
  464. Value += Pos+1; // Increment the original value pointer as well...
  465. // Check for another comma...
  466. Pos = Val.find(',');
  467. }
  468. }
  469. // If this is a named positional argument, just remember that it is the
  470. // active one...
  471. if (Handler->getFormattingFlag() == cl::Positional)
  472. ActivePositionalArg = Handler;
  473. else
  474. ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
  475. }
  476. // Check and handle positional arguments now...
  477. if (NumPositionalRequired > PositionalVals.size()) {
  478. cerr << ProgramName
  479. << ": Not enough positional command line arguments specified!\n"
  480. << "Must specify at least " << NumPositionalRequired
  481. << " positional arguments: See: " << argv[0] << " --help\n";
  482. ErrorParsing = true;
  483. } else if (!HasUnlimitedPositionals
  484. && PositionalVals.size() > PositionalOpts.size()) {
  485. cerr << ProgramName
  486. << ": Too many positional arguments specified!\n"
  487. << "Can specify at most " << PositionalOpts.size()
  488. << " positional arguments: See: " << argv[0] << " --help\n";
  489. ErrorParsing = true;
  490. } else if (ConsumeAfterOpt == 0) {
  491. // Positional args have already been handled if ConsumeAfter is specified...
  492. unsigned ValNo = 0, NumVals = PositionalVals.size();
  493. for (unsigned i = 0, e = PositionalOpts.size(); i != e; ++i) {
  494. if (RequiresValue(PositionalOpts[i])) {
  495. ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
  496. PositionalVals[ValNo].second);
  497. ValNo++;
  498. --NumPositionalRequired; // We fulfilled our duty...
  499. }
  500. // If we _can_ give this option more arguments, do so now, as long as we
  501. // do not give it values that others need. 'Done' controls whether the
  502. // option even _WANTS_ any more.
  503. //
  504. bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
  505. while (NumVals-ValNo > NumPositionalRequired && !Done) {
  506. switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
  507. case cl::Optional:
  508. Done = true; // Optional arguments want _at most_ one value
  509. // FALL THROUGH
  510. case cl::ZeroOrMore: // Zero or more will take all they can get...
  511. case cl::OneOrMore: // One or more will take all they can get...
  512. ProvidePositionalOption(PositionalOpts[i],
  513. PositionalVals[ValNo].first,
  514. PositionalVals[ValNo].second);
  515. ValNo++;
  516. break;
  517. default:
  518. assert(0 && "Internal error, unexpected NumOccurrences flag in "
  519. "positional argument processing!");
  520. }
  521. }
  522. }
  523. } else {
  524. assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
  525. unsigned ValNo = 0;
  526. for (unsigned j = 1, e = PositionalOpts.size(); j != e; ++j)
  527. if (RequiresValue(PositionalOpts[j])) {
  528. ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
  529. PositionalVals[ValNo].first,
  530. PositionalVals[ValNo].second);
  531. ValNo++;
  532. }
  533. // Handle the case where there is just one positional option, and it's
  534. // optional. In this case, we want to give JUST THE FIRST option to the
  535. // positional option and keep the rest for the consume after. The above
  536. // loop would have assigned no values to positional options in this case.
  537. //
  538. if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
  539. ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
  540. PositionalVals[ValNo].first,
  541. PositionalVals[ValNo].second);
  542. ValNo++;
  543. }
  544. // Handle over all of the rest of the arguments to the
  545. // cl::ConsumeAfter command line option...
  546. for (; ValNo != PositionalVals.size(); ++ValNo)
  547. ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
  548. PositionalVals[ValNo].first,
  549. PositionalVals[ValNo].second);
  550. }
  551. // Loop over args and make sure all required args are specified!
  552. for (std::map<std::string, Option*>::iterator I = Opts.begin(),
  553. E = Opts.end(); I != E; ++I) {
  554. switch (I->second->getNumOccurrencesFlag()) {
  555. case Required:
  556. case OneOrMore:
  557. if (I->second->getNumOccurrences() == 0) {
  558. I->second->error(" must be specified at least once!");
  559. ErrorParsing = true;
  560. }
  561. // Fall through
  562. default:
  563. break;
  564. }
  565. }
  566. // Free all of the memory allocated to the map. Command line options may only
  567. // be processed once!
  568. Opts.clear();
  569. PositionalOpts.clear();
  570. MoreHelp->clear();
  571. // If we had an error processing our arguments, don't let the program execute
  572. if (ErrorParsing) exit(1);
  573. }
  574. //===----------------------------------------------------------------------===//
  575. // Option Base class implementation
  576. //
  577. bool Option::error(std::string Message, const char *ArgName) {
  578. if (ArgName == 0) ArgName = ArgStr;
  579. if (ArgName[0] == 0)
  580. cerr << HelpStr; // Be nice for positional arguments
  581. else
  582. cerr << ProgramName << ": for the -" << ArgName;
  583. cerr << " option: " << Message << "\n";
  584. return true;
  585. }
  586. bool Option::addOccurrence(unsigned pos, const char *ArgName,
  587. const std::string &Value) {
  588. NumOccurrences++; // Increment the number of times we have been seen
  589. switch (getNumOccurrencesFlag()) {
  590. case Optional:
  591. if (NumOccurrences > 1)
  592. return error(": may only occur zero or one times!", ArgName);
  593. break;
  594. case Required:
  595. if (NumOccurrences > 1)
  596. return error(": must occur exactly one time!", ArgName);
  597. // Fall through
  598. case OneOrMore:
  599. case ZeroOrMore:
  600. case ConsumeAfter: break;
  601. default: return error(": bad num occurrences flag value!");
  602. }
  603. return handleOccurrence(pos, ArgName, Value);
  604. }
  605. // getValueStr - Get the value description string, using "DefaultMsg" if nothing
  606. // has been specified yet.
  607. //
  608. static const char *getValueStr(const Option &O, const char *DefaultMsg) {
  609. if (O.ValueStr[0] == 0) return DefaultMsg;
  610. return O.ValueStr;
  611. }
  612. //===----------------------------------------------------------------------===//
  613. // cl::alias class implementation
  614. //
  615. // Return the width of the option tag for printing...
  616. unsigned alias::getOptionWidth() const {
  617. return std::strlen(ArgStr)+6;
  618. }
  619. // Print out the option for the alias.
  620. void alias::printOptionInfo(unsigned GlobalWidth) const {
  621. unsigned L = std::strlen(ArgStr);
  622. cout << " -" << ArgStr << std::string(GlobalWidth-L-6, ' ') << " - "
  623. << HelpStr << "\n";
  624. }
  625. //===----------------------------------------------------------------------===//
  626. // Parser Implementation code...
  627. //
  628. // basic_parser implementation
  629. //
  630. // Return the width of the option tag for printing...
  631. unsigned basic_parser_impl::getOptionWidth(const Option &O) const {
  632. unsigned Len = std::strlen(O.ArgStr);
  633. if (const char *ValName = getValueName())
  634. Len += std::strlen(getValueStr(O, ValName))+3;
  635. return Len + 6;
  636. }
  637. // printOptionInfo - Print out information about this option. The
  638. // to-be-maintained width is specified.
  639. //
  640. void basic_parser_impl::printOptionInfo(const Option &O,
  641. unsigned GlobalWidth) const {
  642. cout << " -" << O.ArgStr;
  643. if (const char *ValName = getValueName())
  644. cout << "=<" << getValueStr(O, ValName) << ">";
  645. cout << std::string(GlobalWidth-getOptionWidth(O), ' ') << " - "
  646. << O.HelpStr << "\n";
  647. }
  648. // parser<bool> implementation
  649. //
  650. bool parser<bool>::parse(Option &O, const char *ArgName,
  651. const std::string &Arg, bool &Value) {
  652. if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
  653. Arg == "1") {
  654. Value = true;
  655. } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
  656. Value = false;
  657. } else {
  658. return O.error(": '" + Arg +
  659. "' is invalid value for boolean argument! Try 0 or 1");
  660. }
  661. return false;
  662. }
  663. // parser<boolOrDefault> implementation
  664. //
  665. bool parser<boolOrDefault>::parse(Option &O, const char *ArgName,
  666. const std::string &Arg, boolOrDefault &Value) {
  667. if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
  668. Arg == "1") {
  669. Value = BOU_TRUE;
  670. } else if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
  671. Value = BOU_FALSE;
  672. } else {
  673. return O.error(": '" + Arg +
  674. "' is invalid value for boolean argument! Try 0 or 1");
  675. }
  676. return false;
  677. }
  678. // parser<int> implementation
  679. //
  680. bool parser<int>::parse(Option &O, const char *ArgName,
  681. const std::string &Arg, int &Value) {
  682. char *End;
  683. Value = (int)strtol(Arg.c_str(), &End, 0);
  684. if (*End != 0)
  685. return O.error(": '" + Arg + "' value invalid for integer argument!");
  686. return false;
  687. }
  688. // parser<unsigned> implementation
  689. //
  690. bool parser<unsigned>::parse(Option &O, const char *ArgName,
  691. const std::string &Arg, unsigned &Value) {
  692. char *End;
  693. errno = 0;
  694. unsigned long V = strtoul(Arg.c_str(), &End, 0);
  695. Value = (unsigned)V;
  696. if (((V == ULONG_MAX) && (errno == ERANGE))
  697. || (*End != 0)
  698. || (Value != V))
  699. return O.error(": '" + Arg + "' value invalid for uint argument!");
  700. return false;
  701. }
  702. // parser<double>/parser<float> implementation
  703. //
  704. static bool parseDouble(Option &O, const std::string &Arg, double &Value) {
  705. const char *ArgStart = Arg.c_str();
  706. char *End;
  707. Value = strtod(ArgStart, &End);
  708. if (*End != 0)
  709. return O.error(": '" +Arg+ "' value invalid for floating point argument!");
  710. return false;
  711. }
  712. bool parser<double>::parse(Option &O, const char *AN,
  713. const std::string &Arg, double &Val) {
  714. return parseDouble(O, Arg, Val);
  715. }
  716. bool parser<float>::parse(Option &O, const char *AN,
  717. const std::string &Arg, float &Val) {
  718. double dVal;
  719. if (parseDouble(O, Arg, dVal))
  720. return true;
  721. Val = (float)dVal;
  722. return false;
  723. }
  724. // generic_parser_base implementation
  725. //
  726. // findOption - Return the option number corresponding to the specified
  727. // argument string. If the option is not found, getNumOptions() is returned.
  728. //
  729. unsigned generic_parser_base::findOption(const char *Name) {
  730. unsigned i = 0, e = getNumOptions();
  731. std::string N(Name);
  732. while (i != e)
  733. if (getOption(i) == N)
  734. return i;
  735. else
  736. ++i;
  737. return e;
  738. }
  739. // Return the width of the option tag for printing...
  740. unsigned generic_parser_base::getOptionWidth(const Option &O) const {
  741. if (O.hasArgStr()) {
  742. unsigned Size = std::strlen(O.ArgStr)+6;
  743. for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
  744. Size = std::max(Size, (unsigned)std::strlen(getOption(i))+8);
  745. return Size;
  746. } else {
  747. unsigned BaseSize = 0;
  748. for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
  749. BaseSize = std::max(BaseSize, (unsigned)std::strlen(getOption(i))+8);
  750. return BaseSize;
  751. }
  752. }
  753. // printOptionInfo - Print out information about this option. The
  754. // to-be-maintained width is specified.
  755. //
  756. void generic_parser_base::printOptionInfo(const Option &O,
  757. unsigned GlobalWidth) const {
  758. if (O.hasArgStr()) {
  759. unsigned L = std::strlen(O.ArgStr);
  760. cout << " -" << O.ArgStr << std::string(GlobalWidth-L-6, ' ')
  761. << " - " << O.HelpStr << "\n";
  762. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  763. unsigned NumSpaces = GlobalWidth-strlen(getOption(i))-8;
  764. cout << " =" << getOption(i) << std::string(NumSpaces, ' ')
  765. << " - " << getDescription(i) << "\n";
  766. }
  767. } else {
  768. if (O.HelpStr[0])
  769. cout << " " << O.HelpStr << "\n";
  770. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  771. unsigned L = std::strlen(getOption(i));
  772. cout << " -" << getOption(i) << std::string(GlobalWidth-L-8, ' ')
  773. << " - " << getDescription(i) << "\n";
  774. }
  775. }
  776. }
  777. //===----------------------------------------------------------------------===//
  778. // --help and --help-hidden option implementation
  779. //
  780. namespace {
  781. class HelpPrinter {
  782. unsigned MaxArgLen;
  783. const Option *EmptyArg;
  784. const bool ShowHidden;
  785. // isHidden/isReallyHidden - Predicates to be used to filter down arg lists.
  786. inline static bool isHidden(std::pair<std::string, Option *> &OptPair) {
  787. return OptPair.second->getOptionHiddenFlag() >= Hidden;
  788. }
  789. inline static bool isReallyHidden(std::pair<std::string, Option *> &OptPair) {
  790. return OptPair.second->getOptionHiddenFlag() == ReallyHidden;
  791. }
  792. public:
  793. HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
  794. EmptyArg = 0;
  795. }
  796. void operator=(bool Value) {
  797. if (Value == false) return;
  798. // Get all the options.
  799. std::vector<Option*> PositionalOpts;
  800. std::map<std::string, Option*> OptMap;
  801. GetOptionInfo(PositionalOpts, OptMap);
  802. // Copy Options into a vector so we can sort them as we like...
  803. std::vector<std::pair<std::string, Option*> > Opts;
  804. copy(OptMap.begin(), OptMap.end(), std::back_inserter(Opts));
  805. // Eliminate Hidden or ReallyHidden arguments, depending on ShowHidden
  806. Opts.erase(std::remove_if(Opts.begin(), Opts.end(),
  807. std::ptr_fun(ShowHidden ? isReallyHidden : isHidden)),
  808. Opts.end());
  809. // Eliminate duplicate entries in table (from enum flags options, f.e.)
  810. { // Give OptionSet a scope
  811. std::set<Option*> OptionSet;
  812. for (unsigned i = 0; i != Opts.size(); ++i)
  813. if (OptionSet.count(Opts[i].second) == 0)
  814. OptionSet.insert(Opts[i].second); // Add new entry to set
  815. else
  816. Opts.erase(Opts.begin()+i--); // Erase duplicate
  817. }
  818. if (ProgramOverview)
  819. cout << "OVERVIEW: " << ProgramOverview << "\n";
  820. cout << "USAGE: " << ProgramName << " [options]";
  821. // Print out the positional options.
  822. Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists...
  823. if (!PositionalOpts.empty() &&
  824. PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
  825. CAOpt = PositionalOpts[0];
  826. for (unsigned i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
  827. if (PositionalOpts[i]->ArgStr[0])
  828. cout << " --" << PositionalOpts[i]->ArgStr;
  829. cout << " " << PositionalOpts[i]->HelpStr;
  830. }
  831. // Print the consume after option info if it exists...
  832. if (CAOpt) cout << " " << CAOpt->HelpStr;
  833. cout << "\n\n";
  834. // Compute the maximum argument length...
  835. MaxArgLen = 0;
  836. for (unsigned i = 0, e = Opts.size(); i != e; ++i)
  837. MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
  838. cout << "OPTIONS:\n";
  839. for (unsigned i = 0, e = Opts.size(); i != e; ++i)
  840. Opts[i].second->printOptionInfo(MaxArgLen);
  841. // Print any extra help the user has declared.
  842. for (std::vector<const char *>::iterator I = MoreHelp->begin(),
  843. E = MoreHelp->end(); I != E; ++I)
  844. cout << *I;
  845. MoreHelp->clear();
  846. // Halt the program since help information was printed
  847. exit(1);
  848. }
  849. };
  850. } // End anonymous namespace
  851. // Define the two HelpPrinter instances that are used to print out help, or
  852. // help-hidden...
  853. //
  854. static HelpPrinter NormalPrinter(false);
  855. static HelpPrinter HiddenPrinter(true);
  856. static cl::opt<HelpPrinter, true, parser<bool> >
  857. HOp("help", cl::desc("Display available options (--help-hidden for more)"),
  858. cl::location(NormalPrinter), cl::ValueDisallowed);
  859. static cl::opt<HelpPrinter, true, parser<bool> >
  860. HHOp("help-hidden", cl::desc("Display all available options"),
  861. cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
  862. static void (*OverrideVersionPrinter)() = 0;
  863. namespace {
  864. class VersionPrinter {
  865. public:
  866. void print() {
  867. cout << "Low Level Virtual Machine (http://llvm.org/):\n";
  868. cout << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
  869. #ifdef LLVM_VERSION_INFO
  870. cout << LLVM_VERSION_INFO;
  871. #endif
  872. cout << "\n ";
  873. #ifndef __OPTIMIZE__
  874. cout << "DEBUG build";
  875. #else
  876. cout << "Optimized build";
  877. #endif
  878. #ifndef NDEBUG
  879. cout << " with assertions";
  880. #endif
  881. cout << ".\n";
  882. }
  883. void operator=(bool OptionWasSpecified) {
  884. if (OptionWasSpecified) {
  885. if (OverrideVersionPrinter == 0) {
  886. print();
  887. exit(1);
  888. } else {
  889. (*OverrideVersionPrinter)();
  890. exit(1);
  891. }
  892. }
  893. }
  894. };
  895. } // End anonymous namespace
  896. // Define the --version option that prints out the LLVM version for the tool
  897. static VersionPrinter VersionPrinterInstance;
  898. static cl::opt<VersionPrinter, true, parser<bool> >
  899. VersOp("version", cl::desc("Display the version of this program"),
  900. cl::location(VersionPrinterInstance), cl::ValueDisallowed);
  901. // Utility function for printing the help message.
  902. void cl::PrintHelpMessage() {
  903. // This looks weird, but it actually prints the help message. The
  904. // NormalPrinter variable is a HelpPrinter and the help gets printed when
  905. // its operator= is invoked. That's because the "normal" usages of the
  906. // help printer is to be assigned true/false depending on whether the
  907. // --help option was given or not. Since we're circumventing that we have
  908. // to make it look like --help was given, so we assign true.
  909. NormalPrinter = true;
  910. }
  911. /// Utility function for printing version number.
  912. void cl::PrintVersionMessage() {
  913. VersionPrinterInstance.print();
  914. }
  915. void cl::SetVersionPrinter(void (*func)()) {
  916. OverrideVersionPrinter = func;
  917. }