From 5a84670f5492967be9892d38fc36d4d83bbf38f1 Mon Sep 17 00:00:00 2001 From: Henner Zeller Date: Fri, 22 Nov 2024 19:02:29 -0800 Subject: [PATCH 1/4] Document a possible nicer way to deal with repos used for smoke tests. Currently, we're fetching them from head, which makes the smoke test run flaky as these projects change over time. --- .github/bin/smoke-test.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/bin/smoke-test.sh b/.github/bin/smoke-test.sh index e23ec5e15..3676da161 100755 --- a/.github/bin/smoke-test.sh +++ b/.github/bin/smoke-test.sh @@ -81,6 +81,9 @@ readonly VERIBLE_TOOLS_TO_RUN="syntax/verible-verilog-syntax \ # # There are some known issues which are all recorded in the associative # array below, mapping them to Verible issue tracker numbers. +# TODO(hzeller): there should be a configuration file that contains two +# columns: URL + hash, so that we can fetch a particular known version not +# a moving target. readonly TEST_GIT_PROJECTS="https://github.com/lowRISC/ibex \ https://github.com/lowRISC/opentitan \ https://github.com/chipsalliance/sv-tests \ From ca2bc19dceb2b7ca2c550561035460c49ee919fa Mon Sep 17 00:00:00 2001 From: Henner Zeller Date: Fri, 22 Nov 2024 19:04:35 -0800 Subject: [PATCH 2/4] Run clang-format and with it, fix the mixed use pointer alignments. Pointers and references should be aligned as C intends it to be. --- .github/bin/run-clang-format.sh | 7 +- common/analysis/lint_rule_status.cc | 44 +- common/analysis/lint_rule_status.h | 82 ++-- common/analysis/lint_rule_status_test.cc | 14 +- common/analysis/violation_handler.cc | 22 +- common/analysis/violation_handler.h | 50 +- common/formatting/align.cc | 278 +++++------ common/formatting/align_test.cc | 112 ++--- common/formatting/layout_optimizer.cc | 98 ++-- common/formatting/layout_optimizer_test.cc | 58 +-- common/formatting/token_partition_tree.cc | 188 ++++---- common/formatting/token_partition_tree.h | 48 +- .../formatting/token_partition_tree_test.cc | 186 ++++---- .../token_partition_tree_test_utils.cc | 12 +- common/formatting/tree_unwrapper.cc | 44 +- common/formatting/tree_unwrapper.h | 50 +- common/formatting/unwrapped_line.h | 44 +- common/text/text_structure.cc | 80 ++-- common/text/text_structure.h | 58 +-- common/text/token_info.h | 38 +- common/util/iterator_range.h | 12 +- common/util/sha256.cc | 2 +- common/util/sha256_test.cc | 2 +- common/util/tree_operations.h | 273 +++++------ common/util/tree_operations_test.cc | 124 ++--- common/util/value_saver.h | 12 +- common/util/vector_tree.h | 56 +-- .../checkers/constraint_name_style_rule.cc | 10 +- .../checkers/constraint_name_style_rule.h | 6 +- verilog/analysis/checkers/line_length_rule.cc | 6 +- verilog/analysis/checkers/line_length_rule.h | 4 +- .../checkers/line_length_rule_test.cc | 2 +- .../parameter_type_name_style_rule.cc | 8 +- .../checkers/parameter_type_name_style_rule.h | 6 +- .../checkers/struct_union_name_style_rule.cc | 24 +- .../checkers/struct_union_name_style_rule.h | 6 +- .../undersized_binary_literal_rule.cc | 18 +- .../checkers/undersized_binary_literal_rule.h | 6 +- verilog/analysis/extractors_test.cc | 6 +- verilog/analysis/flow_tree_test.cc | 28 +- verilog/analysis/lint_rule_registry.cc | 46 +- verilog/analysis/lint_rule_registry.h | 14 +- verilog/analysis/lint_rule_registry_test.cc | 30 +- verilog/analysis/symbol_table.h | 136 +++--- verilog/analysis/verilog_analyzer.cc | 48 +- verilog/analysis/verilog_analyzer_test.cc | 76 +-- verilog/formatting/align.cc | 238 +++++----- verilog/formatting/format_style.h | 2 +- verilog/formatting/formatter.cc | 182 ++++---- verilog/formatting/formatter.h | 40 +- verilog/formatting/formatter_test.cc | 82 ++-- verilog/formatting/token_annotator.cc | 88 ++-- verilog/formatting/tree_unwrapper.cc | 440 +++++++++--------- verilog/formatting/tree_unwrapper.h | 44 +- verilog/formatting/tree_unwrapper_test.cc | 110 ++--- verilog/formatting/verilog_token.cc | 2 +- verilog/parser/verilog_lexer_unittest.cc | 8 +- verilog/parser/verilog_lexical_context.cc | 12 +- verilog/parser/verilog_parser_unittest.cc | 34 +- verilog/preprocessor/verilog_preprocess.cc | 92 ++-- verilog/preprocessor/verilog_preprocess.h | 59 ++- verilog/tools/formatter/verilog_format.cc | 22 +- .../preprocessor/verilog_preprocessor.cc | 44 +- 63 files changed, 1984 insertions(+), 1989 deletions(-) diff --git a/.github/bin/run-clang-format.sh b/.github/bin/run-clang-format.sh index 7abc539c8..5d1f26225 100755 --- a/.github/bin/run-clang-format.sh +++ b/.github/bin/run-clang-format.sh @@ -25,14 +25,9 @@ ${CLANG_FORMAT} --version # Run on all files. -# For now, we only use the Google style, without enforcing the pointer -# alignment. The toplevel .clang-format will over time make files people -# edit and locally format adhere to the style. -# (TODO: once there is a quiet phase with not much PRs open, do a bulk format). - find . -name "*.h" -o -name "*.cc" \ | egrep -v 'third_party/|external_libs/|.github/' \ - | xargs -P2 ${CLANG_FORMAT} --style="Google" -i + | xargs -P2 ${CLANG_FORMAT} -i # If we have buildifier installed, use that on BUILD files if command -v ${BUILDIFIER} >/dev/null; then diff --git a/common/analysis/lint_rule_status.cc b/common/analysis/lint_rule_status.cc index dac335098..2042f45c6 100644 --- a/common/analysis/lint_rule_status.cc +++ b/common/analysis/lint_rule_status.cc @@ -42,7 +42,7 @@ namespace verible { std::string AutoFix::Apply(absl::string_view base) const { std::string result; auto prev_start = base.cbegin(); - for (const auto& edit : edits_) { + for (const auto &edit : edits_) { CHECK_LE(base.cbegin(), edit.fragment.cbegin()); CHECK_GE(base.cend(), edit.fragment.cend()); @@ -57,9 +57,9 @@ std::string AutoFix::Apply(absl::string_view base) const { return absl::StrCat(result, text_after); } -bool AutoFix::AddEdits(const std::set& new_edits) { +bool AutoFix::AddEdits(const std::set &new_edits) { // Check for conflicts - for (const auto& edit : new_edits) { + for (const auto &edit : new_edits) { if (edits_.find(edit) != edits_.end()) { return false; } @@ -68,8 +68,8 @@ bool AutoFix::AddEdits(const std::set& new_edits) { return true; } -static TokenInfo SymbolToToken(const Symbol& root) { - const auto* leaf = GetLeftmostLeaf(root); +static TokenInfo SymbolToToken(const Symbol &root) { + const auto *leaf = GetLeftmostLeaf(root); if (leaf) { return leaf->get(); } @@ -77,10 +77,10 @@ static TokenInfo SymbolToToken(const Symbol& root) { return TokenInfo::EOFToken(); } -LintViolation::LintViolation(const Symbol& root, absl::string_view reason, - const SyntaxTreeContext& context, - const std::vector& autofixes, - const std::vector& related_tokens) +LintViolation::LintViolation(const Symbol &root, absl::string_view reason, + const SyntaxTreeContext &context, + const std::vector &autofixes, + const std::vector &related_tokens) : root(&root), token(SymbolToToken(root)), reason(reason), @@ -88,11 +88,11 @@ LintViolation::LintViolation(const Symbol& root, absl::string_view reason, autofixes(autofixes), related_tokens(related_tokens) {} -void LintStatusFormatter::FormatLintRuleStatus(std::ostream* stream, - const LintRuleStatus& status, +void LintStatusFormatter::FormatLintRuleStatus(std::ostream *stream, + const LintRuleStatus &status, absl::string_view base, absl::string_view path) const { - for (const auto& violation : status.violations) { + for (const auto &violation : status.violations) { FormatViolation(stream, violation, base, path, status.url, status.lint_rule_name); (*stream) << std::endl; @@ -100,7 +100,7 @@ void LintStatusFormatter::FormatLintRuleStatus(std::ostream* stream, } std::string LintStatusFormatter::FormatWithRelatedTokens( - const std::vector& tokens, absl::string_view message, + const std::vector &tokens, absl::string_view message, absl::string_view path, absl::string_view base) const { if (tokens.empty()) { return std::string(message); @@ -108,7 +108,7 @@ std::string LintStatusFormatter::FormatWithRelatedTokens( size_t beg_pos = 0; size_t end_pos = message.find("@", beg_pos); std::ostringstream s; - for (const auto& token : tokens) { + for (const auto &token : tokens) { if (end_pos == absl::string_view::npos) { s << message.substr(beg_pos); break; @@ -129,14 +129,14 @@ std::string LintStatusFormatter::FormatWithRelatedTokens( } void LintStatusFormatter::FormatLintRuleStatuses( - std::ostream* stream, const std::vector& statuses, + std::ostream *stream, const std::vector &statuses, absl::string_view base, absl::string_view path, - const std::vector& lines) const { + const std::vector &lines) const { std::set violations; // TODO(fangism): rewrite as a linear time merge of pre-ordered sub-sequences - for (const auto& status : statuses) { - for (const auto& violation : status.violations) { + for (const auto &status : statuses) { + for (const auto &violation : status.violations) { violations.insert(LintViolationWithStatus(&violation, &status)); } } @@ -159,8 +159,8 @@ void LintStatusFormatter::FormatLintRuleStatuses( // Formats and outputs violation on stream // Path is file path of original file and url is a link to violated rule -void LintStatusFormatter::FormatViolation(std::ostream* stream, - const LintViolation& violation, +void LintStatusFormatter::FormatViolation(std::ostream *stream, + const LintViolation &violation, absl::string_view base, absl::string_view path, absl::string_view url, @@ -180,7 +180,7 @@ void LintStatusFormatter::FormatViolation(std::ostream* stream, // Formats and outputs violation to a file stream in a syntax accepted by // --waiver_files flag. Path is file path of original file void LintStatusFormatter::FormatViolationWaiver( - std::ostream* stream, const LintViolation& violation, + std::ostream *stream, const LintViolation &violation, absl::string_view base, absl::string_view path, absl::string_view rule_name) const { const verible::LineColumnRange range{ @@ -193,7 +193,7 @@ void LintStatusFormatter::FormatViolationWaiver( } void LintRuleStatus::WaiveViolations( - std::function&& is_waived) { + std::function &&is_waived) { std::set filtered_violations; std::remove_copy_if( violations.begin(), violations.end(), diff --git a/common/analysis/lint_rule_status.h b/common/analysis/lint_rule_status.h index 8d4df30fc..3ec04f6b2 100644 --- a/common/analysis/lint_rule_status.h +++ b/common/analysis/lint_rule_status.h @@ -42,13 +42,13 @@ namespace verible { // ReplacementEdit differs from editscript's Edit in that it stores a // replacement string, so it doesn't need the "after" text to be useful. struct ReplacementEdit { - ReplacementEdit(absl::string_view fragment, const std::string& replacement) + ReplacementEdit(absl::string_view fragment, const std::string &replacement) : fragment(fragment), replacement(replacement) {} - ReplacementEdit(const TokenInfo& token, const std::string& replacement) + ReplacementEdit(const TokenInfo &token, const std::string &replacement) : fragment(token.text()), replacement(replacement) {} - bool operator<(const ReplacementEdit& other) const { + bool operator<(const ReplacementEdit &other) const { // Check that the fragment is located before the other's fragment. When they // overlap, `this edits) @@ -72,16 +72,16 @@ class AutoFix { CHECK_EQ(edits_.size(), edits.size()) << "Edits must not overlap."; } - AutoFix(absl::string_view description, const ReplacementEdit& edit) + AutoFix(absl::string_view description, const ReplacementEdit &edit) : AutoFix(description, {edit}) {} // Applies the fix on a `base` and returns modified text. std::string Apply(absl::string_view base) const; - bool AddEdits(const std::set& new_edits); + bool AddEdits(const std::set &new_edits); - const std::set& Edits() const { return edits_; } - const std::string& Description() const { return description_; } + const std::set &Edits() const { return edits_; } + const std::string &Description() const { return description_; } private: std::string description_; @@ -91,9 +91,9 @@ class AutoFix { // LintViolation is a class that represents a single rule violation. struct LintViolation { // This construct records a token stream lint violation. - LintViolation(const TokenInfo& token, absl::string_view reason, - const std::vector& autofixes = {}, - const std::vector& related_tokens = {}) + LintViolation(const TokenInfo &token, absl::string_view reason, + const std::vector &autofixes = {}, + const std::vector &related_tokens = {}) : token(token), reason(reason), context(), @@ -102,16 +102,16 @@ struct LintViolation { // This construct records a token stream lint violation. // with additional tokens that might be related somehow with vulnerable token - LintViolation(const TokenInfo& token, absl::string_view reason, - const std::vector& tokens) + LintViolation(const TokenInfo &token, absl::string_view reason, + const std::vector &tokens) : token(token), reason(reason), context(), related_tokens(tokens) {} // This construct records a syntax tree lint violation. // Use this variation when the violation can be localized to a single token. - LintViolation(const TokenInfo& token, absl::string_view reason, - const SyntaxTreeContext& context, - const std::vector& autofixes = {}, - const std::vector& related_tokens = {}) + LintViolation(const TokenInfo &token, absl::string_view reason, + const SyntaxTreeContext &context, + const std::vector &autofixes = {}, + const std::vector &related_tokens = {}) : token(token), reason(reason), context(context), @@ -122,15 +122,15 @@ struct LintViolation { // Use this variation when the range of violation is a subtree that spans // multiple tokens. The violation will be reported at the location of // the left-most leaf of the subtree. - LintViolation(const Symbol& root, absl::string_view reason, - const SyntaxTreeContext& context, - const std::vector& autofixes = {}, - const std::vector& related_tokens = {}); + LintViolation(const Symbol &root, absl::string_view reason, + const SyntaxTreeContext &context, + const std::vector &autofixes = {}, + const std::vector &related_tokens = {}); // root is a reference into original ConcreteSyntaxTree that // linter was run against. LintViolations should not outlive this tree. // It should point to the root symbol that the linter failed on. - const Symbol* root = nullptr; + const Symbol *root = nullptr; // The token at which the error occurs, which includes location information. const TokenInfo token; @@ -147,7 +147,7 @@ struct LintViolation { // Additional tokens that are related somehow to offending token. const std::vector related_tokens; - bool operator<(const LintViolation& r) const { + bool operator<(const LintViolation &r) const { // compares addresses of violations, which correspond to substring // locations return token.text().data() < r.token.text().data(); @@ -158,27 +158,27 @@ struct LintViolation { struct LintRuleStatus { LintRuleStatus() = default; - LintRuleStatus(const std::set& vs, absl::string_view rule_name, - const std::string& url) + LintRuleStatus(const std::set &vs, absl::string_view rule_name, + const std::string &url) : lint_rule_name(rule_name), url(url), violations(vs) {} // TODO(hzeller): the LintRuleDescriptor is in verilog/analysis namespace, // don't want to move that to common in first step. So making this a // template for it to be a 'source code compatible' adaption. template - LintRuleStatus(const std::set& vs, - const Descriptor& descriptor) + LintRuleStatus(const std::set &vs, + const Descriptor &descriptor) : lint_rule_name(descriptor.name), url(GetStyleGuideCitation(descriptor.topic)), violations(vs) {} - explicit LintRuleStatus(const std::set& vs) : violations(vs) {} + explicit LintRuleStatus(const std::set &vs) : violations(vs) {} bool isOk() const { return violations.empty(); } // Remove subset of violations that is waived from report. // If `is_waived`() is true, remove the finding from the set of violations. - void WaiveViolations(std::function&& is_waived); + void WaiveViolations(std::function &&is_waived); // Name of the lint rule that produced this status. absl::string_view lint_rule_name; @@ -191,13 +191,13 @@ struct LintRuleStatus { }; struct LintViolationWithStatus { - const LintViolation* violation; - const LintRuleStatus* status; + const LintViolation *violation; + const LintRuleStatus *status; - LintViolationWithStatus(const LintViolation* v, const LintRuleStatus* s) + LintViolationWithStatus(const LintViolation *v, const LintRuleStatus *s) : violation(v), status(s) {} - bool operator<(const LintViolationWithStatus& r) const { + bool operator<(const LintViolationWithStatus &r) const { // compares addresses which correspond to locations within the same string return violation->token.text().data() < r.violation->token.text().data(); } @@ -223,7 +223,7 @@ class LintStatusFormatter { // contained in status. // Base is the string_view of the entire contents, used only for byte offset // calculation. - void FormatLintRuleStatus(std::ostream* stream, const LintRuleStatus& status, + void FormatLintRuleStatus(std::ostream *stream, const LintRuleStatus &status, absl::string_view base, absl::string_view path) const; @@ -236,16 +236,16 @@ class LintStatusFormatter { // Base is the string_view of the entire contents, used only for byte offset // calculation. void FormatLintRuleStatuses( - std::ostream* stream, const std::vector& statuses, + std::ostream *stream, const std::vector &statuses, absl::string_view base, absl::string_view path, - const std::vector& lines) const; + const std::vector &lines) const; // Formats and outputs violation on stream. // Path is file path of original file and url is a link to the ratified rule // that is being violated. // Base is the string_view of the entire contents, used only for byte offset // calculation. - void FormatViolation(std::ostream* stream, const LintViolation& violation, + void FormatViolation(std::ostream *stream, const LintViolation &violation, absl::string_view base, absl::string_view path, absl::string_view url, absl::string_view rule_name) const; @@ -254,8 +254,8 @@ class LintStatusFormatter { // --waiver_files flag. Path is file path of original file that is being // violated. Base is the string_view of the entire contents, used only for // byte offset calculation. - void FormatViolationWaiver(std::ostream* stream, - const LintViolation& violation, + void FormatViolationWaiver(std::ostream *stream, + const LintViolation &violation, absl::string_view base, absl::string_view path, absl::string_view rule_name) const; // Substitute the markers \@ with tokens location @@ -264,7 +264,7 @@ class LintStatusFormatter { // vulnerable token. It is important to note that all the tokens // must come from the same file. std::string FormatWithRelatedTokens( - const std::vector& tokens, absl::string_view message, + const std::vector &tokens, absl::string_view message, absl::string_view path, absl::string_view base) const; private: diff --git a/common/analysis/lint_rule_status_test.cc b/common/analysis/lint_rule_status_test.cc index 7a5f253e7..31c480da7 100644 --- a/common/analysis/lint_rule_status_test.cc +++ b/common/analysis/lint_rule_status_test.cc @@ -59,11 +59,11 @@ TEST(LintRuleStatusTest, WaiveViolations) { EXPECT_FALSE(status.violations.empty()); EXPECT_FALSE(status.isOk()); // First, waive nothing. - status.WaiveViolations([](const LintViolation&) { return false; }); + status.WaiveViolations([](const LintViolation &) { return false; }); EXPECT_FALSE(status.violations.empty()); EXPECT_FALSE(status.isOk()); // Second, waive everything. - status.WaiveViolations([](const LintViolation&) { return true; }); + status.WaiveViolations([](const LintViolation &) { return true; }); EXPECT_TRUE(status.violations.empty()); EXPECT_TRUE(status.isOk()); } @@ -89,14 +89,14 @@ struct LintStatusTest { std::vector violations; }; -void RunLintStatusTest(const LintStatusTest& test) { +void RunLintStatusTest(const LintStatusTest &test) { // Dummy tree so we have something for test cases to point at SymbolPtr root = Node(); LintRuleStatus status; status.url = test.url; status.lint_rule_name = test.rule_name; - for (const auto& violation_test : test.violations) { + for (const auto &violation_test : test.violations) { status.violations.insert(LintViolation(violation_test.token, violation_test.reason, {}, violation_test.related_tokens)); @@ -109,7 +109,7 @@ void RunLintStatusTest(const LintStatusTest& test) { auto result_parts = absl::StrSplit(ss.str(), '\n'); auto part_iterator = result_parts.begin(); - for (const auto& violation_test : test.violations) { + for (const auto &violation_test : test.violations) { EXPECT_EQ(*part_iterator, violation_test.expected_output); part_iterator++; } @@ -192,7 +192,7 @@ TEST(LintRuleStatusFormatterTest, NoOutput) { RunLintStatusTest(test); } -void RunLintStatusesTest(const LintStatusTest& test, bool show_context) { +void RunLintStatusesTest(const LintStatusTest &test, bool show_context) { // Dummy tree so we have something for test cases to point at SymbolPtr root = Node(); @@ -237,7 +237,7 @@ void RunLintStatusesTest(const LintStatusTest& test, bool show_context) { auto part_iterator = result_parts.begin(); - for (const auto& violation_test : test.violations) { + for (const auto &violation_test : test.violations) { EXPECT_EQ(*part_iterator, violation_test.expected_output); part_iterator++; } diff --git a/common/analysis/violation_handler.cc b/common/analysis/violation_handler.cc index 85d405422..90e369182 100644 --- a/common/analysis/violation_handler.cc +++ b/common/analysis/violation_handler.cc @@ -34,16 +34,16 @@ namespace verible { namespace { -void PrintFix(std::ostream& stream, absl::string_view text, - const verible::AutoFix& fix) { +void PrintFix(std::ostream &stream, absl::string_view text, + const verible::AutoFix &fix) { std::string after = fix.Apply(text); verible::LineDiffs diff(text, after); verible::LineDiffsToUnifiedDiff(stream, diff, 1); } -void PrintFixAlternatives(std::ostream& stream, absl::string_view text, - const std::vector& fixes) { +void PrintFixAlternatives(std::ostream &stream, absl::string_view text, + const std::vector &fixes) { const bool print_alternative_number = fixes.size() > 1; for (size_t i = 0; i < fixes.size(); ++i) { if (print_alternative_number) { @@ -61,7 +61,7 @@ void PrintFixAlternatives(std::ostream& stream, absl::string_view text, } // namespace void ViolationPrinter::HandleViolations( - const std::set& violations, absl::string_view base, + const std::set &violations, absl::string_view base, absl::string_view path) { verible::LintStatusFormatter formatter(base); for (auto violation : violations) { @@ -73,7 +73,7 @@ void ViolationPrinter::HandleViolations( } void ViolationWaiverPrinter::HandleViolations( - const std::set& violations, absl::string_view base, + const std::set &violations, absl::string_view base, absl::string_view path) { verible::LintStatusFormatter formatter(base); for (auto violation : violations) { @@ -90,7 +90,7 @@ void ViolationWaiverPrinter::HandleViolations( void ViolationFixer::CommitFixes(absl::string_view source_content, absl::string_view source_path, - const verible::AutoFix& fix) const { + const verible::AutoFix &fix) const { if (fix.Edits().empty()) { return; } @@ -111,7 +111,7 @@ void ViolationFixer::CommitFixes(absl::string_view source_content, } void ViolationFixer::HandleViolations( - const std::set& violations, absl::string_view base, + const std::set &violations, absl::string_view base, absl::string_view path) { verible::AutoFix fix; verible::LintStatusFormatter formatter(base); @@ -124,9 +124,9 @@ void ViolationFixer::HandleViolations( } void ViolationFixer::HandleViolation( - const verible::LintViolation& violation, absl::string_view base, + const verible::LintViolation &violation, absl::string_view base, absl::string_view path, absl::string_view url, absl::string_view rule_name, - const verible::LintStatusFormatter& formatter, verible::AutoFix* fix) { + const verible::LintStatusFormatter &formatter, verible::AutoFix *fix) { std::stringstream violation_message; formatter.FormatViolation(&violation_message, violation, base, path, url, rule_name); @@ -198,7 +198,7 @@ void ViolationFixer::HandleViolation( } ViolationFixer::Answer ViolationFixer::InteractiveAnswerChooser( - const verible::LintViolation& violation, absl::string_view rule_name) { + const verible::LintViolation &violation, absl::string_view rule_name) { static absl::string_view fixed_help_message = "n - reject fix\n" "a - apply this and all remaining fixes for violations of this rule\n" diff --git a/common/analysis/violation_handler.h b/common/analysis/violation_handler.h index 8886b314a..368d50f14 100644 --- a/common/analysis/violation_handler.h +++ b/common/analysis/violation_handler.h @@ -39,7 +39,7 @@ class ViolationHandler { // located at `path`. It can be called multiple times with statuses generated // from different files. `base` contains source code from the file. virtual void HandleViolations( - const std::set& violations, + const std::set &violations, absl::string_view base, absl::string_view path) = 0; }; @@ -47,33 +47,33 @@ class ViolationHandler { // messages. class ViolationPrinter : public ViolationHandler { public: - explicit ViolationPrinter(std::ostream* stream) : stream_(stream) {} + explicit ViolationPrinter(std::ostream *stream) : stream_(stream) {} void HandleViolations( - const std::set& violations, + const std::set &violations, absl::string_view base, absl::string_view path) final; protected: - std::ostream* const stream_; - verible::LintStatusFormatter* formatter_ = nullptr; + std::ostream *const stream_; + verible::LintStatusFormatter *formatter_ = nullptr; }; // ViolationHandler that prints all violations in a format required by // --waiver_files flag class ViolationWaiverPrinter : public ViolationHandler { public: - explicit ViolationWaiverPrinter(std::ostream* message_stream_, - std::ostream* waiver_stream_) + explicit ViolationWaiverPrinter(std::ostream *message_stream_, + std::ostream *waiver_stream_) : message_stream_(message_stream_), waiver_stream_(waiver_stream_) {} void HandleViolations( - const std::set& violations, + const std::set &violations, absl::string_view base, absl::string_view path) final; protected: - std::ostream* const message_stream_; - std::ostream* const waiver_stream_; - verible::LintStatusFormatter* formatter_ = nullptr; + std::ostream *const message_stream_; + std::ostream *const waiver_stream_; + verible::LintStatusFormatter *formatter_ = nullptr; }; // ViolationHandler that prints all violations and gives an option to fix those @@ -117,46 +117,46 @@ class ViolationFixer : public verible::ViolationHandler { }; using AnswerChooser = - std::function; + std::function; // Violation fixer with user-chosen answer chooser. - ViolationFixer(std::ostream* message_stream, std::ostream* patch_stream, - const AnswerChooser& answer_chooser) + ViolationFixer(std::ostream *message_stream, std::ostream *patch_stream, + const AnswerChooser &answer_chooser) : ViolationFixer(message_stream, patch_stream, answer_chooser, false) {} // Violation fixer with interactive answer choice. - ViolationFixer(std::ostream* message_stream, std::ostream* patch_stream) + ViolationFixer(std::ostream *message_stream, std::ostream *patch_stream) : ViolationFixer(message_stream, patch_stream, InteractiveAnswerChooser, true) {} void HandleViolations( - const std::set& violations, + const std::set &violations, absl::string_view base, absl::string_view path) final; private: - ViolationFixer(std::ostream* message_stream, std::ostream* patch_stream, - const AnswerChooser& answer_chooser, bool is_interactive) + ViolationFixer(std::ostream *message_stream, std::ostream *patch_stream, + const AnswerChooser &answer_chooser, bool is_interactive) : message_stream_(message_stream), patch_stream_(patch_stream), answer_chooser_(answer_chooser), is_interactive_(is_interactive), ultimate_answer_({AnswerChoice::kUnknown, 0}) {} - void HandleViolation(const verible::LintViolation& violation, + void HandleViolation(const verible::LintViolation &violation, absl::string_view base, absl::string_view path, absl::string_view url, absl::string_view rule_name, - const verible::LintStatusFormatter& formatter, - verible::AutoFix* fix); + const verible::LintStatusFormatter &formatter, + verible::AutoFix *fix); static Answer InteractiveAnswerChooser( - const verible::LintViolation& violation, absl::string_view rule_name); + const verible::LintViolation &violation, absl::string_view rule_name); void CommitFixes(absl::string_view source_content, absl::string_view source_path, - const verible::AutoFix& fix) const; + const verible::AutoFix &fix) const; - std::ostream* const message_stream_; - std::ostream* const patch_stream_; + std::ostream *const message_stream_; + std::ostream *const patch_stream_; const AnswerChooser answer_chooser_; const bool is_interactive_; diff --git a/common/formatting/align.cc b/common/formatting/align.cc index 06569d226..19b9fd8b9 100644 --- a/common/formatting/align.cc +++ b/common/formatting/align.cc @@ -53,7 +53,7 @@ namespace verible { -static const verible::EnumNameMap& AlignmentPolicyNameMap() { +static const verible::EnumNameMap &AlignmentPolicyNameMap() { static const verible::EnumNameMap kAlignmentPolicyNameMap({ {"align", AlignmentPolicy::kAlign}, {"flush-left", AlignmentPolicy::kFlushLeft}, @@ -64,29 +64,29 @@ static const verible::EnumNameMap& AlignmentPolicyNameMap() { return kAlignmentPolicyNameMap; } -std::ostream& operator<<(std::ostream& stream, AlignmentPolicy policy) { +std::ostream &operator<<(std::ostream &stream, AlignmentPolicy policy) { return AlignmentPolicyNameMap().Unparse(policy, stream); } -bool AbslParseFlag(absl::string_view text, AlignmentPolicy* policy, - std::string* error) { +bool AbslParseFlag(absl::string_view text, AlignmentPolicy *policy, + std::string *error) { return AlignmentPolicyNameMap().Parse(text, policy, error, "AlignmentPolicy"); } -std::string AbslUnparseFlag(const AlignmentPolicy& policy) { +std::string AbslUnparseFlag(const AlignmentPolicy &policy) { std::ostringstream stream; stream << policy; return stream.str(); } -static int EffectiveCellWidth(const FormatTokenRange& tokens) { +static int EffectiveCellWidth(const FormatTokenRange &tokens) { if (tokens.empty()) return 0; VLOG(2) << __FUNCTION__; // Sum token text lengths plus required pre-spacings (except first token). // Note: LeadingSpacesLength() honors where original spacing when preserved. return std::accumulate( tokens.begin(), tokens.end(), -tokens.front().LeadingSpacesLength(), - [](int total_width, const PreFormatToken& ftoken) { + [](int total_width, const PreFormatToken &ftoken) { const int pre_width = ftoken.LeadingSpacesLength(); const int text_length = ftoken.token->text().length(); VLOG(2) << " +" << pre_width << " +" << text_length; @@ -96,7 +96,7 @@ static int EffectiveCellWidth(const FormatTokenRange& tokens) { }); } -static int EffectiveLeftBorderWidth(const FormatTokenRange& tokens) { +static int EffectiveLeftBorderWidth(const FormatTokenRange &tokens) { if (tokens.empty()) return 0; return tokens.front().before.spaces_required; } @@ -132,11 +132,11 @@ struct AlignmentCell { using AlignmentRow = VectorTree; using AlignmentMatrix = std::vector; -std::ostream& operator<<(std::ostream& stream, const AlignmentCell& cell) { +std::ostream &operator<<(std::ostream &stream, const AlignmentCell &cell) { if (!cell.tokens.empty()) { // See UnwrappedLine::AsCode for similar printing. stream << absl::StrJoin(cell.tokens, " ", - [](std::string* out, const PreFormatToken& token) { + [](std::string *out, const PreFormatToken &token) { absl::StrAppend(out, token.Text()); }); } @@ -150,25 +150,25 @@ std::ostream& operator<<(std::ostream& stream, const AlignmentCell& cell) { // a filler for cell's empty space. template using CellLabelGetterFunc = - std::function(const VectorTree&)>; + std::function(const VectorTree &)>; // Recursively creates a tree with cells textual data. Its main purpose is to // split multi-line cell labels and calculate how many lines have to be printed. // This is a helper function used in ColumsTreeFormatter. template static std::size_t CreateTextNodes( - const VectorTree& src_node, VectorTree* dst_node, - const CellLabelGetterFunc& get_cell_label) { + const VectorTree &src_node, VectorTree *dst_node, + const CellLabelGetterFunc &get_cell_label) { static constexpr std::size_t kMinCellWidth = 2; std::size_t depth = 0; std::size_t subtree_depth = 0; - for (const auto& src_child : src_node.Children()) { + for (const auto &src_child : src_node.Children()) { const auto [text, filler] = get_cell_label(src_child); const std::vector lines = absl::StrSplit(text, '\n'); - auto* dst_child = dst_node; - for (const auto& line : lines) { + auto *dst_child = dst_node; + for (const auto &line : lines) { dst_child->Children().emplace_back( Cell{line, filler, std::max(line.size(), kMinCellWidth)}); dst_child = &dst_child->Children().back(); @@ -191,8 +191,8 @@ static std::size_t CreateTextNodes( // to the right. Empty space is filled with label's filler character. template static void ColumnsTreeFormatter( - std::ostream& stream, const VectorTree& root, - const CellLabelGetterFunc& get_cell_label) { + std::ostream &stream, const VectorTree &root, + const CellLabelGetterFunc &get_cell_label) { if (root.Children().empty()) return; static constexpr absl::string_view kCellSeparator = "|"; @@ -208,13 +208,13 @@ static void ColumnsTreeFormatter( CreateTextNodes(root, &text_tree, get_cell_label); // Adjust cells width to fit all their children - for (auto& node : VectorTreePostOrderTraversal(text_tree)) { + for (auto &node : VectorTreePostOrderTraversal(text_tree)) { // Include separator width in cell width node.Value().width += kCellSeparator.size(); if (is_leaf(node)) continue; const std::size_t children_width = std::accumulate(node.Children().begin(), node.Children().end(), 0, - [](std::size_t width, const VectorTree& child) { + [](std::size_t width, const VectorTree &child) { return width + child.Value().width; }); if (node.Value().width < children_width) { @@ -222,11 +222,11 @@ static void ColumnsTreeFormatter( } } // Adjust cells width to fill their parents - for (auto& node : VectorTreePreOrderTraversal(text_tree)) { + for (auto &node : VectorTreePreOrderTraversal(text_tree)) { if (is_leaf(node)) continue; std::size_t children_width = std::accumulate(node.Children().begin(), node.Children().end(), 0, - [](std::size_t width, const VectorTree& child) { + [](std::size_t width, const VectorTree &child) { return width + child.Value().width; }); // There is at least one child; each cell minimum width is equal to: @@ -234,7 +234,7 @@ static void ColumnsTreeFormatter( CHECK_GT(children_width, 0); if (node.Value().width > children_width) { auto extra_width = node.Value().width - children_width; - for (auto& child : node.Children()) { + for (auto &child : node.Children()) { CHECK_GT(children_width, 0); const auto added_child_width = extra_width * child.Value().width / children_width; // NOLINT @@ -248,8 +248,8 @@ static void ColumnsTreeFormatter( std::vector lines(depth); auto range = VectorTreePreOrderTraversal(text_tree); auto level_offset = NumAncestors(text_tree) + 1; - for (auto& node : make_range(range.begin() + 1, range.end())) { - auto& cell = node.Value(); + for (auto &node : make_range(range.begin() + 1, range.end())) { + auto &cell = node.Value(); const std::size_t level = NumAncestors(node) - level_offset; if (level > 0 && verible::IsFirstChild(node)) { const int padding_len = lines[level - 1].size() - lines[level].size() - @@ -298,7 +298,7 @@ static void ColumnsTreeFormatter( CHECK_LE(parts.size(), 3); } } - for (const auto& line : lines) { + for (const auto &line : lines) { if (!line.empty()) stream << line << kCellSeparator << "\n"; } } @@ -310,20 +310,20 @@ struct AlignedColumnConfiguration { int TotalWidth() const { return left_border + width; } - void UpdateFromCell(const AlignmentCell& cell) { + void UpdateFromCell(const AlignmentCell &cell) { width = std::max(width, cell.compact_width); left_border = std::max(left_border, cell.left_border_width); } }; -/* static */ ColumnPositionTree* ColumnSchemaScanner::ReserveNewColumn( - ColumnPositionTree* parent_column, const Symbol& symbol, - const AlignmentColumnProperties& properties, const SyntaxTreePath& path) { +/* static */ ColumnPositionTree *ColumnSchemaScanner::ReserveNewColumn( + ColumnPositionTree *parent_column, const Symbol &symbol, + const AlignmentColumnProperties &properties, const SyntaxTreePath &path) { CHECK_NOTNULL(parent_column); // The path helps establish a total ordering among all desired alignment // points, given that they may come from optional or repeated language // constructs. - const SyntaxTreeLeaf* leaf = GetLeftmostLeaf(symbol); + const SyntaxTreeLeaf *leaf = GetLeftmostLeaf(symbol); // It is possible for a node to be empty, in which case, ignore. if (leaf == nullptr) return nullptr; if (parent_column->Parent() != nullptr && parent_column->Children().empty()) { @@ -339,7 +339,7 @@ struct AlignedColumnConfiguration { parent_column->Children().back().Value().path != path) { parent_column->Children().emplace_back( ColumnPositionEntry{path, leaf->get(), properties}); - const auto& column = parent_column->Children().back(); + const auto &column = parent_column->Children().back(); ColumnsTreePath column_path; verible::Path(column, column_path); VLOG(2) << "reserving new column for " << TreePathFormatter(path) << " at " @@ -359,7 +359,7 @@ struct AggregateColumnData { SyntaxTreePath path; - void Import(const ColumnPositionEntry& cell) { + void Import(const ColumnPositionEntry &cell) { if (starting_tokens.empty()) { path = cell.path; // Take the first set of properties, and ignore the rest. @@ -373,7 +373,7 @@ struct AggregateColumnData { class ColumnSchemaAggregator { public: - void Collect(const ColumnPositionTree& columns) { + void Collect(const ColumnPositionTree &columns) { CollectColumnsTree(columns, &columns_); } @@ -382,7 +382,7 @@ class ColumnSchemaAggregator { void Finalize() { syntax_to_columns_map_.clear(); - for (auto& node : VectorTreePreOrderTraversal(columns_)) { + for (auto &node : VectorTreePreOrderTraversal(columns_)) { if (node.Parent()) { // Index the column auto it = syntax_to_columns_map_.emplace_hint( @@ -393,11 +393,11 @@ class ColumnSchemaAggregator { // Sort subcolumns. This puts negative paths (leading non-tree token // columns) before empty, zero, and positive ones. std::sort(node.Children().begin(), node.Children().end(), - [](const auto& a, const auto& b) { + [](const auto &a, const auto &b) { return a.Value().path < b.Value().path; }); // Propagate left_border_override property to the left subcolumn - auto& left_child_data = node.Children().front().Value(); + auto &left_child_data = node.Children().front().Value(); left_child_data.properties.left_border_override = std::max(left_child_data.properties.left_border_override, node.Value().properties.left_border_override); @@ -405,27 +405,27 @@ class ColumnSchemaAggregator { } } - const std::map& SyntaxToColumnsMap() const { + const std::map &SyntaxToColumnsMap() const { return syntax_to_columns_map_; } - const VectorTree& Columns() const { return columns_; } + const VectorTree &Columns() const { return columns_; } VectorTree ColumnProperties() const { return Transform>( - columns_, [](const VectorTree& data_node) { + columns_, [](const VectorTree &data_node) { return data_node.Value().properties; }); } private: - void CollectColumnsTree(const ColumnPositionTree& column, - VectorTree* aggregate_column) { + void CollectColumnsTree(const ColumnPositionTree &column, + VectorTree *aggregate_column) { CHECK_NOTNULL(aggregate_column); - for (const auto& subcolumn : column.Children()) { + for (const auto &subcolumn : column.Children()) { const auto [index_entry, insert] = syntax_to_columns_map_.try_emplace(subcolumn.Value().path); - VectorTree* aggregate_subcolumn; + VectorTree *aggregate_subcolumn; if (insert) { aggregate_column->Children().emplace_back(); aggregate_subcolumn = &aggregate_column->Children().back(); @@ -458,13 +458,13 @@ class ColumnSchemaAggregator { // `T` should be either AggregateColumnData or ColumnPositionEntry. template static std::pair GetColumnDataCellLabel( - const VectorTree& node) { + const VectorTree &node) { std::ostringstream label; - const SyntaxTreePath& path = node.Value().path; + const SyntaxTreePath &path = node.Value().path; auto begin = path.begin(); if (node.Parent()) { // Find and skip common prefix - const auto& parent_path = node.Parent()->Value().path; + const auto &parent_path = node.Parent()->Value().path; auto parent_begin = parent_path.begin(); while (begin != path.end() && parent_begin != parent_path.end() && *begin == *parent_begin) { @@ -481,26 +481,26 @@ static std::pair GetColumnDataCellLabel( return {label.str(), node.Value().properties.flush_left ? '<' : '>'}; } -std::ostream& operator<<(std::ostream& stream, - const VectorTree& tree) { +std::ostream &operator<<(std::ostream &stream, + const VectorTree &tree) { ColumnsTreeFormatter( stream, tree, GetColumnDataCellLabel); return stream; } -std::ostream& operator<<(std::ostream& stream, const ColumnPositionTree& tree) { +std::ostream &operator<<(std::ostream &stream, const ColumnPositionTree &tree) { ColumnsTreeFormatter( stream, tree, GetColumnDataCellLabel); return stream; } -std::ostream& operator<<(std::ostream& stream, - const VectorTree& tree) { +std::ostream &operator<<(std::ostream &stream, + const VectorTree &tree) { ColumnsTreeFormatter( stream, tree, - [](const VectorTree& node) + [](const VectorTree &node) -> std::pair { - const auto& cell = node.Value(); + const auto &cell = node.Value(); if (cell.IsUnused()) { return {"", '.'}; } @@ -516,11 +516,11 @@ std::ostream& operator<<(std::ostream& stream, return stream; } -std::ostream& operator<<(std::ostream& stream, - const VectorTree& tree) { +std::ostream &operator<<(std::ostream &stream, + const VectorTree &tree) { ColumnsTreeFormatter( - stream, tree, [](const VectorTree& node) { - const auto& cell = node.Value(); + stream, tree, [](const VectorTree &node) { + const auto &cell = node.Value(); const auto label = absl::StrCat("\t", cell.left_border, "+", cell.width, "\t"); return std::pair{label, ' '}; @@ -538,21 +538,21 @@ struct AlignmentRowData { }; static void FillAlignmentRow( - const AlignmentRowData& row_data, - const std::map& columns_map, - AlignmentRow* row) { - const auto& sparse_columns(row_data.sparse_columns); + const AlignmentRowData &row_data, + const std::map &columns_map, + AlignmentRow *row) { + const auto &sparse_columns(row_data.sparse_columns); FormatTokenRange remaining_tokens_range(row_data.ftoken_range); - FormatTokenRange* prev_cell_tokens = nullptr; + FormatTokenRange *prev_cell_tokens = nullptr; if (!is_leaf(sparse_columns)) { - for (const auto& col : VectorTreeLeavesTraversal(sparse_columns)) { + for (const auto &col : VectorTreeLeavesTraversal(sparse_columns)) { const auto column_loc_iter = columns_map.find(col.Value().path); CHECK(column_loc_iter != columns_map.end()); const auto token_iter = std::find_if( remaining_tokens_range.begin(), remaining_tokens_range.end(), - [=](const PreFormatToken& ftoken) { + [=](const PreFormatToken &ftoken) { return BoundsEqual(ftoken.Text(), col.Value().starting_token.text()); }); @@ -561,7 +561,7 @@ static void FillAlignmentRow( if (prev_cell_tokens != nullptr) prev_cell_tokens->set_end(token_iter); - AlignmentRow& row_cell = verible::DescendPath( + AlignmentRow &row_cell = verible::DescendPath( *row, column_loc_iter->second.begin(), column_loc_iter->second.end()); row_cell.Value().tokens = remaining_tokens_range; prev_cell_tokens = &row_cell.Value().tokens; @@ -571,13 +571,13 @@ static void FillAlignmentRow( // Recursively calculates widths of each cell's subcells and, if needed, updates // cell's width to fit all subcells. -static void UpdateAndPropagateRowCellWidths(AlignmentRow* node) { +static void UpdateAndPropagateRowCellWidths(AlignmentRow *node) { node->Value().UpdateWidths(); if (is_leaf(*node)) return; int total_width = 0; - for (auto& child : node->Children()) { + for (auto &child : node->Children()) { UpdateAndPropagateRowCellWidths(&child); total_width += child.Value().TotalWidth(); } @@ -589,14 +589,14 @@ static void UpdateAndPropagateRowCellWidths(AlignmentRow* node) { } } -static void ComputeRowCellWidths(AlignmentRow* row) { +static void ComputeRowCellWidths(AlignmentRow *row) { VLOG(2) << __FUNCTION__; UpdateAndPropagateRowCellWidths(row); // Force leftmost table border to be 0 because these cells start new lines // and thus should not factor into alignment calculation. // Note: this is different from how StateNode calculates column positions. - auto* front = row; + auto *front = row; while (!front->Children().empty()) { front = &front->Children().front(); front->Value().left_border_width = 0; @@ -607,26 +607,26 @@ static void ComputeRowCellWidths(AlignmentRow* row) { using AlignedFormattingColumnSchema = VectorTree; static AlignedFormattingColumnSchema ComputeColumnWidths( - const AlignmentMatrix& matrix, - const VectorTree& column_properties) { + const AlignmentMatrix &matrix, + const VectorTree &column_properties) { VLOG(2) << __FUNCTION__; AlignedFormattingColumnSchema column_configs = Transform( matrix.front(), - [](const AlignmentRow&) { return AlignedColumnConfiguration{}; }); + [](const AlignmentRow &) { return AlignedColumnConfiguration{}; }); // Check which cell before delimiter is the longest // If this cell is in the last row, the sizes of column with delimiter // must be set to 0 int longest_cell_before_delimiter = 0; bool align_to_last_row = false; - for (const AlignmentRow& row : matrix) { + for (const AlignmentRow &row : matrix) { auto column_prop_iter = VectorTreePreOrderTraversal(column_properties).begin(); const auto column_prop_end = VectorTreePreOrderTraversal(column_properties).end(); - for (const auto& node : VectorTreePreOrderTraversal(row)) { + for (const auto &node : VectorTreePreOrderTraversal(row)) { const auto next_prop = std::next(column_prop_iter, 1); if (next_prop != column_prop_end && next_prop->Value().contains_delimiter) { @@ -640,12 +640,12 @@ static AlignedFormattingColumnSchema ComputeColumnWidths( } } - for (const AlignmentRow& row : matrix) { + for (const AlignmentRow &row : matrix) { auto column_iter = VectorTreePreOrderTraversal(column_configs).begin(); auto column_prop_iter = VectorTreePreOrderTraversal(column_properties).begin(); - for (const auto& node : VectorTreePreOrderTraversal(row)) { + for (const auto &node : VectorTreePreOrderTraversal(row)) { if (column_prop_iter->Value().contains_delimiter && align_to_last_row) { column_iter->Value().width = 0; column_iter->Value().left_border = 0; @@ -663,11 +663,11 @@ static AlignedFormattingColumnSchema ComputeColumnWidths( } // Make sure columns are wide enough to fit all their subcolumns - for (auto& column_iter : VectorTreePostOrderTraversal(column_configs)) { + for (auto &column_iter : VectorTreePostOrderTraversal(column_configs)) { if (!is_leaf(column_iter)) { int children_width = std::accumulate( column_iter.Children().begin(), column_iter.Children().end(), 0, - [](int width, const AlignedFormattingColumnSchema& node) { + [](int width, const AlignedFormattingColumnSchema &node) { return width + node.Value().TotalWidth(); }); column_iter.Value().left_border = @@ -703,10 +703,10 @@ struct DeferredTokenAlignment { }; static void ComputeAlignedRowCellSpacings( - const VectorTree& column_configs, - const VectorTree& properties, - const AlignmentRow& row, std::vector* align_actions, - int* accrued_spaces) { + const VectorTree &column_configs, + const VectorTree &properties, + const AlignmentRow &row, std::vector *align_actions, + int *accrued_spaces) { ColumnsTreePath node_path; verible::Path(row, node_path); VLOG(2) << TreePathFormatter(node_path) << " " << __FUNCTION__ << std::endl; @@ -715,7 +715,7 @@ static void ComputeAlignedRowCellSpacings( auto column_config_it = column_configs.Children().begin(); auto column_properties_it = properties.Children().begin(); - for (const auto& cell : row.Children()) { + for (const auto &cell : row.Children()) { node_path.clear(); verible::Path(cell, node_path); if (cell.Value().IsUnused()) { @@ -732,7 +732,7 @@ static void ComputeAlignedRowCellSpacings( const int subcolumns_width = std::accumulate( column_config_it->Children().begin(), column_config_it->Children().end(), 0, - [](int width, const VectorTree& node) { + [](int width, const VectorTree &node) { return width + node.Value().TotalWidth(); }); const int padding = @@ -783,9 +783,9 @@ static void ComputeAlignedRowCellSpacings( // Align cells by adjusting pre-token spacing for a single row. static std::vector ComputeAlignedRowSpacings( - const VectorTree& column_configs, - const VectorTree& properties, - const AlignmentRow& row) { + const VectorTree &column_configs, + const VectorTree &properties, + const AlignmentRow &row) { VLOG(2) << __FUNCTION__ << "; row:\n" << row; std::vector align_actions; int accrued_spaces = 0; @@ -797,10 +797,10 @@ static std::vector ComputeAlignedRowSpacings( return align_actions; } -static const AlignmentRow* RightmostSubcolumnWithTokens( - const AlignmentRow& node) { +static const AlignmentRow *RightmostSubcolumnWithTokens( + const AlignmentRow &node) { if (!node.Value().tokens.empty()) return &node; - for (const auto& child : reversed_view(node.Children())) { + for (const auto &child : reversed_view(node.Children())) { if (child.Value().TotalWidth() > 0) { return RightmostSubcolumnWithTokens(child); } @@ -808,8 +808,8 @@ static const AlignmentRow* RightmostSubcolumnWithTokens( return nullptr; } -static FormatTokenRange EpilogRange(const TokenPartitionTree& partition, - const AlignmentRow& last_subcol) { +static FormatTokenRange EpilogRange(const TokenPartitionTree &partition, + const AlignmentRow &last_subcol) { // Identify the unaligned epilog tokens of this 'partition', i.e. those not // spanned by 'row'. auto partition_end = partition.Value().TokensRange().end(); @@ -820,11 +820,11 @@ static FormatTokenRange EpilogRange(const TokenPartitionTree& partition, // This width calculation accounts for the unaligned tokens in the tail position // of each aligned row (e.g. unaligned trailing comments). static bool AlignedRowsFitUnderColumnLimit( - const std::vector& rows, - const AlignmentMatrix& matrix, int total_column_width, int column_limit) { + const std::vector &rows, + const AlignmentMatrix &matrix, int total_column_width, int column_limit) { auto partition_iter = rows.begin(); - for (const auto& row : matrix) { - const auto* rightmost_subcolumn = RightmostSubcolumnWithTokens(row); + for (const auto &row : matrix) { + const auto *rightmost_subcolumn = RightmostSubcolumnWithTokens(row); if (rightmost_subcolumn) { // Identify the unaligned epilog text on each partition. const FormatTokenRange epilog_range( @@ -853,8 +853,8 @@ struct AlignablePartitionGroup::GroupAlignmentData { int MaxAbsoluteAlignVsFlushLeftSpacingDifference() const { int result = std::numeric_limits::min(); - for (const auto& align_actions : align_actions_2D) { - for (const auto& action : align_actions) { + for (const auto &align_actions : align_actions_2D) { + for (const auto &action : align_actions) { int abs_diff = std::abs(action.AlignVsFlushLeftSpacingDifference()); result = std::max(abs_diff, result); } @@ -863,13 +863,13 @@ struct AlignablePartitionGroup::GroupAlignmentData { } AlignmentPolicy InferUserIntendedAlignmentPolicy( - const TokenPartitionRange& partitions) const; + const TokenPartitionRange &partitions) const; }; AlignablePartitionGroup::GroupAlignmentData AlignablePartitionGroup::CalculateAlignmentSpacings( - const std::vector& rows, - const AlignmentCellScannerFunction& cell_scanner_gen, int column_limit) { + const std::vector &rows, + const AlignmentCellScannerFunction &cell_scanner_gen, int column_limit) { VLOG(1) << __FUNCTION__; GroupAlignmentData result; // Alignment requires 2+ rows. @@ -886,9 +886,9 @@ AlignablePartitionGroup::CalculateAlignmentSpacings( // Simultaneously step through each node's tree, adding a column to the // schema if *any* row wants it. This captures optional and repeated // constructs. - for (const auto& row : rows) { + for (const auto &row : rows) { // Each row should correspond to an individual list element - const UnwrappedLine& unwrapped_line = row->Value(); + const UnwrappedLine &unwrapped_line = row->Value(); // Scan each token-range for cell boundaries based on syntax, // and establish partial ordering based on syntax tree paths. @@ -896,7 +896,7 @@ AlignablePartitionGroup::CalculateAlignmentSpacings( // Make sure columns are properly ordered. std::sort( sparse_columns.Children().begin(), sparse_columns.Children().end(), - [](const auto& a, const auto& b) { + [](const auto &a, const auto &b) { return CompareSyntaxTreePath(a.Value().path, b.Value().path) < 0; }); const AlignmentRowData row_data{ @@ -920,16 +920,16 @@ AlignablePartitionGroup::CalculateAlignmentSpacings( result.matrix.resize(rows.size()); { auto row_data_iter = alignment_row_data.cbegin(); - for (auto& row : result.matrix) { + for (auto &row : result.matrix) { VLOG(3) << "Row tokens: " << StringSpanOfTokenRange( FormatTokenRange(row_data_iter->ftoken_range.begin(), row_data_iter->ftoken_range.end())); - row = Transform(column_schema.Columns(), - [](const VectorTree&) { - return AlignmentCell{}; - }); + row = Transform( + column_schema.Columns(), [](const VectorTree &) { + return AlignmentCell{}; + }); FillAlignmentRow(*row_data_iter, column_schema.SyntaxToColumnsMap(), &row); @@ -981,7 +981,7 @@ AlignablePartitionGroup::CalculateAlignmentSpacings( // partitions and alignment matrix representation. result.align_actions_2D.reserve(result.matrix.size()); - for (const auto& row : result.matrix) { + for (const auto &row : result.matrix) { result.align_actions_2D.push_back( ComputeAlignedRowSpacings(column_configs, column_properties, row)); } @@ -991,26 +991,26 @@ AlignablePartitionGroup::CalculateAlignmentSpacings( // This applies pre-calculated alignment spacings to aligned groups of format // tokens. void AlignablePartitionGroup::ApplyAlignment( - const GroupAlignmentData& align_data) const { + const GroupAlignmentData &align_data) const { auto row = alignable_rows_.begin(); - for (const auto& align_actions : align_data.align_actions_2D) { + for (const auto &align_actions : align_data.align_actions_2D) { (*row)->Children().clear(); VLOG(3) << __FUNCTION__ << " processing row: " << **row; if (!align_actions.empty()) { - auto& node = **row; - auto& line = node.Value(); + auto &node = **row; + auto &line = node.Value(); auto ftokens = line.TokensRange(); line.SetPartitionPolicy(PartitionPolicyEnum::kAlreadyFormatted); - verible::TokenPartitionTree* current_cell = nullptr; + verible::TokenPartitionTree *current_cell = nullptr; if (align_actions.front().ftoken != ftokens.begin()) { node.Children().emplace_back( UnwrappedLine(0, ftokens.begin(), PartitionPolicyEnum::kInline)); current_cell = &node.Children().back(); } - for (const auto& action : align_actions) { + for (const auto &action : align_actions) { if (current_cell) { current_cell->Value().SpanUpToToken(action.ftoken); VLOG(3) << "new cell: margin=" @@ -1036,8 +1036,8 @@ void AlignablePartitionGroup::ApplyAlignment( } std::vector FilterAlignablePartitions( - const TokenPartitionRange& range, - const IgnoreAlignmentRowPredicate& ignore_partition_predicate) { + const TokenPartitionRange &range, + const IgnoreAlignmentRowPredicate &ignore_partition_predicate) { // This partition range may contain partitions that should not be // considered for column alignment purposes, so filter those out. std::vector qualified_partitions; @@ -1056,18 +1056,18 @@ std::vector FilterAlignablePartitions( ExtractAlignmentGroupsFunction ExtractAlignmentGroupsAdapter( const std::function( - const TokenPartitionRange&)>& legacy_extractor, - const IgnoreAlignmentRowPredicate& legacy_ignore_predicate, - const AlignmentCellScannerFunction& alignment_cell_scanner, + const TokenPartitionRange &)> &legacy_extractor, + const IgnoreAlignmentRowPredicate &legacy_ignore_predicate, + const AlignmentCellScannerFunction &alignment_cell_scanner, AlignmentPolicy alignment_policy) { return [legacy_extractor, legacy_ignore_predicate, alignment_cell_scanner, - alignment_policy](const TokenPartitionRange& full_range) { + alignment_policy](const TokenPartitionRange &full_range) { // must copy the closures, not just reference, to ensure valid lifetime const std::vector ranges( legacy_extractor(full_range)); std::vector groups; groups.reserve(ranges.size()); - for (const auto& range : ranges) { + for (const auto &range : ranges) { // Apply the same alignment scanner and policy to all alignment groups. // This ignores range.match_subtype. groups.emplace_back( @@ -1079,9 +1079,9 @@ ExtractAlignmentGroupsFunction ExtractAlignmentGroupsAdapter( }; } -static int MaxOfPositives2D(const std::vector>& values) { +static int MaxOfPositives2D(const std::vector> &values) { int result = 0; - for (const auto& row : values) { + for (const auto &row : values) { for (const int delta : row) { // Only accumulate positive values. if (delta > result) result = delta; @@ -1093,7 +1093,7 @@ static int MaxOfPositives2D(const std::vector>& values) { // Educated guess whether user wants alignment. AlignmentPolicy AlignablePartitionGroup::GroupAlignmentData::InferUserIntendedAlignmentPolicy( - const TokenPartitionRange& partitions) const { + const TokenPartitionRange &partitions) const { // Heuristics are implemented as a sequence of priority-ordered rules. { @@ -1147,7 +1147,7 @@ AlignablePartitionGroup::GroupAlignmentData::InferUserIntendedAlignmentPolicy( // TODO(mglb): this eventually could be moved to token_partition_tree.cc. void FormatUsingOriginalSpacing(TokenPartitionRange partition_range) { - for (auto& partition : partition_range) { + for (auto &partition : partition_range) { VLOG(4) << "partition before:\n" << TokenPartitionTreePrinter(partition, true); @@ -1182,7 +1182,7 @@ void FormatUsingOriginalSpacing(TokenPartitionRange partition_range) { // Remaining tokens for (auto it = tokens.begin() + 1; it != tokens.end(); ++it) { - const auto& token = *it; + const auto &token = *it; const auto whitespace = token.OriginalLeadingSpaces(); VLOG(5) << "token: \"" << EscapeString(whitespace) << EscapeString(token.Text()) << '\"'; @@ -1274,15 +1274,15 @@ void AlignablePartitionGroup::Align(int column_limit) const { void TabularAlignTokens( int column_limit, absl::string_view full_text, - const ByteOffsetSet& disabled_byte_ranges, - const ExtractAlignmentGroupsFunction& extract_alignment_groups, - TokenPartitionTree* partition_ptr) { + const ByteOffsetSet &disabled_byte_ranges, + const ExtractAlignmentGroupsFunction &extract_alignment_groups, + TokenPartitionTree *partition_ptr) { VLOG(1) << __FUNCTION__; // Each subpartition is presumed to correspond to a list element or // possibly some other ignored element like comments. - auto& partition = *partition_ptr; - auto& subpartitions = partition.Children(); + auto &partition = *partition_ptr; + auto &subpartitions = partition.Children(); // Identify groups of partitions to align, separated by blank lines. const TokenPartitionRange subpartitions_range(subpartitions.begin(), subpartitions.end()); @@ -1290,7 +1290,7 @@ void TabularAlignTokens( VLOG(2) << "extracting alignment partition groups..."; const std::vector alignment_groups( extract_alignment_groups(subpartitions_range)); - for (const auto& alignment_group : alignment_groups) { + for (const auto &alignment_group : alignment_groups) { const TokenPartitionRange partition_range(alignment_group.Range()); if (partition_range.empty()) continue; if (AnyPartitionSubRangeIsDisabled(partition_range, full_text, @@ -1318,21 +1318,21 @@ void TabularAlignTokens( std::vector GetSubpartitionsBetweenBlankLinesSingleTag( - const TokenPartitionRange& full_range, int subtype) { + const TokenPartitionRange &full_range, int subtype) { std::vector ranges( GetSubpartitionsBetweenBlankLines(full_range)); std::vector result; result.reserve(ranges.size()); - for (const auto& range : ranges) { + for (const auto &range : ranges) { result.emplace_back(range, subtype); } return result; } std::vector GetPartitionAlignmentSubranges( - const TokenPartitionRange& partitions, + const TokenPartitionRange &partitions, const std::function& partition_selector, + const TokenPartitionTree &)> &partition_selector, int min_match_count) { std::vector result; diff --git a/common/formatting/align_test.cc b/common/formatting/align_test.cc index 8178a2ab0..219329b71 100644 --- a/common/formatting/align_test.cc +++ b/common/formatting/align_test.cc @@ -92,10 +92,10 @@ class TokenColumnizer : public ColumnSchemaScanner { public: TokenColumnizer() = default; - void Visit(const SyntaxTreeNode& node) final { + void Visit(const SyntaxTreeNode &node) final { ColumnSchemaScanner::Visit(node); } - void Visit(const SyntaxTreeLeaf& leaf) final { + void Visit(const SyntaxTreeLeaf &leaf) final { // Let each token occupy its own column. ReserveNewColumn(leaf, FlushLeft); } @@ -105,10 +105,10 @@ class TokenColumnizerRightFlushed : public ColumnSchemaScanner { public: TokenColumnizerRightFlushed() = default; - void Visit(const SyntaxTreeNode& node) final { + void Visit(const SyntaxTreeNode &node) final { ColumnSchemaScanner::Visit(node); } - void Visit(const SyntaxTreeLeaf& leaf) final { + void Visit(const SyntaxTreeLeaf &leaf) final { // Let each token occupy its own column. ReserveNewColumn(leaf, FlushRight); } @@ -120,10 +120,10 @@ class TabularAlignTokenTest : public AlignmentTestFixture { : AlignmentTestFixture("one two three four five six") {} }; -static bool IgnoreNone(const TokenPartitionTree&) { return false; } +static bool IgnoreNone(const TokenPartitionTree &) { return false; } static std::vector -PartitionBetweenBlankLines(const TokenPartitionRange& range) { +PartitionBetweenBlankLines(const TokenPartitionRange &range) { // Don't care about the subtype tag. return GetSubpartitionsBetweenBlankLinesSingleTag(range, 0); } @@ -176,7 +176,7 @@ class MatrixTreeAlignmentTestFixture : public AlignmentTestFixture { std::string Render() { std::ostringstream stream; - for (auto& child : partition_.Children()) { + for (auto &child : partition_.Children()) { const auto policy = child.Value().PartitionPolicy(); if (policy == PartitionPolicyEnum::kAlreadyFormatted) { ApplyAlreadyFormattedPartitionPropertiesToTokens(&child, @@ -286,7 +286,7 @@ TEST_F(Sparse3x3MatrixAlignmentTest, AlignmentPolicyPreserve) { TEST_F(Sparse3x3MatrixAlignmentTest, OneInterTokenPadding) { // Require 1 space between tokens. // Will have no effect on the first token in each partition. - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } @@ -302,7 +302,7 @@ TEST_F(Sparse3x3MatrixAlignmentTest, OneInterTokenPadding) { TEST_F(Sparse3x3MatrixAlignmentTest, OneInterTokenPaddingExceptFront) { // Require 1 space between tokens, except ones at the beginning of partitions. - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } pre_format_tokens_[0].before.spaces_required = 0; @@ -327,7 +327,7 @@ static const ExtractAlignmentGroupsFunction kFlushRightAlignmentHandler = TEST_F(Sparse3x3MatrixAlignmentTest, RightFlushed) { // Require 1 space between tokens. - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } @@ -343,11 +343,11 @@ TEST_F(Sparse3x3MatrixAlignmentTest, RightFlushed) { TEST_F(Sparse3x3MatrixAlignmentTest, OneInterTokenPaddingWithIndent) { // Require 1 space between tokens, except ones at the beginning of partitions. - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } // Indent each partition. - for (auto& child : partition_.Children()) { + for (auto &child : partition_.Children()) { child.Value().SetIndentationSpaces(4); } @@ -363,7 +363,7 @@ TEST_F(Sparse3x3MatrixAlignmentTest, OneInterTokenPaddingWithIndent) { TEST_F(Sparse3x3MatrixAlignmentTest, IgnoreCommentLine) { // Require 1 space between tokens. - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } // Leave the 'commented' line indented. @@ -371,7 +371,7 @@ TEST_F(Sparse3x3MatrixAlignmentTest, IgnoreCommentLine) { partition_.Children()[1].Value().SetIndentationSpaces(1); // Pretend lines that begin with "three" are to be ignored, like comments. - auto ignore_threes = [](const TokenPartitionTree& partition) { + auto ignore_threes = [](const TokenPartitionTree &partition) { return partition.Value().TokensRange().front().Text() == "three"; }; @@ -395,7 +395,7 @@ TEST_F(Sparse3x3MatrixAlignmentTest, CompletelyDisabledNoAlignment) { &pre_format_tokens_); // Require 1 space between tokens. - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } @@ -417,10 +417,10 @@ TEST_F(Sparse3x3MatrixAlignmentTest, CompletelyDisabledNoAlignmentWithIndent) { &pre_format_tokens_); // Require 1 space between tokens. - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } - for (auto& child : partition_.Children()) { + for (auto &child : partition_.Children()) { child.Value().SetIndentationSpaces(3); } pre_format_tokens_[0].before.break_decision = SpacingOptions::kMustWrap; @@ -453,10 +453,10 @@ class Sparse3x3MatrixAlignmentMoreSpacesTest TEST_F(Sparse3x3MatrixAlignmentMoreSpacesTest, PartiallyDisabledIndentButPreserveOtherSpaces) { // Require 1 space between tokens. - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } - for (auto& child : partition_.Children()) { + for (auto &child : partition_.Children()) { child.Value().SetIndentationSpaces(1); } pre_format_tokens_[0].before.break_decision = SpacingOptions::kMustWrap; @@ -484,7 +484,7 @@ TEST_F(Sparse3x3MatrixAlignmentTest, PartiallyDisabledNoAlignment) { &pre_format_tokens_); // Require 1 space between tokens. - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } @@ -503,7 +503,7 @@ TEST_F(Sparse3x3MatrixAlignmentTest, PartiallyDisabledNoAlignment) { TEST_F(Sparse3x3MatrixAlignmentTest, DisabledByColumnLimit) { // Require 1 space between tokens. - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } @@ -521,10 +521,10 @@ TEST_F(Sparse3x3MatrixAlignmentTest, DisabledByColumnLimit) { TEST_F(Sparse3x3MatrixAlignmentTest, DisabledByColumnLimitIndented) { // Require 1 space between tokens. - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } - for (auto& child : partition_.Children()) { + for (auto &child : partition_.Children()) { child.Value().SetIndentationSpaces(3); } @@ -606,7 +606,7 @@ class MultiAlignmentGroupTest : public AlignmentTestFixture { std::ostringstream stream; int position = 0; const absl::string_view text(sample_); - for (auto& child : partition_.Children()) { + for (auto &child : partition_.Children()) { const auto policy = child.Value().PartitionPolicy(); if (policy == PartitionPolicyEnum::kAlreadyFormatted) { ApplyAlreadyFormattedPartitionPropertiesToTokens(&child, @@ -636,7 +636,7 @@ class MultiAlignmentGroupTest : public AlignmentTestFixture { TEST_F(MultiAlignmentGroupTest, BlankLineSeparatedGroups) { // Require 1 space between tokens. - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } @@ -710,7 +710,7 @@ class GetPartitionAlignmentSubrangesTestFixture : public AlignmentTestFixture { protected: static AlignmentGroupAction PartitionSelector( - const TokenPartitionTree& partition) { + const TokenPartitionTree &partition) { const absl::string_view text = partition.Value().TokensRange().front().Text(); if (text == "match") { @@ -735,8 +735,8 @@ TEST_F(GetPartitionAlignmentSubrangesTestFixture, VariousRanges) { partition_.Children().end()); const std::vector ranges( - GetPartitionAlignmentSubranges(children, [](const TokenPartitionTree& - partition) { + GetPartitionAlignmentSubranges(children, [](const TokenPartitionTree + &partition) { // Don't care about the subtype tag. return AlignedPartitionClassification{PartitionSelector(partition), 0}; })); @@ -744,7 +744,7 @@ TEST_F(GetPartitionAlignmentSubrangesTestFixture, VariousRanges) { using P = std::pair; std::vector

