command_line.cpp 51 KB

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