command_line.cpp 51 KB

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