llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT--> @llvm/pr-subscribers-tablegen Author: Fangrui Song (MaskRay) <details> <summary>Changes</summary> Follow-up to #<!-- -->246766: Generalize `OptionsStruct` so that a tool, not only a library, can get its options as a generated struct. opt::parseToolArgs parses argv with OptTable::parseArgs, keeping response files and typo suggestions, and fills the struct. OptionsStruct<""> gives a tool's struct internal linkage. `RepeatedField` appends each occurrence's whole value, for options such as -extra-arg whose values contain commas. The parts a struct needs without cl:: move from LibraryOptions.h to the new OptionsStruct.h, and LibraryOptTable becomes OptionsStructTable. Convert clang-diff. LLM-aided --- Patch is 31.86 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/246881.diff 13 Files Affected: - (modified) clang/tools/clang-diff/ClangDiff.cpp (+44-79) - (modified) clang/tools/clang-diff/Opts.td (+12-17) - (modified) llvm/docs/CommandLine.md (+6) - (modified) llvm/include/llvm/Option/LibraryOptions.h (+4-99) - (modified) llvm/include/llvm/Option/LibraryOptions.td (+9) - (added) llvm/include/llvm/Option/OptionsStruct.h (+166) - (modified) llvm/lib/Option/CMakeLists.txt (+1) - (modified) llvm/lib/Option/LibraryOptions.cpp (-2) - (added) llvm/lib/Option/OptionsStruct.cpp (+41) - (modified) llvm/unittests/Option/LibraryOptionsTest.cpp (+24) - (modified) llvm/unittests/Option/LibraryOpts.td (+1) - (modified) llvm/utils/TableGen/Basic/OptionParserEmitter.cpp (+11-5) - (modified) llvm/utils/gn/secondary/llvm/lib/Option/BUILD.gn (+1) ``````````diff diff --git a/clang/tools/clang-diff/ClangDiff.cpp b/clang/tools/clang-diff/ClangDiff.cpp index 1cee8f62cd9f5d..00701ee3c45ebf 100644 --- a/clang/tools/clang-diff/ClangDiff.cpp +++ b/clang/tools/clang-diff/ClangDiff.cpp @@ -11,59 +11,47 @@ // //===----------------------------------------------------------------------===// +#define OPTIONS_STRUCT_DECL +#include "Opts.inc" + #include "clang/Tooling/ASTDiff/ASTDiff.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Tooling.h" -#include "llvm/Option/ArgList.h" -#include "llvm/Option/OptTable.h" +#include "llvm/Option/OptionsStruct.h" + +#define OPTIONS_STRUCT_DEFS +#include "Opts.inc" using namespace llvm; using namespace clang; using namespace clang::tooling; -namespace { -using namespace llvm::opt; -enum ID { - OPT_INVALID = 0, -#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__), -#include "Opts.inc" -#undef OPTION -}; - -#define OPTTABLE_CODE -#include "Opts.inc" - -class ClangDiffOptTable : public OptTable { -public: - ClangDiffOptTable() : OptTable(optionTables()) {} -}; -} // namespace - -static std::string BuildPath; -static std::vector<std::string> ArgsAfter; -static std::vector<std::string> ArgsBefore; - -static void addExtraArgs(std::unique_ptr<CompilationDatabase> &Compilations) { +static void addExtraArgs(const ClangDiffOptions &Opts, + std::unique_ptr<CompilationDatabase> &Compilations) { if (!Compilations) return; auto AdjustingCompilations = std::make_unique<ArgumentsAdjustingCompilations>( std::move(Compilations)); - AdjustingCompilations->appendArgumentsAdjuster( - getInsertArgumentAdjuster(ArgsBefore, ArgumentInsertPosition::BEGIN)); - AdjustingCompilations->appendArgumentsAdjuster( - getInsertArgumentAdjuster(ArgsAfter, ArgumentInsertPosition::END)); + AdjustingCompilations->appendArgumentsAdjuster(getInsertArgumentAdjuster( + std::vector<std::string>(Opts.extra_arg_before.begin(), + Opts.extra_arg_before.end()), + ArgumentInsertPosition::BEGIN)); + AdjustingCompilations->appendArgumentsAdjuster(getInsertArgumentAdjuster( + std::vector<std::string>(Opts.extra_arg.begin(), Opts.extra_arg.end()), + ArgumentInsertPosition::END)); Compilations = std::move(AdjustingCompilations); } static std::unique_ptr<ASTUnit> -getAST(const std::unique_ptr<CompilationDatabase> &CommonCompilations, +getAST(const ClangDiffOptions &Opts, + const std::unique_ptr<CompilationDatabase> &CommonCompilations, const StringRef Filename) { std::string ErrorMessage; std::unique_ptr<CompilationDatabase> Compilations; if (!CommonCompilations) { Compilations = CompilationDatabase::autoDetectFromSource( - BuildPath.empty() ? Filename : BuildPath, ErrorMessage); + Opts.p.empty() ? Filename : Opts.p, ErrorMessage); if (!Compilations) { llvm::errs() << "Error while trying to load a compilation database, running " @@ -74,7 +62,7 @@ getAST(const std::unique_ptr<CompilationDatabase> &CommonCompilations, ".", std::vector<std::string>()); } } - addExtraArgs(Compilations); + addExtraArgs(Opts, Compilations); std::array<std::string, 1> Files = {{std::string(Filename)}}; ClangTool Tool(Compilations ? *Compilations : *CommonCompilations, Files); std::vector<std::unique_ptr<ASTUnit>> ASTs; @@ -420,54 +408,37 @@ int main(int argc, const char **argv) { if (!CommonCompilations && !ErrorMessage.empty()) llvm::errs() << ErrorMessage; BumpPtrAllocator Alloc; - StringSaver Saver(Alloc); - ClangDiffOptTable Tbl; - opt::InputArgList Args = Tbl.parseArgs( - argc, const_cast<char **>(argv), OPT_UNKNOWN, Saver, [](StringRef Msg) { - llvm::errs() << "Error: " << Msg << "\n"; - exit(1); - }); - if (Args.hasArg(OPT_help)) { - Tbl.printHelp(llvm::outs(), "clang-diff [options] <source> [<destination>]", - "Compare source files by AST nodes"); + ClangDiffOptions Opts; + SmallVector<StringRef, 2> Inputs; + if (Error E = opt::parseToolArgs(Opts, argc, argv, Alloc, Inputs)) { + llvm::errs() << "Error: " << toString(std::move(E)) << "\n"; + return 1; + } + if (Opts.help) { + ClangDiffOptions::optTable().printHelp( + llvm::outs(), "clang-diff [options] <source> [<destination>]", + "Compare source files by AST nodes"); return 0; } - std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT); if (Inputs.empty() || Inputs.size() > 2) { llvm::errs() << "Error: Expected one or two paths.\n"; return 1; } - std::string SourcePath = Inputs[0]; - std::string DestinationPath = Inputs.size() > 1 ? Inputs[1] : ""; - bool ASTDump = Args.hasArg(OPT_ast_dump); - bool ASTDumpJson = Args.hasArg(OPT_ast_dump_json); - bool PrintMatches = Args.hasArg(OPT_dump_matches); - bool HtmlDiff = Args.hasArg(OPT_html); - std::string StopAfter = Args.getLastArgValue(OPT_stop_diff_after).str(); - int MaxSize = -1; - if (const opt::Arg *A = Args.getLastArg(OPT_s)) { - if (StringRef(A->getValue()).getAsInteger(0, MaxSize)) { - llvm::errs() << "Error: Invalid argument '" << A->getValue() - << "' for -s\n"; - return 1; - } - } - BuildPath = Args.getLastArgValue(OPT_p).str(); - ArgsAfter = Args.getAllArgValues(OPT_extra_arg); - ArgsBefore = Args.getAllArgValues(OPT_extra_arg_before); + StringRef SourcePath = Inputs[0]; + StringRef DestinationPath = Inputs.size() > 1 ? Inputs[1] : ""; - addExtraArgs(CommonCompilations); + addExtraArgs(Opts, CommonCompilations); - if (ASTDump || ASTDumpJson) { + if (Opts.ast_dump || Opts.ast_dump_json) { if (!DestinationPath.empty()) { llvm::errs() << "Error: Please specify exactly one filename.\n"; return 1; } - std::unique_ptr<ASTUnit> AST = getAST(CommonCompilations, SourcePath); + std::unique_ptr<ASTUnit> AST = getAST(Opts, CommonCompilations, SourcePath); if (!AST) return 1; diff::SyntaxTree Tree(AST->getASTContext()); - if (ASTDump) { + if (Opts.ast_dump) { printTree(llvm::outs(), Tree); return 0; } @@ -484,27 +455,21 @@ int main(int argc, const char **argv) { return 1; } - std::unique_ptr<ASTUnit> Src = getAST(CommonCompilations, SourcePath); - std::unique_ptr<ASTUnit> Dst = getAST(CommonCompilations, DestinationPath); + std::unique_ptr<ASTUnit> Src = getAST(Opts, CommonCompilations, SourcePath); + std::unique_ptr<ASTUnit> Dst = + getAST(Opts, CommonCompilations, DestinationPath); if (!Src || !Dst) return 1; diff::ComparisonOptions Options; - if (MaxSize != -1) - Options.MaxSize = MaxSize; - if (!StopAfter.empty()) { - if (StopAfter == "topdown") - Options.StopAfterTopDown = true; - else if (StopAfter != "bottomup") { - llvm::errs() << "Error: Invalid argument for -stop-after\n"; - return 1; - } - } + if (Opts.s) + Options.MaxSize = *Opts.s; + Options.StopAfterTopDown = Opts.stop_after_topdown; diff::SyntaxTree SrcTree(Src->getASTContext()); diff::SyntaxTree DstTree(Dst->getASTContext()); diff::ASTDiff Diff(SrcTree, DstTree, Options); - if (HtmlDiff) { + if (Opts.html) { llvm::outs() << HtmlDiffHeader << "<pre>"; llvm::outs() << "<div id='L' class='code'>"; printHtmlForNode(llvm::outs(), Diff, SrcTree, true, SrcTree.getRootId(), 0); @@ -519,7 +484,7 @@ int main(int argc, const char **argv) { for (diff::NodeId Dst : DstTree) { diff::NodeId Src = Diff.getMapped(DstTree, Dst); - if (PrintMatches && Src.isValid()) { + if (Opts.dump_matches && Src.isValid()) { llvm::outs() << "Match "; printNode(llvm::outs(), SrcTree, Src); llvm::outs() << " to "; diff --git a/clang/tools/clang-diff/Opts.td b/clang/tools/clang-diff/Opts.td index c0a7d108889c49..b60e3ccd9b0027 100644 --- a/clang/tools/clang-diff/Opts.td +++ b/clang/tools/clang-diff/Opts.td @@ -1,19 +1,14 @@ -include "llvm/Option/OptParser.td" +include "llvm/Option/LibraryOptions.td" -class F<string name, string help> : Flag<["-", "--"], name>, HelpText<help>; +def ClangDiffOptions : OptionsStruct<"">; -multiclass Eq<string name, string help> { - def NAME : Separate<["-", "--"], name>, HelpText<help>; - def : Joined<["-", "--"], name #"=">, Alias<!cast<Separate>(NAME)>; -} - -def ast_dump : F<"ast-dump", "Print the internal representation of the AST.">; -def ast_dump_json : F<"ast-dump-json", "Print the internal representation of the AST as JSON.">; -def dump_matches : F<"dump-matches", "Print the matched nodes.">; -defm extra_arg : Eq<"extra-arg", "Additional argument to append to the compiler command line">, MetaVarName<"<arg>">; -defm extra_arg_before : Eq<"extra-arg-before", "Additional argument to prepend to the compiler command line">, MetaVarName<"<arg>">; -def help : F<"help", "Display available options">; -def html : F<"html", "Output a side-by-side diff in HTML.">; -defm p : Eq<"p", "Build path">, MetaVarName<"<build-path>">; -defm s : Eq<"s", "Maximum subtree size for the optimal bottom-up mapping">, MetaVarName<"<maxsize>">; -defm stop_diff_after : Eq<"stop-diff-after", "Stop after the given matching phase">, MetaVarName<"<topdown|bottomup>">; +defm : BoolField<"ast-dump", "false", "Print the internal representation of the AST">; +defm : BoolField<"ast-dump-json", "false", "Print the internal representation of the AST as JSON">; +defm : BoolField<"dump-matches", "false", "Print the matched nodes">; +defm : RepeatedField<"extra-arg", "StringRef", "Additional argument to append to the compiler command line">, MetaVarName<"<arg>">; +defm : RepeatedField<"extra-arg-before", "StringRef", "Additional argument to prepend to the compiler command line">, MetaVarName<"<arg>">; +defm : BoolField<"help", "false", "Display available options">; +defm : BoolField<"html", "false", "Output a side-by-side diff in HTML">; +defm : ValueField<"p", "StringRef", "", "Build path">, MetaVarName<"<build-path>">; +defm : OptionalValueField<"s", "int", "Maximum subtree size for the optimal bottom-up mapping">, MetaVarName<"<maxsize>">; +defm stop_after_topdown : EnumField<"stop-diff-after", "bool", "false", "topdown,bottomup", ["true", "false"], "Stop after the given matching phase">; diff --git a/llvm/docs/CommandLine.md b/llvm/docs/CommandLine.md index 795555aaecf97e..7ce1f5b3f4c7db 100644 --- a/llvm/docs/CommandLine.md +++ b/llvm/docs/CommandLine.md @@ -1582,6 +1582,7 @@ defm : ValueField<"foo-path", "StringRef", "\"-\"", "The input path">; ``` The struct is in namespace `llvm` unless the def names another, as in `OptionsStruct<"mlir">`. +A tool's `OptionsStruct<"">` is in an anonymous namespace. A member is named after its option, `enable_foo` for `-enable-foo`; a named `defm` such as `defm threshold` names it `threshold`. `OptionsStruct<prefix = "foo-">` drops that prefix from member names, so `-foo-path` sets `path`. @@ -1592,6 +1593,7 @@ A reader applies a `cl::list_init` default to an empty list, since a given optio An `OptionalBoolField` is a `BoolOrDefault` that stays `Default` unless the option is given, replacing `cl::boolOrDefault`; read it with `valueOr(X, Default)`. An `EnumField` maps each of its comma-separated values to an enumerator, replacing `cl::values`: `defm : EnumField<"foo-mode", "FooMode", "FooMode::Fast", "fast,safe", ["FooMode::Fast", "FooMode::Safe"], "The mode">;` accepts `-foo-mode=fast` and `-foo-mode=safe`. An `EnumListField` is a `ListField` whose values map to enumerators as in an `EnumField`. +A `RepeatedField` is an `ArrayRef` to which each occurrence appends its whole value, commas included, replacing a `cl::list` without `cl::CommaSeparated`. A `FlagOrEnumField` takes one more argument, the enumerator the bare option selects, replacing `cl::ValueOptional`: with `"FooMode::Fast"`, `-foo-mode` sets `FooMode::Fast`, and `-foo-mode safe` does not consume `safe`. A `DefaultOnOffField` is a `BoolOrDefault` set by `=Default`, `=Enable`, or `=Disable`. Both accept `--` for `-`. @@ -1606,3 +1608,7 @@ The library then lists `FooOptionsTableGen` under `DEPENDS` and `Option` under ` A library that otherwise needs only `llvm-min-tblgen` sets `LLVM_TABLEGEN_PROJECT` to `LLVM_HEADERS` before its `llvm_tablegen()` call, so that its sources need not wait for `llvm-tblgen`. Code reads `C.get<FooOptions>().enable_foo` from the context `C` that the tool parsed its command line into, usually through an `LLVMContext`. Keep the header in `lib/`, as private as the `static cl::opt` it replaces; another library that needs a value calls a function or takes a parameter. + +A tool can declare its own options the same way and, including `llvm/Option/OptionsStruct.h`, parse its command line without `cl::`. +`opt::parseToolArgs(Opts, argc, argv, Alloc, Inputs)` expands response files, sets the members of `Opts`, whose strings refer to `argv` or `Alloc`, and collects the positional arguments, and every argument after `--`, in `Inputs`. +`T::optTable().printHelp` prints the tool's help. diff --git a/llvm/include/llvm/Option/LibraryOptions.h b/llvm/include/llvm/Option/LibraryOptions.h index e30fc5e105089a..bbda8dea15703c 100644 --- a/llvm/include/llvm/Option/LibraryOptions.h +++ b/llvm/include/llvm/Option/LibraryOptions.h @@ -6,119 +6,24 @@ // //===----------------------------------------------------------------------===// // -// Support for the options struct that -gen-opt-parser-defs generates from an -// OptionsStruct def. See "Declaring a Library's Options in TableGen" in -// llvm/docs/CommandLine.md. +// Connects the options struct that -gen-opt-parser-defs generates from an +// OptionsStruct def to cl::parseCommandLineOptions. See "Declaring a Library's +// Options in TableGen" in llvm/docs/CommandLine.md. // //===----------------------------------------------------------------------===// #ifndef LLVM_OPTION_LIBRARYOPTIONS_H #define LLVM_OPTION_LIBRARYOPTIONS_H -#include "llvm/ADT/ArrayRef.h" -#include "llvm/ADT/BoolOrDefault.h" -#include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/StringExtras.h" -#include "llvm/Option/Arg.h" -#include "llvm/Option/OptTable.h" -#include "llvm/Option/Option.h" +#include "llvm/Option/OptionsStruct.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Compiler.h" -#include <optional> -#include <type_traits> #include <utility> namespace llvm { namespace opt { -// Each accepts the spellings cl::opt accepts for the type. -inline bool parseArgValue(StringRef S, bool &V) { - if (S == "true" || S == "1") - V = true; - else if (S == "false" || S == "0") - V = false; - else - return false; - return true; -} - -inline bool parseArgValue(StringRef S, BoolOrDefault &V) { - bool B; - if (!parseArgValue(S, B)) - return false; - V = B ? BoolOrDefault::True : BoolOrDefault::False; - return true; -} - -inline bool parseArgValue(StringRef S, StringRef &V) { - V = S; - return true; -} - -template <typename T> -std::enable_if_t<std::is_arithmetic_v<T> && !std::is_same_v<T, bool>, bool> -parseArgValue(StringRef S, T &V) { - if constexpr (std::is_floating_point_v<T>) - return to_float(S, V); - else - return to_integer(S, V); -} - -// A std::optional member is set only when its option is given. -template <typename T> bool parseArgValue(StringRef S, std::optional<T> &V) { - T X{}; - if (!parseArgValue(S, X)) - return false; - V = X; - return true; -} - -// The generated apply() passes Alloc, which only a list member uses. -template <typename T> -bool parseArgValue(StringRef S, T &V, BumpPtrAllocator &) { - return parseArgValue(S, V); -} - -// An enum member is set by Parse, the generated value-to-enumerator mapping. -template <typename T, typename F> -bool parseArgValue(StringRef S, T &V, BumpPtrAllocator &, F Parse) { - return Parse(S, V); -} - -// A list member appends the comma-separated values of each occurrence. Its -// storage comes from Alloc, keeping the options struct trivially destructible. -template <typename T, typename F> -bool parseArgValue(StringRef S, ArrayRef<T> &List, BumpPtrAllocator &Alloc, - F ParseElem) { - static_assert(std::is_trivially_copyable_v<T>); - SmallVector<T, 4> Elems(List.begin(), List.end()); - for (StringRef Item : split(S, ',')) { - T Elem{}; - if (!ParseElem(Item, Elem)) - return false; - Elems.push_back(Elem); - } - T *Storage = Alloc.Allocate<T>(Elems.size()); - llvm::copy(Elems, Storage); - List = ArrayRef(Storage, Elems.size()); - return true; -} - -template <typename T> -bool parseArgValue(StringRef S, ArrayRef<T> &List, BumpPtrAllocator &Alloc) { - return parseArgValue(S, List, Alloc, [](StringRef Item, T &Elem) { - return parseArgValue(Item, Elem); - }); -} - -/// An OptTable with a public constructor, shared by every options struct. -class LLVM_ABI LibraryOptTable : public OptTable { -public: - explicit LibraryOptTable(const Tables &T) : OptTable(T) {} - ~LibraryOptTable() override; -}; - /// Connects options struct T to cl::parseCommandLineOptions and /// cl::LibraryOptionsContext. class LLVM_ABI LibraryOptionsParser final : public cl::LibraryOptions { diff --git a/llvm/include/llvm/Option/LibraryOptions.td b/llvm/include/llvm/Option/LibraryOptions.td index d54145debc299e..6630f8dc77d4c0 100644 --- a/llvm/include/llvm/Option/LibraryOptions.td +++ b/llvm/include/llvm/Option/LibraryOptions.td @@ -113,6 +113,15 @@ multiclass ListField<string name, string type, string help> { Field<NAME, "llvm::ArrayRef<"#type#">", "">, HelpText<help>; } +// An llvm::ArrayRef<<type>> member. Each -<name>=<value> or -<name> <value> +// appends its whole value, commas included. +multiclass RepeatedField<string name, string type, string help> { + def NAME : SeparateOrEq<["-", "--"], name>, + Field<NAME, "llvm::ArrayRef<"#type#">", "">, HelpText<help> { + bit Repeated = 1; + } +} + // A ListField of the enumeration <type>, with <values> mapping to <enumerators> // as in EnumField. multiclass EnumListField<string name, string type, string values, diff --git a/llvm/include/llvm/Option/OptionsStruct.h b/llvm/include/llvm/Option/OptionsStruct.h new file mode 100644 index 00000000000000..39ce8bdcd23189 --- /dev/null +++ b/llvm/include/llvm/Option/OptionsStruct.h @@ -0,0 +1,166 @@ +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Support for the options struct that -gen-opt-parser-defs generates from an +// OptionsStruct def, and for a tool that parses its command line into one. +// See "Declaring a Library's Options in TableGen" in llvm/docs/CommandLine.md. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_OPTION_OPTIONSSTRUCT_H +#define LLVM_OPTION_OPTIONSSTRUCT_H + +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/BoolOrDefault.h" +#include "llvm/ADT/STLFunctionalExtras.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringExtras.h" +#include "llvm/Option/Arg.h" +#include "llvm/Option/OptTable.h" +#include "llvm/Option/Option.h" +#include "llvm/Support/Allocator.h" +#include "llvm/Support/Compiler.h" +#include "llvm/Support/Error.h" +#include "llvm/Support/StringSaver.h" +#include <optional> +#include <type_traits> + +namespace llvm { +namespace opt { + +// Each accepts the spellings cl::opt accepts for the type. +inline bool parseArgValue(StringRef S, bool &V) { + if (S == "true" || S == "1") + V = true; + else if (S == "false" || S == "0") + V = false; + else + return false; + return true; +} + +inline bool parseArgValue(StringRef S, BoolOrDefault &V) { + bool B; + if (!parseArgValue(S, B)) + return false; + V = B ? BoolOrDefault::True : BoolOrDefault::False; + return true; +} + +inline bool parseArgValue(StringRef S, StringRef &V) { + V = S; + return true; +} + +template <typename T> +std::enable_if_t<std::is_arithmetic_v<T> && !std::is_same_v<T, bool>, bool> +parseArgValue(StringRef S, T &V) { + if constexpr (std::is_floating_point_v<T>) + return to_float(S, V); + else + retu... [truncated] `````````` </details> https://github.com/llvm/llvm-project/pull/246881 _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
