command_line.cpp 49 KB

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