CommandLine.cpp 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807
  1. //===-- CommandLine.cpp - Command line parser implementation --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This class implements a command line argument processor that is useful when
  10. // creating a tool. It provides a simple, minimalistic interface that is easily
  11. // extensible and supports nonlocal (library) command line options.
  12. //
  13. // Note that rather than trying to figure out what this code does, you could try
  14. // reading the library documentation located in docs/CommandLine.html
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/Support/CommandLine.h"
  18. #include "DebugOptions.h"
  19. #include "llvm-c/Support.h"
  20. #include "llvm/ADT/ArrayRef.h"
  21. #include "llvm/ADT/STLFunctionalExtras.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/SmallString.h"
  24. #include "llvm/ADT/StringExtras.h"
  25. #include "llvm/ADT/StringMap.h"
  26. #include "llvm/ADT/StringRef.h"
  27. #include "llvm/ADT/Twine.h"
  28. #include "llvm/Config/config.h"
  29. #include "llvm/Support/ConvertUTF.h"
  30. #include "llvm/Support/Debug.h"
  31. #include "llvm/Support/Error.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include "llvm/Support/FileSystem.h"
  34. #include "llvm/Support/ManagedStatic.h"
  35. #include "llvm/Support/MemoryBuffer.h"
  36. #include "llvm/Support/Path.h"
  37. #include "llvm/Support/Process.h"
  38. #include "llvm/Support/StringSaver.h"
  39. #include "llvm/Support/VirtualFileSystem.h"
  40. #include "llvm/Support/raw_ostream.h"
  41. #include <cstdlib>
  42. #include <optional>
  43. #include <string>
  44. using namespace llvm;
  45. using namespace cl;
  46. #define DEBUG_TYPE "commandline"
  47. //===----------------------------------------------------------------------===//
  48. // Template instantiations and anchors.
  49. //
  50. namespace llvm {
  51. namespace cl {
  52. template class basic_parser<bool>;
  53. template class basic_parser<boolOrDefault>;
  54. template class basic_parser<int>;
  55. template class basic_parser<long>;
  56. template class basic_parser<long long>;
  57. template class basic_parser<unsigned>;
  58. template class basic_parser<unsigned long>;
  59. template class basic_parser<unsigned long long>;
  60. template class basic_parser<double>;
  61. template class basic_parser<float>;
  62. template class basic_parser<std::string>;
  63. template class basic_parser<char>;
  64. template class opt<unsigned>;
  65. template class opt<int>;
  66. template class opt<std::string>;
  67. template class opt<char>;
  68. template class opt<bool>;
  69. } // namespace cl
  70. } // namespace llvm
  71. // Pin the vtables to this file.
  72. void GenericOptionValue::anchor() {}
  73. void OptionValue<boolOrDefault>::anchor() {}
  74. void OptionValue<std::string>::anchor() {}
  75. void Option::anchor() {}
  76. void basic_parser_impl::anchor() {}
  77. void parser<bool>::anchor() {}
  78. void parser<boolOrDefault>::anchor() {}
  79. void parser<int>::anchor() {}
  80. void parser<long>::anchor() {}
  81. void parser<long long>::anchor() {}
  82. void parser<unsigned>::anchor() {}
  83. void parser<unsigned long>::anchor() {}
  84. void parser<unsigned long long>::anchor() {}
  85. void parser<double>::anchor() {}
  86. void parser<float>::anchor() {}
  87. void parser<std::string>::anchor() {}
  88. void parser<char>::anchor() {}
  89. //===----------------------------------------------------------------------===//
  90. const static size_t DefaultPad = 2;
  91. static StringRef ArgPrefix = "-";
  92. static StringRef ArgPrefixLong = "--";
  93. static StringRef ArgHelpPrefix = " - ";
  94. static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad = DefaultPad) {
  95. size_t Len = ArgName.size();
  96. if (Len == 1)
  97. return Len + Pad + ArgPrefix.size() + ArgHelpPrefix.size();
  98. return Len + Pad + ArgPrefixLong.size() + ArgHelpPrefix.size();
  99. }
  100. static SmallString<8> argPrefix(StringRef ArgName, size_t Pad = DefaultPad) {
  101. SmallString<8> Prefix;
  102. for (size_t I = 0; I < Pad; ++I) {
  103. Prefix.push_back(' ');
  104. }
  105. Prefix.append(ArgName.size() > 1 ? ArgPrefixLong : ArgPrefix);
  106. return Prefix;
  107. }
  108. // Option predicates...
  109. static inline bool isGrouping(const Option *O) {
  110. return O->getMiscFlags() & cl::Grouping;
  111. }
  112. static inline bool isPrefixedOrGrouping(const Option *O) {
  113. return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
  114. O->getFormattingFlag() == cl::AlwaysPrefix;
  115. }
  116. namespace {
  117. class PrintArg {
  118. StringRef ArgName;
  119. size_t Pad;
  120. public:
  121. PrintArg(StringRef ArgName, size_t Pad = DefaultPad) : ArgName(ArgName), Pad(Pad) {}
  122. friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg &);
  123. };
  124. raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) {
  125. OS << argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
  126. return OS;
  127. }
  128. class CommandLineParser {
  129. public:
  130. // Globals for name and overview of program. Program name is not a string to
  131. // avoid static ctor/dtor issues.
  132. std::string ProgramName;
  133. StringRef ProgramOverview;
  134. // This collects additional help to be printed.
  135. std::vector<StringRef> MoreHelp;
  136. // This collects Options added with the cl::DefaultOption flag. Since they can
  137. // be overridden, they are not added to the appropriate SubCommands until
  138. // ParseCommandLineOptions actually runs.
  139. SmallVector<Option*, 4> DefaultOptions;
  140. // This collects the different option categories that have been registered.
  141. SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
  142. // This collects the different subcommands that have been registered.
  143. SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
  144. CommandLineParser() {
  145. registerSubCommand(&SubCommand::getTopLevel());
  146. registerSubCommand(&SubCommand::getAll());
  147. }
  148. void ResetAllOptionOccurrences();
  149. bool ParseCommandLineOptions(int argc, const char *const *argv,
  150. StringRef Overview, raw_ostream *Errs = nullptr,
  151. bool LongOptionsUseDoubleDash = false);
  152. void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
  153. if (Opt.hasArgStr())
  154. return;
  155. if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
  156. errs() << ProgramName << ": CommandLine Error: Option '" << Name
  157. << "' registered more than once!\n";
  158. report_fatal_error("inconsistency in registered CommandLine options");
  159. }
  160. // If we're adding this to all sub-commands, add it to the ones that have
  161. // already been registered.
  162. if (SC == &SubCommand::getAll()) {
  163. for (auto *Sub : RegisteredSubCommands) {
  164. if (SC == Sub)
  165. continue;
  166. addLiteralOption(Opt, Sub, Name);
  167. }
  168. }
  169. }
  170. void addLiteralOption(Option &Opt, StringRef Name) {
  171. if (Opt.Subs.empty())
  172. addLiteralOption(Opt, &SubCommand::getTopLevel(), Name);
  173. else {
  174. for (auto *SC : Opt.Subs)
  175. addLiteralOption(Opt, SC, Name);
  176. }
  177. }
  178. void addOption(Option *O, SubCommand *SC) {
  179. bool HadErrors = false;
  180. if (O->hasArgStr()) {
  181. // If it's a DefaultOption, check to make sure it isn't already there.
  182. if (O->isDefaultOption() &&
  183. SC->OptionsMap.find(O->ArgStr) != SC->OptionsMap.end())
  184. return;
  185. // Add argument to the argument map!
  186. if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
  187. errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
  188. << "' registered more than once!\n";
  189. HadErrors = true;
  190. }
  191. }
  192. // Remember information about positional options.
  193. if (O->getFormattingFlag() == cl::Positional)
  194. SC->PositionalOpts.push_back(O);
  195. else if (O->getMiscFlags() & cl::Sink) // Remember sink options
  196. SC->SinkOpts.push_back(O);
  197. else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
  198. if (SC->ConsumeAfterOpt) {
  199. O->error("Cannot specify more than one option with cl::ConsumeAfter!");
  200. HadErrors = true;
  201. }
  202. SC->ConsumeAfterOpt = O;
  203. }
  204. // Fail hard if there were errors. These are strictly unrecoverable and
  205. // indicate serious issues such as conflicting option names or an
  206. // incorrectly
  207. // linked LLVM distribution.
  208. if (HadErrors)
  209. report_fatal_error("inconsistency in registered CommandLine options");
  210. // If we're adding this to all sub-commands, add it to the ones that have
  211. // already been registered.
  212. if (SC == &SubCommand::getAll()) {
  213. for (auto *Sub : RegisteredSubCommands) {
  214. if (SC == Sub)
  215. continue;
  216. addOption(O, Sub);
  217. }
  218. }
  219. }
  220. void addOption(Option *O, bool ProcessDefaultOption = false) {
  221. if (!ProcessDefaultOption && O->isDefaultOption()) {
  222. DefaultOptions.push_back(O);
  223. return;
  224. }
  225. if (O->Subs.empty()) {
  226. addOption(O, &SubCommand::getTopLevel());
  227. } else {
  228. for (auto *SC : O->Subs)
  229. addOption(O, SC);
  230. }
  231. }
  232. void removeOption(Option *O, SubCommand *SC) {
  233. SmallVector<StringRef, 16> OptionNames;
  234. O->getExtraOptionNames(OptionNames);
  235. if (O->hasArgStr())
  236. OptionNames.push_back(O->ArgStr);
  237. SubCommand &Sub = *SC;
  238. auto End = Sub.OptionsMap.end();
  239. for (auto Name : OptionNames) {
  240. auto I = Sub.OptionsMap.find(Name);
  241. if (I != End && I->getValue() == O)
  242. Sub.OptionsMap.erase(I);
  243. }
  244. if (O->getFormattingFlag() == cl::Positional)
  245. for (auto *Opt = Sub.PositionalOpts.begin();
  246. Opt != Sub.PositionalOpts.end(); ++Opt) {
  247. if (*Opt == O) {
  248. Sub.PositionalOpts.erase(Opt);
  249. break;
  250. }
  251. }
  252. else if (O->getMiscFlags() & cl::Sink)
  253. for (auto *Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
  254. if (*Opt == O) {
  255. Sub.SinkOpts.erase(Opt);
  256. break;
  257. }
  258. }
  259. else if (O == Sub.ConsumeAfterOpt)
  260. Sub.ConsumeAfterOpt = nullptr;
  261. }
  262. void removeOption(Option *O) {
  263. if (O->Subs.empty())
  264. removeOption(O, &SubCommand::getTopLevel());
  265. else {
  266. if (O->isInAllSubCommands()) {
  267. for (auto *SC : RegisteredSubCommands)
  268. removeOption(O, SC);
  269. } else {
  270. for (auto *SC : O->Subs)
  271. removeOption(O, SC);
  272. }
  273. }
  274. }
  275. bool hasOptions(const SubCommand &Sub) const {
  276. return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
  277. nullptr != Sub.ConsumeAfterOpt);
  278. }
  279. bool hasOptions() const {
  280. for (const auto *S : RegisteredSubCommands) {
  281. if (hasOptions(*S))
  282. return true;
  283. }
  284. return false;
  285. }
  286. SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
  287. void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
  288. SubCommand &Sub = *SC;
  289. if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
  290. errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
  291. << "' registered more than once!\n";
  292. report_fatal_error("inconsistency in registered CommandLine options");
  293. }
  294. Sub.OptionsMap.erase(O->ArgStr);
  295. }
  296. void updateArgStr(Option *O, StringRef NewName) {
  297. if (O->Subs.empty())
  298. updateArgStr(O, NewName, &SubCommand::getTopLevel());
  299. else {
  300. if (O->isInAllSubCommands()) {
  301. for (auto *SC : RegisteredSubCommands)
  302. updateArgStr(O, NewName, SC);
  303. } else {
  304. for (auto *SC : O->Subs)
  305. updateArgStr(O, NewName, SC);
  306. }
  307. }
  308. }
  309. void printOptionValues();
  310. void registerCategory(OptionCategory *cat) {
  311. assert(count_if(RegisteredOptionCategories,
  312. [cat](const OptionCategory *Category) {
  313. return cat->getName() == Category->getName();
  314. }) == 0 &&
  315. "Duplicate option categories");
  316. RegisteredOptionCategories.insert(cat);
  317. }
  318. void registerSubCommand(SubCommand *sub) {
  319. assert(count_if(RegisteredSubCommands,
  320. [sub](const SubCommand *Sub) {
  321. return (!sub->getName().empty()) &&
  322. (Sub->getName() == sub->getName());
  323. }) == 0 &&
  324. "Duplicate subcommands");
  325. RegisteredSubCommands.insert(sub);
  326. // For all options that have been registered for all subcommands, add the
  327. // option to this subcommand now.
  328. if (sub != &SubCommand::getAll()) {
  329. for (auto &E : SubCommand::getAll().OptionsMap) {
  330. Option *O = E.second;
  331. if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
  332. O->hasArgStr())
  333. addOption(O, sub);
  334. else
  335. addLiteralOption(*O, sub, E.first());
  336. }
  337. }
  338. }
  339. void unregisterSubCommand(SubCommand *sub) {
  340. RegisteredSubCommands.erase(sub);
  341. }
  342. iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
  343. getRegisteredSubcommands() {
  344. return make_range(RegisteredSubCommands.begin(),
  345. RegisteredSubCommands.end());
  346. }
  347. void reset() {
  348. ActiveSubCommand = nullptr;
  349. ProgramName.clear();
  350. ProgramOverview = StringRef();
  351. MoreHelp.clear();
  352. RegisteredOptionCategories.clear();
  353. ResetAllOptionOccurrences();
  354. RegisteredSubCommands.clear();
  355. SubCommand::getTopLevel().reset();
  356. SubCommand::getAll().reset();
  357. registerSubCommand(&SubCommand::getTopLevel());
  358. registerSubCommand(&SubCommand::getAll());
  359. DefaultOptions.clear();
  360. }
  361. private:
  362. SubCommand *ActiveSubCommand = nullptr;
  363. Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
  364. Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value,
  365. bool LongOptionsUseDoubleDash, bool HaveDoubleDash) {
  366. Option *Opt = LookupOption(Sub, Arg, Value);
  367. if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !isGrouping(Opt))
  368. return nullptr;
  369. return Opt;
  370. }
  371. SubCommand *LookupSubCommand(StringRef Name);
  372. };
  373. } // namespace
  374. static ManagedStatic<CommandLineParser> GlobalParser;
  375. void cl::AddLiteralOption(Option &O, StringRef Name) {
  376. GlobalParser->addLiteralOption(O, Name);
  377. }
  378. extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
  379. GlobalParser->MoreHelp.push_back(Help);
  380. }
  381. void Option::addArgument() {
  382. GlobalParser->addOption(this);
  383. FullyInitialized = true;
  384. }
  385. void Option::removeArgument() { GlobalParser->removeOption(this); }
  386. void Option::setArgStr(StringRef S) {
  387. if (FullyInitialized)
  388. GlobalParser->updateArgStr(this, S);
  389. assert((S.empty() || S[0] != '-') && "Option can't start with '-");
  390. ArgStr = S;
  391. if (ArgStr.size() == 1)
  392. setMiscFlag(Grouping);
  393. }
  394. void Option::addCategory(OptionCategory &C) {
  395. assert(!Categories.empty() && "Categories cannot be empty.");
  396. // Maintain backward compatibility by replacing the default GeneralCategory
  397. // if it's still set. Otherwise, just add the new one. The GeneralCategory
  398. // must be explicitly added if you want multiple categories that include it.
  399. if (&C != &getGeneralCategory() && Categories[0] == &getGeneralCategory())
  400. Categories[0] = &C;
  401. else if (!is_contained(Categories, &C))
  402. Categories.push_back(&C);
  403. }
  404. void Option::reset() {
  405. NumOccurrences = 0;
  406. setDefault();
  407. if (isDefaultOption())
  408. removeArgument();
  409. }
  410. void OptionCategory::registerCategory() {
  411. GlobalParser->registerCategory(this);
  412. }
  413. // A special subcommand representing no subcommand. It is particularly important
  414. // that this ManagedStatic uses constant initailization and not dynamic
  415. // initialization because it is referenced from cl::opt constructors, which run
  416. // dynamically in an arbitrary order.
  417. LLVM_REQUIRE_CONSTANT_INITIALIZATION
  418. ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
  419. // A special subcommand that can be used to put an option into all subcommands.
  420. ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
  421. SubCommand &SubCommand::getTopLevel() { return *TopLevelSubCommand; }
  422. SubCommand &SubCommand::getAll() { return *AllSubCommands; }
  423. void SubCommand::registerSubCommand() {
  424. GlobalParser->registerSubCommand(this);
  425. }
  426. void SubCommand::unregisterSubCommand() {
  427. GlobalParser->unregisterSubCommand(this);
  428. }
  429. void SubCommand::reset() {
  430. PositionalOpts.clear();
  431. SinkOpts.clear();
  432. OptionsMap.clear();
  433. ConsumeAfterOpt = nullptr;
  434. }
  435. SubCommand::operator bool() const {
  436. return (GlobalParser->getActiveSubCommand() == this);
  437. }
  438. //===----------------------------------------------------------------------===//
  439. // Basic, shared command line option processing machinery.
  440. //
  441. /// LookupOption - Lookup the option specified by the specified option on the
  442. /// command line. If there is a value specified (after an equal sign) return
  443. /// that as well. This assumes that leading dashes have already been stripped.
  444. Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
  445. StringRef &Value) {
  446. // Reject all dashes.
  447. if (Arg.empty())
  448. return nullptr;
  449. assert(&Sub != &SubCommand::getAll());
  450. size_t EqualPos = Arg.find('=');
  451. // If we have an equals sign, remember the value.
  452. if (EqualPos == StringRef::npos) {
  453. // Look up the option.
  454. return Sub.OptionsMap.lookup(Arg);
  455. }
  456. // If the argument before the = is a valid option name and the option allows
  457. // non-prefix form (ie is not AlwaysPrefix), we match. If not, signal match
  458. // failure by returning nullptr.
  459. auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
  460. if (I == Sub.OptionsMap.end())
  461. return nullptr;
  462. auto *O = I->second;
  463. if (O->getFormattingFlag() == cl::AlwaysPrefix)
  464. return nullptr;
  465. Value = Arg.substr(EqualPos + 1);
  466. Arg = Arg.substr(0, EqualPos);
  467. return I->second;
  468. }
  469. SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
  470. if (Name.empty())
  471. return &SubCommand::getTopLevel();
  472. for (auto *S : RegisteredSubCommands) {
  473. if (S == &SubCommand::getAll())
  474. continue;
  475. if (S->getName().empty())
  476. continue;
  477. if (StringRef(S->getName()) == StringRef(Name))
  478. return S;
  479. }
  480. return &SubCommand::getTopLevel();
  481. }
  482. /// LookupNearestOption - Lookup the closest match to the option specified by
  483. /// the specified option on the command line. If there is a value specified
  484. /// (after an equal sign) return that as well. This assumes that leading dashes
  485. /// have already been stripped.
  486. static Option *LookupNearestOption(StringRef Arg,
  487. const StringMap<Option *> &OptionsMap,
  488. std::string &NearestString) {
  489. // Reject all dashes.
  490. if (Arg.empty())
  491. return nullptr;
  492. // Split on any equal sign.
  493. std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
  494. StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
  495. StringRef &RHS = SplitArg.second;
  496. // Find the closest match.
  497. Option *Best = nullptr;
  498. unsigned BestDistance = 0;
  499. for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
  500. ie = OptionsMap.end();
  501. it != ie; ++it) {
  502. Option *O = it->second;
  503. // Do not suggest really hidden options (not shown in any help).
  504. if (O->getOptionHiddenFlag() == ReallyHidden)
  505. continue;
  506. SmallVector<StringRef, 16> OptionNames;
  507. O->getExtraOptionNames(OptionNames);
  508. if (O->hasArgStr())
  509. OptionNames.push_back(O->ArgStr);
  510. bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
  511. StringRef Flag = PermitValue ? LHS : Arg;
  512. for (const auto &Name : OptionNames) {
  513. unsigned Distance = StringRef(Name).edit_distance(
  514. Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
  515. if (!Best || Distance < BestDistance) {
  516. Best = O;
  517. BestDistance = Distance;
  518. if (RHS.empty() || !PermitValue)
  519. NearestString = std::string(Name);
  520. else
  521. NearestString = (Twine(Name) + "=" + RHS).str();
  522. }
  523. }
  524. }
  525. return Best;
  526. }
  527. /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
  528. /// that does special handling of cl::CommaSeparated options.
  529. static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
  530. StringRef ArgName, StringRef Value,
  531. bool MultiArg = false) {
  532. // Check to see if this option accepts a comma separated list of values. If
  533. // it does, we have to split up the value into multiple values.
  534. if (Handler->getMiscFlags() & CommaSeparated) {
  535. StringRef Val(Value);
  536. StringRef::size_type Pos = Val.find(',');
  537. while (Pos != StringRef::npos) {
  538. // Process the portion before the comma.
  539. if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
  540. return true;
  541. // Erase the portion before the comma, AND the comma.
  542. Val = Val.substr(Pos + 1);
  543. // Check for another comma.
  544. Pos = Val.find(',');
  545. }
  546. Value = Val;
  547. }
  548. return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
  549. }
  550. /// ProvideOption - For Value, this differentiates between an empty value ("")
  551. /// and a null value (StringRef()). The later is accepted for arguments that
  552. /// don't allow a value (-foo) the former is rejected (-foo=).
  553. static inline bool ProvideOption(Option *Handler, StringRef ArgName,
  554. StringRef Value, int argc,
  555. const char *const *argv, int &i) {
  556. // Is this a multi-argument option?
  557. unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
  558. // Enforce value requirements
  559. switch (Handler->getValueExpectedFlag()) {
  560. case ValueRequired:
  561. if (!Value.data()) { // No value specified?
  562. // If no other argument or the option only supports prefix form, we
  563. // cannot look at the next argument.
  564. if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
  565. return Handler->error("requires a value!");
  566. // Steal the next argument, like for '-o filename'
  567. assert(argv && "null check");
  568. Value = StringRef(argv[++i]);
  569. }
  570. break;
  571. case ValueDisallowed:
  572. if (NumAdditionalVals > 0)
  573. return Handler->error("multi-valued option specified"
  574. " with ValueDisallowed modifier!");
  575. if (Value.data())
  576. return Handler->error("does not allow a value! '" + Twine(Value) +
  577. "' specified.");
  578. break;
  579. case ValueOptional:
  580. break;
  581. }
  582. // If this isn't a multi-arg option, just run the handler.
  583. if (NumAdditionalVals == 0)
  584. return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
  585. // If it is, run the handle several times.
  586. bool MultiArg = false;
  587. if (Value.data()) {
  588. if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
  589. return true;
  590. --NumAdditionalVals;
  591. MultiArg = true;
  592. }
  593. while (NumAdditionalVals > 0) {
  594. if (i + 1 >= argc)
  595. return Handler->error("not enough values!");
  596. assert(argv && "null check");
  597. Value = StringRef(argv[++i]);
  598. if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
  599. return true;
  600. MultiArg = true;
  601. --NumAdditionalVals;
  602. }
  603. return false;
  604. }
  605. bool llvm::cl::ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
  606. int Dummy = i;
  607. return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
  608. }
  609. // getOptionPred - Check to see if there are any options that satisfy the
  610. // specified predicate with names that are the prefixes in Name. This is
  611. // checked by progressively stripping characters off of the name, checking to
  612. // see if there options that satisfy the predicate. If we find one, return it,
  613. // otherwise return null.
  614. //
  615. static Option *getOptionPred(StringRef Name, size_t &Length,
  616. bool (*Pred)(const Option *),
  617. const StringMap<Option *> &OptionsMap) {
  618. StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
  619. if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
  620. OMI = OptionsMap.end();
  621. // Loop while we haven't found an option and Name still has at least two
  622. // characters in it (so that the next iteration will not be the empty
  623. // string.
  624. while (OMI == OptionsMap.end() && Name.size() > 1) {
  625. Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
  626. OMI = OptionsMap.find(Name);
  627. if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
  628. OMI = OptionsMap.end();
  629. }
  630. if (OMI != OptionsMap.end() && Pred(OMI->second)) {
  631. Length = Name.size();
  632. return OMI->second; // Found one!
  633. }
  634. return nullptr; // No option found!
  635. }
  636. /// HandlePrefixedOrGroupedOption - The specified argument string (which started
  637. /// with at least one '-') does not fully match an available option. Check to
  638. /// see if this is a prefix or grouped option. If so, split arg into output an
  639. /// Arg/Value pair and return the Option to parse it with.
  640. static Option *
  641. HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
  642. bool &ErrorParsing,
  643. const StringMap<Option *> &OptionsMap) {
  644. if (Arg.size() == 1)
  645. return nullptr;
  646. // Do the lookup!
  647. size_t Length = 0;
  648. Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
  649. if (!PGOpt)
  650. return nullptr;
  651. do {
  652. StringRef MaybeValue =
  653. (Length < Arg.size()) ? Arg.substr(Length) : StringRef();
  654. Arg = Arg.substr(0, Length);
  655. assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
  656. // cl::Prefix options do not preserve '=' when used separately.
  657. // The behavior for them with grouped options should be the same.
  658. if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix ||
  659. (PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) {
  660. Value = MaybeValue;
  661. return PGOpt;
  662. }
  663. if (MaybeValue[0] == '=') {
  664. Value = MaybeValue.substr(1);
  665. return PGOpt;
  666. }
  667. // This must be a grouped option.
  668. assert(isGrouping(PGOpt) && "Broken getOptionPred!");
  669. // Grouping options inside a group can't have values.
  670. if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
  671. ErrorParsing |= PGOpt->error("may not occur within a group!");
  672. return nullptr;
  673. }
  674. // Because the value for the option is not required, we don't need to pass
  675. // argc/argv in.
  676. int Dummy = 0;
  677. ErrorParsing |= ProvideOption(PGOpt, Arg, StringRef(), 0, nullptr, Dummy);
  678. // Get the next grouping option.
  679. Arg = MaybeValue;
  680. PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
  681. } while (PGOpt);
  682. // We could not find a grouping option in the remainder of Arg.
  683. return nullptr;
  684. }
  685. static bool RequiresValue(const Option *O) {
  686. return O->getNumOccurrencesFlag() == cl::Required ||
  687. O->getNumOccurrencesFlag() == cl::OneOrMore;
  688. }
  689. static bool EatsUnboundedNumberOfValues(const Option *O) {
  690. return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
  691. O->getNumOccurrencesFlag() == cl::OneOrMore;
  692. }
  693. static bool isWhitespace(char C) {
  694. return C == ' ' || C == '\t' || C == '\r' || C == '\n';
  695. }
  696. static bool isWhitespaceOrNull(char C) {
  697. return isWhitespace(C) || C == '\0';
  698. }
  699. static bool isQuote(char C) { return C == '\"' || C == '\''; }
  700. void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
  701. SmallVectorImpl<const char *> &NewArgv,
  702. bool MarkEOLs) {
  703. SmallString<128> Token;
  704. for (size_t I = 0, E = Src.size(); I != E; ++I) {
  705. // Consume runs of whitespace.
  706. if (Token.empty()) {
  707. while (I != E && isWhitespace(Src[I])) {
  708. // Mark the end of lines in response files.
  709. if (MarkEOLs && Src[I] == '\n')
  710. NewArgv.push_back(nullptr);
  711. ++I;
  712. }
  713. if (I == E)
  714. break;
  715. }
  716. char C = Src[I];
  717. // Backslash escapes the next character.
  718. if (I + 1 < E && C == '\\') {
  719. ++I; // Skip the escape.
  720. Token.push_back(Src[I]);
  721. continue;
  722. }
  723. // Consume a quoted string.
  724. if (isQuote(C)) {
  725. ++I;
  726. while (I != E && Src[I] != C) {
  727. // Backslash escapes the next character.
  728. if (Src[I] == '\\' && I + 1 != E)
  729. ++I;
  730. Token.push_back(Src[I]);
  731. ++I;
  732. }
  733. if (I == E)
  734. break;
  735. continue;
  736. }
  737. // End the token if this is whitespace.
  738. if (isWhitespace(C)) {
  739. if (!Token.empty())
  740. NewArgv.push_back(Saver.save(Token.str()).data());
  741. // Mark the end of lines in response files.
  742. if (MarkEOLs && C == '\n')
  743. NewArgv.push_back(nullptr);
  744. Token.clear();
  745. continue;
  746. }
  747. // This is a normal character. Append it.
  748. Token.push_back(C);
  749. }
  750. // Append the last token after hitting EOF with no whitespace.
  751. if (!Token.empty())
  752. NewArgv.push_back(Saver.save(Token.str()).data());
  753. }
  754. /// Backslashes are interpreted in a rather complicated way in the Windows-style
  755. /// command line, because backslashes are used both to separate path and to
  756. /// escape double quote. This method consumes runs of backslashes as well as the
  757. /// following double quote if it's escaped.
  758. ///
  759. /// * If an even number of backslashes is followed by a double quote, one
  760. /// backslash is output for every pair of backslashes, and the last double
  761. /// quote remains unconsumed. The double quote will later be interpreted as
  762. /// the start or end of a quoted string in the main loop outside of this
  763. /// function.
  764. ///
  765. /// * If an odd number of backslashes is followed by a double quote, one
  766. /// backslash is output for every pair of backslashes, and a double quote is
  767. /// output for the last pair of backslash-double quote. The double quote is
  768. /// consumed in this case.
  769. ///
  770. /// * Otherwise, backslashes are interpreted literally.
  771. static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
  772. size_t E = Src.size();
  773. int BackslashCount = 0;
  774. // Skip the backslashes.
  775. do {
  776. ++I;
  777. ++BackslashCount;
  778. } while (I != E && Src[I] == '\\');
  779. bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
  780. if (FollowedByDoubleQuote) {
  781. Token.append(BackslashCount / 2, '\\');
  782. if (BackslashCount % 2 == 0)
  783. return I - 1;
  784. Token.push_back('"');
  785. return I;
  786. }
  787. Token.append(BackslashCount, '\\');
  788. return I - 1;
  789. }
  790. // Windows treats whitespace, double quotes, and backslashes specially, except
  791. // when parsing the first token of a full command line, in which case
  792. // backslashes are not special.
  793. static bool isWindowsSpecialChar(char C) {
  794. return isWhitespaceOrNull(C) || C == '\\' || C == '\"';
  795. }
  796. static bool isWindowsSpecialCharInCommandName(char C) {
  797. return isWhitespaceOrNull(C) || C == '\"';
  798. }
  799. // Windows tokenization implementation. The implementation is designed to be
  800. // inlined and specialized for the two user entry points.
  801. static inline void tokenizeWindowsCommandLineImpl(
  802. StringRef Src, StringSaver &Saver, function_ref<void(StringRef)> AddToken,
  803. bool AlwaysCopy, function_ref<void()> MarkEOL, bool InitialCommandName) {
  804. SmallString<128> Token;
  805. // Sometimes, this function will be handling a full command line including an
  806. // executable pathname at the start. In that situation, the initial pathname
  807. // needs different handling from the following arguments, because when
  808. // CreateProcess or cmd.exe scans the pathname, it doesn't treat \ as
  809. // escaping the quote character, whereas when libc scans the rest of the
  810. // command line, it does.
  811. bool CommandName = InitialCommandName;
  812. // Try to do as much work inside the state machine as possible.
  813. enum { INIT, UNQUOTED, QUOTED } State = INIT;
  814. for (size_t I = 0, E = Src.size(); I < E; ++I) {
  815. switch (State) {
  816. case INIT: {
  817. assert(Token.empty() && "token should be empty in initial state");
  818. // Eat whitespace before a token.
  819. while (I < E && isWhitespaceOrNull(Src[I])) {
  820. if (Src[I] == '\n')
  821. MarkEOL();
  822. ++I;
  823. }
  824. // Stop if this was trailing whitespace.
  825. if (I >= E)
  826. break;
  827. size_t Start = I;
  828. if (CommandName) {
  829. while (I < E && !isWindowsSpecialCharInCommandName(Src[I]))
  830. ++I;
  831. } else {
  832. while (I < E && !isWindowsSpecialChar(Src[I]))
  833. ++I;
  834. }
  835. StringRef NormalChars = Src.slice(Start, I);
  836. if (I >= E || isWhitespaceOrNull(Src[I])) {
  837. // No special characters: slice out the substring and start the next
  838. // token. Copy the string if the caller asks us to.
  839. AddToken(AlwaysCopy ? Saver.save(NormalChars) : NormalChars);
  840. if (I < E && Src[I] == '\n') {
  841. MarkEOL();
  842. CommandName = InitialCommandName;
  843. } else {
  844. CommandName = false;
  845. }
  846. } else if (Src[I] == '\"') {
  847. Token += NormalChars;
  848. State = QUOTED;
  849. } else if (Src[I] == '\\') {
  850. assert(!CommandName && "or else we'd have treated it as a normal char");
  851. Token += NormalChars;
  852. I = parseBackslash(Src, I, Token);
  853. State = UNQUOTED;
  854. } else {
  855. llvm_unreachable("unexpected special character");
  856. }
  857. break;
  858. }
  859. case UNQUOTED:
  860. if (isWhitespaceOrNull(Src[I])) {
  861. // Whitespace means the end of the token. If we are in this state, the
  862. // token must have contained a special character, so we must copy the
  863. // token.
  864. AddToken(Saver.save(Token.str()));
  865. Token.clear();
  866. if (Src[I] == '\n') {
  867. CommandName = InitialCommandName;
  868. MarkEOL();
  869. } else {
  870. CommandName = false;
  871. }
  872. State = INIT;
  873. } else if (Src[I] == '\"') {
  874. State = QUOTED;
  875. } else if (Src[I] == '\\' && !CommandName) {
  876. I = parseBackslash(Src, I, Token);
  877. } else {
  878. Token.push_back(Src[I]);
  879. }
  880. break;
  881. case QUOTED:
  882. if (Src[I] == '\"') {
  883. if (I < (E - 1) && Src[I + 1] == '"') {
  884. // Consecutive double-quotes inside a quoted string implies one
  885. // double-quote.
  886. Token.push_back('"');
  887. ++I;
  888. } else {
  889. // Otherwise, end the quoted portion and return to the unquoted state.
  890. State = UNQUOTED;
  891. }
  892. } else if (Src[I] == '\\' && !CommandName) {
  893. I = parseBackslash(Src, I, Token);
  894. } else {
  895. Token.push_back(Src[I]);
  896. }
  897. break;
  898. }
  899. }
  900. if (State != INIT)
  901. AddToken(Saver.save(Token.str()));
  902. }
  903. void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
  904. SmallVectorImpl<const char *> &NewArgv,
  905. bool MarkEOLs) {
  906. auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
  907. auto OnEOL = [&]() {
  908. if (MarkEOLs)
  909. NewArgv.push_back(nullptr);
  910. };
  911. tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
  912. /*AlwaysCopy=*/true, OnEOL, false);
  913. }
  914. void cl::TokenizeWindowsCommandLineNoCopy(StringRef Src, StringSaver &Saver,
  915. SmallVectorImpl<StringRef> &NewArgv) {
  916. auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok); };
  917. auto OnEOL = []() {};
  918. tokenizeWindowsCommandLineImpl(Src, Saver, AddToken, /*AlwaysCopy=*/false,
  919. OnEOL, false);
  920. }
  921. void cl::TokenizeWindowsCommandLineFull(StringRef Src, StringSaver &Saver,
  922. SmallVectorImpl<const char *> &NewArgv,
  923. bool MarkEOLs) {
  924. auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
  925. auto OnEOL = [&]() {
  926. if (MarkEOLs)
  927. NewArgv.push_back(nullptr);
  928. };
  929. tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
  930. /*AlwaysCopy=*/true, OnEOL, true);
  931. }
  932. void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver,
  933. SmallVectorImpl<const char *> &NewArgv,
  934. bool MarkEOLs) {
  935. for (const char *Cur = Source.begin(); Cur != Source.end();) {
  936. SmallString<128> Line;
  937. // Check for comment line.
  938. if (isWhitespace(*Cur)) {
  939. while (Cur != Source.end() && isWhitespace(*Cur))
  940. ++Cur;
  941. continue;
  942. }
  943. if (*Cur == '#') {
  944. while (Cur != Source.end() && *Cur != '\n')
  945. ++Cur;
  946. continue;
  947. }
  948. // Find end of the current line.
  949. const char *Start = Cur;
  950. for (const char *End = Source.end(); Cur != End; ++Cur) {
  951. if (*Cur == '\\') {
  952. if (Cur + 1 != End) {
  953. ++Cur;
  954. if (*Cur == '\n' ||
  955. (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
  956. Line.append(Start, Cur - 1);
  957. if (*Cur == '\r')
  958. ++Cur;
  959. Start = Cur + 1;
  960. }
  961. }
  962. } else if (*Cur == '\n')
  963. break;
  964. }
  965. // Tokenize line.
  966. Line.append(Start, Cur);
  967. cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
  968. }
  969. }
  970. // It is called byte order marker but the UTF-8 BOM is actually not affected
  971. // by the host system's endianness.
  972. static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
  973. return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
  974. }
  975. // Substitute <CFGDIR> with the file's base path.
  976. static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver,
  977. const char *&Arg) {
  978. assert(sys::path::is_absolute(BasePath));
  979. constexpr StringLiteral Token("<CFGDIR>");
  980. const StringRef ArgString(Arg);
  981. SmallString<128> ResponseFile;
  982. StringRef::size_type StartPos = 0;
  983. for (StringRef::size_type TokenPos = ArgString.find(Token);
  984. TokenPos != StringRef::npos;
  985. TokenPos = ArgString.find(Token, StartPos)) {
  986. // Token may appear more than once per arg (e.g. comma-separated linker
  987. // args). Support by using path-append on any subsequent appearances.
  988. const StringRef LHS = ArgString.substr(StartPos, TokenPos - StartPos);
  989. if (ResponseFile.empty())
  990. ResponseFile = LHS;
  991. else
  992. llvm::sys::path::append(ResponseFile, LHS);
  993. ResponseFile.append(BasePath);
  994. StartPos = TokenPos + Token.size();
  995. }
  996. if (!ResponseFile.empty()) {
  997. // Path-append the remaining arg substring if at least one token appeared.
  998. const StringRef Remaining = ArgString.substr(StartPos);
  999. if (!Remaining.empty())
  1000. llvm::sys::path::append(ResponseFile, Remaining);
  1001. Arg = Saver.save(ResponseFile.str()).data();
  1002. }
  1003. }
  1004. // FName must be an absolute path.
  1005. Error ExpansionContext::expandResponseFile(
  1006. StringRef FName, SmallVectorImpl<const char *> &NewArgv) {
  1007. assert(sys::path::is_absolute(FName));
  1008. llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
  1009. FS->getBufferForFile(FName);
  1010. if (!MemBufOrErr) {
  1011. std::error_code EC = MemBufOrErr.getError();
  1012. return llvm::createStringError(EC, Twine("cannot not open file '") + FName +
  1013. "': " + EC.message());
  1014. }
  1015. MemoryBuffer &MemBuf = *MemBufOrErr.get();
  1016. StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
  1017. // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
  1018. ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
  1019. std::string UTF8Buf;
  1020. if (hasUTF16ByteOrderMark(BufRef)) {
  1021. if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
  1022. return llvm::createStringError(std::errc::illegal_byte_sequence,
  1023. "Could not convert UTF16 to UTF8");
  1024. Str = StringRef(UTF8Buf);
  1025. }
  1026. // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
  1027. // these bytes before parsing.
  1028. // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
  1029. else if (hasUTF8ByteOrderMark(BufRef))
  1030. Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
  1031. // Tokenize the contents into NewArgv.
  1032. Tokenizer(Str, Saver, NewArgv, MarkEOLs);
  1033. // Expanded file content may require additional transformations, like using
  1034. // absolute paths instead of relative in '@file' constructs or expanding
  1035. // macros.
  1036. if (!RelativeNames && !InConfigFile)
  1037. return Error::success();
  1038. StringRef BasePath = llvm::sys::path::parent_path(FName);
  1039. for (const char *&Arg : NewArgv) {
  1040. if (!Arg)
  1041. continue;
  1042. // Substitute <CFGDIR> with the file's base path.
  1043. if (InConfigFile)
  1044. ExpandBasePaths(BasePath, Saver, Arg);
  1045. // Discover the case, when argument should be transformed into '@file' and
  1046. // evaluate 'file' for it.
  1047. StringRef ArgStr(Arg);
  1048. StringRef FileName;
  1049. bool ConfigInclusion = false;
  1050. if (ArgStr.consume_front("@")) {
  1051. FileName = ArgStr;
  1052. if (!llvm::sys::path::is_relative(FileName))
  1053. continue;
  1054. } else if (ArgStr.consume_front("--config=")) {
  1055. FileName = ArgStr;
  1056. ConfigInclusion = true;
  1057. } else {
  1058. continue;
  1059. }
  1060. // Update expansion construct.
  1061. SmallString<128> ResponseFile;
  1062. ResponseFile.push_back('@');
  1063. if (ConfigInclusion && !llvm::sys::path::has_parent_path(FileName)) {
  1064. SmallString<128> FilePath;
  1065. if (!findConfigFile(FileName, FilePath))
  1066. return createStringError(
  1067. std::make_error_code(std::errc::no_such_file_or_directory),
  1068. "cannot not find configuration file: " + FileName);
  1069. ResponseFile.append(FilePath);
  1070. } else {
  1071. ResponseFile.append(BasePath);
  1072. llvm::sys::path::append(ResponseFile, FileName);
  1073. }
  1074. Arg = Saver.save(ResponseFile.str()).data();
  1075. }
  1076. return Error::success();
  1077. }
  1078. /// Expand response files on a command line recursively using the given
  1079. /// StringSaver and tokenization strategy.
  1080. Error ExpansionContext::expandResponseFiles(
  1081. SmallVectorImpl<const char *> &Argv) {
  1082. struct ResponseFileRecord {
  1083. std::string File;
  1084. size_t End;
  1085. };
  1086. // To detect recursive response files, we maintain a stack of files and the
  1087. // position of the last argument in the file. This position is updated
  1088. // dynamically as we recursively expand files.
  1089. SmallVector<ResponseFileRecord, 3> FileStack;
  1090. // Push a dummy entry that represents the initial command line, removing
  1091. // the need to check for an empty list.
  1092. FileStack.push_back({"", Argv.size()});
  1093. // Don't cache Argv.size() because it can change.
  1094. for (unsigned I = 0; I != Argv.size();) {
  1095. while (I == FileStack.back().End) {
  1096. // Passing the end of a file's argument list, so we can remove it from the
  1097. // stack.
  1098. FileStack.pop_back();
  1099. }
  1100. const char *Arg = Argv[I];
  1101. // Check if it is an EOL marker
  1102. if (Arg == nullptr) {
  1103. ++I;
  1104. continue;
  1105. }
  1106. if (Arg[0] != '@') {
  1107. ++I;
  1108. continue;
  1109. }
  1110. const char *FName = Arg + 1;
  1111. // Note that CurrentDir is only used for top-level rsp files, the rest will
  1112. // always have an absolute path deduced from the containing file.
  1113. SmallString<128> CurrDir;
  1114. if (llvm::sys::path::is_relative(FName)) {
  1115. if (CurrentDir.empty()) {
  1116. if (auto CWD = FS->getCurrentWorkingDirectory()) {
  1117. CurrDir = *CWD;
  1118. } else {
  1119. return createStringError(
  1120. CWD.getError(), Twine("cannot get absolute path for: ") + FName);
  1121. }
  1122. } else {
  1123. CurrDir = CurrentDir;
  1124. }
  1125. llvm::sys::path::append(CurrDir, FName);
  1126. FName = CurrDir.c_str();
  1127. }
  1128. ErrorOr<llvm::vfs::Status> Res = FS->status(FName);
  1129. if (!Res || !Res->exists()) {
  1130. std::error_code EC = Res.getError();
  1131. if (!InConfigFile) {
  1132. // If the specified file does not exist, leave '@file' unexpanded, as
  1133. // libiberty does.
  1134. if (!EC || EC == llvm::errc::no_such_file_or_directory) {
  1135. ++I;
  1136. continue;
  1137. }
  1138. }
  1139. if (!EC)
  1140. EC = llvm::errc::no_such_file_or_directory;
  1141. return createStringError(EC, Twine("cannot not open file '") + FName +
  1142. "': " + EC.message());
  1143. }
  1144. const llvm::vfs::Status &FileStatus = Res.get();
  1145. auto IsEquivalent =
  1146. [FileStatus, this](const ResponseFileRecord &RFile) -> ErrorOr<bool> {
  1147. ErrorOr<llvm::vfs::Status> RHS = FS->status(RFile.File);
  1148. if (!RHS)
  1149. return RHS.getError();
  1150. return FileStatus.equivalent(*RHS);
  1151. };
  1152. // Check for recursive response files.
  1153. for (const auto &F : drop_begin(FileStack)) {
  1154. if (ErrorOr<bool> R = IsEquivalent(F)) {
  1155. if (R.get())
  1156. return createStringError(
  1157. R.getError(), Twine("recursive expansion of: '") + F.File + "'");
  1158. } else {
  1159. return createStringError(R.getError(),
  1160. Twine("cannot open file: ") + F.File);
  1161. }
  1162. }
  1163. // Replace this response file argument with the tokenization of its
  1164. // contents. Nested response files are expanded in subsequent iterations.
  1165. SmallVector<const char *, 0> ExpandedArgv;
  1166. if (Error Err = expandResponseFile(FName, ExpandedArgv))
  1167. return Err;
  1168. for (ResponseFileRecord &Record : FileStack) {
  1169. // Increase the end of all active records by the number of newly expanded
  1170. // arguments, minus the response file itself.
  1171. Record.End += ExpandedArgv.size() - 1;
  1172. }
  1173. FileStack.push_back({FName, I + ExpandedArgv.size()});
  1174. Argv.erase(Argv.begin() + I);
  1175. Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
  1176. }
  1177. // If successful, the top of the file stack will mark the end of the Argv
  1178. // stream. A failure here indicates a bug in the stack popping logic above.
  1179. // Note that FileStack may have more than one element at this point because we
  1180. // don't have a chance to pop the stack when encountering recursive files at
  1181. // the end of the stream, so seeing that doesn't indicate a bug.
  1182. assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End);
  1183. return Error::success();
  1184. }
  1185. bool cl::expandResponseFiles(int Argc, const char *const *Argv,
  1186. const char *EnvVar, StringSaver &Saver,
  1187. SmallVectorImpl<const char *> &NewArgv) {
  1188. #ifdef _WIN32
  1189. auto Tokenize = cl::TokenizeWindowsCommandLine;
  1190. #else
  1191. auto Tokenize = cl::TokenizeGNUCommandLine;
  1192. #endif
  1193. // The environment variable specifies initial options.
  1194. if (EnvVar)
  1195. if (std::optional<std::string> EnvValue = sys::Process::GetEnv(EnvVar))
  1196. Tokenize(*EnvValue, Saver, NewArgv, /*MarkEOLs=*/false);
  1197. // Command line options can override the environment variable.
  1198. NewArgv.append(Argv + 1, Argv + Argc);
  1199. ExpansionContext ECtx(Saver.getAllocator(), Tokenize);
  1200. if (Error Err = ECtx.expandResponseFiles(NewArgv)) {
  1201. errs() << toString(std::move(Err)) << '\n';
  1202. return false;
  1203. }
  1204. return true;
  1205. }
  1206. bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
  1207. SmallVectorImpl<const char *> &Argv) {
  1208. ExpansionContext ECtx(Saver.getAllocator(), Tokenizer);
  1209. if (Error Err = ECtx.expandResponseFiles(Argv)) {
  1210. errs() << toString(std::move(Err)) << '\n';
  1211. return false;
  1212. }
  1213. return true;
  1214. }
  1215. ExpansionContext::ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T)
  1216. : Saver(A), Tokenizer(T), FS(vfs::getRealFileSystem().get()) {}
  1217. bool ExpansionContext::findConfigFile(StringRef FileName,
  1218. SmallVectorImpl<char> &FilePath) {
  1219. SmallString<128> CfgFilePath;
  1220. const auto FileExists = [this](SmallString<128> Path) -> bool {
  1221. auto Status = FS->status(Path);
  1222. return Status &&
  1223. Status->getType() == llvm::sys::fs::file_type::regular_file;
  1224. };
  1225. // If file name contains directory separator, treat it as a path to
  1226. // configuration file.
  1227. if (llvm::sys::path::has_parent_path(FileName)) {
  1228. CfgFilePath = FileName;
  1229. if (llvm::sys::path::is_relative(FileName) && FS->makeAbsolute(CfgFilePath))
  1230. return false;
  1231. if (!FileExists(CfgFilePath))
  1232. return false;
  1233. FilePath.assign(CfgFilePath.begin(), CfgFilePath.end());
  1234. return true;
  1235. }
  1236. // Look for the file in search directories.
  1237. for (const StringRef &Dir : SearchDirs) {
  1238. if (Dir.empty())
  1239. continue;
  1240. CfgFilePath.assign(Dir);
  1241. llvm::sys::path::append(CfgFilePath, FileName);
  1242. llvm::sys::path::native(CfgFilePath);
  1243. if (FileExists(CfgFilePath)) {
  1244. FilePath.assign(CfgFilePath.begin(), CfgFilePath.end());
  1245. return true;
  1246. }
  1247. }
  1248. return false;
  1249. }
  1250. Error ExpansionContext::readConfigFile(StringRef CfgFile,
  1251. SmallVectorImpl<const char *> &Argv) {
  1252. SmallString<128> AbsPath;
  1253. if (sys::path::is_relative(CfgFile)) {
  1254. AbsPath.assign(CfgFile);
  1255. if (std::error_code EC = FS->makeAbsolute(AbsPath))
  1256. return make_error<StringError>(
  1257. EC, Twine("cannot get absolute path for " + CfgFile));
  1258. CfgFile = AbsPath.str();
  1259. }
  1260. InConfigFile = true;
  1261. RelativeNames = true;
  1262. if (Error Err = expandResponseFile(CfgFile, Argv))
  1263. return Err;
  1264. return expandResponseFiles(Argv);
  1265. }
  1266. static void initCommonOptions();
  1267. bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
  1268. StringRef Overview, raw_ostream *Errs,
  1269. const char *EnvVar,
  1270. bool LongOptionsUseDoubleDash) {
  1271. initCommonOptions();
  1272. SmallVector<const char *, 20> NewArgv;
  1273. BumpPtrAllocator A;
  1274. StringSaver Saver(A);
  1275. NewArgv.push_back(argv[0]);
  1276. // Parse options from environment variable.
  1277. if (EnvVar) {
  1278. if (std::optional<std::string> EnvValue =
  1279. sys::Process::GetEnv(StringRef(EnvVar)))
  1280. TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
  1281. }
  1282. // Append options from command line.
  1283. for (int I = 1; I < argc; ++I)
  1284. NewArgv.push_back(argv[I]);
  1285. int NewArgc = static_cast<int>(NewArgv.size());
  1286. // Parse all options.
  1287. return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
  1288. Errs, LongOptionsUseDoubleDash);
  1289. }
  1290. /// Reset all options at least once, so that we can parse different options.
  1291. void CommandLineParser::ResetAllOptionOccurrences() {
  1292. // Reset all option values to look like they have never been seen before.
  1293. // Options might be reset twice (they can be reference in both OptionsMap
  1294. // and one of the other members), but that does not harm.
  1295. for (auto *SC : RegisteredSubCommands) {
  1296. for (auto &O : SC->OptionsMap)
  1297. O.second->reset();
  1298. for (Option *O : SC->PositionalOpts)
  1299. O->reset();
  1300. for (Option *O : SC->SinkOpts)
  1301. O->reset();
  1302. if (SC->ConsumeAfterOpt)
  1303. SC->ConsumeAfterOpt->reset();
  1304. }
  1305. }
  1306. bool CommandLineParser::ParseCommandLineOptions(int argc,
  1307. const char *const *argv,
  1308. StringRef Overview,
  1309. raw_ostream *Errs,
  1310. bool LongOptionsUseDoubleDash) {
  1311. assert(hasOptions() && "No options specified!");
  1312. ProgramOverview = Overview;
  1313. bool IgnoreErrors = Errs;
  1314. if (!Errs)
  1315. Errs = &errs();
  1316. bool ErrorParsing = false;
  1317. // Expand response files.
  1318. SmallVector<const char *, 20> newArgv(argv, argv + argc);
  1319. BumpPtrAllocator A;
  1320. #ifdef _WIN32
  1321. auto Tokenize = cl::TokenizeWindowsCommandLine;
  1322. #else
  1323. auto Tokenize = cl::TokenizeGNUCommandLine;
  1324. #endif
  1325. ExpansionContext ECtx(A, Tokenize);
  1326. if (Error Err = ECtx.expandResponseFiles(newArgv)) {
  1327. *Errs << toString(std::move(Err)) << '\n';
  1328. return false;
  1329. }
  1330. argv = &newArgv[0];
  1331. argc = static_cast<int>(newArgv.size());
  1332. // Copy the program name into ProgName, making sure not to overflow it.
  1333. ProgramName = std::string(sys::path::filename(StringRef(argv[0])));
  1334. // Check out the positional arguments to collect information about them.
  1335. unsigned NumPositionalRequired = 0;
  1336. // Determine whether or not there are an unlimited number of positionals
  1337. bool HasUnlimitedPositionals = false;
  1338. int FirstArg = 1;
  1339. SubCommand *ChosenSubCommand = &SubCommand::getTopLevel();
  1340. if (argc >= 2 && argv[FirstArg][0] != '-') {
  1341. // If the first argument specifies a valid subcommand, start processing
  1342. // options from the second argument.
  1343. ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
  1344. if (ChosenSubCommand != &SubCommand::getTopLevel())
  1345. FirstArg = 2;
  1346. }
  1347. GlobalParser->ActiveSubCommand = ChosenSubCommand;
  1348. assert(ChosenSubCommand);
  1349. auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
  1350. auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
  1351. auto &SinkOpts = ChosenSubCommand->SinkOpts;
  1352. auto &OptionsMap = ChosenSubCommand->OptionsMap;
  1353. for (auto *O: DefaultOptions) {
  1354. addOption(O, true);
  1355. }
  1356. if (ConsumeAfterOpt) {
  1357. assert(PositionalOpts.size() > 0 &&
  1358. "Cannot specify cl::ConsumeAfter without a positional argument!");
  1359. }
  1360. if (!PositionalOpts.empty()) {
  1361. // Calculate how many positional values are _required_.
  1362. bool UnboundedFound = false;
  1363. for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
  1364. Option *Opt = PositionalOpts[i];
  1365. if (RequiresValue(Opt))
  1366. ++NumPositionalRequired;
  1367. else if (ConsumeAfterOpt) {
  1368. // ConsumeAfter cannot be combined with "optional" positional options
  1369. // unless there is only one positional argument...
  1370. if (PositionalOpts.size() > 1) {
  1371. if (!IgnoreErrors)
  1372. Opt->error("error - this positional option will never be matched, "
  1373. "because it does not Require a value, and a "
  1374. "cl::ConsumeAfter option is active!");
  1375. ErrorParsing = true;
  1376. }
  1377. } else if (UnboundedFound && !Opt->hasArgStr()) {
  1378. // This option does not "require" a value... Make sure this option is
  1379. // not specified after an option that eats all extra arguments, or this
  1380. // one will never get any!
  1381. //
  1382. if (!IgnoreErrors)
  1383. Opt->error("error - option can never match, because "
  1384. "another positional argument will match an "
  1385. "unbounded number of values, and this option"
  1386. " does not require a value!");
  1387. *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
  1388. << "' is all messed up!\n";
  1389. *Errs << PositionalOpts.size();
  1390. ErrorParsing = true;
  1391. }
  1392. UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
  1393. }
  1394. HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
  1395. }
  1396. // PositionalVals - A vector of "positional" arguments we accumulate into
  1397. // the process at the end.
  1398. //
  1399. SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
  1400. // If the program has named positional arguments, and the name has been run
  1401. // across, keep track of which positional argument was named. Otherwise put
  1402. // the positional args into the PositionalVals list...
  1403. Option *ActivePositionalArg = nullptr;
  1404. // Loop over all of the arguments... processing them.
  1405. bool DashDashFound = false; // Have we read '--'?
  1406. for (int i = FirstArg; i < argc; ++i) {
  1407. Option *Handler = nullptr;
  1408. Option *NearestHandler = nullptr;
  1409. std::string NearestHandlerString;
  1410. StringRef Value;
  1411. StringRef ArgName = "";
  1412. bool HaveDoubleDash = false;
  1413. // Check to see if this is a positional argument. This argument is
  1414. // considered to be positional if it doesn't start with '-', if it is "-"
  1415. // itself, or if we have seen "--" already.
  1416. //
  1417. if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
  1418. // Positional argument!
  1419. if (ActivePositionalArg) {
  1420. ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
  1421. continue; // We are done!
  1422. }
  1423. if (!PositionalOpts.empty()) {
  1424. PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
  1425. // All of the positional arguments have been fulfulled, give the rest to
  1426. // the consume after option... if it's specified...
  1427. //
  1428. if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
  1429. for (++i; i < argc; ++i)
  1430. PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
  1431. break; // Handle outside of the argument processing loop...
  1432. }
  1433. // Delay processing positional arguments until the end...
  1434. continue;
  1435. }
  1436. } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
  1437. !DashDashFound) {
  1438. DashDashFound = true; // This is the mythical "--"?
  1439. continue; // Don't try to process it as an argument itself.
  1440. } else if (ActivePositionalArg &&
  1441. (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
  1442. // If there is a positional argument eating options, check to see if this
  1443. // option is another positional argument. If so, treat it as an argument,
  1444. // otherwise feed it to the eating positional.
  1445. ArgName = StringRef(argv[i] + 1);
  1446. // Eat second dash.
  1447. if (!ArgName.empty() && ArgName[0] == '-') {
  1448. HaveDoubleDash = true;
  1449. ArgName = ArgName.substr(1);
  1450. }
  1451. Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
  1452. LongOptionsUseDoubleDash, HaveDoubleDash);
  1453. if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
  1454. ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
  1455. continue; // We are done!
  1456. }
  1457. } else { // We start with a '-', must be an argument.
  1458. ArgName = StringRef(argv[i] + 1);
  1459. // Eat second dash.
  1460. if (!ArgName.empty() && ArgName[0] == '-') {
  1461. HaveDoubleDash = true;
  1462. ArgName = ArgName.substr(1);
  1463. }
  1464. Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
  1465. LongOptionsUseDoubleDash, HaveDoubleDash);
  1466. // Check to see if this "option" is really a prefixed or grouped argument.
  1467. if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
  1468. Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
  1469. OptionsMap);
  1470. // Otherwise, look for the closest available option to report to the user
  1471. // in the upcoming error.
  1472. if (!Handler && SinkOpts.empty())
  1473. NearestHandler =
  1474. LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
  1475. }
  1476. if (!Handler) {
  1477. if (SinkOpts.empty()) {
  1478. *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
  1479. << "'. Try: '" << argv[0] << " --help'\n";
  1480. if (NearestHandler) {
  1481. // If we know a near match, report it as well.
  1482. *Errs << ProgramName << ": Did you mean '"
  1483. << PrintArg(NearestHandlerString, 0) << "'?\n";
  1484. }
  1485. ErrorParsing = true;
  1486. } else {
  1487. for (Option *SinkOpt : SinkOpts)
  1488. SinkOpt->addOccurrence(i, "", StringRef(argv[i]));
  1489. }
  1490. continue;
  1491. }
  1492. // If this is a named positional argument, just remember that it is the
  1493. // active one...
  1494. if (Handler->getFormattingFlag() == cl::Positional) {
  1495. if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
  1496. Handler->error("This argument does not take a value.\n"
  1497. "\tInstead, it consumes any positional arguments until "
  1498. "the next recognized option.", *Errs);
  1499. ErrorParsing = true;
  1500. }
  1501. ActivePositionalArg = Handler;
  1502. }
  1503. else
  1504. ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
  1505. }
  1506. // Check and handle positional arguments now...
  1507. if (NumPositionalRequired > PositionalVals.size()) {
  1508. *Errs << ProgramName
  1509. << ": Not enough positional command line arguments specified!\n"
  1510. << "Must specify at least " << NumPositionalRequired
  1511. << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
  1512. << ": See: " << argv[0] << " --help\n";
  1513. ErrorParsing = true;
  1514. } else if (!HasUnlimitedPositionals &&
  1515. PositionalVals.size() > PositionalOpts.size()) {
  1516. *Errs << ProgramName << ": Too many positional arguments specified!\n"
  1517. << "Can specify at most " << PositionalOpts.size()
  1518. << " positional arguments: See: " << argv[0] << " --help\n";
  1519. ErrorParsing = true;
  1520. } else if (!ConsumeAfterOpt) {
  1521. // Positional args have already been handled if ConsumeAfter is specified.
  1522. unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
  1523. for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
  1524. if (RequiresValue(PositionalOpts[i])) {
  1525. ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
  1526. PositionalVals[ValNo].second);
  1527. ValNo++;
  1528. --NumPositionalRequired; // We fulfilled our duty...
  1529. }
  1530. // If we _can_ give this option more arguments, do so now, as long as we
  1531. // do not give it values that others need. 'Done' controls whether the
  1532. // option even _WANTS_ any more.
  1533. //
  1534. bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
  1535. while (NumVals - ValNo > NumPositionalRequired && !Done) {
  1536. switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
  1537. case cl::Optional:
  1538. Done = true; // Optional arguments want _at most_ one value
  1539. [[fallthrough]];
  1540. case cl::ZeroOrMore: // Zero or more will take all they can get...
  1541. case cl::OneOrMore: // One or more will take all they can get...
  1542. ProvidePositionalOption(PositionalOpts[i],
  1543. PositionalVals[ValNo].first,
  1544. PositionalVals[ValNo].second);
  1545. ValNo++;
  1546. break;
  1547. default:
  1548. llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
  1549. "positional argument processing!");
  1550. }
  1551. }
  1552. }
  1553. } else {
  1554. assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
  1555. unsigned ValNo = 0;
  1556. for (size_t J = 0, E = PositionalOpts.size(); J != E; ++J)
  1557. if (RequiresValue(PositionalOpts[J])) {
  1558. ErrorParsing |= ProvidePositionalOption(PositionalOpts[J],
  1559. PositionalVals[ValNo].first,
  1560. PositionalVals[ValNo].second);
  1561. ValNo++;
  1562. }
  1563. // Handle the case where there is just one positional option, and it's
  1564. // optional. In this case, we want to give JUST THE FIRST option to the
  1565. // positional option and keep the rest for the consume after. The above
  1566. // loop would have assigned no values to positional options in this case.
  1567. //
  1568. if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
  1569. ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
  1570. PositionalVals[ValNo].first,
  1571. PositionalVals[ValNo].second);
  1572. ValNo++;
  1573. }
  1574. // Handle over all of the rest of the arguments to the
  1575. // cl::ConsumeAfter command line option...
  1576. for (; ValNo != PositionalVals.size(); ++ValNo)
  1577. ErrorParsing |=
  1578. ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
  1579. PositionalVals[ValNo].second);
  1580. }
  1581. // Loop over args and make sure all required args are specified!
  1582. for (const auto &Opt : OptionsMap) {
  1583. switch (Opt.second->getNumOccurrencesFlag()) {
  1584. case Required:
  1585. case OneOrMore:
  1586. if (Opt.second->getNumOccurrences() == 0) {
  1587. Opt.second->error("must be specified at least once!");
  1588. ErrorParsing = true;
  1589. }
  1590. [[fallthrough]];
  1591. default:
  1592. break;
  1593. }
  1594. }
  1595. // Now that we know if -debug is specified, we can use it.
  1596. // Note that if ReadResponseFiles == true, this must be done before the
  1597. // memory allocated for the expanded command line is free()d below.
  1598. LLVM_DEBUG(dbgs() << "Args: ";
  1599. for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
  1600. dbgs() << '\n';);
  1601. // Free all of the memory allocated to the map. Command line options may only
  1602. // be processed once!
  1603. MoreHelp.clear();
  1604. // If we had an error processing our arguments, don't let the program execute
  1605. if (ErrorParsing) {
  1606. if (!IgnoreErrors)
  1607. exit(1);
  1608. return false;
  1609. }
  1610. return true;
  1611. }
  1612. //===----------------------------------------------------------------------===//
  1613. // Option Base class implementation
  1614. //
  1615. bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
  1616. if (!ArgName.data())
  1617. ArgName = ArgStr;
  1618. if (ArgName.empty())
  1619. Errs << HelpStr; // Be nice for positional arguments
  1620. else
  1621. Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName, 0);
  1622. Errs << " option: " << Message << "\n";
  1623. return true;
  1624. }
  1625. bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
  1626. bool MultiArg) {
  1627. if (!MultiArg)
  1628. NumOccurrences++; // Increment the number of times we have been seen
  1629. return handleOccurrence(pos, ArgName, Value);
  1630. }
  1631. // getValueStr - Get the value description string, using "DefaultMsg" if nothing
  1632. // has been specified yet.
  1633. //
  1634. static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
  1635. if (O.ValueStr.empty())
  1636. return DefaultMsg;
  1637. return O.ValueStr;
  1638. }
  1639. //===----------------------------------------------------------------------===//
  1640. // cl::alias class implementation
  1641. //
  1642. // Return the width of the option tag for printing...
  1643. size_t alias::getOptionWidth() const {
  1644. return argPlusPrefixesSize(ArgStr);
  1645. }
  1646. void Option::printHelpStr(StringRef HelpStr, size_t Indent,
  1647. size_t FirstLineIndentedBy) {
  1648. assert(Indent >= FirstLineIndentedBy);
  1649. std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
  1650. outs().indent(Indent - FirstLineIndentedBy)
  1651. << ArgHelpPrefix << Split.first << "\n";
  1652. while (!Split.second.empty()) {
  1653. Split = Split.second.split('\n');
  1654. outs().indent(Indent) << Split.first << "\n";
  1655. }
  1656. }
  1657. void Option::printEnumValHelpStr(StringRef HelpStr, size_t BaseIndent,
  1658. size_t FirstLineIndentedBy) {
  1659. const StringRef ValHelpPrefix = " ";
  1660. assert(BaseIndent >= FirstLineIndentedBy);
  1661. std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
  1662. outs().indent(BaseIndent - FirstLineIndentedBy)
  1663. << ArgHelpPrefix << ValHelpPrefix << Split.first << "\n";
  1664. while (!Split.second.empty()) {
  1665. Split = Split.second.split('\n');
  1666. outs().indent(BaseIndent + ValHelpPrefix.size()) << Split.first << "\n";
  1667. }
  1668. }
  1669. // Print out the option for the alias.
  1670. void alias::printOptionInfo(size_t GlobalWidth) const {
  1671. outs() << PrintArg(ArgStr);
  1672. printHelpStr(HelpStr, GlobalWidth, argPlusPrefixesSize(ArgStr));
  1673. }
  1674. //===----------------------------------------------------------------------===//
  1675. // Parser Implementation code...
  1676. //
  1677. // basic_parser implementation
  1678. //
  1679. // Return the width of the option tag for printing...
  1680. size_t basic_parser_impl::getOptionWidth(const Option &O) const {
  1681. size_t Len = argPlusPrefixesSize(O.ArgStr);
  1682. auto ValName = getValueName();
  1683. if (!ValName.empty()) {
  1684. size_t FormattingLen = 3;
  1685. if (O.getMiscFlags() & PositionalEatsArgs)
  1686. FormattingLen = 6;
  1687. Len += getValueStr(O, ValName).size() + FormattingLen;
  1688. }
  1689. return Len;
  1690. }
  1691. // printOptionInfo - Print out information about this option. The
  1692. // to-be-maintained width is specified.
  1693. //
  1694. void basic_parser_impl::printOptionInfo(const Option &O,
  1695. size_t GlobalWidth) const {
  1696. outs() << PrintArg(O.ArgStr);
  1697. auto ValName = getValueName();
  1698. if (!ValName.empty()) {
  1699. if (O.getMiscFlags() & PositionalEatsArgs) {
  1700. outs() << " <" << getValueStr(O, ValName) << ">...";
  1701. } else if (O.getValueExpectedFlag() == ValueOptional)
  1702. outs() << "[=<" << getValueStr(O, ValName) << ">]";
  1703. else {
  1704. outs() << (O.ArgStr.size() == 1 ? " <" : "=<") << getValueStr(O, ValName)
  1705. << '>';
  1706. }
  1707. }
  1708. Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
  1709. }
  1710. void basic_parser_impl::printOptionName(const Option &O,
  1711. size_t GlobalWidth) const {
  1712. outs() << PrintArg(O.ArgStr);
  1713. outs().indent(GlobalWidth - O.ArgStr.size());
  1714. }
  1715. // parser<bool> implementation
  1716. //
  1717. bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1718. bool &Value) {
  1719. if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
  1720. Arg == "1") {
  1721. Value = true;
  1722. return false;
  1723. }
  1724. if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
  1725. Value = false;
  1726. return false;
  1727. }
  1728. return O.error("'" + Arg +
  1729. "' is invalid value for boolean argument! Try 0 or 1");
  1730. }
  1731. // parser<boolOrDefault> implementation
  1732. //
  1733. bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1734. boolOrDefault &Value) {
  1735. if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
  1736. Arg == "1") {
  1737. Value = BOU_TRUE;
  1738. return false;
  1739. }
  1740. if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
  1741. Value = BOU_FALSE;
  1742. return false;
  1743. }
  1744. return O.error("'" + Arg +
  1745. "' is invalid value for boolean argument! Try 0 or 1");
  1746. }
  1747. // parser<int> implementation
  1748. //
  1749. bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1750. int &Value) {
  1751. if (Arg.getAsInteger(0, Value))
  1752. return O.error("'" + Arg + "' value invalid for integer argument!");
  1753. return false;
  1754. }
  1755. // parser<long> implementation
  1756. //
  1757. bool parser<long>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1758. long &Value) {
  1759. if (Arg.getAsInteger(0, Value))
  1760. return O.error("'" + Arg + "' value invalid for long argument!");
  1761. return false;
  1762. }
  1763. // parser<long long> implementation
  1764. //
  1765. bool parser<long long>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1766. long long &Value) {
  1767. if (Arg.getAsInteger(0, Value))
  1768. return O.error("'" + Arg + "' value invalid for llong argument!");
  1769. return false;
  1770. }
  1771. // parser<unsigned> implementation
  1772. //
  1773. bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1774. unsigned &Value) {
  1775. if (Arg.getAsInteger(0, Value))
  1776. return O.error("'" + Arg + "' value invalid for uint argument!");
  1777. return false;
  1778. }
  1779. // parser<unsigned long> implementation
  1780. //
  1781. bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1782. unsigned long &Value) {
  1783. if (Arg.getAsInteger(0, Value))
  1784. return O.error("'" + Arg + "' value invalid for ulong argument!");
  1785. return false;
  1786. }
  1787. // parser<unsigned long long> implementation
  1788. //
  1789. bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
  1790. StringRef Arg,
  1791. unsigned long long &Value) {
  1792. if (Arg.getAsInteger(0, Value))
  1793. return O.error("'" + Arg + "' value invalid for ullong argument!");
  1794. return false;
  1795. }
  1796. // parser<double>/parser<float> implementation
  1797. //
  1798. static bool parseDouble(Option &O, StringRef Arg, double &Value) {
  1799. if (to_float(Arg, Value))
  1800. return false;
  1801. return O.error("'" + Arg + "' value invalid for floating point argument!");
  1802. }
  1803. bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1804. double &Val) {
  1805. return parseDouble(O, Arg, Val);
  1806. }
  1807. bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1808. float &Val) {
  1809. double dVal;
  1810. if (parseDouble(O, Arg, dVal))
  1811. return true;
  1812. Val = (float)dVal;
  1813. return false;
  1814. }
  1815. // generic_parser_base implementation
  1816. //
  1817. // findOption - Return the option number corresponding to the specified
  1818. // argument string. If the option is not found, getNumOptions() is returned.
  1819. //
  1820. unsigned generic_parser_base::findOption(StringRef Name) {
  1821. unsigned e = getNumOptions();
  1822. for (unsigned i = 0; i != e; ++i) {
  1823. if (getOption(i) == Name)
  1824. return i;
  1825. }
  1826. return e;
  1827. }
  1828. static StringRef EqValue = "=<value>";
  1829. static StringRef EmptyOption = "<empty>";
  1830. static StringRef OptionPrefix = " =";
  1831. static size_t getOptionPrefixesSize() {
  1832. return OptionPrefix.size() + ArgHelpPrefix.size();
  1833. }
  1834. static bool shouldPrintOption(StringRef Name, StringRef Description,
  1835. const Option &O) {
  1836. return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
  1837. !Description.empty();
  1838. }
  1839. // Return the width of the option tag for printing...
  1840. size_t generic_parser_base::getOptionWidth(const Option &O) const {
  1841. if (O.hasArgStr()) {
  1842. size_t Size =
  1843. argPlusPrefixesSize(O.ArgStr) + EqValue.size();
  1844. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  1845. StringRef Name = getOption(i);
  1846. if (!shouldPrintOption(Name, getDescription(i), O))
  1847. continue;
  1848. size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
  1849. Size = std::max(Size, NameSize + getOptionPrefixesSize());
  1850. }
  1851. return Size;
  1852. } else {
  1853. size_t BaseSize = 0;
  1854. for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
  1855. BaseSize = std::max(BaseSize, getOption(i).size() + 8);
  1856. return BaseSize;
  1857. }
  1858. }
  1859. // printOptionInfo - Print out information about this option. The
  1860. // to-be-maintained width is specified.
  1861. //
  1862. void generic_parser_base::printOptionInfo(const Option &O,
  1863. size_t GlobalWidth) const {
  1864. if (O.hasArgStr()) {
  1865. // When the value is optional, first print a line just describing the
  1866. // option without values.
  1867. if (O.getValueExpectedFlag() == ValueOptional) {
  1868. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  1869. if (getOption(i).empty()) {
  1870. outs() << PrintArg(O.ArgStr);
  1871. Option::printHelpStr(O.HelpStr, GlobalWidth,
  1872. argPlusPrefixesSize(O.ArgStr));
  1873. break;
  1874. }
  1875. }
  1876. }
  1877. outs() << PrintArg(O.ArgStr) << EqValue;
  1878. Option::printHelpStr(O.HelpStr, GlobalWidth,
  1879. EqValue.size() +
  1880. argPlusPrefixesSize(O.ArgStr));
  1881. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  1882. StringRef OptionName = getOption(i);
  1883. StringRef Description = getDescription(i);
  1884. if (!shouldPrintOption(OptionName, Description, O))
  1885. continue;
  1886. size_t FirstLineIndent = OptionName.size() + getOptionPrefixesSize();
  1887. outs() << OptionPrefix << OptionName;
  1888. if (OptionName.empty()) {
  1889. outs() << EmptyOption;
  1890. assert(FirstLineIndent >= EmptyOption.size());
  1891. FirstLineIndent += EmptyOption.size();
  1892. }
  1893. if (!Description.empty())
  1894. Option::printEnumValHelpStr(Description, GlobalWidth, FirstLineIndent);
  1895. else
  1896. outs() << '\n';
  1897. }
  1898. } else {
  1899. if (!O.HelpStr.empty())
  1900. outs() << " " << O.HelpStr << '\n';
  1901. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  1902. StringRef Option = getOption(i);
  1903. outs() << " " << PrintArg(Option);
  1904. Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
  1905. }
  1906. }
  1907. }
  1908. static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
  1909. // printGenericOptionDiff - Print the value of this option and it's default.
  1910. //
  1911. // "Generic" options have each value mapped to a name.
  1912. void generic_parser_base::printGenericOptionDiff(
  1913. const Option &O, const GenericOptionValue &Value,
  1914. const GenericOptionValue &Default, size_t GlobalWidth) const {
  1915. outs() << " " << PrintArg(O.ArgStr);
  1916. outs().indent(GlobalWidth - O.ArgStr.size());
  1917. unsigned NumOpts = getNumOptions();
  1918. for (unsigned i = 0; i != NumOpts; ++i) {
  1919. if (Value.compare(getOptionValue(i)))
  1920. continue;
  1921. outs() << "= " << getOption(i);
  1922. size_t L = getOption(i).size();
  1923. size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
  1924. outs().indent(NumSpaces) << " (default: ";
  1925. for (unsigned j = 0; j != NumOpts; ++j) {
  1926. if (Default.compare(getOptionValue(j)))
  1927. continue;
  1928. outs() << getOption(j);
  1929. break;
  1930. }
  1931. outs() << ")\n";
  1932. return;
  1933. }
  1934. outs() << "= *unknown option value*\n";
  1935. }
  1936. // printOptionDiff - Specializations for printing basic value types.
  1937. //
  1938. #define PRINT_OPT_DIFF(T) \
  1939. void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
  1940. size_t GlobalWidth) const { \
  1941. printOptionName(O, GlobalWidth); \
  1942. std::string Str; \
  1943. { \
  1944. raw_string_ostream SS(Str); \
  1945. SS << V; \
  1946. } \
  1947. outs() << "= " << Str; \
  1948. size_t NumSpaces = \
  1949. MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
  1950. outs().indent(NumSpaces) << " (default: "; \
  1951. if (D.hasValue()) \
  1952. outs() << D.getValue(); \
  1953. else \
  1954. outs() << "*no default*"; \
  1955. outs() << ")\n"; \
  1956. }
  1957. PRINT_OPT_DIFF(bool)
  1958. PRINT_OPT_DIFF(boolOrDefault)
  1959. PRINT_OPT_DIFF(int)
  1960. PRINT_OPT_DIFF(long)
  1961. PRINT_OPT_DIFF(long long)
  1962. PRINT_OPT_DIFF(unsigned)
  1963. PRINT_OPT_DIFF(unsigned long)
  1964. PRINT_OPT_DIFF(unsigned long long)
  1965. PRINT_OPT_DIFF(double)
  1966. PRINT_OPT_DIFF(float)
  1967. PRINT_OPT_DIFF(char)
  1968. void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
  1969. const OptionValue<std::string> &D,
  1970. size_t GlobalWidth) const {
  1971. printOptionName(O, GlobalWidth);
  1972. outs() << "= " << V;
  1973. size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
  1974. outs().indent(NumSpaces) << " (default: ";
  1975. if (D.hasValue())
  1976. outs() << D.getValue();
  1977. else
  1978. outs() << "*no default*";
  1979. outs() << ")\n";
  1980. }
  1981. // Print a placeholder for options that don't yet support printOptionDiff().
  1982. void basic_parser_impl::printOptionNoValue(const Option &O,
  1983. size_t GlobalWidth) const {
  1984. printOptionName(O, GlobalWidth);
  1985. outs() << "= *cannot print option value*\n";
  1986. }
  1987. //===----------------------------------------------------------------------===//
  1988. // -help and -help-hidden option implementation
  1989. //
  1990. static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
  1991. const std::pair<const char *, Option *> *RHS) {
  1992. return strcmp(LHS->first, RHS->first);
  1993. }
  1994. static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
  1995. const std::pair<const char *, SubCommand *> *RHS) {
  1996. return strcmp(LHS->first, RHS->first);
  1997. }
  1998. // Copy Options into a vector so we can sort them as we like.
  1999. static void sortOpts(StringMap<Option *> &OptMap,
  2000. SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
  2001. bool ShowHidden) {
  2002. SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
  2003. for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
  2004. I != E; ++I) {
  2005. // Ignore really-hidden options.
  2006. if (I->second->getOptionHiddenFlag() == ReallyHidden)
  2007. continue;
  2008. // Unless showhidden is set, ignore hidden flags.
  2009. if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
  2010. continue;
  2011. // If we've already seen this option, don't add it to the list again.
  2012. if (!OptionSet.insert(I->second).second)
  2013. continue;
  2014. Opts.push_back(
  2015. std::pair<const char *, Option *>(I->getKey().data(), I->second));
  2016. }
  2017. // Sort the options list alphabetically.
  2018. array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
  2019. }
  2020. static void
  2021. sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
  2022. SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
  2023. for (auto *S : SubMap) {
  2024. if (S->getName().empty())
  2025. continue;
  2026. Subs.push_back(std::make_pair(S->getName().data(), S));
  2027. }
  2028. array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
  2029. }
  2030. namespace {
  2031. class HelpPrinter {
  2032. protected:
  2033. const bool ShowHidden;
  2034. typedef SmallVector<std::pair<const char *, Option *>, 128>
  2035. StrOptionPairVector;
  2036. typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
  2037. StrSubCommandPairVector;
  2038. // Print the options. Opts is assumed to be alphabetically sorted.
  2039. virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
  2040. for (size_t i = 0, e = Opts.size(); i != e; ++i)
  2041. Opts[i].second->printOptionInfo(MaxArgLen);
  2042. }
  2043. void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
  2044. for (const auto &S : Subs) {
  2045. outs() << " " << S.first;
  2046. if (!S.second->getDescription().empty()) {
  2047. outs().indent(MaxSubLen - strlen(S.first));
  2048. outs() << " - " << S.second->getDescription();
  2049. }
  2050. outs() << "\n";
  2051. }
  2052. }
  2053. public:
  2054. explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
  2055. virtual ~HelpPrinter() = default;
  2056. // Invoke the printer.
  2057. void operator=(bool Value) {
  2058. if (!Value)
  2059. return;
  2060. printHelp();
  2061. // Halt the program since help information was printed
  2062. exit(0);
  2063. }
  2064. void printHelp() {
  2065. SubCommand *Sub = GlobalParser->getActiveSubCommand();
  2066. auto &OptionsMap = Sub->OptionsMap;
  2067. auto &PositionalOpts = Sub->PositionalOpts;
  2068. auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
  2069. StrOptionPairVector Opts;
  2070. sortOpts(OptionsMap, Opts, ShowHidden);
  2071. StrSubCommandPairVector Subs;
  2072. sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
  2073. if (!GlobalParser->ProgramOverview.empty())
  2074. outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
  2075. if (Sub == &SubCommand::getTopLevel()) {
  2076. outs() << "USAGE: " << GlobalParser->ProgramName;
  2077. if (Subs.size() > 2)
  2078. outs() << " [subcommand]";
  2079. outs() << " [options]";
  2080. } else {
  2081. if (!Sub->getDescription().empty()) {
  2082. outs() << "SUBCOMMAND '" << Sub->getName()
  2083. << "': " << Sub->getDescription() << "\n\n";
  2084. }
  2085. outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
  2086. << " [options]";
  2087. }
  2088. for (auto *Opt : PositionalOpts) {
  2089. if (Opt->hasArgStr())
  2090. outs() << " --" << Opt->ArgStr;
  2091. outs() << " " << Opt->HelpStr;
  2092. }
  2093. // Print the consume after option info if it exists...
  2094. if (ConsumeAfterOpt)
  2095. outs() << " " << ConsumeAfterOpt->HelpStr;
  2096. if (Sub == &SubCommand::getTopLevel() && !Subs.empty()) {
  2097. // Compute the maximum subcommand length...
  2098. size_t MaxSubLen = 0;
  2099. for (size_t i = 0, e = Subs.size(); i != e; ++i)
  2100. MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
  2101. outs() << "\n\n";
  2102. outs() << "SUBCOMMANDS:\n\n";
  2103. printSubCommands(Subs, MaxSubLen);
  2104. outs() << "\n";
  2105. outs() << " Type \"" << GlobalParser->ProgramName
  2106. << " <subcommand> --help\" to get more help on a specific "
  2107. "subcommand";
  2108. }
  2109. outs() << "\n\n";
  2110. // Compute the maximum argument length...
  2111. size_t MaxArgLen = 0;
  2112. for (size_t i = 0, e = Opts.size(); i != e; ++i)
  2113. MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
  2114. outs() << "OPTIONS:\n";
  2115. printOptions(Opts, MaxArgLen);
  2116. // Print any extra help the user has declared.
  2117. for (const auto &I : GlobalParser->MoreHelp)
  2118. outs() << I;
  2119. GlobalParser->MoreHelp.clear();
  2120. }
  2121. };
  2122. class CategorizedHelpPrinter : public HelpPrinter {
  2123. public:
  2124. explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
  2125. // Helper function for printOptions().
  2126. // It shall return a negative value if A's name should be lexicographically
  2127. // ordered before B's name. It returns a value greater than zero if B's name
  2128. // should be ordered before A's name, and it returns 0 otherwise.
  2129. static int OptionCategoryCompare(OptionCategory *const *A,
  2130. OptionCategory *const *B) {
  2131. return (*A)->getName().compare((*B)->getName());
  2132. }
  2133. // Make sure we inherit our base class's operator=()
  2134. using HelpPrinter::operator=;
  2135. protected:
  2136. void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
  2137. std::vector<OptionCategory *> SortedCategories;
  2138. DenseMap<OptionCategory *, std::vector<Option *>> CategorizedOptions;
  2139. // Collect registered option categories into vector in preparation for
  2140. // sorting.
  2141. for (OptionCategory *Category : GlobalParser->RegisteredOptionCategories)
  2142. SortedCategories.push_back(Category);
  2143. // Sort the different option categories alphabetically.
  2144. assert(SortedCategories.size() > 0 && "No option categories registered!");
  2145. array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
  2146. OptionCategoryCompare);
  2147. // Walk through pre-sorted options and assign into categories.
  2148. // Because the options are already alphabetically sorted the
  2149. // options within categories will also be alphabetically sorted.
  2150. for (size_t I = 0, E = Opts.size(); I != E; ++I) {
  2151. Option *Opt = Opts[I].second;
  2152. for (auto &Cat : Opt->Categories) {
  2153. assert(llvm::is_contained(SortedCategories, Cat) &&
  2154. "Option has an unregistered category");
  2155. CategorizedOptions[Cat].push_back(Opt);
  2156. }
  2157. }
  2158. // Now do printing.
  2159. for (OptionCategory *Category : SortedCategories) {
  2160. // Hide empty categories for --help, but show for --help-hidden.
  2161. const auto &CategoryOptions = CategorizedOptions[Category];
  2162. bool IsEmptyCategory = CategoryOptions.empty();
  2163. if (!ShowHidden && IsEmptyCategory)
  2164. continue;
  2165. // Print category information.
  2166. outs() << "\n";
  2167. outs() << Category->getName() << ":\n";
  2168. // Check if description is set.
  2169. if (!Category->getDescription().empty())
  2170. outs() << Category->getDescription() << "\n\n";
  2171. else
  2172. outs() << "\n";
  2173. // When using --help-hidden explicitly state if the category has no
  2174. // options associated with it.
  2175. if (IsEmptyCategory) {
  2176. outs() << " This option category has no options.\n";
  2177. continue;
  2178. }
  2179. // Loop over the options in the category and print.
  2180. for (const Option *Opt : CategoryOptions)
  2181. Opt->printOptionInfo(MaxArgLen);
  2182. }
  2183. }
  2184. };
  2185. // This wraps the Uncategorizing and Categorizing printers and decides
  2186. // at run time which should be invoked.
  2187. class HelpPrinterWrapper {
  2188. private:
  2189. HelpPrinter &UncategorizedPrinter;
  2190. CategorizedHelpPrinter &CategorizedPrinter;
  2191. public:
  2192. explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
  2193. CategorizedHelpPrinter &CategorizedPrinter)
  2194. : UncategorizedPrinter(UncategorizedPrinter),
  2195. CategorizedPrinter(CategorizedPrinter) {}
  2196. // Invoke the printer.
  2197. void operator=(bool Value);
  2198. };
  2199. } // End anonymous namespace
  2200. #if defined(__GNUC__)
  2201. // GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are
  2202. // enabled.
  2203. # if defined(__OPTIMIZE__)
  2204. # define LLVM_IS_DEBUG_BUILD 0
  2205. # else
  2206. # define LLVM_IS_DEBUG_BUILD 1
  2207. # endif
  2208. #elif defined(_MSC_VER)
  2209. // MSVC doesn't have a predefined macro indicating if optimizations are enabled.
  2210. // Use _DEBUG instead. This macro actually corresponds to the choice between
  2211. // debug and release CRTs, but it is a reasonable proxy.
  2212. # if defined(_DEBUG)
  2213. # define LLVM_IS_DEBUG_BUILD 1
  2214. # else
  2215. # define LLVM_IS_DEBUG_BUILD 0
  2216. # endif
  2217. #else
  2218. // Otherwise, for an unknown compiler, assume this is an optimized build.
  2219. # define LLVM_IS_DEBUG_BUILD 0
  2220. #endif
  2221. namespace {
  2222. class VersionPrinter {
  2223. public:
  2224. void print(std::vector<VersionPrinterTy> ExtraPrinters = {}) {
  2225. raw_ostream &OS = outs();
  2226. #ifdef PACKAGE_VENDOR
  2227. OS << PACKAGE_VENDOR << " ";
  2228. #else
  2229. OS << "LLVM (http://llvm.org/):\n ";
  2230. #endif
  2231. OS << PACKAGE_NAME << " version " << PACKAGE_VERSION << "\n ";
  2232. #if LLVM_IS_DEBUG_BUILD
  2233. OS << "DEBUG build";
  2234. #else
  2235. OS << "Optimized build";
  2236. #endif
  2237. #ifndef NDEBUG
  2238. OS << " with assertions";
  2239. #endif
  2240. OS << ".\n";
  2241. // Iterate over any registered extra printers and call them to add further
  2242. // information.
  2243. if (!ExtraPrinters.empty()) {
  2244. for (const auto &I : ExtraPrinters)
  2245. I(outs());
  2246. }
  2247. }
  2248. void operator=(bool OptionWasSpecified);
  2249. };
  2250. struct CommandLineCommonOptions {
  2251. // Declare the four HelpPrinter instances that are used to print out help, or
  2252. // help-hidden as an uncategorized list or in categories.
  2253. HelpPrinter UncategorizedNormalPrinter{false};
  2254. HelpPrinter UncategorizedHiddenPrinter{true};
  2255. CategorizedHelpPrinter CategorizedNormalPrinter{false};
  2256. CategorizedHelpPrinter CategorizedHiddenPrinter{true};
  2257. // Declare HelpPrinter wrappers that will decide whether or not to invoke
  2258. // a categorizing help printer
  2259. HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
  2260. CategorizedNormalPrinter};
  2261. HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
  2262. CategorizedHiddenPrinter};
  2263. // Define a category for generic options that all tools should have.
  2264. cl::OptionCategory GenericCategory{"Generic Options"};
  2265. // Define uncategorized help printers.
  2266. // --help-list is hidden by default because if Option categories are being
  2267. // used then --help behaves the same as --help-list.
  2268. cl::opt<HelpPrinter, true, parser<bool>> HLOp{
  2269. "help-list",
  2270. cl::desc(
  2271. "Display list of available options (--help-list-hidden for more)"),
  2272. cl::location(UncategorizedNormalPrinter),
  2273. cl::Hidden,
  2274. cl::ValueDisallowed,
  2275. cl::cat(GenericCategory),
  2276. cl::sub(SubCommand::getAll())};
  2277. cl::opt<HelpPrinter, true, parser<bool>> HLHOp{
  2278. "help-list-hidden",
  2279. cl::desc("Display list of all available options"),
  2280. cl::location(UncategorizedHiddenPrinter),
  2281. cl::Hidden,
  2282. cl::ValueDisallowed,
  2283. cl::cat(GenericCategory),
  2284. cl::sub(SubCommand::getAll())};
  2285. // Define uncategorized/categorized help printers. These printers change their
  2286. // behaviour at runtime depending on whether one or more Option categories
  2287. // have been declared.
  2288. cl::opt<HelpPrinterWrapper, true, parser<bool>> HOp{
  2289. "help",
  2290. cl::desc("Display available options (--help-hidden for more)"),
  2291. cl::location(WrappedNormalPrinter),
  2292. cl::ValueDisallowed,
  2293. cl::cat(GenericCategory),
  2294. cl::sub(SubCommand::getAll())};
  2295. cl::alias HOpA{"h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
  2296. cl::DefaultOption};
  2297. cl::opt<HelpPrinterWrapper, true, parser<bool>> HHOp{
  2298. "help-hidden",
  2299. cl::desc("Display all available options"),
  2300. cl::location(WrappedHiddenPrinter),
  2301. cl::Hidden,
  2302. cl::ValueDisallowed,
  2303. cl::cat(GenericCategory),
  2304. cl::sub(SubCommand::getAll())};
  2305. cl::opt<bool> PrintOptions{
  2306. "print-options",
  2307. cl::desc("Print non-default options after command line parsing"),
  2308. cl::Hidden,
  2309. cl::init(false),
  2310. cl::cat(GenericCategory),
  2311. cl::sub(SubCommand::getAll())};
  2312. cl::opt<bool> PrintAllOptions{
  2313. "print-all-options",
  2314. cl::desc("Print all option values after command line parsing"),
  2315. cl::Hidden,
  2316. cl::init(false),
  2317. cl::cat(GenericCategory),
  2318. cl::sub(SubCommand::getAll())};
  2319. VersionPrinterTy OverrideVersionPrinter = nullptr;
  2320. std::vector<VersionPrinterTy> ExtraVersionPrinters;
  2321. // Define the --version option that prints out the LLVM version for the tool
  2322. VersionPrinter VersionPrinterInstance;
  2323. cl::opt<VersionPrinter, true, parser<bool>> VersOp{
  2324. "version", cl::desc("Display the version of this program"),
  2325. cl::location(VersionPrinterInstance), cl::ValueDisallowed,
  2326. cl::cat(GenericCategory)};
  2327. };
  2328. } // End anonymous namespace
  2329. // Lazy-initialized global instance of options controlling the command-line
  2330. // parser and general handling.
  2331. static ManagedStatic<CommandLineCommonOptions> CommonOptions;
  2332. static void initCommonOptions() {
  2333. *CommonOptions;
  2334. initDebugCounterOptions();
  2335. initGraphWriterOptions();
  2336. initSignalsOptions();
  2337. initStatisticOptions();
  2338. initTimerOptions();
  2339. initTypeSizeOptions();
  2340. initWithColorOptions();
  2341. initDebugOptions();
  2342. initRandomSeedOptions();
  2343. }
  2344. OptionCategory &cl::getGeneralCategory() {
  2345. // Initialise the general option category.
  2346. static OptionCategory GeneralCategory{"General options"};
  2347. return GeneralCategory;
  2348. }
  2349. void VersionPrinter::operator=(bool OptionWasSpecified) {
  2350. if (!OptionWasSpecified)
  2351. return;
  2352. if (CommonOptions->OverrideVersionPrinter != nullptr) {
  2353. CommonOptions->OverrideVersionPrinter(outs());
  2354. exit(0);
  2355. }
  2356. print(CommonOptions->ExtraVersionPrinters);
  2357. exit(0);
  2358. }
  2359. void HelpPrinterWrapper::operator=(bool Value) {
  2360. if (!Value)
  2361. return;
  2362. // Decide which printer to invoke. If more than one option category is
  2363. // registered then it is useful to show the categorized help instead of
  2364. // uncategorized help.
  2365. if (GlobalParser->RegisteredOptionCategories.size() > 1) {
  2366. // unhide --help-list option so user can have uncategorized output if they
  2367. // want it.
  2368. CommonOptions->HLOp.setHiddenFlag(NotHidden);
  2369. CategorizedPrinter = true; // Invoke categorized printer
  2370. } else
  2371. UncategorizedPrinter = true; // Invoke uncategorized printer
  2372. }
  2373. // Print the value of each option.
  2374. void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
  2375. void CommandLineParser::printOptionValues() {
  2376. if (!CommonOptions->PrintOptions && !CommonOptions->PrintAllOptions)
  2377. return;
  2378. SmallVector<std::pair<const char *, Option *>, 128> Opts;
  2379. sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
  2380. // Compute the maximum argument length...
  2381. size_t MaxArgLen = 0;
  2382. for (size_t i = 0, e = Opts.size(); i != e; ++i)
  2383. MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
  2384. for (size_t i = 0, e = Opts.size(); i != e; ++i)
  2385. Opts[i].second->printOptionValue(MaxArgLen, CommonOptions->PrintAllOptions);
  2386. }
  2387. // Utility function for printing the help message.
  2388. void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
  2389. if (!Hidden && !Categorized)
  2390. CommonOptions->UncategorizedNormalPrinter.printHelp();
  2391. else if (!Hidden && Categorized)
  2392. CommonOptions->CategorizedNormalPrinter.printHelp();
  2393. else if (Hidden && !Categorized)
  2394. CommonOptions->UncategorizedHiddenPrinter.printHelp();
  2395. else
  2396. CommonOptions->CategorizedHiddenPrinter.printHelp();
  2397. }
  2398. /// Utility function for printing version number.
  2399. void cl::PrintVersionMessage() {
  2400. CommonOptions->VersionPrinterInstance.print(CommonOptions->ExtraVersionPrinters);
  2401. }
  2402. void cl::SetVersionPrinter(VersionPrinterTy func) {
  2403. CommonOptions->OverrideVersionPrinter = func;
  2404. }
  2405. void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
  2406. CommonOptions->ExtraVersionPrinters.push_back(func);
  2407. }
  2408. StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
  2409. initCommonOptions();
  2410. auto &Subs = GlobalParser->RegisteredSubCommands;
  2411. (void)Subs;
  2412. assert(is_contained(Subs, &Sub));
  2413. return Sub.OptionsMap;
  2414. }
  2415. iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
  2416. cl::getRegisteredSubcommands() {
  2417. return GlobalParser->getRegisteredSubcommands();
  2418. }
  2419. void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
  2420. initCommonOptions();
  2421. for (auto &I : Sub.OptionsMap) {
  2422. bool Unrelated = true;
  2423. for (auto &Cat : I.second->Categories) {
  2424. if (Cat == &Category || Cat == &CommonOptions->GenericCategory)
  2425. Unrelated = false;
  2426. }
  2427. if (Unrelated)
  2428. I.second->setHiddenFlag(cl::ReallyHidden);
  2429. }
  2430. }
  2431. void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
  2432. SubCommand &Sub) {
  2433. initCommonOptions();
  2434. for (auto &I : Sub.OptionsMap) {
  2435. bool Unrelated = true;
  2436. for (auto &Cat : I.second->Categories) {
  2437. if (is_contained(Categories, Cat) ||
  2438. Cat == &CommonOptions->GenericCategory)
  2439. Unrelated = false;
  2440. }
  2441. if (Unrelated)
  2442. I.second->setHiddenFlag(cl::ReallyHidden);
  2443. }
  2444. }
  2445. void cl::ResetCommandLineParser() { GlobalParser->reset(); }
  2446. void cl::ResetAllOptionOccurrences() {
  2447. GlobalParser->ResetAllOptionOccurrences();
  2448. }
  2449. void LLVMParseCommandLineOptions(int argc, const char *const *argv,
  2450. const char *Overview) {
  2451. llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
  2452. &llvm::nulls());
  2453. }