diff --git a/common/command_line.cpp b/common/command_line.cpp index ce8f07e1b7af..443194c92e30 100644 --- a/common/command_line.cpp +++ b/common/command_line.cpp @@ -108,13 +108,15 @@ class MetaPrinter { // // This adds meta subcommands or options to print both help and version // information for the command. - void RegisterWithCommand(const Command& command, CommandBuilder& builder); + auto RegisterWithCommand(const Command& command, CommandBuilder& builder) + -> void; - void PrintHelp(const Command& command) const; - void PrintHelpForSubcommandName(const Command& command, - llvm::StringRef subcommand_name) const; - void PrintVersion(const Command& command) const; - void PrintSubcommands(const Command& command) const; + auto PrintHelp(const Command& command) const -> void; + auto PrintHelpForSubcommandName(const Command& command, + llvm::StringRef subcommand_name) const + -> void; + auto PrintVersion(const Command& command) const -> void; + auto PrintSubcommands(const Command& command) const -> void; private: // The indent is calibrated to allow a short and long option after a two @@ -193,33 +195,37 @@ Prints the version of this command. }; // A general helper for rendering a text block. - void PrintTextBlock(llvm::StringRef indent, llvm::StringRef text) const; + auto PrintTextBlock(llvm::StringRef indent, llvm::StringRef text) const + -> void; // Helpers for version and build information printing. - void PrintRawVersion(const Command& command, llvm::StringRef indent) const; - void PrintRawBuildInfo(const Command& command, llvm::StringRef indent) const; + auto PrintRawVersion(const Command& command, llvm::StringRef indent) const + -> void; + auto PrintRawBuildInfo(const Command& command, llvm::StringRef indent) const + -> void; // Helpers for printing components of help and usage output for arguments, // including options and positional arguments. - void PrintArgValueUsage(const Arg& arg) const; - void PrintOptionUsage(const Arg& option) const; - void PrintOptionShortName(const Arg& arg) const; - void PrintArgShortValues(const Arg& arg) const; - void PrintArgLongValues(const Arg& arg, llvm::StringRef indent) const; - void PrintArgHelp(const Arg& arg, llvm::StringRef indent) const; + auto PrintArgValueUsage(const Arg& arg) const -> void; + auto PrintOptionUsage(const Arg& option) const -> void; + auto PrintOptionShortName(const Arg& arg) const -> void; + auto PrintArgShortValues(const Arg& arg) const -> void; + auto PrintArgLongValues(const Arg& arg, llvm::StringRef indent) const -> void; + auto PrintArgHelp(const Arg& arg, llvm::StringRef indent) const -> void; // Helpers for printing command usage summaries. - void PrintRawUsageCommandAndOptions( + auto PrintRawUsageCommandAndOptions( const Command& command, - int max_option_width = MaxLeafOptionUsageWidth) const; - void PrintRawUsage(const Command& command, llvm::StringRef indent) const; - void PrintUsage(const Command& command) const; + int max_option_width = MaxLeafOptionUsageWidth) const -> void; + auto PrintRawUsage(const Command& command, llvm::StringRef indent) const + -> void; + auto PrintUsage(const Command& command) const -> void; // Helpers to print various sections of `PrintHelp` that only occur within // that output. - void PrintHelpSubcommands(const Command& command) const; - void PrintHelpPositionalArgs(const Command& command) const; - void PrintHelpOptions(const Command& command) const; + auto PrintHelpSubcommands(const Command& command) const -> void; + auto PrintHelpPositionalArgs(const Command& command) const -> void; + auto PrintHelpOptions(const Command& command) const -> void; llvm::raw_ostream* out_; @@ -231,8 +237,8 @@ Prints the version of this command. llvm::StringRef help_subcommand_; }; -void MetaPrinter::RegisterWithCommand(const Command& command, - CommandBuilder& builder) { +auto MetaPrinter::RegisterWithCommand(const Command& command, + CommandBuilder& builder) -> void { bool is_subcommand = command.parent; bool has_subcommands = !command.subcommands.empty(); @@ -285,7 +291,7 @@ void MetaPrinter::RegisterWithCommand(const Command& command, } } -void MetaPrinter::PrintHelp(const Command& command) const { +auto MetaPrinter::PrintHelp(const Command& command) const -> void { // TODO: begin using the short setting to customize the output. (void)short_help_; @@ -320,8 +326,8 @@ void MetaPrinter::PrintHelp(const Command& command) const { *out_ << "\n"; } -void MetaPrinter::PrintHelpForSubcommandName( - const Command& command, llvm::StringRef subcommand_name) const { +auto MetaPrinter::PrintHelpForSubcommandName( + const Command& command, llvm::StringRef subcommand_name) const -> void { for (const auto& subcommand : command.subcommands) { if (subcommand->info.name == subcommand_name) { PrintHelp(*subcommand); @@ -335,7 +341,7 @@ void MetaPrinter::PrintHelpForSubcommandName( << "'\n"; } -void MetaPrinter::PrintVersion(const Command& command) const { +auto MetaPrinter::PrintVersion(const Command& command) const -> void { CARBON_CHECK( !command.info.version.empty(), "Printing should not be enabled without a version string configured."); @@ -347,21 +353,21 @@ void MetaPrinter::PrintVersion(const Command& command) const { } } -void MetaPrinter::PrintSubcommands(const Command& command) const { +auto MetaPrinter::PrintSubcommands(const Command& command) const -> void { PrintListOfAlternatives(*out_, llvm::ArrayRef(command.subcommands), [](const std::unique_ptr& subcommand) { return subcommand->info.name; }); } -void MetaPrinter::PrintRawVersion(const Command& command, - llvm::StringRef indent) const { +auto MetaPrinter::PrintRawVersion(const Command& command, + llvm::StringRef indent) const -> void { // Newlines are trimmed from the version string an a closing newline added but // no other formatting is performed. *out_ << indent << command.info.version.trim('\n') << "\n"; } -void MetaPrinter::PrintRawBuildInfo(const Command& command, - llvm::StringRef indent) const { +auto MetaPrinter::PrintRawBuildInfo(const Command& command, + llvm::StringRef indent) const -> void { // Print the build info line-by-line without any wrapping in case it // contains line-oriented formatted text, but drop leading and trailing blank // lines. @@ -372,8 +378,8 @@ void MetaPrinter::PrintRawBuildInfo(const Command& command, } } -void MetaPrinter::PrintTextBlock(llvm::StringRef indent, - llvm::StringRef text) const { +auto MetaPrinter::PrintTextBlock(llvm::StringRef indent, + llvm::StringRef text) const -> void { // Strip leading and trailing newlines to make it easy to use multiline raw // string literals that will naturally have those. text = text.trim('\n'); @@ -448,7 +454,7 @@ void MetaPrinter::PrintTextBlock(llvm::StringRef indent, } } -void MetaPrinter::PrintArgValueUsage(const Arg& arg) const { +auto MetaPrinter::PrintArgValueUsage(const Arg& arg) const -> void { if (!arg.info.value_name.empty()) { *out_ << arg.info.value_name; return; @@ -465,7 +471,7 @@ void MetaPrinter::PrintArgValueUsage(const Arg& arg) const { *out_ << "..."; } -void MetaPrinter::PrintOptionUsage(const Arg& option) const { +auto MetaPrinter::PrintOptionUsage(const Arg& option) const -> void { if (option.kind == Arg::Kind::Flag) { *out_ << "--" << (option.default_flag ? "no-" : "") << option.info.name; return; @@ -480,12 +486,12 @@ void MetaPrinter::PrintOptionUsage(const Arg& option) const { } } -void MetaPrinter::PrintOptionShortName(const Arg& arg) const { +auto MetaPrinter::PrintOptionShortName(const Arg& arg) const -> void { CARBON_CHECK(!arg.info.short_name.empty(), "No short name to use."); *out_ << "-" << arg.info.short_name; } -void MetaPrinter::PrintArgShortValues(const Arg& arg) const { +auto MetaPrinter::PrintArgShortValues(const Arg& arg) const -> void { CARBON_CHECK( arg.kind == Arg::Kind::OneOf, "Only one-of arguments have interesting value snippets to print."); @@ -494,8 +500,8 @@ void MetaPrinter::PrintArgShortValues(const Arg& arg) const { *out_ << sep << value_string; } } -void MetaPrinter::PrintArgLongValues(const Arg& arg, - llvm::StringRef indent) const { +auto MetaPrinter::PrintArgLongValues(const Arg& arg, + llvm::StringRef indent) const -> void { *out_ << indent << "Possible values:\n"; // TODO: It would be good to add help text for each value and then print it // here. @@ -509,7 +515,8 @@ void MetaPrinter::PrintArgLongValues(const Arg& arg, } } -void MetaPrinter::PrintArgHelp(const Arg& arg, llvm::StringRef indent) const { +auto MetaPrinter::PrintArgHelp(const Arg& arg, llvm::StringRef indent) const + -> void { // Print out the main help text. PrintTextBlock(indent, arg.info.help); @@ -540,8 +547,9 @@ void MetaPrinter::PrintArgHelp(const Arg& arg, llvm::StringRef indent) const { } } -void MetaPrinter::PrintRawUsageCommandAndOptions(const Command& command, - int max_option_width) const { +auto MetaPrinter::PrintRawUsageCommandAndOptions(const Command& command, + int max_option_width) const + -> void { // Recursively print parent usage first with a compressed width. if (command.parent) { PrintRawUsageCommandAndOptions(*command.parent, MaxParentOptionUsageWidth); @@ -597,8 +605,8 @@ void MetaPrinter::PrintRawUsageCommandAndOptions(const Command& command, } } -void MetaPrinter::PrintRawUsage(const Command& command, - llvm::StringRef indent) const { +auto MetaPrinter::PrintRawUsage(const Command& command, + llvm::StringRef indent) const -> void { if (!command.info.usage.empty()) { PrintTextBlock(indent, command.info.usage); return; @@ -644,7 +652,7 @@ void MetaPrinter::PrintRawUsage(const Command& command, } } -void MetaPrinter::PrintUsage(const Command& command) const { +auto MetaPrinter::PrintUsage(const Command& command) const -> void { if (!command.parent) { *out_ << "Usage:\n"; } else { @@ -653,7 +661,7 @@ void MetaPrinter::PrintUsage(const Command& command) const { PrintRawUsage(command, " "); } -void MetaPrinter::PrintHelpSubcommands(const Command& command) const { +auto MetaPrinter::PrintHelpSubcommands(const Command& command) const -> void { bool first_subcommand = true; for (const auto& subcommand : command.subcommands) { if (subcommand->is_help_hidden) { @@ -673,7 +681,8 @@ void MetaPrinter::PrintHelpSubcommands(const Command& command) const { } } -void MetaPrinter::PrintHelpPositionalArgs(const Command& command) const { +auto MetaPrinter::PrintHelpPositionalArgs(const Command& command) const + -> void { bool first_positional_arg = true; for (const auto& positional_arg : command.positional_args) { if (positional_arg->is_help_hidden) { @@ -694,7 +703,7 @@ void MetaPrinter::PrintHelpPositionalArgs(const Command& command) const { } } -void MetaPrinter::PrintHelpOptions(const Command& command) const { +auto MetaPrinter::PrintHelpOptions(const Command& command) const -> void { bool first_option = true; for (const auto& option : command.options) { if (option->is_help_hidden) { @@ -729,7 +738,7 @@ class Parser { public: // `out` must not be null. explicit Parser(llvm::raw_ostream* out, CommandInfo command_info, - llvm::function_ref build); + llvm::function_refvoid> build); auto Parse(llvm::ArrayRef unparsed_args) -> ErrorOr; @@ -750,9 +759,9 @@ class Parser { // character's numeric value makes for a convenient map. using ShortOptionTableT = std::array; - void PopulateMaps(const Command& command); + auto PopulateMaps(const Command& command) -> void; - void SetOptionDefault(const Arg& option); + auto SetOptionDefault(const Arg& option) -> void; auto ParseNegatedFlag(const Arg& flag, std::optional value) -> ErrorOr; @@ -801,7 +810,7 @@ class Parser { ActionT arg_meta_action_; }; -void Parser::PopulateMaps(const Command& command) { +auto Parser::PopulateMaps(const Command& command) -> void { option_map_.clear(); for (const auto& option : command.options) { option_map_.insert({option->info.name, {option.get(), false}}); @@ -825,7 +834,7 @@ void Parser::PopulateMaps(const Command& command) { } } -void Parser::SetOptionDefault(const Arg& option) { +auto Parser::SetOptionDefault(const Arg& option) -> void { CARBON_CHECK(option.has_default, "No default value available!"); switch (option.kind) { case Arg::Kind::Flag: @@ -1235,7 +1244,7 @@ auto Parser::ParsePositionalSuffix( } Parser::Parser(llvm::raw_ostream* out, CommandInfo command_info, - llvm::function_ref build) + llvm::function_refvoid> build) : meta_printer_(out), root_command_(command_info) { // Run the command building lambda on a builder for the root command. CommandBuilder builder(&root_command_, &meta_printer_); @@ -1305,48 +1314,50 @@ auto Parser::Parse(llvm::ArrayRef unparsed_args) return FinalizeParse(); } -void ArgBuilder::Required(bool is_required) { arg_->is_required = is_required; } +auto ArgBuilder::Required(bool is_required) -> void { + arg_->is_required = is_required; +} -void ArgBuilder::HelpHidden(bool is_help_hidden) { +auto ArgBuilder::HelpHidden(bool is_help_hidden) -> void { arg_->is_help_hidden = is_help_hidden; } ArgBuilder::ArgBuilder(Arg* arg) : arg_(arg) {} -void FlagBuilder::Default(bool flag_value) { +auto FlagBuilder::Default(bool flag_value) -> void { arg()->has_default = true; arg()->default_flag = flag_value; } -void FlagBuilder::Set(bool* flag) { arg()->flag_storage = flag; } +auto FlagBuilder::Set(bool* flag) -> void { arg()->flag_storage = flag; } -void IntegerArgBuilder::Default(int integer_value) { +auto IntegerArgBuilder::Default(int integer_value) -> void { arg()->has_default = true; arg()->default_integer = integer_value; } -void IntegerArgBuilder::Set(int* integer) { +auto IntegerArgBuilder::Set(int* integer) -> void { arg()->is_append = false; arg()->integer_storage = integer; } -void IntegerArgBuilder::Append(llvm::SmallVectorImpl* sequence) { +auto IntegerArgBuilder::Append(llvm::SmallVectorImpl* sequence) -> void { arg()->is_append = true; arg()->integer_sequence = sequence; } -void StringArgBuilder::Default(llvm::StringRef string_value) { +auto StringArgBuilder::Default(llvm::StringRef string_value) -> void { arg()->has_default = true; arg()->default_string = string_value; } -void StringArgBuilder::Set(llvm::StringRef* string) { +auto StringArgBuilder::Set(llvm::StringRef* string) -> void { arg()->is_append = false; arg()->string_storage = string; } -void StringArgBuilder::Append( - llvm::SmallVectorImpl* sequence) { +auto StringArgBuilder::Append(llvm::SmallVectorImpl* sequence) + -> void { arg()->is_append = true; arg()->string_sequence = sequence; } @@ -1371,8 +1382,9 @@ static auto IsValidName(llvm::StringRef name) -> bool { return !name.starts_with("no-"); } -void CommandBuilder::AddFlag(const ArgInfo& info, - llvm::function_ref build) { +auto CommandBuilder::AddFlag(const ArgInfo& info, + llvm::function_refvoid> build) + -> void { FlagBuilder builder(AddArgImpl(info, Arg::Kind::Flag)); // All boolean flags have an implicit default of `false`, although it can be // overridden in the build callback. @@ -1380,56 +1392,64 @@ void CommandBuilder::AddFlag(const ArgInfo& info, build(builder); } -void CommandBuilder::AddIntegerOption( - const ArgInfo& info, llvm::function_ref build) { +auto CommandBuilder::AddIntegerOption( + const ArgInfo& info, + llvm::function_refvoid> build) -> void { IntegerArgBuilder builder(AddArgImpl(info, Arg::Kind::Integer)); build(builder); } -void CommandBuilder::AddStringOption( - const ArgInfo& info, llvm::function_ref build) { +auto CommandBuilder::AddStringOption( + const ArgInfo& info, + llvm::function_refvoid> build) -> void { StringArgBuilder builder(AddArgImpl(info, Arg::Kind::String)); build(builder); } -void CommandBuilder::AddOneOfOption( - const ArgInfo& info, llvm::function_ref build) { +auto CommandBuilder::AddOneOfOption( + const ArgInfo& info, llvm::function_refvoid> build) + -> void { OneOfArgBuilder builder(AddArgImpl(info, Arg::Kind::OneOf)); build(builder); } -void CommandBuilder::AddMetaActionOption( - const ArgInfo& info, llvm::function_ref build) { +auto CommandBuilder::AddMetaActionOption( + const ArgInfo& info, llvm::function_refvoid> build) + -> void { ArgBuilder builder(AddArgImpl(info, Arg::Kind::MetaActionOnly)); build(builder); } -void CommandBuilder::AddIntegerPositionalArg( - const ArgInfo& info, llvm::function_ref build) { +auto CommandBuilder::AddIntegerPositionalArg( + const ArgInfo& info, + llvm::function_refvoid> build) -> void { AddPositionalArgImpl(info, Arg::Kind::Integer, [build](Arg& arg) { IntegerArgBuilder builder(&arg); build(builder); }); } -void CommandBuilder::AddStringPositionalArg( - const ArgInfo& info, llvm::function_ref build) { +auto CommandBuilder::AddStringPositionalArg( + const ArgInfo& info, + llvm::function_refvoid> build) -> void { AddPositionalArgImpl(info, Arg::Kind::String, [build](Arg& arg) { StringArgBuilder builder(&arg); build(builder); }); } -void CommandBuilder::AddOneOfPositionalArg( - const ArgInfo& info, llvm::function_ref build) { +auto CommandBuilder::AddOneOfPositionalArg( + const ArgInfo& info, llvm::function_refvoid> build) + -> void { AddPositionalArgImpl(info, Arg::Kind::OneOf, [build](Arg& arg) { OneOfArgBuilder builder(&arg); build(builder); }); } -void CommandBuilder::AddSubcommand( - const CommandInfo& info, llvm::function_ref build) { +auto CommandBuilder::AddSubcommand( + const CommandInfo& info, + llvm::function_refvoid> build) -> void { CARBON_CHECK(IsValidName(info.name), "Invalid subcommand name: {0}", info.name); CARBON_CHECK(subcommand_names_.insert(info.name).second, @@ -1444,11 +1464,11 @@ void CommandBuilder::AddSubcommand( builder.Finalize(); } -void CommandBuilder::HelpHidden(bool is_help_hidden) { +auto CommandBuilder::HelpHidden(bool is_help_hidden) -> void { command_->is_help_hidden = is_help_hidden; } -void CommandBuilder::RequiresSubcommand() { +auto CommandBuilder::RequiresSubcommand() -> void { CARBON_CHECK(!command_->subcommands.empty(), "Cannot require subcommands unless there are subcommands."); CARBON_CHECK(command_->positional_args.empty(), @@ -1459,7 +1479,7 @@ void CommandBuilder::RequiresSubcommand() { command_->kind = Kind::RequiresSubcommand; } -void CommandBuilder::Do(ActionT action) { +auto CommandBuilder::Do(ActionT action) -> void { CARBON_CHECK(command_->kind == Kind::Invalid, "Already established the kind of this command as: {0}", command_->kind); @@ -1467,7 +1487,7 @@ void CommandBuilder::Do(ActionT action) { command_->action = std::move(action); } -void CommandBuilder::Meta(ActionT action) { +auto CommandBuilder::Meta(ActionT action) -> void { CARBON_CHECK(command_->kind == Kind::Invalid, "Already established the kind of this command as: {0}", command_->kind); @@ -1489,8 +1509,9 @@ auto CommandBuilder::AddArgImpl(const ArgInfo& info, Arg::Kind kind) -> Arg* { return arg; } -void CommandBuilder::AddPositionalArgImpl( - const ArgInfo& info, Arg::Kind kind, llvm::function_ref build) { +auto CommandBuilder::AddPositionalArgImpl( + const ArgInfo& info, Arg::Kind kind, + llvm::function_refvoid> build) -> void { CARBON_CHECK(IsValidName(info.name), "Invalid argument name: {0}", info.name); CARBON_CHECK( command_->subcommands.empty(), @@ -1511,13 +1532,13 @@ void CommandBuilder::AddPositionalArgImpl( } } -void CommandBuilder::Finalize() { +auto CommandBuilder::Finalize() -> void { meta_printer_->RegisterWithCommand(*command_, *this); } auto Parse(llvm::ArrayRef unparsed_args, llvm::raw_ostream& out, CommandInfo command_info, - llvm::function_ref build) + llvm::function_refvoid> build) -> ErrorOr { // Build a parser, which includes building the command description provided by // the user. diff --git a/common/command_line.h b/common/command_line.h index 62303b339b10..0218165228c1 100644 --- a/common/command_line.h +++ b/common/command_line.h @@ -237,7 +237,7 @@ auto operator<<(llvm::raw_ostream& output, ParseResult result) // Actions are stored in data structures so we use an owning closure to model // them. -using ActionT = std::function; +using ActionT = std::functionvoid>; // The core argument info used to render help and other descriptive // information. This is used for both options and positional arguments. @@ -294,17 +294,17 @@ class ArgBuilder { public: // When marked as required, if an argument is not provided explicitly in the // command line the parse will produce an error. - void Required(bool is_required); + auto Required(bool is_required) -> void; // An argument can be hidden from the help output. - void HelpHidden(bool is_help_hidden); + auto HelpHidden(bool is_help_hidden) -> void; // Sets a meta-action to run when this argument is parsed. This is used to // set up arguments like `--help` or `--version` that can be entirely // handled during parsing and rather than produce parsed information about // the command line, override that for some custom behavior. template - void MetaAction(T action); + auto MetaAction(T action) -> void; protected: friend class CommandBuilder; @@ -323,12 +323,12 @@ class FlagBuilder : public ArgBuilder { // Flags can be defaulted to true. However, flags always have *some* // default, this merely customizes which value is default. If uncustomized, // the default of a flag is false. - void Default(bool flag_value); + auto Default(bool flag_value) -> void; // Configures the argument to store a parsed value in the provided storage. // // This must be called on the builder. - void Set(bool* flag); + auto Set(bool* flag) -> void; private: using ArgBuilder::ArgBuilder; @@ -345,7 +345,7 @@ class IntegerArgBuilder : public ArgBuilder { // below, this value will be used whenever the argument occurs without an // explicit value, but unless the argument is parsed nothing will be // appended. - void Default(int integer_value); + auto Default(int integer_value) -> void; // Configures the argument to store a parsed value in the provided storage. // Each time the argument is parsed, it will write a new value to this @@ -353,7 +353,7 @@ class IntegerArgBuilder : public ArgBuilder { // // Exactly one of this method or `Append` below must be configured for the // argument. - void Set(int* integer); + auto Set(int* integer) -> void; // Configures the argument to append a parsed value to the provided // container. Each time the argument is parsed, a new value will be @@ -361,7 +361,7 @@ class IntegerArgBuilder : public ArgBuilder { // // Exactly one of this method or `Set` above must be configured for the // argument. - void Append(llvm::SmallVectorImpl* sequence); + auto Append(llvm::SmallVectorImpl* sequence) -> void; private: using ArgBuilder::ArgBuilder; @@ -378,7 +378,7 @@ class StringArgBuilder : public ArgBuilder { // below, this value will be used whenever the argument occurs without an // explicit value, but unless the argument is parsed nothing will be // appended. - void Default(llvm::StringRef string_value); + auto Default(llvm::StringRef string_value) -> void; // Configures the argument to store a parsed value in the provided storage. // Each time the argument is parsed, it will write a new value to this @@ -386,7 +386,7 @@ class StringArgBuilder : public ArgBuilder { // // Exactly one of this method or `Append` below must be configured for the // argument. - void Set(llvm::StringRef* string); + auto Set(llvm::StringRef* string) -> void; // Configures the argument to append a parsed value to the provided // container. Each time the argument is parsed, a new value will be @@ -394,7 +394,7 @@ class StringArgBuilder : public ArgBuilder { // // Exactly one of this method or `Set` above must be configured for the // argument. - void Append(llvm::SmallVectorImpl* sequence); + auto Append(llvm::SmallVectorImpl* sequence) -> void; private: using ArgBuilder::ArgBuilder; @@ -463,7 +463,7 @@ class OneOfArgBuilder : public ArgBuilder { // optional, and also will cause that value to be stored into the result // even if the argument is not parsed explicitly. template - void SetOneOf(const OneOfValueT (&values)[N], T* result); + auto SetOneOf(const OneOfValueT (&values)[N], T* result) -> void; // Configures the argument to append a parsed value to the provided // container. Each time the argument is parsed, a new value will be @@ -491,15 +491,15 @@ class OneOfArgBuilder : public ArgBuilder { // However, appending one-of arguments cannot use a default. The values must // always be explicitly parsed. template - void AppendOneOf(const OneOfValueT (&values)[N], - llvm::SmallVectorImpl* sequence); + auto AppendOneOf(const OneOfValueT (&values)[N], + llvm::SmallVectorImpl* sequence) -> void; private: using ArgBuilder::ArgBuilder; template - void OneOfImpl(const OneOfValueT (&input_values)[N], MatchT match, - std::index_sequence /*indices*/); + auto OneOfImpl(const OneOfValueT (&input_values)[N], MatchT match, + std::index_sequence /*indices*/) -> void; }; // The extended info for a command, including for a subcommand. @@ -593,37 +593,45 @@ class CommandBuilder { public: using Kind = CommandKind; - void AddFlag(const ArgInfo& info, - llvm::function_ref build); - void AddIntegerOption(const ArgInfo& info, - llvm::function_ref build); - void AddStringOption(const ArgInfo& info, - llvm::function_ref build); - void AddOneOfOption(const ArgInfo& info, - llvm::function_ref build); - void AddMetaActionOption(const ArgInfo& info, - llvm::function_ref build); + auto AddFlag(const ArgInfo& info, + llvm::function_refvoid> build) -> void; + auto AddIntegerOption( + const ArgInfo& info, + llvm::function_refvoid> build) -> void; + auto AddStringOption(const ArgInfo& info, + llvm::function_refvoid> build) + -> void; + auto AddOneOfOption(const ArgInfo& info, + llvm::function_refvoid> build) + -> void; + auto AddMetaActionOption(const ArgInfo& info, + llvm::function_refvoid> build) + -> void; - void AddIntegerPositionalArg( - const ArgInfo& info, llvm::function_ref build); - void AddStringPositionalArg( - const ArgInfo& info, llvm::function_ref build); - void AddOneOfPositionalArg(const ArgInfo& info, - llvm::function_ref build); + auto AddIntegerPositionalArg( + const ArgInfo& info, + llvm::function_refvoid> build) -> void; + auto AddStringPositionalArg( + const ArgInfo& info, + llvm::function_refvoid> build) -> void; + auto AddOneOfPositionalArg( + const ArgInfo& info, + llvm::function_refvoid> build) -> void; - void AddSubcommand(const CommandInfo& info, - llvm::function_ref build); + auto AddSubcommand(const CommandInfo& info, + llvm::function_refvoid> build) + -> void; // Subcommands can be hidden from the help listing of their parents with // this setting. Hiding a subcommand doesn't disable its own help, it just // removes it from the listing. - void HelpHidden(bool is_help_hidden); + auto HelpHidden(bool is_help_hidden) -> void; // Exactly one of these three should be called to select and configure the // kind of the built command. - void RequiresSubcommand(); - void Do(ActionT action); - void Meta(ActionT meta_action); + auto RequiresSubcommand() -> void; + auto Do(ActionT action) -> void; + auto Meta(ActionT meta_action) -> void; private: friend Parser; @@ -632,9 +640,9 @@ class CommandBuilder { explicit CommandBuilder(Command* command, MetaPrinter* meta_printer); auto AddArgImpl(const ArgInfo& info, ArgKind kind) -> Arg*; - void AddPositionalArgImpl(const ArgInfo& info, ArgKind kind, - llvm::function_ref build); - void Finalize(); + auto AddPositionalArgImpl(const ArgInfo& info, ArgKind kind, + llvm::function_refvoid> build) -> void; + auto Finalize() -> void; Command* command_; MetaPrinter* meta_printer_; @@ -658,7 +666,7 @@ class CommandBuilder { // to `out`. auto Parse(llvm::ArrayRef unparsed_args, llvm::raw_ostream& out, CommandInfo command_info, - llvm::function_ref build) + llvm::function_refvoid> build) -> ErrorOr; // Implementation details only below. @@ -667,8 +675,8 @@ auto Parse(llvm::ArrayRef unparsed_args, struct Arg { using Kind = ArgKind; using ValueActionT = - std::function; - using DefaultActionT = std::function; + std::functionbool>; + using DefaultActionT = std::functionvoid>; explicit Arg(ArgInfo info); ~Arg(); @@ -733,7 +741,7 @@ struct Command { }; template -void ArgBuilder::MetaAction(T action) { +auto ArgBuilder::MetaAction(T action) -> void { CARBON_CHECK(!arg_->meta_action, "Cannot set a meta action twice!"); arg_->meta_action = std::move(action); } @@ -757,7 +765,8 @@ auto OneOfArgBuilder::OneOfValue(llvm::StringRef str, T value) } template -void OneOfArgBuilder::SetOneOf(const OneOfValueT (&values)[N], T* result) { +auto OneOfArgBuilder::SetOneOf(const OneOfValueT (&values)[N], T* result) + -> void { static_assert(N > 0, "Must include at least one value."); arg()->is_append = false; OneOfImpl( @@ -766,8 +775,8 @@ void OneOfArgBuilder::SetOneOf(const OneOfValueT (&values)[N], T* result) { } template -void OneOfArgBuilder::AppendOneOf(const OneOfValueT (&values)[N], - llvm::SmallVectorImpl* sequence) { +auto OneOfArgBuilder::AppendOneOf(const OneOfValueT (&values)[N], + llvm::SmallVectorImpl* sequence) -> void { static_assert(N > 0, "Must include at least one value."); arg()->is_append = true; OneOfImpl( @@ -787,9 +796,10 @@ void OneOfArgBuilder::AppendOneOf(const OneOfValueT (&values)[N], // lambdas that do the type-aware operations and storing those into type-erased // function objects. template -void OneOfArgBuilder::OneOfImpl(const OneOfValueT (&input_values)[N], +auto OneOfArgBuilder::OneOfImpl(const OneOfValueT (&input_values)[N], MatchT match, - std::index_sequence /*indices*/) { + std::index_sequence /*indices*/) + -> void { std::array value_strings = {input_values[Indices].str...}; std::array values = {input_values[Indices].value...}; diff --git a/common/command_line_test.cpp b/common/command_line_test.cpp index 909f5db89010..b2c7b2e57a21 100644 --- a/common/command_line_test.cpp +++ b/common/command_line_test.cpp @@ -437,9 +437,9 @@ TEST(ArgParserTest, PositionalAppending) { EXPECT_THAT(strings3, ElementsAre(StrEq("e"), StrEq("f"))); } -static auto ParseOneOfOption(llvm::ArrayRef args, - llvm::raw_ostream& s, - llvm::function_ref build) +static auto ParseOneOfOption( + llvm::ArrayRef args, llvm::raw_ostream& s, + llvm::function_refvoid> build) -> ErrorOr { return Parse(args, s, TestCommandInfo, [&](auto& b) { b.AddOneOfOption({.name = "option"}, build); diff --git a/common/error.h b/common/error.h index ec18eb9d1a2e..72486e5821e1 100644 --- a/common/error.h +++ b/common/error.h @@ -21,7 +21,7 @@ namespace Carbon { // using `ErrorOr` and `return Success();` if no value needs to be // returned. struct Success : public Printable { - void Print(llvm::raw_ostream& out) const { out << "Success"; } + auto Print(llvm::raw_ostream& out) const -> void { out << "Success"; } }; // Tracks an error message. @@ -50,7 +50,7 @@ class [[nodiscard]] Error : public Printable { } // Prints the error string. - void Print(llvm::raw_ostream& out) const { + auto Print(llvm::raw_ostream& out) const -> void { if (!location().empty()) { out << location() << ": "; } diff --git a/common/hashing_benchmark.cpp b/common/hashing_benchmark.cpp index b4392fe01f71..9a1b2f1a61ec 100644 --- a/common/hashing_benchmark.cpp +++ b/common/hashing_benchmark.cpp @@ -195,7 +195,7 @@ struct LLVMHashBench : HashBenchBase { }; template -void BM_LatencyHash(benchmark::State& state) { +auto BM_LatencyHash(benchmark::State& state) -> void { uint64_t x = 13; Values v; Hasher h; diff --git a/common/map.h b/common/map.h index 33c261073cec..fae8a2f3f675 100644 --- a/common/map.h +++ b/common/map.h @@ -114,7 +114,7 @@ class MapView // Run the provided callback for every key and value in the map. template - void ForEach(CallbackT callback) + auto ForEach(CallbackT callback) -> void requires(std::invocable); // This routine is relatively inefficient and only intended for use in @@ -224,7 +224,7 @@ class MapBase : protected RawHashtable::BaseImpl - void ForEach(CallbackT callback) const + auto ForEach(CallbackT callback) const -> void requires(std::invocable) { return ViewT(*this).ForEach(callback); @@ -345,7 +345,7 @@ class MapBase : protected RawHashtable::BaseImpl void; protected: using ImplT::ImplT; @@ -390,7 +390,7 @@ class Map : public RawHashtable::TableImpl< // Reset the entire state of the hashtable to as it was when constructed, // throwing away any intervening allocations. - void Reset(); + auto Reset() -> void; }; template @@ -418,8 +418,8 @@ auto MapView::operator[]( template template -void MapView::ForEach( - CallbackT callback) +auto MapView::ForEach( + CallbackT callback) -> void requires(std::invocable) { this->ForEachEntry( @@ -551,14 +551,14 @@ MapBase::Update( } template -void MapBase::GrowToAllocSize( - ssize_t target_alloc_size, KeyContextT key_context) { +auto MapBase::GrowToAllocSize( + ssize_t target_alloc_size, KeyContextT key_context) -> void { this->GrowToAllocSizeImpl(target_alloc_size, key_context); } template -void MapBase::GrowForInsertCount( - ssize_t count, KeyContextT key_context) { +auto MapBase::GrowForInsertCount( + ssize_t count, KeyContextT key_context) -> void { this->GrowForInsertCountImpl(count, key_context); } @@ -570,13 +570,13 @@ auto MapBase::Erase( } template -void MapBase::Clear() { +auto MapBase::Clear() -> void { this->ClearImpl(); } template -void Map::Reset() { +auto Map::Reset() -> void { this->ResetImpl(); } diff --git a/common/map_test.cpp b/common/map_test.cpp index b39bb7cdac1d..b1cc739d3a1b 100644 --- a/common/map_test.cpp +++ b/common/map_test.cpp @@ -25,7 +25,7 @@ using ::testing::Pair; using ::testing::UnorderedElementsAreArray; template -void ExpectMapElementsAre(MapT&& m, MatcherRangeT element_matchers) { +auto ExpectMapElementsAre(MapT&& m, MatcherRangeT element_matchers) -> void { // Now collect the elements into a container. using KeyT = typename std::remove_reference::type::KeyT; using ValueT = typename std::remove_reference::type::ValueT; @@ -41,14 +41,16 @@ void ExpectMapElementsAre(MapT&& m, MatcherRangeT element_matchers) { // Allow directly using an initializer list. template -void ExpectMapElementsAre(MapT&& m, - std::initializer_list element_matchers) { +auto ExpectMapElementsAre(MapT&& m, + std::initializer_list element_matchers) + -> void { std::vector element_matchers_storage = element_matchers; ExpectMapElementsAre(m, element_matchers_storage); } template -auto MakeKeyValues(ValueCB value_cb, RangeT&& range, RangeTs&&... ranges) { +auto MakeKeyValues(ValueCB value_cb, RangeT&& range, RangeTs&&... ranges) + -> auto { using KeyT = typename RangeT::value_type; using ValueT = decltype(value_cb(std::declval())); std::vector> elements; diff --git a/common/raw_hashtable.h b/common/raw_hashtable.h index 23ff9983fcc8..959c23db8c4b 100644 --- a/common/raw_hashtable.h +++ b/common/raw_hashtable.h @@ -691,7 +691,7 @@ class ProbeSequence { #endif } - void Next() { + auto Next() -> void { step_ += GroupSize; p_ = (p_ + step_) & mask_; #ifndef NDEBUG diff --git a/common/raw_string_ostream.h b/common/raw_string_ostream.h index 37b121143c21..210c3ff2391c 100644 --- a/common/raw_string_ostream.h +++ b/common/raw_string_ostream.h @@ -51,7 +51,7 @@ class RawStringOstream : public llvm::raw_pwrite_stream { str_.append(ptr, size); } - void reserveExtraSpace(uint64_t extra_size) override { + auto reserveExtraSpace(uint64_t extra_size) -> void override { str_.reserve(str_.size() + extra_size); } diff --git a/common/set.h b/common/set.h index b85027eafde1..f2e325abfb01 100644 --- a/common/set.h +++ b/common/set.h @@ -94,7 +94,7 @@ class SetView : RawHashtable::ViewImpl { // Run the provided callback for every key in the set. template - void ForEach(CallbackT callback) + auto ForEach(CallbackT callback) -> void requires(std::invocable); // This routine is relatively inefficient and only intended for use in @@ -184,7 +184,7 @@ class SetBase // Convenience forwarder to the view type. template - void ForEach(CallbackT callback) + auto ForEach(CallbackT callback) -> void requires(std::invocable) { return ViewT(*this).ForEach(callback); @@ -257,7 +257,7 @@ class SetBase // Clear all key/value pairs from the set but leave the underlying hashtable // allocated and in place. - void Clear(); + auto Clear() -> void; protected: using ImplT::ImplT; @@ -301,7 +301,7 @@ class Set : public RawHashtable::TableImpl, // Reset the entire state of the hashtable to as it was when constructed, // throwing away any intervening allocations. - void Reset(); + auto Reset() -> void; }; template @@ -326,7 +326,7 @@ auto SetView::Lookup(LookupKeyT lookup_key, template template -void SetView::ForEach(CallbackT callback) +auto SetView::ForEach(CallbackT callback) -> void requires(std::invocable) { this->ForEachEntry([callback](EntryT& entry) { callback(entry.key()); }, @@ -383,14 +383,14 @@ auto SetBase::Insert(LookupKeyT lookup_key, } template -void SetBase::GrowToAllocSize( - ssize_t target_alloc_size, KeyContextT key_context) { +auto SetBase::GrowToAllocSize( + ssize_t target_alloc_size, KeyContextT key_context) -> void { this->GrowToAllocSizeImpl(target_alloc_size, key_context); } template -void SetBase::GrowForInsertCount( - ssize_t count, KeyContextT key_context) { +auto SetBase::GrowForInsertCount( + ssize_t count, KeyContextT key_context) -> void { this->GrowForInsertCountImpl(count, key_context); } @@ -403,12 +403,12 @@ auto SetBase::Erase(LookupKeyT lookup_key, } template -void SetBase::Clear() { +auto SetBase::Clear() -> void { this->ClearImpl(); } template -void Set::Reset() { +auto Set::Reset() -> void { this->ResetImpl(); } diff --git a/common/set_test.cpp b/common/set_test.cpp index 1a215898e680..2de94b171cea 100644 --- a/common/set_test.cpp +++ b/common/set_test.cpp @@ -21,7 +21,7 @@ using RawHashtable::TestData; using ::testing::UnorderedElementsAreArray; template -void ExpectSetElementsAre(SetT&& s, MatcherRangeT element_matchers) { +auto ExpectSetElementsAre(SetT&& s, MatcherRangeT element_matchers) -> void { // Collect the elements into a container. using KeyT = typename std::remove_reference::type::KeyT; std::vector entries; @@ -34,8 +34,9 @@ void ExpectSetElementsAre(SetT&& s, MatcherRangeT element_matchers) { // Allow directly using an initializer list. template -void ExpectSetElementsAre(SetT&& s, - std::initializer_list element_matchers) { +auto ExpectSetElementsAre(SetT&& s, + std::initializer_list element_matchers) + -> void { std::vector element_matchers_storage = element_matchers; ExpectSetElementsAre(s, element_matchers_storage); } diff --git a/common/vlog_test.cpp b/common/vlog_test.cpp index 3761e24628a6..648a17211d5d 100644 --- a/common/vlog_test.cpp +++ b/common/vlog_test.cpp @@ -24,8 +24,8 @@ class VLogger { } } - void VLog() { CARBON_VLOG("Test\n"); } - void VLogFormatArgs() { CARBON_VLOG("Test {0} {1} {2}\n", 1, 2, 3); } + auto VLog() -> void { CARBON_VLOG("Test\n"); } + auto VLogFormatArgs() -> void { CARBON_VLOG("Test {0} {1} {2}\n", 1, 2, 3); } auto TakeStr() -> std::string { return buffer_.TakeStr(); } diff --git a/docs/project/cpp_style_guide.md b/docs/project/cpp_style_guide.md index 8409ca4379a2..13268f86c201 100644 --- a/docs/project/cpp_style_guide.md +++ b/docs/project/cpp_style_guide.md @@ -85,7 +85,8 @@ to pick a consistent option. Where possible, [`clang-format`](#suggested-clang-format-contents) should be used to enforce these. -- Always use trailing return type syntax for functions and methods. +- Always use trailing return type syntax for functions and methods, including + `-> void`, for consistency with Carbon syntax. - Place the pointer `*` adjacent to the type: `TypeName* variable_name`. - Only declare one variable at a time (declaring multiple variables requires confusing repetition of part of the type). diff --git a/testing/file_test/autoupdate.h b/testing/file_test/autoupdate.h index ea9d9917c9fd..9da9ed920061 100644 --- a/testing/file_test/autoupdate.h +++ b/testing/file_test/autoupdate.h @@ -42,7 +42,7 @@ class FileTestAutoupdater { llvm::StringRef actual_stdout, llvm::StringRef actual_stderr, const std::optional& default_file_re, const llvm::SmallVector& line_number_replacements, - std::function do_extra_check_replacements) + std::functionvoid> do_extra_check_replacements) : file_test_path_(file_test_path), test_command_(std::move(test_command)), dump_command_(std::move(dump_command)), @@ -203,7 +203,7 @@ class FileTestAutoupdater { const llvm::SmallVector& non_check_lines_; const std::optional& default_file_re_; const llvm::SmallVector& line_number_replacements_; - std::function do_extra_check_replacements_; + std::functionvoid> do_extra_check_replacements_; // Generated TIP lines, from AddTips. llvm::SmallVector tips_; diff --git a/testing/file_test/file_test_base.h b/testing/file_test/file_test_base.h index e54e1e1ea855..b1edcf09aac4 100644 --- a/testing/file_test/file_test_base.h +++ b/testing/file_test/file_test_base.h @@ -220,9 +220,9 @@ struct FileTestFactory { // A factory function for tests. The output_mutex is optional; see // `FileTestBase::output_mutex_`. - std::function + std::functionFileTestBase*> factory_fn; }; diff --git a/testing/file_test/file_test_base_test.cpp b/testing/file_test/file_test_base_test.cpp index 262e3644be20..37d2f5d56b03 100644 --- a/testing/file_test/file_test_base_test.cpp +++ b/testing/file_test/file_test_base_test.cpp @@ -273,7 +273,7 @@ auto FileTestBaseTest::Run( // Choose the test function based on filename. auto test_fn = - llvm::StringSwitch(TestParams&)>>( + llvm::StringSwitchErrorOr>>( filename.string()) .Case("alternating_files.carbon", &TestAlternatingFiles) .Case("capture_console_output.carbon", &TestCaptureConsoleOutput) diff --git a/toolchain/base/pretty_stack_trace_function.h b/toolchain/base/pretty_stack_trace_function.h index 92eff6199521..8317f0a9c628 100644 --- a/toolchain/base/pretty_stack_trace_function.h +++ b/toolchain/base/pretty_stack_trace_function.h @@ -13,14 +13,15 @@ namespace Carbon { class PrettyStackTraceFunction : public llvm::PrettyStackTraceEntry { public: - explicit PrettyStackTraceFunction(std::function fn) + explicit PrettyStackTraceFunction( + std::functionvoid> fn) : fn_(std::move(fn)) {} ~PrettyStackTraceFunction() override = default; auto print(llvm::raw_ostream& output) const -> void override { fn_(output); } private: - const std::function fn_; + const std::functionvoid> fn_; }; } // namespace Carbon diff --git a/toolchain/base/yaml.h b/toolchain/base/yaml.h index 0e4997970366..dfe6d0cbfe4c 100644 --- a/toolchain/base/yaml.h +++ b/toolchain/base/yaml.h @@ -47,13 +47,13 @@ class OutputScalar { val.print(out, /*isSigned=*/false); }) {} - explicit OutputScalar(std::function output) + explicit OutputScalar(std::functionvoid> output) : output_(std::move(output)) {} auto Output(llvm::raw_ostream& out) const -> void { output_(out); } private: - std::function output_; + std::functionvoid> output_; }; // Adapts a function for outputting YAML as a mapping. @@ -74,13 +74,13 @@ class OutputMapping { llvm::yaml::IO& io_; }; - explicit OutputMapping(std::function output) + explicit OutputMapping(std::functionvoid> output) : output_(std::move(output)) {} auto Output(llvm::yaml::IO& io) -> void { output_(Map(io)); } private: - std::function output_; + std::functionvoid> output_; }; } // namespace Carbon::Yaml diff --git a/toolchain/check/deduce.cpp b/toolchain/check/deduce.cpp index 45396697b71d..703f6bb9c95a 100644 --- a/toolchain/check/deduce.cpp +++ b/toolchain/check/deduce.cpp @@ -226,7 +226,7 @@ class DeductionContext { auto MakeSpecific() -> SemIR::SpecificId; private: - void NoteInitializingParam(SemIR::InstId param_id, auto& builder) { + auto NoteInitializingParam(SemIR::InstId param_id, auto& builder) -> void { if (auto param = context().insts().TryGetAs( param_id)) { CARBON_DIAGNOSTIC(InitializingGenericParam, Note, diff --git a/toolchain/check/import.cpp b/toolchain/check/import.cpp index f299f1d96a25..314a4c49d6f8 100644 --- a/toolchain/check/import.cpp +++ b/toolchain/check/import.cpp @@ -97,11 +97,10 @@ struct NamespaceResult { // conflict. diagnose_duplicate_namespace is used when handling a cross-package // import, where an existing namespace is in the current package and the new // namespace is a different package. -static auto AddNamespace(Context& context, SemIR::TypeId namespace_type_id, - SemIR::NameId name_id, - SemIR::NameScopeId parent_scope_id, - bool diagnose_duplicate_namespace, - llvm::function_ref make_import_id) +static auto AddNamespace( + Context& context, SemIR::TypeId namespace_type_id, SemIR::NameId name_id, + SemIR::NameScopeId parent_scope_id, bool diagnose_duplicate_namespace, + llvm::function_refSemIR::InstId> make_import_id) -> NamespaceResult { auto* parent_scope = &context.name_scopes().Get(parent_scope_id); auto [inserted, entry_id] = parent_scope->LookupOrAdd( diff --git a/toolchain/diagnostics/diagnostic.h b/toolchain/diagnostics/diagnostic.h index 5bce1d963d3d..4a80530a1842 100644 --- a/toolchain/diagnostics/diagnostic.h +++ b/toolchain/diagnostics/diagnostic.h @@ -104,7 +104,7 @@ struct DiagnosticMessage { llvm::SmallVector format_args; // Returns the formatted string. By default, this uses llvm::formatv. - std::function format_fn; + std::functionstd::string> format_fn; }; // An instance of a single error or warning. Information about the diagnostic diff --git a/toolchain/diagnostics/diagnostic_emitter.h b/toolchain/diagnostics/diagnostic_emitter.h index 38080fa1dc5b..995590379372 100644 --- a/toolchain/diagnostics/diagnostic_emitter.h +++ b/toolchain/diagnostics/diagnostic_emitter.h @@ -164,7 +164,7 @@ class DiagnosticEmitter { // Note that the first parameter type is DiagnosticLoc rather than // LocT, because ConvertLoc must not recurse. using ContextFnT = - llvm::function_ref&)>; + llvm::function_ref&)->void>; // Converts a LocT to a DiagnosticLoc and its `last_byte_offset` (see // `DiagnosticMessage`). ConvertLoc may invoke context_fn to provide context diff --git a/toolchain/diagnostics/mocks.cpp b/toolchain/diagnostics/mocks.cpp index 65af0af99056..31d4c13d0fa6 100644 --- a/toolchain/diagnostics/mocks.cpp +++ b/toolchain/diagnostics/mocks.cpp @@ -6,7 +6,7 @@ namespace Carbon { -void PrintTo(const Diagnostic& diagnostic, std::ostream* os) { +auto PrintTo(const Diagnostic& diagnostic, std::ostream* os) -> void { *os << "Diagnostic{"; PrintTo(diagnostic.level, os); for (const auto& message : diagnostic.messages) { @@ -17,7 +17,7 @@ void PrintTo(const Diagnostic& diagnostic, std::ostream* os) { *os << "\"}"; } -void PrintTo(DiagnosticLevel level, std::ostream* os) { +auto PrintTo(DiagnosticLevel level, std::ostream* os) -> void { switch (level) { case DiagnosticLevel::LocationInfo: *os << "LocationInfo"; diff --git a/toolchain/diagnostics/mocks.h b/toolchain/diagnostics/mocks.h index 0f42951583ef..91107a25b5f3 100644 --- a/toolchain/diagnostics/mocks.h +++ b/toolchain/diagnostics/mocks.h @@ -66,8 +66,8 @@ inline auto IsSingleDiagnostic(testing::Matcher kind, namespace Carbon { // Printing helpers for tests. -void PrintTo(const Diagnostic& diagnostic, std::ostream* os); -void PrintTo(DiagnosticLevel level, std::ostream* os); +auto PrintTo(const Diagnostic& diagnostic, std::ostream* os) -> void; +auto PrintTo(DiagnosticLevel level, std::ostream* os) -> void; } // namespace Carbon diff --git a/toolchain/diagnostics/sorting_diagnostic_consumer.h b/toolchain/diagnostics/sorting_diagnostic_consumer.h index 3406690deced..0c55a0112a2c 100644 --- a/toolchain/diagnostics/sorting_diagnostic_consumer.h +++ b/toolchain/diagnostics/sorting_diagnostic_consumer.h @@ -39,7 +39,7 @@ class SortingDiagnosticConsumer : public DiagnosticConsumer { } // Sorts and flushes buffered diagnostics. - void Flush() override { + auto Flush() -> void override { llvm::stable_sort(diagnostics_, [](const Diagnostic& lhs, const Diagnostic& rhs) { return lhs.last_byte_offset < rhs.last_byte_offset; diff --git a/toolchain/driver/codegen_options.cpp b/toolchain/driver/codegen_options.cpp index 22c8567713c9..fdae3a6c4537 100644 --- a/toolchain/driver/codegen_options.cpp +++ b/toolchain/driver/codegen_options.cpp @@ -6,7 +6,7 @@ namespace Carbon { -void CodegenOptions::Build(CommandLine::CommandBuilder& b) { +auto CodegenOptions::Build(CommandLine::CommandBuilder& b) -> void { b.AddStringOption( { .name = "target", diff --git a/toolchain/driver/compile_subcommand.cpp b/toolchain/driver/compile_subcommand.cpp index 044ae7dbcc25..6743f38491f1 100644 --- a/toolchain/driver/compile_subcommand.cpp +++ b/toolchain/driver/compile_subcommand.cpp @@ -372,8 +372,8 @@ class CompilationUnit { // with the actual function name, but marks timings with the appropriate // phase. auto LogCall(llvm::StringLiteral logging_label, - llvm::StringLiteral timing_label, llvm::function_ref fn) - -> void; + llvm::StringLiteral timing_label, + llvm::function_refvoid> fn) -> void; // Returns true if the current input file can be dumped. auto IncludeInDumps() const -> bool; @@ -409,7 +409,7 @@ class CompilationUnit { std::optional tokens_; std::optional parse_tree_; std::optional parse_tree_and_subtrees_; - std::optional> + std::optionalconst Parse::TreeAndSubtrees&>> tree_and_subtrees_getter_; std::optional sem_ir_; std::unique_ptr llvm_context_; @@ -710,7 +710,7 @@ auto CompilationUnit::GetParseTreeAndSubtrees() auto CompilationUnit::LogCall(llvm::StringLiteral logging_label, llvm::StringLiteral timing_label, - llvm::function_ref fn) -> void { + llvm::function_refvoid> fn) -> void { CARBON_VLOG("*** {0}: {1} ***\n", logging_label, input_filename_); Timings::ScopedTiming timing(timings_ ? &*timings_ : nullptr, timing_label); fn(); diff --git a/toolchain/language_server/handle.h b/toolchain/language_server/handle.h index 08ba21d2d208..82aa3a1b6616 100644 --- a/toolchain/language_server/handle.h +++ b/toolchain/language_server/handle.h @@ -29,21 +29,22 @@ auto HandleDidOpenTextDocument( auto HandleDocumentSymbol( Context& context, const clang::clangd::DocumentSymbolParams& params, llvm::function_ref< - void(llvm::Expected>)> + auto(llvm::Expected>)->void> on_done) -> void; // Tells the client what features are supported. auto HandleInitialize( Context& /*context*/, const clang::clangd::NoParams& /*client_capabilities*/, - llvm::function_ref)> on_done) + llvm::function_ref)->void> on_done) -> void; // Prepares LSP for shutdown. auto HandleShutdown( Context& /*context*/, const clang::clangd::NoParams& /*client_capabilities*/, - llvm::function_ref)> on_done) -> void; + llvm::function_ref)->void> on_done) + -> void; } // namespace Carbon::LanguageServer diff --git a/toolchain/language_server/handle_document_symbol.cpp b/toolchain/language_server/handle_document_symbol.cpp index 84e7b168d85b..c78d004e2774 100644 --- a/toolchain/language_server/handle_document_symbol.cpp +++ b/toolchain/language_server/handle_document_symbol.cpp @@ -74,7 +74,7 @@ static auto GetSymbolRange(const Parse::TreeAndSubtrees& tree_and_subtrees, auto HandleDocumentSymbol( Context& context, const clang::clangd::DocumentSymbolParams& params, llvm::function_ref< - void(llvm::Expected>)> + auto(llvm::Expected>)->void> on_done) -> void { auto* file = context.LookupFile(params.textDocument.uri.file()); if (!file) { diff --git a/toolchain/language_server/handle_initialize.cpp b/toolchain/language_server/handle_initialize.cpp index 77884820853b..b1adf0188e05 100644 --- a/toolchain/language_server/handle_initialize.cpp +++ b/toolchain/language_server/handle_initialize.cpp @@ -9,7 +9,7 @@ namespace Carbon::LanguageServer { auto HandleInitialize( Context& /*context*/, const clang::clangd::NoParams& /*client_capabilities*/, - llvm::function_ref)> on_done) + llvm::function_ref)->void> on_done) -> void { llvm::json::Object capabilities{{"documentSymbolProvider", true}, {"textDocumentSync", /*Full=*/1}}; diff --git a/toolchain/language_server/handle_shutdown.cpp b/toolchain/language_server/handle_shutdown.cpp index 269bd76c2e4d..64d78dbd8b56 100644 --- a/toolchain/language_server/handle_shutdown.cpp +++ b/toolchain/language_server/handle_shutdown.cpp @@ -9,7 +9,8 @@ namespace Carbon::LanguageServer { auto HandleShutdown( Context& /*context*/, const clang::clangd::NoParams& /*client_capabilities*/, - llvm::function_ref)> on_done) -> void { + llvm::function_ref)->void> on_done) + -> void { // TODO: Track that `shutdown` was called, and: // - Warn on duplicate calls. // - Make `exit` return `1` if `shutdown` wasn't called. diff --git a/toolchain/language_server/incoming_messages.cpp b/toolchain/language_server/incoming_messages.cpp index 42a733a5bf08..219da3b9e1b1 100644 --- a/toolchain/language_server/incoming_messages.cpp +++ b/toolchain/language_server/incoming_messages.cpp @@ -29,14 +29,14 @@ inline auto Parse(llvm::StringRef name, const llvm::json::Value& raw_params) template auto IncomingMessages::AddCallHandler( llvm::StringRef name, - void (*handler)(Context&, const ParamsT&, - llvm::function_ref)>)) - -> void { + auto (*handler)(Context&, const ParamsT&, + llvm::function_ref)->void>) + ->void) -> void { CallHandler parsing_handler = [name, handler]( Context& context, llvm::json::Value raw_params, - llvm::function_ref)> on_done) - -> void { + llvm::function_ref)->void> + on_done) -> void { auto params = Parse(name, raw_params); if (!params) { on_done(params.takeError()); @@ -49,9 +49,8 @@ auto IncomingMessages::AddCallHandler( } template -auto IncomingMessages::AddNotificationHandler(llvm::StringRef name, - void (*handler)(Context&, - const ParamsT&)) +auto IncomingMessages::AddNotificationHandler( + llvm::StringRef name, auto (*handler)(Context&, const ParamsT&)->void) -> void { NotificationHandler parsing_handler = [name, handler](Context& context, llvm::json::Value raw_params) -> void { diff --git a/toolchain/language_server/incoming_messages.h b/toolchain/language_server/incoming_messages.h index 407dc98a7f94..fa1534dd7b8e 100644 --- a/toolchain/language_server/incoming_messages.h +++ b/toolchain/language_server/incoming_messages.h @@ -40,21 +40,23 @@ class IncomingMessages : public clang::clangd::Transport::MessageHandler { private: // These are the signatures expected for handlers. - using CallHandler = std::function)> on_done)>; + using CallHandler = std::function< + auto(Context& context, llvm::json::Value raw_params, + llvm::function_ref)->void> + on_done) + ->void>; using NotificationHandler = - std::function; + std::functionvoid>; template auto AddCallHandler( llvm::StringRef name, - void (*handler)(Context&, const ParamsT&, - llvm::function_ref)>)) - -> void; + auto (*handler)(Context&, const ParamsT&, + llvm::function_ref)->void>) + ->void) -> void; template auto AddNotificationHandler(llvm::StringRef name, - void (*handler)(Context&, const ParamsT&)) + auto (*handler)(Context&, const ParamsT&)->void) -> void; // The connection to the client. diff --git a/toolchain/lex/tokenized_buffer_benchmark.cpp b/toolchain/lex/tokenized_buffer_benchmark.cpp index 3ed9b1f91f1a..5ec07304bd16 100644 --- a/toolchain/lex/tokenized_buffer_benchmark.cpp +++ b/toolchain/lex/tokenized_buffer_benchmark.cpp @@ -75,7 +75,7 @@ struct RandomSourceOptions { int comment_line_percent = 0; int blank_line_percent = 0; - void Validate() { + auto Validate() -> void { auto is_percentage = [](int n) { return 0 <= n && n <= 100; }; CARBON_CHECK(is_percentage(symbol_percent)); CARBON_CHECK(is_percentage(keyword_percent)); @@ -244,7 +244,7 @@ class LexerBenchHelper { SourceBuffer source_; }; -void BM_ValidKeywords(benchmark::State& state) { +auto BM_ValidKeywords(benchmark::State& state) -> void { absl::BitGen gen; std::array tokens; for (int i : llvm::seq(NumTokens)) { @@ -266,7 +266,7 @@ void BM_ValidKeywords(benchmark::State& state) { } BENCHMARK(BM_ValidKeywords); -void BM_ValidKeywordsAsRawIdentifiers(benchmark::State& state) { +auto BM_ValidKeywordsAsRawIdentifiers(benchmark::State& state) -> void { absl::BitGen gen; std::array tokens; for (int i : llvm::seq(NumTokens)) { @@ -291,7 +291,7 @@ BENCHMARK(BM_ValidKeywordsAsRawIdentifiers); // This benchmark does a 50-50 split of r-prefixed and r#-prefixed identifiers // to directly compare raw and non-raw performance. -void BM_RawIdentifierFocus(benchmark::State& state) { +auto BM_RawIdentifierFocus(benchmark::State& state) -> void { llvm::SmallVector ids = Testing::SourceGen::Global().GetIdentifiers(NumTokens / 2); @@ -328,7 +328,7 @@ void BM_RawIdentifierFocus(benchmark::State& state) { BENCHMARK(BM_RawIdentifierFocus); template -void BM_ValidIdentifiers(benchmark::State& state) { +auto BM_ValidIdentifiers(benchmark::State& state) -> void { std::string source = RandomIdentifierSeq(MinLength, MaxLength, Uniform); LexerBenchHelper helper(source); @@ -361,7 +361,7 @@ BENCHMARK(BM_ValidIdentifiers<80, 80, /*Uniform=*/true>); // Benchmark to stress the lexing of horizontal whitespace. This sets up what is // nearly a worst-case scenario of short-but-expensive-to-lex tokens with runs // of horizontal whitespace between them. -void BM_HorizontalWhitespace(benchmark::State& state) { +auto BM_HorizontalWhitespace(benchmark::State& state) -> void { int num_spaces = state.range(0); std::string separator(num_spaces, ' '); std::string source = RandomIdentifierSeq(3, 5, /*uniform=*/true, separator); @@ -381,7 +381,7 @@ void BM_HorizontalWhitespace(benchmark::State& state) { } BENCHMARK(BM_HorizontalWhitespace)->RangeMultiplier(4)->Range(1, 128); -void BM_RandomSource(benchmark::State& state) { +auto BM_RandomSource(benchmark::State& state) -> void { std::string source = RandomSource(DefaultSourceDist); LexerBenchHelper helper(source); @@ -407,7 +407,7 @@ void BM_RandomSource(benchmark::State& state) { BENCHMARK(BM_RandomSource); // Benchmark to stress opening and closing grouped symbols. -void BM_GroupingSymbols(benchmark::State& state) { +auto BM_GroupingSymbols(benchmark::State& state) -> void { int curly_brace_depth = state.range(0); int paren_depth = state.range(1); int square_bracket_depth = state.range(2); @@ -495,7 +495,7 @@ BENCHMARK(BM_GroupingSymbols) // Benchmark to stress the lexing of blank lines. This uses a simple, easy to // lex token, but separates each one by varying numbers of blank lines. -void BM_BlankLines(benchmark::State& state) { +auto BM_BlankLines(benchmark::State& state) -> void { int num_blank_lines = state.range(0); std::string separator(num_blank_lines, '\n'); std::string source = RandomIdentifierSeq(3, 5, /*uniform=*/true, separator); @@ -521,7 +521,7 @@ BENCHMARK(BM_BlankLines)->RangeMultiplier(4)->Range(1, 128); // Benchmark to stress the lexing of comment lines. This uses a simple, easy to // lex token, but separates each one by varying numbers of comment lines, with // varying comment line length and indentation. -void BM_CommentLines(benchmark::State& state) { +auto BM_CommentLines(benchmark::State& state) -> void { int num_comment_lines = state.range(0); int comment_length = state.range(1); int comment_indent = state.range(2); diff --git a/toolchain/lower/function_context.h b/toolchain/lower/function_context.h index fee0c328525c..5cdacda9a356 100644 --- a/toolchain/lower/function_context.h +++ b/toolchain/lower/function_context.h @@ -142,7 +142,7 @@ class FunctionContext { : inst_namer_(inst_namer) {} // Sets the instruction we are currently emitting. - void SetCurrentInstId(SemIR::InstId inst_id) { inst_id_ = inst_id; } + auto SetCurrentInstId(SemIR::InstId inst_id) -> void { inst_id_ = inst_id; } private: auto InsertHelper(llvm::Instruction* inst, const llvm::Twine& name, diff --git a/toolchain/parse/handle_import_and_package.cpp b/toolchain/parse/handle_import_and_package.cpp index b58271f21b81..5112a5189488 100644 --- a/toolchain/parse/handle_import_and_package.cpp +++ b/toolchain/parse/handle_import_and_package.cpp @@ -37,7 +37,7 @@ static auto HasModifier(Context& context, Context::StateStackEntry state, static auto HandleDeclContent(Context& context, Context::StateStackEntry state, NodeKind declaration, bool is_export, bool is_impl, - llvm::function_ref on_parse_error) + llvm::function_refvoid> on_parse_error) -> void { Tree::PackagingNames names{ .node_id = ImportDeclId(NodeId(state.subtree_start)), diff --git a/toolchain/parse/tree_and_subtrees.h b/toolchain/parse/tree_and_subtrees.h index 10f1447e7f1c..5c2aa515fe3d 100644 --- a/toolchain/parse/tree_and_subtrees.h +++ b/toolchain/parse/tree_and_subtrees.h @@ -194,7 +194,7 @@ class TreeAndSubtrees { }; // A standard signature for a callback to support lazy construction. -using GetTreeAndSubtreesFn = llvm::function_ref; +using GetTreeAndSubtreesFn = llvm::function_refconst TreeAndSubtrees&>; // A forward iterator across the siblings at a particular level in the parse // tree. It produces `Tree::NodeId` objects which are opaque handles and must diff --git a/toolchain/sem_ir/inst_kind.h b/toolchain/sem_ir/inst_kind.h index eb603e377c80..5f632e04b8c5 100644 --- a/toolchain/sem_ir/inst_kind.h +++ b/toolchain/sem_ir/inst_kind.h @@ -145,7 +145,7 @@ class InstKind : public CARBON_ENUM_BASE(InstKind) { // Compute a fingerprint for this instruction kind, allowing its use as part // of the key in a `FoldingSet`. - void Profile(llvm::FoldingSetNodeID& id) { id.AddInteger(AsInt()); } + auto Profile(llvm::FoldingSetNodeID& id) -> void { id.AddInteger(AsInt()); } private: // Returns the DefinitionInfo for the kind.