command_line.cpp 50 KB

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