range_indices; range_indices.reserve(ranges.size()); - for (const auto& range : ranges) { + for (const auto &range : ranges) { range_indices.push_back(SubRangeIndices(range.range, children)); } EXPECT_THAT(range_indices, ElementsAre(P(3, 6), P(8, 11))); @@ -810,7 +810,7 @@ class GetPartitionAlignmentSubrangesSubtypedTestFixture protected: static AlignedPartitionClassification PartitionSelector( - const TokenPartitionTree& partition) { + const TokenPartitionTree &partition) { const absl::string_view text = partition.Value().TokensRange().front().Text(); if (absl::StartsWith(text, "match")) { @@ -844,7 +844,7 @@ TEST_F(GetPartitionAlignmentSubrangesSubtypedTestFixture, VariousRanges) { using P = std::pair; std::vector

range_indices; range_indices.reserve(ranges.size()); - for (const auto& range : ranges) { + for (const auto &range : ranges) { range_indices.push_back(SubRangeIndices(range.range, children)); } EXPECT_THAT(range_indices, @@ -869,7 +869,7 @@ class Dense2x2MatrixAlignmentTest : public MatrixTreeAlignmentTestFixture { &pre_format_tokens_); // Require 1 space between tokens. - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; // Default to append, so we can see the effect of falling-back to // preserve-spacing behavior. @@ -1004,24 +1004,24 @@ TEST_F(InferAmbiguousAlignIntentTest, DifferenceSufficientlySmall) { // Creates columns tree with the same layout as the syntax tree. // Columns created for tokens ',' have `contains_delimiter` set. -template +template class SyntaxTreeColumnizer : public ColumnSchemaScanner { public: SyntaxTreeColumnizer() = default; - void Visit(const SyntaxTreeNode& node) final { - ColumnPositionTree* column; + void Visit(const SyntaxTreeNode &node) final { + ColumnPositionTree *column; if (!current_column_) { column = ReserveNewColumn(node, props); } else { column = ReserveNewColumn(current_column_, node, props); } - ValueSaver current_column_saver(¤t_column_, - column); + ValueSaver current_column_saver(¤t_column_, + column); ColumnSchemaScanner::Visit(node); } - void Visit(const SyntaxTreeLeaf& leaf) final { + void Visit(const SyntaxTreeLeaf &leaf) final { AlignmentColumnProperties local_props = props; if (leaf.get().text() == ",") local_props.contains_delimiter = true; @@ -1033,7 +1033,7 @@ class SyntaxTreeColumnizer : public ColumnSchemaScanner { } private: - ColumnPositionTree* current_column_ = nullptr; + ColumnPositionTree *current_column_ = nullptr; }; class SubcolumnsTreeAlignmentTest : public MatrixTreeAlignmentTestFixture { @@ -1085,8 +1085,8 @@ class SubcolumnsTreeAlignmentTest : public MatrixTreeAlignmentTestFixture { private: SymbolPtr ParseList( - std::vector::iterator* it, - const std::vector::iterator& end) { + std::vector::iterator *it, + const std::vector::iterator &end) { SymbolPtr list = TNode(0); SymbolPtr item; while ((item = ParseItem(it, end)) != nullptr) { @@ -1096,8 +1096,8 @@ class SubcolumnsTreeAlignmentTest : public MatrixTreeAlignmentTestFixture { } SymbolPtr ParseItem( - std::vector::iterator* it, - const std::vector::iterator& end) { + std::vector::iterator *it, + const std::vector::iterator &end) { CHECK_NOTNULL(it); if (*it == end) return SymbolPtr(nullptr); @@ -1185,7 +1185,7 @@ TEST_F(SubcolumnsTreeAlignmentTest, AlignmentPolicyPreserve) { } TEST_F(SubcolumnsTreeAlignmentTest, OneInterTokenPadding) { - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } @@ -1201,17 +1201,17 @@ TEST_F(SubcolumnsTreeAlignmentTest, OneInterTokenPadding) { } TEST_F(SubcolumnsTreeAlignmentTest, OneInterTokenPaddingExceptFront) { - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } // Find first token of each line and require 0 spaces before them. - for (auto& line : partition_.Children()) { + for (auto &line : partition_.Children()) { const auto tokens = line.Value().TokensRange(); if (!tokens.empty()) { - const PreFormatToken& front = tokens.front(); + const PreFormatToken &front = tokens.front(); auto mutable_token = std::find_if(pre_format_tokens_.begin(), pre_format_tokens_.end(), - [&](const PreFormatToken& ftoken) { + [&](const PreFormatToken &ftoken) { return BoundsEqual(ftoken.Text(), front.Text()); }); if (mutable_token != pre_format_tokens_.end()) { @@ -1232,7 +1232,7 @@ TEST_F(SubcolumnsTreeAlignmentTest, OneInterTokenPaddingExceptFront) { } TEST_F(SubcolumnsTreeAlignmentTest, RightFlushed) { - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } @@ -1249,10 +1249,10 @@ TEST_F(SubcolumnsTreeAlignmentTest, RightFlushed) { TEST_F(SubcolumnsTreeAlignmentTest, RightFlushedOneInterTokenPaddingWithIndent) { - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } - for (auto& line : partition_.Children()) { + for (auto &line : partition_.Children()) { line.Value().SetIndentationSpaces(2); } @@ -1283,7 +1283,7 @@ class MultiSubcolumnsTreeAlignmentTest : public SubcolumnsTreeAlignmentTest { std::ostringstream stream; int position = 0; const absl::string_view text(sample_); - for (auto& child : partition_.Children()) { + for (auto &child : partition_.Children()) { const auto policy = child.Value().PartitionPolicy(); if (policy == PartitionPolicyEnum::kAlreadyFormatted) { ApplyAlreadyFormattedPartitionPropertiesToTokens(&child, @@ -1305,7 +1305,7 @@ class MultiSubcolumnsTreeAlignmentTest : public SubcolumnsTreeAlignmentTest { }; TEST_F(MultiSubcolumnsTreeAlignmentTest, BlankLineSeparatedGroups) { - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; } @@ -1336,7 +1336,7 @@ class InferSubcolumnsTreeAlignmentTest : public SubcolumnsTreeAlignmentTest { &pre_format_tokens_); // Require 1 space between tokens. - for (auto& ftoken : pre_format_tokens_) { + for (auto &ftoken : pre_format_tokens_) { ftoken.before.spaces_required = 1; // Default to append, so we can see the effect of falling-back to // preserve-spacing behavior. @@ -1449,7 +1449,7 @@ TEST(ColumnsTreeFormatter, ColumnPositionTreePrinter) { }, }; - for (const auto& test_case : kTestCases) { + for (const auto &test_case : kTestCases) { std::ostringstream stream; stream << test_case.input; EXPECT_EQ(stream.str(), test_case.expected); @@ -1511,7 +1511,7 @@ class FormatUsingOriginalSpacingTest : public ::testing::Test, protected: void RunTestCase(TokenPartitionTree actual, - const TokenPartitionTree& expected) { + const TokenPartitionTree &expected) { TokenPartitionTree::subnodes_type nodes; nodes.push_back(std::move(actual)); FormatUsingOriginalSpacing(TokenPartitionRange(nodes.begin(), nodes.end())); diff --git a/common/formatting/layout_optimizer.cc b/common/formatting/layout_optimizer.cc index aff340be5..674c9be07 100644 --- a/common/formatting/layout_optimizer.cc +++ b/common/formatting/layout_optimizer.cc @@ -42,8 +42,8 @@ namespace verible { -void OptimizeTokenPartitionTree(const BasicFormatStyle& style, - TokenPartitionTree* node) { +void OptimizeTokenPartitionTree(const BasicFormatStyle &style, + TokenPartitionTree *node) { CHECK_NOTNULL(node); VLOG(4) << __FUNCTION__ << ", before:\n" << verible::TokenPartitionTreePrinter(*node); @@ -61,19 +61,19 @@ namespace { // Adopts sublayouts of 'source' into 'destination' if 'source' and // 'destination' types are equal and 'source' doesn't have extra indentation. // Otherwise adopts whole 'source'. -void AdoptLayoutAndFlattenIfSameType(const LayoutTree& source, - LayoutTree* destination) { +void AdoptLayoutAndFlattenIfSameType(const LayoutTree &source, + LayoutTree *destination) { CHECK_NOTNULL(destination); - const auto& src_item = source.Value(); - const auto& dst_item = destination->Value(); + const auto &src_item = source.Value(); + const auto &dst_item = destination->Value(); if (!verible::is_leaf(source) && src_item.Type() == dst_item.Type() && src_item.IndentationSpaces() == 0) { - const auto& first_subitem = source.Children().front().Value(); + const auto &first_subitem = source.Children().front().Value(); CHECK(src_item.MustWrap() == first_subitem.MustWrap()); CHECK(src_item.SpacesBefore() == first_subitem.SpacesBefore()); destination->Children().reserve(destination->Children().size() + source.Children().size()); - for (const auto& sublayout : source.Children()) { + for (const auto &sublayout : source.Children()) { AdoptSubtree(*destination, sublayout); } } else { @@ -81,7 +81,7 @@ void AdoptLayoutAndFlattenIfSameType(const LayoutTree& source, } } -int AlreadyFormattedPartitionLength(const TokenPartitionTree& partition) { +int AlreadyFormattedPartitionLength(const TokenPartitionTree &partition) { auto tokens = partition.Value().TokensRange(); if (tokens.empty()) return 0; int width = 0; @@ -89,7 +89,7 @@ int AlreadyFormattedPartitionLength(const TokenPartitionTree& partition) { width += partition.Value().IndentationSpaces(); width += tokens.front().Length(); - for (const auto& token : make_range(tokens.begin() + 1, tokens.end())) { + for (const auto &token : make_range(tokens.begin() + 1, tokens.end())) { // TODO(mglb): either handle tokens with kPreserve break_decision, or // explicitly check for their absence. Preserved space is currently expected // to be emulated with kAlreadyFormatted/kInline partitions. Only tabular @@ -97,10 +97,10 @@ int AlreadyFormattedPartitionLength(const TokenPartitionTree& partition) { width += token.before.spaces_required + token.Length(); } - for (const auto& child : partition.Children()) { + for (const auto &child : partition.Children()) { CHECK_EQ(child.Value().PartitionPolicy(), PartitionPolicyEnum::kInline); if (child.Value().TokensRange().begin() != tokens.begin()) { - const auto& first_token = child.Value().TokensRange().front(); + const auto &first_token = child.Value().TokensRange().front(); // Substract spacing added in the loop above width -= first_token.before.spaces_required; } @@ -115,7 +115,7 @@ constexpr int kInfinity = std::numeric_limits::max(); } // namespace -std::ostream& operator<<(std::ostream& stream, LayoutType type) { +std::ostream &operator<<(std::ostream &stream, LayoutType type) { switch (type) { case LayoutType::kLine: return stream << "line"; @@ -128,7 +128,7 @@ std::ostream& operator<<(std::ostream& stream, LayoutType type) { return stream << "???"; } -std::ostream& operator<<(std::ostream& stream, const LayoutItem& layout) { +std::ostream &operator<<(std::ostream &stream, const LayoutItem &layout) { if (layout.Type() == LayoutType::kLine) { stream << "[ " << layout.Text() << " ]" << ", length: " << layout.Length(); @@ -141,8 +141,8 @@ std::ostream& operator<<(std::ostream& stream, const LayoutItem& layout) { return stream; } -std::ostream& operator<<(std::ostream& stream, - const LayoutFunctionSegment& segment) { +std::ostream &operator<<(std::ostream &stream, + const LayoutFunctionSegment &segment) { stream << "[" << std::setw(3) << std::setfill(' ') << segment.column << "] (" << std::fixed << std::setprecision(3) << segment.intercept << " + " << segment.gradient << "*x), span: " << segment.span << ", layout:\n"; @@ -150,11 +150,11 @@ std::ostream& operator<<(std::ostream& stream, return stream; } -std::ostream& operator<<(std::ostream& stream, const LayoutFunction& lf) { +std::ostream &operator<<(std::ostream &stream, const LayoutFunction &lf) { if (lf.empty()) return stream << "{}"; stream << "{\n"; - for (const auto& segment : lf) { + for (const auto &segment : lf) { stream << " [" << std::setw(3) << std::setfill(' ') << segment.column << "] (" << std::fixed << std::setprecision(3) << std::setw(8) << std::setfill(' ') << segment.intercept << " + " << std::setw(4) @@ -189,7 +189,7 @@ LayoutFunction::const_iterator LayoutFunction::AtOrToTheLeftOf( if (empty()) return end(); const auto it = std::lower_bound( - begin(), end(), column, [](const LayoutFunctionSegment& s, int column) { + begin(), end(), column, [](const LayoutFunctionSegment &s, int column) { return s.column <= column; }); CHECK_NE(it, begin()); @@ -197,7 +197,7 @@ LayoutFunction::const_iterator LayoutFunction::AtOrToTheLeftOf( } LayoutFunction LayoutFunctionFactory::WrappedLine( - const UnwrappedLine& uwline) const { + const UnwrappedLine &uwline) const { const auto tokens = uwline.TokensRange(); auto token_lfs = absl::FixedArray(tokens.size()); @@ -211,7 +211,7 @@ LayoutFunction LayoutFunctionFactory::WrappedLine( return Wrap(token_lfs.begin(), token_lfs.end(), true, style_.wrap_spaces); } -LayoutFunction LayoutFunctionFactory::Line(const UnwrappedLine& uwline) const { +LayoutFunction LayoutFunctionFactory::Line(const UnwrappedLine &uwline) const { auto layout = LayoutTree(LayoutItem(uwline)); const auto span = layout.Value().Length(); @@ -231,7 +231,7 @@ LayoutFunction LayoutFunctionFactory::Line(const UnwrappedLine& uwline) const { }; } -LayoutFunction LayoutFunctionFactory::Indent(const LayoutFunction& lf, +LayoutFunction LayoutFunctionFactory::Indent(const LayoutFunction &lf, int indent) const { CHECK(!lf.empty()); CHECK_GE(indent, 0); @@ -270,7 +270,7 @@ LayoutFunction LayoutFunctionFactory::Indent(const LayoutFunction& lf, } LayoutFunction LayoutFunctionFactory::Juxtaposition( - const LayoutFunction& left, const LayoutFunction& right) const { + const LayoutFunction &left, const LayoutFunction &right) const { CHECK(!left.empty()); CHECK(!right.empty()); @@ -281,7 +281,7 @@ LayoutFunction LayoutFunctionFactory::Juxtaposition( // Do not crash, fallback to stack layout. Set huge penalty to let the // layout be dropped in Choice() operator if it ends up in one. auto result = Stack({left, right}); - for (auto& segment : result) segment.intercept += 2e6; + for (auto &segment : result) segment.intercept += 2e6; return result; } @@ -304,8 +304,8 @@ LayoutFunction LayoutFunctionFactory::Juxtaposition( segment_l->gradient + segment_r->gradient - (columns_over_limit >= 0 ? style_.over_column_limit_penalty : 0); - const auto& layout_l = segment_l->layout; - const auto& layout_r = segment_r->layout; + const auto &layout_l = segment_l->layout; + const auto &layout_r = segment_r->layout; auto new_layout = LayoutTree(LayoutItem(LayoutType::kJuxtaposition, layout_l.Value().SpacesBefore(), layout_l.Value().MustWrap())); @@ -351,7 +351,7 @@ LayoutFunction LayoutFunctionFactory::Juxtaposition( } LayoutFunction LayoutFunctionFactory::Stack( - absl::FixedArray* segments) const { + absl::FixedArray *segments) const { CHECK(!segments->empty()); LayoutFunction result; @@ -364,12 +364,12 @@ LayoutFunction LayoutFunctionFactory::Stack( int current_column = 0; do { // Point iterators to segments under current column. - for (auto& segment_it : *segments) { + for (auto &segment_it : *segments) { segment_it.MoveToKnotAtOrToTheLeftOf(current_column); } // Use first line's spacing for new layouts. - const auto& first_layout_item = segments->front()->layout.Value(); + const auto &first_layout_item = segments->front()->layout.Value(); const auto spaces_before = first_layout_item.SpacesBefore(); const auto break_decision = first_layout_item.MustWrap(); // Use last line's span for new layouts. Other lines won't be modified by @@ -382,7 +382,7 @@ LayoutFunction LayoutFunctionFactory::Stack( LayoutItem(LayoutType::kStack, spaces_before, break_decision)), span, line_breaks_penalty, 0}; - for (const auto& segment_it : *segments) { + for (const auto &segment_it : *segments) { new_segment.intercept += segment_it->CostAt(current_column); new_segment.gradient += segment_it->gradient; AdoptLayoutAndFlattenIfSameType(segment_it->layout, &new_segment.layout); @@ -406,7 +406,7 @@ LayoutFunction LayoutFunctionFactory::Stack( } LayoutFunction LayoutFunctionFactory::Choice( - absl::FixedArray* segments) { + absl::FixedArray *segments) { CHECK(!segments->empty()); LayoutFunction result; @@ -423,7 +423,7 @@ LayoutFunction LayoutFunctionFactory::Choice( // Starting column of the next closest segment. int next_knot = kInfinity; - for (auto& segment_it : *segments) { + for (auto &segment_it : *segments) { segment_it.MoveToKnotAtOrToTheLeftOf(current_column); const int column = @@ -434,7 +434,7 @@ LayoutFunction LayoutFunctionFactory::Choice( do { const LayoutFunction::const_iterator min_cost_segment = *std::min_element( segments->begin(), segments->end(), - [current_column](const auto& a, const auto& b) { + [current_column](const auto &a, const auto &b) { if (a->CostAt(current_column) != b->CostAt(current_column)) { return (a->CostAt(current_column) < b->CostAt(current_column)); } @@ -453,7 +453,7 @@ LayoutFunction LayoutFunctionFactory::Choice( // Find closest crossover point located before next knot. int next_column = next_knot; - for (const auto& segment : *segments) { + for (const auto &segment : *segments) { if (segment->gradient >= min_cost_segment->gradient) continue; float gamma = (segment->CostAt(current_column) - min_cost_segment->CostAt(current_column)) / @@ -472,7 +472,7 @@ LayoutFunction LayoutFunctionFactory::Choice( } void TokenPartitionsLayoutOptimizer::Optimize(int indentation, - TokenPartitionTree* node) const { + TokenPartitionTree *node) const { CHECK_NOTNULL(node); CHECK_GE(indentation, 0); @@ -491,7 +491,7 @@ void TokenPartitionsLayoutOptimizer::Optimize(int indentation, } LayoutFunction TokenPartitionsLayoutOptimizer::CalculateOptimalLayout( - const TokenPartitionTree& node) const { + const TokenPartitionTree &node) const { if (is_leaf(node)) { // Wrapping complexity is n*(n+1)/2. constexpr int kWrapTokensLimit = 25; @@ -516,7 +516,7 @@ LayoutFunction TokenPartitionsLayoutOptimizer::CalculateOptimalLayout( case PartitionPolicyEnum::kAppendFittingSubPartitions: case PartitionPolicyEnum::kJuxtapositionOrIndentedStack: { std::transform(node.Children().begin(), node.Children().end(), - layouts.begin(), [this](const TokenPartitionTree& n) { + layouts.begin(), [this](const TokenPartitionTree &n) { return this->CalculateOptimalLayout(n); }); break; @@ -528,7 +528,7 @@ LayoutFunction TokenPartitionsLayoutOptimizer::CalculateOptimalLayout( const int indentation = node.Value().IndentationSpaces(); std::transform( node.Children().begin(), node.Children().end(), layouts.begin(), - [this, &node, indentation](const TokenPartitionTree& n) { + [this, &node, indentation](const TokenPartitionTree &n) { const int relative_indentation = n.Value().IndentationSpaces() - indentation; if (relative_indentation < 0) { @@ -566,7 +566,7 @@ LayoutFunction TokenPartitionsLayoutOptimizer::CalculateOptimalLayout( case PartitionPolicyEnum::kWrap: { if (VLOG_IS_ON(0) && node.Children().size() > 2) { const int indentation = node.Children()[1].Value().IndentationSpaces(); - for (const auto& child : iterator_range(node.Children().begin() + 2, + for (const auto &child : iterator_range(node.Children().begin() + 2, node.Children().end())) { if (child.Value().IndentationSpaces() != indentation) { VLOG(1) << "Indentations of subpartitions from the second to the " @@ -594,7 +594,7 @@ LayoutFunction TokenPartitionsLayoutOptimizer::CalculateOptimalLayout( LayoutFunction juxtaposition; const bool juxtaposition_allowed = !std::any_of(layouts.begin() + 1, layouts.end(), - [](const LayoutFunction& lf) { return lf.MustWrap(); }); + [](const LayoutFunction &lf) { return lf.MustWrap(); }); if (juxtaposition_allowed) { juxtaposition = factory_.Juxtaposition(layouts.begin(), layouts.end()); } @@ -627,7 +627,7 @@ LayoutFunction TokenPartitionsLayoutOptimizer::CalculateOptimalLayout( // policy. Pack them horizontally. const bool all_children_are_inlines = std::all_of(node.Children().begin(), node.Children().end(), - [](const TokenPartitionTree& child) { + [](const TokenPartitionTree &child) { return child.Value().PartitionPolicy() == PartitionPolicyEnum::kInline; }); @@ -669,8 +669,8 @@ LayoutFunction TokenPartitionsLayoutOptimizer::CalculateOptimalLayout( return factory_.Stack(layouts.begin(), layouts.end()); } -void TreeReconstructor::TraverseTree(const LayoutTree& layout_tree) { - const auto& layout = layout_tree.Value(); +void TreeReconstructor::TraverseTree(const LayoutTree &layout_tree) { + const auto &layout = layout_tree.Value(); const auto relative_indentation = layout.IndentationSpaces(); const ValueSaver indent_saver( ¤t_indentation_spaces_, @@ -698,7 +698,7 @@ void TreeReconstructor::TraverseTree(const LayoutTree& layout_tree) { current_node_->Value().SpanUpToToken(tokens.end()); - auto& slices = current_node_->Children(); + auto &slices = current_node_->Children(); // TODO(mglb): add support for break_decision == Preserve if (layout.SpacesBefore() == tokens.front().before.spaces_required) { // No need for separate inline partition @@ -727,7 +727,7 @@ void TreeReconstructor::TraverseTree(const LayoutTree& layout_tree) { case LayoutType::kJuxtaposition: { // Append all children - for (const auto& child : layout_tree.Children()) { + for (const auto &child : layout_tree.Children()) { TraverseTree(child); } return; @@ -755,7 +755,7 @@ void TreeReconstructor::TraverseTree(const LayoutTree& layout_tree) { // Put remaining children in their own (indented) lines const ValueSaver indent_saver(¤t_indentation_spaces_, indentation); - for (const auto& child : make_range(layout_tree.Children().begin() + 1, + for (const auto &child : make_range(layout_tree.Children().begin() + 1, layout_tree.Children().end())) { current_node_ = nullptr; TraverseTree(child); @@ -766,15 +766,15 @@ void TreeReconstructor::TraverseTree(const LayoutTree& layout_tree) { } void TreeReconstructor::ReplaceTokenPartitionTreeNode( - TokenPartitionTree* node) { + TokenPartitionTree *node) { CHECK_NOTNULL(node); CHECK(!tree_.Children().empty()); if (tree_.Children().size() == 1) { *node = std::move(tree_.Children().front()); } else { - const auto& first_line = tree_.Children().front().Value(); - const auto& last_line = tree_.Children().back().Value(); + const auto &first_line = tree_.Children().front().Value(); + const auto &last_line = tree_.Children().back().Value(); node->Value() = UnwrappedLine(current_indentation_spaces_, first_line.TokensRange().begin(), diff --git a/common/formatting/layout_optimizer_test.cc b/common/formatting/layout_optimizer_test.cc index 9e6967d33..ed720204d 100644 --- a/common/formatting/layout_optimizer_test.cc +++ b/common/formatting/layout_optimizer_test.cc @@ -46,24 +46,24 @@ namespace verible { namespace { template -std::string ToString(const T& value) { +std::string ToString(const T &value) { std::ostringstream s; s << value; return s.str(); } -std::ostream& PrintIndented(std::ostream& stream, absl::string_view str, +std::ostream &PrintIndented(std::ostream &stream, absl::string_view str, int indentation) { - for (const auto& line : verible::SplitLinesKeepLineTerminator(str)) { + for (const auto &line : verible::SplitLinesKeepLineTerminator(str)) { stream << verible::Spacer(indentation) << line; } return stream; } template -void PrintInvalidValueMessage(std::ostream& stream, - absl::string_view value_name, const Value& actual, - const Value& expected, int indentation = 0, +void PrintInvalidValueMessage(std::ostream &stream, + absl::string_view value_name, const Value &actual, + const Value &expected, int indentation = 0, bool multiline = false) { using ::testing::PrintToString; using verible::Spacer; @@ -80,8 +80,8 @@ void PrintInvalidValueMessage(std::ostream& stream, } } -void ExpectLayoutFunctionsEqual(const LayoutFunction& actual, - const LayoutFunction& expected, int line_no) { +void ExpectLayoutFunctionsEqual(const LayoutFunction &actual, + const LayoutFunction &expected, int line_no) { using ::testing::PrintToString; std::ostringstream msg; if (actual.size() != expected.size()) { @@ -146,7 +146,7 @@ TEST(LayoutTypeTest, ToString) { EXPECT_EQ(ToString(static_cast(-1)), "???"); } -bool TokenRangeEqual(const UnwrappedLine& left, const UnwrappedLine& right) { +bool TokenRangeEqual(const UnwrappedLine &left, const UnwrappedLine &right) { return left.TokensRange() == right.TokensRange(); } @@ -382,7 +382,7 @@ TEST_F(LayoutFunctionTest, Iteration) { EXPECT_EQ(it->column, 0); auto column_it = columns.begin(); - for (auto& segment : layout_function_) { + for (auto &segment : layout_function_) { EXPECT_EQ(segment.column, *column_it); EXPECT_NE(column_it, columns.end()); ++column_it; @@ -396,7 +396,7 @@ TEST_F(LayoutFunctionTest, Iteration) { EXPECT_EQ(it->column, 0); auto column_it = columns.begin(); - for (auto& segment : const_layout_function_) { + for (auto &segment : const_layout_function_) { EXPECT_EQ(segment.column, *column_it); EXPECT_NE(column_it, columns.end()); ++column_it; @@ -408,7 +408,7 @@ TEST_F(LayoutFunctionTest, Iteration) { auto it = empty_layout_function.begin(); EXPECT_EQ(it, empty_layout_function.end()); - for (auto& segment [[maybe_unused]] : empty_layout_function) { + for (auto &segment [[maybe_unused]] : empty_layout_function) { EXPECT_FALSE(true); } } @@ -701,7 +701,7 @@ class LayoutFunctionFactoryTest : public ::testing::Test, // Setup pointers for OriginalLeadingSpaces() auto must_wrap_token = must_wrap_pre_format_tokens.begin(); auto joinable_token = joinable_pre_format_tokens.begin(); - const char* buffer_start = sample_.data(); + const char *buffer_start = sample_.data(); for (size_t i = 0; i < number_of_tokens_in_set; ++i) { must_wrap_token->before.preserved_space_start = buffer_start; joinable_token->before.preserved_space_start = buffer_start; @@ -721,8 +721,8 @@ class LayoutFunctionFactoryTest : public ::testing::Test, static void ProcessTokensAndCreateUnwrappedLines( bool first_on_line_must_wrap, - verible::iterator_range* pftokens, - std::vector* uwlines) { + verible::iterator_range *pftokens, + std::vector *uwlines) { uwlines->emplace_back(0, pftokens->begin()); for (auto token = pftokens->begin(); token != pftokens->end(); ++token) { const auto leading_spaces = token->OriginalLeadingSpaces(); @@ -750,19 +750,19 @@ class LayoutFunctionFactoryTest : public ::testing::Test, // Wrapper for UnwrappedLine vector with readable getter for each line struct NamedUnwrappedLines { - const UnwrappedLine& Short() const { return uwlines_.at(0); } - const UnwrappedLine& Long() const { return uwlines_.at(1); } - const UnwrappedLine& Indented() const { return uwlines_.at(2); } + const UnwrappedLine &Short() const { return uwlines_.at(0); } + const UnwrappedLine &Long() const { return uwlines_.at(1); } + const UnwrappedLine &Indented() const { return uwlines_.at(2); } - const UnwrappedLine& OneUnder40Limit() const { return uwlines_.at(3); } - const UnwrappedLine& ExactlyAt40Limit() const { return uwlines_.at(4); } - const UnwrappedLine& OneOver40Limit() const { return uwlines_.at(5); } + const UnwrappedLine &OneUnder40Limit() const { return uwlines_.at(3); } + const UnwrappedLine &ExactlyAt40Limit() const { return uwlines_.at(4); } + const UnwrappedLine &OneOver40Limit() const { return uwlines_.at(5); } - const UnwrappedLine& OneUnder30Limit() const { return uwlines_.at(6); } - const UnwrappedLine& ExactlyAt30Limit() const { return uwlines_.at(7); } - const UnwrappedLine& OneOver30Limit() const { return uwlines_.at(8); } + const UnwrappedLine &OneUnder30Limit() const { return uwlines_.at(6); } + const UnwrappedLine &ExactlyAt30Limit() const { return uwlines_.at(7); } + const UnwrappedLine &OneOver30Limit() const { return uwlines_.at(8); } - const UnwrappedLine& Exactly10Columns() const { return uwlines_.at(9); } + const UnwrappedLine &Exactly10Columns() const { return uwlines_.at(9); } std::vector uwlines_; }; @@ -842,7 +842,7 @@ TEST_F(LayoutFunctionFactoryTest, Stack) { { const auto line = factory_.Line(lines_.Short()); const auto lf = factory_.Stack({line}); - const auto& expected_lf = line; + const auto &expected_lf = line; ExpectLayoutFunctionsEqual(lf, expected_lf, __LINE__); } { @@ -1108,7 +1108,7 @@ TEST_F(LayoutFunctionFactoryTest, Juxtaposition) { { const auto line = factory_.Line(lines_.Short()); const auto lf = factory_.Juxtaposition({line}); - const auto& expected_lf = line; + const auto &expected_lf = line; ExpectLayoutFunctionsEqual(lf, expected_lf, __LINE__); } { @@ -1456,7 +1456,7 @@ TEST_F(LayoutFunctionFactoryTest, Choice) { }}, }; - for (const auto& test_case : kTestCases) { + for (const auto &test_case : kTestCases) { const LayoutFunction choice_result = factory_.Choice(test_case.choices); ExpectLayoutFunctionsEqual(choice_result, test_case.expected, test_case.line_no); @@ -2403,7 +2403,7 @@ class TokenPartitionsLayoutOptimizerTest : public ::testing::Test, &pre_format_tokens_); // Set token properties - for (auto& token : pre_format_tokens_) { + for (auto &token : pre_format_tokens_) { const auto leading_spaces = token.OriginalLeadingSpaces(); // First token in a line diff --git a/common/formatting/token_partition_tree.cc b/common/formatting/token_partition_tree.cc index 3ce971b2a..8562cca0a 100644 --- a/common/formatting/token_partition_tree.cc +++ b/common/formatting/token_partition_tree.cc @@ -44,7 +44,7 @@ namespace verible { using format_token_iterator = std::vector::const_iterator; -void VerifyTreeNodeFormatTokenRanges(const TokenPartitionTree& node, +void VerifyTreeNodeFormatTokenRanges(const TokenPartitionTree &node, format_token_iterator base) { VLOG(4) << __FUNCTION__ << " @ node path: " << NodePath(node); @@ -53,13 +53,13 @@ void VerifyTreeNodeFormatTokenRanges(const TokenPartitionTree& node, return std::distance(base, iter); }; - const auto& children = node.Children(); + const auto &children = node.Children(); if (!children.empty()) { const TokenPartitionTreePrinter node_printer(node); { // Hierarchy invariant: parent's range == range spanned by children. // Check against first child's begin, and last child's end. - const auto& parent_range = node.Value().TokensRange(); + const auto &parent_range = node.Value().TokensRange(); // Translates ranges' iterators into positional indices. const int parent_begin = TokenIndex(parent_range.begin()); const int parent_end = TokenIndex(parent_range.end()); @@ -88,27 +88,27 @@ void VerifyTreeNodeFormatTokenRanges(const TokenPartitionTree& node, VLOG(4) << __FUNCTION__ << " (verified)"; } -void VerifyFullTreeFormatTokenRanges(const TokenPartitionTree& tree, +void VerifyFullTreeFormatTokenRanges(const TokenPartitionTree &tree, format_token_iterator base) { VLOG(4) << __FUNCTION__ << '\n' << TokenPartitionTreePrinter{tree}; - ApplyPreOrder(tree, [=](const TokenPartitionTree& node) { + ApplyPreOrder(tree, [=](const TokenPartitionTree &node) { VerifyTreeNodeFormatTokenRanges(node, base); }); } struct SizeCompare { - bool operator()(const UnwrappedLine* left, const UnwrappedLine* right) const { + bool operator()(const UnwrappedLine *left, const UnwrappedLine *right) const { return left->Size() > right->Size(); } }; -std::vector FindLargestPartitions( - const TokenPartitionTree& token_partitions, size_t num_partitions) { +std::vector FindLargestPartitions( + const TokenPartitionTree &token_partitions, size_t num_partitions) { // Sort UnwrappedLines from leaf partitions by size. - using partition_set_type = verible::TopN; + using partition_set_type = verible::TopN; partition_set_type partitions(num_partitions); ApplyPreOrder(token_partitions, - [&partitions](const TokenPartitionTree& node) { + [&partitions](const TokenPartitionTree &node) { if (is_leaf(node)) { // only look at leaf partitions partitions.push(&node.Value()); } @@ -117,29 +117,29 @@ std::vector FindLargestPartitions( } std::vector> FlushLeftSpacingDifferences( - const TokenPartitionRange& partitions) { + const TokenPartitionRange &partitions) { // Compute per-token differences between original spacings and reference-value // spacings. std::vector> flush_left_spacing_deltas; flush_left_spacing_deltas.reserve(partitions.size()); - for (const auto& partition : partitions) { + for (const auto &partition : partitions) { flush_left_spacing_deltas.emplace_back(); - std::vector& row(flush_left_spacing_deltas.back()); + std::vector &row(flush_left_spacing_deltas.back()); FormatTokenRange ftokens(partition.Value().TokensRange()); if (ftokens.empty()) continue; // Skip the first token, because that represents indentation. ftokens.pop_front(); - for (const auto& ftoken : ftokens) { + for (const auto &ftoken : ftokens) { row.push_back(ftoken.ExcessSpaces()); } } return flush_left_spacing_deltas; } -std::ostream& TokenPartitionTreePrinter::PrintTree(std::ostream& stream, +std::ostream &TokenPartitionTreePrinter::PrintTree(std::ostream &stream, int indent) const { - const auto& value = node.Value(); - const auto& children = node.Children(); + const auto &value = node.Value(); + const auto &children = node.Children(); stream << Spacer(indent) << "{ "; if (children.empty()) { stream << '('; @@ -160,7 +160,7 @@ std::ostream& TokenPartitionTreePrinter::PrintTree(std::ostream& stream, } stream << '\n'; // token range spans all of children nodes - for (const auto& child : children) { + for (const auto &child : children) { TokenPartitionTreePrinter(child, verbose, origin_printer) .PrintTree(stream, indent + 2) << '\n'; @@ -170,8 +170,8 @@ std::ostream& TokenPartitionTreePrinter::PrintTree(std::ostream& stream, return stream; } -std::ostream& operator<<(std::ostream& stream, - const TokenPartitionTreePrinter& printer) { +std::ostream &operator<<(std::ostream &stream, + const TokenPartitionTreePrinter &printer) { return printer.PrintTree(stream); } @@ -180,7 +180,7 @@ std::ostream& operator<<(std::ostream& stream, class BlankLineSeparatorDetector { public: // 'bounds' range must not be empty. - explicit BlankLineSeparatorDetector(const TokenPartitionRange& bounds) + explicit BlankLineSeparatorDetector(const TokenPartitionRange &bounds) : previous_end_(bounds.front() .Value() .TokensRange() @@ -188,7 +188,7 @@ class BlankLineSeparatorDetector { .token->text() .begin()) {} - bool operator()(const TokenPartitionTree& node) { + bool operator()(const TokenPartitionTree &node) { const auto range = node.Value().TokensRange(); if (range.empty()) return false; const auto begin = range.front().token->text().begin(); @@ -208,7 +208,7 @@ class BlankLineSeparatorDetector { // Subdivides the 'bounds' range into sub-ranges broken up by blank lines. static std::vector -PartitionTokenPartitionRangesAtBlankLines(const TokenPartitionRange& bounds) { +PartitionTokenPartitionRangesAtBlankLines(const TokenPartitionRange &bounds) { VLOG(2) << __FUNCTION__; std::vector subpartitions; if (bounds.empty()) return subpartitions; @@ -225,7 +225,7 @@ PartitionTokenPartitionRangesAtBlankLines(const TokenPartitionRange& bounds) { } std::vector GetSubpartitionsBetweenBlankLines( - const TokenPartitionRange& outer_partition_bounds) { + const TokenPartitionRange &outer_partition_bounds) { VLOG(2) << __FUNCTION__; std::vector result; { @@ -246,7 +246,7 @@ std::vector GetSubpartitionsBetweenBlankLines( } static absl::string_view StringSpanOfPartitionRange( - const TokenPartitionRange& range) { + const TokenPartitionRange &range) { CHECK(!range.empty()); const auto front_range = range.front().Value().TokensRange(); const auto back_range = range.back().Value().TokensRange(); @@ -258,7 +258,7 @@ static absl::string_view StringSpanOfPartitionRange( bool AnyPartitionSubRangeIsDisabled(TokenPartitionRange range, absl::string_view full_text, - const ByteOffsetSet& disabled_byte_ranges) { + const ByteOffsetSet &disabled_byte_ranges) { if (range.empty()) return false; const absl::string_view span = StringSpanOfPartitionRange(range); VLOG(4) << "text spanned: " << AutoTruncate{span, 40}; @@ -269,21 +269,21 @@ bool AnyPartitionSubRangeIsDisabled(TokenPartitionRange range, return diff != span_set; } -void AdjustIndentationRelative(TokenPartitionTree* tree, int amount) { - ApplyPreOrder(*ABSL_DIE_IF_NULL(tree), [&](UnwrappedLine& line) { +void AdjustIndentationRelative(TokenPartitionTree *tree, int amount) { + ApplyPreOrder(*ABSL_DIE_IF_NULL(tree), [&](UnwrappedLine &line) { const int new_indent = std::max(line.IndentationSpaces() + amount, 0); line.SetIndentationSpaces(new_indent); }); } -void AdjustIndentationAbsolute(TokenPartitionTree* tree, int amount) { +void AdjustIndentationAbsolute(TokenPartitionTree *tree, int amount) { // Compare the indentation difference at the root node. const int indent_diff = amount - tree->Value().IndentationSpaces(); if (indent_diff == 0) return; AdjustIndentationRelative(tree, indent_diff); } -absl::string_view StringSpanOfTokenRange(const FormatTokenRange& range) { +absl::string_view StringSpanOfTokenRange(const FormatTokenRange &range) { if (range.empty()) return {}; return make_string_view_range(range.front().Text().begin(), range.back().Text().end()); @@ -291,8 +291,8 @@ absl::string_view StringSpanOfTokenRange(const FormatTokenRange& range) { void IndentButPreserveOtherSpacing(TokenPartitionRange partition_range, absl::string_view full_text, - std::vector* ftokens) { - for (const auto& partition : partition_range) { + std::vector *ftokens) { + for (const auto &partition : partition_range) { const auto token_range = partition.Value().TokensRange(); const absl::string_view partition_text = StringSpanOfTokenRange(token_range); @@ -306,15 +306,15 @@ void IndentButPreserveOtherSpacing(TokenPartitionRange partition_range, } void ApplyAlreadyFormattedPartitionPropertiesToTokens( - TokenPartitionTree* already_formatted_partition_node, - std::vector* ftokens) { + TokenPartitionTree *already_formatted_partition_node, + std::vector *ftokens) { CHECK_NOTNULL(already_formatted_partition_node); CHECK_NOTNULL(ftokens); VLOG(4) << __FUNCTION__ << ": partition:\n" << TokenPartitionTreePrinter(*already_formatted_partition_node, true); - const auto& uwline = already_formatted_partition_node->Value(); + const auto &uwline = already_formatted_partition_node->Value(); CHECK_EQ(uwline.PartitionPolicy(), PartitionPolicyEnum::kAlreadyFormatted) << *already_formatted_partition_node; if (uwline.IsEmpty()) { @@ -329,7 +329,7 @@ void ApplyAlreadyFormattedPartitionPropertiesToTokens( mutable_tokens_begin->before.break_decision = verible::SpacingOptions::kMustWrap; - for (auto& child : already_formatted_partition_node->Children()) { + for (auto &child : already_formatted_partition_node->Children()) { auto slice = child.Value(); if (slice.PartitionPolicy() != PartitionPolicyEnum::kInline) { VLOG(1) << "Partition policy is not kInline - ignoring. Parent " @@ -348,8 +348,8 @@ void ApplyAlreadyFormattedPartitionPropertiesToTokens( auto mutable_tokens_end = ConvertToMutableIterator(uwline.TokensRange().end(), ftokens->begin()); - for (auto& token : make_range(mutable_tokens_begin, mutable_tokens_end)) { - auto& decision = token.before.break_decision; + for (auto &token : make_range(mutable_tokens_begin, mutable_tokens_end)) { + auto &decision = token.before.break_decision; if (decision == verible::SpacingOptions::kUndecided) { decision = verible::SpacingOptions::kMustAppend; } @@ -360,11 +360,11 @@ void ApplyAlreadyFormattedPartitionPropertiesToTokens( << TokenPartitionTreePrinter(*already_formatted_partition_node, true); } -void MergeConsecutiveSiblings(TokenPartitionTree* tree, size_t pos) { +void MergeConsecutiveSiblings(TokenPartitionTree *tree, size_t pos) { CHECK_NOTNULL(tree); CHECK_LT(pos + 1, tree->Children().size()); - const auto& current = tree->Children()[pos]; - const auto& next = tree->Children()[pos + 1]; + const auto ¤t = tree->Children()[pos]; + const auto &next = tree->Children()[pos + 1]; // Merge of a non-leaf partition and a leaf partition produces a non-leaf // partition with token range wider than concatenated token ranges of its // children. @@ -372,7 +372,7 @@ void MergeConsecutiveSiblings(TokenPartitionTree* tree, size_t pos) { << current << "\nright:" << next; // Effectively concatenate unwrapped line ranges of sibling subpartitions. MergeConsecutiveSiblings( - *tree, pos, [](UnwrappedLine* left, const UnwrappedLine& right) { + *tree, pos, [](UnwrappedLine *left, const UnwrappedLine &right) { // Verify token range continuity. CHECK(left->TokensRange().end() == right.TokensRange().begin()); left->SpanUpToToken(right.TokensRange().end()); @@ -381,10 +381,10 @@ void MergeConsecutiveSiblings(TokenPartitionTree* tree, size_t pos) { // From leaf node's parent upwards, update the left bound of the UnwrappedLine's // TokenRange. Stop as soon as a node is not a (leftmost) first child. -static void UpdateTokenRangeLowerBound(TokenPartitionTree* leaf, - TokenPartitionTree* last, +static void UpdateTokenRangeLowerBound(TokenPartitionTree *leaf, + TokenPartitionTree *last, format_token_iterator token_iter) { - for (auto* node = leaf; node != nullptr && node != last; + for (auto *node = leaf; node != nullptr && node != last; node = node->Parent()) { node->Value().SpanBackToToken(token_iter); } @@ -392,24 +392,24 @@ static void UpdateTokenRangeLowerBound(TokenPartitionTree* leaf, // From leaf node upwards, update the right bound of the UnwrappedLine's // TokenRange. Stop as soon as a node is not a (rightmost) last child. -static void UpdateTokenRangeUpperBound(TokenPartitionTree* leaf, - TokenPartitionTree* last, +static void UpdateTokenRangeUpperBound(TokenPartitionTree *leaf, + TokenPartitionTree *last, format_token_iterator token_iter) { - for (auto* node = leaf; node != nullptr && node != last; + for (auto *node = leaf; node != nullptr && node != last; node = node->Parent()) { node->Value().SpanUpToToken(token_iter); } } -TokenPartitionTree* GroupLeafWithPreviousLeaf(TokenPartitionTree* leaf) { +TokenPartitionTree *GroupLeafWithPreviousLeaf(TokenPartitionTree *leaf) { CHECK_NOTNULL(leaf); VLOG(4) << "origin leaf:\n" << *leaf; - auto* previous_leaf = PreviousLeaf(*leaf); + auto *previous_leaf = PreviousLeaf(*leaf); if (previous_leaf == nullptr) return nullptr; VLOG(4) << "previous leaf:\n" << *previous_leaf; // If there is no common ancestor, do nothing and return. - auto& common_ancestor = + auto &common_ancestor = *ABSL_DIE_IF_NULL(NearestCommonAncestor(*leaf, *previous_leaf)); VLOG(4) << "common ancestor:\n" << common_ancestor; @@ -417,7 +417,7 @@ TokenPartitionTree* GroupLeafWithPreviousLeaf(TokenPartitionTree* leaf) { CHECK(previous_leaf->Value().TokensRange().end() == leaf->Value().TokensRange().begin()); - auto* leaf_parent = leaf->Parent(); + auto *leaf_parent = leaf->Parent(); { // Extend the upper-bound of the previous leaf partition to cover the // partition that is about to be removed. @@ -451,15 +451,15 @@ TokenPartitionTree* GroupLeafWithPreviousLeaf(TokenPartitionTree* leaf) { } // Note: this destroys leaf -TokenPartitionTree* MergeLeafIntoPreviousLeaf(TokenPartitionTree* leaf) { +TokenPartitionTree *MergeLeafIntoPreviousLeaf(TokenPartitionTree *leaf) { CHECK_NOTNULL(leaf); VLOG(4) << "origin leaf:\n" << *leaf; - auto* target_leaf = PreviousLeaf(*leaf); + auto *target_leaf = PreviousLeaf(*leaf); if (target_leaf == nullptr) return nullptr; VLOG(4) << "target leaf:\n" << *target_leaf; // If there is no common ancestor, do nothing and return. - auto& common_ancestor = + auto &common_ancestor = *ABSL_DIE_IF_NULL(NearestCommonAncestor(*leaf, *target_leaf)); VLOG(4) << "common ancestor:\n" << common_ancestor; @@ -467,7 +467,7 @@ TokenPartitionTree* MergeLeafIntoPreviousLeaf(TokenPartitionTree* leaf) { CHECK(target_leaf->Value().TokensRange().end() == leaf->Value().TokensRange().begin()); - auto* leaf_parent = leaf->Parent(); + auto *leaf_parent = leaf->Parent(); { // Extend the upper-bound of the previous leaf partition to cover the // partition that is about to be removed. @@ -497,15 +497,15 @@ TokenPartitionTree* MergeLeafIntoPreviousLeaf(TokenPartitionTree* leaf) { } // Note: this destroys leaf -TokenPartitionTree* MergeLeafIntoNextLeaf(TokenPartitionTree* leaf) { +TokenPartitionTree *MergeLeafIntoNextLeaf(TokenPartitionTree *leaf) { CHECK_NOTNULL(leaf); VLOG(4) << "origin leaf:\n" << *leaf; - auto* target_leaf = NextLeaf(*leaf); + auto *target_leaf = NextLeaf(*leaf); if (target_leaf == nullptr) return nullptr; VLOG(4) << "target leaf:\n" << *target_leaf; // If there is no common ancestor, do nothing and return. - auto& common_ancestor = + auto &common_ancestor = *ABSL_DIE_IF_NULL(NearestCommonAncestor(*leaf, *target_leaf)); VLOG(4) << "common ancestor:\n" << common_ancestor; @@ -513,7 +513,7 @@ TokenPartitionTree* MergeLeafIntoNextLeaf(TokenPartitionTree* leaf) { CHECK(target_leaf->Value().TokensRange().begin() == leaf->Value().TokensRange().end()); - auto* leaf_parent = leaf->Parent(); + auto *leaf_parent = leaf->Parent(); { // Extend the lower-bound of the next leaf partition to cover the // partition that is about to be removed. @@ -551,12 +551,12 @@ TokenPartitionTree* MergeLeafIntoNextLeaf(TokenPartitionTree* leaf) { class TokenPartitionTreeWrapper { public: /* implicit */ TokenPartitionTreeWrapper( // NOLINT - const TokenPartitionTree& node) + const TokenPartitionTree &node) : node_(&node) {} // Grouping node with no corresponding TokenPartitionTree node /* implicit */ TokenPartitionTreeWrapper( // NOLINT - const UnwrappedLine& unwrapped_line) + const UnwrappedLine &unwrapped_line) : node_(nullptr) { unwrapped_line_ = std::make_unique(unwrapped_line); } @@ -564,7 +564,7 @@ class TokenPartitionTreeWrapper { // At least one of node_ or unwrapped_line_ should not be nullptr TokenPartitionTreeWrapper() = delete; - TokenPartitionTreeWrapper(const TokenPartitionTreeWrapper& other) { + TokenPartitionTreeWrapper(const TokenPartitionTreeWrapper &other) { CHECK((other.node_ != nullptr) || (other.unwrapped_line_ != nullptr)); if (other.node_) { @@ -576,12 +576,12 @@ class TokenPartitionTreeWrapper { } // Return wrapped node value or concatenation of subnodes values - const UnwrappedLine& Value() const { + const UnwrappedLine &Value() const { return node_ ? node_->Value() : *unwrapped_line_; } // Concatenate subnodes value with other node value - UnwrappedLine Value(const TokenPartitionTree& other) const { + UnwrappedLine Value(const TokenPartitionTree &other) const { CHECK((node_ == nullptr) && (unwrapped_line_ != nullptr)); UnwrappedLine uw = *unwrapped_line_; uw.SpanUpToToken(other.Value().TokensRange().end()); @@ -589,9 +589,9 @@ class TokenPartitionTreeWrapper { } // Update concatenated value of subnodes - void Update(const VectorTree* child) { - const auto& token_partition_tree_wrapper = child->Value(); - const auto& uwline = token_partition_tree_wrapper.Value(); + void Update(const VectorTree *child) { + const auto &token_partition_tree_wrapper = child->Value(); + const auto &uwline = token_partition_tree_wrapper.Value(); unwrapped_line_->SpanUpToToken(uwline.TokensRange().end()); } @@ -603,11 +603,11 @@ class TokenPartitionTreeWrapper { } // Return address to wrapped node - const TokenPartitionTree* Node() const { return node_; } + const TokenPartitionTree *Node() const { return node_; } private: // Wrapped node - const TokenPartitionTree* node_; + const TokenPartitionTree *node_; // Concatenated value of subnodes std::unique_ptr unwrapped_line_; @@ -649,9 +649,9 @@ struct AppendFittingSubpartitionsResult { // // static AppendFittingSubpartitionsResult AppendFittingSubpartitions( - VectorTree* fitted_partitions, - const TokenPartitionTree& header, const partition_range& subpartitions, - const TokenPartitionTree* trailer, const BasicFormatStyle& style, + VectorTree *fitted_partitions, + const TokenPartitionTree &header, const partition_range &subpartitions, + const TokenPartitionTree *trailer, const BasicFormatStyle &style, bool one_per_line, bool wrap_first_subpartition) { // at least one argument CHECK_GE(subpartitions.size(), 1); @@ -659,14 +659,14 @@ static AppendFittingSubpartitionsResult AppendFittingSubpartitions( // Create first partition group // and populate it with function name (e.g. { [function foo (] }) fitted_partitions->Children().emplace_back(header.Value()); - auto* group = &fitted_partitions->Children().back(); + auto *group = &fitted_partitions->Children().back(); group->Children().emplace_back(header); int indent; // Try appending first argument - const TokenPartitionTree& first_arg = subpartitions.front(); + const TokenPartitionTree &first_arg = subpartitions.front(); verible::UnwrappedLine first_line = group->Value().Value(first_arg); if (trailer && subpartitions.size() == 1) { first_line.SpanUpToToken(trailer->Value().TokensRange().end()); @@ -679,7 +679,7 @@ static AppendFittingSubpartitionsResult AppendFittingSubpartitions( wrap_first_subpartition || !fit_result.fits; if (!wrapped_first_subpartition) { // Compute new indentation level based on first partition - const UnwrappedLine& uwline = group->Value().Value(); + const UnwrappedLine &uwline = group->Value().Value(); indent = FitsOnLine(uwline, style).final_column; // Append first argument to current group @@ -696,7 +696,7 @@ static AppendFittingSubpartitionsResult AppendFittingSubpartitions( // Use original indentation of the subpartition indent = first_arg.Value().IndentationSpaces(); // wrap line - auto& siblings = group->Parent()->Children(); + auto &siblings = group->Parent()->Children(); siblings.emplace_back(first_arg.Value()); group = &siblings.back(); group->Children().emplace_back(first_arg); @@ -709,7 +709,7 @@ static AppendFittingSubpartitionsResult AppendFittingSubpartitions( const auto remaining_args = make_container_range(subpartitions.begin() + 1, subpartitions.end()); - for (const auto& arg : remaining_args) { + for (const auto &arg : remaining_args) { // Every group should have at least one child CHECK(!group->Children().empty()); @@ -732,7 +732,7 @@ static AppendFittingSubpartitionsResult AppendFittingSubpartitions( } // Forced one per line or does not fit, start new group with current child - auto& siblings = group->Parent()->Children(); + auto &siblings = group->Parent()->Children(); siblings.emplace_back(arg.Value()); group = &siblings.back(); group->Children().emplace_back(arg); @@ -747,7 +747,7 @@ static AppendFittingSubpartitionsResult AppendFittingSubpartitions( } if (trailer) { if (wrapped_first_subpartition) { - auto& siblings = group->Parent()->Children(); + auto &siblings = group->Parent()->Children(); siblings.emplace_back(trailer->Value()); group = &siblings.back(); group->Children().emplace_back(*trailer); @@ -783,10 +783,10 @@ static AppendFittingSubpartitionsResult AppendFittingSubpartitions( // // When "subpartitions" group has kAlwaysExpand policy, line break is forced // between each subpartition from the group. -void ReshapeFittingSubpartitions(const BasicFormatStyle& style, - TokenPartitionTree* node) { +void ReshapeFittingSubpartitions(const BasicFormatStyle &style, + TokenPartitionTree *node) { VLOG(4) << __FUNCTION__ << ", before:\n" << *node; - VectorTree* fitted_tree = nullptr; + VectorTree *fitted_tree = nullptr; // Leaf or simple node, e.g. '[function foo ( ) ;]' if (node->Children().size() < 2) { @@ -795,11 +795,11 @@ void ReshapeFittingSubpartitions(const BasicFormatStyle& style, } // Partition with arguments should have at least one argument - const auto& children = node->Children(); - const auto& header = children[0]; - const auto& args_partition = children[1]; - const auto& subpartitions = args_partition.Children(); - const auto* trailer = children.size() > 2 ? &children[2] : nullptr; + const auto &children = node->Children(); + const auto &header = children[0]; + const auto &args_partition = children[1]; + const auto &subpartitions = args_partition.Children(); + const auto *trailer = children.size() > 2 ? &children[2] : nullptr; const bool one_per_line = args_partition.Value().PartitionPolicy() == PartitionPolicyEnum::kAlwaysExpand; @@ -855,7 +855,7 @@ void ReshapeFittingSubpartitions(const BasicFormatStyle& style, TokenPartitionTree temporary_tree(node->Value()); // Iterate over partition groups - for (const auto& itr : fitted_tree->Children()) { + for (const auto &itr : fitted_tree->Children()) { auto uwline = itr.Value().Value(); // Partitions groups should fit in line but we're // leaving final decision to ExpandableTreeView @@ -863,12 +863,12 @@ void ReshapeFittingSubpartitions(const BasicFormatStyle& style, // Create new grouping node temporary_tree.Children().emplace_back(uwline); - auto* group = &temporary_tree.Children().back(); + auto *group = &temporary_tree.Children().back(); // Iterate over partitions in group - for (const auto& partition : itr.Children()) { + for (const auto &partition : itr.Children()) { // access partition_node_type - const auto* node = partition.Value().Node(); + const auto *node = partition.Value().Node(); // Append child (warning contains original indentation) group->Children().push_back(*node); @@ -877,8 +877,8 @@ void ReshapeFittingSubpartitions(const BasicFormatStyle& style, // Update grouped childrens indentation in case of expanding grouping // partitions - for (auto& group : temporary_tree.Children()) { - for (auto& subpart : group.Children()) { + for (auto &group : temporary_tree.Children()) { + for (auto &subpart : group.Children()) { AdjustIndentationAbsolute(&subpart, group.Value().IndentationSpaces()); } } diff --git a/common/formatting/token_partition_tree.h b/common/formatting/token_partition_tree.h index b9ec2704c..a5054a8db 100644 --- a/common/formatting/token_partition_tree.h +++ b/common/formatting/token_partition_tree.h @@ -50,25 +50,25 @@ using TokenPartitionRange = container_iterator_range; // ranges. This function fails with a fatal-error like CHECK() if the // invariants do not hold true. void VerifyTreeNodeFormatTokenRanges( - const TokenPartitionTree& node, + const TokenPartitionTree &node, std::vector::const_iterator base); // Verifies TokenPartitionTree invariants at every node in the tree, // which covers and entire hierarchical partition of format tokens. void VerifyFullTreeFormatTokenRanges( - const TokenPartitionTree& tree, + const TokenPartitionTree &tree, std::vector::const_iterator base); // Returns the largest leaf partitions of tokens, ordered by number of tokens // spanned. -std::vector FindLargestPartitions( - const TokenPartitionTree& token_partitions, size_t num_partitions); +std::vector FindLargestPartitions( + const TokenPartitionTree &token_partitions, size_t num_partitions); // Compute (original_spacing - spaces_required) for every format token, // except the first token in each partition. // A perfectly formatted (flushed-left) original spacing will return all zeros. std::vector> FlushLeftSpacingDifferences( - const TokenPartitionRange& partitions); + const TokenPartitionRange &partitions); // Custom printer, alternative to the default stream operator<<. // Modeled after VectorTree<>::PrintTree, but suppresses printing of the @@ -77,23 +77,23 @@ std::vector> FlushLeftSpacingDifferences( // Usage: stream << TokenPartitionTreePrinter(tree) << std::endl; struct TokenPartitionTreePrinter { explicit TokenPartitionTreePrinter( - const TokenPartitionTree& n, bool verbose = false, + const TokenPartitionTree &n, bool verbose = false, UnwrappedLine::OriginPrinterFunction origin_printer = UnwrappedLine::DefaultOriginPrinter) : node(n), verbose(verbose), origin_printer(std::move(origin_printer)) {} - std::ostream& PrintTree(std::ostream& stream, int indent = 0) const; + std::ostream &PrintTree(std::ostream &stream, int indent = 0) const; // The (sub)tree to display. - const TokenPartitionTree& node; + const TokenPartitionTree &node; // If true, display inter-token information. bool verbose; UnwrappedLine::OriginPrinterFunction origin_printer; }; -std::ostream& operator<<(std::ostream& stream, - const TokenPartitionTreePrinter& printer); +std::ostream &operator<<(std::ostream &stream, + const TokenPartitionTreePrinter &printer); // Returns true if any substring range spanned by the token partition 'range' is // disabled by 'disabled_byte_ranges'. @@ -101,45 +101,45 @@ std::ostream& operator<<(std::ostream& stream, // tokens were lexed, and is used in byte-offset calculation. bool AnyPartitionSubRangeIsDisabled(TokenPartitionRange range, absl::string_view full_text, - const ByteOffsetSet& disabled_byte_ranges); + const ByteOffsetSet &disabled_byte_ranges); // Return ranges of subpartitions separated by blank lines. // This does not modify the partition, but does return ranges of mutable // iterators of partitions. std::vector GetSubpartitionsBetweenBlankLines( - const TokenPartitionRange&); + const TokenPartitionRange &); // Transformations (modifying): // Adds or removes a constant amount of indentation from entire token // partition tree. Relative indentation amount may be positive or negative. // Final indentation will be at least 0, and never go negative. -void AdjustIndentationRelative(TokenPartitionTree* tree, int amount); +void AdjustIndentationRelative(TokenPartitionTree *tree, int amount); // Adjusts indentation to align root of partition tree to new indentation // amount. -void AdjustIndentationAbsolute(TokenPartitionTree* tree, int amount); +void AdjustIndentationAbsolute(TokenPartitionTree *tree, int amount); // Returns the range of text spanned by tokens range. -absl::string_view StringSpanOfTokenRange(const FormatTokenRange& range); +absl::string_view StringSpanOfTokenRange(const FormatTokenRange &range); // Mark ranges of tokens (corresponding to formatting-disabled lines) to // have their original spacing preserved, except allow the first token // to follow the formatter's calculated indentation. void IndentButPreserveOtherSpacing(TokenPartitionRange partition_range, absl::string_view full_text, - std::vector* ftokens); + std::vector *ftokens); // Finalizes formatting of a partition with kAlreadyFormatted policy and // optional kTokenModifer subpartitions. // Spacing described by the partitions is applied to underlying tokens. All // subpartitions of the passed node are removed. void ApplyAlreadyFormattedPartitionPropertiesToTokens( - TokenPartitionTree* already_formatted_partition_node, - std::vector* ftokens); + TokenPartitionTree *already_formatted_partition_node, + std::vector *ftokens); // Merges the two subpartitions of tree at index pos and pos+1. -void MergeConsecutiveSiblings(TokenPartitionTree* tree, size_t pos); +void MergeConsecutiveSiblings(TokenPartitionTree *tree, size_t pos); // Groups this leaf with the leaf partition that preceded it, which could be // a distant relative. The grouping node is created in place of the preceding @@ -148,7 +148,7 @@ void MergeConsecutiveSiblings(TokenPartitionTree* tree, size_t pos); // policies. The group partition's indentation level and partition policy is // copied from the first partition in the group. // Returns the grouped partition if operation succeeded, else nullptr. -TokenPartitionTree* GroupLeafWithPreviousLeaf(TokenPartitionTree* leaf); +TokenPartitionTree *GroupLeafWithPreviousLeaf(TokenPartitionTree *leaf); // Merges this leaf into the leaf partition that preceded it, which could be // a distant relative. The leaf is destroyed in the process. @@ -157,7 +157,7 @@ TokenPartitionTree* GroupLeafWithPreviousLeaf(TokenPartitionTree* leaf); // (If you need that information, save it before moving the leaf.) // Returns the parent of the leaf partition that was moved if the move // occurred, else nullptr. -TokenPartitionTree* MergeLeafIntoPreviousLeaf(TokenPartitionTree* leaf); +TokenPartitionTree *MergeLeafIntoPreviousLeaf(TokenPartitionTree *leaf); // Merges this leaf into the leaf partition that follows it, which could be // a distant relative. The leaf is destroyed in the process. @@ -166,7 +166,7 @@ TokenPartitionTree* MergeLeafIntoPreviousLeaf(TokenPartitionTree* leaf); // (If you need that information, save it before moving the leaf.) // Returns the parent of the leaf partition that was moved if the move // occurred, else nullptr. -TokenPartitionTree* MergeLeafIntoNextLeaf(TokenPartitionTree* leaf); +TokenPartitionTree *MergeLeafIntoNextLeaf(TokenPartitionTree *leaf); // Evaluates two partitioning schemes wrapped and appended first // subpartition. Then reshapes node tree according to scheme with less @@ -250,8 +250,8 @@ TokenPartitionTree* MergeLeafIntoNextLeaf(TokenPartitionTree* leaf); // { (>>>>>>[type_f ffff ) ;]) } // } // } -void ReshapeFittingSubpartitions(const verible::BasicFormatStyle& style, - TokenPartitionTree* node); +void ReshapeFittingSubpartitions(const verible::BasicFormatStyle &style, + TokenPartitionTree *node); } // namespace verible diff --git a/common/formatting/token_partition_tree_test.cc b/common/formatting/token_partition_tree_test.cc index 0050a8602..2d42b6bce 100644 --- a/common/formatting/token_partition_tree_test.cc +++ b/common/formatting/token_partition_tree_test.cc @@ -64,7 +64,7 @@ class VerifyFullTreeFormatTokenRangesTest TEST_F(VerifyFullTreeFormatTokenRangesTest, ParentChildRangeBeginMismatch) { // Construct three partitions, sizes: 1, 3, 2 - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); // one short of partition0's begin, and will fail invariant. UnwrappedLine all(0, begin + 1); @@ -91,7 +91,7 @@ TEST_F(VerifyFullTreeFormatTokenRangesTest, ParentChildRangeBeginMismatch) { TEST_F(VerifyFullTreeFormatTokenRangesTest, ParentChildRangeEndMismatch) { // Construct three partitions, sizes: 1, 3, 2 - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); // one short of partition2's end, and will fail invariant. @@ -118,7 +118,7 @@ TEST_F(VerifyFullTreeFormatTokenRangesTest, ParentChildRangeEndMismatch) { TEST_F(VerifyFullTreeFormatTokenRangesTest, ChildrenRangeDiscontinuity) { // Construct three partitions, sizes: 1, 3, 2 - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(preformat_tokens.end()); @@ -148,7 +148,7 @@ class FindLargestPartitionsTest : public TokenPartitionTreeTestFixture {}; // Verify that this finds the K largest leaf partitions. TEST_F(FindLargestPartitionsTest, VectorTree) { // Construct three partitions, sizes: 1, 3, 2 - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(preformat_tokens.end()); @@ -179,7 +179,7 @@ TEST_F(FindLargestPartitionsTest, VectorTree) { class FlushLeftSpacingDifferencesTest : public TokenPartitionTreeTestFixture {}; TEST_F(FlushLeftSpacingDifferencesTest, EmptyPartitions) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); TokenPartitionTree tree{all}; // no children @@ -191,7 +191,7 @@ TEST_F(FlushLeftSpacingDifferencesTest, EmptyPartitions) { } TEST_F(FlushLeftSpacingDifferencesTest, OnePartitionsOneToken) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(begin + 1); @@ -207,7 +207,7 @@ TEST_F(FlushLeftSpacingDifferencesTest, OnePartitionsOneToken) { } TEST_F(FlushLeftSpacingDifferencesTest, OnePartitionsTwoTokens) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(begin + 2); @@ -223,7 +223,7 @@ TEST_F(FlushLeftSpacingDifferencesTest, OnePartitionsTwoTokens) { } TEST_F(FlushLeftSpacingDifferencesTest, TwoPartitionsOneTokenEach) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(begin + 2); @@ -241,7 +241,7 @@ TEST_F(FlushLeftSpacingDifferencesTest, TwoPartitionsOneTokenEach) { } TEST_F(FlushLeftSpacingDifferencesTest, TwoPartitionsTwoTokensEach) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(begin + 4); @@ -268,7 +268,7 @@ TEST_F(TokenPartitionTreePrinterTest, VectorTreeShallow) { pre_format_tokens_[3].before.break_decision = SpacingOptions::kMustAppend; pre_format_tokens_[4].before.break_penalty = 22; pre_format_tokens_[5].before.break_decision = SpacingOptions::kMustWrap; - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(preformat_tokens.end()); @@ -310,7 +310,7 @@ TEST_F(TokenPartitionTreePrinterTest, VectorTreeShallow) { TEST_F(TokenPartitionTreePrinterTest, VectorTreeDeep) { // Construct partitions, sizes: 1, (2, 1), (1, 1) - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(preformat_tokens.end()); @@ -364,7 +364,7 @@ TEST_F(TokenPartitionTreePrinterTest, VectorTreeDeep) { class AdjustIndentationTest : public TokenPartitionTreeTestFixture {}; TEST_F(AdjustIndentationTest, Relative) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(5, begin); all.SpanUpToToken(preformat_tokens.end()); @@ -394,7 +394,7 @@ TEST_F(AdjustIndentationTest, Relative) { } TEST_F(AdjustIndentationTest, Absolute) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(5, begin); all.SpanUpToToken(preformat_tokens.end()); @@ -423,8 +423,8 @@ TEST_F(AdjustIndentationTest, Absolute) { EXPECT_EQ(tree.Children().front().Value().IndentationSpaces(), 2); } -static bool PropertiesEqual(const UnwrappedLine& left, - const UnwrappedLine& right) { +static bool PropertiesEqual(const UnwrappedLine &left, + const UnwrappedLine &right) { return (left.TokensRange() == right.TokensRange() && left.IndentationSpaces() == right.IndentationSpaces() && left.PartitionPolicy() == right.PartitionPolicy()); @@ -433,7 +433,7 @@ static bool PropertiesEqual(const UnwrappedLine& left, class GroupLeafWithPreviousLeafTest : public TokenPartitionTreeTestFixture {}; TEST_F(GroupLeafWithPreviousLeafTest, RootOnly) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(preformat_tokens.end()); @@ -445,7 +445,7 @@ TEST_F(GroupLeafWithPreviousLeafTest, RootOnly) { }; const auto saved_tree(tree); // deep copy - auto* group = GroupLeafWithPreviousLeaf(&tree); + auto *group = GroupLeafWithPreviousLeaf(&tree); EXPECT_EQ(group, nullptr); // Expect no change. @@ -456,7 +456,7 @@ TEST_F(GroupLeafWithPreviousLeafTest, RootOnly) { } TEST_F(GroupLeafWithPreviousLeafTest, OneChild) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(preformat_tokens.end()); @@ -469,7 +469,7 @@ TEST_F(GroupLeafWithPreviousLeafTest, OneChild) { ASSERT_FALSE(is_leaf(tree)); const auto saved_tree(tree); // deep copy - auto* group = GroupLeafWithPreviousLeaf(&tree.Children().front()); + auto *group = GroupLeafWithPreviousLeaf(&tree.Children().front()); EXPECT_EQ(group, nullptr); // Expect no change. @@ -480,7 +480,7 @@ TEST_F(GroupLeafWithPreviousLeafTest, OneChild) { } TEST_F(GroupLeafWithPreviousLeafTest, TwoChild) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); // Construct an artificial tree using the following partitions. @@ -516,7 +516,7 @@ TEST_F(GroupLeafWithPreviousLeafTest, TwoChild) { }, }; - auto* group = GroupLeafWithPreviousLeaf(&tree.Children().back()); + auto *group = GroupLeafWithPreviousLeaf(&tree.Children().back()); EXPECT_EQ(group, &tree.Children().back()); const auto diff = DeepEqual(tree, expected_tree, PropertiesEqual); @@ -526,7 +526,7 @@ TEST_F(GroupLeafWithPreviousLeafTest, TwoChild) { } TEST_F(GroupLeafWithPreviousLeafTest, TwoGenerations) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); // Construct an artificial tree using the following partitions. @@ -567,7 +567,7 @@ TEST_F(GroupLeafWithPreviousLeafTest, TwoGenerations) { }, }; - auto* group = GroupLeafWithPreviousLeaf(&tree.Children().back()); + auto *group = GroupLeafWithPreviousLeaf(&tree.Children().back()); EXPECT_EQ(group, &tree.Children().back().Children().back()); const auto diff = DeepEqual(tree, expected_tree, PropertiesEqual); @@ -577,7 +577,7 @@ TEST_F(GroupLeafWithPreviousLeafTest, TwoGenerations) { } TEST_F(GroupLeafWithPreviousLeafTest, Cousins) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); // Construct an artificial tree using the following partitions. @@ -632,7 +632,7 @@ TEST_F(GroupLeafWithPreviousLeafTest, Cousins) { }, }; - auto* group = + auto *group = GroupLeafWithPreviousLeaf(&tree.Children().back().Children().front()); EXPECT_EQ(group, &tree.Children().front().Children().back()); @@ -643,7 +643,7 @@ TEST_F(GroupLeafWithPreviousLeafTest, Cousins) { } TEST_F(GroupLeafWithPreviousLeafTest, ExtendCommonAncestor) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); // Construct an artificial tree using the following partitions. @@ -678,7 +678,7 @@ TEST_F(GroupLeafWithPreviousLeafTest, ExtendCommonAncestor) { }, }; - auto* group = GroupLeafWithPreviousLeaf(&tree.Children().back()); + auto *group = GroupLeafWithPreviousLeaf(&tree.Children().back()); EXPECT_EQ(group, &tree.Children().back()); const auto diff = DeepEqual(tree, expected_tree, PropertiesEqual); @@ -687,15 +687,15 @@ TEST_F(GroupLeafWithPreviousLeafTest, ExtendCommonAncestor) { << *diff.right << '\n'; } -static bool TokenRangeEqual(const UnwrappedLine& left, - const UnwrappedLine& right) { +static bool TokenRangeEqual(const UnwrappedLine &left, + const UnwrappedLine &right) { return left.TokensRange() == right.TokensRange(); } class MergeLeafIntoPreviousLeafTest : public TokenPartitionTreeTestFixture {}; TEST_F(MergeLeafIntoPreviousLeafTest, RootOnly) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(preformat_tokens.end()); @@ -707,7 +707,7 @@ TEST_F(MergeLeafIntoPreviousLeafTest, RootOnly) { }; const auto saved_tree(tree); // deep copy - auto* parent = MergeLeafIntoPreviousLeaf(&tree); + auto *parent = MergeLeafIntoPreviousLeaf(&tree); EXPECT_EQ(parent, nullptr); // Expect no change. @@ -718,7 +718,7 @@ TEST_F(MergeLeafIntoPreviousLeafTest, RootOnly) { } TEST_F(MergeLeafIntoPreviousLeafTest, OneChild) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(preformat_tokens.end()); @@ -731,7 +731,7 @@ TEST_F(MergeLeafIntoPreviousLeafTest, OneChild) { ASSERT_FALSE(is_leaf(tree)); const auto saved_tree(tree); // deep copy - auto* parent = MergeLeafIntoPreviousLeaf(&tree.Children().front()); + auto *parent = MergeLeafIntoPreviousLeaf(&tree.Children().front()); EXPECT_EQ(parent, nullptr); // Expect no change. @@ -742,7 +742,7 @@ TEST_F(MergeLeafIntoPreviousLeafTest, OneChild) { } TEST_F(MergeLeafIntoPreviousLeafTest, TwoChild) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); // Construct an artificial tree using the following partitions. @@ -765,7 +765,7 @@ TEST_F(MergeLeafIntoPreviousLeafTest, TwoChild) { tree_type{all}, }; - auto* parent = MergeLeafIntoPreviousLeaf(&tree.Children().back()); + auto *parent = MergeLeafIntoPreviousLeaf(&tree.Children().back()); EXPECT_EQ(parent, &tree); const auto diff = DeepEqual(tree, expected_tree, TokenRangeEqual); @@ -775,7 +775,7 @@ TEST_F(MergeLeafIntoPreviousLeafTest, TwoChild) { } TEST_F(MergeLeafIntoPreviousLeafTest, TwoGenerations) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); // Construct an artificial tree using the following partitions. @@ -812,7 +812,7 @@ TEST_F(MergeLeafIntoPreviousLeafTest, TwoGenerations) { }, }; - auto* parent = MergeLeafIntoPreviousLeaf(&tree.Children().back()); + auto *parent = MergeLeafIntoPreviousLeaf(&tree.Children().back()); EXPECT_EQ(parent, &tree); const auto diff = DeepEqual(tree, expected_tree, TokenRangeEqual); @@ -822,7 +822,7 @@ TEST_F(MergeLeafIntoPreviousLeafTest, TwoGenerations) { } TEST_F(MergeLeafIntoPreviousLeafTest, Cousins) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); // Construct an artificial tree using the following partitions. @@ -873,7 +873,7 @@ TEST_F(MergeLeafIntoPreviousLeafTest, Cousins) { }, }; - auto* parent = + auto *parent = MergeLeafIntoPreviousLeaf(&tree.Children().back().Children().front()); EXPECT_EQ(parent, &tree.Children().back()); @@ -886,7 +886,7 @@ TEST_F(MergeLeafIntoPreviousLeafTest, Cousins) { class MergeLeafIntoNextLeafTest : public TokenPartitionTreeTestFixture {}; TEST_F(MergeLeafIntoNextLeafTest, RootOnly) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(preformat_tokens.end()); @@ -898,7 +898,7 @@ TEST_F(MergeLeafIntoNextLeafTest, RootOnly) { }; const auto saved_tree(tree); // deep copy - auto* parent = MergeLeafIntoNextLeaf(&tree); + auto *parent = MergeLeafIntoNextLeaf(&tree); EXPECT_EQ(parent, nullptr); // Expect no change. @@ -909,7 +909,7 @@ TEST_F(MergeLeafIntoNextLeafTest, RootOnly) { } TEST_F(MergeLeafIntoNextLeafTest, OneChild) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(preformat_tokens.end()); @@ -922,7 +922,7 @@ TEST_F(MergeLeafIntoNextLeafTest, OneChild) { ASSERT_FALSE(is_leaf(tree)); const auto saved_tree(tree); // deep copy - auto* parent = MergeLeafIntoNextLeaf(&tree.Children().front()); + auto *parent = MergeLeafIntoNextLeaf(&tree.Children().front()); EXPECT_EQ(parent, nullptr); // Expect no change. @@ -933,7 +933,7 @@ TEST_F(MergeLeafIntoNextLeafTest, OneChild) { } TEST_F(MergeLeafIntoNextLeafTest, TwoChild) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); // Construct an artificial tree using the following partitions. @@ -956,7 +956,7 @@ TEST_F(MergeLeafIntoNextLeafTest, TwoChild) { tree_type{all}, }; - auto* parent = MergeLeafIntoNextLeaf(&tree.Children().front()); + auto *parent = MergeLeafIntoNextLeaf(&tree.Children().front()); EXPECT_EQ(parent, &tree); const auto diff = DeepEqual(tree, expected_tree, TokenRangeEqual); @@ -966,7 +966,7 @@ TEST_F(MergeLeafIntoNextLeafTest, TwoChild) { } TEST_F(MergeLeafIntoNextLeafTest, TwoGenerations) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); // Construct an artificial tree using the following partitions. @@ -1004,7 +1004,7 @@ TEST_F(MergeLeafIntoNextLeafTest, TwoGenerations) { tree_type{fused_part}, // fused target partition }; - auto* parent = + auto *parent = MergeLeafIntoNextLeaf(&tree.Children().front().Children().back()); EXPECT_EQ(parent, &tree.Children().front()); @@ -1015,7 +1015,7 @@ TEST_F(MergeLeafIntoNextLeafTest, TwoGenerations) { } TEST_F(MergeLeafIntoNextLeafTest, Cousins) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); // Construct an artificial tree using the following partitions. @@ -1067,7 +1067,7 @@ TEST_F(MergeLeafIntoNextLeafTest, Cousins) { }, }; - auto* parent = + auto *parent = MergeLeafIntoNextLeaf(&tree.Children().front().Children().back()); EXPECT_EQ(parent, &tree.Children().front()); @@ -1080,7 +1080,7 @@ TEST_F(MergeLeafIntoNextLeafTest, Cousins) { class MergeConsecutiveSiblingsTest : public TokenPartitionTreeTestFixture {}; TEST_F(MergeConsecutiveSiblingsTest, OneChild) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(preformat_tokens.end()); @@ -1096,7 +1096,7 @@ TEST_F(MergeConsecutiveSiblingsTest, OneChild) { } TEST_F(MergeConsecutiveSiblingsTest, TwoChild) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); // Construct an artificial tree using the following partitions. @@ -1126,7 +1126,7 @@ TEST_F(MergeConsecutiveSiblingsTest, TwoChild) { } TEST_F(MergeConsecutiveSiblingsTest, TwoGenerations) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); // Construct an artificial tree using the following partitions. @@ -1184,7 +1184,7 @@ class AnyPartitionSubRangeIsDisabledTest TEST_F(AnyPartitionSubRangeIsDisabledTest, Various) { // Construct three partitions, sizes: 1, 3, 2 - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(preformat_tokens.end()); @@ -1248,7 +1248,7 @@ class GetSubpartitionsBetweenBlankLinesTest CreateTokenInfosExternalStringBuffer(ftokens_); // Establish format token ranges per partition. - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(preformat_tokens.end()); @@ -1335,7 +1335,7 @@ class IndentButPreserveOtherSpacingTest : public TokenPartitionTreeTestFixture { TEST_F(IndentButPreserveOtherSpacingTest, Various) { // Construct three partitions, sizes: 1, 3, 2 - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); all.SpanUpToToken(preformat_tokens.end()); @@ -1360,11 +1360,11 @@ TEST_F(IndentButPreserveOtherSpacingTest, Various) { IndentButPreserveOtherSpacing(range, joined_token_text_, &pre_format_tokens_); // The first tokens on each partition need not be preserved, but all // subsequent tokens should be preserved. - for (const auto& child : range) { + for (const auto &child : range) { auto token_range = child.Value().TokensRange(); if (token_range.empty()) continue; token_range.pop_front(); - for (const auto& ftoken : token_range) { + for (const auto &ftoken : token_range) { EXPECT_EQ(ftoken.before.break_decision, SpacingOptions::kPreserve); } } @@ -1373,7 +1373,7 @@ TEST_F(IndentButPreserveOtherSpacingTest, Various) { class ReshapeFittingSubpartitionsTest : public TokenPartitionTreeTestFixture {}; TEST_F(ReshapeFittingSubpartitionsTest, NoArguments) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine header(0, begin); @@ -1403,7 +1403,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, NoArguments) { } TEST_F(ReshapeFittingSubpartitionsTest, OneArgumentInSubpartition) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine header(0, begin); @@ -1445,7 +1445,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, OneArgumentInSubpartition) { } TEST_F(ReshapeFittingSubpartitionsTest, OneArgumentInSubpartitionAndTrailer) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine header(0, begin); @@ -1491,7 +1491,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, OneArgumentInSubpartitionAndTrailer) { } TEST_F(ReshapeFittingSubpartitionsTest, OneArgumentFlat) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine header(0, begin); @@ -1528,7 +1528,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, OneArgumentFlat) { } TEST_F(ReshapeFittingSubpartitionsTest, OneArgumentFlatAndTrailer) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine header(0, begin); @@ -1571,7 +1571,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, OneArgumentFlatAndTrailer) { } TEST_F(ReshapeFittingSubpartitionsTest, TwoArguments) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine header(0, begin); @@ -1621,7 +1621,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, TwoArguments) { } TEST_F(ReshapeFittingSubpartitionsTest, TwoArgumentsAndTrailer) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine header(0, begin); @@ -1677,7 +1677,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, TwoArgumentsAndTrailer) { // All fits in one partition TEST_F(ReshapeFittingSubpartitionsTest, OnePartition) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine header(0, begin); @@ -1740,7 +1740,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, OnePartition) { // All fits in one partition TEST_F(ReshapeFittingSubpartitionsTest, OnePartitionWithTrailer) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine header(0, begin); @@ -1804,7 +1804,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, OnePartitionWithTrailer) { // Wrap into two partitions TEST_F(ReshapeFittingSubpartitionsTest, TwoPartitions) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine header(0, begin); @@ -1879,7 +1879,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, TwoPartitions) { // Wrap into two partitions TEST_F(ReshapeFittingSubpartitionsTest, TwoPartitionsWithTrailer) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine header(0, begin); @@ -1955,7 +1955,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, TwoPartitionsWithTrailer) { // None fits TEST_F(ReshapeFittingSubpartitionsTest, NoneOneFits) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine header(0, begin); @@ -1995,8 +1995,8 @@ TEST_F(ReshapeFittingSubpartitionsTest, NoneOneFits) { }, }; - ApplyPreOrder(tree.Children()[1], [&style](TokenPartitionTree& node) { - auto& uwline = node.Value(); + ApplyPreOrder(tree.Children()[1], [&style](TokenPartitionTree &node) { + auto &uwline = node.Value(); uwline.SetIndentationSpaces(style.wrap_spaces); }); @@ -2025,7 +2025,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, NoneOneFits) { // None fits TEST_F(ReshapeFittingSubpartitionsTest, NoneOneFitsWithTrailer) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); verible::BasicFormatStyle style; // default @@ -2092,7 +2092,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, NoneOneFitsWithTrailer) { // All fits in one partition TEST_F(ReshapeFittingSubpartitionsTest, IndentationOnePartition) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine header(0, begin); @@ -2131,8 +2131,8 @@ TEST_F(ReshapeFittingSubpartitionsTest, IndentationOnePartition) { }, }; - ApplyPreOrder(tree.Children()[1], [&style](TokenPartitionTree& node) { - auto& uwline = node.Value(); + ApplyPreOrder(tree.Children()[1], [&style](TokenPartitionTree &node) { + auto &uwline = node.Value(); uwline.SetIndentationSpaces(3 + style.indentation_spaces); }); @@ -2166,7 +2166,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, IndentationOnePartition) { // All fits in one partition TEST_F(ReshapeFittingSubpartitionsTest, IndentationOnePartitionWithTrailer) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); verible::BasicFormatStyle style; // default @@ -2233,7 +2233,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, IndentationOnePartitionWithTrailer) { // Wrap into two partitions TEST_F(ReshapeFittingSubpartitionsTest, IndentationTwoPartitions) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine header(0, begin); @@ -2273,8 +2273,8 @@ TEST_F(ReshapeFittingSubpartitionsTest, IndentationTwoPartitions) { verible::BasicFormatStyle style; // default style.column_limit = 14 + 7; - ApplyPreOrder(tree.Children()[1], [&style](TokenPartitionTree& node) { - auto& uwline = node.Value(); + ApplyPreOrder(tree.Children()[1], [&style](TokenPartitionTree &node) { + auto &uwline = node.Value(); uwline.SetIndentationSpaces(7 + style.indentation_spaces); }); @@ -2329,7 +2329,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, IndentationTwoPartitions) { // Wrap into two partitions TEST_F(ReshapeFittingSubpartitionsTest, IndentationTwoPartitionsWithTrailer) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); verible::BasicFormatStyle style; // default @@ -2418,7 +2418,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, IndentationTwoPartitionsWithTrailer) { // One subpartition per line TEST_F(ReshapeFittingSubpartitionsTest, OnePerLine) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); verible::BasicFormatStyle style; // default @@ -2506,7 +2506,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, OnePerLine) { // One subpartition per line TEST_F(ReshapeFittingSubpartitionsTest, OnePerLineWithTrailer) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); verible::BasicFormatStyle style; // default @@ -2605,7 +2605,7 @@ TEST_F(ReshapeFittingSubpartitionsTest, OnePerLineWithTrailer) { } TEST_F(ReshapeFittingSubpartitionsTest, AvoidExceedingColumnLimit) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); verible::BasicFormatStyle style; // default @@ -2721,7 +2721,7 @@ class ReshapeFittingSubpartitionsFunctionTest TEST_F(ReshapeFittingSubpartitionsFunctionTest, FunctionWithSixArgumentsAndColumnLimit20Characters) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); @@ -2766,8 +2766,8 @@ TEST_F(ReshapeFittingSubpartitionsFunctionTest, verible::BasicFormatStyle style; style.column_limit = 20; - ApplyPreOrder(tree.Children()[1], [&style](TokenPartitionTree& node) { - auto& uwline = node.Value(); + ApplyPreOrder(tree.Children()[1], [&style](TokenPartitionTree &node) { + auto &uwline = node.Value(); uwline.SetIndentationSpaces(style.wrap_spaces); }); @@ -2801,7 +2801,7 @@ TEST_F(ReshapeFittingSubpartitionsFunctionTest, TEST_F(ReshapeFittingSubpartitionsFunctionTest, FunctionWithSixArgumentsAndColumnLimit40Characters) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); @@ -2846,8 +2846,8 @@ TEST_F(ReshapeFittingSubpartitionsFunctionTest, verible::BasicFormatStyle style; style.column_limit = 40; - ApplyPreOrder(tree.Children()[1], [&style](TokenPartitionTree& node) { - auto& uwline = node.Value(); + ApplyPreOrder(tree.Children()[1], [&style](TokenPartitionTree &node) { + auto &uwline = node.Value(); uwline.SetIndentationSpaces(style.wrap_spaces); }); @@ -2896,7 +2896,7 @@ TEST_F(ReshapeFittingSubpartitionsFunctionTest, TEST_F(ReshapeFittingSubpartitionsFunctionTest, FunctionWithSixArgumentsAndColumnLimit56Characters) { - const auto& preformat_tokens = pre_format_tokens_; + const auto &preformat_tokens = pre_format_tokens_; const auto begin = preformat_tokens.begin(); UnwrappedLine all(0, begin); @@ -2997,7 +2997,7 @@ TEST_F(ApplyAlreadyFormattedPartitionPropertiesToTokensTest, EmptyTokenRange) { SO::kUndecided, SO::kUndecided, SO::kUndecided, }; for (int i = 0; i < static_cast(pre_format_tokens_.size()); ++i) { - const auto& token = pre_format_tokens_.at(i); + const auto &token = pre_format_tokens_.at(i); EXPECT_EQ(token.before.spaces_required, expected_spaces[i]) << "Token " << i; EXPECT_EQ(token.before.break_decision, expected_decision[i]) @@ -3020,7 +3020,7 @@ TEST_F(ApplyAlreadyFormattedPartitionPropertiesToTokensTest, NoInlines) { SO::kMustAppend, SO::kMustAppend, SO::kUndecided, }; for (int i = 0; i < static_cast(pre_format_tokens_.size()); ++i) { - const auto& token = pre_format_tokens_.at(i); + const auto &token = pre_format_tokens_.at(i); EXPECT_EQ(token.before.spaces_required, expected_spaces[i]) << "Token " << i; EXPECT_EQ(token.before.break_decision, expected_decision[i]) @@ -3047,7 +3047,7 @@ TEST_F(ApplyAlreadyFormattedPartitionPropertiesToTokensTest, TwoInlines) { SO::kMustAppend, SO::kMustAppend, SO::kUndecided, }; for (int i = 0; i < static_cast(pre_format_tokens_.size()); ++i) { - const auto& token = pre_format_tokens_.at(i); + const auto &token = pre_format_tokens_.at(i); EXPECT_EQ(token.before.spaces_required, expected_spaces[i]) << "Token " << i; EXPECT_EQ(token.before.break_decision, expected_decision[i]) diff --git a/common/formatting/token_partition_tree_test_utils.cc b/common/formatting/token_partition_tree_test_utils.cc index facade98d..09977f3ab 100644 --- a/common/formatting/token_partition_tree_test_utils.cc +++ b/common/formatting/token_partition_tree_test_utils.cc @@ -27,7 +27,7 @@ namespace verible { namespace { -bool PartitionsEqual(const UnwrappedLine& left, const UnwrappedLine& right) { +bool PartitionsEqual(const UnwrappedLine &left, const UnwrappedLine &right) { return (left.TokensRange() == right.TokensRange()) && (left.IndentationSpaces() == right.IndentationSpaces()) && (left.PartitionPolicy() == right.PartitionPolicy()) && @@ -37,17 +37,17 @@ bool PartitionsEqual(const UnwrappedLine& left, const UnwrappedLine& right) { } // namespace TokenPartitionTree TokenPartitionTreeBuilder::build( - const std::vector& tokens) const { + const std::vector &tokens) const { TokenPartitionTree node; node.Children().reserve(children_.size()); - for (const auto& child : children_) { + for (const auto &child : children_) { node.Children().push_back(child.build(tokens)); } FormatTokenRange node_tokens; if (token_indexes_range_.first < 0) { - const auto& child_nodes = node.Children(); + const auto &child_nodes = node.Children(); CHECK(!child_nodes.empty()); CHECK_LT(token_indexes_range_.second, 0); node_tokens.set_begin(child_nodes.front().Value().TokensRange().begin()); @@ -64,8 +64,8 @@ TokenPartitionTree TokenPartitionTreeBuilder::build( } ::testing::AssertionResult TokenPartitionTreesEqualPredFormat( - const char* actual_expr, const char* expected_expr, - const TokenPartitionTree& actual, const TokenPartitionTree& expected) { + const char *actual_expr, const char *expected_expr, + const TokenPartitionTree &actual, const TokenPartitionTree &expected) { const auto diff = DeepEqual(actual, expected, PartitionsEqual); if (diff.left != nullptr) { return ::testing::AssertionFailure() diff --git a/common/formatting/tree_unwrapper.cc b/common/formatting/tree_unwrapper.cc index bc680d519..6fe60225c 100644 --- a/common/formatting/tree_unwrapper.cc +++ b/common/formatting/tree_unwrapper.cc @@ -55,8 +55,8 @@ static TokenPartitionTree MakeInitialUnwrappedLines( } TreeUnwrapper::TreeUnwrapper( - const TextStructureView& view, - const preformatted_tokens_type& preformatted_tokens) + const TextStructureView &view, + const preformatted_tokens_type &preformatted_tokens) : text_structure_view_(view), preformatted_tokens_(preformatted_tokens), next_unfiltered_token_(text_structure_view_.TokenStream().begin()), @@ -71,7 +71,7 @@ TreeUnwrapper::TreeUnwrapper( // array, and be able to 'extend' into the array of preformatted_tokens_. } -const TokenPartitionTree* TreeUnwrapper::Unwrap() { +const TokenPartitionTree *TreeUnwrapper::Unwrap() { // Collect tokens that appear before first syntax tree leaf, e.g. comments. CollectLeadingFilteredTokens(); @@ -116,7 +116,7 @@ std::vector TreeUnwrapper::FullyPartitionedUnwrappedLines() // visit only the node's children. std::vector result; verible::ApplyPostOrder(unwrapped_lines_, - [&result](const TokenPartitionTree& node) { + [&result](const TokenPartitionTree &node) { if (is_leaf(node)) { result.push_back(node.Value()); } @@ -130,7 +130,7 @@ std::vector TreeUnwrapper::FullyPartitionedUnwrappedLines() } TokenSequence::const_iterator TreeUnwrapper::NextUnfilteredToken() const { - const auto& origin_tokens = text_structure_view_.TokenStream(); + const auto &origin_tokens = text_structure_view_.TokenStream(); CHECK(next_unfiltered_token_ >= origin_tokens.begin()); CHECK(next_unfiltered_token_ <= origin_tokens.end()); return next_unfiltered_token_; @@ -142,25 +142,25 @@ TreeUnwrapper::CurrentFormatTokenIterator() const { return CurrentUnwrappedLine().TokensRange().end(); } -UnwrappedLine& TreeUnwrapper::CurrentUnwrappedLine() { +UnwrappedLine &TreeUnwrapper::CurrentUnwrappedLine() { return ABSL_DIE_IF_NULL(CurrentTokenPartition())->Value(); } -const UnwrappedLine& TreeUnwrapper::CurrentUnwrappedLine() const { +const UnwrappedLine &TreeUnwrapper::CurrentUnwrappedLine() const { return ABSL_DIE_IF_NULL(CurrentTokenPartition())->Value(); } -void TreeUnwrapper::RemoveTrailingEmptyPartitions(TokenPartitionTree* node) { - auto& children = node->Children(); +void TreeUnwrapper::RemoveTrailingEmptyPartitions(TokenPartitionTree *node) { + auto &children = node->Children(); while (!children.empty() && children.back().Value().IsEmpty()) { children.pop_back(); } } void TreeUnwrapper::CloseUnwrappedLineTreeNode( - TokenPartitionTree* node, + TokenPartitionTree *node, preformatted_tokens_type::const_iterator token_iter) { - const auto& children = node->Children(); + const auto &children = node->Children(); if (!children.empty()) { const auto last_child_end = children.back().Value().TokensRange().end(); CHECK(last_child_end >= token_iter) @@ -188,9 +188,9 @@ void TreeUnwrapper::FinishUnwrappedLine() { } void TreeUnwrapper::StartNewUnwrappedLine(PartitionPolicyEnum partitioning, - const Symbol* origin) { + const Symbol *origin) { // TODO(fangism): Take an optional indentation depth override parameter. - auto& current_unwrapped_line = CurrentUnwrappedLine(); + auto ¤t_unwrapped_line = CurrentUnwrappedLine(); if (current_unwrapped_line.IsEmpty()) { // token range is empty // Re-use previously created unwrapped line. current_unwrapped_line.SetIndentationSpaces(current_indentation_spaces_); @@ -215,7 +215,7 @@ void TreeUnwrapper::StartNewUnwrappedLine(PartitionPolicyEnum partitioning, FinishUnwrappedLine(); // Create new sibling to current unwrapped line, maintaining same level. - auto& siblings = active_unwrapped_lines_->Parent()->Children(); + auto &siblings = active_unwrapped_lines_->Parent()->Children(); siblings.emplace_back(UnwrappedLine(current_indentation_spaces_, CurrentFormatTokenIterator(), partitioning)); @@ -249,7 +249,7 @@ bool TreeUnwrapper::NextUnfilteredTokenIsRetained() const { } void TreeUnwrapper::SkipUnfilteredTokens( - const std::function& predicate) { + const std::function &predicate) { while (predicate(*next_unfiltered_token_)) { ++next_unfiltered_token_; } @@ -272,12 +272,12 @@ void TreeUnwrapper::AdvanceNextUnfilteredToken() { } } -void TreeUnwrapper::TraverseChildren(const verible::SyntaxTreeNode& node) { +void TreeUnwrapper::TraverseChildren(const verible::SyntaxTreeNode &node) { // Can't just use TreeContextVisitor::Visit(node) because we need to // call a visit hook between children. const verible::SyntaxTreeContext::AutoPop p(¤t_context_, &node); InterChildNodeHook(node); - for (const auto& child : node.children()) { + for (const auto &child : node.children()) { if (child) { child->Accept(this); InterChildNodeHook(node); @@ -286,7 +286,7 @@ void TreeUnwrapper::TraverseChildren(const verible::SyntaxTreeNode& node) { } TreeUnwrapper::preformatted_tokens_type::const_iterator -TreeUnwrapper::VisitIndentedChildren(const SyntaxTreeNode& node, +TreeUnwrapper::VisitIndentedChildren(const SyntaxTreeNode &node, int indentation_delta, PartitionPolicyEnum partitioning) { // Visit subtree with increased indentation level. @@ -301,7 +301,7 @@ TreeUnwrapper::VisitIndentedChildren(const SyntaxTreeNode& node, active_unwrapped_lines_->Children().emplace_back( UnwrappedLine(current_indentation_spaces_, CurrentFormatTokenIterator(), PartitionPolicyEnum::kFitOnLineElseExpand /* default */)); - const ValueSaver tree_saver( + const ValueSaver tree_saver( &active_unwrapped_lines_, &active_unwrapped_lines_->Children().back()); VLOG(3) << __FUNCTION__ << ", new child node " << NodePath(*active_unwrapped_lines_) << ": " @@ -318,7 +318,7 @@ TreeUnwrapper::VisitIndentedChildren(const SyntaxTreeNode& node, // See StartNewUnwrappedLine(). } -void TreeUnwrapper::VisitIndentedSection(const SyntaxTreeNode& node, +void TreeUnwrapper::VisitIndentedSection(const SyntaxTreeNode &node, int indentation_delta, PartitionPolicyEnum partitioning) { const auto last_ftoken_iter = @@ -334,8 +334,8 @@ void TreeUnwrapper::VisitIndentedSection(const SyntaxTreeNode& node, StartNewUnwrappedLine(PartitionPolicyEnum::kUninitialized, nullptr); } -std::ostream& operator<<(std::ostream& stream, const TreeUnwrapper& unwrapper) { - for (const auto& uwline : unwrapper.FullyPartitionedUnwrappedLines()) { +std::ostream &operator<<(std::ostream &stream, const TreeUnwrapper &unwrapper) { + for (const auto &uwline : unwrapper.FullyPartitionedUnwrappedLines()) { stream << uwline << std::endl; } return stream; diff --git a/common/formatting/tree_unwrapper.h b/common/formatting/tree_unwrapper.h index c3f723db5..c2e3391f5 100644 --- a/common/formatting/tree_unwrapper.h +++ b/common/formatting/tree_unwrapper.h @@ -42,22 +42,22 @@ class TreeUnwrapper : public TreeContextVisitor { using preformatted_tokens_type = std::vector; public: - explicit TreeUnwrapper(const TextStructureView& view, - const preformatted_tokens_type&); + explicit TreeUnwrapper(const TextStructureView &view, + const preformatted_tokens_type &); // Deleted standard interfaces: TreeUnwrapper() = delete; - TreeUnwrapper(const TreeUnwrapper&) = delete; - TreeUnwrapper(TreeUnwrapper&&) = delete; - TreeUnwrapper& operator=(const TreeUnwrapper&) = delete; - TreeUnwrapper& operator=(TreeUnwrapper&&) = delete; + TreeUnwrapper(const TreeUnwrapper &) = delete; + TreeUnwrapper(TreeUnwrapper &&) = delete; + TreeUnwrapper &operator=(const TreeUnwrapper &) = delete; + TreeUnwrapper &operator=(TreeUnwrapper &&) = delete; ~TreeUnwrapper() override = default; // not yet final. // Partitions the token stream (in text_structure_view_) into // unwrapped_lines_ by traversing the syntax tree representation. // TODO(fangism): rename this Partition. - const TokenPartitionTree* Unwrap(); + const TokenPartitionTree *Unwrap(); // Returns a flattened copy of all of the deepest nodes in the tree of // unwrapped lines, which represents maximal partitioning into the smallest @@ -71,13 +71,13 @@ class TreeUnwrapper : public TreeContextVisitor { virtual void CollectTrailingFilteredTokens() = 0; // Refers to the UnwrappedLine that is currently being built (const). - const UnwrappedLine& CurrentUnwrappedLine() const; + const UnwrappedLine &CurrentUnwrappedLine() const; - const TokenPartitionTree* CurrentTokenPartition() const { + const TokenPartitionTree *CurrentTokenPartition() const { return active_unwrapped_lines_; } - TokenPartitionTree* CurrentTokenPartition() { + TokenPartitionTree *CurrentTokenPartition() { return active_unwrapped_lines_; } @@ -87,31 +87,31 @@ class TreeUnwrapper : public TreeContextVisitor { // Transformation // Apply a mutating transformation to this class tree, pre-order traversal. - void ApplyPreOrder(const std::function& f) { + void ApplyPreOrder(const std::function &f) { verible::ApplyPreOrder(unwrapped_lines_, f); } // Apply a mutating transformation to this class tree, post-order traversal. - void ApplyPostOrder(const std::function& f) { + void ApplyPostOrder(const std::function &f) { verible::ApplyPostOrder(unwrapped_lines_, f); } protected: // Begins a new UnwrappedLine to span a new sub-range of format tokens. void StartNewUnwrappedLine(PartitionPolicyEnum partitioning, - const Symbol* origin); + const Symbol *origin); // Traverses the children of a node in postorder, recursively accepting this // visitor. - void TraverseChildren(const verible::SyntaxTreeNode& node); + void TraverseChildren(const verible::SyntaxTreeNode &node); // Override-able hook for actions that should be taken while in the // context of traversing children. - virtual void InterChildNodeHook(const verible::SyntaxTreeNode&) {} + virtual void InterChildNodeHook(const verible::SyntaxTreeNode &) {} // Visits a subtree with (possibly) additional indentation. // TODO(fangism): NOW: rename this to VisitSubPartition. - void VisitIndentedSection(const verible::SyntaxTreeNode& node, + void VisitIndentedSection(const verible::SyntaxTreeNode &node, int indentation_delta, PartitionPolicyEnum); // Adds a token to CurrentUnwrappedLine() by advancing the end-iterator @@ -122,7 +122,7 @@ class TreeUnwrapper : public TreeContextVisitor { void AddTokenToCurrentUnwrappedLine(); // Refers to the UnwrappedLine that is currently being built (mutable). - UnwrappedLine& CurrentUnwrappedLine(); + UnwrappedLine &CurrentUnwrappedLine(); // Iterator pointing to the most recent position in the preformatted_tokens_ // array, that is accounted for in the CurrentUnwrappedLine(). @@ -138,7 +138,7 @@ class TreeUnwrapper : public TreeContextVisitor { // Skip over uninteresting tokens, those for which the predicate is true. // For example, this could be used to skip over spaces, but not newlines. void SkipUnfilteredTokens( - const std::function& predicate); + const std::function &predicate); // Returns true of next_unfiltered_tokens_ points to a token that was kept // in preformatted_tokens_. @@ -157,11 +157,11 @@ class TreeUnwrapper : public TreeContextVisitor { private: // Removes subtrees that represent empty token ranges, from the back. - static void RemoveTrailingEmptyPartitions(TokenPartitionTree*); + static void RemoveTrailingEmptyPartitions(TokenPartitionTree *); // Maintain invariant that parent range's end is equal to last-child's end. static void CloseUnwrappedLineTreeNode( - TokenPartitionTree*, preformatted_tokens_type::const_iterator); + TokenPartitionTree *, preformatted_tokens_type::const_iterator); // Finalizes an UnwrappedLine, prior to starting the next one. void FinishUnwrappedLine(); @@ -169,7 +169,7 @@ class TreeUnwrapper : public TreeContextVisitor { // Returns the last iterator position from visiting a set of children. // This automatically restores active_unwrapped_lines_ on return. preformatted_tokens_type::const_iterator VisitIndentedChildren( - const verible::SyntaxTreeNode& node, int indentation_delta, + const verible::SyntaxTreeNode &node, int indentation_delta, PartitionPolicyEnum); // Verifies parent-child token range equivalence in the entire tree of @@ -182,7 +182,7 @@ class TreeUnwrapper : public TreeContextVisitor { // The TextStructureView includes all of the information about the contents // of the file, including a syntax tree, raw token stream, and filtered // token stream - const TextStructureView& text_structure_view_; + const TextStructureView &text_structure_view_; // This is an annotated representation of tokens that require formatting // decisions, such as spaces and line breaks. UnwrappedLines (in @@ -190,7 +190,7 @@ class TreeUnwrapper : public TreeContextVisitor { // (thus, this member should outlive those UnwrappedLines). // CurrentFormatTokenIterator() always points to iterators in this // container's range. - const preformatted_tokens_type& preformatted_tokens_; + const preformatted_tokens_type &preformatted_tokens_; // Iterator pointing into text_structure_view_.TokenStream(). // This covers non-whitespace tokens like comments and attributes @@ -220,11 +220,11 @@ class TreeUnwrapper : public TreeContextVisitor { // tree traversal. // No container is actually needed because popping the stack is a matter // of replacing this pointer with its Parent(). - TokenPartitionTree* active_unwrapped_lines_ = nullptr; + TokenPartitionTree *active_unwrapped_lines_ = nullptr; }; // Prints all of the unwrapped_lines_. Used for diagnostics only. -std::ostream& operator<<(std::ostream&, const TreeUnwrapper&); +std::ostream &operator<<(std::ostream &, const TreeUnwrapper &); } // namespace verible diff --git a/common/formatting/unwrapped_line.h b/common/formatting/unwrapped_line.h index 8c807c40b..60d04227a 100644 --- a/common/formatting/unwrapped_line.h +++ b/common/formatting/unwrapped_line.h @@ -105,7 +105,7 @@ enum class PartitionPolicyEnum { kJuxtapositionOrIndentedStack, }; -std::ostream& operator<<(std::ostream&, PartitionPolicyEnum); +std::ostream &operator<<(std::ostream &, PartitionPolicyEnum); // An UnwrappedLine represents a partition of the input token stream that // is an independent unit of work for other phases of formatting, such as @@ -127,10 +127,10 @@ class UnwrappedLine { // Allow default construction for use in resize-able containers. UnwrappedLine() = default; - UnwrappedLine(const UnwrappedLine&) = default; - UnwrappedLine(UnwrappedLine&&) = default; - UnwrappedLine& operator=(const UnwrappedLine&) = default; - UnwrappedLine& operator=(UnwrappedLine&&) = default; + UnwrappedLine(const UnwrappedLine &) = default; + UnwrappedLine(UnwrappedLine &&) = default; + UnwrappedLine &operator=(const UnwrappedLine &) = default; + UnwrappedLine &operator=(UnwrappedLine &&) = default; // Extends PreFormatToken range spanned by this UnwrappedLine by one token at // the back. @@ -157,8 +157,8 @@ class UnwrappedLine { partition_policy_ = policy; } - const Symbol* Origin() const { return origin_; } - void SetOrigin(const Symbol* origin) { origin_ = origin; } + const Symbol *Origin() const { return origin_; } + void SetOrigin(const Symbol *origin) { origin_ = origin; } // Returns the range of PreFormatTokens spanned by this UnwrappedLine. // Note that this is a *copy*, and not a reference to the underlying range. @@ -172,15 +172,15 @@ class UnwrappedLine { // Used by AsCode() and other code using it using OriginPrinterFunction = - std::function; + std::function; // Default origin printing function used by AsCode() - static void DefaultOriginPrinter(std::ostream&, const verible::Symbol*); + static void DefaultOriginPrinter(std::ostream &, const verible::Symbol *); // Currently for debugging, prints the UnwrappedLine as Code - std::ostream* AsCode( - std::ostream*, bool verbose = false, - const OriginPrinterFunction& origin_printer = DefaultOriginPrinter) const; + std::ostream *AsCode( + std::ostream *, bool verbose = false, + const OriginPrinterFunction &origin_printer = DefaultOriginPrinter) const; private: // Data members: @@ -199,10 +199,10 @@ class UnwrappedLine { // Hint about the origin of this partition, e.g. a particular syntax // tree node/leaf. - const Symbol* origin_ = nullptr; + const Symbol *origin_ = nullptr; }; -std::ostream& operator<<(std::ostream&, const UnwrappedLine&); +std::ostream &operator<<(std::ostream &, const UnwrappedLine &); // FormattedExcerpt is the result of formatting a slice of code represented // as an UnwrappedLine. In this representation, wrapping and spacing decisions @@ -212,15 +212,15 @@ class FormattedExcerpt { public: FormattedExcerpt() = default; - explicit FormattedExcerpt(const UnwrappedLine&); + explicit FormattedExcerpt(const UnwrappedLine &); // Returns the number of spaces to indent. int IndentationSpaces() const { return indentation_spaces_; } - const std::vector& Tokens() const { return tokens_; } + const std::vector &Tokens() const { return tokens_; } // Note: The mutable variant is only intended for use in StateNode. - std::vector& MutableTokens() { return tokens_; } + std::vector &MutableTokens() { return tokens_; } // Prints formatted text. If indent is true, include the spacing // that is to the left of the first token. @@ -228,10 +228,10 @@ class FormattedExcerpt { // always emit). // TODO(hzeller): instead of "indent" parameter, handle that with the // include_token_p() predicate ? - std::ostream& FormattedText( - std::ostream&, bool indent, - const std::function& include_token_p = - [](const TokenInfo&) { return true; }) const; + std::ostream &FormattedText( + std::ostream &, bool indent, + const std::function &include_token_p = + [](const TokenInfo &) { return true; }) const; // Returns formatted code as a string. std::string Render() const; @@ -256,7 +256,7 @@ class FormattedExcerpt { bool completed_formatting_ = true; }; -std::ostream& operator<<(std::ostream&, const FormattedExcerpt&); +std::ostream &operator<<(std::ostream &, const FormattedExcerpt &); } // namespace verible diff --git a/common/text/text_structure.cc b/common/text/text_structure.cc index 266277bd6..fb4378590 100644 --- a/common/text/text_structure.cc +++ b/common/text/text_structure.cc @@ -71,14 +71,14 @@ void TextStructureView::Clear() { contents_ = contents_.substr(0, 0); // clear } -static bool TokenLocationLess(const TokenInfo& token, const char* offset) { +static bool TokenLocationLess(const TokenInfo &token, const char *offset) { return token.text().begin() < offset; } // Makes an iterator-writable copy of items_view without using const_cast. template std::vector CopyWriteableIterators( - V& items, const std::vector& items_view) { + V &items, const std::vector &items_view) { // precondition: items_view's iterators all point into items array. // postcondition: results's iterators point to the same items as items_view. std::vector result; @@ -95,12 +95,12 @@ TokenStreamReferenceView TextStructureView::MakeTokenStreamReferenceView() { return CopyWriteableIterators(tokens_, tokens_view_); } -const std::vector& +const std::vector & TextStructureView::GetLineTokenMap() const { // Lazily calculate the map. It is mutable, so we can modify it here. if (lazy_line_token_map_.empty()) { auto token_iter = tokens_.cbegin(); - const auto& offset_map = GetLineColumnMap().GetBeginningOfLineOffsets(); + const auto &offset_map = GetLineColumnMap().GetBeginningOfLineOffsets(); for (const auto offset : offset_map) { // TODO(fangism): linear search might be as competitive as binary search token_iter = @@ -131,7 +131,7 @@ TokenRange TextStructureView::TokenRangeSpanningOffsets(size_t lower, } LineColumnRange TextStructureView::GetRangeForToken( - const TokenInfo& token) const { + const TokenInfo &token) const { if (token.isEOF()) { // In particular some unit tests pass in an artificial EOF token, not a // EOF token generated from this view. So handle this directly. @@ -160,17 +160,17 @@ bool TextStructureView::ContainsText(absl::string_view text) const { } TokenRange TextStructureView::TokenRangeOnLine(size_t lineno) const { - const auto& line_token_map = GetLineTokenMap(); + const auto &line_token_map = GetLineTokenMap(); if (lineno + 1 < line_token_map.size()) { return make_range(line_token_map[lineno], line_token_map[lineno + 1]); } return make_range(tokens_.cend(), tokens_.cend()); } -TokenInfo TextStructureView::FindTokenAt(const LineColumn& pos) const { +TokenInfo TextStructureView::FindTokenAt(const LineColumn &pos) const { if (pos.line < 0 || pos.column < 0) return EOFToken(); // Maybe do binary search here if we have a huge amount tokens per line. - for (const TokenInfo& token : TokenRangeOnLine(pos.line)) { + for (const TokenInfo &token : TokenRangeOnLine(pos.line)) { if (GetRangeForToken(token).PositionInRange(pos)) return token; } return EOFToken(); @@ -182,11 +182,11 @@ TokenInfo TextStructureView::EOFToken() const { // Removes tokens from the TokenStreamView that do not satisfy the keep // predicate. -void TextStructureView::FilterTokens(const TokenFilterPredicate& keep) { +void TextStructureView::FilterTokens(const TokenFilterPredicate &keep) { FilterTokenStreamViewInPlace(keep, &tokens_view_); } -static void TerminateTokenStream(TokenSequence* tokens) { +static void TerminateTokenStream(TokenSequence *tokens) { if (tokens->empty()) return; if (tokens->back().isEOF()) return; // push_back might cause re-alloc. @@ -254,7 +254,7 @@ void TextStructureView::TrimTokensToSubstring(int left_offset, if (!trimmed_stream.empty()) { const absl::string_view substr( contents_.substr(left_offset, right_offset - left_offset)); - TokenInfo& last(trimmed_stream.back()); + TokenInfo &last(trimmed_stream.back()); const int overhang = std::distance(substr.end(), last.text().end()); if (!IsSubRange(last.text(), substr)) { VLOG(2) << "last token overhangs end by " << overhang << ": " << last; @@ -289,7 +289,7 @@ void TextStructureView::TrimContents(int left_offset, int length) { contents_ = contents_.substr(left_offset, length); } -const TextStructureView::LinesInfo& TextStructureView::LinesInfo::Get( +const TextStructureView::LinesInfo &TextStructureView::LinesInfo::Get( absl::string_view contents) { if (valid) return *this; @@ -303,7 +303,7 @@ const TextStructureView::LinesInfo& TextStructureView::LinesInfo::Get( void TextStructureView::RebaseTokensToSuperstring(absl::string_view superstring, absl::string_view src_base, int offset) { - MutateTokens([&](TokenInfo* token) { + MutateTokens([&](TokenInfo *token) { const int delta = token->left(src_base); // Superstring must point to separate memory space. token->RebaseStringView(superstring.begin() + offset + delta); @@ -313,8 +313,8 @@ void TextStructureView::RebaseTokensToSuperstring(absl::string_view superstring, lazy_lines_info_.valid = false; } -void TextStructureView::MutateTokens(const LeafMutator& mutator) { - for (auto& token : tokens_) { +void TextStructureView::MutateTokens(const LeafMutator &mutator) { + for (auto &token : tokens_) { mutator(&token); } // No need to touch tokens_view_, all transformations are in-place. @@ -327,10 +327,10 @@ void TextStructureView::MutateTokens(const LeafMutator& mutator) { } // Find the last non-EOF token. Usually searches at most 2 tokens. -static const TokenInfo* FindLastNonEOFToken(const TokenSequence& tokens) { +static const TokenInfo *FindLastNonEOFToken(const TokenSequence &tokens) { const auto iter = std::find_if(tokens.rbegin(), tokens.rend(), - [](const TokenInfo& token) { return !token.isEOF(); }); + [](const TokenInfo &token) { return !token.isEOF(); }); return iter != tokens.rend() ? &*iter : nullptr; } @@ -342,13 +342,13 @@ absl::Status TextStructureView::FastTokenRangeConsistencyCheck() const { const auto upper_bound = contents_.end(); if (!tokens_.empty()) { // Check that extremities of first and last token lie inside contents_. - const TokenInfo& first = tokens_.front(); + const TokenInfo &first = tokens_.front(); if (!first.isEOF() && lower_bound > first.text().cbegin()) { return absl::InternalError(absl::StrCat( "Token offset points before beginning of string contents. delta=", std::distance(first.text().cbegin(), lower_bound))); } - const TokenInfo* last = FindLastNonEOFToken(tokens_); + const TokenInfo *last = FindLastNonEOFToken(tokens_); if (last != nullptr && last->text().cend() > upper_bound) { return absl::InternalError(absl::StrCat( "Token offset points past end of string contents. delta=", @@ -391,7 +391,7 @@ absl::Status TextStructureView::FastTokenRangeConsistencyCheck() const { absl::Status TextStructureView::FastLineRangeConsistencyCheck() const { VLOG(2) << __FUNCTION__; - const auto& lines = Lines(); + const auto &lines = Lines(); if (!lines.empty()) { if (lines.front().cbegin() != contents_.cbegin()) { return absl::InternalError( @@ -408,12 +408,12 @@ absl::Status TextStructureView::SyntaxTreeConsistencyCheck() const { VLOG(2) << __FUNCTION__; // Check that first and last token in syntax_tree_ point to text // inside contents_. - const char* const lower_bound = contents_.data(); - const char* const upper_bound = lower_bound + contents_.length(); + const char *const lower_bound = contents_.data(); + const char *const upper_bound = lower_bound + contents_.length(); if (syntax_tree_ != nullptr) { - const SyntaxTreeLeaf* left = GetLeftmostLeaf(*syntax_tree_); + const SyntaxTreeLeaf *left = GetLeftmostLeaf(*syntax_tree_); if (!left) return absl::OkStatus(); - const SyntaxTreeLeaf* right = GetRightmostLeaf(*syntax_tree_); + const SyntaxTreeLeaf *right = GetRightmostLeaf(*syntax_tree_); if (lower_bound > left->get().text().cbegin()) { return absl::InternalError( "Left-most tree leaf points before beginning of contents."); @@ -438,14 +438,14 @@ absl::Status TextStructureView::InternalConsistencyCheck() const { // "view_source" is a sequence of iterators pointing to token_source content. // The TokenViewRange can be a container reference or iterator range. template -static void CopyTokensAndView(TokenSequence* destination, - std::vector* view_indices, - const TokenRange& token_source, - const TokenViewRange& view_source) { +static void CopyTokensAndView(TokenSequence *destination, + std::vector *view_indices, + const TokenRange &token_source, + const TokenViewRange &view_source) { // Translate token_view's iterators into array indices, adjusting for the // number of pre-existing tokens. const auto pre_existing_start_index = destination->size(); - for (const auto& token_iter : view_source) { + for (const auto &token_iter : view_source) { // TODO: something is wrong here, the view should never have iterators // pointing outside the range of the source. Needs to be explored. #if 0 @@ -456,7 +456,7 @@ static void CopyTokensAndView(TokenSequence* destination, std::distance(token_source.begin(), token_iter)); } // Copy tokens up to this expansion point. - for (const auto& token : token_source) { + for (const auto &token : token_source) { destination->push_back(token); } } @@ -467,22 +467,22 @@ static void CopyTokensAndView(TokenSequence* destination, // tree. Indices into the final token stream view are collected in // token_view_indices. Offset is the location of each expansion point. void TextStructureView::ConsumeDeferredExpansion( - TokenSequence::const_iterator* next_token_iter, - TokenStreamView::const_iterator* next_token_view_iter, - DeferredExpansion* expansion, TokenSequence* combined_tokens, - std::vector* token_view_indices, const char* offset) { + TokenSequence::const_iterator *next_token_iter, + TokenStreamView::const_iterator *next_token_view_iter, + DeferredExpansion *expansion, TokenSequence *combined_tokens, + std::vector *token_view_indices, const char *offset) { auto token_iter = *next_token_iter; auto token_view_iter = *next_token_view_iter; // Find the position up to each expansion point. *next_token_iter = std::lower_bound(token_iter, tokens_.cend(), offset, - [](const TokenInfo& token, const char* target) { + [](const TokenInfo &token, const char *target) { return std::distance(target, token.text().begin()) < 0; }); CHECK(*next_token_iter != tokens_.cend()); *next_token_view_iter = std::lower_bound( token_view_iter, tokens_view_.cend(), offset, - [](TokenStreamView::const_reference token_ref, const char* target) { + [](TokenStreamView::const_reference token_ref, const char *target) { return std::distance(target, token_ref->text().begin()) < 0; }); CHECK(*next_token_view_iter != tokens_view_.cend()); @@ -494,8 +494,8 @@ void TextStructureView::ConsumeDeferredExpansion( // Adjust locations of tokens in the expanded tree by pointing them // into the original text (contents_). - std::unique_ptr& subanalysis = expansion->subanalysis; - TextStructureView& sub_data = ABSL_DIE_IF_NULL(subanalysis)->MutableData(); + std::unique_ptr &subanalysis = expansion->subanalysis; + TextStructureView &sub_data = ABSL_DIE_IF_NULL(subanalysis)->MutableData(); const absl::string_view sub_data_text(sub_data.Contents()); CHECK(!IsSubRange(sub_data_text, contents_)); CHECK_EQ(sub_data_text, absl::string_view(offset, sub_data_text.length())); @@ -536,14 +536,14 @@ TextStructure::~TextStructure() { CHECK(status.ok()) << status.message() << " (in dtor)"; } -void TextStructureView::ExpandSubtrees(NodeExpansionMap* expansions) { +void TextStructureView::ExpandSubtrees(NodeExpansionMap *expansions) { TokenSequence combined_tokens; // Gather indices and reconstruct iterators after there are no more // reallocations due to growing combined_tokens. std::vector combined_token_view_indices; auto token_iter = tokens_.cbegin(); auto token_view_iter = tokens_view_.cbegin(); - for (auto& expansion_entry : *expansions) { + for (auto &expansion_entry : *expansions) { const auto offset = Contents().begin() + expansion_entry.first; ConsumeDeferredExpansion(&token_iter, &token_view_iter, &expansion_entry.second, &combined_tokens, diff --git a/common/text/text_structure.h b/common/text/text_structure.h index 7c6f0c1a0..2dcdcccd5 100644 --- a/common/text/text_structure.h +++ b/common/text/text_structure.h @@ -61,7 +61,7 @@ class TextStructureView { // TODO(b/136014603): Replace with expandable token stream view abstraction. struct DeferredExpansion { // Position in the syntax tree to expand (leaf or node). - SymbolPtr* expansion_point; + SymbolPtr *expansion_point; // Analysis of the substring that corresponds to the expansion_point. std::unique_ptr subanalysis; @@ -78,32 +78,32 @@ class TextStructureView { ~TextStructureView(); // Do not copy/assign. This contains pointers/iterators to internals. - TextStructureView(const TextStructureView&) = delete; - TextStructureView& operator=(const TextStructureView&) = delete; + TextStructureView(const TextStructureView &) = delete; + TextStructureView &operator=(const TextStructureView &) = delete; absl::string_view Contents() const { return contents_; } - const std::vector& Lines() const { + const std::vector &Lines() const { return lazy_lines_info_.Get(contents_).lines; } - const ConcreteSyntaxTree& SyntaxTree() const { return syntax_tree_; } + const ConcreteSyntaxTree &SyntaxTree() const { return syntax_tree_; } - ConcreteSyntaxTree& MutableSyntaxTree() { return syntax_tree_; } + ConcreteSyntaxTree &MutableSyntaxTree() { return syntax_tree_; } - const TokenSequence& TokenStream() const { return tokens_; } + const TokenSequence &TokenStream() const { return tokens_; } - TokenSequence& MutableTokenStream() { return tokens_; } + TokenSequence &MutableTokenStream() { return tokens_; } - const TokenStreamView& GetTokenStreamView() const { return tokens_view_; } + const TokenStreamView &GetTokenStreamView() const { return tokens_view_; } - TokenStreamView& MutableTokenStreamView() { return tokens_view_; } + TokenStreamView &MutableTokenStreamView() { return tokens_view_; } // Creates a stream of modifiable iterators to the filtered tokens. // Uses tokens_view_ to create the iterators. TokenStreamReferenceView MakeTokenStreamReferenceView(); - const LineColumnMap& GetLineColumnMap() const { + const LineColumnMap &GetLineColumnMap() const { return *lazy_lines_info_.Get(contents_).line_column_map; } @@ -114,7 +114,7 @@ class TextStructureView { } // Convenience function: Given the token, return the range it covers. - LineColumnRange GetRangeForToken(const TokenInfo& token) const; + LineColumnRange GetRangeForToken(const TokenInfo &token) const; // Convenience function: Given a text snippet, that needs to be a substring // of Contents(), return the range it covers. @@ -123,11 +123,11 @@ class TextStructureView { // checks if a given text belongs to the TextStructure bool ContainsText(absl::string_view text) const; - const std::vector& GetLineTokenMap() const; + const std::vector &GetLineTokenMap() const; // Given line/column, find token that is available there. If this is out of // range, returns EOF. - TokenInfo FindTokenAt(const LineColumn& pos) const; + TokenInfo FindTokenAt(const LineColumn &pos) const; // Create the EOF token given the contents. TokenInfo EOFToken() const; @@ -147,11 +147,11 @@ class TextStructureView { // Filter out tokens from token stream view before parsing. // Can be called successively with different predicates. - void FilterTokens(const TokenFilterPredicate&); + void FilterTokens(const TokenFilterPredicate &); // Apply the same transformation to the token sequence, and the tokens // that were copied into the syntax tree. - void MutateTokens(const LeafMutator& mutator); + void MutateTokens(const LeafMutator &mutator); // Update tokens to point their text into new (superstring) owner. // This is done to prepare for transfer of ownership of syntax_tree_ @@ -170,7 +170,7 @@ class TextStructureView { // subtrees that result from other analyses. Memory ownership of the // analysis results passed through the expansions is transferred (consumed) // by this function. - void ExpandSubtrees(NodeExpansionMap* expansions); + void ExpandSubtrees(NodeExpansionMap *expansions); // All of this class's consistency checks combined. absl::Status InternalConsistencyCheck() const; @@ -193,7 +193,7 @@ class TextStructureView { // Map to translate byte-offsets to line and column for diagnostics. std::unique_ptr line_column_map; - const LinesInfo& Get(absl::string_view contents); + const LinesInfo &Get(absl::string_view contents); }; // Mutable as we fill it lazily on request; conceptually the data is const. mutable LinesInfo lazy_lines_info_; @@ -219,10 +219,10 @@ class TextStructureView { void TrimContents(int left_offset, int length); void ConsumeDeferredExpansion( - TokenSequence::const_iterator* next_token_iter, - TokenStreamView::const_iterator* next_token_view_iter, - DeferredExpansion* expansion, TokenSequence* combined_tokens, - std::vector* token_view_indices, const char* offset); + TokenSequence::const_iterator *next_token_iter, + TokenStreamView::const_iterator *next_token_view_iter, + DeferredExpansion *expansion, TokenSequence *combined_tokens, + std::vector *token_view_indices, const char *offset); // Resets all fields. Only needed in tests. void Clear(); @@ -275,19 +275,19 @@ class TextStructure { explicit TextStructure(absl::string_view contents); public: - TextStructure(const TextStructure&) = delete; - TextStructure& operator=(const TextStructure&) = delete; - TextStructure(TextStructure&&) = delete; - TextStructure& operator=(TextStructure&&) = delete; + TextStructure(const TextStructure &) = delete; + TextStructure &operator=(const TextStructure &) = delete; + TextStructure(TextStructure &&) = delete; + TextStructure &operator=(TextStructure &&) = delete; // DeferredExpansion::subanalysis requires this destructor to be virtual. virtual ~TextStructure(); - const TextStructureView& Data() const { return data_; } + const TextStructureView &Data() const { return data_; } - TextStructureView& MutableData() { return data_; } + TextStructureView &MutableData() { return data_; } - const ConcreteSyntaxTree& SyntaxTree() const { return data_.SyntaxTree(); } + const ConcreteSyntaxTree &SyntaxTree() const { return data_.SyntaxTree(); } // Verify that string_views are inside memory owned by owned_contents_. absl::Status StringViewConsistencyCheck() const; diff --git a/common/text/token_info.h b/common/text/token_info.h index ace8c5460..57ce7d04d 100644 --- a/common/text/token_info.h +++ b/common/text/token_info.h @@ -54,9 +54,9 @@ class TokenInfo { TokenInfo(int token_enum, absl::string_view text) : token_enum_(token_enum), text_(text) {} - TokenInfo(const TokenInfo&) = default; - TokenInfo(TokenInfo&&) = default; - TokenInfo& operator=(const TokenInfo&) = default; + TokenInfo(const TokenInfo &) = default; + TokenInfo(TokenInfo &&) = default; + TokenInfo &operator=(const TokenInfo &) = default; // Context contains the information needed to display meaningful information // about a TokenInfo. @@ -66,12 +66,12 @@ class TokenInfo { absl::string_view base; // Prints a human-readable interpretation form of a token enumeration. - std::function token_enum_translator; + std::function token_enum_translator; explicit Context(absl::string_view b); Context(absl::string_view b, - std::function translator) + std::function translator) : base(b), token_enum_translator(std::move(translator)) {} }; @@ -99,13 +99,13 @@ class TokenInfo { } // Writes a human-readable string representation of the token. - std::ostream& ToStream(std::ostream&, const Context& context) const; + std::ostream &ToStream(std::ostream &, const Context &context) const; // Prints token representation without byte offsets. - std::ostream& ToStream(std::ostream&) const; + std::ostream &ToStream(std::ostream &) const; // Returns a human-readable string representation of the token. - std::string ToString(const Context&) const; + std::string ToString(const Context &) const; // Prints token representation without byte offsets. std::string ToString() const; @@ -123,7 +123,7 @@ class TokenInfo { // same length as the current string_view. // string_view::iterator happens to be const char*, but don't rely on that // fact as it can be implementation-dependent. - void RebaseStringView(const char* new_text) { + void RebaseStringView(const char *new_text) { RebaseStringView(absl::string_view(new_text, text_.length())); } @@ -133,17 +133,17 @@ class TokenInfo { // string_views will be abutting *subranges* of 'out', and their left/right // offsets will be updated to be relative to out->begin(). // This is very useful for lexer test case construction. - static void Concatenate(std::string* out, std::vector* tokens); + static void Concatenate(std::string *out, std::vector *tokens); // The default comparison operator requires that not only the contents // of the internal string_view be equal, but that they point to the // same buffer range. See EquivalentWithoutLocation() for the variant that // doesn't require range equality. - bool operator==(const TokenInfo& token) const; - bool operator!=(const TokenInfo& token) const { return !(*this == token); } + bool operator==(const TokenInfo &token) const; + bool operator!=(const TokenInfo &token) const { return !(*this == token); } // Returns true if tokens are considered equivalent, ignoring location. - bool EquivalentWithoutLocation(const TokenInfo& token) const { + bool EquivalentWithoutLocation(const TokenInfo &token) const { return token_enum_ == token.token_enum_ && (token_enum_ == TK_EOF || text_ == token.text_); } @@ -151,7 +151,7 @@ class TokenInfo { // Returns true if tokens have equal enum and equal string length (but // otherwise ignoring string contents). This is useful for verifying // space-preserving obfuscation transformations. - bool EquivalentBySpace(const TokenInfo& token) const { + bool EquivalentBySpace(const TokenInfo &token) const { return token_enum_ == token.token_enum_ && (token_enum_ == TK_EOF || text_.length() == token.text_.length()); } @@ -165,7 +165,7 @@ class TokenInfo { absl::string_view text_; }; -std::ostream& operator<<(std::ostream&, const TokenInfo&); +std::ostream &operator<<(std::ostream &, const TokenInfo &); // Streamable structure that combines a token with its detailed context. struct TokenWithContext { @@ -173,7 +173,7 @@ struct TokenWithContext { TokenInfo::Context context; }; -std::ostream& operator<<(std::ostream&, const TokenWithContext&); +std::ostream &operator<<(std::ostream &, const TokenWithContext &); // Joins a range of TokenInfo-like objects to form a string whose contents // match those of the elements's ranges, and also points the elements @@ -182,13 +182,13 @@ std::ostream& operator<<(std::ostream&, const TokenWithContext&); // TokenInfo's element type must have the same interface as TokenInfo, // e.g. a (public) subclass of TokenInfo. template -void ConcatenateTokenInfos(std::string* out, TokenIter begin, TokenIter end) { +void ConcatenateTokenInfos(std::string *out, TokenIter begin, TokenIter end) { // Inspired by absl::StrCat implementation details. // Calculate total string length, used to allocate one-time. const auto token_range = make_range(begin, end); size_t total_length = 0; - for (const auto& token : token_range) { + for (const auto &token : token_range) { total_length += token.text().length(); } out->resize(total_length); @@ -197,7 +197,7 @@ void ConcatenateTokenInfos(std::string* out, TokenIter begin, TokenIter end) { // Copy text into new buffer. auto code_iter = out->begin(); // writeable iterator (like char*) int offset = 0; - for (auto& token : token_range) { + for (auto &token : token_range) { // Expect library/compiler to optimize this to a strcpy()/memcpy(). code_iter = std::copy(token.text().begin(), token.text().end(), code_iter); const auto new_text = out_view.substr(offset, token.text().length()); diff --git a/common/util/iterator_range.h b/common/util/iterator_range.h index 59851181e..f8a8e5df8 100644 --- a/common/util/iterator_range.h +++ b/common/util/iterator_range.h @@ -41,13 +41,13 @@ class iterator_range { explicit iterator_range(std::pair p) : begin_(std::move(p.first)), end_(std::move(p.second)) {} - iterator_range(const iterator_range&) = default; - iterator_range(iterator_range&&) noexcept = default; - iterator_range& operator=(const iterator_range&) = default; - iterator_range& operator=(iterator_range&&) noexcept = default; + iterator_range(const iterator_range &) = default; + iterator_range(iterator_range &&) noexcept = default; + iterator_range &operator=(const iterator_range &) = default; + iterator_range &operator=(iterator_range &&) noexcept = default; - const iterator& begin() const { return begin_; } - const iterator& end() const { return end_; } + const iterator &begin() const { return begin_; } + const iterator &end() const { return end_; } private: iterator begin_; diff --git a/common/util/sha256.cc b/common/util/sha256.cc index 693080473..c98a2a47b 100644 --- a/common/util/sha256.cc +++ b/common/util/sha256.cc @@ -266,7 +266,7 @@ std::string Sha256Hex(absl::string_view content) { return ""; } return absl::BytesToHexString(absl::string_view( - reinterpret_cast(sha256bytes.data()), sha256bytes.size())); + reinterpret_cast(sha256bytes.data()), sha256bytes.size())); } } // namespace verible diff --git a/common/util/sha256_test.cc b/common/util/sha256_test.cc index b637210e2..a35c98983 100644 --- a/common/util/sha256_test.cc +++ b/common/util/sha256_test.cc @@ -103,7 +103,7 @@ TEST(Sha256, IncrementallyAddedDigestsAreEqual) { auto digest = context.BuildAndReset(); std::string actual = absl::BytesToHexString(absl::string_view( - reinterpret_cast(digest.data()), digest.size())); + reinterpret_cast(digest.data()), digest.size())); EXPECT_EQ(actual, kOpenSslSha256BananaDigest); } diff --git a/common/util/tree_operations.h b/common/util/tree_operations.h index 395b6c7ab..2439c3063 100644 --- a/common/util/tree_operations.h +++ b/common/util/tree_operations.h @@ -131,10 +131,10 @@ struct TreeNodeParentTraits : FeatureTraits {}; // BirthRank implementation supporting any container. // This overload is a linear-time operation. template -size_t BirthRank(const T& node, std::input_iterator_tag) { +size_t BirthRank(const T &node, std::input_iterator_tag) { if (node.Parent() != nullptr) { size_t index = 0; - for (const auto& child : node.Parent()->Children()) { + for (const auto &child : node.Parent()->Children()) { if (&node == &child) return index; ++index; } @@ -144,7 +144,7 @@ size_t BirthRank(const T& node, std::input_iterator_tag) { // BirthRank optimized for random access containers. template -size_t BirthRank(const T& node, std::random_access_iterator_tag) { +size_t BirthRank(const T &node, std::random_access_iterator_tag) { if (node.Parent() != nullptr) { return std::distance(&*(node.Parent()->Children().begin()), &node); } @@ -155,7 +155,7 @@ size_t BirthRank(const T& node, std::random_access_iterator_tag) { // Calls `container.reserve(new_cap)` if container supports this method. template -auto /* void */ ReserveIfSupported(Container& container, +auto /* void */ ReserveIfSupported(Container &container, typename Container::size_type new_cap) -> std::void_t { container.reserve(new_cap); @@ -163,7 +163,7 @@ auto /* void */ ReserveIfSupported(Container& container, // No-op candidate used when Container doesn't provide `reserve()` method. template -void ReserveIfSupported(Container&, ...) {} +void ReserveIfSupported(Container &, ...) {} } // namespace tree_operations_internal @@ -189,8 +189,8 @@ struct TreeNodeTraits : FeatureTraits { // Returns true when `node` is a leaf, false otherwise. template ::available>* = nullptr> -bool is_leaf(const T& node) { + std::enable_if_t::available> * = nullptr> +bool is_leaf(const T &node) { return node.Children().empty(); } @@ -201,11 +201,11 @@ bool is_leaf(const T& node) { // The const-ness of the returned reference matches the const-ness of the node // argument. template ::available>* = nullptr> -T& DescendPath(T& node, Iterator start, Iterator end) { - auto* current_node = &node; + std::enable_if_t::available> * = nullptr> +T &DescendPath(T &node, Iterator start, Iterator end) { + auto *current_node = &node; for (auto iter = start; iter != end; ++iter) { - auto& children = current_node->Children(); + auto &children = current_node->Children(); const std::size_t index = *iter; CHECK_LT(index, std::size(children)); current_node = &*std::next(children.begin(), index); // descend @@ -217,9 +217,9 @@ T& DescendPath(T& node, Iterator start, Iterator end) { // The const-ness of the returned reference matches the const-ness of the node // argumnent. template ::available>* = nullptr> -T& LeftmostDescendant(T& node) { - T* leaf = &node; + std::enable_if_t::available> * = nullptr> +T &LeftmostDescendant(T &node) { + T *leaf = &node; while (!leaf->Children().empty()) { leaf = &*leaf->Children().begin(); } @@ -231,11 +231,12 @@ T& LeftmostDescendant(T& node) { // argumnent. // // Requires `back()` method in the children container. -template ::available>* = nullptr, - std::void_t().Children().back())>* = nullptr> -T& RightmostDescendant(T& node) { - T* leaf = &node; +template < + class T, // + std::enable_if_t::available> * = nullptr, + std::void_t().Children().back())> * = nullptr> +T &RightmostDescendant(T &node) { + T *leaf = &node; while (!leaf->Children().empty()) { leaf = &leaf->Children().back(); } @@ -244,8 +245,8 @@ T& RightmostDescendant(T& node) { // std::function type representing a printer function in PrintTree. template -using PrintTreePrinterFunction = std::function::Value::const_reference)>; +using PrintTreePrinterFunction = std::function::Value::const_reference)>; // Pretty-print in tree-form. Value() is enclosed in parens, and the whole // node is enclosed in braces. @@ -253,16 +254,16 @@ using PrintTreePrinterFunction = std::function::Value::available>* = nullptr> -std::ostream& PrintTree(const T& node, std::ostream* stream, - const PrintTreePrinterFunction& printer, + std::enable_if_t::Value::available> * = nullptr> +std::ostream &PrintTree(const T &node, std::ostream *stream, + const PrintTreePrinterFunction &printer, size_t indent = 0) { printer(*stream << Spacer(indent) << "{ (", node.Value()) << ')'; if (node.Children().empty()) { *stream << " }"; } else { *stream << '\n'; - for (const auto& child : node.Children()) { + for (const auto &child : node.Children()) { PrintTree(child, stream, printer, indent + 2) << '\n'; } *stream << Spacer(indent) << '}'; @@ -275,13 +276,13 @@ std::ostream& PrintTree(const T& node, std::ostream* stream, // // Requires `Value()` method in the node. template ::Value::available>* = nullptr> -std::ostream& PrintTree(const T& node, std::ostream* stream, + std::enable_if_t::Value::available> * = nullptr> +std::ostream &PrintTree(const T &node, std::ostream *stream, size_t indent = 0) { using ConstValueRef = typename TreeNodeTraits::Value::const_reference; return PrintTree( node, stream, - [](std::ostream& s, ConstValueRef v) -> std::ostream& { return s << v; }, + [](std::ostream &s, ConstValueRef v) -> std::ostream & { return s << v; }, indent); } @@ -289,8 +290,8 @@ std::ostream& PrintTree(const T& node, std::ostream* stream, // // Requires `Value()` method in the node. template ::Value::available>* = nullptr> -std::ostream& operator<<(std::ostream& stream, const T& node) { + std::enable_if_t::Value::available> * = nullptr> +std::ostream &operator<<(std::ostream &stream, const T &node) { return PrintTree(node, &stream); } @@ -310,18 +311,18 @@ using ApplyOnNodeFunction = // Visits all tree nodes in pre-order traversal applying function to all nodes. // Useful for checking invariants between parents and their children. template ::available>* = nullptr> -void ApplyPreOrder(T& node, const ApplyOnNodeFunction& f) { + std::enable_if_t::available> * = nullptr> +void ApplyPreOrder(T &node, const ApplyOnNodeFunction &f) { f(node); - for (auto& child : node.Children()) ApplyPreOrder(child, f); + for (auto &child : node.Children()) ApplyPreOrder(child, f); } // Visits all tree nodes in post-order traversal applying function to all nodes. // Useful for checking invariants between parents and their children. template ::available>* = nullptr> -void ApplyPostOrder(T& node, const ApplyOnNodeFunction& f) { - for (auto& child : node.Children()) ApplyPostOrder(child, f); + std::enable_if_t::available> * = nullptr> +void ApplyPostOrder(T &node, const ApplyOnNodeFunction &f) { + for (auto &child : node.Children()) ApplyPostOrder(child, f); f(node); } @@ -336,10 +337,10 @@ using ApplyOnNodeValueFunction = // // Requires `Value()` method in the node. template ::Value::available>* = nullptr> -void ApplyPreOrder(T& node, const ApplyOnNodeValueFunction& f) { + std::enable_if_t::Value::available> * = nullptr> +void ApplyPreOrder(T &node, const ApplyOnNodeValueFunction &f) { f(node.Value()); - for (auto& child : node.Children()) ApplyPreOrder(child, f); + for (auto &child : node.Children()) ApplyPreOrder(child, f); } // This variant of ApplyPostOrder expects a function on the underlying @@ -347,12 +348,12 @@ void ApplyPreOrder(T& node, const ApplyOnNodeValueFunction& f) { // // Requires `Value()` method in the node. template ::Value::available>* = nullptr> + std::enable_if_t::Value::available> * = nullptr> void ApplyPostOrder( - T& node, - const std::function::Value::reference)>& - f) { - for (auto& child : node.Children()) ApplyPostOrder(child, f); + T &node, + const std::function::Value::reference)> + &f) { + for (auto &child : node.Children()) ApplyPostOrder(child, f); f(node.Value()); } @@ -364,8 +365,8 @@ void ApplyPostOrder( // // Requires `Parent()` method in the node. template ::Parent::available>* = nullptr> -size_t BirthRank(const T& node) { + std::enable_if_t::Parent::available> * = nullptr> +size_t BirthRank(const T &node) { using Iterator = decltype(node.Parent()->Children().begin()); return tree_operations_internal::BirthRank( node, typename std::iterator_traits::iterator_category()); @@ -375,10 +376,10 @@ size_t BirthRank(const T& node) { // // Requires `Parent()` method in the node. template ::Parent::available>* = nullptr> -size_t NumAncestors(const T& node) { + std::enable_if_t::Parent::available> * = nullptr> +size_t NumAncestors(const T &node) { size_t depth = 0; - for (const T* p = node.Parent(); p != nullptr; p = p->Parent()) { + for (const T *p = node.Parent(); p != nullptr; p = p->Parent()) { ++depth; } return depth; @@ -392,10 +393,10 @@ size_t NumAncestors(const T& node) { // // Requires `Parent()` method in the node. template ::Parent::available>* = nullptr> -bool HasAncestor(const T& node, const T* other) { + std::enable_if_t::Parent::available> * = nullptr> +bool HasAncestor(const T &node, const T *other) { if (other == nullptr) return false; - for (const auto* p = node.Parent(); p != nullptr; p = p->Parent()) { + for (const auto *p = node.Parent(); p != nullptr; p = p->Parent()) { if (p == other) return true; } return false; @@ -405,8 +406,8 @@ bool HasAncestor(const T& node, const T* other) { // // Requires `Parent()` method in the node. template ::Parent::available>* = nullptr> -constexpr bool HasAncestor(const T& node, std::nullptr_t) { + std::enable_if_t::Parent::available> * = nullptr> +constexpr bool HasAncestor(const T &node, std::nullptr_t) { return false; } @@ -416,9 +417,9 @@ constexpr bool HasAncestor(const T& node, std::nullptr_t) { // // Requires `Parent()` method in the node. template ::Parent::available>* = nullptr> -T& Root(T& node) { - T* root = &node; + std::enable_if_t::Parent::available> * = nullptr> +T &Root(T &node) { + T *root = &node; while (root->Parent() != nullptr) { root = root->Parent(); } @@ -431,11 +432,11 @@ T& Root(T& node) { // // Requires `Parent()` method in the node. template ::Parent::available>* = nullptr> -T* NearestCommonAncestor(T& node_a, T& node_b) { - T* a = &node_a; - T* b = &node_b; - std::set ancestors_a, ancestors_b; + std::enable_if_t::Parent::available> * = nullptr> +T *NearestCommonAncestor(T &node_a, T &node_b) { + T *a = &node_a; + T *b = &node_b; + std::set ancestors_a, ancestors_b; // In alternation, insert a/b into its respective set of ancestors, // and check for membership in the other ancestor set. // Return as soon as one is found in the other's set of ancestors. @@ -463,8 +464,8 @@ T* NearestCommonAncestor(T& node_a, T& node_b) { // // Requires `Parent()` method in the node. template ::Parent::available>* = nullptr> -bool IsFirstChild(const T& node) { + std::enable_if_t::Parent::available> * = nullptr> +bool IsFirstChild(const T &node) { if (node.Parent() == nullptr) return true; return &*node.Parent()->Children().begin() == &node; } @@ -474,11 +475,11 @@ bool IsFirstChild(const T& node) { // // Requires `back()` method in the children container. // Requires `Parent()` method in the node. -template < - class T, // - std::enable_if_t::Parent::available>* = nullptr, - std::void_t().Children().back())>* = nullptr> -bool IsLastChild(const T& node) { +template ::Parent::available> * = nullptr, + std::void_t().Children().back())> * = + nullptr> +bool IsLastChild(const T &node) { if (node.Parent() == nullptr) return true; return &node.Parent()->Children().back() == &node; } @@ -490,16 +491,16 @@ bool IsLastChild(const T& node) { // // Requires `Parent()` method in the node. template ::Parent::available>* = nullptr> -T* NextLeaf(T& node) { - auto* parent = node.Parent(); + std::enable_if_t::Parent::available> * = nullptr> +T *NextLeaf(T &node) { + auto *parent = node.Parent(); if (parent == nullptr) { // Root node has no next sibling, this is the end(). return nullptr; } // Find the next sibling, if there is one. - auto& siblings = parent->Children(); + auto &siblings = parent->Children(); const size_t birth_rank = BirthRank(node); const size_t next_rank = birth_rank + 1; if (next_rank != std::size(siblings)) { @@ -510,7 +511,7 @@ T* NextLeaf(T& node) { // This is the last child of the group. // Find the nearest parent that has a next child (ascending). // TODO(fangism): rewrite without recursion - auto* next_ancestor = NextLeaf(*parent); + auto *next_ancestor = NextLeaf(*parent); if (next_ancestor == nullptr) return nullptr; // next_ancestor is the NearestCommonAncestor() to the original @@ -525,16 +526,16 @@ T* NextLeaf(T& node) { // // Requires `Parent()` method in the node. template ::Parent::available>* = nullptr> -T* PreviousLeaf(T& node) { - auto* parent = node.Parent(); + std::enable_if_t::Parent::available> * = nullptr> +T *PreviousLeaf(T &node) { + auto *parent = node.Parent(); if (parent == nullptr) { // Root node has no previous sibling, this is the reverse-end(). return nullptr; } // Find the next sibling, if there is one. - auto& siblings = parent->Children(); + auto &siblings = parent->Children(); const size_t birth_rank = BirthRank(node); if (birth_rank > 0) { // More children precede this one. @@ -544,7 +545,7 @@ T* PreviousLeaf(T& node) { // This is the first child of the group. // Find the nearest parent that has a previous child (descending). // TODO(fangism): rewrite without recursion - auto* prev_ancestor = PreviousLeaf(*parent); + auto *prev_ancestor = PreviousLeaf(*parent); if (prev_ancestor == nullptr) return nullptr; // prev_ancestor is the NearestCommonAncestor() to the original @@ -558,8 +559,8 @@ T* PreviousLeaf(T& node) { // // Requires `Parent()` method in the node. template ::Parent::available>* = nullptr> -T* NextSibling(T& node) { + std::enable_if_t::Parent::available> * = nullptr> +T *NextSibling(T &node) { if (node.Parent() == nullptr) { return nullptr; } @@ -578,8 +579,8 @@ T* NextSibling(T& node) { // // Requires `Parent()` method in the node. template ::Parent::available>* = nullptr> -T* PreviousSibling(T& node) { + std::enable_if_t::Parent::available> * = nullptr> +T *PreviousSibling(T &node) { if (node.Parent() == nullptr) { return nullptr; } @@ -604,9 +605,9 @@ T* PreviousSibling(T& node) { // Requires `erase()` method in the children container. template ::Parent::available && - !std::is_const_v>* = nullptr> -void RemoveSelfFromParent(T& node) { - auto& siblings = ABSL_DIE_IF_NULL(node.Parent())->Children(); + !std::is_const_v> * = nullptr> +void RemoveSelfFromParent(T &node) { + auto &siblings = ABSL_DIE_IF_NULL(node.Parent())->Children(); auto self_iter = std::next(siblings.begin(), verible::BirthRank(node)); CHECK_EQ(&*self_iter, &node); siblings.erase(self_iter); @@ -620,7 +621,7 @@ void RemoveSelfFromParent(T& node) { template std::enable_if_t::available && !std::is_const_v && (std::is_convertible_v, T> && ...)> -AdoptSubtree(T& node, AdoptedNodeN&&... node_n) { +AdoptSubtree(T &node, AdoptedNodeN &&...node_n) { using tree_operations_internal::ReserveIfSupported; ReserveIfSupported(node.Children(), std::size(node.Children()) + sizeof...(node_n)); @@ -632,14 +633,14 @@ AdoptSubtree(T& node, AdoptedNodeN&&... node_n) { // // Requires `push_back()` and `clear()` method in the children container. template ::available && - !std::is_const_v>* = nullptr> -void AdoptSubtreesFrom(T& node, T* other) { + std::enable_if_t::available && !std::is_const_v> + * = nullptr> +void AdoptSubtreesFrom(T &node, T *other) { using tree_operations_internal::ReserveIfSupported; - auto& src_children = other->Children(); + auto &src_children = other->Children(); ReserveIfSupported(node.Children(), std::size(node.Children()) + std::size(src_children)); - for (auto& src_child : src_children) { + for (auto &src_child : src_children) { node.Children().push_back(std::move(src_child)); } other->Children().clear(); @@ -656,16 +657,16 @@ void AdoptSubtreesFrom(T& node, T* other) { template < class DstTree, class SrcTree, class SrcNodeToDstValueFunc, class DstValue_ = - std::invoke_result_t, // + std::invoke_result_t, // std::enable_if_t::available && TreeNodeTraits::available && - std::is_constructible_v>* = nullptr> -DstTree Transform(const SrcTree& src_node, const SrcNodeToDstValueFunc& f) { + std::is_constructible_v> * = nullptr> +DstTree Transform(const SrcTree &src_node, const SrcNodeToDstValueFunc &f) { using tree_operations_internal::ReserveIfSupported; // Using invoke() to allow passing SrcTree's method pointers as `f` DstTree dst_node(std::invoke(f, src_node)); ReserveIfSupported(dst_node.Children(), std::size(src_node.Children())); - for (const auto& child : src_node.Children()) { + for (const auto &child : src_node.Children()) { AdoptSubtree(dst_node, Transform(child, f)); } return dst_node; @@ -674,9 +675,9 @@ DstTree Transform(const SrcTree& src_node, const SrcNodeToDstValueFunc& f) { // If this node has exactly one child, replace this node with that child // and return true, otherwise, do nothing and return false. template ::available && - !std::is_const_v>* = nullptr> -bool HoistOnlyChild(T& node) { + std::enable_if_t::available && !std::is_const_v> + * = nullptr> +bool HoistOnlyChild(T &node) { if (std::size(node.Children()) != 1) return false; // Can't do this directly, as assignment to node destroys its child // (`only`) before it is moved. @@ -698,10 +699,10 @@ bool HoistOnlyChild(T& node) { // Requires `push_back()` and `erase()` methods in the children container. template ::Value::available && - !std::is_const_v>* = nullptr> + !std::is_const_v> * = nullptr> void MergeConsecutiveSiblings( - T& node, size_t N, - std::function::Value::type*, + T &node, size_t N, + std::function::Value::type *, typename TreeNodeTraits::Value::const_reference)> joiner) { CHECK_LT(N + 1, std::size(node.Children())); @@ -723,12 +724,12 @@ void MergeConsecutiveSiblings( // // Requires `insert()` and `erase()` methods in the children container. template ::available && - !std::is_const_v>* = nullptr> -void FlattenOnce(T& node) { + std::enable_if_t::available && !std::is_const_v> + * = nullptr> +void FlattenOnce(T &node) { const int grandchildren_count = std::transform_reduce( node.Children().begin(), node.Children().end(), 0, std::plus<>(), - [](const T& gc) { return std::size(gc.Children()); }); + [](const T &gc) { return std::size(gc.Children()); }); using tree_operations_internal::ReserveIfSupported; // Build new children list in a standalone container, then move-assign it to @@ -737,8 +738,8 @@ void FlattenOnce(T& node) { Container grandchildren; ReserveIfSupported(grandchildren, grandchildren_count); - for (auto& child : node.Children()) { - for (auto& grandchild : child.Children()) { + for (auto &child : node.Children()) { + for (auto &grandchild : child.Children()) { grandchildren.push_back(std::move(grandchild)); } } @@ -754,13 +755,13 @@ void FlattenOnce(T& node) { // // Requires `push_back()` method in the children container. template ::available && - !std::is_const_v>* = nullptr> + std::enable_if_t::available && !std::is_const_v> + * = nullptr> void FlattenOnlyChildrenWithChildren( - T& node, std::vector* new_offsets = nullptr) { + T &node, std::vector *new_offsets = nullptr) { const int new_children_count = std::transform_reduce( node.Children().begin(), node.Children().end(), 0, std::plus<>(), - [](const T& gc) { + [](const T &gc) { return std::max(std::size(gc.Children()), 1u); }); using tree_operations_internal::ReserveIfSupported; @@ -778,7 +779,7 @@ void FlattenOnlyChildrenWithChildren( } size_t new_index = 0; - for (auto& child : node.Children()) { + for (auto &child : node.Children()) { if (new_offsets) new_offsets->push_back(new_index); if (child.Children().empty()) { // Use child node @@ -786,7 +787,7 @@ void FlattenOnlyChildrenWithChildren( ++new_index; } else { // Use grandchildren - for (auto& grandchild : child.Children()) { + for (auto &grandchild : child.Children()) { new_children.push_back(std::move(grandchild)); ++new_index; } @@ -800,9 +801,9 @@ void FlattenOnlyChildrenWithChildren( // // Requires `insert()` and `erase()` methods in the children container. template ::available && - !std::is_const_v>* = nullptr> -void FlattenOneChild(T& node, size_t i) { + std::enable_if_t::available && !std::is_const_v> + * = nullptr> +void FlattenOneChild(T &node, size_t i) { const size_t original_size = std::size(node.Children()); CHECK_LT(i, original_size); @@ -834,8 +835,8 @@ void FlattenOneChild(T& node, size_t i) { // // Requires `Parent()` method in the node. template ::Parent::available>* = nullptr> -void Path(const T& node, PathType& path) { + std::enable_if_t::Parent::available> * = nullptr> +void Path(const T &node, PathType &path) { if (node.Parent() != nullptr) { Path(*node.Parent(), path); path.push_back(verible::BirthRank(node)); @@ -849,14 +850,14 @@ void Path(const T& node, PathType& path) { // Requires `Parent()` method in the node. struct NodePath { template ::Parent::available>* = nullptr> - explicit NodePath(const T& node) { + std::enable_if_t::Parent::available> * = nullptr> + explicit NodePath(const T &node) { verible::Path(node, path); } std::vector path; }; -std::ostream& operator<<(std::ostream& stream, const NodePath& p); +std::ostream &operator<<(std::ostream &stream, const NodePath &p); // Binary operations @@ -872,12 +873,12 @@ std::ostream& operator<<(std::ostream& stream, const NodePath& p); // traversal. template ::available && - TreeNodeTraits::available>* = nullptr> + TreeNodeTraits::available> * = nullptr> struct TreeNodePair { TreeNodePair() = default; - TreeNodePair(const LT* l, const RT* r) : left(l), right(r) {} - const LT* left = nullptr; - const RT* right = nullptr; + TreeNodePair(const LT *l, const RT *r) : left(l), right(r) {} + const LT *left = nullptr; + const RT *right = nullptr; }; // Recursively compares two trees node-for-node, checking their values @@ -894,12 +895,12 @@ struct TreeNodePair { // Requires `Value()` method in the node. template ::Value::available && - TreeNodeTraits::Value::available>* = nullptr> + TreeNodeTraits::Value::available> * = nullptr> TreeNodePair DeepEqual( - const LT& left, const RT& right, + const LT &left, const RT &right, const std::function< bool(typename TreeNodeTraits::Value::const_reference, - typename TreeNodeTraits::Value::const_reference)>& comp) { + typename TreeNodeTraits::Value::const_reference)> &comp) { using result_type = TreeNodePair; // Node value comparison at current level. if (!comp(left.Value(), right.Value())) { @@ -908,8 +909,8 @@ TreeNodePair DeepEqual( // Subtree comparison: check number of children first, returning early if // different. - const auto& left_children = left.Children(); - const auto& right_children = right.Children(); + const auto &left_children = left.Children(); + const auto &right_children = right.Children(); if (std::size(left_children) != std::size(right_children)) { return result_type{&left, &right}; } @@ -920,7 +921,7 @@ TreeNodePair DeepEqual( result_type first_diff; // initially nullptrs (void)std::mismatch(left_children.begin(), left_children.end(), right_children.begin(), - [&comp, &first_diff](const LT& l, const RT& r) -> bool { + [&comp, &first_diff](const LT &l, const RT &r) -> bool { const auto result = DeepEqual(l, r, comp); if (result.left == nullptr) { return true; @@ -942,8 +943,8 @@ TreeNodePair DeepEqual( // Requires `Value()` method in the node. template ::Value::available && - TreeNodeTraits::Value::available>* = nullptr> -TreeNodePair DeepEqual(const LT& left, const RT& right) { + TreeNodeTraits::Value::available> * = nullptr> +TreeNodePair DeepEqual(const LT &left, const RT &right) { using LValueRef = typename TreeNodeTraits::Value::const_reference; using RValueRef = typename TreeNodeTraits::Value::const_reference; return DeepEqual(left, right, @@ -959,8 +960,8 @@ TreeNodePair DeepEqual(const LT& left, const RT& right) { // Requires `Value()` method in the node. template ::Value::available && - TreeNodeTraits::Value::available>* = nullptr> -TreeNodePair StructureEqual(const LT& left, const RT& right) { + TreeNodeTraits::Value::available> * = nullptr> +TreeNodePair StructureEqual(const LT &left, const RT &right) { using LValueRef = typename TreeNodeTraits::Value::const_reference; using RValueRef = typename TreeNodeTraits::Value::const_reference; // Ignore node values by always treating them as equal. diff --git a/common/util/tree_operations_test.cc b/common/util/tree_operations_test.cc index b34fa4767..2c3fadab5 100644 --- a/common/util/tree_operations_test.cc +++ b/common/util/tree_operations_test.cc @@ -63,8 +63,8 @@ namespace { // Not intended for direct use - use the other VerifyTree with // EXPECT_PRED_FORMAT2 instead. template -testing::AssertionResult VerifyTree(const T& actual, const T& expected, - const std::vector& path) { +testing::AssertionResult VerifyTree(const T &actual, const T &expected, + const std::vector &path) { const bool id_ok = actual.id() == expected.id(); const bool children_count_ok = actual.Children().size() == expected.Children().size(); @@ -105,9 +105,9 @@ testing::AssertionResult VerifyTree(const T& actual, const T& expected, // Recursively verifies two trees. // This verification function is intended for use with EXPECT_PRED_FORMAT2. template -testing::AssertionResult VerifyTree(const char* actual_expr, - const char* expected_expr, const T& actual, - const T& expected) { +testing::AssertionResult VerifyTree(const char *actual_expr, + const char *expected_expr, const T &actual, + const T &expected) { auto result = VerifyTree(actual, expected, {}); if (!result) { result << "\n" @@ -133,30 +133,30 @@ class SimpleNode { public: using ChildrenType = Container; - explicit SimpleNode(absl::string_view id, ChildrenType&& children = {}) + explicit SimpleNode(absl::string_view id, ChildrenType &&children = {}) : children_(std::move(children)), id_(id) { Relink(); } - ChildrenType& Children() { return children_; } - const ChildrenType& Children() const { return children_; } + ChildrenType &Children() { return children_; } + const ChildrenType &Children() const { return children_; } // Debug/test functions: - const std::string& id() const { return id_; } + const std::string &id() const { return id_; } - void set_id(std::string&& new_id) { id_ = new_id; } + void set_id(std::string &&new_id) { id_ = new_id; } - bool operator==(const ThisType& other) const { return this == &other; } - bool operator!=(const ThisType& other) const { return !(*this == other); } + bool operator==(const ThisType &other) const { return this == &other; } + bool operator!=(const ThisType &other) const { return !(*this == other); } - friend std::ostream& operator<<(std::ostream& stream, const ThisType& self) { + friend std::ostream &operator<<(std::ostream &stream, const ThisType &self) { self.PrintRecursively(stream, 0); return stream; } - friend std::ostream& operator<<(std::ostream& stream, - const ThisType* self_ptr) { + friend std::ostream &operator<<(std::ostream &stream, + const ThisType *self_ptr) { if (self_ptr == nullptr) { return stream << "nullptr"; } @@ -166,26 +166,26 @@ class SimpleNode { // Updates parent pointers in children. void Relink() { - for (auto& child : children_) { + for (auto &child : children_) { child.Relink(); - child.parent_ = static_cast(this); + child.parent_ = static_cast(this); } } protected: - void PrintRecursively(std::ostream& stream, size_t depth = 0) const { + void PrintRecursively(std::ostream &stream, size_t depth = 0) const { stream << verible::Spacer(4 * depth) << absl::StreamFormat("@%p (%s; parent=%p)\n", - static_cast(this), id_, + static_cast(this), id_, parent_); - for (const auto& child : Children()) { + for (const auto &child : Children()) { child.PrintRecursively(stream, depth + 1); } } ChildrenType children_; std::string id_; // Exposed in subclasses as value - ThisType* parent_ = nullptr; // Exposed in subclasses + ThisType *parent_ = nullptr; // Exposed in subclasses }; template