command_line.cpp 51 KB

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