command_line.cpp 50 KB

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