command_line.cpp 50 KB

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