command_line.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "common/command_line.h"
  5. #include <initializer_list>
  6. #include <memory>
  7. #include "llvm/Support/FormatVariadic.h"
  8. namespace Carbon::CommandLine {
  9. auto operator<<(llvm::raw_ostream& output, ParseResult result)
  10. -> llvm::raw_ostream& {
  11. switch (result) {
  12. case ParseResult::Error:
  13. return output << "Error";
  14. case ParseResult::MetaSuccess:
  15. return output << "MetaSuccess";
  16. case ParseResult::Success:
  17. return output << "Success";
  18. }
  19. CARBON_FATAL() << "Corrupt parse result!";
  20. }
  21. auto operator<<(llvm::raw_ostream& output, ArgKind kind) -> llvm::raw_ostream& {
  22. switch (kind) {
  23. case ArgKind::Flag:
  24. return output << "Boolean";
  25. case ArgKind::Integer:
  26. return output << "Integer";
  27. case ArgKind::String:
  28. return output << "String";
  29. case ArgKind::OneOf:
  30. return output << "OneOf";
  31. case ArgKind::MetaActionOnly:
  32. return output << "MetaActionOnly";
  33. case ArgKind::Invalid:
  34. return output << "Invalid";
  35. }
  36. CARBON_FATAL() << "Corrupt argument kind!";
  37. }
  38. auto operator<<(llvm::raw_ostream& output, CommandKind kind)
  39. -> llvm::raw_ostream& {
  40. switch (kind) {
  41. case CommandKind::Invalid:
  42. return output << "Invalid";
  43. case CommandKind::RequiresSubcommand:
  44. return output << "RequiresSubcommand";
  45. case CommandKind::Action:
  46. return output << "Action";
  47. case CommandKind::MetaAction:
  48. return output << "MetaAction";
  49. }
  50. CARBON_FATAL() << "Corrupt command kind!";
  51. }
  52. Arg::Arg(const ArgInfo& info) : info(info) {}
  53. Arg::~Arg() {
  54. switch (kind) {
  55. case Kind::Flag:
  56. case Kind::Integer:
  57. case Kind::String:
  58. case Kind::MetaActionOnly:
  59. case Kind::Invalid:
  60. // Nothing to do!
  61. break;
  62. case Kind::OneOf:
  63. value_strings.~decltype(value_strings)();
  64. value_action.~ValueActionT();
  65. if (has_default) {
  66. default_action.~DefaultActionT();
  67. }
  68. break;
  69. }
  70. }
  71. Command::Command(const CommandInfo& info, Command* parent)
  72. : info(info), parent(parent) {}
  73. class MetaPrinter {
  74. public:
  75. explicit MetaPrinter(llvm::raw_ostream& out) : out_(out) {}
  76. // Registers this meta printer with a command through the provided builder.
  77. //
  78. // This adds meta subcommands or options to print both help and version
  79. // information for the command.
  80. void RegisterWithCommand(const Command& command, CommandBuilder& builder);
  81. void PrintHelp(const Command& command) const;
  82. void PrintVersion(const Command& command) const;
  83. void PrintSubcommands(const Command& command) const;
  84. private:
  85. // The indent is calibrated to allow a short and long option after a two
  86. // character indent on the prior line to be visually recognized as separate
  87. // from the hanging indent.
  88. //
  89. // Visual guide: | -x, --extract
  90. // | Hanging indented.
  91. static constexpr llvm::StringRef BlockIndent = " ";
  92. // Width limit for parent command options in usage rendering.
  93. static constexpr int MaxParentOptionUsageWidth = 8;
  94. // Width limit for the leaf command options in usage rendering.
  95. static constexpr int MaxLeafOptionUsageWidth = 16;
  96. static constexpr CommandInfo HelpCommandInfo = {
  97. .name = "help",
  98. .help = R"""(
  99. Prints help information for the command, including a description, command line
  100. usage, and details of each subcommand and option that can be provided.
  101. )""",
  102. .help_short = R"""(
  103. Prints help information.
  104. )""",
  105. };
  106. static constexpr ArgInfo HelpArgInfo = {
  107. .name = "help",
  108. .value_name = "(full|short)",
  109. .help = R"""(
  110. Prints help information for the command, including a description, command line
  111. usage, and details of each option that can be provided.
  112. )""",
  113. .help_short = HelpCommandInfo.help_short,
  114. };
  115. // Provide a customized description for help on a subcommand to avoid
  116. // confusion with the top-level help.
  117. static constexpr CommandInfo SubHelpCommandInfo = {
  118. .name = "help",
  119. .help = R"""(
  120. Prints help information for the subcommand, including a description, command
  121. line usage, and details of each further subcommand and option that can be
  122. provided.
  123. )""",
  124. .help_short = R"""(
  125. Prints subcommand help information.
  126. )""",
  127. };
  128. static constexpr ArgInfo SubHelpArgInfo = {
  129. .name = "help",
  130. .value_name = "(full|short)",
  131. .help = R"""(
  132. Prints help information for the subcommand, including a description, command
  133. line usage, and details of each option that can be provided.
  134. )""",
  135. .help_short = SubHelpCommandInfo.help_short,
  136. };
  137. static constexpr CommandInfo VersionCommandInfo = {
  138. .name = "version",
  139. .help = R"""(
  140. Prints the version of this command.
  141. )""",
  142. };
  143. static constexpr ArgInfo VersionArgInfo = {
  144. .name = "version",
  145. .help = VersionCommandInfo.help,
  146. };
  147. // A general helper for rendering a text block.
  148. void PrintTextBlock(llvm::StringRef indent, llvm::StringRef text) const;
  149. // Helpers for version and build information printing.
  150. void PrintRawVersion(const Command& command, llvm::StringRef indent) const;
  151. void PrintRawBuildInfo(const Command& command, llvm::StringRef indent) const;
  152. // Helpers for printing components of help and usage output for arguments,
  153. // including options and positional arguments.
  154. void PrintArgValueUsage(const Arg& arg) const;
  155. void PrintOptionUsage(const Arg& option) const;
  156. void PrintOptionShortName(const Arg& arg) const;
  157. void PrintArgShortValues(const Arg& arg) const;
  158. void PrintArgLongValues(const Arg& arg, llvm::StringRef indent) const;
  159. void PrintArgHelp(const Arg& arg, llvm::StringRef indent) const;
  160. // Helpers for printing command usage summaries.
  161. void PrintRawUsageCommandAndOptions(
  162. const Command& command,
  163. int max_option_width = MaxLeafOptionUsageWidth) const;
  164. void PrintRawUsage(const Command& command, llvm::StringRef indent) const;
  165. void PrintUsage(const Command& command) const;
  166. // Helpers to print various sections of `PrintHelp` that only occur within
  167. // that output.
  168. void PrintHelpSubcommands(const Command& command) const;
  169. void PrintHelpPositionalArgs(const Command& command) const;
  170. void PrintHelpOptions(const Command& command) const;
  171. llvm::raw_ostream& out_;
  172. // A flag that may be configured during command line parsing to select between
  173. // long and short form help output.
  174. bool short_help_ = false;
  175. };
  176. void MetaPrinter::RegisterWithCommand(const Command& command,
  177. CommandBuilder& builder) {
  178. bool is_subcommand = command.parent;
  179. bool has_subcommands = !command.subcommands.empty();
  180. // If this command has subcommands, we prefer that model for access meta
  181. // actions, but still silently support using the flags. But we never want to
  182. // *add* subcommands if they aren't already being used.
  183. if (has_subcommands) {
  184. builder.AddSubcommand(
  185. is_subcommand ? SubHelpCommandInfo : HelpCommandInfo,
  186. [&](CommandBuilder& sub_b) {
  187. sub_b.Meta([this, &command]() { PrintHelp(command); });
  188. });
  189. // Only add version printing support if there is a version string
  190. // configured for this command.
  191. if (!command.info.version.empty()) {
  192. builder.AddSubcommand(VersionCommandInfo, [&](CommandBuilder& sub_b) {
  193. sub_b.Meta([this, &command]() { PrintVersion(command); });
  194. });
  195. }
  196. }
  197. builder.AddOneOfOption(
  198. is_subcommand ? SubHelpArgInfo : HelpArgInfo, [&](auto& arg_b) {
  199. arg_b.HelpHidden(has_subcommands);
  200. arg_b.SetOneOf(
  201. {
  202. arg_b.OneOfValue("full", false).Default(true),
  203. arg_b.OneOfValue("short", true),
  204. },
  205. &short_help_);
  206. arg_b.MetaAction([this, &command]() { PrintHelp(command); });
  207. });
  208. // Only add version printing support if there is a version string configured
  209. // for this command.
  210. if (!command.info.version.empty()) {
  211. builder.AddMetaActionOption(VersionArgInfo, [&](auto& arg_b) {
  212. arg_b.HelpHidden(has_subcommands);
  213. arg_b.MetaAction([this, &command]() { PrintVersion(command); });
  214. });
  215. }
  216. }
  217. void MetaPrinter::PrintHelp(const Command& command) const {
  218. // TODO: begin using the short setting to customize the output.
  219. (void)short_help_;
  220. const CommandInfo& info = command.info;
  221. if (!info.version.empty()) {
  222. // We use the version string as a header for the command help when present.
  223. PrintRawVersion(command, /*indent=*/"");
  224. out_ << "\n";
  225. }
  226. if (!command.info.help.empty()) {
  227. PrintTextBlock("", info.help);
  228. out_ << "\n";
  229. }
  230. if (!info.build_info.empty()) {
  231. out_ << "Build info:\n";
  232. PrintRawBuildInfo(command, /*indent=*/" ");
  233. out_ << "\n";
  234. }
  235. PrintUsage(command);
  236. PrintHelpSubcommands(command);
  237. PrintHelpPositionalArgs(command);
  238. PrintHelpOptions(command);
  239. if (!info.help_epilogue.empty()) {
  240. out_ << "\n";
  241. PrintTextBlock("", info.help_epilogue);
  242. }
  243. // End with a blank line for the long help to make it easier to separate from
  244. // anything that follows in the shell.
  245. out_ << "\n";
  246. }
  247. void MetaPrinter::PrintVersion(const Command& command) const {
  248. CARBON_CHECK(!command.info.version.empty())
  249. << "Printing should not be enabled without a version string configured.";
  250. PrintRawVersion(command, /*indent=*/"");
  251. if (!command.info.build_info.empty()) {
  252. out_ << "\n";
  253. // If there is build info to print, we also render that without any indent.
  254. PrintRawBuildInfo(command, /*indent=*/"");
  255. }
  256. }
  257. void MetaPrinter::PrintSubcommands(const Command& command) const {
  258. for (const auto& subcommand :
  259. llvm::ArrayRef(command.subcommands).drop_back()) {
  260. out_ << "'" << subcommand->info.name << "', ";
  261. }
  262. if (command.subcommands.size() > 1) {
  263. out_ << "or ";
  264. }
  265. out_ << "'" << command.subcommands.back()->info.name << "'";
  266. }
  267. void MetaPrinter::PrintRawVersion(const Command& command,
  268. llvm::StringRef indent) const {
  269. // Newlines are trimmed from the version string an a closing newline added but
  270. // no other formatting is performed.
  271. out_ << indent << command.info.version.trim('\n') << "\n";
  272. }
  273. void MetaPrinter::PrintRawBuildInfo(const Command& command,
  274. llvm::StringRef indent) const {
  275. // Print the build info line-by-line without any wrapping in case it
  276. // contains line-oriented formatted text, but drop leading and trailing blank
  277. // lines.
  278. llvm::SmallVector<llvm::StringRef, 128> lines;
  279. command.info.build_info.trim('\n').split(lines, "\n");
  280. for (auto line : lines) {
  281. out_ << indent << line << "\n";
  282. }
  283. }
  284. void MetaPrinter::PrintTextBlock(llvm::StringRef indent,
  285. llvm::StringRef text) const {
  286. // Strip leading and trailing newlines to make it easy to use multiline raw
  287. // string literals that will naturally have those.
  288. text = text.trim('\n');
  289. // For empty text, print nothing at all. The caller formatting will work to
  290. // handle this gracefully.
  291. if (text.empty()) {
  292. return;
  293. }
  294. // Remove line breaks from the text that would typically be removed when
  295. // rendering it as Markdown. The goal is to preserve:
  296. //
  297. // - Blank lines as paragraph separators.
  298. // - Line breaks after list items or other structural components in Markdown.
  299. // - Fenced regions exactly as they appear.
  300. //
  301. // And within paragraphs (including those nested in lists), reflow the
  302. // paragraph intelligently to the column width. There are TODOs below about
  303. // both lists and reflowing.
  304. llvm::SmallVector<llvm::StringRef, 128> input_lines;
  305. text.split(input_lines, "\n");
  306. for (int i = 0, size = input_lines.size(); i < size;) {
  307. if (input_lines[i].empty()) {
  308. // Blank lines are preserved.
  309. out_ << "\n";
  310. ++i;
  311. continue;
  312. }
  313. if (input_lines[i].starts_with("```")) {
  314. // Fenced regions are preserved verbatim.
  315. llvm::StringRef fence =
  316. input_lines[i].slice(0, input_lines[i].find_first_not_of("`"));
  317. do {
  318. out_ << indent << input_lines[i] << "\n";
  319. ++i;
  320. } while (i < size && !input_lines[i].starts_with(fence));
  321. if (i >= size) {
  322. // Don't error on malformed text blocks, just print what we've got.
  323. break;
  324. }
  325. // Including the close of the fence.
  326. out_ << indent << input_lines[i] << "\n";
  327. ++i;
  328. continue;
  329. }
  330. if (input_lines[i].starts_with(" ")) {
  331. // Indented code blocks ar preserved verbatim, but we don't support tabs
  332. // in the indent for simplicity.
  333. do {
  334. out_ << indent << input_lines[i] << "\n";
  335. ++i;
  336. } while (i < size && input_lines[i].starts_with(" "));
  337. continue;
  338. }
  339. // TODO: Detect other Markdown structures, especially lists and tables.
  340. // Otherwise, collect all of the lines until the end or the next blank line
  341. // as a block of text.
  342. //
  343. // TODO: This is where we should re-flow.
  344. llvm::StringRef space = indent;
  345. do {
  346. out_ << space << input_lines[i].trim();
  347. space = " ";
  348. ++i;
  349. } while (i < size && !input_lines[i].empty());
  350. out_ << "\n";
  351. }
  352. }
  353. void MetaPrinter::PrintArgValueUsage(const Arg& arg) const {
  354. if (!arg.info.value_name.empty()) {
  355. out_ << arg.info.value_name;
  356. return;
  357. }
  358. if (arg.kind == Arg::Kind::OneOf) {
  359. out_ << "(";
  360. llvm::ListSeparator sep("|");
  361. for (llvm::StringRef value_string : arg.value_strings) {
  362. out_ << sep << value_string;
  363. }
  364. out_ << ")";
  365. return;
  366. }
  367. out_ << "...";
  368. }
  369. void MetaPrinter::PrintOptionUsage(const Arg& option) const {
  370. if (option.kind == Arg::Kind::Flag) {
  371. out_ << "--" << (option.default_flag ? "no-" : "") << option.info.name;
  372. return;
  373. }
  374. out_ << "--" << option.info.name;
  375. if (option.kind != Arg::Kind::MetaActionOnly) {
  376. out_ << (option.has_default ? "[" : "") << "=";
  377. PrintArgValueUsage(option);
  378. if (option.has_default) {
  379. out_ << "]";
  380. }
  381. }
  382. }
  383. void MetaPrinter::PrintOptionShortName(const Arg& arg) const {
  384. CARBON_CHECK(!arg.info.short_name.empty()) << "No short name to use.";
  385. out_ << "-" << arg.info.short_name;
  386. }
  387. void MetaPrinter::PrintArgShortValues(const Arg& arg) const {
  388. CARBON_CHECK(arg.kind == Arg::Kind::OneOf)
  389. << "Only one-of arguments have interesting value snippets to print.";
  390. llvm::ListSeparator sep;
  391. for (llvm::StringRef value_string : arg.value_strings) {
  392. out_ << sep << value_string;
  393. }
  394. }
  395. void MetaPrinter::PrintArgLongValues(const Arg& arg,
  396. llvm::StringRef indent) const {
  397. out_ << indent << "Possible values:\n";
  398. // TODO: It would be good to add help text for each value and then print it
  399. // here.
  400. for (int i : llvm::seq<int>(0, arg.value_strings.size())) {
  401. llvm::StringRef value_string = arg.value_strings[i];
  402. out_ << indent << "- " << value_string;
  403. if (arg.has_default && i == arg.default_value_index) {
  404. out_ << " (default)";
  405. }
  406. out_ << "\n";
  407. }
  408. }
  409. void MetaPrinter::PrintArgHelp(const Arg& arg, llvm::StringRef indent) const {
  410. // Print out the main help text.
  411. PrintTextBlock(indent, arg.info.help);
  412. // Then print out any help based on the values.
  413. switch (arg.kind) {
  414. case Arg::Kind::Integer:
  415. if (arg.has_default) {
  416. out_ << "\n";
  417. out_ << indent << "Default value: " << arg.default_integer << "\n";
  418. }
  419. break;
  420. case Arg::Kind::String:
  421. if (arg.has_default) {
  422. out_ << "\n";
  423. out_ << indent << "Default value: " << arg.default_string << "\n";
  424. }
  425. break;
  426. case Arg::Kind::OneOf:
  427. out_ << "\n";
  428. PrintArgLongValues(arg, indent);
  429. break;
  430. case Arg::Kind::Flag:
  431. case Arg::Kind::MetaActionOnly:
  432. // No value help.
  433. break;
  434. case Arg::Kind::Invalid:
  435. CARBON_FATAL() << "Argument configured without any action or kind!";
  436. }
  437. }
  438. void MetaPrinter::PrintRawUsageCommandAndOptions(const Command& command,
  439. int max_option_width) const {
  440. // Recursively print parent usage first with a compressed width.
  441. if (command.parent) {
  442. PrintRawUsageCommandAndOptions(*command.parent, MaxParentOptionUsageWidth);
  443. out_ << " ";
  444. }
  445. out_ << command.info.name;
  446. // Buffer the options rendering so we can limit its length.
  447. std::string buffer_str;
  448. llvm::raw_string_ostream buffer_out(buffer_str);
  449. MetaPrinter buffer_printer(buffer_out);
  450. bool have_short_flags = false;
  451. for (const auto& arg : command.options) {
  452. if (static_cast<int>(buffer_str.size()) > max_option_width) {
  453. break;
  454. }
  455. // We can summarize positive boolean flags with a short name using a
  456. // sequence of short names in a single rendered argument.
  457. if (arg->kind == Arg::Kind::Flag && !arg->default_flag &&
  458. !arg->info.short_name.empty()) {
  459. if (!have_short_flags) {
  460. have_short_flags = true;
  461. buffer_out << "-";
  462. }
  463. buffer_out << arg->info.short_name;
  464. }
  465. }
  466. llvm::StringRef space = have_short_flags ? " " : "";
  467. for (const auto& option : command.options) {
  468. if (static_cast<int>(buffer_str.size()) > max_option_width) {
  469. break;
  470. }
  471. if (option->is_help_hidden || option->meta_action) {
  472. // Skip hidden and options with meta actions attached.
  473. continue;
  474. }
  475. if (option->kind == Arg::Kind::Flag && !option->default_flag &&
  476. !option->info.short_name.empty()) {
  477. // Handled with short names above.
  478. continue;
  479. }
  480. buffer_out << space;
  481. buffer_printer.PrintOptionUsage(*option);
  482. space = " ";
  483. }
  484. if (!buffer_str.empty()) {
  485. if (static_cast<int>(buffer_str.size()) <= max_option_width) {
  486. out_ << " [" << buffer_str << "]";
  487. } else {
  488. out_ << " [OPTIONS]";
  489. }
  490. }
  491. }
  492. void MetaPrinter::PrintRawUsage(const Command& command,
  493. llvm::StringRef indent) const {
  494. if (!command.info.usage.empty()) {
  495. PrintTextBlock(indent, command.info.usage);
  496. return;
  497. }
  498. if (command.kind != Command::Kind::RequiresSubcommand) {
  499. // We're a valid leaf command, so synthesize a full usage line.
  500. out_ << indent;
  501. PrintRawUsageCommandAndOptions(command);
  502. if (!command.positional_args.empty()) {
  503. bool open_optional = false;
  504. for (int i : llvm::seq<int>(0, command.positional_args.size())) {
  505. out_ << " ";
  506. if (i != 0 && command.positional_args[i - 1]->is_append) {
  507. out_ << "-- ";
  508. }
  509. const auto& arg = command.positional_args[i];
  510. if (!arg->is_required && !open_optional) {
  511. out_ << "[";
  512. open_optional = true;
  513. }
  514. out_ << "<" << arg->info.name << ">";
  515. if (arg->is_append) {
  516. out_ << "...";
  517. }
  518. }
  519. if (open_optional) {
  520. out_ << "]";
  521. }
  522. }
  523. out_ << "\n";
  524. }
  525. // If we have subcommands, also recurse into them so each one can print their
  526. // usage lines.
  527. for (const auto& subcommand : command.subcommands) {
  528. if (subcommand->is_help_hidden ||
  529. subcommand->kind == Command::Kind::MetaAction) {
  530. continue;
  531. }
  532. PrintRawUsage(*subcommand, indent);
  533. }
  534. }
  535. void MetaPrinter::PrintUsage(const Command& command) const {
  536. if (!command.parent) {
  537. out_ << "Usage:\n";
  538. } else {
  539. out_ << "Subcommand '" << command.info.name << "' usage:\n";
  540. }
  541. PrintRawUsage(command, " ");
  542. }
  543. void MetaPrinter::PrintHelpSubcommands(const Command& command) const {
  544. bool first_subcommand = true;
  545. for (const auto& subcommand : command.subcommands) {
  546. if (subcommand->is_help_hidden) {
  547. continue;
  548. }
  549. if (first_subcommand) {
  550. first_subcommand = false;
  551. if (!command.parent) {
  552. out_ << "\nSubcommands:";
  553. } else {
  554. out_ << "\nSubcommand '" << command.info.name << "' subcommands:";
  555. }
  556. }
  557. out_ << "\n";
  558. out_ << " " << subcommand->info.name << "\n";
  559. PrintTextBlock(BlockIndent, subcommand->info.help);
  560. }
  561. }
  562. void MetaPrinter::PrintHelpPositionalArgs(const Command& command) const {
  563. bool first_positional_arg = true;
  564. for (const auto& positional_arg : command.positional_args) {
  565. if (positional_arg->is_help_hidden) {
  566. continue;
  567. }
  568. if (first_positional_arg) {
  569. first_positional_arg = false;
  570. if (!command.parent) {
  571. out_ << "\nPositional arguments:";
  572. } else {
  573. out_ << "\nSubcommand '" << command.info.name
  574. << "' positional arguments:";
  575. }
  576. }
  577. out_ << "\n";
  578. out_ << " " << positional_arg->info.name << "\n";
  579. PrintArgHelp(*positional_arg, BlockIndent);
  580. }
  581. }
  582. void MetaPrinter::PrintHelpOptions(const Command& command) const {
  583. bool first_option = true;
  584. for (const auto& option : command.options) {
  585. if (option->is_help_hidden) {
  586. continue;
  587. }
  588. if (first_option) {
  589. first_option = false;
  590. if (!command.parent && command.subcommands.empty()) {
  591. // Only one command level.
  592. out_ << "\nOptions:";
  593. } else if (!command.parent) {
  594. out_ << "\nCommand options:";
  595. } else {
  596. out_ << "\nSubcommand '" << command.info.name << "' options:";
  597. }
  598. }
  599. out_ << "\n";
  600. out_ << " ";
  601. if (!option->info.short_name.empty()) {
  602. PrintOptionShortName(*option);
  603. out_ << ", ";
  604. } else {
  605. out_ << " ";
  606. }
  607. PrintOptionUsage(*option);
  608. out_ << "\n";
  609. PrintArgHelp(*option, BlockIndent);
  610. }
  611. }
  612. class Parser {
  613. public:
  614. explicit Parser(llvm::raw_ostream& out, llvm::raw_ostream& errors,
  615. const CommandInfo& command_info,
  616. llvm::function_ref<void(CommandBuilder&)> build);
  617. auto Parse(llvm::ArrayRef<llvm::StringRef> unparsed_args) -> ParseResult;
  618. private:
  619. friend CommandBuilder;
  620. // For the option and subcommand maps, we use somewhat large small size
  621. // buffers (16) as there is no real size pressure on these and its nice to
  622. // avoid heap allocation in the small cases.
  623. using OptionMapT =
  624. llvm::SmallDenseMap<llvm::StringRef, llvm::PointerIntPair<Arg*, 1, bool>,
  625. 16>;
  626. using SubcommandMapT = llvm::SmallDenseMap<llvm::StringRef, Command*, 16>;
  627. // This table is sized to be 128 so that it can hold ASCII characters. We
  628. // don't need any more than this and using a direct table indexed by the
  629. // character's numeric value makes for a convenient map.
  630. using ShortOptionTableT = std::array<OptionMapT::mapped_type*, 128>;
  631. void PopulateMaps(const Command& command);
  632. void SetOptionDefault(const Arg& option);
  633. auto ParseNegatedFlag(const Arg& flag, std::optional<llvm::StringRef> value)
  634. -> bool;
  635. auto ParseFlag(const Arg& flag, std::optional<llvm::StringRef> value) -> bool;
  636. auto ParseIntegerArgValue(const Arg& arg, llvm::StringRef value) -> bool;
  637. auto ParseStringArgValue(const Arg& arg, llvm::StringRef value) -> bool;
  638. auto ParseOneOfArgValue(const Arg& arg, llvm::StringRef value) -> bool;
  639. auto ParseArg(const Arg& arg, bool short_spelling,
  640. std::optional<llvm::StringRef> value, bool negated_name = false)
  641. -> bool;
  642. auto SplitValue(llvm::StringRef& unparsed_arg)
  643. -> std::optional<llvm::StringRef>;
  644. auto ParseLongOption(llvm::StringRef unparsed_arg) -> bool;
  645. auto ParseShortOptionSeq(llvm::StringRef unparsed_arg) -> bool;
  646. auto FinalizeParsedOptions() -> bool;
  647. auto ParsePositionalArg(llvm::StringRef unparsed_arg) -> bool;
  648. auto ParseSubcommand(llvm::StringRef unparsed_arg) -> bool;
  649. auto ParsePositionalSuffix(llvm::ArrayRef<llvm::StringRef> unparsed_args)
  650. -> bool;
  651. auto FinalizeParse() -> ParseResult;
  652. // When building a command, it registers arguments and potentially subcommands
  653. // that are meta actions to print things to standard out, so we build a meta
  654. // printer for that here.
  655. MetaPrinter meta_printer_;
  656. // Most parsing output goes to an error stream, and we also provide an
  657. // error-oriented meta printer for when that is useful during parsing.
  658. llvm::raw_ostream& errors_;
  659. MetaPrinter error_meta_printer_;
  660. Command root_command_;
  661. const Command* command_;
  662. OptionMapT option_map_;
  663. ShortOptionTableT short_option_table_;
  664. SubcommandMapT subcommand_map_;
  665. int positional_arg_index_ = 0;
  666. bool appending_to_positional_arg_ = false;
  667. ActionT arg_meta_action_;
  668. };
  669. void Parser::PopulateMaps(const Command& command) {
  670. option_map_.clear();
  671. for (const auto& option : command.options) {
  672. option_map_.insert({option->info.name, {option.get(), false}});
  673. }
  674. short_option_table_.fill(nullptr);
  675. for (auto& map_entry : option_map_) {
  676. const Arg* option = map_entry.second.getPointer();
  677. if (option->info.short_name.empty()) {
  678. continue;
  679. }
  680. CARBON_CHECK(option->info.short_name.size() == 1)
  681. << "Short option names must have exactly one character.";
  682. unsigned char short_char = option->info.short_name[0];
  683. CARBON_CHECK(short_char < short_option_table_.size())
  684. << "Short option name outside of the expected range.";
  685. short_option_table_[short_char] = &map_entry.second;
  686. }
  687. subcommand_map_.clear();
  688. for (const auto& subcommand : command.subcommands) {
  689. subcommand_map_.insert({subcommand->info.name, subcommand.get()});
  690. }
  691. }
  692. void Parser::SetOptionDefault(const Arg& option) {
  693. CARBON_CHECK(option.has_default) << "No default value available!";
  694. switch (option.kind) {
  695. case Arg::Kind::Flag:
  696. *option.flag_storage = option.default_flag;
  697. break;
  698. case Arg::Kind::Integer:
  699. *option.integer_storage = option.default_integer;
  700. break;
  701. case Arg::Kind::String:
  702. *option.string_storage = option.default_string;
  703. break;
  704. case Arg::Kind::OneOf:
  705. option.default_action(option);
  706. break;
  707. case Arg::Kind::MetaActionOnly:
  708. CARBON_FATAL() << "Can't set a default value for a meta action!";
  709. case Arg::Kind::Invalid:
  710. CARBON_FATAL() << "Option configured without any action or kind!";
  711. }
  712. }
  713. auto Parser::ParseNegatedFlag(const Arg& flag,
  714. std::optional<llvm::StringRef> value) -> bool {
  715. if (flag.kind != Arg::Kind::Flag) {
  716. errors_ << "ERROR: Cannot use a negated flag name by prefixing it with "
  717. "'no-' when it isn't a boolean flag argument.\n";
  718. return false;
  719. }
  720. if (value) {
  721. errors_ << "ERROR: Cannot specify a value when using a flag name prefixed "
  722. "with 'no-' -- that prefix implies a value of 'false'.\n";
  723. return false;
  724. }
  725. *flag.flag_storage = false;
  726. return true;
  727. }
  728. auto Parser::ParseFlag(const Arg& flag, std::optional<llvm::StringRef> value)
  729. -> bool {
  730. CARBON_CHECK(flag.kind == Arg::Kind::Flag) << "Incorrect kind: " << flag.kind;
  731. if (!value || *value == "true") {
  732. *flag.flag_storage = true;
  733. } else if (*value == "false") {
  734. *flag.flag_storage = false;
  735. } else {
  736. errors_ << "ERROR: Invalid value specified for the boolean flag '--"
  737. << flag.info.name << "': " << *value << "\n";
  738. return false;
  739. }
  740. return true;
  741. }
  742. auto Parser::ParseIntegerArgValue(const Arg& arg, llvm::StringRef value)
  743. -> bool {
  744. CARBON_CHECK(arg.kind == Arg::Kind::Integer)
  745. << "Incorrect kind: " << arg.kind;
  746. int integer_value;
  747. // Note that this method returns *true* on error!
  748. if (value.getAsInteger(/*Radix=*/0, integer_value)) {
  749. errors_ << "ERROR: Cannot parse value for option '--" << arg.info.name
  750. << "' as an integer: " << value << "\n";
  751. return false;
  752. }
  753. if (!arg.is_append) {
  754. *arg.integer_storage = integer_value;
  755. } else {
  756. arg.integer_sequence->push_back(integer_value);
  757. }
  758. return true;
  759. }
  760. auto Parser::ParseStringArgValue(const Arg& arg, llvm::StringRef value)
  761. -> bool {
  762. CARBON_CHECK(arg.kind == Arg::Kind::String) << "Incorrect kind: " << arg.kind;
  763. if (!arg.is_append) {
  764. *arg.string_storage = value;
  765. } else {
  766. arg.string_sequence->push_back(value);
  767. }
  768. return true;
  769. }
  770. auto Parser::ParseOneOfArgValue(const Arg& arg, llvm::StringRef value) -> bool {
  771. CARBON_CHECK(arg.kind == Arg::Kind::OneOf) << "Incorrect kind: " << arg.kind;
  772. if (!arg.value_action(arg, value)) {
  773. errors_ << "ERROR: Option '--" << arg.info.name << "=";
  774. llvm::printEscapedString(value, errors_);
  775. errors_ << "' has an invalid value '";
  776. llvm::printEscapedString(value, errors_);
  777. errors_ << "'; valid values are: ";
  778. for (auto value_string : arg.value_strings.drop_back()) {
  779. errors_ << "'" << value_string << "', ";
  780. }
  781. if (arg.value_strings.size() > 1) {
  782. errors_ << "or ";
  783. }
  784. errors_ << "'" << arg.value_strings.back() << "'\n";
  785. return false;
  786. }
  787. return true;
  788. }
  789. auto Parser::ParseArg(const Arg& arg, bool short_spelling,
  790. std::optional<llvm::StringRef> value, bool negated_name)
  791. -> bool {
  792. // If this argument has a meta action, replace the current meta action with
  793. // it.
  794. if (arg.meta_action) {
  795. arg_meta_action_ = arg.meta_action;
  796. }
  797. // Boolean flags have special parsing logic.
  798. if (negated_name) {
  799. return ParseNegatedFlag(arg, value);
  800. }
  801. if (arg.kind == Arg::Kind::Flag) {
  802. return ParseFlag(arg, value);
  803. }
  804. auto name =
  805. llvm::formatv(short_spelling ? "'-{0}' (short for '--{1}')" : "'--{1}'",
  806. arg.info.short_name, arg.info.name);
  807. if (!value) {
  808. // We can't have a positional argument without a value, so we know this is
  809. // an option and handle it as such.
  810. if (arg.kind == Arg::Kind::MetaActionOnly) {
  811. // Nothing further to do here, this is only a meta-action.
  812. return true;
  813. }
  814. if (!arg.has_default) {
  815. errors_ << "ERROR: Option " << name
  816. << " requires a value to be provided and none was.\n";
  817. return false;
  818. }
  819. SetOptionDefault(arg);
  820. return true;
  821. }
  822. // There is a value to parse as part of the argument.
  823. switch (arg.kind) {
  824. case Arg::Kind::Integer:
  825. return ParseIntegerArgValue(arg, *value);
  826. case Arg::Kind::String:
  827. return ParseStringArgValue(arg, *value);
  828. case Arg::Kind::OneOf:
  829. return ParseOneOfArgValue(arg, *value);
  830. case Arg::Kind::MetaActionOnly:
  831. errors_ << "ERROR: Option " << name
  832. << " cannot be used with a value, and '" << *value
  833. << "' was provided.\n";
  834. // TODO: improve message
  835. return false;
  836. case Arg::Kind::Flag:
  837. case Arg::Kind::Invalid:
  838. CARBON_FATAL() << "Invalid kind!";
  839. }
  840. }
  841. auto Parser::SplitValue(llvm::StringRef& unparsed_arg)
  842. -> std::optional<llvm::StringRef> {
  843. // Split out a value if present.
  844. std::optional<llvm::StringRef> value;
  845. auto index = unparsed_arg.find('=');
  846. if (index != llvm::StringRef::npos) {
  847. value = unparsed_arg.substr(index + 1);
  848. unparsed_arg = unparsed_arg.substr(0, index);
  849. }
  850. return value;
  851. }
  852. auto Parser::ParseLongOption(llvm::StringRef unparsed_arg) -> bool {
  853. CARBON_CHECK(unparsed_arg.starts_with("--") && unparsed_arg.size() > 2)
  854. << "Must only be called on a potential long option.";
  855. // Walk past the double dash.
  856. unparsed_arg = unparsed_arg.drop_front(2);
  857. bool negated_name = unparsed_arg.consume_front("no-");
  858. std::optional<llvm::StringRef> value = SplitValue(unparsed_arg);
  859. auto option_it = option_map_.find(unparsed_arg);
  860. if (option_it == option_map_.end()) {
  861. errors_ << "ERROR: Unknown option '--" << (negated_name ? "no-" : "")
  862. << unparsed_arg << "'\n";
  863. // TODO: improve error
  864. return false;
  865. }
  866. // Mark this option as parsed.
  867. option_it->second.setInt(true);
  868. // Parse this specific option and any value.
  869. const Arg& option = *option_it->second.getPointer();
  870. return ParseArg(option, /*short_spelling=*/false, value, negated_name);
  871. }
  872. auto Parser::ParseShortOptionSeq(llvm::StringRef unparsed_arg) -> bool {
  873. CARBON_CHECK(unparsed_arg.starts_with("-") && unparsed_arg.size() > 1)
  874. << "Must only be called on a potential short option sequence.";
  875. unparsed_arg = unparsed_arg.drop_front();
  876. std::optional<llvm::StringRef> value = SplitValue(unparsed_arg);
  877. if (value && unparsed_arg.size() != 1) {
  878. errors_ << "ERROR: Cannot provide a value to the group of multiple short "
  879. "options '-"
  880. << unparsed_arg
  881. << "=...'; values must be provided to a single option, using "
  882. "either the short or long spelling.\n";
  883. return false;
  884. }
  885. for (unsigned char c : unparsed_arg) {
  886. auto* arg_entry = short_option_table_[c];
  887. if (!arg_entry) {
  888. errors_ << "ERROR: Unknown short option '" << c << "'\n";
  889. return false;
  890. }
  891. // Mark this argument as parsed.
  892. arg_entry->setInt(true);
  893. // Parse the argument, including the value if this is the last.
  894. const Arg& arg = *arg_entry->getPointer();
  895. if (!ParseArg(arg, /*short_spelling=*/true, value)) {
  896. return false;
  897. }
  898. }
  899. return true;
  900. }
  901. auto Parser::FinalizeParsedOptions() -> bool {
  902. llvm::SmallVector<const Arg*> missing_options;
  903. for (const auto& option_entry : option_map_) {
  904. const Arg* option = option_entry.second.getPointer();
  905. if (!option_entry.second.getInt()) {
  906. // If the argument has a default value and isn't a meta-action, we need to
  907. // act on that when it isn't passed.
  908. if (option->has_default && !option->meta_action) {
  909. SetOptionDefault(*option);
  910. }
  911. // Remember any missing required arguments, we'll diagnose those.
  912. if (option->is_required) {
  913. missing_options.push_back(option);
  914. }
  915. }
  916. }
  917. if (missing_options.empty()) {
  918. return true;
  919. }
  920. // Sort the missing arguments by name to provide a stable and deterministic
  921. // error message. We know there can't be duplicate names because these came
  922. // from a may keyed on the name, so this provides a total ordering.
  923. std::sort(missing_options.begin(), missing_options.end(),
  924. [](const Arg* lhs, const Arg* rhs) {
  925. return lhs->info.name < rhs->info.name;
  926. });
  927. for (const Arg* option : missing_options) {
  928. errors_ << "ERROR: Required option '--" << option->info.name
  929. << "' not provided.\n";
  930. }
  931. return false;
  932. }
  933. auto Parser::ParsePositionalArg(llvm::StringRef unparsed_arg) -> bool {
  934. if (static_cast<size_t>(positional_arg_index_) >=
  935. command_->positional_args.size()) {
  936. errors_ << "ERROR: Completed parsing all "
  937. << command_->positional_args.size()
  938. << " configured positional arguments, and found an additional "
  939. "positional argument: '"
  940. << unparsed_arg << "'\n";
  941. return false;
  942. }
  943. const Arg& arg = *command_->positional_args[positional_arg_index_];
  944. // Mark that we'll keep appending here until a `--` marker. When already
  945. // appending this is redundant but harmless.
  946. appending_to_positional_arg_ = arg.is_append;
  947. if (!appending_to_positional_arg_) {
  948. // If we're not continuing to append to a current positional arg,
  949. // increment the positional arg index to find the next argument we
  950. // should use here.
  951. ++positional_arg_index_;
  952. }
  953. return ParseArg(arg, /*short_spelling=*/false, unparsed_arg);
  954. }
  955. auto Parser::ParseSubcommand(llvm::StringRef unparsed_arg) -> bool {
  956. auto subcommand_it = subcommand_map_.find(unparsed_arg);
  957. if (subcommand_it == subcommand_map_.end()) {
  958. errors_ << "ERROR: Invalid subcommand '" << unparsed_arg
  959. << "'. Available subcommands: ";
  960. error_meta_printer_.PrintSubcommands(*command_);
  961. errors_ << "\n";
  962. return false;
  963. }
  964. // Before we recurse into the subcommand, verify that all the required
  965. // arguments for this command were in fact parsed.
  966. if (!FinalizeParsedOptions()) {
  967. return false;
  968. }
  969. // Recurse into the subcommand, tracking the active command.
  970. command_ = subcommand_it->second;
  971. PopulateMaps(*command_);
  972. return true;
  973. }
  974. auto Parser::FinalizeParse() -> ParseResult {
  975. // If an argument action is provided, we run that and consider the parse
  976. // meta-successful rather than verifying required arguments were provided and
  977. // the (sub)command action.
  978. if (arg_meta_action_) {
  979. arg_meta_action_();
  980. return ParseResult::MetaSuccess;
  981. }
  982. // Verify we're not missing any arguments.
  983. if (!FinalizeParsedOptions()) {
  984. return ParseResult::Error;
  985. }
  986. // If we were appending to a positional argument, mark that as complete.
  987. llvm::ArrayRef positional_args = command_->positional_args;
  988. if (appending_to_positional_arg_) {
  989. CARBON_CHECK(static_cast<size_t>(positional_arg_index_) <
  990. positional_args.size())
  991. << "Appending to a positional argument with an invalid index: "
  992. << positional_arg_index_;
  993. ++positional_arg_index_;
  994. }
  995. // See if any positional args are required and unparsed.
  996. auto unparsed_positional_args = positional_args.slice(positional_arg_index_);
  997. if (!unparsed_positional_args.empty()) {
  998. // There are un-parsed positional arguments, make sure they aren't required.
  999. const Arg& missing_arg = *unparsed_positional_args.front();
  1000. if (missing_arg.is_required) {
  1001. errors_ << "ERROR: Not all required positional arguments were provided. "
  1002. "First missing and required positional argument: '"
  1003. << missing_arg.info.name << "'\n";
  1004. return ParseResult::Error;
  1005. }
  1006. for (const auto& arg_ptr : unparsed_positional_args) {
  1007. CARBON_CHECK(!arg_ptr->is_required)
  1008. << "Cannot have required positional parameters after an optional "
  1009. "one.";
  1010. }
  1011. }
  1012. switch (command_->kind) {
  1013. case Command::Kind::Invalid:
  1014. CARBON_FATAL() << "Should never have a parser with an invalid command!";
  1015. case Command::Kind::RequiresSubcommand:
  1016. errors_ << "ERROR: No subcommand specified. Available subcommands: ";
  1017. error_meta_printer_.PrintSubcommands(*command_);
  1018. errors_ << "\n";
  1019. return ParseResult::Error;
  1020. case Command::Kind::Action:
  1021. // All arguments have been successfully parsed, run any action for the
  1022. // most specific selected command. Only the leaf command's action is run.
  1023. command_->action();
  1024. return ParseResult::Success;
  1025. case Command::Kind::MetaAction:
  1026. command_->action();
  1027. return ParseResult::MetaSuccess;
  1028. }
  1029. }
  1030. auto Parser::ParsePositionalSuffix(
  1031. llvm::ArrayRef<llvm::StringRef> unparsed_args) -> bool {
  1032. CARBON_CHECK(!command_->positional_args.empty())
  1033. << "Cannot do positional suffix parsing without positional arguments!";
  1034. CARBON_CHECK(!unparsed_args.empty() && unparsed_args.front() == "--")
  1035. << "Must be called with a suffix of arguments starting with a `--` that "
  1036. "switches to positional suffix parsing.";
  1037. // Once we're in the positional suffix, we can track empty positional
  1038. // arguments.
  1039. bool empty_positional = false;
  1040. while (!unparsed_args.empty()) {
  1041. llvm::StringRef unparsed_arg = unparsed_args.front();
  1042. unparsed_args = unparsed_args.drop_front();
  1043. if (unparsed_arg != "--") {
  1044. if (!ParsePositionalArg(unparsed_arg)) {
  1045. return false;
  1046. }
  1047. empty_positional = false;
  1048. continue;
  1049. }
  1050. if (appending_to_positional_arg_ || empty_positional) {
  1051. ++positional_arg_index_;
  1052. if (static_cast<size_t>(positional_arg_index_) >=
  1053. command_->positional_args.size()) {
  1054. errors_
  1055. << "ERROR: Completed parsing all "
  1056. << command_->positional_args.size()
  1057. << " configured positional arguments, but found a subsequent `--` "
  1058. "and have no further positional arguments to parse beyond it.\n";
  1059. return false;
  1060. }
  1061. }
  1062. appending_to_positional_arg_ = false;
  1063. empty_positional = true;
  1064. }
  1065. return true;
  1066. }
  1067. Parser::Parser(llvm::raw_ostream& out, llvm::raw_ostream& errors,
  1068. const CommandInfo& command_info,
  1069. llvm::function_ref<void(CommandBuilder&)> build)
  1070. : meta_printer_(out),
  1071. errors_(errors),
  1072. error_meta_printer_(errors),
  1073. root_command_(command_info) {
  1074. // Run the command building lambda on a builder for the root command.
  1075. CommandBuilder builder(root_command_, meta_printer_);
  1076. build(builder);
  1077. builder.Finalize();
  1078. command_ = &root_command_;
  1079. }
  1080. auto Parser::Parse(llvm::ArrayRef<llvm::StringRef> unparsed_args)
  1081. -> ParseResult {
  1082. PopulateMaps(*command_);
  1083. while (!unparsed_args.empty()) {
  1084. llvm::StringRef unparsed_arg = unparsed_args.front();
  1085. // Peak at the front for an exact `--` argument that switches to a
  1086. // positional suffix parsing without dropping this argument.
  1087. if (unparsed_arg == "--") {
  1088. if (command_->positional_args.empty()) {
  1089. errors_ << "ERROR: Cannot meaningfully end option and subcommand "
  1090. "arguments with a `--` argument when there are no "
  1091. "positional arguments to parse.\n";
  1092. return ParseResult::Error;
  1093. }
  1094. if (static_cast<size_t>(positional_arg_index_) >=
  1095. command_->positional_args.size()) {
  1096. errors_ << "ERROR: Switched to purely positional arguments with a `--` "
  1097. "argument despite already having parsed all positional "
  1098. "arguments for this command.\n";
  1099. return ParseResult::Error;
  1100. }
  1101. if (!ParsePositionalSuffix(unparsed_args)) {
  1102. return ParseResult::Error;
  1103. }
  1104. // No more unparsed arguments to handle.
  1105. break;
  1106. }
  1107. // Now that we're not switching parse modes, drop the current unparsed
  1108. // argument and parse it.
  1109. unparsed_args = unparsed_args.drop_front();
  1110. if (unparsed_arg.starts_with("--")) {
  1111. // Note that the exact argument "--" has been handled above already.
  1112. if (!ParseLongOption(unparsed_arg)) {
  1113. return ParseResult::Error;
  1114. }
  1115. continue;
  1116. }
  1117. if (unparsed_arg.starts_with("-") && unparsed_arg.size() > 1) {
  1118. if (!ParseShortOptionSeq(unparsed_arg)) {
  1119. return ParseResult::Error;
  1120. }
  1121. continue;
  1122. }
  1123. CARBON_CHECK(command_->positional_args.empty() ||
  1124. command_->subcommands.empty())
  1125. << "Cannot have both positional arguments and subcommands!";
  1126. if (command_->positional_args.empty() && command_->subcommands.empty()) {
  1127. errors_ << "ERROR: Found unexpected positional argument or subcommand: '"
  1128. << unparsed_arg << "'\n";
  1129. return ParseResult::Error;
  1130. }
  1131. if (!command_->positional_args.empty()) {
  1132. if (!ParsePositionalArg(unparsed_arg)) {
  1133. return ParseResult::Error;
  1134. }
  1135. continue;
  1136. }
  1137. if (!ParseSubcommand(unparsed_arg)) {
  1138. return ParseResult::Error;
  1139. }
  1140. }
  1141. return FinalizeParse();
  1142. }
  1143. void ArgBuilder::Required(bool is_required) { arg_.is_required = is_required; }
  1144. void ArgBuilder::HelpHidden(bool is_help_hidden) {
  1145. arg_.is_help_hidden = is_help_hidden;
  1146. }
  1147. ArgBuilder::ArgBuilder(Arg& arg) : arg_(arg) {}
  1148. void FlagBuilder::Default(bool flag_value) {
  1149. arg_.has_default = true;
  1150. arg_.default_flag = flag_value;
  1151. }
  1152. void FlagBuilder::Set(bool* flag) { arg_.flag_storage = flag; }
  1153. void IntegerArgBuilder::Default(int integer_value) {
  1154. arg_.has_default = true;
  1155. arg_.default_integer = integer_value;
  1156. }
  1157. void IntegerArgBuilder::Set(int* integer) {
  1158. arg_.is_append = false;
  1159. arg_.integer_storage = integer;
  1160. }
  1161. void IntegerArgBuilder::Append(llvm::SmallVectorImpl<int>* sequence) {
  1162. arg_.is_append = true;
  1163. arg_.integer_sequence = sequence;
  1164. }
  1165. void StringArgBuilder::Default(llvm::StringRef string_value) {
  1166. arg_.has_default = true;
  1167. arg_.default_string = string_value;
  1168. }
  1169. void StringArgBuilder::Set(llvm::StringRef* string) {
  1170. arg_.is_append = false;
  1171. arg_.string_storage = string;
  1172. }
  1173. void StringArgBuilder::Append(
  1174. llvm::SmallVectorImpl<llvm::StringRef>* sequence) {
  1175. arg_.is_append = true;
  1176. arg_.string_sequence = sequence;
  1177. }
  1178. static auto IsValidName(llvm::StringRef name) -> bool {
  1179. if (name.size() <= 1) {
  1180. return false;
  1181. }
  1182. if (!llvm::isAlnum(name.front())) {
  1183. return false;
  1184. }
  1185. if (!llvm::isAlnum(name.back())) {
  1186. return false;
  1187. }
  1188. for (char c : name.drop_front().drop_back()) {
  1189. if (c != '-' && c != '_' && !llvm::isAlnum(c)) {
  1190. return false;
  1191. }
  1192. }
  1193. // We disallow names starting with "no-" as we will parse those for boolean
  1194. // flags.
  1195. return !name.starts_with("no-");
  1196. }
  1197. void CommandBuilder::AddFlag(const ArgInfo& info,
  1198. llvm::function_ref<void(FlagBuilder&)> build) {
  1199. FlagBuilder builder(AddArgImpl(info, Arg::Kind::Flag));
  1200. // All boolean flags have an implicit default of `false`, although it can be
  1201. // overridden in the build callback.
  1202. builder.Default(false);
  1203. build(builder);
  1204. }
  1205. void CommandBuilder::AddIntegerOption(
  1206. const ArgInfo& info, llvm::function_ref<void(IntegerArgBuilder&)> build) {
  1207. IntegerArgBuilder builder(AddArgImpl(info, Arg::Kind::Integer));
  1208. build(builder);
  1209. }
  1210. void CommandBuilder::AddStringOption(
  1211. const ArgInfo& info, llvm::function_ref<void(StringArgBuilder&)> build) {
  1212. StringArgBuilder builder(AddArgImpl(info, Arg::Kind::String));
  1213. build(builder);
  1214. }
  1215. void CommandBuilder::AddOneOfOption(
  1216. const ArgInfo& info, llvm::function_ref<void(OneOfArgBuilder&)> build) {
  1217. OneOfArgBuilder builder(AddArgImpl(info, Arg::Kind::OneOf));
  1218. build(builder);
  1219. }
  1220. void CommandBuilder::AddMetaActionOption(
  1221. const ArgInfo& info, llvm::function_ref<void(ArgBuilder&)> build) {
  1222. ArgBuilder builder(AddArgImpl(info, Arg::Kind::MetaActionOnly));
  1223. build(builder);
  1224. }
  1225. void CommandBuilder::AddIntegerPositionalArg(
  1226. const ArgInfo& info, llvm::function_ref<void(IntegerArgBuilder&)> build) {
  1227. AddPositionalArgImpl(info, Arg::Kind::Integer, [build](Arg& arg) {
  1228. IntegerArgBuilder builder(arg);
  1229. build(builder);
  1230. });
  1231. }
  1232. void CommandBuilder::AddStringPositionalArg(
  1233. const ArgInfo& info, llvm::function_ref<void(StringArgBuilder&)> build) {
  1234. AddPositionalArgImpl(info, Arg::Kind::String, [build](Arg& arg) {
  1235. StringArgBuilder builder(arg);
  1236. build(builder);
  1237. });
  1238. }
  1239. void CommandBuilder::AddOneOfPositionalArg(
  1240. const ArgInfo& info, llvm::function_ref<void(OneOfArgBuilder&)> build) {
  1241. AddPositionalArgImpl(info, Arg::Kind::OneOf, [build](Arg& arg) {
  1242. OneOfArgBuilder builder(arg);
  1243. build(builder);
  1244. });
  1245. }
  1246. void CommandBuilder::AddSubcommand(
  1247. const CommandInfo& info, llvm::function_ref<void(CommandBuilder&)> build) {
  1248. CARBON_CHECK(IsValidName(info.name))
  1249. << "Invalid subcommand name: " << info.name;
  1250. CARBON_CHECK(subcommand_names_.insert(info.name).second)
  1251. << "Added a duplicate subcommand: " << info.name;
  1252. CARBON_CHECK(command_.positional_args.empty())
  1253. << "Cannot add subcommands to a command with a positional argument.";
  1254. command_.subcommands.emplace_back(new Command(info, &command_));
  1255. CommandBuilder builder(*command_.subcommands.back(), meta_printer_);
  1256. build(builder);
  1257. builder.Finalize();
  1258. }
  1259. void CommandBuilder::HelpHidden(bool is_help_hidden) {
  1260. command_.is_help_hidden = is_help_hidden;
  1261. }
  1262. void CommandBuilder::RequiresSubcommand() {
  1263. CARBON_CHECK(!command_.subcommands.empty())
  1264. << "Cannot require subcommands unless there are subcommands.";
  1265. CARBON_CHECK(command_.positional_args.empty())
  1266. << "Cannot require subcommands and have a positional argument.";
  1267. CARBON_CHECK(command_.kind == Kind::Invalid)
  1268. << "Already established the kind of this command as: " << command_.kind;
  1269. command_.kind = Kind::RequiresSubcommand;
  1270. }
  1271. void CommandBuilder::Do(ActionT action) {
  1272. CARBON_CHECK(command_.kind == Kind::Invalid)
  1273. << "Already established the kind of this command as: " << command_.kind;
  1274. command_.kind = Kind::Action;
  1275. command_.action = std::move(action);
  1276. }
  1277. void CommandBuilder::Meta(ActionT action) {
  1278. CARBON_CHECK(command_.kind == Kind::Invalid)
  1279. << "Already established the kind of this command as: " << command_.kind;
  1280. command_.kind = Kind::MetaAction;
  1281. command_.action = std::move(action);
  1282. }
  1283. CommandBuilder::CommandBuilder(Command& command, MetaPrinter& meta_printer)
  1284. : command_(command), meta_printer_(meta_printer) {}
  1285. auto CommandBuilder::AddArgImpl(const ArgInfo& info, Arg::Kind kind) -> Arg& {
  1286. CARBON_CHECK(IsValidName(info.name))
  1287. << "Invalid argument name: " << info.name;
  1288. CARBON_CHECK(arg_names_.insert(info.name).second)
  1289. << "Added a duplicate argument name: " << info.name;
  1290. command_.options.emplace_back(new Arg(info));
  1291. Arg& arg = *command_.options.back();
  1292. arg.kind = kind;
  1293. return arg;
  1294. }
  1295. void CommandBuilder::AddPositionalArgImpl(
  1296. const ArgInfo& info, Arg::Kind kind, llvm::function_ref<void(Arg&)> build) {
  1297. CARBON_CHECK(IsValidName(info.name))
  1298. << "Invalid argument name: " << info.name;
  1299. CARBON_CHECK(command_.subcommands.empty())
  1300. << "Cannot add a positional argument to a command with subcommands.";
  1301. command_.positional_args.emplace_back(new Arg(info));
  1302. Arg& arg = *command_.positional_args.back();
  1303. arg.kind = kind;
  1304. build(arg);
  1305. CARBON_CHECK(!arg.is_help_hidden)
  1306. << "Cannot have a help-hidden positional argument.";
  1307. if (arg.is_required && command_.positional_args.size() > 1) {
  1308. CARBON_CHECK((*std::prev(command_.positional_args.end(), 2))->is_required)
  1309. << "A required positional argument cannot be added after an optional "
  1310. "one.";
  1311. }
  1312. }
  1313. void CommandBuilder::Finalize() {
  1314. meta_printer_.RegisterWithCommand(command_, *this);
  1315. }
  1316. auto Parse(llvm::ArrayRef<llvm::StringRef> unparsed_args,
  1317. llvm::raw_ostream& out, llvm::raw_ostream& errors,
  1318. const CommandInfo& command_info,
  1319. llvm::function_ref<void(CommandBuilder&)> build) -> ParseResult {
  1320. // Build a parser, which includes building the command description provided by
  1321. // the user.
  1322. Parser parser(out, errors, command_info, build);
  1323. // Now parse the arguments provided using that parser.
  1324. return parser.Parse(unparsed_args);
  1325. }
  1326. } // namespace Carbon::CommandLine