CommandLine.cpp 41 KB

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