command_line.cpp 51 KB

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