diff --git a/common/analysis/command_file_lexer.cc b/common/analysis/command_file_lexer.cc index 0fff69d74..37bca0c15 100644 --- a/common/analysis/command_file_lexer.cc +++ b/common/analysis/command_file_lexer.cc @@ -25,12 +25,12 @@ namespace verible { CommandFileLexer::CommandFileLexer(absl::string_view config) : parent_lexer_type(config) { const auto lex_status = MakeTokenSequence( - this, config, &tokens_, [&](const TokenInfo& error_token) { + this, config, &tokens_, [&](const TokenInfo &error_token) { LOG(ERROR) << "erroneous token: " << error_token; }); // Pre-process all tokens where its needed - for (auto& t : tokens_) { + for (auto &t : tokens_) { switch (t.token_enum()) { case ConfigToken::kFlag: // Skip -- prefix @@ -45,7 +45,7 @@ CommandFileLexer::CommandFileLexer(absl::string_view config) Restart(config); } -bool CommandFileLexer::TokenIsError(const verible::TokenInfo& token) const { +bool CommandFileLexer::TokenIsError(const verible::TokenInfo &token) const { return false; } diff --git a/common/analysis/command_file_lexer.h b/common/analysis/command_file_lexer.h index d25c367af..757854d1b 100644 --- a/common/analysis/command_file_lexer.h +++ b/common/analysis/command_file_lexer.h @@ -56,7 +56,7 @@ class CommandFileLexer : public FlexLexerAdapter { explicit CommandFileLexer(absl::string_view config); // Returns true if token is invalid. - bool TokenIsError(const verible::TokenInfo&) const final; + bool TokenIsError(const verible::TokenInfo &) const final; // Runs the Lexer and attached command handlers std::vector GetCommandsTokenRanges(); diff --git a/common/analysis/command_file_lexer_test.cc b/common/analysis/command_file_lexer_test.cc index cf208833e..eab65126d 100644 --- a/common/analysis/command_file_lexer_test.cc +++ b/common/analysis/command_file_lexer_test.cc @@ -31,7 +31,7 @@ class FilteredCommandFileLexer : public CommandFileLexer { explicit FilteredCommandFileLexer(absl::string_view code) : CommandFileLexer(code) {} - bool KeepSyntaxTreeTokens(const verible::TokenInfo& t) { + bool KeepSyntaxTreeTokens(const verible::TokenInfo &t) { switch (t.token_enum()) { case ConfigToken::kNewline: return false; @@ -40,7 +40,7 @@ class FilteredCommandFileLexer : public CommandFileLexer { } } - const verible::TokenInfo& DoNextToken() final { + const verible::TokenInfo &DoNextToken() final { do { CommandFileLexer::DoNextToken(); } while (!KeepSyntaxTreeTokens(GetLastToken())); @@ -52,13 +52,13 @@ using LexerTestData = verible::SynthesizedLexerTestData; // Forwarding function to the template test driver function. template -static void TestLexer(Args&&... args) { +static void TestLexer(Args &&...args) { verible::TestLexer(std::forward(args)...); } // Forwarding function to the template test driver function. template -static void TestFilteredLexer(Args&&... args) { +static void TestFilteredLexer(Args &&...args) { verible::TestLexer(std::forward(args)...); } diff --git a/common/analysis/file_analyzer.cc b/common/analysis/file_analyzer.cc index a2051f790..61527a23e 100644 --- a/common/analysis/file_analyzer.cc +++ b/common/analysis/file_analyzer.cc @@ -36,7 +36,7 @@ namespace verible { // Translates phase enum into string for diagnostic messages. -const char* AnalysisPhaseName(const AnalysisPhase& phase) { +const char *AnalysisPhaseName(const AnalysisPhase &phase) { switch (phase) { case AnalysisPhase::kLexPhase: return "lexical"; @@ -47,11 +47,11 @@ const char* AnalysisPhaseName(const AnalysisPhase& phase) { } return "UNKNOWN"; } -std::ostream& operator<<(std::ostream& stream, const AnalysisPhase& phase) { +std::ostream &operator<<(std::ostream &stream, const AnalysisPhase &phase) { return stream << AnalysisPhaseName(phase); } -const char* ErrorSeverityDescription(const ErrorSeverity& severity) { +const char *ErrorSeverityDescription(const ErrorSeverity &severity) { switch (severity) { case ErrorSeverity::kError: return "error"; @@ -60,23 +60,23 @@ const char* ErrorSeverityDescription(const ErrorSeverity& severity) { } return "UNKNOWN"; } -std::ostream& operator<<(std::ostream& stream, const ErrorSeverity& severity) { +std::ostream &operator<<(std::ostream &stream, const ErrorSeverity &severity) { return stream << ErrorSeverityDescription(severity); } -std::ostream& operator<<(std::ostream& stream, const RejectedToken& r) { +std::ostream &operator<<(std::ostream &stream, const RejectedToken &r) { return stream << r.token_info << " (" << r.phase << " " << r.severity << "): " << r.explanation; } // Grab tokens until EOF, and initialize a stream view with all tokens. -absl::Status FileAnalyzer::Tokenize(Lexer* lexer) { +absl::Status FileAnalyzer::Tokenize(Lexer *lexer) { const auto buffer = Data().Contents(); - TokenSequence& tokens = MutableData().MutableTokenStream(); + TokenSequence &tokens = MutableData().MutableTokenStream(); if (auto lex_status = MakeTokenSequence( lexer, buffer, &tokens, - [&](const TokenInfo& error_token) { + [&](const TokenInfo &error_token) { VLOG(1) << "Lexical error with token: " << error_token; // Save error details in rejected_tokens_. rejected_tokens_.push_back( @@ -96,7 +96,7 @@ absl::Status FileAnalyzer::Tokenize(Lexer* lexer) { } // Runs the parser on the current TokenStreamView. -absl::Status FileAnalyzer::Parse(Parser* parser) { +absl::Status FileAnalyzer::Parse(Parser *parser) { absl::Status status = parser->Parse(); // Transfer syntax tree root, even if there were (recovered) syntax errors, // because the partial tree can still be useful to analyze. @@ -105,7 +105,7 @@ absl::Status FileAnalyzer::Parse(Parser* parser) { CHECK(Data().SyntaxTree().get()) << "Expected syntax tree from parsing \"" << filename_ << "\", but got none."; } else { - for (const auto& token : parser->RejectedTokens()) { + for (const auto &token : parser->RejectedTokens()) { rejected_tokens_.push_back(RejectedToken{ token, AnalysisPhase::kParsePhase, "" /* no detailed explanation */}); } @@ -115,7 +115,7 @@ absl::Status FileAnalyzer::Parse(Parser* parser) { // Reports human-readable token error. std::string FileAnalyzer::TokenErrorMessage( - const TokenInfo& error_token) const { + const TokenInfo &error_token) const { // TODO(fangism): accept a RejectedToken to get an explanation message. std::ostringstream output_stream; if (!error_token.isEOF()) { @@ -131,18 +131,18 @@ std::string FileAnalyzer::TokenErrorMessage( std::vector FileAnalyzer::TokenErrorMessages() const { std::vector messages; messages.reserve(rejected_tokens_.size()); - for (const auto& rejected_token : rejected_tokens_) { + for (const auto &rejected_token : rejected_tokens_) { messages.push_back(TokenErrorMessage(rejected_token.token_info)); } return messages; } void FileAnalyzer::ExtractLinterTokenErrorDetail( - const RejectedToken& error_token, - const ReportLinterErrorFunction& error_report) const { + const RejectedToken &error_token, + const ReportLinterErrorFunction &error_report) const { const LineColumnRange range = Data().GetRangeForToken(error_token.token_info); absl::string_view context_line = ""; - const auto& lines = Data().Lines(); + const auto &lines = Data().Lines(); if (range.start.line < static_cast(lines.size())) { context_line = lines[range.start.line]; } @@ -154,14 +154,14 @@ void FileAnalyzer::ExtractLinterTokenErrorDetail( } std::string FileAnalyzer::LinterTokenErrorMessage( - const RejectedToken& error_token, bool diagnostic_context) const { + const RejectedToken &error_token, bool diagnostic_context) const { std::ostringstream out; ExtractLinterTokenErrorDetail( error_token, - [&](const std::string& filename, LineColumnRange range, + [&](const std::string &filename, LineColumnRange range, ErrorSeverity severity, AnalysisPhase phase, absl::string_view token_text, absl::string_view context_line, - const std::string& message) { + const std::string &message) { out << filename_ << ':' << range << " " << phase << " " << severity; if (error_token.token_info.isEOF()) { out << " (unexpected EOF)"; @@ -186,7 +186,7 @@ std::vector FileAnalyzer::LinterTokenErrorMessages( bool diagnostic_context) const { std::vector messages; messages.reserve(rejected_tokens_.size()); - for (const auto& rejected_token : rejected_tokens_) { + for (const auto &rejected_token : rejected_tokens_) { messages.push_back( LinterTokenErrorMessage(rejected_token, diagnostic_context)); } diff --git a/common/analysis/file_analyzer.h b/common/analysis/file_analyzer.h index e8cc17b2c..6f09408ae 100644 --- a/common/analysis/file_analyzer.h +++ b/common/analysis/file_analyzer.h @@ -62,15 +62,15 @@ enum class AnalysisPhase { }; // String representation of phase (needed for CHECK). -const char* AnalysisPhaseName(const AnalysisPhase& phase); -std::ostream& operator<<(std::ostream&, const AnalysisPhase&); +const char *AnalysisPhaseName(const AnalysisPhase &phase); +std::ostream &operator<<(std::ostream &, const AnalysisPhase &); enum class ErrorSeverity { kError, kWarning, }; -const char* ErrorSeverityDescription(const ErrorSeverity& severity); -std::ostream& operator<<(std::ostream&, const ErrorSeverity&); +const char *ErrorSeverityDescription(const ErrorSeverity &severity); +std::ostream &operator<<(std::ostream &, const ErrorSeverity &); // RejectedToken is a categorized warning/error token. // TODO(hzeller): In the presence of warnings, this probably needs to be @@ -82,7 +82,7 @@ struct RejectedToken { ErrorSeverity severity = ErrorSeverity::kError; }; -std::ostream& operator<<(std::ostream&, const RejectedToken&); +std::ostream &operator<<(std::ostream &, const RejectedToken &); // FileAnalyzer holds the results of lexing and parsing. class FileAnalyzer { @@ -100,13 +100,13 @@ class FileAnalyzer { virtual absl::Status Tokenize() = 0; // Break file contents (string) into tokens. - absl::Status Tokenize(Lexer* lexer); + absl::Status Tokenize(Lexer *lexer); // Construct ConcreteSyntaxTree from TokenStreamView. - absl::Status Parse(Parser* parser); + absl::Status Parse(Parser *parser); // Diagnostic message for one rejected token. - std::string TokenErrorMessage(const TokenInfo&) const; + std::string TokenErrorMessage(const TokenInfo &) const; // Collect diagnostic messages for rejected tokens. std::vector TokenErrorMessages() const; @@ -124,14 +124,14 @@ class FileAnalyzer { // The "message" finally is a human-readable error message // TODO(hzeller): these are a lot of parameters, maybe a struct would be good. using ReportLinterErrorFunction = std::function; + absl::string_view context_line, const std::string &message)>; // Extract detailed diagnostic information for rejected token. void ExtractLinterTokenErrorDetail( - const RejectedToken& error_token, - const ReportLinterErrorFunction& error_report) const; + const RejectedToken &error_token, + const ReportLinterErrorFunction &error_report) const; // -- convenience functions using the above @@ -139,25 +139,25 @@ class FileAnalyzer { // Second argument is the show_context option. When enabled // additional diagnostic line is concatenated to an error message // with marker that points to vulnerable token - std::string LinterTokenErrorMessage(const RejectedToken&, bool) const; + std::string LinterTokenErrorMessage(const RejectedToken &, bool) const; // First argument is the show_context option. When enabled // additional diagnostic line is concatenated to an error message // with marker that points to vulnerable token std::vector LinterTokenErrorMessages(bool) const; - const std::vector& GetRejectedTokens() const { + const std::vector &GetRejectedTokens() const { return rejected_tokens_; } // Convenience methods to access text structure view. - const ConcreteSyntaxTree& SyntaxTree() const { + const ConcreteSyntaxTree &SyntaxTree() const { return ABSL_DIE_IF_NULL(text_structure_)->SyntaxTree(); } - const TextStructureView& Data() const { + const TextStructureView &Data() const { return ABSL_DIE_IF_NULL(text_structure_)->Data(); } - TextStructureView& MutableData() { + TextStructureView &MutableData() { return ABSL_DIE_IF_NULL(text_structure_)->MutableData(); } diff --git a/common/analysis/file_analyzer_test.cc b/common/analysis/file_analyzer_test.cc index 7c33eec3c..17f138766 100644 --- a/common/analysis/file_analyzer_test.cc +++ b/common/analysis/file_analyzer_test.cc @@ -43,7 +43,7 @@ TEST(RejectedTokenStreamTest, StringRepresentation) { // Subclass for the purpose of testing FileAnalyzer. class FakeFileAnalyzer : public FileAnalyzer { public: - FakeFileAnalyzer(const std::string& text, const std::string& filename) + FakeFileAnalyzer(const std::string &text, const std::string &filename) : FileAnalyzer(text, filename) {} absl::Status Tokenize() final { @@ -73,10 +73,10 @@ TEST(FileAnalyzerTest, TokenErrorMessageSameLine) { { analyzer.ExtractLinterTokenErrorDetail( {error_token, AnalysisPhase::kParsePhase}, - [](const std::string& filename, LineColumnRange range, + [](const std::string &filename, LineColumnRange range, ErrorSeverity severity, AnalysisPhase phase, absl::string_view token_text, absl::string_view context_line, - const std::string& message) { + const std::string &message) { EXPECT_EQ(filename, "hello.txt"); EXPECT_EQ(range.start.line, 1); EXPECT_EQ(range.start.column, 4); @@ -111,10 +111,10 @@ TEST(FileAnalyzerTest, TokenErrorMessageSameLineWithContext) { { analyzer.ExtractLinterTokenErrorDetail( {error_token, AnalysisPhase::kParsePhase}, - [](const std::string& filename, LineColumnRange range, + [](const std::string &filename, LineColumnRange range, ErrorSeverity severity, AnalysisPhase phase, absl::string_view token_text, absl::string_view context_line, - const std::string& message) { + const std::string &message) { EXPECT_EQ(filename, "hello.txt"); EXPECT_EQ(range.start.line, 1); EXPECT_EQ(range.start.column, 4); @@ -147,10 +147,10 @@ TEST(FileAnalyzerTest, TokenErrorMessageOneChar) { { analyzer.ExtractLinterTokenErrorDetail( {error_token, AnalysisPhase::kParsePhase}, - [](const std::string& filename, LineColumnRange range, + [](const std::string &filename, LineColumnRange range, ErrorSeverity severity, AnalysisPhase phase, absl::string_view token_text, absl::string_view context_line, - const std::string& message) { + const std::string &message) { EXPECT_EQ(filename, "hello.txt"); EXPECT_EQ(range.start.line, 0); EXPECT_EQ(range.start.column, 5); @@ -204,10 +204,10 @@ TEST(FileAnalyzerTest, TokenErrorMessageDifferentLine) { { analyzer.ExtractLinterTokenErrorDetail( {error_token, AnalysisPhase::kParsePhase}, - [](const std::string& filename, LineColumnRange range, + [](const std::string &filename, LineColumnRange range, ErrorSeverity severity, AnalysisPhase phase, absl::string_view token_text, absl::string_view context_line, - const std::string& message) { + const std::string &message) { EXPECT_EQ(filename, "hello.txt"); EXPECT_EQ(range.start.line, 0); EXPECT_EQ(range.start.column, 7); @@ -282,10 +282,10 @@ TEST(FileAnalyzerTest, TokenErrorMessageEOFWithContext) { { analyzer.ExtractLinterTokenErrorDetail( {error_token, AnalysisPhase::kParsePhase}, - [](const std::string& filename, LineColumnRange range, + [](const std::string &filename, LineColumnRange range, ErrorSeverity severity, AnalysisPhase phase, absl::string_view token_text, absl::string_view context_line, - const std::string& message) { + const std::string &message) { EXPECT_EQ(filename, "unbalanced.txt"); EXPECT_EQ(range.start.line, 2); EXPECT_EQ(range.start.column, 7); diff --git a/common/analysis/line_linter.cc b/common/analysis/line_linter.cc index 962af0857..7b4cb1945 100644 --- a/common/analysis/line_linter.cc +++ b/common/analysis/line_linter.cc @@ -24,14 +24,14 @@ namespace verible { -void LineLinter::Lint(const std::vector& lines) { +void LineLinter::Lint(const std::vector &lines) { VLOG(1) << "LineLinter analyzing lines with " << rules_.size() << " rules."; - for (const auto& line : lines) { - for (const auto& rule : rules_) { + for (const auto &line : lines) { + for (const auto &rule : rules_) { ABSL_DIE_IF_NULL(rule)->HandleLine(line); } } - for (const auto& rule : rules_) { + for (const auto &rule : rules_) { rule->Finalize(); } } @@ -39,7 +39,7 @@ void LineLinter::Lint(const std::vector& lines) { std::vector LineLinter::ReportStatus() const { std::vector status; status.reserve(rules_.size()); - for (const auto& rule : rules_) { + for (const auto &rule : rules_) { status.push_back(ABSL_DIE_IF_NULL(rule)->Report()); } return status; diff --git a/common/analysis/line_linter.h b/common/analysis/line_linter.h index 56135f099..17a1cdac8 100644 --- a/common/analysis/line_linter.h +++ b/common/analysis/line_linter.h @@ -32,7 +32,7 @@ namespace verible { class LineLinter { public: // Analyzes a sequence of lines. - void Lint(const std::vector& lines); + void Lint(const std::vector &lines); // Transfers ownership of rule into this Linter void AddRule(std::unique_ptr rule) { diff --git a/common/analysis/line_linter_test_utils.h b/common/analysis/line_linter_test_utils.h index 0a849b7c0..29ae79068 100644 --- a/common/analysis/line_linter_test_utils.h +++ b/common/analysis/line_linter_test_utils.h @@ -35,7 +35,7 @@ class LintRunner { linter_.AddRule(std::move(rule)); } - LintRuleStatus Run(const TextStructureView& text_structure, + LintRuleStatus Run(const TextStructureView &text_structure, absl::string_view) { linter_.Lint(text_structure.Lines()); // Looking for one type of rule violation at a time. diff --git a/common/analysis/lint_waiver.cc b/common/analysis/lint_waiver.cc index 845a7d760..0dbff3f25 100644 --- a/common/analysis/lint_waiver.cc +++ b/common/analysis/lint_waiver.cc @@ -46,13 +46,13 @@ void LintWaiver::WaiveOneLine(absl::string_view rule_name, int line_number) { void LintWaiver::WaiveLineRange(absl::string_view rule_name, int line_begin, int line_end) { - LineNumberSet& line_set = waiver_map_[rule_name]; + LineNumberSet &line_set = waiver_map_[rule_name]; line_set.Add({line_begin, line_end}); } void LintWaiver::WaiveWithRegex(absl::string_view rule_name, - const std::string& regex_str) { - RegexVector& regex_vector = waiver_re_map_[rule_name]; + const std::string ®ex_str) { + RegexVector ®ex_vector = waiver_re_map_[rule_name]; auto regex_iter = regex_cache_.find(regex_str); if (regex_iter == regex_cache_.end()) { @@ -63,12 +63,12 @@ void LintWaiver::WaiveWithRegex(absl::string_view rule_name, } void LintWaiver::RegexToLines(absl::string_view contents, - const LineColumnMap& line_map) { - for (const auto& rule : waiver_re_map_) { - for (const auto* re : rule.second) { + const LineColumnMap &line_map) { + for (const auto &rule : waiver_re_map_) { + for (const auto *re : rule.second) { for (std::cregex_iterator i(contents.begin(), contents.end(), *re); i != std::cregex_iterator(); i++) { - const std::cmatch& match = *i; + const std::cmatch &match = *i; WaiveOneLine(rule.first, line_map.LineAtOffset(match.position())); } } @@ -77,12 +77,12 @@ void LintWaiver::RegexToLines(absl::string_view contents, bool LintWaiver::RuleIsWaivedOnLine(absl::string_view rule_name, int line_number) const { - const auto* line_set = verible::container::FindOrNull(waiver_map_, rule_name); + const auto *line_set = verible::container::FindOrNull(waiver_map_, rule_name); return line_set != nullptr && LineNumberSetContains(*line_set, line_number); } bool LintWaiver::Empty() const { - for (const auto& rule_waiver : waiver_map_) { + for (const auto &rule_waiver : waiver_map_) { if (!rule_waiver.second.empty()) { return false; } @@ -92,11 +92,11 @@ bool LintWaiver::Empty() const { absl::string_view LintWaiverBuilder::ExtractWaivedRuleFromComment( absl::string_view comment_text, - std::vector* comment_tokens) const { + std::vector *comment_tokens) const { // Look for directives of the form: // Addition text beyond the last argument is ignored, so it could // contain more comment text. - auto& tokens = *comment_tokens; + auto &tokens = *comment_tokens; // TODO(fangism): Stop splitting after 3 tokens, everything after that is // ignored. Use something like absl::MaxSplits, but works with multi-spaces. tokens = absl::StrSplit(comment_text, ' ', absl::SkipEmpty()); @@ -113,7 +113,7 @@ absl::string_view LintWaiverBuilder::ExtractWaivedRuleFromComment( return ""; } -void LintWaiverBuilder::ProcessLine(const TokenRange& tokens, int line_number) { +void LintWaiverBuilder::ProcessLine(const TokenRange &tokens, int line_number) { // TODO(fangism): [optimization] Use a SmallVector, or function-local // static to avoid re-allocation in every call. This method does not // need to be re-entrant. @@ -129,13 +129,13 @@ void LintWaiverBuilder::ProcessLine(const TokenRange& tokens, int line_number) { // Determine whether line contains any non-space, non-comment tokens. const bool line_has_tokens = - std::any_of(tokens.begin(), tokens.end(), [this](const TokenInfo& t) { + std::any_of(tokens.begin(), tokens.end(), [this](const TokenInfo &t) { return !(is_token_whitespace_(t) || is_token_comment_(t)); }); if (line_has_tokens) { // Apply un-applied one-line waivers, and then reset them. - for (const auto& rule : unapplied_oneline_waivers_) { + for (const auto &rule : unapplied_oneline_waivers_) { lint_waiver_.WaiveOneLine(rule, line_number); } unapplied_oneline_waivers_.clear(); @@ -143,7 +143,7 @@ void LintWaiverBuilder::ProcessLine(const TokenRange& tokens, int line_number) { // Find all directives on this line. std::vector comment_tokens; // Re-use in loop. - for (const auto& token : tokens) { + for (const auto &token : tokens) { if (is_token_comment_(token)) { // Lex the comment text. const absl::string_view comment_text = @@ -185,9 +185,9 @@ void LintWaiverBuilder::ProcessLine(const TokenRange& tokens, int line_number) { } void LintWaiverBuilder::ProcessTokenRangesByLine( - const TextStructureView& text_structure) { + const TextStructureView &text_structure) { const int total_lines = text_structure.Lines().size(); - const auto& tokens = text_structure.TokenStream(); + const auto &tokens = text_structure.TokenStream(); for (int i = 0; i < total_lines; ++i) { const auto token_range = text_structure.TokenRangeOnLine(i); const int begin_dist = std::distance(tokens.begin(), token_range.begin()); @@ -205,7 +205,7 @@ void LintWaiverBuilder::ProcessTokenRangesByLine( // Flush out any remaining open-ranges, so that those waivers take effect // until the end-of-file. // TODO(b/78064145): Detect these as suspiciously unbalanced waiver uses. - for (const auto& open_range : waiver_open_ranges_) { + for (const auto &open_range : waiver_open_ranges_) { lint_waiver_.WaiveLineRange(open_range.first, open_range.second, total_lines); } @@ -216,7 +216,7 @@ template static std::string WaiveCommandErrorFmt(LineColumn pos, absl::string_view filename, absl::string_view msg, - const T&... args) { + const T &...args) { return absl::StrCat(filename, ":", pos.line + 1, ":", pos.column + 1, ": command error: ", msg, args...); } @@ -224,16 +224,16 @@ static std::string WaiveCommandErrorFmt(LineColumn pos, template static absl::Status WaiveCommandError(LineColumn pos, absl::string_view filename, - absl::string_view msg, const T&... args) { + absl::string_view msg, const T &...args) { return absl::InvalidArgumentError( WaiveCommandErrorFmt(pos, filename, msg, args...)); } static absl::Status WaiveCommandHandler( - const TokenRange& tokens, absl::string_view waive_file, + const TokenRange &tokens, absl::string_view waive_file, absl::string_view waive_content, absl::string_view lintee_filename, - const LineColumnMap& line_map, LintWaiver* waiver, - const std::set& active_rules) { + const LineColumnMap &line_map, LintWaiver *waiver, + const std::set &active_rules) { absl::string_view rule; absl::string_view option; @@ -250,7 +250,7 @@ static absl::Status WaiveCommandHandler( LineColumn token_pos; LineColumn regex_token_pos = {}; - for (const auto& token : tokens) { + for (const auto &token : tokens) { token_pos = line_map.GetLineColAtOffset(waive_content, token.left(waive_content)); @@ -337,7 +337,7 @@ static absl::Status WaiveCommandHandler( const std::regex file_matcher(file_match_regex); location_match = std::regex_search(std::string(lintee_filename), file_matcher); - } catch (const std::regex_error& e) { + } catch (const std::regex_error &e) { return WaiveCommandError(token_pos, waive_file, "--location regex is invalid"); } @@ -365,8 +365,8 @@ static absl::Status WaiveCommandHandler( if (can_use_regex) { try { waiver->WaiveWithRegex(rule, regex); - } catch (const std::regex_error& e) { - const char* reason = e.what(); + } catch (const std::regex_error &e) { + const char *reason = e.what(); return WaiveCommandError(regex_token_pos, waive_file, "Invalid regex: ", reason); @@ -403,12 +403,12 @@ static absl::Status WaiveCommandHandler( } using HandlerFun = std::function&)>; -static const std::map& GetCommandHandlers() { + const LineColumnMap &, LintWaiver *, const std::set &)>; +static const std::map &GetCommandHandlers() { // allocated once, never freed - static const auto* handlers = new std::map{ + static const auto *handlers = new std::map{ // Right now, we only have one handler {"waive", WaiveCommandHandler}, }; @@ -416,7 +416,7 @@ static const std::map& GetCommandHandlers() { } absl::Status LintWaiverBuilder::ApplyExternalWaivers( - const std::set& active_rules, + const std::set &active_rules, absl::string_view lintee_filename, absl::string_view waiver_filename, absl::string_view waivers_config_content) { if (waivers_config_content.empty()) { @@ -427,12 +427,12 @@ absl::Status LintWaiverBuilder::ApplyExternalWaivers( const LineColumnMap line_map(waivers_config_content); LineColumn command_pos; - const auto& handlers = GetCommandHandlers(); + const auto &handlers = GetCommandHandlers(); std::vector commands = lexer.GetCommandsTokenRanges(); bool all_commands_ok = true; - for (const auto& c_range : commands) { + for (const auto &c_range : commands) { const auto command = make_container_range(c_range.begin(), c_range.end()); command_pos = line_map.GetLineColAtOffset( diff --git a/common/analysis/lint_waiver.h b/common/analysis/lint_waiver.h index da4c7ef0b..22e09aadc 100644 --- a/common/analysis/lint_waiver.h +++ b/common/analysis/lint_waiver.h @@ -33,7 +33,7 @@ namespace verible { // LintWaiver maintains a set of line ranges per lint rule that should be // exempt from each rule. class LintWaiver { - using RegexVector = std::vector; + using RegexVector = std::vector; public: LintWaiver() = default; @@ -56,11 +56,11 @@ class LintWaiver { int line_end); // Adds a regular expression which will be used to apply a waiver. - void WaiveWithRegex(absl::string_view rule_name, const std::string& regex); + void WaiveWithRegex(absl::string_view rule_name, const std::string ®ex); // Converts the prepared regular expressions to line numbers and applies the // waivers. - void RegexToLines(absl::string_view content, const LineColumnMap& line_map); + void RegexToLines(absl::string_view content, const LineColumnMap &line_map); // Returns true if `line_number` should be waived for a particular rule. bool RuleIsWaivedOnLine(absl::string_view rule_name, int line_number) const; @@ -70,12 +70,12 @@ class LintWaiver { // TODO(hzeller): The following methods break abstraction and are only // for performance. Reconsider if this is worth it. - const LineNumberSet* LookupLineNumberSet(absl::string_view rule_name) const { + const LineNumberSet *LookupLineNumberSet(absl::string_view rule_name) const { return verible::container::FindOrNull(waiver_map_, rule_name); } // Test if a particular line is included in the set. - static bool LineNumberSetContains(const LineNumberSet& line_set, int line) { + static bool LineNumberSetContains(const LineNumberSet &line_set, int line) { return line_set.Contains(line); } @@ -115,8 +115,8 @@ class LintWaiverBuilder { // The first argument after the trigger is the name of the rule to waive. // 'waive_command' is the second argument after the trigger, and is the // command for 'waive-one-line'. - LintWaiverBuilder(TokenFilterPredicate&& is_comment, - TokenFilterPredicate&& is_space, absl::string_view trigger, + LintWaiverBuilder(TokenFilterPredicate &&is_comment, + TokenFilterPredicate &&is_space, absl::string_view trigger, absl::string_view waive_line_command, absl::string_view waive_start_command, absl::string_view waive_stop_command) @@ -129,21 +129,21 @@ class LintWaiverBuilder { // Takes a single line's worth of tokens and determines updates to the set of // waived lines. Pass a slice of tokens using make_range. - void ProcessLine(const TokenRange& tokens, int line_number); + void ProcessLine(const TokenRange &tokens, int line_number); // Takes a lexically analyzed text structure and determines the entire set of // waived lines. This can be more easily unit-tested using // TextStructureTokenized from text_structure_test_utils.h. - void ProcessTokenRangesByLine(const TextStructureView&); + void ProcessTokenRangesByLine(const TextStructureView &); // Takes a set of active linter rules and the affected filename to be linted, // and applies waivers from waiver_filename and its content. absl::Status ApplyExternalWaivers( - const std::set& active_rules, + const std::set &active_rules, absl::string_view lintee_filename, absl::string_view waiver_filename, absl::string_view waivers_config_content); - const LintWaiver& GetLintWaiver() const { return lint_waiver_; } + const LintWaiver &GetLintWaiver() const { return lint_waiver_; } protected: // Parses a comment and extracts a waived rule name. @@ -151,7 +151,7 @@ class LintWaiverBuilder { // `comment_tokens` is just re-used memory to avoid re-allocation. absl::string_view ExtractWaivedRuleFromComment( absl::string_view comment_text, - std::vector* comment_tokens) const; + std::vector *comment_tokens) const; // Special string that leads a comment that is a waiver directive // Typically, name of linter tool is used here. diff --git a/common/analysis/lint_waiver_test.cc b/common/analysis/lint_waiver_test.cc index fd6eec121..55ef7039b 100644 --- a/common/analysis/lint_waiver_test.cc +++ b/common/analysis/lint_waiver_test.cc @@ -144,10 +144,10 @@ class LintWaiverBuilderTest : public testing::Test, public LintWaiverBuilder { public: LintWaiverBuilderTest() : LintWaiverBuilder( - [](const TokenInfo& token) { + [](const TokenInfo &token) { return token.token_enum() == kComment; }, - [](const TokenInfo& token) { + [](const TokenInfo &token) { return token.token_enum() == kSpace || token.token_enum() == kNewline; }, @@ -155,7 +155,7 @@ class LintWaiverBuilderTest : public testing::Test, public LintWaiverBuilder { kWaiveStopCommand) {} // Convenient sequence adapter to iterator range. - void ProcessLine(const TokenSequence& tokens, size_t line_number) { + void ProcessLine(const TokenSequence &tokens, size_t line_number) { LintWaiverBuilder::ProcessLine(make_range(tokens.begin(), tokens.end()), line_number); } @@ -163,7 +163,7 @@ class LintWaiverBuilderTest : public testing::Test, public LintWaiverBuilder { // Tests that initial state contains no line waivers. TEST_F(LintWaiverBuilderTest, PostConstruction) { - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_TRUE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("some-rule", 0)); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("some-rule", 1)); @@ -174,7 +174,7 @@ TEST_F(LintWaiverBuilderTest, PostConstruction) { TEST_F(LintWaiverBuilderTest, EmptyLine) { const TokenSequence tokens{}; ProcessLine(tokens, 0); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_TRUE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("some-rule", 0)); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("some-rule", 1)); @@ -189,7 +189,7 @@ TEST_F(LintWaiverBuilderTest, OneCommentOnly) { {TokenInfo(kOther, "hello")}}; ProcessLine(lines[0], 2); ProcessLine(lines[1], 3); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("x-rule", 2)); EXPECT_TRUE(waiver.RuleIsWaivedOnLine("x-rule", 3)); @@ -202,7 +202,7 @@ TEST_F(LintWaiverBuilderTest, LastLineWaiveNextLine) { {TokenInfo(kComment, "// mylinter waive z-rule")}}; ProcessLine(lines[0], 2); ProcessLine(lines[1], 3); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("z-rule", 2)); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("z-rule", 3)); // Does nothing with next line until next line is actually encountered. @@ -221,7 +221,7 @@ TEST_F(LintWaiverBuilderTest, OneCommentOnlyMissingWaiveCommand) { {TokenInfo(kOther, "hello")}}; ProcessLine(lines[0], 2); ProcessLine(lines[1], 3); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_TRUE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("x-rule", 2)); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("x-rule", 3)); @@ -235,7 +235,7 @@ TEST_F(LintWaiverBuilderTest, OneCommentOnlyWrongWaiveCommand) { {TokenInfo(kOther, "hello")}}; ProcessLine(lines[0], 2); ProcessLine(lines[1], 3); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_TRUE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("x-rule", 2)); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("x-rule", 3)); @@ -248,7 +248,7 @@ TEST_F(LintWaiverBuilderTest, OneCommentOnlyExtraTextIgnored) { {TokenInfo(kOther, "hello")}}; ProcessLine(lines[0], 0); ProcessLine(lines[1], 1); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("x-rule", 0)); EXPECT_TRUE(waiver.RuleIsWaivedOnLine("x-rule", 1)); @@ -261,7 +261,7 @@ TEST_F(LintWaiverBuilderTest, OneCommentOnlyOddSpacing) { {TokenInfo(kOther, "hello")}}; ProcessLine(lines[0], 0); ProcessLine(lines[1], 1); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("y-rule", 0)); EXPECT_TRUE(waiver.RuleIsWaivedOnLine("y-rule", 1)); @@ -277,7 +277,7 @@ TEST_F(LintWaiverBuilderTest, OneCommentOnlyLeadingSpace) { {TokenInfo(kOther, "hello"), TokenInfo(kOther, "world")}}; ProcessLine(lines[0], 0); ProcessLine(lines[1], 1); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("xx-rule", 0)); EXPECT_TRUE(waiver.RuleIsWaivedOnLine("xx-rule", 1)); @@ -294,7 +294,7 @@ TEST_F(LintWaiverBuilderTest, OneCommentOnlyBlockStyle) { {TokenInfo(kOther, "hello"), TokenInfo(kOther, "world")}}; ProcessLine(lines[0], 0); ProcessLine(lines[1], 1); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("xx-rule", 0)); EXPECT_TRUE(waiver.RuleIsWaivedOnLine("xx-rule", 1)); @@ -309,7 +309,7 @@ TEST_F(LintWaiverBuilderTest, CommentWaiverCanceledByBlankLine) { ProcessLine(lines[0], 0); ProcessLine(lines[1], 1); ProcessLine(lines[2], 2); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_TRUE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("xx-rule", 0)); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("xx-rule", 1)); @@ -325,7 +325,7 @@ TEST_F(LintWaiverBuilderTest, CommentWaiverCarriedToNextLine) { ProcessLine(lines[0], 0); ProcessLine(lines[1], 1); ProcessLine(lines[2], 2); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("xx-rule", 0)); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("xx-rule", 1)); @@ -345,7 +345,7 @@ TEST_F(LintWaiverBuilderTest, CommentWaiverCarriedToNextLineLeadingSpaces) { ProcessLine(lines[0], 3); ProcessLine(lines[1], 4); ProcessLine(lines[2], 5); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("xx-rule", 3)); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("xx-rule", 4)); @@ -362,7 +362,7 @@ TEST_F(LintWaiverBuilderTest, MultipleNextLineWaiversAccumulate) { ProcessLine(lines[0], 0); ProcessLine(lines[1], 1); ProcessLine(lines[2], 2); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("aa-rule", 0)); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("aa-rule", 1)); @@ -382,7 +382,7 @@ TEST_F(LintWaiverBuilderTest, ThisLineWaiver) { TokenInfo(kComment, "// mylinter waive bb-rule")}}; ProcessLine(lines[0], 8); ProcessLine(lines[1], 9); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("bb-rule", 8)); EXPECT_TRUE(waiver.RuleIsWaivedOnLine("bb-rule", 9)); @@ -397,7 +397,7 @@ TEST_F(LintWaiverBuilderTest, NextLineAndThisLineWaiversCombine) { TokenInfo(kComment, "// mylinter waive bb-rule")}}; ProcessLine(lines[0], 0); ProcessLine(lines[1], 1); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("aa-rule", 0)); EXPECT_TRUE(waiver.RuleIsWaivedOnLine("aa-rule", 1)); @@ -416,7 +416,7 @@ TEST_F(LintWaiverBuilderTest, MultipleThisLineWaiver) { TokenInfo(kComment, "/* mylinter waive cc-rule */")}}; ProcessLine(lines[0], 8); ProcessLine(lines[1], 9); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("bb-rule", 8)); EXPECT_TRUE(waiver.RuleIsWaivedOnLine("bb-rule", 9)); @@ -438,7 +438,7 @@ TEST_F(LintWaiverBuilderTest, SingleRangeWaiver) { ProcessLine(lines[0], 2); ProcessLine(lines[1], 3); ProcessLine(lines[2], 4); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("cc-rule", 2)); EXPECT_TRUE(waiver.RuleIsWaivedOnLine("cc-rule", 3)); @@ -454,7 +454,7 @@ TEST_F(LintWaiverBuilderTest, EndRangeWaiverNoEffect) { }; ProcessLine(lines[0], 12); ProcessLine(lines[1], 15); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_TRUE(waiver.Empty()); } @@ -468,7 +468,7 @@ TEST_F(LintWaiverBuilderTest, SingleRangeWaiverDirectivesOnOwnLine) { ProcessLine(lines[0], 4); ProcessLine(lines[1], 5); ProcessLine(lines[2], 6); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("cc-rule", 4)); EXPECT_TRUE(waiver.RuleIsWaivedOnLine("cc-rule", 5)); @@ -487,7 +487,7 @@ TEST_F(LintWaiverBuilderTest, SingleRangeWaiverLonger) { ProcessLine(lines[0], 2); ProcessLine(lines[1], 3); ProcessLine(lines[2], 8); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("cc-rule", 2)); EXPECT_TRUE(waiver.RuleIsWaivedOnLine("cc-rule", 3)); @@ -509,7 +509,7 @@ TEST_F(LintWaiverBuilderTest, SingleRangeWaiverDoubleOpenDoubleClose) { ProcessLine(lines[1], 4); // duplicate waive-begin (ignored) ProcessLine(lines[2], 5); ProcessLine(lines[2], 6); // duplicate waive-end (harmless) - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("cc-rule", 2)); EXPECT_TRUE(waiver.RuleIsWaivedOnLine("cc-rule", 3)); @@ -532,7 +532,7 @@ TEST_F(LintWaiverBuilderTest, MultiRangeWaiver) { ProcessLine(lines[2], 5); ProcessLine(lines[3], 7); ProcessLine(lines[4], 9); - const LintWaiver& waiver = GetLintWaiver(); + const LintWaiver &waiver = GetLintWaiver(); EXPECT_FALSE(waiver.Empty()); EXPECT_FALSE(waiver.RuleIsWaivedOnLine("cc-rule", 2)); EXPECT_TRUE(waiver.RuleIsWaivedOnLine("cc-rule", 3)); @@ -550,7 +550,7 @@ static const TokenInfo EOL(kNewline, "\n"); TEST_F(LintWaiverBuilderTest, FromTextStructureEmptyFile) { const TextStructureTokenized text_structure({}); // empty ProcessTokenRangesByLine(text_structure.Data()); - const auto& lint_waiver = GetLintWaiver(); + const auto &lint_waiver = GetLintWaiver(); EXPECT_TRUE(lint_waiver.Empty()); EXPECT_FALSE(lint_waiver.RuleIsWaivedOnLine("abc-rule", 0)); } @@ -564,7 +564,7 @@ TEST_F(LintWaiverBuilderTest, FromTextStructureNoWaivers) { {TokenInfo(kOther, "hello"), TokenInfo(kOther, ","), TokenInfo(kSpace, " "), TokenInfo(kOther, "world"), EOL}}); ProcessTokenRangesByLine(text_structure.Data()); - const auto& lint_waiver = GetLintWaiver(); + const auto &lint_waiver = GetLintWaiver(); EXPECT_TRUE(lint_waiver.Empty()); EXPECT_FALSE(lint_waiver.RuleIsWaivedOnLine("abc-rule", 0)); } @@ -575,7 +575,7 @@ TEST_F(LintWaiverBuilderTest, FromTextStructureOneWaiverNextLine) { {{TokenInfo(kComment, "// mylinter waive abc-rule"), EOL}, {TokenInfo(kOther, "hello"), EOL}}); ProcessTokenRangesByLine(text_structure.Data()); - const auto& lint_waiver = GetLintWaiver(); + const auto &lint_waiver = GetLintWaiver(); EXPECT_FALSE(lint_waiver.Empty()); EXPECT_TRUE(lint_waiver.RuleIsWaivedOnLine("abc-rule", 1)); } @@ -589,7 +589,7 @@ TEST_F(LintWaiverBuilderTest, FromTextStructureOneWaiverThisLine) { TokenInfo(kComment, "// mylinter waive qq-rule"), EOL}, {TokenInfo(kOther, "bye"), EOL}}); ProcessTokenRangesByLine(text_structure.Data()); - const auto& lint_waiver = GetLintWaiver(); + const auto &lint_waiver = GetLintWaiver(); EXPECT_FALSE(lint_waiver.Empty()); EXPECT_TRUE(lint_waiver.RuleIsWaivedOnLine("qq-rule", 2)); } @@ -604,7 +604,7 @@ TEST_F(LintWaiverBuilderTest, FromTextStructureOneWaiverRange) { {TokenInfo(kOther, "bye"), EOL} // line[4] }); ProcessTokenRangesByLine(text_structure.Data()); - const auto& lint_waiver = GetLintWaiver(); + const auto &lint_waiver = GetLintWaiver(); EXPECT_FALSE(lint_waiver.Empty()); EXPECT_FALSE(lint_waiver.RuleIsWaivedOnLine("qq-rule", 0)); EXPECT_TRUE(lint_waiver.RuleIsWaivedOnLine("qq-rule", 1)); @@ -621,7 +621,7 @@ TEST_F(LintWaiverBuilderTest, FromTextStructureOneWaiverRangeOpened) { {TokenInfo(kOther, "bye"), EOL} // line[3] }); ProcessTokenRangesByLine(text_structure.Data()); - const auto& lint_waiver = GetLintWaiver(); + const auto &lint_waiver = GetLintWaiver(); EXPECT_FALSE(lint_waiver.Empty()); EXPECT_FALSE(lint_waiver.RuleIsWaivedOnLine("qq-rule", 0)); EXPECT_TRUE(lint_waiver.RuleIsWaivedOnLine("qq-rule", 1)); diff --git a/common/analysis/linter_test_utils.cc b/common/analysis/linter_test_utils.cc index af406fe62..9960f6785 100644 --- a/common/analysis/linter_test_utils.cc +++ b/common/analysis/linter_test_utils.cc @@ -30,7 +30,7 @@ namespace verible { // By comparing only the left-bound of the corresponding text ranges, // this assumes that no two violations start at the same location. // This assumption could be removed later, if needed. -static int CompareViolation(const LintViolation& lhs, const TokenInfo& rhs) { +static int CompareViolation(const LintViolation &lhs, const TokenInfo &rhs) { { const int delta = std::distance(rhs.text().begin(), lhs.token.text().begin()); @@ -50,8 +50,8 @@ static int CompareViolation(const LintViolation& lhs, const TokenInfo& rhs) { // TODO(b/151371397): refactor this for re-use for multi-findings style tests. bool LintTestCase::ExactMatchFindings( - const std::set& found_violations, absl::string_view base, - std::ostream* diffstream) const { + const std::set &found_violations, absl::string_view base, + std::ostream *diffstream) const { // Due to the order in which violations are visited, we can assert that // the reported violations are thus ordered. // TODO(fangism): It wouldn't be too expensive to verify this assertion. @@ -76,7 +76,7 @@ bool LintTestCase::ExactMatchFindings( all_match = false; *diffstream << "FOUND these violations, but did not match the expected ones:\n"; - for (const auto& violation : unmatched_found_violations) { + for (const auto &violation : unmatched_found_violations) { violation.token.ToStream(*diffstream, context) << std::endl; } } @@ -84,7 +84,7 @@ bool LintTestCase::ExactMatchFindings( all_match = false; *diffstream << "EXPECTED these violations, but did not match the ones found:\n"; - for (const auto& violation : unmatched_expected_violations) { + for (const auto &violation : unmatched_expected_violations) { violation.ToStream(*diffstream, context) << std::endl; } } diff --git a/common/analysis/linter_test_utils.h b/common/analysis/linter_test_utils.h index ebefed3d2..a33420380 100644 --- a/common/analysis/linter_test_utils.h +++ b/common/analysis/linter_test_utils.h @@ -50,9 +50,9 @@ struct LintTestCase : public TokenInfoTestData { // Returns true if every element is an exact match to the expected set. // TODO(b/141875806): Take a symbol translator function to produce a // human-readable, language-specific enum name. - bool ExactMatchFindings(const std::set& found_violations, + bool ExactMatchFindings(const std::set &found_violations, absl::string_view base, - std::ostream* diffstream) const; + std::ostream *diffstream) const; }; template @@ -66,8 +66,8 @@ class LintRunner; // Tests that LintTestCase test has expected violations under make_rule // Expects test.code to be accepted by AnalyzerType. template -void RunLintTestCase(const LintTestCase& test, - const LintRuleGenerator& make_rule, +void RunLintTestCase(const LintTestCase &test, + const LintRuleGenerator &make_rule, absl::string_view filename) { // All linters start by parsing to yield a TextStructure. // TODO(hzeller): make preprocessor configurable. Right now, preprocessor @@ -78,7 +78,7 @@ void RunLintTestCase(const LintTestCase& test, // Instantiate a linter that runs a single rule to analyze text. LintRunner lint_runner(make_rule()); const LintRuleStatus rule_status = lint_runner.Run(analyzer.Data(), filename); - const auto& violations(rule_status.violations); + const auto &violations(rule_status.violations); // Report detailed differences, if any. const absl::string_view base_text = analyzer.Data().Contents(); @@ -100,7 +100,7 @@ void RunConfiguredLintTestCases( CHECK(config_status.ok()) << config_status.message(); return instance; }; - for (const auto& test : tests) { + for (const auto &test : tests) { RunLintTestCase(test, rule_generator, filename); } } @@ -120,8 +120,8 @@ struct AutoFixInOut { // Tests that LintTestCase test has expected violations under make_rule // Expects test.code to be accepted by AnalyzerType. template -void RunLintAutoFixCase(const AutoFixInOut& test, - const LintRuleGenerator& make_rule) { +void RunLintAutoFixCase(const AutoFixInOut &test, + const LintRuleGenerator &make_rule) { // All linters start by parsing to yield a TextStructure. AnalyzerType analyzer(test.code, ""); absl::Status unused_parser_status = analyzer.Analyze(); @@ -129,11 +129,11 @@ void RunLintAutoFixCase(const AutoFixInOut& test, // Instantiate a linter that runs a single rule to analyze text. LintRunner lint_runner(make_rule()); const LintRuleStatus rule_status = lint_runner.Run(analyzer.Data(), ""); - const auto& violations(rule_status.violations); + const auto &violations(rule_status.violations); CHECK_EQ(violations.size(), 1) << "TODO: apply multi-violation fixes"; CHECK_GT(violations.begin()->autofixes.size(), test.fix_alternative); - const verible::AutoFix& fix = + const verible::AutoFix &fix = rule_status.violations.begin()->autofixes[test.fix_alternative]; std::string fix_out = fix.Apply(analyzer.Data().Contents()); @@ -150,7 +150,7 @@ void RunApplyFixCases(std::initializer_list tests, CHECK(config_status.ok()) << config_status.message(); return instance; }; - for (const auto& test : tests) { + for (const auto &test : tests) { RunLintAutoFixCase(test, rule_generator); } } diff --git a/common/analysis/matcher/bound_symbol_manager.cc b/common/analysis/matcher/bound_symbol_manager.cc index be9c4edba..984b73b96 100644 --- a/common/analysis/matcher/bound_symbol_manager.cc +++ b/common/analysis/matcher/bound_symbol_manager.cc @@ -26,17 +26,17 @@ using verible::container::FindOrNull; namespace verible { namespace matcher { -bool BoundSymbolManager::ContainsSymbol(const std::string& id) const { +bool BoundSymbolManager::ContainsSymbol(const std::string &id) const { return bound_symbols_.find(id) != bound_symbols_.end(); } -const Symbol* BoundSymbolManager::FindSymbol(const std::string& id) const { - auto* result = FindOrNull(bound_symbols_, id); +const Symbol *BoundSymbolManager::FindSymbol(const std::string &id) const { + auto *result = FindOrNull(bound_symbols_, id); return result ? *result : nullptr; } -void BoundSymbolManager::BindSymbol(const std::string& id, - const Symbol* symbol) { +void BoundSymbolManager::BindSymbol(const std::string &id, + const Symbol *symbol) { bound_symbols_[id] = ABSL_DIE_IF_NULL(symbol); } diff --git a/common/analysis/matcher/bound_symbol_manager.h b/common/analysis/matcher/bound_symbol_manager.h index 060e1023a..6bf705bc8 100644 --- a/common/analysis/matcher/bound_symbol_manager.h +++ b/common/analysis/matcher/bound_symbol_manager.h @@ -36,29 +36,29 @@ namespace matcher { class BoundSymbolManager { public: // True if id is in bound_symbols. False otherwise. - bool ContainsSymbol(const std::string& id) const; + bool ContainsSymbol(const std::string &id) const; // If id is in bound_symbols, return matching Symbol*. // Otherwise, returns nullptr. - const Symbol* FindSymbol(const std::string& id) const; + const Symbol *FindSymbol(const std::string &id) const; // Adds symbol to bound_symbols with id as key. - void BindSymbol(const std::string& id, const Symbol* symbol); + void BindSymbol(const std::string &id, const Symbol *symbol); void Clear() { bound_symbols_.clear(); } int Size() const { return bound_symbols_.size(); } - const std::map& GetBoundMap() const { + const std::map &GetBoundMap() const { return bound_symbols_; } template - const T* GetAs(const std::string& key) const { - return down_cast(FindSymbol(key)); + const T *GetAs(const std::string &key) const { + return down_cast(FindSymbol(key)); } private: - std::map bound_symbols_; + std::map bound_symbols_; }; } // namespace matcher diff --git a/common/analysis/matcher/core_matchers.h b/common/analysis/matcher/core_matchers.h index 672aa7484..c796efd70 100644 --- a/common/analysis/matcher/core_matchers.h +++ b/common/analysis/matcher/core_matchers.h @@ -48,12 +48,12 @@ namespace matcher { // TNode(5, Node(5)); // TNode(5, Leaf(2)); template -Matcher AllOf(Args&&... args) { +Matcher AllOf(Args &&...args) { static_assert(sizeof...(args) > 0, "AllOf requires at least one inner matcher"); // AllOf matcher's behavior is completely determined by its inner_matchers - auto predicate = [](const Symbol& symbol) { return true; }; + auto predicate = [](const Symbol &symbol) { return true; }; Matcher matcher(predicate, InnerMatchAll); @@ -88,12 +88,12 @@ Matcher AllOf(Args&&... args) { // And fails to match: // TNode(5, Leaf(2)); template -Matcher AnyOf(Args&&... args) { +Matcher AnyOf(Args &&...args) { static_assert(sizeof...(args) > 0, "AnyOf requires at least one inner matcher"); // AnyOf matcher's behavior is completely determined by its inner_matchers. - auto predicate = [](const Symbol& symbol) { return true; }; + auto predicate = [](const Symbol &symbol) { return true; }; Matcher matcher(predicate, InnerMatchAny); @@ -127,12 +127,12 @@ Matcher AnyOf(Args&&... args) { // And fails to match // TNode(5, Leaf(2)); template -Matcher EachOf(Args&&... args) { +Matcher EachOf(Args &&...args) { static_assert(sizeof...(args) > 0, "EachOf requires at least one inner matcher"); // EachOf matcher's behavior is completely determined by its inner_matchers. - auto predicate = [](const Symbol& symbol) { return true; }; + auto predicate = [](const Symbol &symbol) { return true; }; Matcher matcher(predicate, InnerMatchEachOf); @@ -158,9 +158,9 @@ Matcher EachOf(Args&&... args) { // And fails to match // TNode(5, TNode(5)); template -Matcher Unless(const Matcher& inner_matcher) { +Matcher Unless(const Matcher &inner_matcher) { // Unless matcher's behavior is completely determined by its inner_matcher. - auto predicate = [](const Symbol& symbol) { return true; }; + auto predicate = [](const Symbol &symbol) { return true; }; Matcher matcher(predicate, InnerMatchUnless); diff --git a/common/analysis/matcher/core_matchers_test.cc b/common/analysis/matcher/core_matchers_test.cc index 40d1465df..2c01cfdaf 100644 --- a/common/analysis/matcher/core_matchers_test.cc +++ b/common/analysis/matcher/core_matchers_test.cc @@ -45,7 +45,7 @@ TEST(MatcherBuildersTest, AnyOfSimple) { Node5(AnyOf(PathNode1(), PathLeaf1())), // commutative }; - for (const auto& matcher : matchers) { + for (const auto &matcher : matchers) { BoundSymbolManager bound_symbol_manager; { const auto should_match_leaf = TNode(5, XLeaf(1)); @@ -72,7 +72,7 @@ TEST(MatcherBuildersTest, EachOfSimple) { Node5(EachOf(PathNode1().Bind("node1"), PathLeaf1().Bind("leaf1"))), }; - for (const auto& matcher : matchers) { + for (const auto &matcher : matchers) { BoundSymbolManager bound_symbol_manager; { const auto should_match_leaf = TNode(5, XLeaf(1)); @@ -102,7 +102,7 @@ TEST(MatcherBuildersTest, AllOfSimple) { Node5(AllOf(PathNode1(), PathLeaf1())), // commutative }; - for (const auto& matcher : matchers) { + for (const auto &matcher : matchers) { BoundSymbolManager bound_symbol_manager; { const auto should_match = TNode(5, XLeaf(1), XLeaf(2), TNode(1)); @@ -180,7 +180,7 @@ TEST(CoreMatchers, AnyOfManyTests) { {}}, }; - for (const auto& test_case : test_cases) { + for (const auto &test_case : test_cases) { RunMatcherTestCase(test_case); } } @@ -228,7 +228,7 @@ TEST(CoreMatchers, EachOfManyTests) { {}}, }; - for (const auto& test_case : test_cases) { + for (const auto &test_case : test_cases) { RunMatcherTestCase(test_case); } } @@ -264,7 +264,7 @@ TEST(CoreMatchers, AllOfManyTests) { {}}, }; - for (const auto& test_case : test_cases) { + for (const auto &test_case : test_cases) { RunMatcherTestCase(test_case); } } @@ -294,7 +294,7 @@ TEST(CoreMatchers, UnlessManyTests) { {}}, }; - for (const auto& test_case : test_cases) { + for (const auto &test_case : test_cases) { RunMatcherTestCase(test_case); } } @@ -346,7 +346,7 @@ TEST(CoreMatchers, AllOfAnyOfManyTests) { {}}, }; - for (const auto& test_case : test_cases) { + for (const auto &test_case : test_cases) { RunMatcherTestCase(test_case); } } diff --git a/common/analysis/matcher/descent_path.cc b/common/analysis/matcher/descent_path.cc index 83241f3c6..45e6ab1f1 100644 --- a/common/analysis/matcher/descent_path.cc +++ b/common/analysis/matcher/descent_path.cc @@ -36,16 +36,17 @@ namespace matcher { // // Discovered children are pushed back onto target static void AggregateAllDescendantsFromPath( - const Symbol& symbol, const DescentPath::const_iterator& position, - const DescentPath::const_iterator& end, std::vector* target); + const Symbol &symbol, const DescentPath::const_iterator &position, + const DescentPath::const_iterator &end, + std::vector *target); -std::vector GetAllDescendantsFromPath(const Symbol& symbol, - const DescentPath& path) { - std::vector target; +std::vector GetAllDescendantsFromPath(const Symbol &symbol, + const DescentPath &path) { + std::vector target; if (symbol.Kind() == SymbolKind::kNode) { - const auto* node = down_cast(&symbol); - for (const auto& child : node->children()) { + const auto *node = down_cast(&symbol); + for (const auto &child : node->children()) { if (child) { AggregateAllDescendantsFromPath(*child, path.begin(), path.end(), &target); @@ -57,9 +58,9 @@ std::vector GetAllDescendantsFromPath(const Symbol& symbol, } static void AggregateAllDescendantsFromPath( - const Symbol& symbol, const DescentPath::const_iterator& position, - const DescentPath::const_iterator& end, - std::vector* target) { + const Symbol &symbol, const DescentPath::const_iterator &position, + const DescentPath::const_iterator &end, + std::vector *target) { // If we are somehow operating on empty vector, stop recursion. if (position == end) { return; @@ -79,7 +80,7 @@ static void AggregateAllDescendantsFromPath( return; } - const auto* node = down_cast(&symbol); + const auto *node = down_cast(&symbol); // If the cast fails or the node does not have the required tag or kind, // then stop recursion @@ -89,7 +90,7 @@ static void AggregateAllDescendantsFromPath( } // Recurse on children - for (const auto& child : node->children()) { + for (const auto &child : node->children()) { if (child) { AggregateAllDescendantsFromPath(*child, position + 1, end, target); } diff --git a/common/analysis/matcher/descent_path.h b/common/analysis/matcher/descent_path.h index 7ced5dd3e..40f63fa5f 100644 --- a/common/analysis/matcher/descent_path.h +++ b/common/analysis/matcher/descent_path.h @@ -34,8 +34,8 @@ using DescentPath = std::vector; // entire subtree and return a very large vector if symbol's subtree contains // path in many different ways. // -std::vector GetAllDescendantsFromPath(const Symbol& symbol, - const DescentPath& path); +std::vector GetAllDescendantsFromPath(const Symbol &symbol, + const DescentPath &path); } // namespace matcher } // namespace verible diff --git a/common/analysis/matcher/descent_path_test.cc b/common/analysis/matcher/descent_path_test.cc index e824c7871..46a0134bb 100644 --- a/common/analysis/matcher/descent_path_test.cc +++ b/common/analysis/matcher/descent_path_test.cc @@ -44,8 +44,8 @@ TEST(DescentPathTest, GetDescendantsFromPathEmbeddedNullPass) { auto descendants = GetAllDescendantsFromPath(*root, path); EXPECT_EQ(descendants.size(), 2); - const auto* leaf1 = down_cast(descendants[0]); - const auto* leaf2 = down_cast(descendants[1]); + const auto *leaf1 = down_cast(descendants[0]); + const auto *leaf2 = down_cast(descendants[1]); ASSERT_NE(leaf1, nullptr); ASSERT_NE(leaf2, nullptr); @@ -59,7 +59,7 @@ TEST(DescentPathTest, GetDescendantsFromPathSingle) { auto descendants = GetAllDescendantsFromPath(*root, path); EXPECT_EQ(descendants.size(), 1); - const auto* leaf = down_cast(descendants[0]); + const auto *leaf = down_cast(descendants[0]); ASSERT_NE(leaf, nullptr); EXPECT_EQ(leaf->get().token_enum(), 10); } @@ -70,8 +70,8 @@ TEST(DescentPathTest, GetDescendantsFromPathMultiple) { auto descendants = GetAllDescendantsFromPath(*root, path); EXPECT_EQ(descendants.size(), 2); - const auto* node1 = down_cast(descendants[0]); - const auto* node2 = down_cast(descendants[1]); + const auto *node1 = down_cast(descendants[0]); + const auto *node2 = down_cast(descendants[1]); ASSERT_NE(node1, nullptr); ASSERT_NE(node2, nullptr); @@ -86,8 +86,8 @@ TEST(DescentPathTest, GetDescendantsFromPathMultiplePaths) { auto descendants = GetAllDescendantsFromPath(*root, path); EXPECT_EQ(descendants.size(), 2); - const auto* leaf1 = down_cast(descendants[0]); - const auto* leaf2 = down_cast(descendants[1]); + const auto *leaf1 = down_cast(descendants[0]); + const auto *leaf2 = down_cast(descendants[1]); ASSERT_NE(leaf1, nullptr); ASSERT_NE(leaf2, nullptr); diff --git a/common/analysis/matcher/inner_match_handlers.cc b/common/analysis/matcher/inner_match_handlers.cc index 2b634f209..c4e173b6d 100644 --- a/common/analysis/matcher/inner_match_handlers.cc +++ b/common/analysis/matcher/inner_match_handlers.cc @@ -22,12 +22,12 @@ namespace verible { namespace matcher { -bool InnerMatchAll(const Symbol& symbol, - const std::vector& inner_matchers, - BoundSymbolManager* manager) { +bool InnerMatchAll(const Symbol &symbol, + const std::vector &inner_matchers, + BoundSymbolManager *manager) { BoundSymbolManager backtrack_checkpoint(*manager); - for (const auto& matcher : inner_matchers) { + for (const auto &matcher : inner_matchers) { if (!matcher.Matches(symbol, manager)) { *manager = backtrack_checkpoint; return false; @@ -36,10 +36,10 @@ bool InnerMatchAll(const Symbol& symbol, return true; } -bool InnerMatchAny(const Symbol& symbol, - const std::vector& inner_matchers, - BoundSymbolManager* manager) { - for (const auto& matcher : inner_matchers) { +bool InnerMatchAny(const Symbol &symbol, + const std::vector &inner_matchers, + BoundSymbolManager *manager) { + for (const auto &matcher : inner_matchers) { BoundSymbolManager lookahead(*manager); if (matcher.Matches(symbol, &lookahead)) { *manager = lookahead; @@ -49,12 +49,12 @@ bool InnerMatchAny(const Symbol& symbol, return false; } -bool InnerMatchEachOf(const Symbol& symbol, - const std::vector& inner_matchers, - BoundSymbolManager* manager) { +bool InnerMatchEachOf(const Symbol &symbol, + const std::vector &inner_matchers, + BoundSymbolManager *manager) { bool some_inner_matched_passed = false; - for (const auto& matcher : inner_matchers) { + for (const auto &matcher : inner_matchers) { BoundSymbolManager backup(*manager); if (matcher.Matches(symbol, manager)) { // If matcher passes, remember that we found a passing inner matcher @@ -68,12 +68,12 @@ bool InnerMatchEachOf(const Symbol& symbol, return some_inner_matched_passed; } -bool InnerMatchUnless(const Symbol& symbol, - const std::vector& inner_matchers, - BoundSymbolManager* manager) { +bool InnerMatchUnless(const Symbol &symbol, + const std::vector &inner_matchers, + BoundSymbolManager *manager) { CHECK_EQ(inner_matchers.size(), 1); - const auto& matcher = inner_matchers[0]; + const auto &matcher = inner_matchers[0]; // We don't need to keep track of what inner matcher matches because any // binds will be discarded if it matches. diff --git a/common/analysis/matcher/inner_match_handlers.h b/common/analysis/matcher/inner_match_handlers.h index 46b670ee1..894c736c5 100644 --- a/common/analysis/matcher/inner_match_handlers.h +++ b/common/analysis/matcher/inner_match_handlers.h @@ -42,9 +42,9 @@ namespace matcher { // inner_matchers. // If not all inner matchers match, then nothing is bound to manager. // -bool InnerMatchAll(const Symbol& symbol, - const std::vector& inner_matchers, - BoundSymbolManager* manager); +bool InnerMatchAll(const Symbol &symbol, + const std::vector &inner_matchers, + BoundSymbolManager *manager); // Returns true if one of inner_matchers matches // @@ -52,9 +52,9 @@ bool InnerMatchAll(const Symbol& symbol, // Subsequent matchers are not run. // If no inner matchers match, then nothing is bound to manager. // -bool InnerMatchAny(const Symbol& symbol, - const std::vector& inner_matchers, - BoundSymbolManager* manager); +bool InnerMatchAny(const Symbol &symbol, + const std::vector &inner_matchers, + BoundSymbolManager *manager); // Returns true if one of inner_matchers matches // @@ -62,9 +62,9 @@ bool InnerMatchAny(const Symbol& symbol, // binds is the order in which matchers appear in inner_matchers. // If no inner matchers match, then nothing is bound to manager. // -bool InnerMatchEachOf(const Symbol& symbol, - const std::vector& inner_matchers, - BoundSymbolManager* manager); +bool InnerMatchEachOf(const Symbol &symbol, + const std::vector &inner_matchers, + BoundSymbolManager *manager); // Returns true if inner_matcher does not match. // Returns false if inner_matcher does match. @@ -73,9 +73,9 @@ bool InnerMatchEachOf(const Symbol& symbol, // // No symbols are bound to manager regardless of outcome. // -bool InnerMatchUnless(const Symbol& symbol, - const std::vector& inner_matchers, - BoundSymbolManager* manager); +bool InnerMatchUnless(const Symbol &symbol, + const std::vector &inner_matchers, + BoundSymbolManager *manager); } // namespace matcher } // namespace verible diff --git a/common/analysis/matcher/matcher.cc b/common/analysis/matcher/matcher.cc index 8521b787d..39af2c762 100644 --- a/common/analysis/matcher/matcher.cc +++ b/common/analysis/matcher/matcher.cc @@ -24,7 +24,7 @@ namespace verible { namespace matcher { -bool Matcher::Matches(const Symbol& symbol, BoundSymbolManager* manager) const { +bool Matcher::Matches(const Symbol &symbol, BoundSymbolManager *manager) const { if (predicate_(symbol)) { // If this matcher matches (as in, predicate succeeds), test inner matchers // to see if they also match. @@ -41,7 +41,7 @@ bool Matcher::Matches(const Symbol& symbol, BoundSymbolManager* manager) const { // TODO(jeremycs): add branching match groups here // Try to match inner matches to every target symbol. - for (const auto& target_symbol : next_targets) { + for (const auto &target_symbol : next_targets) { if (!target_symbol) continue; bool inner_match_result = inner_match_handler_(*target_symbol, inner_matchers_, manager); diff --git a/common/analysis/matcher/matcher.h b/common/analysis/matcher/matcher.h index 999dbb39a..ad0e430cb 100644 --- a/common/analysis/matcher/matcher.h +++ b/common/analysis/matcher/matcher.h @@ -30,14 +30,14 @@ namespace matcher { // Forward declaration of Matcher class class Matcher; -using SymbolPredicate = std::function; +using SymbolPredicate = std::function; using SymbolTransformer = - std::function(const Symbol&)>; + std::function(const Symbol &)>; // Manages recursion on symbol for inner_matchers using InnerMatchHandler = std::function& inner_matchers, - BoundSymbolManager* manager)>; + const Symbol &symbol, const std::vector &inner_matchers, + BoundSymbolManager *manager)>; // Matcher provides an interface for creating nested tree pattern matchers. // @@ -54,11 +54,11 @@ using InnerMatchHandler = std::function - void AddMatchers(const Matcher& matcher, Args&&... args) { + void AddMatchers(const Matcher &matcher, Args &&...args) { inner_matchers_.push_back(matcher); AddMatchers(std::forward(args)...); } @@ -93,7 +93,7 @@ class Matcher { // to inner matchers. // Default transformation does not modify symbol. SymbolTransformer transformer_ = - [](const Symbol& symbol) -> std::vector { + [](const Symbol &symbol) -> std::vector { return {&symbol}; }; @@ -125,7 +125,7 @@ class BindableMatcher : public Matcher { // Inherit constructors from Matcher using Matcher::Matcher; - BindableMatcher& Bind(const std::string& id) { + BindableMatcher &Bind(const std::string &id) { bind_id_ = id; return *this; } diff --git a/common/analysis/matcher/matcher_builders.h b/common/analysis/matcher/matcher_builders.h index b85e0098d..8888dfa05 100644 --- a/common/analysis/matcher/matcher_builders.h +++ b/common/analysis/matcher/matcher_builders.h @@ -41,7 +41,7 @@ namespace matcher { // See verible/doc/style_lint.md for example usage template -bool EqualTagPredicate(const Symbol& symbol) { +bool EqualTagPredicate(const Symbol &symbol) { SymbolTag symbol_tag = {Kind, static_cast(Tag)}; return symbol.Tag() == symbol_tag; } @@ -73,7 +73,7 @@ class PathMatchBuilder { static_assert(N > 0, "Path must have at least one element"); public: - explicit constexpr PathMatchBuilder(const std::array& path) + explicit constexpr PathMatchBuilder(const std::array &path) : path_(path) {} template @@ -86,13 +86,13 @@ class PathMatchBuilder { // As long as one of the inner_matchers matches against discovered // descendants, PathMatchBuilder also matches. - auto predicate = [](const Symbol& symbol) { return true; }; + auto predicate = [](const Symbol &symbol) { return true; }; // The transformation that is performed on the symbol before it passed // off to the InnerMatchHandler. // Each descendant in returned vector is matched seperately. // TODO(jeremycs): describe match branching behavior here - auto transformer = [local_path](const Symbol& symbol) { + auto transformer = [local_path](const Symbol &symbol) { return GetAllDescendantsFromPath(symbol, local_path); }; @@ -183,7 +183,7 @@ class DynamicTagMatchBuilder { template BindableMatcher operator()(Args... args) const { - BindableMatcher matcher([this](const Symbol& s) { return s.Tag() == tag_; }, + BindableMatcher matcher([this](const Symbol &s) { return s.Tag() == tag_; }, InnerMatchAll); matcher.AddMatchers(std::forward(args)...); return matcher; diff --git a/common/analysis/matcher/matcher_builders_test.cc b/common/analysis/matcher/matcher_builders_test.cc index 86bcd837d..7501b8c58 100644 --- a/common/analysis/matcher/matcher_builders_test.cc +++ b/common/analysis/matcher/matcher_builders_test.cc @@ -102,7 +102,7 @@ TEST(MatcherBuildersTest, MatcherTestCases) { {Node5(PathLeaf1(PathLeaf1())), TNode(5, XLeaf(1), XLeaf(1)), false, {}}, }; - for (const auto& test_case : test_cases) { + for (const auto &test_case : test_cases) { RunMatcherTestCase(test_case); } } @@ -168,7 +168,7 @@ TEST(MatcherBuildersTest, DynamicMatcherTestCases) { {DNode5(PathLeaf1(PathLeaf1())), TNode(5, XLeaf(1), XLeaf(1)), false, {}}, }; - for (const auto& test_case : test_cases) { + for (const auto &test_case : test_cases) { RunMatcherTestCase(test_case); } } @@ -195,9 +195,9 @@ TEST(MatcherBuildersTest, MatchPathSimple) { EXPECT_TRUE(bound_symbol_manager.ContainsSymbol("outer")); EXPECT_TRUE(bound_symbol_manager.ContainsSymbol("inner")); - const auto* outer_match = down_cast( + const auto *outer_match = down_cast( bound_symbol_manager.FindSymbol("outer")); - const auto* inner_match = down_cast( + const auto *inner_match = down_cast( bound_symbol_manager.FindSymbol("inner")); ASSERT_NE(outer_match, nullptr); ASSERT_NE(inner_match, nullptr); diff --git a/common/analysis/matcher/matcher_test.cc b/common/analysis/matcher/matcher_test.cc index 83477780c..3144842ab 100644 --- a/common/analysis/matcher/matcher_test.cc +++ b/common/analysis/matcher/matcher_test.cc @@ -103,8 +103,8 @@ TEST(MatcherTest, BindMatcherFlat) { const auto should_match = TNode(5); EXPECT_TRUE(matcher.Matches(*should_match, &bound_symbol_manager)); EXPECT_TRUE(bound_symbol_manager.ContainsSymbol("f")); - const auto* node_ptr = - down_cast(bound_symbol_manager.FindSymbol("f")); + const auto *node_ptr = + down_cast(bound_symbol_manager.FindSymbol("f")); ASSERT_NE(node_ptr, nullptr); EXPECT_TRUE(node_ptr->MatchesTag(5)); EXPECT_EQ(bound_symbol_manager.Size(), 1); @@ -133,10 +133,10 @@ TEST(MatcherTest, BindMatcherNested) { EXPECT_TRUE(outer_matcher.Matches(*should_match, &bound_symbol_manager)); EXPECT_TRUE(bound_symbol_manager.ContainsSymbol("f")); EXPECT_TRUE(bound_symbol_manager.ContainsSymbol("g")); - const auto* outer_match = - down_cast(bound_symbol_manager.FindSymbol("f")); + const auto *outer_match = + down_cast(bound_symbol_manager.FindSymbol("f")); auto inner_match = - down_cast(bound_symbol_manager.FindSymbol("g")); + down_cast(bound_symbol_manager.FindSymbol("g")); ASSERT_NE(outer_match, nullptr); ASSERT_NE(inner_match, nullptr); EXPECT_TRUE(inner_match->MatchesTag(5)); @@ -153,9 +153,9 @@ TEST(MatcherTest, BindMatcherNested) { // Returns first child of symbol as a one element array. // If symbol is a leaf or doesn't have children, returns empty array. -static std::vector GetFirstChild(const Symbol& symbol) { +static std::vector GetFirstChild(const Symbol &symbol) { if (symbol.Kind() == SymbolKind::kNode) { - const auto& node = down_cast(symbol); + const auto &node = down_cast(symbol); if (node.children().empty()) return {}; return {node.children()[0].get()}; } @@ -163,7 +163,7 @@ static std::vector GetFirstChild(const Symbol& symbol) { return {}; } -static bool HasExactlyOneChild(const Symbol& symbol) { +static bool HasExactlyOneChild(const Symbol &symbol) { return GetFirstChild(symbol).size() == 1; } @@ -185,10 +185,10 @@ TEST(MatcherTest, SimpleTransformerTest) { EXPECT_TRUE(bound_symbol_manager.ContainsSymbol("f")); EXPECT_TRUE(bound_symbol_manager.ContainsSymbol("g")); - const auto* outer_match = - down_cast(bound_symbol_manager.FindSymbol("f")); - const auto* inner_match = - down_cast(bound_symbol_manager.FindSymbol("g")); + const auto *outer_match = + down_cast(bound_symbol_manager.FindSymbol("f")); + const auto *inner_match = + down_cast(bound_symbol_manager.FindSymbol("g")); ASSERT_NE(outer_match, nullptr); ASSERT_NE(inner_match, nullptr); EXPECT_EQ(outer_match->Tag(), NodeTag(5)); diff --git a/common/analysis/matcher/matcher_test_utils.cc b/common/analysis/matcher/matcher_test_utils.cc index b852d45c9..8f6855144 100644 --- a/common/analysis/matcher/matcher_test_utils.cc +++ b/common/analysis/matcher/matcher_test_utils.cc @@ -30,7 +30,7 @@ namespace verible { namespace matcher { -void RunMatcherTestCase(const MatcherTestCase& test) { +void RunMatcherTestCase(const MatcherTestCase &test) { BoundSymbolManager bound_symbol_manager; ASSERT_NE(test.root, nullptr); @@ -42,7 +42,7 @@ void RunMatcherTestCase(const MatcherTestCase& test) { // If test passed, then all bound symbols should precisely matched expected. EXPECT_EQ(test.expected_bound_nodes.size(), bound_symbol_manager.Size()); - for (const auto& expected : test.expected_bound_nodes) { + for (const auto &expected : test.expected_bound_nodes) { EXPECT_TRUE(bound_symbol_manager.ContainsSymbol(expected.first)); auto matched_symbol = bound_symbol_manager.FindSymbol(expected.first); @@ -57,22 +57,22 @@ void RunMatcherTestCase(const MatcherTestCase& test) { class MatchCounter : public TreeVisitorRecursive { public: - explicit MatchCounter(const Matcher& matcher) : matcher_(matcher) {} + explicit MatchCounter(const Matcher &matcher) : matcher_(matcher) {} - int Count(const Symbol& symbol) { + int Count(const Symbol &symbol) { num_matches_ = 0; symbol.Accept(this); return num_matches_; } - void Visit(const SyntaxTreeLeaf& leaf) final { TestSymbol(leaf); } - void Visit(const SyntaxTreeNode& node) final { TestSymbol(node); } + void Visit(const SyntaxTreeLeaf &leaf) final { TestSymbol(leaf); } + void Visit(const SyntaxTreeNode &node) final { TestSymbol(node); } private: const Matcher matcher_; int num_matches_ = 0; - void TestSymbol(const Symbol& symbol) { + void TestSymbol(const Symbol &symbol) { BoundSymbolManager manager; bool found_match = matcher_.Matches(symbol, &manager); @@ -82,7 +82,7 @@ class MatchCounter : public TreeVisitorRecursive { } }; -void ExpectMatchesInAST(const Symbol& tree, const Matcher& matcher, +void ExpectMatchesInAST(const Symbol &tree, const Matcher &matcher, int num_matches, absl::string_view code) { MatchCounter counter(matcher); EXPECT_EQ(num_matches, counter.Count(tree)) << "code:\n" diff --git a/common/analysis/matcher/matcher_test_utils.h b/common/analysis/matcher/matcher_test_utils.h index 5a34809fb..d6bdb38f5 100644 --- a/common/analysis/matcher/matcher_test_utils.h +++ b/common/analysis/matcher/matcher_test_utils.h @@ -41,18 +41,18 @@ struct RawMatcherTestCase { const int num_matches; }; -void ExpectMatchesInAST(const Symbol& tree, const Matcher& matcher, +void ExpectMatchesInAST(const Symbol &tree, const Matcher &matcher, int num_matches, absl::string_view code); // Runs a raw test case. Expects test.code to be correctly parsed by // analyzer A. template -void RunRawMatcherTestCase(const RawMatcherTestCase& test) { +void RunRawMatcherTestCase(const RawMatcherTestCase &test) { A analyzer(test.code, "<>"); absl::Status status = analyzer.Analyze(); EXPECT_TRUE(status.ok()) << "code with error:\n" << test.code; - auto* tree = analyzer.SyntaxTree().get(); + auto *tree = analyzer.SyntaxTree().get(); EXPECT_TRUE(tree != nullptr); ExpectMatchesInAST(*tree, test.matcher, test.num_matches, test.code); @@ -73,7 +73,7 @@ struct MatcherTestCase { const std::map expected_bound_nodes; }; -void RunMatcherTestCase(const MatcherTestCase& test); +void RunMatcherTestCase(const MatcherTestCase &test); } // namespace matcher } // namespace verible diff --git a/common/analysis/syntax_tree_lint_rule.h b/common/analysis/syntax_tree_lint_rule.h index b9f46a84d..184fcdcb3 100644 --- a/common/analysis/syntax_tree_lint_rule.h +++ b/common/analysis/syntax_tree_lint_rule.h @@ -40,12 +40,12 @@ class SyntaxTreeLintRule : public LintRule { public: ~SyntaxTreeLintRule() override = default; - virtual void HandleLeaf(const SyntaxTreeLeaf& leaf, - const SyntaxTreeContext& context) {} - virtual void HandleNode(const SyntaxTreeNode& node, - const SyntaxTreeContext& context) {} - virtual void HandleSymbol(const Symbol& node, - const SyntaxTreeContext& context) {} + virtual void HandleLeaf(const SyntaxTreeLeaf &leaf, + const SyntaxTreeContext &context) {} + virtual void HandleNode(const SyntaxTreeNode &node, + const SyntaxTreeContext &context) {} + virtual void HandleSymbol(const Symbol &node, + const SyntaxTreeContext &context) {} }; } // namespace verible diff --git a/common/analysis/syntax_tree_linter.cc b/common/analysis/syntax_tree_linter.cc index 8fb100a1f..c07a4ee49 100644 --- a/common/analysis/syntax_tree_linter.cc +++ b/common/analysis/syntax_tree_linter.cc @@ -27,7 +27,7 @@ namespace verible { -void SyntaxTreeLinter::Lint(const Symbol& root) { +void SyntaxTreeLinter::Lint(const Symbol &root) { VLOG(1) << "SyntaxTreeLinter analyzing syntax tree with " << rules_.size() << " rules."; root.Accept(this); @@ -36,15 +36,15 @@ void SyntaxTreeLinter::Lint(const Symbol& root) { std::vector SyntaxTreeLinter::ReportStatus() const { std::vector status; status.reserve(rules_.size()); - for (const auto& rule : rules_) { + for (const auto &rule : rules_) { status.push_back(ABSL_DIE_IF_NULL(rule)->Report()); } return status; } // Visits a leaf. Every held rule handles that leaf. -void SyntaxTreeLinter::Visit(const SyntaxTreeLeaf& leaf) { - for (const auto& rule : rules_) { +void SyntaxTreeLinter::Visit(const SyntaxTreeLeaf &leaf) { + for (const auto &rule : rules_) { // Have rule handle the leaf as both a leaf and a symbol. ABSL_DIE_IF_NULL(rule)->HandleLeaf(leaf, Context()); rule->HandleSymbol(leaf, Context()); @@ -54,8 +54,8 @@ void SyntaxTreeLinter::Visit(const SyntaxTreeLeaf& leaf) { // Visits a node. First, linter has every rule handle that node // Second, linter recurses on every non-null child of that node in order // to visit the entire tree -void SyntaxTreeLinter::Visit(const SyntaxTreeNode& node) { - for (const auto& rule : rules_) { +void SyntaxTreeLinter::Visit(const SyntaxTreeNode &node) { + for (const auto &rule : rules_) { // Have rule handle the node as both a node and a symbol. ABSL_DIE_IF_NULL(rule)->HandleNode(node, Context()); rule->HandleSymbol(node, Context()); diff --git a/common/analysis/syntax_tree_linter.h b/common/analysis/syntax_tree_linter.h index 63940e394..458131756 100644 --- a/common/analysis/syntax_tree_linter.h +++ b/common/analysis/syntax_tree_linter.h @@ -51,8 +51,8 @@ class SyntaxTreeLinter : public TreeContextVisitor { public: SyntaxTreeLinter() = default; - void Visit(const SyntaxTreeLeaf& leaf) final; - void Visit(const SyntaxTreeNode& node) final; + void Visit(const SyntaxTreeLeaf &leaf) final; + void Visit(const SyntaxTreeNode &node) final; // Transfers ownership of rule into Linter void AddRule(std::unique_ptr rule) { @@ -63,7 +63,7 @@ class SyntaxTreeLinter : public TreeContextVisitor { std::vector ReportStatus() const; // Performs lint analysis on root - void Lint(const Symbol& root); + void Lint(const Symbol &root); private: // List of rules that the linter is using. Rules are responsible for tracking diff --git a/common/analysis/syntax_tree_linter_test.cc b/common/analysis/syntax_tree_linter_test.cc index de1bbf7f7..cfbb1f551 100644 --- a/common/analysis/syntax_tree_linter_test.cc +++ b/common/analysis/syntax_tree_linter_test.cc @@ -39,16 +39,16 @@ class AllLeavesMustBeN : public SyntaxTreeLintRule { // When handling leaf, check that it has target tag and report a violation // is not - void HandleLeaf(const SyntaxTreeLeaf& leaf, - const SyntaxTreeContext& context) final { + void HandleLeaf(const SyntaxTreeLeaf &leaf, + const SyntaxTreeContext &context) final { if (leaf.get().token_enum() != target_) { violations_.insert(LintViolation(leaf.get(), "", context)); } } // Do not operate on nodes - void HandleNode(const SyntaxTreeNode& node, - const SyntaxTreeContext& context) final {} + void HandleNode(const SyntaxTreeNode &node, + const SyntaxTreeContext &context) final {} LintRuleStatus Report() const final { return LintRuleStatus(violations_); } private: @@ -113,18 +113,18 @@ TEST(SyntaxTreeLinterTest, MultipleRules) { class ChildrenLeavesAscending : public SyntaxTreeLintRule { public: // Do not process leaves - void HandleLeaf(const SyntaxTreeLeaf& leaf, - const SyntaxTreeContext& context) final {} + void HandleLeaf(const SyntaxTreeLeaf &leaf, + const SyntaxTreeContext &context) final {} // When handling nodes, iterate through all children and check that tags // are ascending. Report leafs nodes that have leaves that are out of order. - void HandleNode(const SyntaxTreeNode& node, - const SyntaxTreeContext& context) final { + void HandleNode(const SyntaxTreeNode &node, + const SyntaxTreeContext &context) final { int last_tag = 0; - for (const auto& child : node.children()) { + for (const auto &child : node.children()) { if (child->Kind() == SymbolKind::kLeaf) { - const SyntaxTreeLeaf* leaf_child = - down_cast(child.get()); + const SyntaxTreeLeaf *leaf_child = + down_cast(child.get()); const int current_tag = leaf_child->get().token_enum(); if (current_tag >= last_tag) { last_tag = current_tag; @@ -221,15 +221,15 @@ TEST(SyntaxTreeLinterTest, HeterogenousTests) { class TagMatchesContextDepth : public SyntaxTreeLintRule { public: // When handling a leaf, check leaf's tag vs the size of its context - void HandleLeaf(const SyntaxTreeLeaf& leaf, - const SyntaxTreeContext& context) final { + void HandleLeaf(const SyntaxTreeLeaf &leaf, + const SyntaxTreeContext &context) final { if (static_cast(leaf.get().token_enum()) != context.size()) { violations_.insert(LintViolation(leaf.get(), "", context)); } } // Do not process nodes - void HandleNode(const SyntaxTreeNode& node, - const SyntaxTreeContext& context) final {} + void HandleNode(const SyntaxTreeNode &node, + const SyntaxTreeContext &context) final {} LintRuleStatus Report() const final { return LintRuleStatus(violations_); } diff --git a/common/analysis/syntax_tree_linter_test_utils.h b/common/analysis/syntax_tree_linter_test_utils.h index 3460aec90..75e460585 100644 --- a/common/analysis/syntax_tree_linter_test_utils.h +++ b/common/analysis/syntax_tree_linter_test_utils.h @@ -37,7 +37,7 @@ class LintRunner { linter_.AddRule(std::move(rule)); } - LintRuleStatus Run(const TextStructureView& text_structure, + LintRuleStatus Run(const TextStructureView &text_structure, absl::string_view) { linter_.Lint(*ABSL_DIE_IF_NULL(text_structure.SyntaxTree())); // Looking for one type of rule violation at a time. diff --git a/common/analysis/syntax_tree_search.cc b/common/analysis/syntax_tree_search.cc index 34a5578fa..5fa39fd56 100644 --- a/common/analysis/syntax_tree_search.cc +++ b/common/analysis/syntax_tree_search.cc @@ -37,31 +37,31 @@ using matcher::BoundSymbolManager; class SyntaxTreeSearcher : public TreeContextVisitor { public: SyntaxTreeSearcher( - const matcher::Matcher& m, - const std::function& context_predicate) + const matcher::Matcher &m, + const std::function &context_predicate) : matcher_(m), context_predicate_(context_predicate) {} - void Search(const Symbol& root) { root.Accept(this); } + void Search(const Symbol &root) { root.Accept(this); } - const std::vector& Matches() const { return matches_; } + const std::vector &Matches() const { return matches_; } private: - void CheckSymbol(const Symbol&); - void Visit(const SyntaxTreeLeaf& leaf) final; - void Visit(const SyntaxTreeNode& node) final; + void CheckSymbol(const Symbol &); + void Visit(const SyntaxTreeLeaf &leaf) final; + void Visit(const SyntaxTreeNode &node) final; // Main matcher that finds a particular type of tree node. const verible::matcher::Matcher matcher_; // Predicate that further qualifies the matches of interest. - const std::function context_predicate_; + const std::function context_predicate_; // Accumulated set of matches. std::vector matches_; }; // Checks if leaf matches critera. -void SyntaxTreeSearcher::CheckSymbol(const Symbol& symbol) { +void SyntaxTreeSearcher::CheckSymbol(const Symbol &symbol) { BoundSymbolManager manager; if (matcher_.Matches(symbol, &manager)) { if (context_predicate_(Context())) { @@ -71,13 +71,13 @@ void SyntaxTreeSearcher::CheckSymbol(const Symbol& symbol) { } // // Checks if leaf matches critera. -void SyntaxTreeSearcher::Visit(const SyntaxTreeLeaf& leaf) { +void SyntaxTreeSearcher::Visit(const SyntaxTreeLeaf &leaf) { CheckSymbol(leaf); } // Checks if node matches criteria. // Then recursively search subtree. -void SyntaxTreeSearcher::Visit(const SyntaxTreeNode& node) { +void SyntaxTreeSearcher::Visit(const SyntaxTreeNode &node) { CheckSymbol(node); TreeContextVisitor::Visit(node); } @@ -85,17 +85,17 @@ void SyntaxTreeSearcher::Visit(const SyntaxTreeNode& node) { } // namespace std::vector SearchSyntaxTree( - const Symbol& root, const verible::matcher::Matcher& matcher, - const std::function& context_predicate) { + const Symbol &root, const verible::matcher::Matcher &matcher, + const std::function &context_predicate) { SyntaxTreeSearcher searcher(matcher, context_predicate); searcher.Search(root); return searcher.Matches(); } std::vector SearchSyntaxTree( - const Symbol& root, const verible::matcher::Matcher& matcher) { + const Symbol &root, const verible::matcher::Matcher &matcher) { return SearchSyntaxTree(root, matcher, - [](const SyntaxTreeContext&) { return true; }); + [](const SyntaxTreeContext &) { return true; }); } } // namespace verible diff --git a/common/analysis/syntax_tree_search.h b/common/analysis/syntax_tree_search.h index 20e41f0c3..658141b2e 100644 --- a/common/analysis/syntax_tree_search.h +++ b/common/analysis/syntax_tree_search.h @@ -33,7 +33,7 @@ namespace verible { struct TreeSearchMatch { // Note: The syntax tree to which the matching node belongs must outlive // this pointer. - const Symbol* match; + const Symbol *match; // A copy of the stack of syntax tree nodes that are ancestors of // the match node/leaf. Note: This is needed because syntax tree nodes // don't have upward links to parents. @@ -44,12 +44,12 @@ struct TreeSearchMatch { // vector. This is useful for analyses that need to look at a collection // of related nodes together, rather than as each one is encountered. std::vector SearchSyntaxTree( - const Symbol& root, const verible::matcher::Matcher& matcher, - const std::function& context_predicate); + const Symbol &root, const verible::matcher::Matcher &matcher, + const std::function &context_predicate); // This overload treats the missing context_predicate as always returning true. std::vector SearchSyntaxTree( - const Symbol& root, const verible::matcher::Matcher& matcher); + const Symbol &root, const verible::matcher::Matcher &matcher); } // namespace verible diff --git a/common/analysis/syntax_tree_search_test.cc b/common/analysis/syntax_tree_search_test.cc index 71704f358..b19fc52fd 100644 --- a/common/analysis/syntax_tree_search_test.cc +++ b/common/analysis/syntax_tree_search_test.cc @@ -119,7 +119,7 @@ TEST(SearchSyntaxTreeTest, RootOnlyNodeMatchFalsePredicate) { auto matcher_builder = NodeMatcher<0>(); auto matcher = matcher_builder(); auto matches = SearchSyntaxTree( - *tree, matcher, [](const SyntaxTreeContext&) { return false; }); + *tree, matcher, [](const SyntaxTreeContext &) { return false; }); EXPECT_TRUE(matches.empty()); } @@ -129,7 +129,7 @@ TEST(SearchSyntaxTreeTest, RootOnlyNodeMatchTruePredicate) { auto matcher_builder = NodeMatcher<0>(); auto matcher = matcher_builder(); auto matches = SearchSyntaxTree( - *tree, matcher, [](const SyntaxTreeContext&) { return true; }); + *tree, matcher, [](const SyntaxTreeContext &) { return true; }); EXPECT_EQ(matches.size(), 1); EXPECT_EQ(&SymbolCastToNode(*matches.front().match), tree.get()); } diff --git a/common/analysis/syntax_tree_search_test_utils.cc b/common/analysis/syntax_tree_search_test_utils.cc index 5826bdcea..448ce49b3 100644 --- a/common/analysis/syntax_tree_search_test_utils.cc +++ b/common/analysis/syntax_tree_search_test_utils.cc @@ -62,7 +62,7 @@ using StringRangeSet = std::set; // This function helps find symmetric differences between two sets // of findings (actual vs. expected) based on locations. -static int CompareFindingLocation(absl::string_view lhs, const TokenInfo& rhs) { +static int CompareFindingLocation(absl::string_view lhs, const TokenInfo &rhs) { const int delta = CompareStringRanges(lhs, rhs.text()); // Then compare enums, where we only care about equality. return delta; @@ -70,13 +70,13 @@ static int CompareFindingLocation(absl::string_view lhs, const TokenInfo& rhs) { // TODO(b/151371397): refactor this for re-use for multi-findings style tests. bool SyntaxTreeSearchTestCase::ExactMatchFindings( - const std::vector& actual_findings, absl::string_view base, - std::ostream* diffstream) const { + const std::vector &actual_findings, absl::string_view base, + std::ostream *diffstream) const { // Convert actual_findings into string ranges. Ignore matches' context. StringRangeSet actual_findings_ranges; - for (const auto& finding : actual_findings) { + for (const auto &finding : actual_findings) { if (finding.match == nullptr) continue; - const auto& match_symbol(*finding.match); + const auto &match_symbol(*finding.match); const absl::string_view spanned_text = StringSpanOfSymbol(match_symbol); // Spanned text can be empty when a subtree is devoid of leaves. if (spanned_text.empty()) continue; @@ -106,7 +106,7 @@ bool SyntaxTreeSearchTestCase::ExactMatchFindings( all_match = false; *diffstream << "The following actual findings did not match the expected ones:\n"; - for (const auto& finding : unmatched_actual_findings) { + for (const auto &finding : unmatched_actual_findings) { constexpr int kIgnored = -1; TokenInfo(kIgnored, finding).ToStream(*diffstream, context) << std::endl; } @@ -115,7 +115,7 @@ bool SyntaxTreeSearchTestCase::ExactMatchFindings( all_match = false; *diffstream << "The following expected findings did not match the ones found:\n"; - for (const auto& finding : unmatched_expected_findings) { + for (const auto &finding : unmatched_expected_findings) { finding.ToStream(*diffstream, context) << std::endl; } } diff --git a/common/analysis/syntax_tree_search_test_utils.h b/common/analysis/syntax_tree_search_test_utils.h index 6265de8fe..4132562c8 100644 --- a/common/analysis/syntax_tree_search_test_utils.h +++ b/common/analysis/syntax_tree_search_test_utils.h @@ -47,9 +47,9 @@ struct SyntaxTreeSearchTestCase : public SynthesizedLexerTestData { // Returns true if every element is an exact match to the expected set. // TODO(b/141875806): Take a symbol translator function to produce a // human-readable, language-specific enum name. - bool ExactMatchFindings(const std::vector& actual_findings, + bool ExactMatchFindings(const std::vector &actual_findings, absl::string_view base, - std::ostream* diffstream) const; + std::ostream *diffstream) const; }; } // namespace verible diff --git a/common/analysis/text_structure_lint_rule.h b/common/analysis/text_structure_lint_rule.h index be1ed3dd9..0116257f4 100644 --- a/common/analysis/text_structure_lint_rule.h +++ b/common/analysis/text_structure_lint_rule.h @@ -41,7 +41,7 @@ class TextStructureLintRule : public LintRule { ~TextStructureLintRule() override = default; // Analyze text structure for violations. - virtual void Lint(const TextStructureView& text_structure, + virtual void Lint(const TextStructureView &text_structure, absl::string_view filename) = 0; }; diff --git a/common/analysis/text_structure_linter.cc b/common/analysis/text_structure_linter.cc index baa86f4a2..4825d479f 100644 --- a/common/analysis/text_structure_linter.cc +++ b/common/analysis/text_structure_linter.cc @@ -24,11 +24,11 @@ namespace verible { -void TextStructureLinter::Lint(const TextStructureView& text_structure, +void TextStructureLinter::Lint(const TextStructureView &text_structure, absl::string_view filename) { VLOG(1) << "TextStructureLinter analyzing text with " << rules_.size() << " rules."; - for (const auto& rule : rules_) { + for (const auto &rule : rules_) { ABSL_DIE_IF_NULL(rule)->Lint(text_structure, filename); } } @@ -36,7 +36,7 @@ void TextStructureLinter::Lint(const TextStructureView& text_structure, std::vector TextStructureLinter::ReportStatus() const { std::vector status; status.reserve(rules_.size()); - for (const auto& rule : rules_) { + for (const auto &rule : rules_) { status.push_back(ABSL_DIE_IF_NULL(rule)->Report()); } return status; diff --git a/common/analysis/text_structure_linter.h b/common/analysis/text_structure_linter.h index 9fac10325..c05b8546b 100644 --- a/common/analysis/text_structure_linter.h +++ b/common/analysis/text_structure_linter.h @@ -33,7 +33,7 @@ namespace verible { class TextStructureLinter { public: // Analyzes a sequence of tokens. - void Lint(const TextStructureView&, absl::string_view); + void Lint(const TextStructureView &, absl::string_view); // Transfers ownership of rule into this Linter void AddRule(std::unique_ptr rule) { diff --git a/common/analysis/text_structure_linter_test.cc b/common/analysis/text_structure_linter_test.cc index 284df224e..a72561e19 100644 --- a/common/analysis/text_structure_linter_test.cc +++ b/common/analysis/text_structure_linter_test.cc @@ -37,9 +37,9 @@ class RequireHelloRule : public TextStructureLintRule { public: RequireHelloRule() = default; - void Lint(const TextStructureView& text_structure, + void Lint(const TextStructureView &text_structure, absl::string_view filename) final { - const auto& lines = text_structure.Lines(); + const auto &lines = text_structure.Lines(); const absl::string_view contents = text_structure.Contents(); if (!lines.empty() && !absl::StartsWith(contents, "Hello")) { const TokenInfo token(1, lines[0]); diff --git a/common/analysis/text_structure_linter_test_utils.h b/common/analysis/text_structure_linter_test_utils.h index 6a9e80df1..2fb0a4e9f 100644 --- a/common/analysis/text_structure_linter_test_utils.h +++ b/common/analysis/text_structure_linter_test_utils.h @@ -36,7 +36,7 @@ class LintRunner { linter_.AddRule(std::move(rule)); } - LintRuleStatus Run(const TextStructureView& text_structure, + LintRuleStatus Run(const TextStructureView &text_structure, absl::string_view filename) { linter_.Lint(text_structure, filename); // Looking for one type of rule violation at a time. diff --git a/common/analysis/token_stream_lint_rule.h b/common/analysis/token_stream_lint_rule.h index da326140f..381ee2dbd 100644 --- a/common/analysis/token_stream_lint_rule.h +++ b/common/analysis/token_stream_lint_rule.h @@ -29,7 +29,7 @@ class TokenStreamLintRule : public LintRule { ~TokenStreamLintRule() override = default; // Scans a single token during analysis. - virtual void HandleToken(const TokenInfo& token) = 0; + virtual void HandleToken(const TokenInfo &token) = 0; }; } // namespace verible diff --git a/common/analysis/token_stream_linter.cc b/common/analysis/token_stream_linter.cc index 4bc3528cd..02e60a4f5 100644 --- a/common/analysis/token_stream_linter.cc +++ b/common/analysis/token_stream_linter.cc @@ -23,11 +23,11 @@ namespace verible { -void TokenStreamLinter::Lint(const TokenSequence& tokens) { +void TokenStreamLinter::Lint(const TokenSequence &tokens) { VLOG(1) << "TokenStreamLinter analyzing tokens with " << rules_.size() << " rules."; - for (const auto& token : tokens) { - for (const auto& rule : rules_) { + for (const auto &token : tokens) { + for (const auto &rule : rules_) { ABSL_DIE_IF_NULL(rule)->HandleToken(token); } } @@ -36,7 +36,7 @@ void TokenStreamLinter::Lint(const TokenSequence& tokens) { std::vector TokenStreamLinter::ReportStatus() const { std::vector status; status.reserve(rules_.size()); - for (const auto& rule : rules_) { + for (const auto &rule : rules_) { status.push_back(ABSL_DIE_IF_NULL(rule)->Report()); } return status; diff --git a/common/analysis/token_stream_linter.h b/common/analysis/token_stream_linter.h index 629a32f31..08e1ac163 100644 --- a/common/analysis/token_stream_linter.h +++ b/common/analysis/token_stream_linter.h @@ -32,7 +32,7 @@ namespace verible { class TokenStreamLinter { public: // Analyzes a sequence of tokens. - void Lint(const TokenSequence& tokens); + void Lint(const TokenSequence &tokens); // Transfers ownership of rule into this Linter void AddRule(std::unique_ptr rule) { diff --git a/common/analysis/token_stream_linter_test.cc b/common/analysis/token_stream_linter_test.cc index b3d80471b..efd4a59d6 100644 --- a/common/analysis/token_stream_linter_test.cc +++ b/common/analysis/token_stream_linter_test.cc @@ -36,7 +36,7 @@ class ForbidTokenRule : public TokenStreamLintRule { public: explicit ForbidTokenRule(int n) : target_(n) {} - void HandleToken(const TokenInfo& token) final { + void HandleToken(const TokenInfo &token) final { if (token.token_enum() == target_) { violations_.insert(LintViolation(token, "some reason")); } diff --git a/common/analysis/token_stream_linter_test_utils.h b/common/analysis/token_stream_linter_test_utils.h index 0b400bb32..34944ee8b 100644 --- a/common/analysis/token_stream_linter_test_utils.h +++ b/common/analysis/token_stream_linter_test_utils.h @@ -36,7 +36,7 @@ class LintRunner { linter_.AddRule(std::move(rule)); } - LintRuleStatus Run(const TextStructureView& text_structure, + LintRuleStatus Run(const TextStructureView &text_structure, absl::string_view) { linter_.Lint(text_structure.TokenStream()); // Looking for one type of rule violation at a time. diff --git a/common/formatting/align.h b/common/formatting/align.h index 337203ff1..b41d2b1dd 100644 --- a/common/formatting/align.h +++ b/common/formatting/align.h @@ -69,7 +69,7 @@ struct ColumnPositionEntry { using ColumnPositionTree = VectorTree; -std::ostream& operator<<(std::ostream&, const ColumnPositionTree&); +std::ostream &operator<<(std::ostream &, const ColumnPositionTree &); // ColumnSchemaScanner traverses syntax subtrees of similar types and // collects the positions that wish to register columns for alignment @@ -84,12 +84,12 @@ class ColumnSchemaScanner : public TreeContextPathVisitor { : sparse_columns_(ColumnPositionTree({{}, TokenInfo::EOFToken(), {}})) {} // Returns the collection of column position entries. - const ColumnPositionTree& SparseColumns() const { return sparse_columns_; } + const ColumnPositionTree &SparseColumns() const { return sparse_columns_; } protected: // Returns subpath relative to base_path static SyntaxTreePath GetSubpath( - const SyntaxTreePath& base_path, + const SyntaxTreePath &base_path, std::initializer_list subpositions) { auto subpath = base_path; subpath.insert(subpath.end(), subpositions); @@ -103,25 +103,25 @@ class ColumnSchemaScanner : public TreeContextPathVisitor { // 'path' represents relative position within the enclosing syntax subtree, // and is used as a key for ordering and matching columns. // Returns pointer to a created column or nullptr if column was not created. - static ColumnPositionTree* ReserveNewColumn( - ColumnPositionTree* parent_column, const Symbol& symbol, - const AlignmentColumnProperties& properties, const SyntaxTreePath& path); - ColumnPositionTree* ReserveNewColumn( - const Symbol& symbol, const AlignmentColumnProperties& properties, - const SyntaxTreePath& path) { + static ColumnPositionTree *ReserveNewColumn( + ColumnPositionTree *parent_column, const Symbol &symbol, + const AlignmentColumnProperties &properties, const SyntaxTreePath &path); + ColumnPositionTree *ReserveNewColumn( + const Symbol &symbol, const AlignmentColumnProperties &properties, + const SyntaxTreePath &path) { return ReserveNewColumn(&sparse_columns_, symbol, properties, path); } // Reserve a column using the current path as the key. - ColumnPositionTree* ReserveNewColumn( - const Symbol& symbol, const AlignmentColumnProperties& properties) { + ColumnPositionTree *ReserveNewColumn( + const Symbol &symbol, const AlignmentColumnProperties &properties) { return ReserveNewColumn(&sparse_columns_, symbol, properties, Path()); } // Reserve a subcolumn using subcolumn number appended to the parent's path // as the key. - static ColumnPositionTree* ReserveNewColumn( - ColumnPositionTree* parent_column, const Symbol& symbol, - const AlignmentColumnProperties& properties) { + static ColumnPositionTree *ReserveNewColumn( + ColumnPositionTree *parent_column, const Symbol &symbol, + const AlignmentColumnProperties &properties) { CHECK_NOTNULL(parent_column); const SyntaxTreePath::value_type subindex = parent_column->Children().size(); @@ -178,7 +178,7 @@ struct TaggedTokenPartitionRange { // of group to align (same syntax). std::vector GetSubpartitionsBetweenBlankLinesSingleTag( - const TokenPartitionRange& full_range, int subtype); + const TokenPartitionRange &full_range, int subtype); // From a range of token 'partitions', this selects sub-ranges to align. // 'partition_selector' decides which partitions qualify for alignment. @@ -216,15 +216,15 @@ GetSubpartitionsBetweenBlankLinesSingleTag( // match (B) // continue group // std::vector GetPartitionAlignmentSubranges( - const TokenPartitionRange& partitions, + const TokenPartitionRange &partitions, const std::function& partition_selector, + const TokenPartitionTree &)> &partition_selector, int min_match_count = 2); // This is the interface used to extract alignment cells from ranges of tokens. // Note that it is not required to use a ColumnSchemaScanner. using AlignmentCellScannerFunction = - std::function; + std::function; // For sections of code that are deemed alignable, this enum controls // the formatter behavior. @@ -243,19 +243,19 @@ enum class AlignmentPolicy { kInferUserIntent, }; -std::ostream& operator<<(std::ostream&, AlignmentPolicy); +std::ostream &operator<<(std::ostream &, AlignmentPolicy); -bool AbslParseFlag(absl::string_view text, AlignmentPolicy* policy, - std::string* error); +bool AbslParseFlag(absl::string_view text, AlignmentPolicy *policy, + std::string *error); -std::string AbslUnparseFlag(const AlignmentPolicy& policy); +std::string AbslUnparseFlag(const AlignmentPolicy &policy); // This represents one unit of alignable work, which is usually a filtered // subset of partitions within a contiguous range of partitions. class AlignablePartitionGroup { public: - AlignablePartitionGroup(const std::vector& rows, - const AlignmentCellScannerFunction& scanner, + AlignablePartitionGroup(const std::vector &rows, + const AlignmentCellScannerFunction &scanner, AlignmentPolicy policy) : alignable_rows_(rows), alignment_cell_scanner_(scanner), @@ -274,10 +274,10 @@ class AlignablePartitionGroup { private: struct GroupAlignmentData; static GroupAlignmentData 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); - void ApplyAlignment(const GroupAlignmentData& align_data) const; + void ApplyAlignment(const GroupAlignmentData &align_data) const; private: // The set of partitions to treat as rows for tabular alignment. @@ -295,18 +295,18 @@ class AlignablePartitionGroup { // a sequence of sub-ranges for the purposes of formatting aligned groups. using ExtractAlignmentGroupsFunction = std::function( - const TokenPartitionRange&)>; + const TokenPartitionRange &)>; // This predicate function is used to select partitions to be ignored within // an alignment group. For example, one may wish to ignore comment-only lines. using IgnoreAlignmentRowPredicate = - std::function; + std::function; // Select subset of iterators inside a partition range that are not ignored // by the predicate. std::vector FilterAlignablePartitions( - const TokenPartitionRange& range, - const IgnoreAlignmentRowPredicate& ignore_partition_predicate); + const TokenPartitionRange &range, + const IgnoreAlignmentRowPredicate &ignore_partition_predicate); // This adapter composes several functions for alignment (legacy interface) into // one used in the current interface. This exists to help migrate existing code @@ -318,9 +318,9 @@ std::vector FilterAlignablePartitions( // TabularAlignTokens(). 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); // Instantiates a ScannerType (implements ColumnSchemaScanner) and extracts @@ -331,26 +331,26 @@ ExtractAlignmentGroupsFunction ExtractAlignmentGroupsAdapter( // for alignment purposes. template ColumnPositionTree ScanPartitionForAlignmentCells( - const TokenPartitionTree& row, - const std::function& scanner_factory) { - const UnwrappedLine& unwrapped_line = row.Value(); + const TokenPartitionTree &row, + const std::function &scanner_factory) { + const UnwrappedLine &unwrapped_line = row.Value(); // Walk the original syntax tree that spans a subset of the tokens spanned by // this 'row', and detect the sparse set of columns found by the scanner. ScannerType scanner = scanner_factory(); - const Symbol* origin = unwrapped_line.Origin(); + const Symbol *origin = unwrapped_line.Origin(); if (origin != nullptr) origin->Accept(&scanner); return scanner.SparseColumns(); } template ColumnPositionTree ScanPartitionForAlignmentCells( - const TokenPartitionTree& row) { + const TokenPartitionTree &row) { return ScanPartitionForAlignmentCells( row, [] { return ScannerType(); }); } using NonTreeTokensScannerFunction = std::function; + FormatTokenRange, FormatTokenRange, ColumnPositionTree *)>; // Similarly to the function above this function creates an instance of // ScannerType and extracts column alignment information. Firstly it reuses @@ -367,27 +367,27 @@ using NonTreeTokensScannerFunction = std::function ColumnPositionTree ScanPartitionForAlignmentCells_WithNonTreeTokens( - const TokenPartitionTree& row, - const std::function& scanner_factory, - const NonTreeTokensScannerFunction& non_tree_column_scanner) { + const TokenPartitionTree &row, + const std::function &scanner_factory, + const NonTreeTokensScannerFunction &non_tree_column_scanner) { // re-use existing scanner ColumnPositionTree column_entries = ScanPartitionForAlignmentCells(row, scanner_factory); - const UnwrappedLine& unwrapped_line = row.Value(); + const UnwrappedLine &unwrapped_line = row.Value(); const auto ftokens = unwrapped_line.TokensRange(); - const Symbol* origin = unwrapped_line.Origin(); + const Symbol *origin = unwrapped_line.Origin(); FormatTokenRange leading_tokens(ftokens.begin(), ftokens.begin()); FormatTokenRange trailing_tokens(ftokens.end(), ftokens.end()); if (origin != nullptr) { // Identify the last token covered by the origin tree. - const SyntaxTreeLeaf* first_leaf = GetLeftmostLeaf(*origin); - const SyntaxTreeLeaf* last_leaf = GetRightmostLeaf(*origin); + const SyntaxTreeLeaf *first_leaf = GetLeftmostLeaf(*origin); + const SyntaxTreeLeaf *last_leaf = GetRightmostLeaf(*origin); CHECK_NOTNULL(first_leaf); CHECK_NOTNULL(last_leaf); - const TokenInfo& first_tree_token = first_leaf->get(); - const TokenInfo& last_tree_token = last_leaf->get(); + const TokenInfo &first_tree_token = first_leaf->get(); + const TokenInfo &last_tree_token = last_leaf->get(); // Collect tokens excluded from SyntaxTree (delimiters and comments) CHECK(!ftokens.empty()); @@ -430,8 +430,8 @@ ColumnPositionTree ScanPartitionForAlignmentCells_WithNonTreeTokens( template ColumnPositionTree ScanPartitionForAlignmentCells_WithNonTreeTokens( - const TokenPartitionTree& row, - const NonTreeTokensScannerFunction& non_tree_column_scanner) { + const TokenPartitionTree &row, + const NonTreeTokensScannerFunction &non_tree_column_scanner) { return ScanPartitionForAlignmentCells_WithNonTreeTokens( row, [] { return ScannerType(); }, non_tree_column_scanner); } @@ -450,15 +450,15 @@ ColumnPositionTree ScanPartitionForAlignmentCells_WithNonTreeTokens( // }; template AlignmentCellScannerFunction AlignmentCellScannerGenerator() { - return [](const TokenPartitionTree& row) { + return [](const TokenPartitionTree &row) { return ScanPartitionForAlignmentCells(row); }; } template AlignmentCellScannerFunction AlignmentCellScannerGenerator( - const std::function& scanner_factory) { - return [scanner_factory](const TokenPartitionTree& row) { + const std::function &scanner_factory) { + return [scanner_factory](const TokenPartitionTree &row) { return ScanPartitionForAlignmentCells(row, scanner_factory); }; } @@ -468,8 +468,8 @@ AlignmentCellScannerFunction AlignmentCellScannerGenerator( // comments. template AlignmentCellScannerFunction AlignmentCellScannerGenerator( - const NonTreeTokensScannerFunction& non_tree_column_scanner) { - return [non_tree_column_scanner](const TokenPartitionTree& row) { + const NonTreeTokensScannerFunction &non_tree_column_scanner) { + return [non_tree_column_scanner](const TokenPartitionTree &row) { return ScanPartitionForAlignmentCells_WithNonTreeTokens( row, non_tree_column_scanner); }; @@ -478,9 +478,9 @@ AlignmentCellScannerFunction AlignmentCellScannerGenerator( template AlignmentCellScannerFunction AlignmentCellScannerGenerator( const std::function scanner_factory, - const NonTreeTokensScannerFunction& non_tree_column_scanner) { + const NonTreeTokensScannerFunction &non_tree_column_scanner) { return [scanner_factory, - non_tree_column_scanner](const TokenPartitionTree& row) { + non_tree_column_scanner](const TokenPartitionTree &row) { return ScanPartitionForAlignmentCells_WithNonTreeTokens( row, scanner_factory, non_tree_column_scanner); }; @@ -534,9 +534,9 @@ void FormatUsingOriginalSpacing(TokenPartitionRange partition_range); // 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); } // namespace verible diff --git a/common/formatting/basic_format_style.cc b/common/formatting/basic_format_style.cc index b5ae714d9..645e814d3 100644 --- a/common/formatting/basic_format_style.cc +++ b/common/formatting/basic_format_style.cc @@ -24,7 +24,7 @@ namespace verible { // This mapping defines how this enum is displayed and parsed. -static const verible::EnumNameMap& IndentationStyleStrings() { +static const verible::EnumNameMap &IndentationStyleStrings() { static const verible::EnumNameMap kIndentationStyleStringMap({ {"indent", IndentationStyle::kIndent}, @@ -33,16 +33,16 @@ static const verible::EnumNameMap& IndentationStyleStrings() { return kIndentationStyleStringMap; } -std::ostream& operator<<(std::ostream& stream, IndentationStyle p) { +std::ostream &operator<<(std::ostream &stream, IndentationStyle p) { return IndentationStyleStrings().Unparse(p, stream); } -bool AbslParseFlag(absl::string_view text, IndentationStyle* mode, - std::string* error) { +bool AbslParseFlag(absl::string_view text, IndentationStyle *mode, + std::string *error) { return IndentationStyleStrings().Parse(text, mode, error, "IndentationStyle"); } -std::string AbslUnparseFlag(const IndentationStyle& mode) { +std::string AbslUnparseFlag(const IndentationStyle &mode) { std::ostringstream stream; stream << mode; return stream.str(); diff --git a/common/formatting/basic_format_style.h b/common/formatting/basic_format_style.h index 1e77b1dd1..2812122c4 100644 --- a/common/formatting/basic_format_style.h +++ b/common/formatting/basic_format_style.h @@ -58,11 +58,11 @@ enum class IndentationStyle { kWrap, }; -std::ostream& operator<<(std::ostream&, IndentationStyle); +std::ostream &operator<<(std::ostream &, IndentationStyle); -bool AbslParseFlag(absl::string_view, IndentationStyle*, std::string*); +bool AbslParseFlag(absl::string_view, IndentationStyle *, std::string *); -std::string AbslUnparseFlag(const IndentationStyle&); +std::string AbslUnparseFlag(const IndentationStyle &); } // namespace verible diff --git a/common/formatting/format_token.cc b/common/formatting/format_token.cc index d77865923..915623b8f 100644 --- a/common/formatting/format_token.cc +++ b/common/formatting/format_token.cc @@ -29,7 +29,7 @@ namespace verible { -std::ostream& operator<<(std::ostream& stream, SpacingOptions b) { +std::ostream &operator<<(std::ostream &stream, SpacingOptions b) { switch (b) { case SpacingOptions::kUndecided: stream << "undecided"; @@ -50,7 +50,7 @@ std::ostream& operator<<(std::ostream& stream, SpacingOptions b) { return stream; } -std::ostream& operator<<(std::ostream& stream, GroupBalancing b) { +std::ostream &operator<<(std::ostream &stream, GroupBalancing b) { switch (b) { case GroupBalancing::kNone: stream << "none"; @@ -65,7 +65,7 @@ std::ostream& operator<<(std::ostream& stream, GroupBalancing b) { return stream; } -std::ostream& operator<<(std::ostream& stream, const InterTokenInfo& t) { +std::ostream &operator<<(std::ostream &stream, const InterTokenInfo &t) { stream << "{\n spaces_required: " << t.spaces_required << "\n break_penalty: " << t.break_penalty << "\n break_decision: " << t.break_decision @@ -74,7 +74,7 @@ std::ostream& operator<<(std::ostream& stream, const InterTokenInfo& t) { return stream; } -std::ostream& InterTokenInfo::CompactNotation(std::ostream& stream) const { +std::ostream &InterTokenInfo::CompactNotation(std::ostream &stream) const { stream << '<'; // break_penalty is irrelevant when the options are constrained, // so don't bother showing it in those cases. @@ -99,7 +99,7 @@ std::ostream& InterTokenInfo::CompactNotation(std::ostream& stream) const { return stream << '>'; } -std::ostream& operator<<(std::ostream& stream, SpacingDecision d) { +std::ostream &operator<<(std::ostream &stream, SpacingDecision d) { switch (d) { case SpacingDecision::kAppend: stream << "append"; @@ -130,13 +130,13 @@ static SpacingDecision ConvertSpacing(SpacingOptions opt) { } } -InterTokenDecision::InterTokenDecision(const InterTokenInfo& info) +InterTokenDecision::InterTokenDecision(const InterTokenInfo &info) : spaces(info.spaces_required), action(ConvertSpacing(info.break_decision)), preserved_space_start(info.preserved_space_start) {} -static absl::string_view OriginalLeadingSpacesRange(const char* begin, - const char* end) { +static absl::string_view OriginalLeadingSpacesRange(const char *begin, + const char *end) { if (begin == nullptr) { VLOG(4) << "no original space range"; return make_string_view_range(end, end); // empty range @@ -152,7 +152,7 @@ absl::string_view FormattedToken::OriginalLeadingSpaces() const { token->text().begin()); } -std::ostream& FormattedToken::FormattedText(std::ostream& stream) const { +std::ostream &FormattedToken::FormattedText(std::ostream &stream) const { switch (before.action) { case SpacingDecision::kPreserve: { if (before.preserved_space_start != nullptr) { @@ -177,7 +177,7 @@ std::ostream& FormattedToken::FormattedText(std::ostream& stream) const { return stream << token->text(); } -std::ostream& operator<<(std::ostream& stream, const FormattedToken& token) { +std::ostream &operator<<(std::ostream &stream, const FormattedToken &token) { return token.FormattedText(stream); } @@ -212,7 +212,7 @@ std::string PreFormatToken::ToString() const { } // Human readable token information -std::ostream& operator<<(std::ostream& stream, const PreFormatToken& t) { +std::ostream &operator<<(std::ostream &stream, const PreFormatToken &t) { // don't care about byte offsets return t.token->ToStream(stream << "TokenInfo: ") << "\nenum: " << t.format_token_enum << "\nbefore: " << t.before @@ -220,10 +220,10 @@ std::ostream& operator<<(std::ostream& stream, const PreFormatToken& t) { } void ConnectPreFormatTokensPreservedSpaceStarts( - const char* buffer_start, std::vector* format_tokens) { + const char *buffer_start, std::vector *format_tokens) { VLOG(4) << __FUNCTION__; CHECK(buffer_start != nullptr); - for (auto& ftoken : *format_tokens) { + for (auto &ftoken : *format_tokens) { ftoken.before.preserved_space_start = buffer_start; VLOG(4) << "space: " << VisualizeWhitespace(ftoken.OriginalLeadingSpaces()); buffer_start = ftoken.Text().end(); @@ -236,28 +236,28 @@ void ConnectPreFormatTokensPreservedSpaceStarts( static MutableFormatTokenRange FindFormatTokensInByteOffsetRange( std::vector::iterator begin, std::vector::iterator end, - const std::pair& byte_offset_range, absl::string_view base_text) { + const std::pair &byte_offset_range, absl::string_view base_text) { const auto tokens_begin = std::lower_bound(begin, end, byte_offset_range.first, - [=](const PreFormatToken& t, int position) { + [=](const PreFormatToken &t, int position) { return t.token->left(base_text) < position; }); const auto tokens_end = std::upper_bound(tokens_begin, end, byte_offset_range.second, - [=](int position, const PreFormatToken& t) { + [=](int position, const PreFormatToken &t) { return position < t.token->right(base_text); }); return {tokens_begin, tokens_end}; } void PreserveSpacesOnDisabledTokenRanges( - std::vector* ftokens, - const ByteOffsetSet& disabled_byte_ranges, absl::string_view base_text) { + std::vector *ftokens, + const ByteOffsetSet &disabled_byte_ranges, absl::string_view base_text) { VLOG(2) << __FUNCTION__; // saved_iter: shrink bounds of binary search with every iteration, // due to monotonic, non-overlapping intervals. auto saved_iter = ftokens->begin(); - for (const auto& byte_range : disabled_byte_ranges) { + for (const auto &byte_range : disabled_byte_ranges) { // 'disable_range' marks the range of format tokens to be // marked as preserving original spacing (i.e. not formatted). VLOG(2) << "disabling bytes: " << AsInterval(byte_range); @@ -274,7 +274,7 @@ void PreserveSpacesOnDisabledTokenRanges( // token's text. This way, rendering the start of the format-disabled // excerpt won't get redundant '\n's. if (!disable_range.empty()) { - auto& first = disable_range.front(); + auto &first = disable_range.front(); VLOG(3) << "checking whether first ftoken in range is a must-wrap."; if (first.before.break_decision == SpacingOptions::kMustWrap) { VLOG(3) << "checking if spaces before first ftoken starts with \\n."; @@ -288,7 +288,7 @@ void PreserveSpacesOnDisabledTokenRanges( } // Mark tokens in the disabled range as preserving original spaces. - for (auto& ft : disable_range) { + for (auto &ft : disable_range) { VLOG(2) << "disable-format preserve spaces before: " << *ft.token; ft.before.break_decision = SpacingOptions::kPreserve; } diff --git a/common/formatting/format_token.h b/common/formatting/format_token.h index 109e7093b..d62b9c58b 100644 --- a/common/formatting/format_token.h +++ b/common/formatting/format_token.h @@ -39,7 +39,7 @@ enum class SpacingOptions { kPreserve, // do not optimize, use original spacing }; -std::ostream& operator<<(std::ostream&, SpacingOptions); +std::ostream &operator<<(std::ostream &, SpacingOptions); // Tri-state value that encodes how this token affects group balancing // for line-wrapping purposes. @@ -50,7 +50,7 @@ enum class GroupBalancing { // TODO(fangism): Reset? (separator) }; -std::ostream& operator<<(std::ostream&, GroupBalancing); +std::ostream &operator<<(std::ostream &, GroupBalancing); // InterTokenInfo defines parameters that are important to formatting // decisions related to adjacent tokens. @@ -76,27 +76,27 @@ struct InterTokenInfo { // tokens, for the sake of preserving space. // Together with the current token, they can form a string_view representing // pre-existing space from the original buffer. - const char* preserved_space_start = nullptr; + const char *preserved_space_start = nullptr; InterTokenInfo() = default; - InterTokenInfo(const InterTokenInfo&) = default; + InterTokenInfo(const InterTokenInfo &) = default; // Comparison is only really used for testing. - bool operator==(const InterTokenInfo& r) const { + bool operator==(const InterTokenInfo &r) const { return spaces_required == r.spaces_required && break_penalty == r.break_penalty && break_decision == r.break_decision && preserved_space_start == r.preserved_space_start; } - bool operator!=(const InterTokenInfo& r) const { return !((*this) == r); } + bool operator!=(const InterTokenInfo &r) const { return !((*this) == r); } // For debug printing. - std::ostream& CompactNotation(std::ostream&) const; + std::ostream &CompactNotation(std::ostream &) const; }; // Human-readable form, for debugging. -std::ostream& operator<<(std::ostream&, const InterTokenInfo&); +std::ostream &operator<<(std::ostream &, const InterTokenInfo &); // PreFormatToken is a wrapper for TokenInfo objects. It contains an original // pointer to a TokenInfo object, as well as additional information for @@ -104,7 +104,7 @@ std::ostream& operator<<(std::ostream&, const InterTokenInfo&); // inter-token annotations. struct PreFormatToken { // The token this PreFormatToken holds. TokenInfo must outlive this object. - const TokenInfo* token = nullptr; + const TokenInfo *token = nullptr; // The enum for this PreFormatToken, an abstraction from the TokenInfo enum // for decision making. The values are intended to come from language-specific @@ -120,9 +120,9 @@ struct PreFormatToken { PreFormatToken() = default; - explicit PreFormatToken(const TokenInfo* t) : token(t) {} + explicit PreFormatToken(const TokenInfo *t) : token(t) {} - explicit PreFormatToken(const verible::SyntaxTreeLeaf& leaf) + explicit PreFormatToken(const verible::SyntaxTreeLeaf &leaf) : PreFormatToken(&leaf.get()) {} // The length of characters in the PreFormatToken @@ -151,15 +151,15 @@ struct PreFormatToken { std::string ToString() const; }; -std::ostream& operator<<(std::ostream& stream, const PreFormatToken& token); +std::ostream &operator<<(std::ostream &stream, const PreFormatToken &token); // Sets pointers that establish substring ranges of (whitespace) text *between* // non-whitespace tokens. This allows for reconstruction and analysis of // inter-token (space) text. // Note that this does not cover the space between the last token and EOF. void ConnectPreFormatTokensPreservedSpaceStarts( - const char* buffer_start, - std::vector* format_tokens); + const char *buffer_start, + std::vector *format_tokens); // Marks formatting-disabled ranges of tokens so that their original spacing is // preserved. 'ftokens' is the array of PreFormatTokens to potentially mark. @@ -167,8 +167,8 @@ void ConnectPreFormatTokensPreservedSpaceStarts( // 'base_text' is the string_view of the whole text being formatted, and serves // as the base reference for 'disabled_byte_ranges' offsets. void PreserveSpacesOnDisabledTokenRanges( - std::vector* ftokens, - const ByteOffsetSet& disabled_byte_ranges, absl::string_view base_text); + std::vector *ftokens, + const ByteOffsetSet &disabled_byte_ranges, absl::string_view base_text); using FormatTokenRange = container_iterator_range::const_iterator>; @@ -187,7 +187,7 @@ enum class SpacingDecision { // front of line. }; -std::ostream& operator<<(std::ostream& stream, SpacingDecision); +std::ostream &operator<<(std::ostream &stream, SpacingDecision); // Set of bound parameters for formatting around this token. // The fields here are related to InterTokenInfo. @@ -199,11 +199,11 @@ struct InterTokenDecision { SpacingDecision action = SpacingDecision::kPreserve; // When preserving spaces before this token, start from this offset. - const char* preserved_space_start = nullptr; + const char *preserved_space_start = nullptr; InterTokenDecision() = default; - explicit InterTokenDecision(const InterTokenInfo&); + explicit InterTokenDecision(const InterTokenInfo &); }; // FormattedToken represents re-formatted text, whose spacing/line-break @@ -214,23 +214,23 @@ struct FormattedToken { // Don't care what spacing decision is at this time, it will be populated // when reconstructing formatting decisions from StateNode. - explicit FormattedToken(const PreFormatToken& ftoken) + explicit FormattedToken(const PreFormatToken &ftoken) : token(ftoken.token), before(ftoken.before) {} // Reconstructs the original spacing that preceded this token. absl::string_view OriginalLeadingSpaces() const; // Print out formatted result after formatting decision optimization. - std::ostream& FormattedText(std::ostream&) const; + std::ostream &FormattedText(std::ostream &) const; // The token this PreFormatToken holds. TokenInfo must outlive this object. - const TokenInfo* token = nullptr; + const TokenInfo *token = nullptr; // Decision about what spaces to apply before printing this token. InterTokenDecision before; }; -std::ostream& operator<<(std::ostream& stream, const FormattedToken& token); +std::ostream &operator<<(std::ostream &stream, const FormattedToken &token); } // namespace verible diff --git a/common/formatting/format_token_test.cc b/common/formatting/format_token_test.cc index 7692d144a..4e2cab7f2 100644 --- a/common/formatting/format_token_test.cc +++ b/common/formatting/format_token_test.cc @@ -273,7 +273,7 @@ TEST_F(PreserveSpacesOnDisabledTokenRangesTest, DisableNone) { ByteOffsetSet disabled_bytes; // empty PreserveSpacesOnDisabledTokenRanges(&pre_format_tokens_, disabled_bytes, text); - for (const auto& ftoken : pre_format_tokens_) { + for (const auto &ftoken : pre_format_tokens_) { EXPECT_EQ(ftoken.before.break_decision, SpacingOptions::kUndecided); } } @@ -290,7 +290,7 @@ TEST_F(PreserveSpacesOnDisabledTokenRangesTest, DisableSpaceBeforeText) { ByteOffsetSet disabled_bytes{{5, 7}}; // substring " d" PreserveSpacesOnDisabledTokenRanges(&pre_format_tokens_, disabled_bytes, text); - const auto& ftokens = pre_format_tokens_; + const auto &ftokens = pre_format_tokens_; EXPECT_EQ(ftokens[0].before.break_decision, SpacingOptions::kUndecided); EXPECT_EQ(ftokens[1].before.break_decision, SpacingOptions::kUndecided); EXPECT_EQ(ftokens[2].before.break_decision, SpacingOptions::kUndecided); @@ -311,7 +311,7 @@ TEST_F(PreserveSpacesOnDisabledTokenRangesTest, DisableSpaceAfterText) { ByteOffsetSet disabled_bytes{{4, 6}}; // substring "c " PreserveSpacesOnDisabledTokenRanges(&pre_format_tokens_, disabled_bytes, text); - const auto& ftokens = pre_format_tokens_; + const auto &ftokens = pre_format_tokens_; EXPECT_EQ(ftokens[0].before.break_decision, SpacingOptions::kUndecided); EXPECT_EQ(ftokens[1].before.break_decision, SpacingOptions::kUndecided); EXPECT_EQ(ftokens[2].before.break_decision, @@ -332,7 +332,7 @@ TEST_F(PreserveSpacesOnDisabledTokenRangesTest, DisableSpanningTwoTokens) { ByteOffsetSet disabled_bytes{{4, 7}}; // substring "c d" PreserveSpacesOnDisabledTokenRanges(&pre_format_tokens_, disabled_bytes, text); - const auto& ftokens = pre_format_tokens_; + const auto &ftokens = pre_format_tokens_; EXPECT_EQ(ftokens[0].before.break_decision, SpacingOptions::kUndecided); EXPECT_EQ(ftokens[1].before.break_decision, SpacingOptions::kUndecided); EXPECT_EQ(ftokens[2].before.break_decision, @@ -355,7 +355,7 @@ TEST_F(PreserveSpacesOnDisabledTokenRangesTest, DisableSpanningMustWrap) { pre_format_tokens_[2].before.break_decision = SpacingOptions::kMustWrap; PreserveSpacesOnDisabledTokenRanges(&pre_format_tokens_, disabled_bytes, text); - const auto& ftokens = pre_format_tokens_; + const auto &ftokens = pre_format_tokens_; EXPECT_EQ(ftokens[0].before.break_decision, SpacingOptions::kUndecided); EXPECT_TRUE( BoundsEqual(ftokens[0].OriginalLeadingSpaces(), text.substr(0, 0))); @@ -388,8 +388,8 @@ TEST_F(PreserveSpacesOnDisabledTokenRangesTest, pre_format_tokens_[1].before.break_decision = SpacingOptions::kMustWrap; PreserveSpacesOnDisabledTokenRanges(&pre_format_tokens_, disabled_bytes, text); - const auto& ftokens = pre_format_tokens_; - auto indices = [&text](const absl::string_view& range) { + const auto &ftokens = pre_format_tokens_; + auto indices = [&text](const absl::string_view &range) { return SubRangeIndices(range, text); }; EXPECT_EQ(ftokens[0].before.break_decision, SpacingOptions::kUndecided); @@ -424,8 +424,8 @@ TEST_F(PreserveSpacesOnDisabledTokenRangesTest, pre_format_tokens_[1].before.break_decision = SpacingOptions::kMustWrap; PreserveSpacesOnDisabledTokenRanges(&pre_format_tokens_, disabled_bytes, text); - const auto& ftokens = pre_format_tokens_; - auto indices = [&text](const absl::string_view& range) { + const auto &ftokens = pre_format_tokens_; + auto indices = [&text](const absl::string_view &range) { return SubRangeIndices(range, text); }; EXPECT_EQ(ftokens[0].before.break_decision, SpacingOptions::kUndecided); @@ -461,8 +461,8 @@ TEST_F(PreserveSpacesOnDisabledTokenRangesTest, MultipleOffsetRanges) { pre_format_tokens_[1].before.break_decision = SpacingOptions::kMustWrap; PreserveSpacesOnDisabledTokenRanges(&pre_format_tokens_, disabled_bytes, text); - const auto& ftokens = pre_format_tokens_; - auto indices = [&text](const absl::string_view& range) { + const auto &ftokens = pre_format_tokens_; + auto indices = [&text](const absl::string_view &range) { return SubRangeIndices(range, text); }; EXPECT_EQ(ftokens[0].before.break_decision, SpacingOptions::kUndecided); diff --git a/common/formatting/layout_optimizer.h b/common/formatting/layout_optimizer.h index 10b898c03..dc84eadda 100644 --- a/common/formatting/layout_optimizer.h +++ b/common/formatting/layout_optimizer.h @@ -37,8 +37,8 @@ namespace verible { // Handles formatting of `node` using LayoutOptimizer. -void OptimizeTokenPartitionTree(const BasicFormatStyle& style, - TokenPartitionTree* node); +void OptimizeTokenPartitionTree(const BasicFormatStyle &style, + TokenPartitionTree *node); } // namespace verible diff --git a/common/formatting/layout_optimizer_internal.h b/common/formatting/layout_optimizer_internal.h index b3c752484..9873bbcdd 100644 --- a/common/formatting/layout_optimizer_internal.h +++ b/common/formatting/layout_optimizer_internal.h @@ -47,7 +47,7 @@ enum class LayoutType { kStack, }; -std::ostream& operator<<(std::ostream& stream, LayoutType type); +std::ostream &operator<<(std::ostream &stream, LayoutType type); // LayoutTree node data class LayoutItem { @@ -65,7 +65,7 @@ class LayoutItem { } // Creates Line item from UnwrappedLine. - explicit LayoutItem(const UnwrappedLine& uwline, int indentation = 0) + explicit LayoutItem(const UnwrappedLine &uwline, int indentation = 0) : type_(LayoutType::kLine), indentation_(indentation), tokens_(uwline.TokensRange()), @@ -76,7 +76,7 @@ class LayoutItem { } // Creates Line item from UnwrappedLine. - explicit LayoutItem(const UnwrappedLine& uwline, bool must_wrap, + explicit LayoutItem(const UnwrappedLine &uwline, bool must_wrap, int indentation) : type_(LayoutType::kLine), indentation_(indentation), @@ -89,11 +89,11 @@ class LayoutItem { // Multiple LayoutFunctionSegments can store copies of the same layout. // The objects are copied mostly in LayoutFunctionFactory::* functions. - LayoutItem(const LayoutItem&) = default; - LayoutItem& operator=(const LayoutItem&) = default; + LayoutItem(const LayoutItem &) = default; + LayoutItem &operator=(const LayoutItem &) = default; - LayoutItem(LayoutItem&&) = default; - LayoutItem& operator=(LayoutItem&&) = default; + LayoutItem(LayoutItem &&) = default; + LayoutItem &operator=(LayoutItem &&) = default; LayoutType Type() const { return type_; } @@ -120,7 +120,7 @@ class LayoutItem { // string for other item types. std::string Text() const { return absl::StrJoin(tokens_, " ", - [](std::string* out, const PreFormatToken& token) { + [](std::string *out, const PreFormatToken &token) { absl::StrAppend(out, token.Text()); }); } @@ -132,7 +132,7 @@ class LayoutItem { if (tokens_.empty()) return 0; int len = 0; - for (const auto& token : tokens_) { + for (const auto &token : tokens_) { // TODO (mglb): support all possible break_decisions len += token.before.spaces_required; if (const auto line_break_pos = token.Text().find('\n'); @@ -157,7 +157,7 @@ class LayoutItem { return tokens_; } - friend bool operator==(const LayoutItem& lhs, const LayoutItem& rhs) { + friend bool operator==(const LayoutItem &lhs, const LayoutItem &rhs) { return (lhs.type_ == rhs.type_ && lhs.indentation_ == rhs.indentation_ && lhs.tokens_ == rhs.tokens_ && lhs.spaces_before_ == rhs.spaces_before_ && @@ -165,7 +165,7 @@ class LayoutItem { } private: - static bool UnwrappedLineMustWrap(const UnwrappedLine& uwline) { + static bool UnwrappedLineMustWrap(const UnwrappedLine &uwline) { if (uwline.TokensRange().empty()) return false; const auto policy = uwline.PartitionPolicy(); @@ -176,7 +176,7 @@ class LayoutItem { return (break_decision == SpacingOptions::kMustWrap); } - static int SpacesRequiredBeforeUnwrappedLine(const UnwrappedLine& uwline) { + static int SpacesRequiredBeforeUnwrappedLine(const UnwrappedLine &uwline) { const auto tokens = uwline.TokensRange(); const auto policy = uwline.PartitionPolicy(); const auto indentation = uwline.IndentationSpaces(); @@ -193,7 +193,7 @@ class LayoutItem { bool must_wrap_; }; -std::ostream& operator<<(std::ostream& stream, const LayoutItem& layout); +std::ostream &operator<<(std::ostream &stream, const LayoutItem &layout); // Intermediate partition tree layout using LayoutTree = VectorTree; @@ -250,13 +250,13 @@ class LayoutFunction { if (!segments_.empty()) CHECK_EQ(segments_.front().column, 0); } - LayoutFunction(LayoutFunction&&) = default; - LayoutFunction& operator=(LayoutFunction&&) = default; + LayoutFunction(LayoutFunction &&) = default; + LayoutFunction &operator=(LayoutFunction &&) = default; - LayoutFunction(const LayoutFunction&) = default; - LayoutFunction& operator=(const LayoutFunction&) = default; + LayoutFunction(const LayoutFunction &) = default; + LayoutFunction &operator=(const LayoutFunction &) = default; - void push_back(const LayoutFunctionSegment& segment) { + void push_back(const LayoutFunctionSegment &segment) { if (!segments_.empty()) { CHECK_LT(segments_.back().column, segment.column); } else { @@ -264,7 +264,7 @@ class LayoutFunction { } segments_.push_back(segment); } - void push_back(LayoutFunctionSegment&& segment) { + void push_back(LayoutFunctionSegment &&segment) { if (!segments_.empty()) { CHECK_LT(segments_.back().column, segment.column); } else { @@ -288,18 +288,18 @@ class LayoutFunction { // AKA: x- const_iterator AtOrToTheLeftOf(int column) const; - LayoutFunctionSegment& front() { return segments_.front(); } - const LayoutFunctionSegment& front() const { return segments_.front(); } + LayoutFunctionSegment &front() { return segments_.front(); } + const LayoutFunctionSegment &front() const { return segments_.front(); } - LayoutFunctionSegment& back() { return segments_.back(); } - const LayoutFunctionSegment& back() const { return segments_.back(); } + LayoutFunctionSegment &back() { return segments_.back(); } + const LayoutFunctionSegment &back() const { return segments_.back(); } - const LayoutFunctionSegment& operator[](size_t index) const { + const LayoutFunctionSegment &operator[](size_t index) const { CHECK_GE(index, 0); CHECK_LT(index, segments_.size()); return segments_[index]; } - LayoutFunctionSegment& operator[](size_t index) { + LayoutFunctionSegment &operator[](size_t index) { CHECK_GE(index, 0); CHECK_LT(index, segments_.size()); return segments_[index]; @@ -313,7 +313,7 @@ class LayoutFunction { // should be taken into account in the code that uses this method. This // shouldn't be the case, as every layout should wrap the same token range. CHECK(std::all_of(segments_.begin(), segments_.end(), - [must_wrap](const auto& segment) { + [must_wrap](const auto &segment) { return segment.layout.Value().MustWrap() == must_wrap; })); return must_wrap; @@ -321,7 +321,7 @@ class LayoutFunction { // Sets whether to force line break just before this layout. void SetMustWrap(bool must_wrap) { - for (auto& segment : segments_) { + for (auto &segment : segments_) { segment.layout.Value().SetMustWrap(must_wrap); } } @@ -330,7 +330,7 @@ class LayoutFunction { bool AreSegmentsSorted() const { return std::is_sorted( segments_.begin(), segments_.end(), - [](const LayoutFunctionSegment& a, const LayoutFunctionSegment& b) { + [](const LayoutFunctionSegment &a, const LayoutFunctionSegment &b) { return a.column < b.column; }); } @@ -356,18 +356,18 @@ class LayoutFunctionIterator { public: LayoutFunctionIterator() = default; - explicit LayoutFunctionIterator(container& layout_function, int index = 0) + explicit LayoutFunctionIterator(container &layout_function, int index = 0) : lf_(&layout_function), index_(index) { CHECK_LE(index_, lf_->size()); } - LayoutFunctionIterator(const iterator&) = default; - LayoutFunctionIterator& operator=(const iterator&) = default; + LayoutFunctionIterator(const iterator &) = default; + LayoutFunctionIterator &operator=(const iterator &) = default; // Helper methods // Returns reference to iterated container - container& Container() const { return *lf_; } + container &Container() const { return *lf_; } // Returns index of current element int Index() const { return index_; } @@ -381,7 +381,7 @@ class LayoutFunctionIterator { if (Container().empty()) return; CHECK_EQ(Container().front().column, 0); - auto& this_ref = *this; + auto &this_ref = *this; if (this_ref->column > column) { while (this_ref->column > column) --this_ref; } else { @@ -397,8 +397,8 @@ class LayoutFunctionIterator { using iterator_category = std::random_access_iterator_tag; using difference_type = std::ptrdiff_t; using value_type = LayoutFunctionSegment; - using pointer = ConditionalConst*; - using reference = ConditionalConst&; + using pointer = ConditionalConst *; + using reference = ConditionalConst &; reference operator*() const { return (*lf_)[index_]; } @@ -409,20 +409,20 @@ class LayoutFunctionIterator { return (*lf_)[index_ + index]; } - iterator& operator+=(difference_type rhs) { + iterator &operator+=(difference_type rhs) { CHECK_LE(rhs, lf_->size() - index_); index_ += rhs; return *this; } - iterator& operator-=(difference_type rhs) { + iterator &operator-=(difference_type rhs) { CHECK_LE(rhs, index_); index_ -= rhs; return *this; } - iterator& operator++() { return *this += 1; } + iterator &operator++() { return *this += 1; } - iterator& operator--() { return *this -= 1; } + iterator &operator--() { return *this -= 1; } iterator operator++(int) { auto tmp = *this; @@ -443,62 +443,62 @@ class LayoutFunctionIterator { return iterator(*lf_, index_ - rhs); } - friend iterator operator+(difference_type lhs, const iterator& rhs) { + friend iterator operator+(difference_type lhs, const iterator &rhs) { return iterator(*rhs.lf_, lhs + rhs.index_); } - friend iterator operator-(difference_type lhs, const iterator& rhs) { + friend iterator operator-(difference_type lhs, const iterator &rhs) { return iterator(*rhs.lf_, lhs - rhs.index_); } template difference_type operator+( - const LayoutFunctionIterator& rhs) const { + const LayoutFunctionIterator &rhs) const { return this->index_ + rhs.index_; } template difference_type operator-( - const LayoutFunctionIterator& rhs) const { + const LayoutFunctionIterator &rhs) const { return this->index_ - rhs.index_; } template - bool operator==(const LayoutFunctionIterator& rhs) const { + bool operator==(const LayoutFunctionIterator &rhs) const { return (lf_ == rhs.lf_) && (index_ == rhs.index_); } template - bool operator<(const LayoutFunctionIterator& rhs) const { + bool operator<(const LayoutFunctionIterator &rhs) const { return (lf_ == rhs.lf_) && (index_ < rhs.index_); } template - bool operator>(const LayoutFunctionIterator& rhs) const { + bool operator>(const LayoutFunctionIterator &rhs) const { return (lf_ == rhs.lf_) && (index_ > rhs.index_); } template - bool operator!=(const LayoutFunctionIterator& rhs) const { + bool operator!=(const LayoutFunctionIterator &rhs) const { return !(*this == rhs); } template - bool operator<=(const LayoutFunctionIterator& rhs) const { + bool operator<=(const LayoutFunctionIterator &rhs) const { return !(*this > rhs); } template - bool operator>=(const LayoutFunctionIterator& rhs) const { + bool operator>=(const LayoutFunctionIterator &rhs) const { return !(*this < rhs); } private: - container* lf_; + container *lf_; int index_; }; -std::ostream& operator<<(std::ostream& stream, - const LayoutFunctionSegment& segment); +std::ostream &operator<<(std::ostream &stream, + const LayoutFunctionSegment &segment); -std::ostream& operator<<(std::ostream& stream, const LayoutFunction& lf); +std::ostream &operator<<(std::ostream &stream, const LayoutFunction &lf); template -std::ostream& operator<<(std::ostream& stream, - const LayoutFunctionIterator& it) { +std::ostream &operator<<(std::ostream &stream, + const LayoutFunctionIterator &it) { return stream << &it.Container() << "[" << it.Index() << "/" << it.Container().size() << "]"; } @@ -511,14 +511,14 @@ inline constexpr bool IsIteratorDereferencingTo = std::is_same_v< // Methods for creating and combining LayoutFunctions class LayoutFunctionFactory { public: - explicit LayoutFunctionFactory(const BasicFormatStyle& style) + explicit LayoutFunctionFactory(const BasicFormatStyle &style) : style_(style) {} // Creates LayoutFunction for a single line from UnwrappedLine 'uwline'. - LayoutFunction Line(const UnwrappedLine& uwline) const; + LayoutFunction Line(const UnwrappedLine &uwline) const; // Creates LayoutFunction from a single line with tokens wrapped using Wrap(). - LayoutFunction WrappedLine(const UnwrappedLine& uwline) const; + LayoutFunction WrappedLine(const UnwrappedLine &uwline) const; // Combines two or more layouts vertically. // All combined layouts start at the same column. The first line of layout @@ -543,7 +543,7 @@ class LayoutFunctionFactory { auto segments = absl::FixedArray(lfs.size()); std::transform(lfs.begin(), lfs.end(), segments.begin(), - [](const LayoutFunction& lf) { + [](const LayoutFunction &lf) { CHECK(!lf.empty()); return lf.begin(); }); @@ -588,7 +588,7 @@ class LayoutFunctionFactory { LayoutFunction incremental = lfs_container.front(); lfs_container.pop_front(); - for (auto& lf : lfs_container) { + for (auto &lf : lfs_container) { incremental = Juxtaposition(incremental, lf); } @@ -622,7 +622,7 @@ class LayoutFunctionFactory { auto segments = absl::FixedArray(lfs.size()); std::transform(lfs.begin(), lfs.end(), segments.begin(), - [](const LayoutFunction& lf) { + [](const LayoutFunction &lf) { CHECK(!lf.empty()); return lf.begin(); }); @@ -631,7 +631,7 @@ class LayoutFunctionFactory { } // Returns LayoutFunction 'lf' with layout indented using 'indent' spaces. - LayoutFunction Indent(const LayoutFunction& lf, int indent) const; + LayoutFunction Indent(const LayoutFunction &lf, int indent) const; // Joins layouts horizontally and wraps them into multiple lines to stay under // column limit. Kind of like a words in a paragraph. @@ -670,18 +670,18 @@ class LayoutFunctionFactory { : results[j + 1], }); - const auto& next_element = lfs[j + 1]; + const auto &next_element = lfs[j + 1]; if (use_tokens_break_penalty) { // Deprioritize token-level wrapping // TODO(mglb): Find a better way to do this. This ratio has been // chosen using only a few test cases. const int wrapping_penalty = style_.over_column_limit_penalty; - const auto& second_layout = results[j + 1].front().layout; - const auto& first_line = LeftmostDescendant(second_layout).Value(); - const auto& first_token = first_line.TokensRange().front(); + const auto &second_layout = results[j + 1].front().layout; + const auto &first_line = LeftmostDescendant(second_layout).Value(); + const auto &first_token = first_line.TokensRange().front(); const int token_break_penalty = first_token.before.break_penalty; - for (auto& segment : results_i[j - i]) { + for (auto &segment : results_i[j - i]) { segment.intercept += wrapping_penalty + token_break_penalty; } } @@ -707,34 +707,34 @@ class LayoutFunctionFactory { } private: - LayoutFunction Juxtaposition(const LayoutFunction& left, - const LayoutFunction& right) const; + LayoutFunction Juxtaposition(const LayoutFunction &left, + const LayoutFunction &right) const; LayoutFunction Stack( - absl::FixedArray* segments) const; + absl::FixedArray *segments) const; static LayoutFunction Choice( - absl::FixedArray* segments); + absl::FixedArray *segments); - const BasicFormatStyle& style_; + const BasicFormatStyle &style_; }; class TokenPartitionsLayoutOptimizer { public: - explicit TokenPartitionsLayoutOptimizer(const BasicFormatStyle& style) + explicit TokenPartitionsLayoutOptimizer(const BasicFormatStyle &style) : factory_(style) {} - TokenPartitionsLayoutOptimizer(const TokenPartitionsLayoutOptimizer&) = + TokenPartitionsLayoutOptimizer(const TokenPartitionsLayoutOptimizer &) = delete; - TokenPartitionsLayoutOptimizer(TokenPartitionsLayoutOptimizer&&) = delete; - TokenPartitionsLayoutOptimizer& operator=( - const TokenPartitionsLayoutOptimizer&) = delete; - TokenPartitionsLayoutOptimizer& operator=(TokenPartitionsLayoutOptimizer&&) = + TokenPartitionsLayoutOptimizer(TokenPartitionsLayoutOptimizer &&) = delete; + TokenPartitionsLayoutOptimizer &operator=( + const TokenPartitionsLayoutOptimizer &) = delete; + TokenPartitionsLayoutOptimizer &operator=(TokenPartitionsLayoutOptimizer &&) = delete; - void Optimize(int indentation, TokenPartitionTree* node) const; + void Optimize(int indentation, TokenPartitionTree *node) const; - LayoutFunction CalculateOptimalLayout(const TokenPartitionTree& node) const; + LayoutFunction CalculateOptimalLayout(const TokenPartitionTree &node) const; private: const LayoutFunctionFactory factory_; @@ -746,18 +746,18 @@ class TreeReconstructor { : current_indentation_spaces_(indentation_spaces) {} ~TreeReconstructor() = default; - TreeReconstructor(const TreeReconstructor&) = delete; - TreeReconstructor(TreeReconstructor&&) = delete; - TreeReconstructor& operator=(const TreeReconstructor&) = delete; - TreeReconstructor& operator=(TreeReconstructor&&) = delete; + TreeReconstructor(const TreeReconstructor &) = delete; + TreeReconstructor(TreeReconstructor &&) = delete; + TreeReconstructor &operator=(const TreeReconstructor &) = delete; + TreeReconstructor &operator=(TreeReconstructor &&) = delete; - void TraverseTree(const LayoutTree& layout_tree); + void TraverseTree(const LayoutTree &layout_tree); - void ReplaceTokenPartitionTreeNode(TokenPartitionTree* node); + void ReplaceTokenPartitionTreeNode(TokenPartitionTree *node); private: TokenPartitionTree tree_; - TokenPartitionTree* current_node_ = nullptr; + TokenPartitionTree *current_node_ = nullptr; int current_indentation_spaces_; }; diff --git a/common/formatting/line_wrap_searcher.cc b/common/formatting/line_wrap_searcher.cc index beafa7dd9..4affe1654 100644 --- a/common/formatting/line_wrap_searcher.cc +++ b/common/formatting/line_wrap_searcher.cc @@ -37,15 +37,15 @@ namespace { struct SearchState { std::shared_ptr state; - explicit SearchState(const std::shared_ptr& s) : state(s) {} + explicit SearchState(const std::shared_ptr &s) : state(s) {} // Inverted to min-heap: *lowest* penalty has the highest search priority. - bool operator<(const SearchState& r) const { return *r.state < *state; } + bool operator<(const SearchState &r) const { return *r.state < *state; } }; } // namespace -std::vector SearchLineWraps(const UnwrappedLine& uwline, - const BasicFormatStyle& style, +std::vector SearchLineWraps(const UnwrappedLine &uwline, + const BasicFormatStyle &style, int max_search_states) { // Dijkstra's algorithm for now: prioritize searching minimum penalty path // until destination is reached. @@ -112,7 +112,7 @@ std::vector SearchLineWraps(const UnwrappedLine& uwline, // Consider the new penalties incurred for the next decision: // break, or no break. Calculate new penalties. // Push one or both branches into the worklist. - const auto& token = next.state->GetNextToken(); + const auto &token = next.state->GetNextToken(); if (token.before.break_decision == SpacingOptions::kPreserve) { VLOG(4) << "preserving spaces before \'" << token.token->text() << '\''; SearchState preserved(std::make_shared( @@ -153,9 +153,9 @@ std::vector SearchLineWraps(const UnwrappedLine& uwline, // winning_paths. Return a modified copy of the original UnwrappedLine. std::vector results; results.reserve(winning_paths.size()); - for (const auto& path : winning_paths) { + for (const auto &path : winning_paths) { results.emplace_back(uwline); - auto& result = results.back(); + auto &result = results.back(); CHECK_EQ(path->Depth(), result.Tokens().size()); path->ReconstructFormatDecisions(&result); if (aborted_search) { @@ -166,19 +166,19 @@ std::vector SearchLineWraps(const UnwrappedLine& uwline, } void DisplayEquallyOptimalWrappings( - std::ostream& stream, const UnwrappedLine& uwline, - const std::vector& solutions) { + std::ostream &stream, const UnwrappedLine &uwline, + const std::vector &solutions) { stream << "Found " << solutions.size() << " equally good solutions for the partition: " << uwline << std::endl; - for (const auto& solution : solutions) { + for (const auto &solution : solutions) { stream << Spacer(40, '-') << std::endl << solution.Render() << std::endl; } stream << Spacer(40, '=') << std::endl; } -FitResult FitsOnLine(const UnwrappedLine& uwline, - const BasicFormatStyle& style) { +FitResult FitsOnLine(const UnwrappedLine &uwline, + const BasicFormatStyle &style) { VLOG(3) << __FUNCTION__; // Leverage search functionality to compute effective line length of a slice // of tokens, taking into account minimum spacing requirements. @@ -192,7 +192,7 @@ FitResult FitsOnLine(const UnwrappedLine& uwline, auto state = std::make_shared(uwline, style); while (!state->Done()) { - const auto& token = state->GetNextToken(); + const auto &token = state->GetNextToken(); // If a line break is required before this token, return false. if (token.before.break_decision == SpacingOptions::kMustWrap) { return {false, state->current_column}; diff --git a/common/formatting/line_wrap_searcher.h b/common/formatting/line_wrap_searcher.h index ad9398dcf..f986be7b2 100644 --- a/common/formatting/line_wrap_searcher.h +++ b/common/formatting/line_wrap_searcher.h @@ -33,15 +33,15 @@ namespace verible { // returning a greedily formatted result (which can still be rendered) // that will be marked as !CompletedFormatting(). // This is guaranteed to return at least one result. -std::vector SearchLineWraps(const UnwrappedLine& uwline, - const BasicFormatStyle& style, +std::vector SearchLineWraps(const UnwrappedLine &uwline, + const BasicFormatStyle &style, int max_search_states); // Diagnostic helper for displaying when multiple optimal wrappings are found // by SearchLineWraps. This aids in development around wrap penalty tuning. void DisplayEquallyOptimalWrappings( - std::ostream& stream, const UnwrappedLine& uwline, - const std::vector& solutions); + std::ostream &stream, const UnwrappedLine &uwline, + const std::vector &solutions); // Returns false as soon as calculated line length exceeds maximum, or a token // that requires a newline is encountered. If everything fits, then return @@ -51,8 +51,8 @@ struct FitResult { int final_column; }; -FitResult FitsOnLine(const UnwrappedLine& uwline, - const BasicFormatStyle& style); +FitResult FitsOnLine(const UnwrappedLine &uwline, + const BasicFormatStyle &style); } // namespace verible diff --git a/common/formatting/line_wrap_searcher_test.cc b/common/formatting/line_wrap_searcher_test.cc index 709c03c0d..53c331696 100644 --- a/common/formatting/line_wrap_searcher_test.cc +++ b/common/formatting/line_wrap_searcher_test.cc @@ -43,8 +43,8 @@ class SearchLineWrapsTestFixture : public UnwrappedLineMemoryHandler, return levels * style_.indentation_spaces; } - FormattedExcerpt SearchLineWraps(const UnwrappedLine& uwline, - const BasicFormatStyle& style) { + FormattedExcerpt SearchLineWraps(const UnwrappedLine &uwline, + const BasicFormatStyle &style) { // Bound the size of search for unit testing. const auto results = verible::SearchLineWraps(uwline, style, 1000); EXPECT_FALSE(results.empty()); @@ -76,12 +76,12 @@ TEST_F(SearchLineWrapsTestFixture, OneToken) { UnwrappedLine uwline_in(LevelsToSpaces(0), pre_format_tokens_.begin()); AddFormatTokens(&uwline_in); EXPECT_EQ(uwline_in.Size(), tokens.size()); - auto& ftokens_in = pre_format_tokens_; + auto &ftokens_in = pre_format_tokens_; ftokens_in[0].before.break_penalty = 0; ftokens_in[0].before.spaces_required = 99; // should be ignored const FormattedExcerpt formatted_line = SearchLineWraps(uwline_in, style_); EXPECT_EQ(formatted_line.Tokens().size(), 1); - const auto& ftokens_out = formatted_line.Tokens(); + const auto &ftokens_out = formatted_line.Tokens(); // First token should never break. EXPECT_EQ(ftokens_out.front().before.action, SpacingDecision::kAppend); EXPECT_EQ(formatted_line.Render(), "aaa"); @@ -95,12 +95,12 @@ TEST_F(SearchLineWrapsTestFixture, OneTokenIndented) { UnwrappedLine uwline_in(LevelsToSpaces(2), pre_format_tokens_.begin()); AddFormatTokens(&uwline_in); EXPECT_EQ(uwline_in.Size(), tokens.size()); - auto& ftokens_in = pre_format_tokens_; + auto &ftokens_in = pre_format_tokens_; ftokens_in[0].before.break_penalty = 0; ftokens_in[0].before.spaces_required = 77; // should be ignored const FormattedExcerpt formatted_line = SearchLineWraps(uwline_in, style_); EXPECT_EQ(formatted_line.Tokens().size(), 1); - const auto& ftokens_out = formatted_line.Tokens(); + const auto &ftokens_out = formatted_line.Tokens(); // First token should never break. EXPECT_EQ(ftokens_out.front().before.action, SpacingDecision::kAppend); // 2 indentation levels, 3 spaces each = 6 spaces @@ -119,7 +119,7 @@ TEST_F(SearchLineWrapsTestFixture, FitsOnOneLine) { UnwrappedLine uwline_in(LevelsToSpaces(1), pre_format_tokens_.begin()); AddFormatTokens(&uwline_in); EXPECT_EQ(uwline_in.Size(), tokens.size()); - auto& ftokens_in = pre_format_tokens_; + auto &ftokens_in = pre_format_tokens_; ftokens_in[0].before.break_penalty = 1; ftokens_in[0].before.spaces_required = 77; // should be ignored ftokens_in[1].before.break_penalty = 1; @@ -130,7 +130,7 @@ TEST_F(SearchLineWrapsTestFixture, FitsOnOneLine) { ftokens_in[3].before.spaces_required = 1; const FormattedExcerpt formatted_line = SearchLineWraps(uwline_in, style_); EXPECT_EQ(formatted_line.Tokens().size(), tokens.size()); - const auto& ftokens_out = formatted_line.Tokens(); + const auto &ftokens_out = formatted_line.Tokens(); // Since all tokens fit on one line, expect no breaks. EXPECT_EQ(ftokens_out[0].before.action, SpacingDecision::kAppend); EXPECT_EQ(ftokens_out[1].before.action, SpacingDecision::kAppend); @@ -152,7 +152,7 @@ TEST_F(SearchLineWrapsTestFixture, WrapsToNextLine) { UnwrappedLine uwline_in(LevelsToSpaces(1), pre_format_tokens_.begin()); AddFormatTokens(&uwline_in); EXPECT_EQ(uwline_in.Size(), tokens.size()); - auto& ftokens_in = pre_format_tokens_; + auto &ftokens_in = pre_format_tokens_; ftokens_in[0].before.break_penalty = 1; ftokens_in[0].before.spaces_required = 77; // should be ignored ftokens_in[1].before.break_penalty = 1; @@ -163,7 +163,7 @@ TEST_F(SearchLineWrapsTestFixture, WrapsToNextLine) { ftokens_in[3].before.spaces_required = 1; const FormattedExcerpt formatted_line = SearchLineWraps(uwline_in, style_); EXPECT_EQ(formatted_line.Tokens().size(), tokens.size()); - const auto& ftokens_out = formatted_line.Tokens(); + const auto &ftokens_out = formatted_line.Tokens(); // First token should never break. EXPECT_EQ(ftokens_out[0].before.action, SpacingDecision::kAppend); EXPECT_EQ(ftokens_out[1].before.action, SpacingDecision::kAppend); @@ -193,7 +193,7 @@ TEST_F(SearchLineWrapsTestFixture, WrapsToNextLineMultiple) { UnwrappedLine uwline_in(LevelsToSpaces(1), pre_format_tokens_.begin()); AddFormatTokens(&uwline_in); EXPECT_EQ(uwline_in.Size(), tokens.size()); - auto& ftokens_in = pre_format_tokens_; + auto &ftokens_in = pre_format_tokens_; ftokens_in[0].before.break_penalty = 1; ftokens_in[0].before.spaces_required = 33; // should be ignored for (size_t i = 1; i < tokens.size(); ++i) { @@ -204,7 +204,7 @@ TEST_F(SearchLineWrapsTestFixture, WrapsToNextLineMultiple) { ftokens_in[5].before.break_penalty = 2; const FormattedExcerpt formatted_line = SearchLineWraps(uwline_in, style_); EXPECT_EQ(formatted_line.Tokens().size(), tokens.size()); - const auto& ftokens_out = formatted_line.Tokens(); + const auto &ftokens_out = formatted_line.Tokens(); EXPECT_EQ(ftokens_out[0].before.action, SpacingDecision::kAppend); EXPECT_EQ(ftokens_out[1].before.action, SpacingDecision::kAppend); EXPECT_EQ(ftokens_out[2].before.action, SpacingDecision::kAppend); @@ -231,7 +231,7 @@ TEST_F(SearchLineWrapsTestFixture, WrapsToNextLineMultipleDifferentSpaces) { UnwrappedLine uwline_in(LevelsToSpaces(1), pre_format_tokens_.begin()); AddFormatTokens(&uwline_in); EXPECT_EQ(uwline_in.Size(), tokens.size()); - auto& ftokens_in = pre_format_tokens_; + auto &ftokens_in = pre_format_tokens_; ftokens_in[0].before.break_penalty = 1; ftokens_in[0].before.spaces_required = 33; // should be ignored ftokens_in[1].before.break_penalty = 1; @@ -244,7 +244,7 @@ TEST_F(SearchLineWrapsTestFixture, WrapsToNextLineMultipleDifferentSpaces) { } const FormattedExcerpt formatted_line = SearchLineWraps(uwline_in, style_); EXPECT_EQ(formatted_line.Tokens().size(), tokens.size()); - const auto& ftokens_out = formatted_line.Tokens(); + const auto &ftokens_out = formatted_line.Tokens(); EXPECT_EQ(ftokens_out[0].before.action, SpacingDecision::kAppend); EXPECT_EQ(ftokens_out[1].before.action, SpacingDecision::kAppend); EXPECT_EQ(ftokens_out[2].before.action, SpacingDecision::kAppend); @@ -269,7 +269,7 @@ TEST_F(SearchLineWrapsTestFixture, ForcedJoins) { UnwrappedLine uwline_in(LevelsToSpaces(1), pre_format_tokens_.begin()); AddFormatTokens(&uwline_in); EXPECT_EQ(uwline_in.Size(), tokens.size()); - auto& ftokens_in = pre_format_tokens_; + auto &ftokens_in = pre_format_tokens_; ftokens_in[0].before.break_penalty = 1; ftokens_in[0].before.spaces_required = 11; // should be ignored ftokens_in[1].before.break_penalty = 1; @@ -280,7 +280,7 @@ TEST_F(SearchLineWrapsTestFixture, ForcedJoins) { SpacingOptions::kMustAppend; // This causes search to break earlier. const FormattedExcerpt formatted_line = SearchLineWraps(uwline_in, style_); EXPECT_EQ(formatted_line.Tokens().size(), tokens.size()); - const auto& ftokens_out = formatted_line.Tokens(); + const auto &ftokens_out = formatted_line.Tokens(); EXPECT_EQ(ftokens_out[0].before.action, SpacingDecision::kAppend); EXPECT_EQ(ftokens_out[1].before.action, SpacingDecision::kWrap); EXPECT_EQ(ftokens_out[2].before.action, SpacingDecision::kAppend); @@ -300,7 +300,7 @@ TEST_F(SearchLineWrapsTestFixture, ForcedWraps) { UnwrappedLine uwline_in(LevelsToSpaces(1), pre_format_tokens_.begin()); AddFormatTokens(&uwline_in); EXPECT_EQ(uwline_in.Size(), tokens.size()); - auto& ftokens_in = pre_format_tokens_; + auto &ftokens_in = pre_format_tokens_; ftokens_in[0].before.break_penalty = 1; ftokens_in[0].before.spaces_required = 11; // should be ignored ftokens_in[1].before.break_penalty = 1; @@ -310,7 +310,7 @@ TEST_F(SearchLineWrapsTestFixture, ForcedWraps) { ftokens_in[2].before.spaces_required = 1; const FormattedExcerpt formatted_line = SearchLineWraps(uwline_in, style_); EXPECT_EQ(formatted_line.Tokens().size(), tokens.size()); - const auto& ftokens_out = formatted_line.Tokens(); + const auto &ftokens_out = formatted_line.Tokens(); EXPECT_EQ(ftokens_out[0].before.action, SpacingDecision::kAppend); EXPECT_EQ(ftokens_out[1].before.action, SpacingDecision::kWrap); EXPECT_EQ(ftokens_out[2].before.action, SpacingDecision::kAppend); @@ -330,7 +330,7 @@ TEST_F(SearchLineWrapsTestFixture, DisplayEquallyOptimalWrappings) { UnwrappedLine uwline_in(LevelsToSpaces(1), pre_format_tokens_.begin()); AddFormatTokens(&uwline_in); EXPECT_EQ(uwline_in.Size(), tokens.size()); - auto& ftokens_in = pre_format_tokens_; + auto &ftokens_in = pre_format_tokens_; ftokens_in[0].before.break_penalty = 1; ftokens_in[0].before.spaces_required = 11; // should be ignored ftokens_in[1].before.break_penalty = 3; @@ -344,7 +344,7 @@ TEST_F(SearchLineWrapsTestFixture, DisplayEquallyOptimalWrappings) { // break before token[2]. // However, using a tie-breaker like terminal-column position, will favor // equally good solutions that break earlier. - const auto& first = formatted_lines.front(); + const auto &first = formatted_lines.front(); EXPECT_EQ(first.Tokens()[1].before.action, SpacingDecision::kAppend); EXPECT_EQ(first.Tokens()[2].before.action, SpacingDecision::kWrap); std::ostringstream stream; @@ -364,7 +364,7 @@ TEST_F(SearchLineWrapsTestFixture, FitsOnLine) { UnwrappedLine uwline_in(LevelsToSpaces(0), pre_format_tokens_.begin()); AddFormatTokens(&uwline_in); EXPECT_EQ(uwline_in.Size(), tokens.size()); - auto& ftokens_in = pre_format_tokens_; + auto &ftokens_in = pre_format_tokens_; ftokens_in[0].before.spaces_required = 99; // irrelevant ftokens_in[1].before.spaces_required = 1; ftokens_in[2].before.spaces_required = 1; @@ -409,7 +409,7 @@ TEST_F(SearchLineWrapsTestFixture, AbortedSearch) { UnwrappedLine uwline_in(LevelsToSpaces(1), pre_format_tokens_.begin()); AddFormatTokens(&uwline_in); EXPECT_EQ(uwline_in.Size(), tokens.size()); - auto& ftokens_in = pre_format_tokens_; + auto &ftokens_in = pre_format_tokens_; ftokens_in[0].before.break_penalty = 1; ftokens_in[0].before.spaces_required = 77; // should be ignored ftokens_in[1].before.break_penalty = 1; @@ -418,7 +418,7 @@ TEST_F(SearchLineWrapsTestFixture, AbortedSearch) { ftokens_in[2].before.spaces_required = 1; // Intentionally limit search space to a small count to force early abort. const auto formatted_lines = verible::SearchLineWraps(uwline_in, style_, 2); - const FormattedExcerpt& formatted_line = formatted_lines.front(); + const FormattedExcerpt &formatted_line = formatted_lines.front(); EXPECT_EQ(formatted_line.Tokens().size(), tokens.size()); EXPECT_FALSE(formatted_line.CompletedFormatting()); // The resulting state is unpredictable, because the search terminated early. diff --git a/common/formatting/state_node.cc b/common/formatting/state_node.cc index 5d13e8400..6efddb4f4 100644 --- a/common/formatting/state_node.cc +++ b/common/formatting/state_node.cc @@ -52,7 +52,7 @@ static SpacingDecision FrontTokenSpacing(const FormatTokenRange range) { return SpacingDecision::kAppend; } -StateNode::StateNode(const UnwrappedLine& uwline, const BasicFormatStyle& style) +StateNode::StateNode(const UnwrappedLine &uwline, const BasicFormatStyle &style) : prev_state(nullptr), undecided_path(uwline.TokensRange().begin(), uwline.TokensRange().end()), spacing_choice(FrontTokenSpacing(uwline.TokensRange())), @@ -75,8 +75,8 @@ StateNode::StateNode(const UnwrappedLine& uwline, const BasicFormatStyle& style) VLOG(4) << "root: " << *this; } -StateNode::StateNode(const std::shared_ptr& parent, - const BasicFormatStyle& style, +StateNode::StateNode(const std::shared_ptr &parent, + const BasicFormatStyle &style, SpacingDecision spacing_choice) : prev_state(ABSL_DIE_IF_NULL(parent)), undecided_path(prev_state->undecided_path.begin() + 1, // pop_front() @@ -87,7 +87,7 @@ StateNode::StateNode(const std::shared_ptr& parent, wrap_column_positions(prev_state->wrap_column_positions) { CHECK(!prev_state->Done()); - const PreFormatToken& current_format_token(GetCurrentToken()); + const PreFormatToken ¤t_format_token(GetCurrentToken()); VLOG(4) << "token.text: \'" << current_format_token.token->text() << '\''; bool called_open_group_balance = false; @@ -127,7 +127,7 @@ StateNode::StateNode(const std::shared_ptr& parent, VLOG(4) << "new state_node: " << *this; } -const PreFormatToken& StateNode::GetPreviousToken() const { +const PreFormatToken &StateNode::GetPreviousToken() const { CHECK(!ABSL_DIE_IF_NULL(prev_state)->Done()); return prev_state->GetCurrentToken(); } @@ -137,7 +137,7 @@ const PreFormatToken& StateNode::GetPreviousToken() const { // current_column for multi-line tokens. int StateNode::UpdateColumnPosition() { VLOG(4) << __FUNCTION__ << " spacing decision: " << spacing_choice; - const PreFormatToken& current_format_token(GetCurrentToken()); + const PreFormatToken ¤t_format_token(GetCurrentToken()); const int token_length = current_format_token.Length(); { @@ -212,7 +212,7 @@ int StateNode::UpdateColumnPosition() { return current_column; } -void StateNode::UpdateCumulativeCost(const BasicFormatStyle& style, +void StateNode::UpdateCumulativeCost(const BasicFormatStyle &style, int column_for_penalty) { // This must be called after UpdateColumnPosition() to account for // the updated current_column. @@ -222,7 +222,7 @@ void StateNode::UpdateCumulativeCost(const BasicFormatStyle& style, if (!IsRootState()) { CHECK_EQ(cumulative_cost, prev_state->cumulative_cost); } - const PreFormatToken& current_format_token(GetCurrentToken()); + const PreFormatToken ¤t_format_token(GetCurrentToken()); if (spacing_choice == SpacingDecision::kWrap) { // Only incur the penalty for breaking before this token. // Newly wrapped, so don't bother checking line length and suppress @@ -239,7 +239,7 @@ void StateNode::UpdateCumulativeCost(const BasicFormatStyle& style, // no additional cost if Spacing::Preserve } -void StateNode::OpenGroupBalance(const BasicFormatStyle& style) { +void StateNode::OpenGroupBalance(const BasicFormatStyle &style) { VLOG(4) << __FUNCTION__; // The adjustment to the wrap_column_positions stack based on a token's // balance type is delayed until we see the token *after*. @@ -274,7 +274,7 @@ void StateNode::OpenGroupBalance(const BasicFormatStyle& style) { CHECK(!wrap_column_positions.empty()); if (!IsRootState()) { - const PreFormatToken& prev_format_token(GetPreviousToken()); + const PreFormatToken &prev_format_token(GetPreviousToken()); if (prev_format_token.balancing == GroupBalancing::kOpen) { VLOG(4) << "previous token is open-group"; switch (spacing_choice) { @@ -315,10 +315,10 @@ void StateNode::CloseGroupBalance() { } std::shared_ptr StateNode::AppendIfItFits( - const std::shared_ptr& current_state, - const verible::BasicFormatStyle& style) { + const std::shared_ptr ¤t_state, + const verible::BasicFormatStyle &style) { if (current_state->Done()) return current_state; - const auto& token = current_state->GetNextToken(); + const auto &token = current_state->GetNextToken(); // It seems little wasteful to always create both states when only one is // returned, but compiler optimization should be able to leverage this. // In any case, this is not a critical path operation, so we're not going to @@ -334,8 +334,8 @@ std::shared_ptr StateNode::AppendIfItFits( } std::shared_ptr StateNode::QuickFinish( - const std::shared_ptr& current_state, - const verible::BasicFormatStyle& style) { + const std::shared_ptr ¤t_state, + const verible::BasicFormatStyle &style) { std::shared_ptr latest(current_state); // Construct a chain of reference-counted states where the returned pointer // "holds on" to all of its ancestors like a singly-linked-list. @@ -345,7 +345,7 @@ std::shared_ptr StateNode::QuickFinish( return latest; } -void StateNode::ReconstructFormatDecisions(FormattedExcerpt* result) const { +void StateNode::ReconstructFormatDecisions(FormattedExcerpt *result) const { // Find all wrap decisions from the greatest ancestor state to this state. // This is allowed to work on any intermediate state in the search process, @@ -354,11 +354,11 @@ void StateNode::ReconstructFormatDecisions(FormattedExcerpt* result) const { const size_t depth = Depth(); CHECK_LE(depth, result->Tokens().size()); - const StateNode* reverse_iter = this; - auto& format_tokens = result->MutableTokens(); + const StateNode *reverse_iter = this; + auto &format_tokens = result->MutableTokens(); const auto format_tokens_slice = make_range(format_tokens.begin(), format_tokens.begin() + depth); - for (auto& format_token : reversed_view(format_tokens_slice)) { + for (auto &format_token : reversed_view(format_tokens_slice)) { const auto text = format_token.token->text(); VLOG(3) << "reconstructing: " << text; // Apply decision at reverse_iter to (formatted) FormatToken. @@ -386,7 +386,7 @@ void StateNode::ReconstructFormatDecisions(FormattedExcerpt* result) const { } } -std::ostream& operator<<(std::ostream& stream, const StateNode& state) { +std::ostream &operator<<(std::ostream &stream, const StateNode &state) { // Omit information about remaining decisions and parent state. CHECK(!state.wrap_column_positions.empty()); return stream << "spacing:" << state.spacing_choice << // noformat diff --git a/common/formatting/state_node.h b/common/formatting/state_node.h index 789aabf7f..47e569a41 100644 --- a/common/formatting/state_node.h +++ b/common/formatting/state_node.h @@ -83,34 +83,34 @@ struct StateNode { // for position tracking purposes. // If the UnwrappedLine has only one token or is empty, the initial state // will be Done(). - StateNode(const UnwrappedLine& uwline, const BasicFormatStyle& style); + StateNode(const UnwrappedLine &uwline, const BasicFormatStyle &style); // Constructor for nodes that represent new wrap decision trees to explore. // 'spacing_choice' reflects the decision being explored, e.g. append, wrap, // preserve. - StateNode(const std::shared_ptr& parent, - const BasicFormatStyle& style, SpacingDecision spacing_choice); + StateNode(const std::shared_ptr &parent, + const BasicFormatStyle &style, SpacingDecision spacing_choice); // Returns true when the undecided_path is empty. // The search is over when there are no more decisions to explore. bool Done() const { return undecided_path.begin() == undecided_path.end(); } // Returns a reference to the token that is being acted upon in this state. - const PreFormatToken& GetCurrentToken() const { + const PreFormatToken &GetCurrentToken() const { // The undecided_path always starts at the position after the current token. return *(undecided_path.begin() - 1); } // Returns a reference to the token that considered for wrapping vs. // appending. - const PreFormatToken& GetNextToken() const { + const PreFormatToken &GetNextToken() const { // The undecided_path always starts at the position after the current token. return *undecided_path.begin(); } // Returns pointer to previous state before this decision node. // This functions as a forward-iterator going up the state ancestry chain. - const StateNode* next() const { return prev_state.get(); } + const StateNode *next() const { return prev_state.get(); } // Returns true if this state was initialized with an unwrapped line and // has no parent state. @@ -120,7 +120,7 @@ struct StateNode { // This occurs in O(N) time, and is only suitable for testing/debug. size_t Depth() const { size_t depth = 1; - const auto* iter = this; + const auto *iter = this; while (!iter->IsRootState()) { ++depth; iter = iter->prev_state.get(); @@ -131,19 +131,19 @@ struct StateNode { // Produce next state by appending a token if the result stays under the // column limit, or breaking onto a new line if required. static std::shared_ptr AppendIfItFits( - const std::shared_ptr& current_state, - const BasicFormatStyle& style); + const std::shared_ptr ¤t_state, + const BasicFormatStyle &style); // Repeatedly apply AppendIfItFits() until Done() with formatting. // TODO(b/134711965): We may want a variant that preserves spaces too. static std::shared_ptr QuickFinish( - const std::shared_ptr& current_state, - const BasicFormatStyle& style); + const std::shared_ptr ¤t_state, + const BasicFormatStyle &style); // Comparator provides an ordering of which paths should be explored // when maintained in a priority queue. For Dijsktra-style algorithms, // we want to explore the min-cost paths first. - bool operator<(const StateNode& r) const { + bool operator<(const StateNode &r) const { return cumulative_cost < r.cumulative_cost || // TODO(b/145558510): Favor solutions that use fewer lines. // To do that would require counting number of wrap decisions, @@ -159,19 +159,19 @@ struct StateNode { // wrap decisions (through ancestry chain: prev_state) all the way back to // the first token in the original UnwrappedLine (that was used to // initialize the root state). - void ReconstructFormatDecisions(FormattedExcerpt*) const; + void ReconstructFormatDecisions(FormattedExcerpt *) const; private: - const PreFormatToken& GetPreviousToken() const; + const PreFormatToken &GetPreviousToken() const; int UpdateColumnPosition(); - void UpdateCumulativeCost(const BasicFormatStyle&, int column_for_penalty); - void OpenGroupBalance(const BasicFormatStyle&); + void UpdateCumulativeCost(const BasicFormatStyle &, int column_for_penalty); + void OpenGroupBalance(const BasicFormatStyle &); void CloseGroupBalance(); }; // Human-readable representation for debugging only. -std::ostream& operator<<(std::ostream&, const StateNode&); +std::ostream &operator<<(std::ostream &, const StateNode &); } // namespace verible diff --git a/common/formatting/state_node_test.cc b/common/formatting/state_node_test.cc index eda9bf442..e1d84bac4 100644 --- a/common/formatting/state_node_test.cc +++ b/common/formatting/state_node_test.cc @@ -31,8 +31,8 @@ namespace verible { namespace { -std::string RenderFormattedText(const StateNode& path, - const UnwrappedLine& uwline) { +std::string RenderFormattedText(const StateNode &path, + const UnwrappedLine &uwline) { FormattedExcerpt formatted_line(uwline); // Discard tokens that have not yet been explored in search. formatted_line.MutableTokens().resize(path.Depth()); @@ -49,7 +49,7 @@ struct StateNodeTestFixture : public UnwrappedLineMemoryHandler, style.over_column_limit_penalty = 200; } - void Initialize(int d, const std::vector& tokens) { + void Initialize(int d, const std::vector &tokens) { CreateTokenInfos(tokens); uwline = std::make_unique(d * style.indentation_spaces, pre_format_tokens_.begin()); @@ -57,14 +57,14 @@ struct StateNodeTestFixture : public UnwrappedLineMemoryHandler, } void InitializeExternalTextBuffer(int d, - const std::vector& tokens) { + const std::vector &tokens) { CreateTokenInfosExternalStringBuffer(tokens); uwline = std::make_unique(d * style.indentation_spaces, pre_format_tokens_.begin()); AddFormatTokens(uwline.get()); } - std::string Render(const StateNode& path, const UnwrappedLine& uwline) const { + std::string Render(const StateNode &path, const UnwrappedLine &uwline) const { return RenderFormattedText(path, uwline); } @@ -132,7 +132,7 @@ TEST_F(StateNodeTestFixture, ConstructionAppendingPrevState) { const int kInitialIndent = 1; const std::vector tokens = {{0, "token1"}, {1, "TT2"}}; Initialize(kInitialIndent, tokens); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; ftokens[0].before.spaces_required = 1; ftokens[1].before.spaces_required = 1; ftokens[1].before.break_penalty = 5; @@ -146,7 +146,7 @@ TEST_F(StateNodeTestFixture, ConstructionAppendingPrevState) { initial_column + style.wrap_spaces); EXPECT_TRUE(parent_state->IsRootState()); - const auto& child_state = parent_state; + const auto &child_state = parent_state; { // Second token, also appended to same line as first: auto child2_state = std::make_shared(child_state, style, @@ -186,7 +186,7 @@ TEST_F(StateNodeTestFixture, ConstructionPreserveSpacesFromPrevStateNoGap) { const std::vector tokens = {{0, text.substr(0, 3)}, {1, text.substr(3, 3)}}; InitializeExternalTextBuffer(kInitialIndent, tokens); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; ftokens[0].before.spaces_required = 1; ftokens[1].before.spaces_required = 4; // ignored because of preserving ftokens[1].before.preserved_space_start = ftokens[0].Text().end(); @@ -219,7 +219,7 @@ TEST_F(StateNodeTestFixture, ConstructionPreserveSpacesFromPrevStateSpaces) { const std::vector tokens = {{1, text.substr(0, 3)}, {2, text.substr(7, 3)}}; InitializeExternalTextBuffer(kInitialIndent, tokens); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; ftokens[0].before.spaces_required = 1; ftokens[1].before.spaces_required = 2; // ignored because of preserving ftokens[1].before.preserved_space_start = ftokens[0].Text().end(); @@ -253,7 +253,7 @@ TEST_F(StateNodeTestFixture, ConstructionPreserveSpacesFromPrevStateNewline) { const std::vector tokens = {{1, text.substr(0, 3)}, {2, text.substr(7, 3)}}; InitializeExternalTextBuffer(kInitialIndent, tokens); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; ftokens[0].before.spaces_required = 1; ftokens[1].before.spaces_required = 2; // ignored because of preserving ftokens[1].before.preserved_space_start = ftokens[0].Text().end(); @@ -286,7 +286,7 @@ TEST_F(StateNodeTestFixture, ConstructionAppendingPrevStateWithGroupBalancing) { const std::vector tokens = { {0, "function_caller"}, {1, "("}, {2, "11"}, {3, ")"}}; Initialize(kInitialIndent, tokens); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; ftokens[0].before.spaces_required = 1; ftokens[1].before.spaces_required = 1; ftokens[1].before.break_penalty = 10; @@ -306,7 +306,7 @@ TEST_F(StateNodeTestFixture, ConstructionAppendingPrevStateWithGroupBalancing) { initial_column + style.wrap_spaces); EXPECT_EQ(Render(*parent_state, *uwline), " function_caller"); - const auto& child_state = parent_state; + const auto &child_state = parent_state; { // Second token, also appended to same line as first: // > function_caller ( @@ -618,7 +618,7 @@ TEST_F(StateNodeTestFixture, ConstructionAppendingPrevStateOverflow) { const std::vector tokens = {{0, "aaaaaaaaaaaaaaaaaaaaa"}, {1, "bbbbbbbbbbbbbbbbbb"}}; Initialize(kInitialIndent, tokens); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; ftokens[0].before.spaces_required = 1; ftokens[1].before.spaces_required = 1; ftokens[1].before.break_penalty = 8; @@ -664,7 +664,7 @@ TEST_F(StateNodeTestFixture, MultiLineTokenFront) { const int kInitialIndent = 1; const std::vector tokens = {{0, "a23456789\nb234"}}; Initialize(kInitialIndent, tokens); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; ftokens[0].before.spaces_required = 1; // First token on line: @@ -681,7 +681,7 @@ TEST_F(StateNodeTestFixture, MultiLineToken) { const std::vector tokens = {{0, "a23456789012345678901"}, {1, "b2345\nc234567890123"}}; Initialize(kInitialIndent, tokens); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; ftokens[0].before.spaces_required = 1; ftokens[1].before.spaces_required = 1; ftokens[1].before.break_penalty = 8; @@ -728,7 +728,7 @@ TEST_F(StateNodeTestFixture, MultiLineTokenOverflow) { const std::vector tokens = {{0, "a23456789012345678901"}, {1, "b234567\nc234567890"}}; Initialize(kInitialIndent, tokens); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; ftokens[0].before.spaces_required = 1; ftokens[1].before.spaces_required = 1; ftokens[1].before.break_penalty = 8; @@ -778,7 +778,7 @@ TEST_F(StateNodeTestFixture, ConstructionWrappingLinePrevState) { const int kInitialIndent = 1; const std::vector tokens = {{0, "token1"}, {1, "token2"}}; Initialize(kInitialIndent, tokens); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; ftokens[1].before.break_penalty = 7; auto parent_state = std::make_shared(*uwline, style); const int initial_column = kInitialIndent * style.indentation_spaces; @@ -809,7 +809,7 @@ TEST_F(StateNodeTestFixture, AppendIfItFitsTryToAppend) { {2, "zzzzzZZZZZ"}, }; Initialize(kInitialIndent, tokens); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; ftokens[0].before.spaces_required = 1; ftokens[1].before.spaces_required = 1; ftokens[2].before.spaces_required = 1; @@ -849,7 +849,7 @@ TEST_F(StateNodeTestFixture, AppendIfItFitsForcedWrap) { {1, "yyyyyYYYYY"}, }; Initialize(kInitialIndent, tokens); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; ftokens[0].before.spaces_required = 1; ftokens[1].before.spaces_required = 1; // Tokens stay under column limit, but here, we force a wrap. @@ -882,7 +882,7 @@ TEST_F(StateNodeTestFixture, QuickFinish) { {2, "zzzzzZZZZZ"}, }; Initialize(kInitialIndent, tokens); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; ftokens[0].before.spaces_required = 1; ftokens[1].before.spaces_required = 1; ftokens[2].before.spaces_required = 1; @@ -902,7 +902,7 @@ TEST_F(StateNodeTestFixture, QuickFinish) { EXPECT_EQ(final_state->spacing_choice, SpacingDecision::kWrap); // Second token, also appended to same line as first: - const auto* child_state = final_state->next(); + const auto *child_state = final_state->next(); EXPECT_EQ(child_state->spacing_choice, SpacingDecision::kAppend); // Second state is decended from initial state. diff --git a/common/formatting/token_partition_tree_test_utils.h b/common/formatting/token_partition_tree_test_utils.h index ecd53034f..7626eaad9 100644 --- a/common/formatting/token_partition_tree_test_utils.h +++ b/common/formatting/token_partition_tree_test_utils.h @@ -90,7 +90,7 @@ class TokenPartitionTreeBuilder { // Builds TokenPartitionTree. Token indexes used during construction are // replaced with iterators from 'tokens' vector. TokenPartitionTree build( - const std::vector& tokens) const; + const std::vector &tokens) const; private: int indent_ = 0; @@ -108,8 +108,8 @@ class TokenPartitionTreeBuilder { // expected_tree); // ::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); } // namespace verible diff --git a/common/formatting/tree_annotator.cc b/common/formatting/tree_annotator.cc index 638181aab..a15ca55c8 100644 --- a/common/formatting/tree_annotator.cc +++ b/common/formatting/tree_annotator.cc @@ -31,10 +31,10 @@ namespace { // implementation detail // refactoring as a common pattern. class TreeAnnotator : public TreeContextVisitor { public: - TreeAnnotator(const Symbol* syntax_tree_root, const TokenInfo& eof_token, + TreeAnnotator(const Symbol *syntax_tree_root, const TokenInfo &eof_token, std::vector::iterator tokens_begin, std::vector::iterator tokens_end, - const ContextTokenAnnotatorFunction& annotator) + const ContextTokenAnnotatorFunction &annotator) : eof_token_(eof_token), syntax_tree_root_(syntax_tree_root), token_annotator_(annotator), @@ -45,16 +45,16 @@ class TreeAnnotator : public TreeContextVisitor { private: // methods using TreeContextVisitor::Visit; // for SyntaxTreeNode - void Visit(const SyntaxTreeLeaf& leaf) final { + void Visit(const SyntaxTreeLeaf &leaf) final { CatchUpToCurrentLeaf(leaf.get()); } - void CatchUpToCurrentLeaf(const TokenInfo& leaf_token); + void CatchUpToCurrentLeaf(const TokenInfo &leaf_token); // TODO(fangism): This exists solely to facilitate CatchUpToCurrentLeaf(). // Consider using position in text_buffer as a terminator, and eliminating // this. - const TokenInfo& EOFToken() const { return eof_token_; } + const TokenInfo &EOFToken() const { return eof_token_; } private: // fields // Saved copy of the EOF token from the original token stream. @@ -63,7 +63,7 @@ class TreeAnnotator : public TreeContextVisitor { // Syntax tree that will be traversed, and will provide context // during leaf visits. - const Symbol* syntax_tree_root_ = nullptr; + const Symbol *syntax_tree_root_ = nullptr; // Function used to annotate the PreFormatTokens. ContextTokenAnnotatorFunction token_annotator_; @@ -97,7 +97,7 @@ void TreeAnnotator::Annotate() { CatchUpToCurrentLeaf(EOFToken()); } -void TreeAnnotator::CatchUpToCurrentLeaf(const TokenInfo& leaf_token) { +void TreeAnnotator::CatchUpToCurrentLeaf(const TokenInfo &leaf_token) { // "Catch up" next_filtered_token_ to the current leaf. // Recall that SyntaxTreeLeaf has its own copy of TokenInfo, // so we need to compare a unique property instead of address. @@ -110,9 +110,9 @@ void TreeAnnotator::CatchUpToCurrentLeaf(const TokenInfo& leaf_token) { // compare const char* addresses: next_filtered_token_->token->text().begin() != leaf_token.text().begin()) { - const auto& left_token = *next_filtered_token_; + const auto &left_token = *next_filtered_token_; ++next_filtered_token_; - auto& right_token = *next_filtered_token_; + auto &right_token = *next_filtered_token_; token_annotator_(left_token, &right_token, saved_left_context_, Context()); } // next_filtered_token_ now points to leaf_token, now caught up. @@ -124,10 +124,10 @@ void TreeAnnotator::CatchUpToCurrentLeaf(const TokenInfo& leaf_token) { } // namespace void AnnotateFormatTokensUsingSyntaxContext( - const Symbol* syntax_tree_root, const TokenInfo& eof_token, + const Symbol *syntax_tree_root, const TokenInfo &eof_token, std::vector::iterator tokens_begin, std::vector::iterator tokens_end, - const ContextTokenAnnotatorFunction& annotator) { + const ContextTokenAnnotatorFunction &annotator) { TreeAnnotator t(syntax_tree_root, eof_token, tokens_begin, tokens_end, annotator); t.Annotate(); diff --git a/common/formatting/tree_annotator.h b/common/formatting/tree_annotator.h index 478312764..f501e9023 100644 --- a/common/formatting/tree_annotator.h +++ b/common/formatting/tree_annotator.h @@ -29,16 +29,16 @@ namespace verible { // left token's syntax tree context, // right token's syntax tree context. using ContextTokenAnnotatorFunction = - std::function; + std::function; // Applies inter-token formatting annotations, using syntactic context // at every token. void AnnotateFormatTokensUsingSyntaxContext( - const Symbol* syntax_tree_root, const TokenInfo& eof_token, + const Symbol *syntax_tree_root, const TokenInfo &eof_token, std::vector::iterator tokens_begin, std::vector::iterator tokens_end, - const ContextTokenAnnotatorFunction& annotator); + const ContextTokenAnnotatorFunction &annotator); } // namespace verible diff --git a/common/formatting/tree_annotator_test.cc b/common/formatting/tree_annotator_test.cc index eadf6f0c7..85310656c 100644 --- a/common/formatting/tree_annotator_test.cc +++ b/common/formatting/tree_annotator_test.cc @@ -28,16 +28,16 @@ namespace { using ::testing::ElementsAre; std::vector ExtractSyntaxTreeContextEnums( - const SyntaxTreeContext& context) { + const SyntaxTreeContext &context) { std::vector result; - for (const auto* node : context) { + for (const auto *node : context) { result.push_back(ABSL_DIE_IF_NULL(node)->Tag().tag); } return result; } -static void DoNothing(const PreFormatToken&, PreFormatToken*, - const SyntaxTreeContext&, const SyntaxTreeContext&) {} +static void DoNothing(const PreFormatToken &, PreFormatToken *, + const SyntaxTreeContext &, const SyntaxTreeContext &) {} TEST(AnnotateFormatTokensUsingSyntaxContextTest, EmptyFormatTokens) { std::vector ftokens; @@ -49,15 +49,15 @@ TEST(AnnotateFormatTokensUsingSyntaxContextTest, EmptyFormatTokens) { constexpr int kForcedSpaces = 5; -void ForceSpaces(const PreFormatToken&, PreFormatToken* right, - const SyntaxTreeContext& /* left_context */, - const SyntaxTreeContext& /* right_context */) { +void ForceSpaces(const PreFormatToken &, PreFormatToken *right, + const SyntaxTreeContext & /* left_context */, + const SyntaxTreeContext & /* right_context */) { right->before.spaces_required = kForcedSpaces; } // The first format token never gets annotated. template -iterator_range ExcludeFirst(const T& t) { +iterator_range ExcludeFirst(const T &t) { return make_range(t.begin() + 1, t.end()); } @@ -70,19 +70,19 @@ TEST(AnnotateFormatTokensUsingSyntaxContextTest, UnusedContext) { {verible::TK_EOF, text.substr(3, 0)}, // EOF }; std::vector ftokens; - for (const auto& t : tokens) { + for (const auto &t : tokens) { ftokens.emplace_back(&t); } AnnotateFormatTokensUsingSyntaxContext(nullptr, tokens[3], ftokens.begin(), ftokens.end(), ForceSpaces); - for (const auto& ftoken : ExcludeFirst(ftokens)) { + for (const auto &ftoken : ExcludeFirst(ftokens)) { EXPECT_EQ(ftoken.before.spaces_required, kForcedSpaces); } } -void LeftIsB(const PreFormatToken& left, PreFormatToken* right, - const SyntaxTreeContext& /* left_context */, - const SyntaxTreeContext& /* right_context */) { +void LeftIsB(const PreFormatToken &left, PreFormatToken *right, + const SyntaxTreeContext & /* left_context */, + const SyntaxTreeContext & /* right_context */) { if (left.token->text() == "b") { right->before.spaces_required = kForcedSpaces; } else { @@ -99,7 +99,7 @@ TEST(AnnotateFormatTokensUsingSyntaxContextTest, UnusedContextBasedOnLeft) { {verible::TK_EOF, text.substr(3, 0)}, // EOF }; std::vector ftokens; - for (const auto& t : tokens) { + for (const auto &t : tokens) { ftokens.emplace_back(&t); } AnnotateFormatTokensUsingSyntaxContext(nullptr, tokens[3], ftokens.begin(), @@ -108,10 +108,10 @@ TEST(AnnotateFormatTokensUsingSyntaxContextTest, UnusedContextBasedOnLeft) { EXPECT_EQ(ftokens[2].before.spaces_required, kForcedSpaces); } -void RightContextDirectParentIsNine(const PreFormatToken&, - PreFormatToken* right, - const SyntaxTreeContext& left_context, - const SyntaxTreeContext& right_context) { +void RightContextDirectParentIsNine(const PreFormatToken &, + PreFormatToken *right, + const SyntaxTreeContext &left_context, + const SyntaxTreeContext &right_context) { if (right_context.DirectParentIs(9)) { right->before.spaces_required = kForcedSpaces; } else { @@ -128,7 +128,7 @@ TEST(AnnotateFormatTokensUsingSyntaxContextTest, UsingRightContext) { {verible::TK_EOF, text.substr(3, 0)}, // EOF }; std::vector ftokens; - for (const auto& t : tokens) { + for (const auto &t : tokens) { ftokens.emplace_back(&t); } const auto tree = TNode(6, // synthesized syntax tree @@ -143,10 +143,10 @@ TEST(AnnotateFormatTokensUsingSyntaxContextTest, UsingRightContext) { EXPECT_EQ(ftokens[2].before.spaces_required, kForcedSpaces); } -void LeftContextDirectParentIsSeven(const PreFormatToken&, - PreFormatToken* right, - const SyntaxTreeContext& left_context, - const SyntaxTreeContext& right_context) { +void LeftContextDirectParentIsSeven(const PreFormatToken &, + PreFormatToken *right, + const SyntaxTreeContext &left_context, + const SyntaxTreeContext &right_context) { if (left_context.DirectParentIs(7)) { right->before.spaces_required = kForcedSpaces + 4; } else { @@ -163,7 +163,7 @@ TEST(AnnotateFormatTokensUsingSyntaxContextTest, UsingLeftContext) { {verible::TK_EOF, text.substr(3, 0)}, // EOF }; std::vector ftokens; - for (const auto& t : tokens) { + for (const auto &t : tokens) { ftokens.emplace_back(&t); } const auto tree = TNode(6, // synthesized syntax tree @@ -202,14 +202,14 @@ TEST(AnnotateFormatTokensUsingSyntaxContextTest, VerifySlidingContexts) { TNode(9, Leaf(tokens[6])) // ); std::vector ftokens; - for (const auto& t : tokens) { + for (const auto &t : tokens) { ftokens.emplace_back(&t); } std::vector> saved_contexts; saved_contexts.push_back({6, 7}); // first leaf's context - auto context_listener = [&](const PreFormatToken&, PreFormatToken*, - const SyntaxTreeContext& left_context, - const SyntaxTreeContext& right_context) { + auto context_listener = [&](const PreFormatToken &, PreFormatToken *, + const SyntaxTreeContext &left_context, + const SyntaxTreeContext &right_context) { // continuity and consistency check const auto left_enums = ExtractSyntaxTreeContextEnums(left_context); EXPECT_EQ(left_enums, saved_contexts.back()); diff --git a/common/formatting/tree_unwrapper_test.cc b/common/formatting/tree_unwrapper_test.cc index ba007dc38..da2a33bb0 100644 --- a/common/formatting/tree_unwrapper_test.cc +++ b/common/formatting/tree_unwrapper_test.cc @@ -35,14 +35,14 @@ namespace verible { -static bool KeepNonWhitespace(const TokenInfo& token) { +static bool KeepNonWhitespace(const TokenInfo &token) { const absl::string_view text(absl::StripAsciiWhitespace(token.text())); return !text.empty(); } class TreeUnwrapperData { public: - explicit TreeUnwrapperData(const verible::TokenSequence& tokens) { + explicit TreeUnwrapperData(const verible::TokenSequence &tokens) { verible::InitTokenStreamView(tokens, &tokens_view_); verible::FilterTokenStreamViewInPlace(KeepNonWhitespace, &tokens_view_); @@ -61,7 +61,7 @@ class TreeUnwrapperData { class FakeTreeUnwrapper : public TreeUnwrapperData, public TreeUnwrapper { public: - explicit FakeTreeUnwrapper(const TextStructureView& view) + explicit FakeTreeUnwrapper(const TextStructureView &view) : TreeUnwrapperData(view.TokenStream()), TreeUnwrapper(view, TreeUnwrapperData::preformatted_tokens_) {} @@ -71,18 +71,18 @@ class FakeTreeUnwrapper : public TreeUnwrapperData, public TreeUnwrapper { // Leaf visit that adds a PreFormatToken from the leaf's TokenInfo // to the current_unwrapped_line_ - void Visit(const verible::SyntaxTreeLeaf& leaf) final { + void Visit(const verible::SyntaxTreeLeaf &leaf) final { CatchUpFilteredTokens(); AddTokenToCurrentUnwrappedLine(); } // Node visit that always starts a new unwrapped line - void Visit(const SyntaxTreeNode& node) final { + void Visit(const SyntaxTreeNode &node) final { StartNewUnwrappedLine(PartitionPolicyEnum::kAlwaysExpand, &node); TraverseChildren(node); } - void InterChildNodeHook(const SyntaxTreeNode& node) final {} + void InterChildNodeHook(const SyntaxTreeNode &node) final {} using TreeUnwrapper::StartNewUnwrappedLine; @@ -90,7 +90,7 @@ class FakeTreeUnwrapper : public TreeUnwrapperData, public TreeUnwrapper { void CatchUpFilteredTokens() { const auto iter = CurrentFormatTokenIterator(); SkipUnfilteredTokens( - [=](const verible::TokenInfo& token) { return &token != iter->token; }); + [=](const verible::TokenInfo &token) { return &token != iter->token; }); } }; @@ -101,14 +101,14 @@ TEST(TreeUnwrapperTest, EmptyStartNewUnwrappedLine) { FakeTreeUnwrapper tree_unwrapper(*view); // const reference forces use of const method - const auto& const_tree_unwrapper(tree_unwrapper); + const auto &const_tree_unwrapper(tree_unwrapper); // Do not call .Unwrap() for this test. - const auto& current = const_tree_unwrapper.CurrentUnwrappedLine(); + const auto ¤t = const_tree_unwrapper.CurrentUnwrappedLine(); tree_unwrapper.StartNewUnwrappedLine(PartitionPolicyEnum::kAlwaysExpand, &*view->SyntaxTree()); - const auto& next = const_tree_unwrapper.CurrentUnwrappedLine(); + const auto &next = const_tree_unwrapper.CurrentUnwrappedLine(); EXPECT_EQ(¤t, &next); } @@ -124,8 +124,8 @@ TEST(TreeUnwrapperTest, NonEmptyUnwrap) { tree_unwrapper.Unwrap(); const auto unwrapped_lines = tree_unwrapper.FullyPartitionedUnwrappedLines(); ASSERT_EQ(unwrapped_lines.size(), 2); - const UnwrappedLine& first_unwrapped_line = unwrapped_lines[0]; - const UnwrappedLine& second_unwrapped_line = unwrapped_lines[1]; + const UnwrappedLine &first_unwrapped_line = unwrapped_lines[0]; + const UnwrappedLine &second_unwrapped_line = unwrapped_lines[1]; EXPECT_EQ(first_unwrapped_line.Size(), 2); EXPECT_EQ(second_unwrapped_line.Size(), 1); diff --git a/common/formatting/unwrapped_line.cc b/common/formatting/unwrapped_line.cc index 08bea2f1a..831827d67 100644 --- a/common/formatting/unwrapped_line.cc +++ b/common/formatting/unwrapped_line.cc @@ -32,7 +32,7 @@ namespace verible { -std::ostream& operator<<(std::ostream& stream, PartitionPolicyEnum p) { +std::ostream &operator<<(std::ostream &stream, PartitionPolicyEnum p) { switch (p) { case PartitionPolicyEnum::kUninitialized: return stream << "uninitialized"; @@ -60,7 +60,7 @@ std::ostream& operator<<(std::ostream& stream, PartitionPolicyEnum p) { LOG(FATAL) << "Unknown partition policy " << int(p); } -static void TokenFormatter(std::string* out, const PreFormatToken& token, +static void TokenFormatter(std::string *out, const PreFormatToken &token, bool verbose) { if (verbose) { std::ostringstream oss; @@ -75,19 +75,19 @@ void UnwrappedLine::SetIndentationSpaces(int spaces) { indentation_spaces_ = spaces; } -void UnwrappedLine::DefaultOriginPrinter(std::ostream& stream, - const verible::Symbol* symbol) { +void UnwrappedLine::DefaultOriginPrinter(std::ostream &stream, + const verible::Symbol *symbol) { static constexpr int kContextLimit = 25; stream << '"' << AutoTruncate{StringSpanOfSymbol(*symbol), kContextLimit} << '"'; } -std::ostream* UnwrappedLine::AsCode( - std::ostream* stream, bool verbose, - const OriginPrinterFunction& origin_printer) const { +std::ostream *UnwrappedLine::AsCode( + std::ostream *stream, bool verbose, + const OriginPrinterFunction &origin_printer) const { *stream << Spacer(indentation_spaces_, kIndentationMarker) << '[' << absl::StrJoin(tokens_, " ", - [=](std::string* out, const PreFormatToken& token) { + [=](std::string *out, const PreFormatToken &token) { TokenFormatter(out, token, verbose); }) << "], policy: " << partition_policy_; @@ -99,23 +99,23 @@ std::ostream* UnwrappedLine::AsCode( return stream; } -std::ostream& operator<<(std::ostream& stream, const UnwrappedLine& line) { +std::ostream &operator<<(std::ostream &stream, const UnwrappedLine &line) { return *line.AsCode(&stream); } -FormattedExcerpt::FormattedExcerpt(const UnwrappedLine& uwline) +FormattedExcerpt::FormattedExcerpt(const UnwrappedLine &uwline) : indentation_spaces_(uwline.IndentationSpaces()) { tokens_.reserve(uwline.Size()); // Convert working PreFormatTokens (computed from wrap optimization) into // decision-bound representation. const auto range = uwline.TokensRange(); std::transform(range.begin(), range.end(), std::back_inserter(tokens_), - [](const PreFormatToken& t) { return FormattedToken(t); }); + [](const PreFormatToken &t) { return FormattedToken(t); }); } -std::ostream& FormattedExcerpt::FormattedText( - std::ostream& stream, bool indent, - const std::function& include_token_p) const { +std::ostream &FormattedExcerpt::FormattedText( + std::ostream &stream, bool indent, + const std::function &include_token_p) const { if (tokens_.empty()) return stream; // Let caller print the preceding/trailing newline. if (indent) { @@ -125,7 +125,7 @@ std::ostream& FormattedExcerpt::FormattedText( } // We do not want the indentation before the first token, if it was // already handled separately. - const auto& front = tokens_.front(); + const auto &front = tokens_.front(); if (include_token_p(*front.token)) { VLOG(2) << "action: " << front.before.action; switch (front.before.action) { @@ -137,15 +137,15 @@ std::ostream& FormattedExcerpt::FormattedText( stream << front.token->text(); } } - for (const auto& ftoken : + for (const auto &ftoken : verible::make_range(tokens_.begin() + 1, tokens_.end())) { if (include_token_p(*ftoken.token)) stream << ftoken; } return stream; } -std::ostream& operator<<(std::ostream& stream, - const FormattedExcerpt& excerpt) { +std::ostream &operator<<(std::ostream &stream, + const FormattedExcerpt &excerpt) { return excerpt.FormattedText(stream, true); } diff --git a/common/formatting/unwrapped_line_test.cc b/common/formatting/unwrapped_line_test.cc index 71616ae96..b1eea0835 100644 --- a/common/formatting/unwrapped_line_test.cc +++ b/common/formatting/unwrapped_line_test.cc @@ -136,8 +136,8 @@ TEST_F(UnwrappedLineTest, SpanNextToken) { UnwrappedLine uwline(0, pre_format_tokens_.begin()); AddFormatTokens(&uwline); - const auto& front_token = tokens.front(); - const auto& back_token = tokens.back(); + const auto &front_token = tokens.front(); + const auto &back_token = tokens.back(); const auto range = uwline.TokensRange(); EXPECT_EQ(range.front().TokenEnum(), front_token.token_enum()); EXPECT_EQ(range.back().TokenEnum(), back_token.token_enum()); @@ -183,8 +183,8 @@ TEST_F(UnwrappedLineTest, SpanPrevToken) { UnwrappedLine uwline(0, pre_format_tokens_.begin()); AddFormatTokens(&uwline); - const auto& front_token = tokens.front(); - const auto& back_token = tokens.back(); + const auto &front_token = tokens.front(); + const auto &back_token = tokens.back(); const auto range = uwline.TokensRange(); EXPECT_EQ(range.front().TokenEnum(), front_token.token_enum()); EXPECT_EQ(range.back().TokenEnum(), back_token.token_enum()); @@ -258,7 +258,7 @@ TEST_F(UnwrappedLineTest, FormattedTextNonEmpty) { CreateTokenInfos(tokens); UnwrappedLine uwline(4, pre_format_tokens_.begin()); AddFormatTokens(&uwline); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; // Pretend we've committed formatting decisions from an optimizer. ftokens[0].before.break_decision = SpacingOptions::kMustWrap; ftokens[0].before.spaces_required = 4; @@ -281,7 +281,7 @@ TEST_F(UnwrappedLineTest, FormattedTextNonEmptySuppressIndent) { CreateTokenInfos(tokens); UnwrappedLine uwline(4, pre_format_tokens_.begin()); AddFormatTokens(&uwline); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; // Pretend we've committed formatting decisions from an optimizer. ftokens[0].before.break_decision = SpacingOptions::kMustWrap; ftokens[0].before.spaces_required = 4; @@ -302,7 +302,7 @@ TEST_F(UnwrappedLineTest, FormattedTextNonEmptyWithIndent) { CreateTokenInfos(tokens); UnwrappedLine uwline(4, pre_format_tokens_.begin()); AddFormatTokens(&uwline); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; // Pretend we've committed formatting decisions from an optimizer. ftokens[0].before.break_decision = SpacingOptions::kMustWrap; ftokens[0].before.spaces_required = 4; @@ -324,13 +324,13 @@ TEST_F(UnwrappedLineTest, FormattedTextSelectiveIncludeToken) { CreateTokenInfos(tokens); UnwrappedLine uwline(4, pre_format_tokens_.begin()); AddFormatTokens(&uwline); - for (auto& t : pre_format_tokens_) { + for (auto &t : pre_format_tokens_) { t.before.spaces_required = 2; } FormattedExcerpt output(uwline); std::ostringstream stream; // Choose to not include test_token2 in output. - output.FormattedText(stream, false, [](const TokenInfo& t) { + output.FormattedText(stream, false, [](const TokenInfo &t) { return t.text() != "test_token2"; }); const char expected[] = R"(test_token1 test_token3)"; @@ -386,7 +386,7 @@ TEST_F(UnwrappedLineTest, FormattedTextPreserveSpacesWithTokens) { CreateTokenInfosExternalStringBuffer(tokens); // use 'text' buffer UnwrappedLine uwline(4, pre_format_tokens_.begin()); AddFormatTokens(&uwline); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; // Don't care about other before.* fields when preserving ftokens[0].before.preserved_space_start = text.begin() + 0; ftokens[0].before.break_decision = SpacingOptions::kPreserve; @@ -412,7 +412,7 @@ TEST_F(UnwrappedLineTest, FormattedTextPreserveNewlines) { CreateTokenInfosExternalStringBuffer(tokens); // use 'text' buffer UnwrappedLine uwline(4, pre_format_tokens_.begin()); AddFormatTokens(&uwline); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; // Don't care about other before.* fields when preserving ftokens[0].before.preserved_space_start = text.begin() + 0; ftokens[0].before.break_decision = SpacingOptions::kPreserve; @@ -435,7 +435,7 @@ TEST_F(UnwrappedLineTest, FormattedTextPreserveNewlinesDropSpaces) { CreateTokenInfosExternalStringBuffer(tokens); // use 'text' buffer UnwrappedLine uwline(4, pre_format_tokens_.begin()); AddFormatTokens(&uwline); - auto& ftokens = pre_format_tokens_; + auto &ftokens = pre_format_tokens_; // Don't care about other before.* fields when preserving ftokens[0].before.preserved_space_start = text.begin() + 0; ftokens[0].before.break_decision = SpacingOptions::kPreserve; @@ -526,7 +526,7 @@ TEST_F(UnwrappedLineTest, AsCodeCustomOriginPrinter) { uwline.SetOrigin(&*tree); { std::ostringstream stream; - uwline.AsCode(&stream, false, [](std::ostream& out, const Symbol* symbol) { + uwline.AsCode(&stream, false, [](std::ostream &out, const Symbol *symbol) { EXPECT_NE(symbol, nullptr); out << "Test/" << symbol->Tag().tag << "/"; UnwrappedLine::DefaultOriginPrinter(out, symbol); diff --git a/common/formatting/unwrapped_line_test_utils.cc b/common/formatting/unwrapped_line_test_utils.cc index 711161976..0189b947b 100644 --- a/common/formatting/unwrapped_line_test_utils.cc +++ b/common/formatting/unwrapped_line_test_utils.cc @@ -25,12 +25,12 @@ namespace verible { void UnwrappedLineMemoryHandler::CreateTokenInfosExternalStringBuffer( - const std::vector& tokens) { + const std::vector &tokens) { // pre-allocate to guarantee address stability, prevent realloc. const size_t N = tokens.size(); token_infos_.reserve(N); pre_format_tokens_.reserve(N); - for (const auto& token : tokens) { + for (const auto &token : tokens) { token_infos_.emplace_back(token.token_enum(), token.text()); pre_format_tokens_.emplace_back(&token_infos_.back()); } @@ -38,14 +38,14 @@ void UnwrappedLineMemoryHandler::CreateTokenInfosExternalStringBuffer( } void UnwrappedLineMemoryHandler::CreateTokenInfos( - const std::vector& tokens) { + const std::vector &tokens) { CreateTokenInfosExternalStringBuffer(tokens); // Join the token string_view fragments into a single contiguous string buffer // and rebase the ranges to point into the new buffer. TokenInfo::Concatenate(&joined_token_text_, &token_infos_); } -void UnwrappedLineMemoryHandler::AddFormatTokens(UnwrappedLine* uwline) { +void UnwrappedLineMemoryHandler::AddFormatTokens(UnwrappedLine *uwline) { for (size_t i = 0; i < pre_format_tokens_.size(); ++i) { uwline->SpanNextToken(); // Note: this leaves PreFormatToken::format_token_enum unset. diff --git a/common/formatting/unwrapped_line_test_utils.h b/common/formatting/unwrapped_line_test_utils.h index b214b06ab..7bab4c954 100644 --- a/common/formatting/unwrapped_line_test_utils.h +++ b/common/formatting/unwrapped_line_test_utils.h @@ -35,17 +35,17 @@ class UnwrappedLineMemoryHandler { // in joined_token_text_ and token_infos_ to be used by FormatTokens. // This variant considers the string_views in tokens as disjoint, // and automatically joins them into an internal buffer. - void CreateTokenInfos(const std::vector& tokens); + void CreateTokenInfos(const std::vector &tokens); // Same as CreateTokenInfos(), except that string_views are already owned // externally, and do not need to be joined into an internal buffer. void CreateTokenInfosExternalStringBuffer( - const std::vector& tokens); + const std::vector &tokens); // Creates format tokens for each of the token info objects passed and // spans the entire array in the UnwrappedLine. // Call this after CreateTokenInfos(). - void AddFormatTokens(UnwrappedLine* uwline); + void AddFormatTokens(UnwrappedLine *uwline); std::vector::iterator GetPreFormatTokensBegin() { return pre_format_tokens_.begin(); diff --git a/common/formatting/verification.cc b/common/formatting/verification.cc index e68db915f..e2fcfad7b 100644 --- a/common/formatting/verification.cc +++ b/common/formatting/verification.cc @@ -22,7 +22,7 @@ namespace verible { absl::Status ReformatMustMatch(absl::string_view original_text, - const LineNumberSet& lines, + const LineNumberSet &lines, absl::string_view formatted_text, absl::string_view reformatted_text) { if (reformatted_text != formatted_text) { diff --git a/common/formatting/verification.h b/common/formatting/verification.h index 2170f8a11..d4afe87bb 100644 --- a/common/formatting/verification.h +++ b/common/formatting/verification.h @@ -27,7 +27,7 @@ namespace verible { // 'original_text' is the text before any formatting was done. // 'lines' is the set of lines requested if incrementally formatting. absl::Status ReformatMustMatch(absl::string_view original_text, - const LineNumberSet& lines, + const LineNumberSet &lines, absl::string_view formatted_text, absl::string_view reformatted_text); diff --git a/common/lexer/flex_lexer_adapter.h b/common/lexer/flex_lexer_adapter.h index 596dd5ba3..8529aa787 100644 --- a/common/lexer/flex_lexer_adapter.h +++ b/common/lexer/flex_lexer_adapter.h @@ -74,10 +74,10 @@ class FlexLexerAdapter : private CodeStreamHolder, protected L, public Lexer { } // Returns the token associated with the last UpdateLocation() call. - const TokenInfo& GetLastToken() const final { return last_token_; } + const TokenInfo &GetLastToken() const final { return last_token_; } // Returns next token and updates its location. - const TokenInfo& DoNextToken() override { + const TokenInfo &DoNextToken() override { if (at_eof_) { // Do not call yylex(), because that will result in the fatal error: // "fatal flex scanner internal error--end of buffer missed" @@ -129,7 +129,7 @@ class FlexLexerAdapter : private CodeStreamHolder, protected L, public Lexer { } // Overrides yyFlexLexer's implementation to handle unrecognized chars. - void LexerOutput(const char* buf, int size) final { + void LexerOutput(const char *buf, int size) final { VLOG(1) << "LexerOutput: rejected text: \"" << std::string(buf, size) << '\"'; @@ -143,7 +143,7 @@ class FlexLexerAdapter : private CodeStreamHolder, protected L, public Lexer { } // Overrides yyFlexLexer's implementation to do proper error handling. - void LexerError(const char* msg) final { + void LexerError(const char *msg) final { std::cerr << "Fatal LexerError: " << msg; abort(); } diff --git a/common/lexer/lexer.h b/common/lexer/lexer.h index 2d10ab7f0..5c2cfa856 100644 --- a/common/lexer/lexer.h +++ b/common/lexer/lexer.h @@ -26,20 +26,20 @@ class Lexer { public: virtual ~Lexer() = default; - Lexer(const Lexer&) = delete; - Lexer& operator=(const Lexer&) = delete; + Lexer(const Lexer &) = delete; + Lexer &operator=(const Lexer &) = delete; // Returns the last token scanned. - virtual const TokenInfo& GetLastToken() const = 0; + virtual const TokenInfo &GetLastToken() const = 0; // Scan next token and return it. - virtual const TokenInfo& DoNextToken() = 0; + virtual const TokenInfo &DoNextToken() = 0; // Reset lexer to new input. Overrides should discard all previous state. virtual void Restart(absl::string_view) = 0; // Return true if token is a lexical error. - virtual bool TokenIsError(const TokenInfo&) const = 0; + virtual bool TokenIsError(const TokenInfo &) const = 0; protected: Lexer() = default; diff --git a/common/lexer/lexer_test_util.cc b/common/lexer/lexer_test_util.cc index b407ab817..eaf626d89 100644 --- a/common/lexer/lexer_test_util.cc +++ b/common/lexer/lexer_test_util.cc @@ -26,17 +26,17 @@ namespace verible { -void FakeLexer::SetTokensData(const std::vector& tokens) { +void FakeLexer::SetTokensData(const std::vector &tokens) { tokens_ = tokens; tokens_iter_ = tokens_.begin(); } -const TokenInfo& FakeLexer::DoNextToken() { +const TokenInfo &FakeLexer::DoNextToken() { CHECK(tokens_iter_ != tokens_.cend()); return *tokens_iter_++; } -std::ostream& operator<<(std::ostream& stream, const ShowCode& code) { +std::ostream &operator<<(std::ostream &stream, const ShowCode &code) { return stream << " from code:\n" << code.text << "<>"; } diff --git a/common/lexer/lexer_test_util.h b/common/lexer/lexer_test_util.h index 1ce3b0e77..bd273d9c8 100644 --- a/common/lexer/lexer_test_util.h +++ b/common/lexer/lexer_test_util.h @@ -41,10 +41,10 @@ class FakeLexer { protected: explicit FakeLexer() = default; - void SetTokensData(const std::vector& tokens); + void SetTokensData(const std::vector &tokens); public: - const TokenInfo& DoNextToken(); + const TokenInfo &DoNextToken(); protected: std::vector tokens_; @@ -58,11 +58,11 @@ struct ShowCode { absl::string_view text; }; -std::ostream& operator<<(std::ostream&, const ShowCode&); +std::ostream &operator<<(std::ostream &, const ShowCode &); // SimpleTestData is used to verify single token values. struct SimpleTestData { - const char* code; + const char *code; // Check for ignored token, that is, EOF. template @@ -84,9 +84,9 @@ struct SimpleTestData { template void testSingleToken(const int expected_token) const { Lexer lexer(code); - const TokenInfo& next_token(lexer.DoNextToken()); + const TokenInfo &next_token(lexer.DoNextToken()); EXPECT_EQ(expected_token, next_token.token_enum()) << ShowCode{code}; - const TokenInfo& last_token(lexer.DoNextToken()); + const TokenInfo &last_token(lexer.DoNextToken()); EXPECT_EQ(TK_EOF, last_token.token_enum()) << ShowCode{code}; } }; @@ -95,21 +95,21 @@ struct SimpleTestData { // This is useful for testing tokens sensitive to lexer start-conditions. // TODO(b/139743437): phase this out in favor of SynthesizedLexerTestData. struct GenericTestDataSequence { - const char* code; + const char *code; const std::initializer_list expected_tokens; template void test() const { Lexer lexer(code); int i = 0; - for (const auto& expected_token_enum : expected_tokens) { - const TokenInfo& next_token(lexer.DoNextToken()); + for (const auto &expected_token_enum : expected_tokens) { + const TokenInfo &next_token(lexer.DoNextToken()); EXPECT_EQ(expected_token_enum, next_token.token_enum()) << " Code[" << i << "]:" << ShowCode{code} << "\n Last token text: \"" << next_token.text() << "\""; ++i; } - const TokenInfo& last_token(lexer.DoNextToken()); + const TokenInfo &last_token(lexer.DoNextToken()); EXPECT_EQ(TK_EOF, last_token.token_enum()) << " expecting " << (expected_tokens.size() - i) << " more tokens: " << ShowCode{code}; @@ -127,11 +127,11 @@ struct SynthesizedLexerTestData : public TokenInfoTestData { void test() const { Lexer lexer(code); int i = 0; - for (const auto& expected_token : expected_tokens) { + for (const auto &expected_token : expected_tokens) { VerifyExpectedToken(&lexer, expected_token); ++i; } - const TokenInfo& final_token(lexer.DoNextToken()); + const TokenInfo &final_token(lexer.DoNextToken()); EXPECT_EQ(TK_EOF, final_token.token_enum()) << " expecting " << (expected_tokens.size() - i) << " more tokens" << ShowCode{code}; @@ -141,12 +141,12 @@ struct SynthesizedLexerTestData : public TokenInfoTestData { // A single expected_text can span multiple tokens, when we're only checking // string contents, and not checking *how* this excerpt is tokenized. template - void DontCareMultiTokens(Lexer* lexer, + void DontCareMultiTokens(Lexer *lexer, absl::string_view expected_text) const { // Consume tokens and compare string fragments against the // expected_text until the text is fully matched. while (!expected_text.empty()) { - const TokenInfo& next_token = lexer->DoNextToken(); + const TokenInfo &next_token = lexer->DoNextToken(); const size_t token_length = next_token.text().length(); ASSERT_LE(token_length, expected_text.length()) << "\nlast token: " << next_token << ShowCode{code}; @@ -161,8 +161,8 @@ struct SynthesizedLexerTestData : public TokenInfoTestData { // Check lexer output against a single expected_token. template - void VerifyExpectedToken(Lexer* lexer, - const TokenInfo& expected_token) const { + void VerifyExpectedToken(Lexer *lexer, + const TokenInfo &expected_token) const { switch (expected_token.token_enum()) { case ExpectedTokenInfo::kDontCare: DontCareMultiTokens(lexer, expected_token.text()); @@ -171,7 +171,7 @@ struct SynthesizedLexerTestData : public TokenInfoTestData { return; default: // Compare full TokenInfo, enum, text (exact range). - const TokenInfo& next_token = lexer->DoNextToken(); + const TokenInfo &next_token = lexer->DoNextToken(); EXPECT_EQ(expected_token, next_token) << ShowCode{code}; } } @@ -186,8 +186,8 @@ inline constexpr SingleCharTok SingleChar{}; // Test for ignored tokens. template void TestLexer(std::initializer_list test_data, - const IgnoredText& not_used) { - for (const auto& test_case : test_data) { + const IgnoredText ¬_used) { + for (const auto &test_case : test_data) { test_case.testIgnored(); } } @@ -195,8 +195,8 @@ void TestLexer(std::initializer_list test_data, // Test for single-character tokens (returned value == that character). template void TestLexer(std::initializer_list test_data, - const SingleCharTok& not_used) { - for (const auto& test_case : test_data) { + const SingleCharTok ¬_used) { + for (const auto &test_case : test_data) { test_case.testSingleChar(); } } @@ -205,7 +205,7 @@ void TestLexer(std::initializer_list test_data, template void TestLexer(std::initializer_list test_data, const int expected_token) { - for (const auto& test_case : test_data) { + for (const auto &test_case : test_data) { test_case.testSingleToken(expected_token); } } @@ -213,7 +213,7 @@ void TestLexer(std::initializer_list test_data, // Test for sequences of expected tokens. template void TestLexer(std::initializer_list test_data) { - for (const auto& test_case : test_data) { + for (const auto &test_case : test_data) { test_case.test(); } } @@ -221,7 +221,7 @@ void TestLexer(std::initializer_list test_data) { // Test for sequences of expected tokens. template void TestLexer(std::initializer_list test_data) { - for (const auto& test_case : test_data) { + for (const auto &test_case : test_data) { test_case.test(); } } diff --git a/common/lexer/token_stream_adapter.cc b/common/lexer/token_stream_adapter.cc index 566d39dab..c7351735a 100644 --- a/common/lexer/token_stream_adapter.cc +++ b/common/lexer/token_stream_adapter.cc @@ -21,18 +21,18 @@ namespace verible { -TokenGenerator MakeTokenGenerator(Lexer* l) { +TokenGenerator MakeTokenGenerator(Lexer *l) { return [=]() { return l->DoNextToken(); }; } absl::Status MakeTokenSequence( - Lexer* lexer, absl::string_view text, TokenSequence* tokens, - const std::function& error_token_handler) { + Lexer *lexer, absl::string_view text, TokenSequence *tokens, + const std::function &error_token_handler) { // TODO(fangism): provide a Lexer interface to grab all tokens en masse, // which would save virtual function dispatch overhead. lexer->Restart(text); do { - const auto& new_token = lexer->DoNextToken(); + const auto &new_token = lexer->DoNextToken(); tokens->push_back(new_token); if (lexer->TokenIsError(new_token)) { // one more virtual function call error_token_handler(new_token); diff --git a/common/lexer/token_stream_adapter.h b/common/lexer/token_stream_adapter.h index 7b8dc492c..65a9e5437 100644 --- a/common/lexer/token_stream_adapter.h +++ b/common/lexer/token_stream_adapter.h @@ -31,18 +31,18 @@ namespace verible { // Creates a TokenInfo generator from a Lexer object. -TokenGenerator MakeTokenGenerator(Lexer* l); +TokenGenerator MakeTokenGenerator(Lexer *l); // Populates a TokenSequence with lexed tokens. absl::Status MakeTokenSequence( - Lexer* lexer, absl::string_view text, TokenSequence* tokens, - const std::function& error_token_handler); + Lexer *lexer, absl::string_view text, TokenSequence *tokens, + const std::function &error_token_handler); // Generic container-to-iterator-generator adapter. // Once the end is reached, keep returning the end iterator. template std::function MakeConstIteratorStreamer( - const Container& c) { + const Container &c) { auto iter = c.begin(); const auto end = c.end(); return [=]() mutable { @@ -53,7 +53,7 @@ std::function MakeConstIteratorStreamer( // Creates a TokenInfo generator from a sequence of TokenInfo. template -TokenGenerator MakeTokenStreamer(const Container& c) { +TokenGenerator MakeTokenStreamer(const Container &c) { using value_type = typename Container::value_type; static_assert(std::is_same::value, "Container must have TokenInfo elements."); @@ -67,7 +67,7 @@ TokenGenerator MakeTokenStreamer(const Container& c) { // Creates a TokenInfo generator from a sequence of TokenInfo iterators. template -TokenGenerator MakeTokenViewer(const Container& c) { +TokenGenerator MakeTokenViewer(const Container &c) { using value_type = typename Container::value_type; using iter_type = std::iterator_traits; using element_type = typename iter_type::value_type; diff --git a/common/lexer/token_stream_adapter_test.cc b/common/lexer/token_stream_adapter_test.cc index 33e3e9554..1bdab2493 100644 --- a/common/lexer/token_stream_adapter_test.cc +++ b/common/lexer/token_stream_adapter_test.cc @@ -28,13 +28,13 @@ class FakeTokenSequenceLexer : public Lexer, public FakeLexer { public: using FakeLexer::SetTokensData; - const TokenInfo& GetLastToken() const final { return *tokens_iter_; } + const TokenInfo &GetLastToken() const final { return *tokens_iter_; } - const TokenInfo& DoNextToken() final { return FakeLexer::DoNextToken(); } + const TokenInfo &DoNextToken() final { return FakeLexer::DoNextToken(); } void Restart(absl::string_view) final {} - bool TokenIsError(const TokenInfo&) const override { return false; } + bool TokenIsError(const TokenInfo &) const override { return false; } }; TEST(MakeTokenGeneratorTest, Generate) { @@ -65,13 +65,13 @@ TEST(MakeTokenSequenceTest, Sequencer) { lexer.SetTokensData(tokens); TokenSequence receiver; const auto lex_status = - MakeTokenSequence(&lexer, text, &receiver, [](const TokenInfo&) {}); + MakeTokenSequence(&lexer, text, &receiver, [](const TokenInfo &) {}); EXPECT_TRUE(lex_status.ok()); EXPECT_EQ(receiver, TokenSequence(tokens)); } class TheNumberTwoIsErrorLexer : public FakeTokenSequenceLexer { - bool TokenIsError(const TokenInfo& token) const final { + bool TokenIsError(const TokenInfo &token) const final { return token.token_enum() == 2; } }; @@ -89,7 +89,7 @@ TEST(MakeTokenSequenceTest, SequencerWithError) { TokenSequence errors; const auto lex_status = MakeTokenSequence( &lexer, text, &receiver, - [&](const TokenInfo& error_token) { errors.push_back(error_token); }); + [&](const TokenInfo &error_token) { errors.push_back(error_token); }); EXPECT_FALSE(lex_status.ok()); ASSERT_EQ(receiver.size(), 2); // includes error token ASSERT_EQ(errors.size(), 1); diff --git a/common/parser/bison_parser_adapter.h b/common/parser/bison_parser_adapter.h index 614ff1e38..263332b51 100644 --- a/common/parser/bison_parser_adapter.h +++ b/common/parser/bison_parser_adapter.h @@ -38,11 +38,11 @@ namespace verible { // ParseFunc is a yacc/bison generated yyparse() function. -template +template class BisonParserAdapter : public Parser { public: // Filename purely FYI. - BisonParserAdapter(TokenGenerator* token_generator, + BisonParserAdapter(TokenGenerator *token_generator, absl::string_view filename) : Parser(), param_(token_generator, filename) {} @@ -60,7 +60,7 @@ class BisonParserAdapter : public Parser { // More detailed error information is stored inside param_. } - const std::vector& RejectedTokens() const final { + const std::vector &RejectedTokens() const final { return param_.RecoveredSyntaxErrors(); } diff --git a/common/parser/bison_parser_common.cc b/common/parser/bison_parser_common.cc index fff936b1c..324dc4b5a 100644 --- a/common/parser/bison_parser_common.cc +++ b/common/parser/bison_parser_common.cc @@ -28,16 +28,16 @@ namespace verible { // token. This no longer calls yylex(), but insteads pulls a token from a token // stream. 'value' points to yylval in yyparse(), which can be accessed as $1, // $2, ... in the yacc grammar semantic actions. -int LexAdapter(SymbolPtr* value, ParserParam* param) { - const auto& last_token = param->FetchToken(); +int LexAdapter(SymbolPtr *value, ParserParam *param) { + const auto &last_token = param->FetchToken(); value->reset(new SyntaxTreeLeaf(last_token)); return last_token.token_enum(); } // Error-reporting function. // Called by Bison-generated parser when a recognition error occurs. -void ParseError(const ParserParam* param, const char* function_name, - const char* message) { +void ParseError(const ParserParam *param, const char *function_name, + const char *message) { VLOG(1) << param->filename() << ": " << function_name << " error: " << message; // Bison's default and 'verbose' error messages are uninformative. diff --git a/common/parser/bison_parser_common.h b/common/parser/bison_parser_common.h index 801863db0..713bcd676 100644 --- a/common/parser/bison_parser_common.h +++ b/common/parser/bison_parser_common.h @@ -54,11 +54,11 @@ namespace verible { // Calls to yylex() in generated code will be redirected here. -int LexAdapter(SymbolPtr* value, ParserParam* param); +int LexAdapter(SymbolPtr *value, ParserParam *param); // Calls to yyerror() in generated code will be redirected hee. -void ParseError(const ParserParam* param, const char* function_name, - const char* message); +void ParseError(const ParserParam *param, const char *function_name, + const char *message); } // namespace verible @@ -71,13 +71,13 @@ void ParseError(const ParserParam* param, const char* function_name, // Called by Bison-generated parser to get a next token. // TODO(fangism): control yylex prototype using YY_DECL, or embed param inside // FlexLexerAdapter class template. -inline int yylex(verible::SymbolPtr* value, verible::ParserParam* param) { +inline int yylex(verible::SymbolPtr *value, verible::ParserParam *param) { return verible::LexAdapter(value, param); } // Error-reporting function. // Called by Bison-generated parser when a recognition error occurs. -inline void yyerror(verible::ParserParam* param, const char* message) { +inline void yyerror(verible::ParserParam *param, const char *message) { // TODO(fangism): record and accumulate multiple errors with error recovery. // TODO(fangism): pass in ParserParam reference to save errors, and analyze // stack state. This may need to be refactored per-language. diff --git a/common/parser/bison_parser_common_test.cc b/common/parser/bison_parser_common_test.cc index 21fe1e973..d2c64a99a 100644 --- a/common/parser/bison_parser_common_test.cc +++ b/common/parser/bison_parser_common_test.cc @@ -36,13 +36,13 @@ class MockLexer : public Lexer { public: MockLexer() : token_(13, "foo") {} - const TokenInfo& GetLastToken() const final { return token_; } + const TokenInfo &GetLastToken() const final { return token_; } - const TokenInfo& DoNextToken() final { return token_; } + const TokenInfo &DoNextToken() final { return token_; } void Restart(absl::string_view) final {} - bool TokenIsError(const TokenInfo&) const final { return false; } + bool TokenIsError(const TokenInfo &) const final { return false; } private: TokenInfo token_; @@ -55,14 +55,14 @@ TEST(BisonParserCommonTest, LexTest) { ParserParam parser_param(&generator, ""); SymbolPtr value; const int token_enum = verible::LexAdapter(&value, &parser_param); - const TokenInfo& t(parser_param.GetLastToken()); + const TokenInfo &t(parser_param.GetLastToken()); EXPECT_EQ(13, token_enum); EXPECT_EQ(13, t.token_enum()); EXPECT_EQ(t.text(), "foo"); EXPECT_EQ(value->Kind(), SymbolKind::kLeaf); - const auto* value_ptr = down_cast(value.get()); + const auto *value_ptr = down_cast(value.get()); ASSERT_NE(value_ptr, nullptr); - const TokenInfo& tref(value_ptr->get()); + const TokenInfo &tref(value_ptr->get()); EXPECT_EQ(13, tref.token_enum()); EXPECT_EQ(tref.text(), "foo"); } diff --git a/common/parser/parse.h b/common/parser/parse.h index 7d44333a5..c9a87910a 100644 --- a/common/parser/parse.h +++ b/common/parser/parse.h @@ -35,16 +35,16 @@ class Parser { virtual ConcreteSyntaxTree TakeRoot() = 0; // Return the collection of rejected tokens from recovered syntax errors. - virtual const std::vector& RejectedTokens() const = 0; + virtual const std::vector &RejectedTokens() const = 0; virtual ~Parser() = default; protected: Parser() = default; - public: // Deleted should be public. - Parser(const Parser&) = delete; // disallow copy - Parser& operator=(const Parser&) = delete; // disallow assign + public: // Deleted should be public. + Parser(const Parser &) = delete; // disallow copy + Parser &operator=(const Parser &) = delete; // disallow assign }; } // namespace verible diff --git a/common/parser/parser_param.cc b/common/parser/parser_param.cc index 911d75c9e..2c3aef090 100644 --- a/common/parser/parser_param.cc +++ b/common/parser/parser_param.cc @@ -29,7 +29,7 @@ namespace verible { -ParserParam::ParserParam(TokenGenerator* token_stream, +ParserParam::ParserParam(TokenGenerator *token_stream, absl::string_view filename) : token_stream_(token_stream), filename_(filename), @@ -38,28 +38,28 @@ ParserParam::ParserParam(TokenGenerator* token_stream, ParserParam::~ParserParam() = default; -const TokenInfo& ParserParam::FetchToken() { +const TokenInfo &ParserParam::FetchToken() { last_token_ = (*token_stream_)(); return last_token_; } -void ParserParam::RecordSyntaxError(const SymbolPtr& symbol_ptr) { - const auto* leaf = down_cast(symbol_ptr.get()); +void ParserParam::RecordSyntaxError(const SymbolPtr &symbol_ptr) { + const auto *leaf = down_cast(symbol_ptr.get()); const auto token = leaf->get(); VLOG(1) << filename_ << ": recovered syntax error: " << token; recovered_syntax_errors_.push_back(token); } template -static void move_stack(T** raw_stack, const int64_t* size, - std::vector* stack) { +static void move_stack(T **raw_stack, const int64_t *size, + std::vector *stack) { stack->resize(*size); std::move(*raw_stack, *raw_stack + *size, stack->begin()); } // See bison_parser_common.h for use of this (yyoverflow). -void ParserParam::ResizeStacksInternal(bison_state_int_type** state_stack, - SymbolPtr** value_stack, int64_t* size) { +void ParserParam::ResizeStacksInternal(bison_state_int_type **state_stack, + SymbolPtr **value_stack, int64_t *size) { if (state_stack_.empty()) { // This is the first reallocation case. move_stack(state_stack, size, &state_stack_); diff --git a/common/parser/parser_param.h b/common/parser/parser_param.h index aacec4384..2c7105c0d 100644 --- a/common/parser/parser_param.h +++ b/common/parser/parser_param.h @@ -43,22 +43,22 @@ class ParserParam { public: // The "filename" is merely to have better error messages, it is purely // FYI, does not change processing. - ParserParam(TokenGenerator* token_stream, absl::string_view filename); + ParserParam(TokenGenerator *token_stream, absl::string_view filename); ~ParserParam(); - const TokenInfo& FetchToken(); + const TokenInfo &FetchToken(); - const TokenInfo& GetLastToken() const { return last_token_; } + const TokenInfo &GetLastToken() const { return last_token_; } // Save a copy of the offending token before bison error-recovery // discards it. - void RecordSyntaxError(const SymbolPtr& symbol_ptr); + void RecordSyntaxError(const SymbolPtr &symbol_ptr); // Filename being processed, if known. absl::string_view filename() const { return filename_; } - const std::vector& RecoveredSyntaxErrors() const { + const std::vector &RecoveredSyntaxErrors() const { return recovered_syntax_errors_; } @@ -70,8 +70,8 @@ class ParserParam { // New bison (at least 3.5) define the size type to be ptrdiff_t, while old // bisons use size_t. Be compatible with any reasonable long-ish type. template - void ResizeStacks(bison_state_int_type** state_stack, SymbolPtr** value_stack, - SizeType* size) { + void ResizeStacks(bison_state_int_type **state_stack, SymbolPtr **value_stack, + SizeType *size) { int64_t s = *size; ResizeStacksInternal(state_stack, value_stack, &s); *size = s; @@ -89,15 +89,15 @@ class ParserParam { void SetRoot(ConcreteSyntaxTree r) { root_ = std::move(r); } private: - void ResizeStacksInternal(bison_state_int_type** state_stack, - SymbolPtr** value_stack, int64_t* size); + void ResizeStacksInternal(bison_state_int_type **state_stack, + SymbolPtr **value_stack, int64_t *size); // Container of syntax-rejected tokens. // TODO(fangism): Pair this with recovery token, the point at which // error-recovery is complete and parsing resumes (for diagnostic purposes). std::vector recovered_syntax_errors_; - TokenGenerator* const token_stream_; + TokenGenerator *const token_stream_; const std::string filename_; TokenInfo last_token_; @@ -109,8 +109,8 @@ class ParserParam { size_t max_used_stack_size_; public: // deleted member functions: public. - ParserParam(const ParserParam&) = delete; - ParserParam& operator=(const ParserParam&) = delete; + ParserParam(const ParserParam &) = delete; + ParserParam &operator=(const ParserParam &) = delete; }; } // namespace verible diff --git a/common/parser/parser_test_util.h b/common/parser/parser_test_util.h index 8ed5c9814..178ed3744 100644 --- a/common/parser/parser_test_util.h +++ b/common/parser/parser_test_util.h @@ -40,7 +40,7 @@ void TestParserAcceptValid(absl::string_view code, int i) { absl::Status status = analyzer.Analyze(); if (!status.ok()) { // Print more detailed error message. - const auto& rejected_tokens = analyzer.GetRejectedTokens(); + const auto &rejected_tokens = analyzer.GetRejectedTokens(); if (!rejected_tokens.empty()) { EXPECT_TRUE(status.ok()) << "Rejected valid code:\n" @@ -56,7 +56,7 @@ void TestParserAcceptValid(absl::string_view code, int i) { // class AnalyzerType is any class with a absl::Status AnalyzerType::Analyze() // method. template -void TestParserRejectInvalid(const TokenInfoTestData& test, int i) { +void TestParserRejectInvalid(const TokenInfoTestData &test, int i) { VLOG(1) << "test_data[" << i << "] = '" << test.code << "'\n"; ASSERT_FALSE(test.expected_tokens.empty()); // Find the first not-don't-care token. @@ -67,14 +67,14 @@ void TestParserRejectInvalid(const TokenInfoTestData& test, int i) { EXPECT_FALSE(status.ok()) << "Accepted invalid code (iteration: " << iteration << "):\n" << test.code; - const auto& rejected_tokens = analyzer.GetRejectedTokens(); + const auto &rejected_tokens = analyzer.GetRejectedTokens(); ASSERT_FALSE(rejected_tokens.empty()); const absl::string_view base_text = analyzer.Data().Contents(); const auto expected_error_tokens = test.FindImportantTokens(base_text); ASSERT_FALSE(expected_error_tokens.empty()); // Only check the first rejected token, ignore the rest. - const auto& expected_error_token = expected_error_tokens.front(); + const auto &expected_error_token = expected_error_tokens.front(); EXPECT_EQ(expected_error_token, rejected_tokens[0].token_info); ++iteration; // Run the analyzer a second time to make sure the parser cleared @@ -91,7 +91,7 @@ struct ErrorRecoveryTestCase { }; template -void TestParserErrorRecovered(const ErrorRecoveryTestCase& test, int i) { +void TestParserErrorRecovered(const ErrorRecoveryTestCase &test, int i) { VLOG(1) << "test_data[" << i << "] = '" << test.code << "'\n"; int iteration = 0; do { @@ -103,7 +103,7 @@ void TestParserErrorRecovered(const ErrorRecoveryTestCase& test, int i) { const auto rejected_tokens = analyzer.GetRejectedTokens(); EXPECT_FALSE(rejected_tokens.empty()); // Only check the first rejected token, ignore the rest. - const auto& tree = analyzer.SyntaxTree(); + const auto &tree = analyzer.SyntaxTree(); const auto matching_paths = matcher::GetAllDescendantsFromPath( *ABSL_DIE_IF_NULL(tree), test.tree_path); EXPECT_FALSE(matching_paths.empty()) @@ -124,10 +124,10 @@ void TestParserAllMatched(absl::string_view code, int i) { EXPECT_TRUE(status.ok()) << status.message() << "\nRejected: " << analyzer.GetRejectedTokens().front().token_info; - const Symbol* tree_ptr = analyzer.SyntaxTree().get(); + const Symbol *tree_ptr = analyzer.SyntaxTree().get(); EXPECT_NE(tree_ptr, nullptr) << "Missing syntax tree with input:\n" << code; if (tree_ptr == nullptr) return; // Already failed, abort this test case. - const Symbol& root = *tree_ptr; + const Symbol &root = *tree_ptr; ParserVerifier verifier(root, analyzer.Data().GetTokenStreamView()); const auto unmatched = verifier.Verify(); diff --git a/common/strings/comment_utils_test.cc b/common/strings/comment_utils_test.cc index b7d7ba5b2..4cd00e808 100644 --- a/common/strings/comment_utils_test.cc +++ b/common/strings/comment_utils_test.cc @@ -23,7 +23,7 @@ namespace { struct TestData { absl::string_view input; - const char* expect; + const char *expect; }; // Test that non-comments are left unmodified. @@ -42,7 +42,7 @@ TEST(StripCommentTest, NotComment) { "**/", // not a comment "/*/", }; - for (const auto& data : test_cases) { + for (const auto &data : test_cases) { EXPECT_EQ(StripComment(data), data); EXPECT_TRUE(IsSubRange(StripComment(data), data)); } @@ -59,7 +59,7 @@ TEST(StripCommentTest, EndlineComment) { {"//foo", "foo"}, {"//foo\nabc", "foo\nabc"}, }; - for (const auto& data : test_cases) { + for (const auto &data : test_cases) { EXPECT_EQ(StripComment(data.input), data.expect) << "input: \"" << data.input << "\""; EXPECT_TRUE(IsSubRange(StripComment(data.input), data.input)); @@ -77,7 +77,7 @@ TEST(StripCommentTest, BlockComment) { {"/* zzz */", " zzz "}, // keeps spaces {"/**jkl****/", "jkl"}, }; - for (const auto& data : test_cases) { + for (const auto &data : test_cases) { EXPECT_EQ(StripComment(data.input), data.expect) << "input: \"" << data.input << "\""; EXPECT_TRUE(IsSubRange(StripComment(data.input), data.input)); @@ -111,7 +111,7 @@ TEST(StripCommentAndSpacePaddingTest, StripsSpaces) { {"/****qqq bbb.******/", "qqq bbb."}, {"/****\n** qqq\n** bbb\n******/", "** qqq\n** bbb"}, }; - for (const auto& data : test_cases) { + for (const auto &data : test_cases) { EXPECT_EQ(StripCommentAndSpacePadding(data.input), data.expect) << "input: \"" << data.input << "\""; EXPECT_TRUE(IsSubRange(StripComment(data.input), data.input)); diff --git a/common/strings/diff.cc b/common/strings/diff.cc index e62983ba6..4b066cfd3 100644 --- a/common/strings/diff.cc +++ b/common/strings/diff.cc @@ -50,16 +50,16 @@ LineDiffs::LineDiffs(absl::string_view before, absl::string_view after) after_lines.begin(), after_lines.end())) {} template -static std::ostream& PrintLineRange(std::ostream& stream, char op, Iter start, +static std::ostream &PrintLineRange(std::ostream &stream, char op, Iter start, Iter end) { - for (const auto& line : make_range(start, end)) { + for (const auto &line : make_range(start, end)) { stream << op << line; } return stream; } -std::ostream& LineDiffs::PrintEdit(std::ostream& stream, - const Edit& edit) const { +std::ostream &LineDiffs::PrintEdit(std::ostream &stream, + const Edit &edit) const { const char op = EditOperationToLineMarker(edit.operation); if (edit.operation == Operation::INSERT) { PrintLineRange(stream, op, after_lines.begin() + edit.start, @@ -74,16 +74,16 @@ std::ostream& LineDiffs::PrintEdit(std::ostream& stream, return stream; } -std::ostream& operator<<(std::ostream& stream, const LineDiffs& diffs) { - for (const auto& edit : diffs.edits) { +std::ostream &operator<<(std::ostream &stream, const LineDiffs &diffs) { + for (const auto &edit : diffs.edits) { diffs.PrintEdit(stream, edit); } return stream; } -LineNumberSet DiffEditsToAddedLineNumbers(const Edits& edits) { +LineNumberSet DiffEditsToAddedLineNumbers(const Edits &edits) { LineNumberSet added_lines; - for (const auto& edit : edits) { + for (const auto &edit : edits) { if (edit.operation == Operation::INSERT) { // Add 1 to convert from 0-indexed to 1-indexed. added_lines.Add( @@ -93,12 +93,12 @@ LineNumberSet DiffEditsToAddedLineNumbers(const Edits& edits) { return added_lines; } -std::vector DiffEditsToPatchHunks(const diff::Edits& edits, +std::vector DiffEditsToPatchHunks(const diff::Edits &edits, int common_context) { const int split_threshold = common_context * 2; std::vector hunks(1); // start with 1 empty destination vector - for (const diff::Edit& edit : edits) { - auto& current_hunk = hunks.back(); + for (const diff::Edit &edit : edits) { + auto ¤t_hunk = hunks.back(); if (edit.operation == Operation::EQUALS) { const int edit_size = edit.end - edit.start; if (current_hunk.empty()) { @@ -135,7 +135,7 @@ std::vector DiffEditsToPatchHunks(const diff::Edits& edits, // The last hunk may have been started before knowing it was the last one. // Remove if it is a no-op. - const auto& last_hunk = hunks.back(); // hunks is always non-empty + const auto &last_hunk = hunks.back(); // hunks is always non-empty if (last_hunk.size() == 1 && last_hunk.front().operation == Operation::EQUALS) { // This last hunk's only element is an Operation::EQUALS (no-change), @@ -144,8 +144,8 @@ std::vector DiffEditsToPatchHunks(const diff::Edits& edits, } // Trim excess EQUALS tail edits in each hunk. - for (auto& hunk : hunks) { - auto& tail = hunk.back(); + for (auto &hunk : hunks) { + auto &tail = hunk.back(); if (tail.operation == Operation::EQUALS) { if (tail.end - tail.start > common_context) { tail.end = tail.start + common_context; @@ -155,7 +155,7 @@ std::vector DiffEditsToPatchHunks(const diff::Edits& edits, return hunks; } -void LineDiffsToUnifiedDiff(std::ostream& stream, const LineDiffs& linediffs, +void LineDiffsToUnifiedDiff(std::ostream &stream, const LineDiffs &linediffs, unsigned common_context, absl::string_view file_a, absl::string_view file_b) { const std::vector chunks = @@ -174,11 +174,11 @@ void LineDiffsToUnifiedDiff(std::ostream& stream, const LineDiffs& linediffs, } int added_lines_count = 0; - for (const auto& chunk : chunks) { + for (const auto &chunk : chunks) { int chunk_before_lines_count = 0; int chunk_added_lines_count = 0; - for (const auto& edit : chunk) { + for (const auto &edit : chunk) { if (edit.operation == Operation::INSERT) { chunk_added_lines_count += edit.end - edit.start; } else if (edit.operation == Operation::DELETE) { @@ -200,7 +200,7 @@ void LineDiffsToUnifiedDiff(std::ostream& stream, const LineDiffs& linediffs, added_lines_count += chunk_added_lines_count; - for (const auto& edit : chunk) { + for (const auto &edit : chunk) { linediffs.PrintEdit(stream, edit); // Last line from either original or new text, and final '\n' is missing? diff --git a/common/strings/diff.h b/common/strings/diff.h index aeedab91d..51d751a66 100644 --- a/common/strings/diff.h +++ b/common/strings/diff.h @@ -42,15 +42,15 @@ struct LineDiffs { // Computes the line-difference between before_text and after_text. LineDiffs(absl::string_view before_text, absl::string_view after_text); - std::ostream& PrintEdit(std::ostream&, const diff::Edit&) const; + std::ostream &PrintEdit(std::ostream &, const diff::Edit &) const; }; // Prints a monolithic single-hunk unified-diff. -std::ostream& operator<<(std::ostream&, const LineDiffs& diffs); +std::ostream &operator<<(std::ostream &, const LineDiffs &diffs); // Translates diff::Edits to an interval-set representation. // diff::Edits are 0-indexed, but the returned line numbers will be 1-indexed. -LineNumberSet DiffEditsToAddedLineNumbers(const diff::Edits&); +LineNumberSet DiffEditsToAddedLineNumbers(const diff::Edits &); // Divides a single edit-sequence (that covers two whole sequences) into // subsequences of of edits ("patch hunks") that skip over unchanged sections. @@ -75,10 +75,10 @@ LineNumberSet DiffEditsToAddedLineNumbers(const diff::Edits&); // // This function could be upstreamed to the editscript library because it is // agnostic to the type being diff-ed. -std::vector DiffEditsToPatchHunks(const diff::Edits& edits, +std::vector DiffEditsToPatchHunks(const diff::Edits &edits, int common_context); -void LineDiffsToUnifiedDiff(std::ostream& stream, const LineDiffs& linediffs, +void LineDiffsToUnifiedDiff(std::ostream &stream, const LineDiffs &linediffs, unsigned common_context, absl::string_view file_a = {}, absl::string_view file_b = {}); diff --git a/common/strings/diff_test.cc b/common/strings/diff_test.cc index 6530a993f..5ca6666bc 100644 --- a/common/strings/diff_test.cc +++ b/common/strings/diff_test.cc @@ -23,7 +23,7 @@ namespace diff { // Print functions copied from external_libs/editscript_test.cc -std::ostream& operator<<(std::ostream& out, Operation operation) { +std::ostream &operator<<(std::ostream &out, Operation operation) { switch (operation) { case Operation::EQUALS: return (out << "EQUALS"); @@ -35,15 +35,15 @@ std::ostream& operator<<(std::ostream& out, Operation operation) { return out; } -std::ostream& operator<<(std::ostream& out, const diff::Edit& edit) { +std::ostream &operator<<(std::ostream &out, const diff::Edit &edit) { out << "{" << edit.operation << ",[" << edit.start << "," << edit.end << ")}"; return out; } -std::ostream& operator<<(std::ostream& out, const Edits& edits) { +std::ostream &operator<<(std::ostream &out, const Edits &edits) { out << "Edits{"; std::string outer_delim; - for (auto& edit : edits) { + for (auto &edit : edits) { out << outer_delim << edit; outer_delim = ","; } @@ -113,7 +113,7 @@ TEST(LineDiffsTest, Various) { "+gandalf\n" " pippin\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { const LineDiffs line_diffs(test.before, test.after); std::ostringstream stream; @@ -151,7 +151,7 @@ TEST(DiffEditsToAddedLineNumbersTest, Various) { {Operation::INSERT, 6, 11}}, // {{3, 5}, {7, 12}}}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { EXPECT_EQ(DiffEditsToAddedLineNumbers(test.edits), test.expected_line_numbers); } @@ -186,10 +186,10 @@ struct RelativeEdit { // // (This is currently well-suited for a test-only library, but // could eventually become a crucial piece of future diff-to-patch-library.) -diff::Edits MakeDiffEdits(const std::vector& relative_edits, +diff::Edits MakeDiffEdits(const std::vector &relative_edits, int64_t old_index = 0, int64_t new_index = 0) { diff::Edits edits; - for (const RelativeEdit& edit : relative_edits) { + for (const RelativeEdit &edit : relative_edits) { if (!edits.empty() && edits.back().operation == edit.operation) { // same type as previous operation, just combine them. edits.back().end += edit.size; @@ -338,7 +338,7 @@ TEST(MakeDiffEditsTest, Various) { {Operation::EQUALS, 17, 25}, }}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { EXPECT_THAT(MakeDiffEdits(test.rel_edits), ElementsAreArray(test.expected_edits)); } @@ -511,7 +511,7 @@ TEST(DiffEditsToPatchHunksTest, Various) { 5, 4), }}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { EXPECT_THAT(DiffEditsToPatchHunks(test.whole_edits, test.common_context), ElementsAreArray(test.expected_hunks)); } @@ -801,7 +801,7 @@ TEST(LineDiffsToUnifiedDiffTest, Various) { }, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { LineDiffs linediffs(test.before_text, test.after_text); std::ostringstream stream; LineDiffsToUnifiedDiff(stream, linediffs, test.common_context, test.file_a, diff --git a/common/strings/display_utils.cc b/common/strings/display_utils.cc index 173ba5cab..420a5d250 100644 --- a/common/strings/display_utils.cc +++ b/common/strings/display_utils.cc @@ -21,7 +21,7 @@ namespace verible { static constexpr absl::string_view kEllipses = "..."; -std::ostream& operator<<(std::ostream& stream, const AutoTruncate& trunc) { +std::ostream &operator<<(std::ostream &stream, const AutoTruncate &trunc) { const auto text = trunc.text; const int length = text.length(); if (length <= trunc.max_chars) return stream << text; @@ -33,7 +33,7 @@ std::ostream& operator<<(std::ostream& stream, const AutoTruncate& trunc) { << text.substr(tail_start, tail_length); } -std::ostream& operator<<(std::ostream& stream, const EscapeString& vis) { +std::ostream &operator<<(std::ostream &stream, const EscapeString &vis) { for (const unsigned char c : vis.text) { switch (c) { case '\a': @@ -76,7 +76,7 @@ std::ostream& operator<<(std::ostream& stream, const EscapeString& vis) { return stream; } -std::ostream& operator<<(std::ostream& stream, const VisualizeWhitespace& vis) { +std::ostream &operator<<(std::ostream &stream, const VisualizeWhitespace &vis) { for (const char c : vis.text) { switch (c) { case ' ': diff --git a/common/strings/display_utils.h b/common/strings/display_utils.h index 243e338e6..d29ea1380 100644 --- a/common/strings/display_utils.h +++ b/common/strings/display_utils.h @@ -35,7 +35,7 @@ struct AutoTruncate { const int max_chars; }; -std::ostream& operator<<(std::ostream&, const AutoTruncate& trunc); +std::ostream &operator<<(std::ostream &, const AutoTruncate &trunc); // To help visualize strings with non-alphanumeric characters, this stream // adapter prints special characters escaped using C escape sequences, without @@ -48,7 +48,7 @@ struct EscapeString { explicit EscapeString(absl::string_view text) : text(text) {} }; -std::ostream& operator<<(std::ostream&, const EscapeString& vis); +std::ostream &operator<<(std::ostream &, const EscapeString &vis); // To help visualize strings that consist of whitespace, this stream adapter // prints spaces, tabs, and newlines with alternate text, without modifying or @@ -72,7 +72,7 @@ struct VisualizeWhitespace { tab_alt(tab_alt) {} }; -std::ostream& operator<<(std::ostream&, const VisualizeWhitespace& vis); +std::ostream &operator<<(std::ostream &, const VisualizeWhitespace &vis); // TODO(fangism): once C++17 becomes the minimum standard for building // push the following block into an internal namespace, and use auto @@ -87,7 +87,7 @@ std::ostream& operator<<(std::ostream&, const VisualizeWhitespace& vis); // accidentally create conflicting definitions, and violate ODR. template struct SequenceStreamFormatter { - const T& sequence; // binds to object that is to be printed + const T &sequence; // binds to object that is to be printed absl::string_view separator; absl::string_view prefix; absl::string_view suffix; @@ -97,8 +97,8 @@ struct SequenceStreamFormatter { // Redirects stream printing to abs::StrJoin wrapped in a single object. template -std::ostream& operator<<(std::ostream& stream, - const SequenceStreamFormatter& t) { +std::ostream &operator<<(std::ostream &stream, + const SequenceStreamFormatter &t) { return stream << t.prefix << absl::StrJoin(t.sequence.begin(), t.sequence.end(), t.separator, absl::StreamFormatter()) @@ -135,7 +135,7 @@ std::ostream& operator<<(std::ostream& stream, // "< 1 | 2 | 3 | ... >" // template -SequenceStreamFormatter SequenceFormatter(const T& t, +SequenceStreamFormatter SequenceFormatter(const T &t, absl::string_view sep = ", ", absl::string_view prefix = "", absl::string_view suffix = "") { diff --git a/common/strings/display_utils_test.cc b/common/strings/display_utils_test.cc index 03f5c4b39..1b8c4076a 100644 --- a/common/strings/display_utils_test.cc +++ b/common/strings/display_utils_test.cc @@ -44,7 +44,7 @@ TEST(AutoTruncateTest, Various) { {"123!(@*#&)!#$!@#(*xyz", 11, "123!...*xyz"}, {"123!(@*#&)!#$!@#(*xyz", 12, "123!(...*xyz"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { std::ostringstream stream; stream << AutoTruncate{test.input, test.max_chars}; EXPECT_EQ(stream.str(), test.expected); @@ -58,7 +58,7 @@ TEST(VisualizeWhitespaceTest, Various) { {" ", "..."}, {"\n\n\n", "\\\n\\\n\\\n"}, {"\t\t\t", "###"}, {"abc \n\t123", "abc.\\\n#123"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { std::ostringstream stream; stream << VisualizeWhitespace{test.first}; EXPECT_EQ(stream.str(), test.second); @@ -72,7 +72,7 @@ TEST(VisualizeWhitespaceTest, OtherSubstitutions) { {" ", "---"}, {"\n\n\n", "NNN"}, {"\t\t\t", "TTT"}, {"abc \n\t123", "abc-NT123"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { std::ostringstream stream; stream << VisualizeWhitespace{test.first, '-', "N", "T"}; EXPECT_EQ(stream.str(), test.second); @@ -97,7 +97,7 @@ TEST(EscapeStringTest, Various) { {" ~", " ~"}, {"\x7f\x80\xfe\xff", R"(\x7f\x80\xfe\xff)"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { std::ostringstream stream; stream << EscapeString{test.first}; EXPECT_EQ(stream.str(), test.second); @@ -110,7 +110,7 @@ using IntVector = std::vector; // to be shared. // TODO(fangism): Use auto return type with C++17 as minimum standard. static SequenceStreamFormatter AngleBracketFormatter( - const IntVector& t) { + const IntVector &t) { return SequenceFormatter(t, " | ", "< ", " >"); } diff --git a/common/strings/line_column_map.cc b/common/strings/line_column_map.cc index 199ce5dc3..f72eeadb7 100644 --- a/common/strings/line_column_map.cc +++ b/common/strings/line_column_map.cc @@ -28,11 +28,11 @@ namespace verible { // Print to the user as 1-based index because that is how lines // and columns are indexed in every file diagnostic tool. -std::ostream& operator<<(std::ostream& out, const LineColumn& line_column) { +std::ostream &operator<<(std::ostream &out, const LineColumn &line_column) { return out << line_column.line + 1 << ':' << line_column.column + 1; } -std::ostream& operator<<(std::ostream& out, const LineColumnRange& r) { +std::ostream &operator<<(std::ostream &out, const LineColumnRange &r) { // Unlike 'technical' representation where we point the end pos one past // the relevant range, for human consumption we want to point to the last // character. @@ -70,9 +70,9 @@ LineColumnMap::LineColumnMap(absl::string_view text) { // Constructor that calculates line break offsets given an already-split // set of lines for a body of text. -LineColumnMap::LineColumnMap(const std::vector& lines) { +LineColumnMap::LineColumnMap(const std::vector &lines) { size_t offset = 0; - for (const auto& line : lines) { + for (const auto &line : lines) { beginning_of_line_offsets_.push_back(offset); offset += line.length() + 1; } diff --git a/common/strings/line_column_map.h b/common/strings/line_column_map.h index 51c3e0031..54a041318 100644 --- a/common/strings/line_column_map.h +++ b/common/strings/line_column_map.h @@ -38,33 +38,33 @@ struct LineColumn { int line; // 0-based index int column; // 0-based index - constexpr bool operator==(const LineColumn& r) const { + constexpr bool operator==(const LineColumn &r) const { return line == r.line && column == r.column; } - constexpr bool operator<(const LineColumn& r) const { + constexpr bool operator<(const LineColumn &r) const { if (line < r.line) return true; if (line > r.line) return false; return column < r.column; } - constexpr bool operator>=(const LineColumn& r) const { return !(*this < r); } + constexpr bool operator>=(const LineColumn &r) const { return !(*this < r); } }; -std::ostream& operator<<(std::ostream&, const LineColumn&); +std::ostream &operator<<(std::ostream &, const LineColumn &); // A complete range. struct LineColumnRange { LineColumn start; // Inclusive LineColumn end; // Exclusive - constexpr bool operator==(const LineColumnRange& r) const { + constexpr bool operator==(const LineColumnRange &r) const { return start == r.start && end == r.end; } - constexpr bool PositionInRange(const LineColumn& pos) const { + constexpr bool PositionInRange(const LineColumn &pos) const { return pos >= start && pos < end; } }; -std::ostream& operator<<(std::ostream&, const LineColumnRange&); +std::ostream &operator<<(std::ostream &, const LineColumnRange &); // Fast mapping of substring position to human-useful line/column class LineColumnMap { @@ -72,7 +72,7 @@ class LineColumnMap { // Build line column map from pre-split contiguous blob of content. // The distance between consecutive string_views is expected to have // a gap of one character (the splitting '\n' character). - explicit LineColumnMap(const std::vector& lines); + explicit LineColumnMap(const std::vector &lines); // This constructor is only used in LintStatusFormatter and // LintWaiverBuilder. @@ -102,7 +102,7 @@ class LineColumnMap { // been considered. LineColumn GetLineColAtOffset(absl::string_view base, int bytes_offset) const; - const std::vector& GetBeginningOfLineOffsets() const { + const std::vector &GetBeginningOfLineOffsets() const { return beginning_of_line_offsets_; } diff --git a/common/strings/line_column_map_test.cc b/common/strings/line_column_map_test.cc index cfde13b15..102f0ea15 100644 --- a/common/strings/line_column_map_test.cc +++ b/common/strings/line_column_map_test.cc @@ -28,12 +28,12 @@ namespace { struct LineColumnTestData { LineColumn line_col; - const char* text; + const char *text; }; struct LineColumnRangeTestData { LineColumnRange range; - const char* text; + const char *text; }; struct LineColumnQuery { @@ -42,7 +42,7 @@ struct LineColumnQuery { }; struct LineColumnMapTestData { - const char* text; + const char *text; std::vector expected_offsets; std::vector queries; }; @@ -77,7 +77,7 @@ TEST(LineColumnTextTest, PrintLineColumn) { {{1, 0}, "2:1"}, {{10, 8}, "11:9"}, }; - for (const auto& test_case : text_test_data) { + for (const auto &test_case : text_test_data) { std::ostringstream oss; oss << test_case.line_col; EXPECT_EQ(oss.str(), test_case.text); @@ -93,7 +93,7 @@ TEST(LineColumnTextTest, PrintLineColumnRange) { {{{10, 8}, {10, 9}}, "11:9:"}, // Single character range {{{10, 8}, {10, 8}}, "11:9:"}, // Empty range. }; - for (const auto& test_case : text_test_data) { + for (const auto &test_case : text_test_data) { std::ostringstream oss; oss << test_case.range; EXPECT_EQ(oss.str(), test_case.text); @@ -112,7 +112,7 @@ TEST(LineColumnMapTest, OffsetAtLine) { // This test verifies the offsets where columns are reset to 0, // which happens after every newline. TEST(LineColumnMapTest, Offsets) { - for (const auto& test_case : map_test_data) { + for (const auto &test_case : map_test_data) { const LineColumnMap line_map(test_case.text); EXPECT_EQ(line_map.GetBeginningOfLineOffsets(), test_case.expected_offsets) << "Text: \"" << test_case.text << "\""; @@ -122,7 +122,7 @@ TEST(LineColumnMapTest, Offsets) { // This tests that computing offsets from pre-split lines is consistent // with the constructor that takes the whole text string. TEST(LineColumnMapTest, OffsetsFromLines) { - for (const auto& test_case : map_test_data) { + for (const auto &test_case : map_test_data) { const LineColumnMap line_map(test_case.text); std::vector lines = absl::StrSplit(test_case.text, '\n'); const LineColumnMap alt_line_map(lines); @@ -153,7 +153,7 @@ TEST(LineColumnMapTest, EndOffsetVarious) { {"aaaa\nbbb\n", 9}, // {"\n\n", 2}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { const LineColumnMap map(test.text); EXPECT_EQ(map.LastLineOffset(), test.expected_offset) << "text:\n" << test.text; @@ -162,9 +162,9 @@ TEST(LineColumnMapTest, EndOffsetVarious) { // This test verifies the translation from byte-offset to line-column. TEST(LineColumnMapTest, Lookup) { - for (const auto& test_case : map_test_data) { + for (const auto &test_case : map_test_data) { const LineColumnMap line_map(test_case.text); - for (const auto& q : test_case.queries) { + for (const auto &q : test_case.queries) { EXPECT_EQ(q.line_col, line_map.GetLineColAtOffset(test_case.text, q.offset)) << "Text: \"" << test_case.text << "\"\n" diff --git a/common/strings/mem_block.h b/common/strings/mem_block.h index 6f7803d5a..0261d53db 100644 --- a/common/strings/mem_block.h +++ b/common/strings/mem_block.h @@ -33,23 +33,23 @@ class MemBlock { MemBlock() = default; public: - MemBlock(const MemBlock&) = delete; - MemBlock(MemBlock&&) = delete; - MemBlock& operator=(const MemBlock&) = delete; - MemBlock& operator=(MemBlock&&) = delete; + MemBlock(const MemBlock &) = delete; + MemBlock(MemBlock &&) = delete; + MemBlock &operator=(const MemBlock &) = delete; + MemBlock &operator=(MemBlock &&) = delete; }; // An implementation of MemBlock backed by a std::string class StringMemBlock final : public MemBlock { public: StringMemBlock() = default; - explicit StringMemBlock(std::string&& move_from) : content_(move_from) {} + explicit StringMemBlock(std::string &&move_from) : content_(move_from) {} explicit StringMemBlock(absl::string_view copy_from) : content_(copy_from.begin(), copy_from.end()) {} // Assign/modify content. Use sparingly, ideally only in initialization // as the expectation of the MemBlock is that it won't change later. - std::string* mutable_content() { return &content_; } + std::string *mutable_content() { return &content_; } absl::string_view AsStringView() const final { return content_; } diff --git a/common/strings/naming_utils_test.cc b/common/strings/naming_utils_test.cc index e04344ab0..cf5b433fa 100644 --- a/common/strings/naming_utils_test.cc +++ b/common/strings/naming_utils_test.cc @@ -22,7 +22,7 @@ namespace { // Tests that all strings containing more than just upper case letters, // underscores, and digits are rejected. TEST(IsNameAllCapsUnderscoresDigitsTest, RejectTests) { - static const char* test_cases[] = { + static const char *test_cases[] = { "foo", "HAS A SPACE", "NOT_ALL_UPPERCASe", "MiXeD", "FO?O", "lower", "lower_underscore", }; @@ -34,7 +34,7 @@ TEST(IsNameAllCapsUnderscoresDigitsTest, RejectTests) { // Tests that all strings containing only upper case letters, underscores, and // digits are accepted. TEST(IsNameAllCapsUnderscoresDigitsTest, AcceptTests) { - static const char* test_cases[] = { + static const char *test_cases[] = { "", "FOO", "HAS_UNDERSCORE", "_UNDERSCORE_AT_BEGINNING", "___", "__UPPER__", "_123", "FOO_1", }; @@ -46,7 +46,7 @@ TEST(IsNameAllCapsUnderscoresDigitsTest, AcceptTests) { // Tests that all strings containing underscores not next to digits are // rejected. TEST(AllUnderscoresFollowedByDigitsTest, RejectTests) { - static const char* test_cases[] = { + static const char *test_cases[] = { "Hello_World", "_H1", "Hello_", "1_", "Foo1_Bar", "Fo_1_o", "_", "Hello__1", "Hello__World", "__1", }; @@ -57,7 +57,7 @@ TEST(AllUnderscoresFollowedByDigitsTest, RejectTests) { // Tests that all strings containing underscores next to a digit are accepted. TEST(AllUnderscoresFollowedByDigitsTest, AcceptTests) { - static const char* test_cases[] = { + static const char *test_cases[] = { "", "Foo_1", "Foo_1_1", @@ -71,7 +71,7 @@ TEST(AllUnderscoresFollowedByDigitsTest, AcceptTests) { // Tests that all strings not following UpperCamelCase naming convention are // rejected. TEST(IsUpperCamelCaseWithDigitsTest, RejectTests) { - static const char* test_cases[] = { + static const char *test_cases[] = { "Hello_World", "hello_world", "helloworld", "helloWorld", "Hello_1_World", "Hello__1", "Foo_", "_Foo", "_1", "__Foo", }; @@ -83,7 +83,7 @@ TEST(IsUpperCamelCaseWithDigitsTest, RejectTests) { // Tests that all strings following UpperCamelCase naming convention are // accepted. TEST(IsUpperCamelCaseWithDigitsTest, AcceptTests) { - static const char* test_cases[] = { + static const char *test_cases[] = { "", "HelloWorld", "Foo_1", @@ -100,7 +100,7 @@ TEST(IsUpperCamelCaseWithDigitsTest, AcceptTests) { // Tests that all strings following lower_snake_case naming convention are // accepted. TEST(IsLowerSnakeCaseWithDigitsTest, AcceptTests) { - static const char* test_cases[] = { + static const char *test_cases[] = { "", "hello_world", "hello_1_world", "hello_1", "hello_world_1_1", "hello1", "hello_", }; @@ -112,7 +112,7 @@ TEST(IsLowerSnakeCaseWithDigitsTest, AcceptTests) { // Tests that all strings not following lower_snake_case naming convention are // rejected. TEST(IsLowerSnakeCaseWithDigitsTest, RejectTests) { - static const char* test_cases[] = { + static const char *test_cases[] = { "_1", "__hello", "Hello_world", "hello_1_World", "hello_1W", "HelloWorld", "helLo1_", }; diff --git a/common/strings/obfuscator.cc b/common/strings/obfuscator.cc index e3582caa6..5c4a5b709 100644 --- a/common/strings/obfuscator.cc +++ b/common/strings/obfuscator.cc @@ -33,10 +33,10 @@ bool Obfuscator::encode(absl::string_view key, absl::string_view value) { absl::string_view Obfuscator::operator()(absl::string_view input) { if (decode_mode_) { - const auto* p = translator_.find_reverse(input); + const auto *p = translator_.find_reverse(input); return (p != nullptr) ? *p : input; } - const std::string* str = translator_.insert_using_value_generator( + const std::string *str = translator_.insert_using_value_generator( std::string(input), [this, input]() { return generator_(input); }); return *str; } @@ -45,7 +45,7 @@ constexpr char kPairSeparator = ' '; std::string Obfuscator::save() const { std::ostringstream stream; - for (const auto& pair : translator_.forward_view()) { + for (const auto &pair : translator_.forward_view()) { stream << pair.first << kPairSeparator << *pair.second << "\n"; } return stream.str(); @@ -54,7 +54,7 @@ std::string Obfuscator::save() const { absl::Status Obfuscator::load(absl::string_view mapping) { const std::vector lines = absl::StrSplit(mapping, '\n', absl::SkipEmpty()); - for (const auto& line : lines) { + for (const auto &line : lines) { const std::vector elements = absl::StrSplit(absl::StripAsciiWhitespace(line), kPairSeparator); if (elements.size() < 2) { diff --git a/common/strings/obfuscator.h b/common/strings/obfuscator.h index cdc6974ab..d7e961ac5 100644 --- a/common/strings/obfuscator.h +++ b/common/strings/obfuscator.h @@ -44,7 +44,7 @@ class Obfuscator { using translator_type = BijectiveMap; - explicit Obfuscator(const generator_type& g) : generator_(g) {} + explicit Obfuscator(const generator_type &g) : generator_(g) {} // Declares a mapping from key-string to value-string that will be // used in obfuscation. This is useful for applying previously used @@ -61,7 +61,7 @@ class Obfuscator { absl::string_view operator()(absl::string_view input); // Read-only view of string translation map. - const translator_type& GetTranslator() const { return translator_; } + const translator_type &GetTranslator() const { return translator_; } // Parses a mapping dictionary, and pre-loads the translator map with it. // Format: one entry per line, each line is space-separated pair of @@ -90,7 +90,7 @@ class IdentifierObfuscator : public Obfuscator { public: // Tip for users of this: use something like RandomEqualLengthIdentifier, // but also make sure to not accidentally generate any of your keywords. - explicit IdentifierObfuscator(const generator_type& g) : Obfuscator(g) {} + explicit IdentifierObfuscator(const generator_type &g) : Obfuscator(g) {} // Same as inherited method, but verifies that key and value are equal length. bool encode(absl::string_view key, absl::string_view value); diff --git a/common/strings/obfuscator_test.cc b/common/strings/obfuscator_test.cc index 41359c52c..c4be497a7 100644 --- a/common/strings/obfuscator_test.cc +++ b/common/strings/obfuscator_test.cc @@ -32,7 +32,7 @@ static char Rot13(char c) { // Non-random generator, just for the sake of testing. static std::string RotateGenerator(absl::string_view input) { std::string s(input); - for (auto& ch : s) ch = Rot13(ch); + for (auto &ch : s) ch = Rot13(ch); return s; } @@ -43,7 +43,7 @@ TEST(ObfuscatorTest, Construction) { TEST(ObfuscatorTest, Transform) { Obfuscator ob(RotateGenerator); - const auto& tran = ob.GetTranslator(); + const auto &tran = ob.GetTranslator(); // repeat same string for (int i = 0; i < 2; ++i) { const auto str = ob("cat"); @@ -66,7 +66,7 @@ TEST(ObfuscatorTest, Transform) { TEST(ObfuscatorTest, Encode) { Obfuscator ob(RotateGenerator); ob.encode("cat", "sheep"); - const auto& tran = ob.GetTranslator(); + const auto &tran = ob.GetTranslator(); EXPECT_EQ(tran.size(), 1); EXPECT_EQ(*ABSL_DIE_IF_NULL(tran.find_forward("cat")), "sheep"); EXPECT_EQ(*ABSL_DIE_IF_NULL(tran.find_reverse("sheep")), "cat"); @@ -158,7 +158,7 @@ TEST(ObfuscatorTest, LoadMap) { TEST(IdentifierObfuscatorTest, Transform) { IdentifierObfuscator ob(RandomEqualLengthIdentifier); - const auto& tran = ob.GetTranslator(); + const auto &tran = ob.GetTranslator(); // repeat same string for (int i = 0; i < 2; ++i) { const auto str = ob("cat"); // str is random @@ -188,7 +188,7 @@ TEST(IdentifierObfuscatorTest, EncodeInvalid) { TEST(IdentifierObfuscatorTest, EncodeValidTransform) { IdentifierObfuscator ob(RandomEqualLengthIdentifier); ob.encode("cat", "cow"); - const auto& tran = ob.GetTranslator(); + const auto &tran = ob.GetTranslator(); // repeat same string for (int i = 0; i < 2; ++i) { const auto str = ob("cat"); diff --git a/common/strings/patch.cc b/common/strings/patch.cc index 35e3fd2e2..5de558a0b 100644 --- a/common/strings/patch.cc +++ b/common/strings/patch.cc @@ -56,7 +56,7 @@ static bool IsValidMarkedLine(absl::string_view line) { namespace internal { template -static std::vector IteratorsToRanges(const std::vector& iters) { +static std::vector IteratorsToRanges(const std::vector &iters) { // TODO(fangism): This pattern appears elsewhere in the codebase, so refactor. CHECK_GE(iters.size(), 2); std::vector result; @@ -78,7 +78,7 @@ absl::Status MarkedLine::Parse(absl::string_view text) { return absl::OkStatus(); } -std::ostream& operator<<(std::ostream& stream, const MarkedLine& line) { +std::ostream &operator<<(std::ostream &stream, const MarkedLine &line) { const term::Color c = line.IsDeleted() ? term::Color::kRed : line.IsAdded() ? term::Color::kCyan : term::Color::kNone; @@ -103,7 +103,7 @@ absl::Status HunkIndices::Parse(absl::string_view text) { return absl::OkStatus(); } -std::ostream& operator<<(std::ostream& stream, const HunkIndices& indices) { +std::ostream &operator<<(std::ostream &stream, const HunkIndices &indices) { return stream << indices.FormatToString(); } @@ -152,7 +152,7 @@ absl::Status HunkHeader::Parse(absl::string_view text) { return absl::OkStatus(); } -std::ostream& operator<<(std::ostream& stream, const HunkHeader& header) { +std::ostream &operator<<(std::ostream &stream, const HunkHeader &header) { return term::Colored( stream, absl::StrCat("@@ -", header.old_range.FormatToString(), " +", @@ -162,10 +162,10 @@ std::ostream& operator<<(std::ostream& stream, const HunkHeader& header) { // Type M could be any container or range of MarkedLines. template -static void CountMarkedLines(const M& lines, int* before, int* after) { +static void CountMarkedLines(const M &lines, int *before, int *after) { *before = 0; *after = 0; - for (const MarkedLine& line : lines) { + for (const MarkedLine &line : lines) { switch (line.Marker()) { case ' ': // line is common to both, unchanged ++*before; @@ -205,7 +205,7 @@ void Hunk::UpdateHeader() { LineNumberSet Hunk::AddedLines() const { LineNumberSet line_numbers; int line_number = header_.new_range.start; - for (const MarkedLine& line : lines_) { + for (const MarkedLine &line : lines_) { if (line.IsAdded()) line_numbers.Add(line_number); if (!line.IsDeleted()) ++line_number; } @@ -214,9 +214,9 @@ LineNumberSet Hunk::AddedLines() const { } absl::Status Hunk::VerifyAgainstOriginalLines( - const std::vector& original_lines) const { + const std::vector &original_lines) const { int line_number = header_.old_range.start; // 1-indexed - for (const MarkedLine& line : lines_) { + for (const MarkedLine &line : lines_) { if (line.IsAdded()) continue; // ignore added lines if (line_number > static_cast(original_lines.size())) { return absl::OutOfRangeError(absl::StrCat( @@ -239,7 +239,7 @@ class HunkSplitter { public: HunkSplitter() = default; - bool operator()(const MarkedLine& line) { + bool operator()(const MarkedLine &line) { if (previous_line_ == nullptr) { // first line previous_line_ = &line; @@ -251,7 +251,7 @@ class HunkSplitter { } private: - const MarkedLine* previous_line_ = nullptr; + const MarkedLine *previous_line_ = nullptr; }; std::vector Hunk::Split() const { @@ -269,7 +269,7 @@ std::vector Hunk::Split() const { if (cut_points.back() != lines_.begin()) { const bool last_partition_has_any_changes = std::any_of(cut_points.back(), lines_.end(), - [](const MarkedLine& m) { return !m.IsCommon(); }); + [](const MarkedLine &m) { return !m.IsCommon(); }); if (!last_partition_has_any_changes) cut_points.pop_back(); } cut_points.push_back(lines_.end()); // always terminate partitions with end() @@ -283,10 +283,10 @@ std::vector Hunk::Split() const { // create sub hunks from each sub-range int old_starting_line = header_.old_range.start; int new_starting_line = header_.new_range.start; - for (const MarkedLineRange& marked_line_range : ranges) { + for (const MarkedLineRange &marked_line_range : ranges) { sub_hunks.emplace_back(old_starting_line, new_starting_line, marked_line_range.begin(), marked_line_range.end()); - const HunkHeader& recent_header(sub_hunks.back().Header()); + const HunkHeader &recent_header(sub_hunks.back().Header()); old_starting_line += recent_header.old_range.count; new_starting_line += recent_header.new_range.count; } @@ -295,29 +295,29 @@ std::vector Hunk::Split() const { return sub_hunks; } -absl::Status Hunk::Parse(const LineRange& hunk_lines) { +absl::Status Hunk::Parse(const LineRange &hunk_lines) { RETURN_IF_ERROR(header_.Parse(hunk_lines.front())); LineRange body(hunk_lines); body.pop_front(); // remove the header lines_.resize(body.size()); auto line_iter = lines_.begin(); - for (const auto& line : body) { + for (const auto &line : body) { RETURN_IF_ERROR(line_iter->Parse(line)); ++line_iter; } return IsValid(); } -std::ostream& Hunk::Print(std::ostream& stream) const { +std::ostream &Hunk::Print(std::ostream &stream) const { stream << header_ << std::endl; - for (const MarkedLine& line : lines_) { + for (const MarkedLine &line : lines_) { stream << line << std::endl; } return stream; } -std::ostream& operator<<(std::ostream& stream, const Hunk& hunk) { +std::ostream &operator<<(std::ostream &stream, const Hunk &hunk) { return hunk.Print(stream); } @@ -339,14 +339,14 @@ absl::Status SourceInfo::Parse(absl::string_view text) { return absl::OkStatus(); } -std::ostream& operator<<(std::ostream& stream, const SourceInfo& info) { +std::ostream &operator<<(std::ostream &stream, const SourceInfo &info) { stream << info.path; if (!info.timestamp.empty()) stream << '\t' << info.timestamp; return stream; } static absl::Status ParseSourceInfoWithMarker( - SourceInfo* info, absl::string_view line, + SourceInfo *info, absl::string_view line, absl::string_view expected_marker) { StringSpliterator splitter(line); absl::string_view marker = splitter(' '); @@ -364,13 +364,13 @@ bool FilePatch::IsDeletedFile() const { return new_file_.path == "/dev/null"; } LineNumberSet FilePatch::AddedLines() const { LineNumberSet line_numbers; - for (const Hunk& hunk : hunks_) { + for (const Hunk &hunk : hunks_) { line_numbers.Union(hunk.AddedLines()); } return line_numbers; } -static char PromptHunkAction(std::istream& ins, std::ostream& outs) { +static char PromptHunkAction(std::istream &ins, std::ostream &outs) { // Suppress prompt in noninteractive mode. term::bold(outs, "Apply this hunk? [y,n,a,d,s,q,?] "); char c; @@ -385,21 +385,21 @@ static char PromptHunkAction(std::istream& ins, std::ostream& outs) { } absl::Status FilePatch::VerifyAgainstOriginalLines( - const std::vector& original_lines) const { - for (const Hunk& hunk : hunks_) { + const std::vector &original_lines) const { + for (const Hunk &hunk : hunks_) { RETURN_IF_ERROR(hunk.VerifyAgainstOriginalLines(original_lines)); } return absl::OkStatus(); } -absl::Status FilePatch::PickApplyInPlace(std::istream& ins, - std::ostream& outs) const { +absl::Status FilePatch::PickApplyInPlace(std::istream &ins, + std::ostream &outs) const { return PickApply(ins, outs, &file::GetContentAsString, &file::SetContents); } -absl::Status FilePatch::PickApply(std::istream& ins, std::ostream& outs, - const FileReaderFunction& file_reader, - const FileWriterFunction& file_writer) const { +absl::Status FilePatch::PickApply(std::istream &ins, std::ostream &outs, + const FileReaderFunction &file_reader, + const FileWriterFunction &file_writer) const { if (IsDeletedFile()) return absl::OkStatus(); // ignore if (IsNewFile()) return absl::OkStatus(); // ignore @@ -430,10 +430,10 @@ absl::Status FilePatch::PickApply(std::istream& ins, std::ostream& outs, std::deque hunks_worklist(hunks_.begin(), hunks_.end()); // copy-fill while (!hunks_worklist.empty()) { VLOG(1) << "hunks remaining: " << hunks_worklist.size(); - const Hunk& hunk(hunks_worklist.front()); + const Hunk &hunk(hunks_worklist.front()); // Copy over unchanged lines before this hunk. - const auto& old_range = hunk.Header().old_range; + const auto &old_range = hunk.Header().old_range; if (old_range.start < last_consumed_line) { return absl::InvalidArgumentError( absl::StrCat("Hunks are not properly ordered. last_consumed_line=", @@ -442,7 +442,7 @@ absl::Status FilePatch::PickApply(std::istream& ins, std::ostream& outs, } for (; last_consumed_line < old_range.start - 1; ++last_consumed_line) { CHECK_LT(last_consumed_line, static_cast(orig_lines.size())); - const absl::string_view& line(orig_lines[last_consumed_line]); + const absl::string_view &line(orig_lines[last_consumed_line]); output_lines.emplace_back(line.begin(), line.end()); // copy string } VLOG(1) << "copied up to (!including) line[" << last_consumed_line << "]."; @@ -462,7 +462,7 @@ absl::Status FilePatch::PickApply(std::istream& ins, std::ostream& outs, } case 'y': { // accept this hunk, copy lines over - for (const MarkedLine& marked_line : hunk.MarkedLines()) { + for (const MarkedLine &marked_line : hunk.MarkedLines()) { if (!marked_line.IsDeleted()) { const absl::string_view line(marked_line.Text()); output_lines.emplace_back(line.begin(), line.end()); // copy string @@ -485,7 +485,7 @@ absl::Status FilePatch::PickApply(std::istream& ins, std::ostream& outs, const auto sub_hunks = hunk.Split(); hunks_worklist.pop_front(); // replace current hunk with sub-hunks // maintain sequential order of sub-hunks in the queue by line number - for (const auto& sub_hunk : verible::reversed_view(sub_hunks)) { + for (const auto &sub_hunk : verible::reversed_view(sub_hunks)) { hunks_worklist.push_front(sub_hunk); } continue; // for-loop @@ -511,7 +511,7 @@ absl::Status FilePatch::PickApply(std::istream& ins, std::ostream& outs, // Copy over remaining lines after the last hunk. for (; last_consumed_line < static_cast(orig_lines.size()); ++last_consumed_line) { - const absl::string_view& line(orig_lines[last_consumed_line]); + const absl::string_view &line(orig_lines[last_consumed_line]); output_lines.emplace_back(line.begin(), line.end()); // copy string } VLOG(1) << "copied reamining lines up to [" << last_consumed_line << "]."; @@ -521,7 +521,7 @@ absl::Status FilePatch::PickApply(std::istream& ins, std::ostream& outs, return file_writer(old_file_.path, rewrite_contents); } -absl::Status FilePatch::Parse(const LineRange& lines) { +absl::Status FilePatch::Parse(const LineRange &lines) { LineIterator line_iter( std::find_if(lines.begin(), lines.end(), &LineMarksOldFile)); if (lines.begin() == lines.end() || line_iter == lines.end()) { @@ -529,7 +529,7 @@ absl::Status FilePatch::Parse(const LineRange& lines) { "Expected a file marker starting with \"---\", but did not find one."); } // Lines leading up to the old file marker "---" are metadata. - for (const auto& line : make_range(lines.begin(), line_iter)) { + for (const auto &line : make_range(lines.begin(), line_iter)) { metadata_.emplace_back(line); } @@ -560,26 +560,26 @@ absl::Status FilePatch::Parse(const LineRange& lines) { hunks_.resize(hunk_ranges.size()); auto hunk_iter = hunks_.begin(); - for (const auto& hunk_range : hunk_ranges) { + for (const auto &hunk_range : hunk_ranges) { RETURN_IF_ERROR(hunk_iter->Parse(hunk_range)); ++hunk_iter; } return absl::OkStatus(); } -std::ostream& FilePatch::Print(std::ostream& stream) const { - for (const std::string& line : metadata_) { +std::ostream &FilePatch::Print(std::ostream &stream) const { + for (const std::string &line : metadata_) { stream << line << std::endl; } stream << "--- " << old_file_ << '\n' // << "+++ " << new_file_ << std::endl; - for (const Hunk& hunk : hunks_) { + for (const Hunk &hunk : hunks_) { stream << hunk; } return stream; } -std::ostream& operator<<(std::ostream& stream, const FilePatch& patch) { +std::ostream &operator<<(std::ostream &stream, const FilePatch &patch) { return patch.Print(stream); } @@ -611,10 +611,10 @@ absl::Status PatchSet::Parse(absl::string_view patch_contents) { if (file_patch_begins.empty()) return absl::OkStatus(); // Move line iterators back to correct starting points. - for (auto& iter : file_patch_begins) { + for (auto &iter : file_patch_begins) { while (iter != lines_range.begin()) { const auto prev = std::prev(iter); - const absl::string_view& peek(*prev); + const absl::string_view &peek(*prev); if (LineBelongsToPreviousSection(peek)) break; iter = prev; } @@ -625,7 +625,7 @@ absl::Status PatchSet::Parse(absl::string_view patch_contents) { } // Record metadata lines, if there are any. - for (const auto& line : + for (const auto &line : make_range(lines_range.begin(), file_patch_begins.front())) { metadata_.emplace_back(line); } @@ -635,7 +635,7 @@ absl::Status PatchSet::Parse(absl::string_view patch_contents) { internal::IteratorsToRanges(file_patch_begins)); file_patches_.resize(file_patch_ranges.size()); auto iter = file_patches_.begin(); - for (const auto& range : file_patch_ranges) { + for (const auto &range : file_patch_ranges) { RETURN_IF_ERROR(iter->Parse(range)); ++iter; } @@ -645,11 +645,11 @@ absl::Status PatchSet::Parse(absl::string_view patch_contents) { return absl::OkStatus(); } -std::ostream& PatchSet::Render(std::ostream& stream) const { - for (const auto& line : metadata_) { +std::ostream &PatchSet::Render(std::ostream &stream) const { + for (const auto &line : metadata_) { stream << line << std::endl; } - for (const internal::FilePatch& file_patch : file_patches_) { + for (const internal::FilePatch &file_patch : file_patches_) { stream << file_patch; } return stream; @@ -657,9 +657,9 @@ std::ostream& PatchSet::Render(std::ostream& stream) const { FileLineNumbersMap PatchSet::AddedLinesMap(bool new_file_ranges) const { FileLineNumbersMap result; - for (const internal::FilePatch& file_patch : file_patches_) { + for (const internal::FilePatch &file_patch : file_patches_) { if (file_patch.IsDeletedFile()) continue; - LineNumberSet& entry = result[file_patch.NewFileInfo().path]; + LineNumberSet &entry = result[file_patch.NewFileInfo().path]; if (file_patch.IsNewFile() && !new_file_ranges) { entry.clear(); } else { @@ -669,22 +669,22 @@ FileLineNumbersMap PatchSet::AddedLinesMap(bool new_file_ranges) const { return result; } -absl::Status PatchSet::PickApplyInPlace(std::istream& ins, - std::ostream& outs) const { +absl::Status PatchSet::PickApplyInPlace(std::istream &ins, + std::ostream &outs) const { return PickApply(ins, outs, &file::GetContentAsString, &file::SetContents); } absl::Status PatchSet::PickApply( - std::istream& ins, std::ostream& outs, - const internal::FileReaderFunction& file_reader, - const internal::FileWriterFunction& file_writer) const { - for (const internal::FilePatch& file_patch : file_patches_) { + std::istream &ins, std::ostream &outs, + const internal::FileReaderFunction &file_reader, + const internal::FileWriterFunction &file_writer) const { + for (const internal::FilePatch &file_patch : file_patches_) { RETURN_IF_ERROR(file_patch.PickApply(ins, outs, file_reader, file_writer)); } return absl::OkStatus(); } -std::ostream& operator<<(std::ostream& stream, const PatchSet& patch) { +std::ostream &operator<<(std::ostream &stream, const PatchSet &patch) { return patch.Render(stream); } diff --git a/common/strings/patch.h b/common/strings/patch.h index ae139db65..f1677efd0 100644 --- a/common/strings/patch.h +++ b/common/strings/patch.h @@ -58,7 +58,7 @@ class PatchSet { absl::Status Parse(absl::string_view patch_contents); // Prints a unified-diff formatted output. - std::ostream& Render(std::ostream& stream) const; + std::ostream &Render(std::ostream &stream) const; // Returns a map that indicates which lines in each // file are new (in patch files, these are hunk lines starting with '+'). @@ -71,13 +71,13 @@ class PatchSet { // Interactively prompt user to select hunks to apply in-place. // 'ins' is the stream from which user-input is read, // and 'outs' is the stream that displays text and prompts to the user. - absl::Status PickApplyInPlace(std::istream& ins, std::ostream& outs) const; + absl::Status PickApplyInPlace(std::istream &ins, std::ostream &outs) const; protected: // For testing, allow mocking out of file I/O. - absl::Status PickApply(std::istream& ins, std::ostream& outs, - const internal::FileReaderFunction& file_reader, - const internal::FileWriterFunction& file_writer) const; + absl::Status PickApply(std::istream &ins, std::ostream &outs, + const internal::FileReaderFunction &file_reader, + const internal::FileWriterFunction &file_writer) const; private: // Non-patch plain text that could describe the origins of the diff/patch, @@ -90,7 +90,7 @@ class PatchSet { std::vector file_patches_; }; -std::ostream& operator<<(std::ostream&, const PatchSet&); +std::ostream &operator<<(std::ostream &, const PatchSet &); // Private implementation details follow. namespace internal { @@ -129,30 +129,30 @@ struct MarkedLine { absl::string_view Text() const { return {&line[1], line.length() - 1}; } // default equality operator - bool operator==(const MarkedLine& other) const { return line == other.line; } - bool operator!=(const MarkedLine& other) const { return !(*this == other); } + bool operator==(const MarkedLine &other) const { return line == other.line; } + bool operator!=(const MarkedLine &other) const { return !(*this == other); } absl::Status Parse(absl::string_view); }; -std::ostream& operator<<(std::ostream&, const MarkedLine&); +std::ostream &operator<<(std::ostream &, const MarkedLine &); struct HunkIndices { int start; // starting line number for a hunk, 1-based int count; // number of lines to expect in this hunk // default equality operator - bool operator==(const HunkIndices& other) const { + bool operator==(const HunkIndices &other) const { return start == other.start && count == other.count; } - bool operator!=(const HunkIndices& other) const { return !(*this == other); } + bool operator!=(const HunkIndices &other) const { return !(*this == other); } std::string FormatToString() const; absl::Status Parse(absl::string_view); }; -std::ostream& operator<<(std::ostream&, const HunkIndices&); +std::ostream &operator<<(std::ostream &, const HunkIndices &); struct HunkHeader { HunkIndices old_range; @@ -162,22 +162,22 @@ struct HunkHeader { std::string context; // default equality operator - bool operator==(const HunkHeader& other) const { + bool operator==(const HunkHeader &other) const { return old_range == other.old_range && new_range == other.new_range && context == other.context; } - bool operator!=(const HunkHeader& other) const { return !(*this == other); } + bool operator!=(const HunkHeader &other) const { return !(*this == other); } absl::Status Parse(absl::string_view); }; -std::ostream& operator<<(std::ostream&, const HunkHeader&); +std::ostream &operator<<(std::ostream &, const HunkHeader &); // One unit of a file change. class Hunk { public: Hunk() = default; - Hunk(const Hunk&) = default; + Hunk(const Hunk &) = default; template Hunk(int old_starting_line, int new_starting_line, Iter begin, Iter end) @@ -191,9 +191,9 @@ class Hunk { // MarkedLines. absl::Status IsValid() const; - const HunkHeader& Header() const { return header_; } + const HunkHeader &Header() const { return header_; } - const std::vector& MarkedLines() const { return lines_; } + const std::vector &MarkedLines() const { return lines_; } // If a hunk is modified for any reason, the number of added/removed lines may // have changed, so this will update the .count values. @@ -202,20 +202,20 @@ class Hunk { // Returns a set of line numbers for lines that are changed or new. LineNumberSet AddedLines() const; - absl::Status Parse(const LineRange&); + absl::Status Parse(const LineRange &); - std::ostream& Print(std::ostream&) const; + std::ostream &Print(std::ostream &) const; // Verify consistency of lines in the patch (old-file) against the file that // is read in whole. absl::Status VerifyAgainstOriginalLines( - const std::vector& original_lines) const; + const std::vector &original_lines) const; // default structural comparison - bool operator==(const Hunk& other) const { + bool operator==(const Hunk &other) const { return header_ == other.header_ && lines_ == other.lines_; } - bool operator!=(const Hunk& other) const { return !(*this == other); } + bool operator!=(const Hunk &other) const { return !(*this == other); } // Splits this Hunk into smaller ones at the points of common context. // Returns array of hunks. If this hunk can no longer be split, then it is @@ -230,7 +230,7 @@ class Hunk { std::vector lines_; }; -std::ostream& operator<<(std::ostream&, const Hunk&); +std::ostream &operator<<(std::ostream &, const Hunk &); struct SourceInfo { std::string path; // location to patched file, absolute or relative @@ -239,13 +239,13 @@ struct SourceInfo { absl::Status Parse(absl::string_view); }; -std::ostream& operator<<(std::ostream&, const SourceInfo&); +std::ostream &operator<<(std::ostream &, const SourceInfo &); // Set of changes for a single file. class FilePatch { public: // Initialize data struct from a range of patch lines. - absl::Status Parse(const LineRange&); + absl::Status Parse(const LineRange &); // Returns true if this file is new. bool IsNewFile() const; @@ -253,25 +253,25 @@ class FilePatch { // Returns true if this file is deleted. bool IsDeletedFile() const; - const SourceInfo& NewFileInfo() const { return new_file_; } + const SourceInfo &NewFileInfo() const { return new_file_; } // Returns a set of line numbers for lines that are changed or new. LineNumberSet AddedLines() const; - std::ostream& Print(std::ostream&) const; + std::ostream &Print(std::ostream &) const; // Verify consistency of lines in the patch (old-file) against the file that // is read in whole. absl::Status VerifyAgainstOriginalLines( - const std::vector& original_lines) const; + const std::vector &original_lines) const; - absl::Status PickApplyInPlace(std::istream& ins, std::ostream& outs) const; + absl::Status PickApplyInPlace(std::istream &ins, std::ostream &outs) const; // For testing with mocked-out file I/O. // Public to allow use by PatchSet::PickApply(). - absl::Status PickApply(std::istream& ins, std::ostream& outs, - const FileReaderFunction& file_reader, - const FileWriterFunction& file_writer) const; + absl::Status PickApply(std::istream &ins, std::ostream &outs, + const FileReaderFunction &file_reader, + const FileWriterFunction &file_writer) const; private: // These are lines of informational text only, such as how the diff was @@ -282,7 +282,7 @@ class FilePatch { std::vector hunks_; }; -std::ostream& operator<<(std::ostream&, const FilePatch&); +std::ostream &operator<<(std::ostream &, const FilePatch &); } // namespace internal diff --git a/common/strings/patch_test.cc b/common/strings/patch_test.cc index dcae74cba..a35f5a7ee 100644 --- a/common/strings/patch_test.cc +++ b/common/strings/patch_test.cc @@ -36,10 +36,10 @@ namespace internal { namespace { static std::vector MakeMarkedLines( - const std::vector& lines) { + const std::vector &lines) { std::vector result; result.reserve(lines.size()); - for (const auto& line : lines) { + for (const auto &line : lines) { result.emplace_back(line); } return result; @@ -62,7 +62,7 @@ TEST(MarkedLineParseTest, InvalidInputs) { constexpr absl::string_view kTestCases[] = { "", "x", "x213", "abc", "diff", "====", }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { MarkedLine m; EXPECT_FALSE(m.Parse(test).ok()) << " input: \"" << test << '"'; } @@ -81,7 +81,7 @@ TEST(MarkedLineParseTest, ValidInputs) { {"- abc", '-', " abc"}, {"+ abc", '+', " abc"}, {"---", '-', "--"}, {"+++", '+', "++"}, {"-", '-', ""}, {"+", '+', ""}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { MarkedLine m; EXPECT_TRUE(m.Parse(test.input).ok()) << " input: \"" << test.input << '"'; EXPECT_EQ(m.Marker(), test.expected_mark); @@ -93,7 +93,7 @@ TEST(MarkedLinePrintTest, Print) { constexpr absl::string_view kTestCases[] = { " ", "+", "-", " 1 2 3", "-xyz", "+\tabc", }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { MarkedLine m; const auto status = m.Parse(test); ASSERT_TRUE(status.ok()) << status.message(); @@ -115,7 +115,7 @@ TEST(HunkIndicesParseTest, InvalidInputs) { constexpr absl::string_view kTestCases[] = { "", ",", "4,", ",5", "2,b", "x,2", "4,5,", "1,2,3", }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { HunkIndices h; EXPECT_FALSE(h.Parse(test).ok()) << " input: \"" << test << '"'; } @@ -132,7 +132,7 @@ TEST(HunkIndicesParseAndPrintTest, ValidInputs) { {"1,1", 1, 1}, {"14,92", 14, 92}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { HunkIndices h; EXPECT_TRUE(h.Parse(test.input).ok()) << " input: \"" << test.input << '"'; EXPECT_EQ(h.start, test.expected_start); @@ -235,7 +235,7 @@ TEST(SourceInfoParseTest, InvalidInputs) { constexpr absl::string_view kTestCases[] = { "", // path must be non-empty }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { SourceInfo info; EXPECT_FALSE(info.Parse(test).ok()) << " input: \"" << test << '"'; } @@ -247,7 +247,7 @@ TEST(SourceInfoParseAndPrintTest, ValidInputsPathOnly) { "p/q/a.txt", "/p/q/a.txt", }; - for (const auto& path : kPaths) { + for (const auto &path : kPaths) { SourceInfo info; EXPECT_TRUE(info.Parse(path).ok()); EXPECT_EQ(info.path, path); @@ -272,8 +272,8 @@ TEST(SourceInfoParseAndPrintTest, ValidInputsWithTimestamps) { "2020-02-02 20:22:02.000000", "2020-02-02 20:22:02.000000 -0700", }; - for (const auto& path : kPaths) { - for (const auto& time : kTimes) { + for (const auto &path : kPaths) { + for (const auto &time : kTimes) { SourceInfo info; const std::string text(absl::StrCat(path, "\t", time)); EXPECT_TRUE(info.Parse(text).ok()); @@ -333,7 +333,7 @@ TEST(HunkParseTest, InvalidInputs) { // missing: " ..." }, }; - for (const auto& lines : kTestCases) { + for (const auto &lines : kTestCases) { Hunk hunk; const LineRange range(lines.begin(), lines.end()); EXPECT_FALSE(hunk.Parse(range).ok()); @@ -364,7 +364,7 @@ TEST(HunkUpdateHeaderTest, Various) { {"@@ -222,4 +333,3 @@", {" common", "-removed", "-removed2", "+added", " common again"}}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { std::vector lines; lines.push_back(kNonsenseHeader); lines.insert(lines.end(), test.payload.begin(), test.payload.end()); @@ -484,7 +484,7 @@ TEST(HunkAddedLinesTest, Various) { {{402, 404}, {406, 407}, {410, 412}}, }, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { const LineRange range(test.hunk_text.begin(), test.hunk_text.end()); Hunk hunk; const auto status = hunk.Parse(range); @@ -537,7 +537,7 @@ TEST(HunkSplitTest, ExpectedSingletons) { " same more context", // " same"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { const std::vector lines(MakeMarkedLines(test)); // can pick any starting line numbers, doesn't matter const Hunk hunk(10, 12, lines.begin(), lines.end()); @@ -554,11 +554,11 @@ struct ExpectedHunk { }; static std::vector MakeExpectedHunks( - const Hunk& original, const std::vector& hunk_infos) { - const auto& marked_lines = original.MarkedLines(); + const Hunk &original, const std::vector &hunk_infos) { + const auto &marked_lines = original.MarkedLines(); std::vector results; results.reserve(hunk_infos.size()); - for (const auto& hunk_info : hunk_infos) { + for (const auto &hunk_info : hunk_infos) { results.emplace_back( hunk_info.old_starting_line, hunk_info.new_starting_line, marked_lines.begin() + hunk_info.marked_line_offsets.first, @@ -573,8 +573,8 @@ struct HunkSplitTestCase { std::vector expected_sub_hunks; HunkSplitTestCase(int old_starting_line, int new_starting_line, - const std::vector& lines, - const std::vector& sub_hunks) + const std::vector &lines, + const std::vector &sub_hunks) : marked_lines(MakeMarkedLines(lines)), original_hunk(old_starting_line, new_starting_line, marked_lines.begin(), marked_lines.end()), @@ -679,7 +679,7 @@ TEST(HunkSplitTest, MultipleSubHunks) { {14, 15, {7, 10}}, }), }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { EXPECT_THAT(test.original_hunk.Split(), ElementsAreArray(test.expected_sub_hunks)); } @@ -710,7 +710,7 @@ TEST(HunkParseAndPrintTest, ValidInputs) { "+ and then like whoa", // " common line2"}, }; - for (const auto& lines : kTestCases) { + for (const auto &lines : kTestCases) { Hunk hunk; const LineRange range(lines.begin(), lines.end()); const auto status = hunk.Parse(range); @@ -833,7 +833,7 @@ TEST(FilePatchParseTest, InvalidInputs) { "malformed line does not begin with [ -+]", }, }; - for (const auto& lines : kTestCases) { + for (const auto &lines : kTestCases) { const LineRange range(lines.begin(), lines.end()); FilePatch file_patch; EXPECT_FALSE(file_patch.Parse(range).ok()) << "lines:\n" @@ -905,7 +905,7 @@ TEST(FilePatchParseAndPrintTest, ValidInputs) { " no change here", }, }; - for (const auto& lines : kTestCases) { + for (const auto &lines : kTestCases) { const LineRange range(lines.begin(), lines.end()); FilePatch file_patch; const auto status = file_patch.Parse(range); @@ -1017,7 +1017,7 @@ TEST(FilePatchAddedLinesTest, Various) { {{44, 46}, {81, 82}}, }, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { const LineRange range(test.hunk_text.begin(), test.hunk_text.end()); FilePatch file_patch; const auto status = file_patch.Parse(range); @@ -1028,7 +1028,7 @@ TEST(FilePatchAddedLinesTest, Various) { class FilePatchPickApplyTest : public FilePatch, public ::testing::Test { protected: - absl::Status ParseLines(const std::vector& lines) { + absl::Status ParseLines(const std::vector &lines) { const LineRange range(lines.begin(), lines.end()); return Parse(range); } @@ -1053,7 +1053,7 @@ struct StringFile { class StringFileSequence { public: - explicit StringFileSequence(const std::vector& files) + explicit StringFileSequence(const std::vector &files) : files_(files) {} StringFileSequence(std::initializer_list files) : files_(files) {} @@ -1067,7 +1067,7 @@ class StringFileSequence { // Can be passed anywhere that takes a FileReaderFunction. // TODO(fangism): move this to a "file_test_util" library. struct ReadStringFileSequence : public StringFileSequence { - explicit ReadStringFileSequence(const std::vector& files) + explicit ReadStringFileSequence(const std::vector &files) : StringFileSequence(files) {} ReadStringFileSequence(std::initializer_list files) : StringFileSequence(files) {} @@ -1079,7 +1079,7 @@ struct ReadStringFileSequence : public StringFileSequence { return absl::OutOfRangeError( absl::StrCat("No more files to read beyond index=", index_)); } - const auto& file = files_[index_]; + const auto &file = files_[index_]; EXPECT_EQ(filename, file.path) << " at index " << index_; ++index_; return std::string{file.contents}; @@ -1090,7 +1090,7 @@ struct ReadStringFileSequence : public StringFileSequence { // Can be passed anywhere that takes a FileWriterFunction. // TODO(fangism): move this to a "file_test_util" library. struct ExpectStringFileSequence : public StringFileSequence { - explicit ExpectStringFileSequence(const std::vector& files) + explicit ExpectStringFileSequence(const std::vector &files) : StringFileSequence(files) {} ExpectStringFileSequence(std::initializer_list files) : StringFileSequence(files) {} @@ -1102,7 +1102,7 @@ struct ExpectStringFileSequence : public StringFileSequence { return absl::OutOfRangeError( absl::StrCat("No more files to compare beyond index=", index_)); } - const auto& file = files_[index_]; + const auto &file = files_[index_]; EXPECT_EQ(filename, file.path) << " at index " << index_; EXPECT_EQ(file.contents, src) << " at index " << index_; ++index_; @@ -2079,7 +2079,7 @@ TEST(PatchSetParseTest, InvalidInputs) { "@@ -2,1 +3,1 @@\n" "malformed line does not begin with [ -+]", }; - for (const auto& patch_contents : kTestCases) { + for (const auto &patch_contents : kTestCases) { PatchSet patch_set; EXPECT_FALSE(patch_set.Parse(patch_contents).ok()) << "contents:\n" << patch_contents; @@ -2150,7 +2150,7 @@ TEST(PatchSetParseAndPrintTest, ValidInputs) { " no change here\n", }; - for (const auto& patch_contents : kTestCases) { + for (const auto &patch_contents : kTestCases) { PatchSet patch_set; const auto status = patch_set.Parse(patch_contents); EXPECT_TRUE(status.ok()) << status.message(); diff --git a/common/strings/position.h b/common/strings/position.h index 47cc45769..30890836d 100644 --- a/common/strings/position.h +++ b/common/strings/position.h @@ -39,7 +39,7 @@ class ByteOffsetSet : public verible::IntervalSet { public: ByteOffsetSet() = default; - explicit ByteOffsetSet(const impl_type& iset) : impl_type(iset) {} + explicit ByteOffsetSet(const impl_type &iset) : impl_type(iset) {} // This constructor can initialize from a sequence of pairs, e.g. // ByteOffsetSet s{{0,1}, {4,7}, {8,10}}; @@ -57,7 +57,7 @@ class LineNumberSet : public verible::IntervalSet { public: LineNumberSet() = default; - explicit LineNumberSet(const impl_type& iset) : impl_type(iset) {} + explicit LineNumberSet(const impl_type &iset) : impl_type(iset) {} // This constructor can initialize from a sequence of pairs, e.g. // LineNumberSet s{{0,1}, {4,7}, {8,10}}; diff --git a/common/strings/random.cc b/common/strings/random.cc index 8d7c2986f..9d2e78162 100644 --- a/common/strings/random.cc +++ b/common/strings/random.cc @@ -40,7 +40,7 @@ std::string RandomEqualLengthIdentifier(absl::string_view input) { CHECK(!input.empty()); std::string s(input.length(), '?'); s.front() = RandomAlphaChar(); - for (auto& ch : verible::make_range(s.begin() + 1, s.end())) { + for (auto &ch : verible::make_range(s.begin() + 1, s.end())) { ch = RandomAlphaNumChar(); } return s; diff --git a/common/strings/range.cc b/common/strings/range.cc index ce48ed5d5..ac88da17c 100644 --- a/common/strings/range.cc +++ b/common/strings/range.cc @@ -23,7 +23,7 @@ namespace verible { -absl::string_view make_string_view_range(const char* begin, const char* end) { +absl::string_view make_string_view_range(const char *begin, const char *end) { const int length = std::distance(begin, end); CHECK_GE(length, 0) << "Malformed string bounds."; return absl::string_view(begin, length); diff --git a/common/strings/range.h b/common/strings/range.h index 4639d6f4f..ab608095d 100644 --- a/common/strings/range.h +++ b/common/strings/range.h @@ -25,7 +25,7 @@ namespace verible { // string_view lacks the two-iterator constructor that (iterator) ranges and // containers do. // This exploits the fact that string_view's iterators are just const char*. -absl::string_view make_string_view_range(const char* begin, const char* end); +absl::string_view make_string_view_range(const char *begin, const char *end); // Returns [x,y] where superstring.substr(x, y-x) == substring. // Precondition: substring must be a sub-range of superstring. diff --git a/common/strings/rebase.cc b/common/strings/rebase.cc index 23a8a037e..6668680d9 100644 --- a/common/strings/rebase.cc +++ b/common/strings/rebase.cc @@ -18,13 +18,13 @@ namespace verible { -void RebaseStringView(absl::string_view* src, absl::string_view dest) { +void RebaseStringView(absl::string_view *src, absl::string_view dest) { CHECK_EQ(*src, dest) << "RebaseStringView() is only valid when the " "new text referenced matches the old text."; *src = dest; } -void RebaseStringView(absl::string_view* src, const char* dest) { +void RebaseStringView(absl::string_view *src, const char *dest) { RebaseStringView(src, absl::string_view(dest, src->length())); } diff --git a/common/strings/rebase.h b/common/strings/rebase.h index 54cfb4d71..44dcdf1c9 100644 --- a/common/strings/rebase.h +++ b/common/strings/rebase.h @@ -26,13 +26,13 @@ namespace verible { // This is a potentially dangerous operation, which can be validated // using a combination of object lifetime management and range-checking. // It is the caller's responsibility that it points to valid memory. -void RebaseStringView(absl::string_view* src, absl::string_view dest); +void RebaseStringView(absl::string_view *src, absl::string_view dest); // This overload assumes that the string of interest from other has the // same length as the current string_view. // string_view::iterator happens to be const char*, but do not rely on that // fact as it can be implementation-dependent. -void RebaseStringView(absl::string_view* src, const char* dest); +void RebaseStringView(absl::string_view *src, const char *dest); } // namespace verible diff --git a/common/strings/rebase_test.cc b/common/strings/rebase_test.cc index 2e546bf64..80f07b04e 100644 --- a/common/strings/rebase_test.cc +++ b/common/strings/rebase_test.cc @@ -85,7 +85,7 @@ TEST(RebaseStringViewTest, NewSubstringNotAtFront) { TEST(RebaseStringViewTest, UsingCharPointer) { const absl::string_view text = "hello"; const absl::string_view new_base = "xxxhelloyyy"; - const char* new_view = new_base.begin() + 3; + const char *new_view = new_base.begin() + 3; absl::string_view text_view(text); RebaseStringView(&text_view, new_view); // assume original length EXPECT_TRUE(BoundsEqual(text_view, new_base.substr(3, 5))); diff --git a/common/strings/split.h b/common/strings/split.h index 69f2c14a3..0b93835df 100644 --- a/common/strings/split.h +++ b/common/strings/split.h @@ -48,10 +48,10 @@ class StringSpliterator { : remainder_(original) {} // Copy-able, movable, assignable. - StringSpliterator(const StringSpliterator&) = default; - StringSpliterator(StringSpliterator&&) = default; - StringSpliterator& operator=(const StringSpliterator&) = default; - StringSpliterator& operator=(StringSpliterator&&) = default; + StringSpliterator(const StringSpliterator &) = default; + StringSpliterator(StringSpliterator &&) = default; + StringSpliterator &operator=(const StringSpliterator &) = default; + StringSpliterator &operator=(StringSpliterator &&) = default; // Returns true if there is at least one result to come. operator bool() const { // NOLINT(google-explicit-constructor) diff --git a/common/strings/split_test.cc b/common/strings/split_test.cc index 26c72bed1..c927f037d 100644 --- a/common/strings/split_test.cc +++ b/common/strings/split_test.cc @@ -25,9 +25,9 @@ namespace { using ::testing::ElementsAre; static void AcceptFunctionChar( - const std::function& func) {} + const std::function &func) {} static void AcceptFunctionStringView( - const std::function& func) {} + const std::function &func) {} // This tests that StringSpliterator can be passed to a std::function. TEST(StringSpliteratorTest, CompileTimeAsFunction) { @@ -125,7 +125,7 @@ using IntPair = std::pair; // which is a stronger check than string contents comparison. static std::vector SplitLinesToOffsets(absl::string_view text) { std::vector offsets; - for (const auto& line : SplitLines(text)) { + for (const auto &line : SplitLines(text)) { offsets.push_back(SubstringOffsets(line, text)); } return offsets; @@ -173,7 +173,7 @@ TEST(SplitLinesTest, NonBlankLinesUnterminated) { static std::vector SplitLinesKeepLineTerminatorToOffsets( absl::string_view text) { std::vector offsets; - for (const auto& line : SplitLinesKeepLineTerminator(text)) { + for (const auto &line : SplitLinesKeepLineTerminator(text)) { offsets.push_back(SubstringOffsets(line, text)); } return offsets; diff --git a/common/strings/string_memory_map.h b/common/strings/string_memory_map.h index b28a610d0..350e37a5a 100644 --- a/common/strings/string_memory_map.h +++ b/common/strings/string_memory_map.h @@ -50,10 +50,10 @@ class StringViewSuperRangeMap { StringViewSuperRangeMap() = default; - StringViewSuperRangeMap(const StringViewSuperRangeMap&) = default; - StringViewSuperRangeMap(StringViewSuperRangeMap&&) = default; - StringViewSuperRangeMap& operator=(const StringViewSuperRangeMap&) = default; - StringViewSuperRangeMap& operator=(StringViewSuperRangeMap&&) = default; + StringViewSuperRangeMap(const StringViewSuperRangeMap &) = default; + StringViewSuperRangeMap(StringViewSuperRangeMap &&) = default; + StringViewSuperRangeMap &operator=(const StringViewSuperRangeMap &) = default; + StringViewSuperRangeMap &operator=(StringViewSuperRangeMap &&) = default; bool empty() const { return string_map_.empty(); } const_iterator begin() const { return string_map_.begin(); } @@ -102,7 +102,7 @@ class StringViewSuperRangeMap { // always return the same range for the same object. One way to ensure this is // to make the underlying storage a 'const std::string'. // -template +template class StringMemoryMap { using key_type = absl::string_view::const_iterator; using map_type = DisjointIntervalMap; @@ -112,15 +112,15 @@ class StringMemoryMap { StringMemoryMap() = default; - StringMemoryMap(const StringMemoryMap&) = delete; - StringMemoryMap(StringMemoryMap&&) = delete; - StringMemoryMap& operator=(const StringMemoryMap&) = delete; - StringMemoryMap& operator=(StringMemoryMap&&) = delete; + StringMemoryMap(const StringMemoryMap &) = delete; + StringMemoryMap(StringMemoryMap &&) = delete; + StringMemoryMap &operator=(const StringMemoryMap &) = delete; + StringMemoryMap &operator=(StringMemoryMap &&) = delete; // Returns reference to the object in the set that owns the memory range of // string 's', or else nullptr if 's' does not fall entirely within one of the // intervals in the map. - const T* find(absl::string_view sv) const { + const T *find(absl::string_view sv) const { const auto iter = memory_map_.find(internal::string_view_to_pair(sv)); if (iter == memory_map_.end()) return nullptr; return &iter->second; @@ -128,7 +128,7 @@ class StringMemoryMap { // Move-inserts an element into the set, keyed on the memory range owned // by the object. - iterator insert(T&& t) { + iterator insert(T &&t) { const absl::string_view key = RangeOf(t); return memory_map_.must_emplace(internal::string_view_to_pair(key), std::move(t)); diff --git a/common/strings/string_memory_map_test.cc b/common/strings/string_memory_map_test.cc index 1957a9fd3..013f1e6c7 100644 --- a/common/strings/string_memory_map_test.cc +++ b/common/strings/string_memory_map_test.cc @@ -27,7 +27,7 @@ namespace verible { namespace { static void ForAllSubstringRanges( - absl::string_view sv, const std::function& func) { + absl::string_view sv, const std::function &func) { for (auto start_iter = sv.begin(); start_iter != sv.end(); ++start_iter) { for (auto end_iter = start_iter; end_iter != sv.end(); ++end_iter) { if (start_iter == end_iter) continue; // skip empty ranges @@ -107,7 +107,7 @@ TEST(StringViewSuperRangeMapTest, TwoStrings) { // Function to get the owned address range of the underlying string. static absl::string_view StringViewKey( - const std::unique_ptr& owned) { + const std::unique_ptr &owned) { return absl::string_view(*ABSL_DIE_IF_NULL(owned)); } @@ -119,7 +119,7 @@ TEST(StringMemoryMapTest, EmptyOwnsNothing) { EXPECT_EQ(sset.find("not-owned-anywhere"), nullptr); } -static absl::string_view InsertStringCopy(StringSet* sset, const char* text) { +static absl::string_view InsertStringCopy(StringSet *sset, const char *text) { const auto new_iter = sset->insert(std::make_unique(text)); // copy return make_string_view_range(new_iter->first.first, new_iter->first.second); @@ -131,7 +131,7 @@ TEST(StringMemoryMapTest, OneElement) { // Check all valid substring ranges ForAllSubstringRanges(sv, [&sset, sv](absl::string_view subrange) { - const auto* f = sset.find(subrange); + const auto *f = sset.find(subrange); ASSERT_NE(f, nullptr) << "subrange returned nullptr: " << subrange; const absl::string_view fv(**f); EXPECT_TRUE(BoundsEqual(fv, sv)) << "got: " << fv << " vs. " << sv; @@ -148,21 +148,21 @@ TEST(StringMemoryMapTest, MultipleElements) { // Check all valid substring ranges ForAllSubstringRanges(sv1, [&sset, sv1](absl::string_view subrange) { - const auto* f = sset.find(subrange); + const auto *f = sset.find(subrange); ASSERT_NE(f, nullptr) << "subrange returned nullptr: " << subrange; const absl::string_view fv(*ABSL_DIE_IF_NULL(*f)); EXPECT_TRUE(BoundsEqual(fv, sv1)) << "got: " << fv << " vs. " << sv1; EXPECT_EQ(fv, "AAA"); }); ForAllSubstringRanges(sv2, [&sset, sv2](absl::string_view subrange) { - const auto* f = sset.find(subrange); + const auto *f = sset.find(subrange); ASSERT_NE(f, nullptr) << "subrange returned nullptr: " << subrange; const absl::string_view fv(*ABSL_DIE_IF_NULL(*f)); EXPECT_TRUE(BoundsEqual(fv, sv2)) << "got: " << fv << " vs. " << sv2; EXPECT_EQ(fv, "BBBB"); }); ForAllSubstringRanges(sv3, [&sset, sv3](absl::string_view subrange) { - const auto* f = sset.find(subrange); + const auto *f = sset.find(subrange); ASSERT_NE(f, nullptr) << "subrange returned nullptr: " << subrange; const absl::string_view fv(*ABSL_DIE_IF_NULL(*f)); EXPECT_TRUE(BoundsEqual(fv, sv3)) << "got: " << fv << " vs. " << sv3; diff --git a/common/text/concrete_syntax_leaf.h b/common/text/concrete_syntax_leaf.h index c70f4107d..9c3a26e41 100644 --- a/common/text/concrete_syntax_leaf.h +++ b/common/text/concrete_syntax_leaf.h @@ -32,31 +32,31 @@ class SyntaxTreeLeaf final : public Symbol { public: SyntaxTreeLeaf() = delete; - explicit SyntaxTreeLeaf(const TokenInfo& token) : token_(token) {} + explicit SyntaxTreeLeaf(const TokenInfo &token) : token_(token) {} // All passed arguments will be forwarded to T's constructor template - explicit SyntaxTreeLeaf(Args&&... args) + explicit SyntaxTreeLeaf(Args &&...args) : token_(std::forward(args)...) {} - const TokenInfo& get() const { return token_; } + const TokenInfo &get() const { return token_; } - TokenInfo* get_mutable() { return &token_; } + TokenInfo *get_mutable() { return &token_; } // Compares this to an arbitrary symbol using compare_tokens - bool equals(const Symbol* symbol, - const TokenComparator& compare_tokens) const final; + bool equals(const Symbol *symbol, + const TokenComparator &compare_tokens) const final; // Compares this to another leaf using compare_tokens - bool equals(const SyntaxTreeLeaf* leaf, - const TokenComparator& compare_tokens) const; + bool equals(const SyntaxTreeLeaf *leaf, + const TokenComparator &compare_tokens) const; // The Accept() methods have the visitor visit this leaf and perform no // other actions. - void Accept(TreeVisitorRecursive* visitor) const final; - void Accept(SymbolVisitor* visitor) const final; - void Accept(MutableTreeVisitorRecursive* visitor, - SymbolPtr* this_owned) final; + void Accept(TreeVisitorRecursive *visitor) const final; + void Accept(SymbolVisitor *visitor) const final; + void Accept(MutableTreeVisitorRecursive *visitor, + SymbolPtr *this_owned) final; // Method override that returns the Kind of SyntaxTreeLeaf SymbolKind Kind() const final { return SymbolKind::kLeaf; } @@ -66,7 +66,7 @@ class SyntaxTreeLeaf final : public Symbol { TokenInfo token_; }; -std::ostream& operator<<(std::ostream& os, const SyntaxTreeLeaf& l); +std::ostream &operator<<(std::ostream &os, const SyntaxTreeLeaf &l); } // namespace verible diff --git a/common/text/concrete_syntax_tree.cc b/common/text/concrete_syntax_tree.cc index bdb9427e7..d275a9cc8 100644 --- a/common/text/concrete_syntax_tree.cc +++ b/common/text/concrete_syntax_tree.cc @@ -26,10 +26,10 @@ namespace verible { // Checks if this is equal to SymbolPtr node under compare_token function -bool SyntaxTreeNode::equals(const Symbol* symbol, - const TokenComparator& compare_tokens) const { +bool SyntaxTreeNode::equals(const Symbol *symbol, + const TokenComparator &compare_tokens) const { if (symbol->Kind() == SymbolKind::kNode) { - const auto* node = down_cast(symbol); + const auto *node = down_cast(symbol); return equals(node, compare_tokens); } return false; @@ -38,8 +38,8 @@ bool SyntaxTreeNode::equals(const Symbol* symbol, // Checks if this is equal to a SyntaxTreeNode under compare_token function // Returns true if both trees have same number of children and children are // equal trees. -bool SyntaxTreeNode::equals(const SyntaxTreeNode* node, - const TokenComparator& compare_tokens) const { +bool SyntaxTreeNode::equals(const SyntaxTreeNode *node, + const TokenComparator &compare_tokens) const { if (Tag().tag != node->Tag().tag) return false; if (children_.size() != node->children().size()) { return false; @@ -54,41 +54,41 @@ bool SyntaxTreeNode::equals(const SyntaxTreeNode* node, return true; } -SymbolPtr& SyntaxTreeNode::operator[](const size_t i) { +SymbolPtr &SyntaxTreeNode::operator[](const size_t i) { CHECK_LT(i, children_.size()); return children_[i]; } -const SymbolPtr& SyntaxTreeNode::operator[](const size_t i) const { +const SymbolPtr &SyntaxTreeNode::operator[](const size_t i) const { CHECK_LT(i, children_.size()); return children_[i]; } // visits self, then forwards visitor to every child -void SyntaxTreeNode::Accept(TreeVisitorRecursive* visitor) const { +void SyntaxTreeNode::Accept(TreeVisitorRecursive *visitor) const { visitor->Visit(*this); - for (const auto& child : children_) { + for (const auto &child : children_) { if (child != nullptr) child->Accept(visitor); } } -void SyntaxTreeNode::Accept(MutableTreeVisitorRecursive* visitor, - SymbolPtr* this_owned) { +void SyntaxTreeNode::Accept(MutableTreeVisitorRecursive *visitor, + SymbolPtr *this_owned) { CHECK_EQ(ABSL_DIE_IF_NULL(this_owned)->get(), this); visitor->Visit(*this, this_owned); - for (auto& child : children_) { + for (auto &child : children_) { if (child != nullptr) child->Accept(visitor, &child); } } -void SyntaxTreeNode::Accept(SymbolVisitor* visitor) const { +void SyntaxTreeNode::Accept(SymbolVisitor *visitor) const { visitor->Visit(*this); } -void SetChild_(const SymbolPtr& parent, int child_index, SymbolPtr new_child) { +void SetChild_(const SymbolPtr &parent, int child_index, SymbolPtr new_child) { CHECK_EQ(ABSL_DIE_IF_NULL(parent)->Kind(), SymbolKind::kNode); - auto* parent_node = down_cast(parent.get()); + auto *parent_node = down_cast(parent.get()); CHECK_LT(child_index, static_cast(parent_node->children().size())); CHECK(parent_node->children()[child_index] == nullptr); diff --git a/common/text/concrete_syntax_tree.h b/common/text/concrete_syntax_tree.h index 95505b7fd..8138e368a 100644 --- a/common/text/concrete_syntax_tree.h +++ b/common/text/concrete_syntax_tree.h @@ -60,7 +60,7 @@ using ConcreteSyntaxTree = SymbolPtr; // This takes over ownership of the symbol pointer. // $$ = MakeNode($1, $2, ForwardChildren($3), $4); struct ForwardChildren { - explicit ForwardChildren(SymbolPtr& symbol) // NOLINT + explicit ForwardChildren(SymbolPtr &symbol) // NOLINT : node(std::move(symbol)) {} SymbolPtr node; }; @@ -72,8 +72,8 @@ class SyntaxTreeNode final : public Symbol { public: explicit SyntaxTreeNode(const int tag = kUntagged) : tag_(tag) {} - const std::vector& children() const { return children_; } - std::vector& mutable_children() { return children_; } + const std::vector &children() const { return children_; } + std::vector &mutable_children() { return children_; } // Transfer ownership of argument to this object. // Call MakeNode or ExtendNode instead of calling this directly. @@ -88,10 +88,10 @@ class SyntaxTreeNode final : public Symbol { children_.push_back(std::move(forwarded_children.node)); return; } - auto* node = down_cast(forwarded_children.node.get()); + auto *node = down_cast(forwarded_children.node.get()); const auto new_size = children_.size() + node->children_.size(); children_.reserve(new_size); - for (auto& child : node->children_) { + for (auto &child : node->children_) { children_.push_back(std::move(child)); } // Remove all the vacated children slots left in the parent. @@ -104,35 +104,35 @@ class SyntaxTreeNode final : public Symbol { // Ownership of all arguments is transferred to this object. // Call MakeNode or ExtendNode instead of calling Append directly. template - void Append(T&& t, Args&&... args) { + void Append(T &&t, Args &&...args) { AppendChild(std::move(t)); // Append the first. Append(std::forward(args)...); // Append the rest. } // Children accessor (mutable). - SymbolPtr& operator[](size_t i); + SymbolPtr &operator[](size_t i); // Children accessor (const). - const SymbolPtr& operator[](size_t i) const; + const SymbolPtr &operator[](size_t i) const; // Compares this node to an arbitrary symbol using the compare_tokens // function. - bool equals(const Symbol* symbol, - const TokenComparator& compare_tokens) const final; + bool equals(const Symbol *symbol, + const TokenComparator &compare_tokens) const final; // Compares this node to another node. // Checks for recursive equality among all children of both nodes. - bool equals(const SyntaxTreeNode* node, - const TokenComparator& compare_tokens) const; + bool equals(const SyntaxTreeNode *node, + const TokenComparator &compare_tokens) const; // Uses passed TreeVisitorRecursive to visit all children recursively, // then visit itself. - void Accept(TreeVisitorRecursive* visitor) const final; - void Accept(MutableTreeVisitorRecursive* visitor, - SymbolPtr* this_owned) final; + void Accept(TreeVisitorRecursive *visitor) const final; + void Accept(MutableTreeVisitorRecursive *visitor, + SymbolPtr *this_owned) final; // Accepting a symbol visitor does not recursively visit children. - void Accept(SymbolVisitor* visitor) const final; + void Accept(SymbolVisitor *visitor) const final; // Method override that returns the Kind of Symbol SymbolKind Kind() const final { return SymbolKind::kNode; } @@ -188,8 +188,8 @@ class SyntaxTreeNode final : public Symbol { // Ownership of all args is transferred, and consumed by the new node. // Sample usage: $$ = MakeNode(TAG, $1, $2, $3); template -SymbolPtr MakeNode(Args&&... args) { - auto* const node_pointer = new SyntaxTreeNode(); +SymbolPtr MakeNode(Args &&...args) { + auto *const node_pointer = new SyntaxTreeNode(); node_pointer->Append(std::forward(args)...); return SymbolPtr(node_pointer); } @@ -200,8 +200,8 @@ SymbolPtr MakeNode(Args&&... args) { // $$ = MakeTaggedNode(TAG); // empty, no children // $$ = MakeTaggedNode(TAG, $1, $2, $3); template -SymbolPtr MakeTaggedNode(const Enum tag, Args&&... args) { - auto* const node_pointer = new SyntaxTreeNode(static_cast(tag)); +SymbolPtr MakeTaggedNode(const Enum tag, Args &&...args) { + auto *const node_pointer = new SyntaxTreeNode(static_cast(tag)); node_pointer->Append(std::forward(args)...); return SymbolPtr(node_pointer); } @@ -212,21 +212,21 @@ SymbolPtr MakeTaggedNode(const Enum tag, Args&&... args) { // $1 is transferred to $$. // Sample usage: $$ = ExtendNode($1, $2, $3); template -SymbolPtr ExtendNode(T&& list_ptr, Args&&... args) { +SymbolPtr ExtendNode(T &&list_ptr, Args &&...args) { return ExtendNodeMoved(std::move(list_ptr), std::forward(args)...); } // Implementation detail, call ExtendNode instead for automatic std::move. template -SymbolPtr ExtendNodeMoved(SymbolPtr list_ptr, Args&&... args) { +SymbolPtr ExtendNodeMoved(SymbolPtr list_ptr, Args &&...args) { CHECK(list_ptr->Kind() == SymbolKind::kNode); - auto* const node_pointer = down_cast(list_ptr.get()); + auto *const node_pointer = down_cast(list_ptr.get()); node_pointer->Append(std::forward(args)...); return list_ptr; } // Helper function to deal with move semantics and argument forwarding -void SetChild_(const SymbolPtr& parent, int child_index, SymbolPtr new_child); +void SetChild_(const SymbolPtr &parent, int child_index, SymbolPtr new_child); // Sets the child at child_index of parent to new_child. // SetChild will crash when: @@ -235,7 +235,7 @@ void SetChild_(const SymbolPtr& parent, int child_index, SymbolPtr new_child); // Preexisting data at target index is not a nullptr // Equivalent to: parent->children[child_index] = std::move(new_child); template -void SetChild(const SymbolPtr& parent, int child_index, T&& new_child) { +void SetChild(const SymbolPtr &parent, int child_index, T &&new_child) { SetChild_(parent, child_index, std::move(new_child)); } diff --git a/common/text/concrete_syntax_tree_test.cc b/common/text/concrete_syntax_tree_test.cc index f3daf4572..fce962ae5 100644 --- a/common/text/concrete_syntax_tree_test.cc +++ b/common/text/concrete_syntax_tree_test.cc @@ -40,9 +40,9 @@ static void SinkValue(SymbolPtr) { // Do nothing, just consume and expire the pointer. } -static SyntaxTreeNode* CheckTree(const SymbolPtr& ptr) { +static SyntaxTreeNode *CheckTree(const SymbolPtr &ptr) { CHECK(ptr->Kind() == SymbolKind::kNode); - return down_cast(ptr.get()); + return down_cast(ptr.get()); } // Test that MatchesTag matches correctly. @@ -260,7 +260,7 @@ TEST(SyntaxTreeNodeAppend, AdoptChildren) { EXPECT_THAT(seq, IsNull()); auto parentnode = CheckTree(parent); EXPECT_THAT(parentnode->children(), SizeIs(3)); - for (const auto& child : parentnode->children()) { + for (const auto &child : parentnode->children()) { EXPECT_THAT(child, NotNull()); } } @@ -272,7 +272,7 @@ TEST(SyntaxTreeNodeAppend, AdoptNullChildren) { EXPECT_THAT(seq, IsNull()); auto parentnode = CheckTree(parent); EXPECT_THAT(parentnode->children(), SizeIs(2)); - for (const auto& child : parentnode->children()) { + for (const auto &child : parentnode->children()) { EXPECT_THAT(child, IsNull()); } } @@ -304,7 +304,7 @@ TEST(SyntaxTreeNodeAppend, AdoptChildrenMixed) { auto parentnode = CheckTree(parent); ASSERT_THAT(parentnode, NotNull()); EXPECT_THAT(parentnode->children(), SizeIs(5)); - for (const auto& child : parentnode->children()) { + for (const auto &child : parentnode->children()) { EXPECT_THAT(child, NotNull()); } } @@ -319,7 +319,7 @@ TEST(SyntaxTreeNodeAppend, AdoptChildrenMultiple) { auto parentnode = CheckTree(parent); ASSERT_THAT(parentnode, NotNull()); EXPECT_THAT(parentnode->children(), SizeIs(7)); - for (const auto& child : parentnode->children()) { + for (const auto &child : parentnode->children()) { EXPECT_THAT(child, NotNull()); } } @@ -331,7 +331,7 @@ TEST(ExtendNodeTest, AdoptChildren) { EXPECT_THAT(seq, IsNull()); auto parentnode = CheckTree(parent); EXPECT_THAT(parentnode->children(), SizeIs(2)); - for (const auto& child : parentnode->children()) { + for (const auto &child : parentnode->children()) { EXPECT_THAT(child, NotNull()); } } @@ -343,7 +343,7 @@ TEST(ExtendNodeTest, AdoptChildrenMixed) { EXPECT_THAT(seq, IsNull()); auto parentnode = CheckTree(parent); EXPECT_THAT(parentnode->children(), SizeIs(4)); - for (const auto& child : parentnode->children()) { + for (const auto &child : parentnode->children()) { EXPECT_THAT(child, NotNull()); } } @@ -377,7 +377,7 @@ TEST(ExtendNodeTest, SetChild1Size2) { // Tests that subscript operator works (mutable). TEST(NodeSubscriptTest, MutableReference) { auto example = Node(Leaf(6, "6"), Leaf(7, "7")); - auto& example_node = down_cast(*example); + auto &example_node = down_cast(*example); EXPECT_EQ(example_node[0]->Tag().tag, 6); EXPECT_EQ(example_node[1]->Tag().tag, 7); } @@ -385,7 +385,7 @@ TEST(NodeSubscriptTest, MutableReference) { // Tests that subscript operator works (const). TEST(NodeSubscriptTest, ConstReference) { auto example = Node(Leaf(8, "8"), Leaf(9, "9")); - const auto& example_node = down_cast(*example); + const auto &example_node = down_cast(*example); EXPECT_EQ(example_node[0]->Tag().tag, 8); EXPECT_EQ(example_node[1]->Tag().tag, 9); } diff --git a/common/text/config_utils.cc b/common/text/config_utils.cc index 197616abb..a49b3ef1f 100644 --- a/common/text/config_utils.cc +++ b/common/text/config_utils.cc @@ -35,7 +35,7 @@ using config::NVConfigSpec; // TODO(hzeller): consider using flex for a more readable tokenization that // can also much easier deal with whitespaces, strings etc. absl::Status ParseNameValues(string_view config_string, - const std::initializer_list& spec) { + const std::initializer_list &spec) { if (config_string.empty()) return absl::OkStatus(); for (const string_view single_config : absl::StrSplit(config_string, ';')) { @@ -43,10 +43,10 @@ absl::Status ParseNameValues(string_view config_string, absl::StrSplit(single_config, ':'); const auto value_config = std::find_if( // linear search spec.begin(), spec.end(), - [&nv_pair](const NVConfigSpec& s) { return nv_pair.first == s.name; }); + [&nv_pair](const NVConfigSpec &s) { return nv_pair.first == s.name; }); if (value_config == spec.end()) { std::string available; - for (const auto& s : spec) { + for (const auto &s : spec) { if (!available.empty()) available.append(", "); available.append("'").append(s.name).append("'"); } @@ -70,7 +70,7 @@ absl::Status ParseNameValues(string_view config_string, } namespace config { -ConfigValueSetter SetInt(int* value, int minimum, int maximum) { +ConfigValueSetter SetInt(int *value, int minimum, int maximum) { CHECK(value) << "Must provide pointer to integer to store."; return [value, minimum, maximum](string_view v) { int parsed_value; @@ -87,12 +87,12 @@ ConfigValueSetter SetInt(int* value, int minimum, int maximum) { }; } -ConfigValueSetter SetInt(int* value) { +ConfigValueSetter SetInt(int *value) { return SetInt(value, std::numeric_limits::min(), std::numeric_limits::max()); } -ConfigValueSetter SetBool(bool* value) { +ConfigValueSetter SetBool(bool *value) { CHECK(value) << "Must provide pointer to boolean to store."; return [value](string_view v) { // clang-format off diff --git a/common/text/config_utils.h b/common/text/config_utils.h index 85df537a1..1b98b6930 100644 --- a/common/text/config_utils.h +++ b/common/text/config_utils.h @@ -27,7 +27,7 @@ namespace config { using ConfigValueSetter = std::function; struct NVConfigSpec { - const char* name; + const char *name; ConfigValueSetter set_value; }; } // namespace config @@ -64,25 +64,25 @@ struct NVConfigSpec { // this function returns with an absl::OkStatus(). absl::Status ParseNameValues( absl::string_view config_string, - const std::initializer_list& spec); + const std::initializer_list &spec); namespace config { // A few utility functions generating setters for ParseNameValues() allowing // to parse values directly into variables. -ConfigValueSetter SetInt(int* value); +ConfigValueSetter SetInt(int *value); // Set an integer value and validate that it is in [minimum...maximum] range. -ConfigValueSetter SetInt(int* value, int minimum, int maximum); -ConfigValueSetter SetBool(bool* value); -ConfigValueSetter SetString(std::string* value); +ConfigValueSetter SetInt(int *value, int minimum, int maximum); +ConfigValueSetter SetBool(bool *value); +ConfigValueSetter SetString(std::string *value); // Set a string, but verify that it is only one of a limited set. The // set is provided as vector for simplicity and to allow the caller to // impose a particular importance order when returning an error. -ConfigValueSetter SetStringOneOf(std::string* value, - const std::vector& allowed); +ConfigValueSetter SetStringOneOf(std::string *value, + const std::vector &allowed); // Set a bitmap from the given values, a '|'-separated list of named bits // to be set. The bit-names provided in the configuration-string can come @@ -91,8 +91,8 @@ ConfigValueSetter SetStringOneOf(std::string* value, // The sequence in the 'choices' array determines the bit to be set. So a bit // named in choices[5] modifies (1<<5). Given the uint32 value, this allows // up to 32 choices. -ConfigValueSetter SetNamedBits(uint32_t* value, - const std::vector& choices); +ConfigValueSetter SetNamedBits(uint32_t *value, + const std::vector &choices); } // namespace config } // namespace verible diff --git a/common/text/config_utils_test.cc b/common/text/config_utils_test.cc index df5228d3d..0bcddc320 100644 --- a/common/text/config_utils_test.cc +++ b/common/text/config_utils_test.cc @@ -134,7 +134,7 @@ TEST(ConfigUtilsTest, ParseNamedBitmap) { }; absl::Status s; - for (const auto& testcase : kTestCases) { + for (const auto &testcase : kTestCases) { uint32_t bitmap = 0x12345678; s = ParseNameValues(testcase.first, {{"baz", SetNamedBits(&bitmap, kBitNames)}}); diff --git a/common/text/macro_definition.cc b/common/text/macro_definition.cc index e321a58a1..8fc7c14cb 100644 --- a/common/text/macro_definition.cc +++ b/common/text/macro_definition.cc @@ -29,7 +29,7 @@ namespace verible { using container::FindOrNull; -bool MacroDefinition::AppendParameter(const MacroParameterInfo& param_info) { +bool MacroDefinition::AppendParameter(const MacroParameterInfo ¶m_info) { is_callable_ = true; // Record position of this parameter. const bool inserted = parameter_positions_ @@ -41,8 +41,8 @@ bool MacroDefinition::AppendParameter(const MacroParameterInfo& param_info) { } absl::Status MacroDefinition::PopulateSubstitutionMap( - const std::vector& macro_call_args, - substitution_map_type* arg_map) const { + const std::vector ¯o_call_args, + substitution_map_type *arg_map) const { if (macro_call_args.size() != parameter_info_array_.size()) { return absl::InvalidArgumentError( absl::StrCat("Error calling macro ", name_.text(), " with ", @@ -54,7 +54,7 @@ absl::Status MacroDefinition::PopulateSubstitutionMap( const auto actuals_end = macro_call_args.end(); auto formals_iter = parameter_info_array_.begin(); for (; actuals_iter != actuals_end; ++actuals_iter, ++formals_iter) { - auto& replacement_text = (*arg_map)[formals_iter->name.text()]; + auto &replacement_text = (*arg_map)[formals_iter->name.text()]; if (!actuals_iter->text().empty()) { // Actual text is provided. replacement_text = *actuals_iter; @@ -68,8 +68,8 @@ absl::Status MacroDefinition::PopulateSubstitutionMap( } absl::Status MacroDefinition::PopulateSubstitutionMap( - const std::vector& macro_call_args, - substitution_map_type* arg_map) const { + const std::vector ¯o_call_args, + substitution_map_type *arg_map) const { if (macro_call_args.size() != parameter_info_array_.size()) { return absl::InvalidArgumentError( absl::StrCat("Error calling macro ", name_.text(), " with ", @@ -81,7 +81,7 @@ absl::Status MacroDefinition::PopulateSubstitutionMap( const auto actuals_end = macro_call_args.end(); auto formals_iter = parameter_info_array_.begin(); for (; actuals_iter != actuals_end; ++actuals_iter, ++formals_iter) { - auto& replacement_text = (*arg_map)[formals_iter->name.text()]; + auto &replacement_text = (*arg_map)[formals_iter->name.text()]; if (!actuals_iter->text().empty()) { // Actual text is provided. replacement_text = *actuals_iter; @@ -94,12 +94,12 @@ absl::Status MacroDefinition::PopulateSubstitutionMap( return absl::OkStatus(); } -const TokenInfo& MacroDefinition::SubstituteText( - const substitution_map_type& substitution_map, const TokenInfo& token_info, +const TokenInfo &MacroDefinition::SubstituteText( + const substitution_map_type &substitution_map, const TokenInfo &token_info, int actual_token_enum) { if (actual_token_enum == 0 || (actual_token_enum == token_info.token_enum())) { - const auto* replacement = FindOrNull(substitution_map, token_info.text()); + const auto *replacement = FindOrNull(substitution_map, token_info.text()); if (replacement) { // Substitute formal parameter for actual text. return *replacement; diff --git a/common/text/macro_definition.h b/common/text/macro_definition.h index 03e3506ae..d65fd0e4e 100644 --- a/common/text/macro_definition.h +++ b/common/text/macro_definition.h @@ -35,10 +35,10 @@ struct DefaultTokenInfo : public TokenInfo { DefaultTokenInfo() : TokenInfo(TokenInfo::EOFToken()) {} // Accept a plain TokenInfo for copy purposes. - explicit DefaultTokenInfo(const TokenInfo& t) : TokenInfo(t) {} + explicit DefaultTokenInfo(const TokenInfo &t) : TokenInfo(t) {} // Accept a plain TokenInfo for assignment purposes. - DefaultTokenInfo& operator=(const TokenInfo& t) { + DefaultTokenInfo &operator=(const TokenInfo &t) { TokenInfo::operator=(t); return *this; } @@ -46,8 +46,8 @@ struct DefaultTokenInfo : public TokenInfo { // Macro formal parameter specification: name with optional default. struct MacroParameterInfo { - explicit MacroParameterInfo(const TokenInfo& n = TokenInfo::EOFToken(), - const TokenInfo& d = TokenInfo::EOFToken()) + explicit MacroParameterInfo(const TokenInfo &n = TokenInfo::EOFToken(), + const TokenInfo &d = TokenInfo::EOFToken()) : name(n), default_value(d) {} // Name of macro parameter. @@ -75,15 +75,15 @@ struct MacroCall { class MacroDefinition { public: - MacroDefinition(const TokenInfo& header, const TokenInfo& name) + MacroDefinition(const TokenInfo &header, const TokenInfo &name) : header_(header), name_(name) {} absl::string_view Name() const { return name_.text(); } - const TokenInfo& NameToken() const { return name_; } + const TokenInfo &NameToken() const { return name_; } - const TokenInfo& DefinitionText() const { return definition_text_; } + const TokenInfo &DefinitionText() const { return definition_text_; } - void SetDefinitionText(const TokenInfo& t) { definition_text_ = t; } + void SetDefinitionText(const TokenInfo &t) { definition_text_ = t; } // Macro definitions with empty () should call this. void SetCallable() { is_callable_ = true; } @@ -94,23 +94,23 @@ class MacroDefinition { // Returns true if parameter was successfully added. // Duplicate parameter names are rejected, and will return false. // This automatically sets is_callable_. - bool AppendParameter(const MacroParameterInfo&); + bool AppendParameter(const MacroParameterInfo &); - const std::vector& Parameters() const { + const std::vector &Parameters() const { return parameter_info_array_; } using substitution_map_type = std::map; // Create a text substitution map to be used for macro expansion. - absl::Status PopulateSubstitutionMap(const std::vector&, - substitution_map_type*) const; - absl::Status PopulateSubstitutionMap(const std::vector&, - substitution_map_type*) const; + absl::Status PopulateSubstitutionMap(const std::vector &, + substitution_map_type *) const; + absl::Status PopulateSubstitutionMap(const std::vector &, + substitution_map_type *) const; // Replace formal parameter references with actuals. - static const TokenInfo& SubstituteText(const substitution_map_type&, - const TokenInfo&, + static const TokenInfo &SubstituteText(const substitution_map_type &, + const TokenInfo &, int actual_token_enum = 0); private: diff --git a/common/text/parser_verifier.cc b/common/text/parser_verifier.cc index daa107553..40d2b8f96 100644 --- a/common/text/parser_verifier.cc +++ b/common/text/parser_verifier.cc @@ -25,12 +25,12 @@ namespace verible { -void ParserVerifier::Visit(const SyntaxTreeLeaf& leaf) { +void ParserVerifier::Visit(const SyntaxTreeLeaf &leaf) { for (;;) { // Check to stop if reached end of stream or end of file if (view_iterator_ == view_.end() || (**view_iterator_).isEOF()) return; - const TokenInfo& view_token = **view_iterator_; + const TokenInfo &view_token = **view_iterator_; if (token_comparator_(view_token, leaf.get())) { // Found a matching token, continue to next leaf view_iterator_++; diff --git a/common/text/parser_verifier.h b/common/text/parser_verifier.h index c536139b4..3a554a294 100644 --- a/common/text/parser_verifier.h +++ b/common/text/parser_verifier.h @@ -41,11 +41,11 @@ namespace verible { class ParserVerifier : public TreeVisitorRecursive { public: - ParserVerifier(const Symbol& root, const TokenStreamView& view) + ParserVerifier(const Symbol &root, const TokenStreamView &view) : root_(root), view_(view), view_iterator_(view.begin()) {} - ParserVerifier(const Symbol& root, const TokenStreamView& view, - const TokenComparator& token_comparator) + ParserVerifier(const Symbol &root, const TokenStreamView &view, + const TokenComparator &token_comparator) : root_(root), view_(view), view_iterator_(view.begin()), @@ -57,12 +57,12 @@ class ParserVerifier : public TreeVisitorRecursive { // Do call these methods directly. Use Verify instead // TODO(jeremycs): changed these to protected and make SyntaxTreeLeaf // and SyntaxTreeNode friend classes - void Visit(const SyntaxTreeLeaf& leaf) final; - void Visit(const SyntaxTreeNode& node) final{}; + void Visit(const SyntaxTreeLeaf &leaf) final; + void Visit(const SyntaxTreeNode &node) final{}; private: - const Symbol& root_; - const TokenStreamView& view_; + const Symbol &root_; + const TokenStreamView &view_; // Current position in view. Ensures visit once behavior for each token TokenStreamView::const_iterator view_iterator_; @@ -72,7 +72,7 @@ class ParserVerifier : public TreeVisitorRecursive { TokenComparator token_comparator_ = default_comparator; - static bool default_comparator(const TokenInfo& t1, const TokenInfo& t2) { + static bool default_comparator(const TokenInfo &t1, const TokenInfo &t2) { return t1 == t2; } }; diff --git a/common/text/symbol.cc b/common/text/symbol.cc index 0e011fd81..827d122bb 100644 --- a/common/text/symbol.cc +++ b/common/text/symbol.cc @@ -18,7 +18,7 @@ namespace verible { -std::ostream& operator<<(std::ostream& stream, SymbolKind kind) { +std::ostream &operator<<(std::ostream &stream, SymbolKind kind) { switch (kind) { case SymbolKind::kLeaf: return stream << "SymbolKind::kLeaf"; diff --git a/common/text/syntax_tree_context.h b/common/text/syntax_tree_context.h index 170154456..45b75dcbe 100644 --- a/common/text/syntax_tree_context.h +++ b/common/text/syntax_tree_context.h @@ -36,9 +36,9 @@ namespace verible { // interface that can express AND/OR/NOT. // Despite of implementation based on pointers. This class requires // that managed elements are non-nullptrs. -class SyntaxTreeContext : public AutoPopStack { +class SyntaxTreeContext : public AutoPopStack { public: - using base_type = AutoPopStack; + using base_type = AutoPopStack; // member class to handle push and pop of stack safely using AutoPop = base_type::AutoPop; @@ -49,7 +49,7 @@ class SyntaxTreeContext : public AutoPopStack { public: // returns the top SyntaxTreeNode of the stack - const SyntaxTreeNode& top() const { + const SyntaxTreeNode &top() const { return *ABSL_DIE_IF_NULL(base_type::top()); } @@ -62,7 +62,7 @@ class SyntaxTreeContext : public AutoPopStack { if (size() <= reverse_offset) return false; return std::any_of( rbegin() + reverse_offset, rend(), - [=](const SyntaxTreeNode* node) { return node->MatchesTag(tag_enum); }); + [=](const SyntaxTreeNode *node) { return node->MatchesTag(tag_enum); }); } // IsInside returns true if there is a node of the specified @@ -80,7 +80,7 @@ class SyntaxTreeContext : public AutoPopStack { template bool IsInsideFirst(std::initializer_list includes, std::initializer_list excludes) const { - for (const auto& type : reversed_view(*this)) { + for (const auto &type : reversed_view(*this)) { if (type->MatchesTagAnyOf(includes)) return true; if (type->MatchesTagAnyOf(excludes)) return false; } @@ -115,18 +115,18 @@ class SyntaxTreeContext : public AutoPopStack { if (tag_enums.size() > size()) return false; // top of stack is back of vector (direct parent) return std::equal(tag_enums.begin(), tag_enums.end(), rbegin(), - [](E tag, const SyntaxTreeNode* node) { + [](E tag, const SyntaxTreeNode *node) { return E(node->Tag().tag) == tag; }); } // Returns the closest ancestor (starting from top of context stack) that // matches the given 'predicate' function, or nullptr if no match is found. - const SyntaxTreeNode* NearestParentMatching( - const std::function& predicate) const { + const SyntaxTreeNode *NearestParentMatching( + const std::function &predicate) const { const auto ancestors(reversed_view(*this)); const auto found = std::find_if(ancestors.begin(), ancestors.end(), - [&predicate](const SyntaxTreeNode* parent) { + [&predicate](const SyntaxTreeNode *parent) { return predicate(*parent); }); return found != ancestors.end() ? *found : nullptr; @@ -135,9 +135,9 @@ class SyntaxTreeContext : public AutoPopStack { // Returns the closest ancestor (starting from top of context stack) with the // specified node tag (enum). template - const SyntaxTreeNode* NearestParentWithTag(E tag) const { + const SyntaxTreeNode *NearestParentWithTag(E tag) const { return NearestParentMatching( - [tag](const SyntaxTreeNode& node) { return E(node.Tag().tag) == tag; }); + [tag](const SyntaxTreeNode &node) { return E(node.Tag().tag) == tag; }); } }; diff --git a/common/text/syntax_tree_context_test.cc b/common/text/syntax_tree_context_test.cc index 6a3ed4fe4..8c35186f2 100644 --- a/common/text/syntax_tree_context_test.cc +++ b/common/text/syntax_tree_context_test.cc @@ -27,7 +27,7 @@ using ::testing::ElementsAre; // Test that AutoPop properly pushes and pops nodes on and off the stack TEST(SyntaxTreeContextTest, PushPopTest) { SyntaxTreeContext context; - const auto& const_context = context; + const auto &const_context = context; EXPECT_TRUE(context.empty()); { SyntaxTreeNode node1(1); @@ -252,9 +252,9 @@ TEST(SyntaxTreeContextTest, DirectParentsAreTest) { TEST(SyntaxTreeContextTest, NearestParentMatchingTest) { // define a few predicate functions - const auto True = [](const SyntaxTreeNode& n) { return true; }; + const auto True = [](const SyntaxTreeNode &n) { return true; }; const auto TagEq = [](int i) { - return [i](const SyntaxTreeNode& n) { return n.Tag().tag == i; }; + return [i](const SyntaxTreeNode &n) { return n.Tag().tag == i; }; }; SyntaxTreeContext context; diff --git a/common/text/text_structure_test.cc b/common/text/text_structure_test.cc index 13eecfa47..f27d4e6a4 100644 --- a/common/text/text_structure_test.cc +++ b/common/text/text_structure_test.cc @@ -51,8 +51,8 @@ using ::testing::SizeIs; // Test constructor and initial state. TEST(TextStructureViewCtorTest, InitializeContents) { - const char* inputs[] = {"", "", "hello world", "foo\nbar\n"}; - for (const auto* input : inputs) { + const char *inputs[] = {"", "", "hello world", "foo\nbar\n"}; + for (const auto *input : inputs) { TextStructureView test_view(input); EXPECT_EQ(test_view.Contents(), input); EXPECT_THAT(test_view.TokenStream(), IsEmpty()); @@ -66,12 +66,12 @@ TEST(TextStructureViewCtorTest, InitializeContents) { TEST(FilterTokensTest, EmptyTokens) { TextStructureView test_view("blah"); EXPECT_THAT(test_view.GetTokenStreamView(), IsEmpty()); - test_view.FilterTokens([](const TokenInfo& token) { return true; }); + test_view.FilterTokens([](const TokenInfo &token) { return true; }); EXPECT_THAT(test_view.GetTokenStreamView(), IsEmpty()); } // Create a one-token token stream and syntax tree. -void OneTokenTextStructureView(TextStructureView* view) { +void OneTokenTextStructureView(TextStructureView *view) { TokenInfo token(1, view->Contents()); view->MutableTokenStream().push_back(token); view->MutableTokenStreamView().push_back(view->TokenStream().begin()); @@ -79,14 +79,14 @@ void OneTokenTextStructureView(TextStructureView* view) { } // Create a two-token token stream, no syntax tree. -void MultiTokenTextStructureViewNoTree(TextStructureView* view) { +void MultiTokenTextStructureViewNoTree(TextStructureView *view) { const auto contents = view->Contents(); CHECK_GE(contents.length(), 5); - auto& stream = view->MutableTokenStream(); + auto &stream = view->MutableTokenStream(); for (int i = 0; i < 5; ++i) { // Populate with 5 single-char tokens. stream.emplace_back(i + 1, contents.substr(i, 1)); } - auto& stream_view = view->MutableTokenStreamView(); + auto &stream_view = view->MutableTokenStreamView(); // Populate view with 2 tokens. stream_view.emplace_back(stream.begin() + 1); stream_view.emplace_back(stream.begin() + 3); @@ -99,7 +99,7 @@ TEST(FilterTokensTest, OneTokenKept) { // Pretend to lex and parse text. OneTokenTextStructureView(&test_view); EXPECT_THAT(test_view.GetTokenStreamView(), SizeIs(1)); - test_view.FilterTokens([](const TokenInfo& token) { return true; }); + test_view.FilterTokens([](const TokenInfo &token) { return true; }); EXPECT_THAT(test_view.GetTokenStreamView(), SizeIs(1)); } @@ -110,14 +110,14 @@ TEST(FilterTokensTest, OneTokenRemoved) { // Pretend to lex and parse text. OneTokenTextStructureView(&test_view); EXPECT_THAT(test_view.GetTokenStreamView(), SizeIs(1)); - test_view.FilterTokens([](const TokenInfo& token) { return false; }); + test_view.FilterTokens([](const TokenInfo &token) { return false; }); EXPECT_THAT(test_view.GetTokenStreamView(), IsEmpty()); } // Test that mutating nothing works. TEST(MutateTokensTest, EmptyTokensNoOp) { TextStructureView test_view(""); - test_view.MutateTokens([](TokenInfo*) {}); + test_view.MutateTokens([](TokenInfo *) {}); EXPECT_THAT(test_view.TokenStream(), IsEmpty()); EXPECT_THAT(test_view.GetTokenStreamView(), IsEmpty()); EXPECT_THAT(test_view.SyntaxTree(), IsNull()); @@ -128,7 +128,7 @@ TEST(TokenStreamReferenceViewTest, ShiftRight) { TextStructureView test_view("hello"); MultiTokenTextStructureViewNoTree(&test_view); auto iterators = test_view.MakeTokenStreamReferenceView(); - const auto& stream_view = test_view.GetTokenStreamView(); + const auto &stream_view = test_view.GetTokenStreamView(); auto view_iter = stream_view.begin(); for (auto iter : iterators) { EXPECT_EQ(iter, *view_iter); // write-iterators same as read-iterators @@ -190,12 +190,12 @@ class TokenRangeTest : public ::testing::Test, public TextStructureTokenized { // Checks for consistency between beginning-of-line offset map and the // beginning-of-line token iterator map. TEST_F(TokenRangeTest, CalculateFirstTokensPerLineTest) { - const auto& line_token_map = data_.GetLineTokenMap(); - const auto& line_column_map = data_.GetLineColumnMap(); + const auto &line_token_map = data_.GetLineTokenMap(); + const auto &line_column_map = data_.GetLineColumnMap(); // There is always one more entry in the line_token_map that points to end(). EXPECT_EQ(line_column_map.GetBeginningOfLineOffsets().size() + 1, line_token_map.size()); - const auto& tokens = data_.TokenStream(); + const auto &tokens = data_.TokenStream(); EXPECT_EQ(line_token_map.front(), tokens.begin()); EXPECT_EQ(line_token_map.back(), tokens.end()); EXPECT_EQ(line_token_map[1], tokens.begin() + 5); @@ -206,7 +206,7 @@ TEST_F(TokenRangeTest, CalculateFirstTokensPerLineTest) { TEST_F(TokenRangeTest, GetRangeOfTokenVerifyAllRangesExclusive) { // Bulk testing: let's see that we constantly progress in emitted ranges. LineColumnRange previous{{0, 0}, {0, 0}}; - for (const TokenInfo& token : data_.TokenStream()) { + for (const TokenInfo &token : data_.TokenStream()) { LineColumnRange token_range = data_.GetRangeForToken(token); EXPECT_EQ(token_range.start, previous.end); EXPECT_LT(previous.end, token_range.end); @@ -223,7 +223,7 @@ TEST_F(TokenRangeTest, GetRangeOfTokenEofTokenAcceptedUniversally) { } TEST_F(TokenRangeTest, GetRangeForTokenOrText) { - const TokenInfo& token = data_.FindTokenAt({0, 7}); + const TokenInfo &token = data_.FindTokenAt({0, 7}); EXPECT_EQ(token.text(), "world"); { // Extract from token const LineColumnRange range = data_.GetRangeForToken(token); @@ -246,7 +246,7 @@ TEST_F(TokenRangeTest, GetRangeForTokenOrText) { } TEST_F(TokenRangeTest, CheckContainsText) { - const TokenInfo& token = data_.FindTokenAt({0, 7}); + const TokenInfo &token = data_.FindTokenAt({0, 7}); const absl::string_view other_string = "other_string"; EXPECT_TRUE(data_.ContainsText(token.text())); EXPECT_FALSE(data_.ContainsText(other_string)); @@ -299,7 +299,7 @@ TEST_F(TokenRangeTest, TokenRangeSpanningOffsetsNonEmpty) { {9, 12, 4, 4}, // empty, does not span a whole token {9, 19, 4, 7}, }; - for (const auto& test_case : test_cases) { + for (const auto &test_case : test_cases) { const auto token_range = data_.TokenRangeSpanningOffsets( test_case.left_offset, test_case.right_offset); EXPECT_EQ(std::distance(data_.TokenStream().cbegin(), token_range.begin()), @@ -322,7 +322,7 @@ TEST_F(TokenRangeTest, TokenRangeOnLine) { {2, 6, 11}, {3, 11, 11}, // There is no line[3], this represents an empty range. }; - for (const auto& test_case : test_cases) { + for (const auto &test_case : test_cases) { const auto token_range = data_.TokenRangeOnLine(test_case.lineno); EXPECT_EQ(std::distance(data_.TokenStream().cbegin(), token_range.begin()), test_case.left_index); @@ -392,7 +392,7 @@ TEST_F(TextStructureViewInternalsTest, TrimTokensToSubstringKeepEverything) { TrimTokensToSubstring(0, contents_.length()); EXPECT_THAT(tokens_, SizeIs(5)); EXPECT_THAT(tokens_view_, SizeIs(3)); - const TokenInfo& back(tokens_.back()); + const TokenInfo &back(tokens_.back()); EXPECT_TRUE(back.isEOF()); EXPECT_TRUE( BoundsEqual(back.text(), make_range(contents_.end(), contents_.end()))); @@ -410,7 +410,7 @@ TEST_F(TextStructureViewInternalsTest, TrimTokensToSubstringKeepSubset) { TrimTokensToSubstring(3, 12); EXPECT_THAT(tokens_, SizeIs(4)); EXPECT_THAT(tokens_view_, SizeIs(2)); - const TokenInfo& back(tokens_.back()); + const TokenInfo &back(tokens_.back()); EXPECT_TRUE(back.isEOF()); EXPECT_TRUE(BoundsEqual( back.text(), make_range(contents_.begin() + 12, contents_.begin() + 12))); @@ -421,7 +421,7 @@ TEST_F(TextStructureViewInternalsTest, TrimTokensToSubstringKeepLeaf) { TrimTokensToSubstring(0, 6); EXPECT_THAT(tokens_, SizeIs(3)); EXPECT_THAT(tokens_view_, SizeIs(2)); - const TokenInfo& back(tokens_.back()); + const TokenInfo &back(tokens_.back()); EXPECT_TRUE(back.isEOF()); EXPECT_TRUE(BoundsEqual( back.text(), make_range(contents_.begin() + 6, contents_.begin() + 6))); @@ -466,11 +466,11 @@ TEST_F(TextStructureViewPublicTest, ExpandSubtreesEmpty) { } // Splits a single token into a syntax tree node with two leaves. -void FakeParseToken(TextStructureView* data, int offset, int node_tag) { - TokenSequence& tokens = data->MutableTokenStream(); +void FakeParseToken(TextStructureView *data, int offset, int node_tag) { + TokenSequence &tokens = data->MutableTokenStream(); tokens.push_back(TokenInfo(11, data->Contents().substr(0, offset))); tokens.push_back(TokenInfo(12, data->Contents().substr(offset))); - TokenStreamView& tokens_view = data->MutableTokenStreamView(); + TokenStreamView &tokens_view = data->MutableTokenStreamView(); tokens_view.push_back(tokens.begin()); tokens_view.push_back(tokens.begin() + 1); data->MutableSyntaxTree() = TNode(node_tag, Leaf(tokens[0]), Leaf(tokens[1])); @@ -484,7 +484,7 @@ TEST_F(TextStructureViewPublicTest, ExpandSubtreesOneLeaf) { std::string subtext(tokens_[0].text().data(), tokens_[0].text().length()); std::unique_ptr subanalysis(new TextStructure(subtext)); FakeParseToken(&subanalysis->MutableData(), divide, new_node_tag); - auto& replacement_node = down_cast(syntax_tree_.get()) + auto &replacement_node = down_cast(syntax_tree_.get()) ->mutable_children() .front(); TextStructureView::DeferredExpansion expansion{&replacement_node, @@ -518,7 +518,7 @@ TEST_F(TextStructureViewPublicTest, ExpandSubtreesMultipleLeaves) { std::string subtext(tokens_[0].text().data(), tokens_[0].text().length()); std::unique_ptr subanalysis(new TextStructure(subtext)); FakeParseToken(&subanalysis->MutableData(), divide1, new_node_tag1); - auto& replacement_node = down_cast(syntax_tree_.get()) + auto &replacement_node = down_cast(syntax_tree_.get()) ->mutable_children() .front(); TextStructureView::DeferredExpansion expansion{&replacement_node, @@ -530,7 +530,7 @@ TEST_F(TextStructureViewPublicTest, ExpandSubtreesMultipleLeaves) { std::string subtext(tokens_[3].text().data(), tokens_[3].text().length()); std::unique_ptr subanalysis(new TextStructure(subtext)); FakeParseToken(&subanalysis->MutableData(), divide2, new_node_tag2); - auto& replacement_node = down_cast(syntax_tree_.get()) + auto &replacement_node = down_cast(syntax_tree_.get()) ->mutable_children() .back(); TextStructureView::DeferredExpansion expansion{&replacement_node, diff --git a/common/text/text_structure_test_utils.cc b/common/text/text_structure_test_utils.cc index b76642e85..2fd841459 100644 --- a/common/text/text_structure_test_utils.cc +++ b/common/text/text_structure_test_utils.cc @@ -34,30 +34,30 @@ namespace verible { -std::string JoinLinesOfTokensIntoString(const LinesOfTokens& lines_of_tokens) { +std::string JoinLinesOfTokensIntoString(const LinesOfTokens &lines_of_tokens) { std::vector token_strings; std::vector line_strings; line_strings.reserve(lines_of_tokens.size()); // Concatenate string_views over all tokens and all lines. - for (const auto& line : lines_of_tokens) { + for (const auto &line : lines_of_tokens) { token_strings.clear(); token_strings.resize(line.size()); CHECK_EQ(line.back().text(), "\n"); std::transform(line.begin(), line.end(), token_strings.begin(), - [](const TokenInfo& t) { return t.text(); }); + [](const TokenInfo &t) { return t.text(); }); line_strings.push_back(absl::StrJoin(token_strings, "")); } return absl::StrJoin(line_strings, ""); } TextStructureTokenized::TextStructureTokenized( - const LinesOfTokens& lines_of_tokens) + const LinesOfTokens &lines_of_tokens) : TextStructure(JoinLinesOfTokensIntoString(lines_of_tokens)) { size_t offset = 0; - auto& new_tokens = data_.MutableTokenStream(); + auto &new_tokens = data_.MutableTokenStream(); const auto joined_text = data_.Contents(); - for (const auto& line : lines_of_tokens) { - for (const auto& token : line) { + for (const auto &line : lines_of_tokens) { + for (const auto &token : line) { new_tokens.push_back(token); // Maintain the invariant that all tokens in a TextStructureView // must belong to the string owned by the TextStructure. @@ -74,19 +74,19 @@ TextStructureTokenized::TextStructureTokenized( std::unique_ptr MakeTextStructureViewHelloWorld() { auto text_structure_view = std::make_unique("hello, world"); - TokenSequence& tokens = text_structure_view->MutableTokenStream(); + TokenSequence &tokens = text_structure_view->MutableTokenStream(); const absl::string_view text_view = text_structure_view->Contents(); tokens.push_back(TokenInfo(0, text_view.substr(0, 5))); // "hello" tokens.push_back(TokenInfo(1, text_view.substr(5, 1))); // "," tokens.push_back(TokenInfo(2, text_view.substr(6, 1))); // " " tokens.push_back(TokenInfo(3, text_view.substr(7, 5))); // "world" - TokenStreamView& view = text_structure_view->MutableTokenStreamView(); + TokenStreamView &view = text_structure_view->MutableTokenStreamView(); view.push_back(tokens.begin()); view.push_back(tokens.begin() + 1); view.push_back(tokens.begin() + 3); SymbolPtr syntax_tree = Node(Leaf(tokens[0]), Leaf(tokens[1]), Node(Leaf(tokens[3]))); - ConcreteSyntaxTree& mutable_tree = text_structure_view->MutableSyntaxTree(); + ConcreteSyntaxTree &mutable_tree = text_structure_view->MutableSyntaxTree(); mutable_tree = std::move(syntax_tree); return text_structure_view; } @@ -95,7 +95,7 @@ std::unique_ptr MakeTextStructureViewHelloWorld() { std::unique_ptr MakeTextStructureViewWithNoLeaves() { auto text_structure_view = std::make_unique(""); SymbolPtr syntax_tree = Node(Node(), Node(), Node(Node(), Node())); - ConcreteSyntaxTree& mutable_tree = text_structure_view->MutableSyntaxTree(); + ConcreteSyntaxTree &mutable_tree = text_structure_view->MutableSyntaxTree(); mutable_tree = std::move(syntax_tree); return text_structure_view; } diff --git a/common/text/text_structure_test_utils.h b/common/text/text_structure_test_utils.h index 6216b413a..9286a265e 100644 --- a/common/text/text_structure_test_utils.h +++ b/common/text/text_structure_test_utils.h @@ -30,14 +30,14 @@ using LinesOfTokens = std::vector>; // Joins the text fields of TokenInfos into a newly allocated string. // All other fields of TokenInfos are ignored. // Each lines of tokens must end with a newline "\n" token. -std::string JoinLinesOfTokensIntoString(const LinesOfTokens&); +std::string JoinLinesOfTokensIntoString(const LinesOfTokens &); // Helper class for constructing a pre-tokenized text structure. // This avoids depending on any lexer for testing. class TextStructureTokenized : public TextStructure { public: // Each line of tokens - explicit TextStructureTokenized(const LinesOfTokens& lines_of_tokens); + explicit TextStructureTokenized(const LinesOfTokens &lines_of_tokens); }; // Return a text structure view of a "hello, world" string diff --git a/common/text/token_info.cc b/common/text/token_info.cc index 303a099a4..d30124506 100644 --- a/common/text/token_info.cc +++ b/common/text/token_info.cc @@ -37,7 +37,7 @@ TokenInfo TokenInfo::EOFToken(absl::string_view buffer) { return {TK_EOF, absl::string_view(buffer.end(), 0)}; } -bool TokenInfo::operator==(const TokenInfo& token) const { +bool TokenInfo::operator==(const TokenInfo &token) const { return token_enum_ == token.token_enum_ && (token_enum_ == TK_EOF || // All EOF tokens considered equal. BoundsEqual(text_, token.text_)); @@ -46,10 +46,10 @@ bool TokenInfo::operator==(const TokenInfo& token) const { TokenInfo::Context::Context(absl::string_view b) : base(b), // By default, just print the enum integer value, un-translated. - token_enum_translator([](std::ostream& stream, int e) { stream << e; }) {} + token_enum_translator([](std::ostream &stream, int e) { stream << e; }) {} -std::ostream& TokenInfo::ToStream(std::ostream& output_stream, - const Context& context) const { +std::ostream &TokenInfo::ToStream(std::ostream &output_stream, + const Context &context) const { output_stream << "(#"; context.token_enum_translator(output_stream, token_enum_); output_stream << " @" << left(context.base) << '-' << right(context.base) @@ -59,11 +59,11 @@ std::ostream& TokenInfo::ToStream(std::ostream& output_stream, return output_stream; } -std::ostream& TokenInfo::ToStream(std::ostream& output_stream) const { +std::ostream &TokenInfo::ToStream(std::ostream &output_stream) const { return output_stream << "(#" << token_enum_ << ": \"" << text_ << "\")"; } -std::string TokenInfo::ToString(const Context& context) const { +std::string TokenInfo::ToString(const Context &context) const { std::ostringstream output_stream; ToStream(output_stream, context); return output_stream.str(); @@ -79,18 +79,18 @@ void TokenInfo::RebaseStringView(absl::string_view new_text) { verible::RebaseStringView(&text_, new_text); } -void TokenInfo::Concatenate(std::string* out, std::vector* tokens) { +void TokenInfo::Concatenate(std::string *out, std::vector *tokens) { ConcatenateTokenInfos(out, tokens->begin(), tokens->end()); } // Print human-readable token information. -std::ostream& operator<<(std::ostream& stream, const TokenInfo& token) { +std::ostream &operator<<(std::ostream &stream, const TokenInfo &token) { // This will exclude any byte offset information because the base address // of the enclosing stream is not known to this function. return token.ToStream(stream); } -std::ostream& operator<<(std::ostream& stream, const TokenWithContext& t) { +std::ostream &operator<<(std::ostream &stream, const TokenWithContext &t) { return t.token.ToStream(stream, t.context); } diff --git a/common/text/token_info_json.cc b/common/text/token_info_json.cc index 69be706f2..260f7e1fa 100644 --- a/common/text/token_info_json.cc +++ b/common/text/token_info_json.cc @@ -20,8 +20,8 @@ namespace verible { -nlohmann::json ToJson(const TokenInfo& token_info, - const TokenInfo::Context& context, bool include_text) { +nlohmann::json ToJson(const TokenInfo &token_info, + const TokenInfo::Context &context, bool include_text) { nlohmann::json json(nlohmann::json::object()); std::ostringstream stream; context.token_enum_translator(stream, token_info.token_enum()); diff --git a/common/text/token_info_json.h b/common/text/token_info_json.h index fba2e0f9e..08865a803 100644 --- a/common/text/token_info_json.h +++ b/common/text/token_info_json.h @@ -21,8 +21,8 @@ namespace verible { // Returns JSON representation of TokenInfo -nlohmann::json ToJson(const TokenInfo& token_info, - const TokenInfo::Context& context, +nlohmann::json ToJson(const TokenInfo &token_info, + const TokenInfo::Context &context, bool include_text = false); } // namespace verible diff --git a/common/text/token_info_json_test.cc b/common/text/token_info_json_test.cc index 368627b16..9894c961c 100644 --- a/common/text/token_info_json_test.cc +++ b/common/text/token_info_json_test.cc @@ -67,7 +67,7 @@ TEST(TokenInfoToJsonTest, ToJsonWithTokenEnumTranslator) { const TokenInfo token_info(143, text); const verible::TokenInfo::Context context( - text, [](std::ostream& stream, int e) { stream << "token enum " << e; }); + text, [](std::ostream &stream, int e) { stream << "token enum " << e; }); EXPECT_EQ(ToJson(token_info, context), nlohmann::json::parse(R"({ "start": 0, diff --git a/common/text/token_info_test.cc b/common/text/token_info_test.cc index 50be0f6e9..0872b0d00 100644 --- a/common/text/token_info_test.cc +++ b/common/text/token_info_test.cc @@ -185,7 +185,7 @@ TEST(TokenInfoTest, ToStringWithBase) { EXPECT_EQ(token_info.ToString(context), "(#7 @9-12: \"cat\")"); } -void TokenTranslator(std::ostream& stream, int e) { +void TokenTranslator(std::ostream &stream, int e) { switch (e) { case 7: stream << "lucky-seven"; diff --git a/common/text/token_info_test_util.cc b/common/text/token_info_test_util.cc index 84ed6355f..148ad1b35 100644 --- a/common/text/token_info_test_util.cc +++ b/common/text/token_info_test_util.cc @@ -36,7 +36,7 @@ ExpectedTokenInfo::ExpectedTokenInfo(char token_enum_and_text) // address) at offset 0 or sizeof(int) -1. // Note: This constructor using a self-pointer makes this struct // non-default-copy/move/assign-able. - absl::string_view(reinterpret_cast(&token_enum_) + absl::string_view(reinterpret_cast(&token_enum_) #ifdef IS_BIG_ENDIAN + (sizeof(typeid(token_enum_)) - 1) #endif @@ -72,7 +72,7 @@ TokenInfoTestData::TokenInfoTestData( std::vector TokenInfoTestData::FindImportantTokens() const { std::vector return_tokens; std::copy_if(expected_tokens.begin(), expected_tokens.end(), - std::back_inserter(return_tokens), [](const TokenInfo& t) { + std::back_inserter(return_tokens), [](const TokenInfo &t) { return t.token_enum() != ExpectedTokenInfo::kDontCare; }); return return_tokens; @@ -85,13 +85,13 @@ std::vector TokenInfoTestData::FindImportantTokens( return return_tokens; } -void TokenInfoTestData::RebaseToCodeCopy(std::vector* tokens, +void TokenInfoTestData::RebaseToCodeCopy(std::vector *tokens, absl::string_view base) const { CHECK_EQ(code, base); // verify content match // Another analyzer object may have made its own copy of 'code', so // we need to translate the expected error token into a rebased version // before directly comparing against the rejected tokens. - for (TokenInfo& token : *tokens) { + for (TokenInfo &token : *tokens) { const auto offset = std::distance(absl::string_view(code).begin(), token.text().begin()); token.RebaseStringView(base.begin() + offset); diff --git a/common/text/token_info_test_util.h b/common/text/token_info_test_util.h index 7132df63c..508c559c9 100644 --- a/common/text/token_info_test_util.h +++ b/common/text/token_info_test_util.h @@ -53,7 +53,7 @@ struct ExpectedTokenInfo : public TokenInfo { // conversion through string_view, to work directly with string literals. // Implicit construction intentional. ExpectedTokenInfo( // NOLINT(google-explicit-constructor) - const char* token_text) + const char *token_text) : ExpectedTokenInfo(absl::string_view(token_text)) {} // delegating // Single-character token constructor, for the cases where the @@ -72,9 +72,9 @@ struct ExpectedTokenInfo : public TokenInfo { // Deleted interfaces. // Deleted because the (char) constructor points the text string_view member // to the internal token_enum member, creating a self-pointer. - ExpectedTokenInfo(const ExpectedTokenInfo&) = delete; - ExpectedTokenInfo(ExpectedTokenInfo&&) = delete; - ExpectedTokenInfo& operator=(const ExpectedTokenInfo&) = delete; + ExpectedTokenInfo(const ExpectedTokenInfo &) = delete; + ExpectedTokenInfo(ExpectedTokenInfo &&) = delete; + ExpectedTokenInfo &operator=(const ExpectedTokenInfo &) = delete; }; static_assert( @@ -98,11 +98,11 @@ struct TokenInfoTestData { // disallow copy/assign because of relationship between expected_tokens' // string_view and code string buffer. - TokenInfoTestData(const TokenInfoTestData&) = delete; - TokenInfoTestData& operator=(const TokenInfoTestData&) = delete; + TokenInfoTestData(const TokenInfoTestData &) = delete; + TokenInfoTestData &operator=(const TokenInfoTestData &) = delete; // No need for moveability (yet). - TokenInfoTestData(TokenInfoTestData&&) = delete; - TokenInfoTestData& operator=(TokenInfoTestData&&) = delete; + TokenInfoTestData(TokenInfoTestData &&) = delete; + TokenInfoTestData &operator=(TokenInfoTestData &&) = delete; // Returns subset of expected_tokens that are *not* enumerated // ExpectedTokenInfo::kDontCare. @@ -115,7 +115,7 @@ struct TokenInfoTestData { // Moves the locations of tokens into the range spanned by the 'base' buffer. // 'base' is another copy of (this) 'code' (content match is verified). - void RebaseToCodeCopy(std::vector* tokens, + void RebaseToCodeCopy(std::vector *tokens, absl::string_view base) const; }; diff --git a/common/text/token_info_test_util_test.cc b/common/text/token_info_test_util_test.cc index 30a1fee8b..60f2ddc7d 100644 --- a/common/text/token_info_test_util_test.cc +++ b/common/text/token_info_test_util_test.cc @@ -37,13 +37,13 @@ TEST(TokenInfoTestDataTest, ConstructorStringLiteral) { }; EXPECT_EQ(test_data.code, "foobar"); - const auto& first(test_data.expected_tokens.front()); + const auto &first(test_data.expected_tokens.front()); EXPECT_EQ(first.text(), "foo"); EXPECT_EQ(first.token_enum(), ExpectedTokenInfo::kDontCare); EXPECT_EQ(first.left(test_data.code), 0); EXPECT_EQ(first.right(test_data.code), 3); - const auto& second(test_data.expected_tokens.back()); + const auto &second(test_data.expected_tokens.back()); EXPECT_EQ(second.text(), "bar"); EXPECT_EQ(second.token_enum(), ExpectedTokenInfo::kDontCare); EXPECT_EQ(second.left(test_data.code), 3); @@ -65,13 +65,13 @@ TEST(TokenInfoTestDataTest, ConstructorCharEnum) { }; EXPECT_EQ(test_data.code, "()"); - const auto& first(test_data.expected_tokens.front()); + const auto &first(test_data.expected_tokens.front()); EXPECT_EQ(first.text(), "("); EXPECT_EQ(first.token_enum(), '('); EXPECT_EQ(first.left(test_data.code), 0); EXPECT_EQ(first.right(test_data.code), 1); - const auto& second(test_data.expected_tokens.back()); + const auto &second(test_data.expected_tokens.back()); EXPECT_EQ(second.text(), ")"); EXPECT_EQ(second.token_enum(), ')'); EXPECT_EQ(second.left(test_data.code), 1); @@ -91,13 +91,13 @@ TEST(TokenInfoTestDataTest, ConstructorEnumAndStringLiteral) { }; EXPECT_EQ(test_data.code, "foobar"); - const auto& first(test_data.expected_tokens.front()); + const auto &first(test_data.expected_tokens.front()); EXPECT_EQ(first.text(), "foo"); EXPECT_EQ(first.token_enum(), 8); EXPECT_EQ(first.left(test_data.code), 0); EXPECT_EQ(first.right(test_data.code), 3); - const auto& second(test_data.expected_tokens.back()); + const auto &second(test_data.expected_tokens.back()); EXPECT_EQ(second.text(), "bar"); EXPECT_EQ(second.token_enum(), 7); EXPECT_EQ(second.left(test_data.code), 3); @@ -110,7 +110,7 @@ TEST(TokenInfoTestDataTest, ConstructorHeterogeneousInitializer) { // written as enumeration values generated by yacc/bison. const TokenInfoTestData test_data = {{8, "foo"}, " ", '(', {7, "bar"}, ')'}; EXPECT_EQ(test_data.code, "foo (bar)"); - const auto& expected_tokens = test_data.expected_tokens; + const auto &expected_tokens = test_data.expected_tokens; ASSERT_EQ(expected_tokens.size(), 5); EXPECT_EQ(expected_tokens[0].text(), "foo"); @@ -147,7 +147,7 @@ TEST(TokenInfoTestDataTest, FindImportantTokensTest) { {8, "foo"}, " ", '(', {7, "bar"}, " ", "/* comment */", ')', }; EXPECT_EQ(test_data.code, "foo (bar /* comment */)"); - const auto& expected_tokens = test_data.expected_tokens; + const auto &expected_tokens = test_data.expected_tokens; EXPECT_EQ(expected_tokens.size(), 7); const auto key_tokens = test_data.FindImportantTokens(); EXPECT_EQ(key_tokens.size(), 4); diff --git a/common/text/token_stream_view.cc b/common/text/token_stream_view.cc index a66438905..5881c824d 100644 --- a/common/text/token_stream_view.cc +++ b/common/text/token_stream_view.cc @@ -24,7 +24,7 @@ namespace verible { -void InitTokenStreamView(const TokenSequence& tokens, TokenStreamView* view) { +void InitTokenStreamView(const TokenSequence &tokens, TokenStreamView *view) { view->resize(tokens.size()); auto iter = tokens.begin(); const auto end = tokens.end(); @@ -34,30 +34,30 @@ void InitTokenStreamView(const TokenSequence& tokens, TokenStreamView* view) { } } -void FilterTokenStreamView(const TokenFilterPredicate& keep, - const TokenStreamView& src, TokenStreamView* dest) { +void FilterTokenStreamView(const TokenFilterPredicate &keep, + const TokenStreamView &src, TokenStreamView *dest) { dest->clear(); dest->reserve(src.size() / 2); // Estimate size of filtered result. - for (const auto& iter : src) { + for (const auto &iter : src) { if (keep(*iter)) { dest->push_back(iter); } } } -void FilterTokenStreamViewInPlace(const TokenFilterPredicate& keep, - TokenStreamView* view) { +void FilterTokenStreamViewInPlace(const TokenFilterPredicate &keep, + TokenStreamView *view) { TokenStreamView temp; FilterTokenStreamView(keep, *view, &temp); view->swap(temp); // old stream view deleted at end-of-scope } -static bool TokenLocationLess(const TokenSequence::const_iterator& token_iter, - const char* offset) { +static bool TokenLocationLess(const TokenSequence::const_iterator &token_iter, + const char *offset) { return token_iter->text().begin() < offset; } -TokenViewRange TokenViewRangeSpanningOffsets(const TokenStreamView& view, +TokenViewRange TokenViewRangeSpanningOffsets(const TokenStreamView &view, absl::string_view range) { const auto lower = range.begin(); const auto upper = range.end(); diff --git a/common/text/token_stream_view.h b/common/text/token_stream_view.h index e5562ad36..b17b25a25 100644 --- a/common/text/token_stream_view.h +++ b/common/text/token_stream_view.h @@ -46,22 +46,22 @@ using TokenStreamReferenceView = std::vector; using TokenViewRange = iterator_range; // Tokens that evaluate to false with these predicates are removed. -using TokenFilterPredicate = std::function; +using TokenFilterPredicate = std::function; // Populates a TokenStreamView with every iterator of a TokenSequence. -void InitTokenStreamView(const TokenSequence&, TokenStreamView*); +void InitTokenStreamView(const TokenSequence &, TokenStreamView *); // Create a new TokenStreamView with tokens conditionally omitted. -void FilterTokenStreamView(const TokenFilterPredicate& keep, - const TokenStreamView& src, TokenStreamView* dest); +void FilterTokenStreamView(const TokenFilterPredicate &keep, + const TokenStreamView &src, TokenStreamView *dest); // Remove tokens from a TokenStreamView according to a predicate. -void FilterTokenStreamViewInPlace(const TokenFilterPredicate& keep, - TokenStreamView*); +void FilterTokenStreamViewInPlace(const TokenFilterPredicate &keep, + TokenStreamView *); // Returns iterator range of TokenSequence iterators that span the given file // offsets. The second iterator points 1-past-the-end of the range. -TokenViewRange TokenViewRangeSpanningOffsets(const TokenStreamView& view, +TokenViewRange TokenViewRangeSpanningOffsets(const TokenStreamView &view, absl::string_view range); } // namespace verible diff --git a/common/text/token_stream_view_test.cc b/common/text/token_stream_view_test.cc index 114500803..ad6c8a61e 100644 --- a/common/text/token_stream_view_test.cc +++ b/common/text/token_stream_view_test.cc @@ -36,7 +36,7 @@ class TokenStreamViewTest : public testing::Test { tokens_.push_back(TokenInfo::EOFToken()); } - static bool KeepEvenTokens(const TokenInfo& t) { + static bool KeepEvenTokens(const TokenInfo &t) { return !(t.token_enum() & 0x1); } @@ -101,7 +101,7 @@ TEST_F(TokenViewRangeTest, TokenViewRangeSpanningOffsetsNonEmpty) { {9, 12, 4, 4}, // empty, does not span a whole token {9, 9, 4, 4}, {9, 19, 4, 7}, }; - for (const auto& test_case : test_cases) { + for (const auto &test_case : test_cases) { const int length = test_case.right_offset - test_case.left_offset; const absl::string_view text_range( data_.Contents().substr(test_case.left_offset, length)); diff --git a/common/text/tree_builder_test_util.cc b/common/text/tree_builder_test_util.cc index 201f85255..44f3d6614 100644 --- a/common/text/tree_builder_test_util.cc +++ b/common/text/tree_builder_test_util.cc @@ -26,11 +26,11 @@ constexpr absl::string_view kDontCareText(""); SymbolPtr XLeaf(int token_enum) { return Leaf(token_enum, kDontCareText); } -const Symbol* DescendPath(const Symbol& symbol, +const Symbol *DescendPath(const Symbol &symbol, std::initializer_list path) { - const Symbol* node = &symbol; - for (const auto& index : path) { - const auto& children = SymbolCastToNode(*ABSL_DIE_IF_NULL(node)).children(); + const Symbol *node = &symbol; + for (const auto &index : path) { + const auto &children = SymbolCastToNode(*ABSL_DIE_IF_NULL(node)).children(); CHECK_LT(index, children.size()); // bounds check, like ::at() node = children[index].get(); } diff --git a/common/text/tree_builder_test_util.h b/common/text/tree_builder_test_util.h index 43a10185a..27c2f9696 100644 --- a/common/text/tree_builder_test_util.h +++ b/common/text/tree_builder_test_util.h @@ -35,7 +35,7 @@ SymbolPtr TNode(Enum e, Args... args) { } template -SymbolPtr Leaf(Args&&... args) { +SymbolPtr Leaf(Args &&...args) { return SymbolPtr(new SyntaxTreeLeaf(std::forward(args)...)); } @@ -50,7 +50,7 @@ SymbolPtr XLeaf(int token_enum); // contents of hand-crafted trees. // This variant does not check node enums. // TODO(fangism): implement one that verifies node enums. -const Symbol* DescendPath(const Symbol& symbol, +const Symbol *DescendPath(const Symbol &symbol, std::initializer_list path); } // namespace verible diff --git a/common/text/tree_builder_test_util_test.cc b/common/text/tree_builder_test_util_test.cc index abcdb7214..ed1f66b1b 100644 --- a/common/text/tree_builder_test_util_test.cc +++ b/common/text/tree_builder_test_util_test.cc @@ -78,8 +78,8 @@ TEST(DescendPathTest, NodeNodeNode) { // Tests that descending reaches two terminal leaves. TEST(DescendPathTest, NodeTwoLeaves) { SymbolPtr node = Node(Leaf(0, "more"), Leaf(0, "text")); - const auto* leaf0 = &SymbolCastToLeaf(*DescendPath(*node, {0})); - const auto* leaf1 = &SymbolCastToLeaf(*DescendPath(*node, {1})); + const auto *leaf0 = &SymbolCastToLeaf(*DescendPath(*node, {0})); + const auto *leaf1 = &SymbolCastToLeaf(*DescendPath(*node, {1})); EXPECT_NE(leaf0, nullptr); EXPECT_NE(leaf1, nullptr); EXPECT_NE(leaf0, leaf1); @@ -89,8 +89,8 @@ TEST(DescendPathTest, NodeTwoLeaves) { // Tests that descending stops as a node with multiple children nodes. TEST(DescendPathTest, NodeTwoSubNodes) { SymbolPtr node = Node(Node(), Node()); - const auto* subnode0 = &SymbolCastToNode(*DescendPath(*node, {0})); - const auto* subnode1 = &SymbolCastToNode(*DescendPath(*node, {1})); + const auto *subnode0 = &SymbolCastToNode(*DescendPath(*node, {0})); + const auto *subnode1 = &SymbolCastToNode(*DescendPath(*node, {1})); EXPECT_NE(subnode0, nullptr); EXPECT_NE(subnode1, nullptr); EXPECT_NE(subnode0, subnode1); @@ -100,8 +100,8 @@ TEST(DescendPathTest, NodeTwoSubNodes) { // Tests that descending stops as a node with multiple children, some null. TEST(DescendPathTest, NodeFirstChildLeafSecondChildNull) { SymbolPtr node = Node(Leaf(0, "text"), nullptr); - const auto* leaf0 = &SymbolCastToLeaf(*DescendPath(*node, {0})); - const auto* leaf1 = DescendPath(*node, {1}); + const auto *leaf0 = &SymbolCastToLeaf(*DescendPath(*node, {0})); + const auto *leaf1 = DescendPath(*node, {1}); EXPECT_NE(leaf0, nullptr); EXPECT_EQ(leaf1, nullptr); EXPECT_DEATH(DescendPath(*node, {2}), ""); // out-of-bounds @@ -111,8 +111,8 @@ TEST(DescendPathTest, NodeFirstChildLeafSecondChildNull) { // Tests that descending stops as a node with multiple children, some null. TEST(DescendPathTest, NodeFirstChildNullSecondChildLeaf) { SymbolPtr node = Node(nullptr, Leaf(0, "text")); - const auto* leaf0 = DescendPath(*node, {0}); - const auto* leaf1 = &SymbolCastToLeaf(*DescendPath(*node, {1})); + const auto *leaf0 = DescendPath(*node, {0}); + const auto *leaf1 = &SymbolCastToLeaf(*DescendPath(*node, {1})); EXPECT_EQ(leaf0, nullptr); EXPECT_NE(leaf1, nullptr); EXPECT_DEATH(DescendPath(*node, {2}), ""); // out-of-bounds @@ -122,8 +122,8 @@ TEST(DescendPathTest, NodeFirstChildNullSecondChildLeaf) { // Tests that descending stops as a node with multiple children, some null. TEST(DescendPathTest, NodeFirstChildNullSecondChildNode) { SymbolPtr node = Node(nullptr, Node()); - const auto* subnode0 = DescendPath(*node, {0}); - const auto* subnode1 = &SymbolCastToNode(*DescendPath(*node, {1})); + const auto *subnode0 = DescendPath(*node, {0}); + const auto *subnode1 = &SymbolCastToNode(*DescendPath(*node, {1})); EXPECT_EQ(subnode0, nullptr); EXPECT_NE(subnode1, nullptr); EXPECT_DEATH(DescendPath(*node, {2}), ""); // out-of-bounds @@ -133,8 +133,8 @@ TEST(DescendPathTest, NodeFirstChildNullSecondChildNode) { // Tests that descending stops as a node with multiple children, some null. TEST(DescendPathTest, NodeFirstChildNodeSecondChildNull) { SymbolPtr node = Node(Node(), nullptr); - const auto* subnode0 = &SymbolCastToNode(*DescendPath(*node, {0})); - const auto* subnode1 = DescendPath(*node, {1}); + const auto *subnode0 = &SymbolCastToNode(*DescendPath(*node, {0})); + const auto *subnode1 = DescendPath(*node, {1}); EXPECT_NE(subnode0, nullptr); EXPECT_EQ(subnode1, nullptr); EXPECT_DEATH(DescendPath(*node, {2}), ""); // out-of-bounds diff --git a/common/text/tree_compare.cc b/common/text/tree_compare.cc index 9c9070d93..d3268fe00 100644 --- a/common/text/tree_compare.cc +++ b/common/text/tree_compare.cc @@ -20,35 +20,35 @@ namespace verible { -bool EqualTrees(const Symbol* lhs, const Symbol* rhs, - const TokenComparator& compare_tokens) { +bool EqualTrees(const Symbol *lhs, const Symbol *rhs, + const TokenComparator &compare_tokens) { if (lhs == nullptr && rhs == nullptr) { return true; } if (lhs == nullptr || rhs == nullptr) { return false; } - const Symbol* rhs_pointer = rhs; + const Symbol *rhs_pointer = rhs; return lhs->equals(rhs_pointer, compare_tokens); } -bool EqualTrees(const Symbol* lhs, const Symbol* rhs) { +bool EqualTrees(const Symbol *lhs, const Symbol *rhs) { return EqualTrees(lhs, rhs, &TokenInfo::operator==); } -bool EqualTreesByEnum(const Symbol* lhs, const Symbol* rhs) { +bool EqualTreesByEnum(const Symbol *lhs, const Symbol *rhs) { return EqualTrees(lhs, rhs, EqualByEnum); } -bool EqualTreesByEnumString(const Symbol* lhs, const Symbol* rhs) { +bool EqualTreesByEnumString(const Symbol *lhs, const Symbol *rhs) { return EqualTrees(lhs, rhs, EqualByEnumString); } -bool EqualByEnum(const TokenInfo& lhs, const TokenInfo& rhs) { +bool EqualByEnum(const TokenInfo &lhs, const TokenInfo &rhs) { return lhs.token_enum() == rhs.token_enum(); } -bool EqualByEnumString(const TokenInfo& lhs, const TokenInfo& rhs) { +bool EqualByEnumString(const TokenInfo &lhs, const TokenInfo &rhs) { return lhs.token_enum() == rhs.token_enum() && lhs.text() == rhs.text(); } diff --git a/common/text/tree_compare.h b/common/text/tree_compare.h index b1d8a5134..1663509ea 100644 --- a/common/text/tree_compare.h +++ b/common/text/tree_compare.h @@ -24,26 +24,27 @@ namespace verible { -using TokenComparator = std::function; +using TokenComparator = + std::function; // Compares two SyntaxTrees. Two trees are equal if they have the same // structure and every TokenInfo is equal under compare_tokens. -bool EqualTrees(const Symbol* lhs, const Symbol* rhs, - const TokenComparator& compare_tokens); +bool EqualTrees(const Symbol *lhs, const Symbol *rhs, + const TokenComparator &compare_tokens); // Compare two syntax trees exactly, using TokenInfo equality. -bool EqualTrees(const Symbol* lhs, const Symbol* rhs); +bool EqualTrees(const Symbol *lhs, const Symbol *rhs); // Compares two tree using the EqualTrees with the EqualByEnum function -bool EqualTreesByEnum(const Symbol* lhs, const Symbol* rhs); +bool EqualTreesByEnum(const Symbol *lhs, const Symbol *rhs); // compare two trees using EqualTrees with the EqualByEnumString function -bool EqualTreesByEnumString(const Symbol* lhs, const Symbol* rhs); +bool EqualTreesByEnumString(const Symbol *lhs, const Symbol *rhs); // Compare two TokenInfo by their enum -bool EqualByEnum(const TokenInfo& lhs, const TokenInfo& rhs); +bool EqualByEnum(const TokenInfo &lhs, const TokenInfo &rhs); // Compare two TokenInfo by both enum and text -bool EqualByEnumString(const TokenInfo& lhs, const TokenInfo& rhs); +bool EqualByEnumString(const TokenInfo &lhs, const TokenInfo &rhs); } // namespace verible diff --git a/common/text/tree_context_visitor.cc b/common/text/tree_context_visitor.cc index 8b1a443ef..e12c39251 100644 --- a/common/text/tree_context_visitor.cc +++ b/common/text/tree_context_visitor.cc @@ -20,9 +20,9 @@ namespace verible { -void TreeContextVisitor::Visit(const SyntaxTreeNode& node) { +void TreeContextVisitor::Visit(const SyntaxTreeNode &node) { const SyntaxTreeContext::AutoPop p(¤t_context_, &node); - for (const auto& child : node.children()) { + for (const auto &child : node.children()) { if (child) child->Accept(this); } } @@ -31,37 +31,37 @@ namespace { template class AutoPopBack { public: - explicit AutoPopBack(V* v) : vec_(v) { vec_->push_back(0); } + explicit AutoPopBack(V *v) : vec_(v) { vec_->push_back(0); } ~AutoPopBack() { vec_->pop_back(); } private: - V* vec_; + V *vec_; }; } // namespace -void TreeContextPathVisitor::Visit(const SyntaxTreeNode& node) { +void TreeContextPathVisitor::Visit(const SyntaxTreeNode &node) { const SyntaxTreeContext::AutoPop c(¤t_context_, &node); const AutoPopBack p(¤t_path_); - for (const auto& child : node.children()) { + for (const auto &child : node.children()) { if (child) child->Accept(this); ++current_path_.back(); } } SequenceStreamFormatter TreePathFormatter( - const SyntaxTreePath& path) { + const SyntaxTreePath &path) { return SequenceFormatter(path, ",", "[", "]"); } -SyntaxTreePath NextSiblingPath(const SyntaxTreePath& path) { +SyntaxTreePath NextSiblingPath(const SyntaxTreePath &path) { CHECK(!path.empty()); auto next = path; ++next.back(); return next; } -static int CompareSyntaxTreePath(const SyntaxTreePath& a, - const SyntaxTreePath& b, int index) { +static int CompareSyntaxTreePath(const SyntaxTreePath &a, + const SyntaxTreePath &b, int index) { // a[index] ? b[index] if (int(a.size()) > index && int(b.size()) > index) { if (a[index] < b[index]) return -1; @@ -76,7 +76,7 @@ static int CompareSyntaxTreePath(const SyntaxTreePath& a, return 0; } -int CompareSyntaxTreePath(const SyntaxTreePath& a, const SyntaxTreePath& b) { +int CompareSyntaxTreePath(const SyntaxTreePath &a, const SyntaxTreePath &b) { return CompareSyntaxTreePath(a, b, 0); } diff --git a/common/text/tree_context_visitor.h b/common/text/tree_context_visitor.h index 963eedacc..687bc8559 100644 --- a/common/text/tree_context_visitor.h +++ b/common/text/tree_context_visitor.h @@ -28,10 +28,10 @@ class TreeContextVisitor : public SymbolVisitor { TreeContextVisitor() = default; protected: - void Visit(const SyntaxTreeLeaf& leaf) override {} - void Visit(const SyntaxTreeNode& node) override; + void Visit(const SyntaxTreeLeaf &leaf) override {} + void Visit(const SyntaxTreeNode &node) override; - const SyntaxTreeContext& Context() const { return current_context_; } + const SyntaxTreeContext &Context() const { return current_context_; } // Keeps track of ancestors as the visitor traverses tree. SyntaxTreeContext current_context_; @@ -43,7 +43,7 @@ class SyntaxTreePath; // elements are assumed to have values that are less than 0 but greater than any // negative number. First non-matching elements pair determines the result: // -1 if a < b, 1 if a > b. If all pairs are equal the result is 0. -int CompareSyntaxTreePath(const SyntaxTreePath& a, const SyntaxTreePath& b); +int CompareSyntaxTreePath(const SyntaxTreePath &a, const SyntaxTreePath &b); // Type that is used to keep track of positions descended from a root // node to reach a particular node. @@ -63,18 +63,18 @@ class SyntaxTreePath : public std::vector { public: using std::vector::vector; // Import base class constructors - bool operator==(const SyntaxTreePath& rhs) const { + bool operator==(const SyntaxTreePath &rhs) const { return CompareSyntaxTreePath(*this, rhs) == 0; } - bool operator<(const SyntaxTreePath& rhs) const { + bool operator<(const SyntaxTreePath &rhs) const { return CompareSyntaxTreePath(*this, rhs) < 0; } - bool operator>(const SyntaxTreePath& rhs) const { + bool operator>(const SyntaxTreePath &rhs) const { return CompareSyntaxTreePath(*this, rhs) > 0; } - bool operator!=(const SyntaxTreePath& rhs) const { return !(*this == rhs); } - bool operator<=(const SyntaxTreePath& rhs) const { return !(*this > rhs); } - bool operator>=(const SyntaxTreePath& rhs) const { return !(*this < rhs); } + bool operator!=(const SyntaxTreePath &rhs) const { return !(*this == rhs); } + bool operator<=(const SyntaxTreePath &rhs) const { return !(*this > rhs); } + bool operator>=(const SyntaxTreePath &rhs) const { return !(*this < rhs); } }; // This visitor traverses a tree and maintains a stack of offsets @@ -87,9 +87,9 @@ class TreeContextPathVisitor : public TreeContextVisitor { TreeContextPathVisitor() = default; protected: - void Visit(const SyntaxTreeNode& node) override; + void Visit(const SyntaxTreeNode &node) override; - const SyntaxTreePath& Path() const { return current_path_; } + const SyntaxTreePath &Path() const { return current_path_; } // Keeps track of path of descent from root node. SyntaxTreePath current_path_; @@ -98,14 +98,14 @@ class TreeContextPathVisitor : public TreeContextVisitor { // Computes the path of the next sibling by incrementing the last element // of the path. Resulting path may not necessarily correspond to a valid // element. 'path' must not be empty. -SyntaxTreePath NextSiblingPath(const SyntaxTreePath& path); +SyntaxTreePath NextSiblingPath(const SyntaxTreePath &path); // Format SyntaxTreePaths using: stream << TreePathFormatter(path); // It is necessary to define this way because SyntaxTreePath is a typedef to a // generic container type. // TODO(fangism): Use auto return type once C++17 become the minimum standard. SequenceStreamFormatter TreePathFormatter( - const SyntaxTreePath& path); + const SyntaxTreePath &path); } // namespace verible diff --git a/common/text/tree_context_visitor_test.cc b/common/text/tree_context_visitor_test.cc index f733f4b0f..a7fdd22fc 100644 --- a/common/text/tree_context_visitor_test.cc +++ b/common/text/tree_context_visitor_test.cc @@ -25,9 +25,9 @@ namespace { using ::testing::ElementsAreArray; -static std::vector ContextToTags(const SyntaxTreeContext& context) { +static std::vector ContextToTags(const SyntaxTreeContext &context) { std::vector values; - for (const auto& ancestor : context) { + for (const auto &ancestor : context) { values.push_back(ancestor->Tag().tag); } return values; @@ -37,11 +37,11 @@ static std::vector ContextToTags(const SyntaxTreeContext& context) { template class ContextRecorder : public BaseVisitor { public: - void Visit(const SyntaxTreeLeaf& leaf) final { + void Visit(const SyntaxTreeLeaf &leaf) final { context_history_.push_back(BaseVisitor::Context()); } - void Visit(const SyntaxTreeNode& node) final { + void Visit(const SyntaxTreeNode &node) final { context_history_.push_back(BaseVisitor::Context()); BaseVisitor::Visit(node); } @@ -49,7 +49,7 @@ class ContextRecorder : public BaseVisitor { std::vector> ContextTagHistory() const { std::vector> result; result.reserve(context_history_.size()); - for (const auto& context : context_history_) { + for (const auto &context : context_history_) { result.emplace_back(ContextToTags(context)); } return result; @@ -60,8 +60,8 @@ class ContextRecorder : public BaseVisitor { }; template -static void TestContextRecorder(const SymbolPtr& tree, - const std::vector>& expect) { +static void TestContextRecorder(const SymbolPtr &tree, + const std::vector> &expect) { ContextRecorder r; tree->Accept(&r); EXPECT_THAT(r.ContextTagHistory(), ElementsAreArray(expect)); @@ -72,8 +72,8 @@ static void TestContextRecorder(const SymbolPtr& tree, // directly use the visitor in the base class, and might have to duplicate // some functionality. This ensures proper coverage, regardless of the // implementation. -static void TestContextRecorders(const SymbolPtr& tree, - const std::vector>& expect) { +static void TestContextRecorders(const SymbolPtr &tree, + const std::vector> &expect) { TestContextRecorder(tree, expect); TestContextRecorder(tree, expect); } @@ -141,16 +141,16 @@ TEST(TreeContextVisitorTest, FullTree) { // Test class demonstrating visitation and path tracking class PathRecorder : public TreeContextPathVisitor { public: - void Visit(const SyntaxTreeLeaf& leaf) final { + void Visit(const SyntaxTreeLeaf &leaf) final { path_history_.push_back(Path()); } - void Visit(const SyntaxTreeNode& node) final { + void Visit(const SyntaxTreeNode &node) final { path_history_.push_back(Path()); TreeContextPathVisitor::Visit(node); } - const std::vector& PathTagHistory() const { + const std::vector &PathTagHistory() const { return path_history_; } @@ -318,7 +318,7 @@ TEST(NextSiblingPathTest, Various) { {{0, 0}, {0, 1}}, // {{1, 1, 1, 1, 1}, {1, 1, 1, 1, 2}}, // }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { EXPECT_EQ(NextSiblingPath(test.first), test.second); } } @@ -331,7 +331,7 @@ TEST(TreePathFormatterTest, Various) { {{0, 1}, "[0,1]"}, // {{1, 1, 2, 3, 5}, "[1,1,2,3,5]"}, // }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { std::ostringstream stream; stream << TreePathFormatter(test.first); EXPECT_EQ(stream.str(), test.second); @@ -369,7 +369,7 @@ TEST(SyntaxTreePathTest, Equal) { SyntaxTreePath{11, 0, -2}, }, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { EXPECT_TRUE(test.first == test.second); EXPECT_TRUE(test.first >= test.second); EXPECT_TRUE(test.first <= test.second); @@ -407,7 +407,7 @@ TEST(SyntaxTreePathTest, LessThanAndGreaterThan) { SyntaxTreePath{1, 0, 2}, }, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { EXPECT_TRUE(test.first < test.second); EXPECT_TRUE(test.first <= test.second); EXPECT_TRUE(test.second > test.first); diff --git a/common/text/tree_utils.cc b/common/text/tree_utils.cc index 0693d5eb5..b7c47e2d6 100644 --- a/common/text/tree_utils.cc +++ b/common/text/tree_utils.cc @@ -36,13 +36,13 @@ namespace verible { -const Symbol* DescendThroughSingletons(const Symbol& symbol) { +const Symbol *DescendThroughSingletons(const Symbol &symbol) { if (symbol.Kind() == SymbolKind::kLeaf) { return &symbol; } // else is a kNode - const auto& node = SymbolCastToNode(symbol); - const auto& children = node.children(); + const auto &node = SymbolCastToNode(symbol); + const auto &children = node.children(); if (children.size() == 1 && children.front() != nullptr) { // If only child is non-null, descend. return DescendThroughSingletons(*children.front()); @@ -51,16 +51,16 @@ const Symbol* DescendThroughSingletons(const Symbol& symbol) { return &symbol; } -const SyntaxTreeLeaf* GetRightmostLeaf(const Symbol& symbol) { +const SyntaxTreeLeaf *GetRightmostLeaf(const Symbol &symbol) { if (symbol.Kind() == SymbolKind::kLeaf) { return &SymbolCastToLeaf(symbol); } - const auto& node = SymbolCastToNode(symbol); + const auto &node = SymbolCastToNode(symbol); - for (const auto& child : reversed_view(node.children())) { + for (const auto &child : reversed_view(node.children())) { if (child != nullptr) { - const auto* leaf = GetRightmostLeaf(*child); + const auto *leaf = GetRightmostLeaf(*child); if (leaf != nullptr) { return leaf; } @@ -70,16 +70,16 @@ const SyntaxTreeLeaf* GetRightmostLeaf(const Symbol& symbol) { return nullptr; } -const SyntaxTreeLeaf* GetLeftmostLeaf(const Symbol& symbol) { +const SyntaxTreeLeaf *GetLeftmostLeaf(const Symbol &symbol) { if (symbol.Kind() == SymbolKind::kLeaf) { return &SymbolCastToLeaf(symbol); } - const auto& node = SymbolCastToNode(symbol); + const auto &node = SymbolCastToNode(symbol); - for (const auto& child : node.children()) { + for (const auto &child : node.children()) { if (child != nullptr) { - const auto* leaf = GetLeftmostLeaf(*child); + const auto *leaf = GetLeftmostLeaf(*child); if (leaf != nullptr) { return leaf; } @@ -89,13 +89,13 @@ const SyntaxTreeLeaf* GetLeftmostLeaf(const Symbol& symbol) { return nullptr; } -absl::string_view StringSpanOfSymbol(const Symbol& symbol) { +absl::string_view StringSpanOfSymbol(const Symbol &symbol) { return StringSpanOfSymbol(symbol, symbol); } -absl::string_view StringSpanOfSymbol(const Symbol& lsym, const Symbol& rsym) { - const auto* left = GetLeftmostLeaf(lsym); - const auto* right = GetRightmostLeaf(rsym); +absl::string_view StringSpanOfSymbol(const Symbol &lsym, const Symbol &rsym) { + const auto *left = GetLeftmostLeaf(lsym); + const auto *right = GetRightmostLeaf(rsym); if (left != nullptr && right != nullptr) { const auto range_begin = left->get().text().begin(); const auto range_end = right->get().text().end(); @@ -105,25 +105,25 @@ absl::string_view StringSpanOfSymbol(const Symbol& lsym, const Symbol& rsym) { return ""; } -const SyntaxTreeNode& SymbolCastToNode(const Symbol& symbol) { +const SyntaxTreeNode &SymbolCastToNode(const Symbol &symbol) { // Assert the symbol is a node. CHECK_EQ(symbol.Kind(), SymbolKind::kNode) << "got: " << RawTreePrinter(symbol); - return down_cast(symbol); + return down_cast(symbol); } -SyntaxTreeNode& SymbolCastToNode(Symbol& symbol) { +SyntaxTreeNode &SymbolCastToNode(Symbol &symbol) { // Assert the symbol is a node. CHECK_EQ(symbol.Kind(), SymbolKind::kNode) << "got: " << RawTreePrinter(symbol); - return down_cast(symbol); + return down_cast(symbol); } -const SyntaxTreeLeaf& SymbolCastToLeaf(const Symbol& symbol) { +const SyntaxTreeLeaf &SymbolCastToLeaf(const Symbol &symbol) { // Assert the symbol is a leaf. CHECK_EQ(symbol.Kind(), SymbolKind::kLeaf) << "got: " << RawTreePrinter(symbol); - return down_cast(symbol); + return down_cast(symbol); } namespace { @@ -133,10 +133,10 @@ namespace { // modifying syntax trees. class FirstSubtreeFinderMutable : public MutableTreeVisitorRecursive { public: - explicit FirstSubtreeFinderMutable(const TreePredicate& predicate) + explicit FirstSubtreeFinderMutable(const TreePredicate &predicate) : predicate_(predicate) {} - void Visit(const SyntaxTreeNode& node, SymbolPtr* symbol_ptr) final { + void Visit(const SyntaxTreeNode &node, SymbolPtr *symbol_ptr) final { CHECK_EQ(symbol_ptr->get(), &node); // symbol_ptr owns node. if (result_ == nullptr) { // If this node matches, return it, and skip evaluating children. @@ -144,9 +144,9 @@ class FirstSubtreeFinderMutable : public MutableTreeVisitorRecursive { result_ = symbol_ptr; } else { // Cast the mutable copy of the node pointer (same object as &node). - auto* const mutable_node = - down_cast(symbol_ptr->get()); - for (SymbolPtr& child : mutable_node->mutable_children()) { + auto *const mutable_node = + down_cast(symbol_ptr->get()); + for (SymbolPtr &child : mutable_node->mutable_children()) { if (child != nullptr) { child->Accept(this, &child); } @@ -157,7 +157,7 @@ class FirstSubtreeFinderMutable : public MutableTreeVisitorRecursive { } } - void Visit(const SyntaxTreeLeaf& leaf, SymbolPtr* symbol_ptr) final { + void Visit(const SyntaxTreeLeaf &leaf, SymbolPtr *symbol_ptr) final { CHECK_EQ(symbol_ptr->get(), &leaf); // symbol_ptr owns leaf. // If already have a result, stop checking and return right away. if (result_ == nullptr) { @@ -167,14 +167,14 @@ class FirstSubtreeFinderMutable : public MutableTreeVisitorRecursive { } } - ConcreteSyntaxTree* result() const { return result_; } + ConcreteSyntaxTree *result() const { return result_; } private: // Matching criterion. TreePredicate predicate_; // Contains first matching result found or nullptr if no match is found. - ConcreteSyntaxTree* result_ = nullptr; + ConcreteSyntaxTree *result_ = nullptr; }; // FirstSubtreeFinder is a visitor class that supports the implementation of @@ -182,16 +182,16 @@ class FirstSubtreeFinderMutable : public MutableTreeVisitorRecursive { // exit early if a match is found. class FirstSubtreeFinder : public SymbolVisitor { public: - explicit FirstSubtreeFinder(const TreePredicate& predicate) + explicit FirstSubtreeFinder(const TreePredicate &predicate) : predicate_(predicate) {} - void Visit(const SyntaxTreeNode& node) final { + void Visit(const SyntaxTreeNode &node) final { if (result_ == nullptr) { // If this node matches, return it, and skip evaluating children. if (predicate_(node)) { result_ = &node; } else { - for (const SymbolPtr& child : node.children()) { + for (const SymbolPtr &child : node.children()) { if (child != nullptr) { child->Accept(this); } @@ -202,7 +202,7 @@ class FirstSubtreeFinder : public SymbolVisitor { } } - void Visit(const SyntaxTreeLeaf& leaf) final { + void Visit(const SyntaxTreeLeaf &leaf) final { // If already have a result, stop checking and return right away. if (result_ == nullptr) { if (predicate_(leaf)) { @@ -211,68 +211,68 @@ class FirstSubtreeFinder : public SymbolVisitor { } } - const Symbol* result() const { return result_; } + const Symbol *result() const { return result_; } private: // Matching criterion. TreePredicate predicate_; // Contains first matching result found or nullptr if no match is found. - const Symbol* result_ = nullptr; + const Symbol *result_ = nullptr; }; // A visitor that finds the last matching node. Inherits from // TreeVisitorRecursive, as it needs to visit all nodes in the tree. class LastSubtreeFinder : public TreeVisitorRecursive { public: - explicit LastSubtreeFinder(const TreePredicate& predicate) + explicit LastSubtreeFinder(const TreePredicate &predicate) : predicate_(predicate) {} - void Visit(const SyntaxTreeNode& node) final { + void Visit(const SyntaxTreeNode &node) final { if (predicate_(node)) result_ = &node; } - void Visit(const SyntaxTreeLeaf& leaf) final { + void Visit(const SyntaxTreeLeaf &leaf) final { if (predicate_(leaf)) result_ = &leaf; } - const Symbol* result() const { return result_; } + const Symbol *result() const { return result_; } private: // Matching criterion. TreePredicate predicate_; // Contains last matching result found or nullptr if no match is found. - const Symbol* result_ = nullptr; + const Symbol *result_ = nullptr; }; } // namespace -ConcreteSyntaxTree* FindFirstSubtreeMutable(ConcreteSyntaxTree* tree, - const TreePredicate& pred) { +ConcreteSyntaxTree *FindFirstSubtreeMutable(ConcreteSyntaxTree *tree, + const TreePredicate &pred) { if (*ABSL_DIE_IF_NULL(tree) == nullptr) return nullptr; FirstSubtreeFinderMutable finder(pred); (*tree)->Accept(&finder, tree); return finder.result(); } -const Symbol* FindFirstSubtree(const Symbol* tree, const TreePredicate& pred) { +const Symbol *FindFirstSubtree(const Symbol *tree, const TreePredicate &pred) { if (tree == nullptr) return nullptr; FirstSubtreeFinder finder(pred); tree->Accept(&finder); return finder.result(); } -const Symbol* FindLastSubtree(const Symbol* tree, const TreePredicate& pred) { +const Symbol *FindLastSubtree(const Symbol *tree, const TreePredicate &pred) { if (tree == nullptr) return nullptr; LastSubtreeFinder finder(pred); tree->Accept(&finder); return finder.result(); } -ConcreteSyntaxTree* FindSubtreeStartingAtOffset( - ConcreteSyntaxTree* tree, const char* first_token_offset) { - auto predicate = [=](const Symbol& s) { - const SyntaxTreeLeaf* leftmost = GetLeftmostLeaf(s); +ConcreteSyntaxTree *FindSubtreeStartingAtOffset( + ConcreteSyntaxTree *tree, const char *first_token_offset) { + auto predicate = [=](const Symbol &s) { + const SyntaxTreeLeaf *leftmost = GetLeftmostLeaf(s); if (leftmost != nullptr) { if (std::distance(first_token_offset, leftmost->get().text().begin()) >= 0) { @@ -281,7 +281,7 @@ ConcreteSyntaxTree* FindSubtreeStartingAtOffset( } return false; }; - ConcreteSyntaxTree* result = + ConcreteSyntaxTree *result = FindFirstSubtreeMutable(ABSL_DIE_IF_NULL(tree), predicate); // This cannot return a null tree node because it would have been skipped // by FirstSubtreeFinderMutable. @@ -292,17 +292,17 @@ ConcreteSyntaxTree* FindSubtreeStartingAtOffset( // Helper function for PruneSyntaxTreeAfterOffset namespace { // Returns true if this node should be deleted by parent (pop_back). -bool PruneTreeFromRight(ConcreteSyntaxTree* tree, const char* offset) { +bool PruneTreeFromRight(ConcreteSyntaxTree *tree, const char *offset) { const auto kind = (*ABSL_DIE_IF_NULL(tree))->Kind(); switch (kind) { case SymbolKind::kLeaf: { - auto* leaf = down_cast(tree->get()); + auto *leaf = down_cast(tree->get()); return std::distance(offset, leaf->get().text().end()) > 0; } case SymbolKind::kNode: { - auto& node = down_cast(*tree->get()); - auto& children = node.mutable_children(); - for (auto& child : reversed_view(children)) { + auto &node = down_cast(*tree->get()); + auto &children = node.mutable_children(); + for (auto &child : reversed_view(children)) { if (child == nullptr) { children.pop_back(); // pop_back() guaranteed to not realloc } else { @@ -325,39 +325,39 @@ bool PruneTreeFromRight(ConcreteSyntaxTree* tree, const char* offset) { } } // namespace -void PruneSyntaxTreeAfterOffset(ConcreteSyntaxTree* tree, const char* offset) { +void PruneSyntaxTreeAfterOffset(ConcreteSyntaxTree *tree, const char *offset) { PruneTreeFromRight(tree, offset); } // Helper functions for ZoomSyntaxTree namespace { // Return the upper bound offset of the rightmost token in the tree. -const char* RightmostOffset(const Symbol& symbol) { - const SyntaxTreeLeaf* leaf_ptr = verible::GetRightmostLeaf(symbol); +const char *RightmostOffset(const Symbol &symbol) { + const SyntaxTreeLeaf *leaf_ptr = verible::GetRightmostLeaf(symbol); return ABSL_DIE_IF_NULL(leaf_ptr)->get().text().end(); } // Return the first non-null child node/leaf of the immediate subtree. -ConcreteSyntaxTree* LeftSubtree(ConcreteSyntaxTree* tree) { +ConcreteSyntaxTree *LeftSubtree(ConcreteSyntaxTree *tree) { if ((ABSL_DIE_IF_NULL(*tree))->Kind() == verible::SymbolKind::kLeaf) { // Leaves don't have subtrees. return nullptr; } - auto& children = down_cast(*tree->get()).mutable_children(); - for (auto& child : children) { + auto &children = down_cast(*tree->get()).mutable_children(); + for (auto &child : children) { if (child != nullptr) return &child; } return nullptr; } } // namespace -ConcreteSyntaxTree* ZoomSyntaxTree(ConcreteSyntaxTree* tree, +ConcreteSyntaxTree *ZoomSyntaxTree(ConcreteSyntaxTree *tree, absl::string_view trim_range) { if (*tree == nullptr) return nullptr; const auto left_offset = trim_range.begin(); // Find shallowest syntax tree node that starts at the given byte offset. - ConcreteSyntaxTree* match = + ConcreteSyntaxTree *match = FindSubtreeStartingAtOffset(ABSL_DIE_IF_NULL(tree), left_offset); // Take leftmost subtree until its right bound falls within offset. @@ -369,8 +369,8 @@ ConcreteSyntaxTree* ZoomSyntaxTree(ConcreteSyntaxTree* tree, return match; } -void TrimSyntaxTree(ConcreteSyntaxTree* tree, absl::string_view trim_range) { - auto* replacement = ZoomSyntaxTree(tree, trim_range); +void TrimSyntaxTree(ConcreteSyntaxTree *tree, absl::string_view trim_range) { + auto *replacement = ZoomSyntaxTree(tree, trim_range); if (replacement == nullptr || *replacement == nullptr) { *tree = nullptr; } else { @@ -384,25 +384,25 @@ class LeafMutatorVisitor : public MutableTreeVisitorRecursive { public: // Maintains a reference but not ownership of the mutator, so the // mutator must outlive this object. - explicit LeafMutatorVisitor(const LeafMutator* mutator) + explicit LeafMutatorVisitor(const LeafMutator *mutator) : leaf_mutator_(*mutator) {} - void Visit(const SyntaxTreeNode&, SymbolPtr*) final {} + void Visit(const SyntaxTreeNode &, SymbolPtr *) final {} // Transforms a single leaf. - void Visit(const SyntaxTreeLeaf& leaf, SymbolPtr* leaf_owner) final { + void Visit(const SyntaxTreeLeaf &leaf, SymbolPtr *leaf_owner) final { CHECK_EQ(leaf_owner->get(), &leaf); - auto* const mutable_leaf = down_cast(leaf_owner->get()); + auto *const mutable_leaf = down_cast(leaf_owner->get()); leaf_mutator_(ABSL_DIE_IF_NULL(mutable_leaf)->get_mutable()); } private: // Mutation to apply to every leaf token. - const LeafMutator& leaf_mutator_; + const LeafMutator &leaf_mutator_; }; } // namespace -void MutateLeaves(ConcreteSyntaxTree* tree, const LeafMutator& mutator) { +void MutateLeaves(ConcreteSyntaxTree *tree, const LeafMutator &mutator) { if (*ABSL_DIE_IF_NULL(tree) != nullptr) { LeafMutatorVisitor visitor(&mutator); (*tree)->Accept(&visitor, tree); @@ -413,21 +413,21 @@ void MutateLeaves(ConcreteSyntaxTree* tree, const LeafMutator& mutator) { // Implementation of printing functions // -std::ostream& RawSymbolPrinter::auto_indent() { +std::ostream &RawSymbolPrinter::auto_indent() { return *stream_ << Spacer(indent_, ' '); } -void RawSymbolPrinter::Visit(const SyntaxTreeLeaf& leaf) { +void RawSymbolPrinter::Visit(const SyntaxTreeLeaf &leaf) { leaf.get().ToStream(auto_indent() << "Leaf @" << child_rank_ << ' ') << std::endl; } -void PrettyPrinter::Visit(const SyntaxTreeLeaf& leaf) { +void PrettyPrinter::Visit(const SyntaxTreeLeaf &leaf) { leaf.get().ToStream(auto_indent() << "Leaf @" << child_rank_ << ' ', context_) << std::endl; } -void RawSymbolPrinter::Visit(const SyntaxTreeNode& node) { +void RawSymbolPrinter::Visit(const SyntaxTreeNode &node) { std::string tag_info; const int tag = node.Tag().tag; if (tag != 0) tag_info = absl::StrCat("(tag: ", tag, ") "); @@ -438,7 +438,7 @@ void RawSymbolPrinter::Visit(const SyntaxTreeNode& node) { { const ValueSaver value_saver(&indent_, indent_ + 2); const ValueSaver rank_saver(&child_rank_, 0); - for (const auto& child : node.children()) { + for (const auto &child : node.children()) { if (child) { child->Accept(this); } else if (print_null_nodes_) { @@ -452,29 +452,29 @@ void RawSymbolPrinter::Visit(const SyntaxTreeNode& node) { auto_indent() << "}" << std::endl; } -std::ostream& RawTreePrinter::Print(std::ostream& stream) const { +std::ostream &RawTreePrinter::Print(std::ostream &stream) const { RawSymbolPrinter printer(&stream, print_null_nodes_); root_.Accept(&printer); return stream; } -std::ostream& operator<<(std::ostream& stream, const RawTreePrinter& printer) { +std::ostream &operator<<(std::ostream &stream, const RawTreePrinter &printer) { return printer.Print(stream); } -void PrettyPrintTree(const Symbol& root, const TokenInfo::Context& context, - std::ostream* stream) { +void PrettyPrintTree(const Symbol &root, const TokenInfo::Context &context, + std::ostream *stream) { PrettyPrinter printer(stream, context); root.Accept(&printer); } -std::ostream& TreePrettyPrinter::Print(std::ostream& stream) const { +std::ostream &TreePrettyPrinter::Print(std::ostream &stream) const { PrettyPrintTree(root_, context_, &stream); return stream; } -std::ostream& operator<<(std::ostream& stream, - const TreePrettyPrinter& printer) { +std::ostream &operator<<(std::ostream &stream, + const TreePrettyPrinter &printer) { return printer.Print(stream); } diff --git a/common/text/tree_utils.h b/common/text/tree_utils.h index d71d6caf4..34a6209e6 100644 --- a/common/text/tree_utils.h +++ b/common/text/tree_utils.h @@ -37,41 +37,41 @@ namespace verible { // If symbol is a leaf node, then it is its own rightmost/leftmost leaf // Otherwise, recursively try to find leftmost/rightmost leaf by searching // through node's children. -const SyntaxTreeLeaf* GetLeftmostLeaf(const Symbol& symbol); -const SyntaxTreeLeaf* GetRightmostLeaf(const Symbol& symbol); +const SyntaxTreeLeaf *GetLeftmostLeaf(const Symbol &symbol); +const SyntaxTreeLeaf *GetRightmostLeaf(const Symbol &symbol); // Returns the range of text spanned by a Symbol, which could be a subtree. -absl::string_view StringSpanOfSymbol(const Symbol& symbol); +absl::string_view StringSpanOfSymbol(const Symbol &symbol); // Variant that takes the left-bound of lsym, and right-bound of rsym. -absl::string_view StringSpanOfSymbol(const Symbol& lsym, const Symbol& rsym); +absl::string_view StringSpanOfSymbol(const Symbol &lsym, const Symbol &rsym); // Returns a SyntaxTreeNode down_casted from a Symbol. -const SyntaxTreeNode& SymbolCastToNode(const Symbol&); +const SyntaxTreeNode &SymbolCastToNode(const Symbol &); // Mutable variant. -SyntaxTreeNode& SymbolCastToNode(Symbol&); // NOLINT +SyntaxTreeNode &SymbolCastToNode(Symbol &); // NOLINT // The following no-op overloads allow SymbolCastToNode() to work with zero // overhead when the argument type is statically known to be the same. -inline const SyntaxTreeNode& SymbolCastToNode(const SyntaxTreeNode& node) { +inline const SyntaxTreeNode &SymbolCastToNode(const SyntaxTreeNode &node) { return node; } -inline SyntaxTreeNode& SymbolCastToNode(SyntaxTreeNode& node) { // NOLINT +inline SyntaxTreeNode &SymbolCastToNode(SyntaxTreeNode &node) { // NOLINT return node; } // Returns a SyntaxTreeLeaf down_casted from a Symbol. -const SyntaxTreeLeaf& SymbolCastToLeaf(const Symbol&); +const SyntaxTreeLeaf &SymbolCastToLeaf(const Symbol &); // Unwrap layers of only-child nodes until reaching a leaf or a node with // multiple children. -const Symbol* DescendThroughSingletons(const Symbol& symbol); +const Symbol *DescendThroughSingletons(const Symbol &symbol); // Succeeds and returns node if node's enum matches 'node_enum'. // Returns same node reference, so that anywhere that expects a SyntaxTreeNode // can be passed MatchNodeEnumOrNull(node, node_enum). template -const SyntaxTreeNode* MatchNodeEnumOrNull(const SyntaxTreeNode& node, +const SyntaxTreeNode *MatchNodeEnumOrNull(const SyntaxTreeNode &node, E expected_node_enum) { // Uses operator<<(std::ostream&, E) for diagnostics. const bool enum_matches = (E(node.Tag().tag) == expected_node_enum); @@ -84,7 +84,7 @@ const SyntaxTreeNode* MatchNodeEnumOrNull(const SyntaxTreeNode& node, // Mutable variant. template -SyntaxTreeNode* MatchNodeEnumOrNull(SyntaxTreeNode& node, // NOLINT +SyntaxTreeNode *MatchNodeEnumOrNull(SyntaxTreeNode &node, // NOLINT E expected_node_enum) { // Uses operator<<(std::ostream&, E) for diagnostics. const bool enum_matches = (E(node.Tag().tag) == expected_node_enum); @@ -96,7 +96,7 @@ SyntaxTreeNode* MatchNodeEnumOrNull(SyntaxTreeNode& node, // NOLINT } template -const SyntaxTreeLeaf* MatchLeafEnumOrNull(const SyntaxTreeLeaf& leaf, +const SyntaxTreeLeaf *MatchLeafEnumOrNull(const SyntaxTreeLeaf &leaf, E expected_token_enum) { // Uses operator<<(std::ostream&, E) for diagnostics. const bool enum_matches = E(leaf.get().token_enum()) == expected_token_enum; @@ -109,7 +109,7 @@ const SyntaxTreeLeaf* MatchLeafEnumOrNull(const SyntaxTreeLeaf& leaf, namespace internal { template -void StaticAssertMustBeCSTSymbolOrNode(S&) { +void StaticAssertMustBeCSTSymbolOrNode(S &) { using base_type = typename std::remove_const::type; static_assert(std::is_same::value || std::is_same::value); @@ -121,7 +121,7 @@ void StaticAssertMustBeCSTSymbolOrNode(S&) { // Constness is deduced from S and reflected in the return type. // S can be {const,non-const}x{Symbol,SyntaxTreeNode}. template -typename match_const::type& CheckSymbolAsNode(S& symbol, +typename match_const::type &CheckSymbolAsNode(S &symbol, E node_enum) { internal::StaticAssertMustBeCSTSymbolOrNode(symbol); // TODO(hzeller) bubble up nullptr. @@ -132,7 +132,7 @@ typename match_const::type& CheckSymbolAsNode(S& symbol, // Succeeds if symbol is a leaf enumerated 'leaf_enum'. // Returns a casted reference on success. template -const SyntaxTreeLeaf& CheckSymbolAsLeaf(const Symbol& symbol, E token_enum) { +const SyntaxTreeLeaf &CheckSymbolAsLeaf(const Symbol &symbol, E token_enum) { // TODO(hzeller) bubble up nullptr. return *ABSL_DIE_IF_NULL( MatchLeafEnumOrNull(SymbolCastToLeaf(symbol), token_enum)); @@ -140,7 +140,7 @@ const SyntaxTreeLeaf& CheckSymbolAsLeaf(const Symbol& symbol, E token_enum) { // Succeeds if symbol is a node, or nullptr (returning nullptr). template -const SyntaxTreeNode* CheckOptionalSymbolAsNode(const SPtr& symbol) { +const SyntaxTreeNode *CheckOptionalSymbolAsNode(const SPtr &symbol) { if (symbol == nullptr) return nullptr; return &SymbolCastToNode(*symbol); } @@ -148,7 +148,7 @@ const SyntaxTreeNode* CheckOptionalSymbolAsNode(const SPtr& symbol) { // Succeeds if symbol is nullptr (returning nullptr), or it is a node // enumerated 'node_enum' (returns casted non-nullptr). template -const SyntaxTreeNode* CheckOptionalSymbolAsNode(const SPtr& symbol, +const SyntaxTreeNode *CheckOptionalSymbolAsNode(const SPtr &symbol, E node_enum) { if (symbol == nullptr) return nullptr; return &CheckSymbolAsNode(*symbol, node_enum); @@ -156,7 +156,7 @@ const SyntaxTreeNode* CheckOptionalSymbolAsNode(const SPtr& symbol, // Specialization for nullptr_t. template -const SyntaxTreeNode* CheckOptionalSymbolAsNode(const std::nullptr_t& symbol, +const SyntaxTreeNode *CheckOptionalSymbolAsNode(const std::nullptr_t &symbol, E) { return nullptr; } @@ -164,7 +164,7 @@ const SyntaxTreeNode* CheckOptionalSymbolAsNode(const std::nullptr_t& symbol, // Succeeds if symbol is nullptr (returning nullptr), or it is a leaf // enumerated 'token_enum' (returns casted non-nullptr). template -const SyntaxTreeLeaf* CheckOptionalSymbolAsLeaf(const SPtr& symbol, +const SyntaxTreeLeaf *CheckOptionalSymbolAsLeaf(const SPtr &symbol, E token_enum) { if (symbol == nullptr) return nullptr; return &CheckSymbolAsLeaf(*symbol, token_enum); @@ -172,7 +172,7 @@ const SyntaxTreeLeaf* CheckOptionalSymbolAsLeaf(const SPtr& symbol, // Specialization for nullptr_t. template -const SyntaxTreeLeaf* CheckOptionalSymbolAsLeaf(const std::nullptr_t& symbol, +const SyntaxTreeLeaf *CheckOptionalSymbolAsLeaf(const std::nullptr_t &symbol, E) { return nullptr; } @@ -182,11 +182,11 @@ const SyntaxTreeLeaf* CheckOptionalSymbolAsLeaf(const std::nullptr_t& symbol, // S can be {const,non-const}x{Symbol,SyntaxTreeNode} // constness is deduced from S and reflected in the return type. template -typename match_const::type* GetSubtreeAsSymbol( - S& symbol, E parent_must_be_node_enum, size_t child_position) { +typename match_const::type *GetSubtreeAsSymbol( + S &symbol, E parent_must_be_node_enum, size_t child_position) { internal::StaticAssertMustBeCSTSymbolOrNode(symbol); if (symbol.Kind() != SymbolKind::kNode) return nullptr; - auto& node = SymbolCastToNode(symbol); + auto &node = SymbolCastToNode(symbol); if (!MatchNodeEnumOrNull(node, parent_must_be_node_enum)) return nullptr; if (node.children().size() <= child_position) return nullptr; return node[child_position].get(); @@ -196,10 +196,10 @@ typename match_const::type* GetSubtreeAsSymbol( // S can be {const,non-const}x{Symbol,SyntaxTreeNode} // constness is deduced from S and reflected in the return type. template -typename match_const::type* GetSubtreeAsNode( - S& symbol, E parent_must_be_node_enum, size_t child_position) { +typename match_const::type *GetSubtreeAsNode( + S &symbol, E parent_must_be_node_enum, size_t child_position) { internal::StaticAssertMustBeCSTSymbolOrNode(symbol); - auto* tree = + auto *tree = GetSubtreeAsSymbol(symbol, parent_must_be_node_enum, child_position); if (!tree) return nullptr; if (tree->Kind() != SymbolKind::kNode) return nullptr; @@ -210,11 +210,11 @@ typename match_const::type* GetSubtreeAsNode( // S can be {const,non-const}x{Symbol,SyntaxTreeNode} // constness is deduced from S and reflected in the return type. template -typename match_const::type* GetSubtreeAsNode( - S& symbol, E parent_must_be_node_enum, size_t child_position, +typename match_const::type *GetSubtreeAsNode( + S &symbol, E parent_must_be_node_enum, size_t child_position, E child_must_be_node_enum) { internal::StaticAssertMustBeCSTSymbolOrNode(symbol); - auto* tree = + auto *tree = GetSubtreeAsNode(symbol, parent_must_be_node_enum, child_position); if (!tree) return nullptr; return MatchNodeEnumOrNull(*tree, child_must_be_node_enum); @@ -223,18 +223,18 @@ typename match_const::type* GetSubtreeAsNode( // Same as GetSubtreeAsSymbol, but casts the result to a leaf. // If subtree does not exist, returns nullptr. template -const SyntaxTreeLeaf* GetSubtreeAsLeaf(const S& symbol, +const SyntaxTreeLeaf *GetSubtreeAsLeaf(const S &symbol, E parent_must_be_node_enum, size_t child_position) { internal::StaticAssertMustBeCSTSymbolOrNode(symbol); - const Symbol* subtree = + const Symbol *subtree = GetSubtreeAsSymbol(symbol, parent_must_be_node_enum, child_position); if (!subtree) return nullptr; return &SymbolCastToLeaf(*subtree); } template -E GetSubtreeNodeEnum(const S& symbol, E parent_must_be_node_enum, +E GetSubtreeNodeEnum(const S &symbol, E parent_must_be_node_enum, size_t child_position) { internal::StaticAssertMustBeCSTSymbolOrNode(symbol); return static_cast( @@ -243,21 +243,21 @@ E GetSubtreeNodeEnum(const S& symbol, E parent_must_be_node_enum, .tag); } -using TreePredicate = std::function; +using TreePredicate = std::function; // Returns the first syntax tree leaf or node that matches the given predicate. // tree must not be null. Both the tree and the returned tree are intended to // be mutable. -ConcreteSyntaxTree* FindFirstSubtreeMutable(ConcreteSyntaxTree* tree, - const TreePredicate&); +ConcreteSyntaxTree *FindFirstSubtreeMutable(ConcreteSyntaxTree *tree, + const TreePredicate &); // Returns the first syntax tree leaf or node that matches the given predicate. // tree must not be null. This is for non-mutating searches. -const Symbol* FindFirstSubtree(const Symbol*, const TreePredicate&); +const Symbol *FindFirstSubtree(const Symbol *, const TreePredicate &); // Returns the last syntax tree leaf or node that matches the given predicate. // Tree must not be null. This is for non-mutating searches. -const Symbol* FindLastSubtree(const Symbol*, const TreePredicate&); +const Symbol *FindLastSubtree(const Symbol *, const TreePredicate &); // Returns the first syntax tree node whose token starts at or after // the given first_token_offset, or nullptr if not found. @@ -266,8 +266,8 @@ const Symbol* FindLastSubtree(const Symbol*, const TreePredicate&); // subtree that starts with the next whole token. // Nodes without leaves will never be considered because they have no location. // Both the tree and the returned tree are intended to be mutable. -ConcreteSyntaxTree* FindSubtreeStartingAtOffset(ConcreteSyntaxTree* tree, - const char* first_token_offset); +ConcreteSyntaxTree *FindSubtreeStartingAtOffset(ConcreteSyntaxTree *tree, + const char *first_token_offset); // Cuts out all nodes and leaves that start at or past the given offset. // This only looks at leaves' location offsets, and not actual text. @@ -275,24 +275,24 @@ ConcreteSyntaxTree* FindSubtreeStartingAtOffset(ConcreteSyntaxTree* tree, // of recursive pruning will also be pruned. // tree must not be null. // This will never prune away the root node. -void PruneSyntaxTreeAfterOffset(ConcreteSyntaxTree* tree, const char* offset); +void PruneSyntaxTreeAfterOffset(ConcreteSyntaxTree *tree, const char *offset); // Returns the pointer to the largest subtree wholly contained // inside the text range spanned by trim_range. // tree must not be null. Tokens outside of this range are discarded. // If there are multiple eligible subtrees in range, then this chooses the // first one. -ConcreteSyntaxTree* ZoomSyntaxTree(ConcreteSyntaxTree* tree, +ConcreteSyntaxTree *ZoomSyntaxTree(ConcreteSyntaxTree *tree, absl::string_view trim_range); // Same as ZoomSyntaxTree(), except that it modifies 'tree' in-place. -void TrimSyntaxTree(ConcreteSyntaxTree* tree, absl::string_view trim_range); +void TrimSyntaxTree(ConcreteSyntaxTree *tree, absl::string_view trim_range); -using LeafMutator = std::function; +using LeafMutator = std::function; // Applies the mutator transformation to every leaf (token) in the syntax tree. // tree may not be null. -void MutateLeaves(ConcreteSyntaxTree* tree, const LeafMutator& mutator); +void MutateLeaves(ConcreteSyntaxTree *tree, const LeafMutator &mutator); // // Set of tree printing functions @@ -304,17 +304,17 @@ void MutateLeaves(ConcreteSyntaxTree* tree, const LeafMutator& mutator); class RawSymbolPrinter : public SymbolVisitor { public: // Print output to stream"; include NULL nodes if "print_null_nodes" set. - explicit RawSymbolPrinter(std::ostream* stream, bool print_null_nodes = false) + explicit RawSymbolPrinter(std::ostream *stream, bool print_null_nodes = false) : stream_(stream), print_null_nodes_(print_null_nodes) {} - void Visit(const SyntaxTreeLeaf&) override; - void Visit(const SyntaxTreeNode&) override; + void Visit(const SyntaxTreeLeaf &) override; + void Visit(const SyntaxTreeNode &) override; protected: // Prints start of line with correct indentation. - std::ostream& auto_indent(); + std::ostream &auto_indent(); - std::ostream* const stream_; // Output stream. + std::ostream *const stream_; // Output stream. const bool print_null_nodes_; // Include empty null children. int indent_ = 0; // Indentation tracks current depth in tree. @@ -329,26 +329,26 @@ class RawSymbolPrinter : public SymbolVisitor { class RawTreePrinter { public: // Print tree "root"; include NULL nodes if "print_null_nodes" set. - explicit RawTreePrinter(const Symbol& root, bool print_null_nodes = false) + explicit RawTreePrinter(const Symbol &root, bool print_null_nodes = false) : root_(root), print_null_nodes_(print_null_nodes) {} - std::ostream& Print(std::ostream&) const; + std::ostream &Print(std::ostream &) const; private: - const Symbol& root_; + const Symbol &root_; const bool print_null_nodes_; }; -std::ostream& operator<<(std::ostream&, const RawTreePrinter&); +std::ostream &operator<<(std::ostream &, const RawTreePrinter &); // Tree printer that includes details about token text byte offsets relative // to a given string buffer base, and using an enum translator. class PrettyPrinter : public RawSymbolPrinter { public: - PrettyPrinter(std::ostream* stream, const TokenInfo::Context& context) + PrettyPrinter(std::ostream *stream, const TokenInfo::Context &context) : RawSymbolPrinter(stream), context_(context) {} - void Visit(const SyntaxTreeLeaf&) override; + void Visit(const SyntaxTreeLeaf &) override; protected: // Range of text spanned by syntax tree, used for offset calculation. @@ -356,24 +356,24 @@ class PrettyPrinter : public RawSymbolPrinter { }; // Prints tree contained at root to stream -void PrettyPrintTree(const Symbol& root, const TokenInfo::Context& context, - std::ostream* stream); +void PrettyPrintTree(const Symbol &root, const TokenInfo::Context &context, + std::ostream *stream); // Streamable tree printing class. // Usage: stream << TreePrettyPrinter(*tree_root, context); class TreePrettyPrinter { public: - TreePrettyPrinter(const Symbol& root, const TokenInfo::Context& context) + TreePrettyPrinter(const Symbol &root, const TokenInfo::Context &context) : root_(root), context_(context) {} - std::ostream& Print(std::ostream&) const; + std::ostream &Print(std::ostream &) const; private: - const Symbol& root_; - const TokenInfo::Context& context_; + const Symbol &root_; + const TokenInfo::Context &context_; }; -std::ostream& operator<<(std::ostream&, const TreePrettyPrinter&); +std::ostream &operator<<(std::ostream &, const TreePrettyPrinter &); } // namespace verible diff --git a/common/text/tree_utils_test.cc b/common/text/tree_utils_test.cc index 135117798..a2a333572 100644 --- a/common/text/tree_utils_test.cc +++ b/common/text/tree_utils_test.cc @@ -33,8 +33,8 @@ namespace verible { namespace { // Helper function for reaching only-child node. -const Symbol* ExpectOnlyChild(const Symbol& node) { - return down_cast(node).children()[0].get(); +const Symbol *ExpectOnlyChild(const Symbol &node) { + return down_cast(node).children()[0].get(); } // Tests that leaf is considered an only-child when descending. @@ -414,41 +414,41 @@ TEST(TreePrintTest, PrettyPrintSkipNullptrs) { // Test that 1-node tree and always-true predicate yields the root node. TEST(FindFirstSubtreeMutableTest, OneNodePredicateTrue) { SymbolPtr tree = Node(); - SymbolPtr* result = - FindFirstSubtreeMutable(&tree, [](const Symbol&) { return true; }); + SymbolPtr *result = + FindFirstSubtreeMutable(&tree, [](const Symbol &) { return true; }); EXPECT_EQ(result, &tree); } // Test that 1-node tree and always-false predicate yields no match. TEST(FindFirstSubtreeMutableTest, OneNodePredicateFalse) { SymbolPtr tree = Node(); - SymbolPtr* result = - FindFirstSubtreeMutable(&tree, [](const Symbol&) { return false; }); + SymbolPtr *result = + FindFirstSubtreeMutable(&tree, [](const Symbol &) { return false; }); EXPECT_EQ(result, nullptr); } // Test that 2-node tree and always-true predicate yields the root node. TEST(FindFirstSubtreeMutableTest, TwoLevelPredicateTrue) { SymbolPtr tree = TNode(1, TNode(2)); - SymbolPtr* result = - FindFirstSubtreeMutable(&tree, [](const Symbol&) { return true; }); + SymbolPtr *result = + FindFirstSubtreeMutable(&tree, [](const Symbol &) { return true; }); EXPECT_EQ(result, &tree); } // Test that 2-node tree and always-false predicate yields nullptr. TEST(FindFirstSubtreeMutableTest, TwoLevelPredicateFalse) { SymbolPtr tree = TNode(1, TNode(2)); - SymbolPtr* result = - FindFirstSubtreeMutable(&tree, [](const Symbol&) { return false; }); + SymbolPtr *result = + FindFirstSubtreeMutable(&tree, [](const Symbol &) { return false; }); EXPECT_EQ(result, nullptr); } -bool IsNodeTagged(const Symbol& s, int tag) { +bool IsNodeTagged(const Symbol &s, int tag) { const SymbolTag t = s.Tag(); return t.kind == SymbolKind::kNode && t.tag == tag; } -bool IsLeafTagged(const Symbol& s, int tag) { +bool IsLeafTagged(const Symbol &s, int tag) { const SymbolTag t = s.Tag(); return t.kind == SymbolKind::kLeaf && t.tag == tag; } @@ -456,8 +456,8 @@ bool IsLeafTagged(const Symbol& s, int tag) { // Test that tree and predicate can match the root node. TEST(FindFirstSubtreeMutableTest, TwoLevelNodeTagIs1) { SymbolPtr tree = TNode(1, TNode(2)); - SymbolPtr* result = FindFirstSubtreeMutable( - &tree, [](const Symbol& s) { return IsNodeTagged(s, 1); }); + SymbolPtr *result = FindFirstSubtreeMutable( + &tree, [](const Symbol &s) { return IsNodeTagged(s, 1); }); EXPECT_EQ(result, &tree); } @@ -465,32 +465,32 @@ TEST(FindFirstSubtreeMutableTest, TwoLevelNodeTagIs1) { TEST(FindFirstSubtreeMutableTest, SkipNulls) { SymbolPtr tree = TNode(1, nullptr, nullptr, TNode(2), nullptr); SymbolPtr expect = TNode(2); - SymbolPtr* result = FindFirstSubtreeMutable( - &tree, [](const Symbol& s) { return IsNodeTagged(s, 2); }); + SymbolPtr *result = FindFirstSubtreeMutable( + &tree, [](const Symbol &s) { return IsNodeTagged(s, 2); }); EXPECT_TRUE(EqualTreesByEnum(result->get(), expect.get())); } // Test that tree and predicate can match no node. TEST(FindFirstSubtreeMutableTest, TwoLevelNoNodeMatch) { SymbolPtr tree = TNode(1, TNode(2)); - SymbolPtr* result = FindFirstSubtreeMutable( - &tree, [](const Symbol& s) { return IsLeafTagged(s, 3); }); + SymbolPtr *result = FindFirstSubtreeMutable( + &tree, [](const Symbol &s) { return IsLeafTagged(s, 3); }); EXPECT_EQ(result, nullptr); } // Test that tree and predicate can match no node with null leaves. TEST(FindFirstSubtreeMutableTest, TwoLevelNoNodeMatchNullLeaves) { SymbolPtr tree = TNode(1, nullptr, nullptr); - SymbolPtr* result = FindFirstSubtreeMutable( - &tree, [](const Symbol& s) { return IsLeafTagged(s, 4); }); + SymbolPtr *result = FindFirstSubtreeMutable( + &tree, [](const Symbol &s) { return IsLeafTagged(s, 4); }); EXPECT_EQ(result, nullptr); } // Test that tree and predicate can match no leaf. TEST(FindFirstSubtreeMutableTest, TwoLevelNoLeafTag) { SymbolPtr tree = TNode(1, TNode(2)); - SymbolPtr* result = FindFirstSubtreeMutable( - &tree, [](const Symbol& s) { return IsLeafTagged(s, 1); }); + SymbolPtr *result = FindFirstSubtreeMutable( + &tree, [](const Symbol &s) { return IsLeafTagged(s, 1); }); EXPECT_EQ(result, nullptr); } @@ -498,8 +498,8 @@ TEST(FindFirstSubtreeMutableTest, TwoLevelNoLeafTag) { TEST(FindFirstSubtreeMutableTest, TwoLevelNodeTagIs2) { SymbolPtr tree = TNode(1, TNode(2)); SymbolPtr expect = TNode(2); - SymbolPtr* result = FindFirstSubtreeMutable( - &tree, [](const Symbol& s) { return IsNodeTagged(s, 2); }); + SymbolPtr *result = FindFirstSubtreeMutable( + &tree, [](const Symbol &s) { return IsNodeTagged(s, 2); }); EXPECT_TRUE(EqualTreesByEnum(result->get(), expect.get())); } @@ -507,16 +507,16 @@ TEST(FindFirstSubtreeMutableTest, TwoLevelNodeTagIs2) { TEST(FindFirstSubtreeMutableTest, TwoLevelLeafTagIs2) { SymbolPtr tree = TNode(1, XLeaf(2)); SymbolPtr expect = XLeaf(2); - SymbolPtr* result = FindFirstSubtreeMutable( - &tree, [](const Symbol& s) { return IsLeafTagged(s, 2); }); + SymbolPtr *result = FindFirstSubtreeMutable( + &tree, [](const Symbol &s) { return IsLeafTagged(s, 2); }); EXPECT_TRUE(EqualTreesByEnum(result->get(), expect.get())); } // Test that tree and predicate can match no leaf. TEST(FindFirstSubtreeMutableTest, TwoLevelLeafTagNoMatch) { SymbolPtr tree = TNode(1, XLeaf(2), XLeaf(3)); - SymbolPtr* result = FindFirstSubtreeMutable( - &tree, [](const Symbol& s) { return IsLeafTagged(s, 1); }); + SymbolPtr *result = FindFirstSubtreeMutable( + &tree, [](const Symbol &s) { return IsLeafTagged(s, 1); }); EXPECT_EQ(result, nullptr); } @@ -524,8 +524,8 @@ TEST(FindFirstSubtreeMutableTest, TwoLevelLeafTagNoMatch) { TEST(FindFirstSubtreeMutableTest, MatchFirstOfSiblings) { SymbolPtr tree = TNode(1, TNode(2, TNode(3)), TNode(2, TNode(4))); SymbolPtr expect = TNode(2, TNode(3)); - SymbolPtr* result = FindFirstSubtreeMutable( - &tree, [](const Symbol& s) { return IsNodeTagged(s, 2); }); + SymbolPtr *result = FindFirstSubtreeMutable( + &tree, [](const Symbol &s) { return IsNodeTagged(s, 2); }); EXPECT_TRUE(EqualTreesByEnum(result->get(), expect.get())); } @@ -533,8 +533,8 @@ TEST(FindFirstSubtreeMutableTest, MatchFirstOfSiblings) { TEST(FindFirstSubtreeMutableTest, MatchFirstInOrder) { SymbolPtr tree = TNode(1, TNode(2, TNode(3)), TNode(3, TNode(4))); SymbolPtr expect = TNode(3); - SymbolPtr* result = FindFirstSubtreeMutable( - &tree, [](const Symbol& s) { return IsNodeTagged(s, 3); }); + SymbolPtr *result = FindFirstSubtreeMutable( + &tree, [](const Symbol &s) { return IsNodeTagged(s, 3); }); EXPECT_TRUE(EqualTreesByEnum(result->get(), expect.get())); } @@ -542,8 +542,8 @@ TEST(FindFirstSubtreeMutableTest, MatchFirstInOrder) { TEST(FindFirstSubtreeMutableTest, MatchLeaf) { SymbolPtr tree = TNode(1, TNode(2, XLeaf(3)), TNode(3, TNode(4))); SymbolPtr expect = XLeaf(3); - SymbolPtr* result = FindFirstSubtreeMutable( - &tree, [](const Symbol& s) { return IsLeafTagged(s, 3); }); + SymbolPtr *result = FindFirstSubtreeMutable( + &tree, [](const Symbol &s) { return IsLeafTagged(s, 3); }); EXPECT_TRUE(EqualTreesByEnum(result->get(), expect.get())); } @@ -552,40 +552,40 @@ TEST(FindFirstSubtreeMutableTest, MatchLeaf) { // Test that 1-node tree and always-true predicate yields the root node. TEST(FindFirstSubtreeTest, OneNodePredicateTrue) { SymbolPtr tree = Node(); - const Symbol* result = - FindFirstSubtree(tree.get(), [](const Symbol&) { return true; }); + const Symbol *result = + FindFirstSubtree(tree.get(), [](const Symbol &) { return true; }); EXPECT_EQ(result, tree.get()); } // Test that 1-node tree and always-false predicate yields no match. TEST(FindFirstSubtreeTest, OneNodePredicateFalse) { SymbolPtr tree = Node(); - const Symbol* result = - FindFirstSubtree(tree.get(), [](const Symbol&) { return false; }); + const Symbol *result = + FindFirstSubtree(tree.get(), [](const Symbol &) { return false; }); EXPECT_EQ(result, nullptr); } // Test that 2-node tree and always-true predicate yields the root node. TEST(FindFirstSubtreeTest, TwoLevelPredicateTrue) { SymbolPtr tree = TNode(1, TNode(2)); - const Symbol* result = - FindFirstSubtree(tree.get(), [](const Symbol&) { return true; }); + const Symbol *result = + FindFirstSubtree(tree.get(), [](const Symbol &) { return true; }); EXPECT_EQ(result, tree.get()); } // Test that 2-node tree and always-false predicate yields nullptr. TEST(FindFirstSubtreeTest, TwoLevelPredicateFalse) { SymbolPtr tree = TNode(1, TNode(2)); - const Symbol* result = - FindFirstSubtree(tree.get(), [](const Symbol&) { return false; }); + const Symbol *result = + FindFirstSubtree(tree.get(), [](const Symbol &) { return false; }); EXPECT_EQ(result, nullptr); } // Test that tree and predicate can match the root node. TEST(FindFirstSubtreeTest, TwoLevelNodeTagIs1) { SymbolPtr tree = TNode(1, TNode(2)); - const Symbol* result = FindFirstSubtree( - tree.get(), [](const Symbol& s) { return IsNodeTagged(s, 1); }); + const Symbol *result = FindFirstSubtree( + tree.get(), [](const Symbol &s) { return IsNodeTagged(s, 1); }); EXPECT_EQ(result, tree.get()); } @@ -593,32 +593,32 @@ TEST(FindFirstSubtreeTest, TwoLevelNodeTagIs1) { TEST(FindFirstSubtreeTest, SkipNulls) { SymbolPtr tree = TNode(1, nullptr, nullptr, TNode(2), nullptr); SymbolPtr expect = TNode(2); - const Symbol* result = FindFirstSubtree( - tree.get(), [](const Symbol& s) { return IsNodeTagged(s, 2); }); + const Symbol *result = FindFirstSubtree( + tree.get(), [](const Symbol &s) { return IsNodeTagged(s, 2); }); EXPECT_TRUE(EqualTreesByEnum(result, expect.get())); } // Test that tree and predicate can match no node. TEST(FindFirstSubtreeTest, TwoLevelNoNodeMatch) { SymbolPtr tree = TNode(1, TNode(2)); - const Symbol* result = FindFirstSubtree( - tree.get(), [](const Symbol& s) { return IsLeafTagged(s, 3); }); + const Symbol *result = FindFirstSubtree( + tree.get(), [](const Symbol &s) { return IsLeafTagged(s, 3); }); EXPECT_EQ(result, nullptr); } // Test that tree and predicate can match no node with null leaves. TEST(FindFirstSubtreeTest, TwoLevelNoNodeMatchNullLeaves) { SymbolPtr tree = TNode(1, nullptr, nullptr); - const Symbol* result = FindFirstSubtree( - tree.get(), [](const Symbol& s) { return IsLeafTagged(s, 4); }); + const Symbol *result = FindFirstSubtree( + tree.get(), [](const Symbol &s) { return IsLeafTagged(s, 4); }); EXPECT_EQ(result, nullptr); } // Test that tree and predicate can match no leaf. TEST(FindFirstSubtreeTest, TwoLevelNoLeafTag) { SymbolPtr tree = TNode(1, TNode(2)); - const Symbol* result = FindFirstSubtree( - tree.get(), [](const Symbol& s) { return IsLeafTagged(s, 1); }); + const Symbol *result = FindFirstSubtree( + tree.get(), [](const Symbol &s) { return IsLeafTagged(s, 1); }); EXPECT_EQ(result, nullptr); } @@ -626,8 +626,8 @@ TEST(FindFirstSubtreeTest, TwoLevelNoLeafTag) { TEST(FindFirstSubtreeTest, TwoLevelNodeTagIs2) { SymbolPtr tree = TNode(1, TNode(2)); SymbolPtr expect = TNode(2); - const Symbol* result = FindFirstSubtree( - tree.get(), [](const Symbol& s) { return IsNodeTagged(s, 2); }); + const Symbol *result = FindFirstSubtree( + tree.get(), [](const Symbol &s) { return IsNodeTagged(s, 2); }); EXPECT_TRUE(EqualTreesByEnum(result, expect.get())); } @@ -635,16 +635,16 @@ TEST(FindFirstSubtreeTest, TwoLevelNodeTagIs2) { TEST(FindFirstSubtreeTest, TwoLevelLeafTagIs2) { SymbolPtr tree = TNode(1, XLeaf(2)); SymbolPtr expect = XLeaf(2); - const Symbol* result = FindFirstSubtree( - tree.get(), [](const Symbol& s) { return IsLeafTagged(s, 2); }); + const Symbol *result = FindFirstSubtree( + tree.get(), [](const Symbol &s) { return IsLeafTagged(s, 2); }); EXPECT_TRUE(EqualTreesByEnum(result, expect.get())); } // Test that tree and predicate can match no leaf. TEST(FindFirstSubtreeTest, TwoLevelLeafTagNoMatch) { SymbolPtr tree = TNode(1, XLeaf(2), XLeaf(3)); - const Symbol* result = FindFirstSubtree( - tree.get(), [](const Symbol& s) { return IsLeafTagged(s, 1); }); + const Symbol *result = FindFirstSubtree( + tree.get(), [](const Symbol &s) { return IsLeafTagged(s, 1); }); EXPECT_EQ(result, nullptr); } @@ -652,8 +652,8 @@ TEST(FindFirstSubtreeTest, TwoLevelLeafTagNoMatch) { TEST(FindFirstSubtreeTest, MatchFirstOfSiblings) { SymbolPtr tree = TNode(1, TNode(2, TNode(3)), TNode(2, TNode(4))); SymbolPtr expect = TNode(2, TNode(3)); - const Symbol* result = FindFirstSubtree( - tree.get(), [](const Symbol& s) { return IsNodeTagged(s, 2); }); + const Symbol *result = FindFirstSubtree( + tree.get(), [](const Symbol &s) { return IsNodeTagged(s, 2); }); EXPECT_TRUE(EqualTreesByEnum(result, expect.get())); } @@ -661,8 +661,8 @@ TEST(FindFirstSubtreeTest, MatchFirstOfSiblings) { TEST(FindFirstSubtreeTest, MatchFirstInOrder) { SymbolPtr tree = TNode(1, TNode(2, TNode(3)), TNode(3, TNode(4))); SymbolPtr expect = TNode(3); - const Symbol* result = FindFirstSubtree( - tree.get(), [](const Symbol& s) { return IsNodeTagged(s, 3); }); + const Symbol *result = FindFirstSubtree( + tree.get(), [](const Symbol &s) { return IsNodeTagged(s, 3); }); EXPECT_TRUE(EqualTreesByEnum(result, expect.get())); } @@ -670,8 +670,8 @@ TEST(FindFirstSubtreeTest, MatchFirstInOrder) { TEST(FindFirstSubtreeTest, MatchLeaf) { SymbolPtr tree = TNode(1, TNode(2, XLeaf(3)), TNode(3, TNode(4))); SymbolPtr expect = XLeaf(3); - const Symbol* result = FindFirstSubtree( - tree.get(), [](const Symbol& s) { return IsLeafTagged(s, 3); }); + const Symbol *result = FindFirstSubtree( + tree.get(), [](const Symbol &s) { return IsLeafTagged(s, 3); }); EXPECT_TRUE(EqualTreesByEnum(result, expect.get())); } @@ -680,16 +680,16 @@ TEST(FindFirstSubtreeTest, MatchLeaf) { // Test that 1-node tree and always-true predicate yields the root node. TEST(FindLastSubtreeTest, OneNodePredicateTrue) { SymbolPtr tree = Node(); - const Symbol* result = - FindLastSubtree(tree.get(), [](const Symbol&) { return true; }); + const Symbol *result = + FindLastSubtree(tree.get(), [](const Symbol &) { return true; }); EXPECT_EQ(result, tree.get()); } // Test that 1-node tree and always-false predicate yields no match. TEST(FindLastSubtreeTest, OneNodePredicateFalse) { SymbolPtr tree = Node(); - const Symbol* result = - FindLastSubtree(tree.get(), [](const Symbol&) { return false; }); + const Symbol *result = + FindLastSubtree(tree.get(), [](const Symbol &) { return false; }); EXPECT_EQ(result, nullptr); } @@ -697,24 +697,24 @@ TEST(FindLastSubtreeTest, OneNodePredicateFalse) { TEST(FindLastSubtreeTest, TwoLevelPredicateTrue) { SymbolPtr tree = TNode(1, TNode(2)); SymbolPtr expect = TNode(2); - const Symbol* result = - FindLastSubtree(tree.get(), [](const Symbol&) { return true; }); + const Symbol *result = + FindLastSubtree(tree.get(), [](const Symbol &) { return true; }); EXPECT_TRUE(EqualTreesByEnum(result, expect.get())); } // Test that 2-node tree and always-false predicate yields nullptr. TEST(FindLastSubtreeTest, TwoLevelPredicateFalse) { SymbolPtr tree = TNode(1, TNode(2)); - const Symbol* result = - FindLastSubtree(tree.get(), [](const Symbol&) { return false; }); + const Symbol *result = + FindLastSubtree(tree.get(), [](const Symbol &) { return false; }); EXPECT_EQ(result, nullptr); } // Test that tree and predicate can match the root node. TEST(FindLastSubtreeTest, TwoLevelNodeTagIs1) { SymbolPtr tree = TNode(1, TNode(2)); - const Symbol* result = FindLastSubtree( - tree.get(), [](const Symbol& s) { return IsNodeTagged(s, 1); }); + const Symbol *result = FindLastSubtree( + tree.get(), [](const Symbol &s) { return IsNodeTagged(s, 1); }); EXPECT_EQ(result, tree.get()); } @@ -722,32 +722,32 @@ TEST(FindLastSubtreeTest, TwoLevelNodeTagIs1) { TEST(FindLastSubtreeTest, SkipNulls) { SymbolPtr tree = TNode(1, nullptr, nullptr, TNode(2), nullptr); SymbolPtr expect = TNode(2); - const Symbol* result = FindLastSubtree( - tree.get(), [](const Symbol& s) { return IsNodeTagged(s, 2); }); + const Symbol *result = FindLastSubtree( + tree.get(), [](const Symbol &s) { return IsNodeTagged(s, 2); }); EXPECT_TRUE(EqualTreesByEnum(result, expect.get())); } // Test that tree and predicate can match no node. TEST(FindLastSubtreeTest, TwoLevelNoNodeMatch) { SymbolPtr tree = TNode(1, TNode(2)); - const Symbol* result = FindLastSubtree( - tree.get(), [](const Symbol& s) { return IsLeafTagged(s, 3); }); + const Symbol *result = FindLastSubtree( + tree.get(), [](const Symbol &s) { return IsLeafTagged(s, 3); }); EXPECT_EQ(result, nullptr); } // Test that tree and predicate can match no node with null leaves. TEST(FindLastSubtreeTest, TwoLevelNoNodeMatchNullLeaves) { SymbolPtr tree = TNode(1, nullptr, nullptr); - const Symbol* result = FindLastSubtree( - tree.get(), [](const Symbol& s) { return IsLeafTagged(s, 4); }); + const Symbol *result = FindLastSubtree( + tree.get(), [](const Symbol &s) { return IsLeafTagged(s, 4); }); EXPECT_EQ(result, nullptr); } // Test that tree and predicate can match no leaf. TEST(FindLastSubtreeTest, TwoLevelNoLeafTag) { SymbolPtr tree = TNode(1, TNode(2)); - const Symbol* result = FindLastSubtree( - tree.get(), [](const Symbol& s) { return IsLeafTagged(s, 1); }); + const Symbol *result = FindLastSubtree( + tree.get(), [](const Symbol &s) { return IsLeafTagged(s, 1); }); EXPECT_EQ(result, nullptr); } @@ -755,8 +755,8 @@ TEST(FindLastSubtreeTest, TwoLevelNoLeafTag) { TEST(FindLastSubtreeTest, TwoLevelNodeTagIs2) { SymbolPtr tree = TNode(1, TNode(2)); SymbolPtr expect = TNode(2); - const Symbol* result = FindLastSubtree( - tree.get(), [](const Symbol& s) { return IsNodeTagged(s, 2); }); + const Symbol *result = FindLastSubtree( + tree.get(), [](const Symbol &s) { return IsNodeTagged(s, 2); }); EXPECT_TRUE(EqualTreesByEnum(result, expect.get())); } @@ -764,16 +764,16 @@ TEST(FindLastSubtreeTest, TwoLevelNodeTagIs2) { TEST(FindLastSubtreeTest, TwoLevelLeafTagIs2) { SymbolPtr tree = TNode(1, XLeaf(2)); SymbolPtr expect = XLeaf(2); - const Symbol* result = FindLastSubtree( - tree.get(), [](const Symbol& s) { return IsLeafTagged(s, 2); }); + const Symbol *result = FindLastSubtree( + tree.get(), [](const Symbol &s) { return IsLeafTagged(s, 2); }); EXPECT_TRUE(EqualTreesByEnum(result, expect.get())); } // Test that tree and predicate can match no leaf. TEST(FindLastSubtreeTest, TwoLevelLeafTagNoMatch) { SymbolPtr tree = TNode(1, XLeaf(2), XLeaf(3)); - const Symbol* result = FindLastSubtree( - tree.get(), [](const Symbol& s) { return IsLeafTagged(s, 1); }); + const Symbol *result = FindLastSubtree( + tree.get(), [](const Symbol &s) { return IsLeafTagged(s, 1); }); EXPECT_EQ(result, nullptr); } @@ -781,8 +781,8 @@ TEST(FindLastSubtreeTest, TwoLevelLeafTagNoMatch) { TEST(FindLastSubtreeTest, MatchLastOfSiblings) { SymbolPtr tree = TNode(1, TNode(2, TNode(2, TNode(2))), TNode(2, TNode(3))); SymbolPtr expect = TNode(2, TNode(3)); - const Symbol* result = FindLastSubtree( - tree.get(), [](const Symbol& s) { return IsNodeTagged(s, 2); }); + const Symbol *result = FindLastSubtree( + tree.get(), [](const Symbol &s) { return IsNodeTagged(s, 2); }); EXPECT_TRUE(EqualTreesByEnum(result, expect.get())); } @@ -790,8 +790,8 @@ TEST(FindLastSubtreeTest, MatchLastOfSiblings) { TEST(FindLastSubtreeTest, MatchLastInOrder) { SymbolPtr tree = TNode(1, TNode(2, TNode(3)), TNode(3, TNode(4))); SymbolPtr expect = TNode(3, TNode(4)); - const Symbol* result = FindLastSubtree( - tree.get(), [](const Symbol& s) { return IsNodeTagged(s, 3); }); + const Symbol *result = FindLastSubtree( + tree.get(), [](const Symbol &s) { return IsNodeTagged(s, 3); }); EXPECT_TRUE(EqualTreesByEnum(result, expect.get())); } @@ -799,7 +799,7 @@ TEST(FindLastSubtreeTest, MatchLastInOrder) { TEST(FindLastSubtreeTest, MatchLeaf) { SymbolPtr tree = TNode(1, TNode(2, XLeaf(3)), TNode(3, TNode(4, XLeaf(4)))); SymbolPtr expect = XLeaf(4); - const Symbol* result = FindLastSubtree(tree.get(), [](const Symbol& s) { + const Symbol *result = FindLastSubtree(tree.get(), [](const Symbol &s) { return IsLeafTagged(s, 3) || IsLeafTagged(s, 4); }); EXPECT_TRUE(EqualTreesByEnum(result, expect.get())); @@ -819,21 +819,21 @@ struct FindSubtreeStartingAtOffsetTest : public testing::Test { // Test that a single leaf yields itself when it starts < offset. TEST_F(FindSubtreeStartingAtOffsetTest, LeafOnlyOffsetLessThan) { - SymbolPtr* subtree = + SymbolPtr *subtree = FindSubtreeStartingAtOffset(&tree, kFindSubtreeTestText.begin()); EXPECT_EQ(*subtree, tree); } // Test that a single leaf yields itself when it starts == offset. TEST_F(FindSubtreeStartingAtOffsetTest, LeafOnlyOffsetLeftEqual) { - SymbolPtr* subtree = + SymbolPtr *subtree = FindSubtreeStartingAtOffset(&tree, kFindSubtreeTestText.begin() + 1); EXPECT_EQ(*subtree, tree); } // Test that a single leaf yields null when it starts > offset. TEST_F(FindSubtreeStartingAtOffsetTest, LeafOnlyOffsetGreaterThan) { - SymbolPtr* subtree = + SymbolPtr *subtree = FindSubtreeStartingAtOffset(&tree, kFindSubtreeTestText.begin() + 2); EXPECT_EQ(subtree, nullptr); } @@ -868,27 +868,27 @@ struct FindSubtreeStartingAtOffsetFakeTreeTest : public testing::Test { // Test that a whole tree is returned when offset is less than leftmost token. TEST_F(FindSubtreeStartingAtOffsetFakeTreeTest, TreeOffsetLessThanFirstToken) { // Note: begin() - 1 points to a valid location due to kBaseTextPadded - SymbolPtr* subtree = + SymbolPtr *subtree = FindSubtreeStartingAtOffset(&tree, kBaseText.begin() - 1); EXPECT_EQ(*subtree, tree); } // Test that a whole tree is returned when offset starts at leftmost token. TEST_F(FindSubtreeStartingAtOffsetFakeTreeTest, TreeOffsetAtFirstToken) { - SymbolPtr* subtree = FindSubtreeStartingAtOffset(&tree, kBaseText.begin()); + SymbolPtr *subtree = FindSubtreeStartingAtOffset(&tree, kBaseText.begin()); EXPECT_EQ(*subtree, tree); } // Test that an offset past last token yields nullptr. TEST_F(FindSubtreeStartingAtOffsetFakeTreeTest, TreeOffsetPastLastToken) { - SymbolPtr* subtree = + SymbolPtr *subtree = FindSubtreeStartingAtOffset(&tree, kBaseText.begin() + 18); EXPECT_EQ(subtree, nullptr); } // Test that an offset in middle of last token yields nullptr. TEST_F(FindSubtreeStartingAtOffsetFakeTreeTest, TreeOffsetInsideLastToken) { - SymbolPtr* subtree = + SymbolPtr *subtree = FindSubtreeStartingAtOffset(&tree, kBaseText.begin() + 13); EXPECT_EQ(subtree, nullptr); } @@ -897,7 +897,7 @@ TEST_F(FindSubtreeStartingAtOffsetFakeTreeTest, TreeOffsetInsideLastToken) { TEST_F(FindSubtreeStartingAtOffsetFakeTreeTest, TreeOffsetInsideFirstToken) { SymbolPtr expect = Leaf(0, kBaseText.substr(0, 5)); for (int offset = 1; offset <= 4; ++offset) { - SymbolPtr* subtree = + SymbolPtr *subtree = FindSubtreeStartingAtOffset(&tree, kBaseText.begin() + offset); EXPECT_TRUE(EqualTreesByEnum(subtree->get(), expect.get())); } @@ -906,7 +906,7 @@ TEST_F(FindSubtreeStartingAtOffsetFakeTreeTest, TreeOffsetInsideFirstToken) { // Test that a subtree is returned when offset starts inside leftmost token. TEST_F(FindSubtreeStartingAtOffsetFakeTreeTest, TreeOffsetInsideMiddleSubtree) { SymbolPtr expect = Leaf(0, kBaseText.substr(5, 3)); - SymbolPtr* subtree = + SymbolPtr *subtree = FindSubtreeStartingAtOffset(&tree, kBaseText.begin() + 5); EXPECT_TRUE(EqualTreesByEnum(subtree->get(), expect.get())); } @@ -918,7 +918,7 @@ TEST_F(FindSubtreeStartingAtOffsetFakeTreeTest, TreeOffsetAtLastSubtree) { Leaf(0, kBaseText.substr(12, 5)) // noformat ); for (int offset = 6; offset <= 8; ++offset) { - SymbolPtr* subtree = + SymbolPtr *subtree = FindSubtreeStartingAtOffset(&tree, kBaseText.begin() + offset); EXPECT_TRUE(EqualTreesByEnum(subtree->get(), expect.get())); } @@ -928,7 +928,7 @@ TEST_F(FindSubtreeStartingAtOffsetFakeTreeTest, TreeOffsetAtLastSubtree) { TEST_F(FindSubtreeStartingAtOffsetFakeTreeTest, TreeOffsetAtLastLeaf) { SymbolPtr expect = Leaf(0, kBaseText.substr(8, 2)); for (int offset = 9; offset <= 12; ++offset) { - SymbolPtr* subtree = + SymbolPtr *subtree = FindSubtreeStartingAtOffset(&tree, kBaseText.begin() + offset); EXPECT_TRUE(EqualTreesByEnum(subtree->get(), expect.get())); } @@ -937,7 +937,7 @@ TEST_F(FindSubtreeStartingAtOffsetFakeTreeTest, TreeOffsetAtLastLeaf) { // MutateLeaves tests // Example LeafMutator -void SetLeafEnum(TokenInfo* token) { token->set_token_enum(9); } +void SetLeafEnum(TokenInfo *token) { token->set_token_enum(9); } // Test that null unique_ptr is ignored. TEST(MutateLeavesTest, UniqueNullPtr) { @@ -1309,13 +1309,13 @@ TEST(TrimSyntaxTreeTest, ComplexMidSpanSubtree2) { TEST(SymbolCastToNodeTest, BasicTest) { const SyntaxTreeNode node_symbol; - const auto& node = SymbolCastToNode(node_symbol); + const auto &node = SymbolCastToNode(node_symbol); CHECK_EQ(node.Kind(), SymbolKind::kNode); } TEST(SymbolCastToNodeTest, BasicTestMutable) { SyntaxTreeNode node_symbol; - SyntaxTreeNode& node = SymbolCastToNode(node_symbol); + SyntaxTreeNode &node = SymbolCastToNode(node_symbol); CHECK_EQ(node.Kind(), SymbolKind::kNode); } @@ -1331,7 +1331,7 @@ TEST(SymbolCastToNodeTest, InvalidInputLeafMutable) { TEST(SymbolCastToLeafTest, BasicTest) { SyntaxTreeLeaf leaf_symbol(3, "foo"); - const auto& leaf = SymbolCastToLeaf(leaf_symbol); + const auto &leaf = SymbolCastToLeaf(leaf_symbol); CHECK_EQ(leaf.Kind(), SymbolKind::kLeaf); } @@ -1356,7 +1356,7 @@ enum class FakeEnum { kTwo, }; -std::ostream& operator<<(std::ostream& stream, FakeEnum e) { +std::ostream &operator<<(std::ostream &stream, FakeEnum e) { switch (e) { case FakeEnum::kZero: stream << "zero"; @@ -1455,7 +1455,7 @@ TEST(CheckOptionalSymbolAsLeafTest, Nullptr) { } TEST(CheckOptionalSymbolAsLeafTest, NullBarePtr) { - const Symbol* root = nullptr; + const Symbol *root = nullptr; EXPECT_EQ(CheckOptionalSymbolAsLeaf(root, FakeEnum::kOne), nullptr); } @@ -1490,12 +1490,12 @@ TEST(CheckOptionalSymbolAsNodeTest, Nullptr) { } TEST(CheckOptionalSymbolAsNodeTest, NullBarePtr) { - const Symbol* root = nullptr; + const Symbol *root = nullptr; EXPECT_EQ(CheckOptionalSymbolAsNode(root, FakeEnum::kOne), nullptr); } TEST(CheckOptionalSymbolAsNodeTest, NullBarePtrNoEnum) { - const Symbol* root = nullptr; + const Symbol *root = nullptr; EXPECT_EQ(CheckOptionalSymbolAsNode(root), nullptr); } @@ -1546,29 +1546,29 @@ TEST(GetSubtreeAsSymbolTest, WrongParentEnumTag) { TEST(GetSubtreeAsSymbolTest, ValidAccessNode) { auto root = TNode(FakeEnum::kTwo, TNode(FakeEnum::kOne)); - const auto* child = GetSubtreeAsSymbol(*root, FakeEnum::kTwo, 0); - const auto* child_node = down_cast(child); + const auto *child = GetSubtreeAsSymbol(*root, FakeEnum::kTwo, 0); + const auto *child_node = down_cast(child); EXPECT_EQ(FakeEnum(child_node->Tag().tag), FakeEnum::kOne); } TEST(GetSubtreeAsSymbolTest, ValidAccessLeaf) { auto root = TNode(FakeEnum::kTwo, Leaf(6, "six")); - const auto* child = GetSubtreeAsSymbol(*root, FakeEnum::kTwo, 0); - const auto* child_leaf = down_cast(child); + const auto *child = GetSubtreeAsSymbol(*root, FakeEnum::kTwo, 0); + const auto *child_leaf = down_cast(child); EXPECT_EQ(child_leaf->get().token_enum(), 6); } TEST(GetSubtreeAsSymbolTest, ValidAccessAtIndexOne) { auto root = TNode(FakeEnum::kTwo, TNode(FakeEnum::kZero), TNode(FakeEnum::kOne)); - const auto* child = GetSubtreeAsSymbol(*root, FakeEnum::kTwo, 1); - const auto* child_node = down_cast(child); + const auto *child = GetSubtreeAsSymbol(*root, FakeEnum::kTwo, 1); + const auto *child_node = down_cast(child); EXPECT_EQ(FakeEnum(child_node->Tag().tag), FakeEnum::kOne); } TEST(GetSubtreeAsNodeTest, ValidatedFoundNodeEnum) { auto root = TNode(FakeEnum::kZero, TNode(FakeEnum::kOne)); - const auto& child = GetSubtreeAsNode(*root, FakeEnum::kZero, 0); + const auto &child = GetSubtreeAsNode(*root, FakeEnum::kZero, 0); EXPECT_EQ(FakeEnum(child->Tag().tag), FakeEnum::kOne); } @@ -1591,7 +1591,7 @@ TEST(GetSubtreeAsNodeTest, ValidatedFoundNodeEnumChildMismatches) { TEST(GetSubtreeAsLeafTest, ValidatedFoundLeaf) { auto root = TNode(FakeEnum::kZero, Leaf(7, "foo")); - const SyntaxTreeLeaf* leaf = GetSubtreeAsLeaf(*root, FakeEnum::kZero, 0); + const SyntaxTreeLeaf *leaf = GetSubtreeAsLeaf(*root, FakeEnum::kZero, 0); EXPECT_EQ(leaf->get().token_enum(), 7); } diff --git a/common/text/visitors.h b/common/text/visitors.h index 8865a7a14..ab76b0db4 100644 --- a/common/text/visitors.h +++ b/common/text/visitors.h @@ -36,8 +36,8 @@ class SyntaxTreeNode; class TreeVisitorRecursive { public: virtual ~TreeVisitorRecursive() = default; - virtual void Visit(const SyntaxTreeLeaf& leaf) = 0; - virtual void Visit(const SyntaxTreeNode& node) = 0; + virtual void Visit(const SyntaxTreeLeaf &leaf) = 0; + virtual void Visit(const SyntaxTreeNode &node) = 0; }; // SymbolVisitor is an abstract visitor class from which visitors can be derived @@ -51,8 +51,8 @@ class TreeVisitorRecursive { class SymbolVisitor { public: virtual ~SymbolVisitor() = default; - virtual void Visit(const SyntaxTreeLeaf& leaf) = 0; - virtual void Visit(const SyntaxTreeNode& node) = 0; + virtual void Visit(const SyntaxTreeLeaf &leaf) = 0; + virtual void Visit(const SyntaxTreeNode &node) = 0; }; // MutableTreeVisitorRecursive is the non-const version of TreeVisitorRecursive. @@ -64,8 +64,8 @@ class SymbolVisitor { class MutableTreeVisitorRecursive { public: virtual ~MutableTreeVisitorRecursive() = default; - virtual void Visit(const SyntaxTreeLeaf& leaf, SymbolPtr*) = 0; - virtual void Visit(const SyntaxTreeNode& node, SymbolPtr*) = 0; + virtual void Visit(const SyntaxTreeLeaf &leaf, SymbolPtr *) = 0; + virtual void Visit(const SyntaxTreeNode &node, SymbolPtr *) = 0; }; } // namespace verible diff --git a/common/tools/patch_tool.cc b/common/tools/patch_tool.cc index c41ad838b..73b5007fc 100644 --- a/common/tools/patch_tool.cc +++ b/common/tools/patch_tool.cc @@ -30,9 +30,9 @@ using verible::SubcommandArgsRange; using verible::SubcommandEntry; -static absl::Status ChangedLines(const SubcommandArgsRange& args, - std::istream& ins, std::ostream& outs, - std::ostream& errs) { +static absl::Status ChangedLines(const SubcommandArgsRange &args, + std::istream &ins, std::ostream &outs, + std::ostream &errs) { if (args.empty()) { return absl::InvalidArgumentError( "Missing patchfile argument. Use '-' for stdin."); @@ -46,7 +46,7 @@ static absl::Status ChangedLines(const SubcommandArgsRange& args, const verible::FileLineNumbersMap changed_lines( patch_set.AddedLinesMap(false)); - for (const auto& file_lines : changed_lines) { + for (const auto &file_lines : changed_lines) { outs << file_lines.first; if (!file_lines.second.empty()) { file_lines.second.FormatInclusive(outs << ' ', true); @@ -56,9 +56,9 @@ static absl::Status ChangedLines(const SubcommandArgsRange& args, return absl::OkStatus(); } -static absl::Status ApplyPick(const SubcommandArgsRange& args, - std::istream& ins, std::ostream& outs, - std::ostream& errs) { +static absl::Status ApplyPick(const SubcommandArgsRange &args, + std::istream &ins, std::ostream &outs, + std::ostream &errs) { if (args.empty()) { return absl::InvalidArgumentError("Missing patchfile argument."); } @@ -73,9 +73,9 @@ static absl::Status ApplyPick(const SubcommandArgsRange& args, return patch_set.PickApplyInPlace(ins, outs); } -static absl::Status StdinTest(const SubcommandArgsRange& args, - std::istream& ins, std::ostream& outs, - std::ostream& errs) { +static absl::Status StdinTest(const SubcommandArgsRange &args, + std::istream &ins, std::ostream &outs, + std::ostream &errs) { constexpr size_t kOpenLimit = 10; outs << "This is a demo of re-opening std::cin, up to " << kOpenLimit << " times.\n" @@ -100,10 +100,10 @@ static absl::Status StdinTest(const SubcommandArgsRange& args, return absl::OkStatus(); } -static absl::Status CatTest(const SubcommandArgsRange& args, std::istream& ins, - std::ostream& outs, std::ostream& errs) { +static absl::Status CatTest(const SubcommandArgsRange &args, std::istream &ins, + std::ostream &outs, std::ostream &errs) { size_t file_count = 0; - for (const auto& arg : args) { + for (const auto &arg : args) { const absl::StatusOr contents_or = verible::file::GetContentAsString(arg); if (!contents_or.ok()) return contents_or.status(); @@ -173,10 +173,10 @@ Each 'file' echoed back to stdout will be enclosed in banner lines with false}}, }; -int main(int argc, char* argv[]) { +int main(int argc, char *argv[]) { // Create a registry of subcommands (locally, rather than as a static global). verible::SubcommandRegistry commands; - for (const auto& entry : kCommands) { + for (const auto &entry : kCommands) { const auto status = commands.RegisterCommand(entry.first, entry.second); if (!status.ok()) { std::cerr << status.message() << std::endl; @@ -200,7 +200,7 @@ int main(int argc, char* argv[]) { // subcommand args start at [2] const SubcommandArgsRange command_args(args.cbegin() + 2, args.cend()); - const auto& sub = commands.GetSubcommandEntry(args[1]); + const auto &sub = commands.GetSubcommandEntry(args[1]); // Run the subcommand. const auto status = sub.main(command_args, std::cin, std::cout, std::cerr); if (!status.ok()) { diff --git a/common/util/algorithm.h b/common/util/algorithm.h index e5aeccf35..930de716b 100644 --- a/common/util/algorithm.h +++ b/common/util/algorithm.h @@ -77,7 +77,7 @@ struct LexicographicalLess { // Compare two sequences lexicographically, element-by-element. template - bool operator()(const T1& left, const T2& right) const { + bool operator()(const T1 &left, const T2 &right) const { return std::lexicographical_compare(left.begin(), left.end(), right.begin(), right.end()); } diff --git a/common/util/algorithm_test.cc b/common/util/algorithm_test.cc index f3da4c27b..85b001296 100644 --- a/common/util/algorithm_test.cc +++ b/common/util/algorithm_test.cc @@ -323,7 +323,7 @@ class EveryN { explicit EveryN(int n, int init = 0) : i_(init), n_(n) {} template - bool operator()(const T&) { + bool operator()(const T &) { const bool ret = (i_ == n_); if (ret) i_ = 0; ++i_; @@ -364,7 +364,7 @@ TEST(LexicographicalLessTest, Containers) { // like substr() template -iterator_range make_subrange(const T& t, size_t b, +iterator_range make_subrange(const T &t, size_t b, size_t e) { return make_range(t.begin() + b, t.begin() + e); } diff --git a/common/util/auto_pop_stack.h b/common/util/auto_pop_stack.h index 7e66de7c4..c54745fde 100644 --- a/common/util/auto_pop_stack.h +++ b/common/util/auto_pop_stack.h @@ -37,8 +37,8 @@ class AutoPopStack { using value_type = T; using this_type = AutoPopStack; - using reference = value_type&; - using const_reference = const value_type&; + using reference = value_type &; + using const_reference = const value_type &; using stack_type = std::vector; using iterator = typename stack_type::iterator; @@ -49,21 +49,21 @@ class AutoPopStack { // it's the only class that can modify number of elements in stack class AutoPop { public: - AutoPop(this_type* stack, value_type&& value) : stack_(stack) { + AutoPop(this_type *stack, value_type &&value) : stack_(stack) { stack->Push(std::move(value)); } - AutoPop(this_type* stack, const_reference value) : stack_(stack) { + AutoPop(this_type *stack, const_reference value) : stack_(stack) { stack->Push(&value); } ~AutoPop() { stack_->Pop(); } - AutoPop& operator=(const AutoPop&) = delete; // copy-assign - AutoPop& operator=(AutoPop&&) = delete; // move-assign - AutoPop(const AutoPop&) = delete; // copy-construct - AutoPop(AutoPop&&) = delete; // move-construct + AutoPop &operator=(const AutoPop &) = delete; // copy-assign + AutoPop &operator=(AutoPop &&) = delete; // move-assign + AutoPop(const AutoPop &) = delete; // copy-construct + AutoPop(AutoPop &&) = delete; // move-construct private: - this_type* stack_; + this_type *stack_; }; // returns depth of context stack @@ -93,7 +93,7 @@ class AutoPopStack { } // Push a value_type onto the stack (takes r-value reference) - void Push(value_type&& value) { stack_.push_back(std::move(value)); } + void Push(value_type &&value) { stack_.push_back(std::move(value)); } // Push a value_type onto the stack (copy, takes reference) void Push(const_reference value) { stack_.push_back(value); } diff --git a/common/util/auto_pop_stack_test.cc b/common/util/auto_pop_stack_test.cc index 7bdf898c5..bec647677 100644 --- a/common/util/auto_pop_stack_test.cc +++ b/common/util/auto_pop_stack_test.cc @@ -28,7 +28,7 @@ using IntStack = AutoPopStack; // Test that AutoPop properly pushes and pops nodes on and off the stack TEST(AutoPopStackTest, PushPopTest) { IntStack context; - const auto& const_context = context; + const auto &const_context = context; EXPECT_TRUE(context.empty()); { IntStack::AutoPop p1(&context, 1); diff --git a/common/util/bijective_map.h b/common/util/bijective_map.h index 20b66b20b..409923f78 100644 --- a/common/util/bijective_map.h +++ b/common/util/bijective_map.h @@ -36,11 +36,11 @@ class BijectiveMap { // Map of keys to values (by pointer). // Would really rather have value_type be a reverse_map_type::const_iterator // but cannot due to mutually recursive template type. - using forward_map_type = std::map; + using forward_map_type = std::map; // Map of values to keys (by pointer). // Would really rather have value_type be a forward_map_type::const_iterator // but cannot due to mutually recursive template type. - using reverse_map_type = std::map; + using reverse_map_type = std::map; public: BijectiveMap() = default; @@ -66,29 +66,29 @@ class BijectiveMap { bool empty() const { return forward_map_.empty(); } // read-only direct access to internal maps - const forward_map_type& forward_view() const { return forward_map_; } - const reverse_map_type& reverse_view() const { return reverse_map_; } + const forward_map_type &forward_view() const { return forward_map_; } + const reverse_map_type &reverse_view() const { return reverse_map_; } // Lookup value given key. Returns nullptr if not found. template - const V* find_forward(const ConvertibleToKey& k) const { + const V *find_forward(const ConvertibleToKey &k) const { const auto found = forward_map_.find(k); return found == forward_map_.end() ? nullptr : found->second; } // Lookup key given value. Returns nullptr if not found. template - const K* find_reverse(const ConvertibleToValue& v) const { + const K *find_reverse(const ConvertibleToValue &v) const { const auto found = reverse_map_.find(v); return found == reverse_map_.end() ? nullptr : found->second; } // Returns true if successfully inserted new pair. - bool insert(const std::pair& p) { return insert(p.first, p.second); } + bool insert(const std::pair &p) { return insert(p.first, p.second); } // Establishes 1-1 association between key and value. // Returns true if successfully inserted new pair. - bool insert(const K& k, const V& v) { + bool insert(const K &k, const V &v) { const auto fwd_p = forward_map_.insert(std::make_pair(k, nullptr)); const auto rev_p = reverse_map_.insert(std::make_pair(v, nullptr)); if (fwd_p.second && rev_p.second) { @@ -115,7 +115,7 @@ class BijectiveMap { // success. If the range of values generated is small, this could result // in more frequent retries. Use cases for this include randomizing generated // values, or using secondary hashes to avoid collisions. - const V* insert_using_value_generator(const K& k, std::function f) { + const V *insert_using_value_generator(const K &k, std::function f) { const auto fwd_p = forward_map_.insert(std::make_pair(k, nullptr)); if (!fwd_p.second) return fwd_p.first->second; // key entry aleady exists do { diff --git a/common/util/bijective_map_test.cc b/common/util/bijective_map_test.cc index db45d3b6a..b567b3d8d 100644 --- a/common/util/bijective_map_test.cc +++ b/common/util/bijective_map_test.cc @@ -132,7 +132,7 @@ TEST(BijectiveMapTest, InsertNewPairs) { } static std::function LoopGeneratorGenerator( - const std::vector& values) { + const std::vector &values) { return [=]() { // fake random generator static const std::vector v(values); static std::vector::const_iterator iter = v.begin(); diff --git a/common/util/casts.h b/common/util/casts.h index 8d1589606..d7b7eff98 100644 --- a/common/util/casts.h +++ b/common/util/casts.h @@ -20,7 +20,7 @@ namespace verible { template -inline To down_cast(From* f) { +inline To down_cast(From *f) { static_assert( (std::is_base_of::type>::value), "target type not derived from source type"); @@ -34,7 +34,7 @@ inline To down_cast(From* f) { } template -inline To down_cast(From& f) { +inline To down_cast(From &f) { static_assert(std::is_lvalue_reference::value, "target type not a reference"); static_assert( @@ -43,7 +43,7 @@ inline To down_cast(From& f) { // We skip the assert and hence the dynamic_cast if RTTI is disabled. #if !defined(__GNUC__) || defined(__GXX_RTTI) - assert(dynamic_cast::type*>(&f) != + assert(dynamic_cast::type *>(&f) != nullptr); #endif // !defined(__GNUC__) || defined(__GXX_RTTI) diff --git a/common/util/container_iterator_range.h b/common/util/container_iterator_range.h index f3bcf7f88..91e398dd6 100644 --- a/common/util/container_iterator_range.h +++ b/common/util/container_iterator_range.h @@ -144,12 +144,12 @@ class container_iterator_range : public iterator_range { // Returns true if begin/end bounds of iterator range are identical. // Templated to allow comparison between const-mismatched iterators. template - bool operator==(const container_iterator_range& other) const { + bool operator==(const container_iterator_range &other) const { return BoundsEqual(*this, other); } template - bool operator!=(const container_iterator_range& other) const { + bool operator!=(const container_iterator_range &other) const { return !(*this == other); } diff --git a/common/util/container_iterator_range_test.cc b/common/util/container_iterator_range_test.cc index eac700a48..2687b9508 100644 --- a/common/util/container_iterator_range_test.cc +++ b/common/util/container_iterator_range_test.cc @@ -426,7 +426,7 @@ TEST(ContainerIteratorRangeTest, WholeVectorMakePair) { TEST(ContainerIteratorRangeTest, PartArray) { int v[] = {2, 3, 5, 7, 11, 13}; - container_iterator_range range(&v[1], &v[4]); // 3, 5, 7 + container_iterator_range range(&v[1], &v[4]); // 3, 5, 7 EXPECT_FALSE(range.empty()); EXPECT_EQ(range.size(), 3); EXPECT_THAT(range, ElementsAre(3, 5, 7)); diff --git a/common/util/container_proxy.h b/common/util/container_proxy.h index 5d0626aec..318219be0 100644 --- a/common/util/container_proxy.h +++ b/common/util/container_proxy.h @@ -133,10 +133,10 @@ class ContainerProxyBase { ContainerProxyBase() = default; // Copy/move of the base class doesn't make sense. - ContainerProxyBase(const ContainerProxyBase&) = delete; - ContainerProxyBase(ContainerProxyBase&&) = delete; - ContainerProxyBase& operator=(const ContainerProxyBase&) = delete; - ContainerProxyBase& operator=(ContainerProxyBase&&) = delete; + ContainerProxyBase(const ContainerProxyBase &) = delete; + ContainerProxyBase(ContainerProxyBase &&) = delete; + ContainerProxyBase &operator=(const ContainerProxyBase &) = delete; + ContainerProxyBase &operator=(ContainerProxyBase &&) = delete; using container_type = ContainerType; @@ -192,38 +192,38 @@ class ContainerProxyBase { // cost, but that is not guaranteed. template - iterator emplace(const_iterator pos, Args&&... args) { + iterator emplace(const_iterator pos, Args &&...args) { const auto iter = container().emplace(pos, std::forward(args)...); CallElementsInserted(iter); return iter; } template - void emplace_front(Args&&... args) { + void emplace_front(Args &&...args) { container().emplace_front(std::forward(args)...); CallElementsInserted(container().begin()); } template - void emplace_back(Args&&... args) { + void emplace_back(Args &&...args) { container().emplace_back(std::forward(args)...); CallElementsInserted(std::prev(container().end())); } - iterator insert(const_iterator pos, const value_type& value) { + iterator insert(const_iterator pos, const value_type &value) { const auto iter = container().insert(pos, value); CallElementsInserted(iter); return iter; } iterator insert(const_iterator pos, size_type count, - const value_type& value) { + const value_type &value) { const auto iter = container().insert(pos, count, value); CallElementsInserted(iter, std::next(iter, count)); return iter; } - iterator insert(const_iterator pos, value_type&& value) { + iterator insert(const_iterator pos, value_type &&value) { const auto iter = container().insert(pos, std::move(value)); CallElementsInserted(iter); return iter; @@ -245,20 +245,20 @@ class ContainerProxyBase { return iter; } - void push_front(const value_type& value) { + void push_front(const value_type &value) { container().push_front(value); CallElementsInserted(container().begin()); } - void push_front(value_type&& value) { + void push_front(value_type &&value) { container().push_front(std::move(value)); CallElementsInserted(container().begin()); } - void push_back(const value_type& value) { + void push_back(const value_type &value) { container().push_back(value); CallElementsInserted(std::prev(container().end())); } - void push_back(value_type&& value) { + void push_back(value_type &&value) { container().push_back(std::move(value)); CallElementsInserted(std::prev(container().end())); } @@ -316,7 +316,7 @@ class ContainerProxyBase { CallElementsWereReplaced(); } - void assign(size_type count, const value_type& value) { + void assign(size_type count, const value_type &value) { CallElementsBeingReplaced(); container().assign(count, value); CallElementsWereReplaced(); @@ -324,7 +324,7 @@ class ContainerProxyBase { // Intended to be exposed via `using` in `DerivedType`. // NOLINTNEXTLINE(misc-unconventional-assign-operator) - DerivedType& operator=(const ContainerType& other_container) { + DerivedType &operator=(const ContainerType &other_container) { CallElementsBeingReplaced(); container() = other_container; CallElementsWereReplaced(); @@ -333,7 +333,7 @@ class ContainerProxyBase { // Intended to be exposed via `using` in `DerivedType`. // NOLINTNEXTLINE(misc-unconventional-assign-operator) - DerivedType& operator=(ContainerType&& other_container) noexcept { + DerivedType &operator=(ContainerType &&other_container) noexcept { CallElementsBeingReplaced(); container() = std::move(other_container); CallElementsWereReplaced(); @@ -342,20 +342,20 @@ class ContainerProxyBase { // Intended to be exposed via `using` in `DerivedType`. // NOLINTNEXTLINE(misc-unconventional-assign-operator) - DerivedType& operator=(std::initializer_list values) { + DerivedType &operator=(std::initializer_list values) { CallElementsBeingReplaced(); container() = values; CallElementsWereReplaced(); return *derived(); } - void swap(ContainerType& other) { + void swap(ContainerType &other) { CallElementsBeingReplaced(); container().swap(other); CallElementsWereReplaced(); } - void swap(DerivedType& other) { + void swap(DerivedType &other) { CallElementsBeingReplaced(); other.CallElementsBeingReplaced(); container().swap(other.container()); @@ -367,8 +367,8 @@ class ContainerProxyBase { // `swap(DerivedType&)` method (either through importing this class' method // via `using` or implementing their own version). template ().swap(std::declval()))> - friend void swap(DerivedType& a, DerivedType& b) { + class = decltype(std::declval().swap(std::declval()))> + friend void swap(DerivedType &a, DerivedType &b) { a.swap(b); } @@ -396,7 +396,7 @@ class ContainerProxyBase { } } - void resize(size_type count, const value_type& value) { + void resize(size_type count, const value_type &value) { const auto initial_size = container().size(); if (count < initial_size) { const iterator first_removed = std::next(container().begin(), count); @@ -429,11 +429,11 @@ class ContainerProxyBase { std::distance(container().cbegin(), iter)); } - auto* derived() { return static_cast(this); } - const auto* derived() const { return static_cast(this); } + auto *derived() { return static_cast(this); } + const auto *derived() const { return static_cast(this); } - ContainerType& container() { return derived()->underlying_container(); } - const ContainerType& container() const { + ContainerType &container() { return derived()->underlying_container(); } + const ContainerType &container() const { return derived()->underlying_container(); } diff --git a/common/util/container_proxy_test.cc b/common/util/container_proxy_test.cc index 2ac0c9dfb..163b5f800 100644 --- a/common/util/container_proxy_test.cc +++ b/common/util/container_proxy_test.cc @@ -52,8 +52,8 @@ struct TestTrace { // Constructors for creating reference object in tests template - TestTrace(ContainerProxyEvent method, const SnapshotRange& snapshot, - int first_index, int last_index, const ValuesRange& values) + TestTrace(ContainerProxyEvent method, const SnapshotRange &snapshot, + int first_index, int last_index, const ValuesRange &values) : triggered_method(method), container_snapshot(std::begin(snapshot), std::end(snapshot)), first_index(first_index), @@ -61,7 +61,7 @@ struct TestTrace { values(std::begin(values), std::end(values)) {} template - TestTrace(ContainerProxyEvent method, const SnapshotRange& snapshot, + TestTrace(ContainerProxyEvent method, const SnapshotRange &snapshot, int first_index, int last_index, std::initializer_list values) : triggered_method(method), @@ -86,12 +86,12 @@ struct TestTrace { // Constructors for creating trace objects in a container implementation template - TestTrace(ContainerProxyEvent method, const Range& container) + TestTrace(ContainerProxyEvent method, const Range &container) : triggered_method(method), container_snapshot(container.begin(), container.end()) {} template - TestTrace(ContainerProxyEvent method, const Range& container, + TestTrace(ContainerProxyEvent method, const Range &container, const_iterator first, const_iterator last) : triggered_method(method), container_snapshot(container.begin(), container.end()), @@ -101,7 +101,7 @@ struct TestTrace { // Operators - bool operator==(const TestTrace& other) const { + bool operator==(const TestTrace &other) const { return triggered_method == other.triggered_method && std::equal(container_snapshot.begin(), container_snapshot.end(), other.container_snapshot.begin()) && @@ -110,7 +110,7 @@ struct TestTrace { std::equal(values.begin(), values.end(), other.values.begin()); } - friend std::ostream& operator<<(std::ostream& s, TestTrace obj) { + friend std::ostream &operator<<(std::ostream &s, TestTrace obj) { switch (obj.triggered_method) { case ContainerProxyEvent::kUnknown: s << "UNKNOWN"; @@ -146,7 +146,7 @@ class ContainerProxy friend Base; public: - explicit ContainerProxy(Container& container) : container_(container) {} + explicit ContainerProxy(Container &container) : container_(container) {} using typename Base::container_type; @@ -209,10 +209,10 @@ class ContainerProxy std::vector> trace_data; private: - Container& container_; + Container &container_; - Container& underlying_container() { return container_; } - const Container& underlying_container() const { return container_; } + Container &underlying_container() { return container_; } + const Container &underlying_container() const { return container_; } void ElementsInserted(const_iterator first, const_iterator last) { trace_data.push_back(TestTrace(ContainerProxyEvent::kInserted, @@ -352,7 +352,7 @@ TYPED_TEST(BidirectionalContainerProxyTest, Iteration) { } { int i = 0; - for (auto& elem : this->proxy) { + for (auto &elem : this->proxy) { EXPECT_EQ(elem, *std::next(this->container.begin(), i)) << "i = " << i; EXPECT_EQ(&elem, &*std::next(this->container.begin(), i)) << "i = " << i; ++i; @@ -404,7 +404,7 @@ TYPED_TEST(MutableBidirectionalContainerProxyTest, ModifiersPushEmplaceBack) { std::string four = std::string("four"); // Make sure the string buffer is dynamically allocated. four.reserve(1000); - const auto* four_data = four.data(); + const auto *four_data = four.data(); this->proxy.push_back(std::move(four)); EXPECT_EQ(this->proxy.size(), initial_size + 2); EXPECT_EQ(this->proxy.back(), "four"); @@ -446,7 +446,7 @@ TYPED_TEST(MutablePrependableContainerProxyTest, ModifiersPushEmplaceFront) { std::string minus_two = std::string("minus_two"); // Make sure the string buffer is dynamically allocated. minus_two.reserve(1000); - const auto* minus_two_data = minus_two.data(); + const auto *minus_two_data = minus_two.data(); this->proxy.push_front(std::move(minus_two)); EXPECT_EQ(this->proxy.size(), initial_size + 2); EXPECT_EQ(this->proxy.front(), "minus_two"); @@ -525,7 +525,7 @@ TYPED_TEST(MutableBidirectionalContainerProxyTest, ModifiersInsertEmplace) { std::string s = std::string("bar"); // Make sure the string buffer is dynamically allocated. s.reserve(1000); - const auto* s_data = s.data(); + const auto *s_data = s.data(); this->proxy.insert(std::next(this->proxy.begin(), 1), std::move(s)); EXPECT_EQ(this->proxy.size(), initial_size + 9); EXPECT_EQ(*std::next(this->proxy.begin(), 1), "bar"); @@ -709,8 +709,8 @@ TYPED_TEST(MutableBidirectionalContainerProxyTest, AssignmentOperator) { this->proxy.trace_data.clear(); - auto& proxy_ref_0 = this->proxy = other_container; - static_assert(std::is_same_v); + auto &proxy_ref_0 = this->proxy = other_container; + static_assert(std::is_same_v); EXPECT_THAT(this->container, ElementsAre("foo", "bar", "baz")); EXPECT_THAT( this->proxy.trace_data, @@ -720,8 +720,8 @@ TYPED_TEST(MutableBidirectionalContainerProxyTest, AssignmentOperator) { this->proxy.trace_data.clear(); - auto& proxy_ref_1 = this->proxy = {"x", "y"}; - static_assert(std::is_same_v); + auto &proxy_ref_1 = this->proxy = {"x", "y"}; + static_assert(std::is_same_v); EXPECT_THAT(this->container, ElementsAre("x", "y")); EXPECT_THAT( this->proxy.trace_data, @@ -731,9 +731,9 @@ TYPED_TEST(MutableBidirectionalContainerProxyTest, AssignmentOperator) { this->proxy.trace_data.clear(); - auto* const foo_ptr = &other_container.front(); - auto& proxy_ref_2 = this->proxy = std::move(other_container); - static_assert(std::is_same_v); + auto *const foo_ptr = &other_container.front(); + auto &proxy_ref_2 = this->proxy = std::move(other_container); + static_assert(std::is_same_v); EXPECT_THAT(this->container, ElementsAre("foo", "bar", "baz")); // Verify that the container has been moved and not copied. EXPECT_EQ(&this->container.front(), foo_ptr); diff --git a/common/util/container_util.h b/common/util/container_util.h index 861595ceb..3c0ef68e9 100644 --- a/common/util/container_util.h +++ b/common/util/container_util.h @@ -34,7 +34,7 @@ struct ValueTypeFromKeyType; template struct ValueTypeFromKeyType> { using ValueType = std::pair; - ValueType operator()(const KeyType& k) const { + ValueType operator()(const KeyType &k) const { return {k, MappedType{}}; // default-value mapped-type } }; @@ -42,15 +42,15 @@ struct ValueTypeFromKeyType> { // Partial specialization for when the KeyType == ValueType, for set-like types. template struct ValueTypeFromKeyType { - const KeyType& operator()(const KeyType& k) const { + const KeyType &operator()(const KeyType &k) const { return k; // just forward the key } }; } // namespace internal template -bool InsertOrUpdate(M* map, const typename M::key_type& k, - const typename M::mapped_type& v) { +bool InsertOrUpdate(M *map, const typename M::key_type &k, + const typename M::mapped_type &v) { auto ret = map->insert({k, v}); if (ret.second) return true; ret.first->second = v; @@ -58,7 +58,7 @@ bool InsertOrUpdate(M* map, const typename M::key_type& k, } template -typename M::mapped_type& InsertKeyOrDie(M* m, const typename M::key_type& k) { +typename M::mapped_type &InsertKeyOrDie(M *m, const typename M::key_type &k) { using value_inserter = internal::ValueTypeFromKeyType; auto res = m->insert(value_inserter()(k)); @@ -67,22 +67,22 @@ typename M::mapped_type& InsertKeyOrDie(M* m, const typename M::key_type& k) { } template -const typename M::mapped_type& FindWithDefault( - M& map, const typename M::key_type& key, const typename M::mapped_type& d) { +const typename M::mapped_type &FindWithDefault( + M &map, const typename M::key_type &key, const typename M::mapped_type &d) { auto found = map.find(key); return (found == map.end()) ? d : found->second; } template -const typename M::mapped_type* FindOrNull(M& map, - const typename M::key_type& k) { +const typename M::mapped_type *FindOrNull(M &map, + const typename M::key_type &k) { auto found = map.find(k); return (found == map.end()) ? nullptr : &found->second; } template -const typename M::mapped_type& FindOrDie(M& map, - const typename M::key_type& k) { +const typename M::mapped_type &FindOrDie(M &map, + const typename M::key_type &k) { auto found = map.find(k); CHECK(found != map.end()); return found->second; diff --git a/common/util/enum_flags.h b/common/util/enum_flags.h index ed60a455b..086912370 100644 --- a/common/util/enum_flags.h +++ b/common/util/enum_flags.h @@ -32,7 +32,7 @@ namespace internal { // Suitable for use with absl::StrJoin()'s formatter arguments. struct FirstElementFormatter { template - void operator()(std::string* out, const P& p) const { + void operator()(std::string *out, const P &p) const { out->append(p.first.begin(), p.first.end()); } }; @@ -109,13 +109,13 @@ class EnumNameMap { : enum_name_map_(pairs) {} ~EnumNameMap() = default; - EnumNameMap(const EnumNameMap&) = delete; - EnumNameMap(EnumNameMap&&) = delete; - EnumNameMap& operator=(const EnumNameMap&) = delete; - EnumNameMap& operator=(EnumNameMap&&) = delete; + EnumNameMap(const EnumNameMap &) = delete; + EnumNameMap(EnumNameMap &&) = delete; + EnumNameMap &operator=(const EnumNameMap &) = delete; + EnumNameMap &operator=(EnumNameMap &&) = delete; // Print a list of string representations of the enums. - std::ostream& ListNames(std::ostream& stream, absl::string_view sep) const { + std::ostream &ListNames(std::ostream &stream, absl::string_view sep) const { return stream << absl::StrJoin(enum_name_map_.forward_view(), sep, internal::FirstElementFormatter()); } @@ -124,9 +124,9 @@ class EnumNameMap { // 'type_name' is a text name for the enum type used in diagnostics. // This variant write diagnostics to the 'errstream' stream. // Returns true if successful. - bool Parse(key_type text, EnumType* enum_value, std::ostream& errstream, + bool Parse(key_type text, EnumType *enum_value, std::ostream &errstream, absl::string_view type_name) const { - const EnumType* found_value = enum_name_map_.find_forward(text); + const EnumType *found_value = enum_name_map_.find_forward(text); if (found_value != nullptr) { *enum_value = *found_value; return true; @@ -139,7 +139,7 @@ class EnumNameMap { // Converts the name of an enum to its corresponding value. // This variant write diagnostics to the 'error' string. - bool Parse(key_type text, EnumType* enum_value, std::string* error, + bool Parse(key_type text, EnumType *enum_value, std::string *error, absl::string_view type_name) const { std::ostringstream stream; const bool success = Parse(text, enum_value, stream, type_name); @@ -149,13 +149,13 @@ class EnumNameMap { // Returns the string representation of an enum. absl::string_view EnumName(EnumType value) const { - const auto* key = enum_name_map_.find_reverse(value); + const auto *key = enum_name_map_.find_reverse(value); if (key == nullptr) return "???"; return *key; } // Prints the string representation of an enum to stream. - std::ostream& Unparse(EnumType value, std::ostream& stream) const { + std::ostream &Unparse(EnumType value, std::ostream &stream) const { return stream << EnumName(value); } diff --git a/common/util/enum_flags_test.cc b/common/util/enum_flags_test.cc index e107911af..420ea3bab 100644 --- a/common/util/enum_flags_test.cc +++ b/common/util/enum_flags_test.cc @@ -55,26 +55,26 @@ class EnumNameMapTest : public ::testing::Test, public TestMapType { static const TestMapType test_map; // Conventional stream printer (declared in header providing enum). -std::ostream& operator<<(std::ostream& stream, MyFakeEnum p) { +std::ostream &operator<<(std::ostream &stream, MyFakeEnum p) { return test_map.Unparse(p, stream); } // Testing using the absl::flags API, but we're only testing this particular // overload, and thus, don't actually need to depend on their library. -bool AbslParseFlag(absl::string_view text, MyFakeEnum* mode, - std::string* error) { +bool AbslParseFlag(absl::string_view text, MyFakeEnum *mode, + std::string *error) { return test_map.Parse(text, mode, error, "MyFakeEnum"); } -std::string AbslUnparseFlag(const MyFakeEnum& mode) { +std::string AbslUnparseFlag(const MyFakeEnum &mode) { std::ostringstream stream; stream << mode; return stream.str(); } TEST_F(EnumNameMapTest, ParseFlagValueValues) { - for (const auto& p : enum_name_map_.forward_view()) { + for (const auto &p : enum_name_map_.forward_view()) { MyFakeEnum e = MyFakeEnum::kValue1; std::string error; EXPECT_TRUE(AbslParseFlag(p.first, &e, &error)) << " parsing " << p.first; @@ -91,13 +91,13 @@ TEST_F(EnumNameMapTest, ParseFlagTestInvalidValue) { // Make sure error message names the offending value, and lists all valid // values (map keys). EXPECT_TRUE(absl::StrContains(error, bad_value)); - for (const auto& p : enum_name_map_.forward_view()) { + for (const auto &p : enum_name_map_.forward_view()) { EXPECT_TRUE(absl::StrContains(error, p.first)); } } TEST_F(EnumNameMapTest, UnparseFlags) { - for (const auto& p : enum_name_map_.forward_view()) { + for (const auto &p : enum_name_map_.forward_view()) { EXPECT_EQ(AbslUnparseFlag(*p.second), p.first); } } @@ -113,7 +113,7 @@ enum class AnotherFakeEnum { kValueC, }; -std::ostream& operator<<(std::ostream& stream, AnotherFakeEnum p) { +std::ostream &operator<<(std::ostream &stream, AnotherFakeEnum p) { return stream << "!!!"; // don't care } diff --git a/common/util/expandable_tree_view.h b/common/util/expandable_tree_view.h index 295707f70..208c392d6 100644 --- a/common/util/expandable_tree_view.h +++ b/common/util/expandable_tree_view.h @@ -35,7 +35,7 @@ class TreeViewNodeInfo { using value_const_reference = typename TreeTraits::Value::const_reference; public: - explicit TreeViewNodeInfo(const WrappedNodeType& node) : node_(&node) {} + explicit TreeViewNodeInfo(const WrappedNodeType &node) : node_(&node) {} void Unexpand() { expand_ = false; } void Expand() { expand_ = true; } @@ -46,7 +46,7 @@ class TreeViewNodeInfo { private: // Immutable pointer to corresponding VectorTree node. // This promises to never modify the node's data. - const WrappedNodeType* const node_; + const WrappedNodeType *const node_; // Current view of this particular subtree node. // If true, then traverse children_, otherwise visit this node as one element. @@ -104,9 +104,9 @@ class ExpandableTreeView { using const_iterator = iterator; // Constructs (recursively) a fully-expanded view from the input tree. - explicit ExpandableTreeView(const tree_type& tree) + explicit ExpandableTreeView(const tree_type &tree) : view_( - Transform(tree, [](const tree_type& other) -> node_type { + Transform(tree, [](const tree_type &other) -> node_type { // Initialize a view node using the address of corresponding node // in the other tree. return node_type(other); @@ -116,19 +116,19 @@ class ExpandableTreeView { } // TODO(fangism): implement later as needed - ExpandableTreeView(const this_type&) = delete; - ExpandableTreeView(this_type&&) = delete; + ExpandableTreeView(const this_type &) = delete; + ExpandableTreeView(this_type &&) = delete; ~ExpandableTreeView() = default; // Accessors - const node_type& Value() const { return view_.Value(); } - node_type& Value() { return view_.Value(); } + const node_type &Value() const { return view_.Value(); } + node_type &Value() { return view_.Value(); } // Directly access children nodes by index. - const impl_type& operator[](size_t i) const { return view_.Children()[i]; } - impl_type& operator[](size_t i) { return view_.Children()[i]; } + const impl_type &operator[](size_t i) const { return view_.Children()[i]; } + impl_type &operator[](size_t i) { return view_.Children()[i]; } // Iteration @@ -138,12 +138,12 @@ class ExpandableTreeView { // Transformation // Apply a mutating transformation to this tree view, pre-order traversal. - void ApplyPreOrder(const std::function& f) { + void ApplyPreOrder(const std::function &f) { verible::ApplyPreOrder(view_, f); } // Apply a mutating transformation to this tree view, post-order traversal. - void ApplyPostOrder(const std::function& f) { + void ApplyPostOrder(const std::function &f) { verible::ApplyPostOrder(view_, f); } @@ -154,8 +154,8 @@ class ExpandableTreeView { // Recall that expanded nodes should *only* visit children, not self. // This behaves a lot like VectorTree::LeftmostDescendant(), only the // termination condition is different. - static const impl_type* first_unexpanded_child(const impl_type& current) { - const auto& info = current.Value(); + static const impl_type *first_unexpanded_child(const impl_type ¤t) { + const auto &info = current.Value(); if (info.IsExpanded() && !is_leaf(current)) { // Let compiler to tail-call optimize self-recursion. return first_unexpanded_child(current.Children().front()); @@ -170,7 +170,7 @@ class ExpandableTreeView { // This behaves a lot like VectorTree::NextLeaf(). // \precondition this->parent_->expand_ is true (for all ancestors), // otherwise we would have never reached this node. - static const impl_type* next_sibling(const impl_type& current) { + static const impl_type *next_sibling(const impl_type ¤t) { if (current.Parent() == nullptr) return nullptr; // Find the next sibling, if there is one. @@ -179,7 +179,7 @@ class ExpandableTreeView { if (next_rank == current.Parent()->Children().size()) { // This is the last child of the group. // Find the nearest parent that has a next child (ascending). - auto* next_ancestor = next_sibling(*current.Parent()); + auto *next_ancestor = next_sibling(*current.Parent()); return next_ancestor ? first_unexpanded_child(*next_ancestor) : nullptr; } // More children follow this one. @@ -208,17 +208,17 @@ class ExpandableTreeView::iterator { using iterator_category = std::forward_iterator_tag; using value_type = typename TreeTraits::Value::type; using difference_type = int; - using pointer = typename TreeTraits::Value::type*; - using reference = typename TreeTraits::Value::type&; + using pointer = typename TreeTraits::Value::type *; + using reference = typename TreeTraits::Value::type &; private: - explicit iterator(const impl_type* node) : node_(node) {} + explicit iterator(const impl_type *node) : node_(node) {} public: - iterator(const iterator&) = default; + iterator(const iterator &) = default; // pre-increment - iterator& operator++() { + iterator &operator++() { node_ = next_sibling(*node_); return *this; } @@ -232,18 +232,18 @@ class ExpandableTreeView::iterator { // TODO(fangism): implement decrement operators, to support bidirectionality - bool operator==(const iterator& rhs) const { return node_ == rhs.node_; } + bool operator==(const iterator &rhs) const { return node_ == rhs.node_; } - bool operator!=(const iterator& rhs) const { return !(*this == rhs); } + bool operator!=(const iterator &rhs) const { return !(*this == rhs); } - const value_type& operator*() const { return node_->Value().Value(); } - const value_type* operator->() const { return &node_->Value().Value(); } + const value_type &operator*() const { return node_->Value().Value(); } + const value_type *operator->() const { return &node_->Value().Value(); } private: // From the node_ pointer alone, we have sufficient information to iterate. // For now, this supports forward-only iteration because, once this becomes // nullptr, there is no way to go backward. - const impl_type* node_; + const impl_type *node_; }; } // namespace verible diff --git a/common/util/expandable_tree_view_test.cc b/common/util/expandable_tree_view_test.cc index 6ba0e1cf4..bc1d95416 100644 --- a/common/util/expandable_tree_view_test.cc +++ b/common/util/expandable_tree_view_test.cc @@ -37,7 +37,7 @@ using ExpandableTreeViewTestType = // Test that basic Tree View operations work on a singleton node. TEST(ExpandableTreeViewTest, RootOnly) { const VectorTreeTestType tree(verible::testing::MakeRootOnlyExampleTree()); - const auto& value = tree.Value(); + const auto &value = tree.Value(); // View testing. const ExpandableTreeViewTestType tree_view(tree); @@ -252,7 +252,7 @@ TEST(ExpandableTreeViewTest, FamilyTreeApplyPreOrder) { std::vector visit_order; tree_view.ApplyPreOrder( [=, &visit_order]( - VectorTree>>& node) { + VectorTree>> &node) { const absl::string_view name = node.Value().Value().name; visit_order.push_back(name); if (name[0] == 'p') { @@ -285,7 +285,7 @@ TEST(ExpandableTreeViewTest, FamilyTreeApplyPostOrder) { std::vector visit_order; tree_view.ApplyPostOrder( [=, &visit_order]( - VectorTree>>& node) { + VectorTree>> &node) { const absl::string_view name = node.Value().Value().name; visit_order.push_back(name); if (name[0] == 'p' && name.back() == '1') { diff --git a/common/util/file_util.h b/common/util/file_util.h index 23591d866..1b88fdf00 100644 --- a/common/util/file_util.h +++ b/common/util/file_util.h @@ -69,10 +69,10 @@ absl::string_view Stem(absl::string_view filename); // and going upwards the directory tree. Returns true if anything is found and // puts the found file in 'result'. absl::Status UpwardFileSearch(absl::string_view start, - absl::string_view filename, std::string* result); + absl::string_view filename, std::string *result); // Determines whether the given filename exists and is a regular file or pipe. -absl::Status FileExists(const std::string& filename); +absl::Status FileExists(const std::string &filename); // Read file "filename" and return its content as string. absl::StatusOr GetContentAsString(absl::string_view filename); @@ -121,15 +121,15 @@ class ScopedTestFile { ~ScopedTestFile(); // not copy-able - ScopedTestFile(const ScopedTestFile&) = delete; - ScopedTestFile& operator=(const ScopedTestFile&) = delete; + ScopedTestFile(const ScopedTestFile &) = delete; + ScopedTestFile &operator=(const ScopedTestFile &) = delete; // move-able (to support vector::emplace_back()) - ScopedTestFile(ScopedTestFile&&) = default; - ScopedTestFile& operator=(ScopedTestFile&&) = default; + ScopedTestFile(ScopedTestFile &&) = default; + ScopedTestFile &operator=(ScopedTestFile &&) = default; // Filename created by this instance. - const std::string& filename() const { return filename_; } + const std::string &filename() const { return filename_; } private: std::string filename_; diff --git a/common/util/file_util_test.cc b/common/util/file_util_test.cc index 1fc5bf8f2..c7c7b29b0 100644 --- a/common/util/file_util_test.cc +++ b/common/util/file_util_test.cc @@ -30,13 +30,13 @@ using testing::HasSubstr; #undef EXPECT_OK #define EXPECT_OK(value) \ { \ - const auto& s = (value); \ + const auto &s = (value); \ EXPECT_TRUE(s.ok()) << s; \ } #undef ASSERT_OK #define ASSERT_OK(value) \ { \ - const auto& s = (value); \ + const auto &s = (value); \ ASSERT_TRUE(s.ok()) << s; \ } @@ -74,7 +74,7 @@ TEST(FileUtil, Stem) { } // Returns the forward-slashed path in platform-specific notation. -static std::string PlatformPath(const std::string& path) { +static std::string PlatformPath(const std::string &path) { return std::filesystem::path(path).lexically_normal().string(); } @@ -88,7 +88,7 @@ TEST(FileUtil, GetContentAsMemBlock) { result = file::GetContentAsMemBlock(test_file); EXPECT_OK(result.status()); - auto& block = *result; + auto &block = *result; EXPECT_EQ(block->AsStringView(), test_content); } @@ -198,7 +198,7 @@ TEST(FileUtil, StatusErrorReporting) { content_or = file::GetContentAsString(test_file); EXPECT_FALSE(content_or.ok()) << "Expected permission denied for " << test_file; - const absl::Status& status = content_or.status(); + const absl::Status &status = content_or.status(); EXPECT_TRUE(absl::IsPermissionDenied(status)) << status; EXPECT_TRUE(absl::StartsWith(status.message(), test_file)) << "expect filename prefixed, but got " << status; @@ -218,7 +218,7 @@ static ScopedTestFile TestFileGenerator(absl::string_view content) { return ScopedTestFile(testing::TempDir(), content); } -static void TestFileConsumer(ScopedTestFile&& f) { +static void TestFileConsumer(ScopedTestFile &&f) { ScopedTestFile temp(std::move(f)); } @@ -238,11 +238,11 @@ TEST(FileUtil, ScopedTestFileEmplace) { files.emplace_back(::testing::TempDir(), "zzz"); names.emplace_back(files.back().filename()); } - for (const auto& name : names) { + for (const auto &name : names) { EXPECT_TRUE(file::FileExists(name).ok()); } } - for (const auto& name : names) { + for (const auto &name : names) { EXPECT_FALSE(file::FileExists(name).ok()); } } @@ -255,7 +255,7 @@ TEST(FileUtil, FileExistsDirectoryErrorMessage) { } static bool CreateFsStructure(absl::string_view base_dir, - const std::vector& tree) { + const std::vector &tree) { for (absl::string_view path : tree) { const std::string full_path = file::JoinPath(base_dir, path); if (absl::EndsWith(path, "/")) { @@ -310,7 +310,7 @@ TEST(FileUtil, ReadEmptyDirectory) { auto dir_or = file::ListDir(test_dir); ASSERT_TRUE(dir_or.ok()); - const auto& dir = *dir_or; + const auto &dir = *dir_or; EXPECT_EQ(dir.path, test_dir); EXPECT_TRUE(dir.directories.empty()); EXPECT_TRUE(dir.files.empty()); @@ -356,7 +356,7 @@ TEST(FileUtil, ReadDirectory) { auto dir_or = file::ListDir(test_dir); ASSERT_TRUE(dir_or.ok()) << dir_or.status().message(); - const auto& dir = *dir_or; + const auto &dir = *dir_or; EXPECT_EQ(dir.path, test_dir); EXPECT_EQ(dir.directories.size(), test_directories.size()); diff --git a/common/util/forward.h b/common/util/forward.h index 086faeaf3..977810809 100644 --- a/common/util/forward.h +++ b/common/util/forward.h @@ -31,12 +31,12 @@ struct ForwardReferenceElseConstruct { // Intentionally restricted to const reference to avoid the surprise // of modifying a temporary reference. // See also the two-parameter overload. - const T& operator()(const T& t) const { return t; } + const T &operator()(const T &t) const { return t; } // (overload) Constructs a temporary rvalue, when types are different. // This works with explicit-only constructors and implicit constructors. template - T operator()(const ConvertibleToT& other) const { + T operator()(const ConvertibleToT &other) const { return T(other); } }; diff --git a/common/util/forward_test.cc b/common/util/forward_test.cc index 5a0bdeac0..9091f0fb5 100644 --- a/common/util/forward_test.cc +++ b/common/util/forward_test.cc @@ -28,50 +28,50 @@ class TestClassA {}; class TestClassB { public: TestClassB() = default; - explicit TestClassB(const TestClassA&) {} + explicit TestClassB(const TestClassA &) {} }; TEST(ForwardReferenceElseConstructTest, ForwardReference) { TestClassA a; - const auto& ref = ForwardReferenceElseConstruct()(a); + const auto &ref = ForwardReferenceElseConstruct()(a); EXPECT_EQ(&ref, &a); // same object forwarded } TEST(ForwardReferenceElseConstructTest, ForwardReferenceConst) { const TestClassA a; - const auto& ref = ForwardReferenceElseConstruct()(a); + const auto &ref = ForwardReferenceElseConstruct()(a); EXPECT_EQ(&ref, &a); // same object forwarded } TEST(ForwardReferenceElseConstructTest, Construct) { const TestClassA a; - const auto& ref = ForwardReferenceElseConstruct()(a); + const auto &ref = ForwardReferenceElseConstruct()(a); static_assert(!std::is_same::value, "!std::is_same::value"); } TEST(ForwardReferenceElseConstructTest, ForwardStringView) { const absl::string_view a("hello"); - const auto& ref = ForwardReferenceElseConstruct()(a); + const auto &ref = ForwardReferenceElseConstruct()(a); EXPECT_EQ(&ref, &a); // same object forwarded } TEST(ForwardReferenceElseConstructTest, ConstructString) { const absl::string_view a("hello"); - const auto& ref = ForwardReferenceElseConstruct()(a); + const auto &ref = ForwardReferenceElseConstruct()(a); static_assert(!std::is_same::value, "!std::is_same::value"); } TEST(ForwardReferenceElseConstructTest, ForwardString) { const std::string a("hello"); - const auto& ref = ForwardReferenceElseConstruct()(a); + const auto &ref = ForwardReferenceElseConstruct()(a); EXPECT_EQ(&ref, &a); // same object forwarded } TEST(ForwardReferenceElseConstructTest, ConstructStringView) { const std::string a("hello"); - const auto& ref = ForwardReferenceElseConstruct()(a); + const auto &ref = ForwardReferenceElseConstruct()(a); static_assert(!std::is_same::value, "!std::is_same::value"); } diff --git a/common/util/init_command_line.cc b/common/util/init_command_line.cc index 2e4e6a32d..e8319c9ae 100644 --- a/common/util/init_command_line.cc +++ b/common/util/init_command_line.cc @@ -64,8 +64,8 @@ static std::string GetBuildVersion() { // We might want to have argc edited in the future, hence non-const param. std::vector InitCommandLine( absl::string_view usage, - int* argc, // NOLINT(readability-non-const-parameter) - char*** argv) { + int *argc, // NOLINT(readability-non-const-parameter) + char ***argv) { absl::InitializeSymbolizer(*argv[0]); absl::FlagsUsageConfig usage_config; usage_config.version_string = GetBuildVersion; @@ -74,7 +74,7 @@ std::vector InitCommandLine( // To avoid confusing and rarely used flags, we just enable logging via // environment variables. - const char* const stderr_log_level = getenv("VERIBLE_LOGTHRESHOLD"); + const char *const stderr_log_level = getenv("VERIBLE_LOGTHRESHOLD"); int log_level = 0; if (stderr_log_level && absl::SimpleAtoi(stderr_log_level, &log_level)) { absl::SetStderrThreshold( @@ -83,7 +83,7 @@ std::vector InitCommandLine( // Until vlog is provided in absl, we use our own global variable, defined // in logging.cc - const char* const vlog_level_env = getenv("VERIBLE_VLOG_DETAIL"); + const char *const vlog_level_env = getenv("VERIBLE_VLOG_DETAIL"); if (!vlog_level_env || !absl::SimpleAtoi(vlog_level_env, &verible::global_vlog_level_)) { global_vlog_level_ = 0; diff --git a/common/util/init_command_line.h b/common/util/init_command_line.h index e319b5ecd..c87134eae 100644 --- a/common/util/init_command_line.h +++ b/common/util/init_command_line.h @@ -31,7 +31,7 @@ std::string GetRepositoryVersion(); // as flags. // Returns positional arguments, where element[0] is the program name. std::vector InitCommandLine(absl::string_view usage, - int* argc, char*** argv); + int *argc, char ***argv); } // namespace verible diff --git a/common/util/interval.h b/common/util/interval.h index e7e16aede..84839928c 100644 --- a/common/util/interval.h +++ b/common/util/interval.h @@ -36,13 +36,13 @@ struct Interval { T max = {}; Interval() = default; - Interval(const T& f, const T& s) : min(f), max(s) {} + Interval(const T &f, const T &s) : min(f), max(s) {} // Want this implicit constructor so that one can pass an initializer list // directly to make an Interval, e.g. Interval<> ii({x, y}); template Interval( // NOLINT(google-explicit-constructor) - const std::pair& p) + const std::pair &p) : min(p.first), max(p.second) {} bool empty() const { return min == max; } @@ -52,28 +52,28 @@ struct Interval { T length() const { return max - min; } // Returns true if integer value is in [min, max). - bool contains(const T& value) const { return value >= min && value < max; } + bool contains(const T &value) const { return value >= min && value < max; } // Returns true if other range is in [min, max). - bool contains(const Interval& other) const { + bool contains(const Interval &other) const { return min <= other.min && max >= other.max; } // Returns true if range [lower, upper) is in [min, max). - bool contains(const T& lower, const T& upper) const { + bool contains(const T &lower, const T &upper) const { return contains(Interval(lower, upper)); } - bool operator==(const Interval& other) const { + bool operator==(const Interval &other) const { return min == other.min && max == other.max; } - bool operator!=(const Interval& other) const { return !(*this == other); } + bool operator!=(const Interval &other) const { return !(*this == other); } // Formats the interval to show an inclusive range. // If 'compact' is true and (min +1 == max), only print the min. // The inverse operation is ParseInclusiveRange(). - std::ostream& FormatInclusive(std::ostream& stream, bool compact, + std::ostream &FormatInclusive(std::ostream &stream, bool compact, char delim = '-') const { const T upper = max - 1; if ((min == upper) && compact) { @@ -87,7 +87,7 @@ struct Interval { // Forwarding function that avoids constructing a temporary Interval. template -const Interval& AsInterval(const Interval& i) { +const Interval &AsInterval(const Interval &i) { return typename Interval::forwarder()(i); } @@ -95,17 +95,17 @@ const Interval& AsInterval(const Interval& i) { // This is useful for conveniently accessing const-methods of Interval. // Relies on compiler optimization to elide temporary construction. template -Interval AsInterval(const std::pair& p) { +Interval AsInterval(const std::pair &p) { return typename Interval::forwarder()(p); } template -Interval AsInterval(const std::pair& p) { +Interval AsInterval(const std::pair &p) { return typename Interval::forwarder()(p); } // Default formatting of Interval<>. template -std::ostream& operator<<(std::ostream& stream, const Interval& interval) { +std::ostream &operator<<(std::ostream &stream, const Interval &interval) { return stream << '[' << interval.min << ", " << interval.max << ')'; } @@ -114,8 +114,8 @@ std::ostream& operator<<(std::ostream& stream, const Interval& interval) { // Returns true on success, false on parse error. // This is the reverse of Interval::FormatInclusive(). template -bool ParseInclusiveRange(Interval* interval, absl::string_view first_str, - absl::string_view last_str, std::ostream* errstream) { +bool ParseInclusiveRange(Interval *interval, absl::string_view first_str, + absl::string_view last_str, std::ostream *errstream) { T first, last; if (!absl::SimpleAtoi(first_str, &first)) { *errstream << "Expected number, but got: \"" << first_str << "\"." diff --git a/common/util/interval_map.h b/common/util/interval_map.h index b2dc2a745..8d7586dea 100644 --- a/common/util/interval_map.h +++ b/common/util/interval_map.h @@ -28,14 +28,14 @@ namespace internal { // Comparator to treat the first value of a pair as the effective key. template struct CompareFirst { - bool operator()(const K& left, const std::pair& right) const { + bool operator()(const K &left, const std::pair &right) const { return left < right.first; } - bool operator()(const std::pair& left, const K& right) const { + bool operator()(const std::pair &left, const K &right) const { return left.first < right; } - bool operator()(const std::pair& left, - const std::pair& right) const { + bool operator()(const std::pair &left, + const std::pair &right) const { return left.first < right.first; } @@ -47,8 +47,8 @@ struct CompareFirst { // or else end(). template // M is a map-type static typename auto_iterator_selector::type // const_iterator or iterator -FindSpanningInterval(M& intervals, - const typename M::key_type::first_type& key) { +FindSpanningInterval(M &intervals, + const typename M::key_type::first_type &key) { const auto iter = intervals.upper_bound({key, key}); // lower_bound misses equality condition if (iter != intervals.begin()) { @@ -64,7 +64,7 @@ FindSpanningInterval(M& intervals, // range of 'value' if there is one, or else end(). template // M is a map-type static typename auto_iterator_selector::type // const_iterator or iterator -FindSpanningInterval(M& intervals, const typename M::key_type interval) { +FindSpanningInterval(M &intervals, const typename M::key_type interval) { // Nothing 'contains' an empty interval. if (interval.first != interval.second) { // not an empty interval // Find an interval that contains the lower bound. @@ -83,7 +83,7 @@ FindSpanningInterval(M& intervals, const typename M::key_type interval) { // Precondition: 'intervals' map contains non-overlapping key ranges. template // M is a map-type static std::pair FindNonoverlappingEmplacePosition( - M& intervals, const typename M::key_type& interval) { + M &intervals, const typename M::key_type &interval) { if (intervals.empty()) return {intervals.end(), true}; const auto iter = intervals.upper_bound({interval.first, interval.second /* don't care */}); @@ -139,11 +139,11 @@ class DisjointIntervalMap { public: DisjointIntervalMap() = default; - DisjointIntervalMap(const DisjointIntervalMap&) = delete; - DisjointIntervalMap(DisjointIntervalMap&&) = + DisjointIntervalMap(const DisjointIntervalMap &) = delete; + DisjointIntervalMap(DisjointIntervalMap &&) = delete; // could be default if needed - DisjointIntervalMap& operator=(const DisjointIntervalMap&) = delete; - DisjointIntervalMap& operator=(DisjointIntervalMap&&) = + DisjointIntervalMap &operator=(const DisjointIntervalMap &) = delete; + DisjointIntervalMap &operator=(DisjointIntervalMap &&) = delete; // could be default if needed bool empty() const { return map_.empty(); } @@ -152,29 +152,29 @@ class DisjointIntervalMap { // Returns an iterator to the entry whose key-range contains 'key', or else // end(). - const_iterator find(const K& key) const { + const_iterator find(const K &key) const { return internal::FindSpanningInterval(map_, key); } // Returns an iterator to the entry whose key-range wholly contains the 'key' // range, or else end(). - const_iterator find(const key_type& key) const { + const_iterator find(const key_type &key) const { return internal::FindSpanningInterval(map_, key); } // Returns an iterator to the entry whose key-range contains 'key', or else // end(). - iterator find(const K& key) { + iterator find(const K &key) { return internal::FindSpanningInterval(map_, key); } // Returns an iterator to the entry whose key-range wholly contains the 'key' // range, or else end(). - iterator find(const key_type& key) { + iterator find(const key_type &key) { return internal::FindSpanningInterval(map_, key); } // Inserts a value associated with the 'key' interval if it does not overlap // with any other key-interval already in the map. // The 'value' must be moved in (emplace). - std::pair emplace(key_type key, V&& value) { + std::pair emplace(key_type key, V &&value) { CHECK(key.first <= key.second); // CHECK_LE requires printability const std::pair p( internal::FindNonoverlappingEmplacePosition(map_, key)); @@ -191,7 +191,7 @@ class DisjointIntervalMap { // consumed 'value'). // Recommend using this for key-ranges that correspond to allocated memory, // because allocators must return non-overlapping memory ranges. - iterator must_emplace(const key_type& key, V&& value) { + iterator must_emplace(const key_type &key, V &&value) { const auto p(emplace(key, std::move(value))); CHECK(p.second) << "Failed to emplace!"; return p.first; diff --git a/common/util/interval_map_test.cc b/common/util/interval_map_test.cc index c3ef789e5..9ed3be268 100644 --- a/common/util/interval_map_test.cc +++ b/common/util/interval_map_test.cc @@ -182,7 +182,7 @@ TEST(DisjointIntervalMapTest, MustEmplaceSuccess) { constexpr std::tuple kTestValues[] = { {3, 4, 5}, {1, 3, 9}, {4, 7, 2}, {-10, -5, 0}, {10, 15, 33}, }; - for (const auto& t : kTestValues) { + for (const auto &t : kTestValues) { const auto iter = imap.must_emplace({std::get<0>(t), std::get<1>(t)}, std::make_unique(std::get<2>(t))); // Ensure that inserted value is the expected key and value. @@ -268,7 +268,7 @@ TEST(DisjointIntervalMapTest, BeginEndRangeConstIterators) { imap.must_emplace({50, 60}, std::make_unique(10)); imap.must_emplace({30, 35}, std::make_unique(5)); imap.must_emplace({39, 46}, std::make_unique(7)); - for (const auto& pair : imap) { + for (const auto &pair : imap) { EXPECT_EQ(pair.first.second - pair.first.first, *pair.second); } } @@ -278,11 +278,11 @@ TEST(DisjointIntervalMapTest, BeginEndRangeConstIterators) { using VectorIntervalMap = DisjointIntervalMap::const_iterator, std::vector>; -static VectorIntervalMap::iterator AllocateVectorBlock(VectorIntervalMap* vmap, +static VectorIntervalMap::iterator AllocateVectorBlock(VectorIntervalMap *vmap, int min, int max) { std::vector v(max - min); int i = min; - for (auto& e : v) { + for (auto &e : v) { e = i; ++i; } @@ -294,7 +294,7 @@ static VectorIntervalMap::iterator AllocateVectorBlock(VectorIntervalMap* vmap, return new_iter; } -static void VerifyVectorBlock(const VectorIntervalMap& vmap, +static void VerifyVectorBlock(const VectorIntervalMap &vmap, VectorIntervalMap::const_iterator block) { for (auto left = block->first.first; left != std::prev(block->first.second); ++left) { diff --git a/common/util/interval_set.h b/common/util/interval_set.h index d27140152..c73fc7da1 100644 --- a/common/util/interval_set.h +++ b/common/util/interval_set.h @@ -36,11 +36,11 @@ namespace verible { // Iter can point to any Interval<> or any type constructible to Interval<> // (like std::pair). template -std::ostream& FormatIntervals(std::ostream& stream, Iter begin, Iter end) { +std::ostream &FormatIntervals(std::ostream &stream, Iter begin, Iter end) { using value_type = typename std::iterator_traits::value_type; return stream << absl::StrJoin( begin, end, ", ", - [](std::string* out, const value_type& interval) { + [](std::string *out, const value_type &interval) { std::ostringstream temp_stream; temp_stream << AsInterval(interval); out->append(temp_stream.str()); @@ -56,7 +56,7 @@ class IntervalSetImpl { // iterator variants. template // M is a map-type static typename auto_iterator_selector::type // const_iterator or iterator - FindLowerBound(M& intervals, const typename M::mapped_type& value) { + FindLowerBound(M &intervals, const typename M::mapped_type &value) { const auto lower_bound = intervals.lower_bound(value); if (lower_bound == intervals.begin()) { return lower_bound; @@ -74,8 +74,8 @@ class IntervalSetImpl { // 'interval', if one exists, else end(). template // M is a map-type static typename auto_iterator_selector::type // const_iterator or iterator - FindSpanningInterval(M& intervals, - const Interval& interval) { + FindSpanningInterval(M &intervals, + const Interval &interval) { CHECK(interval.valid()); // Nothing 'contains' an empty interval. if (!interval.empty()) { @@ -93,7 +93,7 @@ class IntervalSetImpl { // This is more efficient than checking for [value, value +1). template // M is a map-type static typename auto_iterator_selector::type // const_iterator or iterator - FindSpanningInterval(M& intervals, const typename M::mapped_type& value) { + FindSpanningInterval(M &intervals, const typename M::mapped_type &value) { const auto upper_bound = intervals.upper_bound(value); // lower_bound misses equality condition if (upper_bound != intervals.begin()) { @@ -113,9 +113,9 @@ class IntervalSetImpl { // Precondition: 'intervals' map contains non-overlapping key ranges. template // M is a map-type static std::pair - FindNonoverlappingEmplacePosition(M& intervals, - const typename M::mapped_type& min, - const typename M::mapped_type& max) { + FindNonoverlappingEmplacePosition(M &intervals, + const typename M::mapped_type &min, + const typename M::mapped_type &max) { if (intervals.empty()) return {intervals.end(), true}; const auto iter = intervals.upper_bound(min); if (iter == intervals.begin()) { @@ -157,17 +157,17 @@ class IntervalSet : private internal::IntervalSetImpl { IntervalSet(std::initializer_list> ranges) { // Add-ing will properly fuse overlapping intervals and maintain intervals_' // invariants. - for (const auto& range : ranges) { + for (const auto &range : ranges) { Add(range); } } - IntervalSet(const IntervalSet&) = default; - IntervalSet(IntervalSet&&) noexcept = default; + IntervalSet(const IntervalSet &) = default; + IntervalSet(IntervalSet &&) noexcept = default; ~IntervalSet() { CheckIntegrity(); } - IntervalSet& operator=(const IntervalSet&) = default; - IntervalSet& operator=(IntervalSet&&) noexcept = default; + IntervalSet &operator=(const IntervalSet &) = default; + IntervalSet &operator=(IntervalSet &&) noexcept = default; public: const_iterator begin() const { return intervals_.begin(); } @@ -186,59 +186,59 @@ class IntervalSet : private internal::IntervalSetImpl { // Remove all intervals from the set. void clear() { intervals_.clear(); } - void swap(IntervalSet& other) { intervals_.swap(other.intervals_); } + void swap(IntervalSet &other) { intervals_.swap(other.intervals_); } - bool operator==(const IntervalSet& other) const { + bool operator==(const IntervalSet &other) const { return intervals_ == other.intervals_; } - bool operator!=(const IntervalSet& other) const { + bool operator!=(const IntervalSet &other) const { return !(*this == other); } // Returns true if value is a member of an interval in the set. - bool Contains(const T& value) const { + bool Contains(const T &value) const { return Find(value) != intervals_.end(); } // Returns true if interval is entirely contained by an interval in the set. // If interval is empty, return false. - bool Contains(const Interval& interval) const { + bool Contains(const Interval &interval) const { return Find(interval) != intervals_.end(); } // TODO(fangism): bool Contains(const IntervalSet& interval) const; // Returns the first (interval) iterator that spans or follows 'value'. - const_iterator LowerBound(const T& value) const { + const_iterator LowerBound(const T &value) const { return internal::IntervalSetImpl::FindLowerBound(intervals_, value); } // Returns the first (interval) iterator that follows 'value'. - const_iterator UpperBound(const T& value) const { + const_iterator UpperBound(const T &value) const { return intervals_.upper_bound(value); } // Returns an iterator to the interval that entirely contains [min,max), // or the end iterator if no such interval exists, or the input is empty. - const_iterator Find(const Interval& interval) const { + const_iterator Find(const Interval &interval) const { return internal::IntervalSetImpl::FindSpanningInterval(intervals_, interval); } // Returns an iterator to the interval that contains 'value', // or the end iterator if no such interval exists. - const_iterator Find(const T& value) const { + const_iterator Find(const T &value) const { return internal::IntervalSetImpl::FindSpanningInterval(intervals_, value); } // Adds an interval to the interval set. // Also fuses any intervals that may result from the addition. - void Add(const Interval& interval) { + void Add(const Interval &interval) { CHECK(interval.valid()); if (interval.empty()) return; // adding empty interval changes nothing - const auto& min = interval.min; - const auto& max = interval.max; + const auto &min = interval.min; + const auto &max = interval.max; T new_max = max; iterator erase_end; @@ -287,15 +287,15 @@ class IntervalSet : private internal::IntervalSetImpl { } // Adds a single value to the interval set. - void Add(const T& value) { Add({value, value + 1}); } + void Add(const T &value) { Add({value, value + 1}); } // Removes an interval from the set. // Run-time: O(lg N), where N is the number of existing intervals. - void Difference(const Interval& interval) { + void Difference(const Interval &interval) { CHECK(interval.valid()); if (interval.empty()) return; // removing an empty interval changes nothing - const auto& min = interval.min; - const auto& max = interval.max; + const auto &min = interval.min; + const auto &max = interval.max; iterator erase_end; bool replace_upper = false; @@ -358,27 +358,27 @@ class IntervalSet : private internal::IntervalSetImpl { } // Removes a single value from the interval set. - void Difference(const T& value) { Difference({value, value + 1}); } + void Difference(const T &value) { Difference({value, value + 1}); } // Subtracts all intervals in the other set from this one. - void Difference(const IntervalSet& iset) { + void Difference(const IntervalSet &iset) { // TODO(fangism): optimize by implementing with two advancing iterators, // like linear-time sorted-sequence set operations. - for (const auto& interval : iset) { + for (const auto &interval : iset) { Difference(AsInterval(interval)); } } // Adds all intervals in the other set from this one. - void Union(const IntervalSet& iset) { + void Union(const IntervalSet &iset) { // Could be optimized with a hand-written linear-merge. - for (const auto& interval : iset) { + for (const auto &interval : iset) { Add(AsInterval(interval)); } } // Inverts the set of integers with respect to the given interval bound. - void Complement(const Interval& interval) { + void Complement(const Interval &interval) { // This could be more efficient with a direct insertion of elements. IntervalSet temp{{interval}}; temp.Difference(*this); @@ -391,7 +391,7 @@ class IntervalSet : private internal::IntervalSetImpl { template IntervalSet MonotonicTransform(std::function func) const { IntervalSet result; - for (const auto& interval : intervals_) { + for (const auto &interval : intervals_) { S left = func(interval.first); S right = func(interval.second); // ignore empty intervals that may result from range compression @@ -415,7 +415,7 @@ class IntervalSet : private internal::IntervalSetImpl { Interval interval; }; // comparator for binary search - auto less = [](size_t l, const cumulative_weighted_interval& r) { + auto less = [](size_t l, const cumulative_weighted_interval &r) { return l < r.cumulative_weight; }; @@ -423,7 +423,7 @@ class IntervalSet : private internal::IntervalSetImpl { std::vector interval_map; CHECK(!empty()) << "Non-empty interval set required for random generator"; size_t cumulative_size = 0; - for (const auto& range : intervals_) { + for (const auto &range : intervals_) { const auto interval = AsInterval(range); interval_map.push_back({cumulative_size, interval}); cumulative_size += interval.length(); @@ -445,11 +445,11 @@ class IntervalSet : private internal::IntervalSetImpl { }; } - std::ostream& FormatInclusive(std::ostream& stream, bool compact, + std::ostream &FormatInclusive(std::ostream &stream, bool compact, char delim = '-') const { return stream << absl::StrJoin( intervals_, ",", - [=](std::string* out, const value_type& interval) { + [=](std::string *out, const value_type &interval) { std::ostringstream temp_stream; AsInterval(interval).FormatInclusive(temp_stream, compact, delim); @@ -460,7 +460,7 @@ class IntervalSet : private internal::IntervalSetImpl { protected: // This operation is only intended for constructing test expect values. // It does not guarantee any invariants among intervals_. - void AddUnsafe(const Interval& interval) { + void AddUnsafe(const Interval &interval) { CHECK(interval.valid()); CHECK(!interval.empty()); intervals_[interval.min] = interval.max; @@ -494,17 +494,17 @@ class IntervalSet : private internal::IntervalSetImpl { // Mutable variants of Find(), LowerBound() are protected to preserve // invariants. - iterator Find(const Interval& interval) { + iterator Find(const Interval &interval) { return internal::IntervalSetImpl::FindSpanningInterval(intervals_, interval); } - iterator Find(const T& value) { + iterator Find(const T &value) { return internal::IntervalSetImpl::FindSpanningInterval(intervals_, value); } - iterator LowerBound(const T& value) { + iterator LowerBound(const T &value) { return internal::IntervalSetImpl::FindLowerBound(intervals_, value); } - iterator UpperBound(const T& value) { return intervals_.upper_bound(value); } + iterator UpperBound(const T &value) { return intervals_.upper_bound(value); } private: // Internal storage of intervals. @@ -516,12 +516,12 @@ class IntervalSet : private internal::IntervalSetImpl { }; // class IntervalSet template -void swap(IntervalSet& t1, IntervalSet& t2) { +void swap(IntervalSet &t1, IntervalSet &t2) { t1.swap(t2); } template -std::ostream& operator<<(std::ostream& stream, const IntervalSet& iset) { +std::ostream &operator<<(std::ostream &stream, const IntervalSet &iset) { // Format each IntervalSet internal interval as an Interval. return FormatIntervals(stream, iset.begin(), iset.end()); } @@ -532,13 +532,13 @@ std::ostream& operator<<(std::ostream& stream, const IntervalSet& iset) { // Iter is any iterator that points to a string (or string-like). // Returns false on any parse eror, true on complete success. template -bool ParseInclusiveRanges(IntervalSet* iset, Iter begin, Iter end, - std::ostream* errstream, const char sep = '-') { +bool ParseInclusiveRanges(IntervalSet *iset, Iter begin, Iter end, + std::ostream *errstream, const char sep = '-') { std::vector bounds; // re-use allocated memory - for (const auto& range : verible::make_range(begin, end)) { + for (const auto &range : verible::make_range(begin, end)) { bounds = absl::StrSplit(range, sep); if (bounds.size() == 1) { - const auto& arg = bounds.front(); + const auto &arg = bounds.front(); // ignore blanks, which comes from splitting "" if (arg.empty()) continue; int line_number; @@ -589,10 +589,10 @@ class DisjointIntervalSet : private internal::IntervalSetImpl { public: DisjointIntervalSet() = default; - DisjointIntervalSet(const DisjointIntervalSet&) = default; - DisjointIntervalSet(DisjointIntervalSet&&) noexcept = default; - DisjointIntervalSet& operator=(const DisjointIntervalSet&) = default; - DisjointIntervalSet& operator=(DisjointIntervalSet&&) noexcept = default; + DisjointIntervalSet(const DisjointIntervalSet &) = default; + DisjointIntervalSet(DisjointIntervalSet &&) noexcept = default; + DisjointIntervalSet &operator=(const DisjointIntervalSet &) = default; + DisjointIntervalSet &operator=(DisjointIntervalSet &&) noexcept = default; bool empty() const { return intervals_.empty(); } const_iterator begin() const { return intervals_.begin(); } @@ -600,19 +600,19 @@ class DisjointIntervalSet : private internal::IntervalSetImpl { // Returns an iterator to the entry whose key-range contains 'key', or else // end(). - const_iterator find(const T& key) const { + const_iterator find(const T &key) const { return FindSpanningInterval(intervals_, key); } // Returns an iterator to the entry whose key-range wholly contains the 'key' // range, or else end(). - const_iterator find(const std::pair& key) const { + const_iterator find(const std::pair &key) const { return FindSpanningInterval(intervals_, key); } // Inserts a value associated with the 'key' interval if it does not overlap // with any other key-interval already in the map. // The 'value' must be moved in (emplace). - std::pair emplace(const T& min_key, const T& max_key) { + std::pair emplace(const T &min_key, const T &max_key) { CHECK(min_key <= max_key); // CHECK_LE requires printability const std::pair p( FindNonoverlappingEmplacePosition(intervals_, min_key, max_key)); @@ -628,7 +628,7 @@ class DisjointIntervalSet : private internal::IntervalSetImpl { // consumed 'value'). // Recommend using this for key-ranges that correspond to allocated memory, // because allocators must return non-overlapping memory ranges. - const_iterator must_emplace(const T& min_key, const T& max_key) { + const_iterator must_emplace(const T &min_key, const T &max_key) { const auto p(emplace(min_key, max_key)); CHECK(p.second) << "Failed to emplace!"; return p.first; diff --git a/common/util/interval_set_test.cc b/common/util/interval_set_test.cc index cd57fdb0d..5ed32f2c3 100644 --- a/common/util/interval_set_test.cc +++ b/common/util/interval_set_test.cc @@ -33,7 +33,7 @@ class UnsafeIntervalSet : public interval_set_type { public: // intervals must be non-overlapping, but can be any order. UnsafeIntervalSet(std::initializer_list intervals) { - for (const auto& interval : intervals) { + for (const auto &interval : intervals) { AddUnsafe(interval); } // Ensure class invariants. @@ -402,7 +402,7 @@ TEST(IntervalSetTest, AddSingleValue) { {40, {{10, 20}, {30, 41}}}, {41, {{10, 20}, {30, 40}, {41, 42}}}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { UnsafeIntervalSet copy(init); copy.Add(test.value); EXPECT_EQ(copy, test.expected); @@ -466,7 +466,7 @@ TEST(IntervalSetTest, AddIntervalNonEmpty) { {{40, 41}, {{10, 20}, {30, 41}}}, {{41, 42}, {{10, 20}, {30, 40}, {41, 42}}}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { UnsafeIntervalSet copy(init); copy.Add(test.value); EXPECT_EQ(copy, test.expected); @@ -522,7 +522,7 @@ TEST(IntervalSetTest, DifferenceSingleValue) { {40, {{10, 20}, {30, 40}}}, {41, {{10, 20}, {30, 40}}}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VLOG(1) << "remove: " << test.value << " expect: " << test.expected; UnsafeIntervalSet copy(init); copy.Difference(test.value); @@ -611,7 +611,7 @@ TEST(IntervalSetTest, DifferenceIntervalNonEmpty) { {{40, 41}, {{10, 20}, {30, 40}}}, {{41, 41}, {{10, 20}, {30, 40}}}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VLOG(1) << "remove: " << test.value << " expect: " << test.expected; UnsafeIntervalSet copy(init); copy.Difference(test.value); @@ -642,7 +642,7 @@ TEST(IntervalSetTest, SetDifferences) { {{{1, 2}, {3, 4}, {5, 6}, {7, 8}}, {{0, 4}}, {{5, 6}, {7, 8}}}, {{{1, 2}, {3, 4}, {5, 6}, {7, 8}}, {{1, 9}}, {}}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VLOG(1) << test.a << " - " << test.b << " == " << test.c; UnsafeIntervalSet set(test.a); set.Difference(test.b); @@ -662,14 +662,14 @@ TEST(IntervalSetTest, SetUnions) { {{{1, 2}, {3, 4}, {5, 6}}, {{2, 7}}, {{1, 7}}}, {{{1, 2}, {5, 6}}, {{3, 4}, {7, 8}}, {{1, 2}, {3, 4}, {5, 6}, {7, 8}}}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VLOG(1) << test.a << " U " << test.b << " == " << test.c; UnsafeIntervalSet set(test.a); set.Union(test.b); EXPECT_EQ(set, test.c); } // commutative test - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VLOG(1) << test.b << " U " << test.a << " == " << test.c; UnsafeIntervalSet set(test.b); set.Union(test.a); @@ -686,7 +686,7 @@ TEST(IntervalSetTest, ComplementEmptyInitial) { {1, 10}, // {10, 100}, // }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { interval_set_type set; set.Complement(test); EXPECT_EQ(set, interval_set_type{test}); @@ -746,7 +746,7 @@ TEST(IntervalSetTest, ComplementGeneral) { {{40, 41}, {{40, 41}}}, {{40, 45}, {{40, 45}}}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VLOG(1) << "comp " << test.value << " == " << test.expected; UnsafeIntervalSet set(initial); set.Complement(test.value); @@ -957,7 +957,7 @@ using VectorIntervalSet = DisjointIntervalSet::const_iterator>; // Make sure values interior to a range point back to the entire range. template -static void DisjointIntervalConsistencyCheck(const M& iset) { +static void DisjointIntervalConsistencyCheck(const M &iset) { // works on integers and iterators for (auto iter = iset.begin(); iter != iset.end(); ++iter) { for (auto i = iter->first; i != iter->second; ++i) { @@ -987,7 +987,7 @@ TEST(DisjointIntervalSetTest, EmplaceOne) { } template -static typename M::const_iterator VerifyEmplace(M* iset, +static typename M::const_iterator VerifyEmplace(M *iset, typename M::mapped_type min, typename M::mapped_type max) { const auto p = iset->emplace(min, max); @@ -1065,7 +1065,7 @@ TEST(DisjointIntervalSetTest, MustEmplaceSuccess) { constexpr std::pair kTestValues[] = { {3, 4}, {1, 3}, {4, 7}, {-10, -5}, {10, 15}, }; - for (const auto& t : kTestValues) { + for (const auto &t : kTestValues) { const auto iter = iset.must_emplace(t.first, t.second); // Ensure that inserted value is the expected key min and max. EXPECT_EQ(iter->first, t.first); diff --git a/common/util/iterator_adaptors.h b/common/util/iterator_adaptors.h index 2915854d6..07e6e1e9a 100644 --- a/common/util/iterator_adaptors.h +++ b/common/util/iterator_adaptors.h @@ -40,7 +40,7 @@ constexpr std::reverse_iterator make_reverse_iterator(Iter i) { template verible::iterator_range< std::reverse_iterator::type>> -reversed_view(T& t) { +reversed_view(T &t) { // equivalent to: // return make_range(t.rbegin(), t.rend()); // but does not require the rbegin/rend methods. diff --git a/common/util/iterator_range_test.cc b/common/util/iterator_range_test.cc index 2ed458b26..93b1f8c41 100644 --- a/common/util/iterator_range_test.cc +++ b/common/util/iterator_range_test.cc @@ -187,7 +187,7 @@ TEST(IteratorRangeTest, WholeVectorMakePair) { TEST(IteratorRangeTest, PartArray) { int v[] = {2, 3, 5, 7, 11, 13}; { - iterator_range range(&v[1], &v[4]); // 3, 5, 7 + iterator_range range(&v[1], &v[4]); // 3, 5, 7 EXPECT_THAT(range, ElementsAre(3, 5, 7)); } { diff --git a/common/util/map_tree.h b/common/util/map_tree.h index 698c5099b..49aa9dc4e 100644 --- a/common/util/map_tree.h +++ b/common/util/map_tree.h @@ -91,7 +91,7 @@ class MapTree { MapTree() = default; // deep-copy, requires node_value_type to be copy-able. - MapTree(const MapTree& other) + MapTree(const MapTree &other) : node_value_(other.node_value_), subtrees_(other.subtrees_), // new copy is disconnected from original parent and is a new root @@ -100,7 +100,7 @@ class MapTree { } // move (with relink) - MapTree(MapTree&& other) noexcept + MapTree(MapTree &&other) noexcept : node_value_(std::move(other.node_value_)), subtrees_(std::move(other.subtrees_)), // Retain existing parent. @@ -109,8 +109,8 @@ class MapTree { } // TODO(fangism): implement assignments as needed - MapTree& operator=(const MapTree&) = delete; - MapTree& operator=(MapTree&&) = delete; + MapTree &operator=(const MapTree &) = delete; + MapTree &operator=(MapTree &&) = delete; // Recursively initialize trees (copy node value). // Example: @@ -126,7 +126,7 @@ class MapTree { // P{key6, M(value6)})} // ); template - explicit MapTree(const node_value_type& v, Args&&... args) + explicit MapTree(const node_value_type &v, Args &&...args) : node_value_(v), subtrees_() { EmplacePairs(std::forward(args)...); } @@ -134,14 +134,14 @@ class MapTree { // Recursively initialize trees (move node value). // See example above, using node_value_type copy. template - explicit MapTree(node_value_type&& v, Args&&... args) + explicit MapTree(node_value_type &&v, Args &&...args) : node_value_(std::move(v)), subtrees_() { EmplacePairs(std::forward(args)...); } ~MapTree() { CHECK(CheckIntegrity()); } - void swap(this_type& other) { + void swap(this_type &other) { std::swap(node_value_, other.node_value_); subtrees_.swap(other.subtrees_); Relink(); @@ -153,7 +153,7 @@ class MapTree { // Ensure parent-child mutual linkage invariant. // This property should hold after any mutating operation. bool CheckIntegrity() const { - for (const auto& node : *this) { + for (const auto &node : *this) { CHECK_EQ(node.second.Parent(), this) << "Inconsistency: child's parent does not point back to this node!"; if (!node.second.CheckIntegrity()) return false; @@ -169,7 +169,7 @@ class MapTree { // whether or not it was newly inserted or already there, and true to indicate // that it was newly created, false if an entry already existed at that key. template - std::pair TryEmplace(const key_type& key, Args&&... args) { + std::pair TryEmplace(const key_type &key, Args &&...args) { const auto p = subtrees_.emplace( key_value_type{key, node_value_type(std::forward(args)...)}); if (p.second) { @@ -188,7 +188,7 @@ class MapTree { // If there are duplicate keys, only the first of each key will be taken, // while the other duplicates will be dropped. template - void EmplacePairs(F&& first, Args&&... args) { + void EmplacePairs(F &&first, Args &&...args) { const auto p = subtrees_.emplace(std::forward(first)); if (p.second) { // Link child to parent. @@ -205,8 +205,8 @@ class MapTree { // Iteration/Navigation - this_type* Parent() { return parent_; } - const this_type* Parent() const { return parent_; } + this_type *Parent() { return parent_; } + const this_type *Parent() const { return parent_; } iterator begin() { return subtrees_.begin(); } const_iterator begin() const { return subtrees_.begin(); } @@ -217,7 +217,7 @@ class MapTree { size_t NumAncestors() const { size_t depth = 0; - for (const this_type* iter = Parent(); iter != nullptr; + for (const this_type *iter = Parent(); iter != nullptr; iter = iter->Parent()) { ++depth; } @@ -229,9 +229,9 @@ class MapTree { // This method could have been named IsDescendedFrom(). // nullptr is never considered an ancestor of any node. // 'this' node is not considered an ancestor of itself. - bool HasAncestor(const this_type* other) const { + bool HasAncestor(const this_type *other) const { if (other == nullptr) return false; - for (const this_type* iter = Parent(); iter != nullptr; + for (const this_type *iter = Parent(); iter != nullptr; iter = iter->Parent()) { if (iter == other) return true; } @@ -239,15 +239,15 @@ class MapTree { } // Returns pointer to the tree root, the greatest ancestor of this node. - const this_type* Root() const { - const this_type* node = this; + const this_type *Root() const { + const this_type *node = this; while (node->Parent() != nullptr) node = node->Parent(); return node; } // Returns pointer to the key-value pair of which this node is the value. // Root nodes return nullptr because they have no associated key. - const key_value_type* KeyValuePair() const { + const key_value_type *KeyValuePair() const { // Note: The use of offsetof below is technically undefined until C++17 // because std::pair is not a standard layout type. However, all compilers // currently provide well-defined behavior as an extension (which is @@ -266,8 +266,8 @@ class MapTree { // pair-co-located with a key. // Use pointer arithmetic to recover location of the key-value pair to which // this node value belongs. - return reinterpret_cast( - reinterpret_cast(this) - value_offset); + return reinterpret_cast( + reinterpret_cast(this) - value_offset); #ifdef __GNUC__ #pragma GCC diagnostic pop #endif @@ -276,24 +276,24 @@ class MapTree { // Returns the key associated with this node (if this is not a root), // otherwise return nullptr. - const key_type* Key() const { + const key_type *Key() const { if (Parent() == nullptr) return nullptr; // Root node has no key return &KeyValuePair()->first; } // Access - const subtrees_type& Children() const { return subtrees_; } + const subtrees_type &Children() const { return subtrees_; } - node_value_type& Value() { return node_value_; } - const node_value_type& Value() const { return node_value_; } + node_value_type &Value() { return node_value_; } + const node_value_type &Value() const { return node_value_; } // Search // Returns an iterator located at 'key' or end() if not found. // O(lg N), same as underlying map type. template - iterator Find(AnyKey&& key) { + iterator Find(AnyKey &&key) { // Forward to underlying map::find, enabling heterogenous lookup. return subtrees_.find(std::forward(key)); } @@ -301,7 +301,7 @@ class MapTree { // Returns a const_iterator located at 'key' or end() if not found. // O(lg N), same as underlying map type. template - const_iterator Find(AnyKey&& key) const { + const_iterator Find(AnyKey &&key) const { // Forward to underlying map::find, enabling heterogenous lookup. return subtrees_.find(std::forward(key)); } @@ -318,15 +318,15 @@ class MapTree { // Applies function 'f' to all nodes in this tree in a pre-order traversal. // Children are visited in key-order. - void ApplyPreOrder(const std::function& f) const { + void ApplyPreOrder(const std::function &f) const { f(*this); - for (const auto& child : *this) { + for (const auto &child : *this) { child.second.ApplyPreOrder(f); } } - void ApplyPreOrder(const std::function& f) { + void ApplyPreOrder(const std::function &f) { f(*this); - for (auto& child : *this) { + for (auto &child : *this) { child.second.ApplyPreOrder(f); } } @@ -334,23 +334,23 @@ class MapTree { // This variant of ApplyPreOrder expects a function on the underlying // node_value_type (const&). void ApplyPreOrder( - const std::function& f) const { - ApplyPreOrder([&f](const this_type& t) { f(t.Value()); }); + const std::function &f) const { + ApplyPreOrder([&f](const this_type &t) { f(t.Value()); }); } - void ApplyPreOrder(const std::function& f) { - ApplyPreOrder([&f](this_type& t) { f(t.Value()); }); + void ApplyPreOrder(const std::function &f) { + ApplyPreOrder([&f](this_type &t) { f(t.Value()); }); } // Applies function 'f' to all nodes in this tree in a post-order traversal. // Children are visited in key-order. - void ApplyPostOrder(const std::function& f) const { - for (const auto& child : *this) { + void ApplyPostOrder(const std::function &f) const { + for (const auto &child : *this) { child.second.ApplyPostOrder(f); } f(*this); } - void ApplyPostOrder(const std::function& f) { - for (auto& child : *this) { + void ApplyPostOrder(const std::function &f) { + for (auto &child : *this) { child.second.ApplyPostOrder(f); } f(*this); @@ -359,11 +359,11 @@ class MapTree { // This variant of ApplyPostOrder expects a function on the underlying // node_value_type (const&). void ApplyPostOrder( - const std::function& f) const { - ApplyPostOrder([&f](const this_type& t) { f(t.Value()); }); + const std::function &f) const { + ApplyPostOrder([&f](const this_type &t) { f(t.Value()); }); } - void ApplyPostOrder(const std::function& f) { - ApplyPostOrder([&f](this_type& t) { f(t.Value()); }); + void ApplyPostOrder(const std::function &f) { + ApplyPostOrder([&f](this_type &t) { f(t.Value()); }); } // Transforms @@ -372,18 +372,18 @@ class MapTree { // Pretty-print tree, using a custom node_value printer function. // Keys are printed using operator<<. - std::ostream& PrintTree( - std::ostream& stream, - const std::function& printer, - size_t indent = 0) const { + std::ostream &PrintTree(std::ostream &stream, + const std::function &printer, + size_t indent = 0) const { // Indentation will be printed before the key, not here. printer(stream << "{ (", Value(), indent) << ')'; if (Children().empty()) { stream << " }"; } else { stream << '\n'; - for (const auto& child : Children()) { + for (const auto &child : Children()) { stream << Spacer(indent + 2) << child.first << ": "; child.second.PrintTree(stream, printer, indent + 2) << '\n'; } @@ -394,18 +394,18 @@ class MapTree { // Pretty-print tree, using the default stream printer, which requires that // operator<<(std::ostream&, const node_value_type&) is defined. - std::ostream& PrintTree(std::ostream& stream, size_t indent = 0) const { + std::ostream &PrintTree(std::ostream &stream, size_t indent = 0) const { return PrintTree( stream, - [](std::ostream& s, const node_value_type& v, - size_t unused_indent) -> std::ostream& { return s << v; }, + [](std::ostream &s, const node_value_type &v, + size_t unused_indent) -> std::ostream & { return s << v; }, indent); } private: // methods // Establish parent-child links. void Relink() { - for (auto& subtree : subtrees_) { + for (auto &subtree : subtrees_) { subtree.second.parent_ = this; } } @@ -418,7 +418,7 @@ class MapTree { subtrees_type subtrees_; // Pointer to parent node, or nullptr if this is a root node. - this_type* parent_ = nullptr; + this_type *parent_ = nullptr; }; } // namespace verible diff --git a/common/util/map_tree_test.cc b/common/util/map_tree_test.cc index 697c21b2a..19f4d3a69 100644 --- a/common/util/map_tree_test.cc +++ b/common/util/map_tree_test.cc @@ -129,10 +129,10 @@ struct NonCopyable { explicit NonCopyable(absl::string_view text) : text(text) {} // move-only, no copy - NonCopyable(const NonCopyable&) = delete; - NonCopyable(NonCopyable&&) = default; - NonCopyable& operator=(const NonCopyable&) = delete; - NonCopyable& operator=(NonCopyable&&) = default; + NonCopyable(const NonCopyable &) = delete; + NonCopyable(NonCopyable &&) = default; + NonCopyable &operator=(const NonCopyable &) = delete; + NonCopyable &operator=(NonCopyable &&) = default; }; TEST(MapTreeTest, EmplaceOneNonCopyable) { @@ -238,7 +238,7 @@ TEST(MapTreeTest, InitializeMultipleChildrenWithDistinctKeys) { } EXPECT_EQ(m.Find(2), m.end()); - for (const auto& p : m) { + for (const auto &p : m) { EXPECT_EQ(p.second.KeyValuePair(), &p); EXPECT_EQ(p.second.Key(), &p.first); EXPECT_EQ(p.second.Parent(), &m); @@ -262,7 +262,7 @@ TEST(MapTreeTest, InitializeTwoGenerationsDeepCopy) { MapTreeTestType("bbb", KV{1, // grandchild MapTreeTestType("dd")})}); - const auto check = [](const MapTreeTestType& root) { + const auto check = [](const MapTreeTestType &root) { const auto child = root.Find(4); const auto grandchild = child->second.Find(1); EXPECT_EQ(child->first, 4); @@ -334,7 +334,7 @@ TEST(MapTreeTest, Swap) { KV{2, // child MapTreeTestType("aaaa")}); - const auto check1 = [](const MapTreeTestType& root) { + const auto check1 = [](const MapTreeTestType &root) { const auto child = root.Find(4); const auto grandchild = child->second.Find(1); EXPECT_EQ(child->first, 4); @@ -351,7 +351,7 @@ TEST(MapTreeTest, Swap) { EXPECT_EQ(grandchild->second.Root(), &root); }; - const auto check2 = [](const MapTreeTestType& root) { + const auto check2 = [](const MapTreeTestType &root) { const auto child = root.Find(2); EXPECT_EQ(child->first, 2); EXPECT_EQ(child->second.Value(), "aaaa"); @@ -380,15 +380,15 @@ TEST(MapTreeTest, TraversePrint) { // pre-order traversals { // print node values (string_views) std::ostringstream stream; - m.ApplyPreOrder([&stream](const MapTreeTestType::node_value_type& v) { + m.ApplyPreOrder([&stream](const MapTreeTestType::node_value_type &v) { stream << v << " "; }); EXPECT_EQ(stream.str(), "groot qq ww vv pp tt ss "); } { // print keys (ints) std::ostringstream stream; - m.ApplyPreOrder([&stream](const MapTreeTestType& node) { - const auto* key = node.Key(); + m.ApplyPreOrder([&stream](const MapTreeTestType &node) { + const auto *key = node.Key(); stream << (key == nullptr ? 0 : *key) << " "; }); EXPECT_EQ(stream.str(), "0 3 2 6 5 1 4 "); @@ -397,15 +397,15 @@ TEST(MapTreeTest, TraversePrint) { // post-order traversals { // print node values (string_views) std::ostringstream stream; - m.ApplyPostOrder([&stream](const MapTreeTestType::node_value_type& v) { + m.ApplyPostOrder([&stream](const MapTreeTestType::node_value_type &v) { stream << v << " "; }); EXPECT_EQ(stream.str(), "ww vv qq tt ss pp groot "); } { // print keys (ints) std::ostringstream stream; - m.ApplyPostOrder([&stream](const MapTreeTestType& node) { - const auto* key = node.Key(); + m.ApplyPostOrder([&stream](const MapTreeTestType &node) { + const auto *key = node.Key(); stream << (key == nullptr ? 0 : *key) << " "; }); EXPECT_EQ(stream.str(), "2 6 3 1 4 5 0 "); @@ -423,7 +423,7 @@ TEST(MapTreeTest, TraverseMutate) { { // mutate node values (string_views) MapTreeTestType m_copy(m); // deep copy, mutate this copy std::ostringstream stream; - m_copy.ApplyPreOrder([&stream](MapTreeTestType::node_value_type& v) { + m_copy.ApplyPreOrder([&stream](MapTreeTestType::node_value_type &v) { v = v.substr(1); // mutate: truncate stream << v << " "; // print to verify order }); @@ -432,7 +432,7 @@ TEST(MapTreeTest, TraverseMutate) { { // mutate nodes MapTreeTestType m_copy(m); // deep copy, mutate this copy std::ostringstream stream; - m_copy.ApplyPreOrder([&stream](MapTreeTestType& v) { + m_copy.ApplyPreOrder([&stream](MapTreeTestType &v) { v.Value() = v.Value().substr(1); // mutate: truncate stream << v.Value() << " "; // print to verify order }); @@ -443,7 +443,7 @@ TEST(MapTreeTest, TraverseMutate) { { // mutate node values (string_views) MapTreeTestType m_copy(m); // deep copy, mutate this copy std::ostringstream stream; - m_copy.ApplyPostOrder([&stream](MapTreeTestType::node_value_type& v) { + m_copy.ApplyPostOrder([&stream](MapTreeTestType::node_value_type &v) { v = v.substr(1); // mutate: truncate stream << v << " "; // print to verify order }); @@ -452,7 +452,7 @@ TEST(MapTreeTest, TraverseMutate) { { // mutate nodes MapTreeTestType m_copy(m); // deep copy, mutate this copy std::ostringstream stream; - m_copy.ApplyPostOrder([&stream](MapTreeTestType& v) { + m_copy.ApplyPostOrder([&stream](MapTreeTestType &v) { v.Value() = v.Value().substr(1); // mutate: truncate stream << v.Value() << " "; // print to verify order }); @@ -508,8 +508,8 @@ TEST(MapTreeTest, PrintTreeTwoGenerationsUsingIndent) { KV{6, MapTreeTestType("vv")})}); std::ostringstream stream; m.PrintTree(stream, - [](std::ostream& s, const std::string& text, - size_t indent) -> std::ostream& { + [](std::ostream &s, const std::string &text, + size_t indent) -> std::ostream & { const Spacer wrap(indent + 4); for (const auto c : text) { s << '\n' << wrap << c; diff --git a/common/util/range.h b/common/util/range.h index 0e288b657..2f60d60da 100644 --- a/common/util/range.h +++ b/common/util/range.h @@ -31,7 +31,7 @@ namespace verible { // The iterator categories need to be RandomAccessIterator for less-comparison. // This can be used to check string_view ranges and their invariants. template -bool IsSubRange(const SubRange& sub, const SuperRange& super) { +bool IsSubRange(const SubRange &sub, const SuperRange &super) { return sub.begin() >= super.begin() && sub.end() <= super.end(); } @@ -45,7 +45,7 @@ bool IsSubRange(const SubRange& sub, const SuperRange& super) { // std::equal_range (and other STL uses of that name). // Could have also been named IntervalEqual. template -bool BoundsEqual(const LRange& l, const RRange& r) { +bool BoundsEqual(const LRange &l, const RRange &r) { return l.begin() == r.begin() && l.end() == r.end(); } @@ -80,8 +80,8 @@ bool BoundsEqual(const LRange& l, const RRange& r) { // EXPECT_EQ(indices(range1), indices(range2)); // template -std::pair SubRangeIndices(const SubRange& subrange, - const SuperRange& superrange) { +std::pair SubRangeIndices(const SubRange &subrange, + const SuperRange &superrange) { const int max = std::distance(superrange.begin(), superrange.end()); const int begin = std::distance(superrange.begin(), subrange.begin()); const int end = std::distance(superrange.begin(), subrange.end()); diff --git a/common/util/range_test.cc b/common/util/range_test.cc index c9bcbb718..fc8e32221 100644 --- a/common/util/range_test.cc +++ b/common/util/range_test.cc @@ -221,7 +221,7 @@ TEST(SubRangeIndicesTest, EqComparable) { const std::vector v; const auto supersequence = make_range(v.begin(), v.end()); const auto subsequence = supersequence; - auto indices = [&v](const decltype(supersequence)& range) { + auto indices = [&v](const decltype(supersequence) &range) { return SubRangeIndices(range, v); // v is the common base for both ranges }; EXPECT_EQ(indices(subsequence), indices(supersequence)); diff --git a/common/util/spacer.cc b/common/util/spacer.cc index cf584be36..156a1a022 100644 --- a/common/util/spacer.cc +++ b/common/util/spacer.cc @@ -19,7 +19,7 @@ namespace verible { -std::ostream& operator<<(std::ostream& stream, const Spacer& spacer) { +std::ostream &operator<<(std::ostream &stream, const Spacer &spacer) { for (size_t i = 0; i < spacer.repeat; ++i) { stream << spacer.repeated_char; } diff --git a/common/util/spacer.h b/common/util/spacer.h index f90066691..799246043 100644 --- a/common/util/spacer.h +++ b/common/util/spacer.h @@ -28,7 +28,7 @@ struct Spacer { char repeated_char; }; -std::ostream& operator<<(std::ostream&, const Spacer&); +std::ostream &operator<<(std::ostream &, const Spacer &); } // namespace verible diff --git a/common/util/subcommand.cc b/common/util/subcommand.cc index 9a7652c31..00b833762 100644 --- a/common/util/subcommand.cc +++ b/common/util/subcommand.cc @@ -27,17 +27,17 @@ SubcommandRegistry::SubcommandRegistry() // Every registry comes initialized with its own generic 'help' // command. {"help", - {[this](const SubcommandArgsRange& args, std::istream& ins, - std::ostream& outs, - std::ostream& errs) { return Help(args, ins, outs, errs); }, + {[this](const SubcommandArgsRange &args, std::istream &ins, + std::ostream &outs, + std::ostream &errs) { return Help(args, ins, outs, errs); }, "help [command]\n" "Prints command help. " "With no command or unknown command, this lists available " "commands.\n"}}, {"error", - {[this](const SubcommandArgsRange& args, std::istream& ins, - std::ostream& outs, std::ostream& errs) { + {[this](const SubcommandArgsRange &args, std::istream &ins, + std::ostream &outs, std::ostream &errs) { // Call with empty arguments to just get the command listing. const auto unused_status = Help({}, ins, outs, errs); return absl::InvalidArgumentError("Unknown subcommand."); @@ -47,9 +47,9 @@ SubcommandRegistry::SubcommandRegistry() command_listing_.emplace_back("help"); } -const SubcommandEntry& SubcommandRegistry::GetSubcommandEntry( +const SubcommandEntry &SubcommandRegistry::GetSubcommandEntry( absl::string_view command) const { - const SubcommandMap& commands(subcommand_map_); + const SubcommandMap &commands(subcommand_map_); const auto iter = commands.find(command); if (iter == commands.end()) { // Command not found, print help and exit non-zero. @@ -59,7 +59,7 @@ const SubcommandEntry& SubcommandRegistry::GetSubcommandEntry( } absl::Status SubcommandRegistry::RegisterCommand( - absl::string_view name, const SubcommandEntry& command) { + absl::string_view name, const SubcommandEntry &command) { const auto p = subcommand_map_.emplace(name, command); if (!p.second) { return absl::InvalidArgumentError(absl::StrCat( @@ -71,15 +71,15 @@ absl::Status SubcommandRegistry::RegisterCommand( return absl::OkStatus(); } -absl::Status SubcommandRegistry::Help(const SubcommandArgsRange& args, - std::istream&, std::ostream&, - std::ostream& errs) const { +absl::Status SubcommandRegistry::Help(const SubcommandArgsRange &args, + std::istream &, std::ostream &, + std::ostream &errs) const { if (args.empty()) { errs << "available commands:\n" << ListCommands() << std::endl; return absl::OkStatus(); } - const SubcommandEntry& entry = GetSubcommandEntry(args.front()); + const SubcommandEntry &entry = GetSubcommandEntry(args.front()); errs << entry.usage << std::endl; return absl::OkStatus(); } diff --git a/common/util/subcommand.h b/common/util/subcommand.h index 4c947042e..de7fc413b 100644 --- a/common/util/subcommand.h +++ b/common/util/subcommand.h @@ -38,8 +38,8 @@ using SubcommandArgsRange = // Currently this function type is hard-coded, but this could eventually // become a template parameter. using SubcommandFunction = - std::function; + std::function; // Represents a function selected by the user. struct SubcommandEntry { @@ -65,26 +65,26 @@ class SubcommandRegistry { SubcommandRegistry(); // Not intended for copy/move-ing. - SubcommandRegistry(const SubcommandRegistry&) = delete; - SubcommandRegistry(SubcommandRegistry&&) = delete; - SubcommandRegistry& operator=(const SubcommandRegistry&) = delete; - SubcommandRegistry& operator=(SubcommandRegistry&&) = delete; + SubcommandRegistry(const SubcommandRegistry &) = delete; + SubcommandRegistry(SubcommandRegistry &&) = delete; + SubcommandRegistry &operator=(const SubcommandRegistry &) = delete; + SubcommandRegistry &operator=(SubcommandRegistry &&) = delete; // Add a function to this map. // Returned status is an error if a function already exists with the given // name. - absl::Status RegisterCommand(absl::string_view name, const SubcommandEntry&); + absl::Status RegisterCommand(absl::string_view name, const SubcommandEntry &); // Lookup a function in this map by name. - const SubcommandEntry& GetSubcommandEntry(absl::string_view command) const; + const SubcommandEntry &GetSubcommandEntry(absl::string_view command) const; // Print a help summary of all registered commands. std::string ListCommands() const; protected: // Every command map comes with a built-in 'help' command. - absl::Status Help(const SubcommandArgsRange& args, std::istream&, - std::ostream&, std::ostream& errs) const; + absl::Status Help(const SubcommandArgsRange &args, std::istream &, + std::ostream &, std::ostream &errs) const; private: using SubcommandMap = diff --git a/common/util/subcommand_test.cc b/common/util/subcommand_test.cc index fffedd348..7ff611fd4 100644 --- a/common/util/subcommand_test.cc +++ b/common/util/subcommand_test.cc @@ -37,7 +37,7 @@ TEST(SubcommandRegistryTest, NoNewCommands) { TEST(SubcommandRegistryTest, HelpNoArgsTest) { SubcommandRegistry registry; // Test built-in help command. - const SubcommandEntry& help(registry.GetSubcommandEntry("help")); + const SubcommandEntry &help(registry.GetSubcommandEntry("help")); std::istringstream ins; std::ostringstream outs, errs; std::vector args; @@ -51,7 +51,7 @@ TEST(SubcommandRegistryTest, HelpNoArgsTest) { TEST(SubcommandRegistryTest, HelpHelpCommand) { SubcommandRegistry registry; // Test built-in help command. - const SubcommandEntry& help(registry.GetSubcommandEntry("help")); + const SubcommandEntry &help(registry.GetSubcommandEntry("help")); std::istringstream ins; std::ostringstream outs, errs; std::vector args{"help"}; @@ -64,8 +64,8 @@ TEST(SubcommandRegistryTest, HelpHelpCommand) { } static const SubcommandEntry fizz_func{ - [](const SubcommandArgsRange, std::istream&, std::ostream& outs, - std::ostream&) { + [](const SubcommandArgsRange, std::istream &, std::ostream &outs, + std::ostream &) { outs << 42; return absl::OkStatus(); }, @@ -83,7 +83,7 @@ TEST(SubcommandRegistryTest, RegisterCommandPublicOk) { std::vector args; const SubcommandArgsRange range(args.begin(), args.end()); - const SubcommandEntry& fizz_entry(registry.GetSubcommandEntry("fizz")); + const SubcommandEntry &fizz_entry(registry.GetSubcommandEntry("fizz")); std::istringstream ins; std::ostringstream outs, errs; @@ -99,7 +99,7 @@ TEST(SubcommandRegistryTest, ShowRegisteredCommandsOnWrongCommandRequest) { EXPECT_TRUE(absl::StrContains(registry.ListCommands(), "fizz")); } - const SubcommandEntry& cmd(registry.GetSubcommandEntry("wrong_command")); + const SubcommandEntry &cmd(registry.GetSubcommandEntry("wrong_command")); std::vector args{"foo", "bar"}; const SubcommandArgsRange range(args.begin(), args.end()); @@ -112,8 +112,8 @@ TEST(SubcommandRegistryTest, ShowRegisteredCommandsOnWrongCommandRequest) { } static const SubcommandEntry buzz_func{ - [](const SubcommandArgsRange, std::istream&, std::ostream& outs, - std::ostream&) { + [](const SubcommandArgsRange, std::istream &, std::ostream &outs, + std::ostream &) { outs << 99; return absl::OkStatus(); }, @@ -131,7 +131,7 @@ TEST(SubcommandRegistryTest, RegisterCommandHiddenOk) { std::vector args; const SubcommandArgsRange range(args.begin(), args.end()); - const SubcommandEntry& buzz_entry(registry.GetSubcommandEntry("buzz")); + const SubcommandEntry &buzz_entry(registry.GetSubcommandEntry("buzz")); std::istringstream ins; std::ostringstream outs, errs; @@ -169,7 +169,7 @@ TEST(SubcommandRegistryTest, RegisterCommandMultipleCommands) { std::vector args; const SubcommandArgsRange range(args.begin(), args.end()); { - const SubcommandEntry& fizz_entry(registry.GetSubcommandEntry("fizz")); + const SubcommandEntry &fizz_entry(registry.GetSubcommandEntry("fizz")); std::istringstream ins; std::ostringstream outs, errs; const auto status = fizz_entry.main(range, ins, outs, errs); @@ -177,7 +177,7 @@ TEST(SubcommandRegistryTest, RegisterCommandMultipleCommands) { EXPECT_EQ(outs.str(), "42"); } { - const SubcommandEntry& buzz_entry(registry.GetSubcommandEntry("buzz")); + const SubcommandEntry &buzz_entry(registry.GetSubcommandEntry("buzz")); std::istringstream ins; std::ostringstream outs, errs; const auto status = buzz_entry.main(range, ins, outs, errs); diff --git a/common/util/top_n.h b/common/util/top_n.h index 4556f31b0..5efcb617b 100644 --- a/common/util/top_n.h +++ b/common/util/top_n.h @@ -47,7 +47,7 @@ class TopN { // Inserts an element in the prescribed sorted order, and caps the size (K). // Has same run-time as heap-insertion, no worse than O(lg K) ~ O(1). // Removing the worst element is a heap-remove-min-key, which is O(1). - void push(const value_type& v) { + void push(const value_type &v) { elements_.push(v); if (size() > max_size()) { elements_.pop(); // remove worst element diff --git a/common/util/tree_operations.cc b/common/util/tree_operations.cc index a41aa4310..ac59a1bb5 100644 --- a/common/util/tree_operations.cc +++ b/common/util/tree_operations.cc @@ -22,7 +22,7 @@ namespace verible { -std::ostream& operator<<(std::ostream& stream, const NodePath& p) { +std::ostream &operator<<(std::ostream &stream, const NodePath &p) { return stream << absl::StrCat( "{", absl::StrJoin(p.path.begin(), p.path.end(), ","), "}"); } diff --git a/common/util/user_interaction.cc b/common/util/user_interaction.cc index 126adcbac..a65ac903c 100644 --- a/common/util/user_interaction.cc +++ b/common/util/user_interaction.cc @@ -30,7 +30,7 @@ namespace verible { -bool IsInteractiveTerminalSession(const std::ostream& s) { +bool IsInteractiveTerminalSession(const std::ostream &s) { // Unix: STDIN_FILENO; windows: _fileno( stdin ). So just name the // file descriptors by number. static bool kStdinIsTerminal = isatty(0); @@ -40,7 +40,7 @@ bool IsInteractiveTerminalSession(const std::ostream& s) { kStdoutIsTerminal); } -char ReadCharFromUser(std::istream& input, std::ostream& output, +char ReadCharFromUser(std::istream &input, std::ostream &output, bool input_is_terminal, absl::string_view prompt) { if (input_is_terminal) { // Terminal input: print prompt, read whole line and return first character. @@ -79,7 +79,7 @@ static constexpr absl::string_view kColorsStart[static_cast(Color::kNu }; // clang-format on -std::ostream& bold(std::ostream& out, absl::string_view s) { +std::ostream &bold(std::ostream &out, absl::string_view s) { if (IsInteractiveTerminalSession(out)) { out << kBoldEscape << s << kNormalEscape; } else { @@ -87,7 +87,7 @@ std::ostream& bold(std::ostream& out, absl::string_view s) { } return out; } -std::ostream& inverse(std::ostream& out, absl::string_view s) { +std::ostream &inverse(std::ostream &out, absl::string_view s) { if (IsInteractiveTerminalSession(out)) { out << kInverseEscape << s << kNormalEscape; } else { @@ -95,7 +95,7 @@ std::ostream& inverse(std::ostream& out, absl::string_view s) { } return out; } -std::ostream& Colored(std::ostream& out, absl::string_view s, Color c) { +std::ostream &Colored(std::ostream &out, absl::string_view s, Color c) { if (IsInteractiveTerminalSession(out) && c != Color::kNone) { out << kColorsStart[static_cast(c)] << s << kNormalEscape; } else { diff --git a/common/util/user_interaction.h b/common/util/user_interaction.h index d5140e10a..5189a453c 100644 --- a/common/util/user_interaction.h +++ b/common/util/user_interaction.h @@ -23,8 +23,8 @@ namespace verible { namespace term { // Convenience functions: Print bold or inverse if and only if this // is an interactive session connected to a terminal. Otherwise just plain. -std::ostream& bold(std::ostream& out, absl::string_view s); -std::ostream& inverse(std::ostream& out, absl::string_view s); +std::ostream &bold(std::ostream &out, absl::string_view s); +std::ostream &inverse(std::ostream &out, absl::string_view s); enum class Color { kGreen = 0, @@ -36,13 +36,13 @@ enum class Color { // Print the `s` string to `out` ostream colored with color `c`. // This will only apply if we're in an interactive terminal session -std::ostream& Colored(std::ostream& out, absl::string_view s, Color c); +std::ostream &Colored(std::ostream &out, absl::string_view s, Color c); } // namespace term // Returns if the stream is likely a terminal session: stream is connected to // terminal and stdin is a terminal. -bool IsInteractiveTerminalSession(const std::ostream& s); +bool IsInteractiveTerminalSession(const std::ostream &s); // Reads single character from user. // @@ -61,7 +61,7 @@ bool IsInteractiveTerminalSession(const std::ostream& s); // const char ch = ReadCharFromUser(std::cin, std::cout, // IsInteractiveTerminalSession(std::cout), // "Type a letter and confirm with ENTER: "); -char ReadCharFromUser(std::istream& input, std::ostream& output, +char ReadCharFromUser(std::istream &input, std::ostream &output, bool input_is_terminal, absl::string_view prompt); } // namespace verible diff --git a/common/util/user_interaction_test.cc b/common/util/user_interaction_test.cc index 569b55ef5..a33d09314 100644 --- a/common/util/user_interaction_test.cc +++ b/common/util/user_interaction_test.cc @@ -28,7 +28,7 @@ TEST(ReadCharFromUserTest, NonTerminalInput) { std::ostringstream output; char characters[6]; - for (char& c : characters) { + for (char &c : characters) { c = ReadCharFromUser(input, output, false, "A prompt."); } @@ -46,7 +46,7 @@ TEST(ReadCharFromUserTest, TerminalInput) { std::ostringstream output; char characters[4]; - for (char& c : characters) { + for (char &c : characters) { output.str(""); output.clear(); c = ReadCharFromUser(input, output, true, "A prompt."); diff --git a/common/util/vector_tree_iterators.h b/common/util/vector_tree_iterators.h index 8733c86fa..d80baa4d9 100644 --- a/common/util/vector_tree_iterators.h +++ b/common/util/vector_tree_iterators.h @@ -39,8 +39,8 @@ class VectorTreeIteratorBase { using iterator_category = std::forward_iterator_tag; using difference_type = std::ptrdiff_t; using value_type = VectorTreeType; - using pointer = VectorTreeType*; - using reference = VectorTreeType&; + using pointer = VectorTreeType *; + using reference = VectorTreeType &; VectorTreeIteratorBase() : node_(nullptr) {} explicit VectorTreeIteratorBase(pointer node) : node_(node) {} @@ -53,12 +53,12 @@ class VectorTreeIteratorBase { CHECK_NOTNULL(node_); return node_; } - ImplType& operator++() { + ImplType &operator++() { node_ = ImplType::GetNextNode(node_); - return static_cast(*this); + return static_cast(*this); } ImplType operator++(int) { - ImplType tmp = static_cast(*this); + ImplType tmp = static_cast(*this); node_ = ImplType::GetNextNode(node_); return tmp; } @@ -66,10 +66,10 @@ class VectorTreeIteratorBase { while (rhs--) ++lhs; return lhs; } - friend bool operator==(const ImplType& a, const ImplType& b) { + friend bool operator==(const ImplType &a, const ImplType &b) { return a.node_ == b.node_; }; - friend bool operator!=(const ImplType& a, const ImplType& b) { + friend bool operator!=(const ImplType &a, const ImplType &b) { return a.node_ != b.node_; }; @@ -88,17 +88,17 @@ class VectorTreeLeavesIterator public: VectorTreeLeavesIterator() : base_type() {} - explicit VectorTreeLeavesIterator(VectorTreeType* node) + explicit VectorTreeLeavesIterator(VectorTreeType *node) : base_type(node ? &LeftmostDescendant(*node) : nullptr) {} - static VectorTreeType* GetNextNode(VectorTreeType* node) { + static VectorTreeType *GetNextNode(VectorTreeType *node) { if (!node) return nullptr; return NextLeaf(*node); } }; template -VectorTreeLeavesIterator(VectorTreeType*) +VectorTreeLeavesIterator(VectorTreeType *) -> VectorTreeLeavesIterator; // Returns VectorTreeLeavesIterator range that spans all leaves of a tree. @@ -106,7 +106,7 @@ VectorTreeLeavesIterator(VectorTreeType*) // this node. template iterator_range> -VectorTreeLeavesTraversal(VectorTreeType& tree) { +VectorTreeLeavesTraversal(VectorTreeType &tree) { VectorTreeLeavesIterator begin(&LeftmostDescendant(tree)); VectorTreeLeavesIterator end(&RightmostDescendant(tree)); ++end; @@ -122,9 +122,9 @@ class VectorTreePreOrderIterator public: VectorTreePreOrderIterator() : base_type() {} - explicit VectorTreePreOrderIterator(VectorTreeType* node) : base_type(node) {} + explicit VectorTreePreOrderIterator(VectorTreeType *node) : base_type(node) {} - static VectorTreeType* GetNextNode(VectorTreeType* node) { + static VectorTreeType *GetNextNode(VectorTreeType *node) { if (!node) return nullptr; if (!node->Children().empty()) return &node->Children().front(); while (node && verible::IsLastChild(*node)) { @@ -142,14 +142,14 @@ class VectorTreePreOrderIterator }; template -VectorTreePreOrderIterator(VectorTreeType*) +VectorTreePreOrderIterator(VectorTreeType *) -> VectorTreePreOrderIterator; // Returns VectorTreePreOrderIterator range that spans all nodes of a tree // (including the tree's root). template iterator_range> -VectorTreePreOrderTraversal(VectorTreeType& tree) { +VectorTreePreOrderTraversal(VectorTreeType &tree) { VectorTreePreOrderIterator it(&tree); return {it.begin(), it.end()}; } @@ -163,10 +163,10 @@ class VectorTreePostOrderIterator public: VectorTreePostOrderIterator() : base_type() {} - explicit VectorTreePostOrderIterator(VectorTreeType* node) + explicit VectorTreePostOrderIterator(VectorTreeType *node) : base_type(node) {} - static VectorTreeType* GetNextNode(VectorTreeType* node) { + static VectorTreeType *GetNextNode(VectorTreeType *node) { if (!node) return nullptr; if (verible::IsLastChild(*node)) return node->Parent(); node = NextSibling(*node); @@ -182,14 +182,14 @@ class VectorTreePostOrderIterator }; template -VectorTreePostOrderIterator(VectorTreeType*) +VectorTreePostOrderIterator(VectorTreeType *) -> VectorTreePostOrderIterator; // Returns VectorTreePostOrderIterator range that spans all nodes of a tree // (including the tree's root). template iterator_range> -VectorTreePostOrderTraversal(VectorTreeType& tree) { +VectorTreePostOrderTraversal(VectorTreeType &tree) { VectorTreePostOrderIterator it(&tree); return {it.begin(), it.end()}; } diff --git a/common/util/vector_tree_iterators_test.cc b/common/util/vector_tree_iterators_test.cc index dd316357d..a92dd8f7e 100644 --- a/common/util/vector_tree_iterators_test.cc +++ b/common/util/vector_tree_iterators_test.cc @@ -31,20 +31,20 @@ namespace verible { // Iterator value printers used by Google Test template -static void PrintTo(const VectorTreeLeavesIterator& it, - std::ostream* os) { +static void PrintTo(const VectorTreeLeavesIterator &it, + std::ostream *os) { *os << "VectorTreeLeavesIterator(" << *it << ")"; } template -static void PrintTo(const VectorTreePreOrderIterator& it, - std::ostream* os) { +static void PrintTo(const VectorTreePreOrderIterator &it, + std::ostream *os) { *os << "VectorTreePreOrderIterator(" << *it << ")"; } template -static void PrintTo(const VectorTreePostOrderIterator& it, - std::ostream* os) { +static void PrintTo(const VectorTreePostOrderIterator &it, + std::ostream *os) { *os << "VectorTreePostOrderIterator(" << *it << ")"; } @@ -53,7 +53,7 @@ namespace { using Tree = verible::VectorTree; template -void ExpectForwardIterator(TreeType* node, TreeType* next_node) { +void ExpectForwardIterator(TreeType *node, TreeType *next_node) { EXPECT_TRUE(std::is_default_constructible_v); EXPECT_TRUE(std::is_copy_constructible_v); EXPECT_TRUE(std::is_copy_assignable_v); @@ -263,11 +263,11 @@ static const TestCaseData kTestCasesData[] = { }; template -void ExpectNodesRangesValuesEq(const NodesRange& nodes, - const ValuesRange& expected_values) { +void ExpectNodesRangesValuesEq(const NodesRange &nodes, + const ValuesRange &expected_values) { auto expected_it = expected_values.begin(); - for (const auto& node : nodes) { + for (const auto &node : nodes) { EXPECT_NE(expected_it, expected_values.end()); EXPECT_EQ(node.Value(), *expected_it); ++expected_it; @@ -276,7 +276,7 @@ void ExpectNodesRangesValuesEq(const NodesRange& nodes, } TEST(VectorTreeIteratorTest, RootNodeTraversal) { - for (const auto& data : kTestCasesData) { + for (const auto &data : kTestCasesData) { std::ostringstream trace_msg; trace_msg << "Input tree:\n" << data.tree; SCOPED_TRACE(trace_msg.str()); @@ -303,11 +303,11 @@ TEST(VectorTreeIteratorTest, RootNodeTraversal) { } TEST(VectorTreeIteratorTest, SubtreeTraversal) { - for (const auto& data : kTestCasesData) { + for (const auto &data : kTestCasesData) { const auto subtree_path = data.subtree_traversal.subtree_path; if (subtree_path.empty()) continue; - const auto& subtree = + const auto &subtree = DescendPath(data.tree, subtree_path.begin(), subtree_path.end()); std::ostringstream trace_msg; @@ -338,11 +338,11 @@ TEST(VectorTreeIteratorTest, SubtreeTraversal) { } TEST(VectorTreeIteratorTest, IteratorSubtreeTraversal) { - for (const auto& data : kTestCasesData) { + for (const auto &data : kTestCasesData) { const auto subtree_path = data.subtree_traversal.subtree_path; if (subtree_path.empty()) continue; - const auto& subtree = + const auto &subtree = DescendPath(data.tree, subtree_path.begin(), subtree_path.end()); std::ostringstream trace_msg; diff --git a/common/util/vector_tree_test.cc b/common/util/vector_tree_test.cc index 47ba84d11..db64002fe 100644 --- a/common/util/vector_tree_test.cc +++ b/common/util/vector_tree_test.cc @@ -38,7 +38,7 @@ using verible::testing::NamedInterval; using verible::testing::VectorTreeTestType; template -void ExpectPath(const Tree& tree, absl::string_view expect) { +void ExpectPath(const Tree &tree, absl::string_view expect) { std::ostringstream stream; stream << NodePath(tree); EXPECT_EQ(stream.str(), expect); @@ -55,7 +55,7 @@ TEST(VectorTreeTest, RootOnly) { EXPECT_TRUE(IsLastChild(tree)); EXPECT_EQ(&Root(tree), &tree); - const auto& value = tree.Value(); + const auto &value = tree.Value(); EXPECT_EQ(value.left, 0); EXPECT_EQ(value.right, 2); EXPECT_EQ(value.name, "root"); @@ -68,7 +68,7 @@ TEST(VectorTreeTest, RootOnlyDescendants) { EXPECT_EQ(&LeftmostDescendant(tree), &tree); EXPECT_EQ(&RightmostDescendant(tree), &tree); { // Test const method variants. - const auto& ctree(tree); + const auto &ctree(tree); EXPECT_EQ(&LeftmostDescendant(ctree), &ctree); EXPECT_EQ(&RightmostDescendant(ctree), &ctree); } @@ -90,7 +90,7 @@ TEST(VectorTreeTest, RootOnlyLeafIteration) { EXPECT_EQ(NextLeaf(tree), nullptr); EXPECT_EQ(PreviousLeaf(tree), nullptr); { // const method variants - const auto& ctree(tree); + const auto &ctree(tree); EXPECT_EQ(NextLeaf(ctree), nullptr); EXPECT_EQ(PreviousLeaf(ctree), nullptr); } @@ -101,7 +101,7 @@ TEST(VectorTreeTest, RootOnlySiblingIteration) { EXPECT_EQ(verible::NextSibling(tree), nullptr); EXPECT_EQ(verible::PreviousSibling(tree), nullptr); { // const method variants - const auto& ctree(tree); + const auto &ctree(tree); EXPECT_EQ(verible::NextSibling(ctree), nullptr); EXPECT_EQ(verible::PreviousSibling(ctree), nullptr); } @@ -345,19 +345,19 @@ TEST(VectorTreeTest, DeepEqualRootToRootValueDifferent) { struct NameOnly { absl::string_view name; - explicit NameOnly(const NamedInterval& v) : name(v.name) {} + explicit NameOnly(const NamedInterval &v) : name(v.name) {} }; -std::ostream& operator<<(std::ostream& stream, const NameOnly& n) { +std::ostream &operator<<(std::ostream &stream, const NameOnly &n) { return stream << '(' << n.name << ")\n"; } -static NameOnly NameOnlyConverter(const VectorTreeTestType& node) { +static NameOnly NameOnlyConverter(const VectorTreeTestType &node) { return NameOnly(node.Value()); } // Heterogeneous comparison. -bool operator==(const NamedInterval& left, const NameOnly& right) { +bool operator==(const NamedInterval &left, const NameOnly &right) { return left.name == right.name; } @@ -370,7 +370,7 @@ TEST(VectorTreeTest, RootOnlyTreeTransformConstruction) { EXPECT_EQ(NumAncestors(other_tree), 0); EXPECT_EQ(BirthRank(other_tree), 0); // no parent - const auto& value = other_tree.Value(); + const auto &value = other_tree.Value(); EXPECT_EQ(value.name, "root"); } @@ -417,12 +417,12 @@ TEST(VectorTreeTest, NewChild) { VectorTreeTestType tree(verible::testing::MakeRootOnlyExampleTree()); { tree.Children().emplace_back(NamedInterval(1, 2, "child")); - auto* child = &tree.Children().back(); + auto *child = &tree.Children().back(); EXPECT_EQ(child->Parent(), &tree); EXPECT_EQ(&Root(*child), &tree); EXPECT_TRUE(verible::is_leaf(*child)); - const auto& value(child->Value()); + const auto &value(child->Value()); EXPECT_EQ(value.left, 1); EXPECT_EQ(value.right, 2); EXPECT_EQ(value.name, "child"); @@ -431,12 +431,12 @@ TEST(VectorTreeTest, NewChild) { } { tree.Children().emplace_back(NamedInterval(2, 3, "lil-bro")); - auto* child = &tree.Children().back(); + auto *child = &tree.Children().back(); EXPECT_EQ(child->Parent(), &tree); EXPECT_EQ(&Root(*child), &tree); EXPECT_TRUE(verible::is_leaf(*child)); - const auto& value(child->Value()); + const auto &value(child->Value()); EXPECT_EQ(value.left, 2); EXPECT_EQ(value.right, 3); EXPECT_EQ(value.name, "lil-bro"); @@ -450,18 +450,18 @@ TEST(VectorTreeTest, NewSibling) { VectorTreeTestType tree(verible::testing::MakeRootOnlyExampleTree()); { tree.Children().emplace_back(NamedInterval(1, 2, "child")); - auto* first_child = &tree.Children().back(); + auto *first_child = &tree.Children().back(); ExpectPath(*first_child, "{0}"); - auto& siblings = first_child->Parent()->Children(); + auto &siblings = first_child->Parent()->Children(); siblings.emplace_back(NamedInterval(2, 3, "lil-bro")); - auto* second_child = &siblings.back(); + auto *second_child = &siblings.back(); // Recall that emplace_back() may invalidate reference to first_child. EXPECT_EQ(second_child->Parent(), &tree); EXPECT_EQ(&Root(*second_child), &tree); EXPECT_TRUE(verible::is_leaf(*second_child)); - const auto& value(second_child->Value()); + const auto &value(second_child->Value()); EXPECT_EQ(value.left, 2); EXPECT_EQ(value.right, 3); EXPECT_EQ(value.name, "lil-bro"); @@ -475,13 +475,13 @@ TEST(VectorTreeTest, OneChildPolicy) { EXPECT_EQ(tree.Parent(), nullptr); EXPECT_FALSE(is_leaf(tree)); - const auto& value = tree.Value(); + const auto &value = tree.Value(); EXPECT_EQ(value.left, 0); EXPECT_EQ(value.right, 3); EXPECT_EQ(value.name, "root"); { - const auto& child = tree.Children().front(); + const auto &child = tree.Children().front(); EXPECT_EQ(child.Parent(), &tree); EXPECT_EQ(&Root(child), &tree); EXPECT_FALSE(is_leaf(child)); @@ -490,7 +490,7 @@ TEST(VectorTreeTest, OneChildPolicy) { EXPECT_TRUE(IsFirstChild(child)); EXPECT_TRUE(IsLastChild(child)); - const auto& cvalue = child.Value(); + const auto &cvalue = child.Value(); EXPECT_EQ(cvalue.left, 0); EXPECT_EQ(cvalue.right, 3); EXPECT_EQ(cvalue.name, "gen1"); @@ -504,7 +504,7 @@ TEST(VectorTreeTest, OneChildPolicy) { EXPECT_EQ(PreviousLeaf(child), nullptr); { - const auto& grandchild = child.Children().front(); + const auto &grandchild = child.Children().front(); EXPECT_EQ(grandchild.Parent(), &child); EXPECT_EQ(&Root(grandchild), &tree); EXPECT_TRUE(is_leaf(grandchild)); @@ -513,7 +513,7 @@ TEST(VectorTreeTest, OneChildPolicy) { EXPECT_TRUE(IsFirstChild(grandchild)); EXPECT_TRUE(IsLastChild(grandchild)); - const auto& gcvalue = grandchild.Value(); + const auto &gcvalue = grandchild.Value(); EXPECT_EQ(gcvalue.left, 0); EXPECT_EQ(gcvalue.right, 3); EXPECT_EQ(gcvalue.name, "gen2"); @@ -540,13 +540,13 @@ TEST(VectorTreeTest, OneChildPolicyHasAncestor) { const auto tree = verible::testing::MakeOneChildPolicyExampleTree(); { - const auto& child = tree.Children().front(); + const auto &child = tree.Children().front(); EXPECT_FALSE(HasAncestor(tree, &child)); EXPECT_TRUE(HasAncestor(child, &tree)); { - const auto& grandchild = child.Children().front(); + const auto &grandchild = child.Children().front(); EXPECT_FALSE(HasAncestor(child, &grandchild)); EXPECT_TRUE(HasAncestor(grandchild, &child)); @@ -590,8 +590,8 @@ TEST(VectorTreeTest, DeepEqualOneChild) { TEST(VectorTreeTest, DeepEqualOneChildDifferentChildValues) { VectorTreeTestType ltree(verible::testing::MakeOneChildPolicyExampleTree()); VectorTreeTestType rtree(verible::testing::MakeOneChildPolicyExampleTree()); - auto& lchild = ltree.Children()[0]; - auto& rchild = rtree.Children()[0]; + auto &lchild = ltree.Children()[0]; + auto &rchild = rtree.Children()[0]; lchild.Value().right = 32; rchild.Value().right = 77; const auto result_pair = DeepEqual(ltree, rtree); @@ -602,8 +602,8 @@ TEST(VectorTreeTest, DeepEqualOneChildDifferentChildValues) { TEST(VectorTreeTest, DeepEqualOneChildDifferentGrandchildValues) { VectorTreeTestType ltree(verible::testing::MakeOneChildPolicyExampleTree()); VectorTreeTestType rtree(verible::testing::MakeOneChildPolicyExampleTree()); - auto& lchild = ltree.Children()[0].Children()[0]; // only grandchild - auto& rchild = rtree.Children()[0].Children()[0]; // only grandchild + auto &lchild = ltree.Children()[0].Children()[0]; // only grandchild + auto &rchild = rtree.Children()[0].Children()[0]; // only grandchild lchild.Value().right = 32; rchild.Value().right = 77; const auto result_pair = DeepEqual(ltree, rtree); @@ -621,8 +621,8 @@ TEST(VectorTreeTest, DeepEqualOneChildGrandchildValuesHeterogeneous) { } { // Mismatch const std::vector path({0, 0}); // only grandchild - auto& lchild = DescendPath(ltree, path.begin(), path.end()); - auto& rchild = DescendPath(rtree, path.begin(), path.end()); + auto &lchild = DescendPath(ltree, path.begin(), path.end()); + auto &rchild = DescendPath(rtree, path.begin(), path.end()); lchild.Value().name = "alex"; rchild.Value().name = "james"; const auto result_pair = DeepEqual(ltree, rtree); @@ -632,7 +632,7 @@ TEST(VectorTreeTest, DeepEqualOneChildGrandchildValuesHeterogeneous) { } template -void VerifyFamilyTree(const VectorTree& tree) { +void VerifyFamilyTree(const VectorTree &tree) { EXPECT_EQ(tree.Parent(), nullptr); EXPECT_EQ(&Root(tree), &tree); EXPECT_FALSE(is_leaf(tree)); @@ -644,7 +644,7 @@ void VerifyFamilyTree(const VectorTree& tree) { EXPECT_EQ(&DescendPath(tree, tree_path.begin(), tree_path.end()), &tree); for (int i = 0; i < 2; ++i) { - const auto& child = tree.Children()[i]; + const auto &child = tree.Children()[i]; EXPECT_EQ(child.Parent(), &tree); EXPECT_EQ(&Root(child), &tree); EXPECT_FALSE(is_leaf(child)); @@ -658,7 +658,7 @@ void VerifyFamilyTree(const VectorTree& tree) { EXPECT_EQ(&DescendPath(tree, child_path.begin(), child_path.end()), &child); for (int j = 0; j < 2; ++j) { - const auto& grandchild = child.Children()[j]; + const auto &grandchild = child.Children()[j]; EXPECT_EQ(grandchild.Parent(), &child); EXPECT_EQ(&Root(grandchild), &tree); EXPECT_TRUE(is_leaf(grandchild)); @@ -716,7 +716,7 @@ TEST(VectorTreeTest, FamilyTreeLeftRightmostDescendants) { &DescendPath(tree, right_path.begin(), right_path.end())); } { // Test const method variants. - const auto& ctree(tree); + const auto &ctree(tree); EXPECT_EQ(&LeftmostDescendant(ctree), &DescendPath(ctree, left_path.begin(), left_path.end())); EXPECT_EQ(&RightmostDescendant(ctree), @@ -726,12 +726,12 @@ TEST(VectorTreeTest, FamilyTreeLeftRightmostDescendants) { TEST(VectorTreeTest, FamilyTreeHasAncestor) { const auto tree = verible::testing::MakeExampleFamilyTree(); - const auto& child_0 = tree.Children()[0]; - const auto& child_1 = tree.Children()[1]; - const auto& grandchild_00 = child_0.Children()[0]; - const auto& grandchild_01 = child_0.Children()[1]; - const auto& grandchild_10 = child_1.Children()[0]; - const auto& grandchild_11 = child_1.Children()[1]; + const auto &child_0 = tree.Children()[0]; + const auto &child_1 = tree.Children()[1]; + const auto &grandchild_00 = child_0.Children()[0]; + const auto &grandchild_01 = child_0.Children()[1]; + const auto &grandchild_10 = child_1.Children()[0]; + const auto &grandchild_11 = child_1.Children()[1]; EXPECT_FALSE(HasAncestor(tree, &child_0)); EXPECT_FALSE(HasAncestor(tree, &child_1)); @@ -771,12 +771,12 @@ TEST(VectorTreeTest, FamilyTreeHasAncestor) { TEST(VectorTreeTest, FamilyTreeNextPreviousSiblings) { auto tree = verible::testing::MakeExampleFamilyTree(); - auto& child_0 = tree.Children()[0]; - auto& child_1 = tree.Children()[1]; - auto& grandchild_00 = child_0.Children()[0]; - auto& grandchild_01 = child_0.Children()[1]; - auto& grandchild_10 = child_1.Children()[0]; - auto& grandchild_11 = child_1.Children()[1]; + auto &child_0 = tree.Children()[0]; + auto &child_1 = tree.Children()[1]; + auto &grandchild_00 = child_0.Children()[0]; + auto &grandchild_01 = child_0.Children()[1]; + auto &grandchild_10 = child_1.Children()[0]; + auto &grandchild_11 = child_1.Children()[1]; // Verify child generation. EXPECT_EQ(verible::NextSibling(child_0), &child_1); @@ -795,12 +795,12 @@ TEST(VectorTreeTest, FamilyTreeNextPreviousSiblings) { EXPECT_EQ(verible::PreviousSibling(grandchild_11), &grandchild_10); { // same but testing const method variants. - const auto& cchild_0(child_0); - const auto& cchild_1(child_1); - const auto& cgrandchild_00(grandchild_00); - const auto& cgrandchild_01(grandchild_01); - const auto& cgrandchild_10(grandchild_10); - const auto& cgrandchild_11(grandchild_11); + const auto &cchild_0(child_0); + const auto &cchild_1(child_1); + const auto &cgrandchild_00(grandchild_00); + const auto &cgrandchild_01(grandchild_01); + const auto &cgrandchild_10(grandchild_10); + const auto &cgrandchild_11(grandchild_11); // Verify child generation. EXPECT_EQ(verible::NextSibling(cchild_0), &cchild_1); @@ -822,10 +822,10 @@ TEST(VectorTreeTest, FamilyTreeNextPreviousSiblings) { TEST(VectorTreeTest, FamilyTreeNextPreviousLeafChain) { auto tree = verible::testing::MakeExampleFamilyTree(); - auto& grandchild_00 = tree.Children()[0].Children()[0]; - auto& grandchild_01 = tree.Children()[0].Children()[1]; - auto& grandchild_10 = tree.Children()[1].Children()[0]; - auto& grandchild_11 = tree.Children()[1].Children()[1]; + auto &grandchild_00 = tree.Children()[0].Children()[0]; + auto &grandchild_01 = tree.Children()[0].Children()[1]; + auto &grandchild_10 = tree.Children()[1].Children()[0]; + auto &grandchild_11 = tree.Children()[1].Children()[1]; // Verify forward links. EXPECT_EQ(NextLeaf(grandchild_00), &grandchild_01); @@ -840,10 +840,10 @@ TEST(VectorTreeTest, FamilyTreeNextPreviousLeafChain) { EXPECT_EQ(PreviousLeaf(grandchild_11), &grandchild_10); { // same but testing const method variants. - const auto& cgrandchild_00(grandchild_00); - const auto& cgrandchild_01(grandchild_01); - const auto& cgrandchild_10(grandchild_10); - const auto& cgrandchild_11(grandchild_11); + const auto &cgrandchild_00(grandchild_00); + const auto &cgrandchild_01(grandchild_01); + const auto &cgrandchild_10(grandchild_10); + const auto &cgrandchild_11(grandchild_11); // Verify forward links. EXPECT_EQ(NextLeaf(cgrandchild_00), &cgrandchild_01); @@ -890,8 +890,8 @@ TEST(VectorTreeTest, FamilyTreeMembersTransformed) { auto ltree(orig_tree); // copy auto rtree(tree); // copy const std::vector path({i, j}); - auto& lchild = DescendPath(ltree, path.begin(), path.end()); - auto& rchild = DescendPath(rtree, path.begin(), path.end()); + auto &lchild = DescendPath(ltree, path.begin(), path.end()); + auto &rchild = DescendPath(rtree, path.begin(), path.end()); lchild.Value().name = "foo"; rchild.Value().name = "bar"; @@ -909,8 +909,8 @@ TEST(VectorTreeTest, FamilyTreeMembersDifferentStructureExtraGreatGrand) { auto ltree = verible::testing::MakeExampleFamilyTree(); auto rtree = verible::testing::MakeExampleFamilyTree(); const std::vector path({i, j}); - auto& lchild = DescendPath(ltree, path.begin(), path.end()); - auto& rchild = DescendPath(rtree, path.begin(), path.end()); + auto &lchild = DescendPath(ltree, path.begin(), path.end()); + auto &rchild = DescendPath(rtree, path.begin(), path.end()); rchild.Children().emplace_back(NamedInterval(8, 9, "black-sheep")); const auto result_pair = StructureEqual(ltree, rtree); @@ -927,9 +927,9 @@ TEST(VectorTreeTest, FamilyTreeMembersDifferentStructureExtraGrand) { auto ltree = verible::testing::MakeExampleFamilyTree(); auto rtree = verible::testing::MakeExampleFamilyTree(); const std::vector path({i, j}); - const auto& lparent = DescendPath(ltree, path.begin(), path.end() - 1); - const auto& rparent = DescendPath(rtree, path.begin(), path.end() - 1); - auto& rchild = DescendPath(rtree, path.begin(), path.end()); + const auto &lparent = DescendPath(ltree, path.begin(), path.end() - 1); + const auto &rparent = DescendPath(rtree, path.begin(), path.end() - 1); + auto &rchild = DescendPath(rtree, path.begin(), path.end()); rchild.Parent()->Children().emplace_back( NamedInterval(8, 9, "black-sheep")); @@ -947,8 +947,8 @@ TEST(VectorTreeTest, FamilyTreeMembersDifferentStructureMissingGrand) { auto ltree = verible::testing::MakeExampleFamilyTree(); auto rtree = verible::testing::MakeExampleFamilyTree(); const std::vector path({i}); - auto& lchild = DescendPath(ltree, path.begin(), path.end()); - auto& rchild = DescendPath(rtree, path.begin(), path.end()); + auto &lchild = DescendPath(ltree, path.begin(), path.end()); + auto &rchild = DescendPath(rtree, path.begin(), path.end()); lchild.Children().clear(); const auto result_pair = StructureEqual(ltree, rtree); @@ -957,8 +957,8 @@ TEST(VectorTreeTest, FamilyTreeMembersDifferentStructureMissingGrand) { } } -bool EqualNamedIntervalIgnoreName(const NamedInterval& l, - const NamedInterval& r) { +bool EqualNamedIntervalIgnoreName(const NamedInterval &l, + const NamedInterval &r) { return l.left == r.left && l.right == r.right; // ignore .name } @@ -969,8 +969,8 @@ TEST(VectorTreeTest, FamilyTreeMembersDeepEqualCustomComparator) { auto ltree = verible::testing::MakeExampleFamilyTree(); auto rtree = verible::testing::MakeExampleFamilyTree(); const std::vector path({i, j}); - auto& lchild = DescendPath(ltree, path.begin(), path.end()); - auto& rchild = DescendPath(rtree, path.begin(), path.end()); + auto &lchild = DescendPath(ltree, path.begin(), path.end()); + auto &rchild = DescendPath(rtree, path.begin(), path.end()); lchild.Value().name = "larry"; rchild.Value().name = "sergey"; @@ -1028,13 +1028,13 @@ TEST(VectorTreeTest, NearestCommonAncestorOneIsRootConst) { for (int i = 0; i < 2; ++i) { { const auto path = {i}; - auto& child = DescendPath(tree, path.begin(), path.end()); + auto &child = DescendPath(tree, path.begin(), path.end()); EXPECT_EQ(NearestCommonAncestor(tree, child), &tree); EXPECT_EQ(NearestCommonAncestor(child, tree), &tree); } for (int j = 0; j < 2; ++j) { const auto path = {i, j}; - auto& grandchild = DescendPath(tree, path.begin(), path.end()); + auto &grandchild = DescendPath(tree, path.begin(), path.end()); EXPECT_EQ(NearestCommonAncestor(tree, grandchild), &tree); EXPECT_EQ(NearestCommonAncestor(grandchild, tree), &tree); } @@ -1048,15 +1048,15 @@ TEST(VectorTreeTest, NearestCommonAncestorNeitherIsRootConst) { tree_type(4), tree_type(5)), tree_type(3, // tree_type(6), tree_type(7))); - auto& left = tree.Children()[0]; - auto& right = tree.Children()[1]; + auto &left = tree.Children()[0]; + auto &right = tree.Children()[1]; EXPECT_EQ(NearestCommonAncestor(left, right), &tree); EXPECT_EQ(NearestCommonAncestor(right, left), &tree); for (int i = 0; i < 2; ++i) { { const auto left_path = {0, i}; - auto& left_grandchild = + auto &left_grandchild = DescendPath(tree, left_path.begin(), left_path.end()); EXPECT_EQ(NearestCommonAncestor(left, left_grandchild), &left); EXPECT_EQ(NearestCommonAncestor(left_grandchild, left), &left); @@ -1065,7 +1065,7 @@ TEST(VectorTreeTest, NearestCommonAncestorNeitherIsRootConst) { } { const auto right_path = {1, i}; - auto& right_grandchild = + auto &right_grandchild = DescendPath(tree, right_path.begin(), right_path.end()); EXPECT_EQ(NearestCommonAncestor(right, right_grandchild), &right); EXPECT_EQ(NearestCommonAncestor(right_grandchild, right), &right); @@ -1079,7 +1079,7 @@ TEST(VectorTreeTest, ApplyPreOrderPrint) { const auto tree = verible::testing::MakeExampleFamilyTree(); std::ostringstream stream; - ApplyPreOrder(tree, [&stream](const NamedInterval& interval) { + ApplyPreOrder(tree, [&stream](const NamedInterval &interval) { IntervalPrinter(&stream, interval); }); EXPECT_EQ(stream.str(), absl::StrJoin( @@ -1102,7 +1102,7 @@ TEST(VectorTreeTest, ApplyPreOrderPrintTransformed) { Transform>(orig_tree, NameOnlyConverter); std::ostringstream stream; - ApplyPreOrder(tree, [&stream](const NameOnly& n) { stream << n; }); + ApplyPreOrder(tree, [&stream](const NameOnly &n) { stream << n; }); EXPECT_EQ(stream.str(), absl::StrJoin( { "(grandparent)", @@ -1121,7 +1121,7 @@ TEST(VectorTreeTest, ApplyPostOrderPrint) { const auto tree = verible::testing::MakeExampleFamilyTree(); std::ostringstream stream; - ApplyPostOrder(tree, [&stream](const NamedInterval& interval) { + ApplyPostOrder(tree, [&stream](const NamedInterval &interval) { IntervalPrinter(&stream, interval); }); EXPECT_EQ(stream.str(), absl::StrJoin( @@ -1156,7 +1156,7 @@ TEST(VectorTreeTest, ApplyPreOrderTransformValue) { // Transform intervals. std::vector visit_order; const int shift = 2; - ApplyPreOrder(tree, [=, &visit_order](NamedInterval& interval) { + ApplyPreOrder(tree, [=, &visit_order](NamedInterval &interval) { visit_order.push_back(interval.name); interval.left += shift; interval.right += shift; @@ -1167,7 +1167,7 @@ TEST(VectorTreeTest, ApplyPreOrderTransformValue) { // Print output for verification. std::ostringstream stream; - ApplyPreOrder(tree, [&stream](const NamedInterval& interval) { + ApplyPreOrder(tree, [&stream](const NamedInterval &interval) { IntervalPrinter(&stream, interval); }); EXPECT_EQ(stream.str(), absl::StrJoin( @@ -1190,8 +1190,8 @@ TEST(VectorTreeTest, ApplyPreOrderTransformNode) { // Transform intervals. std::vector visit_order; const int shift = 2; - ApplyPreOrder(tree, [=, &visit_order](VectorTreeTestType& node) { - auto& interval = node.Value(); + ApplyPreOrder(tree, [=, &visit_order](VectorTreeTestType &node) { + auto &interval = node.Value(); visit_order.push_back(interval.name); interval.left += shift; interval.right += shift; @@ -1202,7 +1202,7 @@ TEST(VectorTreeTest, ApplyPreOrderTransformNode) { // Print output for verification. std::ostringstream stream; - ApplyPreOrder(tree, [&stream](const NamedInterval& interval) { + ApplyPreOrder(tree, [&stream](const NamedInterval &interval) { IntervalPrinter(&stream, interval); }); EXPECT_EQ(stream.str(), absl::StrJoin( @@ -1225,7 +1225,7 @@ TEST(VectorTreeTest, ApplyPostOrderTransformValue) { // Transform intervals. std::vector visit_order; const int shift = 1; - ApplyPostOrder(tree, [=, &visit_order](NamedInterval& interval) { + ApplyPostOrder(tree, [=, &visit_order](NamedInterval &interval) { visit_order.push_back(interval.name); interval.left += shift; interval.right += shift; @@ -1235,7 +1235,7 @@ TEST(VectorTreeTest, ApplyPostOrderTransformValue) { // Print output for verification. std::ostringstream stream; - ApplyPostOrder(tree, [&stream](const NamedInterval& interval) { + ApplyPostOrder(tree, [&stream](const NamedInterval &interval) { IntervalPrinter(&stream, interval); }); EXPECT_EQ(stream.str(), absl::StrJoin( @@ -1258,8 +1258,8 @@ TEST(VectorTreeTest, ApplyPostOrderTransformNode) { // Transform intervals. std::vector visit_order; const int shift = 1; - ApplyPostOrder(tree, [=, &visit_order](VectorTreeTestType& node) { - auto& interval = node.Value(); + ApplyPostOrder(tree, [=, &visit_order](VectorTreeTestType &node) { + auto &interval = node.Value(); visit_order.push_back(interval.name); interval.left += shift; interval.right += shift; @@ -1269,7 +1269,7 @@ TEST(VectorTreeTest, ApplyPostOrderTransformNode) { // Print output for verification. std::ostringstream stream; - ApplyPostOrder(tree, [&stream](const NamedInterval& interval) { + ApplyPostOrder(tree, [&stream](const NamedInterval &interval) { IntervalPrinter(&stream, interval); }); EXPECT_EQ(stream.str(), absl::StrJoin( @@ -1297,7 +1297,7 @@ TEST(VectorTreeTest, HoistOnlyChildRootOnly) { EXPECT_EQ(BirthRank(tree), 0); // no parent EXPECT_EQ(&Root(tree), &tree); - const auto& value = tree.Value(); + const auto &value = tree.Value(); EXPECT_EQ(value.left, 0); EXPECT_EQ(value.right, 2); EXPECT_EQ(value.name, "root"); @@ -1310,14 +1310,14 @@ TEST(VectorTreeTest, HoistOnlyChildOneChildTreeGreatestAncestor) { // effectively remove the "root" generation EXPECT_TRUE(HoistOnlyChild(tree)); { - const auto& child = tree; + const auto &child = tree; EXPECT_EQ(child.Parent(), nullptr); EXPECT_EQ(&Root(child), &tree); EXPECT_FALSE(is_leaf(child)); EXPECT_EQ(NumAncestors(child), 0); EXPECT_EQ(BirthRank(child), 0); - const auto& cvalue = child.Value(); + const auto &cvalue = child.Value(); EXPECT_EQ(cvalue.left, 0); EXPECT_EQ(cvalue.right, 3); EXPECT_EQ(cvalue.name, "gen1"); @@ -1331,14 +1331,14 @@ TEST(VectorTreeTest, HoistOnlyChildOneChildTreeGreatestAncestor) { EXPECT_EQ(PreviousLeaf(child), nullptr); { - const auto& grandchild = child.Children().front(); + const auto &grandchild = child.Children().front(); EXPECT_EQ(grandchild.Parent(), &child); EXPECT_EQ(&Root(grandchild), &tree); EXPECT_TRUE(is_leaf(grandchild)); EXPECT_EQ(NumAncestors(grandchild), 1); EXPECT_EQ(BirthRank(grandchild), 0); - const auto& gcvalue = grandchild.Value(); + const auto &gcvalue = grandchild.Value(); EXPECT_EQ(gcvalue.left, 0); EXPECT_EQ(gcvalue.right, 3); EXPECT_EQ(gcvalue.name, "gen2"); @@ -1365,7 +1365,7 @@ TEST(VectorTreeTest, HoistOnlyChildOneChildTreeMiddleAncestor) { VectorTreeTestType tree(verible::testing::MakeOneChildPolicyExampleTree()); EXPECT_TRUE(HoistOnlyChild(tree.Children().front())); { - const auto& value = tree.Value(); + const auto &value = tree.Value(); EXPECT_EQ(value.left, 0); EXPECT_EQ(value.right, 3); EXPECT_EQ(value.name, "root"); @@ -1379,14 +1379,14 @@ TEST(VectorTreeTest, HoistOnlyChildOneChildTreeMiddleAncestor) { // The "gen1" node is removed, and now the grandchild is directly linked. { - const auto& grandchild = tree.Children().front(); + const auto &grandchild = tree.Children().front(); EXPECT_EQ(grandchild.Parent(), &tree); EXPECT_EQ(&Root(grandchild), &tree); EXPECT_TRUE(is_leaf(grandchild)); EXPECT_EQ(NumAncestors(grandchild), 1); EXPECT_EQ(BirthRank(grandchild), 0); - const auto& gcvalue = grandchild.Value(); + const auto &gcvalue = grandchild.Value(); EXPECT_EQ(gcvalue.left, 0); EXPECT_EQ(gcvalue.right, 3); EXPECT_EQ(gcvalue.name, "gen2"); @@ -1416,10 +1416,10 @@ TEST(VectorTreeTest, HoistOnlyChildFamilyTree) { // Copy-extract tree values from a node's direct children only. // TODO(fangism): Adapt this into a public method of VectorTree. template -static std::vector NodeValues(const T& node) { +static std::vector NodeValues(const T &node) { std::vector result; result.reserve(node.Children().size()); - for (const auto& child : node.Children()) { + for (const auto &child : node.Children()) { result.emplace_back(child.Value()); } return result; @@ -1473,7 +1473,7 @@ TEST(VectorTreeTest, AdoptSubtreesFromNonemptyToNonempty) { TEST(VectorTreeTest, MergeConsecutiveSiblingsTooFewElements) { using tree_type = VectorTree; tree_type tree(1, tree_type(2)); - auto adder = [](int* left, const int& right) { *left += right; }; + auto adder = [](int *left, const int &right) { *left += right; }; EXPECT_THAT(NodeValues(tree), ElementsAre(2)); EXPECT_DEATH(MergeConsecutiveSiblings(tree, 0, adder), ""); } @@ -1481,7 +1481,7 @@ TEST(VectorTreeTest, MergeConsecutiveSiblingsTooFewElements) { TEST(VectorTreeTest, MergeConsecutiveSiblingsOutOfBounds) { using tree_type = VectorTree; tree_type tree(1, tree_type(2), tree_type(3)); - auto adder = [](int* left, const int& right) { *left += right; }; + auto adder = [](int *left, const int &right) { *left += right; }; EXPECT_THAT(NodeValues(tree), ElementsAre(2, 3)); EXPECT_DEATH(MergeConsecutiveSiblings(tree, 1, adder), ""); } @@ -1489,7 +1489,7 @@ TEST(VectorTreeTest, MergeConsecutiveSiblingsOutOfBounds) { TEST(VectorTreeTest, MergeConsecutiveSiblingsAddLeaves) { using tree_type = VectorTree; tree_type tree(1, tree_type(2), tree_type(3), tree_type(4), tree_type(5)); - auto adder = [](int* left, const int& right) { *left += right; }; + auto adder = [](int *left, const int &right) { *left += right; }; EXPECT_THAT(NodeValues(tree), ElementsAre(2, 3, 4, 5)); VLOG(1) << __FUNCTION__ << ": before first merge"; @@ -1518,7 +1518,7 @@ TEST(VectorTreeTest, MergeConsecutiveSiblingsConcatenateSubtreesOnce) { tree_type(10), tree_type(11)), tree_type(5, // tree_type(12), tree_type(13))); - auto subtractor = [](int* left, const int& right) { *left -= right; }; + auto subtractor = [](int *left, const int &right) { *left -= right; }; EXPECT_THAT(NodeValues(tree), ElementsAre(2, 3, 4, 5)); MergeConsecutiveSiblings(tree, 1, subtractor); // combine middle two subtrees @@ -1537,7 +1537,7 @@ TEST(VectorTreeTest, MergeConsecutiveSiblingsConcatenateSubtrees) { tree_type(10), tree_type(11)), tree_type(5, // tree_type(12), tree_type(13))); - auto subtractor = [](int* left, const int& right) { *left -= right; }; + auto subtractor = [](int *left, const int &right) { *left -= right; }; EXPECT_THAT(NodeValues(tree), ElementsAre(2, 3, 4, 5)); MergeConsecutiveSiblings(tree, 0, subtractor); // combine first two subtrees @@ -2059,8 +2059,8 @@ TEST(VectorTreeTest, PrintTreeCustom) { const auto tree = verible::testing::MakeExampleFamilyTree(); std::ostringstream stream; PrintTree(tree, &stream, - [](std::ostream& s, - const decltype(tree)::value_type& value) -> std::ostream& { + [](std::ostream &s, + const decltype(tree)::value_type &value) -> std::ostream & { return s << value.name; // print only the name field }); EXPECT_EQ(stream.str(), R"({ (grandparent) @@ -2078,7 +2078,7 @@ TEST(VectorTreeTest, PrintTreeCustom) { TEST(VectorTreeTest, ChildrenManipulation) { VectorTreeTestType tree(verible::testing::MakeExampleFamilyTree()); - auto& children_gp = tree.Children(); + auto &children_gp = tree.Children(); children_gp.push_back(VectorTreeTestType(NamedInterval(4, 6, "parent3"))); @@ -2086,8 +2086,8 @@ TEST(VectorTreeTest, ChildrenManipulation) { EXPECT_EQ(tree.Children().back().Value(), NamedInterval(4, 6, "parent3")); EXPECT_EQ(tree.Children().back().Parent(), &tree); - auto& p3 = tree.Children().back(); - auto& children_p3 = p3.Children(); + auto &p3 = tree.Children().back(); + auto &children_p3 = p3.Children(); children_p3.push_back(VectorTreeTestType(NamedInterval(4, 5, "child5"))); children_p3.emplace_back(NamedInterval(5, 6, "child6")); @@ -2100,7 +2100,7 @@ TEST(VectorTreeTest, ChildrenManipulation) { EXPECT_EQ(p3.Children().at(1).Value(), NamedInterval(5, 6, "child6")); EXPECT_EQ(p3.Children().at(1).Parent(), &p3); - auto& p2 = tree.Children().at(1); + auto &p2 = tree.Children().at(1); const NamedInterval original_p2_children[] = { p2.Children().at(0).Value(), diff --git a/common/util/vector_tree_test_util.cc b/common/util/vector_tree_test_util.cc index 349fdfb39..70147e3ac 100644 --- a/common/util/vector_tree_test_util.cc +++ b/common/util/vector_tree_test_util.cc @@ -24,7 +24,7 @@ namespace verible { namespace testing { -std::ostream& operator<<(std::ostream& stream, const NamedInterval& i) { +std::ostream &operator<<(std::ostream &stream, const NamedInterval &i) { return stream << '(' << i.left << ", " << i.right << ", " << i.name << ')'; } @@ -57,15 +57,15 @@ VectorTreeTestType MakeExampleFamilyTree() { ); } -void IntervalPrinter(std::ostream* stream, const NamedInterval& interval) { +void IntervalPrinter(std::ostream *stream, const NamedInterval &interval) { *stream << interval << '\n'; } // Verify the invariant that parent spans same interval range as children. -void VerifyInterval(const VectorTreeTestType& node) { - const auto& children = node.Children(); +void VerifyInterval(const VectorTreeTestType &node) { + const auto &children = node.Children(); if (!children.empty()) { - const auto& interval = node.Value(); + const auto &interval = node.Value(); EXPECT_EQ(interval.left, children.front().Value().left); EXPECT_EQ(interval.right, children.back().Value().right); } diff --git a/common/util/vector_tree_test_util.h b/common/util/vector_tree_test_util.h index 4c82b6da6..a1f082038 100644 --- a/common/util/vector_tree_test_util.h +++ b/common/util/vector_tree_test_util.h @@ -35,17 +35,17 @@ struct NamedInterval { NamedInterval(int l, int r, absl::string_view n) : left(l), right(r), name(n) {} - NamedInterval(const NamedInterval&) = default; - NamedInterval(NamedInterval&&) = default; - NamedInterval& operator=(const NamedInterval&) = default; - NamedInterval& operator=(NamedInterval&&) = default; + NamedInterval(const NamedInterval &) = default; + NamedInterval(NamedInterval &&) = default; + NamedInterval &operator=(const NamedInterval &) = default; + NamedInterval &operator=(NamedInterval &&) = default; - bool operator==(const NamedInterval& other) const { + bool operator==(const NamedInterval &other) const { return left == other.left && right == other.right && name == other.name; } }; -std::ostream& operator<<(std::ostream& stream, const NamedInterval& i); +std::ostream &operator<<(std::ostream &stream, const NamedInterval &i); using VectorTreeTestType = VectorTree; @@ -56,16 +56,16 @@ VectorTreeTestType MakeOneChildPolicyExampleTree(); VectorTreeTestType MakeExampleFamilyTree(); template -std::vector MakePath(const VectorTree& node) { +std::vector MakePath(const VectorTree &node) { std::vector path; verible::Path(node, path); return path; } -void IntervalPrinter(std::ostream* stream, const NamedInterval& interval); +void IntervalPrinter(std::ostream *stream, const NamedInterval &interval); // Verify the invariant that parent spans same interval range as children. -void VerifyInterval(const VectorTreeTestType& node); +void VerifyInterval(const VectorTreeTestType &node); } // namespace testing } // namespace verible diff --git a/common/util/with_reason.h b/common/util/with_reason.h index 785098541..4bc24e443 100644 --- a/common/util/with_reason.h +++ b/common/util/with_reason.h @@ -41,7 +41,7 @@ namespace verible { template struct WithReason { T value; - const char* reason; // A simple string literal shall suffice. + const char *reason; // A simple string literal shall suffice. }; } // namespace verible diff --git a/common/util/with_reason_test.cc b/common/util/with_reason_test.cc index 26a9b2dbf..523a35c22 100644 --- a/common/util/with_reason_test.cc +++ b/common/util/with_reason_test.cc @@ -22,7 +22,7 @@ namespace verible { namespace { // Example of a priority-ordered function. -static WithReason FizzBuzzer(int i) { +static WithReason FizzBuzzer(int i) { if (i % 3 == 0) { if (i % 5 == 0) { return {"fizzbuzz", "value is divisible by 3 and 5."}; diff --git a/verilog/CST/DPI.cc b/verilog/CST/DPI.cc index 8f9b66c98..c754d5897 100644 --- a/verilog/CST/DPI.cc +++ b/verilog/CST/DPI.cc @@ -21,11 +21,11 @@ namespace verilog { using verible::Symbol; using verible::SyntaxTreeNode; -std::vector FindAllDPIImports(const Symbol& root) { +std::vector FindAllDPIImports(const Symbol &root) { return SearchSyntaxTree(root, NodekDPIImportItem()); } -const SyntaxTreeNode* GetDPIImportPrototype(const Symbol& symbol) { +const SyntaxTreeNode *GetDPIImportPrototype(const Symbol &symbol) { return GetSubtreeAsNode(symbol, NodeEnum::kDPIImportItem, 5); } diff --git a/verilog/CST/DPI.h b/verilog/CST/DPI.h index b54e2d541..aae81c244 100644 --- a/verilog/CST/DPI.h +++ b/verilog/CST/DPI.h @@ -37,8 +37,8 @@ namespace verilog { template -verible::SymbolPtr MakeDPIImport(T0&& keyword, T1&& spec, T2&& property, - T3&& id, T4&& equals, T5&& proto) { +verible::SymbolPtr MakeDPIImport(T0 &&keyword, T1 &&spec, T2 &&property, + T3 &&id, T4 &&equals, T5 &&proto) { verible::CheckSymbolAsLeaf(*keyword, verilog_tokentype::TK_import); verible::CheckSymbolAsLeaf(*spec, verilog_tokentype::TK_StringLiteral); if (id != nullptr) { @@ -58,9 +58,9 @@ verible::SymbolPtr MakeDPIImport(T0&& keyword, T1&& spec, T2&& property, // in positions 3 and 4 (optional symbols). Compiler is not guaranteed // to deduce to that some paths are not reachble/applicable. template -verible::SymbolPtr MakeDPIImport(T0&& keyword, T1&& spec, T2&& property, +verible::SymbolPtr MakeDPIImport(T0 &&keyword, T1 &&spec, T2 &&property, std::nullptr_t id, std::nullptr_t equals, - T3&& proto, T4&& semi) { + T3 &&proto, T4 &&semi) { verible::CheckSymbolAsLeaf(*keyword, verilog_tokentype::TK_import); verible::CheckSymbolAsLeaf(*spec, verilog_tokentype::TK_StringLiteral); CHECK(verible::SymbolCastToNode(*proto).MatchesTagAnyOf( @@ -72,10 +72,11 @@ verible::SymbolPtr MakeDPIImport(T0&& keyword, T1&& spec, T2&& property, } // Find all DPI imports. -std::vector FindAllDPIImports(const verible::Symbol&); +std::vector FindAllDPIImports( + const verible::Symbol &); // Returns the function/task prototype. -const verible::SyntaxTreeNode* GetDPIImportPrototype(const verible::Symbol&); +const verible::SyntaxTreeNode *GetDPIImportPrototype(const verible::Symbol &); } // namespace verilog diff --git a/verilog/CST/DPI_test.cc b/verilog/CST/DPI_test.cc index 99d014e32..acc70ae1f 100644 --- a/verilog/CST/DPI_test.cc +++ b/verilog/CST/DPI_test.cc @@ -71,10 +71,10 @@ TEST(FindAllDPIImportsTest, CountMatches) { "\n" "endmodule\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllDPIImports(*ABSL_DIE_IF_NULL(root)); }); } @@ -111,15 +111,15 @@ TEST(GetDPIImportPrototypeTest, Various) { "\n" "endmodule\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto dpi_imports = FindAllDPIImports(*ABSL_DIE_IF_NULL(root)); std::vector prototypes; prototypes.reserve(dpi_imports.size()); - for (const auto& dpi_import : dpi_imports) { + for (const auto &dpi_import : dpi_imports) { prototypes.push_back(TreeSearchMatch{ GetDPIImportPrototype(*dpi_import.match), /* no context */}); } diff --git a/verilog/CST/class.cc b/verilog/CST/class.cc index 3bfe60341..615add05c 100644 --- a/verilog/CST/class.cc +++ b/verilog/CST/class.cc @@ -33,48 +33,48 @@ using verible::Symbol; using verible::SyntaxTreeNode; std::vector FindAllClassDeclarations( - const verible::Symbol& root) { + const verible::Symbol &root) { return SearchSyntaxTree(root, NodekClassDeclaration()); } std::vector FindAllClassConstructors( - const verible::Symbol& root) { + const verible::Symbol &root) { return SearchSyntaxTree(root, NodekClassConstructor()); } std::vector FindAllHierarchyExtensions( - const verible::Symbol& root) { + const verible::Symbol &root) { return SearchSyntaxTree(root, NodekHierarchyExtension()); } -const verible::SyntaxTreeNode* GetClassHeader( - const verible::Symbol& class_symbol) { +const verible::SyntaxTreeNode *GetClassHeader( + const verible::Symbol &class_symbol) { return verible::GetSubtreeAsNode(class_symbol, NodeEnum::kClassDeclaration, 0, NodeEnum::kClassHeader); } -const verible::SyntaxTreeLeaf* GetClassName( - const verible::Symbol& class_declaration) { - const auto* header_node = GetClassHeader(class_declaration); +const verible::SyntaxTreeLeaf *GetClassName( + const verible::Symbol &class_declaration) { + const auto *header_node = GetClassHeader(class_declaration); if (!header_node) return nullptr; - const verible::SyntaxTreeLeaf* name_leaf = + const verible::SyntaxTreeLeaf *name_leaf = verible::GetSubtreeAsLeaf(*header_node, NodeEnum::kClassHeader, 3); return name_leaf; } -const verible::SyntaxTreeNode* GetExtendedClass( - const verible::Symbol& class_declaration) { - const auto* class_header = GetClassHeader(class_declaration); +const verible::SyntaxTreeNode *GetExtendedClass( + const verible::Symbol &class_declaration) { + const auto *class_header = GetClassHeader(class_declaration); if (!class_header) return nullptr; - const auto* extends_list = + const auto *extends_list = verible::GetSubtreeAsSymbol(*class_header, NodeEnum::kClassHeader, 5); if (!extends_list) return nullptr; return verible::GetSubtreeAsNode(*extends_list, NodeEnum::kExtendsList, 1); } -const verible::SyntaxTreeLeaf* GetClassEndLabel( - const verible::Symbol& class_declaration) { - const auto* label_node = verible::GetSubtreeAsSymbol( +const verible::SyntaxTreeLeaf *GetClassEndLabel( + const verible::Symbol &class_declaration) { + const auto *label_node = verible::GetSubtreeAsSymbol( class_declaration, NodeEnum::kClassDeclaration, 3); if (label_node == nullptr) { return nullptr; @@ -83,40 +83,40 @@ const verible::SyntaxTreeLeaf* GetClassEndLabel( NodeEnum::kLabel, 1); } -const verible::SyntaxTreeNode* GetClassItemList( - const verible::Symbol& class_declaration) { +const verible::SyntaxTreeNode *GetClassItemList( + const verible::Symbol &class_declaration) { return verible::GetSubtreeAsNode( class_declaration, NodeEnum::kClassDeclaration, 1, NodeEnum::kClassItems); } -const verible::SyntaxTreeLeaf* GetUnqualifiedIdFromHierarchyExtension( - const verible::Symbol& hierarchy_extension) { - const verible::SyntaxTreeNode* unqualified = verible::GetSubtreeAsNode( +const verible::SyntaxTreeLeaf *GetUnqualifiedIdFromHierarchyExtension( + const verible::Symbol &hierarchy_extension) { + const verible::SyntaxTreeNode *unqualified = verible::GetSubtreeAsNode( hierarchy_extension, NodeEnum::kHierarchyExtension, 1, NodeEnum::kUnqualifiedId); if (!unqualified) return nullptr; return AutoUnwrapIdentifier(*unqualified); } -const verible::SyntaxTreeNode* GetParamDeclarationListFromClassDeclaration( - const verible::Symbol& class_declaration) { - const auto* header_node = GetClassHeader(class_declaration); +const verible::SyntaxTreeNode *GetParamDeclarationListFromClassDeclaration( + const verible::Symbol &class_declaration) { + const auto *header_node = GetClassHeader(class_declaration); if (!header_node) return nullptr; - const verible::Symbol* param_declaration_list = + const verible::Symbol *param_declaration_list = verible::GetSubtreeAsSymbol(*header_node, NodeEnum::kClassHeader, 4); return verible::CheckOptionalSymbolAsNode( param_declaration_list, NodeEnum::kFormalParameterListDeclaration); } -const verible::SyntaxTreeNode* GetClassConstructorStatementList( - const verible::Symbol& class_constructor) { +const verible::SyntaxTreeNode *GetClassConstructorStatementList( + const verible::Symbol &class_constructor) { return verible::GetSubtreeAsNode(class_constructor, NodeEnum::kClassConstructor, 2); } -const verible::SyntaxTreeLeaf* GetNewKeywordFromClassConstructor( - const verible::Symbol& class_constructor) { - const verible::SyntaxTreeNode* constructor_prototype = +const verible::SyntaxTreeLeaf *GetNewKeywordFromClassConstructor( + const verible::Symbol &class_constructor) { + const verible::SyntaxTreeNode *constructor_prototype = verible::GetSubtreeAsNode(class_constructor, NodeEnum::kClassConstructor, 1, NodeEnum::kClassConstructorPrototype); if (!constructor_prototype) return nullptr; diff --git a/verilog/CST/class.h b/verilog/CST/class.h index a7dc71f0a..9c36f7312 100644 --- a/verilog/CST/class.h +++ b/verilog/CST/class.h @@ -25,54 +25,54 @@ namespace verilog { // Find all class declarations. std::vector FindAllClassDeclarations( - const verible::Symbol&); + const verible::Symbol &); // Find all class constructors. std::vector FindAllClassConstructors( - const verible::Symbol& root); + const verible::Symbol &root); // Find all hierarchy extensions. std::vector FindAllHierarchyExtensions( - const verible::Symbol&); + const verible::Symbol &); // Returns the full header of a class. -const verible::SyntaxTreeNode* GetClassHeader(const verible::Symbol&); +const verible::SyntaxTreeNode *GetClassHeader(const verible::Symbol &); // Returns the leaf node for class name. -const verible::SyntaxTreeLeaf* GetClassName(const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetClassName(const verible::Symbol &); // Returns the node that spans the extended class name(if exists). // e.g from "class my_class extends other_class;" return "other_class". // e.g from "class my_class extends pkg::my_class2" => return the node that // spans "pkg::my_class2". e.g "class my_class;" return "nullptr". -const verible::SyntaxTreeNode* GetExtendedClass(const verible::Symbol&); +const verible::SyntaxTreeNode *GetExtendedClass(const verible::Symbol &); // Returns class name token after endclass. // e.g. from "class foo; endclass: foo" returns the second "foo". -const verible::SyntaxTreeLeaf* GetClassEndLabel(const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetClassEndLabel(const verible::Symbol &); // Returns the node spanning class's Item list. -const verible::SyntaxTreeNode* GetClassItemList(const verible::Symbol&); +const verible::SyntaxTreeNode *GetClassItemList(const verible::Symbol &); // Returns the identifier from node tagged with kHierarchyExtension. // e.g from "instance1.x" => return "x". -const verible::SyntaxTreeLeaf* GetUnqualifiedIdFromHierarchyExtension( - const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetUnqualifiedIdFromHierarchyExtension( + const verible::Symbol &); // Extract the subnode of a param declaration list from class decalration. // e.g from "class m#(parameter x = 2)" return the node spanning "#(parameter x // = 2)". -const verible::SyntaxTreeNode* GetParamDeclarationListFromClassDeclaration( - const verible::Symbol&); +const verible::SyntaxTreeNode *GetParamDeclarationListFromClassDeclaration( + const verible::Symbol &); // Returns the node spanning the class constructor body (tagged with // kStatementList) from node tagged with kClassConstructor. -const verible::SyntaxTreeNode* GetClassConstructorStatementList( - const verible::Symbol& class_constructor); +const verible::SyntaxTreeNode *GetClassConstructorStatementList( + const verible::Symbol &class_constructor); // Returns the leaf spanning the "new" keyword from class constructor. -const verible::SyntaxTreeLeaf* GetNewKeywordFromClassConstructor( - const verible::Symbol& class_constructor); +const verible::SyntaxTreeLeaf *GetNewKeywordFromClassConstructor( + const verible::Symbol &class_constructor); } // namespace verilog diff --git a/verilog/CST/class_test.cc b/verilog/CST/class_test.cc index 884f1a6ea..ebd9830b3 100644 --- a/verilog/CST/class_test.cc +++ b/verilog/CST/class_test.cc @@ -68,16 +68,16 @@ TEST(GetClassNameTest, ClassName) { {kTag, "bar"}, "; endclass\nendclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllClassDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& decl : decls) { - const auto* type = GetClassName(*decl.match); + for (const auto &decl : decls) { + const auto *type = GetClassName(*decl.match); names.push_back(TreeSearchMatch{type, {/* ignored context */}}); } return names; @@ -103,16 +103,16 @@ TEST(GetClassNameTest, ClassEndLabel) { "\nendclass: ", {kTag, "foo"}}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllClassDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& decl : decls) { - const auto* name = GetClassEndLabel(*decl.match); + for (const auto &decl : decls) { + const auto *name = GetClassEndLabel(*decl.match); names.push_back(TreeSearchMatch{name, {/* ignored context */}}); } return names; @@ -124,14 +124,14 @@ TEST(GetClassNameTest, NoClassEndLabelTest) { constexpr absl::string_view kTestCases[] = { {"class foo; endclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test, "test-file"); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto decls = FindAllClassDeclarations(*ABSL_DIE_IF_NULL(root)); - for (const auto& decl : decls) { - const auto* type = GetClassEndLabel(*decl.match); + for (const auto &decl : decls) { + const auto *type = GetClassEndLabel(*decl.match); EXPECT_EQ(type, nullptr); } } @@ -157,16 +157,16 @@ TEST(GetClassMemberTest, GetMemberName) { {kTag, "r"}, ";\nendmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& members = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &members = FindAllHierarchyExtensions(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& decl : members) { - const auto* name = + for (const auto &decl : members) { + const auto *name = GetUnqualifiedIdFromHierarchyExtension(*decl.match); names.emplace_back(TreeSearchMatch{name, {/* ignored context */}}); } @@ -189,16 +189,16 @@ TEST(FindAllModuleDeclarationTest, FindClassParameters) { {kTag, "#(parameter type x = 3,\n parameter logic y = 4)"}, ";\nendclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllClassDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector params; - for (const auto& instance : instances) { - const auto* decl = + for (const auto &instance : instances) { + const auto *decl = GetParamDeclarationListFromClassDeclaration(*instance.match); if (decl == nullptr) { continue; @@ -220,16 +220,16 @@ TEST(GetClassExtendTest, GetExtendListIdentifiers) { {"class X extends ", {kTag, "Y::K::h"}, ";\nendclass"}, {"class X extends ", {kTag, "Y::O"}, ";\nendclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& members = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &members = FindAllClassDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector identifiers; - for (const auto& decl : members) { - const auto* identifier = GetExtendedClass(*decl.match); + for (const auto &decl : members) { + const auto *identifier = GetExtendedClass(*decl.match); if (identifier == nullptr) { continue; } @@ -251,16 +251,16 @@ TEST(GetClassConstructorTest, GetConstructorBody) { {kTag, "x = y;"}, "\nendfunction\nendclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& constructors = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &constructors = FindAllClassConstructors(*ABSL_DIE_IF_NULL(root)); std::vector bodies; - for (const auto& constructor : constructors) { - const auto* body = + for (const auto &constructor : constructors) { + const auto *body = GetClassConstructorStatementList(*constructor.match); bodies.emplace_back(TreeSearchMatch{body, {/* ignored context */}}); } @@ -277,16 +277,16 @@ TEST(GetClassConstructorTest, GetNewKeyword) { {"module m;endmodule"}, {"class foo;\nfunction ", {kTag, "new"}, "();\n\nendfunction\nendclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& constructors = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &constructors = FindAllClassConstructors(*ABSL_DIE_IF_NULL(root)); std::vector keywords; - for (const auto& constructor : constructors) { - const auto* keyword = + for (const auto &constructor : constructors) { + const auto *keyword = GetNewKeywordFromClassConstructor(*constructor.match); keywords.emplace_back( TreeSearchMatch{keyword, {/* ignored context */}}); diff --git a/verilog/CST/constraints.cc b/verilog/CST/constraints.cc index 205138bdd..c613ba8a1 100644 --- a/verilog/CST/constraints.cc +++ b/verilog/CST/constraints.cc @@ -32,20 +32,20 @@ namespace verilog { std::vector FindAllConstraintDeclarations( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekConstraintDeclaration()); } -bool IsOutOfLineConstraintDefinition(const verible::Symbol& symbol) { - const auto* identifier_symbol = +bool IsOutOfLineConstraintDefinition(const verible::Symbol &symbol) { + const auto *identifier_symbol = verible::GetSubtreeAsSymbol(symbol, NodeEnum::kConstraintDeclaration, 2); return IdIsQualified(*identifier_symbol); } -const verible::TokenInfo* GetSymbolIdentifierFromConstraintDeclaration( - const verible::Symbol& symbol) { - const auto* identifier_symbol = +const verible::TokenInfo *GetSymbolIdentifierFromConstraintDeclaration( + const verible::Symbol &symbol) { + const auto *identifier_symbol = verible::GetSubtreeAsSymbol(symbol, NodeEnum::kConstraintDeclaration, 2); if (!identifier_symbol) return nullptr; return &AutoUnwrapIdentifier(*identifier_symbol)->get(); diff --git a/verilog/CST/constraints.h b/verilog/CST/constraints.h index eec5dd12e..47f45a6bb 100644 --- a/verilog/CST/constraints.h +++ b/verilog/CST/constraints.h @@ -33,12 +33,12 @@ namespace verilog { std::vector FindAllConstraintDeclarations( - const verible::Symbol& root); + const verible::Symbol &root); -bool IsOutOfLineConstraintDefinition(const verible::Symbol& symbol); +bool IsOutOfLineConstraintDefinition(const verible::Symbol &symbol); -const verible::TokenInfo* GetSymbolIdentifierFromConstraintDeclaration( - const verible::Symbol& symbol); +const verible::TokenInfo *GetSymbolIdentifierFromConstraintDeclaration( + const verible::Symbol &symbol); } // namespace verilog diff --git a/verilog/CST/constraints_test.cc b/verilog/CST/constraints_test.cc index 9efa0e027..4e3530edf 100644 --- a/verilog/CST/constraints_test.cc +++ b/verilog/CST/constraints_test.cc @@ -66,10 +66,10 @@ TEST(FindAllConstraintDeclarationsTest, BasicTests) { {kTag, "constraint y { x == 10; }"}, "; endclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllConstraintDeclarations(*root); }); } @@ -80,10 +80,10 @@ TEST(IsOutOfLineConstraintDefinitionTest, BasicTests) { {"class foo; rand logic a; constraint Bar { a < 16; } endclass", false}, {"constraint classname::constraint_c { a <= b; }", true}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.first, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); std::vector constraint_declarations = FindAllConstraintDeclarations(*root); @@ -103,10 +103,10 @@ TEST(GetSymbolIdentifierFromConstraintDeclarationTest, BasicTests) { {"class foo; rand logic a; constraint b { a >= 16; } endclass", "b"}, {"class foo; rand logic a; constraint stH { a == 16; } endclass", "stH"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.first, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); std::vector constraint_declarations = FindAllConstraintDeclarations(*root); diff --git a/verilog/CST/context_functions.h b/verilog/CST/context_functions.h index 8bdbe2217..8e073c800 100644 --- a/verilog/CST/context_functions.h +++ b/verilog/CST/context_functions.h @@ -23,48 +23,48 @@ namespace analysis { // The following functions are specialized for common Verilog context queries. -inline bool ContextIsInsideClass(const verible::SyntaxTreeContext& context) { +inline bool ContextIsInsideClass(const verible::SyntaxTreeContext &context) { return context.IsInside(NodeEnum::kClassDeclaration); } -inline bool ContextIsInsideModule(const verible::SyntaxTreeContext& context) { +inline bool ContextIsInsideModule(const verible::SyntaxTreeContext &context) { return context.IsInside(NodeEnum::kModuleDeclaration); } // Does not treat global scope as being inside a package. -inline bool ContextIsInsidePackage(const verible::SyntaxTreeContext& context) { +inline bool ContextIsInsidePackage(const verible::SyntaxTreeContext &context) { return context.IsInside(NodeEnum::kPackageDeclaration); } inline bool ContextIsInsidePackedDimensions( - const verible::SyntaxTreeContext& context) { + const verible::SyntaxTreeContext &context) { return context.IsInside(NodeEnum::kPackedDimensions); } inline bool ContextIsInsideUnpackedDimensions( - const verible::SyntaxTreeContext& context) { + const verible::SyntaxTreeContext &context) { // Exclude being inside an associative array dimensions ([type]). return context.IsInsideFirst({NodeEnum::kUnpackedDimensions}, {NodeEnum::kDimensionAssociativeType}); } inline bool ContextIsInsideFormalParameterList( - const verible::SyntaxTreeContext& context) { + const verible::SyntaxTreeContext &context) { return context.IsInside(NodeEnum::kFormalParameterList); } inline bool ContextIsInsideTaskFunctionPortList( - const verible::SyntaxTreeContext& context) { + const verible::SyntaxTreeContext &context) { return context.IsInside(NodeEnum::kPortList); } inline bool ContextIsInsideStatement( - const verible::SyntaxTreeContext& context) { + const verible::SyntaxTreeContext &context) { return context.IsInside(NodeEnum::kStatement); } inline bool ContextIsInsideDeclarationDimensions( - const verible::SyntaxTreeContext& context) { + const verible::SyntaxTreeContext &context) { return context.DirectParentIsOneOf( {NodeEnum::kDimensionRange, NodeEnum::kDimensionScalar, NodeEnum::kDimensionSlice, NodeEnum::kDimensionAssociativeType}); diff --git a/verilog/CST/context_functions_test.cc b/verilog/CST/context_functions_test.cc index 6ddab7418..46a78dec5 100644 --- a/verilog/CST/context_functions_test.cc +++ b/verilog/CST/context_functions_test.cc @@ -32,8 +32,8 @@ using verible::SyntaxTreeContext; using verible::SyntaxTreeNode; using verible::TNode; -const SyntaxTreeNode& CastAsNode(const SymbolPtr& p) { - return down_cast(*p.get()); +const SyntaxTreeNode &CastAsNode(const SymbolPtr &p) { + return down_cast(*p.get()); } // Test that empty context is handled correctly. diff --git a/verilog/CST/data.cc b/verilog/CST/data.cc index 642131e8c..9e55d324c 100644 --- a/verilog/CST/data.cc +++ b/verilog/CST/data.cc @@ -32,7 +32,7 @@ using verible::Symbol; using verible::TokenInfo; // Helper predicate to match all types of applicable variables -static bool ExpectedTagPredicate(const Symbol& symbol) { +static bool ExpectedTagPredicate(const Symbol &symbol) { verible::SymbolTag reg_symbol = { verible::SymbolKind::kNode, static_cast(NodeEnum::kRegisterVariable)}; @@ -49,11 +49,11 @@ static bool ExpectedTagPredicate(const Symbol& symbol) { return symbol.Tag() == reg_symbol || symbol.Tag() == gate_symbol; } -std::vector GetIdentifiersFromDataDeclaration( - const Symbol& symbol) { +std::vector GetIdentifiersFromDataDeclaration( + const Symbol &symbol) { // TODO(fangism): leverage GetInstanceListFromDataDeclaration(). // Instead of searching, use direct access. See CST/declaration.h. - std::vector identifiers; + std::vector identifiers; auto matcher = verible::matcher::Matcher(ExpectedTagPredicate, verible::matcher::InnerMatchAll); @@ -61,11 +61,11 @@ std::vector GetIdentifiersFromDataDeclaration( std::vector identifier_nodes = SearchSyntaxTree(symbol, matcher); - for (auto& id : identifier_nodes) { - const auto* identifier = SymbolCastToNode(*id.match)[0].get(); + for (auto &id : identifier_nodes) { + const auto *identifier = SymbolCastToNode(*id.match)[0].get(); if (!identifier) continue; - const auto* identifier_leaf = AutoUnwrapIdentifier(*identifier); + const auto *identifier_leaf = AutoUnwrapIdentifier(*identifier); identifiers.push_back(&identifier_leaf->get()); } diff --git a/verilog/CST/data.h b/verilog/CST/data.h index f491de3df..287adcc67 100644 --- a/verilog/CST/data.h +++ b/verilog/CST/data.h @@ -27,8 +27,8 @@ namespace verilog { // Returns tokens that correspond to declared names in data declarations -std::vector GetIdentifiersFromDataDeclaration( - const verible::Symbol& symbol); +std::vector GetIdentifiersFromDataDeclaration( + const verible::Symbol &symbol); } // namespace verilog diff --git a/verilog/CST/data_test.cc b/verilog/CST/data_test.cc index 4f4e93d37..263d0422f 100644 --- a/verilog/CST/data_test.cc +++ b/verilog/CST/data_test.cc @@ -42,7 +42,7 @@ namespace { TEST(GetIdentifiersFromDataDeclarationTest, EmptySource) { VerilogAnalyzer analyzer("", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto data_declarations = GetIdentifiersFromDataDeclaration(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(data_declarations.empty()); @@ -51,7 +51,7 @@ TEST(GetIdentifiersFromDataDeclarationTest, EmptySource) { TEST(GetIdentifiersFromDataDeclarationTest, NoData) { VerilogAnalyzer analyzer("module foo; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto data_declarations = GetIdentifiersFromDataDeclaration(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(data_declarations.empty()); @@ -60,7 +60,7 @@ TEST(GetIdentifiersFromDataDeclarationTest, NoData) { TEST(GetIdentifiersFromDataDeclarationTest, OneVariable) { VerilogAnalyzer analyzer("module foo; logic v; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto data_declarations = GetIdentifiersFromDataDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(data_declarations.size(), 1); @@ -70,7 +70,7 @@ TEST(GetIdentifiersFromDataDeclarationTest, OneVariable) { TEST(GetIdentifiersFromDataDeclarationTest, MultipleVariables) { VerilogAnalyzer analyzer("module foo; logic x; logic y; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto data_declarations = GetIdentifiersFromDataDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(data_declarations.size(), 2); @@ -81,7 +81,7 @@ TEST(GetIdentifiersFromDataDeclarationTest, MultipleVariables) { TEST(GetIdentifiersFromDataDeclarationTest, MultipleInlineVariables) { VerilogAnalyzer analyzer("module foo; logic x, y, z; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto data_declarations = GetIdentifiersFromDataDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(data_declarations.size(), 3); @@ -93,7 +93,7 @@ TEST(GetIdentifiersFromDataDeclarationTest, MultipleInlineVariables) { TEST(GetIdentifiersFromDataDeclarationTest, MultipleMixedVariables) { VerilogAnalyzer analyzer("module foo; logic x, y, z; logic a; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto data_declarations = GetIdentifiersFromDataDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(data_declarations.size(), 4); @@ -106,7 +106,7 @@ TEST(GetIdentifiersFromDataDeclarationTest, MultipleMixedVariables) { TEST(GetIdentifiersFromDataDeclarationTest, OneObjectVariable) { VerilogAnalyzer analyzer("module top; foo baz(0); endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto data_declarations = GetIdentifiersFromDataDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(data_declarations.size(), 1); @@ -116,7 +116,7 @@ TEST(GetIdentifiersFromDataDeclarationTest, OneObjectVariable) { TEST(GetIdentifiersFromDataDeclarationTest, MultipleObjectVariables) { VerilogAnalyzer analyzer("module top; foo baz(0); foo bay(1); endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto data_declarations = GetIdentifiersFromDataDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(data_declarations.size(), 2); @@ -127,7 +127,7 @@ TEST(GetIdentifiersFromDataDeclarationTest, MultipleObjectVariables) { TEST(GetIdentifiersFromDataDeclarationTest, MultipleInlineObjectVariables) { VerilogAnalyzer analyzer("module top; foo baz(0), bay(1); endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto data_declarations = GetIdentifiersFromDataDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(data_declarations.size(), 2); @@ -145,7 +145,7 @@ logic b, c; endmodule)", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto data_declarations = GetIdentifiersFromDataDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(data_declarations.size(), 6); @@ -160,7 +160,7 @@ endmodule)", TEST(GetIdentifiersFromDataDeclarationTest, DoNotMatchArrayDeclarations) { VerilogAnalyzer analyzer("module top; logic v[M:N]; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto data_declarations = GetIdentifiersFromDataDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(data_declarations.size(), 1); @@ -170,7 +170,7 @@ TEST(GetIdentifiersFromDataDeclarationTest, DoNotMatchArrayDeclarations) { TEST(GetIdentifiersFromDataDeclarationTest, DoNotMatchAssignedVariables) { VerilogAnalyzer analyzer("module top; logic v = z; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto data_declarations = GetIdentifiersFromDataDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(data_declarations.size(), 1); diff --git a/verilog/CST/declaration.cc b/verilog/CST/declaration.cc index 4a81009e2..10baddf92 100644 --- a/verilog/CST/declaration.cc +++ b/verilog/CST/declaration.cc @@ -38,7 +38,7 @@ using verible::SyntaxTreeNode; using verible::container::FindWithDefault; SymbolPtr RepackReturnTypeId(SymbolPtr type_id_tuple) { - auto& node = CheckSymbolAsNode(*type_id_tuple, + auto &node = CheckSymbolAsNode(*type_id_tuple, NodeEnum::kDataTypeImplicitBasicIdDimensions); return verible::MakeNode(std::move(node[0]) /* type */, std::move(node[1]) /* id */); @@ -46,8 +46,8 @@ SymbolPtr RepackReturnTypeId(SymbolPtr type_id_tuple) { // syntactically valid. } -NodeEnum DeclarationKeywordToNodeEnum(const Symbol& symbol) { - static const auto* node_map = new std::map{ +NodeEnum DeclarationKeywordToNodeEnum(const Symbol &symbol) { + static const auto *node_map = new std::map{ {TK_module, NodeEnum::kModuleDeclaration}, {TK_macromodule, NodeEnum::kMacroModuleDeclaration}, {TK_program, NodeEnum::kProgramDeclaration}, @@ -60,90 +60,90 @@ NodeEnum DeclarationKeywordToNodeEnum(const Symbol& symbol) { } std::vector FindAllDataDeclarations( - const Symbol& root) { + const Symbol &root) { return SearchSyntaxTree(root, NodekDataDeclaration()); } -std::vector FindAllNetVariables(const Symbol& root) { +std::vector FindAllNetVariables(const Symbol &root) { return SearchSyntaxTree(root, NodekNetVariable()); } std::vector FindAllRegisterVariables( - const Symbol& root) { + const Symbol &root) { return SearchSyntaxTree(root, NodekRegisterVariable()); } -std::vector FindAllGateInstances(const Symbol& root) { +std::vector FindAllGateInstances(const Symbol &root) { return SearchSyntaxTree(root, NodekGateInstance()); } std::vector FindAllVariableDeclarationAssignment( - const verible::Symbol& root) { + const verible::Symbol &root) { return SearchSyntaxTree(root, NodekVariableDeclarationAssignment()); } // Don't want to expose kInstantiationBase because it is an artificial grouping. -static const SyntaxTreeNode* GetInstantiationBaseFromDataDeclaration( - const Symbol& data_declaration) { +static const SyntaxTreeNode *GetInstantiationBaseFromDataDeclaration( + const Symbol &data_declaration) { return GetSubtreeAsNode(data_declaration, NodeEnum::kDataDeclaration, 1, NodeEnum::kInstantiationBase); } -const SyntaxTreeNode* GetQualifiersOfDataDeclaration( - const Symbol& data_declaration) { - const auto* quals = +const SyntaxTreeNode *GetQualifiersOfDataDeclaration( + const Symbol &data_declaration) { + const auto *quals = GetSubtreeAsSymbol(data_declaration, NodeEnum::kDataDeclaration, 0); return verible::CheckOptionalSymbolAsNode(quals, NodeEnum::kQualifierList); } -const SyntaxTreeNode* GetInstantiationTypeOfDataDeclaration( - const Symbol& data_declaration) { - const auto* base = GetInstantiationBaseFromDataDeclaration(data_declaration); +const SyntaxTreeNode *GetInstantiationTypeOfDataDeclaration( + const Symbol &data_declaration) { + const auto *base = GetInstantiationBaseFromDataDeclaration(data_declaration); if (!base) return nullptr; return GetSubtreeAsNode(*base, NodeEnum::kInstantiationBase, 0); } -const SyntaxTreeNode* GetInstanceListFromDataDeclaration( - const Symbol& data_declaration) { - const auto* base = GetInstantiationBaseFromDataDeclaration(data_declaration); +const SyntaxTreeNode *GetInstanceListFromDataDeclaration( + const Symbol &data_declaration) { + const auto *base = GetInstantiationBaseFromDataDeclaration(data_declaration); if (!base) return nullptr; return GetSubtreeAsNode(*base, NodeEnum::kInstantiationBase, 1); } -const verible::SyntaxTreeNode* GetParamListFromDataDeclaration( - const verible::Symbol& data_declaration) { - const SyntaxTreeNode* instantiation_type = +const verible::SyntaxTreeNode *GetParamListFromDataDeclaration( + const verible::Symbol &data_declaration) { + const SyntaxTreeNode *instantiation_type = GetInstantiationTypeOfDataDeclaration(data_declaration); if (!instantiation_type) return nullptr; return GetParamListFromInstantiationType(*instantiation_type); } -const verible::TokenInfo* GetModuleInstanceNameTokenInfoFromGateInstance( - const verible::Symbol& gate_instance) { - const verible::SyntaxTreeLeaf* instance_name = +const verible::TokenInfo *GetModuleInstanceNameTokenInfoFromGateInstance( + const verible::Symbol &gate_instance) { + const verible::SyntaxTreeLeaf *instance_name = GetSubtreeAsLeaf(gate_instance, NodeEnum::kGateInstance, 0); if (!instance_name) return nullptr; return &instance_name->get(); } -const verible::TokenInfo* GetInstanceNameTokenInfoFromRegisterVariable( - const verible::Symbol& regiseter_variable) { - const verible::SyntaxTreeLeaf* instance_name = +const verible::TokenInfo *GetInstanceNameTokenInfoFromRegisterVariable( + const verible::Symbol ®iseter_variable) { + const verible::SyntaxTreeLeaf *instance_name = GetSubtreeAsLeaf(regiseter_variable, NodeEnum::kRegisterVariable, 0); if (!instance_name) return nullptr; return &instance_name->get(); } -const verible::SyntaxTreeNode* GetParenGroupFromModuleInstantiation( - const verible::Symbol& gate_instance) { +const verible::SyntaxTreeNode *GetParenGroupFromModuleInstantiation( + const verible::Symbol &gate_instance) { return GetSubtreeAsNode(gate_instance, NodeEnum::kGateInstance, 2, NodeEnum::kParenGroup); } -const verible::SyntaxTreeLeaf* +const verible::SyntaxTreeLeaf * GetUnqualifiedIdFromVariableDeclarationAssignment( - const verible::Symbol& variable_declaration_assign) { - const verible::Symbol* identifier = GetSubtreeAsSymbol( + const verible::Symbol &variable_declaration_assign) { + const verible::Symbol *identifier = GetSubtreeAsSymbol( variable_declaration_assign, NodeEnum::kVariableDeclarationAssignment, 0); if (!identifier) return nullptr; if (identifier->Kind() == verible::SymbolKind::kLeaf) { @@ -156,70 +156,70 @@ GetUnqualifiedIdFromVariableDeclarationAssignment( return AutoUnwrapIdentifier(*identifier); } -const verible::SyntaxTreeNode* +const verible::SyntaxTreeNode * GetTrailingExpressionFromVariableDeclarationAssign( - const verible::Symbol& variable_declaration_assign) { - const Symbol* trailing_expression = GetSubtreeAsSymbol( + const verible::Symbol &variable_declaration_assign) { + const Symbol *trailing_expression = GetSubtreeAsSymbol( variable_declaration_assign, NodeEnum::kVariableDeclarationAssignment, 2); return verible::CheckOptionalSymbolAsNode(trailing_expression, NodeEnum::kTrailingAssign); } -const verible::SyntaxTreeNode* GetTrailingExpressionFromRegisterVariable( - const verible::Symbol& register_variable) { - const Symbol* trailing_expression = +const verible::SyntaxTreeNode *GetTrailingExpressionFromRegisterVariable( + const verible::Symbol ®ister_variable) { + const Symbol *trailing_expression = GetSubtreeAsSymbol(register_variable, NodeEnum::kRegisterVariable, 2); return verible::CheckOptionalSymbolAsNode(trailing_expression, NodeEnum::kTrailingAssign); } -const verible::SyntaxTreeNode* GetPackedDimensionFromDataDeclaration( - const verible::Symbol& data_declaration) { - const verible::SyntaxTreeNode* instantiation_type = +const verible::SyntaxTreeNode *GetPackedDimensionFromDataDeclaration( + const verible::Symbol &data_declaration) { + const verible::SyntaxTreeNode *instantiation_type = GetInstantiationTypeOfDataDeclaration(data_declaration); if (!instantiation_type) return nullptr; - const verible::Symbol* data_type = verible::GetSubtreeAsSymbol( + const verible::Symbol *data_type = verible::GetSubtreeAsSymbol( *instantiation_type, NodeEnum::kInstantiationType, 0); if (data_type == nullptr) return nullptr; return GetPackedDimensionFromDataType(*data_type); } -const verible::SyntaxTreeNode* GetUnpackedDimensionFromRegisterVariable( - const verible::Symbol& register_variable) { +const verible::SyntaxTreeNode *GetUnpackedDimensionFromRegisterVariable( + const verible::Symbol ®ister_variable) { return verible::GetSubtreeAsNode(register_variable, NodeEnum::kRegisterVariable, 1, NodeEnum::kUnpackedDimensions); } -const verible::SyntaxTreeNode* +const verible::SyntaxTreeNode * GetUnpackedDimensionFromVariableDeclarationAssign( - const verible::Symbol& variable_declaration_assign) { + const verible::Symbol &variable_declaration_assign) { return verible::GetSubtreeAsNode(variable_declaration_assign, NodeEnum::kVariableDeclarationAssignment, 1, NodeEnum::kUnpackedDimensions); } -const verible::Symbol* GetTypeIdentifierFromDataDeclaration( - const verible::Symbol& data_declaration) { - const SyntaxTreeNode* instantiation_type = +const verible::Symbol *GetTypeIdentifierFromDataDeclaration( + const verible::Symbol &data_declaration) { + const SyntaxTreeNode *instantiation_type = GetInstantiationTypeOfDataDeclaration(data_declaration); if (!instantiation_type) return nullptr; - const verible::Symbol* identifier = + const verible::Symbol *identifier = GetTypeIdentifierFromInstantiationType(*instantiation_type); if (identifier != nullptr) { return identifier; } - const verible::Symbol* base_type = + const verible::Symbol *base_type = GetBaseTypeFromInstantiationType(*instantiation_type); if (base_type == nullptr) return nullptr; return GetTypeIdentifierFromBaseType(*base_type); } -const verible::SyntaxTreeNode* GetStructOrUnionOrEnumTypeFromDataDeclaration( - const verible::Symbol& data_declaration) { - const SyntaxTreeNode* instantiation_type = +const verible::SyntaxTreeNode *GetStructOrUnionOrEnumTypeFromDataDeclaration( + const verible::Symbol &data_declaration) { + const SyntaxTreeNode *instantiation_type = GetInstantiationTypeOfDataDeclaration(data_declaration); if (!instantiation_type) return nullptr; return GetStructOrUnionOrEnumTypeFromInstantiationType(*instantiation_type); diff --git a/verilog/CST/declaration.h b/verilog/CST/declaration.h index 015534d9d..c212bd91b 100644 --- a/verilog/CST/declaration.h +++ b/verilog/CST/declaration.h @@ -31,8 +31,8 @@ namespace verilog { // Interface for consistently building a type-id-dimensions tuple. template -verible::SymbolPtr MakeTypeIdDimensionsTuple(T1&& type, T2&& id, - T3&& unpacked_dimensions) { +verible::SymbolPtr MakeTypeIdDimensionsTuple(T1 &&type, T2 &&id, + T3 &&unpacked_dimensions) { verible::CheckSymbolAsNode(*type.get(), NodeEnum::kDataType); // id can be qualified or unqualified verible::CheckOptionalSymbolAsNode(unpacked_dimensions, @@ -46,7 +46,7 @@ verible::SymbolPtr MakeTypeIdDimensionsTuple(T1&& type, T2&& id, // TODO(fangism): combine this with MakeTypeIdDimensionsTuple above? // That would be one fewer auxiliary CST node type. template -verible::SymbolPtr MakeTypeIdTuple(T1&& type, T2&& id) { +verible::SymbolPtr MakeTypeIdTuple(T1 &&type, T2 &&id) { verible::CheckSymbolAsNode(*type.get(), NodeEnum::kDataType); verible::CheckSymbolAsNode(*id.get(), NodeEnum::kUnqualifiedId); return verible::MakeTaggedNode(NodeEnum::kTypeIdentifierId, @@ -58,10 +58,10 @@ verible::SymbolPtr RepackReturnTypeId(verible::SymbolPtr type_id_tuple); // Maps lexical token enum to corresponding syntax tree node. // Useful for syntax tree construction. -NodeEnum DeclarationKeywordToNodeEnum(const verible::Symbol&); +NodeEnum DeclarationKeywordToNodeEnum(const verible::Symbol &); template -verible::SymbolPtr MakeInstantiationBase(T1&& type, T2&& decl_list) { +verible::SymbolPtr MakeInstantiationBase(T1 &&type, T2 &&decl_list) { verible::CheckSymbolAsNode(*type.get(), NodeEnum::kInstantiationType); // decl_list could contain either instantiations or variable declarations return verible::MakeTaggedNode(NodeEnum::kInstantiationBase, @@ -71,8 +71,8 @@ verible::SymbolPtr MakeInstantiationBase(T1&& type, T2&& decl_list) { // Interface for consistently building a data declaration. template -verible::SymbolPtr MakeDataDeclaration(T1&& qualifiers, T2&& inst_base, - T3&& semicolon) { +verible::SymbolPtr MakeDataDeclaration(T1 &&qualifiers, T2 &&inst_base, + T3 &&semicolon) { verible::CheckOptionalSymbolAsNode(qualifiers, NodeEnum::kQualifierList); if (inst_base.get()->Tag().tag == (int)NodeEnum::kFunctionCall) { return verible::ExtendNode(std::forward(inst_base), @@ -87,100 +87,100 @@ verible::SymbolPtr MakeDataDeclaration(T1&& qualifiers, T2&& inst_base, // Find all data declarations. std::vector FindAllDataDeclarations( - const verible::Symbol&); + const verible::Symbol &); std::vector FindAllNetVariables( - const verible::Symbol&); + const verible::Symbol &); std::vector FindAllRegisterVariables( - const verible::Symbol&); + const verible::Symbol &); std::vector FindAllGateInstances( - const verible::Symbol&); + const verible::Symbol &); std::vector FindAllVariableDeclarationAssignment( - const verible::Symbol&); + const verible::Symbol &); // For a given data declaration (includes module instantiation), returns the // subtree containing qualifiers. e.g. from "const foo bar, baz;", // this returns the subtree spanning "const". Returns nullptr if there // are no qualifiers. -const verible::SyntaxTreeNode* GetQualifiersOfDataDeclaration( - const verible::Symbol& data_declaration); +const verible::SyntaxTreeNode *GetQualifiersOfDataDeclaration( + const verible::Symbol &data_declaration); // For a given data declaration (includes module instantiation), returns the // subtree containing the type. e.g. from "foo #(...) bar..., baz...;", // this returns the subtree spanning "foo #(...)". // It is possible for type to be implicit, in which case, the node // will be an empty subtree. -const verible::SyntaxTreeNode* GetInstantiationTypeOfDataDeclaration( - const verible::Symbol& data_declaration); +const verible::SyntaxTreeNode *GetInstantiationTypeOfDataDeclaration( + const verible::Symbol &data_declaration); // For a given data declaration returns the node spanning param declaration // list. e.g "module_type #(N)" return the node for "#(N)". -const verible::SyntaxTreeNode* GetParamListFromDataDeclaration( - const verible::Symbol&); +const verible::SyntaxTreeNode *GetParamListFromDataDeclaration( + const verible::Symbol &); // For a given data declaration (includes module instantiation), returns the // subtree containing instances. e.g. from "foo bar..., baz...;", // this returns the subtree spanning "bar..., baz..." -const verible::SyntaxTreeNode* GetInstanceListFromDataDeclaration( - const verible::Symbol& data_declaration); +const verible::SyntaxTreeNode *GetInstanceListFromDataDeclaration( + const verible::Symbol &data_declaration); // For a given module gate instance return the node spanning the paren group. // e.g "module_type instance(a, b, c)" return the node spanning "(a, b, c)". -const verible::SyntaxTreeNode* GetParenGroupFromModuleInstantiation( - const verible::Symbol& gate_instance); +const verible::SyntaxTreeNode *GetParenGroupFromModuleInstantiation( + const verible::Symbol &gate_instance); // For a given gate instance subtree returns the TokenInfo of the module name. // e.g. "bar b1();" returns TokenInfo for "b1". -const verible::TokenInfo* GetModuleInstanceNameTokenInfoFromGateInstance( - const verible::Symbol&); +const verible::TokenInfo *GetModuleInstanceNameTokenInfoFromGateInstance( + const verible::Symbol &); // For a given register variable subtree returns the TokenInfo of the instance // name. e.g. "int b1;" returns TokenInfo for "b1". -const verible::TokenInfo* GetInstanceNameTokenInfoFromRegisterVariable( - const verible::Symbol&); +const verible::TokenInfo *GetInstanceNameTokenInfoFromRegisterVariable( + const verible::Symbol &); // For a given node tagged with kVariableDeclarationAssign return the // unqualified id inside that node. // e.g from "int x" or "logic x" or "bit x" return the leaf spanning "x". -const verible::SyntaxTreeLeaf* +const verible::SyntaxTreeLeaf * GetUnqualifiedIdFromVariableDeclarationAssignment( - const verible::Symbol& variable_declaration_assign); + const verible::Symbol &variable_declaration_assign); // Extracts kExpression node from nodes tagged with kVariableDeclarationAssign // (if exists). -const verible::SyntaxTreeNode* +const verible::SyntaxTreeNode * GetTrailingExpressionFromVariableDeclarationAssign( - const verible::Symbol& variable_declaration_assign); + const verible::Symbol &variable_declaration_assign); // Extracts kExpression node from nodes tagged with kRegisterVariable (if // exists). -const verible::SyntaxTreeNode* GetTrailingExpressionFromRegisterVariable( - const verible::Symbol& register_variable); +const verible::SyntaxTreeNode *GetTrailingExpressionFromRegisterVariable( + const verible::Symbol ®ister_variable); // Extracts kPackedDimensions node from nodes tagged with kDataDeclaration. -const verible::SyntaxTreeNode* GetPackedDimensionFromDataDeclaration( - const verible::Symbol& data_declaration); +const verible::SyntaxTreeNode *GetPackedDimensionFromDataDeclaration( + const verible::Symbol &data_declaration); // Extracts kUnpackedDimensions node from nodes tagged with kRegisterVariable. -const verible::SyntaxTreeNode* GetUnpackedDimensionFromRegisterVariable( - const verible::Symbol& register_variable); +const verible::SyntaxTreeNode *GetUnpackedDimensionFromRegisterVariable( + const verible::Symbol ®ister_variable); // Extracts kUnpackedDimensions node from nodes tagged with // kVariableDeclarationAssign. -const verible::SyntaxTreeNode* +const verible::SyntaxTreeNode * GetUnpackedDimensionFromVariableDeclarationAssign( - const verible::Symbol& variable_declaration_assign); + const verible::Symbol &variable_declaration_assign); // Returns the type name from data declaration (if exists). // The type can be inside a node tagged with kDataType or kLocalRoot. // e.g module_type m(); return "module_type". // e.g some_type m; return "some_type". -const verible::Symbol* GetTypeIdentifierFromDataDeclaration( - const verible::Symbol&); +const verible::Symbol *GetTypeIdentifierFromDataDeclaration( + const verible::Symbol &); // Returns the node tagged with kStructType, kEnumType or kUnionType from node // tagged with kDataDeclaration. -const verible::SyntaxTreeNode* GetStructOrUnionOrEnumTypeFromDataDeclaration( - const verible::Symbol&); +const verible::SyntaxTreeNode *GetStructOrUnionOrEnumTypeFromDataDeclaration( + const verible::Symbol &); } // namespace verilog diff --git a/verilog/CST/declaration_test.cc b/verilog/CST/declaration_test.cc index 91a2d17e7..c58dbee3d 100644 --- a/verilog/CST/declaration_test.cc +++ b/verilog/CST/declaration_test.cc @@ -58,10 +58,10 @@ TEST(FindAllDataDeclarations, CountMatches) { "\n" "endmodule\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root)); }); } @@ -95,10 +95,10 @@ TEST(FindAllNetVariablesTest, Various) { {"module m;\nlogic bar;\nendmodule\n"}, {"module m;\nreg bar;\nendmodule\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllNetVariables(*ABSL_DIE_IF_NULL(root)); }); } @@ -122,10 +122,10 @@ TEST(FindAllRegisterVariablesTest, Various) { ";\nendmodule\n"}, {"module m;\nwire bar;\nendmodule\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllRegisterVariables(*ABSL_DIE_IF_NULL(root)); }); } @@ -166,10 +166,10 @@ TEST(FindAllGateInstancesTest, Various) { {kTag, "blah()"}, ";\nendmodule\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllGateInstances(*ABSL_DIE_IF_NULL(root)); }); } @@ -210,15 +210,15 @@ TEST(FindAllGateInstancesTest, FindArgumentListOfGateInstance) { {kTag, "()"}, ";\nendmodule\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = FindAllGateInstances(*ABSL_DIE_IF_NULL(root)); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllGateInstances(*ABSL_DIE_IF_NULL(root)); std::vector paren_groups; - for (const auto& decl : instances) { - const auto* paren_group = + for (const auto &decl : instances) { + const auto *paren_group = GetParenGroupFromModuleInstantiation(*decl.match); paren_groups.emplace_back( TreeSearchMatch{paren_group, {/* ignored context */}}); @@ -255,18 +255,18 @@ TEST(GetQualifiersOfDataDeclarationTest, NoQualifiers) { "\n" "endtask\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); auto decls = FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root)); // Verify that quals is either nullptr or empty or contains only // nullptrs. - for (const auto& decl : decls) { - const auto* quals = GetQualifiersOfDataDeclaration(*decl.match); + for (const auto &decl : decls) { + const auto *quals = GetQualifiersOfDataDeclaration(*decl.match); if (quals != nullptr) { - for (const auto& child : quals->children()) { + for (const auto &child : quals->children()) { EXPECT_EQ(child, nullptr) << "unexpected qualifiers:\n" << verible::RawTreePrinter(*child) << "\nfailed on:\n" @@ -336,15 +336,15 @@ TEST(GetTypeOfDataDeclarationTest, ExplicitTypes) { "endfunction\n", "endclass\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector types; - for (const auto& decl : decls) { - const auto* type = + for (const auto &decl : decls) { + const auto *type = GetInstantiationTypeOfDataDeclaration(*decl.match); types.emplace_back(TreeSearchMatch{type, {/* ignored context */}}); } @@ -401,15 +401,15 @@ TEST(GetQualifiersOfDataDeclarationTest, SomeQualifiers) { "endfunction\n" "endclass\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector quals; - for (const auto& decl : decls) { - const auto* qual = GetQualifiersOfDataDeclaration(*decl.match); + for (const auto &decl : decls) { + const auto *qual = GetQualifiersOfDataDeclaration(*decl.match); if (qual != nullptr) { quals.push_back(TreeSearchMatch{qual, {/* ignored context */}}); } else { @@ -486,15 +486,15 @@ TEST(GetInstanceListFromDataDeclarationTest, InstanceLists) { ";\n" "endpackage\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector inst_lists; - for (const auto& decl : decls) { - const auto& insts = GetInstanceListFromDataDeclaration(*decl.match); + for (const auto &decl : decls) { + const auto &insts = GetInstanceListFromDataDeclaration(*decl.match); inst_lists.push_back( TreeSearchMatch{insts, {/* ignored context */}}); } @@ -546,16 +546,16 @@ TEST(GetVariableDeclarationAssign, VariableName) { ";\nendclass"}, // `branch` lexed as a (AMS) keyword, not identifier. {"class m;\n some_type ", {kTag, "branch"}, ";\nendclass"}}; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllVariableDeclarationAssignment(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& decl : decls) { - const auto* name = + for (const auto &decl : decls) { + const auto *name = GetUnqualifiedIdFromVariableDeclarationAssignment(*decl.match); names.emplace_back(TreeSearchMatch{name, {/* ignored context */}}); } @@ -577,16 +577,16 @@ TEST(GetTypeFromDeclaration, GetTypeName) { {kTag, "some_type"}, " x = new;\nendmodule"}, {"class x;\nvirtual ", {kTag, "y"}, " m;\nendclass"}}; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& decl : instances) { - const auto* name = + for (const auto &decl : instances) { + const auto *name = GetTypeIdentifierFromDataDeclaration(*decl.match); names.emplace_back(TreeSearchMatch{name, {/* ignored context */}}); } @@ -616,16 +616,16 @@ TEST(GetStructTypeFromDeclaration, GetStructOrUnionOrEnumType) { {kTag, "enum {x}"}, " var1;\nendpackage"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector types; - for (const auto& decl : instances) { - const auto* type = + for (const auto &decl : instances) { + const auto *type = GetStructOrUnionOrEnumTypeFromDataDeclaration(*decl.match); if (type == nullptr) { continue; @@ -659,16 +659,16 @@ TEST(GetVariableDeclarationAssign, {kTag, "= fun_call()"}, ";\nendclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllVariableDeclarationAssignment(*ABSL_DIE_IF_NULL(root)); std::vector paren_groups; - for (const auto& decl : instances) { - const auto* paren_group = + for (const auto &decl : instances) { + const auto *paren_group = GetTrailingExpressionFromVariableDeclarationAssign(*decl.match); paren_groups.emplace_back( TreeSearchMatch{paren_group, {/* ignored context */}}); @@ -708,16 +708,16 @@ TEST(FindAllRegisterVariablesTest, FindTrailingAssignOfRegisterVariable) { {kTag, "= fun_call()"}, ";\nreturn 1;\nendfunction"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllRegisterVariables(*ABSL_DIE_IF_NULL(root)); std::vector paren_groups; - for (const auto& decl : instances) { - const auto* paren_group = + for (const auto &decl : instances) { + const auto *paren_group = GetTrailingExpressionFromRegisterVariable(*decl.match); paren_groups.emplace_back( TreeSearchMatch{paren_group, {/* ignored context */}}); @@ -741,17 +741,17 @@ TEST(FindAllDataDeclarationTest, FindDataDeclarationParameters) { "y1();\nendmodule"}, {"module m;\n module_type ", {kTag, "#(x, y)"}, "y1();\nendmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VLOG(1) << "code:\n" << test.code; TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& decls = FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root)); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &decls = FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector params; - for (const auto& decl : decls) { + for (const auto &decl : decls) { VLOG(1) << "decl: " << verible::StringSpanOfSymbol(*decl.match); - const auto* param_list = + const auto *param_list = GetParamListFromDataDeclaration(*decl.match); if (param_list == nullptr) { continue; @@ -786,16 +786,16 @@ TEST(GetVariableDeclarationAssign, {kTag, "[k:y]"}, " = fun_call();\nendclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllVariableDeclarationAssignment(*ABSL_DIE_IF_NULL(root)); std::vector unpacked_dimensions; - for (const auto& decl : instances) { - const auto* unpacked_dimension = + for (const auto &decl : instances) { + const auto *unpacked_dimension = GetUnpackedDimensionFromVariableDeclarationAssign(*decl.match); unpacked_dimensions.emplace_back( TreeSearchMatch{unpacked_dimension, {/* ignored context */}}); @@ -846,16 +846,16 @@ TEST(FindAllRegisterVariablesTest, FindUnpackedDimensionOfRegisterVariable) { {kTag, "[k:y]"}, "= fun_call();\nreturn 1;\nendfunction"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllRegisterVariables(*ABSL_DIE_IF_NULL(root)); std::vector unpacked_dimensions; - for (const auto& decl : instances) { - const auto* unpacked_dimension = + for (const auto &decl : instances) { + const auto *unpacked_dimension = GetUnpackedDimensionFromRegisterVariable(*decl.match); unpacked_dimensions.emplace_back( TreeSearchMatch{unpacked_dimension, {/* ignored context */}}); @@ -921,17 +921,17 @@ TEST(GetVariableDeclaration, FindPackedDimensionFromDataDeclaration) { {"package c;\n bar#(foo)::baz ", {kTag, "[x+1][y-1]"}, " x;\nendpackage"}, {"class c;\n class_type x;\nendclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VLOG(1) << "code:\n" << test.code; TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector packed_dimensions; - for (const auto& decl : instances) { - const auto* packed_dimension = + for (const auto &decl : instances) { + const auto *packed_dimension = GetPackedDimensionFromDataDeclaration(*decl.match); if (packed_dimension == nullptr) { continue; diff --git a/verilog/CST/dimensions.cc b/verilog/CST/dimensions.cc index 265622bef..5aba38cee 100644 --- a/verilog/CST/dimensions.cc +++ b/verilog/CST/dimensions.cc @@ -29,25 +29,25 @@ namespace verilog { using verible::Symbol; std::vector FindAllPackedDimensions( - const Symbol& root) { + const Symbol &root) { return SearchSyntaxTree(root, NodekPackedDimensions()); } std::vector FindAllUnpackedDimensions( - const Symbol& root) { + const Symbol &root) { return SearchSyntaxTree(root, NodekUnpackedDimensions()); } std::vector FindAllDeclarationDimensions( - const Symbol& root) { + const Symbol &root) { return SearchSyntaxTree(root, NodekDeclarationDimensions()); } -const Symbol* GetDimensionRangeLeftBound(const Symbol& s) { +const Symbol *GetDimensionRangeLeftBound(const Symbol &s) { return verible::GetSubtreeAsSymbol(s, NodeEnum::kDimensionRange, 1); } -const Symbol* GetDimensionRangeRightBound(const verible::Symbol& s) { +const Symbol *GetDimensionRangeRightBound(const verible::Symbol &s) { return verible::GetSubtreeAsSymbol(s, NodeEnum::kDimensionRange, 3); } diff --git a/verilog/CST/dimensions.h b/verilog/CST/dimensions.h index 57c3705fe..3806ed718 100644 --- a/verilog/CST/dimensions.h +++ b/verilog/CST/dimensions.h @@ -28,24 +28,24 @@ namespace verilog { // Find all packed dimensions. std::vector FindAllPackedDimensions( - const verible::Symbol&); + const verible::Symbol &); // Find all unpacked dimensions. std::vector FindAllUnpackedDimensions( - const verible::Symbol&); + const verible::Symbol &); // Find all dimension sequences, which can appear in packed and unpacked // dimensions. std::vector FindAllDeclarationDimensions( - const verible::Symbol&); + const verible::Symbol &); // Returns x from [x:y] declared dimensions. Argument must be a DimensionRange // node. -const verible::Symbol* GetDimensionRangeLeftBound(const verible::Symbol&); +const verible::Symbol *GetDimensionRangeLeftBound(const verible::Symbol &); // Returns y from [x:y] declared dimensions. Argument must be a DimensionRange // node. -const verible::Symbol* GetDimensionRangeRightBound(const verible::Symbol&); +const verible::Symbol *GetDimensionRangeRightBound(const verible::Symbol &); } // namespace verilog diff --git a/verilog/CST/dimensions_test.cc b/verilog/CST/dimensions_test.cc index d4a61b1e6..27ab7a12f 100644 --- a/verilog/CST/dimensions_test.cc +++ b/verilog/CST/dimensions_test.cc @@ -45,7 +45,7 @@ using verible::down_cast; using verible::SyntaxTreeLeaf; struct MatchTestCase { - const char* code; + const char *code; int expect_packed_matches; int expect_unpacked_matches; }; @@ -166,27 +166,27 @@ static const MatchTestCase kMatchTestCases[] = { // {"parameter int p[0:1] = {0,2}, q[0:1] = {1,3};", 0, 2}, }; -static size_t ExtractNumDimensions(const verible::Symbol* root) { +static size_t ExtractNumDimensions(const verible::Symbol *root) { if (root == nullptr) return 0; const auto matches = FindAllDeclarationDimensions(*root); if (matches.empty()) return 0; // Only extract from the first match. if (matches[0].match == nullptr) return 0; - const auto& s = *matches[0].match; - return (down_cast(s).children()).size(); + const auto &s = *matches[0].match; + return (down_cast(s).children()).size(); } // Test that number of sets of packed dimensions found is correct. TEST(FindAllPackedDimensionsTest, MatchCounts) { - for (const auto& test : kMatchTestCases) { + for (const auto &test : kMatchTestCases) { VerilogAnalyzer analyzer(test.code, ""); ASSERT_OK(analyzer.Analyze()) << "Failed test code: " << test.code; - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto packed_dimensions = FindAllPackedDimensions(*ABSL_DIE_IF_NULL(root)); const int nonempty_packed_dimensions = std::count_if(packed_dimensions.begin(), packed_dimensions.end(), - [](const verible::TreeSearchMatch& m) { + [](const verible::TreeSearchMatch &m) { return ExtractNumDimensions(m.match) > 0; }); EXPECT_EQ(nonempty_packed_dimensions, test.expect_packed_matches) @@ -196,15 +196,15 @@ TEST(FindAllPackedDimensionsTest, MatchCounts) { // Test that number of sets of unpacked dimensions found is correct. TEST(FindAllUnpackedDimensionsTest, MatchCounts) { - for (const auto& test : kMatchTestCases) { + for (const auto &test : kMatchTestCases) { VerilogAnalyzer analyzer(test.code, ""); ASSERT_OK(analyzer.Analyze()) << "Failed test code: " << test.code; - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto unpacked_dimensions = FindAllUnpackedDimensions(*ABSL_DIE_IF_NULL(root)); const int nonempty_unpacked_dimensions = std::count_if(unpacked_dimensions.begin(), unpacked_dimensions.end(), - [](const verible::TreeSearchMatch& m) { + [](const verible::TreeSearchMatch &m) { return ExtractNumDimensions(m.match) > 0; }); EXPECT_EQ(nonempty_unpacked_dimensions, test.expect_unpacked_matches) @@ -213,7 +213,7 @@ TEST(FindAllUnpackedDimensionsTest, MatchCounts) { } struct DimensionTestCase { - const char* code; + const char *code; int expect_dimensions; }; @@ -227,19 +227,19 @@ TEST(ExtractNumDimensionsTest, DimensionCounts) { {"wire w [2];", 1}, {"wire w [3][5];", 2}, {"wire w [];", 1}, }; - for (const auto& test : kDimensionTestCases) { + for (const auto &test : kDimensionTestCases) { VerilogAnalyzer analyzer(test.code, ""); ASSERT_OK(analyzer.Analyze()) << "Failed test code: " << test.code; - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); EXPECT_EQ(ExtractNumDimensions(root.get()), test.expect_dimensions) << "Failed test code: " << test.code; } } struct RangeTestCase { - const char* code; - const char* expect_left; - const char* expect_right; + const char *code; + const char *expect_left; + const char *expect_right; }; // Each of these test cases should have exactly one ranged-dimension. @@ -252,31 +252,31 @@ static const RangeTestCase kRangeTestCases[] = { // Test that left-expression of dimension range is extracted correctly. TEST(GetDimensionRangeLeftBoundTest, CheckBounds) { - for (const auto& test : kRangeTestCases) { + for (const auto &test : kRangeTestCases) { VerilogAnalyzer analyzer(test.code, ""); ASSERT_OK(analyzer.Analyze()) << "Failed test code: " << test.code; - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto range_matches = SearchSyntaxTree(*ABSL_DIE_IF_NULL(root), NodekDimensionRange()); ASSERT_EQ(range_matches.size(), 1); - const auto* left = GetDimensionRangeLeftBound(*range_matches.front().match); - const SyntaxTreeLeaf* left_leaf = verible::GetLeftmostLeaf(*left); + const auto *left = GetDimensionRangeLeftBound(*range_matches.front().match); + const SyntaxTreeLeaf *left_leaf = verible::GetLeftmostLeaf(*left); EXPECT_EQ(ABSL_DIE_IF_NULL(left_leaf)->get().text(), test.expect_left); } } // Test that right-expression of dimension range is extracted correctly. TEST(GetDimensionRangeRightBoundTest, CheckBounds) { - for (const auto& test : kRangeTestCases) { + for (const auto &test : kRangeTestCases) { VerilogAnalyzer analyzer(test.code, ""); ASSERT_OK(analyzer.Analyze()) << "Failed test code: " << test.code; - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto range_matches = SearchSyntaxTree(*ABSL_DIE_IF_NULL(root), NodekDimensionRange()); ASSERT_EQ(range_matches.size(), 1); - const auto* right = + const auto *right = GetDimensionRangeRightBound(*range_matches.front().match); - const SyntaxTreeLeaf* right_leaf = verible::GetLeftmostLeaf(*right); + const SyntaxTreeLeaf *right_leaf = verible::GetLeftmostLeaf(*right); EXPECT_EQ(ABSL_DIE_IF_NULL(right_leaf)->get().text(), test.expect_right); } } diff --git a/verilog/CST/expression.cc b/verilog/CST/expression.cc index 1693533d1..d864cc1d4 100644 --- a/verilog/CST/expression.cc +++ b/verilog/CST/expression.cc @@ -41,78 +41,78 @@ using verible::SyntaxTreeLeaf; using verible::SyntaxTreeNode; using verible::TreeSearchMatch; -bool IsExpression(const verible::SymbolPtr& symbol_ptr) { +bool IsExpression(const verible::SymbolPtr &symbol_ptr) { if (symbol_ptr == nullptr) return false; if (symbol_ptr->Kind() != SymbolKind::kNode) return false; - const auto& node = down_cast(*symbol_ptr); + const auto &node = down_cast(*symbol_ptr); return node.MatchesTag(NodeEnum::kExpression); } -bool IsZero(const Symbol& expr) { - const Symbol* child = verible::DescendThroughSingletons(expr); +bool IsZero(const Symbol &expr) { + const Symbol *child = verible::DescendThroughSingletons(expr); int value; if (ConstantIntegerValue(*child, &value)) { return value == 0; } if (child->Kind() != SymbolKind::kLeaf) return false; - const auto& term = down_cast(*child); + const auto &term = down_cast(*child); auto text = term.get().text(); // TODO(fangism): Could do more sophisticated constant expression evaluation // but for now this is a good first implementation. return (text == "\'0"); } -bool ConstantIntegerValue(const verible::Symbol& expr, int* value) { - const Symbol* child = verible::DescendThroughSingletons(expr); +bool ConstantIntegerValue(const verible::Symbol &expr, int *value) { + const Symbol *child = verible::DescendThroughSingletons(expr); if (child->Kind() != SymbolKind::kLeaf) return false; - const auto& term = down_cast(*child); + const auto &term = down_cast(*child); // Don't even need to check the leaf token's enumeration type. auto text = term.get().text(); return absl::SimpleAtoi(text, value); } -const verible::Symbol* UnwrapExpression(const verible::Symbol& expr) { +const verible::Symbol *UnwrapExpression(const verible::Symbol &expr) { if (expr.Kind() == SymbolKind::kLeaf) return &expr; - const auto& node = verible::SymbolCastToNode(expr); + const auto &node = verible::SymbolCastToNode(expr); const auto tag = static_cast(node.Tag().tag); if (tag != NodeEnum::kExpression) return &expr; - const auto& children = node.children(); + const auto &children = node.children(); return children.front().get(); } -const verible::Symbol* GetConditionExpressionPredicate( - const verible::Symbol& condition_expr) { +const verible::Symbol *GetConditionExpressionPredicate( + const verible::Symbol &condition_expr) { return GetSubtreeAsSymbol(condition_expr, NodeEnum::kConditionExpression, 0); } -const verible::Symbol* GetConditionExpressionTrueCase( - const verible::Symbol& condition_expr) { +const verible::Symbol *GetConditionExpressionTrueCase( + const verible::Symbol &condition_expr) { return GetSubtreeAsSymbol(condition_expr, NodeEnum::kConditionExpression, 2); } -const verible::Symbol* GetConditionExpressionFalseCase( - const verible::Symbol& condition_expr) { +const verible::Symbol *GetConditionExpressionFalseCase( + const verible::Symbol &condition_expr) { return GetSubtreeAsSymbol(condition_expr, NodeEnum::kConditionExpression, 4); } -const verible::TokenInfo* GetUnaryPrefixOperator( - const verible::Symbol& symbol) { - const SyntaxTreeNode* node = symbol.Kind() == SymbolKind::kNode +const verible::TokenInfo *GetUnaryPrefixOperator( + const verible::Symbol &symbol) { + const SyntaxTreeNode *node = symbol.Kind() == SymbolKind::kNode ? &verible::SymbolCastToNode(symbol) : nullptr; if (!node || !MatchNodeEnumOrNull(*node, NodeEnum::kUnaryPrefixExpression)) { return nullptr; } - const verible::Symbol* leaf_symbol = node->children().front().get(); - return &verible::down_cast(leaf_symbol) + const verible::Symbol *leaf_symbol = node->children().front().get(); + return &verible::down_cast(leaf_symbol) ->get(); } -const verible::Symbol* GetUnaryPrefixOperand(const verible::Symbol& symbol) { - const SyntaxTreeNode* node = symbol.Kind() == SymbolKind::kNode +const verible::Symbol *GetUnaryPrefixOperand(const verible::Symbol &symbol) { + const SyntaxTreeNode *node = symbol.Kind() == SymbolKind::kNode ? &verible::SymbolCastToNode(symbol) : nullptr; if (!node || !MatchNodeEnumOrNull(*node, NodeEnum::kUnaryPrefixExpression)) { @@ -122,21 +122,21 @@ const verible::Symbol* GetUnaryPrefixOperand(const verible::Symbol& symbol) { } std::vector FindAllBinaryOperations( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekBinaryExpression()); } std::vector FindAllConditionExpressions( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekConditionExpression()); } std::vector FindAllReferenceFullExpressions( - const verible::Symbol& root) { + const verible::Symbol &root) { auto references = verible::SearchSyntaxTree(root, NodekReference()); auto reference_calls = verible::SearchSyntaxTree(root, NodekReferenceCallBase()); - for (auto& reference : references) { + for (auto &reference : references) { if (!(reference.context.DirectParentIs(NodeEnum::kReferenceCallBase))) { reference_calls.emplace_back(reference); } @@ -144,23 +144,23 @@ std::vector FindAllReferenceFullExpressions( return reference_calls; } -static const verible::TokenInfo* ReferenceBaseIsSimple( - const verible::SyntaxTreeNode& reference_base) { - const Symbol* bottom = verible::DescendThroughSingletons(reference_base); +static const verible::TokenInfo *ReferenceBaseIsSimple( + const verible::SyntaxTreeNode &reference_base) { + const Symbol *bottom = verible::DescendThroughSingletons(reference_base); if (!bottom) return nullptr; const auto tag = bottom->Tag(); if (tag.kind == verible::SymbolKind::kLeaf) { - const auto& token(verible::SymbolCastToLeaf(*bottom).get()); + const auto &token(verible::SymbolCastToLeaf(*bottom).get()); return token.token_enum() == SymbolIdentifier ? &token : nullptr; } // Expect to hit kUnqualifiedId, which has two children. // child[0] should be a SymbolIdentifier (or similar) token. // child[1] are optional #(parameters), which would imply child[0] is // referring to a parameterized type. - const auto& unqualified_id( + const auto &unqualified_id( verible::CheckSymbolAsNode(*bottom, NodeEnum::kUnqualifiedId)); - const auto* params = GetParamListFromUnqualifiedId(unqualified_id); + const auto *params = GetParamListFromUnqualifiedId(unqualified_id); // If there are parameters, it is not simple reference. // It is most likely a class-qualified static reference. return params == nullptr @@ -169,19 +169,19 @@ static const verible::TokenInfo* ReferenceBaseIsSimple( : nullptr; } -const verible::TokenInfo* ReferenceIsSimpleIdentifier( - const verible::Symbol& reference) { +const verible::TokenInfo *ReferenceIsSimpleIdentifier( + const verible::Symbol &reference) { // remove calls since they are not simple - but a ReferenceCallBase can be // just a reference, depending on where it is placed in the code if (reference.Tag().tag == (int)NodeEnum::kReferenceCallBase) return nullptr; - const auto& reference_node( + const auto &reference_node( verible::CheckSymbolAsNode(reference, NodeEnum::kReference)); // A simple reference contains one component without hierarchy, indexing, or // calls; it looks like just an identifier. if (reference_node.children().size() > 1) return nullptr; - const auto& base_symbol = reference_node.children().front(); + const auto &base_symbol = reference_node.children().front(); if (!base_symbol) return nullptr; - const auto& base_node = verible::SymbolCastToNode(*base_symbol); + const auto &base_node = verible::SymbolCastToNode(*base_symbol); if (!base_node.MatchesTag(NodeEnum::kLocalRoot)) return nullptr; return ReferenceBaseIsSimple(base_node); } diff --git a/verilog/CST/expression.h b/verilog/CST/expression.h index 4cf106e60..e872c354b 100644 --- a/verilog/CST/expression.h +++ b/verilog/CST/expression.h @@ -32,18 +32,18 @@ namespace verilog { // Example usage: $$ = MakeBinaryExpression($1, $2, $3); template -verible::SymbolPtr MakeBinaryExpression(T1&& lhs, T2&& op, T3&& rhs) { - const verible::SyntaxTreeLeaf& this_op(SymbolCastToLeaf(*op)); +verible::SymbolPtr MakeBinaryExpression(T1 &&lhs, T2 &&op, T3 &&rhs) { + const verible::SyntaxTreeLeaf &this_op(SymbolCastToLeaf(*op)); const auto this_tag = verilog_tokentype(this_op.Tag().tag); // If parent (lhs) operator is associative and matches this one, // then flatten them into the same set of siblings. // This prevents excessive tree depth for long associative expressions. if (IsAssociativeOperator(this_tag) && lhs->Kind() == verible::SymbolKind::kNode) { - const auto& lhs_node = - verible::down_cast(*lhs); + const auto &lhs_node = + verible::down_cast(*lhs); if (lhs_node.MatchesTag(NodeEnum::kBinaryExpression)) { - const verible::SyntaxTreeLeaf& lhs_op = + const verible::SyntaxTreeLeaf &lhs_op = verible::SymbolCastToLeaf(*lhs_node[1]); const auto lhs_tag = verilog_tokentype(lhs_op.Tag().tag); if (lhs_tag == this_tag) { @@ -59,44 +59,44 @@ verible::SymbolPtr MakeBinaryExpression(T1&& lhs, T2&& op, T3&& rhs) { // Returns true if symbol is a kNode tagged with kExpression // Does not match other Expression tags -bool IsExpression(const verible::SymbolPtr&); +bool IsExpression(const verible::SymbolPtr &); // Returns true if expression is a literal 0. // Does not evaluate constant expressions for equivalence to 0. -bool IsZero(const verible::Symbol&); +bool IsZero(const verible::Symbol &); // Returns true if integer value is successfully interpreted. -bool ConstantIntegerValue(const verible::Symbol&, int*); +bool ConstantIntegerValue(const verible::Symbol &, int *); // Returns the Symbol directly underneath a `kExpression` node, otherwise // returns itself. -const verible::Symbol* UnwrapExpression(const verible::Symbol&); +const verible::Symbol *UnwrapExpression(const verible::Symbol &); // Returns the predicate expression of a kConditionExpression. -const verible::Symbol* GetConditionExpressionPredicate(const verible::Symbol&); +const verible::Symbol *GetConditionExpressionPredicate(const verible::Symbol &); // Returns the true-case expression of a kConditionExpression. -const verible::Symbol* GetConditionExpressionTrueCase(const verible::Symbol&); +const verible::Symbol *GetConditionExpressionTrueCase(const verible::Symbol &); // Returns the false-case expression of a kConditionExpression. -const verible::Symbol* GetConditionExpressionFalseCase(const verible::Symbol&); +const verible::Symbol *GetConditionExpressionFalseCase(const verible::Symbol &); // Returns the operator of a kUnaryPrefixExpression -const verible::TokenInfo* GetUnaryPrefixOperator(const verible::Symbol&); +const verible::TokenInfo *GetUnaryPrefixOperator(const verible::Symbol &); // Returns the operand of a kUnaryPrefixExpression -const verible::Symbol* GetUnaryPrefixOperand(const verible::Symbol&); +const verible::Symbol *GetUnaryPrefixOperand(const verible::Symbol &); // From binary expression operations, e.g. "a + b". // Associative binary operators may span more than two operands, e.g. "a+b+c". std::vector FindAllBinaryOperations( - const verible::Symbol&); + const verible::Symbol &); // TODO(fangism): evaluate constant expressions // From a statement like "assign foo = condition_a ? a : b;", returns condition // expressions "condition_a ? a : b". std::vector FindAllConditionExpressions( - const verible::Symbol&); + const verible::Symbol &); // TODO(fangism): evaluate constant expressions @@ -105,12 +105,12 @@ std::vector FindAllConditionExpressions( // References include any indexing [], hierarchy ".x" or call "(...)" // extensions. std::vector FindAllReferenceFullExpressions( - const verible::Symbol&); + const verible::Symbol &); // Returns true if reference expression is a plain variable reference with no // hierarchy, no indexing, no calls. -const verible::TokenInfo* ReferenceIsSimpleIdentifier( - const verible::Symbol& reference); +const verible::TokenInfo *ReferenceIsSimpleIdentifier( + const verible::Symbol &reference); } // namespace verilog diff --git a/verilog/CST/functions.cc b/verilog/CST/functions.cc index c4b38c17b..3bf6c87b4 100644 --- a/verilog/CST/functions.cc +++ b/verilog/CST/functions.cc @@ -34,112 +34,112 @@ using verible::Symbol; using verible::SyntaxTreeNode; std::vector FindAllFunctionDeclarations( - const Symbol& root) { + const Symbol &root) { return verible::SearchSyntaxTree(root, NodekFunctionDeclaration()); } std::vector FindAllFunctionPrototypes( - const Symbol& root) { + const Symbol &root) { return verible::SearchSyntaxTree(root, NodekFunctionPrototype()); } std::vector FindAllFunctionHeaders( - const Symbol& root) { + const Symbol &root) { return verible::SearchSyntaxTree(root, NodekFunctionHeader()); } std::vector FindAllFunctionOrTaskCalls( - const Symbol& root) { + const Symbol &root) { return verible::SearchSyntaxTree(root, NodekFunctionCall()); } std::vector FindAllFunctionOrTaskCallsExtension( - const Symbol& root) { + const Symbol &root) { auto calls = verible::SearchSyntaxTree(root, NodekFunctionCall()); std::vector names; - for (const auto& Call : calls) { + for (const auto &Call : calls) { std::vector names_ext = verible::SearchSyntaxTree(*Call.match, NodekHierarchyExtension()); - for (const auto& foo : names_ext) { + for (const auto &foo : names_ext) { names.emplace_back(foo); } } auto method_extensions = verible::SearchSyntaxTree(root, NodekMethodCallExtension()); - for (const auto& foo : method_extensions) names.emplace_back(foo); + for (const auto &foo : method_extensions) names.emplace_back(foo); return names; } std::vector FindAllConstructorPrototypes( - const Symbol& root) { + const Symbol &root) { return verible::SearchSyntaxTree(root, NodekClassConstructorPrototype()); } -const verible::SyntaxTreeNode* GetFunctionHeader(const Symbol& function_decl) { +const verible::SyntaxTreeNode *GetFunctionHeader(const Symbol &function_decl) { return GetSubtreeAsNode(function_decl, NodeEnum::kFunctionDeclaration, 0, NodeEnum::kFunctionHeader); } -const verible::SyntaxTreeNode* GetFunctionPrototypeHeader( - const Symbol& function_decl) { +const verible::SyntaxTreeNode *GetFunctionPrototypeHeader( + const Symbol &function_decl) { return GetSubtreeAsNode(function_decl, NodeEnum::kFunctionPrototype, 0, NodeEnum::kFunctionHeader); } -const Symbol* GetFunctionHeaderLifetime(const Symbol& function_header) { +const Symbol *GetFunctionHeaderLifetime(const Symbol &function_header) { return GetSubtreeAsSymbol(function_header, NodeEnum::kFunctionHeader, 2); } -const Symbol* GetFunctionHeaderReturnType(const Symbol& function_header) { +const Symbol *GetFunctionHeaderReturnType(const Symbol &function_header) { return GetSubtreeAsSymbol(function_header, NodeEnum::kFunctionHeader, 3); } -const Symbol* GetFunctionHeaderId(const Symbol& function_header) { +const Symbol *GetFunctionHeaderId(const Symbol &function_header) { return GetSubtreeAsSymbol(function_header, NodeEnum::kFunctionHeader, 4); } -const Symbol* GetFunctionHeaderFormalPortsGroup(const Symbol& function_header) { +const Symbol *GetFunctionHeaderFormalPortsGroup(const Symbol &function_header) { return GetSubtreeAsSymbol(function_header, NodeEnum::kFunctionHeader, 5); } -const Symbol* GetFunctionLifetime(const Symbol& function_decl) { - const auto* header = GetFunctionHeader(function_decl); +const Symbol *GetFunctionLifetime(const Symbol &function_decl) { + const auto *header = GetFunctionHeader(function_decl); return header ? GetFunctionHeaderLifetime(*header) : nullptr; } -const Symbol* GetFunctionReturnType(const Symbol& function_decl) { - const auto* header = GetFunctionHeader(function_decl); +const Symbol *GetFunctionReturnType(const Symbol &function_decl) { + const auto *header = GetFunctionHeader(function_decl); return header ? GetFunctionHeaderReturnType(*header) : nullptr; } -const Symbol* GetFunctionId(const Symbol& function_decl) { - const auto* header = GetFunctionHeader(function_decl); +const Symbol *GetFunctionId(const Symbol &function_decl) { + const auto *header = GetFunctionHeader(function_decl); return header ? GetFunctionHeaderId(*header) : nullptr; } -const Symbol* GetFunctionFormalPortsGroup(const Symbol& function_decl) { - const auto* header = GetFunctionHeader(function_decl); +const Symbol *GetFunctionFormalPortsGroup(const Symbol &function_decl) { + const auto *header = GetFunctionHeader(function_decl); return header ? GetFunctionHeaderFormalPortsGroup(*header) : nullptr; } -const verible::SyntaxTreeLeaf* GetFunctionName( - const verible::Symbol& function_decl) { - const auto* function_id = GetFunctionId(function_decl); +const verible::SyntaxTreeLeaf *GetFunctionName( + const verible::Symbol &function_decl) { + const auto *function_id = GetFunctionId(function_decl); if (!function_id) return nullptr; return GetIdentifier(*function_id); } -const verible::SyntaxTreeNode* GetLocalRootFromFunctionCall( - const verible::Symbol& function_call) { +const verible::SyntaxTreeNode *GetLocalRootFromFunctionCall( + const verible::Symbol &function_call) { return GetSubtreeAsNode(function_call, NodeEnum::kFunctionCall, 0, NodeEnum::kLocalRoot); } -const verible::SyntaxTreeNode* GetIdentifiersFromFunctionCall( - const verible::Symbol& function_call) { - const verible::Symbol* reference = nullptr; - const verible::Symbol* reference_call_base = nullptr; - const verible::Symbol* identifier = nullptr; +const verible::SyntaxTreeNode *GetIdentifiersFromFunctionCall( + const verible::Symbol &function_call) { + const verible::Symbol *reference = nullptr; + const verible::Symbol *reference_call_base = nullptr; + const verible::Symbol *identifier = nullptr; reference_call_base = GetSubtreeAsSymbol(function_call, NodeEnum::kFunctionCall, 0); if (reference_call_base->Tag().tag != (int)NodeEnum::kReferenceCallBase) { @@ -149,7 +149,7 @@ const verible::SyntaxTreeNode* GetIdentifiersFromFunctionCall( GetSubtreeAsSymbol(*reference_call_base, NodeEnum::kReferenceCallBase, 0); if (!reference) return nullptr; if (reference->Tag().tag == (int)NodeEnum::kReference) { - const verible::SyntaxTreeNode* local_root = GetSubtreeAsNode( + const verible::SyntaxTreeNode *local_root = GetSubtreeAsNode( *reference, NodeEnum::kReference, 0, NodeEnum::kLocalRoot); if (!local_root) return nullptr; if (local_root->Tag().tag != (int)NodeEnum::kLocalRoot) { @@ -164,36 +164,36 @@ const verible::SyntaxTreeNode* GetIdentifiersFromFunctionCall( return &verible::SymbolCastToNode(*identifier); } -const verible::SyntaxTreeLeaf* GetFunctionCallName( - const verible::Symbol& function_call) { - const auto* local_root = GetLocalRootFromFunctionCall(function_call); +const verible::SyntaxTreeLeaf *GetFunctionCallName( + const verible::Symbol &function_call) { + const auto *local_root = GetLocalRootFromFunctionCall(function_call); if (!local_root) return nullptr; - const auto* unqualified_id = GetSubtreeAsNode( + const auto *unqualified_id = GetSubtreeAsNode( *local_root, NodeEnum::kLocalRoot, 0, NodeEnum::kUnqualifiedId); if (!unqualified_id) return nullptr; return GetIdentifier(*unqualified_id); } -const verible::SyntaxTreeLeaf* GetFunctionCallNameFromCallExtension( - const verible::Symbol& function_call) { - const auto* unqualified_id = +const verible::SyntaxTreeLeaf *GetFunctionCallNameFromCallExtension( + const verible::Symbol &function_call) { + const auto *unqualified_id = GetSubtreeAsNode(function_call, NodeEnum::kHierarchyExtension, 1, NodeEnum::kUnqualifiedId); if (!unqualified_id) return nullptr; return GetIdentifier(*unqualified_id); } -const verible::SyntaxTreeNode* GetFunctionBlockStatementList( - const verible::Symbol& function_decl) { +const verible::SyntaxTreeNode *GetFunctionBlockStatementList( + const verible::Symbol &function_decl) { return verible::GetSubtreeAsNode(function_decl, NodeEnum::kFunctionDeclaration, 2); } -const verible::SyntaxTreeNode* GetParenGroupFromCall( - const verible::Symbol& function_call) { +const verible::SyntaxTreeNode *GetParenGroupFromCall( + const verible::Symbol &function_call) { if (function_call.Tag().tag == (int)NodeEnum::kFunctionCall) { - const verible::Symbol* reference_or_call = + const verible::Symbol *reference_or_call = verible::GetSubtreeAsSymbol(function_call, NodeEnum::kFunctionCall, 0); if (reference_or_call->Tag().tag != (int)NodeEnum::kReferenceCallBase) { return nullptr; @@ -205,14 +205,14 @@ const verible::SyntaxTreeNode* GetParenGroupFromCall( return nullptr; } -const verible::SyntaxTreeNode* GetParenGroupFromCallExtension( - const verible::Symbol& function_call) { +const verible::SyntaxTreeNode *GetParenGroupFromCallExtension( + const verible::Symbol &function_call) { return verible::GetSubtreeAsNode( function_call, NodeEnum::kMethodCallExtension, 2, NodeEnum::kParenGroup); } -const verible::SyntaxTreeLeaf* GetConstructorPrototypeNewKeyword( - const verible::Symbol& constructor_prototype) { +const verible::SyntaxTreeLeaf *GetConstructorPrototypeNewKeyword( + const verible::Symbol &constructor_prototype) { return GetSubtreeAsLeaf(constructor_prototype, NodeEnum::kClassConstructorPrototype, 1); } diff --git a/verilog/CST/functions.h b/verilog/CST/functions.h index 5e9dc17cb..4f3e6aff9 100644 --- a/verilog/CST/functions.h +++ b/verilog/CST/functions.h @@ -33,9 +33,9 @@ namespace verilog { // Construct a function header CST node, without the trailing ';'. template -verible::SymbolPtr MakeFunctionHeader(T0&& qualifiers, T1&& function_start, - T2&& lifetime, T3&& return_type_id, - T4&& ports) { +verible::SymbolPtr MakeFunctionHeader(T0 &&qualifiers, T1 &&function_start, + T2 &&lifetime, T3 &&return_type_id, + T4 &&ports) { verible::CheckOptionalSymbolAsNode(qualifiers, NodeEnum::kQualifierList); ExpectString(function_start, "function"); verible::CheckOptionalSymbolAsNode(ports, NodeEnum::kParenGroup); @@ -50,9 +50,9 @@ verible::SymbolPtr MakeFunctionHeader(T0&& qualifiers, T1&& function_start, // Construct a function header CST node, with the trailing ';'. template -verible::SymbolPtr MakeFunctionHeader(T0&& qualifiers, T1&& function_start, - T2&& lifetime, T3&& return_type_id, - T4&& ports, T5&& semicolon) { +verible::SymbolPtr MakeFunctionHeader(T0 &&qualifiers, T1 &&function_start, + T2 &&lifetime, T3 &&return_type_id, + T4 &&ports, T5 &&semicolon) { ExpectString(semicolon, ";"); return ExtendNode( MakeFunctionHeader( @@ -66,11 +66,11 @@ verible::SymbolPtr MakeFunctionHeader(T0&& qualifiers, T1&& function_start, template -verible::SymbolPtr MakeFunctionDeclaration(T0&& qualifiers, T1&& function_start, - T2&& lifetime, T3&& return_type_id, - T4&& ports, T5&& semicolon, - T6&& function_items, T7&& body, - T8&& function_end, T9&& label) { +verible::SymbolPtr MakeFunctionDeclaration(T0 &&qualifiers, T1 &&function_start, + T2 &&lifetime, T3 &&return_type_id, + T4 &&ports, T5 &&semicolon, + T6 &&function_items, T7 &&body, + T8 &&function_end, T9 &&label) { ExpectString(function_end, "endfunction"); return verible::MakeTaggedNode( NodeEnum::kFunctionDeclaration, @@ -86,109 +86,109 @@ verible::SymbolPtr MakeFunctionDeclaration(T0&& qualifiers, T1&& function_start, // Find all function declarations, including class method declarations. std::vector FindAllFunctionDeclarations( - const verible::Symbol&); + const verible::Symbol &); // Find all function headers (in declarations and prototypes). std::vector FindAllFunctionHeaders( - const verible::Symbol&); + const verible::Symbol &); // Find all function prototypes (extern, pure virtual). std::vector FindAllFunctionPrototypes( - const verible::Symbol&); + const verible::Symbol &); // Find all function (or Task) calls. std::vector FindAllFunctionOrTaskCalls( - const verible::Symbol&); + const verible::Symbol &); // Find all function (or Task) calls extension e.g class_name.function_call(). std::vector FindAllFunctionOrTaskCallsExtension( - const verible::Symbol&); + const verible::Symbol &); // Find all constructor prototypes. std::vector FindAllConstructorPrototypes( - const verible::Symbol&); + const verible::Symbol &); // Returns the function declaration header (return type, id, ports) -const verible::SyntaxTreeNode* GetFunctionHeader( - const verible::Symbol& function_decl); +const verible::SyntaxTreeNode *GetFunctionHeader( + const verible::Symbol &function_decl); // Returns the function prototype header (return type, id, ports) -const verible::SyntaxTreeNode* GetFunctionPrototypeHeader( - const verible::Symbol& function_decl); +const verible::SyntaxTreeNode *GetFunctionPrototypeHeader( + const verible::Symbol &function_decl); // FunctionHeader accessors // Returns the function lifetime of the function header. -const verible::Symbol* GetFunctionHeaderLifetime( - const verible::Symbol& function_header); +const verible::Symbol *GetFunctionHeaderLifetime( + const verible::Symbol &function_header); // Returns the parenthesis group containing the formal ports list, or nullptr. -const verible::Symbol* GetFunctionHeaderFormalPortsGroup( - const verible::Symbol& function_header); +const verible::Symbol *GetFunctionHeaderFormalPortsGroup( + const verible::Symbol &function_header); // Returns the return type of the function header. -const verible::Symbol* GetFunctionHeaderReturnType( - const verible::Symbol& function_header); +const verible::Symbol *GetFunctionHeaderReturnType( + const verible::Symbol &function_header); // Returns the id of the function header. -const verible::Symbol* GetFunctionHeaderId( - const verible::Symbol& function_header); +const verible::Symbol *GetFunctionHeaderId( + const verible::Symbol &function_header); // FunctionDeclaration acccessors // Returns the function lifetime of the node. -const verible::Symbol* GetFunctionLifetime( - const verible::Symbol& function_decl); +const verible::Symbol *GetFunctionLifetime( + const verible::Symbol &function_decl); // Returns the parenthesis group containing the formal ports list, or nullptr. -const verible::Symbol* GetFunctionFormalPortsGroup( - const verible::Symbol& function_decl); +const verible::Symbol *GetFunctionFormalPortsGroup( + const verible::Symbol &function_decl); // Returns the return type of the function declaration. -const verible::Symbol* GetFunctionReturnType( - const verible::Symbol& function_decl); +const verible::Symbol *GetFunctionReturnType( + const verible::Symbol &function_decl); // Returns the id of the function declaration. -const verible::Symbol* GetFunctionId(const verible::Symbol& function_decl); +const verible::Symbol *GetFunctionId(const verible::Symbol &function_decl); // Returns leaf node for function name. // e.g. function my_fun(); return leaf node for "my_fun". -const verible::SyntaxTreeLeaf* GetFunctionName(const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetFunctionName(const verible::Symbol &); // Returns local root node from node tagged with kFunctionCall. -const verible::SyntaxTreeNode* GetLocalRootFromFunctionCall( - const verible::Symbol&); +const verible::SyntaxTreeNode *GetLocalRootFromFunctionCall( + const verible::Symbol &); // Return the node spanning identifier for the function call node. // e.g from "pkg::get()" returns the node spanning "pkg::get". -const verible::SyntaxTreeNode* GetIdentifiersFromFunctionCall( - const verible::Symbol& function_call); +const verible::SyntaxTreeNode *GetIdentifiersFromFunctionCall( + const verible::Symbol &function_call); // Returns leaf node for function name in function call. // e.g my_function(); return leaf node for "my_function". -const verible::SyntaxTreeLeaf* GetFunctionCallName(const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetFunctionCallName(const verible::Symbol &); // Returns leaf node for function name in function call extension. // e.g class_name.my_function(); return leaf node for "my_function". -const verible::SyntaxTreeLeaf* GetFunctionCallNameFromCallExtension( - const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetFunctionCallNameFromCallExtension( + const verible::Symbol &); // Returns the function declaration body. -const verible::SyntaxTreeNode* GetFunctionBlockStatementList( - const verible::Symbol&); +const verible::SyntaxTreeNode *GetFunctionBlockStatementList( + const verible::Symbol &); // Return the node spanning the paren group of function call. // e.g my_function(a, b, c) return the node spanning (a, b, c). -const verible::SyntaxTreeNode* GetParenGroupFromCall(const verible::Symbol&); +const verible::SyntaxTreeNode *GetParenGroupFromCall(const verible::Symbol &); // Return the node spanning the paren group of function call extension. // e.g my_class.my_function(a, b, c) return the node spanning (a, b, c). -const verible::SyntaxTreeNode* GetParenGroupFromCallExtension( - const verible::Symbol&); +const verible::SyntaxTreeNode *GetParenGroupFromCallExtension( + const verible::Symbol &); // Returns leaf node for the "new" keyword of a constructor prototype. -const verible::SyntaxTreeLeaf* GetConstructorPrototypeNewKeyword( - const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetConstructorPrototypeNewKeyword( + const verible::Symbol &); } // namespace verilog diff --git a/verilog/CST/functions_test.cc b/verilog/CST/functions_test.cc index e67a29b34..471a4252f 100644 --- a/verilog/CST/functions_test.cc +++ b/verilog/CST/functions_test.cc @@ -106,10 +106,10 @@ TEST(FindAllFunctionDeclarationsTest, Various) { "endgroup\n" "endmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllFunctionDeclarations(*ABSL_DIE_IF_NULL(root)); }); } @@ -153,22 +153,22 @@ TEST(FindAllFunctionPrototypesTest, Various) { "endfunction\n" "endclass\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllFunctionPrototypes(*ABSL_DIE_IF_NULL(root)); }); } // Protype headers map to the same range as the enclosing prototype. - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto protos(FindAllFunctionPrototypes(*ABSL_DIE_IF_NULL(root))); std::vector headers; headers.reserve(protos.size()); - for (const auto& proto : protos) { + for (const auto &proto : protos) { headers.push_back(TreeSearchMatch{ GetFunctionPrototypeHeader(*proto.match), /* no context */}); } @@ -203,14 +203,14 @@ TEST(FunctionPrototypesReturnTypesTest, Various) { "endclass\n"}, }; // Protype headers map to the same range as the enclosing prototype. - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto protos(FindAllFunctionPrototypes(*ABSL_DIE_IF_NULL(root))); std::vector returns; - for (const auto& proto : protos) { - const auto* return_type = GetFunctionHeaderReturnType( + for (const auto &proto : protos) { + const auto *return_type = GetFunctionHeaderReturnType( *GetFunctionPrototypeHeader(*proto.match)); if (return_type == nullptr) continue; if (verible::StringSpanOfSymbol(*return_type).empty()) continue; @@ -251,14 +251,14 @@ TEST(FunctionPrototypesIdsTest, Various) { "endclass\n"}, }; // Protype headers map to the same range as the enclosing prototype. - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto protos(FindAllFunctionPrototypes(*ABSL_DIE_IF_NULL(root))); std::vector ids; - for (const auto& proto : protos) { - const auto* id = + for (const auto &proto : protos) { + const auto *id = GetFunctionHeaderId(*GetFunctionPrototypeHeader(*proto.match)); if (id == nullptr) continue; if (verible::StringSpanOfSymbol(*id).empty()) continue; @@ -328,10 +328,10 @@ TEST(FindAllFunctionHeadersTest, Various) { "endgroup\n" "endmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllFunctionHeaders(*ABSL_DIE_IF_NULL(root)); }); } @@ -345,15 +345,15 @@ TEST(GetFunctionHeaderTest, DeclarationHeader) { {"module m; ", {kTag, "function foo();"}, " endfunction endmodule"}, {"package p; ", {kTag, "function foo();"}, " endfunction endpackage"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); // Root node is a description list, not a function. const auto function_declarations = FindAllFunctionDeclarations(*root); std::vector headers; - for (const auto& decl : function_declarations) { - const auto& function_node = SymbolCastToNode(*decl.match); + for (const auto &decl : function_declarations) { + const auto &function_node = SymbolCastToNode(*decl.match); headers.push_back(TreeSearchMatch{GetFunctionHeader(function_node), /* no context */}); } @@ -366,12 +366,12 @@ TEST(GetFunctionLifetimeTest, NoLifetimeDeclared) { VerilogAnalyzer analyzer("function foo(); endfunction", ""); ASSERT_OK(analyzer.Analyze()); // Root node is a description list, not a function. - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto function_declarations = FindAllFunctionDeclarations(*root); ASSERT_EQ(function_declarations.size(), 1); - const auto& function_node = + const auto &function_node = SymbolCastToNode(*function_declarations.front().match); - const auto* lifetime = GetFunctionLifetime(function_node); + const auto *lifetime = GetFunctionLifetime(function_node); EXPECT_EQ(lifetime, nullptr); } @@ -379,12 +379,12 @@ TEST(GetFunctionLifetimeTest, StaticLifetimeDeclared) { VerilogAnalyzer analyzer("function static foo(); endfunction", ""); ASSERT_OK(analyzer.Analyze()); // Root node is a description list, not a function. - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto function_declarations = FindAllFunctionDeclarations(*root); ASSERT_EQ(function_declarations.size(), 1); - const auto& function_node = + const auto &function_node = SymbolCastToNode(*function_declarations.front().match); - const auto* lifetime = GetFunctionLifetime(function_node); + const auto *lifetime = GetFunctionLifetime(function_node); CheckSymbolAsLeaf(*ABSL_DIE_IF_NULL(lifetime), TK_static); // TODO(b/151371397): verify substring range } @@ -393,12 +393,12 @@ TEST(GetFunctionLifetimeTest, AutomaticLifetimeDeclared) { VerilogAnalyzer analyzer("function automatic foo(); endfunction", ""); ASSERT_OK(analyzer.Analyze()); // Root node is a description list, not a function.e - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto function_declarations = FindAllFunctionDeclarations(*root); ASSERT_EQ(function_declarations.size(), 1); - const auto& function_node = + const auto &function_node = SymbolCastToNode(*function_declarations.front().match); - const auto* lifetime = GetFunctionLifetime(function_node); + const auto *lifetime = GetFunctionLifetime(function_node); CheckSymbolAsLeaf(*ABSL_DIE_IF_NULL(lifetime), TK_automatic); // TODO(b/151371397): verify substring range } @@ -413,17 +413,17 @@ TEST(GetFunctionIdTest, UnqualifiedIds) { {"class c; function ", {kTag, "zoo"}, "(); endfunction endclass"}, {"function ", {kTag, "myclass"}, "::", {kTag, "foo"}, "(); endfunction"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto function_declarations = FindAllFunctionDeclarations(*root); std::vector got_ids; - for (const auto& decl : function_declarations) { - const auto& function_node = SymbolCastToNode(*decl.match); - const auto* function_id = GetFunctionId(function_node); - for (const auto& id : FindAllUnqualifiedIds(*function_id)) { - const verible::SyntaxTreeLeaf* base = GetIdentifier(*id.match); + for (const auto &decl : function_declarations) { + const auto &function_node = SymbolCastToNode(*decl.match); + const auto *function_id = GetFunctionId(function_node); + for (const auto &id : FindAllUnqualifiedIds(*function_id)) { + const verible::SyntaxTreeLeaf *base = GetIdentifier(*id.match); got_ids.push_back(TreeSearchMatch{base, /* empty context */}); } } @@ -438,16 +438,16 @@ TEST(GetFunctionIdTest, QualifiedIds) { {"function foo(); endfunction"}, {"function ", {kTag, "myclass::foo"}, "(); endfunction"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto function_declarations = FindAllFunctionDeclarations(*root); std::vector got_ids; - for (const auto& decl : function_declarations) { - const auto& function_node = SymbolCastToNode(*decl.match); - const auto* function_id = GetFunctionId(function_node); - for (const auto& id : FindAllQualifiedIds(*function_id)) { + for (const auto &decl : function_declarations) { + const auto &function_node = SymbolCastToNode(*decl.match); + const auto *function_id = GetFunctionId(function_node); + for (const auto &id : FindAllQualifiedIds(*function_id)) { got_ids.push_back(id); } } @@ -481,16 +481,16 @@ TEST(GetFunctionReturnTypeTest, VariousReturnTypes) { {kTag, "foo#(bar)"}, " f;\nendfunction\nendmodule\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllFunctionDeclarations(*root); std::vector returns; - for (const auto& decl : decls) { - const auto& statement = *decl.match; - const auto* return_type = GetFunctionReturnType(statement); + for (const auto &decl : decls) { + const auto &statement = *decl.match; + const auto *return_type = GetFunctionReturnType(statement); // Expect a type node, even when type is implicit or empty. if (return_type == nullptr) continue; const auto return_type_span = @@ -524,16 +524,16 @@ TEST(GetFunctionFormalPortsGroupTest, MixedFormalPorts) { {kTag, "(input logic foo, bar)"}, ";\nendfunction\nendmodule\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllFunctionDeclarations(*root); std::vector ports; - for (const auto& decl : decls) { - const auto& statement = *decl.match; - const auto* port_formals = GetFunctionFormalPortsGroup(statement); + for (const auto &decl : decls) { + const auto &statement = *decl.match; + const auto *port_formals = GetFunctionFormalPortsGroup(statement); if (port_formals == nullptr) continue; const auto port_formals_span = verible::StringSpanOfSymbol(*port_formals); @@ -584,16 +584,16 @@ TEST(GetFunctionHeaderTest, GetFunctionName) { {kTag, "my_fun"}, "();\n return 10;\n endfunction\n endclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllFunctionDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector types; - for (const auto& decl : decls) { - const auto* type = GetFunctionName(*decl.match); + for (const auto &decl : decls) { + const auto *type = GetFunctionName(*decl.match); types.push_back(TreeSearchMatch{type, {/* ignored context */}}); } return types; @@ -614,16 +614,16 @@ TEST(GetFunctionHeaderTest, GetFunctionClassCallName) { {kTag, "function_name"}, "());\nendmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto calls = FindAllFunctionOrTaskCallsExtension(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& Call : calls) { - const auto* name = + for (const auto &Call : calls) { + const auto *name = GetFunctionCallNameFromCallExtension(*Call.match); names.emplace_back(TreeSearchMatch{name, {/* ignored context */}}); } @@ -662,16 +662,16 @@ TEST(GetFunctionBlockStatement, GetFunctionBody) { {kTag, "return 1;"}, "\nendfunction\nendclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllFunctionDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector functions_body; - for (const auto& decl : decls) { - const auto& body = GetFunctionBlockStatementList(*decl.match); + for (const auto &decl : decls) { + const auto &body = GetFunctionBlockStatementList(*decl.match); functions_body.push_back( TreeSearchMatch{body, {/* ignored context */}}); } @@ -693,16 +693,16 @@ TEST(FunctionCallTest, GetFunctionCallName) { {"r=this();"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& calls = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &calls = FindAllFunctionOrTaskCalls(*ABSL_DIE_IF_NULL(root)); std::vector identifiers; - for (const auto& call : calls) { - const auto* identifier = + for (const auto &call : calls) { + const auto *identifier = GetIdentifiersFromFunctionCall(*call.match); if (identifier == nullptr) { continue; @@ -748,16 +748,16 @@ TEST(FunctionCallTest, GetFunctionCallArguments) { }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllFunctionOrTaskCalls(*ABSL_DIE_IF_NULL(root)); std::vector paren_groups; - for (const auto& decl : instances) { - const auto* paren_group = GetParenGroupFromCall(*decl.match); + for (const auto &decl : instances) { + const auto *paren_group = GetParenGroupFromCall(*decl.match); paren_groups.emplace_back( TreeSearchMatch{paren_group, {/* ignored context */}}); } @@ -780,16 +780,16 @@ TEST(FunctionCallTest, GetFunctionCallExtensionArguments) { ");\nendmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllFunctionOrTaskCallsExtension(*ABSL_DIE_IF_NULL(root)); std::vector paren_groups; - for (const auto& decl : instances) { - const auto* paren_group = + for (const auto &decl : instances) { + const auto *paren_group = GetParenGroupFromCallExtension(*decl.match); paren_groups.emplace_back( TreeSearchMatch{paren_group, {/* ignored context */}}); @@ -828,16 +828,16 @@ TEST(FunctionCallTest, GetConstructorNewKeyword) { "endclass\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& ctors = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &ctors = FindAllConstructorPrototypes(*ABSL_DIE_IF_NULL(root)); std::vector new_tokens; - for (const auto& decl : ctors) { - const auto* paren_group = + for (const auto &decl : ctors) { + const auto *paren_group = GetConstructorPrototypeNewKeyword(*decl.match); new_tokens.emplace_back( TreeSearchMatch{paren_group, {/* ignored context */}}); diff --git a/verilog/CST/identifier.cc b/verilog/CST/identifier.cc index 481a10bbe..c1a7138ec 100644 --- a/verilog/CST/identifier.cc +++ b/verilog/CST/identifier.cc @@ -35,50 +35,50 @@ using verible::down_cast; using verible::SymbolKind; std::vector FindAllIdentifierUnpackedDimensions( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekIdentifierUnpackedDimensions()); } std::vector FindAllPortIdentifiers( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekPortIdentifier()); } std::vector FindAllUnqualifiedIds( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekUnqualifiedId()); } std::vector FindAllQualifiedIds( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekQualifiedId()); } std::vector FindAllSymbolIdentifierLeafs( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, SymbolIdentifierLeaf()); } -bool IdIsQualified(const verible::Symbol& symbol) { +bool IdIsQualified(const verible::Symbol &symbol) { auto t = symbol.Tag(); if (t.kind != SymbolKind::kNode) return false; return NodeEnum(t.tag) == NodeEnum::kQualifiedId; } -const verible::SyntaxTreeLeaf* GetIdentifier(const verible::Symbol& symbol) { +const verible::SyntaxTreeLeaf *GetIdentifier(const verible::Symbol &symbol) { auto t = symbol.Tag(); if (t.kind != SymbolKind::kNode) return nullptr; if (NodeEnum(t.tag) != NodeEnum::kUnqualifiedId && NodeEnum(t.tag) != NodeEnum::kPortIdentifier) { return nullptr; } - const auto& node = down_cast(symbol); - const auto* leaf = down_cast(node[0].get()); + const auto &node = down_cast(symbol); + const auto *leaf = down_cast(node[0].get()); return leaf; } -const verible::SyntaxTreeLeaf* AutoUnwrapIdentifier( - const verible::Symbol& symbol) { +const verible::SyntaxTreeLeaf *AutoUnwrapIdentifier( + const verible::Symbol &symbol) { // If it's a leaf, then just return that leaf. Otherwise it is an // kUnqualifiedId const auto t = symbol.Tag(); @@ -92,10 +92,10 @@ const verible::SyntaxTreeLeaf* AutoUnwrapIdentifier( return GetIdentifier(symbol); } -const verible::SyntaxTreeLeaf* +const verible::SyntaxTreeLeaf * GetSymbolIdentifierFromIdentifierUnpackedDimensions( - const verible::Symbol& identifier_unpacked_dimension) { - const verible::Symbol* child_node = + const verible::Symbol &identifier_unpacked_dimension) { + const verible::Symbol *child_node = GetSubtreeAsSymbol(identifier_unpacked_dimension, NodeEnum::kIdentifierUnpackedDimensions, 0); return AutoUnwrapIdentifier(*child_node); diff --git a/verilog/CST/identifier.h b/verilog/CST/identifier.h index c835feab0..93655490a 100644 --- a/verilog/CST/identifier.h +++ b/verilog/CST/identifier.h @@ -25,38 +25,38 @@ namespace verilog { // Returns all sub-nodes tagged with kIdentifierUnpackedDimensions std::vector FindAllIdentifierUnpackedDimensions( - const verible::Symbol&); + const verible::Symbol &); // Returns all sub-nodes tagged with kPortIdentifier std::vector FindAllPortIdentifiers( - const verible::Symbol&); + const verible::Symbol &); // Returns all sub-nodes tagged with kUnqualifiedId std::vector FindAllUnqualifiedIds( - const verible::Symbol&); + const verible::Symbol &); // Returns all sub-nodes tagged with kQualifiedId std::vector FindAllQualifiedIds( - const verible::Symbol&); + const verible::Symbol &); // Returns all leafs with token type SymbolIdentifier std::vector FindAllSymbolIdentifierLeafs( - const verible::Symbol&); + const verible::Symbol &); // Returns true if identifier node is qualified/scoped. -bool IdIsQualified(const verible::Symbol&); +bool IdIsQualified(const verible::Symbol &); // Extracts identifier leaf from a kUnqualifiedId node. -const verible::SyntaxTreeLeaf* GetIdentifier(const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetIdentifier(const verible::Symbol &); // Extracts identifier leaf from a kUnqualifiedId node, or returns the leaf // as-is. This automatically peels away the kUnqualifiedId node layer. -const verible::SyntaxTreeLeaf* AutoUnwrapIdentifier(const verible::Symbol&); +const verible::SyntaxTreeLeaf *AutoUnwrapIdentifier(const verible::Symbol &); // Extracts SymbolIdentifier leaf from a kIdentifierUnpackedDimensions node. // e.g. extracts "a" from "a[0:1]" -const verible::SyntaxTreeLeaf* -GetSymbolIdentifierFromIdentifierUnpackedDimensions(const verible::Symbol&); +const verible::SyntaxTreeLeaf * +GetSymbolIdentifierFromIdentifierUnpackedDimensions(const verible::Symbol &); } // namespace verilog diff --git a/verilog/CST/identifier_test.cc b/verilog/CST/identifier_test.cc index 78214a602..2ca298da7 100644 --- a/verilog/CST/identifier_test.cc +++ b/verilog/CST/identifier_test.cc @@ -50,19 +50,19 @@ TEST(IdIsQualifiedTest, VariousIds) { {"task goo(); endtask", 0 /* goo */}, {"task fff::goo(); endtask", 1 /* fff::goo */}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.first, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto q_ids = FindAllQualifiedIds(*root); ASSERT_EQ(q_ids.size(), test.second); if (!q_ids.empty()) { - for (const auto& id : q_ids) { + for (const auto &id : q_ids) { EXPECT_TRUE(IdIsQualified(*id.match)); } } else { const auto u_ids = FindAllUnqualifiedIds(*root); - for (const auto& id : u_ids) { + for (const auto &id : u_ids) { EXPECT_FALSE(IdIsQualified(*id.match)); } } @@ -96,30 +96,30 @@ TEST(GetIdentifierTest, UnqualifiedIds) { {{kTag, "p_pkg"}, "::", {kTag, "tree"}, "#(11) ", {kTag, "bark"}, ";"}, }; // Test GetIdentifier - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VLOG(1) << "[GetIdentifier] code:\n" << test.code; TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto ids = FindAllUnqualifiedIds(*root); std::vector got_ids; - for (const auto& id : ids) { - const verible::SyntaxTreeLeaf* base = GetIdentifier(*id.match); + for (const auto &id : ids) { + const verible::SyntaxTreeLeaf *base = GetIdentifier(*id.match); got_ids.push_back(TreeSearchMatch{base, /* ignored context */}); } return got_ids; }); } // Test AutoUnwrapIdentifier - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VLOG(1) << "[AutoUnwrapIdentifier] code:\n" << test.code; TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto ids = FindAllUnqualifiedIds(*root); std::vector got_ids; - for (const auto& id : ids) { - const verible::SyntaxTreeLeaf* base = + for (const auto &id : ids) { + const verible::SyntaxTreeLeaf *base = AutoUnwrapIdentifier(*id.match); if (base == nullptr) continue; got_ids.push_back(TreeSearchMatch{base, /* ignored context */}); @@ -137,15 +137,15 @@ TEST(GetIdentifierTest, PortIdentifiers) { {"module t; output reg ", {kTag, "o"}, "; endmodule"}, }; // Test GetIdentifier - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VLOG(1) << "[GetIdentifier] code:\n" << test.code; TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto ids = FindAllPortIdentifiers(*root); std::vector got_ids; - for (const auto& id : ids) { - const verible::SyntaxTreeLeaf* base = GetIdentifier(*id.match); + for (const auto &id : ids) { + const verible::SyntaxTreeLeaf *base = GetIdentifier(*id.match); got_ids.push_back(TreeSearchMatch{base, /* ignored context */}); } return got_ids; @@ -181,16 +181,16 @@ TEST(GetIdentifierTest, IdentifierUnpackedDimensions) { {kTag, "c"}, ";\nendmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllIdentifierUnpackedDimensions(*ABSL_DIE_IF_NULL(root)); std::vector identifiers; - for (const auto& decl : decls) { - const auto* identifier = + for (const auto &decl : decls) { + const auto *identifier = GetSymbolIdentifierFromIdentifierUnpackedDimensions( *decl.match); identifiers.push_back( @@ -222,14 +222,14 @@ TEST(FindAllSymbolIdentifierTest, VariousIds) { ");\n", "endmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto symb_ids = FindAllSymbolIdentifierLeafs(*root); std::vector identifiers; identifiers.reserve(symb_ids.size()); - for (const auto& symb_id : symb_ids) { + for (const auto &symb_id : symb_ids) { identifiers.push_back( TreeSearchMatch{symb_id.match, {/* ignored context */}}); } diff --git a/verilog/CST/macro.cc b/verilog/CST/macro.cc index 1ed19bc71..89681d9f1 100644 --- a/verilog/CST/macro.cc +++ b/verilog/CST/macro.cc @@ -29,54 +29,54 @@ using verible::SyntaxTreeNode; using verible::TokenInfo; std::vector FindAllMacroDefinitions( - const verible::Symbol& root) { + const verible::Symbol &root) { return SearchSyntaxTree(root, NodekPreprocessorDefine()); } std::vector FindAllPreprocessorInclude( - const verible::Symbol& root) { + const verible::Symbol &root) { return SearchSyntaxTree(root, NodekPreprocessorInclude()); } -std::vector FindAllMacroCalls(const Symbol& root) { +std::vector FindAllMacroCalls(const Symbol &root) { return SearchSyntaxTree(root, NodekMacroCall()); } std::vector FindAllMacroGenericItems( - const Symbol& root) { + const Symbol &root) { return SearchSyntaxTree(root, NodekMacroGenericItem()); } std::vector FindAllMacroDefinitionsArgs( - const verible::Symbol& macro_definition) { + const verible::Symbol ¯o_definition) { return SearchSyntaxTree(macro_definition, NodekMacroFormalArg()); } -const TokenInfo* GetMacroCallId(const Symbol& s) { - const SyntaxTreeLeaf* call = GetSubtreeAsLeaf(s, NodeEnum::kMacroCall, 0); +const TokenInfo *GetMacroCallId(const Symbol &s) { + const SyntaxTreeLeaf *call = GetSubtreeAsLeaf(s, NodeEnum::kMacroCall, 0); return call ? &call->get() : nullptr; } -const TokenInfo* GetMacroGenericItemId(const Symbol& s) { - const SyntaxTreeLeaf* generic = +const TokenInfo *GetMacroGenericItemId(const Symbol &s) { + const SyntaxTreeLeaf *generic = GetSubtreeAsLeaf(s, NodeEnum::kMacroGenericItem, 0); return generic ? &generic->get() : nullptr; } -const SyntaxTreeNode* GetMacroCallParenGroup(const Symbol& s) { +const SyntaxTreeNode *GetMacroCallParenGroup(const Symbol &s) { return GetSubtreeAsNode(s, NodeEnum::kMacroCall, 1, NodeEnum::kParenGroup); } -const SyntaxTreeNode* GetMacroCallArgs(const Symbol& s) { +const SyntaxTreeNode *GetMacroCallArgs(const Symbol &s) { // See structure of (CST) MakeParenGroup(). - const SyntaxTreeNode* parent = GetMacroCallParenGroup(s); + const SyntaxTreeNode *parent = GetMacroCallParenGroup(s); if (!parent) return nullptr; return GetSubtreeAsNode(*parent, NodeEnum::kParenGroup, 1, NodeEnum::kMacroArgList); } -bool MacroCallArgsIsEmpty(const SyntaxTreeNode& args) { - const auto& sub = +bool MacroCallArgsIsEmpty(const SyntaxTreeNode &args) { + const auto &sub = ABSL_DIE_IF_NULL(MatchNodeEnumOrNull(args, NodeEnum::kMacroArgList)) ->children(); // Empty macro args are always constructed with one nullptr child in @@ -85,20 +85,20 @@ bool MacroCallArgsIsEmpty(const SyntaxTreeNode& args) { return sub.front() == nullptr; } -const verible::SyntaxTreeLeaf* GetMacroName( - const verible::Symbol& preprocessor_define) { +const verible::SyntaxTreeLeaf *GetMacroName( + const verible::Symbol &preprocessor_define) { return GetSubtreeAsLeaf(preprocessor_define, NodeEnum::kPreprocessorDefine, 1); } -const verible::SyntaxTreeLeaf* GetMacroArgName( - const verible::Symbol& macro_formal_arg) { +const verible::SyntaxTreeLeaf *GetMacroArgName( + const verible::Symbol ¯o_formal_arg) { return GetSubtreeAsLeaf(macro_formal_arg, NodeEnum::kMacroFormalArg, 0); } -const verible::SyntaxTreeLeaf* GetFileFromPreprocessorInclude( - const verible::Symbol& preprocessor_include) { - const verible::Symbol* included_filename = verible::GetSubtreeAsSymbol( +const verible::SyntaxTreeLeaf *GetFileFromPreprocessorInclude( + const verible::Symbol &preprocessor_include) { + const verible::Symbol *included_filename = verible::GetSubtreeAsSymbol( preprocessor_include, NodeEnum::kPreprocessorInclude, 1); if (!included_filename) return nullptr; // Terminate if this isn't a string literal. diff --git a/verilog/CST/macro.h b/verilog/CST/macro.h index 43e0fe11d..cab3fba5b 100644 --- a/verilog/CST/macro.h +++ b/verilog/CST/macro.h @@ -29,53 +29,54 @@ namespace verilog { // Find all nodes tagged with kPreprocessorDefine. std::vector FindAllMacroDefinitions( - const verible::Symbol&); + const verible::Symbol &); // Find all macro calls. -std::vector FindAllMacroCalls(const verible::Symbol&); +std::vector FindAllMacroCalls( + const verible::Symbol &); // Find all preprocessor includes. std::vector FindAllPreprocessorInclude( - const verible::Symbol& root); + const verible::Symbol &root); // Find all macro calls that are whole item-level constructs. // Compared to FindAllMacroCalls, this excludes macro call expressions. std::vector FindAllMacroGenericItems( - const verible::Symbol&); + const verible::Symbol &); // Finds all macro definition args e.g `PRINT(str1, str2) returns the nodes // spanning str1 and str2. std::vector FindAllMacroDefinitionsArgs( - const verible::Symbol&); + const verible::Symbol &); // Returns the leaf containing the macro call name. -const verible::TokenInfo* GetMacroCallId(const verible::Symbol&); +const verible::TokenInfo *GetMacroCallId(const verible::Symbol &); // Returns the leaf containing the macro (as generic item) name. -const verible::TokenInfo* GetMacroGenericItemId(const verible::Symbol&); +const verible::TokenInfo *GetMacroGenericItemId(const verible::Symbol &); // Returns the node containing the macro call paren group -const verible::SyntaxTreeNode* GetMacroCallParenGroup(const verible::Symbol& s); +const verible::SyntaxTreeNode *GetMacroCallParenGroup(const verible::Symbol &s); // Returns the node containing the macro call arguments (without parentheses). -const verible::SyntaxTreeNode* GetMacroCallArgs(const verible::Symbol&); +const verible::SyntaxTreeNode *GetMacroCallArgs(const verible::Symbol &); // Returns true if there are no macro call args, e.g. `foo(). -bool MacroCallArgsIsEmpty(const verible::SyntaxTreeNode&); +bool MacroCallArgsIsEmpty(const verible::SyntaxTreeNode &); // Returns the leaf node containing the macro name from node tagged with // kPreprocessorDefine or nullptr if it doesn't exist. -const verible::SyntaxTreeLeaf* GetMacroName(const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetMacroName(const verible::Symbol &); // Returns the leaf node containing the macro arg name from node tagged with // kMacroFormalArg or nullptr if it doesn't exist. -const verible::SyntaxTreeLeaf* GetMacroArgName(const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetMacroArgName(const verible::Symbol &); // Returns the leaf node containing the filename from the node tagged with // kPreprocessorInclude or nullptr if the argument is not a simple // string-literal. -const verible::SyntaxTreeLeaf* GetFileFromPreprocessorInclude( - const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetFileFromPreprocessorInclude( + const verible::Symbol &); } // namespace verilog diff --git a/verilog/CST/macro_test.cc b/verilog/CST/macro_test.cc index 376efb5ca..e48a81821 100644 --- a/verilog/CST/macro_test.cc +++ b/verilog/CST/macro_test.cc @@ -64,10 +64,10 @@ TEST(FindAllMacroCallsTest, Various) { {"function f;\nf = `BAR(`FOO());\nendfunction\n", 2}, {"function f;\nf = `BAR() * `FOO();\nendfunction\n", 2}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.code, ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto macro_calls = FindAllMacroCalls(*ABSL_DIE_IF_NULL(root)); EXPECT_EQ(macro_calls.size(), test.expected_matches) << "code:\n" << test.code; @@ -94,14 +94,14 @@ TEST(GetMacroCallIdsTest, Various) { {"function f;\nf = `BAR10() * `FOO10();\nendfunction\n", {"`BAR10", "`FOO10"}}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.code, ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto macro_calls = FindAllMacroCalls(*ABSL_DIE_IF_NULL(root)); std::vector found_names; found_names.reserve(macro_calls.size()); - for (const auto& match : macro_calls) { + for (const auto &match : macro_calls) { found_names.push_back(GetMacroCallId(*match.match)->text()); } EXPECT_THAT(found_names, ElementsAreArray(test.expected_names)) @@ -129,13 +129,13 @@ TEST(MacroCallArgsTest, Emptiness) { {"function f;\nf = `BAR(`FOO());\nendfunction\n", false}, {"function f;\nf = `BAR() * `FOO();\nendfunction\n", true}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.code, ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto macro_calls = FindAllMacroCalls(*ABSL_DIE_IF_NULL(root)); ASSERT_FALSE(macro_calls.empty()); - const auto* args = GetMacroCallArgs(*macro_calls.front().match); + const auto *args = GetMacroCallArgs(*macro_calls.front().match); EXPECT_EQ(MacroCallArgsIsEmpty(*args), test.expect_empty) << "code:\n" << test.code; // TODO(b/151371397): check exact substrings @@ -152,17 +152,17 @@ TEST(GetFunctionFormalPortsGroupTest, WithFormalPorts) { {"task t;\n", {kTag, "`FOO"}, "\nendtask\n"}, {"module m;\n", {kTag, "`FOO"}, "\nendmodule\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { const absl::string_view code(test.code); VerilogAnalyzer analyzer(code, "test-file"); const absl::string_view code_copy(analyzer.Data().Contents()); ASSERT_OK(analyzer.Analyze()) << "failed on:\n" << code; - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto macro_items = FindAllMacroGenericItems(*root); ASSERT_EQ(macro_items.size(), 1); - const auto& macro_item = *macro_items.front().match; - const auto& id = GetMacroGenericItemId(macro_item); + const auto ¯o_item = *macro_items.front().match; + const auto &id = GetMacroGenericItemId(macro_item); const absl::string_view id_text = id->text(); // TODO(b/151371397): Refactor this test code along with @@ -212,15 +212,15 @@ TEST(FindAllMacroDefinitions, MacroName) { {kTag, "my_macro"}, " 10\n endclass\n module m(); int x = `TEN;\n endmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllMacroDefinitions(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& decl : decls) { - const auto* type = GetMacroName(*decl.match); + for (const auto &decl : decls) { + const auto *type = GetMacroName(*decl.match); names.push_back(TreeSearchMatch{type, {/* ignored context */}}); } return names; @@ -262,17 +262,17 @@ TEST(FindAllMacroDefinitions, MacroArgsName) { {kTag, "i"}, ") i\n endclass\n module m(); int x = `TEN(1);\n endmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllMacroDefinitions(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& decl : decls) { - const auto& args = FindAllMacroDefinitionsArgs(*decl.match); - for (const auto& arg : args) { - const auto* name = GetMacroArgName(*arg.match); + for (const auto &decl : decls) { + const auto &args = FindAllMacroDefinitionsArgs(*decl.match); + for (const auto &arg : args) { + const auto *name = GetMacroArgName(*arg.match); names.push_back(TreeSearchMatch{name, {/* ignored context */}}); } } @@ -291,16 +291,16 @@ TEST(FindAllPreprocessorInclude, IncludedFileName) { {"`include `d"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& includes = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &includes = FindAllPreprocessorInclude(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& include : includes) { - const auto* filename = + for (const auto &include : includes) { + const auto *filename = GetFileFromPreprocessorInclude(*include.match); if (filename == nullptr) { continue; diff --git a/verilog/CST/match_test_utils.cc b/verilog/CST/match_test_utils.cc index 4de7ad306..dbef328de 100644 --- a/verilog/CST/match_test_utils.cc +++ b/verilog/CST/match_test_utils.cc @@ -34,13 +34,13 @@ using verible::TextStructureView; using verible::TreeSearchMatch; void TestVerilogSyntaxRangeMatches( - absl::string_view test_name, const SyntaxTreeSearchTestCase& test_case, - const std::function(const TextStructureView&)>& - match_collector) { + absl::string_view test_name, const SyntaxTreeSearchTestCase &test_case, + const std::function(const TextStructureView &)> + &match_collector) { const absl::string_view code(test_case.code); // Parse Verilog source code into syntax tree. VerilogAnalyzer analyzer(code, "test-file"); - const TextStructureView& text_structure(analyzer.Data()); + const TextStructureView &text_structure(analyzer.Data()); const absl::string_view code_copy = text_structure.Contents(); ASSERT_OK(analyzer.Analyze()) << test_name << " failed on:\n" << code; diff --git a/verilog/CST/match_test_utils.h b/verilog/CST/match_test_utils.h index d7707369d..ef4811f66 100644 --- a/verilog/CST/match_test_utils.h +++ b/verilog/CST/match_test_utils.h @@ -31,9 +31,9 @@ namespace verilog { // Test will terminate early if there are lexical or syntax errors. void TestVerilogSyntaxRangeMatches( absl::string_view test_name, - const verible::SyntaxTreeSearchTestCase& test_case, + const verible::SyntaxTreeSearchTestCase &test_case, const std::function( - const verible::TextStructureView&)>& match_collector); + const verible::TextStructureView &)> &match_collector); } // namespace verilog diff --git a/verilog/CST/module.cc b/verilog/CST/module.cc index d32fceb4b..f0c6be289 100644 --- a/verilog/CST/module.cc +++ b/verilog/CST/module.cc @@ -33,72 +33,72 @@ using verible::SyntaxTreeNode; using verible::TokenInfo; std::vector FindAllModuleDeclarations( - const Symbol& root) { + const Symbol &root) { return SearchSyntaxTree(root, NodekModuleDeclaration()); } -std::vector FindAllModuleHeaders(const Symbol& root) { +std::vector FindAllModuleHeaders(const Symbol &root) { return SearchSyntaxTree(root, NodekModuleHeader()); } std::vector FindAllInterfaceDeclarations( - const verible::Symbol& root) { + const verible::Symbol &root) { return SearchSyntaxTree(root, NodekInterfaceDeclaration()); } std::vector FindAllProgramDeclarations( - const verible::Symbol& root) { + const verible::Symbol &root) { return SearchSyntaxTree(root, NodekProgramDeclaration()); } bool IsModuleOrInterfaceOrProgramDeclaration( - const SyntaxTreeNode& declaration) { + const SyntaxTreeNode &declaration) { return declaration.MatchesTagAnyOf({NodeEnum::kModuleDeclaration, NodeEnum::kInterfaceDeclaration, NodeEnum::kProgramDeclaration}); } -const SyntaxTreeNode* GetModuleHeader(const Symbol& module_declaration) { +const SyntaxTreeNode *GetModuleHeader(const Symbol &module_declaration) { if (module_declaration.Kind() != verible::SymbolKind::kNode) return nullptr; - const SyntaxTreeNode& module_node = + const SyntaxTreeNode &module_node = verible::SymbolCastToNode(module_declaration); if (!IsModuleOrInterfaceOrProgramDeclaration(module_node)) return nullptr; if (module_node.children().empty()) return nullptr; return &verible::SymbolCastToNode(*module_node[0].get()); } -const SyntaxTreeNode* GetInterfaceHeader(const Symbol& module_symbol) { +const SyntaxTreeNode *GetInterfaceHeader(const Symbol &module_symbol) { return verible::GetSubtreeAsNode(module_symbol, NodeEnum::kInterfaceDeclaration, 0, NodeEnum::kModuleHeader); } -const verible::SyntaxTreeLeaf* GetModuleName(const Symbol& s) { - const auto* header_node = GetModuleHeader(s); +const verible::SyntaxTreeLeaf *GetModuleName(const Symbol &s) { + const auto *header_node = GetModuleHeader(s); if (!header_node) return nullptr; return verible::GetSubtreeAsLeaf(*header_node, NodeEnum::kModuleHeader, 2); } -const TokenInfo* GetInterfaceNameToken(const Symbol& s) { - const auto* header_node = GetInterfaceHeader(s); +const TokenInfo *GetInterfaceNameToken(const Symbol &s) { + const auto *header_node = GetInterfaceHeader(s); if (!header_node) return nullptr; - const verible::SyntaxTreeLeaf* name_leaf = + const verible::SyntaxTreeLeaf *name_leaf = verible::GetSubtreeAsLeaf(*header_node, NodeEnum::kModuleHeader, 2); return name_leaf ? &name_leaf->get() : nullptr; } -const SyntaxTreeNode* GetModulePortParenGroup( - const Symbol& module_declaration) { - const auto* header_node = GetModuleHeader(module_declaration); +const SyntaxTreeNode *GetModulePortParenGroup( + const Symbol &module_declaration) { + const auto *header_node = GetModuleHeader(module_declaration); if (!header_node) return nullptr; - const auto* ports = + const auto *ports = verible::GetSubtreeAsSymbol(*header_node, NodeEnum::kModuleHeader, 5); return verible::CheckOptionalSymbolAsNode(ports, NodeEnum::kParenGroup); } -const SyntaxTreeNode* GetModulePortDeclarationList( - const Symbol& module_declaration) { - const auto* paren_group = GetModulePortParenGroup(module_declaration); +const SyntaxTreeNode *GetModulePortDeclarationList( + const Symbol &module_declaration) { + const auto *paren_group = GetModulePortParenGroup(module_declaration); if (verible::CheckOptionalSymbolAsNode(paren_group, NodeEnum::kParenGroup) == nullptr) { return nullptr; @@ -107,13 +107,13 @@ const SyntaxTreeNode* GetModulePortDeclarationList( NodeEnum::kPortDeclarationList); } -const verible::SyntaxTreeLeaf* GetModuleEndLabel( - const verible::Symbol& module_declaration) { - const SyntaxTreeNode& module_node = +const verible::SyntaxTreeLeaf *GetModuleEndLabel( + const verible::Symbol &module_declaration) { + const SyntaxTreeNode &module_node = verible::SymbolCastToNode(module_declaration); CHECK(IsModuleOrInterfaceOrProgramDeclaration(module_node)); - const auto* label_node = module_node[3].get(); + const auto *label_node = module_node[3].get(); if (label_node == nullptr) { return nullptr; } @@ -121,32 +121,32 @@ const verible::SyntaxTreeLeaf* GetModuleEndLabel( NodeEnum::kLabel, 1); } -const verible::SyntaxTreeNode* GetModuleItemList( - const verible::Symbol& module_declaration) { +const verible::SyntaxTreeNode *GetModuleItemList( + const verible::Symbol &module_declaration) { if (module_declaration.Kind() != verible::SymbolKind::kNode) return nullptr; - const SyntaxTreeNode& module_node = + const SyntaxTreeNode &module_node = verible::SymbolCastToNode(module_declaration); if (!IsModuleOrInterfaceOrProgramDeclaration(module_node)) return nullptr; if (module_node.children().size() < 2) return nullptr; - verible::Symbol* item = module_node[1].get(); + verible::Symbol *item = module_node[1].get(); return item ? &verible::SymbolCastToNode(*item) : nullptr; } -const verible::SyntaxTreeNode* GetParamDeclarationListFromModuleDeclaration( - const verible::Symbol& module_declaration) { - const auto* header_node = GetModuleHeader(module_declaration); +const verible::SyntaxTreeNode *GetParamDeclarationListFromModuleDeclaration( + const verible::Symbol &module_declaration) { + const auto *header_node = GetModuleHeader(module_declaration); if (!header_node) return nullptr; - const verible::Symbol* param_declaration_list = + const verible::Symbol *param_declaration_list = verible::GetSubtreeAsSymbol(*header_node, NodeEnum::kModuleHeader, 4); return verible::CheckOptionalSymbolAsNode( param_declaration_list, NodeEnum::kFormalParameterListDeclaration); } -const verible::SyntaxTreeNode* GetParamDeclarationListFromInterfaceDeclaration( - const verible::Symbol& interface_declaration) { - const auto* header_node = GetInterfaceHeader(interface_declaration); +const verible::SyntaxTreeNode *GetParamDeclarationListFromInterfaceDeclaration( + const verible::Symbol &interface_declaration) { + const auto *header_node = GetInterfaceHeader(interface_declaration); if (!header_node) return nullptr; - const verible::Symbol* param_declaration_list = + const verible::Symbol *param_declaration_list = verible::GetSubtreeAsSymbol(*header_node, NodeEnum::kModuleHeader, 4); return verible::CheckOptionalSymbolAsNode( param_declaration_list, NodeEnum::kFormalParameterListDeclaration); diff --git a/verilog/CST/module.h b/verilog/CST/module.h index eda47bc6f..371fe65b4 100644 --- a/verilog/CST/module.h +++ b/verilog/CST/module.h @@ -32,9 +32,9 @@ namespace verilog { template -verible::SymbolPtr MakeModuleHeader(T0&& keyword, T1&& lifetime, T2&& id, - T3&& imports, T4&& parameters, T5&& ports, - T6&& attribute, T7&& semi) { +verible::SymbolPtr MakeModuleHeader(T0 &&keyword, T1 &&lifetime, T2 &&id, + T3 &&imports, T4 &¶meters, T5 &&ports, + T6 &&attribute, T7 &&semi) { verible::SymbolCastToLeaf(*keyword); if (lifetime != nullptr) verible::SymbolCastToLeaf(*lifetime); verible::SymbolCastToLeaf(*id); // SymbolIdentifier or other identifier @@ -55,64 +55,64 @@ verible::SymbolPtr MakeModuleHeader(T0&& keyword, T1&& lifetime, T2&& id, // Find all module declarations. std::vector FindAllModuleDeclarations( - const verible::Symbol&); + const verible::Symbol &); // Find all module headers. std::vector FindAllModuleHeaders( - const verible::Symbol&); + const verible::Symbol &); // Find all interface declarations. std::vector FindAllInterfaceDeclarations( - const verible::Symbol&); + const verible::Symbol &); // Find all program declarations. std::vector FindAllProgramDeclarations( - const verible::Symbol& root); + const verible::Symbol &root); // Returns the full header of a module (params, ports, etc...). // Works also with interfaces and programs. -const verible::SyntaxTreeNode* GetModuleHeader(const verible::Symbol&); +const verible::SyntaxTreeNode *GetModuleHeader(const verible::Symbol &); // Returns the full header of an interface (params, ports, etc...). -const verible::SyntaxTreeNode* GetInterfaceHeader(const verible::Symbol&); +const verible::SyntaxTreeNode *GetInterfaceHeader(const verible::Symbol &); // Extract the subnode of a module declaration that is the module name or // nullptr if not found. -const verible::SyntaxTreeLeaf* GetModuleName(const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetModuleName(const verible::Symbol &); // Extract the subnode of an interface declaration that is the module name. -const verible::TokenInfo* GetInterfaceNameToken(const verible::Symbol&); +const verible::TokenInfo *GetInterfaceNameToken(const verible::Symbol &); // Returns the node spanning the module's port paren group, or nullptr. // e.g. from "module foo(input x); endmodule", this returns the node that spans // "(input x)", including parentheses. -const verible::SyntaxTreeNode* GetModulePortParenGroup( - const verible::Symbol& module_declaration); +const verible::SyntaxTreeNode *GetModulePortParenGroup( + const verible::Symbol &module_declaration); // Returns the node spanning module's port declarations list, or nullptr. // e.g. from "module foo(input x); endmodule", this returns the node that spans // PortDescriptionList -const verible::SyntaxTreeNode* GetModulePortDeclarationList( - const verible::Symbol& module_declaration); +const verible::SyntaxTreeNode *GetModulePortDeclarationList( + const verible::Symbol &module_declaration); // Returns module name leaf after endmodule. // e.g. from "module foo(); endmodule: foo" returns the second "foo". -const verible::SyntaxTreeLeaf* GetModuleEndLabel(const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetModuleEndLabel(const verible::Symbol &); // Returns the node spanning module's Item list. -const verible::SyntaxTreeNode* GetModuleItemList( - const verible::Symbol& module_declaration); +const verible::SyntaxTreeNode *GetModuleItemList( + const verible::Symbol &module_declaration); // Extract the subnode of a param declaration list from module decalration. // e.g module m#(parameter x = 2) return the node spanning "#(parameter x = 2)". -const verible::SyntaxTreeNode* GetParamDeclarationListFromModuleDeclaration( - const verible::Symbol&); +const verible::SyntaxTreeNode *GetParamDeclarationListFromModuleDeclaration( + const verible::Symbol &); // Extract the subnode of a param declaration list from interface decalration. // e.g interface m#(parameter x = 2) return the node spanning "#(parameter x = // 2)". -const verible::SyntaxTreeNode* GetParamDeclarationListFromInterfaceDeclaration( - const verible::Symbol&); +const verible::SyntaxTreeNode *GetParamDeclarationListFromInterfaceDeclaration( + const verible::Symbol &); } // namespace verilog diff --git a/verilog/CST/module_test.cc b/verilog/CST/module_test.cc index 3dc45f84a..f7193e5c2 100644 --- a/verilog/CST/module_test.cc +++ b/verilog/CST/module_test.cc @@ -56,7 +56,7 @@ using verible::TreeSearchMatch; TEST(FindAllModuleDeclarationsTest, EmptySource) { VerilogAnalyzer analyzer("", ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto module_declarations = FindAllModuleDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(module_declarations.empty()); @@ -65,7 +65,7 @@ TEST(FindAllModuleDeclarationsTest, EmptySource) { TEST(FindAllModuleDeclarationsTest, NonModule) { VerilogAnalyzer analyzer("class foo; endclass", ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto module_declarations = FindAllModuleDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(module_declarations.empty()); @@ -74,7 +74,7 @@ TEST(FindAllModuleDeclarationsTest, NonModule) { TEST(FindAllModuleDeclarationsTest, OneModule) { VerilogAnalyzer analyzer("module mod; endmodule", ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto module_declarations = FindAllModuleDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_EQ(module_declarations.size(), 1); @@ -93,7 +93,7 @@ endclass )", ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto module_declarations = FindAllModuleDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_EQ(module_declarations.size(), 2); @@ -102,7 +102,7 @@ endclass TEST(GetModuleNameTokenTest, RootIsNotAModule) { VerilogAnalyzer analyzer("module foo; endmodule", ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); // Root node is a description list, not a module. // If this happens, it is a programmer error, not user error. EXPECT_EQ(GetModuleName(*ABSL_DIE_IF_NULL(root)), nullptr); @@ -115,16 +115,16 @@ TEST(GetModuleNameTokenTest, ValidModule) { {"interface m;\nendinterface\n"}, {"module ", {kTag, "foo"}, "; endmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& programs = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &programs = FindAllModuleDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& instance : programs) { - const auto* name = GetModuleName(*instance.match); + for (const auto &instance : programs) { + const auto *name = GetModuleName(*instance.match); names.emplace_back(TreeSearchMatch{name, {/* ignored context */}}); } return names; @@ -139,16 +139,16 @@ TEST(GetModuleNameTokenTest, ValidInterface) { {"module m;\nendmodule\n"}, {"interface ", {kTag, "foo"}, "; endinterface"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& programs = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &programs = FindAllInterfaceDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& instance : programs) { - const auto* name = GetModuleName(*instance.match); + for (const auto &instance : programs) { + const auto *name = GetModuleName(*instance.match); names.emplace_back(TreeSearchMatch{name, {/* ignored context */}}); } return names; @@ -163,16 +163,16 @@ TEST(GetModuleNameTokenTest, ValidProgram) { {"module m;\nendmodule\n"}, {"program ", {kTag, "foo"}, "; endprogram"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& programs = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &programs = FindAllProgramDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& instance : programs) { - const auto* name = GetModuleName(*instance.match); + for (const auto &instance : programs) { + const auto *name = GetModuleName(*instance.match); names.emplace_back(TreeSearchMatch{name, {/* ignored context */}}); } return names; @@ -194,16 +194,16 @@ TEST(GetModulePortDeclarationListTest, ModulePorts) { {"module m", {kTag, "(\ninput clk\n)"}, ";\nendmodule\n"}, {"module m", {kTag, "(\ninput clk,\noutput foo\n)"}, ";\nendmodule\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& modules = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &modules = FindAllModuleDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector groups; - for (const auto& instance : modules) { - const auto* group = GetModulePortParenGroup(*instance.match); + for (const auto &instance : modules) { + const auto *group = GetModulePortParenGroup(*instance.match); if (group == nullptr) { continue; } @@ -228,16 +228,16 @@ TEST(FindAllModuleDeclarationTest, FindModuleParameters) { {kTag, "#(parameter int x = 3,\n parameter logic y = 4)"}, "();\nendmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllModuleDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector params; - for (const auto& instance : instances) { - const auto* decl = + for (const auto &instance : instances) { + const auto *decl = GetParamDeclarationListFromModuleDeclaration(*instance.match); if (decl == nullptr) { continue; @@ -262,16 +262,16 @@ TEST(FindAllInterfaceDeclarationTest, FindInterfaceParameters) { {kTag, "#(parameter int x = 3,\n parameter logic y = 4)"}, "();\nendinterface"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllInterfaceDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector params; - for (const auto& instance : instances) { - const auto* decl = GetParamDeclarationListFromInterfaceDeclaration( + for (const auto &instance : instances) { + const auto *decl = GetParamDeclarationListFromInterfaceDeclaration( *instance.match); if (decl == nullptr) { continue; @@ -291,16 +291,16 @@ TEST(GetModulePortDeclarationListTest, ModulePortList) { {"module m(", {kTag, "input clk, y"}, ");\nendmodule\n"}, {"module m;\nendmodule\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllModuleDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector lists; - for (const auto& instance : instances) { - const auto* list = GetModulePortDeclarationList(*instance.match); + for (const auto &instance : instances) { + const auto *list = GetModulePortDeclarationList(*instance.match); if (list == nullptr) { continue; } @@ -319,16 +319,16 @@ TEST(GetInterfacePortDeclarationListTest, InterfacePortList) { {"interface m(", {kTag, "input clk, y"}, ");\nendinterface\n"}, {"interface m;\nendinterface\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllInterfaceDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector lists; - for (const auto& instance : instances) { - const auto* list = GetModulePortDeclarationList(*instance.match); + for (const auto &instance : instances) { + const auto *list = GetModulePortDeclarationList(*instance.match); if (list == nullptr) { continue; } @@ -347,16 +347,16 @@ TEST(GetProgramPortDeclarationListTest, ProgramPortList) { {"program m(", {kTag, "input clk, y"}, ");\nendprogram\n"}, {"program m;\nendprogram\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllProgramDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector lists; - for (const auto& instance : instances) { - const auto* list = GetModulePortDeclarationList(*instance.match); + for (const auto &instance : instances) { + const auto *list = GetModulePortDeclarationList(*instance.match); if (list == nullptr) { continue; } @@ -378,16 +378,16 @@ TEST(FindModuleEndTest, ModuleEndName) { {"interface m;\nendinterface: m"}, {"program m;\nendprogram: m"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllModuleDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector labels; - for (const auto& instance : instances) { - const auto* label = GetModuleEndLabel(*instance.match); + for (const auto &instance : instances) { + const auto *label = GetModuleEndLabel(*instance.match); if (label == nullptr) { continue; } @@ -410,16 +410,16 @@ TEST(FindInterfaceEndTest, InterfaceEndName) { {"interface m;\nendinterface: ", {kTag, "m"}}, {"program m;\nendprogram: m"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllInterfaceDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector labels; - for (const auto& instance : instances) { - const auto* label = GetModuleEndLabel(*instance.match); + for (const auto &instance : instances) { + const auto *label = GetModuleEndLabel(*instance.match); if (label == nullptr) { continue; } @@ -442,16 +442,16 @@ TEST(FindProgramEndTest, ProgramEndName) { {"interface m;\nendinterface: m"}, {"program m;\nendprogram: ", {kTag, "m"}}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllProgramDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector labels; - for (const auto& instance : instances) { - const auto* label = GetModuleEndLabel(*instance.match); + for (const auto &instance : instances) { + const auto *label = GetModuleEndLabel(*instance.match); if (label == nullptr) { continue; } @@ -467,7 +467,7 @@ TEST(FindProgramEndTest, ProgramEndName) { TEST(FindAllModuleHeadersTest, MatchesProgram) { VerilogAnalyzer analyzer("program p;\nendprogram\n", ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto module_headers = FindAllModuleHeaders(*ABSL_DIE_IF_NULL(root)); EXPECT_EQ(module_headers.size(), 1); } @@ -476,7 +476,7 @@ TEST(FindAllModuleHeadersTest, MatchesProgram) { TEST(FindAllModuleHeadersTest, MatchesInterface) { VerilogAnalyzer analyzer("interface m;\nendinterface\n", ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto module_headers = FindAllModuleHeaders(*ABSL_DIE_IF_NULL(root)); EXPECT_EQ(module_headers.size(), 1); } @@ -485,7 +485,7 @@ TEST(FindAllModuleHeadersTest, MatchesInterface) { TEST(FindAllModuleHeadersTest, ClassNoMatch) { VerilogAnalyzer analyzer("class foo; endclass", ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto module_headers = FindAllModuleHeaders(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(module_headers.empty()); } diff --git a/verilog/CST/net.cc b/verilog/CST/net.cc index abbad2a6c..97efb07bc 100644 --- a/verilog/CST/net.cc +++ b/verilog/CST/net.cc @@ -32,12 +32,12 @@ using verible::Symbol; using verible::TokenInfo; std::vector FindAllNetDeclarations( - const verible::Symbol& root) { + const verible::Symbol &root) { return SearchSyntaxTree(root, NodekNetDeclaration()); } // Helper predicate to match all types of applicable nets -static bool ExpectedTagPredicate(const Symbol& symbol) { +static bool ExpectedTagPredicate(const Symbol &symbol) { verible::SymbolTag var_symbol = {verible::SymbolKind::kNode, static_cast(NodeEnum::kNetVariable)}; verible::SymbolTag assign_symbol = { @@ -54,22 +54,22 @@ static bool ExpectedTagPredicate(const Symbol& symbol) { return symbol.Tag() == var_symbol || symbol.Tag() == assign_symbol; } -const verible::SyntaxTreeLeaf* GetNameLeafOfNetVariable( - const verible::Symbol& net_variable) { +const verible::SyntaxTreeLeaf *GetNameLeafOfNetVariable( + const verible::Symbol &net_variable) { return verible::GetSubtreeAsLeaf(net_variable, NodeEnum::kNetVariable, 0); } -const verible::SyntaxTreeLeaf* GetNameLeafOfRegisterVariable( - const verible::Symbol& register_variable) { +const verible::SyntaxTreeLeaf *GetNameLeafOfRegisterVariable( + const verible::Symbol ®ister_variable) { return verible::GetSubtreeAsLeaf(register_variable, NodeEnum::kRegisterVariable, 0); } -std::vector GetIdentifiersFromNetDeclaration( - const Symbol& symbol) { +std::vector GetIdentifiersFromNetDeclaration( + const Symbol &symbol) { // TODO: re-implement this without search, instead using direct access for // efficiency. - std::vector identifiers; + std::vector identifiers; auto matcher = verible::matcher::Matcher(ExpectedTagPredicate, verible::matcher::InnerMatchAll); @@ -77,10 +77,10 @@ std::vector GetIdentifiersFromNetDeclaration( std::vector identifier_nodes = SearchSyntaxTree(symbol, matcher); - for (auto& id : identifier_nodes) { - const auto* identifier = SymbolCastToNode(*id.match)[0].get(); + for (auto &id : identifier_nodes) { + const auto *identifier = SymbolCastToNode(*id.match)[0].get(); if (!identifier) continue; - const auto* identifier_leaf = AutoUnwrapIdentifier(*identifier); + const auto *identifier_leaf = AutoUnwrapIdentifier(*identifier); if (!identifier_leaf) continue; identifiers.push_back(&identifier_leaf->get()); diff --git a/verilog/CST/net.h b/verilog/CST/net.h index ba960dccf..151789d51 100644 --- a/verilog/CST/net.h +++ b/verilog/CST/net.h @@ -32,19 +32,19 @@ namespace verilog { // See port.h for port declarations. // TODO(b/132652866): handle data declarations like 'logic' and 'reg'. std::vector FindAllNetDeclarations( - const verible::Symbol&); + const verible::Symbol &); // Returns tokens that correspond to declared names in net declarations -std::vector GetIdentifiersFromNetDeclaration( - const verible::Symbol& symbol); +std::vector GetIdentifiersFromNetDeclaration( + const verible::Symbol &symbol); // Returns the declared identifier from a kNetVariable or nullptr if invalid. -const verible::SyntaxTreeLeaf* GetNameLeafOfNetVariable( - const verible::Symbol& net_variable); +const verible::SyntaxTreeLeaf *GetNameLeafOfNetVariable( + const verible::Symbol &net_variable); // Returns the declared identifier from a kRegisterVariable. -const verible::SyntaxTreeLeaf* GetNameLeafOfRegisterVariable( - const verible::Symbol& register_variable); +const verible::SyntaxTreeLeaf *GetNameLeafOfRegisterVariable( + const verible::Symbol ®ister_variable); } // namespace verilog diff --git a/verilog/CST/net_test.cc b/verilog/CST/net_test.cc index 5fcae0773..79a6ed2d6 100644 --- a/verilog/CST/net_test.cc +++ b/verilog/CST/net_test.cc @@ -51,7 +51,7 @@ using verible::TreeSearchMatch; TEST(FindAllNetDeclarationsTest, EmptySource) { VerilogAnalyzer analyzer("", ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = FindAllNetDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(net_declarations.empty()); } @@ -60,13 +60,13 @@ TEST(FindAllNetDeclarationsTest, EmptySource) { TEST(FindAllNetDeclarationsTest, NonNet) { VerilogAnalyzer analyzer("class foo; endclass", ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = FindAllNetDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(net_declarations.empty()); } // Declarations of single nets, used across multiple tests. Semicolon omitted. -static const char* kSingleDeclTestCases[] = { +static const char *kSingleDeclTestCases[] = { "wire w", "wire [7:0] w", "wire w [0:3]", "wire w [4]", "wire [7:0] w [0:3]", }; @@ -77,11 +77,11 @@ TEST(FindAllNetDeclarationsTest, OneWireNet) { VerilogAnalyzer analyzer(absl::StrCat(test, ";"), ""); EXPECT_TRUE(true) << "code: " << test; EXPECT_OK(analyzer.Analyze()) << "code: " << test; - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = FindAllNetDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_EQ(net_declarations.size(), 1); - const auto& decl = net_declarations.front(); + const auto &decl = net_declarations.front(); EXPECT_FALSE(decl.context.IsInside(NodeEnum::kModuleDeclaration)); } } @@ -98,7 +98,7 @@ endclass )", ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = FindAllNetDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_EQ(net_declarations.size(), 2); } @@ -107,7 +107,7 @@ endclass TEST(FindAllNetDeclarationsTest, OneNetWithDimensions) { VerilogAnalyzer analyzer("wire [7:0] w [0:3];", ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = FindAllNetDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_EQ(net_declarations.size(), 1); } @@ -118,7 +118,7 @@ TEST(FindAllNetDeclarationsTest, OnePortInModule) { VerilogAnalyzer analyzer(absl::StrCat("module m(", test, "); endmodule"), ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = FindAllNetDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(net_declarations.empty()); @@ -131,11 +131,11 @@ TEST(FindAllNetDeclarationsTest, OneLocalNetInModule) { VerilogAnalyzer analyzer(absl::StrCat("module m;", test, "; endmodule"), ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = FindAllNetDeclarations(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(net_declarations.size(), 1); - const auto& decl = net_declarations.front(); + const auto &decl = net_declarations.front(); EXPECT_TRUE(decl.context.IsInside(NodeEnum::kModuleDeclaration)); } } @@ -143,7 +143,7 @@ TEST(FindAllNetDeclarationsTest, OneLocalNetInModule) { TEST(GetIdentifiersFromNetDeclarationTest, EmptySource) { VerilogAnalyzer analyzer("", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = GetIdentifiersFromNetDeclaration(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(net_declarations.empty()); @@ -152,7 +152,7 @@ TEST(GetIdentifiersFromNetDeclarationTest, EmptySource) { TEST(GetIdentifiersFromNetDeclarationTest, NoNet) { VerilogAnalyzer analyzer("module foo; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = GetIdentifiersFromNetDeclaration(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(net_declarations.empty()); @@ -161,7 +161,7 @@ TEST(GetIdentifiersFromNetDeclarationTest, NoNet) { TEST(GetIdentifiersFromNetDeclarationTest, OneVariable) { VerilogAnalyzer analyzer("module foo; wire v; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = GetIdentifiersFromNetDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(net_declarations.size(), 1); @@ -171,7 +171,7 @@ TEST(GetIdentifiersFromNetDeclarationTest, OneVariable) { TEST(GetIdentifiersFromNetDeclarationTest, MultipleVariables) { VerilogAnalyzer analyzer("module foo; wire x; wire y; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = GetIdentifiersFromNetDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(net_declarations.size(), 2); @@ -182,7 +182,7 @@ TEST(GetIdentifiersFromNetDeclarationTest, MultipleVariables) { TEST(GetIdentifiersFromNetDeclarationTest, MultipleInlineVariables) { VerilogAnalyzer analyzer("module foo; wire x, y, z; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = GetIdentifiersFromNetDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(net_declarations.size(), 3); @@ -194,7 +194,7 @@ TEST(GetIdentifiersFromNetDeclarationTest, MultipleInlineVariables) { TEST(GetIdentifiersFromNetDeclarationTest, MultipleMixedVariables) { VerilogAnalyzer analyzer("module foo; wire x, y, z; wire a; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = GetIdentifiersFromNetDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(net_declarations.size(), 4); @@ -207,7 +207,7 @@ TEST(GetIdentifiersFromNetDeclarationTest, MultipleMixedVariables) { TEST(GetIdentifiersFromNetDeclarationTest, DoNotMatchArrayDeclarations) { VerilogAnalyzer analyzer("module top; wire v[M:N]; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = GetIdentifiersFromNetDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(net_declarations.size(), 1); @@ -217,7 +217,7 @@ TEST(GetIdentifiersFromNetDeclarationTest, DoNotMatchArrayDeclarations) { TEST(GetIdentifiersFromNetDeclarationTest, DoNotMatchNetArrayDeclarations) { VerilogAnalyzer analyzer("module top; wire[X:Z] v[M:N]; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = GetIdentifiersFromNetDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(net_declarations.size(), 1); @@ -227,7 +227,7 @@ TEST(GetIdentifiersFromNetDeclarationTest, DoNotMatchNetArrayDeclarations) { TEST(GetIdentifiersFromNetDeclarationTest, DoNotMatchNetType) { VerilogAnalyzer analyzer("module top; wire othertype v; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = GetIdentifiersFromNetDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(net_declarations.size(), 1); @@ -237,7 +237,7 @@ TEST(GetIdentifiersFromNetDeclarationTest, DoNotMatchNetType) { TEST(GetIdentifiersFromNetDeclarationTest, DoNotMatchAssignedVariables) { VerilogAnalyzer analyzer("module top; wire v = z; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto net_declarations = GetIdentifiersFromNetDeclaration(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(net_declarations.size(), 1); @@ -291,16 +291,16 @@ TEST(GetNameLeafOfNetVariableTest, Various) { "endmodule\n", }, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VLOG(1) << "code:\n" << test.code; TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& net_decls = FindAllNetVariables(*ABSL_DIE_IF_NULL(root)); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &net_decls = FindAllNetVariables(*ABSL_DIE_IF_NULL(root)); std::vector net_ids; - for (const auto& decl : net_decls) { - const auto* net_name = GetNameLeafOfNetVariable(*decl.match); + for (const auto &decl : net_decls) { + const auto *net_name = GetNameLeafOfNetVariable(*decl.match); net_ids.emplace_back( TreeSearchMatch{net_name, {/* ignored context */}}); } @@ -356,17 +356,17 @@ TEST(GetNameLeafOfRegisterVariableTest, Various) { "endmodule\n", }, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VLOG(1) << "code:\n" << test.code; TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& net_decls = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &net_decls = FindAllRegisterVariables(*ABSL_DIE_IF_NULL(root)); std::vector net_ids; - for (const auto& decl : net_decls) { - const auto* net_name = GetNameLeafOfRegisterVariable(*decl.match); + for (const auto &decl : net_decls) { + const auto *net_name = GetNameLeafOfRegisterVariable(*decl.match); net_ids.emplace_back( TreeSearchMatch{net_name, {/* ignored context */}}); } diff --git a/verilog/CST/numbers.cc b/verilog/CST/numbers.cc index 9805e9b0e..a411cb4fe 100644 --- a/verilog/CST/numbers.cc +++ b/verilog/CST/numbers.cc @@ -27,7 +27,7 @@ namespace verilog { namespace analysis { -std::ostream& operator<<(std::ostream& stream, const BasedNumber& number) { +std::ostream &operator<<(std::ostream &stream, const BasedNumber &number) { if (number.ok) { stream << "base:" << number.base << " signed:" << number.signedness << " literal:" << number.literal; diff --git a/verilog/CST/numbers.h b/verilog/CST/numbers.h index dd22a3f7e..f49ea1567 100644 --- a/verilog/CST/numbers.h +++ b/verilog/CST/numbers.h @@ -50,13 +50,13 @@ struct BasedNumber { BasedNumber(char base_, bool sign_, absl::string_view text) : base(base_), signedness(sign_), literal(text), ok(true) {} - bool operator==(const BasedNumber& rhs) const { + bool operator==(const BasedNumber &rhs) const { return base == rhs.base && signedness == rhs.signedness && literal == rhs.literal && ok && rhs.ok; } }; -std::ostream& operator<<(std::ostream& stream, const BasedNumber& number); +std::ostream &operator<<(std::ostream &stream, const BasedNumber &number); } // namespace analysis } // namespace verilog diff --git a/verilog/CST/numbers_test.cc b/verilog/CST/numbers_test.cc index 683ed1559..db3fe87fb 100644 --- a/verilog/CST/numbers_test.cc +++ b/verilog/CST/numbers_test.cc @@ -51,7 +51,7 @@ TEST(BasedNumberTest, ParseLiteral) { {"\'H", "FEED_face", {'h', false, "FEEDface"}}, {"\'sh", "ADee", {'h', true, "ADee"}}, }; - for (const auto& test : test_cases) { + for (const auto &test : test_cases) { const BasedNumber actual(test.base, test.digits); EXPECT_TRUE(actual.ok); EXPECT_EQ(test.expected, actual); @@ -66,7 +66,7 @@ TEST(BasedNumberTest, ParseInvalidLiterals) { {"", "96"}, {"1'b", "1"}, // valid literals start with ' }; - for (const auto& test : test_cases) { + for (const auto &test : test_cases) { const BasedNumber actual(test.first, test.second); EXPECT_FALSE(actual.ok); } diff --git a/verilog/CST/package.cc b/verilog/CST/package.cc index 6453ea701..0f34b9303 100644 --- a/verilog/CST/package.cc +++ b/verilog/CST/package.cc @@ -29,28 +29,28 @@ namespace verilog { std::vector FindAllPackageDeclarations( - const verible::Symbol& root) { + const verible::Symbol &root) { return SearchSyntaxTree(root, NodekPackageDeclaration()); } std::vector FindAllPackageImportItems( - const verible::Symbol& root) { + const verible::Symbol &root) { return SearchSyntaxTree(root, NodekPackageImportItem()); } -const verible::TokenInfo* GetPackageNameToken(const verible::Symbol& s) { - const auto* package_name = GetPackageNameLeaf(s); +const verible::TokenInfo *GetPackageNameToken(const verible::Symbol &s) { + const auto *package_name = GetPackageNameLeaf(s); if (!package_name) return nullptr; return &GetPackageNameLeaf(s)->get(); } -const verible::SyntaxTreeLeaf* GetPackageNameLeaf(const verible::Symbol& s) { +const verible::SyntaxTreeLeaf *GetPackageNameLeaf(const verible::Symbol &s) { return verible::GetSubtreeAsLeaf(s, NodeEnum::kPackageDeclaration, 2); } -const verible::SyntaxTreeLeaf* GetPackageNameEndLabel( - const verible::Symbol& package_declaration) { - const auto* label_node = verible::GetSubtreeAsSymbol( +const verible::SyntaxTreeLeaf *GetPackageNameEndLabel( + const verible::Symbol &package_declaration) { + const auto *label_node = verible::GetSubtreeAsSymbol( package_declaration, NodeEnum::kPackageDeclaration, 6); if (label_node == nullptr) { return nullptr; @@ -59,29 +59,29 @@ const verible::SyntaxTreeLeaf* GetPackageNameEndLabel( NodeEnum::kLabel, 1); } -const verible::Symbol* GetPackageItemList( - const verible::Symbol& package_declaration) { +const verible::Symbol *GetPackageItemList( + const verible::Symbol &package_declaration) { return verible::GetSubtreeAsSymbol(package_declaration, NodeEnum::kPackageDeclaration, 4); } -const verible::SyntaxTreeNode* GetScopePrefixFromPackageImportItem( - const verible::Symbol& package_import_item) { +const verible::SyntaxTreeNode *GetScopePrefixFromPackageImportItem( + const verible::Symbol &package_import_item) { return verible::GetSubtreeAsNode(package_import_item, NodeEnum::kPackageImportItem, 0, NodeEnum::kScopePrefix); } -const verible::SyntaxTreeLeaf* GetImportedPackageName( - const verible::Symbol& package_import_item) { - const auto* prefix = GetScopePrefixFromPackageImportItem(package_import_item); +const verible::SyntaxTreeLeaf *GetImportedPackageName( + const verible::Symbol &package_import_item) { + const auto *prefix = GetScopePrefixFromPackageImportItem(package_import_item); if (!prefix) return nullptr; return verible::GetSubtreeAsLeaf(*prefix, NodeEnum::kScopePrefix, 0); } -const verible::SyntaxTreeLeaf* GeImportedItemNameFromPackageImportItem( - const verible::Symbol& package_import_item) { - const verible::SyntaxTreeLeaf* imported_item = verible::GetSubtreeAsLeaf( +const verible::SyntaxTreeLeaf *GeImportedItemNameFromPackageImportItem( + const verible::Symbol &package_import_item) { + const verible::SyntaxTreeLeaf *imported_item = verible::GetSubtreeAsLeaf( package_import_item, NodeEnum::kPackageImportItem, 1); if (!imported_item || imported_item->get().token_enum() != diff --git a/verilog/CST/package.h b/verilog/CST/package.h index 054910d52..02205d06d 100644 --- a/verilog/CST/package.h +++ b/verilog/CST/package.h @@ -28,43 +28,43 @@ namespace verilog { // Find all package declarations. std::vector FindAllPackageDeclarations( - const verible::Symbol&); + const verible::Symbol &); // Find all package imports items. std::vector FindAllPackageImportItems( - const verible::Symbol& root); + const verible::Symbol &root); // Extract the subnode of a package declaration that is the package name. -const verible::TokenInfo* GetPackageNameToken(const verible::Symbol&); +const verible::TokenInfo *GetPackageNameToken(const verible::Symbol &); // Return the node spanning the name of the package. -const verible::SyntaxTreeLeaf* GetPackageNameLeaf(const verible::Symbol& s); +const verible::SyntaxTreeLeaf *GetPackageNameLeaf(const verible::Symbol &s); // Extracts the node that spans the name of the package after endpackage if // exists. -const verible::SyntaxTreeLeaf* GetPackageNameEndLabel( - const verible::Symbol& package_declaration); +const verible::SyntaxTreeLeaf *GetPackageNameEndLabel( + const verible::Symbol &package_declaration); // Extracts the node that spans the body of the package. -const verible::Symbol* GetPackageItemList( - const verible::Symbol& package_declaration); +const verible::Symbol *GetPackageItemList( + const verible::Symbol &package_declaration); // Extracts the node spanning the ScopePrefix node within PackageImportItem // node. -const verible::SyntaxTreeNode* GetScopePrefixFromPackageImportItem( - const verible::Symbol& package_import_item); +const verible::SyntaxTreeNode *GetScopePrefixFromPackageImportItem( + const verible::Symbol &package_import_item); // Extracts package name for package import (node tagged with // kPackageImportItem). // e.g import pkg::my_integer return the node spanning "pkg". -const verible::SyntaxTreeLeaf* GetImportedPackageName( - const verible::Symbol& package_import_item); +const verible::SyntaxTreeLeaf *GetImportedPackageName( + const verible::Symbol &package_import_item); // Extracts the symbol identifier from PackageImportItem if exits. // e.g import pkg::my_integer return the node spanning "my_integer". // return nullptr in case of import pkg::*. -const verible::SyntaxTreeLeaf* GeImportedItemNameFromPackageImportItem( - const verible::Symbol& package_import_item); +const verible::SyntaxTreeLeaf *GeImportedItemNameFromPackageImportItem( + const verible::Symbol &package_import_item); } // namespace verilog diff --git a/verilog/CST/package_test.cc b/verilog/CST/package_test.cc index 3fcd22351..28ff65c56 100644 --- a/verilog/CST/package_test.cc +++ b/verilog/CST/package_test.cc @@ -161,10 +161,10 @@ TEST(FindAllPackageDeclarationsTest, VariousTests) { "`endif\n", "`endif\n", {kTag, "package p; \n endpackage"}}}; - for (const auto& test : testcases) { + for (const auto &test : testcases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllPackageDeclarations(*ABSL_DIE_IF_NULL(root)); }); } @@ -293,16 +293,16 @@ TEST(GetPackageNameTokenTest, VariousPackageTokenTests) { "; \n endpackage", " localparam real foo = 323.846;\n"}}; - for (const auto& test : testcases) { + for (const auto &test : testcases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto declarations = FindAllPackageDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector declIdentifiers; - for (const auto& decl : declarations) { - const auto* packageToken = GetPackageNameLeaf(*decl.match); + for (const auto &decl : declarations) { + const auto *packageToken = GetPackageNameLeaf(*decl.match); declIdentifiers.push_back(TreeSearchMatch{packageToken, {}}); } return declIdentifiers; @@ -313,7 +313,7 @@ TEST(GetPackageNameTokenTest, VariousPackageTokenTests) { TEST(GetPackageNameTokenTest, RootIsNotAPackage) { VerilogAnalyzer analyzer("package foo; endpackage", ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); // Root node is a description list, not a package. EXPECT_EQ(GetPackageNameToken(*ABSL_DIE_IF_NULL(root)), nullptr); } @@ -321,13 +321,13 @@ TEST(GetPackageNameTokenTest, RootIsNotAPackage) { TEST(GetPackageNameTokenTest, ValidPackage) { VerilogAnalyzer analyzer("package foo; endpackage", ""); EXPECT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto package_declarations = FindAllPackageDeclarations(*root); EXPECT_EQ(package_declarations.size(), 1); - const auto& package_node = - down_cast(*package_declarations.front().match); + const auto &package_node = + down_cast(*package_declarations.front().match); // Root node is a description list, not a package. - const auto* token = GetPackageNameToken(package_node); + const auto *token = GetPackageNameToken(package_node); EXPECT_EQ(token->text(), "foo"); } @@ -343,17 +343,17 @@ TEST(GetPackageNameTest, GetPackageEndLabelName) { {kTag, "foo"}}, }; - for (const auto& test : testcases) { + for (const auto &test : testcases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto declarations = FindAllPackageDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& decl : declarations) { - const auto* package_name = GetPackageNameEndLabel(*decl.match); + for (const auto &decl : declarations) { + const auto *package_name = GetPackageNameEndLabel(*decl.match); if (package_name == nullptr) continue; names.push_back(TreeSearchMatch{package_name, {}}); } @@ -376,17 +376,17 @@ TEST(GetPackageBodyTest, GetPackageItemList) { "endpackage: foo"}, }; - for (const auto& test : testcases) { + for (const auto &test : testcases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto declarations = FindAllPackageDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector lists; - for (const auto& decl : declarations) { - const auto* package_item_list = GetPackageItemList(*decl.match); + for (const auto &decl : declarations) { + const auto *package_item_list = GetPackageItemList(*decl.match); if (package_item_list == nullptr) continue; lists.push_back(TreeSearchMatch{package_item_list, {}}); } @@ -409,15 +409,15 @@ TEST(PackageImportTest, GetImportedPackageName) { {kTag, "pkg"}, "::my_int;\n();\nendmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllPackageImportItems(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& decl : decls) { - const auto* name = GetImportedPackageName(*decl.match); + for (const auto &decl : decls) { + const auto *name = GetImportedPackageName(*decl.match); names.emplace_back(TreeSearchMatch{name, {/* ignored context */}}); } return names; @@ -450,15 +450,15 @@ TEST(PackageImportTest, GetImportedItemName) { {kTag, "my_class"}, ";\n();\n\nendmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllPackageImportItems(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& decl : decls) { - const auto* name = + for (const auto &decl : decls) { + const auto *name = GeImportedItemNameFromPackageImportItem(*decl.match); if (name == nullptr) continue; names.emplace_back(TreeSearchMatch{name, {/* ignored context*/}}); diff --git a/verilog/CST/parameters.cc b/verilog/CST/parameters.cc index e0817da56..d01007052 100644 --- a/verilog/CST/parameters.cc +++ b/verilog/CST/parameters.cc @@ -38,116 +38,116 @@ using verible::down_cast; using verible::SyntaxTreeLeaf; std::vector FindAllParamDeclarations( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekParamDeclaration()); } std::vector FindAllNamedParams( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekParamByName()); } -verilog_tokentype GetParamKeyword(const verible::Symbol& symbol) { +verilog_tokentype GetParamKeyword(const verible::Symbol &symbol) { // Currently the LRM is vague on what to do if no parameter/localparam is // declared, see example below. As such, if it's not declared, we will treat // it as a parameter. // // module foo #(int Bar = 1); endmodule // - const auto* param_keyword_symbol = + const auto *param_keyword_symbol = verible::GetSubtreeAsSymbol(symbol, NodeEnum::kParamDeclaration, 0); if (param_keyword_symbol == nullptr) return TK_parameter; - const auto* leaf = down_cast(param_keyword_symbol); + const auto *leaf = down_cast(param_keyword_symbol); return static_cast(leaf->get().token_enum()); } -const verible::Symbol* GetParamTypeSymbol(const verible::Symbol& symbol) { +const verible::Symbol *GetParamTypeSymbol(const verible::Symbol &symbol) { return verible::GetSubtreeAsSymbol(symbol, NodeEnum::kParamDeclaration, 1); } -const verible::TokenInfo* GetParameterNameToken(const verible::Symbol& symbol) { - const auto* param_type_symbol = GetParamTypeSymbol(symbol); +const verible::TokenInfo *GetParameterNameToken(const verible::Symbol &symbol) { + const auto *param_type_symbol = GetParamTypeSymbol(symbol); if (!param_type_symbol) return nullptr; // Check for implicit type declaration, in which case [2] will be a leaf. - const auto* identifier_symbol = + const auto *identifier_symbol = verible::GetSubtreeAsSymbol(*param_type_symbol, NodeEnum::kParamType, 2); if (!identifier_symbol) return nullptr; auto t = identifier_symbol->Tag(); - const SyntaxTreeLeaf* identifier_leaf = nullptr; + const SyntaxTreeLeaf *identifier_leaf = nullptr; if (t.kind == verible::SymbolKind::kNode) { identifier_leaf = GetIdentifier(*identifier_symbol); } else { - identifier_leaf = down_cast(identifier_symbol); + identifier_leaf = down_cast(identifier_symbol); } if (!identifier_leaf) return nullptr; return &identifier_leaf->get(); } -std::vector GetAllParameterNameTokens( - const verible::Symbol& symbol) { - std::vector identifiers; +std::vector GetAllParameterNameTokens( + const verible::Symbol &symbol) { + std::vector identifiers; identifiers.push_back(GetParameterNameToken(symbol)); - for (const auto* s : GetAllAssignedParameterSymbols(symbol)) { + for (const auto *s : GetAllAssignedParameterSymbols(symbol)) { identifiers.push_back(GetAssignedParameterNameToken(*s)); } return identifiers; } -const verible::TokenInfo* GetAssignedParameterNameToken( - const verible::Symbol& symbol) { - const auto* identifier = SymbolCastToNode(symbol)[0].get(); +const verible::TokenInfo *GetAssignedParameterNameToken( + const verible::Symbol &symbol) { + const auto *identifier = SymbolCastToNode(symbol)[0].get(); if (!identifier) return nullptr; return &AutoUnwrapIdentifier(*identifier)->get(); } -std::vector GetAllAssignedParameterSymbols( - const verible::Symbol& root) { - std::vector symbols; +std::vector GetAllAssignedParameterSymbols( + const verible::Symbol &root) { + std::vector symbols; - for (const auto& id : SearchSyntaxTree(root, NodekParameterAssign())) { + for (const auto &id : SearchSyntaxTree(root, NodekParameterAssign())) { symbols.push_back(id.match); } return symbols; } -const verible::TokenInfo* GetSymbolIdentifierFromParamDeclaration( - const verible::Symbol& symbol) { +const verible::TokenInfo *GetSymbolIdentifierFromParamDeclaration( + const verible::Symbol &symbol) { // Assert that symbol is a 'parameter type' declaration. if (!IsParamTypeDeclaration(symbol)) return nullptr; - const auto* type_symbol = GetTypeAssignmentFromParamDeclaration(symbol); + const auto *type_symbol = GetTypeAssignmentFromParamDeclaration(symbol); if (!type_symbol) return nullptr; - const auto* symbol_identifier_leaf = + const auto *symbol_identifier_leaf = GetIdentifierLeafFromTypeAssignment(*type_symbol); if (!symbol_identifier_leaf) return nullptr; return &symbol_identifier_leaf->get(); } -bool IsParamTypeDeclaration(const verible::Symbol& symbol) { +bool IsParamTypeDeclaration(const verible::Symbol &symbol) { // Assert that symbol is a parameter declaration. auto t = symbol.Tag(); CHECK_EQ(t.kind, verible::SymbolKind::kNode); CHECK_EQ(NodeEnum(t.tag), NodeEnum::kParamDeclaration); - const auto* param_type_symbol = GetParamTypeSymbol(symbol); + const auto *param_type_symbol = GetParamTypeSymbol(symbol); if (param_type_symbol->Kind() == verible::SymbolKind::kLeaf) { // Check that its token_enum is TK_type. - const auto* tk_type_leaf = - down_cast(param_type_symbol); + const auto *tk_type_leaf = + down_cast(param_type_symbol); CHECK_EQ(tk_type_leaf->get().token_enum(), TK_type); return true; } return false; } -const verible::SyntaxTreeNode* GetTypeAssignmentFromParamDeclaration( - const verible::Symbol& symbol) { +const verible::SyntaxTreeNode *GetTypeAssignmentFromParamDeclaration( + const verible::Symbol &symbol) { // Get the Type AssignmentList or kTypeAssignment symbol. - const auto* assignment_symbol = + const auto *assignment_symbol = verible::GetSubtreeAsSymbol(symbol, NodeEnum::kParamDeclaration, 2); if (assignment_symbol == nullptr) { return nullptr; @@ -161,7 +161,7 @@ const verible::SyntaxTreeNode* GetTypeAssignmentFromParamDeclaration( return &verible::SymbolCastToNode(*assignment_symbol); } if (NodeEnum(assignment_tag.tag) == NodeEnum::kTypeAssignmentList) { - const auto& type_symbol = verible::GetSubtreeAsNode( + const auto &type_symbol = verible::GetSubtreeAsNode( *assignment_symbol, NodeEnum::kTypeAssignmentList, 0, NodeEnum::kTypeAssignment); return type_symbol; @@ -170,14 +170,14 @@ const verible::SyntaxTreeNode* GetTypeAssignmentFromParamDeclaration( return nullptr; } -const verible::SyntaxTreeLeaf* GetIdentifierLeafFromTypeAssignment( - const verible::Symbol& symbol) { +const verible::SyntaxTreeLeaf *GetIdentifierLeafFromTypeAssignment( + const verible::Symbol &symbol) { return verible::GetSubtreeAsLeaf(symbol, NodeEnum::kTypeAssignment, 0); } -const verible::SyntaxTreeNode* GetExpressionFromTypeAssignment( - const verible::Symbol& type_assignment) { - const verible::Symbol* expression = verible::GetSubtreeAsSymbol( +const verible::SyntaxTreeNode *GetExpressionFromTypeAssignment( + const verible::Symbol &type_assignment) { + const verible::Symbol *expression = verible::GetSubtreeAsSymbol( type_assignment, NodeEnum::kTypeAssignment, 2); if (expression == nullptr || NodeEnum(expression->Tag().tag) != NodeEnum::kExpression) { @@ -186,8 +186,8 @@ const verible::SyntaxTreeNode* GetExpressionFromTypeAssignment( return &verible::SymbolCastToNode(*expression); } -const verible::Symbol* GetParamTypeInfoSymbol(const verible::Symbol& symbol) { - const auto* param_type_symbol = GetParamTypeSymbol(symbol); +const verible::Symbol *GetParamTypeInfoSymbol(const verible::Symbol &symbol) { + const auto *param_type_symbol = GetParamTypeSymbol(symbol); return verible::GetSubtreeAsSymbol(*param_type_symbol, NodeEnum::kParamType, 0); } @@ -198,9 +198,9 @@ struct EnumTokenIndex { NodeEnum expected_type; int next_index; }; -const verible::Symbol* TryDescentPath( - const verible::Symbol& symbol, std::initializer_list path) { - const verible::Symbol* value = &symbol; +const verible::Symbol *TryDescentPath( + const verible::Symbol &symbol, std::initializer_list path) { + const verible::Symbol *value = &symbol; for (auto p : path) { if (NodeEnum(value->Tag().tag) != p.expected_type) return nullptr; value = GetSubtreeAsSymbol(*value, p.expected_type, p.next_index); @@ -210,33 +210,33 @@ const verible::Symbol* TryDescentPath( } } // namespace -const verible::Symbol* GetParamAssignExpression(const verible::Symbol& symbol) { +const verible::Symbol *GetParamAssignExpression(const verible::Symbol &symbol) { return TryDescentPath(symbol, {{NodeEnum::kParamDeclaration, 2}, {NodeEnum::kTrailingAssign, 1}, {NodeEnum::kExpression, 0}}); } -bool IsTypeInfoEmpty(const verible::Symbol& symbol) { +bool IsTypeInfoEmpty(const verible::Symbol &symbol) { // Assert that symbol is NodekTypeInfo CHECK_EQ(symbol.Kind(), verible::SymbolKind::kNode); CHECK_EQ(NodeEnum(symbol.Tag().tag), NodeEnum::kTypeInfo); - const auto& type_info_node = verible::SymbolCastToNode(symbol); + const auto &type_info_node = verible::SymbolCastToNode(symbol); return (type_info_node[0] == nullptr && type_info_node[1] == nullptr && type_info_node[2] == nullptr); } -const verible::SyntaxTreeLeaf* GetNamedParamFromActualParam( - const verible::Symbol& param_by_name) { - const verible::SyntaxTreeLeaf* param_name = +const verible::SyntaxTreeLeaf *GetNamedParamFromActualParam( + const verible::Symbol ¶m_by_name) { + const verible::SyntaxTreeLeaf *param_name = verible::GetSubtreeAsLeaf(param_by_name, NodeEnum::kParamByName, 1); if (!param_name) return nullptr; return AutoUnwrapIdentifier(*param_name); } -const verible::SyntaxTreeNode* GetParenGroupFromActualParam( - const verible::Symbol& param_by_name) { +const verible::SyntaxTreeNode *GetParenGroupFromActualParam( + const verible::Symbol ¶m_by_name) { return verible::CheckOptionalSymbolAsNode( verible::GetSubtreeAsSymbol(param_by_name, NodeEnum::kParamByName, 2)); } diff --git a/verilog/CST/parameters.h b/verilog/CST/parameters.h index fb9d897c4..3b7210f6d 100644 --- a/verilog/CST/parameters.h +++ b/verilog/CST/parameters.h @@ -39,10 +39,10 @@ namespace verilog { // From "parameter type [dim] id [dim] = value;", // this node spans "type [dim] id [dim]." template -verible::SymbolPtr MakeParamTypeDeclaration(T0&& type_info, - T1&& packed_dimensions, - T2&& identifier, - T3&& unpacked_dimensions) { +verible::SymbolPtr MakeParamTypeDeclaration(T0 &&type_info, + T1 &&packed_dimensions, + T2 &&identifier, + T3 &&unpacked_dimensions) { CHECK(verible::SymbolCastToNode(*ABSL_DIE_IF_NULL(type_info)) .MatchesTag(NodeEnum::kTypeInfo)); return verible::MakeTaggedNode( @@ -53,8 +53,8 @@ verible::SymbolPtr MakeParamTypeDeclaration(T0&& type_info, // Creates a node tagged kTypeInfo, which holds the parameter type information. template -verible::SymbolPtr MakeTypeInfoNode(T0&& primitive_type, T1&& signed_unsigned, - T2&& user_defined_type) { +verible::SymbolPtr MakeTypeInfoNode(T0 &&primitive_type, T1 &&signed_unsigned, + T2 &&user_defined_type) { return verible::MakeTaggedNode( NodeEnum::kTypeInfo, std::forward(primitive_type), std::forward(signed_unsigned), std::forward(user_defined_type)); @@ -62,80 +62,80 @@ verible::SymbolPtr MakeTypeInfoNode(T0&& primitive_type, T1&& signed_unsigned, // Finds all parameter/localparam declarations. std::vector FindAllParamDeclarations( - const verible::Symbol&); + const verible::Symbol &); // Finds all nodes tagged with kParamByName. std::vector FindAllNamedParams( - const verible::Symbol&); + const verible::Symbol &); // Returns the token_enum of the parameter keyword from the node // kParamDeclaration (either TK_parameter or TK_localparam). -verilog_tokentype GetParamKeyword(const verible::Symbol&); +verilog_tokentype GetParamKeyword(const verible::Symbol &); // Returns a pointer to either TK_type or kParamType node, which holds the param // type, id, and dimensions info for that parameter. -const verible::Symbol* GetParamTypeSymbol(const verible::Symbol&); +const verible::Symbol *GetParamTypeSymbol(const verible::Symbol &); // Returns a pointer to the symbol holding the node kTypeInfo under the node // kParamDeclaration. -const verible::Symbol* GetParamTypeInfoSymbol(const verible::Symbol&); +const verible::Symbol *GetParamTypeInfoSymbol(const verible::Symbol &); // Get right-hand side of a parameter assignment expression. -const verible::Symbol* GetParamAssignExpression(const verible::Symbol& symbol); +const verible::Symbol *GetParamAssignExpression(const verible::Symbol &symbol); // Returns the token of the declared parameter. -const verible::TokenInfo* GetParameterNameToken(const verible::Symbol&); +const verible::TokenInfo *GetParameterNameToken(const verible::Symbol &); // Returns all tokens for a parameter declaration. -std::vector GetAllParameterNameTokens( - const verible::Symbol&); +std::vector GetAllParameterNameTokens( + const verible::Symbol &); // Get the token info for a given kParameterAssign node symbol -const verible::TokenInfo* GetAssignedParameterNameToken( - const verible::Symbol& symbol); +const verible::TokenInfo *GetAssignedParameterNameToken( + const verible::Symbol &symbol); // Get the symbols for all kParameterAssign nodes -std::vector GetAllAssignedParameterSymbols( - const verible::Symbol& root); +std::vector GetAllAssignedParameterSymbols( + const verible::Symbol &root); // Returns the token of the SymbolIdentifier from the node kParamDeclaration. // Used specifically for 'parameter type' declarations. -const verible::TokenInfo* GetSymbolIdentifierFromParamDeclaration( - const verible::Symbol&); +const verible::TokenInfo *GetSymbolIdentifierFromParamDeclaration( + const verible::Symbol &); // Returns true if the parameter is a parameter type declaration from the node // kParamDeclaration. -bool IsParamTypeDeclaration(const verible::Symbol&); +bool IsParamTypeDeclaration(const verible::Symbol &); // Returns a pointer to the symbol holding the node kTypeAssignment under the // node kParamDeclaration. -const verible::SyntaxTreeNode* GetTypeAssignmentFromParamDeclaration( - const verible::Symbol&); +const verible::SyntaxTreeNode *GetTypeAssignmentFromParamDeclaration( + const verible::Symbol &); // Returns a pointer to the identifier leaf holding the SymbolIdentifier under // the node kTypeAssignment. -const verible::SyntaxTreeLeaf* GetIdentifierLeafFromTypeAssignment( - const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetIdentifierLeafFromTypeAssignment( + const verible::Symbol &); // Returns a pointer to the expression node holding under the node // kTypeAssignment. // e.g from "class m(type x = y)" returns the node spanning "y". -const verible::SyntaxTreeNode* GetExpressionFromTypeAssignment( - const verible::Symbol&); +const verible::SyntaxTreeNode *GetExpressionFromTypeAssignment( + const verible::Symbol &); // Returns true if the node kTypeInfo is empty (all children are nullptr). -bool IsTypeInfoEmpty(const verible::Symbol&); +bool IsTypeInfoEmpty(const verible::Symbol &); // Return the node spanning param name from a node tagged with kParamByName. // e.g from "module_type #(.N(x))" return the leaf spanning "N". -const verible::SyntaxTreeLeaf* GetNamedParamFromActualParam( - const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetNamedParamFromActualParam( + const verible::Symbol &); // Return the node spanning the paren group from a node tagged with // kParamByName. // e.g from "module_type #(.N(x))" return the leaf spanning "(x)". -const verible::SyntaxTreeNode* GetParenGroupFromActualParam( - const verible::Symbol&); +const verible::SyntaxTreeNode *GetParenGroupFromActualParam( + const verible::Symbol &); } // namespace verilog diff --git a/verilog/CST/parameters_test.cc b/verilog/CST/parameters_test.cc index bef7b3dec..c8d4707e5 100644 --- a/verilog/CST/parameters_test.cc +++ b/verilog/CST/parameters_test.cc @@ -70,10 +70,10 @@ TEST(FindAllParamDeclarationsTest, BasicParams) { {{kTag, "parameter int Bar = 1;"}}, {{kTag, "parameter Bar = 1;"}}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllParamDeclarations(*ABSL_DIE_IF_NULL(root)); }); } @@ -87,13 +87,13 @@ TEST(GetParamKeywordTest, LocalParamDeclared) { {"class foo; localparam int Bar = 1; endclass", 1}, {"module foo; localparam Bar = 1; endmodule", 1}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.first, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto param_declarations = FindAllParamDeclarations(*root); ASSERT_EQ(param_declarations.size(), test.second); - const auto& param_node = down_cast( + const auto ¶m_node = down_cast( *param_declarations.front().match); const auto param_keyword = GetParamKeyword(param_node); EXPECT_EQ(param_keyword, TK_localparam); @@ -115,13 +115,13 @@ TEST(GetParamKeywordTest, ParameterDeclared) { {"parameter int Bar = 1;", 1}, {"parameter Bar = 1;", 1}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.first, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto param_declarations = FindAllParamDeclarations(*root); ASSERT_EQ(param_declarations.size(), test.second); - const auto& param_node = down_cast( + const auto ¶m_node = down_cast( *param_declarations.front().match); const auto param_keyword = GetParamKeyword(param_node); EXPECT_EQ(param_keyword, TK_parameter); @@ -136,21 +136,21 @@ TEST(GetParamKeywordTest, MultipleParamsDeclared) { "endmodule"}, {"class foo; parameter int Bar = 1; localparam int Bar_2 = 2; endclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto param_declarations = FindAllParamDeclarations(*root); // Make sure the first one is TK_parameter. - const auto& param_node = - down_cast(*param_declarations[0].match); + const auto ¶m_node = down_cast( + *param_declarations[0].match); const auto param_keyword = GetParamKeyword(param_node); EXPECT_EQ(param_keyword, TK_parameter); // Make sure the second one is TK_localparam. - const auto& localparam_node = - down_cast(*param_declarations[1].match); + const auto &localparam_node = down_cast( + *param_declarations[1].match); const auto localparam_keyword = GetParamKeyword(localparam_node); EXPECT_EQ(localparam_keyword, TK_localparam); } @@ -168,12 +168,12 @@ TEST(GetParamTypeSymbolTest, BasicTests) { {"package foo; parameter int Bar = 1; endpackage"}, {"parameter int Bar = 1;"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto param_declarations = FindAllParamDeclarations(*root); - const auto* param_type_symbol = + const auto *param_type_symbol = GetParamTypeSymbol(*param_declarations.front().match); const auto t = param_type_symbol->Tag(); EXPECT_EQ(t.kind, verible::SymbolKind::kNode); @@ -196,10 +196,10 @@ TEST(GetParameterNameTokenTest, BasicTests) { {"package foo; parameter int HELLO_WORLD = 1; endpackage", "HELLO_WORLD"}, {"parameter int Bar = 1;", "Bar"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.first, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto param_declarations = FindAllParamDeclarations(*root); const auto name_token = GetParameterNameToken(*param_declarations.front().match); @@ -227,10 +227,10 @@ TEST(GetAllParameterNameTokensTest, BasicTests) { {"module foo; parameter int Bar = 1, Foo = 1, Baz = 1; endmodule;", 3}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.first, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto param_declarations = FindAllParamDeclarations(*root); const auto name_tokens = GetAllParameterNameTokens(*param_declarations.front().match); @@ -259,10 +259,10 @@ TEST(GetAllAssignedParameterSymbolsTest, BasicTests) { {"module foo; parameter int Bar = 1, Foo = 1, Baz = 1; endmodule;", 2}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.first, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto param_declarations = FindAllParamDeclarations(*root); const auto assigned_parameters = GetAllAssignedParameterSymbols(*param_declarations.front().match); @@ -276,10 +276,10 @@ TEST(GetAssignedParameterNameToken, BasicTests) { {"module foo; parameter int Bar = 1, Fox = 1; endmodule;", "Fox"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.first, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto param_declarations = FindAllParamDeclarations(*root); const auto assigned_parameters = GetAllAssignedParameterSymbols(*param_declarations.front().match); @@ -304,10 +304,10 @@ TEST(GetSymbolIdentifierFromParamDeclarationTest, BasicTests) { {"package foo; parameter type HELLO_WORLD; endpackage", "HELLO_WORLD"}, {"parameter type Bar;", "Bar"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.first, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto param_declarations = FindAllParamDeclarations(*root); const auto name_token = GetSymbolIdentifierFromParamDeclaration( *param_declarations.front().match); @@ -334,10 +334,10 @@ TEST(IsParamTypeDeclarationTest, BasicTests) { {"class foo; localparam FooBar = 1; endclass", false}, {"package foo; parameter int HELLO_WORLD = 1; endpackage", false}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.first, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto param_declarations = FindAllParamDeclarations(*root); const auto is_param_type = IsParamTypeDeclaration(*param_declarations.front().match); @@ -359,12 +359,12 @@ TEST(GetTypeAssignmentFromParamDeclarationTests, BasicTests) { {"module m#(parameter type Bar)();\nendmodule"}, {"module m#(parameter Bar)();\nendmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto param_declarations = FindAllParamDeclarations(*root); - const auto* type_assignment_symbol = GetTypeAssignmentFromParamDeclaration( + const auto *type_assignment_symbol = GetTypeAssignmentFromParamDeclaration( *param_declarations.front().match); if (type_assignment_symbol == nullptr) { continue; @@ -389,14 +389,14 @@ TEST(GetIdentifierLeafFromTypeAssignmentTest, BasicTests) { {"package foo; parameter type ", {kTag, "HELLO_WORLD"}, "; endpackage"}, {"parameter type ", {kTag, "Bar"}, ";"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto param_declarations = FindAllParamDeclarations(*root); std::vector ids; - for (const auto& decl : param_declarations) { - const auto* type_assignment_symbol = + for (const auto &decl : param_declarations) { + const auto *type_assignment_symbol = GetTypeAssignmentFromParamDeclaration(*decl.match); ids.push_back(TreeSearchMatch{ GetIdentifierLeafFromTypeAssignment(*type_assignment_symbol), @@ -419,12 +419,12 @@ TEST(GetParamTypeInfoSymbolTest, BasicTests) { {"package foo; parameter int Bar = 1; endpackage"}, {"parameter int Bar = 1;"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto param_declarations = FindAllParamDeclarations(*root); - const auto* type_info_symbol = + const auto *type_info_symbol = GetParamTypeInfoSymbol(*param_declarations.front().match); const auto t = type_info_symbol->Tag(); EXPECT_EQ(t.kind, verible::SymbolKind::kNode); @@ -442,12 +442,12 @@ TEST(IsTypeInfoEmptyTest, EmptyTests) { {"package foo; parameter Bar = 1; endpackage"}, {"parameter Bar = 1;"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto param_declarations = FindAllParamDeclarations(*root); - const auto* type_info_symbol = + const auto *type_info_symbol = GetParamTypeInfoSymbol(*param_declarations.front().match); const auto t = type_info_symbol->Tag(); EXPECT_EQ(t.kind, verible::SymbolKind::kNode); @@ -479,12 +479,12 @@ TEST(IsTypeInfoEmptyTest, NonEmptyTests) { {"class foo #(parameter pkg::Other_t Bar); endclass"}, {"class foo #(parameter pkg::Other_t Bar = enum_e::value); endclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto param_declarations = FindAllParamDeclarations(*root); - const auto* type_info_symbol = + const auto *type_info_symbol = GetParamTypeInfoSymbol(*param_declarations.front().match); const auto t = type_info_symbol->Tag(); EXPECT_EQ(t.kind, verible::SymbolKind::kNode); @@ -511,15 +511,15 @@ TEST(FindAllParamByNameTest, FindNamesOfParams) { "(3)) y1();\nendmodule"}, {"module m;\n module_type #(x, y) y1();\nendmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = FindAllNamedParams(*ABSL_DIE_IF_NULL(root)); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllNamedParams(*ABSL_DIE_IF_NULL(root)); std::vector params; - for (const auto& instance : instances) { - const auto* decl = GetNamedParamFromActualParam(*instance.match); + for (const auto &instance : instances) { + const auto *decl = GetNamedParamFromActualParam(*instance.match); params.emplace_back(TreeSearchMatch{decl, {/* ignored context */}}); } @@ -547,15 +547,15 @@ TEST(FindAllParamByNameTest, FindParenGroupOfNamedParam) { {"module m;\n module_type #(x, y) y1();\nendmodule"}, {"module m;\n module_type #(.x, .y) y1();\nendmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = FindAllNamedParams(*ABSL_DIE_IF_NULL(root)); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllNamedParams(*ABSL_DIE_IF_NULL(root)); std::vector paren_groups; - for (const auto& instance : instances) { - const auto* paren_group = + for (const auto &instance : instances) { + const auto *paren_group = GetParenGroupFromActualParam(*instance.match); if (paren_group == nullptr) { continue; @@ -589,20 +589,20 @@ TEST(FindAllParamTest, FindExpressionFromParameterType) { {kTag, "Foo#(Baz#(int))"}, "); endmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& types = FindAllParamDeclarations(*ABSL_DIE_IF_NULL(root)); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &types = FindAllParamDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector expressions; - for (const auto& type : types) { - const auto* type_assignment = + for (const auto &type : types) { + const auto *type_assignment = GetTypeAssignmentFromParamDeclaration(*type.match); if (type_assignment == nullptr) { continue; } - const auto* expression = + const auto *expression = GetExpressionFromTypeAssignment(*type_assignment); if (expression == nullptr) { continue; diff --git a/verilog/CST/port.cc b/verilog/CST/port.cc index 4e7cfbc2f..87a18ca8a 100644 --- a/verilog/CST/port.cc +++ b/verilog/CST/port.cc @@ -33,34 +33,34 @@ using verible::Symbol; using verible::SyntaxTreeLeaf; std::vector FindAllPortDeclarations( - const Symbol& root) { + const Symbol &root) { return SearchSyntaxTree(root, NodekPortDeclaration()); } std::vector FindAllActualNamedPort( - const Symbol& root) { + const Symbol &root) { return SearchSyntaxTree(root, NodekActualNamedPort()); } std::vector FindAllPortReferences( - const verible::Symbol& root) { + const verible::Symbol &root) { return SearchSyntaxTree(root, NodekPort()); } std::vector FindAllTaskFunctionPortDeclarations( - const Symbol& root) { + const Symbol &root) { return SearchSyntaxTree(root, NodekPortItem()); } -const SyntaxTreeLeaf* GetIdentifierFromPortDeclaration(const Symbol& symbol) { - const auto* identifier_symbol = +const SyntaxTreeLeaf *GetIdentifierFromPortDeclaration(const Symbol &symbol) { + const auto *identifier_symbol = verible::GetSubtreeAsSymbol(symbol, NodeEnum::kPortDeclaration, 3); if (!identifier_symbol) return nullptr; return AutoUnwrapIdentifier(*identifier_symbol); } -const SyntaxTreeLeaf* GetDirectionFromPortDeclaration(const Symbol& symbol) { - if (const auto* dir_symbol = +const SyntaxTreeLeaf *GetDirectionFromPortDeclaration(const Symbol &symbol) { + if (const auto *dir_symbol = GetSubtreeAsSymbol(symbol, NodeEnum::kPortDeclaration, 0)) { return &SymbolCastToLeaf(*dir_symbol); } @@ -68,15 +68,15 @@ const SyntaxTreeLeaf* GetDirectionFromPortDeclaration(const Symbol& symbol) { } std::vector FindAllModulePortDeclarations( - const verible::Symbol& root) { + const verible::Symbol &root) { return SearchSyntaxTree(root, NodekModulePortDeclaration()); } -const verible::SyntaxTreeLeaf* GetIdentifierFromModulePortDeclaration( - const verible::Symbol& symbol) { - static const char* const TOO_MANY_IDS_ERROR = +const verible::SyntaxTreeLeaf *GetIdentifierFromModulePortDeclaration( + const verible::Symbol &symbol) { + static const char *const TOO_MANY_IDS_ERROR = "Expected one identifier node in module port declaration, but got "; - auto& node = SymbolCastToNode(symbol); + auto &node = SymbolCastToNode(symbol); if (!MatchNodeEnumOrNull(node, NodeEnum::kModulePortDeclaration)) { return nullptr; } @@ -96,39 +96,39 @@ const verible::SyntaxTreeLeaf* GetIdentifierFromModulePortDeclaration( *id_unpacked_dims.front().match); } -const verible::SyntaxTreeLeaf* GetDirectionFromModulePortDeclaration( - const verible::Symbol& symbol) { - if (const auto* dir_symbol = +const verible::SyntaxTreeLeaf *GetDirectionFromModulePortDeclaration( + const verible::Symbol &symbol) { + if (const auto *dir_symbol = GetSubtreeAsSymbol(symbol, NodeEnum::kModulePortDeclaration, 0)) { return &SymbolCastToLeaf(*dir_symbol); } return nullptr; } -const verible::SyntaxTreeLeaf* GetIdentifierFromPortReference( - const verible::Symbol& port_reference) { - const auto* identifier_symbol = +const verible::SyntaxTreeLeaf *GetIdentifierFromPortReference( + const verible::Symbol &port_reference) { + const auto *identifier_symbol = verible::GetSubtreeAsSymbol(port_reference, NodeEnum::kPortReference, 0); if (!identifier_symbol) return nullptr; return AutoUnwrapIdentifier(*identifier_symbol); } -const verible::SyntaxTreeNode* GetPortReferenceFromPort( - const verible::Symbol& port) { +const verible::SyntaxTreeNode *GetPortReferenceFromPort( + const verible::Symbol &port) { return verible::GetSubtreeAsNode(port, NodeEnum::kPort, 0, NodeEnum::kPortReference); } -static const verible::SyntaxTreeNode* -GetTypeIdDimensionsFromTaskFunctionPortItem(const Symbol& symbol) { +static const verible::SyntaxTreeNode * +GetTypeIdDimensionsFromTaskFunctionPortItem(const Symbol &symbol) { return verible::GetSubtreeAsNode( symbol, NodeEnum::kPortItem, 1, NodeEnum::kDataTypeImplicitBasicIdDimensions); } -const verible::SyntaxTreeNode* GetUnpackedDimensionsFromTaskFunctionPortItem( - const verible::Symbol& port_item) { - const auto& type_id_dimensions = +const verible::SyntaxTreeNode *GetUnpackedDimensionsFromTaskFunctionPortItem( + const verible::Symbol &port_item) { + const auto &type_id_dimensions = GetTypeIdDimensionsFromTaskFunctionPortItem(port_item); if (!type_id_dimensions) return nullptr; return verible::GetSubtreeAsNode(*type_id_dimensions, @@ -136,8 +136,8 @@ const verible::SyntaxTreeNode* GetUnpackedDimensionsFromTaskFunctionPortItem( 2, NodeEnum::kUnpackedDimensions); } -const Symbol* GetTypeOfTaskFunctionPortItem(const verible::Symbol& symbol) { - const auto& type_id_dimensions = +const Symbol *GetTypeOfTaskFunctionPortItem(const verible::Symbol &symbol) { + const auto &type_id_dimensions = GetTypeIdDimensionsFromTaskFunctionPortItem(symbol); if (!type_id_dimensions) return nullptr; return verible::GetSubtreeAsNode(*type_id_dimensions, @@ -145,24 +145,24 @@ const Symbol* GetTypeOfTaskFunctionPortItem(const verible::Symbol& symbol) { 0, NodeEnum::kDataType); } -const SyntaxTreeLeaf* GetIdentifierFromTaskFunctionPortItem( - const verible::Symbol& symbol) { - const auto* type_id_dimensions = +const SyntaxTreeLeaf *GetIdentifierFromTaskFunctionPortItem( + const verible::Symbol &symbol) { + const auto *type_id_dimensions = GetTypeIdDimensionsFromTaskFunctionPortItem(symbol); if (!type_id_dimensions) return nullptr; if (type_id_dimensions->children().size() <= 1) return nullptr; - const auto* port_item = (*type_id_dimensions)[1].get(); + const auto *port_item = (*type_id_dimensions)[1].get(); return port_item ? AutoUnwrapIdentifier(*port_item) : nullptr; } -const verible::SyntaxTreeLeaf* GetActualNamedPortName( - const verible::Symbol& actual_named_port) { +const verible::SyntaxTreeLeaf *GetActualNamedPortName( + const verible::Symbol &actual_named_port) { return verible::GetSubtreeAsLeaf(actual_named_port, NodeEnum::kActualNamedPort, 1); } -const verible::Symbol* GetActualNamedPortParenGroup( - const verible::Symbol& actual_named_port) { +const verible::Symbol *GetActualNamedPortParenGroup( + const verible::Symbol &actual_named_port) { return verible::GetSubtreeAsSymbol(actual_named_port, NodeEnum::kActualNamedPort, 2); } diff --git a/verilog/CST/port.h b/verilog/CST/port.h index 7ff13afae..138b08851 100644 --- a/verilog/CST/port.h +++ b/verilog/CST/port.h @@ -31,54 +31,55 @@ namespace verilog { // Find all individual port declarations. std::vector FindAllPortDeclarations( - const verible::Symbol&); + const verible::Symbol &); // Find all nodes tagged with kPort. std::vector FindAllPortReferences( - const verible::Symbol&); + const verible::Symbol &); // Find all nodes tagged with kActualNamedPort. std::vector FindAllActualNamedPort( - const verible::Symbol&); + const verible::Symbol &); // Extract the name of the port identifier from a port declaration. -const verible::SyntaxTreeLeaf* GetIdentifierFromPortDeclaration( - const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetIdentifierFromPortDeclaration( + const verible::Symbol &); // Extract the direction from a port declaration. // Can return nullptr if the direction is not explicitly specified. -const verible::SyntaxTreeLeaf* GetDirectionFromPortDeclaration( - const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetDirectionFromPortDeclaration( + const verible::Symbol &); // Find all individual module port declarations. std::vector FindAllModulePortDeclarations( - const verible::Symbol&); + const verible::Symbol &); // Extract the name of the module port identifier from a port declaration. -const verible::SyntaxTreeLeaf* GetIdentifierFromModulePortDeclaration( - const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetIdentifierFromModulePortDeclaration( + const verible::Symbol &); // Extract the direction from a module port declaration. -const verible::SyntaxTreeLeaf* GetDirectionFromModulePortDeclaration( - const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetDirectionFromModulePortDeclaration( + const verible::Symbol &); // Extract the name of the module port identifier from a port reference. // For Non-ANSI style ports e.g module m(a, b); -const verible::SyntaxTreeLeaf* GetIdentifierFromPortReference( - const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetIdentifierFromPortReference( + const verible::Symbol &); // Extracts the node tagged with kPortReference from a node tagged with kPort. -const verible::SyntaxTreeNode* GetPortReferenceFromPort(const verible::Symbol&); +const verible::SyntaxTreeNode *GetPortReferenceFromPort( + const verible::Symbol &); // Find all task/function port declarations. std::vector FindAllTaskFunctionPortDeclarations( - const verible::Symbol&); + const verible::Symbol &); // Syntax tree node builder for tp_port_item nonterminal. template -verible::SymbolPtr MakeTaskFunctionPortItem(T0&& direction, - T1&& type_id_dimensions, - T2&& default_value) { +verible::SymbolPtr MakeTaskFunctionPortItem(T0 &&direction, + T1 &&type_id_dimensions, + T2 &&default_value) { // TODO(fangism): check assumptions about arguments' node/symbol types return verible::MakeTaggedNode( NodeEnum::kPortItem, std::forward(direction), @@ -87,26 +88,26 @@ verible::SymbolPtr MakeTaskFunctionPortItem(T0&& direction, // Extract the kDataType from a single task/function port item. // The data type could contain only nullptrs (implicit). -const verible::Symbol* GetTypeOfTaskFunctionPortItem(const verible::Symbol&); +const verible::Symbol *GetTypeOfTaskFunctionPortItem(const verible::Symbol &); // Extract the declared identifier from a task/function port item. -const verible::SyntaxTreeLeaf* GetIdentifierFromTaskFunctionPortItem( - const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetIdentifierFromTaskFunctionPortItem( + const verible::Symbol &); // Extract the unpacked dimensions from a task/function port item. -const verible::SyntaxTreeNode* GetUnpackedDimensionsFromTaskFunctionPortItem( - const verible::Symbol&); +const verible::SyntaxTreeNode *GetUnpackedDimensionsFromTaskFunctionPortItem( + const verible::Symbol &); // Returns the leaf node containing the name of the actual named port. // example: from ".x(y)" this returns the leaf spanning "x". // Returns nullptr if it doesn't exist. -const verible::SyntaxTreeLeaf* GetActualNamedPortName(const verible::Symbol&); +const verible::SyntaxTreeLeaf *GetActualNamedPortName(const verible::Symbol &); // Returns the node containing the paren group of the actual named port (if // exists). // e.g. from ".x(y)" returns the node spanning (y), from ".z" return // nullptr. -const verible::Symbol* GetActualNamedPortParenGroup(const verible::Symbol&); +const verible::Symbol *GetActualNamedPortParenGroup(const verible::Symbol &); } // namespace verilog diff --git a/verilog/CST/port_test.cc b/verilog/CST/port_test.cc index 7d0a3e16f..c7e879d1e 100644 --- a/verilog/CST/port_test.cc +++ b/verilog/CST/port_test.cc @@ -58,7 +58,7 @@ using verible::TreeSearchMatch; TEST(FindAllPortDeclarationsTest, EmptySource) { VerilogAnalyzer analyzer("", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto port_declarations = FindAllPortDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(port_declarations.empty()); @@ -68,7 +68,7 @@ TEST(FindAllPortDeclarationsTest, EmptySource) { TEST(FindAllPortDeclarationsTest, NonPort) { VerilogAnalyzer analyzer("module foo; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto port_declarations = FindAllPortDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(port_declarations.empty()); @@ -78,7 +78,7 @@ TEST(FindAllPortDeclarationsTest, NonPort) { TEST(FindAllPortDeclarationsTest, OneWire) { VerilogAnalyzer analyzer("wire w;", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto port_declarations = FindAllPortDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(port_declarations.empty()); @@ -88,7 +88,7 @@ TEST(FindAllPortDeclarationsTest, OneWire) { TEST(FindAllPortDeclarationsTest, OneWireInModule) { VerilogAnalyzer analyzer("module m; wire w; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto port_declarations = FindAllPortDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(port_declarations.empty()); @@ -96,7 +96,7 @@ TEST(FindAllPortDeclarationsTest, OneWireInModule) { // Tests that a port wire inside a module is found. TEST(FindAllPortDeclarationsTest, OnePortInModule) { - const char* kTestCases[] = { + const char *kTestCases[] = { "logic l", "wire w", "input w", @@ -116,11 +116,11 @@ TEST(FindAllPortDeclarationsTest, OnePortInModule) { VerilogAnalyzer analyzer(absl::StrCat("module m(", test, "); endmodule"), ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto port_declarations = FindAllPortDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_EQ(port_declarations.size(), 1); - const auto& decl = port_declarations.front(); + const auto &decl = port_declarations.front(); EXPECT_TRUE(decl.context.IsInside(NodeEnum::kModuleDeclaration)); } } @@ -167,14 +167,14 @@ TEST(GetIdentifierFromPortDeclarationTest, VariousPorts) { {kTag, "bar2"}, "); endmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto port_declarations = FindAllPortDeclarations(*root); std::vector ids; - for (const auto& port : port_declarations) { - const auto* identifier_leaf = + for (const auto &port : port_declarations) { + const auto *identifier_leaf = GetIdentifierFromPortDeclaration(*port.match); ids.push_back(TreeSearchMatch{identifier_leaf, /* no context */}); } @@ -187,7 +187,7 @@ TEST(GetIdentifierFromPortDeclarationTest, VariousPorts) { TEST(FindAllModulePortDeclarationsTest, EmptySource) { VerilogAnalyzer analyzer("", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto port_declarations = FindAllModulePortDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(port_declarations.empty()); @@ -197,7 +197,7 @@ TEST(FindAllModulePortDeclarationsTest, EmptySource) { TEST(FindAllModulePortDeclarationsTest, NonPort) { VerilogAnalyzer analyzer("module foo; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto port_declarations = FindAllModulePortDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(port_declarations.empty()); @@ -207,7 +207,7 @@ TEST(FindAllModulePortDeclarationsTest, NonPort) { TEST(FindAllModulePortDeclarationsTest, OneWire) { VerilogAnalyzer analyzer("wire w;", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto port_declarations = FindAllModulePortDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(port_declarations.empty()); @@ -217,7 +217,7 @@ TEST(FindAllModulePortDeclarationsTest, OneWire) { TEST(FindAllModulePortDeclarationsTest, OneWireInModule) { VerilogAnalyzer analyzer("module m; wire w; endmodule", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto port_declarations = FindAllModulePortDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(port_declarations.empty()); @@ -225,7 +225,7 @@ TEST(FindAllModulePortDeclarationsTest, OneWireInModule) { // Tests that a port wire inside a module is found. TEST(FindAllModulePortDeclarationsTest, OnePortInModule) { - const char* kTestCases[] = { + const char *kTestCases[] = { "input p", "input [1:0] p", "input p [0:1]", "input p [6]", "input [7:0] p [6]", "input wire p", "output p", "output reg p", "output reg [1:0] p", @@ -234,11 +234,11 @@ TEST(FindAllModulePortDeclarationsTest, OnePortInModule) { VerilogAnalyzer analyzer(absl::StrCat("module m(p); ", test, "; endmodule"), ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto port_declarations = FindAllModulePortDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_EQ(port_declarations.size(), 1); - const auto& decl = port_declarations.front(); + const auto &decl = port_declarations.front(); EXPECT_TRUE(decl.context.IsInside(NodeEnum::kModuleDeclaration)); } } @@ -283,14 +283,14 @@ TEST(GetIdentifierFromModulePortDeclarationTest, VariousPorts) { {kTag, "bar2"}, "; endmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto port_declarations = FindAllModulePortDeclarations(*root); std::vector ids; - for (const auto& port : port_declarations) { - const auto* identifier_leaf = + for (const auto &port : port_declarations) { + const auto *identifier_leaf = GetIdentifierFromModulePortDeclaration(*port.match); ids.push_back(TreeSearchMatch{identifier_leaf, /* no context */}); } @@ -301,7 +301,7 @@ TEST(GetIdentifierFromModulePortDeclarationTest, VariousPorts) { // Negative tests that no ports are found where they are not expected. TEST(FindAllTaskFunctionPortDeclarationsTest, ExpectNoTaskFunctionPorts) { - constexpr const char* kTestCases[] = { + constexpr const char *kTestCases[] = { "", "module foo(input wire bar); endmodule", "function void foo(); endfunction", @@ -309,10 +309,10 @@ TEST(FindAllTaskFunctionPortDeclarationsTest, ExpectNoTaskFunctionPorts) { "class foo; endclass", "class foo; function void bar(); endfunction endclass", }; - for (const auto* code : kTestCases) { + for (const auto *code : kTestCases) { VerilogAnalyzer analyzer(code, "<>"); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto port_declarations = FindAllTaskFunctionPortDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_TRUE(port_declarations.empty()); @@ -357,26 +357,26 @@ TEST(GetIdentifierFromTaskFunctionPortItemTest, ExpectSomeTaskFunctionPorts) { {"task automatic foo(input pkg::t_t bar, output pkg::t_t baz); endtask", {{"bar", true}, {"baz", true}}}, }; - for (const auto& test : kTestCases) { - const std::string& code = test.code; - const auto& expected_ports = test.expected_ports; + for (const auto &test : kTestCases) { + const std::string &code = test.code; + const auto &expected_ports = test.expected_ports; VerilogAnalyzer analyzer(code, "<>"); ASSERT_OK(analyzer.Analyze()) << "Failed code:\n" << code; - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto port_declarations = FindAllTaskFunctionPortDeclarations(*ABSL_DIE_IF_NULL(root)); ASSERT_EQ(port_declarations.size(), expected_ports.size()); // Compare expected port ids one-by-one, and check for type presence. int i = 0; - for (const auto& expected_port : expected_ports) { - const auto& port_decl = port_declarations[i]; - const auto* identifier_leaf = + for (const auto &expected_port : expected_ports) { + const auto &port_decl = port_declarations[i]; + const auto *identifier_leaf = GetIdentifierFromTaskFunctionPortItem(*port_decl.match); EXPECT_EQ(identifier_leaf->get().text(), expected_port.id) << "Failed code:\n" << code; - const auto* port_type = GetTypeOfTaskFunctionPortItem(*port_decl.match); + const auto *port_type = GetTypeOfTaskFunctionPortItem(*port_decl.match); EXPECT_EQ(IsStorageTypeOfDataTypeSpecified(*ABSL_DIE_IF_NULL(port_type)), expected_port.have_type) << "Failed code:\n" @@ -401,16 +401,16 @@ TEST(GetAllPortReferences, GetPortReferenceIdentifier) { {"module m(input wire a,", {kTag, "b"}, "[0:1]); endmodule: m"}, {"module m(wire a,", {kTag, "b"}, "[0:1]); endmodule: m"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllPortReferences(*ABSL_DIE_IF_NULL(root)); std::vector types; - for (const auto& decl : decls) { - const auto* type = GetIdentifierFromPortReference( + for (const auto &decl : decls) { + const auto *type = GetIdentifierFromPortReference( *GetPortReferenceFromPort(*decl.match)); types.push_back(TreeSearchMatch{type, {/* ignored context */}}); } @@ -433,15 +433,15 @@ TEST(GetActualNamedPort, GetActualPortName) { {kTag, "in3"}, ");\nendmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& ports = FindAllActualNamedPort(*ABSL_DIE_IF_NULL(root)); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &ports = FindAllActualNamedPort(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& port : ports) { - const auto* name = GetActualNamedPortName(*port.match); + for (const auto &port : ports) { + const auto *name = GetActualNamedPortName(*port.match); names.emplace_back(TreeSearchMatch{name, {/* ignored context */}}); } return names; @@ -461,15 +461,15 @@ TEST(GetActualNamedPort, GetActualNamedPortParenGroup) { ", ", ".in3);\nendmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& ports = FindAllActualNamedPort(*ABSL_DIE_IF_NULL(root)); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &ports = FindAllActualNamedPort(*ABSL_DIE_IF_NULL(root)); std::vector paren_groups; - for (const auto& port : ports) { - const auto* paren_group = GetActualNamedPortParenGroup(*port.match); + for (const auto &port : ports) { + const auto *paren_group = GetActualNamedPortParenGroup(*port.match); if (paren_group == nullptr) { continue; } @@ -495,16 +495,16 @@ TEST(FunctionPort, GetUnpackedDimensions) { ");\nendtask"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& ports = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &ports = FindAllTaskFunctionPortDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector dimensions; - for (const auto& port : ports) { - const auto* dimension = + for (const auto &port : ports) { + const auto *dimension = GetUnpackedDimensionsFromTaskFunctionPortItem(*port.match); dimensions.emplace_back( TreeSearchMatch{dimension, {/* ignored context */}}); @@ -534,18 +534,18 @@ TEST(FunctionPort, GetDirection) { " b); endmodule;"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& ports = FindAllPortDeclarations(*ABSL_DIE_IF_NULL(root)); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &ports = FindAllPortDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector directions; - for (const auto& port : ports) { - const auto* direction = + for (const auto &port : ports) { + const auto *direction = GetDirectionFromPortDeclaration(*port.match); directions.emplace_back( - TreeSearchMatch{(const verible::Symbol*)direction, {}}); + TreeSearchMatch{(const verible::Symbol *)direction, {}}); } return directions; }); diff --git a/verilog/CST/seq_block.cc b/verilog/CST/seq_block.cc index 2a1c3c8cc..626e7cd20 100644 --- a/verilog/CST/seq_block.cc +++ b/verilog/CST/seq_block.cc @@ -31,8 +31,8 @@ using verible::SyntaxTreeNode; using verible::TokenInfo; // kLabel could be prefix "label :" or suffix ": label". Handle both cases. -static const verible::SyntaxTreeLeaf& GetLabelLeafText(const Symbol& label) { - const auto& node = CheckSymbolAsNode(label, NodeEnum::kLabel); +static const verible::SyntaxTreeLeaf &GetLabelLeafText(const Symbol &label) { + const auto &node = CheckSymbolAsNode(label, NodeEnum::kLabel); CHECK_EQ(node.children().size(), 2); if (node.children().front()->Tag() == verible::SymbolTag{verible::SymbolKind::kLeaf, ':'}) { @@ -50,8 +50,8 @@ static const verible::SyntaxTreeLeaf& GetLabelLeafText(const Symbol& label) { // In verilog.y, kBegin is constructed one of two ways: // begin : label (shaped as [begin [: label]]) // label : begin (shaped as [[label :] begin]) -static const SyntaxTreeNode* GetBeginLabel(const Symbol& begin) { - const auto& node = CheckSymbolAsNode(begin, NodeEnum::kBegin); +static const SyntaxTreeNode *GetBeginLabel(const Symbol &begin) { + const auto &node = CheckSymbolAsNode(begin, NodeEnum::kBegin); CHECK_EQ(node.children().size(), 2); if (node.children().front()->Tag() == verible::SymbolTag{verible::SymbolKind::kLeaf, @@ -66,26 +66,26 @@ static const SyntaxTreeNode* GetBeginLabel(const Symbol& begin) { NodeEnum::kLabel); } -static const SyntaxTreeNode* GetEndLabel(const Symbol& end) { - const auto* label = verible::GetSubtreeAsSymbol(end, NodeEnum::kEnd, 1); +static const SyntaxTreeNode *GetEndLabel(const Symbol &end) { + const auto *label = verible::GetSubtreeAsSymbol(end, NodeEnum::kEnd, 1); if (label == nullptr) return nullptr; return verible::CheckOptionalSymbolAsNode(label, NodeEnum::kLabel); } -const TokenInfo* GetBeginLabelTokenInfo(const Symbol& symbol) { - const SyntaxTreeNode* label = GetBeginLabel(symbol); +const TokenInfo *GetBeginLabelTokenInfo(const Symbol &symbol) { + const SyntaxTreeNode *label = GetBeginLabel(symbol); if (label == nullptr) return nullptr; return &GetLabelLeafText(*label).get(); } -const TokenInfo* GetEndLabelTokenInfo(const Symbol& symbol) { - const SyntaxTreeNode* label = GetEndLabel(symbol); +const TokenInfo *GetEndLabelTokenInfo(const Symbol &symbol) { + const SyntaxTreeNode *label = GetEndLabel(symbol); if (label == nullptr) return nullptr; return &GetLabelLeafText(*label).get(); } -const Symbol* GetMatchingEnd(const Symbol& symbol, - const SyntaxTreeContext& context) { +const Symbol *GetMatchingEnd(const Symbol &symbol, + const SyntaxTreeContext &context) { CHECK_EQ(NodeEnum(symbol.Tag().tag), NodeEnum::kBegin); return context.top().children().back().get(); } diff --git a/verilog/CST/seq_block.h b/verilog/CST/seq_block.h index 6eb23b82a..72469111f 100644 --- a/verilog/CST/seq_block.h +++ b/verilog/CST/seq_block.h @@ -26,14 +26,14 @@ namespace verilog { // Get TokenInfo of a label for a given kBegin symbol if exists, else nullptr -const verible::TokenInfo* GetBeginLabelTokenInfo(const verible::Symbol& symbol); +const verible::TokenInfo *GetBeginLabelTokenInfo(const verible::Symbol &symbol); // Get TokenInfo of a label for a given kEnd symbol if exists, else nullptr -const verible::TokenInfo* GetEndLabelTokenInfo(const verible::Symbol& symbol); +const verible::TokenInfo *GetEndLabelTokenInfo(const verible::Symbol &symbol); // Find and return a pointer to a kEnd symbol corresponding to a given kBegin -const verible::Symbol* GetMatchingEnd( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context); +const verible::Symbol *GetMatchingEnd( + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context); } // namespace verilog diff --git a/verilog/CST/seq_block_test.cc b/verilog/CST/seq_block_test.cc index 5511a6b22..4936a6b0c 100644 --- a/verilog/CST/seq_block_test.cc +++ b/verilog/CST/seq_block_test.cc @@ -34,7 +34,7 @@ namespace verilog { namespace { static std::vector FindAllBeginStatements( - const verible::Symbol& root) { + const verible::Symbol &root) { return SearchSyntaxTree(root, NodekBegin()); } @@ -47,7 +47,7 @@ endmodule)", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto begin_statements = FindAllBeginStatements(*root); ASSERT_EQ(begin_statements.size(), 1); @@ -66,12 +66,12 @@ endmodule)", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto begin_statements = FindAllBeginStatements(*root); ASSERT_EQ(begin_statements.size(), 1); - const auto* beginToken = GetBeginLabelTokenInfo(*begin_statements[0].match); + const auto *beginToken = GetBeginLabelTokenInfo(*begin_statements[0].match); EXPECT_EQ(ABSL_DIE_IF_NULL(beginToken)->text(), "begin_label"); } @@ -84,12 +84,12 @@ endmodule)", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto begin_statements = FindAllBeginStatements(*root); ASSERT_EQ(begin_statements.size(), 1); - const auto* beginToken = GetBeginLabelTokenInfo(*begin_statements[0].match); + const auto *beginToken = GetBeginLabelTokenInfo(*begin_statements[0].match); EXPECT_EQ(beginToken, nullptr); } @@ -102,12 +102,12 @@ endmodule)", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto begin_statements = FindAllBeginStatements(*root); ASSERT_EQ(begin_statements.size(), 1); - const auto* beginToken = GetBeginLabelTokenInfo(*begin_statements[0].match); + const auto *beginToken = GetBeginLabelTokenInfo(*begin_statements[0].match); EXPECT_EQ(ABSL_DIE_IF_NULL(beginToken)->text(), "prefix_label"); } @@ -120,16 +120,16 @@ endmodule)", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto begin_statements = FindAllBeginStatements(*root); ASSERT_EQ(begin_statements.size(), 1); - const auto* matchingEnd = + const auto *matchingEnd = GetMatchingEnd(*begin_statements[0].match, begin_statements[0].context); ASSERT_EQ(NodeEnum(matchingEnd->Tag().tag), NodeEnum::kEnd); - const auto* endToken = GetEndLabelTokenInfo(*matchingEnd); + const auto *endToken = GetEndLabelTokenInfo(*matchingEnd); EXPECT_EQ(endToken, nullptr); } @@ -142,16 +142,16 @@ endmodule)", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto begin_statements = FindAllBeginStatements(*root); ASSERT_EQ(begin_statements.size(), 1); - const auto* matchingEnd = + const auto *matchingEnd = GetMatchingEnd(*begin_statements[0].match, begin_statements[0].context); ASSERT_EQ(NodeEnum(matchingEnd->Tag().tag), NodeEnum::kEnd); - const auto* endToken = GetEndLabelTokenInfo(*matchingEnd); + const auto *endToken = GetEndLabelTokenInfo(*matchingEnd); EXPECT_EQ(ABSL_DIE_IF_NULL(endToken)->text(), "end_label"); } @@ -167,29 +167,29 @@ endmodule)", ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto begin_statements = FindAllBeginStatements(*root); ASSERT_EQ(begin_statements.size(), 2); - const auto* matchingOuterEnd = + const auto *matchingOuterEnd = GetMatchingEnd(*begin_statements[0].match, begin_statements[0].context); ASSERT_EQ(NodeEnum(matchingOuterEnd->Tag().tag), NodeEnum::kEnd); - const auto* matchingInnerEnd = + const auto *matchingInnerEnd = GetMatchingEnd(*begin_statements[1].match, begin_statements[1].context); ASSERT_EQ(NodeEnum(matchingInnerEnd->Tag().tag), NodeEnum::kEnd); - const auto& outerBeginToken = + const auto &outerBeginToken = *ABSL_DIE_IF_NULL(GetBeginLabelTokenInfo(*begin_statements[0].match)); - const auto& innerBeginToken = + const auto &innerBeginToken = *ABSL_DIE_IF_NULL(GetBeginLabelTokenInfo(*begin_statements[1].match)); - const auto& outerEndToken = + const auto &outerEndToken = *ABSL_DIE_IF_NULL(GetEndLabelTokenInfo(*matchingOuterEnd)); - const auto& innerEndToken = + const auto &innerEndToken = *ABSL_DIE_IF_NULL(GetEndLabelTokenInfo(*matchingInnerEnd)); EXPECT_EQ(outerBeginToken.text(), "outer_begin_label"); diff --git a/verilog/CST/tasks.cc b/verilog/CST/tasks.cc index ddc065da7..b0bc73194 100644 --- a/verilog/CST/tasks.cc +++ b/verilog/CST/tasks.cc @@ -28,57 +28,57 @@ namespace verilog { std::vector FindAllTaskDeclarations( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekTaskDeclaration()); } std::vector FindAllTaskPrototypes( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekTaskPrototype()); } std::vector FindAllTaskHeaders( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekTaskHeader()); } -const verible::SyntaxTreeNode* GetTaskHeader(const verible::Symbol& task_decl) { +const verible::SyntaxTreeNode *GetTaskHeader(const verible::Symbol &task_decl) { return verible::GetSubtreeAsNode(task_decl, NodeEnum::kTaskDeclaration, 0, NodeEnum::kTaskHeader); } -const verible::SyntaxTreeNode* GetTaskPrototypeHeader( - const verible::Symbol& task_proto) { +const verible::SyntaxTreeNode *GetTaskPrototypeHeader( + const verible::Symbol &task_proto) { return verible::GetSubtreeAsNode(task_proto, NodeEnum::kTaskPrototype, 0, NodeEnum::kTaskHeader); } -const verible::Symbol* GetTaskHeaderLifetime( - const verible::Symbol& task_header) { +const verible::Symbol *GetTaskHeaderLifetime( + const verible::Symbol &task_header) { return verible::GetSubtreeAsSymbol(task_header, NodeEnum::kTaskHeader, 2); } -const verible::Symbol* GetTaskHeaderId(const verible::Symbol& task_header) { +const verible::Symbol *GetTaskHeaderId(const verible::Symbol &task_header) { return verible::GetSubtreeAsSymbol(task_header, NodeEnum::kTaskHeader, 3); } -const verible::Symbol* GetTaskLifetime(const verible::Symbol& task_decl) { - const auto* header = GetTaskHeader(task_decl); +const verible::Symbol *GetTaskLifetime(const verible::Symbol &task_decl) { + const auto *header = GetTaskHeader(task_decl); return header ? GetTaskHeaderLifetime(*header) : nullptr; } -const verible::Symbol* GetTaskId(const verible::Symbol& task_decl) { - const auto* header = GetTaskHeader(task_decl); +const verible::Symbol *GetTaskId(const verible::Symbol &task_decl) { + const auto *header = GetTaskHeader(task_decl); return header ? GetTaskHeaderId(*header) : nullptr; } -const verible::SyntaxTreeLeaf* GetTaskName(const verible::Symbol& task_decl) { - const auto* function_id = GetTaskId(task_decl); +const verible::SyntaxTreeLeaf *GetTaskName(const verible::Symbol &task_decl) { + const auto *function_id = GetTaskId(task_decl); return function_id ? GetIdentifier(*function_id) : nullptr; } -const verible::SyntaxTreeNode* GetTaskStatementList( - const verible::Symbol& task_decl) { +const verible::SyntaxTreeNode *GetTaskStatementList( + const verible::Symbol &task_decl) { return verible::GetSubtreeAsNode(task_decl, NodeEnum::kTaskDeclaration, 1, NodeEnum::kStatementList); } diff --git a/verilog/CST/tasks.h b/verilog/CST/tasks.h index 44d5f5bff..1f4e999aa 100644 --- a/verilog/CST/tasks.h +++ b/verilog/CST/tasks.h @@ -24,47 +24,47 @@ namespace verilog { // Find all task declarations, including class method declarations. std::vector FindAllTaskDeclarations( - const verible::Symbol&); + const verible::Symbol &); // Find all task headers, which are common to declarations and prototypes. std::vector FindAllTaskHeaders( - const verible::Symbol&); + const verible::Symbol &); // Find all task prototypes, including class method prototypes. std::vector FindAllTaskPrototypes( - const verible::Symbol&); + const verible::Symbol &); // Returns the task declaration header -const verible::SyntaxTreeNode* GetTaskHeader(const verible::Symbol& task_decl); +const verible::SyntaxTreeNode *GetTaskHeader(const verible::Symbol &task_decl); // Returns the task prototype header -const verible::SyntaxTreeNode* GetTaskPrototypeHeader( - const verible::Symbol& task_proto); +const verible::SyntaxTreeNode *GetTaskPrototypeHeader( + const verible::Symbol &task_proto); // task header accessors // Returns the task header's lifetime. -const verible::Symbol* GetTaskHeaderLifetime( - const verible::Symbol& task_header); +const verible::Symbol *GetTaskHeaderLifetime( + const verible::Symbol &task_header); // Returns the id of the task declaration. -const verible::Symbol* GetTaskHeaderId(const verible::Symbol& task_header); +const verible::Symbol *GetTaskHeaderId(const verible::Symbol &task_header); // task declaration accessors // Returns the task lifetime of the node. -const verible::Symbol* GetTaskLifetime(const verible::Symbol& task_decl); +const verible::Symbol *GetTaskLifetime(const verible::Symbol &task_decl); // Returns the id of the task declaration. -const verible::Symbol* GetTaskId(const verible::Symbol& task_decl); +const verible::Symbol *GetTaskId(const verible::Symbol &task_decl); // Returns leaf node for task name. // e.g. task my_task(); return leaf node for "my_task". -const verible::SyntaxTreeLeaf* GetTaskName(const verible::Symbol& task_decl); +const verible::SyntaxTreeLeaf *GetTaskName(const verible::Symbol &task_decl); // Returns the task declaration body. -const verible::SyntaxTreeNode* GetTaskStatementList( - const verible::Symbol& task_decl); +const verible::SyntaxTreeNode *GetTaskStatementList( + const verible::Symbol &task_decl); } // namespace verilog diff --git a/verilog/CST/tasks_test.cc b/verilog/CST/tasks_test.cc index 11bdbec01..e7d385299 100644 --- a/verilog/CST/tasks_test.cc +++ b/verilog/CST/tasks_test.cc @@ -79,10 +79,10 @@ TEST(FindAllTaskDeclarationsTest, Various) { {kTag, "task foo();\nendtask"}, " endmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllTaskDeclarations(*ABSL_DIE_IF_NULL(root)); }); } @@ -115,20 +115,20 @@ TEST(FindAllTaskPrototypesTest, Various) { {kTag, "task foo();"}, "\nendclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllTaskPrototypes(*ABSL_DIE_IF_NULL(root)); }); } // Prototype header span the same range as their enclosing prototypes. - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); std::vector headers; - for (const auto& proto : + for (const auto &proto : FindAllTaskPrototypes(*ABSL_DIE_IF_NULL(root))) { headers.push_back(TreeSearchMatch{ GetTaskPrototypeHeader(*proto.match), /* no context */}); @@ -154,15 +154,15 @@ TEST(TaskPrototypesIdsTest, Various) { "();\n" "endclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); std::vector ids; - for (const auto& proto : + for (const auto &proto : FindAllTaskPrototypes(*ABSL_DIE_IF_NULL(root))) { - const auto* header = GetTaskPrototypeHeader(*proto.match); - const auto* id = ABSL_DIE_IF_NULL(GetTaskHeaderId(*header)); + const auto *header = GetTaskPrototypeHeader(*proto.match); + const auto *id = ABSL_DIE_IF_NULL(GetTaskHeaderId(*header)); EXPECT_TRUE(verible::SymbolCastToNode(*id).MatchesTag( NodeEnum::kUnqualifiedId)); ids.push_back(TreeSearchMatch{id, /* no context */}); @@ -205,10 +205,10 @@ TEST(FindAllTaskHeadersTest, Various) { {kTag, "task foo();"}, "\nendclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllTaskHeaders(*ABSL_DIE_IF_NULL(root)); }); } @@ -223,15 +223,15 @@ TEST(GetTaskHeaderTest, DeclarationsHeader) { {"module m; ", {kTag, "task foo();"}, " endtask endmodule"}, {"package p; ", {kTag, "task foo();"}, " endtask endpackage"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { + __FUNCTION__, test, [](const TextStructureView &text_structure) { // Root node is a description list, not a task. - const auto& root = text_structure.SyntaxTree(); + const auto &root = text_structure.SyntaxTree(); const auto task_declarations = FindAllTaskDeclarations(*root); std::vector headers; - for (const auto& decl : task_declarations) { - const auto& task_node = verible::SymbolCastToNode(*decl.match); + for (const auto &decl : task_declarations) { + const auto &task_node = verible::SymbolCastToNode(*decl.match); headers.push_back( TreeSearchMatch{GetTaskHeader(task_node), /* no context */}); } @@ -244,12 +244,12 @@ TEST(GetTaskLifetimeTest, NoLifetimeDeclared) { VerilogAnalyzer analyzer("task foo(); endtask", ""); ASSERT_OK(analyzer.Analyze()); // Root node is a description list, not a task. - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto task_declarations = FindAllTaskDeclarations(*root); ASSERT_EQ(task_declarations.size(), 1); - const auto& task_node = + const auto &task_node = verible::SymbolCastToNode(*task_declarations.front().match); - const auto* lifetime = GetTaskLifetime(task_node); + const auto *lifetime = GetTaskLifetime(task_node); EXPECT_EQ(lifetime, nullptr); } @@ -257,13 +257,13 @@ TEST(GetTaskLifetimeTest, StaticLifetimeDeclared) { VerilogAnalyzer analyzer("task static foo(); endtask", ""); ASSERT_OK(analyzer.Analyze()); // Root node is a description list, not a task. - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto task_declarations = FindAllTaskDeclarations(*root); ASSERT_EQ(task_declarations.size(), 1); - const auto& task_node = + const auto &task_node = verible::SymbolCastToNode(*task_declarations.front().match); - const auto* lifetime = GetTaskLifetime(task_node); - const auto& leaf = verible::SymbolCastToLeaf(*ABSL_DIE_IF_NULL(lifetime)); + const auto *lifetime = GetTaskLifetime(task_node); + const auto &leaf = verible::SymbolCastToLeaf(*ABSL_DIE_IF_NULL(lifetime)); EXPECT_EQ(leaf.get().token_enum(), TK_static); } @@ -271,13 +271,13 @@ TEST(GetTaskLifetimeTest, AutomaticLifetimeDeclared) { VerilogAnalyzer analyzer("task automatic foo(); endtask", ""); ASSERT_OK(analyzer.Analyze()); // Root node is a description list, not a task. - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto task_declarations = FindAllTaskDeclarations(*root); ASSERT_EQ(task_declarations.size(), 1); - const auto& task_node = + const auto &task_node = verible::SymbolCastToNode(*task_declarations.front().match); - const auto* lifetime = GetTaskLifetime(task_node); - const auto& leaf = verible::SymbolCastToLeaf(*ABSL_DIE_IF_NULL(lifetime)); + const auto *lifetime = GetTaskLifetime(task_node); + const auto &leaf = verible::SymbolCastToLeaf(*ABSL_DIE_IF_NULL(lifetime)); EXPECT_EQ(leaf.get().token_enum(), TK_automatic); } @@ -291,19 +291,19 @@ TEST(GetTaskIdTest, UnqualifiedIds) { {"class c; task ", {kTag, "zoo"}, "(); endtask endclass"}, {"task ", {kTag, "myclass"}, "::", {kTag, "foo"}, "(); endtask"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { + __FUNCTION__, test, [](const TextStructureView &text_structure) { // Root node is a description list, not a task. - const auto& root = text_structure.SyntaxTree(); + const auto &root = text_structure.SyntaxTree(); const auto task_declarations = FindAllTaskDeclarations(*root); std::vector got_ids; - for (const auto& task_decl : task_declarations) { - const auto& task_node = - down_cast(*task_decl.match); - const auto* task_id = GetTaskId(task_node); + for (const auto &task_decl : task_declarations) { + const auto &task_node = + down_cast(*task_decl.match); + const auto *task_id = GetTaskId(task_node); const auto ids = FindAllUnqualifiedIds(*task_id); - for (const auto& id : ids) { + for (const auto &id : ids) { got_ids.push_back(TreeSearchMatch{ GetIdentifier(*ABSL_DIE_IF_NULL(id.match)), /* no context */}); @@ -321,17 +321,17 @@ TEST(GetTaskIdTest, QualifiedIds) { {"class c; task foo(); endtask endclass"}, {"task ", {kTag, "myclass::foo"}, "(); endtask"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { + __FUNCTION__, test, [](const TextStructureView &text_structure) { // Root node is a description list, not a task. - const auto& root = text_structure.SyntaxTree(); + const auto &root = text_structure.SyntaxTree(); const auto task_declarations = FindAllTaskDeclarations(*root); std::vector ids; - for (const auto& decl : task_declarations) { - const auto& task_node = verible::SymbolCastToNode(*decl.match); - const auto* task_id = GetTaskId(task_node); - for (const auto& id : FindAllQualifiedIds(*task_id)) { + for (const auto &decl : task_declarations) { + const auto &task_node = verible::SymbolCastToNode(*decl.match); + const auto *task_id = GetTaskId(task_node); + for (const auto &id : FindAllQualifiedIds(*task_id)) { ids.push_back(id); } } @@ -367,16 +367,16 @@ TEST(GetTaskHeaderTest, GetTaskName) { {kTag, "my_task"}, "();\n endtask\n endclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllTaskDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector types; - for (const auto& decl : decls) { - const auto* type = GetTaskName(*decl.match); + for (const auto &decl : decls) { + const auto *type = GetTaskName(*decl.match); types.push_back(TreeSearchMatch{type, {/* ignored context */}}); } return types; @@ -398,16 +398,16 @@ TEST(GetTaskHeaderTest, GetTaskBody) { {kTag, "int x = 1;"}, "\nendtask\nendpackage"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto decls = FindAllTaskDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector bodies; - for (const auto& decl : decls) { - const auto& body = GetTaskStatementList(*decl.match); + for (const auto &decl : decls) { + const auto &body = GetTaskStatementList(*decl.match); bodies.push_back(TreeSearchMatch{body, {/* ignored context */}}); } return bodies; diff --git a/verilog/CST/type.cc b/verilog/CST/type.cc index 210de4a69..2c16b2976 100644 --- a/verilog/CST/type.cc +++ b/verilog/CST/type.cc @@ -32,24 +32,24 @@ namespace verilog { using verible::Symbol; using verible::SymbolPtr; -static SymbolPtr ReinterpretLocalRootAsType(Symbol& local_root) { // NOLINT - auto& children(verible::SymbolCastToNode(local_root).mutable_children()); +static SymbolPtr ReinterpretLocalRootAsType(Symbol &local_root) { // NOLINT + auto &children(verible::SymbolCastToNode(local_root).mutable_children()); CHECK(!children.empty()); return std::move(children[0]); } SymbolPtr ReinterpretReferenceAsDataTypePackedDimensions( - SymbolPtr& reference_call_base) { + SymbolPtr &reference_call_base) { if (reference_call_base->Tag().tag == static_cast(NodeEnum::kMacroCall)) { return std::move(reference_call_base); } - verible::SyntaxTreeNode& base(verible::CheckSymbolAsNode( + verible::SyntaxTreeNode &base(verible::CheckSymbolAsNode( *ABSL_DIE_IF_NULL(reference_call_base), NodeEnum::kReference)); - auto& children(base.mutable_children()); + auto &children(base.mutable_children()); CHECK(!children.empty()); - Symbol& local_root(*children.front()); + Symbol &local_root(*children.front()); if (local_root.Kind() != verible::SymbolKind::kNode || verible::SymbolCastToNode(*children.back()) .MatchesTag(NodeEnum::kHierarchyExtension)) { @@ -60,18 +60,18 @@ SymbolPtr ReinterpretReferenceAsDataTypePackedDimensions( SymbolPtr packed_dimensions( verible::MakeTaggedNode(NodeEnum::kPackedDimensions)); - verible::SyntaxTreeNode& pdim_node( + verible::SyntaxTreeNode &pdim_node( verible::SymbolCastToNode(*packed_dimensions)); SymbolPtr local_root_with_extension( verible::MakeTaggedNode(NodeEnum::kLocalRoot)); - verible::SyntaxTreeNode& local_root_with_extension_node( + verible::SyntaxTreeNode &local_root_with_extension_node( verible::SymbolCastToNode(*local_root_with_extension)); local_root_with_extension_node.AppendChild( ReinterpretLocalRootAsType(*children.front())); - for (auto& child : + for (auto &child : verible::make_range(children.begin() + 1, children.end())) { // Each child could be a call-extension or an index (bit-select/slice). // Only [] indices are valid, any others are syntax errors. @@ -93,7 +93,7 @@ SymbolPtr ReinterpretReferenceAsDataTypePackedDimensions( continue; } - auto& node = verible::SymbolCastToNode(*child); + auto &node = verible::SymbolCastToNode(*child); if (node.MatchesTagAnyOf( {NodeEnum::kDimensionRange, NodeEnum::kDimensionScalar})) { pdim_node.AppendChild(std::move(child)); @@ -105,74 +105,74 @@ SymbolPtr ReinterpretReferenceAsDataTypePackedDimensions( } std::vector FindAllDataTypeDeclarations( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekDataType()); } std::vector FindAllEnumNames( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekEnumName()); } std::vector FindAllDataTypePrimitive( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekDataTypePrimitive()); } std::vector FindAllTypeDeclarations( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekTypeDeclaration()); } std::vector FindAllEnumTypes( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekEnumType()); } std::vector FindAllStructTypes( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekStructType()); } std::vector FindAllDataTypeImplicitIdDimensions( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekDataTypeImplicitIdDimensions()); } std::vector FindAllUnionTypes( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekUnionType()); } std::vector FindAllInterfaceTypes( - const verible::Symbol& root) { + const verible::Symbol &root) { return verible::SearchSyntaxTree(root, NodekInterfaceType()); } -bool IsStorageTypeOfDataTypeSpecified(const verible::Symbol& symbol) { - const auto* storage = GetBaseTypeFromDataType(symbol); +bool IsStorageTypeOfDataTypeSpecified(const verible::Symbol &symbol) { + const auto *storage = GetBaseTypeFromDataType(symbol); return (storage != nullptr); } -const verible::SyntaxTreeLeaf* GetIdentifierFromTypeDeclaration( - const verible::Symbol& symbol) { +const verible::SyntaxTreeLeaf *GetIdentifierFromTypeDeclaration( + const verible::Symbol &symbol) { // For enum, struct and union identifier is found at the same position - const auto* identifier_symbol = + const auto *identifier_symbol = verible::GetSubtreeAsSymbol(symbol, NodeEnum::kTypeDeclaration, 2); return identifier_symbol ? AutoUnwrapIdentifier(*identifier_symbol) : nullptr; } -const verible::Symbol* GetBaseTypeFromDataType( - const verible::Symbol& data_type) { - const auto* local_root = +const verible::Symbol *GetBaseTypeFromDataType( + const verible::Symbol &data_type) { + const auto *local_root = verible::GetSubtreeAsNode(data_type, NodeEnum::kDataType, 1); if (!local_root) return nullptr; if (local_root->Tag().tag != (int)NodeEnum::kLocalRoot) return local_root; - auto& children = local_root->children(); + auto &children = local_root->children(); CHECK(!children.empty()); - verible::Symbol* last_child = nullptr; - for (auto& child : children) { + verible::Symbol *last_child = nullptr; + for (auto &child : children) { if (child != nullptr && child->Kind() == verible::SymbolKind::kNode) { last_child = child.get(); } @@ -186,62 +186,62 @@ const verible::Symbol* GetBaseTypeFromDataType( return last_child; } -const verible::SyntaxTreeNode* GetPackedDimensionFromDataType( - const verible::Symbol& data_type) { - const auto* pdim = +const verible::SyntaxTreeNode *GetPackedDimensionFromDataType( + const verible::Symbol &data_type) { + const auto *pdim = verible::GetSubtreeAsSymbol(data_type, NodeEnum::kDataType, 3); return verible::CheckOptionalSymbolAsNode(pdim, NodeEnum::kPackedDimensions); } -static const verible::SyntaxTreeNode* GetDataTypeFromInstantiationType( - const verible::Symbol& instantiation_type) { +static const verible::SyntaxTreeNode *GetDataTypeFromInstantiationType( + const verible::Symbol &instantiation_type) { return verible::GetSubtreeAsNode(instantiation_type, NodeEnum::kInstantiationType, 0); // returned node could be kDataType or kInterfaceType } -static const verible::SyntaxTreeNode* GetReferenceFromReferenceCallBase( - const verible::Symbol& reference_call_base) { +static const verible::SyntaxTreeNode *GetReferenceFromReferenceCallBase( + const verible::Symbol &reference_call_base) { return verible::GetSubtreeAsNode(reference_call_base, NodeEnum::kReferenceCallBase, 0); } -const verible::SyntaxTreeNode* GetLocalRootFromReference( - const verible::Symbol& reference) { +const verible::SyntaxTreeNode *GetLocalRootFromReference( + const verible::Symbol &reference) { return verible::GetSubtreeAsNode(reference, NodeEnum::kReference, 0); } -const verible::Symbol* GetIdentifiersFromLocalRoot( - const verible::Symbol& local_root) { +const verible::Symbol *GetIdentifiersFromLocalRoot( + const verible::Symbol &local_root) { return verible::GetSubtreeAsSymbol(local_root, NodeEnum::kLocalRoot, 0); } -const verible::Symbol* GetIdentifiersFromDataType( - const verible::Symbol& data_type) { +const verible::Symbol *GetIdentifiersFromDataType( + const verible::Symbol &data_type) { return verible::GetSubtreeAsSymbol(data_type, NodeEnum::kDataType, 1); } -const verible::SyntaxTreeNode* GetUnqualifiedIdFromReferenceCallBase( - const verible::Symbol& reference_call_base) { - const verible::SyntaxTreeNode* reference = +const verible::SyntaxTreeNode *GetUnqualifiedIdFromReferenceCallBase( + const verible::Symbol &reference_call_base) { + const verible::SyntaxTreeNode *reference = GetReferenceFromReferenceCallBase(reference_call_base); if (!reference) return nullptr; - const verible::SyntaxTreeNode* local_root = + const verible::SyntaxTreeNode *local_root = GetLocalRootFromReference(*reference); if (!local_root) return nullptr; - const verible::Symbol* identifiers = GetIdentifiersFromLocalRoot(*local_root); + const verible::Symbol *identifiers = GetIdentifiersFromLocalRoot(*local_root); return identifiers ? &verible::SymbolCastToNode(*identifiers) : nullptr; } -const verible::SyntaxTreeNode* GetStructOrUnionOrEnumTypeFromDataType( - const verible::Symbol& data_type) { - const verible::Symbol* type = GetBaseTypeFromDataType(data_type); +const verible::SyntaxTreeNode *GetStructOrUnionOrEnumTypeFromDataType( + const verible::Symbol &data_type) { + const verible::Symbol *type = GetBaseTypeFromDataType(data_type); if (type == nullptr || (NodeEnum(type->Tag().tag) != NodeEnum::kDataTypePrimitive && NodeEnum(type->Tag().tag) != NodeEnum::kLocalRoot)) { return nullptr; } - const verible::Symbol* inner_type = + const verible::Symbol *inner_type = verible::GetSubtreeAsSymbol(*type, NodeEnum::kDataTypePrimitive, 0); if (inner_type->Kind() != verible::SymbolKind::kNode) { @@ -251,9 +251,9 @@ const verible::SyntaxTreeNode* GetStructOrUnionOrEnumTypeFromDataType( return &verible::SymbolCastToNode(*inner_type); } -const verible::SyntaxTreeNode* GetStructOrUnionOrEnumTypeFromInstantiationType( - const verible::Symbol& instantiation_type) { - const verible::Symbol* type = +const verible::SyntaxTreeNode *GetStructOrUnionOrEnumTypeFromInstantiationType( + const verible::Symbol &instantiation_type) { + const verible::Symbol *type = GetDataTypeFromInstantiationType(instantiation_type); if (type == nullptr || NodeEnum(type->Tag().tag) != NodeEnum::kDataType) { return nullptr; @@ -261,9 +261,9 @@ const verible::SyntaxTreeNode* GetStructOrUnionOrEnumTypeFromInstantiationType( return GetStructOrUnionOrEnumTypeFromDataType(*type); } -const verible::Symbol* GetBaseTypeFromInstantiationType( - const verible::Symbol& instantiation_type) { - const verible::SyntaxTreeNode* data_type = +const verible::Symbol *GetBaseTypeFromInstantiationType( + const verible::Symbol &instantiation_type) { + const verible::SyntaxTreeNode *data_type = GetDataTypeFromInstantiationType(instantiation_type); if (!data_type) return nullptr; if (NodeEnum(data_type->Tag().tag) != NodeEnum::kDataType) { @@ -272,29 +272,29 @@ const verible::Symbol* GetBaseTypeFromInstantiationType( return GetBaseTypeFromDataType(*data_type); } -const verible::SyntaxTreeNode* GetParamListFromUnqualifiedId( - const verible::Symbol& unqualified_id) { - const verible::SyntaxTreeNode& unqualified_id_node = +const verible::SyntaxTreeNode *GetParamListFromUnqualifiedId( + const verible::Symbol &unqualified_id) { + const verible::SyntaxTreeNode &unqualified_id_node = verible::CheckSymbolAsNode(unqualified_id, NodeEnum::kUnqualifiedId); if (unqualified_id_node.children().size() < 2) { return nullptr; } - const verible::Symbol* param_list = unqualified_id_node.children()[1].get(); + const verible::Symbol *param_list = unqualified_id_node.children()[1].get(); return verible::CheckOptionalSymbolAsNode(param_list, NodeEnum::kActualParameterList); } -const verible::SyntaxTreeNode* GetParamListFromBaseType( - const verible::Symbol& base_type) { +const verible::SyntaxTreeNode *GetParamListFromBaseType( + const verible::Symbol &base_type) { if (base_type.Tag().kind != verible::SymbolKind::kNode) return nullptr; - const verible::SyntaxTreeNode& node(verible::SymbolCastToNode(base_type)); + const verible::SyntaxTreeNode &node(verible::SymbolCastToNode(base_type)); if (!node.MatchesTag(NodeEnum::kUnqualifiedId)) return nullptr; return GetParamListFromUnqualifiedId(node); } -const verible::SyntaxTreeNode* GetParamListFromInstantiationType( - const verible::Symbol& instantiation_type) { - const verible::Symbol* base_type = +const verible::SyntaxTreeNode *GetParamListFromInstantiationType( + const verible::Symbol &instantiation_type) { + const verible::Symbol *base_type = GetBaseTypeFromInstantiationType(instantiation_type); if (base_type == nullptr) { return nullptr; @@ -302,11 +302,11 @@ const verible::SyntaxTreeNode* GetParamListFromInstantiationType( return GetParamListFromBaseType(*base_type); } -std::pair +std::pair GetSymbolIdentifierFromDataTypeImplicitIdDimensions( - const verible::Symbol& struct_union_member) { + const verible::Symbol &struct_union_member) { // The Identifier can be at index 1 or 2. - const verible::Symbol* identifier = verible::GetSubtreeAsSymbol( + const verible::Symbol *identifier = verible::GetSubtreeAsSymbol( struct_union_member, NodeEnum::kDataTypeImplicitIdDimensions, 2); if (identifier != nullptr && identifier->Kind() == verible::SymbolKind::kLeaf) { @@ -317,17 +317,17 @@ GetSymbolIdentifierFromDataTypeImplicitIdDimensions( 1}; } -const verible::SyntaxTreeLeaf* GetNonprimitiveTypeOfDataTypeImplicitDimensions( - const verible::Symbol& data_type_implicit_id_dimensions) { - const verible::SyntaxTreeNode* type_node = +const verible::SyntaxTreeLeaf *GetNonprimitiveTypeOfDataTypeImplicitDimensions( + const verible::Symbol &data_type_implicit_id_dimensions) { + const verible::SyntaxTreeNode *type_node = verible::GetSubtreeAsNode(data_type_implicit_id_dimensions, NodeEnum::kDataTypeImplicitIdDimensions, 0); if (!type_node) return nullptr; - const verible::Symbol* base_type = GetBaseTypeFromDataType(*type_node); + const verible::Symbol *base_type = GetBaseTypeFromDataType(*type_node); if (!base_type) return nullptr; - const verible::Symbol* type_id = GetTypeIdentifierFromBaseType(*base_type); + const verible::Symbol *type_id = GetTypeIdentifierFromBaseType(*base_type); if (!type_id) return nullptr; - const verible::Symbol* identifier = verible::GetLeftmostLeaf(*type_id); + const verible::Symbol *identifier = verible::GetLeftmostLeaf(*type_id); if (identifier == nullptr || identifier->Kind() != verible::SymbolKind::kLeaf) { return nullptr; @@ -335,26 +335,26 @@ const verible::SyntaxTreeLeaf* GetNonprimitiveTypeOfDataTypeImplicitDimensions( return &verible::SymbolCastToLeaf(*identifier); } -const verible::SyntaxTreeNode* GetReferencedTypeOfTypeDeclaration( - const verible::Symbol& type_declaration) { +const verible::SyntaxTreeNode *GetReferencedTypeOfTypeDeclaration( + const verible::Symbol &type_declaration) { // Could be a kForwardTypeDeclaration, which could be empty. return verible::GetSubtreeAsNode(type_declaration, NodeEnum::kTypeDeclaration, 1); } -const verible::SyntaxTreeLeaf* GetSymbolIdentifierFromEnumName( - const verible::Symbol& enum_name) { +const verible::SyntaxTreeLeaf *GetSymbolIdentifierFromEnumName( + const verible::Symbol &enum_name) { return verible::GetSubtreeAsLeaf(enum_name, NodeEnum::kEnumName, 0); } -const verible::SyntaxTreeLeaf* GetTypeIdentifierFromInterfaceType( - const verible::Symbol& interface_type) { +const verible::SyntaxTreeLeaf *GetTypeIdentifierFromInterfaceType( + const verible::Symbol &interface_type) { return verible::GetSubtreeAsLeaf(interface_type, NodeEnum::kInterfaceType, 2); } -const verible::Symbol* GetTypeIdentifierFromInstantiationType( - const verible::Symbol& instantiation_type) { - const verible::SyntaxTreeNode* data_type = +const verible::Symbol *GetTypeIdentifierFromInstantiationType( + const verible::Symbol &instantiation_type) { + const verible::SyntaxTreeNode *data_type = GetDataTypeFromInstantiationType(instantiation_type); if (!data_type) return nullptr; if (NodeEnum(data_type->Tag().tag) == NodeEnum::kDataType) { @@ -372,9 +372,9 @@ const verible::Symbol* GetTypeIdentifierFromInstantiationType( return nullptr; } -const verible::SyntaxTreeNode* GetTypeIdentifierFromDataType( - const verible::Symbol& data_type) { - const verible::SyntaxTreeNode& data_type_node = +const verible::SyntaxTreeNode *GetTypeIdentifierFromDataType( + const verible::Symbol &data_type) { + const verible::SyntaxTreeNode &data_type_node = verible::SymbolCastToNode(data_type); if (!data_type_node.MatchesTag(NodeEnum::kDataType)) return nullptr; // TODO(fangism): remove this check after fixing this bug: @@ -385,13 +385,13 @@ const verible::SyntaxTreeNode* GetTypeIdentifierFromDataType( if (data_type_node.children().empty()) { return nullptr; } - const verible::Symbol* base_type = GetBaseTypeFromDataType(data_type); + const verible::Symbol *base_type = GetBaseTypeFromDataType(data_type); if (base_type == nullptr) return nullptr; return GetTypeIdentifierFromBaseType(*base_type); } -const verible::SyntaxTreeNode* GetTypeIdentifierFromBaseType( - const verible::Symbol& base_type) { +const verible::SyntaxTreeNode *GetTypeIdentifierFromBaseType( + const verible::Symbol &base_type) { const auto tag = static_cast(base_type.Tag().tag); if (tag == NodeEnum::kLocalRoot) { return verible::GetSubtreeAsNode(base_type, NodeEnum::kLocalRoot, 0); diff --git a/verilog/CST/type.h b/verilog/CST/type.h index 826709d59..4206fc84b 100644 --- a/verilog/CST/type.h +++ b/verilog/CST/type.h @@ -30,9 +30,9 @@ namespace verilog { template -verible::SymbolPtr MakeDataType(T1&& qualifiers, T2&& type, - T3&& delay_or_drive_strength, - T4&& packed_dimensions) { +verible::SymbolPtr MakeDataType(T1 &&qualifiers, T2 &&type, + T3 &&delay_or_drive_strength, + T4 &&packed_dimensions) { verible::CheckOptionalSymbolAsNode(packed_dimensions, NodeEnum::kPackedDimensions); return verible::MakeTaggedNode( @@ -43,28 +43,28 @@ verible::SymbolPtr MakeDataType(T1&& qualifiers, T2&& type, // 3-argument form assumes no delay/drive-strength modifiers template -verible::SymbolPtr MakeDataType(T1&& qualifiers, T2&& type, - T3&& packed_dimensions) { +verible::SymbolPtr MakeDataType(T1 &&qualifiers, T2 &&type, + T3 &&packed_dimensions) { return MakeDataType(std::forward(qualifiers), std::forward(type), nullptr, std::forward(packed_dimensions)); } // 2-argument form assumes null qualifiers template -verible::SymbolPtr MakeDataType(T1&& type, T2&& packed_dimensions) { +verible::SymbolPtr MakeDataType(T1 &&type, T2 &&packed_dimensions) { return MakeDataType(nullptr, std::forward(type), std::forward(packed_dimensions)); } // 1-argument form assumes no packed dimensions, no qualifiers template -verible::SymbolPtr MakeDataType(T1&& type) { +verible::SymbolPtr MakeDataType(T1 &&type) { return MakeDataType(std::forward(type), nullptr); } template -verible::SymbolPtr MakeTypeDeclaration(T1&& keyword, T2&& referenced_type, - T3&& id, T4&& dimensions, T5&& semi) { +verible::SymbolPtr MakeTypeDeclaration(T1 &&keyword, T2 &&referenced_type, + T3 &&id, T4 &&dimensions, T5 &&semi) { verible::CheckSymbolAsLeaf(*ABSL_DIE_IF_NULL(keyword), TK_typedef); /* id should be one of several identifier types, usually SymbolIdentifier */ verible::CheckSymbolAsLeaf(*ABSL_DIE_IF_NULL(semi), ';'); @@ -78,15 +78,15 @@ verible::SymbolPtr MakeTypeDeclaration(T1&& keyword, T2&& referenced_type, // 4-argument form assumes null dimensions template -verible::SymbolPtr MakeTypeDeclaration(T1&& keyword, T2&& referenced_type, - T3&& id, T4&& semi) { +verible::SymbolPtr MakeTypeDeclaration(T1 &&keyword, T2 &&referenced_type, + T3 &&id, T4 &&semi) { return MakeTypeDeclaration(keyword, referenced_type, id, nullptr, semi); } // From a type like "foo::bar_t[3:0]", returns the node spanning "foo::bar_t", // removing any qualifiers or dimensions. -const verible::Symbol* GetBaseTypeFromDataType( - const verible::Symbol& data_type); +const verible::Symbol *GetBaseTypeFromDataType( + const verible::Symbol &data_type); // Re-structures and re-tags subtree to look like a data-type with packed // dimensions. This is needed as a consequence of re-using a slice of the @@ -94,104 +94,104 @@ const verible::Symbol* GetBaseTypeFromDataType( // grammar conflicts. // The original reference_call_base pointer is consumed in the process. verible::SymbolPtr ReinterpretReferenceAsDataTypePackedDimensions( - verible::SymbolPtr& reference_call_base); // NOLINT + verible::SymbolPtr &reference_call_base); // NOLINT // Finds all node kDataType declarations. Used for testing the functions below. std::vector FindAllDataTypeDeclarations( - const verible::Symbol&); + const verible::Symbol &); // Finds all nodes tagged with kEnumName. std::vector FindAllEnumNames( - const verible::Symbol& root); + const verible::Symbol &root); // Finds all node kDataTypePrimitive declarations. Used for testing the // functions below. std::vector FindAllDataTypePrimitive( - const verible::Symbol& root); + const verible::Symbol &root); // Finds all kTypeDeclaration nodes. Used for testing the functions below. std::vector FindAllTypeDeclarations( - const verible::Symbol&); + const verible::Symbol &); // Finds all node kEnumType declarations. Used for testing if the type // declaration is an enum. std::vector FindAllEnumTypes( - const verible::Symbol& root); + const verible::Symbol &root); // Finds all node kStructType declarations. Used for testing if the type // declaration is a struct. std::vector FindAllStructTypes( - const verible::Symbol& root); + const verible::Symbol &root); // Finds all node kDataTypeImplicitIdDimensions. Used for testing if the type // declaration is a struct. std::vector FindAllDataTypeImplicitIdDimensions( - const verible::Symbol& root); + const verible::Symbol &root); // Finds all node kUnionType declarations. Used for testing if the type // declaration is a union. std::vector FindAllUnionTypes( - const verible::Symbol& root); + const verible::Symbol &root); // Finds all node kInterfaceType declarations. Used for testing if the type // declaration is an interface. std::vector FindAllInterfaceTypes( - const verible::Symbol& root); + const verible::Symbol &root); // Returns true if the node kDataType has declared a storage type. -bool IsStorageTypeOfDataTypeSpecified(const verible::Symbol&); +bool IsStorageTypeOfDataTypeSpecified(const verible::Symbol &); // Extract the name of the typedef identifier from an enum, struct or union // declaration. -const verible::SyntaxTreeLeaf* GetIdentifierFromTypeDeclaration( - const verible::Symbol& symbol); +const verible::SyntaxTreeLeaf *GetIdentifierFromTypeDeclaration( + const verible::Symbol &symbol); // Extracts kUnqualifiedId or kQualifiedId node from nodes tagged with // kLocalRoot. // e.g from "pkg::some_type var1" return "pkg::some_type". -const verible::Symbol* GetIdentifiersFromLocalRoot( - const verible::Symbol& local_root); +const verible::Symbol *GetIdentifiersFromLocalRoot( + const verible::Symbol &local_root); // Extracts kUnqualifiedId or kQualifiedId node from nodes tagged with // kDataType. // e.g from "pkg::some_type var1" return "pkg::some_type". -const verible::Symbol* GetIdentifiersFromDataType( - const verible::Symbol& data_type); +const verible::Symbol *GetIdentifiersFromDataType( + const verible::Symbol &data_type); // Extracts kUnqualifiedId node from nodes tagged with kReferenceCallBase. -const verible::SyntaxTreeNode* GetUnqualifiedIdFromReferenceCallBase( - const verible::Symbol& reference_call_base); +const verible::SyntaxTreeNode *GetUnqualifiedIdFromReferenceCallBase( + const verible::Symbol &reference_call_base); // Returns the node tagged with kStructType, kEnumType or kUnionType from node // tagged with kInstantationType. -const verible::SyntaxTreeNode* GetStructOrUnionOrEnumTypeFromInstantiationType( - const verible::Symbol& instantiation_type); +const verible::SyntaxTreeNode *GetStructOrUnionOrEnumTypeFromInstantiationType( + const verible::Symbol &instantiation_type); // Returns the node tagged with kStructType, kEnumType or kUnionType from node // tagged with kDataType. -const verible::SyntaxTreeNode* GetStructOrUnionOrEnumTypeFromDataType( - const verible::Symbol& data_type); +const verible::SyntaxTreeNode *GetStructOrUnionOrEnumTypeFromDataType( + const verible::Symbol &data_type); // Extracts kPackedDimensions node from node tagged with kDataTypePrimitive. -const verible::SyntaxTreeNode* GetPackedDimensionFromDataType( - const verible::Symbol& data_type_primitive); +const verible::SyntaxTreeNode *GetPackedDimensionFromDataType( + const verible::Symbol &data_type_primitive); // Extracts a type node (without dimensions) from nodes tagged with // kInstantiationType. -const verible::Symbol* GetBaseTypeFromInstantiationType( - const verible::Symbol& instantiation_type); +const verible::Symbol *GetBaseTypeFromInstantiationType( + const verible::Symbol &instantiation_type); // For a given unqualified id node returns the node spanning param // declaration. // e.g from "class_name#(x, y)" returns returns the node spanning "#(x, y)". -const verible::SyntaxTreeNode* GetParamListFromUnqualifiedId( - const verible::Symbol& unqualified_id); -const verible::SyntaxTreeNode* GetParamListFromBaseType( - const verible::Symbol& base_type); +const verible::SyntaxTreeNode *GetParamListFromUnqualifiedId( + const verible::Symbol &unqualified_id); +const verible::SyntaxTreeNode *GetParamListFromBaseType( + const verible::Symbol &base_type); // Return the type node of the given type declaration. -const verible::SyntaxTreeNode* GetReferencedTypeOfTypeDeclaration( - const verible::Symbol& type_declaration); +const verible::SyntaxTreeNode *GetReferencedTypeOfTypeDeclaration( + const verible::Symbol &type_declaration); // Extracts symbol identifier node from node tagged with // kDataTypeImplicitIdDimension. @@ -199,50 +199,50 @@ const verible::SyntaxTreeNode* GetReferencedTypeOfTypeDeclaration( // The symbol can be found at index 1 or 2 and each one is different so the // index is returned to distinguish between them. // This works around CST structural inconsistency (bug). -std::pair +std::pair GetSymbolIdentifierFromDataTypeImplicitIdDimensions( - const verible::Symbol& struct_union_member); + const verible::Symbol &struct_union_member); // For a given node tagged with GetTypeOfDataTypeImplicitIdDimensions returns // the node spanning the type if it's not primitive type or returns nullptr. // e.g "logic x" => returns nullptr. // e.g from "some_type x" => return "some_type". -const verible::SyntaxTreeLeaf* GetNonprimitiveTypeOfDataTypeImplicitDimensions( - const verible::Symbol& data_type_implicit_id_dimensions); +const verible::SyntaxTreeLeaf *GetNonprimitiveTypeOfDataTypeImplicitDimensions( + const verible::Symbol &data_type_implicit_id_dimensions); // For a given instantiation type node returns the node spanning param // declaration. -const verible::SyntaxTreeNode* GetParamListFromInstantiationType( - const verible::Symbol& instantiation_type); +const verible::SyntaxTreeNode *GetParamListFromInstantiationType( + const verible::Symbol &instantiation_type); // Extracts symbol identifier node from node tagged with kEnumName or // nullptr if it doesn't exist. // e.g from "enum {first}" extracts "first". -const verible::SyntaxTreeLeaf* GetSymbolIdentifierFromEnumName( - const verible::Symbol& enum_name); +const verible::SyntaxTreeLeaf *GetSymbolIdentifierFromEnumName( + const verible::Symbol &enum_name); // Returns symbol identifier node for the type name from node tagged with // kInstantiationType (if exists) or return nullptr. //- e.g from "some_type x;" return "some_type". -const verible::Symbol* GetTypeIdentifierFromInstantiationType( - const verible::Symbol& instantiation_type); +const verible::Symbol *GetTypeIdentifierFromInstantiationType( + const verible::Symbol &instantiation_type); // Returns symbol identifier node for the type name from node tagged with // kDataType (if exists) or return nullptr if the base type is not a named // user-defined type. //- e.g "Bus [x:y]" => extracts "Bus". -const verible::SyntaxTreeNode* GetTypeIdentifierFromDataType( - const verible::Symbol& data_type); +const verible::SyntaxTreeNode *GetTypeIdentifierFromDataType( + const verible::Symbol &data_type); // Returns symbol identifier node for the type name from node tagged with // kDataType (if exists) or return nullptr if the base type is not a named // user-defined type. //- e.g "Bus" (as a type) return "Bus" (leaf token). -const verible::SyntaxTreeNode* GetTypeIdentifierFromBaseType( - const verible::Symbol& base_type); +const verible::SyntaxTreeNode *GetTypeIdentifierFromBaseType( + const verible::Symbol &base_type); -const verible::SyntaxTreeNode* GetLocalRootFromReference( - const verible::Symbol& reference); +const verible::SyntaxTreeNode *GetLocalRootFromReference( + const verible::Symbol &reference); } // namespace verilog diff --git a/verilog/CST/type_test.cc b/verilog/CST/type_test.cc index c48b13b03..1d891d317 100644 --- a/verilog/CST/type_test.cc +++ b/verilog/CST/type_test.cc @@ -61,10 +61,10 @@ TEST(FindAllDataTypeDeclarationsTest, BasicTests) { {"task foo(int foo, inout bar); endtask", 2}, {"task foo(bit foo, ref bar); endtask", 2}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.first, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto data_type_declarations = FindAllDataTypeDeclarations(*ABSL_DIE_IF_NULL(root)); EXPECT_EQ(data_type_declarations.size(), test.second); @@ -88,10 +88,10 @@ TEST(FindAllTypeDeclarationsTest, BasicTests) { {kTag, "typedef enum { Idle, Busy } another_name;"}, }, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllTypeDeclarations(*ABSL_DIE_IF_NULL(root)); }); } @@ -126,10 +126,10 @@ TEST(FindAllEnumTypesTest, BasicTests) { {kTag, "enum { Idle, Busy }"}, " another_name;"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllEnumTypes(*ABSL_DIE_IF_NULL(root)); }); } @@ -160,10 +160,10 @@ TEST(FindAllStructTypesTest, BasicTests) { " other_name; " "typedef enum { Idle, Busy } another_name;"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllStructTypes(*ABSL_DIE_IF_NULL(root)); }); } @@ -194,10 +194,10 @@ TEST(FindAllUnionTypesTest, BasicTests) { " other_name; " "typedef enum { Idle, Busy } another_name;"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); return FindAllUnionTypes(*ABSL_DIE_IF_NULL(root)); }); } @@ -213,12 +213,12 @@ TEST(IsStorageTypeOfDataTypeSpecifiedTest, AcceptTests) { {"task foo(int bar); endtask", 1}, {"task foo(int foo, bit bar); endtask", 2}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.first, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto data_type_declarations = FindAllDataTypeDeclarations(*root); - for (const auto& data_type : data_type_declarations) { + for (const auto &data_type : data_type_declarations) { // Only check the node kDataTypes within a node kPortList. if (analysis::ContextIsInsideTaskFunctionPortList(data_type.context)) { EXPECT_TRUE(IsStorageTypeOfDataTypeSpecified(*(data_type.match))) @@ -240,12 +240,12 @@ TEST(IsStorageTypeOfDataTypeSpecifiedTest, RejectTests) { {"task foo(foo, input bar); endtask"}, {"task foo(input foo, inout bar); endtask"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test, ""); ASSERT_OK(analyzer.Analyze()); - const auto& root = analyzer.Data().SyntaxTree(); + const auto &root = analyzer.Data().SyntaxTree(); const auto data_type_declarations = FindAllDataTypeDeclarations(*root); - for (const auto& data_type : data_type_declarations) { + for (const auto &data_type : data_type_declarations) { // Only check the node kDataTypes within a node kPortList. if (analysis::ContextIsInsideTaskFunctionPortList(data_type.context)) { EXPECT_FALSE(IsStorageTypeOfDataTypeSpecified(*(data_type.match))); @@ -270,14 +270,14 @@ TEST(GetIdentifierFromTypeDeclarationTest, TypedefNames) { {"typedef union { int a; bit [8:0] b; } ", {kTag, "bar2"}, ";"}, {"typedef union { int a; } ", {kTag, "name"}, ";"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); const auto type_declarations = FindAllTypeDeclarations(*root); std::vector ids; ids.reserve(type_declarations.size()); - for (const auto& decl : type_declarations) { + for (const auto &decl : type_declarations) { ids.push_back(TreeSearchMatch{ GetIdentifierFromTypeDeclaration(*decl.match), /* no context */}); @@ -326,17 +326,17 @@ TEST(GetVariableDeclaration, FindPackedDimensionFromDataDeclaration) { " v2 [x:y], v3 [x:y];\nendfunction"}, {"class c;\n class_type x;\nendclass"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VLOG(1) << "code:\n" << test.code; TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& decls = FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root)); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &decls = FindAllDataDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector packed_dimensions; - for (const auto& decl : decls) { + for (const auto &decl : decls) { VLOG(1) << "decl: " << verible::StringSpanOfSymbol(*decl.match); - const auto* packed_dimension = + const auto *packed_dimension = GetPackedDimensionFromDataDeclaration(*decl.match); if (packed_dimension == nullptr) continue; if (packed_dimension->children().empty()) continue; @@ -371,16 +371,16 @@ TEST(GetType, GetStructOrUnionOrEnumType) { {kTag, "enum { Idle, Busy }"}, " another_name;"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VLOG(1) << "code:\n" << test.code; TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& types = FindAllTypeDeclarations(*ABSL_DIE_IF_NULL(root)); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &types = FindAllTypeDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& decl : types) { - const auto* name = GetReferencedTypeOfTypeDeclaration(*decl.match); + for (const auto &decl : types) { + const auto *name = GetReferencedTypeOfTypeDeclaration(*decl.match); if (name == nullptr) continue; names.emplace_back(TreeSearchMatch{name, {/* ignored context */}}); } @@ -396,16 +396,16 @@ TEST(GetTypeIdentifier, GetNameOfDataType) { {"module m(logic x);\nendmodule"}, {"module m(", {kTag, "bus"}, " x);\nendmodule"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& types = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &types = FindAllDataTypeDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& decl : types) { - const auto* name = GetTypeIdentifierFromDataType(*decl.match); + for (const auto &decl : types) { + const auto *name = GetTypeIdentifierFromDataType(*decl.match); if (name == nullptr) { continue; } @@ -426,17 +426,17 @@ TEST(GetDataImplicitIdDimensions, GetTypeOfDataImplicitIdDimensions) { {"union {union {int x;} var2;} var1;"}, {"union {", {kTag, "my_type"}, " var2;} var1;"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VLOG(1) << "code:\n" << test.code; TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& types = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &types = FindAllDataTypeImplicitIdDimensions(*ABSL_DIE_IF_NULL(root)); std::vector inner_types; - for (const auto& decl : types) { - const auto* inner_type = + for (const auto &decl : types) { + const auto *inner_type = GetNonprimitiveTypeOfDataTypeImplicitDimensions(*decl.match); if (inner_type == nullptr) { continue; @@ -482,15 +482,15 @@ TEST(GetDataImplicitIdDimensions, GetNameOfDataImplicitIdDimensions) { {kTag, "yy"}, ";}\nfar;"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& types = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &types = FindAllDataTypeImplicitIdDimensions(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& decl : types) { + for (const auto &decl : types) { const auto name = GetSymbolIdentifierFromDataTypeImplicitIdDimensions( *decl.match); @@ -528,15 +528,15 @@ TEST(GetEnumName, GetEnumNameIdentifier) { {kTag, "BB"}, "} enum_var;\nendpackage"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = FindAllEnumNames(*ABSL_DIE_IF_NULL(root)); + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllEnumNames(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& decl : instances) { - const auto* name = GetSymbolIdentifierFromEnumName(*decl.match); + for (const auto &decl : instances) { + const auto *name = GetSymbolIdentifierFromEnumName(*decl.match); names.emplace_back(TreeSearchMatch{name, {/* ignored context */}}); } return names; @@ -552,16 +552,16 @@ TEST(GetIdentifiersFromDataType, GetIdentifier) { {"function ", {kTag, "void"}, " foo();\nendfunction"}, {"function foo();\n ", {kTag, "test"}, " data = foo();\nendfunction"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllDataTypeDeclarations(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& decl : instances) { - const auto* name = GetIdentifiersFromDataType(*decl.match); + for (const auto &decl : instances) { + const auto *name = GetIdentifiersFromDataType(*decl.match); names.emplace_back(TreeSearchMatch{name, {/* ignored context */}}); } return names; @@ -577,17 +577,17 @@ TEST(GetLocalRootFromReference, GetLocalRoot) { " = foo.foo();\n" "endfunction"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { TestVerilogSyntaxRangeMatches( - __FUNCTION__, test, [](const TextStructureView& text_structure) { - const auto& root = text_structure.SyntaxTree(); - const auto& instances = + __FUNCTION__, test, [](const TextStructureView &text_structure) { + const auto &root = text_structure.SyntaxTree(); + const auto &instances = FindAllReferenceFullExpressions(*ABSL_DIE_IF_NULL(root)); std::vector names; - for (const auto& decl : instances) { + for (const auto &decl : instances) { if (ReferenceIsSimpleIdentifier(*decl.match)) { - const auto* name = GetLocalRootFromReference(*decl.match); + const auto *name = GetLocalRootFromReference(*decl.match); names.emplace_back( TreeSearchMatch{name, {/* ignored context */}}); } diff --git a/verilog/CST/verilog_matchers_test.cc b/verilog/CST/verilog_matchers_test.cc index 35646ba00..d36f6c7f8 100644 --- a/verilog/CST/verilog_matchers_test.cc +++ b/verilog/CST/verilog_matchers_test.cc @@ -35,7 +35,7 @@ TEST(VerilogMatchers, SystemTFIdentifierLeafTests) { {SystemTFIdentifierLeaf(), EmbedInClass(""), 0}, {SystemTFIdentifierLeaf(), "", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -53,7 +53,7 @@ TEST(VerilogMatchers, MacroCallIdLeafTests) { {MacroCallIdLeaf(), EmbedInClassMethod("uvm_foo(\"foo\");"), 0}, {MacroCallIdLeaf(), EmbedInClassMethod("$uvm_foo(\"foo\");"), 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -68,7 +68,7 @@ TEST(VerilogMatchers, SymbolIdentifierLeaf) { {SymbolIdentifierLeaf(), EmbedInClassMethod("uvm_foo(\"foo\");"), 3}, {SymbolIdentifierLeaf(), "parameter foo = 32'hDEADBEEF;", 1}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -81,7 +81,7 @@ TEST(VerilogMatchers, VoidCastNodeTests) { {NodekVoidcast(), EmbedInClass(""), 0}, {NodekVoidcast(), "", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -94,7 +94,7 @@ TEST(VerilogMatchers, ExpressionNodeTests) { {NodekExpression(), EmbedInClass(""), 0}, {NodekExpression(), "", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -120,7 +120,7 @@ TEST(VerilogMatchers, ExpressionHasFunctionCallTests) { FunctionCallHasParenGroup()), EmbedInClassMethod("x = bar.foo();"), 1}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -135,7 +135,7 @@ TEST(VerilogMatchers, NonCallExpressionHasRandomizeCallExtensionTests) { {NonCallHasRandomizeCallExtension(), EmbedInClass(""), 0}, {NonCallHasRandomizeCallExtension(), "", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -148,7 +148,7 @@ TEST(VerilogMatchers, CallExpressionHasRandomizeCallExtensionTests) { {CallHasRandomizeCallExtension(), EmbedInClass(""), 0}, {CallHasRandomizeCallExtension(), "", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -162,7 +162,7 @@ TEST(VerilogMatchers, ExpressionHasRandomizeFunctionTests) { {ExpressionHasRandomizeFunction(), EmbedInClass(""), 0}, {ExpressionHasRandomizeFunction(), "", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -172,7 +172,7 @@ TEST(VerilogMatchers, FunctionCallHasIdTests) { const RawMatcherTestCase tests[] = { {FunctionCallHasId(), EmbedInClassMethod("foo();"), 1}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -186,7 +186,7 @@ TEST(VerilogMatchers, NumberHasConstantWidthTests) { {NumberHasConstantWidth(), "localparam x = 8'b0000_1111;", 1}, {NumberHasConstantWidth(), "localparam x = `WIDTH'bx;", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -210,7 +210,7 @@ TEST(VerilogMatchers, NumberHasBasedLiteralTests) { {NumberHasBasedLiteral(), "localparam x = 32'h 0000_4321;", 1}, {NumberHasBasedLiteral(), "localparam x = 64'H aaaa_bbbb_cccc_dddd;", 1}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -235,7 +235,7 @@ TEST(VerilogMatchers, NumberIsBinaryTests) { {NumberIsBinary(), "localparam x = 32'h 0000_4321;", 0}, {NumberIsBinary(), "localparam x = 64'H aaaa_bbbb_cccc_dddd;", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -260,7 +260,7 @@ TEST(VerilogMatchers, NumberHasBinaryDigitsTests) { {NumberHasBinaryDigits(), "localparam x = 32'h 0000_4321;", 0}, {NumberHasBinaryDigits(), "localparam x = 64'H aaaa_bbbb_cccc_dddd;", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -275,7 +275,7 @@ TEST(VerilogMatchers, ActualParameterListNodeTests) { {NodekActualParameterList(), EmbedInModule(""), 0}, {NodekActualParameterList(), "", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -290,7 +290,7 @@ TEST(VerilogMatchers, ActualParameterListHasPositionalParameterListTests) { {ActualParameterListHasPositionalParameterList(), EmbedInModule(""), 0}, {ActualParameterListHasPositionalParameterList(), "", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -304,7 +304,7 @@ TEST(VerilogMatchers, GateInstanceNodeTests) { {NodekGateInstance(), EmbedInModule(""), 0}, {NodekGateInstance(), "", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -317,7 +317,7 @@ TEST(VerilogMatchers, GateInstanceHasPortListTests) { {GateInstanceHasPortList(), EmbedInModule(""), 0}, {GateInstanceHasPortList(), "", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -339,7 +339,7 @@ TEST(VerilogMatchers, GenerateBlockNodeTests) { {NodekGenerateBlock(), EmbedInModule(""), 0}, {NodekGenerateBlock(), "", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -362,7 +362,7 @@ TEST(VerilogMatchers, GenerateRegionNodeTests) { {NodekGenerateRegion(), EmbedInModule(""), 0}, {NodekGenerateRegion(), "", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -387,7 +387,7 @@ TEST(VerilogMatchers, HasBeginLabelTests) { {HasBeginLabel(), EmbedInModule(""), 0}, {HasBeginLabel(), "", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -426,7 +426,7 @@ TEST(VerilogMatchers, HasGenerateBlockTests) { "endgenerate"), 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -449,7 +449,7 @@ TEST(VerilogMatchers, GenerateBlockHasBeginLabelTests) { "endgenerate"), 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -472,7 +472,7 @@ TEST(VerilogMatchers, AlwaysStatementNodeTests) { "always_comb begin a = b; end"), 2}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -493,7 +493,7 @@ TEST(VerilogMatchers, AlwaysKeywordTests) { "always_comb begin a = b; end"), 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -514,7 +514,7 @@ TEST(VerilogMatchers, AlwaysCombKeywordTests) { "always_comb begin a = b; end"), 1}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -535,7 +535,7 @@ TEST(VerilogMatchers, AlwaysFFKeywordTests) { "always_comb begin a = b; end"), 1}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -559,7 +559,7 @@ TEST(VerilogMatchers, AlwaysStatementHasEventControlStarTests) { "always_comb begin a = b; end"), 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -577,7 +577,7 @@ TEST(VerilogMatchers, AlwaysStatementHasEventControlStarAndParentheses) { {AlwaysStatementHasEventControlStarAndParentheses(), EmbedInModule("always @( * ) begin a = b; end"), 1}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -598,7 +598,7 @@ TEST(VerilogMatchers, AlwaysStatementHasParentheses) { {AlwaysStatementHasParentheses(), EmbedInModule("always @(posedge foo) begin a <= b; end"), 1}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -621,7 +621,7 @@ TEST(VerilogMatchers, PathkLPValueTests) { {PathkLPValue(), EmbedInClassMethod("forever x = y;"), 1}, {PathkLPValue(), EmbedInClassMethod("x = 1;\ny = two();"), 2}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -643,7 +643,7 @@ TEST(VerilogMatchers, RValueIsFunctionCallTest) { {RValueIsFunctionCall(), EmbedInClassMethod("x = bar::foo() -12;"), 0}, {RValueIsFunctionCall(), EmbedInClassMethod("x = a + bar::foo();"), 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -666,7 +666,7 @@ TEST(VerilogMatchers, FunctionCallIsQualifiedTest) { {FunctionCallIsQualified(), EmbedInClassMethod("x = bar::foo() -12;"), 1}, {FunctionCallIsQualified(), EmbedInClassMethod("x = a + bar::foo();"), 1}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -714,7 +714,7 @@ TEST(VerilogMatchers, RValueFunctionCallIsQualifiedTest) { {RValueIsFunctionCall(FunctionCallIsQualified()), EmbedInClassMethod("x = a + bar::foo();"), 0}, // outermost rvalue is + }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -736,7 +736,7 @@ TEST(VerilogMatchers, FunctionCallArgumentsTest) { {FunctionCallArguments(), EmbedInClassMethod("x = foobar();"), 0}, {FunctionCallArguments(), EmbedInClassMethod("f.g.h = foobar(g);"), 1}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -756,7 +756,7 @@ TEST(VerilogMatchers, DeclarationDimensionsHasRanges) { {DeclarationDimensionsHasRanges(), EmbedInModule("wire [1:2] w [1:0];"), 2}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } @@ -784,7 +784,7 @@ TEST(VerilogMatchers, HasDefaultCaseTests) { )", 0}, }; - for (const auto& test : tests) { + for (const auto &test : tests) { verible::matcher::RunRawMatcherTestCase(test); } } diff --git a/verilog/CST/verilog_nonterminals.cc b/verilog/CST/verilog_nonterminals.cc index 87c0d6677..3564076ec 100644 --- a/verilog/CST/verilog_nonterminals.cc +++ b/verilog/CST/verilog_nonterminals.cc @@ -35,7 +35,7 @@ std::string NodeEnumToString(NodeEnum node_enum) { } } -std::ostream& operator<<(std::ostream& stream, const NodeEnum& e) { +std::ostream &operator<<(std::ostream &stream, const NodeEnum &e) { return stream << NodeEnumToString(e); } diff --git a/verilog/CST/verilog_nonterminals.h b/verilog/CST/verilog_nonterminals.h index a22a78558..1acb10737 100644 --- a/verilog/CST/verilog_nonterminals.h +++ b/verilog/CST/verilog_nonterminals.h @@ -518,7 +518,7 @@ enum class NodeEnum { // must be maintained manually as NodeEnum's are added std::string NodeEnumToString(NodeEnum node_enum); -std::ostream& operator<<(std::ostream&, const NodeEnum&); +std::ostream &operator<<(std::ostream &, const NodeEnum &); // Predicate which returns true if the node_enum is a preprocessing node bool IsPreprocessingNode(NodeEnum node_enum); diff --git a/verilog/CST/verilog_tree_json.cc b/verilog/CST/verilog_tree_json.cc index 68547b504..fae95abd8 100644 --- a/verilog/CST/verilog_tree_json.cc +++ b/verilog/CST/verilog_tree_json.cc @@ -33,8 +33,8 @@ class VerilogTreeToJsonConverter : public verible::SymbolVisitor { public: explicit VerilogTreeToJsonConverter(absl::string_view base); - void Visit(const verible::SyntaxTreeLeaf&) final; - void Visit(const verible::SyntaxTreeNode&) final; + void Visit(const verible::SyntaxTreeLeaf &) final; + void Visit(const verible::SyntaxTreeNode &) final; json TakeJsonValue() { return std::move(json_); } @@ -47,17 +47,17 @@ class VerilogTreeToJsonConverter : public verible::SymbolVisitor { // Pointer to JSON value of currently visited symbol in its parent's // children list. - json* value_; + json *value_; }; VerilogTreeToJsonConverter::VerilogTreeToJsonConverter(absl::string_view base) : context_(base, - [](std::ostream& stream, int e) { + [](std::ostream &stream, int e) { stream << TokenTypeToString(static_cast(e)); }), value_(&json_) {} -void VerilogTreeToJsonConverter::Visit(const verible::SyntaxTreeLeaf& leaf) { +void VerilogTreeToJsonConverter::Visit(const verible::SyntaxTreeLeaf &leaf) { const verilog_tokentype tokentype = static_cast(leaf.Tag().tag); absl::string_view type_str = TokenTypeToString(tokentype); @@ -71,14 +71,14 @@ void VerilogTreeToJsonConverter::Visit(const verible::SyntaxTreeLeaf& leaf) { *value_ = verible::ToJson(leaf.get(), context_, include_text); } -void VerilogTreeToJsonConverter::Visit(const verible::SyntaxTreeNode& node) { +void VerilogTreeToJsonConverter::Visit(const verible::SyntaxTreeNode &node) { *value_ = json::object(); (*value_)["tag"] = NodeEnumToString(static_cast(node.Tag().tag)); - json& children = (*value_)["children"] = json::array(); + json &children = (*value_)["children"] = json::array(); { - const verible::ValueSaver value_saver(&value_, nullptr); - for (const auto& child : node.children()) { + const verible::ValueSaver value_saver(&value_, nullptr); + for (const auto &child : node.children()) { value_ = &children.emplace_back(nullptr); // nullptrs from children list are intentionally preserved in JSON as // `null` values. @@ -87,7 +87,7 @@ void VerilogTreeToJsonConverter::Visit(const verible::SyntaxTreeNode& node) { } } -json ConvertVerilogTreeToJson(const verible::Symbol& root, +json ConvertVerilogTreeToJson(const verible::Symbol &root, absl::string_view base) { VerilogTreeToJsonConverter converter(base); root.Accept(&converter); diff --git a/verilog/CST/verilog_tree_json.h b/verilog/CST/verilog_tree_json.h index cb5212036..d77f4ba80 100644 --- a/verilog/CST/verilog_tree_json.h +++ b/verilog/CST/verilog_tree_json.h @@ -22,7 +22,7 @@ namespace verilog { // Returns a JSON representation of tree contained at root. -nlohmann::json ConvertVerilogTreeToJson(const verible::Symbol& root, +nlohmann::json ConvertVerilogTreeToJson(const verible::Symbol &root, absl::string_view base); } // namespace verilog diff --git a/verilog/CST/verilog_tree_json_test.cc b/verilog/CST/verilog_tree_json_test.cc index 2ddb3c009..42cc6a639 100644 --- a/verilog/CST/verilog_tree_json_test.cc +++ b/verilog/CST/verilog_tree_json_test.cc @@ -32,7 +32,7 @@ TEST(VerilogTreeJsonTest, GeneratesGoodJsonTree) { "module foo;\nendmodule\n", "fake_file.sv"); const auto status = ABSL_DIE_IF_NULL(analyzer_ptr)->Analyze(); EXPECT_TRUE(status.ok()) << status.message(); - const verible::SymbolPtr& tree_ptr = analyzer_ptr->SyntaxTree(); + const verible::SymbolPtr &tree_ptr = analyzer_ptr->SyntaxTree(); ASSERT_NE(tree_ptr, nullptr); const json tree_json(verilog::ConvertVerilogTreeToJson( diff --git a/verilog/CST/verilog_tree_print.cc b/verilog/CST/verilog_tree_print.cc index 8532cf74b..4197db0ae 100644 --- a/verilog/CST/verilog_tree_print.cc +++ b/verilog/CST/verilog_tree_print.cc @@ -32,20 +32,20 @@ namespace verilog { -VerilogPrettyPrinter::VerilogPrettyPrinter(std::ostream* output_stream, +VerilogPrettyPrinter::VerilogPrettyPrinter(std::ostream *output_stream, absl::string_view base) : verible::PrettyPrinter( output_stream, - verible::TokenInfo::Context(base, [](std::ostream& stream, int e) { + verible::TokenInfo::Context(base, [](std::ostream &stream, int e) { stream << verilog_symbol_name(e); })) {} -void VerilogPrettyPrinter::Visit(const verible::SyntaxTreeLeaf& leaf) { +void VerilogPrettyPrinter::Visit(const verible::SyntaxTreeLeaf &leaf) { auto_indent() << "Leaf @" << child_rank_ << ' ' << verible::TokenWithContext{leaf.get(), context_} << std::endl; } -void VerilogPrettyPrinter::Visit(const verible::SyntaxTreeNode& node) { +void VerilogPrettyPrinter::Visit(const verible::SyntaxTreeNode &node) { std::string tag_info = absl::StrCat( "(tag: ", NodeEnumToString(static_cast(node.Tag().tag)), ") "); @@ -55,7 +55,7 @@ void VerilogPrettyPrinter::Visit(const verible::SyntaxTreeNode& node) { { const verible::ValueSaver value_saver(&indent_, indent_ + 2); const verible::ValueSaver rank_saver(&child_rank_, 0); - for (const auto& child : node.children()) { + for (const auto &child : node.children()) { // TODO(fangism): display nullptrs or child indices to show position. if (child) child->Accept(this); ++child_rank_; @@ -64,8 +64,8 @@ void VerilogPrettyPrinter::Visit(const verible::SyntaxTreeNode& node) { auto_indent() << "}" << std::endl; } -void PrettyPrintVerilogTree(const verible::Symbol& root, absl::string_view base, - std::ostream* stream) { +void PrettyPrintVerilogTree(const verible::Symbol &root, absl::string_view base, + std::ostream *stream) { VerilogPrettyPrinter printer(stream, base); root.Accept(&printer); } diff --git a/verilog/CST/verilog_tree_print.h b/verilog/CST/verilog_tree_print.h index a012bd58e..276d9553c 100644 --- a/verilog/CST/verilog_tree_print.h +++ b/verilog/CST/verilog_tree_print.h @@ -28,18 +28,18 @@ namespace verilog { class VerilogPrettyPrinter : public verible::PrettyPrinter { public: - explicit VerilogPrettyPrinter(std::ostream* output_stream, + explicit VerilogPrettyPrinter(std::ostream *output_stream, absl::string_view base); - void Visit(const verible::SyntaxTreeLeaf&) final; - void Visit(const verible::SyntaxTreeNode&) final; + void Visit(const verible::SyntaxTreeLeaf &) final; + void Visit(const verible::SyntaxTreeNode &) final; // void Visit(verible::SyntaxTreeNode*) final; }; // Prints tree contained at root to stream -void PrettyPrintVerilogTree(const verible::Symbol& root, absl::string_view base, - std::ostream* stream); +void PrettyPrintVerilogTree(const verible::Symbol &root, absl::string_view base, + std::ostream *stream); } // namespace verilog diff --git a/verilog/CST/verilog_tree_print_test.cc b/verilog/CST/verilog_tree_print_test.cc index 17c072250..c93b22d30 100644 --- a/verilog/CST/verilog_tree_print_test.cc +++ b/verilog/CST/verilog_tree_print_test.cc @@ -35,7 +35,7 @@ TEST(VerilogTreePrintTest, Prints) { EXPECT_TRUE(status.ok()); std::ostringstream stream; EXPECT_TRUE(stream.str().empty()); - const verible::SymbolPtr& tree_ptr = analyzer->SyntaxTree(); + const verible::SymbolPtr &tree_ptr = analyzer->SyntaxTree(); ASSERT_NE(tree_ptr, nullptr); PrettyPrintVerilogTree(*tree_ptr, analyzer->Data().Contents(), &stream); diff --git a/verilog/CST/verilog_treebuilder_utils.cc b/verilog/CST/verilog_treebuilder_utils.cc index 00e9dee4e..2893bf81f 100644 --- a/verilog/CST/verilog_treebuilder_utils.cc +++ b/verilog/CST/verilog_treebuilder_utils.cc @@ -48,9 +48,9 @@ std::string EmbedInClassMethod(absl::string_view text) { return EmbedInClass(EmbedInFunction(text)); } -void ExpectString(const verible::SymbolPtr& symbol, +void ExpectString(const verible::SymbolPtr &symbol, absl::string_view expected) { - const auto* leaf = down_cast(symbol.get()); + const auto *leaf = down_cast(symbol.get()); CHECK(leaf != nullptr) << "expected: " << expected; CHECK_EQ(leaf->get().text(), expected); } diff --git a/verilog/CST/verilog_treebuilder_utils.h b/verilog/CST/verilog_treebuilder_utils.h index 36b7bec9d..be78cbe60 100644 --- a/verilog/CST/verilog_treebuilder_utils.h +++ b/verilog/CST/verilog_treebuilder_utils.h @@ -51,11 +51,11 @@ std::string EmbedInClassMethod(absl::string_view text); // Checks that symbol is symbol is a leaf and its text matches expected // Uses gunit's CHECK to raise error -void ExpectString(const verible::SymbolPtr& symbol, absl::string_view expected); +void ExpectString(const verible::SymbolPtr &symbol, absl::string_view expected); template -verible::SymbolPtr MakeParenGroup(T1&& left_paren, T2&& contents, - T3&& right_paren) { +verible::SymbolPtr MakeParenGroup(T1 &&left_paren, T2 &&contents, + T3 &&right_paren) { ExpectString(left_paren, "("); if (contents != nullptr) { ExpectString(right_paren, ")"); @@ -66,8 +66,8 @@ verible::SymbolPtr MakeParenGroup(T1&& left_paren, T2&& contents, } template -verible::SymbolPtr MakeBracketGroup(T1&& left_brace, T2&& contents, - T3&& right_brace) { +verible::SymbolPtr MakeBracketGroup(T1 &&left_brace, T2 &&contents, + T3 &&right_brace) { ExpectString(left_brace, "["); ExpectString(right_brace, "]"); return verible::MakeTaggedNode( @@ -76,8 +76,8 @@ verible::SymbolPtr MakeBracketGroup(T1&& left_brace, T2&& contents, } template -verible::SymbolPtr MakeBraceGroup(T1&& left_brace, T2&& contents, - T3&& right_brace) { +verible::SymbolPtr MakeBraceGroup(T1 &&left_brace, T2 &&contents, + T3 &&right_brace) { ExpectString(left_brace, "{"); ExpectString(right_brace, "}"); return verible::MakeTaggedNode( diff --git a/verilog/analysis/checkers/always_comb_blocking_rule.h b/verilog/analysis/checkers/always_comb_blocking_rule.h index a75262604..b14eab74c 100644 --- a/verilog/analysis/checkers/always_comb_blocking_rule.h +++ b/verilog/analysis/checkers/always_comb_blocking_rule.h @@ -31,10 +31,10 @@ class AlwaysCombBlockingRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/always_comb_rule.h b/verilog/analysis/checkers/always_comb_rule.h index 5e1c77293..e90107436 100644 --- a/verilog/analysis/checkers/always_comb_rule.h +++ b/verilog/analysis/checkers/always_comb_rule.h @@ -34,10 +34,10 @@ class AlwaysCombRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/always_ff_non_blocking_rule.cc b/verilog/analysis/checkers/always_ff_non_blocking_rule.cc index ce61e47fd..4d3fabb6c 100644 --- a/verilog/analysis/checkers/always_ff_non_blocking_rule.cc +++ b/verilog/analysis/checkers/always_ff_non_blocking_rule.cc @@ -48,7 +48,7 @@ static constexpr absl::string_view kMessage = "Use blocking assignments, at most, for locals inside " "'always_ff' sequential blocks."; -const LintRuleDescriptor& AlwaysFFNonBlockingRule::GetDescriptor() { +const LintRuleDescriptor &AlwaysFFNonBlockingRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "always-ff-non-blocking", .topic = "sequential-logic", @@ -78,8 +78,8 @@ absl::Status AlwaysFFNonBlockingRule::Configure( } //- Processing -------------------------------------------------------------- -void AlwaysFFNonBlockingRule::HandleSymbol(const verible::Symbol& symbol, - const SyntaxTreeContext& context) { +void AlwaysFFNonBlockingRule::HandleSymbol(const verible::Symbol &symbol, + const SyntaxTreeContext &context) { //- Process and filter context before locating blocking assigments -------- // Detect entering and leaving of always_ff blocks @@ -99,14 +99,14 @@ void AlwaysFFNonBlockingRule::HandleSymbol(const verible::Symbol& symbol, // Rule may be waived if complete lhs consists of local variables // -> determine root of lhs - const verible::Symbol* check_root = nullptr; + const verible::Symbol *check_root = nullptr; verible::matcher::BoundSymbolManager symbol_man; if (asgn_blocking_matcher.Matches(symbol, &symbol_man)) { - if (const auto* const node = - verible::down_cast(&symbol)) { + if (const auto *const node = + verible::down_cast(&symbol)) { check_root = - /* lhs */ verible::down_cast( + /* lhs */ verible::down_cast( node->children()[0].get()); } } else { @@ -114,10 +114,10 @@ void AlwaysFFNonBlockingRule::HandleSymbol(const verible::Symbol& symbol, if (!catch_modifying_assignments_) return; if (asgn_modify_matcher.Matches(symbol, &symbol_man)) { - if (const auto* const node = - verible::down_cast(&symbol)) { + if (const auto *const node = + verible::down_cast(&symbol)) { check_root = - /* lhs */ verible::down_cast( + /* lhs */ verible::down_cast( node->children()[0].get()); } } else if (asgn_incdec_matcher.Matches(symbol, &symbol_man)) { @@ -133,16 +133,16 @@ void AlwaysFFNonBlockingRule::HandleSymbol(const verible::Symbol& symbol, bool waived = false; if (waive_for_locals_ && check_root) { waived = true; - for (const auto& var : SearchSyntaxTree(*check_root, ident_matcher)) { + for (const auto &var : SearchSyntaxTree(*check_root, ident_matcher)) { if (var.context.IsInside(NodeEnum::kDimensionScalar)) continue; if (var.context.IsInside(NodeEnum::kDimensionSlice)) continue; if (var.context.IsInside(NodeEnum::kHierarchyExtension)) continue; bool found = false; - if (const auto* const varn = - verible::down_cast(var.match)) { - if (const auto* const ident = - verible::down_cast( + if (const auto *const varn = + verible::down_cast(var.match)) { + if (const auto *const ident = + verible::down_cast( varn->children()[0].get())) { found = std::find(locals_.begin(), locals_.end(), ident->get().text()) != locals_.end(); @@ -158,7 +158,7 @@ void AlwaysFFNonBlockingRule::HandleSymbol(const verible::Symbol& symbol, if (!waived) violations_.insert(LintViolation(symbol, kMessage, context)); } // HandleSymbol() -bool AlwaysFFNonBlockingRule::InsideBlock(const verible::Symbol& symbol, +bool AlwaysFFNonBlockingRule::InsideBlock(const verible::Symbol &symbol, const int depth) { static const Matcher always_ff_matcher{ NodekAlwaysStatement(AlwaysFFKeyword())}; @@ -197,18 +197,18 @@ bool AlwaysFFNonBlockingRule::InsideBlock(const verible::Symbol& symbol, return true; } // InsideBlock() -bool AlwaysFFNonBlockingRule::LocalDeclaration(const verible::Symbol& symbol) { +bool AlwaysFFNonBlockingRule::LocalDeclaration(const verible::Symbol &symbol) { static const Matcher decl_matcher{NodekDataDeclaration()}; static const Matcher var_matcher{NodekRegisterVariable()}; verible::matcher::BoundSymbolManager symbol_man; if (decl_matcher.Matches(symbol, &symbol_man)) { - auto& count = scopes_.top().inherited_local_count; - for (const auto& var : SearchSyntaxTree(symbol, var_matcher)) { - if (const auto* const node = - verible::down_cast(var.match)) { - if (const auto* const ident = - verible::down_cast( + auto &count = scopes_.top().inherited_local_count; + for (const auto &var : SearchSyntaxTree(symbol, var_matcher)) { + if (const auto *const node = + verible::down_cast(var.match)) { + if (const auto *const ident = + verible::down_cast( node->children()[0].get())) { const absl::string_view name = ident->get().text(); VLOG(4) << "Registering '" << name << '\'' << std::endl; diff --git a/verilog/analysis/checkers/always_ff_non_blocking_rule.h b/verilog/analysis/checkers/always_ff_non_blocking_rule.h index e2d7bcd56..5e041bdc1 100644 --- a/verilog/analysis/checkers/always_ff_non_blocking_rule.h +++ b/verilog/analysis/checkers/always_ff_non_blocking_rule.h @@ -32,19 +32,19 @@ class AlwaysFFNonBlockingRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); absl::Status Configure(absl::string_view configuration) final; - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; private: // Detects entering and leaving relevant code inside always_ff - bool InsideBlock(const verible::Symbol& symbol, int depth); + bool InsideBlock(const verible::Symbol &symbol, int depth); // Processes local declarations - bool LocalDeclaration(const verible::Symbol& symbol); + bool LocalDeclaration(const verible::Symbol &symbol); private: // Collected violations. diff --git a/verilog/analysis/checkers/banned_declared_name_patterns_rule.cc b/verilog/analysis/checkers/banned_declared_name_patterns_rule.cc index e898dd2aa..7a7ed812b 100644 --- a/verilog/analysis/checkers/banned_declared_name_patterns_rule.cc +++ b/verilog/analysis/checkers/banned_declared_name_patterns_rule.cc @@ -40,7 +40,7 @@ using verible::LintViolation; static constexpr absl::string_view kMessage = "Check banned declared name patterns"; -const LintRuleDescriptor& BannedDeclaredNamePatternsRule::GetDescriptor() { +const LintRuleDescriptor &BannedDeclaredNamePatternsRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "banned-declared-name-patterns", .topic = "identifiers", @@ -52,12 +52,12 @@ const LintRuleDescriptor& BannedDeclaredNamePatternsRule::GetDescriptor() { } void BannedDeclaredNamePatternsRule::HandleNode( - const verible::SyntaxTreeNode& node, - const verible::SyntaxTreeContext& context) { + const verible::SyntaxTreeNode &node, + const verible::SyntaxTreeContext &context) { const auto tag = static_cast(node.Tag().tag); switch (tag) { case NodeEnum::kModuleDeclaration: { - const auto* module_match = GetModuleName(node); + const auto *module_match = GetModuleName(node); if (module_match) { const absl::string_view module_id = module_match->get().text(); @@ -68,7 +68,7 @@ void BannedDeclaredNamePatternsRule::HandleNode( break; } case NodeEnum::kPackageDeclaration: { - const verible::TokenInfo* pack_match = GetPackageNameToken(node); + const verible::TokenInfo *pack_match = GetPackageNameToken(node); if (pack_match) { absl::string_view pack_id = pack_match->text(); if (absl::EqualsIgnoreCase(pack_id, "ILLEGALNAME")) { diff --git a/verilog/analysis/checkers/banned_declared_name_patterns_rule.h b/verilog/analysis/checkers/banned_declared_name_patterns_rule.h index e84c27df5..a51ce9161 100644 --- a/verilog/analysis/checkers/banned_declared_name_patterns_rule.h +++ b/verilog/analysis/checkers/banned_declared_name_patterns_rule.h @@ -35,10 +35,10 @@ class BannedDeclaredNamePatternsRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleNode(const verible::SyntaxTreeNode& node, - const verible::SyntaxTreeContext& context) final; + void HandleNode(const verible::SyntaxTreeNode &node, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/case_missing_default_rule.cc b/verilog/analysis/checkers/case_missing_default_rule.cc index 04f08a838..e777ab04d 100644 --- a/verilog/analysis/checkers/case_missing_default_rule.cc +++ b/verilog/analysis/checkers/case_missing_default_rule.cc @@ -42,7 +42,7 @@ VERILOG_REGISTER_LINT_RULE(CaseMissingDefaultRule); static constexpr absl::string_view kMessage = "Explicitly define a default case for every case statement."; -const LintRuleDescriptor& CaseMissingDefaultRule::GetDescriptor() { +const LintRuleDescriptor &CaseMissingDefaultRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "case-missing-default", .topic = "case-statements", @@ -51,14 +51,14 @@ const LintRuleDescriptor& CaseMissingDefaultRule::GetDescriptor() { return d; } -static const Matcher& CaseMatcher() { +static const Matcher &CaseMatcher() { static const Matcher matcher( NodekCaseItemList(verible::matcher::Unless(HasDefaultCase()))); return matcher; } void CaseMissingDefaultRule::HandleSymbol( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) { + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (context.DirectParentIs(NodeEnum::kCaseStatement) && CaseMatcher().Matches(symbol, &manager)) { diff --git a/verilog/analysis/checkers/case_missing_default_rule.h b/verilog/analysis/checkers/case_missing_default_rule.h index a1103e850..0f065282c 100644 --- a/verilog/analysis/checkers/case_missing_default_rule.h +++ b/verilog/analysis/checkers/case_missing_default_rule.h @@ -33,10 +33,10 @@ class CaseMissingDefaultRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/create_object_name_match_rule.cc b/verilog/analysis/checkers/create_object_name_match_rule.cc index 9d5af8c9f..d3c3f57ac 100644 --- a/verilog/analysis/checkers/create_object_name_match_rule.cc +++ b/verilog/analysis/checkers/create_object_name_match_rule.cc @@ -53,7 +53,7 @@ using verible::matcher::Matcher; // Register CreateObjectNameMatchRule VERILOG_REGISTER_LINT_RULE(CreateObjectNameMatchRule); -const LintRuleDescriptor& CreateObjectNameMatchRule::GetDescriptor() { +const LintRuleDescriptor &CreateObjectNameMatchRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "create-object-name-match", .topic = "uvm-naming", @@ -72,7 +72,7 @@ const LintRuleDescriptor& CreateObjectNameMatchRule::GetDescriptor() { // Here, the LHS var_h will be bound to "lval" (only for simple references), // the qualified function call (mytype::type_id::create) will be bound to // "func", and the list of function call arguments will be bound to "args". -static const Matcher& CreateAssignmentMatcher() { +static const Matcher &CreateAssignmentMatcher() { // function-local static to avoid initialization-ordering problems static const Matcher matcher(NodekNetVariableAssignment( PathkLPValue(PathkReference().Bind("lval_ref")), @@ -85,15 +85,15 @@ static const Matcher& CreateAssignmentMatcher() { // and returns false if the necessary conditions are not met. // TODO(fangism): This function will be useful to many other analyses. // Make public and refactor. -static bool UnqualifiedIdEquals(const SyntaxTreeNode& node, +static bool UnqualifiedIdEquals(const SyntaxTreeNode &node, absl::string_view name) { if (node.MatchesTag(NodeEnum::kUnqualifiedId)) { if (!node.children().empty()) { // The one-and-only child is the SymbolIdentifier token - const auto& leaf_ptr = - down_cast(node.children().front().get()); + const auto &leaf_ptr = + down_cast(node.children().front().get()); if (leaf_ptr != nullptr) { - const TokenInfo& token = leaf_ptr->get(); + const TokenInfo &token = leaf_ptr->get(); return token.token_enum() == SymbolIdentifier && token.text() == name; } } @@ -104,17 +104,17 @@ static bool UnqualifiedIdEquals(const SyntaxTreeNode& node, // Returns true if the qualified call is in the form "::type_id::create". // TODO(fangism): Refactor into QualifiedCallEndsWith(). static bool QualifiedCallIsTypeIdCreate( - const SyntaxTreeNode& qualified_id_node) { - const auto& children = qualified_id_node.children(); + const SyntaxTreeNode &qualified_id_node) { + const auto &children = qualified_id_node.children(); const size_t num_children = children.size(); // Allow for more than 3 segments, in case of package qualification, e.g. // my_pkg::class_type::type_id::create. // 5: 3 segments + 2 separators (in alternation), e.g. A::B::C if (qualified_id_node.children().size() >= 5) { - const auto* create_leaf_ptr = - down_cast(children.back().get()); - const auto* type_id_leaf_ptr = - down_cast(children[num_children - 3].get()); + const auto *create_leaf_ptr = + down_cast(children.back().get()); + const auto *type_id_leaf_ptr = + down_cast(children[num_children - 3].get()); if (create_leaf_ptr != nullptr && type_id_leaf_ptr != nullptr) { return UnqualifiedIdEquals(*create_leaf_ptr, "create") && UnqualifiedIdEquals(*type_id_leaf_ptr, "type_id"); @@ -135,8 +135,8 @@ static absl::string_view StripOuterQuotes(absl::string_view text) { // Returns token information for a single string literal expression, or nullptr // if the expression is not a string literal. // `expr_node` should be a SyntaxTreeNode tagged as an expression. -static const TokenInfo* ExtractStringLiteralToken( - const SyntaxTreeNode& expr_node) { +static const TokenInfo *ExtractStringLiteralToken( + const SyntaxTreeNode &expr_node) { if (!expr_node.MatchesTag(NodeEnum::kExpression)) return nullptr; // this check is limited to only checking string literal leaf tokens @@ -145,10 +145,10 @@ static const TokenInfo* ExtractStringLiteralToken( return nullptr; } - const auto* leaf_ptr = - down_cast(expr_node.children().front().get()); + const auto *leaf_ptr = + down_cast(expr_node.children().front().get()); if (leaf_ptr != nullptr) { - const TokenInfo& token = leaf_ptr->get(); + const TokenInfo &token = leaf_ptr->get(); if (token.token_enum() == TK_StringLiteral) { return &token; } @@ -157,12 +157,12 @@ static const TokenInfo* ExtractStringLiteralToken( } // Returns the first expression from an argument list, if it exists. -static const SyntaxTreeNode* GetFirstExpressionFromArgs( - const SyntaxTreeNode& args_node) { +static const SyntaxTreeNode *GetFirstExpressionFromArgs( + const SyntaxTreeNode &args_node) { if (!args_node.children().empty()) { - const auto& first_arg = args_node.children().front(); - if (const auto* first_expr = - down_cast(first_arg.get())) { + const auto &first_arg = args_node.children().front(); + if (const auto *first_expr = + down_cast(first_arg.get())) { return first_expr; } } @@ -178,30 +178,30 @@ static std::string FormatReason(absl::string_view decl_name, decl_name, ", got: ", name_text, ". "); } -void CreateObjectNameMatchRule::HandleSymbol(const verible::Symbol& symbol, - const SyntaxTreeContext& context) { +void CreateObjectNameMatchRule::HandleSymbol(const verible::Symbol &symbol, + const SyntaxTreeContext &context) { // Check for assignments that match the pattern. verible::matcher::BoundSymbolManager manager; if (!CreateAssignmentMatcher().Matches(symbol, &manager)) return; // Extract named bindings for matched nodes within this match. - const auto* lval_ref = manager.GetAs("lval_ref"); + const auto *lval_ref = manager.GetAs("lval_ref"); if (lval_ref == nullptr) return; - const TokenInfo* lval_id = ReferenceIsSimpleIdentifier(*lval_ref); + const TokenInfo *lval_id = ReferenceIsSimpleIdentifier(*lval_ref); if (lval_id == nullptr) return; if (lval_id->token_enum() != SymbolIdentifier) return; - const auto* call = manager.GetAs("func"); - const auto* args = manager.GetAs("args"); + const auto *call = manager.GetAs("func"); + const auto *args = manager.GetAs("args"); if (call == nullptr) return; if (args == nullptr) return; if (!QualifiedCallIsTypeIdCreate(*call)) return; // The first argument is a string that must match the variable name, lval. - if (const auto* expr = GetFirstExpressionFromArgs(*args)) { - if (const TokenInfo* name_token = ExtractStringLiteralToken(*expr)) { + if (const auto *expr = GetFirstExpressionFromArgs(*args)) { + if (const TokenInfo *name_token = ExtractStringLiteralToken(*expr)) { if (StripOuterQuotes(name_token->text()) != lval_id->text()) { violations_.insert(LintViolation( *name_token, FormatReason(lval_id->text(), name_token->text()))); diff --git a/verilog/analysis/checkers/create_object_name_match_rule.h b/verilog/analysis/checkers/create_object_name_match_rule.h index 02b9c6d22..de7a9d37f 100644 --- a/verilog/analysis/checkers/create_object_name_match_rule.h +++ b/verilog/analysis/checkers/create_object_name_match_rule.h @@ -44,10 +44,10 @@ class CreateObjectNameMatchRule : public verible::SyntaxTreeLintRule { // verilog/analysis/lint_rule_registry.h. using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/disable_statement_rule.cc b/verilog/analysis/checkers/disable_statement_rule.cc index a61ccc464..46df21989 100644 --- a/verilog/analysis/checkers/disable_statement_rule.cc +++ b/verilog/analysis/checkers/disable_statement_rule.cc @@ -48,7 +48,7 @@ static constexpr absl::string_view kMessageSeqBlock = "Invalid usage of disable statement. Preferred construction is: disable " "label_of_seq_block;"; -const LintRuleDescriptor& DisableStatementNoLabelsRule::GetDescriptor() { +const LintRuleDescriptor &DisableStatementNoLabelsRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "disable-statement", .topic = "disable-invalid-in-non-sequential", @@ -60,21 +60,21 @@ const LintRuleDescriptor& DisableStatementNoLabelsRule::GetDescriptor() { return d; } -static const Matcher& DisableMatcher() { +static const Matcher &DisableMatcher() { static const Matcher matcher( NodekDisableStatement(DisableStatementHasLabel())); return matcher; } void DisableStatementNoLabelsRule::HandleSymbol( - const verible::Symbol& symbol, const SyntaxTreeContext& context) { + const verible::Symbol &symbol, const SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (!DisableMatcher().Matches(symbol, &manager)) { return; } absl::string_view message_final = kMessage; // if no kDisable label, return, nothing to be checked - const auto& disableLabels = FindAllSymbolIdentifierLeafs(symbol); + const auto &disableLabels = FindAllSymbolIdentifierLeafs(symbol); if (disableLabels.empty()) { return; } @@ -85,30 +85,30 @@ void DisableStatementNoLabelsRule::HandleSymbol( // considered to be invalid. If the label for disable statements is not // found, it means that there is no appropriate label or the label // points to the illegal node such as forked label - const auto& rcontext = reversed_view(context); + const auto &rcontext = reversed_view(context); for (auto rc = rcontext.begin(); rc != rcontext.end(); rc++) { - const auto& node = *rc; + const auto &node = *rc; if (node->Tag().tag != static_cast(NodeEnum::kSeqBlock)) { continue; } - for (const auto& ch : node->children()) { + for (const auto &ch : node->children()) { if (ch->Tag().tag != static_cast(NodeEnum::kBegin)) { continue; } - const auto& beginLabels = FindAllSymbolIdentifierLeafs(*ch); + const auto &beginLabels = FindAllSymbolIdentifierLeafs(*ch); if (beginLabels.empty()) { continue; } - const auto& pnode = *std::next(rc); - const auto& ptag = pnode->Tag().tag; + const auto &pnode = *std::next(rc); + const auto &ptag = pnode->Tag().tag; if (ptag == static_cast(NodeEnum::kInitialStatement) || ptag == static_cast(NodeEnum::kFinalStatement) || ptag == static_cast(NodeEnum::kAlwaysStatement)) { message_final = kMessageSeqBlock; break; } - const auto& beginLabel = SymbolCastToLeaf(*beginLabels[0].match); - const auto& disableLabel = SymbolCastToLeaf(*disableLabels[0].match); + const auto &beginLabel = SymbolCastToLeaf(*beginLabels[0].match); + const auto &disableLabel = SymbolCastToLeaf(*disableLabels[0].match); if (beginLabel.get().text() == disableLabel.get().text()) { return; } diff --git a/verilog/analysis/checkers/disable_statement_rule.h b/verilog/analysis/checkers/disable_statement_rule.h index 062b9820f..69328fd7b 100644 --- a/verilog/analysis/checkers/disable_statement_rule.h +++ b/verilog/analysis/checkers/disable_statement_rule.h @@ -32,10 +32,10 @@ class DisableStatementNoLabelsRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/endif_comment_rule.cc b/verilog/analysis/checkers/endif_comment_rule.cc index 5ae757a98..d307f5678 100644 --- a/verilog/analysis/checkers/endif_comment_rule.cc +++ b/verilog/analysis/checkers/endif_comment_rule.cc @@ -45,7 +45,7 @@ static constexpr absl::string_view kMessage = "`endif should be followed on the same line by a comment that matches the " "opening `ifdef/`ifndef."; -const LintRuleDescriptor& EndifCommentRule::GetDescriptor() { +const LintRuleDescriptor &EndifCommentRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "endif-comment", .topic = "endif-comment", @@ -57,7 +57,7 @@ const LintRuleDescriptor& EndifCommentRule::GetDescriptor() { return d; } -void EndifCommentRule::HandleToken(const TokenInfo& token) { +void EndifCommentRule::HandleToken(const TokenInfo &token) { // Responds to a token by updating the state of the analysis. switch (state_) { case State::kNormal: { diff --git a/verilog/analysis/checkers/endif_comment_rule.h b/verilog/analysis/checkers/endif_comment_rule.h index 10f08b55c..bee2c2401 100644 --- a/verilog/analysis/checkers/endif_comment_rule.h +++ b/verilog/analysis/checkers/endif_comment_rule.h @@ -48,11 +48,11 @@ class EndifCommentRule : public verible::TokenStreamLintRule { public: using rule_type = verible::TokenStreamLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); EndifCommentRule() = default; - void HandleToken(const verible::TokenInfo& token) final; + void HandleToken(const verible::TokenInfo &token) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/explicit_function_lifetime_rule.cc b/verilog/analysis/checkers/explicit_function_lifetime_rule.cc index 20d66d181..c2d733787 100644 --- a/verilog/analysis/checkers/explicit_function_lifetime_rule.cc +++ b/verilog/analysis/checkers/explicit_function_lifetime_rule.cc @@ -45,7 +45,7 @@ VERILOG_REGISTER_LINT_RULE(ExplicitFunctionLifetimeRule); static constexpr absl::string_view kMessage = "Explicitly define static or automatic lifetime for non-class functions"; -const LintRuleDescriptor& ExplicitFunctionLifetimeRule::GetDescriptor() { +const LintRuleDescriptor &ExplicitFunctionLifetimeRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "explicit-function-lifetime", .topic = "function-task-explicit-lifetime", @@ -56,13 +56,13 @@ const LintRuleDescriptor& ExplicitFunctionLifetimeRule::GetDescriptor() { return d; } -static const Matcher& FunctionMatcher() { +static const Matcher &FunctionMatcher() { static const Matcher matcher(NodekFunctionDeclaration()); return matcher; } void ExplicitFunctionLifetimeRule::HandleSymbol( - const verible::Symbol& symbol, const SyntaxTreeContext& context) { + const verible::Symbol &symbol, const SyntaxTreeContext &context) { // Don't need to check for lifetime declaration if context is inside a class if (ContextIsInsideClass(context)) return; @@ -70,7 +70,7 @@ void ExplicitFunctionLifetimeRule::HandleSymbol( if (FunctionMatcher().Matches(symbol, &manager)) { // If function id is qualified, it is an out-of-line // class method definition, which is also exempt. - const auto* function_id = ABSL_DIE_IF_NULL(GetFunctionId(symbol)); + const auto *function_id = ABSL_DIE_IF_NULL(GetFunctionId(symbol)); if (IdIsQualified(*function_id)) return; // Make sure the lifetime was set diff --git a/verilog/analysis/checkers/explicit_function_lifetime_rule.h b/verilog/analysis/checkers/explicit_function_lifetime_rule.h index 416e59107..168b6a074 100644 --- a/verilog/analysis/checkers/explicit_function_lifetime_rule.h +++ b/verilog/analysis/checkers/explicit_function_lifetime_rule.h @@ -33,10 +33,10 @@ class ExplicitFunctionLifetimeRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/explicit_function_task_parameter_type_rule.cc b/verilog/analysis/checkers/explicit_function_task_parameter_type_rule.cc index ca215c1cb..27251c90b 100644 --- a/verilog/analysis/checkers/explicit_function_task_parameter_type_rule.cc +++ b/verilog/analysis/checkers/explicit_function_task_parameter_type_rule.cc @@ -45,7 +45,7 @@ VERILOG_REGISTER_LINT_RULE(ExplicitFunctionTaskParameterTypeRule); static constexpr absl::string_view kMessage = "Explicitly define a storage type for every function parameter."; -const LintRuleDescriptor& +const LintRuleDescriptor & ExplicitFunctionTaskParameterTypeRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "explicit-function-task-parameter-type", @@ -57,18 +57,18 @@ ExplicitFunctionTaskParameterTypeRule::GetDescriptor() { return d; } -static const Matcher& PortMatcher() { +static const Matcher &PortMatcher() { static const Matcher matcher(NodekPortItem()); return matcher; } void ExplicitFunctionTaskParameterTypeRule::HandleSymbol( - const verible::Symbol& symbol, const SyntaxTreeContext& context) { + const verible::Symbol &symbol, const SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (PortMatcher().Matches(symbol, &manager)) { - const auto* type_node = GetTypeOfTaskFunctionPortItem(symbol); + const auto *type_node = GetTypeOfTaskFunctionPortItem(symbol); if (!IsStorageTypeOfDataTypeSpecified(*ABSL_DIE_IF_NULL(type_node))) { - const auto* port_id = GetIdentifierFromTaskFunctionPortItem(symbol); + const auto *port_id = GetIdentifierFromTaskFunctionPortItem(symbol); violations_.insert(LintViolation(*port_id, kMessage, context)); } } diff --git a/verilog/analysis/checkers/explicit_function_task_parameter_type_rule.h b/verilog/analysis/checkers/explicit_function_task_parameter_type_rule.h index b288a77cf..44f2cd92c 100644 --- a/verilog/analysis/checkers/explicit_function_task_parameter_type_rule.h +++ b/verilog/analysis/checkers/explicit_function_task_parameter_type_rule.h @@ -34,10 +34,10 @@ class ExplicitFunctionTaskParameterTypeRule public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/explicit_parameter_storage_type_rule.cc b/verilog/analysis/checkers/explicit_parameter_storage_type_rule.cc index c9c9513f5..3998cf024 100644 --- a/verilog/analysis/checkers/explicit_parameter_storage_type_rule.cc +++ b/verilog/analysis/checkers/explicit_parameter_storage_type_rule.cc @@ -45,7 +45,7 @@ VERILOG_REGISTER_LINT_RULE(ExplicitParameterStorageTypeRule); static constexpr absl::string_view kMessage = "Explicitly define a storage type for every parameter and localparam, "; -const LintRuleDescriptor& ExplicitParameterStorageTypeRule::GetDescriptor() { +const LintRuleDescriptor &ExplicitParameterStorageTypeRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "explicit-parameter-storage-type", .topic = "constants", @@ -57,13 +57,13 @@ const LintRuleDescriptor& ExplicitParameterStorageTypeRule::GetDescriptor() { return d; } -static const Matcher& ParamMatcher() { +static const Matcher &ParamMatcher() { static const Matcher matcher(NodekParamDeclaration()); return matcher; } -static bool HasStringAssignment(const verible::Symbol& param_decl) { - const auto* s = GetParamAssignExpression(param_decl); +static bool HasStringAssignment(const verible::Symbol ¶m_decl) { + const auto *s = GetParamAssignExpression(param_decl); if (s == nullptr) return false; // We can't really do expression evaluation and determine the type of the // RHS, so here we focus on the simple case in which the RHS is a @@ -74,16 +74,16 @@ static bool HasStringAssignment(const verible::Symbol& param_decl) { } void ExplicitParameterStorageTypeRule::HandleSymbol( - const verible::Symbol& symbol, const SyntaxTreeContext& context) { + const verible::Symbol &symbol, const SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (ParamMatcher().Matches(symbol, &manager)) { // 'parameter type' declarations have a storage type declared. if (IsParamTypeDeclaration(symbol)) return; - const auto* type_info_symbol = GetParamTypeInfoSymbol(symbol); + const auto *type_info_symbol = GetParamTypeInfoSymbol(symbol); if (IsTypeInfoEmpty(*ABSL_DIE_IF_NULL(type_info_symbol))) { if (exempt_string_ && HasStringAssignment(symbol)) return; - const verible::TokenInfo* param_name = GetParameterNameToken(symbol); + const verible::TokenInfo *param_name = GetParameterNameToken(symbol); violations_.insert(LintViolation( *param_name, absl::StrCat(kMessage, "(", param_name->text(), ")."), context)); diff --git a/verilog/analysis/checkers/explicit_parameter_storage_type_rule.h b/verilog/analysis/checkers/explicit_parameter_storage_type_rule.h index 15ef5f9e8..b708f039c 100644 --- a/verilog/analysis/checkers/explicit_parameter_storage_type_rule.h +++ b/verilog/analysis/checkers/explicit_parameter_storage_type_rule.h @@ -33,10 +33,10 @@ class ExplicitParameterStorageTypeRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/explicit_task_lifetime_rule.cc b/verilog/analysis/checkers/explicit_task_lifetime_rule.cc index 5ec2fdeba..416150d7a 100644 --- a/verilog/analysis/checkers/explicit_task_lifetime_rule.cc +++ b/verilog/analysis/checkers/explicit_task_lifetime_rule.cc @@ -45,7 +45,7 @@ VERILOG_REGISTER_LINT_RULE(ExplicitTaskLifetimeRule); static constexpr absl::string_view kMessage = "Explicitly define static or automatic lifetime for non-class tasks"; -const LintRuleDescriptor& ExplicitTaskLifetimeRule::GetDescriptor() { +const LintRuleDescriptor &ExplicitTaskLifetimeRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "explicit-task-lifetime", .topic = "function-task-explicit-lifetime", @@ -56,13 +56,13 @@ const LintRuleDescriptor& ExplicitTaskLifetimeRule::GetDescriptor() { return d; } -static const Matcher& TaskMatcher() { +static const Matcher &TaskMatcher() { static const Matcher matcher(NodekTaskDeclaration()); return matcher; } -void ExplicitTaskLifetimeRule::HandleSymbol(const verible::Symbol& symbol, - const SyntaxTreeContext& context) { +void ExplicitTaskLifetimeRule::HandleSymbol(const verible::Symbol &symbol, + const SyntaxTreeContext &context) { // Don't need to check for lifetime declaration if context is inside a class if (ContextIsInsideClass(context)) return; @@ -70,7 +70,7 @@ void ExplicitTaskLifetimeRule::HandleSymbol(const verible::Symbol& symbol, if (TaskMatcher().Matches(symbol, &manager)) { // If task id is qualified, it is an out-of-line // class task definition, which is also exempt. - const auto* task_id = GetTaskId(symbol); + const auto *task_id = GetTaskId(symbol); if (IdIsQualified(*task_id)) return; // Make sure the lifetime was set diff --git a/verilog/analysis/checkers/explicit_task_lifetime_rule.h b/verilog/analysis/checkers/explicit_task_lifetime_rule.h index 796fd6d09..15c11dd78 100644 --- a/verilog/analysis/checkers/explicit_task_lifetime_rule.h +++ b/verilog/analysis/checkers/explicit_task_lifetime_rule.h @@ -36,10 +36,10 @@ class ExplicitTaskLifetimeRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/forbid_consecutive_null_statements_rule.cc b/verilog/analysis/checkers/forbid_consecutive_null_statements_rule.cc index c4d3db315..aa4d7bd97 100644 --- a/verilog/analysis/checkers/forbid_consecutive_null_statements_rule.cc +++ b/verilog/analysis/checkers/forbid_consecutive_null_statements_rule.cc @@ -40,7 +40,7 @@ VERILOG_REGISTER_LINT_RULE(ForbidConsecutiveNullStatementsRule); static constexpr absl::string_view kMessage = "Do not use consecutive null statements like \';;\'."; -const LintRuleDescriptor& ForbidConsecutiveNullStatementsRule::GetDescriptor() { +const LintRuleDescriptor &ForbidConsecutiveNullStatementsRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "forbid-consecutive-null-statements", .topic = "redundant-semicolons", @@ -52,7 +52,7 @@ const LintRuleDescriptor& ForbidConsecutiveNullStatementsRule::GetDescriptor() { } void ForbidConsecutiveNullStatementsRule::HandleLeaf( - const verible::SyntaxTreeLeaf& leaf, const SyntaxTreeContext& context) { + const verible::SyntaxTreeLeaf &leaf, const SyntaxTreeContext &context) { if (context.IsInside(NodeEnum::kForSpec)) { // for loops are allowed to be: for (;;) state_ = State::kNormal; diff --git a/verilog/analysis/checkers/forbid_consecutive_null_statements_rule.h b/verilog/analysis/checkers/forbid_consecutive_null_statements_rule.h index 42eee8bca..d04e3816f 100644 --- a/verilog/analysis/checkers/forbid_consecutive_null_statements_rule.h +++ b/verilog/analysis/checkers/forbid_consecutive_null_statements_rule.h @@ -38,10 +38,10 @@ class ForbidConsecutiveNullStatementsRule : public verible::SyntaxTreeLintRule { ForbidConsecutiveNullStatementsRule() = default; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleLeaf(const verible::SyntaxTreeLeaf& leaf, - const verible::SyntaxTreeContext& context) final; + void HandleLeaf(const verible::SyntaxTreeLeaf &leaf, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/forbid_defparam_rule.cc b/verilog/analysis/checkers/forbid_defparam_rule.cc index 83b21262f..68a8e3701 100644 --- a/verilog/analysis/checkers/forbid_defparam_rule.cc +++ b/verilog/analysis/checkers/forbid_defparam_rule.cc @@ -37,7 +37,7 @@ VERILOG_REGISTER_LINT_RULE(ForbidDefparamRule); static constexpr absl::string_view kMessage = "Do not use defparam."; -const LintRuleDescriptor& ForbidDefparamRule::GetDescriptor() { +const LintRuleDescriptor &ForbidDefparamRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "forbid-defparam", .topic = "module-instantiation", @@ -47,19 +47,19 @@ const LintRuleDescriptor& ForbidDefparamRule::GetDescriptor() { } // Matches the defparam construct. -static const Matcher& OverrideMatcher() { +static const Matcher &OverrideMatcher() { static const Matcher matcher(NodekParameterOverride()); return matcher; } void ForbidDefparamRule::HandleSymbol( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) { + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (OverrideMatcher().Matches(symbol, &manager)) { - const verible::SyntaxTreeLeaf* defparam = + const verible::SyntaxTreeLeaf *defparam = GetSubtreeAsLeaf(symbol, NodeEnum::kParameterOverride, 0); if (defparam) { - const auto& defparam_token = defparam->get(); + const auto &defparam_token = defparam->get(); CHECK_EQ(defparam_token.token_enum(), TK_defparam); violations_.insert( verible::LintViolation(defparam_token, kMessage, context)); diff --git a/verilog/analysis/checkers/forbid_defparam_rule.h b/verilog/analysis/checkers/forbid_defparam_rule.h index 1af913cd2..ab3144d85 100644 --- a/verilog/analysis/checkers/forbid_defparam_rule.h +++ b/verilog/analysis/checkers/forbid_defparam_rule.h @@ -33,10 +33,10 @@ class ForbidDefparamRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/forbid_negative_array_dim.cc b/verilog/analysis/checkers/forbid_negative_array_dim.cc index 2cc1e5466..6d4ca4ee8 100644 --- a/verilog/analysis/checkers/forbid_negative_array_dim.cc +++ b/verilog/analysis/checkers/forbid_negative_array_dim.cc @@ -44,7 +44,7 @@ VERILOG_REGISTER_LINT_RULE(ForbidNegativeArrayDim); static constexpr absl::string_view kMessage = "Avoid using negative constant literals for array dimensions."; -const LintRuleDescriptor& ForbidNegativeArrayDim::GetDescriptor() { +const LintRuleDescriptor &ForbidNegativeArrayDim::GetDescriptor() { static const LintRuleDescriptor d{ .name = "forbid-negative-array-dim", .topic = "forbid-negative-array-dim", @@ -54,13 +54,13 @@ const LintRuleDescriptor& ForbidNegativeArrayDim::GetDescriptor() { } // Matches the begin node. -static const Matcher& UnaryPrefixExprMatcher() { +static const Matcher &UnaryPrefixExprMatcher() { static const Matcher matcher(NodekUnaryPrefixExpression()); return matcher; } void ForbidNegativeArrayDim::HandleSymbol( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) { + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context) { // This only works for simple unary expressions. They can't be nested inside // other expressions. This avoids false positives of the form: // logic l [10+(-5):0], logic l[-(-5):0] @@ -75,9 +75,9 @@ void ForbidNegativeArrayDim::HandleSymbol( // As we've previously ensured that this symbol is a kUnaryPrefixExpression // both its operator and operand are defined - const verible::TokenInfo* u_operator = + const verible::TokenInfo *u_operator = verilog::GetUnaryPrefixOperator(symbol); - const verible::Symbol* operand = verilog::GetUnaryPrefixOperand(symbol); + const verible::Symbol *operand = verilog::GetUnaryPrefixOperand(symbol); int value = 0; const bool is_constant = verilog::ConstantIntegerValue(*operand, &value); diff --git a/verilog/analysis/checkers/forbid_negative_array_dim.h b/verilog/analysis/checkers/forbid_negative_array_dim.h index 5bc505713..a15077830 100644 --- a/verilog/analysis/checkers/forbid_negative_array_dim.h +++ b/verilog/analysis/checkers/forbid_negative_array_dim.h @@ -40,10 +40,10 @@ class ForbidNegativeArrayDim : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/forbidden_anonymous_enums_rule.cc b/verilog/analysis/checkers/forbidden_anonymous_enums_rule.cc index 22ab6d008..373c2e7ff 100644 --- a/verilog/analysis/checkers/forbidden_anonymous_enums_rule.cc +++ b/verilog/analysis/checkers/forbidden_anonymous_enums_rule.cc @@ -40,7 +40,7 @@ VERILOG_REGISTER_LINT_RULE(ForbiddenAnonymousEnumsRule); static constexpr absl::string_view kMessage = "enum types always should be named using typedef."; -const LintRuleDescriptor& ForbiddenAnonymousEnumsRule::GetDescriptor() { +const LintRuleDescriptor &ForbiddenAnonymousEnumsRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "typedef-enums", .topic = "typedef-enums", @@ -51,13 +51,13 @@ const LintRuleDescriptor& ForbiddenAnonymousEnumsRule::GetDescriptor() { return d; } -static const Matcher& EnumMatcher() { +static const Matcher &EnumMatcher() { static const Matcher matcher(NodekEnumType()); return matcher; } void ForbiddenAnonymousEnumsRule::HandleSymbol( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) { + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (EnumMatcher().Matches(symbol, &manager)) { // Check if it is preceded by a typedef diff --git a/verilog/analysis/checkers/forbidden_anonymous_enums_rule.h b/verilog/analysis/checkers/forbidden_anonymous_enums_rule.h index 7113e2a1c..fe3f29335 100644 --- a/verilog/analysis/checkers/forbidden_anonymous_enums_rule.h +++ b/verilog/analysis/checkers/forbidden_anonymous_enums_rule.h @@ -46,10 +46,10 @@ class ForbiddenAnonymousEnumsRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/forbidden_anonymous_structs_unions_rule.cc b/verilog/analysis/checkers/forbidden_anonymous_structs_unions_rule.cc index 63f12a253..c82d618e2 100644 --- a/verilog/analysis/checkers/forbidden_anonymous_structs_unions_rule.cc +++ b/verilog/analysis/checkers/forbidden_anonymous_structs_unions_rule.cc @@ -44,7 +44,7 @@ static constexpr absl::string_view kMessageStruct = static constexpr absl::string_view kMessageUnion = "union definitions always should be named using typedef."; -const LintRuleDescriptor& ForbiddenAnonymousStructsUnionsRule::GetDescriptor() { +const LintRuleDescriptor &ForbiddenAnonymousStructsUnionsRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "typedef-structs-unions", .topic = "typedef-structs-unions", @@ -65,34 +65,34 @@ absl::Status ForbiddenAnonymousStructsUnionsRule::Configure( {{"allow_anonymous_nested", SetBool(&allow_anonymous_nested_type_)}}); } -static const Matcher& StructMatcher() { +static const Matcher &StructMatcher() { static const Matcher matcher(NodekStructType()); return matcher; } -static const Matcher& UnionMatcher() { +static const Matcher &UnionMatcher() { static const Matcher matcher(NodekUnionType()); return matcher; } -static bool IsPreceededByTypedef(const verible::SyntaxTreeContext& context) { +static bool IsPreceededByTypedef(const verible::SyntaxTreeContext &context) { return context.DirectParentsAre({NodeEnum::kDataTypePrimitive, NodeEnum::kDataType, NodeEnum::kTypeDeclaration}); } -static bool NestedInStructOrUnion(const verible::SyntaxTreeContext& context) { +static bool NestedInStructOrUnion(const verible::SyntaxTreeContext &context) { return context.IsInsideStartingFrom(NodeEnum::kDataTypePrimitive, 1); } bool ForbiddenAnonymousStructsUnionsRule::IsRuleMet( - const verible::SyntaxTreeContext& context) const { + const verible::SyntaxTreeContext &context) const { return IsPreceededByTypedef(context) || (allow_anonymous_nested_type_ && NestedInStructOrUnion(context)); } void ForbiddenAnonymousStructsUnionsRule::HandleSymbol( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) { + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (StructMatcher().Matches(symbol, &manager) && !IsRuleMet(context)) { violations_.insert(LintViolation(symbol, kMessageStruct, context)); diff --git a/verilog/analysis/checkers/forbidden_anonymous_structs_unions_rule.h b/verilog/analysis/checkers/forbidden_anonymous_structs_unions_rule.h index 36a22f96e..bbc701591 100644 --- a/verilog/analysis/checkers/forbidden_anonymous_structs_unions_rule.h +++ b/verilog/analysis/checkers/forbidden_anonymous_structs_unions_rule.h @@ -55,18 +55,18 @@ class ForbiddenAnonymousStructsUnionsRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); absl::Status Configure(absl::string_view configuration) final; - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; private: // Tests if the rule is met, taking waiving condition into account. - bool IsRuleMet(const verible::SyntaxTreeContext& context) const; + bool IsRuleMet(const verible::SyntaxTreeContext &context) const; bool allow_anonymous_nested_type_ = false; diff --git a/verilog/analysis/checkers/forbidden_macro_rule.cc b/verilog/analysis/checkers/forbidden_macro_rule.cc index 47337a7ea..40ac0ca8c 100644 --- a/verilog/analysis/checkers/forbidden_macro_rule.cc +++ b/verilog/analysis/checkers/forbidden_macro_rule.cc @@ -44,7 +44,7 @@ using verible::matcher::Matcher; VERILOG_REGISTER_LINT_RULE(ForbiddenMacroRule); // TODO(fangism): Generate table of URLs from InvalidMacrosMap(). -const LintRuleDescriptor& ForbiddenMacroRule::GetDescriptor() { +const LintRuleDescriptor &ForbiddenMacroRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "forbidden-macro", .topic = "uvm-logging", @@ -54,27 +54,27 @@ const LintRuleDescriptor& ForbiddenMacroRule::GetDescriptor() { } // Matches all macro call ids, like `foo. -static const Matcher& MacroCallMatcher() { +static const Matcher &MacroCallMatcher() { static const Matcher matcher(MacroCallIdLeaf().Bind("name")); return matcher; } // Set of invalid macros and URLs -const std::map& -ForbiddenMacroRule::InvalidMacrosMap() { +const std::map + &ForbiddenMacroRule::InvalidMacrosMap() { // TODO(hzeller): don't use GetStyleGuideCitation here, more downstream. - static const auto* invalid_symbols = new std::map({ + static const auto *invalid_symbols = new std::map({ {"`uvm_warning", GetStyleGuideCitation("uvm-logging")}, }); return *invalid_symbols; } void ForbiddenMacroRule::HandleSymbol( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) { + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (MacroCallMatcher().Matches(symbol, &manager)) { - if (const auto* leaf = manager.GetAs("name")) { - const auto& imm = InvalidMacrosMap(); + if (const auto *leaf = manager.GetAs("name")) { + const auto &imm = InvalidMacrosMap(); if (imm.find(std::string(leaf->get().text())) != imm.end()) { violations_.insert( verible::LintViolation(leaf->get(), FormatReason(*leaf), context)); @@ -90,7 +90,7 @@ verible::LintRuleStatus ForbiddenMacroRule::Report() const { } /* static */ std::string ForbiddenMacroRule::FormatReason( - const verible::SyntaxTreeLeaf& leaf) { + const verible::SyntaxTreeLeaf &leaf) { const std::string function_name(leaf.get().text()); const auto url = FindWithDefault(InvalidMacrosMap(), function_name, ""); auto message = function_name + " is a forbidden macro"; diff --git a/verilog/analysis/checkers/forbidden_macro_rule.h b/verilog/analysis/checkers/forbidden_macro_rule.h index 805a7cc76..bbe684622 100644 --- a/verilog/analysis/checkers/forbidden_macro_rule.h +++ b/verilog/analysis/checkers/forbidden_macro_rule.h @@ -42,18 +42,18 @@ class ForbiddenMacroRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; private: - static std::string FormatReason(const verible::SyntaxTreeLeaf& leaf); + static std::string FormatReason(const verible::SyntaxTreeLeaf &leaf); // Set of invalid macros, mapped to style guide links. - static const std::map& InvalidMacrosMap(); + static const std::map &InvalidMacrosMap(); private: std::set violations_; diff --git a/verilog/analysis/checkers/forbidden_symbol_rule.cc b/verilog/analysis/checkers/forbidden_symbol_rule.cc index 4bf6d2a21..47efc1969 100644 --- a/verilog/analysis/checkers/forbidden_symbol_rule.cc +++ b/verilog/analysis/checkers/forbidden_symbol_rule.cc @@ -41,7 +41,7 @@ using verible::matcher::Matcher; // Register ForbiddenSystemTaskFunctionRule VERILOG_REGISTER_LINT_RULE(ForbiddenSystemTaskFunctionRule); -const LintRuleDescriptor& ForbiddenSystemTaskFunctionRule::GetDescriptor() { +const LintRuleDescriptor &ForbiddenSystemTaskFunctionRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "invalid-system-task-function", .topic = "forbidden-system-functions", @@ -53,15 +53,15 @@ const LintRuleDescriptor& ForbiddenSystemTaskFunctionRule::GetDescriptor() { return d; } -static const Matcher& IdMatcher() { +static const Matcher &IdMatcher() { static const Matcher matcher(SystemTFIdentifierLeaf().Bind("name")); return matcher; } // Set of invalid functions and suggested replacements -const std::map& -ForbiddenSystemTaskFunctionRule::InvalidSymbolsMap() { - static const auto* invalid_symbols = new std::map({ +const std::map + &ForbiddenSystemTaskFunctionRule::InvalidSymbolsMap() { + static const auto *invalid_symbols = new std::map({ {"$psprintf", "$sformatf"}, {"$random", "$urandom"}, {"$srandom", "process::self().srandom()"}, @@ -78,11 +78,11 @@ ForbiddenSystemTaskFunctionRule::InvalidSymbolsMap() { } void ForbiddenSystemTaskFunctionRule::HandleSymbol( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) { + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (IdMatcher().Matches(symbol, &manager)) { - if (const auto* leaf = manager.GetAs("name")) { - const auto& ism = InvalidSymbolsMap(); + if (const auto *leaf = manager.GetAs("name")) { + const auto &ism = InvalidSymbolsMap(); if (ism.find(std::string(leaf->get().text())) != ism.end()) { violations_.insert( verible::LintViolation(leaf->get(), FormatReason(*leaf), context)); @@ -96,7 +96,7 @@ verible::LintRuleStatus ForbiddenSystemTaskFunctionRule::Report() const { } /* static */ std::string ForbiddenSystemTaskFunctionRule::FormatReason( - const verible::SyntaxTreeLeaf& leaf) { + const verible::SyntaxTreeLeaf &leaf) { const auto function_name = std::string(leaf.get().text()); const auto replacement = FindWithDefault(InvalidSymbolsMap(), function_name, ""); diff --git a/verilog/analysis/checkers/forbidden_symbol_rule.h b/verilog/analysis/checkers/forbidden_symbol_rule.h index b00e60893..f4bd2b642 100644 --- a/verilog/analysis/checkers/forbidden_symbol_rule.h +++ b/verilog/analysis/checkers/forbidden_symbol_rule.h @@ -42,18 +42,18 @@ class ForbiddenSystemTaskFunctionRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; private: - static std::string FormatReason(const verible::SyntaxTreeLeaf& leaf); + static std::string FormatReason(const verible::SyntaxTreeLeaf &leaf); // Set of invalid functions and suggested replacements - static const std::map& InvalidSymbolsMap(); + static const std::map &InvalidSymbolsMap(); private: std::set violations_; diff --git a/verilog/analysis/checkers/generate_label_prefix_rule.cc b/verilog/analysis/checkers/generate_label_prefix_rule.cc index ded9b82c0..54be44a80 100644 --- a/verilog/analysis/checkers/generate_label_prefix_rule.cc +++ b/verilog/analysis/checkers/generate_label_prefix_rule.cc @@ -45,7 +45,7 @@ static constexpr absl::string_view kMessage = // TODO(fangism): generalize to a configurable pattern and // rename this class/rule to GenerateLabelNamingStyle? -const LintRuleDescriptor& GenerateLabelPrefixRule::GetDescriptor() { +const LintRuleDescriptor &GenerateLabelPrefixRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "generate-label-prefix", .topic = "generate-constructs", @@ -55,13 +55,13 @@ const LintRuleDescriptor& GenerateLabelPrefixRule::GetDescriptor() { } // Matches begin statements -static const Matcher& BlockMatcher() { +static const Matcher &BlockMatcher() { static const Matcher matcher(NodekGenerateBlock()); return matcher; } void GenerateLabelPrefixRule::HandleSymbol( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) { + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (BlockMatcher().Matches(symbol, &manager)) { // Exclude case generate statements, as kGenerateBlock is generated for @@ -70,8 +70,8 @@ void GenerateLabelPrefixRule::HandleSymbol( return; } - for (const auto& child : SymbolCastToNode(symbol).children()) { - const verible::TokenInfo* label = nullptr; + for (const auto &child : SymbolCastToNode(symbol).children()) { + const verible::TokenInfo *label = nullptr; switch (NodeEnum(SymbolCastToNode(*child).Tag().tag)) { case NodeEnum::kBegin: label = GetBeginLabelTokenInfo(*child); diff --git a/verilog/analysis/checkers/generate_label_prefix_rule.h b/verilog/analysis/checkers/generate_label_prefix_rule.h index 15e2d80c7..f9abf9f07 100644 --- a/verilog/analysis/checkers/generate_label_prefix_rule.h +++ b/verilog/analysis/checkers/generate_label_prefix_rule.h @@ -34,10 +34,10 @@ class GenerateLabelPrefixRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/generate_label_rule.cc b/verilog/analysis/checkers/generate_label_rule.cc index 8320cb54f..322a28887 100644 --- a/verilog/analysis/checkers/generate_label_rule.cc +++ b/verilog/analysis/checkers/generate_label_rule.cc @@ -39,7 +39,7 @@ VERILOG_REGISTER_LINT_RULE(GenerateLabelRule); static constexpr absl::string_view kMessage = "All generate block statements must have a label"; -const LintRuleDescriptor& GenerateLabelRule::GetDescriptor() { +const LintRuleDescriptor &GenerateLabelRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "generate-label", .topic = "generate-statements", @@ -55,14 +55,14 @@ const LintRuleDescriptor& GenerateLabelRule::GetDescriptor() { // always @(posedge clk) foo <= bar; // end // -static const Matcher& BlockMatcher() { +static const Matcher &BlockMatcher() { static const Matcher matcher( NodekGenerateBlock(verible::matcher::Unless(HasBeginLabel()))); return matcher; } void GenerateLabelRule::HandleSymbol( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) { + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (BlockMatcher().Matches(symbol, &manager)) { violations_.insert(verible::LintViolation(symbol, kMessage, context)); diff --git a/verilog/analysis/checkers/generate_label_rule.h b/verilog/analysis/checkers/generate_label_rule.h index 347495097..e30fcd368 100644 --- a/verilog/analysis/checkers/generate_label_rule.h +++ b/verilog/analysis/checkers/generate_label_rule.h @@ -44,10 +44,10 @@ class GenerateLabelRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/legacy_generate_region_rule.cc b/verilog/analysis/checkers/legacy_generate_region_rule.cc index f61224f02..474a92424 100644 --- a/verilog/analysis/checkers/legacy_generate_region_rule.cc +++ b/verilog/analysis/checkers/legacy_generate_region_rule.cc @@ -40,7 +40,7 @@ using verible::matcher::EqualTagPredicate; static constexpr absl::string_view kMessage = "Do not use generate regions."; -const LintRuleDescriptor& LegacyGenerateRegionRule::GetDescriptor() { +const LintRuleDescriptor &LegacyGenerateRegionRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "legacy-generate-region", .topic = "generate-constructs", @@ -50,14 +50,14 @@ const LintRuleDescriptor& LegacyGenerateRegionRule::GetDescriptor() { } void LegacyGenerateRegionRule::HandleNode( - const verible::SyntaxTreeNode& node, - const verible::SyntaxTreeContext& context) { + const verible::SyntaxTreeNode &node, + const verible::SyntaxTreeContext &context) { const auto tag = static_cast(node.Tag().tag); if (tag == NodeEnum::kGenerateRegion) { - const auto* generate_keyword = ABSL_DIE_IF_NULL(FindFirstSubtree( + const auto *generate_keyword = ABSL_DIE_IF_NULL(FindFirstSubtree( &node, EqualTagPredicate)); - const auto& leaf = verible::SymbolCastToLeaf(*generate_keyword); + const auto &leaf = verible::SymbolCastToLeaf(*generate_keyword); violations_.insert(LintViolation(leaf.get(), kMessage)); } } diff --git a/verilog/analysis/checkers/legacy_generate_region_rule.h b/verilog/analysis/checkers/legacy_generate_region_rule.h index d7e975765..620cd1cce 100644 --- a/verilog/analysis/checkers/legacy_generate_region_rule.h +++ b/verilog/analysis/checkers/legacy_generate_region_rule.h @@ -32,10 +32,10 @@ class LegacyGenerateRegionRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleNode(const verible::SyntaxTreeNode& node, - const verible::SyntaxTreeContext& context) final; + void HandleNode(const verible::SyntaxTreeNode &node, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/legacy_genvar_declaration_rule.cc b/verilog/analysis/checkers/legacy_genvar_declaration_rule.cc index 858fc1adc..a15f8671f 100644 --- a/verilog/analysis/checkers/legacy_genvar_declaration_rule.cc +++ b/verilog/analysis/checkers/legacy_genvar_declaration_rule.cc @@ -40,7 +40,7 @@ using verible::LintViolation; static constexpr absl::string_view kMessage = "Do not use separate genvar declaration."; -const LintRuleDescriptor& LegacyGenvarDeclarationRule::GetDescriptor() { +const LintRuleDescriptor &LegacyGenvarDeclarationRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "legacy-genvar-declaration", .topic = "generate-constructs", @@ -50,13 +50,13 @@ const LintRuleDescriptor& LegacyGenvarDeclarationRule::GetDescriptor() { } void LegacyGenvarDeclarationRule::HandleNode( - const verible::SyntaxTreeNode& node, - const verible::SyntaxTreeContext& context) { + const verible::SyntaxTreeNode &node, + const verible::SyntaxTreeContext &context) { const auto tag = static_cast(node.Tag().tag); if (tag == NodeEnum::kGenvarDeclaration) { const auto identifier_matches = FindAllSymbolIdentifierLeafs(node); - for (const auto& match : identifier_matches) { - const auto& leaf = verible::SymbolCastToLeaf(*match.match); + for (const auto &match : identifier_matches) { + const auto &leaf = verible::SymbolCastToLeaf(*match.match); violations_.insert(LintViolation(leaf.get(), kMessage)); } } diff --git a/verilog/analysis/checkers/legacy_genvar_declaration_rule.h b/verilog/analysis/checkers/legacy_genvar_declaration_rule.h index d8e7c5db4..062bb8faa 100644 --- a/verilog/analysis/checkers/legacy_genvar_declaration_rule.h +++ b/verilog/analysis/checkers/legacy_genvar_declaration_rule.h @@ -33,10 +33,10 @@ class LegacyGenvarDeclarationRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleNode(const verible::SyntaxTreeNode& node, - const verible::SyntaxTreeContext& context) final; + void HandleNode(const verible::SyntaxTreeNode &node, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/macro_name_style_rule.cc b/verilog/analysis/checkers/macro_name_style_rule.cc index a32f7f51b..abf21c255 100644 --- a/verilog/analysis/checkers/macro_name_style_rule.cc +++ b/verilog/analysis/checkers/macro_name_style_rule.cc @@ -44,7 +44,7 @@ static constexpr absl::string_view kMessage = "Macro names must contain only CAPITALS, underscores, and digits. " "Exception: UVM-like macros."; -const LintRuleDescriptor& MacroNameStyleRule::GetDescriptor() { +const LintRuleDescriptor &MacroNameStyleRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "macro-name-style", .topic = "defines", @@ -55,13 +55,13 @@ const LintRuleDescriptor& MacroNameStyleRule::GetDescriptor() { return d; } -void MacroNameStyleRule::HandleToken(const TokenInfo& token) { +void MacroNameStyleRule::HandleToken(const TokenInfo &token) { const auto token_enum = static_cast(token.token_enum()); const absl::string_view text(token.text()); if (IsUnlexed(verilog_tokentype(token.token_enum()))) { // recursively lex to examine inside macro definition bodies, etc. RecursiveLexText( - text, [this](const TokenInfo& subtoken) { HandleToken(subtoken); }); + text, [this](const TokenInfo &subtoken) { HandleToken(subtoken); }); return; } diff --git a/verilog/analysis/checkers/macro_name_style_rule.h b/verilog/analysis/checkers/macro_name_style_rule.h index 72895d6e6..2f59f0fb7 100644 --- a/verilog/analysis/checkers/macro_name_style_rule.h +++ b/verilog/analysis/checkers/macro_name_style_rule.h @@ -32,11 +32,11 @@ class MacroNameStyleRule : public verible::TokenStreamLintRule { public: using rule_type = verible::TokenStreamLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); MacroNameStyleRule() = default; - void HandleToken(const verible::TokenInfo& token) final; + void HandleToken(const verible::TokenInfo &token) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/macro_string_concatenation_rule.cc b/verilog/analysis/checkers/macro_string_concatenation_rule.cc index 88c6fe600..062b081d6 100644 --- a/verilog/analysis/checkers/macro_string_concatenation_rule.cc +++ b/verilog/analysis/checkers/macro_string_concatenation_rule.cc @@ -38,7 +38,7 @@ VERILOG_REGISTER_LINT_RULE(MacroStringConcatenationRule); static constexpr absl::string_view kMessage = "Token concatenation (``) used inside plain string literal."; -const LintRuleDescriptor& MacroStringConcatenationRule::GetDescriptor() { +const LintRuleDescriptor &MacroStringConcatenationRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "macro-string-concatenation", .topic = "defines", @@ -48,7 +48,7 @@ const LintRuleDescriptor& MacroStringConcatenationRule::GetDescriptor() { return d; } -void MacroStringConcatenationRule::HandleToken(const TokenInfo& token) { +void MacroStringConcatenationRule::HandleToken(const TokenInfo &token) { const auto token_enum = static_cast(token.token_enum()); const absl::string_view text(token.text()); @@ -57,7 +57,7 @@ void MacroStringConcatenationRule::HandleToken(const TokenInfo& token) { if (IsUnlexed(token_enum)) { verible::ValueSaver state_saver(&state_, State::kInsideDefineBody); RecursiveLexText( - text, [this](const TokenInfo& subtoken) { HandleToken(subtoken); }); + text, [this](const TokenInfo &subtoken) { HandleToken(subtoken); }); } } else if (state_ == State::kInsideDefineBody && token_enum == TK_StringLiteral) { diff --git a/verilog/analysis/checkers/macro_string_concatenation_rule.h b/verilog/analysis/checkers/macro_string_concatenation_rule.h index be3f7e39a..4d359c9c9 100644 --- a/verilog/analysis/checkers/macro_string_concatenation_rule.h +++ b/verilog/analysis/checkers/macro_string_concatenation_rule.h @@ -31,11 +31,11 @@ class MacroStringConcatenationRule : public verible::TokenStreamLintRule { public: using rule_type = verible::TokenStreamLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); MacroStringConcatenationRule() = default; - void HandleToken(const verible::TokenInfo& token) final; + void HandleToken(const verible::TokenInfo &token) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/mismatched_labels_rule.cc b/verilog/analysis/checkers/mismatched_labels_rule.cc index 75219fe85..94e2c0aba 100644 --- a/verilog/analysis/checkers/mismatched_labels_rule.cc +++ b/verilog/analysis/checkers/mismatched_labels_rule.cc @@ -45,7 +45,7 @@ static constexpr absl::string_view kMessageMismatch = static constexpr absl::string_view kMessageMissing = "Matching begin label is missing."; -const LintRuleDescriptor& MismatchedLabelsRule::GetDescriptor() { +const LintRuleDescriptor &MismatchedLabelsRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "mismatched-labels", .topic = "mismatched-labels", @@ -55,20 +55,20 @@ const LintRuleDescriptor& MismatchedLabelsRule::GetDescriptor() { } // Matches the begin node. -static const Matcher& BeginMatcher() { +static const Matcher &BeginMatcher() { static const Matcher matcher(NodekBegin()); return matcher; } void MismatchedLabelsRule::HandleSymbol( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) { + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (BeginMatcher().Matches(symbol, &manager)) { - const auto& matchingEnd = GetMatchingEnd(symbol, context); + const auto &matchingEnd = GetMatchingEnd(symbol, context); - const auto* begin_label = GetBeginLabelTokenInfo(symbol); - const auto* end_label = GetEndLabelTokenInfo(*matchingEnd); + const auto *begin_label = GetBeginLabelTokenInfo(symbol); + const auto *end_label = GetEndLabelTokenInfo(*matchingEnd); // Don't check anything if there is no end label if (end_label == nullptr) { diff --git a/verilog/analysis/checkers/mismatched_labels_rule.h b/verilog/analysis/checkers/mismatched_labels_rule.h index fa945d27f..f55b47826 100644 --- a/verilog/analysis/checkers/mismatched_labels_rule.h +++ b/verilog/analysis/checkers/mismatched_labels_rule.h @@ -34,10 +34,10 @@ class MismatchedLabelsRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/module_begin_block_rule.cc b/verilog/analysis/checkers/module_begin_block_rule.cc index 84c464965..ee42fe85a 100644 --- a/verilog/analysis/checkers/module_begin_block_rule.cc +++ b/verilog/analysis/checkers/module_begin_block_rule.cc @@ -38,7 +38,7 @@ VERILOG_REGISTER_LINT_RULE(ModuleBeginBlockRule); static constexpr absl::string_view kMessage = "Module-level begin-end blocks are not LRM-valid syntax."; -const LintRuleDescriptor& ModuleBeginBlockRule::GetDescriptor() { +const LintRuleDescriptor &ModuleBeginBlockRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "module-begin-block", .topic = "floating-begin-end-blocks", @@ -50,13 +50,13 @@ const LintRuleDescriptor& ModuleBeginBlockRule::GetDescriptor() { } // Matches begin-end blocks at the module-item level. -static const Matcher& BlockMatcher() { +static const Matcher &BlockMatcher() { static const Matcher matcher(NodekModuleBlock()); return matcher; } void ModuleBeginBlockRule::HandleSymbol( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) { + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (BlockMatcher().Matches(symbol, &manager)) { violations_.insert(verible::LintViolation(symbol, kMessage, context)); diff --git a/verilog/analysis/checkers/module_begin_block_rule.h b/verilog/analysis/checkers/module_begin_block_rule.h index e61020d07..d0e5abf42 100644 --- a/verilog/analysis/checkers/module_begin_block_rule.h +++ b/verilog/analysis/checkers/module_begin_block_rule.h @@ -40,10 +40,10 @@ class ModuleBeginBlockRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/module_filename_rule.cc b/verilog/analysis/checkers/module_filename_rule.cc index 8744347fe..ea7aa00ae 100644 --- a/verilog/analysis/checkers/module_filename_rule.cc +++ b/verilog/analysis/checkers/module_filename_rule.cc @@ -49,7 +49,7 @@ static constexpr absl::string_view kMessage = "Declared module does not match the first dot-delimited component " "of file name: "; -const LintRuleDescriptor& ModuleFilenameRule::GetDescriptor() { +const LintRuleDescriptor &ModuleFilenameRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "module-filename", .topic = "file-names", @@ -65,19 +65,19 @@ const LintRuleDescriptor& ModuleFilenameRule::GetDescriptor() { return d; } -static bool ModuleNameMatches(const verible::Symbol& s, +static bool ModuleNameMatches(const verible::Symbol &s, absl::string_view name) { - const auto* module_leaf = GetModuleName(s); + const auto *module_leaf = GetModuleName(s); return module_leaf && module_leaf->get().text() == name; } -void ModuleFilenameRule::Lint(const TextStructureView& text_structure, +void ModuleFilenameRule::Lint(const TextStructureView &text_structure, absl::string_view filename) { if (verible::file::IsStdin(filename)) { return; } - const auto& tree = text_structure.SyntaxTree(); + const auto &tree = text_structure.SyntaxTree(); if (tree == nullptr) return; // Find all module declarations. @@ -92,7 +92,7 @@ void ModuleFilenameRule::Lint(const TextStructureView& text_structure, std::back_insert_iterator> back_it( module_cleaned); std::remove_copy_if(module_matches.begin(), module_matches.end(), back_it, - [](verible::TreeSearchMatch& m) { + [](verible::TreeSearchMatch &m) { return m.context.IsInside(NodeEnum::kModuleDeclaration); }); @@ -112,14 +112,14 @@ void ModuleFilenameRule::Lint(const TextStructureView& text_structure, // If there is at least one module with a matching name, suppress finding. if (std::any_of(module_cleaned.begin(), module_cleaned.end(), - [=](const verible::TreeSearchMatch& m) { + [=](const verible::TreeSearchMatch &m) { return ModuleNameMatches(*m.match, unitname); })) { return; } // Only report a violation on the last module declaration. - const auto* last_module_id = GetModuleName(*module_cleaned.back().match); + const auto *last_module_id = GetModuleName(*module_cleaned.back().match); if (!last_module_id) LOG(ERROR) << "Couldn't extract module name"; if (last_module_id) { violations_.insert(verible::LintViolation( diff --git a/verilog/analysis/checkers/module_filename_rule.h b/verilog/analysis/checkers/module_filename_rule.h index 0ef3a9a04..9fa26bc13 100644 --- a/verilog/analysis/checkers/module_filename_rule.h +++ b/verilog/analysis/checkers/module_filename_rule.h @@ -32,12 +32,12 @@ class ModuleFilenameRule : public verible::TextStructureLintRule { public: using rule_type = verible::TextStructureLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); ModuleFilenameRule() = default; absl::Status Configure(absl::string_view configuration) final; - void Lint(const verible::TextStructureView&, absl::string_view) final; + void Lint(const verible::TextStructureView &, absl::string_view) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/module_instantiation_rules.cc b/verilog/analysis/checkers/module_instantiation_rules.cc index 49163d158..a4f32f3ef 100644 --- a/verilog/analysis/checkers/module_instantiation_rules.cc +++ b/verilog/analysis/checkers/module_instantiation_rules.cc @@ -47,7 +47,7 @@ using verible::matcher::Matcher; VERILOG_REGISTER_LINT_RULE(ModuleParameterRule); VERILOG_REGISTER_LINT_RULE(ModulePortRule); -const LintRuleDescriptor& ModuleParameterRule::GetDescriptor() { +const LintRuleDescriptor &ModuleParameterRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "module-parameter", .topic = "module-instantiation", @@ -59,7 +59,7 @@ const LintRuleDescriptor& ModuleParameterRule::GetDescriptor() { return d; } -const LintRuleDescriptor& ModulePortRule::GetDescriptor() { +const LintRuleDescriptor &ModulePortRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "module-port", .topic = "module-instantiation", @@ -75,7 +75,7 @@ const LintRuleDescriptor& ModulePortRule::GetDescriptor() { // For example: // foo bar (port1, port2); // Here, the node representing "port1, port2" will be bound to "list" -static const Matcher& InstanceMatcher() { +static const Matcher &InstanceMatcher() { static const Matcher matcher( NodekGateInstance(GateInstanceHasPortList().Bind("list"))); return matcher; @@ -85,23 +85,23 @@ static const Matcher& InstanceMatcher() { // For examples: // foo #(1, 2) bar; // Here, the node representing "1, 2" will be bound to "list". -static const Matcher& ParamsMatcher() { +static const Matcher &ParamsMatcher() { static const Matcher matcher(NodekActualParameterList( ActualParameterListHasPositionalParameterList().Bind("list"))); return matcher; } -static bool IsComma(const verible::Symbol& symbol) { +static bool IsComma(const verible::Symbol &symbol) { if (symbol.Kind() == verible::SymbolKind::kLeaf) { - const auto* leaf = down_cast(&symbol); + const auto *leaf = down_cast(&symbol); if (leaf) return leaf->get().token_enum() == ','; } return false; } -static bool IsAnyPort(const verible::Symbol* symbol) { +static bool IsAnyPort(const verible::Symbol *symbol) { if (symbol->Kind() == verible::SymbolKind::kNode) { - const auto* node = down_cast(symbol); + const auto *node = down_cast(symbol); return node->MatchesTag(NodeEnum::kActualNamedPort) || node->MatchesTag(NodeEnum::kActualPositionalPort); } @@ -113,7 +113,7 @@ static bool IsAnyPort(const verible::Symbol* symbol) { // void ModuleParameterRule::HandleSymbol( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) { + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context) { static constexpr absl::string_view kMessage = "Pass named parameters for parameterized module instantiations with " "more than one parameter"; @@ -125,16 +125,16 @@ void ModuleParameterRule::HandleSymbol( verible::matcher::BoundSymbolManager manager; if (ParamsMatcher().Matches(symbol, &manager)) { - if (const auto* list = manager.GetAs("list")) { - const auto& children = list->children(); + if (const auto *list = manager.GetAs("list")) { + const auto &children = list->children(); auto parameter_count = std::count_if( children.begin(), children.end(), - [](const verible::SymbolPtr& n) { return n ? !IsComma(*n) : false; }); + [](const verible::SymbolPtr &n) { return n ? !IsComma(*n) : false; }); // One positional parameter is permitted, but any more require all // parameters to be named. if (parameter_count > 1) { // Determine the spanning location - const auto* leaf_ptr = verible::GetLeftmostLeaf(*list); + const auto *leaf_ptr = verible::GetLeftmostLeaf(*list); const verible::TokenInfo token = ABSL_DIE_IF_NULL(leaf_ptr)->get(); violations_.insert(verible::LintViolation(token, kMessage, context)); } @@ -150,8 +150,8 @@ verible::LintRuleStatus ModuleParameterRule::Report() const { // ModulePortRule Implementation // -void ModulePortRule::HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) { +void ModulePortRule::HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) { static constexpr absl::string_view kMessage = "Use named ports for module instantiation with " "more than one port"; @@ -159,14 +159,14 @@ void ModulePortRule::HandleSymbol(const verible::Symbol& symbol, verible::matcher::BoundSymbolManager manager; if (InstanceMatcher().Matches(symbol, &manager)) { - if (const auto* port_list_node = + if (const auto *port_list_node = manager.GetAs("list")) { // Don't know how to handle unexpected non-portlist, so proceed if (!port_list_node->MatchesTag(NodeEnum::kPortActualList)) return; if (!IsPortListCompliant(*port_list_node)) { // Determine the leftmost location - const auto* leaf_ptr = verible::GetLeftmostLeaf(*port_list_node); + const auto *leaf_ptr = verible::GetLeftmostLeaf(*port_list_node); const verible::TokenInfo token = ABSL_DIE_IF_NULL(leaf_ptr)->get(); violations_.insert(verible::LintViolation(token, kMessage, context)); } @@ -180,24 +180,24 @@ void ModulePortRule::HandleSymbol(const verible::Symbol& symbol, // Returns false if node has 2 or more children and at least // one child is an unnamed positional port /* static */ bool ModulePortRule::IsPortListCompliant( - const verible::SyntaxTreeNode& port_list_node) { - const auto& children = port_list_node.children(); + const verible::SyntaxTreeNode &port_list_node) { + const auto &children = port_list_node.children(); auto port_count = std::count_if( children.begin(), children.end(), - [](const verible::SymbolPtr& n) { return IsAnyPort(n.get()); }); + [](const verible::SymbolPtr &n) { return IsAnyPort(n.get()); }); // Do not enforce rule if node has 0 or 1 ports if (port_count <= 1) { return true; } - for (const auto& child : port_list_node.children()) { + for (const auto &child : port_list_node.children()) { if (child == nullptr) continue; // If child is a node, then it must be a kPort if (child->Kind() == verible::SymbolKind::kNode) { - const auto* child_node = - down_cast(child.get()); + const auto *child_node = + down_cast(child.get()); if (child_node->MatchesTag(NodeEnum::kActualPositionalPort)) return false; } } diff --git a/verilog/analysis/checkers/module_instantiation_rules.h b/verilog/analysis/checkers/module_instantiation_rules.h index 177c0c86f..dbc6c0fb6 100644 --- a/verilog/analysis/checkers/module_instantiation_rules.h +++ b/verilog/analysis/checkers/module_instantiation_rules.h @@ -33,10 +33,10 @@ namespace analysis { class ModuleParameterRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; private: @@ -48,17 +48,17 @@ class ModuleParameterRule : public verible::SyntaxTreeLintRule { class ModulePortRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; private: // Returns false if a port list node is in violation of this rule and // true if it is not. static bool IsPortListCompliant( - const verible::SyntaxTreeNode& port_list_node); + const verible::SyntaxTreeNode &port_list_node); std::set violations_; }; diff --git a/verilog/analysis/checkers/no_tabs_rule.cc b/verilog/analysis/checkers/no_tabs_rule.cc index c8b2ad7a3..d5abfd3b0 100644 --- a/verilog/analysis/checkers/no_tabs_rule.cc +++ b/verilog/analysis/checkers/no_tabs_rule.cc @@ -38,7 +38,7 @@ VERILOG_REGISTER_LINT_RULE(NoTabsRule); static constexpr absl::string_view kMessage = "Use spaces, not tabs."; -const LintRuleDescriptor& NoTabsRule::GetDescriptor() { +const LintRuleDescriptor &NoTabsRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "no-tabs", .topic = "tabs", diff --git a/verilog/analysis/checkers/no_tabs_rule.h b/verilog/analysis/checkers/no_tabs_rule.h index c25f724bc..f16a06783 100644 --- a/verilog/analysis/checkers/no_tabs_rule.h +++ b/verilog/analysis/checkers/no_tabs_rule.h @@ -32,7 +32,7 @@ class NoTabsRule : public verible::LineLintRule { public: using rule_type = verible::LineLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); NoTabsRule() = default; diff --git a/verilog/analysis/checkers/no_trailing_spaces_rule.cc b/verilog/analysis/checkers/no_trailing_spaces_rule.cc index 80eafc35f..3eda29e8d 100644 --- a/verilog/analysis/checkers/no_trailing_spaces_rule.cc +++ b/verilog/analysis/checkers/no_trailing_spaces_rule.cc @@ -43,7 +43,7 @@ VERILOG_REGISTER_LINT_RULE(NoTrailingSpacesRule); static constexpr absl::string_view kMessage = "Remove trailing spaces."; -const LintRuleDescriptor& NoTrailingSpacesRule::GetDescriptor() { +const LintRuleDescriptor &NoTrailingSpacesRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "no-trailing-spaces", .topic = "trailing-spaces", diff --git a/verilog/analysis/checkers/no_trailing_spaces_rule.h b/verilog/analysis/checkers/no_trailing_spaces_rule.h index c74d696cb..be5684b12 100644 --- a/verilog/analysis/checkers/no_trailing_spaces_rule.h +++ b/verilog/analysis/checkers/no_trailing_spaces_rule.h @@ -32,7 +32,7 @@ class NoTrailingSpacesRule : public verible::LineLintRule { public: using rule_type = verible::LineLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); NoTrailingSpacesRule() = default; diff --git a/verilog/analysis/checkers/numeric_format_string_style_rule.cc b/verilog/analysis/checkers/numeric_format_string_style_rule.cc index a0e9152c7..faf3e6035 100644 --- a/verilog/analysis/checkers/numeric_format_string_style_rule.cc +++ b/verilog/analysis/checkers/numeric_format_string_style_rule.cc @@ -44,7 +44,7 @@ VERILOG_REGISTER_LINT_RULE(NumericFormatStringStyleRule); static constexpr absl::string_view kMessage = "Formatting string must contain proper style-compilant numeric specifiers."; -const LintRuleDescriptor& NumericFormatStringStyleRule::GetDescriptor() { +const LintRuleDescriptor &NumericFormatStringStyleRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "numeric-format-string-style", .topic = "number-formatting", @@ -60,7 +60,7 @@ template class TD; void NumericFormatStringStyleRule::CheckAndReportViolation( - const TokenInfo& token, size_t pos, size_t len, + const TokenInfo &token, size_t pos, size_t len, std::initializer_list prefixes) { const absl::string_view text(token.text()); @@ -68,7 +68,7 @@ void NumericFormatStringStyleRule::CheckAndReportViolation( if (pos >= 2 && (text[pos - 2] == '0' || text[pos - 2] == '\'')) { const auto ch = text[pos - 1]; if (std::none_of(prefixes.begin(), prefixes.end(), - [&ch](const char& _ch) { return _ch == ch; })) { + [&ch](const char &_ch) { return _ch == ch; })) { // Report whole prefix with a "0" or "'" violations_.insert(LintViolation( TokenInfo(token.token_enum(), text.substr(pos - 2, len + 2)), @@ -81,21 +81,21 @@ void NumericFormatStringStyleRule::CheckAndReportViolation( } } -void NumericFormatStringStyleRule::HandleToken(const TokenInfo& token) { +void NumericFormatStringStyleRule::HandleToken(const TokenInfo &token) { const auto token_enum = static_cast(token.token_enum()); const absl::string_view text(token.text()); if (IsUnlexed(verilog_tokentype(token.token_enum()))) { // recursively lex to examine inside macro definition bodies, etc. RecursiveLexText( - text, [this](const TokenInfo& subtoken) { HandleToken(subtoken); }); + text, [this](const TokenInfo &subtoken) { HandleToken(subtoken); }); return; } if (token_enum != TK_StringLiteral) return; for (size_t pos = 0; pos < text.size();) { - const auto& ch = text[pos]; + const auto &ch = text[pos]; // Skip ordinary characters if (ch != '%') { diff --git a/verilog/analysis/checkers/numeric_format_string_style_rule.h b/verilog/analysis/checkers/numeric_format_string_style_rule.h index 06512cdfb..2f169e107 100644 --- a/verilog/analysis/checkers/numeric_format_string_style_rule.h +++ b/verilog/analysis/checkers/numeric_format_string_style_rule.h @@ -32,16 +32,16 @@ class NumericFormatStringStyleRule : public verible::TokenStreamLintRule { public: using rule_type = verible::TokenStreamLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); NumericFormatStringStyleRule() = default; - void HandleToken(const verible::TokenInfo& token) final; + void HandleToken(const verible::TokenInfo &token) final; verible::LintRuleStatus Report() const final; private: - void CheckAndReportViolation(const verible::TokenInfo& token, size_t position, + void CheckAndReportViolation(const verible::TokenInfo &token, size_t position, size_t length, std::initializer_list prefixes); diff --git a/verilog/analysis/checkers/one_module_per_file_rule.cc b/verilog/analysis/checkers/one_module_per_file_rule.cc index 1f23d85e5..ba5e67bc0 100644 --- a/verilog/analysis/checkers/one_module_per_file_rule.cc +++ b/verilog/analysis/checkers/one_module_per_file_rule.cc @@ -47,7 +47,7 @@ VERILOG_REGISTER_LINT_RULE(OneModulePerFileRule); static constexpr absl::string_view kMessage = "Each file should have only one module declaration. Found: "; -const LintRuleDescriptor& OneModulePerFileRule::GetDescriptor() { +const LintRuleDescriptor &OneModulePerFileRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "one-module-per-file", .topic = "file-extensions", @@ -56,9 +56,9 @@ const LintRuleDescriptor& OneModulePerFileRule::GetDescriptor() { return d; } -void OneModulePerFileRule::Lint(const TextStructureView& text_structure, +void OneModulePerFileRule::Lint(const TextStructureView &text_structure, absl::string_view) { - const auto& tree = text_structure.SyntaxTree(); + const auto &tree = text_structure.SyntaxTree(); if (tree == nullptr) return; auto module_matches = FindAllModuleDeclarations(*tree); @@ -72,13 +72,13 @@ void OneModulePerFileRule::Lint(const TextStructureView& text_structure, std::back_insert_iterator> back_it( module_cleaned); std::remove_copy_if(module_matches.begin(), module_matches.end(), back_it, - [](verible::TreeSearchMatch& m) { + [](verible::TreeSearchMatch &m) { return m.context.IsInside(NodeEnum::kModuleDeclaration); }); if (module_cleaned.size() > 1) { // Report second module declaration - const auto* second_module_id = GetModuleName(*module_cleaned[1].match); + const auto *second_module_id = GetModuleName(*module_cleaned[1].match); if (!second_module_id) LOG(ERROR) << "Couldn't extract module name"; if (second_module_id) { violations_.insert(verible::LintViolation( diff --git a/verilog/analysis/checkers/one_module_per_file_rule.h b/verilog/analysis/checkers/one_module_per_file_rule.h index ef9969241..98304a7f9 100644 --- a/verilog/analysis/checkers/one_module_per_file_rule.h +++ b/verilog/analysis/checkers/one_module_per_file_rule.h @@ -32,11 +32,11 @@ class OneModulePerFileRule : public verible::TextStructureLintRule { public: using rule_type = verible::TextStructureLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); OneModulePerFileRule() = default; - void Lint(const verible::TextStructureView&, absl::string_view) final; + void Lint(const verible::TextStructureView &, absl::string_view) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/package_filename_rule.cc b/verilog/analysis/checkers/package_filename_rule.cc index acbdaa3e6..53b763008 100644 --- a/verilog/analysis/checkers/package_filename_rule.cc +++ b/verilog/analysis/checkers/package_filename_rule.cc @@ -48,7 +48,7 @@ static constexpr absl::string_view kMessage = "Package declaration name must match the file name " "(ignoring optional \"_pkg\" file name suffix). "; -const LintRuleDescriptor& PackageFilenameRule::GetDescriptor() { +const LintRuleDescriptor &PackageFilenameRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "package-filename", .topic = "file-names", @@ -63,13 +63,13 @@ const LintRuleDescriptor& PackageFilenameRule::GetDescriptor() { return d; } -void PackageFilenameRule::Lint(const TextStructureView& text_structure, +void PackageFilenameRule::Lint(const TextStructureView &text_structure, absl::string_view filename) { if (verible::file::IsStdin(filename)) { return; } - const auto& tree = text_structure.SyntaxTree(); + const auto &tree = text_structure.SyntaxTree(); if (tree == nullptr) return; // Find all package declarations. @@ -100,8 +100,8 @@ void PackageFilenameRule::Lint(const TextStructureView& text_structure, } // Report a violation on every package declaration, potentially. - for (const auto& package_match : package_matches) { - const verible::TokenInfo* package_name_token = + for (const auto &package_match : package_matches) { + const verible::TokenInfo *package_name_token = GetPackageNameToken(*package_match.match); if (!package_name_token) continue; absl::string_view package_id = package_name_token->text(); diff --git a/verilog/analysis/checkers/package_filename_rule.h b/verilog/analysis/checkers/package_filename_rule.h index dd2a286d1..c78e0c957 100644 --- a/verilog/analysis/checkers/package_filename_rule.h +++ b/verilog/analysis/checkers/package_filename_rule.h @@ -33,12 +33,12 @@ class PackageFilenameRule : public verible::TextStructureLintRule { public: using rule_type = verible::TextStructureLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); PackageFilenameRule() = default; absl::Status Configure(absl::string_view configuration) final; - void Lint(const verible::TextStructureView&, absl::string_view) final; + void Lint(const verible::TextStructureView &, absl::string_view) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/packed_dimensions_rule.cc b/verilog/analysis/checkers/packed_dimensions_rule.cc index 52905b030..4a6327b92 100644 --- a/verilog/analysis/checkers/packed_dimensions_rule.cc +++ b/verilog/analysis/checkers/packed_dimensions_rule.cc @@ -47,7 +47,7 @@ static constexpr absl::string_view kMessage = "Declare packed dimension range in little-endian (decreasing) order, " "e.g. [N-1:0]."; -const LintRuleDescriptor& PackedDimensionsRule::GetDescriptor() { +const LintRuleDescriptor &PackedDimensionsRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "packed-dimensions-range-ordering", .topic = "packed-ordering", @@ -58,13 +58,13 @@ const LintRuleDescriptor& PackedDimensionsRule::GetDescriptor() { return d; } -static const Matcher& DimensionRangeMatcher() { +static const Matcher &DimensionRangeMatcher() { static const Matcher matcher(NodekDimensionRange()); return matcher; } void PackedDimensionsRule::HandleSymbol( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) { + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context) { if (!ContextIsInsidePackedDimensions(context)) return; verible::matcher::BoundSymbolManager manager; @@ -72,8 +72,8 @@ void PackedDimensionsRule::HandleSymbol( // Check whether or not bounds are numeric constants, including 0. // If one can conclude that left < right, then record as violation. - const auto& left = *ABSL_DIE_IF_NULL(GetDimensionRangeLeftBound(symbol)); - const auto& right = *ABSL_DIE_IF_NULL(GetDimensionRangeRightBound(symbol)); + const auto &left = *ABSL_DIE_IF_NULL(GetDimensionRangeLeftBound(symbol)); + const auto &right = *ABSL_DIE_IF_NULL(GetDimensionRangeRightBound(symbol)); int left_value, right_value; const bool left_is_constant = ConstantIntegerValue(left, &left_value); const bool right_is_constant = ConstantIntegerValue(right, &right_value); diff --git a/verilog/analysis/checkers/packed_dimensions_rule.h b/verilog/analysis/checkers/packed_dimensions_rule.h index 159306d6d..f9851c834 100644 --- a/verilog/analysis/checkers/packed_dimensions_rule.h +++ b/verilog/analysis/checkers/packed_dimensions_rule.h @@ -33,10 +33,10 @@ class PackedDimensionsRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; private: diff --git a/verilog/analysis/checkers/parameter_name_style_rule.cc b/verilog/analysis/checkers/parameter_name_style_rule.cc index 21fc693d9..3890c612f 100644 --- a/verilog/analysis/checkers/parameter_name_style_rule.cc +++ b/verilog/analysis/checkers/parameter_name_style_rule.cc @@ -44,7 +44,7 @@ using Matcher = verible::matcher::Matcher; // Register ParameterNameStyleRule. VERILOG_REGISTER_LINT_RULE(ParameterNameStyleRule); -const LintRuleDescriptor& ParameterNameStyleRule::GetDescriptor() { +const LintRuleDescriptor &ParameterNameStyleRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "parameter-name-style", .topic = "constants", @@ -60,7 +60,7 @@ const LintRuleDescriptor& ParameterNameStyleRule::GetDescriptor() { return d; } -static const Matcher& ParamDeclMatcher() { +static const Matcher &ParamDeclMatcher() { static const Matcher matcher(NodekParamDeclaration()); return matcher; } @@ -69,10 +69,10 @@ std::string ParameterNameStyleRule::ViolationMsg(absl::string_view symbol_type, uint32_t allowed_bitmap) { // TODO(hzeller): there are multiple places in this file referring to the // same string representations of these options. - static constexpr std::pair kBitNames[] = { + static constexpr std::pair kBitNames[] = { {kUpperCamelCase, "CamelCase"}, {kAllCaps, "ALL_CAPS"}}; std::string bit_list; - for (const auto& b : kBitNames) { + for (const auto &b : kBitNames) { if (allowed_bitmap & b.first) { if (!bit_list.empty()) bit_list.append(" or "); bit_list.append(b.second); @@ -82,8 +82,8 @@ std::string ParameterNameStyleRule::ViolationMsg(absl::string_view symbol_type, bit_list); } -void ParameterNameStyleRule::HandleSymbol(const verible::Symbol& symbol, - const SyntaxTreeContext& context) { +void ParameterNameStyleRule::HandleSymbol(const verible::Symbol &symbol, + const SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (ParamDeclMatcher().Matches(symbol, &manager)) { if (IsParamTypeDeclaration(symbol)) return; @@ -92,7 +92,7 @@ void ParameterNameStyleRule::HandleSymbol(const verible::Symbol& symbol, auto identifiers = GetAllParameterNameTokens(symbol); - for (const auto* id : identifiers) { + for (const auto *id : identifiers) { const auto param_name = id->text(); uint32_t observed_style = 0; if (verible::IsUpperCamelCaseWithDigits(param_name)) { diff --git a/verilog/analysis/checkers/parameter_name_style_rule.h b/verilog/analysis/checkers/parameter_name_style_rule.h index c78d8a86a..0e48fe423 100644 --- a/verilog/analysis/checkers/parameter_name_style_rule.h +++ b/verilog/analysis/checkers/parameter_name_style_rule.h @@ -36,12 +36,12 @@ class ParameterNameStyleRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); absl::Status Configure(absl::string_view configuration) final; - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/plusarg_assignment_rule.cc b/verilog/analysis/checkers/plusarg_assignment_rule.cc index 1a2388708..b5bea5820 100644 --- a/verilog/analysis/checkers/plusarg_assignment_rule.cc +++ b/verilog/analysis/checkers/plusarg_assignment_rule.cc @@ -40,7 +40,7 @@ VERILOG_REGISTER_LINT_RULE(PlusargAssignmentRule); static constexpr absl::string_view kForbiddenFunctionName = "$test$plusargs"; static constexpr absl::string_view kCorrectFunctionName = "$value$plusargs"; -const LintRuleDescriptor& PlusargAssignmentRule::GetDescriptor() { +const LintRuleDescriptor &PlusargAssignmentRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "plusarg-assignment", .topic = "plusarg-value-assignment", @@ -52,16 +52,16 @@ const LintRuleDescriptor& PlusargAssignmentRule::GetDescriptor() { return d; } -static const Matcher& IdMatcher() { +static const Matcher &IdMatcher() { static const Matcher matcher(SystemTFIdentifierLeaf().Bind("name")); return matcher; } void PlusargAssignmentRule::HandleSymbol( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) { + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (IdMatcher().Matches(symbol, &manager)) { - if (const auto* leaf = manager.GetAs("name")) { + if (const auto *leaf = manager.GetAs("name")) { if (kForbiddenFunctionName == leaf->get().text()) { violations_.insert( verible::LintViolation(leaf->get(), FormatReason(), context)); diff --git a/verilog/analysis/checkers/plusarg_assignment_rule.h b/verilog/analysis/checkers/plusarg_assignment_rule.h index ab5c576e2..27c84f1a7 100644 --- a/verilog/analysis/checkers/plusarg_assignment_rule.h +++ b/verilog/analysis/checkers/plusarg_assignment_rule.h @@ -41,10 +41,10 @@ class PlusargAssignmentRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/port_name_suffix_rule.cc b/verilog/analysis/checkers/port_name_suffix_rule.cc index bd19ecb3e..8fa0e9bf7 100644 --- a/verilog/analysis/checkers/port_name_suffix_rule.cc +++ b/verilog/analysis/checkers/port_name_suffix_rule.cc @@ -55,7 +55,7 @@ static constexpr absl::string_view kMessageOut = static constexpr absl::string_view kMessageInOut = "inout port names must end with _io, _nio or _pio"; -const LintRuleDescriptor& PortNameSuffixRule::GetDescriptor() { +const LintRuleDescriptor &PortNameSuffixRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "port-name-suffix", .topic = "suffixes-for-signals-and-types", @@ -68,14 +68,14 @@ const LintRuleDescriptor& PortNameSuffixRule::GetDescriptor() { return d; } -static const Matcher& PortMatcher() { +static const Matcher &PortMatcher() { static const Matcher matcher(NodekPortDeclaration()); return matcher; } void PortNameSuffixRule::Violation(absl::string_view direction, - const TokenInfo& token, - const SyntaxTreeContext& context) { + const TokenInfo &token, + const SyntaxTreeContext &context) { if (direction == "input") { violations_.insert(LintViolation(token, kMessageIn, context)); } else if (direction == "output") { @@ -98,13 +98,13 @@ bool PortNameSuffixRule::IsSuffixCorrect(absl::string_view suffix, return suffixes.at(direction).count(suffix) == 1; } -void PortNameSuffixRule::HandleSymbol(const Symbol& symbol, - const SyntaxTreeContext& context) { +void PortNameSuffixRule::HandleSymbol(const Symbol &symbol, + const SyntaxTreeContext &context) { constexpr absl::string_view implicit_direction = "input"; verible::matcher::BoundSymbolManager manager; if (PortMatcher().Matches(symbol, &manager)) { - const auto* identifier_leaf = GetIdentifierFromPortDeclaration(symbol); - const auto* direction_leaf = GetDirectionFromPortDeclaration(symbol); + const auto *identifier_leaf = GetIdentifierFromPortDeclaration(symbol); + const auto *direction_leaf = GetDirectionFromPortDeclaration(symbol); const auto token = identifier_leaf->get(); const auto direction = direction_leaf ? direction_leaf->get().text() : implicit_direction; diff --git a/verilog/analysis/checkers/port_name_suffix_rule.h b/verilog/analysis/checkers/port_name_suffix_rule.h index a3cd4b5ae..3046754e5 100644 --- a/verilog/analysis/checkers/port_name_suffix_rule.h +++ b/verilog/analysis/checkers/port_name_suffix_rule.h @@ -35,17 +35,17 @@ class PortNameSuffixRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; private: // Helper functions - void Violation(absl::string_view direction, const verible::TokenInfo& token, - const verible::SyntaxTreeContext& context); + void Violation(absl::string_view direction, const verible::TokenInfo &token, + const verible::SyntaxTreeContext &context); static bool IsSuffixCorrect(absl::string_view suffix, absl::string_view direction); diff --git a/verilog/analysis/checkers/positive_meaning_parameter_name_rule.cc b/verilog/analysis/checkers/positive_meaning_parameter_name_rule.cc index 3724b02ff..a512e84c7 100644 --- a/verilog/analysis/checkers/positive_meaning_parameter_name_rule.cc +++ b/verilog/analysis/checkers/positive_meaning_parameter_name_rule.cc @@ -47,7 +47,7 @@ VERILOG_REGISTER_LINT_RULE(PositiveMeaningParameterNameRule); static constexpr absl::string_view kMessage = "Use positive naming for parameters, start the name with 'enable' instead."; -const LintRuleDescriptor& PositiveMeaningParameterNameRule::GetDescriptor() { +const LintRuleDescriptor &PositiveMeaningParameterNameRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "positive-meaning-parameter-name", .topic = "binary-parameters", @@ -58,19 +58,19 @@ const LintRuleDescriptor& PositiveMeaningParameterNameRule::GetDescriptor() { return d; } -static const Matcher& ParamDeclMatcher() { +static const Matcher &ParamDeclMatcher() { static const Matcher matcher(NodekParamDeclaration()); return matcher; } void PositiveMeaningParameterNameRule::HandleSymbol( - const verible::Symbol& symbol, const SyntaxTreeContext& context) { + const verible::Symbol &symbol, const SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (ParamDeclMatcher().Matches(symbol, &manager)) { if (IsParamTypeDeclaration(symbol)) return; auto identifiers = GetAllParameterNameTokens(symbol); - for (const auto& id : identifiers) { + for (const auto &id : identifiers) { const auto param_name = id->text(); if (absl::StartsWithIgnoreCase(param_name, "disable")) { diff --git a/verilog/analysis/checkers/positive_meaning_parameter_name_rule.h b/verilog/analysis/checkers/positive_meaning_parameter_name_rule.h index 42a95d6f1..a353d376d 100644 --- a/verilog/analysis/checkers/positive_meaning_parameter_name_rule.h +++ b/verilog/analysis/checkers/positive_meaning_parameter_name_rule.h @@ -33,10 +33,10 @@ class PositiveMeaningParameterNameRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/posix_eof_rule.cc b/verilog/analysis/checkers/posix_eof_rule.cc index ecd9b2441..591821171 100644 --- a/verilog/analysis/checkers/posix_eof_rule.cc +++ b/verilog/analysis/checkers/posix_eof_rule.cc @@ -40,7 +40,7 @@ VERILOG_REGISTER_LINT_RULE(PosixEOFRule); static constexpr absl::string_view kMessage = "File must end with a newline."; -const LintRuleDescriptor& PosixEOFRule::GetDescriptor() { +const LintRuleDescriptor &PosixEOFRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "posix-eof", .topic = "posix-file-endings", @@ -49,10 +49,10 @@ const LintRuleDescriptor& PosixEOFRule::GetDescriptor() { return d; } -void PosixEOFRule::Lint(const TextStructureView& text_structure, +void PosixEOFRule::Lint(const TextStructureView &text_structure, absl::string_view) { if (!text_structure.Contents().empty()) { - const auto& last_line = text_structure.Lines().back(); + const auto &last_line = text_structure.Lines().back(); if (!last_line.empty()) { // Point to the end of the line (also EOF). const TokenInfo token(TK_OTHER, last_line.substr(last_line.length(), 0)); diff --git a/verilog/analysis/checkers/posix_eof_rule.h b/verilog/analysis/checkers/posix_eof_rule.h index f3c149a2d..9870ad5ef 100644 --- a/verilog/analysis/checkers/posix_eof_rule.h +++ b/verilog/analysis/checkers/posix_eof_rule.h @@ -39,11 +39,11 @@ class PosixEOFRule : public verible::TextStructureLintRule { public: using rule_type = verible::TextStructureLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); PosixEOFRule() = default; - void Lint(const verible::TextStructureView&, absl::string_view) final; + void Lint(const verible::TextStructureView &, absl::string_view) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/proper_parameter_declaration_rule.cc b/verilog/analysis/checkers/proper_parameter_declaration_rule.cc index 342946ca0..ab3e4bad5 100644 --- a/verilog/analysis/checkers/proper_parameter_declaration_rule.cc +++ b/verilog/analysis/checkers/proper_parameter_declaration_rule.cc @@ -48,7 +48,7 @@ static constexpr absl::string_view kLocalParamMessage = "\'localparam\' declarations should only be within modules\' or classes\' " "definition bodies."; -const LintRuleDescriptor& ProperParameterDeclarationRule::GetDescriptor() { +const LintRuleDescriptor &ProperParameterDeclarationRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "proper-parameter-declaration", .topic = "constants", @@ -60,14 +60,14 @@ const LintRuleDescriptor& ProperParameterDeclarationRule::GetDescriptor() { return d; } -static const Matcher& ParamDeclMatcher() { +static const Matcher &ParamDeclMatcher() { static const Matcher matcher(NodekParamDeclaration()); return matcher; } // TODO(kathuriac): Also check the 'interface' and 'program' constructs. void ProperParameterDeclarationRule::HandleSymbol( - const verible::Symbol& symbol, const SyntaxTreeContext& context) { + const verible::Symbol &symbol, const SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (ParamDeclMatcher().Matches(symbol, &manager)) { const auto param_decl_token = GetParamKeyword(symbol); diff --git a/verilog/analysis/checkers/proper_parameter_declaration_rule.h b/verilog/analysis/checkers/proper_parameter_declaration_rule.h index 24c5f848f..a7e0c2fd9 100644 --- a/verilog/analysis/checkers/proper_parameter_declaration_rule.h +++ b/verilog/analysis/checkers/proper_parameter_declaration_rule.h @@ -34,10 +34,10 @@ class ProperParameterDeclarationRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/signal_name_style_rule.cc b/verilog/analysis/checkers/signal_name_style_rule.cc index 0b2fd3d1a..b8ad2cde7 100644 --- a/verilog/analysis/checkers/signal_name_style_rule.cc +++ b/verilog/analysis/checkers/signal_name_style_rule.cc @@ -48,7 +48,7 @@ using verible::matcher::Matcher; static constexpr absl::string_view kMessage = "Signal names must use lower_snake_case naming convention."; -const LintRuleDescriptor& SignalNameStyleRule::GetDescriptor() { +const LintRuleDescriptor &SignalNameStyleRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "signal-name-style", .topic = "signal-conventions", @@ -60,26 +60,26 @@ const LintRuleDescriptor& SignalNameStyleRule::GetDescriptor() { return d; } -static const Matcher& PortMatcher() { +static const Matcher &PortMatcher() { static const Matcher matcher(NodekPortDeclaration()); return matcher; } -static const Matcher& NetMatcher() { +static const Matcher &NetMatcher() { static const Matcher matcher(NodekNetDeclaration()); return matcher; } -static const Matcher& DataMatcher() { +static const Matcher &DataMatcher() { static const Matcher matcher(NodekDataDeclaration()); return matcher; } -void SignalNameStyleRule::HandleSymbol(const verible::Symbol& symbol, - const SyntaxTreeContext& context) { +void SignalNameStyleRule::HandleSymbol(const verible::Symbol &symbol, + const SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (PortMatcher().Matches(symbol, &manager)) { - const auto* identifier_leaf = GetIdentifierFromPortDeclaration(symbol); + const auto *identifier_leaf = GetIdentifierFromPortDeclaration(symbol); const auto name = ABSL_DIE_IF_NULL(identifier_leaf)->get().text(); if (!verible::IsLowerSnakeCaseWithDigits(name)) { violations_.insert( @@ -87,7 +87,7 @@ void SignalNameStyleRule::HandleSymbol(const verible::Symbol& symbol, } } else if (NetMatcher().Matches(symbol, &manager)) { const auto identifier_leaves = GetIdentifiersFromNetDeclaration(symbol); - for (const auto* leaf : identifier_leaves) { + for (const auto *leaf : identifier_leaves) { const auto name = leaf->text(); if (!verible::IsLowerSnakeCaseWithDigits(name)) { violations_.insert(LintViolation(*leaf, kMessage, context)); @@ -95,7 +95,7 @@ void SignalNameStyleRule::HandleSymbol(const verible::Symbol& symbol, } } else if (DataMatcher().Matches(symbol, &manager)) { const auto identifier_leaves = GetIdentifiersFromDataDeclaration(symbol); - for (const auto* leaf : identifier_leaves) { + for (const auto *leaf : identifier_leaves) { const auto name = leaf->text(); if (!verible::IsLowerSnakeCaseWithDigits(name)) { violations_.insert(LintViolation(*leaf, kMessage, context)); diff --git a/verilog/analysis/checkers/signal_name_style_rule.h b/verilog/analysis/checkers/signal_name_style_rule.h index 32223b92a..f9d22fbc8 100644 --- a/verilog/analysis/checkers/signal_name_style_rule.h +++ b/verilog/analysis/checkers/signal_name_style_rule.h @@ -34,10 +34,10 @@ class SignalNameStyleRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/suggest_parentheses_rule.cc b/verilog/analysis/checkers/suggest_parentheses_rule.cc index fc7786ba6..f109fc4bf 100644 --- a/verilog/analysis/checkers/suggest_parentheses_rule.cc +++ b/verilog/analysis/checkers/suggest_parentheses_rule.cc @@ -32,7 +32,7 @@ static constexpr absl::string_view kMessage = "Parenthesize condition expressions that appear in the true-clause of " "another condition expression."; -const LintRuleDescriptor& SuggestParenthesesRule::GetDescriptor() { +const LintRuleDescriptor &SuggestParenthesesRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "suggest-parentheses", .topic = "parentheses", @@ -44,15 +44,15 @@ const LintRuleDescriptor& SuggestParenthesesRule::GetDescriptor() { } void SuggestParenthesesRule::HandleNode( - const verible::SyntaxTreeNode& node, - const verible::SyntaxTreeContext& context) { + const verible::SyntaxTreeNode &node, + const verible::SyntaxTreeContext &context) { const auto tag = static_cast(node.Tag().tag); // TODO: evaluate other types of expressions switch (tag) { case NodeEnum::kConditionExpression: { - const verible::Symbol* trueCase = GetConditionExpressionTrueCase(node); + const verible::Symbol *trueCase = GetConditionExpressionTrueCase(node); - const verible::Symbol* trueCaseChild = UnwrapExpression(*trueCase); + const verible::Symbol *trueCaseChild = UnwrapExpression(*trueCase); const auto trueCaseChildtag = static_cast(trueCaseChild->Tag().tag); diff --git a/verilog/analysis/checkers/suggest_parentheses_rule.h b/verilog/analysis/checkers/suggest_parentheses_rule.h index 45635c8fa..61af79b02 100644 --- a/verilog/analysis/checkers/suggest_parentheses_rule.h +++ b/verilog/analysis/checkers/suggest_parentheses_rule.h @@ -30,10 +30,10 @@ class SuggestParenthesesRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleNode(const verible::SyntaxTreeNode& node, - const verible::SyntaxTreeContext& context) final; + void HandleNode(const verible::SyntaxTreeNode &node, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/token_stream_lint_rule.cc b/verilog/analysis/checkers/token_stream_lint_rule.cc index 5abbe5f5b..56e5a6720 100644 --- a/verilog/analysis/checkers/token_stream_lint_rule.cc +++ b/verilog/analysis/checkers/token_stream_lint_rule.cc @@ -45,7 +45,7 @@ static constexpr absl::string_view kMessage = "The lines can't be continued with \'\\\', use concatenation operator with " "braces"; -const LintRuleDescriptor& TokenStreamLintRule::GetDescriptor() { +const LintRuleDescriptor &TokenStreamLintRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "forbid-line-continuations", .topic = "forbid-line-continuations", @@ -57,24 +57,24 @@ const LintRuleDescriptor& TokenStreamLintRule::GetDescriptor() { return d; } -static const Matcher& StringLiteralMatcher() { +static const Matcher &StringLiteralMatcher() { static const Matcher matcher(StringLiteralKeyword()); return matcher; } -void TokenStreamLintRule::HandleSymbol(const verible::Symbol& symbol, - const SyntaxTreeContext& context) { +void TokenStreamLintRule::HandleSymbol(const verible::Symbol &symbol, + const SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (!StringLiteralMatcher().Matches(symbol, &manager)) { return; } - const auto& string_node = SymbolCastToNode(symbol); - const auto& node_children = string_node.children(); - const auto& literal = std::find_if(node_children.begin(), node_children.end(), - [](const verible::SymbolPtr& p) { + const auto &string_node = SymbolCastToNode(symbol); + const auto &node_children = string_node.children(); + const auto &literal = std::find_if(node_children.begin(), node_children.end(), + [](const verible::SymbolPtr &p) { return p->Tag().tag == TK_StringLiteral; }); - const auto& string_literal = SymbolCastToLeaf(**literal); + const auto &string_literal = SymbolCastToLeaf(**literal); if (absl::StrContains(string_literal.get().text(), "\\\n")) { violations_.insert(LintViolation(string_literal, kMessage, context)); } diff --git a/verilog/analysis/checkers/token_stream_lint_rule.h b/verilog/analysis/checkers/token_stream_lint_rule.h index 7f54411d6..699fc3c5a 100644 --- a/verilog/analysis/checkers/token_stream_lint_rule.h +++ b/verilog/analysis/checkers/token_stream_lint_rule.h @@ -32,10 +32,10 @@ class TokenStreamLintRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/truncated_numeric_literal_rule.cc b/verilog/analysis/checkers/truncated_numeric_literal_rule.cc index 7b912d9cd..763949ce2 100644 --- a/verilog/analysis/checkers/truncated_numeric_literal_rule.cc +++ b/verilog/analysis/checkers/truncated_numeric_literal_rule.cc @@ -50,7 +50,7 @@ using verible::matcher::Matcher; VERILOG_REGISTER_LINT_RULE(TruncatedNumericLiteralRule); -const LintRuleDescriptor& TruncatedNumericLiteralRule::GetDescriptor() { +const LintRuleDescriptor &TruncatedNumericLiteralRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "truncated-numeric-literal", .topic = "number-literals", @@ -61,7 +61,7 @@ const LintRuleDescriptor& TruncatedNumericLiteralRule::GetDescriptor() { return d; } -static const Matcher& NumberMatcher() { +static const Matcher &NumberMatcher() { static const Matcher matcher( NodekNumber(NumberHasConstantWidth().Bind("width"), NumberHasBasedLiteral().Bind("literal"))); @@ -69,7 +69,7 @@ static const Matcher& NumberMatcher() { } // Given a binary/oct/hex digit, return how many bits it occupies -static int digitBits(char digit, bool* is_lower_bound) { +static int digitBits(char digit, bool *is_lower_bound) { if (digit == 'z' || digit == 'x' || digit == '?') { *is_lower_bound = true; return 1; // Minimum number of bits assumed @@ -89,7 +89,7 @@ static absl::string_view StripLeadingZeroes(absl::string_view str) { // Return count of bits the given number occupies. Sometims we can only make // a lower bound estimate, return that in "is_lower_bound". -static size_t GetBitWidthOfNumber(const BasedNumber& n, bool* is_lower_bound) { +static size_t GetBitWidthOfNumber(const BasedNumber &n, bool *is_lower_bound) { const absl::string_view literal = StripLeadingZeroes(n.literal); *is_lower_bound = true; // Can only estimate for the following two @@ -146,22 +146,22 @@ static size_t GetBitWidthOfNumber(const BasedNumber& n, bool* is_lower_bound) { } void TruncatedNumericLiteralRule::HandleSymbol( - const verible::Symbol& symbol, const SyntaxTreeContext& context) { + const verible::Symbol &symbol, const SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (!NumberMatcher().Matches(symbol, &manager)) return; - const auto* width_leaf = manager.GetAs("width"); - const auto* literal_node = manager.GetAs("literal"); + const auto *width_leaf = manager.GetAs("width"); + const auto *literal_node = manager.GetAs("literal"); if (!width_leaf || !literal_node) return; const auto width_text = width_leaf->get().text(); size_t width; if (!absl::SimpleAtoi(width_text, &width)) return; - const auto& base_digit_part = literal_node->children(); - const auto* base_leaf = - down_cast(base_digit_part[0].get()); - const auto* digits_leaf = - down_cast(base_digit_part[1].get()); + const auto &base_digit_part = literal_node->children(); + const auto *base_leaf = + down_cast(base_digit_part[0].get()); + const auto *digits_leaf = + down_cast(base_digit_part[1].get()); const auto base_text = base_leaf->get().text(); const auto digits_text = digits_leaf->get().text(); diff --git a/verilog/analysis/checkers/truncated_numeric_literal_rule.h b/verilog/analysis/checkers/truncated_numeric_literal_rule.h index 58516dcf5..282d84b46 100644 --- a/verilog/analysis/checkers/truncated_numeric_literal_rule.h +++ b/verilog/analysis/checkers/truncated_numeric_literal_rule.h @@ -34,10 +34,10 @@ class TruncatedNumericLiteralRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/unpacked_dimensions_rule.cc b/verilog/analysis/checkers/unpacked_dimensions_rule.cc index 1aa670a8e..be1b84853 100644 --- a/verilog/analysis/checkers/unpacked_dimensions_rule.cc +++ b/verilog/analysis/checkers/unpacked_dimensions_rule.cc @@ -51,7 +51,7 @@ static constexpr absl::string_view kMessageReorder = "Declare unpacked dimension range in big-endian (increasing) order, " "e.g. [N:N+M]."; -const LintRuleDescriptor& UnpackedDimensionsRule::GetDescriptor() { +const LintRuleDescriptor &UnpackedDimensionsRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "unpacked-dimensions-range-ordering", .topic = "unpacked-ordering", @@ -64,13 +64,13 @@ const LintRuleDescriptor& UnpackedDimensionsRule::GetDescriptor() { return d; } -static const Matcher& DimensionRangeMatcher() { +static const Matcher &DimensionRangeMatcher() { static const Matcher matcher(NodekDimensionRange()); return matcher; } void UnpackedDimensionsRule::HandleSymbol( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) { + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context) { if (!ContextIsInsideUnpackedDimensions(context) || context.IsInside(NodeEnum::kGateInstance)) { return; @@ -80,8 +80,8 @@ void UnpackedDimensionsRule::HandleSymbol( // Check whether or not bounds are numeric constants, including 0. // If one can conclude that left > right, then record as violation. - const auto& left = *ABSL_DIE_IF_NULL(GetDimensionRangeLeftBound(symbol)); - const auto& right = *ABSL_DIE_IF_NULL(GetDimensionRangeRightBound(symbol)); + const auto &left = *ABSL_DIE_IF_NULL(GetDimensionRangeLeftBound(symbol)); + const auto &right = *ABSL_DIE_IF_NULL(GetDimensionRangeRightBound(symbol)); int left_value, right_value; const bool left_is_constant = ConstantIntegerValue(left, &left_value); const bool right_is_constant = ConstantIntegerValue(right, &right_value); diff --git a/verilog/analysis/checkers/unpacked_dimensions_rule.h b/verilog/analysis/checkers/unpacked_dimensions_rule.h index e481bf56b..0311fdca2 100644 --- a/verilog/analysis/checkers/unpacked_dimensions_rule.h +++ b/verilog/analysis/checkers/unpacked_dimensions_rule.h @@ -34,10 +34,10 @@ class UnpackedDimensionsRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; private: diff --git a/verilog/analysis/checkers/uvm_macro_semicolon_rule.cc b/verilog/analysis/checkers/uvm_macro_semicolon_rule.cc index eae87b588..3e7bc9d1c 100644 --- a/verilog/analysis/checkers/uvm_macro_semicolon_rule.cc +++ b/verilog/analysis/checkers/uvm_macro_semicolon_rule.cc @@ -37,7 +37,7 @@ using verible::LintViolation; // Register UvmMacroSemicolonRule VERILOG_REGISTER_LINT_RULE(UvmMacroSemicolonRule); -const LintRuleDescriptor& UvmMacroSemicolonRule::GetDescriptor() { +const LintRuleDescriptor &UvmMacroSemicolonRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "uvm-macro-semicolon", .topic = "uvm-macro-semicolon-convention", // TODO(b/155128436): verify @@ -48,13 +48,13 @@ const LintRuleDescriptor& UvmMacroSemicolonRule::GetDescriptor() { } // Returns a diagnostic message for this lint violation. -static std::string FormatReason(const verible::TokenInfo& macro_id) { +static std::string FormatReason(const verible::TokenInfo ¯o_id) { return absl::StrCat("UVM macro call, ", macro_id.text(), " should not be followed by a semicolon \';\'."); } // Returns true if leaf is a macro and matches `uvm_ -static bool IsUvmMacroId(const verible::SyntaxTreeLeaf& leaf) { +static bool IsUvmMacroId(const verible::SyntaxTreeLeaf &leaf) { if (leaf.Tag().tag == verilog_tokentype::MacroCallId || leaf.Tag().tag == verilog_tokentype::MacroIdItem || leaf.Tag().tag == verilog_tokentype::MacroIdentifier) { @@ -64,8 +64,8 @@ static bool IsUvmMacroId(const verible::SyntaxTreeLeaf& leaf) { } void UvmMacroSemicolonRule::HandleLeaf( - const verible::SyntaxTreeLeaf& leaf, - const verible::SyntaxTreeContext& context) { + const verible::SyntaxTreeLeaf &leaf, + const verible::SyntaxTreeContext &context) { if (ContextIsInsideStatement(context) || context.IsInside(NodeEnum::kMacroCall) || context.IsInside(NodeEnum::kDataDeclaration)) { diff --git a/verilog/analysis/checkers/uvm_macro_semicolon_rule.h b/verilog/analysis/checkers/uvm_macro_semicolon_rule.h index b86a716af..6481c5409 100644 --- a/verilog/analysis/checkers/uvm_macro_semicolon_rule.h +++ b/verilog/analysis/checkers/uvm_macro_semicolon_rule.h @@ -46,10 +46,10 @@ class UvmMacroSemicolonRule : public verible::SyntaxTreeLintRule { UvmMacroSemicolonRule() = default; // Returns the description of the rule implemented - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleLeaf(const verible::SyntaxTreeLeaf& leaf, - const verible::SyntaxTreeContext& context) final; + void HandleLeaf(const verible::SyntaxTreeLeaf &leaf, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/v2001_generate_begin_rule.cc b/verilog/analysis/checkers/v2001_generate_begin_rule.cc index 62da5245f..bb0f48f6a 100644 --- a/verilog/analysis/checkers/v2001_generate_begin_rule.cc +++ b/verilog/analysis/checkers/v2001_generate_begin_rule.cc @@ -42,7 +42,7 @@ VERILOG_REGISTER_LINT_RULE(V2001GenerateBeginRule); static constexpr absl::string_view kMessage = "Do not begin a generate block inside a generate region."; -const LintRuleDescriptor& V2001GenerateBeginRule::GetDescriptor() { +const LintRuleDescriptor &V2001GenerateBeginRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "v2001-generate-begin", .topic = "generate-constructs", @@ -53,17 +53,17 @@ const LintRuleDescriptor& V2001GenerateBeginRule::GetDescriptor() { return d; } -static const Matcher& GenerateRegionMatcher() { +static const Matcher &GenerateRegionMatcher() { static const Matcher matcher( NodekGenerateRegion(HasGenerateBlock().Bind("block"))); return matcher; } void V2001GenerateBeginRule::HandleSymbol( - const verible::Symbol& symbol, const verible::SyntaxTreeContext& context) { + const verible::Symbol &symbol, const verible::SyntaxTreeContext &context) { verible::matcher::BoundSymbolManager manager; if (GenerateRegionMatcher().Matches(symbol, &manager)) { - if (const auto* block = manager.GetAs("block")) { + if (const auto *block = manager.GetAs("block")) { violations_.insert(LintViolation(verible::GetLeftmostLeaf(*block)->get(), kMessage, context)); } diff --git a/verilog/analysis/checkers/v2001_generate_begin_rule.h b/verilog/analysis/checkers/v2001_generate_begin_rule.h index 61619b6e1..c7fffd744 100644 --- a/verilog/analysis/checkers/v2001_generate_begin_rule.h +++ b/verilog/analysis/checkers/v2001_generate_begin_rule.h @@ -43,10 +43,10 @@ class V2001GenerateBeginRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; diff --git a/verilog/analysis/checkers/void_cast_rule.cc b/verilog/analysis/checkers/void_cast_rule.cc index 110e43b65..310399967 100644 --- a/verilog/analysis/checkers/void_cast_rule.cc +++ b/verilog/analysis/checkers/void_cast_rule.cc @@ -46,7 +46,7 @@ using verible::matcher::Matcher; // Register VoidCastRule VERILOG_REGISTER_LINT_RULE(VoidCastRule); -const LintRuleDescriptor& VoidCastRule::GetDescriptor() { +const LintRuleDescriptor &VoidCastRule::GetDescriptor() { static const LintRuleDescriptor d{ .name = "void-cast", .topic = "void-casts", @@ -57,8 +57,8 @@ const LintRuleDescriptor& VoidCastRule::GetDescriptor() { return d; } -const std::set& VoidCastRule::ForbiddenFunctionsSet() { - static const auto* forbidden_functions = +const std::set &VoidCastRule::ForbiddenFunctionsSet() { + static const auto *forbidden_functions = new std::set({"uvm_hdl_read"}); return *forbidden_functions; } @@ -67,7 +67,7 @@ const std::set& VoidCastRule::ForbiddenFunctionsSet() { // For example: // void'(foo()); // Here, the leaf representing "foo" will be bound to id -static const Matcher& FunctionMatcher() { +static const Matcher &FunctionMatcher() { static const Matcher matcher( NodekVoidcast(VoidcastHasExpression(verible::matcher::EachOf( ExpressionHasFunctionCall(), @@ -85,7 +85,7 @@ static const Matcher& FunctionMatcher() { // void'(randomize(obj)); // Here, the node representing "randomize(obj)" will be bound to "id" // -static const Matcher& RandomizeMatcher() { +static const Matcher &RandomizeMatcher() { static const Matcher matcher(NodekVoidcast(VoidcastHasExpression( verible::matcher::AnyOf(NonCallHasRandomizeCallExtension().Bind("id"), CallHasRandomizeCallExtension().Bind("id"), @@ -94,14 +94,14 @@ static const Matcher& RandomizeMatcher() { return matcher; } -void VoidCastRule::HandleSymbol(const verible::Symbol& symbol, - const SyntaxTreeContext& context) { +void VoidCastRule::HandleSymbol(const verible::Symbol &symbol, + const SyntaxTreeContext &context) { // Check for forbidden function names verible::matcher::BoundSymbolManager manager; if (FunctionMatcher().Matches(symbol, &manager)) { - if (const auto* function_id = + if (const auto *function_id = manager.GetAs("id")) { - const auto& bfs = ForbiddenFunctionsSet(); + const auto &bfs = ForbiddenFunctionsSet(); if (bfs.find(std::string(function_id->get().text())) != bfs.end()) { violations_.insert(LintViolation(function_id->get(), FormatReason(*function_id), context)); @@ -112,9 +112,9 @@ void VoidCastRule::HandleSymbol(const verible::Symbol& symbol, // Check for forbidden calls to randomize manager.Clear(); if (RandomizeMatcher().Matches(symbol, &manager)) { - if (const auto* randomize_node = + if (const auto *randomize_node = manager.GetAs("id")) { - const auto* leaf_ptr = verible::GetLeftmostLeaf(*randomize_node); + const auto *leaf_ptr = verible::GetLeftmostLeaf(*randomize_node); const verible::TokenInfo token = ABSL_DIE_IF_NULL(leaf_ptr)->get(); violations_.insert(LintViolation( token, "randomize() is forbidden within void casts", context)); @@ -127,7 +127,7 @@ LintRuleStatus VoidCastRule::Report() const { } /* static */ std::string VoidCastRule::FormatReason( - const verible::SyntaxTreeLeaf& leaf) { + const verible::SyntaxTreeLeaf &leaf) { return std::string(leaf.get().text()) + " is an invalid call within this void cast"; } diff --git a/verilog/analysis/checkers/void_cast_rule.h b/verilog/analysis/checkers/void_cast_rule.h index b0e3f37a3..422ff399a 100644 --- a/verilog/analysis/checkers/void_cast_rule.h +++ b/verilog/analysis/checkers/void_cast_rule.h @@ -34,18 +34,18 @@ class VoidCastRule : public verible::SyntaxTreeLintRule { public: using rule_type = verible::SyntaxTreeLintRule; - static const LintRuleDescriptor& GetDescriptor(); + static const LintRuleDescriptor &GetDescriptor(); - void HandleSymbol(const verible::Symbol& symbol, - const verible::SyntaxTreeContext& context) final; + void HandleSymbol(const verible::Symbol &symbol, + const verible::SyntaxTreeContext &context) final; verible::LintRuleStatus Report() const final; private: // Generate diagnostic message of why lint error occurred. - static std::string FormatReason(const verible::SyntaxTreeLeaf& leaf); + static std::string FormatReason(const verible::SyntaxTreeLeaf &leaf); - static const std::set& ForbiddenFunctionsSet(); + static const std::set &ForbiddenFunctionsSet(); std::set violations_; }; diff --git a/verilog/analysis/default_rules_test.cc b/verilog/analysis/default_rules_test.cc index 329bede5c..823a4093f 100644 --- a/verilog/analysis/default_rules_test.cc +++ b/verilog/analysis/default_rules_test.cc @@ -23,7 +23,7 @@ namespace { // Test that rules in the default set are all registered. TEST(DefaultRuleTest, AllDefaultValid) { - for (const auto& rule_id : kDefaultRuleSet) { + for (const auto &rule_id : kDefaultRuleSet) { EXPECT_TRUE(IsRegisteredLintRule(rule_id)) << "Registry is missing rule_id: " << rule_id; } diff --git a/verilog/analysis/dependencies.cc b/verilog/analysis/dependencies.cc index e80d4ae88..2dd39430d 100644 --- a/verilog/analysis/dependencies.cc +++ b/verilog/analysis/dependencies.cc @@ -25,7 +25,7 @@ namespace verilog { static FileDependencies::symbol_index_type CreateSymbolMapFromSymbolTable( - const SymbolTableNode& root, const VerilogProject* project) { + const SymbolTableNode &root, const VerilogProject *project) { VLOG(1) << __FUNCTION__ << ": collecting definitions"; CHECK(project != nullptr) << "VerilogProject* is required for dependency analysis."; @@ -34,12 +34,12 @@ static FileDependencies::symbol_index_type CreateSymbolMapFromSymbolTable( using SymbolData = FileDependencies::SymbolData; // Collect definers of root-level symbols. - for (const SymbolTableNode::key_value_type& child : root) { + for (const SymbolTableNode::key_value_type &child : root) { const absl::string_view symbol_name(child.first); - const VerilogSourceFile* file_origin = child.second.Value().file_origin; + const VerilogSourceFile *file_origin = child.second.Value().file_origin; if (file_origin == nullptr) continue; - SymbolData& symbol_data(symbols_index[symbol_name]); + SymbolData &symbol_data(symbols_index[symbol_name]); if (symbol_data.definer == nullptr) { // Take the first definition, arbitrarily. symbol_data.definer = file_origin; @@ -48,21 +48,21 @@ static FileDependencies::symbol_index_type CreateSymbolMapFromSymbolTable( // Collect all unqualified and unresolved references from all scopes. VLOG(1) << __FUNCTION__ << ": collecting references"; - root.ApplyPreOrder([&symbols_index, project](const SymbolTableNode& node) { - const SymbolInfo& symbol_info(node.Value()); - for (const DependentReferences& ref : + root.ApplyPreOrder([&symbols_index, project](const SymbolTableNode &node) { + const SymbolInfo &symbol_info(node.Value()); + for (const DependentReferences &ref : symbol_info.local_references_to_bind) { // Only look at the root reference node, which is unqualified. - const ReferenceComponent& ref_comp(ref.components->Value()); + const ReferenceComponent &ref_comp(ref.components->Value()); const absl::string_view ref_id(ref_comp.identifier); VLOG(2) << " referenced id: " << ref_id; - const VerilogSourceFile* ref_file_origin = + const VerilogSourceFile *ref_file_origin = project->LookupFileOrigin(ref_id); if (ref_file_origin == nullptr) continue; // unknown file if (ref_comp.resolved_symbol != nullptr) { - const VerilogSourceFile* def_file_origin = + const VerilogSourceFile *def_file_origin = ref_comp.resolved_symbol->Value().file_origin; if (ref_file_origin == def_file_origin) { continue; // skip already resolved symbols in same file @@ -70,7 +70,7 @@ static FileDependencies::symbol_index_type CreateSymbolMapFromSymbolTable( } VLOG(2) << " registering reference edge"; - SymbolData& symbol_data(symbols_index[ref_id]); + SymbolData &symbol_data(symbols_index[ref_id]); symbol_data.referencers.insert(ref_file_origin); } }); @@ -80,12 +80,12 @@ static FileDependencies::symbol_index_type CreateSymbolMapFromSymbolTable( // Struct for printing readable dependency edge. struct DepEdge { - const VerilogSourceFile* const ref; - const VerilogSourceFile* const def; - const FileDependencies::SymbolNameSet& symbols; + const VerilogSourceFile *const ref; + const VerilogSourceFile *const def; + const FileDependencies::SymbolNameSet &symbols; }; -static std::ostream& operator<<(std::ostream& stream, const DepEdge& dep) { +static std::ostream &operator<<(std::ostream &stream, const DepEdge &dep) { return stream << '"' << dep.ref->ReferencedPath() << "\" depends on \"" << dep.def->ReferencedPath() << "\" for symbols " << verible::SequenceFormatter(dep.symbols, ", ", "{ ", " }"); @@ -93,17 +93,17 @@ static std::ostream& operator<<(std::ostream& stream, const DepEdge& dep) { static FileDependencies::file_deps_graph_type CreateFileDependenciesFromSymbolMap( - const FileDependencies::symbol_index_type& symbol_map) { + const FileDependencies::symbol_index_type &symbol_map) { VLOG(1) << __FUNCTION__; FileDependencies::file_deps_graph_type file_deps; - for (const auto& symbol_entry : symbol_map) { + for (const auto &symbol_entry : symbol_map) { const absl::string_view symbol_name(symbol_entry.first); - const FileDependencies::SymbolData& symbol_info(symbol_entry.second); - const VerilogSourceFile* def = symbol_info.definer; + const FileDependencies::SymbolData &symbol_info(symbol_entry.second); + const VerilogSourceFile *def = symbol_info.definer; // If no definition is found, then do not create any edges for it. if (def == nullptr) continue; - for (const VerilogSourceFile* ref : symbol_info.referencers) { + for (const VerilogSourceFile *ref : symbol_info.referencers) { // Skip self-edges. if (ref == def) continue; VLOG(2) << DepEdge{.ref = ref, .def = def, .symbols = {symbol_name}}; @@ -114,7 +114,7 @@ CreateFileDependenciesFromSymbolMap( return file_deps; // move } -FileDependencies::FileDependencies(const SymbolTable& symbol_table) +FileDependencies::FileDependencies(const SymbolTable &symbol_table) : root_symbols_index(CreateSymbolMapFromSymbolTable( symbol_table.Root(), symbol_table.Project())), file_deps(CreateFileDependenciesFromSymbolMap(root_symbols_index)) { @@ -122,8 +122,8 @@ FileDependencies::FileDependencies(const SymbolTable& symbol_table) } bool FileDependencies::Empty() const { - for (const auto& ref : file_deps) { - for (const auto& def : ref.second) { + for (const auto &ref : file_deps) { + for (const auto &def : ref.second) { if (!def.second.empty()) return false; } } @@ -131,24 +131,24 @@ bool FileDependencies::Empty() const { } void FileDependencies::TraverseDependencyEdges( - const std::function& edge_func) const { - for (const auto& tail : file_deps) { - for (const auto& head : tail.second) { + const std::function &edge_func) const { + for (const auto &tail : file_deps) { + for (const auto &head : tail.second) { edge_func(tail.first, head.first, head.second); } } } -std::ostream& FileDependencies::PrintGraph(std::ostream& stream) const { - TraverseDependencyEdges([&stream](const node_type& ref, const node_type& def, - const SymbolNameSet& symbols) { +std::ostream &FileDependencies::PrintGraph(std::ostream &stream) const { + TraverseDependencyEdges([&stream](const node_type &ref, const node_type &def, + const SymbolNameSet &symbols) { stream << DepEdge{.ref = ref, .def = def, .symbols = symbols} << std::endl; }); return stream; } -std::ostream& operator<<(std::ostream& stream, const FileDependencies& deps) { +std::ostream &operator<<(std::ostream &stream, const FileDependencies &deps) { return deps.PrintGraph(stream); } diff --git a/verilog/analysis/dependencies.h b/verilog/analysis/dependencies.h index 58d1e873a..bf34964fa 100644 --- a/verilog/analysis/dependencies.h +++ b/verilog/analysis/dependencies.h @@ -37,7 +37,7 @@ struct FileDependencies { // A node is represented as a source file. // Edges are just a pair of nodes. - using node_type = const VerilogSourceFile*; + using node_type = const VerilogSourceFile *; // A set of strings, whose memory is owned outside of this data structure. using SymbolNameSet = std::set; @@ -57,11 +57,11 @@ struct FileDependencies { struct SymbolData { // Which file defines this symbol (first)? - const VerilogSourceFile* definer = nullptr; + const VerilogSourceFile *definer = nullptr; // Which files might reference this symbol? // Elements are never nullptr. - std::set referencers; + std::set referencers; }; // Map of symbol name to definition and references (files). @@ -86,22 +86,22 @@ struct FileDependencies { // The symbol table only needs to be built (.Build()), and need not be // Resolve()d. // Once initialized, all data members are const. - explicit FileDependencies(const SymbolTable& symbol_table); + explicit FileDependencies(const SymbolTable &symbol_table); bool Empty() const; // Visit every edge with a function. // This can print or export data. void TraverseDependencyEdges( - const std::function& edge_func) const; + const std::function &edge_func) const; - std::ostream& PrintGraph(std::ostream&) const; + std::ostream &PrintGraph(std::ostream &) const; // TODO: print unresolved references (no definition found) }; -std::ostream& operator<<(std::ostream&, const FileDependencies&); +std::ostream &operator<<(std::ostream &, const FileDependencies &); } // namespace verilog diff --git a/verilog/analysis/dependencies_test.cc b/verilog/analysis/dependencies_test.cc index a9e9c68ab..97c7f7c68 100644 --- a/verilog/analysis/dependencies_test.cc +++ b/verilog/analysis/dependencies_test.cc @@ -74,7 +74,7 @@ TEST(FileDependenciesTest, OneFileNoDeps) { "localparam int bar = foo + 1;\n", }; - for (const auto& code : kTestCases) { + for (const auto &code : kTestCases) { VLOG(1) << "code: " << code; VerilogProject project(sources_dir, {/* no include paths */}); @@ -122,11 +122,11 @@ TEST(FileDependenciesTest, TwoFilesNoDeps) { } struct SymbolTableDebug { - const SymbolTable& symbol_table; + const SymbolTable &symbol_table; }; -static std::ostream& operator<<(std::ostream& stream, - const SymbolTableDebug& p) { +static std::ostream &operator<<(std::ostream &stream, + const SymbolTableDebug &p) { stream << "Definitions:" << std::endl; p.symbol_table.PrintSymbolDefinitions(stream) << std::endl; stream << "References:" << std::endl; @@ -143,12 +143,12 @@ TEST(FileDependenciesTest, TwoFilesWithParamDepAtRootScope) { ScopedTestFile tf1(sources_dir, "localparam int zzz = 0;\n"); const auto status_or_file1 = project.OpenTranslationUnit(Basename(tf1.filename())); - const VerilogSourceFile* file1 = *status_or_file1; + const VerilogSourceFile *file1 = *status_or_file1; ScopedTestFile tf2(sources_dir, "localparam int yyy = zzz * 2;\n"); const auto status_or_file2 = project.OpenTranslationUnit(Basename(tf2.filename())); - const VerilogSourceFile* file2 = *status_or_file2; + const VerilogSourceFile *file2 = *status_or_file2; SymbolTable symbol_table(&project); std::vector build_diagnostics; @@ -184,14 +184,14 @@ TEST(FileDependenciesTest, TwoFilesWithParamDep) { "endpackage\n"); const auto status_or_file1 = project.OpenTranslationUnit(Basename(tf1.filename())); - const VerilogSourceFile* file1 = *status_or_file1; + const VerilogSourceFile *file1 = *status_or_file1; ScopedTestFile tf2(sources_dir, "localparam int bar = foo - 2;\n" "localparam int baz = p_pkg::goo;\n"); const auto status_or_file2 = project.OpenTranslationUnit(Basename(tf2.filename())); - const VerilogSourceFile* file2 = *status_or_file2; + const VerilogSourceFile *file2 = *status_or_file2; SymbolTable symbol_table(&project); std::vector build_diagnostics; @@ -225,14 +225,14 @@ TEST(FileDependenciesTest, TwoFilesWithCyclicDep) { "endpackage\n"); const auto status_or_file1 = project.OpenTranslationUnit(Basename(tf1.filename())); - const VerilogSourceFile* file1 = *status_or_file1; + const VerilogSourceFile *file1 = *status_or_file1; ScopedTestFile tf2(sources_dir, "localparam int bar = foo - 2;\n" "localparam int baz = p_pkg::goo;\n"); const auto status_or_file2 = project.OpenTranslationUnit(Basename(tf2.filename())); - const VerilogSourceFile* file2 = *status_or_file2; + const VerilogSourceFile *file2 = *status_or_file2; SymbolTable symbol_table(&project); std::vector build_diagnostics; @@ -277,7 +277,7 @@ TEST(FileDependenciesTest, ModuleDiamondDependencies) { "endmodule\n"); const auto mmm_status_or_file = project.OpenTranslationUnit(Basename(mmm.filename())); - const VerilogSourceFile* mmm_file = *mmm_status_or_file; + const VerilogSourceFile *mmm_file = *mmm_status_or_file; ScopedTestFile ppp(sources_dir, "module ppp;\n" @@ -285,7 +285,7 @@ TEST(FileDependenciesTest, ModuleDiamondDependencies) { "endmodule\n"); const auto ppp_status_or_file = project.OpenTranslationUnit(Basename(ppp.filename())); - const VerilogSourceFile* ppp_file = *ppp_status_or_file; + const VerilogSourceFile *ppp_file = *ppp_status_or_file; ScopedTestFile qqq(sources_dir, "module qqq;\n" @@ -293,7 +293,7 @@ TEST(FileDependenciesTest, ModuleDiamondDependencies) { "endmodule\n"); const auto qqq_status_or_file = project.OpenTranslationUnit(Basename(qqq.filename())); - const VerilogSourceFile* qqq_file = *qqq_status_or_file; + const VerilogSourceFile *qqq_file = *qqq_status_or_file; ScopedTestFile rrr(sources_dir, "module rrr;\n" @@ -301,7 +301,7 @@ TEST(FileDependenciesTest, ModuleDiamondDependencies) { "endmodule\n"); const auto rrr_status_or_file = project.OpenTranslationUnit(Basename(rrr.filename())); - const VerilogSourceFile* rrr_file = *rrr_status_or_file; + const VerilogSourceFile *rrr_file = *rrr_status_or_file; SymbolTable symbol_table(&project); std::vector build_diagnostics; diff --git a/verilog/analysis/extractors.cc b/verilog/analysis/extractors.cc index f0966e1cb..9f74bf10c 100644 --- a/verilog/analysis/extractors.cc +++ b/verilog/analysis/extractors.cc @@ -25,8 +25,8 @@ namespace analysis { // Find all modules and collect interface names absl::Status CollectInterfaceNames( - absl::string_view content, std::set* if_names, - const VerilogPreprocess::Config& preprocess_config) { + absl::string_view content, std::set *if_names, + const VerilogPreprocess::Config &preprocess_config) { VLOG(1) << __FUNCTION__; const auto analyzer = verilog::VerilogAnalyzer::AnalyzeAutomaticMode( @@ -40,16 +40,16 @@ absl::Status CollectInterfaceNames( // TODO: Having a syntax error may still result in a partial syntax tree // to work with. Currently, this utility has zero tolerance on syntax error. - const auto& syntax_tree = analyzer->SyntaxTree(); + const auto &syntax_tree = analyzer->SyntaxTree(); const auto mod_headers = FindAllModuleHeaders(*ABSL_DIE_IF_NULL(syntax_tree).get()); // For each module, collect all identifiers under the module // header tree into if_names. - for (const auto& mod_header : mod_headers) { + for (const auto &mod_header : mod_headers) { const auto if_leafs = FindAllSymbolIdentifierLeafs(*mod_header.match); - for (const auto& if_leaf_match : if_leafs) { - const auto& if_leaf = SymbolCastToLeaf(*if_leaf_match.match); + for (const auto &if_leaf_match : if_leafs) { + const auto &if_leaf = SymbolCastToLeaf(*if_leaf_match.match); absl::string_view if_name = if_leaf.get().text(); if_names->insert(std::string(if_name)); // TODO: use absl::string_view } diff --git a/verilog/analysis/extractors.h b/verilog/analysis/extractors.h index 52e3f2968..09b366358 100644 --- a/verilog/analysis/extractors.h +++ b/verilog/analysis/extractors.h @@ -33,8 +33,8 @@ namespace analysis { // This could be useful when interface names are required to be // preserved. absl::Status CollectInterfaceNames( - absl::string_view content, std::set* if_names, - const verilog::VerilogPreprocess::Config& preprocess_config); + absl::string_view content, std::set *if_names, + const verilog::VerilogPreprocess::Config &preprocess_config); } // namespace analysis } // namespace verilog diff --git a/verilog/analysis/json_diagnostics.cc b/verilog/analysis/json_diagnostics.cc index 0d333629a..cc67c85f5 100644 --- a/verilog/analysis/json_diagnostics.cc +++ b/verilog/analysis/json_diagnostics.cc @@ -32,7 +32,7 @@ namespace verilog { // Returns AnalysisPhase as JSON value. // Try not to change. External tools may use these values as a constant phase // IDs. -static json analysis_phase_to_json(const verible::AnalysisPhase& phase) { +static json analysis_phase_to_json(const verible::AnalysisPhase &phase) { switch (phase) { case verible::AnalysisPhase::kLexPhase: return "lex"; @@ -45,21 +45,21 @@ static json analysis_phase_to_json(const verible::AnalysisPhase& phase) { } } -json GetLinterTokenErrorsAsJson(const verilog::VerilogAnalyzer* analyzer, +json GetLinterTokenErrorsAsJson(const verilog::VerilogAnalyzer *analyzer, size_t limit) { json syntax_errors = json::array(); - const std::vector& rejected_tokens = + const std::vector &rejected_tokens = analyzer->GetRejectedTokens(); - for (const auto& rejected_token : rejected_tokens) { - json& error = syntax_errors.emplace_back(json::object()); + for (const auto &rejected_token : rejected_tokens) { + json &error = syntax_errors.emplace_back(json::object()); analyzer->ExtractLinterTokenErrorDetail( rejected_token, - [&error](const std::string& filename, LineColumnRange range, + [&error](const std::string &filename, LineColumnRange range, ErrorSeverity severity, AnalysisPhase phase, absl::string_view token_text, absl::string_view context_line, - const std::string& message) { + const std::string &message) { // TODO: should this do something different for severity = kWarning ? error["line"] = range.start.line; // NB: zero based index error["column"] = range.start.column; diff --git a/verilog/analysis/json_diagnostics.h b/verilog/analysis/json_diagnostics.h index 125a237b7..1e3cfedb4 100644 --- a/verilog/analysis/json_diagnostics.h +++ b/verilog/analysis/json_diagnostics.h @@ -23,7 +23,7 @@ namespace verilog { // Returns JSON list with information about errors. At most "limit" errors // are returned (zero means unlimited). nlohmann::json GetLinterTokenErrorsAsJson( - const verilog::VerilogAnalyzer* analyzer, size_t limit); + const verilog::VerilogAnalyzer *analyzer, size_t limit); } // namespace verilog diff --git a/verilog/analysis/json_diagnostics_test.cc b/verilog/analysis/json_diagnostics_test.cc index 1e94aafa6..efb2a81e9 100644 --- a/verilog/analysis/json_diagnostics_test.cc +++ b/verilog/analysis/json_diagnostics_test.cc @@ -25,8 +25,8 @@ namespace verilog { namespace { -static void CheckJsonErrorItem(const nlohmann::json& json, const char* phase, - const char* text) { +static void CheckJsonErrorItem(const nlohmann::json &json, const char *phase, + const char *text) { EXPECT_TRUE(json["column"].is_number()); EXPECT_TRUE(json["line"].is_number()); ASSERT_TRUE(json["phase"].is_string()); diff --git a/verilog/analysis/verilog_analyzer.h b/verilog/analysis/verilog_analyzer.h index 930e5434b..c81d2bbe7 100644 --- a/verilog/analysis/verilog_analyzer.h +++ b/verilog/analysis/verilog_analyzer.h @@ -34,13 +34,13 @@ class VerilogAnalyzer : public verible::FileAnalyzer { public: VerilogAnalyzer(std::shared_ptr text, absl::string_view name, - const VerilogPreprocess::Config& preprocess_config) + const VerilogPreprocess::Config &preprocess_config) : verible::FileAnalyzer(std::move(text), name), preprocess_config_(preprocess_config) {} // Legacy constructor. VerilogAnalyzer(absl::string_view text, absl::string_view name, - const VerilogPreprocess::Config& preprocess_config) + const VerilogPreprocess::Config &preprocess_config) : verible::FileAnalyzer(text, name), preprocess_config_(preprocess_config) {} @@ -49,8 +49,8 @@ class VerilogAnalyzer : public verible::FileAnalyzer { VerilogAnalyzer(absl::string_view text, absl::string_view name) : VerilogAnalyzer(text, name, VerilogPreprocess::Config()) {} - VerilogAnalyzer(const VerilogAnalyzer&) = delete; - VerilogAnalyzer(VerilogAnalyzer&&) = delete; + VerilogAnalyzer(const VerilogAnalyzer &) = delete; + VerilogAnalyzer(VerilogAnalyzer &&) = delete; // Lex-es the input text into tokens. absl::Status Tokenize() final; @@ -73,12 +73,12 @@ class VerilogAnalyzer : public verible::FileAnalyzer { // Automatically analyze with the correct parsing mode, as detected // by parser directive comments. static std::unique_ptr AnalyzeAutomaticMode( - const std::shared_ptr& text, absl::string_view name, - const VerilogPreprocess::Config& preprocess_config); + const std::shared_ptr &text, absl::string_view name, + const VerilogPreprocess::Config &preprocess_config); static std::unique_ptr AnalyzeAutomaticMode( absl::string_view text, absl::string_view name, - const VerilogPreprocess::Config& preprocess_config); + const VerilogPreprocess::Config &preprocess_config); // Automatically analyze with correct parsing mode like AnalyzeAutomaticMode() // but attempt first with preprocessor disabled to get as complete as @@ -87,7 +87,7 @@ class VerilogAnalyzer : public verible::FileAnalyzer { static std::unique_ptr AnalyzeAutomaticPreprocessFallback( absl::string_view text, absl::string_view name); - const VerilogPreprocessData& PreprocessorData() const { + const VerilogPreprocessData &PreprocessorData() const { return preprocessor_data_; } @@ -104,7 +104,7 @@ class VerilogAnalyzer : public verible::FileAnalyzer { // // verilog_syntax: mode-x // results in "mode-x". static absl::string_view ScanParsingModeDirective( - const verible::TokenSequence& raw_tokens); + const verible::TokenSequence &raw_tokens); // Special string inside a comment that triggers setting parsing mode. static constexpr absl::string_view kParseDirectiveName = "verilog_syntax:"; diff --git a/verilog/analysis/verilog_equivalence.cc b/verilog/analysis/verilog_equivalence.cc index 230c0fcdb..41f9de361 100644 --- a/verilog/analysis/verilog_equivalence.cc +++ b/verilog/analysis/verilog_equivalence.cc @@ -42,7 +42,7 @@ using verible::TokenSequence; // TODO(fangism): majority of this code is not Verilog-specific and could // be factored into a common/analysis library. -static const verible::EnumNameMap& DiffStatusStringMap() { +static const verible::EnumNameMap &DiffStatusStringMap() { static const verible::EnumNameMap kDiffStatusStringMap({ {"equivalent", DiffStatus::kEquivalent}, {"different", DiffStatus::kDifferent}, @@ -52,22 +52,22 @@ static const verible::EnumNameMap& DiffStatusStringMap() { return kDiffStatusStringMap; } -std::ostream& operator<<(std::ostream& stream, DiffStatus status) { +std::ostream &operator<<(std::ostream &stream, DiffStatus status) { return DiffStatusStringMap().Unparse(status, stream); } // Lex a token into smaller substrings/subtokens. // Lexical errors are reported to errstream. // Returns true if lexing succeeded, false on error. -static bool LexText(absl::string_view text, TokenSequence* subtokens, - std::ostream* errstream) { +static bool LexText(absl::string_view text, TokenSequence *subtokens, + std::ostream *errstream) { VLOG(1) << __FUNCTION__; VerilogLexer lexer(text); // Reservation slot to capture first error token, if any. auto err_tok = TokenInfo::EOFToken(text); // Lex token's text into subtokens. const auto status = MakeTokenSequence( - &lexer, text, subtokens, [&](const TokenInfo& err) { err_tok = err; }); + &lexer, text, subtokens, [&](const TokenInfo &err) { err_tok = err; }); if (!status.ok()) { VLOG(1) << "lex error on: " << err_tok; if (errstream != nullptr) { @@ -81,24 +81,24 @@ static bool LexText(absl::string_view text, TokenSequence* subtokens, return true; } -static void VerilogTokenPrinter(const TokenInfo& token, std::ostream& stream) { +static void VerilogTokenPrinter(const TokenInfo &token, std::ostream &stream) { stream << '(' << verilog_symbol_name(token.token_enum()) << ") " << token; } -static bool ShouldRecursivelyAnalyzeToken(const TokenInfo& token) { +static bool ShouldRecursivelyAnalyzeToken(const TokenInfo &token) { return IsUnlexed(verilog_tokentype(token.token_enum())); } DiffStatus VerilogLexicallyEquivalent( absl::string_view left, absl::string_view right, - const std::function& remove_predicate, - const std::function& equal_comparator, - std::ostream* errstream) { + const std::function &remove_predicate, + const std::function &equal_comparator, + std::ostream *errstream) { // Bind some Verilog-specific parameters. return LexicallyEquivalent( left, right, - [=](absl::string_view text, TokenSequence* tokens) { + [=](absl::string_view text, TokenSequence *tokens) { return LexText(text, tokens, errstream); }, ShouldRecursivelyAnalyzeToken, // @@ -110,14 +110,14 @@ DiffStatus VerilogLexicallyEquivalent( DiffStatus LexicallyEquivalent( absl::string_view left_text, absl::string_view right_text, - const std::function& lexer, - const std::function& recursion_predicate, - const std::function& remove_predicate, - const std::function& equal_comparator, - const std::function& - token_printer, - std::ostream* errstream) { + const std::function &lexer, + const std::function &recursion_predicate, + const std::function &remove_predicate, + const std::function &equal_comparator, + const std::function + &token_printer, + std::ostream *errstream) { VLOG(2) << __FUNCTION__; // Lex texts into token sequences. verible::TokenSequence left_tokens, right_tokens; @@ -142,7 +142,7 @@ DiffStatus LexicallyEquivalent( verible::TokenStreamView left_filtered, right_filtered; verible::InitTokenStreamView(left_tokens, &left_filtered); verible::InitTokenStreamView(right_tokens, &right_filtered); - verible::TokenFilterPredicate keep_predicate = [&](const TokenInfo& t) { + verible::TokenFilterPredicate keep_predicate = [&](const TokenInfo &t) { return !remove_predicate(t); }; verible::FilterTokenStreamViewInPlace(keep_predicate, &left_filtered); @@ -230,8 +230,8 @@ DiffStatus LexicallyEquivalent( if (errstream != nullptr) { const size_t mismatch_index = std::distance(left_filtered.begin(), mismatch_pair.first); - const auto& left_token = **mismatch_pair.first; - const auto& right_token = **mismatch_pair.second; + const auto &left_token = **mismatch_pair.first; + const auto &right_token = **mismatch_pair.second; *errstream << "First mismatched token [" << mismatch_index << "]: "; token_printer(left_token, *errstream); *errstream << " vs. "; @@ -243,13 +243,13 @@ DiffStatus LexicallyEquivalent( } DiffStatus FormatEquivalent(absl::string_view left, absl::string_view right, - std::ostream* errstream) { + std::ostream *errstream) { return VerilogLexicallyEquivalent( left, right, - [](const TokenInfo& t) { + [](const TokenInfo &t) { return IsWhitespace(verilog_tokentype(t.token_enum())); }, - [=](const TokenInfo& l, const TokenInfo& r) { + [=](const TokenInfo &l, const TokenInfo &r) { // MacroCallCloseToEndLine should be considered equivalent to ')', as // they are whitespace dependant if (((r.token_enum() == verilog_tokentype::MacroCallCloseToEndLine) && @@ -263,8 +263,8 @@ DiffStatus FormatEquivalent(absl::string_view left, absl::string_view right, errstream); } -static bool ObfuscationEquivalentTokens(const TokenInfo& l, - const TokenInfo& r) { +static bool ObfuscationEquivalentTokens(const TokenInfo &l, + const TokenInfo &r) { const auto l_vtoken_enum = verilog_tokentype(l.token_enum()); if (IsIdentifierLike(l_vtoken_enum)) { return l.EquivalentBySpace(r); @@ -274,10 +274,10 @@ static bool ObfuscationEquivalentTokens(const TokenInfo& l, DiffStatus ObfuscationEquivalent(absl::string_view left, absl::string_view right, - std::ostream* errstream) { + std::ostream *errstream) { return VerilogLexicallyEquivalent( left, right, - [](const TokenInfo&) { + [](const TokenInfo &) { // Whitespaces are required to match exactly. return false; }, diff --git a/verilog/analysis/verilog_equivalence.h b/verilog/analysis/verilog_equivalence.h index 9bb5dc741..ff9056b8c 100644 --- a/verilog/analysis/verilog_equivalence.h +++ b/verilog/analysis/verilog_equivalence.h @@ -32,7 +32,7 @@ enum class DiffStatus { kRightError, // some error processing right input }; -std::ostream& operator<<(std::ostream&, DiffStatus); +std::ostream &operator<<(std::ostream &, DiffStatus); // Compares two strings for equivalence. // Returns a DiffStatus that captures 'equivalence' ignoring tokens filtered @@ -46,30 +46,30 @@ std::ostream& operator<<(std::ostream&, DiffStatus); // TODO(fangism): move this to language-agnostic common/analysis library. DiffStatus LexicallyEquivalent( absl::string_view left, absl::string_view right, - const std::function& - lexer, - const std::function& recursion_predicate, - const std::function& remove_predicate, - const std::function& equal_comparator, - const std::function& - token_printer, - std::ostream* errstream = nullptr); + const std::function + &lexer, + const std::function &recursion_predicate, + const std::function &remove_predicate, + const std::function &equal_comparator, + const std::function + &token_printer, + std::ostream *errstream = nullptr); // Returns a DiffStatus that captures 'equivalence' ignoring tokens filtered // out by remove_predicate, and using the equal_comparator binary predicate. // If errstream is provided, print detailed error message to that stream. DiffStatus VerilogLexicallyEquivalent( absl::string_view left, absl::string_view right, - const std::function& remove_predicate, - const std::function& equal_comparator, - std::ostream* errstream = nullptr); + const std::function &remove_predicate, + const std::function &equal_comparator, + std::ostream *errstream = nullptr); // Returns true if both token sequences are equivalent, ignoring whitespace. // If errstream is provided, print detailed error message to that stream. DiffStatus FormatEquivalent(absl::string_view left, absl::string_view right, - std::ostream* errstream = nullptr); + std::ostream *errstream = nullptr); // Similar to FormatEquivalent except that: // 1) whitespaces must match @@ -78,7 +78,7 @@ DiffStatus FormatEquivalent(absl::string_view left, absl::string_view right, // Such equivalence is good for formatter test cases. DiffStatus ObfuscationEquivalent(absl::string_view left, absl::string_view right, - std::ostream* errstream = nullptr); + std::ostream *errstream = nullptr); } // namespace verilog diff --git a/verilog/analysis/verilog_equivalence_test.cc b/verilog/analysis/verilog_equivalence_test.cc index 8ea625737..aa4f0c592 100644 --- a/verilog/analysis/verilog_equivalence_test.cc +++ b/verilog/analysis/verilog_equivalence_test.cc @@ -63,9 +63,9 @@ static DiffStatus FlipStatus(DiffStatus status) { static void ExpectCompareWithErrstream( const std::function& func, + std::ostream *)> &func, DiffStatus expect_compare, absl::string_view left, absl::string_view right, - std::ostream* errstream = &std::cout) { + std::ostream *errstream = &std::cout) { EXPECT_EQ(func(left, right, errstream), expect_compare) << "left:\n" << left << "\nright:\n" @@ -78,7 +78,7 @@ static void ExpectCompareWithErrstream( } TEST(FormatEquivalentTest, Spaces) { - const std::vector kTestCases = { + const std::vector kTestCases = { "", " ", "\n", @@ -93,7 +93,7 @@ TEST(FormatEquivalentTest, Spaces) { } TEST(FormatEquivalentTest, ShortSequences) { - const char* kTestCases[] = { + const char *kTestCases[] = { "1", "2", "1;", @@ -114,7 +114,7 @@ TEST(FormatEquivalentTest, ShortSequences) { } TEST(FormatEquivalentTest, Identifiers) { - const char* kTestCases[] = { + const char *kTestCases[] = { "foo bar;", " foo\t\tbar ; ", "foobar;", // only 2 tokens @@ -135,7 +135,7 @@ TEST(FormatEquivalentTest, Identifiers) { } TEST(FormatEquivalentTest, Keyword) { - const char* kTestCases[] = { + const char *kTestCases[] = { "wire foo;", " wire \n\t\t foo ;\n", }; @@ -144,7 +144,7 @@ TEST(FormatEquivalentTest, Keyword) { } TEST(FormatEquivalentTest, Comments) { - const char* kTestCases[] = { + const char *kTestCases[] = { "// comment1\n", // "// comment1 \n", // "// comment1\n", // @@ -171,7 +171,7 @@ TEST(FormatEquivalentTest, Comments) { } TEST(FormatEquivalentTest, DiagnosticLength) { - const char* kTestCases[] = { + const char *kTestCases[] = { "module foo\n", "module foo;\n", }; @@ -239,7 +239,7 @@ TEST(FormatEquivalentTest, MismatchTokenType) { } TEST(FormatEquivalentTest, EquivalenceOfRightParen) { - const char* kTestCases[] = { + const char *kTestCases[] = { "{`FOO()\n}\n", "{`FOO()}\n", "{`FOO()()}\n", @@ -258,7 +258,7 @@ TEST(FormatEquivalentTest, EquivalenceOfRightParen) { } TEST(FormatEquivalentTest, DiagnosticMismatch) { - const char* kTestCases[] = { + const char *kTestCases[] = { "module foo;\n", "module bar;\n", "module foo,\n", @@ -479,7 +479,7 @@ TEST(ObfuscationEquivalentTest, Various) { {"`CAT(aa``bb, cc``dd)\n", "`DOG(jj``kk, ll``mms)\n", DiffStatus::kDifferent}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { ExpectCompareWithErrstream(ObfuscationEquivalent, test.expect_match, test.before, test.after); } diff --git a/verilog/analysis/verilog_excerpt_parse.cc b/verilog/analysis/verilog_excerpt_parse.cc index 3a7fd7647..bef94a828 100644 --- a/verilog/analysis/verilog_excerpt_parse.cc +++ b/verilog/analysis/verilog_excerpt_parse.cc @@ -50,7 +50,7 @@ using verible::container::FindOrNull; static std::unique_ptr AnalyzeVerilogConstruct( absl::string_view prolog, absl::string_view text, absl::string_view epilog, absl::string_view filename, - const VerilogPreprocess::Config& preprocess_config) { + const VerilogPreprocess::Config &preprocess_config) { VLOG(2) << __FUNCTION__; CHECK(epilog.empty() || absl::ascii_isspace(epilog[0])) << "epilog text must begin with a whitespace to prevent unintentional " @@ -80,7 +80,7 @@ static std::unique_ptr AnalyzeVerilogConstruct( std::unique_ptr AnalyzeVerilogPropertySpec( absl::string_view text, absl::string_view filename, - const VerilogPreprocess::Config& preprocess_config) { + const VerilogPreprocess::Config &preprocess_config) { return AnalyzeVerilogConstruct("module foo;\nproperty p;\n", text, "\nendproperty;\nendmodule;\n", filename, preprocess_config); @@ -88,14 +88,14 @@ std::unique_ptr AnalyzeVerilogPropertySpec( std::unique_ptr AnalyzeVerilogStatements( absl::string_view text, absl::string_view filename, - const VerilogPreprocess::Config& preprocess_config) { + const VerilogPreprocess::Config &preprocess_config) { return AnalyzeVerilogConstruct("function foo();\n", text, "\nendfunction\n", filename, preprocess_config); } std::unique_ptr AnalyzeVerilogExpression( absl::string_view text, absl::string_view filename, - const VerilogPreprocess::Config& preprocess_config) { + const VerilogPreprocess::Config &preprocess_config) { return AnalyzeVerilogConstruct("module foo;\nif (", text, " ) $error;\nendmodule\n", filename, preprocess_config); @@ -107,28 +107,28 @@ std::unique_ptr AnalyzeVerilogExpression( std::unique_ptr AnalyzeVerilogModuleBody( absl::string_view text, absl::string_view filename, - const VerilogPreprocess::Config& preprocess_config) { + const VerilogPreprocess::Config &preprocess_config) { return AnalyzeVerilogConstruct("module foo;\n", text, "\nendmodule\n", filename, preprocess_config); } std::unique_ptr AnalyzeVerilogClassBody( absl::string_view text, absl::string_view filename, - const VerilogPreprocess::Config& preprocess_config) { + const VerilogPreprocess::Config &preprocess_config) { return AnalyzeVerilogConstruct("class foo;\n", text, "\nendclass\n", filename, preprocess_config); } std::unique_ptr AnalyzeVerilogPackageBody( absl::string_view text, absl::string_view filename, - const VerilogPreprocess::Config& preprocess_config) { + const VerilogPreprocess::Config &preprocess_config) { return AnalyzeVerilogConstruct("package foo;\n", text, "\nendpackage\n", filename, preprocess_config); } std::unique_ptr AnalyzeVerilogLibraryMap( absl::string_view text, absl::string_view filename, - const VerilogPreprocess::Config& preprocess_config) { + const VerilogPreprocess::Config &preprocess_config) { // The prolog/epilog strings come from verilog.lex as token enums: // PD_LIBRARY_SYNTAX_BEGIN and PD_LIBRARY_SYNTAX_END. // These are used in verilog.y to enclose the complete library_description @@ -140,12 +140,12 @@ std::unique_ptr AnalyzeVerilogLibraryMap( std::unique_ptr AnalyzeVerilogWithMode( absl::string_view text, absl::string_view filename, absl::string_view mode, - const VerilogPreprocess::Config& preprocess_config) { - static const auto* func_map = + const VerilogPreprocess::Config &preprocess_config) { + static const auto *func_map = new std::map( absl::string_view, absl::string_view, - const VerilogPreprocess::Config&)>>{ + const VerilogPreprocess::Config &)>>{ {"parse-as-statements", &AnalyzeVerilogStatements}, {"parse-as-expression", &AnalyzeVerilogExpression}, {"parse-as-module-body", &AnalyzeVerilogModuleBody}, @@ -154,7 +154,7 @@ std::unique_ptr AnalyzeVerilogWithMode( {"parse-as-property-spec", &AnalyzeVerilogPropertySpec}, {"parse-as-library-map", &AnalyzeVerilogLibraryMap}, }; - const auto* func_ptr = FindOrNull(*func_map, mode); + const auto *func_ptr = FindOrNull(*func_map, mode); if (!func_ptr) return nullptr; return (*func_ptr)(text, filename, preprocess_config); } diff --git a/verilog/analysis/verilog_excerpt_parse.h b/verilog/analysis/verilog_excerpt_parse.h index a610da2a1..cc944de69 100644 --- a/verilog/analysis/verilog_excerpt_parse.h +++ b/verilog/analysis/verilog_excerpt_parse.h @@ -37,44 +37,44 @@ namespace verilog { // Analyzes test as Verilog property_spec std::unique_ptr AnalyzeVerilogPropertySpec( absl::string_view text, absl::string_view filename, - const VerilogPreprocess::Config& preprocess_config); + const VerilogPreprocess::Config &preprocess_config); // Analyzes text as Verilog statements. std::unique_ptr AnalyzeVerilogStatements( absl::string_view text, absl::string_view filename, - const VerilogPreprocess::Config& preprocess_config); + const VerilogPreprocess::Config &preprocess_config); // Analyzes text as any Verilog expression. std::unique_ptr AnalyzeVerilogExpression( absl::string_view text, absl::string_view filename, - const VerilogPreprocess::Config& preprocess_config); + const VerilogPreprocess::Config &preprocess_config); // Analyzes text as any Verilog module body. std::unique_ptr AnalyzeVerilogModuleBody( absl::string_view text, absl::string_view filename, - const VerilogPreprocess::Config& preprocess_config); + const VerilogPreprocess::Config &preprocess_config); // Analyzes text as any Verilog class body. std::unique_ptr AnalyzeVerilogClassBody( absl::string_view text, absl::string_view filename, - const VerilogPreprocess::Config& preprocess_config); + const VerilogPreprocess::Config &preprocess_config); // Analyzes text as any Verilog package body. std::unique_ptr AnalyzeVerilogPackageBody( absl::string_view text, absl::string_view filename, - const VerilogPreprocess::Config& preprocess_config); + const VerilogPreprocess::Config &preprocess_config); // TODO(fangism): analogous functions for: function, task, ... // Analyzes text as any Verilog library map. std::unique_ptr AnalyzeVerilogLibraryMap( absl::string_view text, absl::string_view filename, - const VerilogPreprocess::Config& preprocess_config); + const VerilogPreprocess::Config &preprocess_config); // Analyzes text in the selected parsing `mode`. std::unique_ptr AnalyzeVerilogWithMode( absl::string_view text, absl::string_view filename, absl::string_view mode, - const VerilogPreprocess::Config& preprocess_config); + const VerilogPreprocess::Config &preprocess_config); } // namespace verilog diff --git a/verilog/analysis/verilog_filelist.cc b/verilog/analysis/verilog_filelist.cc index 36b428e13..1b03b736c 100644 --- a/verilog/analysis/verilog_filelist.cc +++ b/verilog/analysis/verilog_filelist.cc @@ -29,8 +29,8 @@ namespace verilog { absl::Status AppendFileListFromContent(absl::string_view file_list_path, - const std::string& file_list_content, - FileList* append_to) { + const std::string &file_list_content, + FileList *append_to) { constexpr absl::string_view kIncludeDirPrefix = "+incdir+"; constexpr absl::string_view kDefineMacroPrefix = "+define+"; append_to->preprocessing.include_dirs.emplace_back( @@ -79,14 +79,14 @@ absl::Status AppendFileListFromContent(absl::string_view file_list_path, } absl::Status AppendFileListFromFile(absl::string_view file_list_file, - FileList* append_to) { + FileList *append_to) { auto content_or = verible::file::GetContentAsString(file_list_file); if (!content_or.ok()) return content_or.status(); return AppendFileListFromContent(file_list_file, *content_or, append_to); } absl::Status AppendFileListFromCommandline( - const std::vector& cmdline, FileList* append_to) { + const std::vector &cmdline, FileList *append_to) { for (absl::string_view argument : cmdline) { if (argument.empty()) continue; if (argument[0] != '+') { @@ -141,7 +141,7 @@ absl::Status AppendFileListFromCommandline( std::string FileList::ToString() const { std::stringstream buffer; - for (const auto& definition : preprocessing.defines) { + for (const auto &definition : preprocessing.defines) { buffer << "+define+" << definition.name << "=" << definition.value << '\n'; } for (absl::string_view include : preprocessing.include_dirs) { diff --git a/verilog/analysis/verilog_filelist.h b/verilog/analysis/verilog_filelist.h index 35bb58492..028b22a0c 100644 --- a/verilog/analysis/verilog_filelist.h +++ b/verilog/analysis/verilog_filelist.h @@ -30,7 +30,7 @@ struct TextMacroDefinition { std::string name; std::string value; - bool operator==(const TextMacroDefinition& other) const { + bool operator==(const TextMacroDefinition &other) const { return name == other.name && value == other.value; } }; @@ -75,19 +75,19 @@ struct FileList { // always possible to pinpoint back to the owning string view in case we want // to provide detailed error messages. absl::Status AppendFileListFromFile(absl::string_view file_list_file, - FileList* append_to); + FileList *append_to); // Reads in a list of files line-by-line from the given string. The include // directories are prefixed by "+incdir+" (TODO: +define+) absl::Status AppendFileListFromContent(absl::string_view file_list_path, - const std::string& file_list_content, - FileList* append_to); + const std::string &file_list_content, + FileList *append_to); // Parse positional parameters from command line and extract files, // +incdir+ and +define+ and appends to FileList. // TODO: Also support --file_list_path (and -f), --file_list_root absl::Status AppendFileListFromCommandline( - const std::vector& cmdline, FileList* append_to); + const std::vector &cmdline, FileList *append_to); } // namespace verilog #endif // VERIBLE_VERILOG_ANALYSIS_VERILOG_FILELIST_H_ diff --git a/verilog/analysis/verilog_filelist_test.cc b/verilog/analysis/verilog_filelist_test.cc index f1ae4a633..d945b642a 100644 --- a/verilog/analysis/verilog_filelist_test.cc +++ b/verilog/analysis/verilog_filelist_test.cc @@ -58,7 +58,7 @@ TEST(FileListTest, AppendFileListFromInvalidCommandline) { {"+define+"}, {"+not_valid_define+"}, {"+foobar+baz"}}; - for (const auto& cmdline : test_cases) { + for (const auto &cmdline : test_cases) { FileList result; auto status = AppendFileListFromCommandline(cmdline, &result); EXPECT_FALSE(status.ok()); diff --git a/verilog/analysis/verilog_linter_configuration.h b/verilog/analysis/verilog_linter_configuration.h index 78e9f9d90..dc4a90a83 100644 --- a/verilog/analysis/verilog_linter_configuration.h +++ b/verilog/analysis/verilog_linter_configuration.h @@ -49,13 +49,13 @@ enum class RuleSet { kNone, kDefault, kAll }; // // AbslUnparseFlag takes the parsed representation of a ruleset // and converts it into string representation. -std::string AbslUnparseFlag(const RuleSet& rules); +std::string AbslUnparseFlag(const RuleSet &rules); // ParseFlags takes a source string text and a target Ruleset. // It attempts to parse text into a RuleSet and put that RuleSet into rules // If successful, returns true. // Otherwise, sets string error to the a error message and returns false. -bool AbslParseFlag(absl::string_view text, RuleSet* rules, std::string* error); +bool AbslParseFlag(absl::string_view text, RuleSet *rules, std::string *error); // Container class for parse/unparse flags // Keys must be the exact string_views in registered maps (not just string @@ -65,7 +65,7 @@ struct RuleBundle { // Parse configuration from input. Separator between rules is 'separator', // typically that would be a comma or newline. bool ParseConfiguration(absl::string_view text, char separator, - std::string* error); + std::string *error); std::string UnparseConfiguration(char separator) const; }; @@ -74,7 +74,7 @@ struct RuleBundle { // // AbslUnparseFlag takes the parsed representation of a flag (RuleBundle) // and converts it into string representation. -std::string AbslUnparseFlag(const RuleBundle& bundle); +std::string AbslUnparseFlag(const RuleBundle &bundle); // ParseFlags takes a source string text and a target RuleBundle. // It clears bundle and parses text into it by checking to make sure @@ -84,8 +84,8 @@ std::string AbslUnparseFlag(const RuleBundle& bundle); // If all rules are parsed successfully, returns true. // Otherwise, sets string error to the a error message containing the // invalid lint rule and returns false. -bool AbslParseFlag(absl::string_view text, RuleBundle* bundle, - std::string* error); +bool AbslParseFlag(absl::string_view text, RuleBundle *bundle, + std::string *error); // ProjectPolicy is needed in a transitional period when new rules are // becoming enabled while pre-existing code is still following their @@ -98,30 +98,30 @@ struct ProjectPolicy { // Raw string to check for being part of the path. Not a regex pattern. // Apply this exemption only if substring occurs in the file path. - std::vector path_substrings; + std::vector path_substrings; // Raw string to check for being part of the path. Not a regex pattern. // Files that match the exclusion will not be analyzed. // This is suitable for paths that contain files that no human will ever // read. - std::vector path_exclusions; + std::vector path_exclusions; // Reviewers to involve for policy changes. At least two. - std::vector owners; + std::vector owners; // Names of lint rules to disable. - std::vector disabled_rules; + std::vector disabled_rules; // Names of lint rules to enable (takes precedence over disabled_rules). - std::vector enabled_rules; + std::vector enabled_rules; // Returns a path if filename matches any of path_substrings, // otherwise nullptr. - const char* MatchesAnyPath(absl::string_view filename) const; + const char *MatchesAnyPath(absl::string_view filename) const; // Returns a path if filename matches any of path_exclusions, // otherwise nullptr. - const char* MatchesAnyExclusions(absl::string_view filename) const; + const char *MatchesAnyExclusions(absl::string_view filename) const; // Returns true if all disabled_rules and enabled_rules refer to registered // rules. This helps catch typos. @@ -139,7 +139,7 @@ struct LinterOptions { // The base set of rules used by linter const RuleSet ruleset; // Bundle of rules to enable/disable in addition to the base set - const RuleBundle& rules; + const RuleBundle &rules; // Path to a file with extra linter configuration, applied on top of the // base 'ruleset' and extra 'rules' std::string config_file; @@ -169,17 +169,17 @@ class LinterConfiguration { LinterConfiguration() = default; // This is copy-able. - LinterConfiguration(const LinterConfiguration&) = default; + LinterConfiguration(const LinterConfiguration &) = default; - void TurnOn(const analysis::LintRuleId& rule) { + void TurnOn(const analysis::LintRuleId &rule) { configuration_[rule] = {true, ""}; } - void TurnOff(const analysis::LintRuleId& rule) { + void TurnOff(const analysis::LintRuleId &rule) { configuration_[rule] = {false, ""}; } - bool RuleIsOn(const analysis::LintRuleId& rule) const; + bool RuleIsOn(const analysis::LintRuleId &rule) const; // Clears configuration and updates to passed ruleset. // Behavior is as follows: @@ -190,14 +190,14 @@ class LinterConfiguration { // // Note that additional rules can be layered on top of a ruleset via // TurnOn/TurnOff/UseRuleBundle. - void UseRuleSet(const RuleSet& rules); + void UseRuleSet(const RuleSet &rules); // Updates LinterConfiguration to enabled/disable all lint rules // in rule_bundle - void UseRuleBundle(const RuleBundle& rule_bundle); + void UseRuleBundle(const RuleBundle &rule_bundle); // Adjust set of active rules based on the filename. - void UseProjectPolicy(const ProjectPolicy& policy, + void UseProjectPolicy(const ProjectPolicy &policy, absl::string_view filename); // Return the keys of enabled lint rules, sorted. @@ -223,22 +223,22 @@ class LinterConfiguration { std::string external_waivers; // Returns true if configurations are equivalent. - bool operator==(const LinterConfiguration&) const; + bool operator==(const LinterConfiguration &) const; - bool operator!=(const LinterConfiguration& r) const { return !(*this == r); } + bool operator!=(const LinterConfiguration &r) const { return !(*this == r); } // Appends linter rules configuration from a file absl::Status AppendFromFile(absl::string_view filename); // Generates configuration forn LinterOptions - absl::Status ConfigureFromOptions(const LinterOptions& options); + absl::Status ConfigureFromOptions(const LinterOptions &options); private: // map of all enabled rules std::map configuration_; }; -std::ostream& operator<<(std::ostream&, const LinterConfiguration&); +std::ostream &operator<<(std::ostream &, const LinterConfiguration &); } // namespace verilog diff --git a/verilog/analysis/verilog_project.h b/verilog/analysis/verilog_project.h index 0482816b6..24210e55e 100644 --- a/verilog/analysis/verilog_project.h +++ b/verilog/analysis/verilog_project.h @@ -45,14 +45,14 @@ class VerilogSourceFile { // When a file is not found among a set of paths, remember it with an // error status. VerilogSourceFile(absl::string_view referenced_path, - const absl::Status& status); + const absl::Status &status); - VerilogSourceFile(const VerilogSourceFile&) = delete; - VerilogSourceFile& operator=(const VerilogSourceFile&) = delete; + VerilogSourceFile(const VerilogSourceFile &) = delete; + VerilogSourceFile &operator=(const VerilogSourceFile &) = delete; - VerilogSourceFile(VerilogSourceFile&&) = + VerilogSourceFile(VerilogSourceFile &&) = default; // need for std::map::emplace - VerilogSourceFile& operator=(VerilogSourceFile&&) = delete; + VerilogSourceFile &operator=(VerilogSourceFile &&) = delete; virtual ~VerilogSourceFile() = default; @@ -76,7 +76,7 @@ class VerilogSourceFile { // After Parse(), text structure may contain other analyzed structural forms. // Before successful Parse(), this is not initialized and returns nullptr. - virtual const verible::TextStructureView* GetTextStructure() const; + virtual const verible::TextStructureView *GetTextStructure() const; // Returns the first non-Ok status if there is one, else OkStatus(). absl::Status Status() const { return status_; } @@ -101,10 +101,10 @@ class VerilogSourceFile { using is_transparent = void; // hetergenous compare static absl::string_view to_string_view(absl::string_view s) { return s; } - static absl::string_view to_string_view(const VerilogSourceFile& f) { + static absl::string_view to_string_view(const VerilogSourceFile &f) { return f.ReferencedPath(); } - static absl::string_view to_string_view(const VerilogSourceFile* f) { + static absl::string_view to_string_view(const VerilogSourceFile *f) { return f->ReferencedPath(); } @@ -162,7 +162,7 @@ class VerilogSourceFile { }; // Printable representation for debugging. -std::ostream& operator<<(std::ostream&, const VerilogSourceFile&); +std::ostream &operator<<(std::ostream &, const VerilogSourceFile &); // An in-memory source file that doesn't require file-system access, // nor create temporary files. @@ -196,7 +196,7 @@ class ParsedVerilogSourceFile final : public VerilogSourceFile { // it sets referenced_path and resolved_path based on URI from language server ParsedVerilogSourceFile(absl::string_view referenced_path, absl::string_view resolved_path, - const verible::TextStructureView* text_structure, + const verible::TextStructureView *text_structure, absl::string_view corpus = "") : VerilogSourceFile(referenced_path, resolved_path, corpus), text_structure_(text_structure) {} @@ -207,7 +207,7 @@ class ParsedVerilogSourceFile final : public VerilogSourceFile { // copy of it and expects it will be available for the lifetime of // object of this class. ParsedVerilogSourceFile(absl::string_view filename, - const verible::TextStructureView* text_structure, + const verible::TextStructureView *text_structure, absl::string_view corpus = "") : VerilogSourceFile(filename, filename, corpus), text_structure_(text_structure) {} @@ -219,14 +219,14 @@ class ParsedVerilogSourceFile final : public VerilogSourceFile { absl::Status Parse() final; // Return TextStructureView provided previously in constructor - const verible::TextStructureView* GetTextStructure() const final; + const verible::TextStructureView *GetTextStructure() const final; absl::string_view GetContent() const final { return text_structure_->Contents(); } private: - const verible::TextStructureView* const text_structure_; + const verible::TextStructureView *const text_structure_; }; // VerilogProject represents a set of files as a cohesive unit of compilation. @@ -248,7 +248,7 @@ class VerilogProject { // view maps) fragments the class's usage. Enabling it prevents removing files // from the project (which is required for Kythe facts extraction). VerilogProject(absl::string_view root, - const std::vector& include_paths, + const std::vector &include_paths, absl::string_view corpus = "", bool populate_string_maps = true) : translation_unit_root_(root), @@ -256,10 +256,10 @@ class VerilogProject { corpus_(corpus), populate_string_maps_(populate_string_maps) {} - VerilogProject(const VerilogProject&) = delete; - VerilogProject(VerilogProject&&) = delete; - VerilogProject& operator=(const VerilogProject&) = delete; - VerilogProject& operator=(VerilogProject&&) = delete; + VerilogProject(const VerilogProject &) = delete; + VerilogProject(VerilogProject &&) = delete; + VerilogProject &operator=(const VerilogProject &) = delete; + VerilogProject &operator=(VerilogProject &&) = delete; const_iterator begin() const { return files_.begin(); } iterator begin() { return files_.begin(); } @@ -277,12 +277,12 @@ class VerilogProject { // Opens a single top-level file, known as a "translation unit". // This uses translation_unit_root_ directory to calculate the file's path. // If the file was previously opened, that data is returned. - absl::StatusOr OpenTranslationUnit( + absl::StatusOr OpenTranslationUnit( absl::string_view referenced_filename); // Opens a file that was `included. // If the file was previously opened, that data is returned. - absl::StatusOr OpenIncludedFile( + absl::StatusOr OpenIncludedFile( absl::string_view referenced_filename); // Adds an already opened file by directly passing its content. @@ -291,7 +291,7 @@ class VerilogProject { absl::string_view content); // Returns a previously referenced file, or else nullptr. - VerilogSourceFile* LookupRegisteredFile( + VerilogSourceFile *LookupRegisteredFile( absl::string_view referenced_filename) { return LookupRegisteredFileInternal(referenced_filename); } @@ -301,14 +301,14 @@ class VerilogProject { bool RemoveRegisteredFile(absl::string_view referenced_filename); // Non-modifying variant of lookup. - const VerilogSourceFile* LookupRegisteredFile( + const VerilogSourceFile *LookupRegisteredFile( absl::string_view referenced_filename) const { return LookupRegisteredFileInternal(referenced_filename); } // Find the source file that a particular string_view came from. // Returns nullptr if lookup failed for any reason. - const VerilogSourceFile* LookupFileOrigin( + const VerilogSourceFile *LookupFileOrigin( absl::string_view content_substring) const; // Returns relative path to the VerilogProject @@ -316,7 +316,7 @@ class VerilogProject { // Updates file from external source, e.g. Language Server void UpdateFileContents(absl::string_view path, - const verible::TextStructureView* updatedtext); + const verible::TextStructureView *updatedtext); // Adds include directory to the project void AddIncludePath(absl::string_view includepath) { @@ -328,7 +328,7 @@ class VerilogProject { } private: - absl::StatusOr OpenFile( + absl::StatusOr OpenFile( absl::string_view referenced_filename, absl::string_view resolved_filename, absl::string_view corpus); @@ -337,12 +337,12 @@ class VerilogProject { absl::string_view referenced_filename) const; // Returns a previously referenced file, or else nullptr. - VerilogSourceFile* LookupRegisteredFileInternal( + VerilogSourceFile *LookupRegisteredFileInternal( absl::string_view referenced_filename) const; // Returns the opened file or parse/not found error. If the file is not // opened, returns nullopt. - absl::optional> FindOpenedFile( + absl::optional> FindOpenedFile( absl::string_view filename) const; // The path from which top-level translation units are referenced relatively diff --git a/verilog/analysis/verilog_project_test.cc b/verilog/analysis/verilog_project_test.cc index 2bcc1d6ef..5b1702f95 100644 --- a/verilog/analysis/verilog_project_test.cc +++ b/verilog/analysis/verilog_project_test.cc @@ -86,13 +86,13 @@ TEST(VerilogSourceFileTest, ParseValidFile) { // Parse automatically opens. EXPECT_TRUE(file.Parse().ok()); EXPECT_TRUE(file.Status().ok()); - const TextStructureView* text_structure = + const TextStructureView *text_structure = ABSL_DIE_IF_NULL(file.GetTextStructure()); const absl::string_view owned_string_range(text_structure->Contents()); EXPECT_EQ(owned_string_range, text); - const auto* tokens = &text_structure->TokenStream(); + const auto *tokens = &text_structure->TokenStream(); EXPECT_NE(tokens, nullptr); - const auto* tree = &text_structure->SyntaxTree(); + const auto *tree = &text_structure->SyntaxTree(); EXPECT_NE(tree, nullptr); // Re-parsing doesn't change anything @@ -111,13 +111,13 @@ TEST(VerilogSourceFileTest, ParseInvalidFile) { // Parse automatically opens. EXPECT_FALSE(file.Parse().ok()); EXPECT_FALSE(file.Status().ok()); - const TextStructureView* text_structure = + const TextStructureView *text_structure = ABSL_DIE_IF_NULL(file.GetTextStructure()); const absl::string_view owned_string_range(text_structure->Contents()); EXPECT_EQ(owned_string_range, text); - const auto* tokens = &text_structure->TokenStream(); + const auto *tokens = &text_structure->TokenStream(); EXPECT_NE(tokens, nullptr); - const auto* tree = &text_structure->SyntaxTree(); + const auto *tree = &text_structure->SyntaxTree(); EXPECT_NE(tree, nullptr); // but syntax tree may be empty, depends on error-recovery @@ -162,13 +162,13 @@ TEST(InMemoryVerilogSourceFileTest, ParseValidFile) { // Parse automatically opens. EXPECT_TRUE(file.Parse().ok()); EXPECT_TRUE(file.Status().ok()); - const TextStructureView* text_structure = + const TextStructureView *text_structure = ABSL_DIE_IF_NULL(file.GetTextStructure()); const absl::string_view owned_string_range(text_structure->Contents()); EXPECT_EQ(owned_string_range, text); - const auto* tokens = &text_structure->TokenStream(); + const auto *tokens = &text_structure->TokenStream(); EXPECT_NE(tokens, nullptr); - const auto* tree = &text_structure->SyntaxTree(); + const auto *tree = &text_structure->SyntaxTree(); EXPECT_NE(tree, nullptr); // Re-parsing doesn't change anything @@ -185,13 +185,13 @@ TEST(InMemoryVerilogSourceFileTest, ParseInvalidFile) { // Parse automatically opens. EXPECT_FALSE(file.Parse().ok()); EXPECT_FALSE(file.Status().ok()); - const TextStructureView* text_structure = + const TextStructureView *text_structure = ABSL_DIE_IF_NULL(file.GetTextStructure()); const absl::string_view owned_string_range(text_structure->Contents()); EXPECT_EQ(owned_string_range, text); - const auto* tokens = &text_structure->TokenStream(); + const auto *tokens = &text_structure->TokenStream(); EXPECT_NE(tokens, nullptr); - const auto* tree = &text_structure->SyntaxTree(); + const auto *tree = &text_structure->SyntaxTree(); EXPECT_NE(tree, nullptr); // but syntax tree may be empty, depends on error-recovery @@ -209,20 +209,20 @@ TEST(ParsedVerilogSourceFileTest, ParseValidFile) { std::make_unique(text, "internal"); absl::Status status = analyzed_structure->Analyze(); EXPECT_TRUE(status.ok()); - const TextStructureView& input_text_structure = analyzed_structure->Data(); + const TextStructureView &input_text_structure = analyzed_structure->Data(); ParsedVerilogSourceFile file("internal", &input_text_structure); // Parse automatically opens. EXPECT_TRUE(file.Parse().ok()); EXPECT_TRUE(file.Status().ok()); - const TextStructureView* text_structure = + const TextStructureView *text_structure = ABSL_DIE_IF_NULL(file.GetTextStructure()); EXPECT_EQ(&input_text_structure, text_structure); const absl::string_view owned_string_range(text_structure->Contents()); EXPECT_EQ(owned_string_range, text); - const auto* tokens = &text_structure->TokenStream(); + const auto *tokens = &text_structure->TokenStream(); EXPECT_NE(tokens, nullptr); - const auto* tree = &text_structure->SyntaxTree(); + const auto *tree = &text_structure->SyntaxTree(); EXPECT_NE(tree, nullptr); // Re-parsing doesn't change anything @@ -251,13 +251,13 @@ TEST(VerilogProjectTest, NonexistentFileLookup) { const auto tempdir = ::testing::TempDir(); VerilogProject project(tempdir, {tempdir}); { // non-const-lookup overload - VerilogSourceFile* file = project.LookupRegisteredFile("never-there.v"); + VerilogSourceFile *file = project.LookupRegisteredFile("never-there.v"); EXPECT_EQ(file, nullptr); } { // const-lookup overload - const VerilogProject& cproject(project); - const VerilogSourceFile* file = + const VerilogProject &cproject(project); + const VerilogSourceFile *file = cproject.LookupRegisteredFile("never-there.v"); EXPECT_EQ(file, nullptr); } @@ -279,7 +279,7 @@ TEST(VerilogProjectTest, LookupFileOriginTest) { const ScopedTestFile tf(sources_dir, "module m;\nendmodule\n"); const auto status_or_file = project.OpenTranslationUnit(Basename(tf.filename())); - VerilogSourceFile* verilog_source_file = *status_or_file; + VerilogSourceFile *verilog_source_file = *status_or_file; const absl::string_view content1(verilog_source_file->GetContent()); { @@ -295,7 +295,7 @@ TEST(VerilogProjectTest, LookupFileOriginTest) { const ScopedTestFile tf2(sources_dir, "class c;\nendclass\n"); const auto status_or_file2 = project.OpenTranslationUnit(Basename(tf2.filename())); - VerilogSourceFile* verilog_source_file2 = *status_or_file2; + VerilogSourceFile *verilog_source_file2 = *status_or_file2; const absl::string_view content2(verilog_source_file2->GetContent()); // Pick substrings known to come from those files. @@ -318,18 +318,18 @@ TEST(VerilogProjectTest, LookupFileOriginTestMoreFiles) { // WArning: Test size is quadratic in N, but linear in memory in N. constexpr int N = 50; std::vector> test_files; - std::vector sources; + std::vector sources; for (int i = 0; i < N; ++i) { // Write files, need not be parse-able. test_files.emplace_back(std::make_unique( sources_dir, "sa89*(98filename())); - const VerilogSourceFile* source_file = *status_or_file; + const VerilogSourceFile *source_file = *status_or_file; ASSERT_NE(source_file, nullptr); sources.push_back(source_file); - for (const auto& source : sources) { + for (const auto &source : sources) { // Pick substrings known to come from those files. EXPECT_EQ(project.LookupFileOrigin(source->GetContent().substr(15, 12)), source); @@ -350,7 +350,7 @@ TEST(VerilogProjectTest, ValidTranslationUnit) { const ScopedTestFile tf(sources_dir, text); const auto status_or_file = project.OpenTranslationUnit(Basename(tf.filename())); - VerilogSourceFile* verilog_source_file = *status_or_file; + VerilogSourceFile *verilog_source_file = *status_or_file; EXPECT_TRUE(verilog_source_file->Status().ok()); EXPECT_EQ(verilog_source_file->ReferencedPath(), Basename(tf.filename())); EXPECT_EQ(verilog_source_file->ResolvedPath(), tf.filename()); @@ -358,7 +358,7 @@ TEST(VerilogProjectTest, ValidTranslationUnit) { verilog_source_file); const absl::string_view content(verilog_source_file->GetContent()); { // const-lookup overload - const VerilogProject& cproject(project); + const VerilogProject &cproject(project); EXPECT_EQ(cproject.LookupRegisteredFile(Basename(tf.filename())), verilog_source_file); EXPECT_EQ(cproject.LookupFileOrigin(content.substr(2, 4)), @@ -366,31 +366,31 @@ TEST(VerilogProjectTest, ValidTranslationUnit) { } EXPECT_TRUE(verilog_source_file->Parse().ok()); - const TextStructureView& text_structure( + const TextStructureView &text_structure( *verilog_source_file->GetTextStructure()); - const auto* tree = ABSL_DIE_IF_NULL(text_structure.SyntaxTree().get()); + const auto *tree = ABSL_DIE_IF_NULL(text_structure.SyntaxTree().get()); EXPECT_EQ(FindAllModuleDeclarations(*tree).size(), 1); { // Re-parsing the file changes nothing. EXPECT_TRUE(verilog_source_file->Parse().ok()); - const auto* tree2 = ABSL_DIE_IF_NULL(text_structure.SyntaxTree().get()); + const auto *tree2 = ABSL_DIE_IF_NULL(text_structure.SyntaxTree().get()); EXPECT_EQ(tree2, tree); EXPECT_EQ(FindAllModuleDeclarations(*tree).size(), 1); } { // Re-opening the file changes nothing. const auto status_or_file2 = project.OpenTranslationUnit(Basename(tf.filename())); - VerilogSourceFile* verilog_source_file2 = *status_or_file2; + VerilogSourceFile *verilog_source_file2 = *status_or_file2; EXPECT_EQ(verilog_source_file2, verilog_source_file); EXPECT_TRUE(verilog_source_file2->Status().ok()); } // Testing begin/end iteration. - for (auto& file : project) { + for (auto &file : project) { EXPECT_TRUE(file.second->Parse().ok()); } - for (const auto& file : project) { + for (const auto &file : project) { EXPECT_TRUE(file.second->Status().ok()); } } @@ -407,14 +407,14 @@ TEST(VerilogProjectTest, ValidIncludeFile) { const ScopedTestFile tf(includes_dir, text); const absl::string_view basename(Basename(tf.filename())); const auto status_or_file = project.OpenIncludedFile(basename); - VerilogSourceFile* verilog_source_file = *status_or_file; + VerilogSourceFile *verilog_source_file = *status_or_file; EXPECT_TRUE(verilog_source_file->Status().ok()); EXPECT_EQ(verilog_source_file->ReferencedPath(), basename); EXPECT_EQ(verilog_source_file->ResolvedPath(), tf.filename()); EXPECT_EQ(project.LookupRegisteredFile(Basename(tf.filename())), verilog_source_file); { // const-lookup overload - const VerilogProject& cproject(project); + const VerilogProject &cproject(project); EXPECT_EQ(cproject.LookupRegisteredFile(Basename(tf.filename())), verilog_source_file); } @@ -422,7 +422,7 @@ TEST(VerilogProjectTest, ValidIncludeFile) { // Re-opening same file, changes nothing { const auto status_or_file2 = project.OpenIncludedFile(basename); - VerilogSourceFile* verilog_source_file2 = *status_or_file2; + VerilogSourceFile *verilog_source_file2 = *status_or_file2; EXPECT_EQ(verilog_source_file2, verilog_source_file); EXPECT_TRUE(verilog_source_file2->Status().ok()); } @@ -452,20 +452,20 @@ TEST(VerilogProjectTest, OpenVirtualIncludeFile) { project.AddVirtualFile(full_path, text); const auto status_or_file = project.OpenIncludedFile(basename); - VerilogSourceFile* verilog_source_file = *status_or_file; + VerilogSourceFile *verilog_source_file = *status_or_file; EXPECT_TRUE(verilog_source_file->Status().ok()); EXPECT_EQ(verilog_source_file->ReferencedPath(), full_path); EXPECT_EQ(verilog_source_file->ResolvedPath(), full_path); EXPECT_EQ(project.LookupRegisteredFile(basename), verilog_source_file); { // const-lookup overload - const VerilogProject& cproject(project); + const VerilogProject &cproject(project); EXPECT_EQ(cproject.LookupRegisteredFile(basename), verilog_source_file); } // Re-opening same file, changes nothing { const auto status_or_file2 = project.OpenIncludedFile(basename); - VerilogSourceFile* verilog_source_file2 = *status_or_file2; + VerilogSourceFile *verilog_source_file2 = *status_or_file2; EXPECT_EQ(verilog_source_file2, verilog_source_file); EXPECT_TRUE(verilog_source_file2->Status().ok()); } @@ -537,7 +537,7 @@ TEST(VerilogProjectTest, AddVirtualFile) { const std::string file_content = "virtual file content"; project.AddVirtualFile(file_path, file_content); - auto* stored_file = project.LookupRegisteredFile(file_path); + auto *stored_file = project.LookupRegisteredFile(file_path); ASSERT_NE(stored_file, nullptr); EXPECT_TRUE(stored_file->Open().ok()); EXPECT_TRUE(stored_file->Status().ok()); diff --git a/verilog/formatting/align.h b/verilog/formatting/align.h index 6051693dd..03fa9ac91 100644 --- a/verilog/formatting/align.h +++ b/verilog/formatting/align.h @@ -30,9 +30,9 @@ namespace formatter { // tokens by inserting padding-spaces. // TODO(fangism): pass in disabled formatting ranges void TabularAlignTokenPartitions( - const FormatStyle& style, absl::string_view full_text, - const verible::ByteOffsetSet& disabled_byte_ranges, - verible::TokenPartitionTree* partition_ptr); + const FormatStyle &style, absl::string_view full_text, + const verible::ByteOffsetSet &disabled_byte_ranges, + verible::TokenPartitionTree *partition_ptr); } // namespace formatter } // namespace verilog diff --git a/verilog/formatting/comment_controls.cc b/verilog/formatting/comment_controls.cc index f4e69b83d..5363b7dbd 100644 --- a/verilog/formatting/comment_controls.cc +++ b/verilog/formatting/comment_controls.cc @@ -37,18 +37,18 @@ using verible::ByteOffsetSet; using verible::EscapeString; ByteOffsetSet DisableFormattingRanges(absl::string_view text, - const verible::TokenSequence& tokens) { + const verible::TokenSequence &tokens) { static constexpr absl::string_view kTrigger = "verilog_format:"; static const auto kDelimiters = absl::ByAnyChar(" \t"); static constexpr int kNullOffset = -1; const verible::TokenInfo::Context context( text, - [](std::ostream& stream, int e) { stream << verilog_symbol_name(e); }); + [](std::ostream &stream, int e) { stream << verilog_symbol_name(e); }); // By default, no text ranges are formatter-disabled. int begin_disable_offset = kNullOffset; ByteOffsetSet disable_set; - for (const auto& token : tokens) { + for (const auto &token : tokens) { VLOG(2) << verible::TokenWithContext{token, context}; const auto vtoken_enum = verilog_tokentype(token.token_enum()); if (IsComment(vtoken_enum)) { @@ -90,8 +90,8 @@ ByteOffsetSet DisableFormattingRanges(absl::string_view text, } ByteOffsetSet EnabledLinesToDisabledByteRanges( - const verible::LineNumberSet& line_numbers, - const verible::LineColumnMap& line_column_map) { + const verible::LineNumberSet &line_numbers, + const verible::LineColumnMap &line_column_map) { // Interpret empty line numbers as enabling all lines for formatting. if (line_numbers.empty()) return ByteOffsetSet(); // Translate lines to byte offsets (strictly monotonic). @@ -114,8 +114,8 @@ static size_t NewlineCount(absl::string_view s) { void FormatWhitespaceWithDisabledByteRanges( absl::string_view text_base, absl::string_view space_text, - const ByteOffsetSet& disabled_ranges, bool include_disabled_ranges, - std::ostream& stream) { + const ByteOffsetSet &disabled_ranges, bool include_disabled_ranges, + std::ostream &stream) { VLOG(3) << __FUNCTION__; CHECK(verible::IsSubRange(space_text, text_base)); const int start = std::distance(text_base.begin(), space_text.begin()); @@ -139,7 +139,7 @@ void FormatWhitespaceWithDisabledByteRanges( bool partially_enabled = false; size_t total_enabled_newlines = 0; int next_start = start; // keep track of last consumed position - for (const auto& range : enabled_ranges) { + for (const auto &range : enabled_ranges) { if (include_disabled_ranges) { // for disabled intervals, print the // original spacing const absl::string_view disabled( diff --git a/verilog/formatting/comment_controls.h b/verilog/formatting/comment_controls.h index a1ed8ddfe..d14397822 100644 --- a/verilog/formatting/comment_controls.h +++ b/verilog/formatting/comment_controls.h @@ -27,15 +27,15 @@ namespace formatter { // Returns a representation of byte offsets where true (membership) means // formatting is disabled. verible::ByteOffsetSet DisableFormattingRanges( - absl::string_view text, const verible::TokenSequence& tokens); + absl::string_view text, const verible::TokenSequence &tokens); // TODO(fangism): Move these next functions into common/formatting. // Same with the above types. // Translates line numbers into a set of byte ranges to disable formatting. verible::ByteOffsetSet EnabledLinesToDisabledByteRanges( - const verible::LineNumberSet& line_numbers, - const verible::LineColumnMap& line_column_map); + const verible::LineNumberSet &line_numbers, + const verible::LineColumnMap &line_column_map); // Formats space between tokens while honoring formatting-disabled ranges. // 'text_base' is the entire original text that was formatted. @@ -46,8 +46,8 @@ verible::ByteOffsetSet EnabledLinesToDisabledByteRanges( // Output is written to 'stream'. void FormatWhitespaceWithDisabledByteRanges( absl::string_view text_base, absl::string_view space_text, - const verible::ByteOffsetSet& disabled_ranges, bool include_disabled_ranges, - std::ostream& stream); + const verible::ByteOffsetSet &disabled_ranges, bool include_disabled_ranges, + std::ostream &stream); } // namespace formatter } // namespace verilog diff --git a/verilog/formatting/comment_controls_test.cc b/verilog/formatting/comment_controls_test.cc index d3aab851e..a41c76637 100644 --- a/verilog/formatting/comment_controls_test.cc +++ b/verilog/formatting/comment_controls_test.cc @@ -64,7 +64,7 @@ struct DisableRangeTestData : public TokenInfoTestData { // convert expected_tokens into expected ranges const auto tokens = FindImportantTokens(); const absl::string_view base(code); - for (const auto& t : tokens) { + for (const auto &t : tokens) { expected.Add({t.left(base), t.right(base)}); } } @@ -73,14 +73,14 @@ struct DisableRangeTestData : public TokenInfoTestData { TEST(DisableFormattingRangesTest, FormatOnNoEffect) { // By default, nothing is disabled, formatter is on for entire file, so these // should have no effect. - const char* kTestCases[] = { + const char *kTestCases[] = { "xxx yyy;\n // verilog_format: on\n", "xxx yyy;\n /* verilog_format: on */\n", "xxx yyy;\n// verilog_format: on\n//verilog_format:on\n", "xxx yyy;\n // verilog_format: other\n", "xxx yyy;\n // verilog_format:\n", // no command }; - for (const auto* code : kTestCases) { + for (const auto *code : kTestCases) { VerilogAnalyzer analyzer(code, ""); EXPECT_TRUE(analyzer.Tokenize().ok()); const auto disable_ranges = DisableFormattingRanges( @@ -103,7 +103,7 @@ TEST(DisableFormattingRangesTest, FormatOffDisableToEndEOLComment) { {"xxx yyy;\n // verilog_format: off\n", {kOff, "\t// verilog_format: off again\n"}}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.code, ""); EXPECT_TRUE(analyzer.Tokenize().ok()); const auto disable_ranges = DisableFormattingRanges( @@ -137,7 +137,7 @@ TEST(DisableFormattingRangesTest, FormatOffDisableToEndBlockComment) { {kOff, "\n\n/* verilog_format:on */"}, "\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.code, ""); EXPECT_TRUE(analyzer.Tokenize().ok()); const auto disable_ranges = DisableFormattingRanges( @@ -201,7 +201,7 @@ TEST(DisableFormattingRangesTest, FormatOffVarious) { "\n" "cc dd;\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { VerilogAnalyzer analyzer(test.code, ""); EXPECT_TRUE(analyzer.Tokenize().ok()); const auto disable_ranges = DisableFormattingRanges( @@ -302,7 +302,7 @@ TEST(EnabledLinesToDisabledByteRangesTest, AllCases) { {{0, 17}} // disable all lines }, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { LineColumnMap line_map(test.text); const ByteOffsetSet result( EnabledLinesToDisabledByteRanges(test.enabled_lines, line_map)); @@ -378,7 +378,7 @@ TEST(FormatWhitespaceWithDisabledByteRangesTest, EmptyStrings) { {"ab\ncd\nef\n", {3, 6}, {{5, 9}}, "\n"}, {"ab\ncd\nef\n", {3, 6}, {{6, 9}}, "\n"}, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { std::ostringstream stream; const auto substr = test.full_text.substr( test.substring_range.first, diff --git a/verilog/formatting/formatter_tuning_test.cc b/verilog/formatting/formatter_tuning_test.cc index 6c03a15b0..6b1fc07f2 100644 --- a/verilog/formatting/formatter_tuning_test.cc +++ b/verilog/formatting/formatter_tuning_test.cc @@ -78,7 +78,7 @@ TEST(FormatterEndToEndTest, PenaltySensitiveLineWrapping) { style.column_limit = 40; style.indentation_spaces = 2; style.wrap_spaces = 4; - for (const auto& test_case : kTestCases) { + for (const auto &test_case : kTestCases) { VLOG(1) << "code-to-format:\n" << test_case.input << ""; std::ostringstream stream, debug_stream; ExecutionControl control; @@ -152,7 +152,7 @@ TEST(FormatterEndToEndTest, PenaltySensitiveLineWrapping100Col) { style.column_limit = 100; style.indentation_spaces = 2; style.wrap_spaces = 4; - for (const auto& test_case : k100ColTestCases) { + for (const auto &test_case : k100ColTestCases) { VLOG(1) << "code-to-format:\n" << test_case.input << ""; std::ostringstream stream, debug_stream; ExecutionControl control; diff --git a/verilog/formatting/token_annotator.h b/verilog/formatting/token_annotator.h index e0e69ad7d..a3b7f94ea 100644 --- a/verilog/formatting/token_annotator.h +++ b/verilog/formatting/token_annotator.h @@ -33,8 +33,8 @@ namespace formatter { // TODO(b/130091585): replace modifiable unwrapped line with a read-only // struct and return separate annotations. void AnnotateFormattingInformation( - const FormatStyle& style, const verible::TextStructureView& text_structure, - std::vector* format_tokens); + const FormatStyle &style, const verible::TextStructureView &text_structure, + std::vector *format_tokens); // This interface is only provided for testing, without requiring a // TextStructureView. @@ -42,10 +42,10 @@ void AnnotateFormattingInformation( // syntax_tree_root: syntax tree used for context-sensitive behavior. // eof_token: EOF token pointing to the end of the unformatted string. void AnnotateFormattingInformation( - const FormatStyle& style, const char* buffer_start, - const verible::Symbol* syntax_tree_root, - const verible::TokenInfo& eof_token, - std::vector* format_tokens); + const FormatStyle &style, const char *buffer_start, + const verible::Symbol *syntax_tree_root, + const verible::TokenInfo &eof_token, + std::vector *format_tokens); } // namespace formatter } // namespace verilog diff --git a/verilog/formatting/token_annotator_test.cc b/verilog/formatting/token_annotator_test.cc index 89d76193a..be156930e 100644 --- a/verilog/formatting/token_annotator_test.cc +++ b/verilog/formatting/token_annotator_test.cc @@ -45,11 +45,11 @@ using ::verible::PreFormatToken; using ::verible::SpacingOptions; // Private function with external linkage from token_annotator.cc. -extern void AnnotateFormatToken(const FormatStyle& style, - const PreFormatToken& prev_token, - PreFormatToken* curr_token, - const verible::SyntaxTreeContext& prev_context, - const verible::SyntaxTreeContext& curr_context); +extern void AnnotateFormatToken(const FormatStyle &style, + const PreFormatToken &prev_token, + PreFormatToken *curr_token, + const verible::SyntaxTreeContext &prev_context, + const verible::SyntaxTreeContext &curr_context); namespace { @@ -59,24 +59,24 @@ namespace { // We do not want to compare break penalties, because that would be too // change-detector-y. struct ExpectedInterTokenInfo { - constexpr ExpectedInterTokenInfo(int spaces, const SpacingOptions& bd) + constexpr ExpectedInterTokenInfo(int spaces, const SpacingOptions &bd) : spaces_required(spaces), break_decision(bd) {} int spaces_required = 0; SpacingOptions break_decision = SpacingOptions::kUndecided; - bool operator==(const InterTokenInfo& before) const { + bool operator==(const InterTokenInfo &before) const { return spaces_required == before.spaces_required && break_decision == before.break_decision; } - bool operator!=(const InterTokenInfo& before) const { + bool operator!=(const InterTokenInfo &before) const { return !(*this == before); } }; -std::ostream& operator<<(std::ostream& stream, - const ExpectedInterTokenInfo& t) { +std::ostream &operator<<(std::ostream &stream, + const ExpectedInterTokenInfo &t) { stream << "{\n spaces_required: " << t.spaces_required << "\n break_decision: " << t.break_decision << "\n}"; return stream; @@ -87,7 +87,7 @@ std::ostream& operator<<(std::ostream& stream, // type T is any container or range over PreFormatTokens. template bool CorrectExpectedFormatTokens( - const std::vector& expected, const T& tokens) { + const std::vector &expected, const T &tokens) { EXPECT_EQ(expected.size(), tokens.size()) << "Size of expected calculations and format tokens does not match."; if (expected.size() != tokens.size()) { @@ -96,8 +96,8 @@ bool CorrectExpectedFormatTokens( const auto first_mismatch = std::mismatch(expected.cbegin(), expected.cend(), tokens.begin(), - [](const ExpectedInterTokenInfo& expected, - const PreFormatToken& token) -> bool { + [](const ExpectedInterTokenInfo &expected, + const PreFormatToken &token) -> bool { return expected == token.before; }); const bool all_match = first_mismatch.first == expected.cend(); @@ -126,11 +126,11 @@ struct AnnotateFormattingInformationTestCase { }; // Print input tokens' text for debugging. -std::ostream& operator<<( - std::ostream& stream, - const AnnotateFormattingInformationTestCase& test_case) { +std::ostream &operator<<( + std::ostream &stream, + const AnnotateFormattingInformationTestCase &test_case) { stream << '['; - for (const auto& token : test_case.input_tokens) { + for (const auto &token : test_case.input_tokens) { stream << ' ' << token.text(); } return stream << " ]"; @@ -143,7 +143,7 @@ class InitializedSyntaxTreeContext : public verible::SyntaxTreeContext { public: InitializedSyntaxTreeContext(std::initializer_list ancestors) { // Build up a "skinny" tree from the bottom-up, much like the parser does. - std::vector parents; + std::vector parents; parents.reserve(ancestors.size()); for (const auto ancestor : verible::reversed_view(ancestors)) { if (root_ == nullptr) { @@ -152,9 +152,9 @@ class InitializedSyntaxTreeContext : public verible::SyntaxTreeContext { root_ = verible::MakeTaggedNode(ancestor, root_); } parents.push_back(ABSL_DIE_IF_NULL( - verible::down_cast(root_.get()))); + verible::down_cast(root_.get()))); } - for (const auto* parent : verible::reversed_view(parents)) { + for (const auto *parent : verible::reversed_view(parents)) { Push(parent); } } @@ -164,10 +164,10 @@ class InitializedSyntaxTreeContext : public verible::SyntaxTreeContext { verible::SymbolPtr root_; }; -std::ostream& operator<<(std::ostream& stream, - const InitializedSyntaxTreeContext& context) { +std::ostream &operator<<(std::ostream &stream, + const InitializedSyntaxTreeContext &context) { stream << "[ "; - for (const auto* node : verible::make_range(context.begin(), context.end())) { + for (const auto *node : verible::make_range(context.begin(), context.end())) { stream << NodeEnumToString(NodeEnum(ABSL_DIE_IF_NULL(node)->Tag().tag)) << " "; } @@ -1807,19 +1807,19 @@ TEST(TokenAnnotatorTest, AnnotateFormattingInfoTest) { }; int test_index = 0; - for (const auto& test_case : kTestCases) { + for (const auto &test_case : kTestCases) { verible::UnwrappedLineMemoryHandler handler; handler.CreateTokenInfos(test_case.input_tokens); verible::UnwrappedLine unwrapped_line(test_case.uwline_indentation, handler.GetPreFormatTokensBegin()); handler.AddFormatTokens(&unwrapped_line); // The format_token_enums are not yet set by AddFormatTokens. - for (auto& ftoken : handler.pre_format_tokens_) { + for (auto &ftoken : handler.pre_format_tokens_) { ftoken.format_token_enum = GetFormatTokenType(verilog_tokentype(ftoken.TokenEnum())); } - auto& ftokens_range = handler.pre_format_tokens_; + auto &ftokens_range = handler.pre_format_tokens_; // nullptr buffer_start is needed because token text do not belong to the // same contiguous string buffer. // Pass an empty/fake tree, which will not be used for testing @@ -4688,7 +4688,7 @@ TEST(TokenAnnotatorTest, AnnotateFormattingWithContextTest) { }, }; int test_index = 0; - for (const auto& test_case : kTestCases) { + for (const auto &test_case : kTestCases) { VLOG(1) << "test_index[" << test_index << "]:"; PreFormatToken left(&test_case.left_token); PreFormatToken right(&test_case.right_token); @@ -5419,7 +5419,7 @@ TEST(TokenAnnotatorTest, OriginalSpacingSensitiveTests) { }, }; int test_index = 0; - for (const auto& test_case : kTestCases) { + for (const auto &test_case : kTestCases) { VLOG(1) << "test_index[" << test_index << "]:"; const verible::TokenInfoTestData test_data = { diff --git a/verilog/formatting/verilog_token_test.cc b/verilog/formatting/verilog_token_test.cc index bee0aee18..e36f3bd29 100644 --- a/verilog/formatting/verilog_token_test.cc +++ b/verilog/formatting/verilog_token_test.cc @@ -83,7 +83,7 @@ const GetFormatTokenTypeTestCase GetFormatTokenTypeTestCases[] = { // have actually been reviewed, whereas other entries in the map have not // necessarily been reviewed, and are just set to some default value. TEST(VerilogTokenTest, GetFormatTokenTypeTest) { - for (const auto& test_case : GetFormatTokenTypeTestCases) { + for (const auto &test_case : GetFormatTokenTypeTestCases) { EXPECT_EQ(test_case.format_token_type, GetFormatTokenType(test_case.token_info_type)); } diff --git a/verilog/parser/verilog_lexer.cc b/verilog/parser/verilog_lexer.cc index a72dc8552..82cba8a09 100644 --- a/verilog/parser/verilog_lexer.cc +++ b/verilog/parser/verilog_lexer.cc @@ -31,13 +31,13 @@ void VerilogLexer::Restart(absl::string_view code) { macro_arg_length_ = 0; } -bool VerilogLexer::TokenIsError(const TokenInfo& token) const { +bool VerilogLexer::TokenIsError(const TokenInfo &token) const { // TODO(fangism): Distinguish different lexical errors by returning different // enums. return token.token_enum() == TK_OTHER; } -bool VerilogLexer::KeepSyntaxTreeTokens(const TokenInfo& t) { +bool VerilogLexer::KeepSyntaxTreeTokens(const TokenInfo &t) { switch (t.token_enum()) { case TK_COMMENT_BLOCK: // fall-through case TK_EOL_COMMENT: // fall-through @@ -53,10 +53,10 @@ bool VerilogLexer::KeepSyntaxTreeTokens(const TokenInfo& t) { } void RecursiveLexText(absl::string_view text, - const std::function& func) { + const std::function &func) { VerilogLexer lexer(text); for (;;) { - const TokenInfo& subtoken(lexer.DoNextToken()); + const TokenInfo &subtoken(lexer.DoNextToken()); if (subtoken.isEOF()) break; func(subtoken); } diff --git a/verilog/parser/verilog_lexer.h b/verilog/parser/verilog_lexer.h index 7231e8faf..46713ab33 100644 --- a/verilog/parser/verilog_lexer.h +++ b/verilog/parser/verilog_lexer.h @@ -46,10 +46,10 @@ class VerilogLexer : public verible::FlexLexerAdapter { void Restart(absl::string_view) final; // Returns true if token is invalid. - bool TokenIsError(const verible::TokenInfo&) const final; + bool TokenIsError(const verible::TokenInfo &) const final; // Filter predicate that can be used for testing and parsing. - static bool KeepSyntaxTreeTokens(const verible::TokenInfo&); + static bool KeepSyntaxTreeTokens(const verible::TokenInfo &); private: // Main lexing function. Will be defined by Flex. @@ -72,7 +72,7 @@ class VerilogLexer : public verible::FlexLexerAdapter { // Recursively lex the given 'text', and apply 'func' to each subtoken. void RecursiveLexText( absl::string_view text, - const std::function& func); + const std::function &func); } // namespace verilog diff --git a/verilog/parser/verilog_lexical_context.h b/verilog/parser/verilog_lexical_context.h index 1a596cecf..7e891e55a 100644 --- a/verilog/parser/verilog_lexical_context.h +++ b/verilog/parser/verilog_lexical_context.h @@ -64,7 +64,7 @@ class ConstraintBlockStateMachine { int InterpretToken(int token_enum) const; // Show representation (for debugging). - std::ostream& Dump(std::ostream&) const; + std::ostream &Dump(std::ostream &) const; private: void DeferInvalidToken(int token_enum); @@ -106,8 +106,8 @@ class ConstraintBlockStateMachine { std::stack states_; }; -inline std::ostream& operator<<(std::ostream& os, - const ConstraintBlockStateMachine& s) { +inline std::ostream &operator<<(std::ostream &os, + const ConstraintBlockStateMachine &s) { return s.Dump(os); } @@ -180,7 +180,7 @@ class LastSemicolonStateMachine { finish_token_enum_(stop), semicolon_replacement_(replacement) {} - void UpdateState(verible::TokenInfo*); + void UpdateState(verible::TokenInfo *); protected: enum State { @@ -200,10 +200,10 @@ class LastSemicolonStateMachine { // Keeps track of the last semicolons. Upon de-activation, the last // semicolon will be replaced. Technically, we only need a two-slot queue, // but a CircularBuffer is overkill. - std::stack semicolons_; + std::stack semicolons_; // One token look-back. - verible::TokenInfo* previous_token_ = nullptr; + verible::TokenInfo *previous_token_ = nullptr; }; } // namespace internal // @@ -230,8 +230,8 @@ class LexicalContext { ~LexicalContext() = default; // Not copy-able. - LexicalContext(const LexicalContext&) = delete; - LexicalContext& operator=(const LexicalContext&) = delete; + LexicalContext(const LexicalContext &) = delete; + LexicalContext &operator=(const LexicalContext &) = delete; // Re-writes some token enums in-place using context-sensitivity. // This function must re-tag tokens enumerated (_TK_*), see verilog.y and @@ -241,7 +241,7 @@ class LexicalContext { // Postcondition: tokens_view's tokens must not be tagged with (_TK_*) // enumerations. void TransformVerilogSymbols( - const verible::TokenStreamReferenceView& tokens_view) { + const verible::TokenStreamReferenceView &tokens_view) { // TODO(fangism): Using a stream interface would further decouple the input // iteration from output iteration. for (auto iter : tokens_view) { @@ -251,18 +251,18 @@ class LexicalContext { protected: // Allow direct testing of some methods. // Reads a single token, and may alter it depending on internal state. - void AdvanceToken(verible::TokenInfo*); + void AdvanceToken(verible::TokenInfo *); // Changes the enum of a token where disambiguation is needed. int InterpretToken(int token_enum) const; // Changes the enum of a token (in-place) without changing internal state. - void MutateToken(verible::TokenInfo* token) const { + void MutateToken(verible::TokenInfo *token) const { token->set_token_enum(InterpretToken(token->token_enum())); } // Updates the internally tracked state without touching the token. - void UpdateState(const verible::TokenInfo& token); + void UpdateState(const verible::TokenInfo &token); // State functions: @@ -287,7 +287,7 @@ class LexicalContext { in_initial_always_final_construct_; } - const verible::TokenInfo* previous_token_ = nullptr; + const verible::TokenInfo *previous_token_ = nullptr; // Non-nestable states can be represented without a stack. // Do not bother trying to accommodate malformed input token sequences. @@ -315,14 +315,14 @@ class LexicalContext { // Tracks if, for, case blocks. struct FlowControlState { - const verible::TokenInfo* start; + const verible::TokenInfo *start; // When this is false, the state is still in the header, which is: // if (...) // for (...) // case (...) (including other case-variants) bool in_body = false; // starts in header state - explicit FlowControlState(const verible::TokenInfo* token) : start(token) {} + explicit FlowControlState(const verible::TokenInfo *token) : start(token) {} }; std::vector flow_control_stack_; @@ -360,10 +360,10 @@ class LexicalContext { // ... // end // pops off of this stack // - std::vector block_stack_; + std::vector block_stack_; // Tracks open-close paired tokens like parentheses and brackets and braces. - std::vector balance_stack_; + std::vector balance_stack_; }; } // namespace verilog diff --git a/verilog/parser/verilog_lexical_context_test.cc b/verilog/parser/verilog_lexical_context_test.cc index c531696d4..d94c9ce24 100644 --- a/verilog/parser/verilog_lexical_context_test.cc +++ b/verilog/parser/verilog_lexical_context_test.cc @@ -65,7 +65,7 @@ using verible::TokenStreamReferenceView; // expected, absl::string_view pattern); #define EXPECT_EQ_REASON(expr, expected, pattern) \ { \ - const auto& r = expr; /* evaluate expr once, auto-extend lifetime */ \ + const auto &r = expr; /* evaluate expr once, auto-extend lifetime */ \ EXPECT_EQ(r.value, expected) << r.reason; \ /* value could be correct, but reason could be wrong. */ \ EXPECT_TRUE(absl::StrContains(absl::string_view(r.reason), pattern)) \ @@ -74,16 +74,16 @@ using verible::TokenStreamReferenceView; template void ExpectStateMachineTokenSequence( - SM& sm, verible::TokenStreamView::const_iterator* token_iter, + SM &sm, verible::TokenStreamView::const_iterator *token_iter, std::initializer_list expect_token_enums) { int i = 0; for (int expect_token_enum : expect_token_enums) { - const TokenInfo& token(***token_iter); + const TokenInfo &token(***token_iter); const int token_enum = token.token_enum(); const int interpreted_enum = sm.InterpretToken(token_enum); - const char* raw_symbol = verilog_symbol_name(token_enum); - const char* interpreted_symbol = verilog_symbol_name(interpreted_enum); - const char* expected_symbol = verilog_symbol_name(expect_token_enum); + const char *raw_symbol = verilog_symbol_name(token_enum); + const char *interpreted_symbol = verilog_symbol_name(interpreted_enum); + const char *expected_symbol = verilog_symbol_name(expect_token_enum); VLOG(1) << "token[" << i << "] enum: " << raw_symbol << " -> " << interpreted_symbol; EXPECT_EQ(interpreted_enum, expect_token_enum) @@ -99,7 +99,7 @@ TEST(KeywordLabelStateMachineTest, NoKeywords) { VerilogAnalyzer analyzer("1, 2; 3;", ""); EXPECT_OK(analyzer.Tokenize()); analyzer.FilterTokensForSyntaxTree(); - const auto& tokens_view = analyzer.Data().GetTokenStreamView(); + const auto &tokens_view = analyzer.Data().GetTokenStreamView(); EXPECT_EQ(tokens_view.size(), 7); // including EOF internal::KeywordLabelStateMachine b; @@ -121,7 +121,7 @@ TEST(KeywordLabelStateMachineTest, KeywordsWithoutLabels) { true, false}}; EXPECT_OK(analyzer.Tokenize()); analyzer.FilterTokensForSyntaxTree(); - const auto& tokens_view = analyzer.Data().GetTokenStreamView(); + const auto &tokens_view = analyzer.Data().GetTokenStreamView(); EXPECT_EQ(tokens_view.size(), expect_item_may_start.size()); internal::KeywordLabelStateMachine b; @@ -145,7 +145,7 @@ TEST(KeywordLabelStateMachineTest, KeywordsWithLabels) { false, true, false, false}}; EXPECT_OK(analyzer.Tokenize()); analyzer.FilterTokensForSyntaxTree(); - const auto& tokens_view = analyzer.Data().GetTokenStreamView(); + const auto &tokens_view = analyzer.Data().GetTokenStreamView(); EXPECT_EQ(tokens_view.size(), expect_item_may_start.size()); // including EOF internal::KeywordLabelStateMachine b; @@ -169,7 +169,7 @@ TEST(KeywordLabelStateMachineTest, ItemsInsideBlocks) { true, true, true, true}}; EXPECT_OK(analyzer.Tokenize()); analyzer.FilterTokensForSyntaxTree(); - const auto& tokens_view = analyzer.Data().GetTokenStreamView(); + const auto &tokens_view = analyzer.Data().GetTokenStreamView(); EXPECT_EQ(tokens_view.size(), expect_item_may_start.size()); // including EOF internal::KeywordLabelStateMachine b; @@ -314,7 +314,7 @@ TEST_F(LastSemicolonStateMachineTest, LifeCycleFinalSemicolon) { // TODO(fangism): move this into a test_util library struct StateMachineTestBase : public ::testing::Test { // Lexes code and initializes token_iter to point to the first token. - void Tokenize(const std::string& code) { + void Tokenize(const std::string &code) { analyzer = std::make_unique(code, ""); EXPECT_OK(analyzer->Tokenize()); analyzer->FilterTokensForSyntaxTree(); @@ -322,7 +322,7 @@ struct StateMachineTestBase : public ::testing::Test { } template - void ExpectTokenSequence(SM& sm, std::initializer_list expect_enums) { + void ExpectTokenSequence(SM &sm, std::initializer_list expect_enums) { ExpectStateMachineTokenSequence(sm, &token_iter, expect_enums); } @@ -1177,7 +1177,7 @@ class LexicalContextTest : public ::testing::Test, public LexicalContext { void AdvanceToken() { TokenSequence::iterator iter(*token_iter_); - TokenInfo& token(*iter); + TokenInfo &token(*iter); LexicalContext::AdvanceToken(&token); ++token_iter_; } @@ -1218,7 +1218,7 @@ class LexicalContextTest : public ::testing::Test, public LexicalContext { } // Lexes code and initializes token_iter to point to the first token. - void Tokenize(const std::string& code) { + void Tokenize(const std::string &code) { analyzer_ = std::make_unique(code, ""); EXPECT_OK(analyzer_->Tokenize()); analyzer_->FilterTokensForSyntaxTree(); diff --git a/verilog/parser/verilog_parser.cc b/verilog/parser/verilog_parser.cc index 380e291d1..4901cd954 100644 --- a/verilog/parser/verilog_parser.cc +++ b/verilog/parser/verilog_parser.cc @@ -29,13 +29,13 @@ namespace verilog { // Bison-generated parsing function. // Its implementation is in the generated file verilog.tab.cc, // from verilog.y, by the genyacc rule for 'verilog_y'. -extern int verilog_parse(::verible::ParserParam* param); +extern int verilog_parse(::verible::ParserParam *param); // Controls yacc/bison's detailed verilog traces extern int verilog_debug; // symbol defined in bison-generated verilog.tab.cc // parser wrapper to enable debug traces -int verilog_parse_wrapper(::verible::ParserParam* param) { +int verilog_parse_wrapper(::verible::ParserParam *param) { const verible::ValueSaver save_global_debug( &verilog_debug, absl::GetFlag(FLAGS_verilog_trace_parser) ? 1 : 0); return verilog_parse(param); diff --git a/verilog/parser/verilog_parser.h b/verilog/parser/verilog_parser.h index 8a7e81c39..88c15a4bd 100644 --- a/verilog/parser/verilog_parser.h +++ b/verilog/parser/verilog_parser.h @@ -29,7 +29,7 @@ namespace verilog { // parser wrapper to enable debug traces -int verilog_parse_wrapper(::verible::ParserParam*); +int verilog_parse_wrapper(::verible::ParserParam *); // TODO(fangism): Use a pseudo-preprocessor between the lexer and parser. using VerilogParser = verible::BisonParserAdapter; @@ -39,7 +39,7 @@ using VerilogParser = verible::BisonParserAdapter; // Defined in verilog.y, emitted in verilog.tab.cc. // // See also: TokenTypeToString() in verilog_token.h -const char* verilog_symbol_name(size_t symbol_enum); +const char *verilog_symbol_name(size_t symbol_enum); } // namespace verilog diff --git a/verilog/tools/diff/verilog_diff.cc b/verilog/tools/diff/verilog_diff.cc index 145e370e9..683eb3a5d 100644 --- a/verilog/tools/diff/verilog_diff.cc +++ b/verilog/tools/diff/verilog_diff.cc @@ -43,7 +43,7 @@ enum class DiffMode { kObfuscate, }; -static const verible::EnumNameMap& DiffModeStringMap() { +static const verible::EnumNameMap &DiffModeStringMap() { static const verible::EnumNameMap kDiffModeStringMap({ {"format", DiffMode::kFormat}, {"obfuscate", DiffMode::kObfuscate}, @@ -51,15 +51,15 @@ static const verible::EnumNameMap& DiffModeStringMap() { return kDiffModeStringMap; } -std::ostream& operator<<(std::ostream& stream, DiffMode p) { +std::ostream &operator<<(std::ostream &stream, DiffMode p) { return DiffModeStringMap().Unparse(p, stream); } -bool AbslParseFlag(absl::string_view text, DiffMode* mode, std::string* error) { +bool AbslParseFlag(absl::string_view text, DiffMode *mode, std::string *error) { return DiffModeStringMap().Parse(text, mode, error, "--mode value"); } -std::string AbslUnparseFlag(const DiffMode& mode) { +std::string AbslUnparseFlag(const DiffMode &mode) { std::ostringstream stream; stream << mode; return stream.str(); @@ -74,14 +74,14 @@ ABSL_FLAG(DiffMode, mode, DiffMode::kFormat, )"); using EquivalenceFunctionType = std::function; + absl::string_view, absl::string_view, std::ostream *)>; static const std::map diff_func_map({ {DiffMode::kFormat, verilog::FormatEquivalent}, {DiffMode::kObfuscate, verilog::ObfuscationEquivalent}, }); -int main(int argc, char** argv) { +int main(int argc, char **argv) { const auto usage = absl::StrCat("usage: ", argv[0], " [options] file1 file2\n" "Use - as a file name to read from stdin."); diff --git a/verilog/tools/kythe/indexing_facts_tree.cc b/verilog/tools/kythe/indexing_facts_tree.cc index 848ab5ab0..da99147fd 100644 --- a/verilog/tools/kythe/indexing_facts_tree.cc +++ b/verilog/tools/kythe/indexing_facts_tree.cc @@ -27,7 +27,7 @@ namespace verilog { namespace kythe { -Anchor::Anchor(const Anchor& other) = default; +Anchor::Anchor(const Anchor &other) = default; std::string Anchor::DebugString() const { if (source_text_range_) { @@ -38,11 +38,11 @@ std::string Anchor::DebugString() const { return absl::StrCat("{", Text(), "}"); } -std::ostream& operator<<(std::ostream& stream, const Anchor& anchor) { +std::ostream &operator<<(std::ostream &stream, const Anchor &anchor) { return stream << anchor.DebugString(); } -bool Anchor::operator==(const Anchor& rhs) const { +bool Anchor::operator==(const Anchor &rhs) const { if (source_text_range_) { if (!rhs.source_text_range_) { return false; @@ -56,41 +56,41 @@ bool Anchor::operator==(const Anchor& rhs) const { return Text() == rhs.Text(); } -std::ostream& IndexingNodeData::DebugString(std::ostream* stream) const { +std::ostream &IndexingNodeData::DebugString(std::ostream *stream) const { *stream << indexing_fact_type_ << ": [" << absl::StrJoin(anchors_.begin(), anchors_.end(), ", ", - [](std::string* out, const Anchor& anchor) { + [](std::string *out, const Anchor &anchor) { absl::StrAppend(out, anchor.DebugString()); }) << ']'; return *stream; } -std::ostream& operator<<(std::ostream& stream, const IndexingNodeData& data) { - const auto& anchors(data.Anchors()); +std::ostream &operator<<(std::ostream &stream, const IndexingNodeData &data) { + const auto &anchors(data.Anchors()); return stream << data.GetIndexingFactType() << ": [" << absl::StrJoin(anchors.begin(), anchors.end(), ", ", absl::StreamFormatter()) << ']'; } -bool IndexingNodeData::operator==(const IndexingNodeData& rhs) const { +bool IndexingNodeData::operator==(const IndexingNodeData &rhs) const { return indexing_fact_type_ == rhs.GetIndexingFactType() && anchors_.size() == rhs.Anchors().size() && std::equal(anchors_.begin(), anchors_.end(), rhs.Anchors().begin()); } -std::ostream& operator<<(std::ostream& stream, - const PrintableIndexingNodeData& printable_node) { +std::ostream &operator<<(std::ostream &stream, + const PrintableIndexingNodeData &printable_node) { return printable_node.data.DebugString(&stream); } -std::ostream& operator<<(std::ostream& stream, - const PrintableIndexingFactNode& printable_node) { +std::ostream &operator<<(std::ostream &stream, + const PrintableIndexingFactNode &printable_node) { return PrintTree( printable_node.data, &stream, - [&printable_node](std::ostream& s, - const IndexingNodeData& d) -> std::ostream& { + [&printable_node](std::ostream &s, + const IndexingNodeData &d) -> std::ostream & { return s << PrintableIndexingNodeData(d, printable_node.base); }); } diff --git a/verilog/tools/kythe/indexing_facts_tree.h b/verilog/tools/kythe/indexing_facts_tree.h index 7f70b7061..4e6f5bf1c 100644 --- a/verilog/tools/kythe/indexing_facts_tree.h +++ b/verilog/tools/kythe/indexing_facts_tree.h @@ -53,7 +53,7 @@ class Anchor { // Delegates construction to use only the string_view spanned by a TokenInfo. // Recall the TokenInfo's string point to substrings of memory owned // elsewhere. - explicit Anchor(const verible::TokenInfo& token, + explicit Anchor(const verible::TokenInfo &token, absl::string_view source_content) : content_(token.text()) { const int token_left = token.left(source_content); @@ -61,10 +61,10 @@ class Anchor { source_text_range_.emplace(token_left, token_right - token_left); } - Anchor(const Anchor&); // TODO(fangism): delete, move-only - Anchor(Anchor&&) = default; - Anchor& operator=(const Anchor&) = delete; - Anchor& operator=(Anchor&&) = delete; + Anchor(const Anchor &); // TODO(fangism): delete, move-only + Anchor(Anchor &&) = default; + Anchor &operator=(const Anchor &) = delete; + Anchor &operator=(Anchor &&) = delete; // Returns human readable view of this Anchor. std::string DebugString() const; @@ -72,12 +72,12 @@ class Anchor { absl::string_view Text() const { return content_; } // Returns the location of the Anchor's content in the original string. - const std::optional& SourceTextRange() const { + const std::optional &SourceTextRange() const { return source_text_range_; } - bool operator==(const Anchor&) const; - bool operator!=(const Anchor& other) const { return !(*this == other); } + bool operator==(const Anchor &) const; + bool operator!=(const Anchor &other) const { return !(*this == other); } private: // Substring of the original text that corresponds to this Anchor. @@ -86,7 +86,7 @@ class Anchor { std::optional source_text_range_; }; -std::ostream& operator<<(std::ostream&, const Anchor&); +std::ostream &operator<<(std::ostream &, const Anchor &); // This class is a simplified representation of CST and contains information // that can be used for extracting indexing-facts for different indexing tools. @@ -97,32 +97,32 @@ class IndexingNodeData { public: template /* implicit */ IndexingNodeData(IndexingFactType language_feature, // NOLINT - Args&&... args) + Args &&...args) : indexing_fact_type_(language_feature) { AppendAnchor(std::forward(args)...); } - IndexingNodeData(const IndexingNodeData&) = default; - IndexingNodeData& operator=(IndexingNodeData&&) = default; + IndexingNodeData(const IndexingNodeData &) = default; + IndexingNodeData &operator=(IndexingNodeData &&) = default; // TODO(fangism): delete copy-ctor to make this move-only - IndexingNodeData(IndexingNodeData&&) = default; - IndexingNodeData& operator=(const IndexingNodeData&) = delete; + IndexingNodeData(IndexingNodeData &&) = default; + IndexingNodeData &operator=(const IndexingNodeData &) = delete; // Consume an Anchor object(s), variadically. template - void AppendAnchor(Anchor&& anchor, Args&&... args) { + void AppendAnchor(Anchor &&anchor, Args &&...args) { anchors_.emplace_back(std::move(anchor)); AppendAnchor(std::forward(args)...); } // Swaps the anchors with the given IndexingNodeData. - void SwapAnchors(IndexingNodeData* other) { anchors_.swap(other->anchors_); } + void SwapAnchors(IndexingNodeData *other) { anchors_.swap(other->anchors_); } // Returns human readable view of this node. - std::ostream& DebugString(std::ostream* stream) const; + std::ostream &DebugString(std::ostream *stream) const; - const std::vector& Anchors() const { return anchors_; } + const std::vector &Anchors() const { return anchors_; } IndexingFactType GetIndexingFactType() const { return indexing_fact_type_; } // Redirects all non-owned string_views to point into a different copy of the @@ -130,8 +130,8 @@ class IndexingNodeData { // text is copied to a different location. void RebaseStringViewsForTesting(std::ptrdiff_t delta); - bool operator==(const IndexingNodeData&) const; - bool operator!=(const IndexingNodeData& other) const { + bool operator==(const IndexingNodeData &) const; + bool operator!=(const IndexingNodeData &other) const { return !(*this == other); } @@ -150,39 +150,39 @@ class IndexingNodeData { // Without a base string_view, this displays the base-address and length of each // Anchor's string_view. See PrintableIndexingNodeData for a more readable // alternative using byte-offsets. -std::ostream& operator<<(std::ostream&, const IndexingNodeData&); +std::ostream &operator<<(std::ostream &, const IndexingNodeData &); // Pairs together IndexingNodeData and string_view to be a printable object. struct PrintableIndexingNodeData { - const IndexingNodeData& data; + const IndexingNodeData &data; // The superstring of which all string_views in this subtree is a substring. const absl::string_view base; - PrintableIndexingNodeData(const IndexingNodeData& data, + PrintableIndexingNodeData(const IndexingNodeData &data, absl::string_view base) : data(data), base(base) {} }; // Human-readable form for debugging, showing in-file byte offsets of // string_views. -std::ostream& operator<<(std::ostream&, const PrintableIndexingNodeData&); +std::ostream &operator<<(std::ostream &, const PrintableIndexingNodeData &); // Renaming for VectorTree; IndexingFactNode is actually a VectorTree which is a // class for constructing trees and dealing with them in a elegant manner. using IndexingFactNode = verible::VectorTree; struct PrintableIndexingFactNode { - const IndexingFactNode& data; + const IndexingFactNode &data; // The superstring of which all string_views in this subtree is a substring. const absl::string_view base; - PrintableIndexingFactNode(const IndexingFactNode& data, + PrintableIndexingFactNode(const IndexingFactNode &data, absl::string_view base) : data(data), base(base) {} }; // Human-readable form for debugging. -std::ostream& operator<<(std::ostream&, const PrintableIndexingFactNode&); +std::ostream &operator<<(std::ostream &, const PrintableIndexingFactNode &); } // namespace kythe } // namespace verilog diff --git a/verilog/tools/kythe/indexing_facts_tree_context.h b/verilog/tools/kythe/indexing_facts_tree_context.h index 4ac6637a3..9b9690b07 100644 --- a/verilog/tools/kythe/indexing_facts_tree_context.h +++ b/verilog/tools/kythe/indexing_facts_tree_context.h @@ -24,16 +24,16 @@ namespace kythe { // Container with a stack of IndexingFactNode to hold context of // IndexingFactNodes during traversal of an IndexingFactsTree. class IndexingFactsTreeContext - : public verible::AutoPopStack { + : public verible::AutoPopStack { public: - using base_type = verible::AutoPopStack; + using base_type = verible::AutoPopStack; // member class to handle push and pop of stack safely using AutoPop = base_type::AutoPop; public: // returns the top IndexingFactsNode of the stack. - IndexingFactNode& top() { return *ABSL_DIE_IF_NULL(base_type::top()); } + IndexingFactNode &top() { return *ABSL_DIE_IF_NULL(base_type::top()); } }; } // namespace kythe diff --git a/verilog/tools/kythe/indexing_facts_tree_extractor.cc b/verilog/tools/kythe/indexing_facts_tree_extractor.cc index 814ef8749..810512d85 100644 --- a/verilog/tools/kythe/indexing_facts_tree_extractor.cc +++ b/verilog/tools/kythe/indexing_facts_tree_extractor.cc @@ -61,20 +61,20 @@ using verible::TreeSearchMatch; struct VerilogExtractionState { // Multi-file tracker. - VerilogProject* const project; + VerilogProject *const project; // Keep track of which files (translation units, includes) have been // extracted. - std::set extracted_files; + std::set extracted_files; }; // This class is used for traversing CST and extracting different indexing // facts from CST nodes and constructs a tree of indexing facts. class IndexingFactsTreeExtractor : public verible::TreeContextVisitor { public: - IndexingFactsTreeExtractor(IndexingFactNode* file_list_facts_tree, - const VerilogSourceFile& source_file, - VerilogExtractionState* extraction_state, - std::vector* errors) + IndexingFactsTreeExtractor(IndexingFactNode *file_list_facts_tree, + const VerilogSourceFile &source_file, + VerilogExtractionState *extraction_state, + std::vector *errors) : file_list_facts_tree_(file_list_facts_tree), source_file_(source_file), extraction_state_(extraction_state), @@ -87,199 +87,199 @@ class IndexingFactsTreeExtractor : public verible::TreeContextVisitor { Anchor(base)); } - void Visit(const SyntaxTreeLeaf& leaf) final; - void Visit(const SyntaxTreeNode& node) final; + void Visit(const SyntaxTreeLeaf &leaf) final; + void Visit(const SyntaxTreeNode &node) final; - const IndexingFactNode& Root() const { return root_; } + const IndexingFactNode &Root() const { return root_; } IndexingFactNode TakeRoot() { return std::move(root_); } private: // methods // Extracts facts from module, intraface and program declarations. - void ExtractModuleOrInterfaceOrProgram(const SyntaxTreeNode& declaration_node, + void ExtractModuleOrInterfaceOrProgram(const SyntaxTreeNode &declaration_node, IndexingFactType node_type); // Extracts modules instantiations and creates its corresponding fact tree. void ExtractModuleInstantiation( - const SyntaxTreeNode& data_declaration_node, - const std::vector& gate_instances); + const SyntaxTreeNode &data_declaration_node, + const std::vector &gate_instances); // Extracts endmodule, endinterface, endprogram and creates its corresponding // fact tree. void ExtractModuleOrInterfaceOrProgramEnd( - const SyntaxTreeNode& module_declaration_node); + const SyntaxTreeNode &module_declaration_node); // Extracts module, interface, program headers and creates its corresponding // fact tree. void ExtractModuleOrInterfaceOrProgramHeader( - const SyntaxTreeNode& module_declaration_node); + const SyntaxTreeNode &module_declaration_node); // Extracts modules ports and creates its corresponding fact tree. // "has_propagated_type" determines if this port is "Non-ANSI" or not. // e.g "module m(a, b, input c, d)" starting from "c" "has_propagated_type" // will be true. - void ExtractModulePort(const SyntaxTreeNode& module_port_node, + void ExtractModulePort(const SyntaxTreeNode &module_port_node, bool has_propagated_type); // Extracts "a" from "input a", "output a" and creates its corresponding fact // tree. void ExtractInputOutputDeclaration( - const SyntaxTreeNode& identifier_unpacked_dimensions); + const SyntaxTreeNode &identifier_unpacked_dimensions); // Extracts "a" from "wire a" and creates its corresponding fact tree. - void ExtractNetDeclaration(const SyntaxTreeNode& net_declaration_node); + void ExtractNetDeclaration(const SyntaxTreeNode &net_declaration_node); // Extract package declarations and creates its corresponding facts tree. void ExtractPackageDeclaration( - const SyntaxTreeNode& package_declaration_node); + const SyntaxTreeNode &package_declaration_node); // Extract macro definitions and explores its arguments and creates its // corresponding facts tree. - void ExtractMacroDefinition(const SyntaxTreeNode& preprocessor_definition); + void ExtractMacroDefinition(const SyntaxTreeNode &preprocessor_definition); // Extract macro calls and explores its arguments and creates its // corresponding facts tree. - void ExtractMacroCall(const SyntaxTreeNode& macro_call); + void ExtractMacroCall(const SyntaxTreeNode ¯o_call); // Extract macro names from "kMacroIdentifiers" which are considered // references to macros and creates its corresponding facts tree. - void ExtractMacroReference(const SyntaxTreeLeaf& macro_identifier); + void ExtractMacroReference(const SyntaxTreeLeaf ¯o_identifier); // Extracts Include statements and creates its corresponding fact tree. - void ExtractInclude(const SyntaxTreeNode& preprocessor_include); + void ExtractInclude(const SyntaxTreeNode &preprocessor_include); // Extracts function and creates its corresponding fact tree. void ExtractFunctionDeclaration( - const SyntaxTreeNode& function_declaration_node); + const SyntaxTreeNode &function_declaration_node); // Extracts class constructor and creates its corresponding fact tree. - void ExtractClassConstructor(const SyntaxTreeNode& class_constructor); + void ExtractClassConstructor(const SyntaxTreeNode &class_constructor); // Extracts task and creates its corresponding fact tree. - void ExtractTaskDeclaration(const SyntaxTreeNode& task_declaration_node); + void ExtractTaskDeclaration(const SyntaxTreeNode &task_declaration_node); // Extracts function or task call and creates its corresponding fact tree. - void ExtractFunctionOrTaskCall(const SyntaxTreeNode& function_call_node); + void ExtractFunctionOrTaskCall(const SyntaxTreeNode &function_call_node); // Extracts function or task call tagged with "kMethodCallExtension" (treated // as kFunctionOrTaskCall in facts tree) and creates its corresponding fact // tree. - void ExtractMethodCallExtension(const SyntaxTreeNode& call_extension_node); + void ExtractMethodCallExtension(const SyntaxTreeNode &call_extension_node); // Extracts members tagged with "kHierarchyExtension" (treated as // kMemberReference in facts tree) and creates its corresponding fact tree. - void ExtractMemberExtension(const SyntaxTreeNode& hierarchy_extension_node); + void ExtractMemberExtension(const SyntaxTreeNode &hierarchy_extension_node); // Extracts function or task ports and parameters. void ExtractFunctionOrTaskOrConstructorPort( - const SyntaxTreeNode& function_declaration_node); + const SyntaxTreeNode &function_declaration_node); // Extracts classes and creates its corresponding fact tree. - void ExtractClassDeclaration(const SyntaxTreeNode& class_declaration); + void ExtractClassDeclaration(const SyntaxTreeNode &class_declaration); // Extracts class instances and creates its corresponding fact tree. void ExtractClassInstances( - const SyntaxTreeNode& data_declaration, - const std::vector& class_instances); + const SyntaxTreeNode &data_declaration, + const std::vector &class_instances); // Extracts primitive types declarations tagged with kRegisterVariable and // creates its corresponding fact tree. - void ExtractRegisterVariable(const SyntaxTreeNode& register_variable); + void ExtractRegisterVariable(const SyntaxTreeNode ®ister_variable); // Extracts primitive types declarations tagged with // kVariableDeclarationAssignment and creates its corresponding fact tree. void ExtractVariableDeclarationAssignment( - const SyntaxTreeNode& variable_declaration_assignment); + const SyntaxTreeNode &variable_declaration_assignment); // Extracts enum name and creates its corresponding fact tree. - void ExtractEnumName(const SyntaxTreeNode& enum_name); + void ExtractEnumName(const SyntaxTreeNode &enum_name); // Extracts type declaration preceeded with "typedef" and creates its // corresponding fact tree. - void ExtractTypeDeclaration(const SyntaxTreeNode& type_declaration); + void ExtractTypeDeclaration(const SyntaxTreeNode &type_declaration); // Extracts pure virtual functions and creates its corresponding fact tree. - void ExtractPureVirtualFunction(const SyntaxTreeNode& function_prototype); + void ExtractPureVirtualFunction(const SyntaxTreeNode &function_prototype); // Extracts pure virtual tasks and creates its corresponding fact tree. - void ExtractPureVirtualTask(const SyntaxTreeNode& task_prototype); + void ExtractPureVirtualTask(const SyntaxTreeNode &task_prototype); // Extracts function header and creates its corresponding fact tree. - void ExtractFunctionHeader(const SyntaxTreeNode& function_header, - IndexingFactNode* function_node); + void ExtractFunctionHeader(const SyntaxTreeNode &function_header, + IndexingFactNode *function_node); // Extracts task header and creates its corresponding fact tree. - void ExtractTaskHeader(const SyntaxTreeNode& task_header, - IndexingFactNode* task_node); + void ExtractTaskHeader(const SyntaxTreeNode &task_header, + IndexingFactNode *task_node); // Extracts enum type declaration preceeded with "typedef" and creates its // corresponding fact tree. - void ExtractEnumTypeDeclaration(const SyntaxTreeNode& enum_type_declaration); + void ExtractEnumTypeDeclaration(const SyntaxTreeNode &enum_type_declaration); // Extracts struct type declaration preceeded with "typedef" and creates its // corresponding fact tree. - void ExtractStructUnionTypeDeclaration(const SyntaxTreeNode& type_declaration, - const SyntaxTreeNode& struct_type); + void ExtractStructUnionTypeDeclaration(const SyntaxTreeNode &type_declaration, + const SyntaxTreeNode &struct_type); // Extracts struct declaration and creates its corresponding fact tree. void ExtractStructUnionDeclaration( - const SyntaxTreeNode& struct_type, - const std::vector& variables_matched); + const SyntaxTreeNode &struct_type, + const std::vector &variables_matched); // Extracts struct and union members and creates its corresponding fact tree. void ExtractDataTypeImplicitIdDimensions( - const SyntaxTreeNode& data_type_implicit_id_dimensions); + const SyntaxTreeNode &data_type_implicit_id_dimensions); // Extracts variable definitions preceeded with some data type and creates its // corresponding fact tree. // e.g "some_type var1;" void ExtractTypedVariableDefinition( - const Symbol& type_identifier, - const std::vector& variables_matched); + const Symbol &type_identifier, + const std::vector &variables_matched); // Extracts leaves tagged with SymbolIdentifier and creates its facts // tree. This should only be reached in case of free variable references. // e.g "assign out = in & in2." // Other extraction functions should terminate in case the inner // SymbolIdentifiers are extracted. - void ExtractSymbolIdentifier(const SyntaxTreeLeaf& symbol_identifier); + void ExtractSymbolIdentifier(const SyntaxTreeLeaf &symbol_identifier); // Extracts nodes tagged with "kUnqualifiedId". - void ExtractUnqualifiedId(const SyntaxTreeNode& unqualified_id); + void ExtractUnqualifiedId(const SyntaxTreeNode &unqualified_id); // Extracts parameter declarations and creates its corresponding fact tree. - void ExtractParamDeclaration(const SyntaxTreeNode& param_declaration); + void ExtractParamDeclaration(const SyntaxTreeNode ¶m_declaration); // Extracts module instantiation named ports and creates its corresponding // fact tree. - void ExtractModuleNamedPort(const SyntaxTreeNode& actual_named_port); + void ExtractModuleNamedPort(const SyntaxTreeNode &actual_named_port); // Extracts package imports and creates its corresponding fact tree. - void ExtractPackageImport(const SyntaxTreeNode& package_import_item); + void ExtractPackageImport(const SyntaxTreeNode &package_import_item); // Extracts qualified ids and creates its corresponding fact tree. // e.g "pkg::member" or "class::member". - void ExtractQualifiedId(const SyntaxTreeNode& qualified_id); + void ExtractQualifiedId(const SyntaxTreeNode &qualified_id); // Extracts initializations in for loop and creates its corresponding fact // tree. e.g from "for(int i = 0, j = k; ...)" extracts "i", "j" and "k". - void ExtractForInitialization(const SyntaxTreeNode& for_initialization); + void ExtractForInitialization(const SyntaxTreeNode &for_initialization); // Extracts param references and the actual references names. // e.g from "counter #(.N(r))" extracts "N". - void ExtractParamByName(const SyntaxTreeNode& param_by_name); + void ExtractParamByName(const SyntaxTreeNode ¶m_by_name); // Extracts new scope and assign unique id to it. // specifically, intended for conditional/loop generate constructs. - void ExtractAnonymousScope(const SyntaxTreeNode& node); + void ExtractAnonymousScope(const SyntaxTreeNode &node); // Determines how to deal with the given data declaration node as it may be // module instance, class instance or primitive variable. - void ExtractDataDeclaration(const SyntaxTreeNode& data_declaration); + void ExtractDataDeclaration(const SyntaxTreeNode &data_declaration); // Moves the anchors and children from the the last extracted node in // "facts_tree_context_", adds them to the new_node and pops remove the last // extracted node. - void MoveAndDeleteLastExtractedNode(IndexingFactNode* new_node); + void MoveAndDeleteLastExtractedNode(IndexingFactNode *new_node); absl::string_view FileContent() { return source_file_.GetTextStructure()->Contents(); @@ -296,16 +296,16 @@ class IndexingFactsTreeExtractor : public verible::TreeContextVisitor { // facts trees of the files in the ordered file list. The extracted files will // be children of this node and ordered as they are given in the ordered file // list. - IndexingFactNode* file_list_facts_tree_; + IndexingFactNode *file_list_facts_tree_; // The current file being extracted. - const VerilogSourceFile& source_file_; + const VerilogSourceFile &source_file_; // The project configuration used to find included files. - VerilogExtractionState* const extraction_state_; + VerilogExtractionState *const extraction_state_; // Processing errors. - std::vector* errors_; + std::vector *errors_; // Counter used as an id for the anonymous scopes. int next_anonymous_id = 0; @@ -314,16 +314,16 @@ class IndexingFactsTreeExtractor : public verible::TreeContextVisitor { // Given a root to CST this function traverses the tree, extracts and constructs // the indexing facts tree for one file. IndexingFactNode BuildIndexingFactsTree( - IndexingFactNode* file_list_facts_tree, - const VerilogSourceFile& source_file, - VerilogExtractionState* extraction_state, - std::vector* errors) { + IndexingFactNode *file_list_facts_tree, + const VerilogSourceFile &source_file, + VerilogExtractionState *extraction_state, + std::vector *errors) { VLOG(1) << __FUNCTION__ << ": file: " << source_file; IndexingFactsTreeExtractor visitor(file_list_facts_tree, source_file, extraction_state, errors); if (source_file.Status().ok()) { - const auto& syntax_tree = source_file.GetTextStructure()->SyntaxTree(); + const auto &syntax_tree = source_file.GetTextStructure()->SyntaxTree(); if (syntax_tree != nullptr) { VLOG(2) << "syntax:\n" << verible::RawTreePrinter(*syntax_tree); syntax_tree->Accept(&visitor); @@ -338,9 +338,9 @@ IndexingFactNode BuildIndexingFactsTree( } // namespace IndexingFactNode ExtractFiles(absl::string_view file_list_path, - VerilogProject* project, - const std::vector& file_names, - std::vector* errors) { + VerilogProject *project, + const std::vector &file_names, + std::vector *errors) { VLOG(1) << __FUNCTION__; // Open all of the translation units. for (absl::string_view file_name : file_names) { @@ -369,7 +369,7 @@ IndexingFactNode ExtractFiles(absl::string_view file_list_path, // pre-allocate file nodes with the number of translation units file_list_facts_tree.Children().reserve(file_names.size()); for (absl::string_view file_name : file_names) { - auto* translation_unit = project->LookupRegisteredFile(file_name); + auto *translation_unit = project->LookupRegisteredFile(file_name); if (translation_unit == nullptr) continue; const auto parse_status = translation_unit->Parse(); // status is also stored in translation_unit for later retrieval. @@ -391,7 +391,7 @@ IndexingFactNode ExtractFiles(absl::string_view file_list_path, return file_list_facts_tree; } -void IndexingFactsTreeExtractor::Visit(const SyntaxTreeNode& node) { +void IndexingFactsTreeExtractor::Visit(const SyntaxTreeNode &node) { const auto tag = static_cast(node.Tag().tag); VLOG(3) << __FUNCTION__ << ", tag: " << tag; switch (tag) { @@ -550,7 +550,7 @@ void IndexingFactsTreeExtractor::Visit(const SyntaxTreeNode& node) { VLOG(3) << "end of " << __FUNCTION__ << ", tag: " << tag; } -void IndexingFactsTreeExtractor::Visit(const SyntaxTreeLeaf& leaf) { +void IndexingFactsTreeExtractor::Visit(const SyntaxTreeLeaf &leaf) { switch (leaf.get().token_enum()) { case verilog_tokentype::SymbolIdentifier: { ExtractSymbolIdentifier(leaf); @@ -563,14 +563,14 @@ void IndexingFactsTreeExtractor::Visit(const SyntaxTreeLeaf& leaf) { } void IndexingFactsTreeExtractor::ExtractSymbolIdentifier( - const SyntaxTreeLeaf& symbol_identifier) { + const SyntaxTreeLeaf &symbol_identifier) { facts_tree_context_.top().Children().emplace_back( IndexingNodeData(IndexingFactType::kVariableReference, Anchor(symbol_identifier.get(), FileContent()))); } void IndexingFactsTreeExtractor::ExtractDataDeclaration( - const SyntaxTreeNode& data_declaration) { + const SyntaxTreeNode &data_declaration) { // For module instantiations const std::vector gate_instances = FindAllGateInstances(data_declaration); @@ -592,7 +592,7 @@ void IndexingFactsTreeExtractor::ExtractDataDeclaration( } // for struct and union types. - const SyntaxTreeNode* type_node = + const SyntaxTreeNode *type_node = GetStructOrUnionOrEnumTypeFromDataDeclaration(data_declaration); // Ignore if this isn't a struct or union type. @@ -603,7 +603,7 @@ void IndexingFactsTreeExtractor::ExtractDataDeclaration( } // In case "some_type var1". - const Symbol* type_identifier = + const Symbol *type_identifier = GetTypeIdentifierFromDataDeclaration(data_declaration); if (type_identifier != nullptr) { ExtractTypedVariableDefinition(*type_identifier, register_variables); @@ -628,7 +628,7 @@ void IndexingFactsTreeExtractor::ExtractDataDeclaration( } // for struct and union types. - const SyntaxTreeNode* type_node = + const SyntaxTreeNode *type_node = GetStructOrUnionOrEnumTypeFromDataDeclaration(data_declaration); // Ignore if this isn't a struct or union type. @@ -639,7 +639,7 @@ void IndexingFactsTreeExtractor::ExtractDataDeclaration( } // In case "some_type var1". - const Symbol* type_identifier = + const Symbol *type_identifier = GetTypeIdentifierFromDataDeclaration(data_declaration); if (type_identifier != nullptr) { ExtractTypedVariableDefinition(*type_identifier, @@ -657,8 +657,8 @@ void IndexingFactsTreeExtractor::ExtractDataDeclaration( } void IndexingFactsTreeExtractor::ExtractTypedVariableDefinition( - const Symbol& type_identifier, - const std::vector& variables_matche) { + const Symbol &type_identifier, + const std::vector &variables_matche) { IndexingFactNode type_node( IndexingNodeData{IndexingFactType::kDataTypeReference}); @@ -667,7 +667,7 @@ void IndexingFactsTreeExtractor::ExtractTypedVariableDefinition( { const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &type_node); - for (const TreeSearchMatch& variable : variables_matche) { + for (const TreeSearchMatch &variable : variables_matche) { variable.match->Accept(this); } } @@ -676,7 +676,7 @@ void IndexingFactsTreeExtractor::ExtractTypedVariableDefinition( } void IndexingFactsTreeExtractor::ExtractModuleOrInterfaceOrProgram( - const SyntaxTreeNode& declaration_node, IndexingFactType node_type) { + const SyntaxTreeNode &declaration_node, IndexingFactType node_type) { IndexingFactNode facts_node(IndexingNodeData{node_type}); { @@ -685,7 +685,7 @@ void IndexingFactsTreeExtractor::ExtractModuleOrInterfaceOrProgram( ExtractModuleOrInterfaceOrProgramHeader(declaration_node); ExtractModuleOrInterfaceOrProgramEnd(declaration_node); - const SyntaxTreeNode* item_list = GetModuleItemList(declaration_node); + const SyntaxTreeNode *item_list = GetModuleItemList(declaration_node); if (item_list) Visit(*item_list); } @@ -693,16 +693,16 @@ void IndexingFactsTreeExtractor::ExtractModuleOrInterfaceOrProgram( } void IndexingFactsTreeExtractor::ExtractModuleOrInterfaceOrProgramHeader( - const SyntaxTreeNode& module_declaration_node) { + const SyntaxTreeNode &module_declaration_node) { // Extract module name e.g from "module my_module" extracts "my_module". - const SyntaxTreeLeaf* module_name_leaf = + const SyntaxTreeLeaf *module_name_leaf = GetModuleName(module_declaration_node); if (!module_name_leaf) return; facts_tree_context_.top().Value().AppendAnchor( Anchor(module_name_leaf->get(), FileContent())); // Extract parameters if exist. - const SyntaxTreeNode* param_declaration_list = + const SyntaxTreeNode *param_declaration_list = GetParamDeclarationListFromModuleDeclaration(module_declaration_node); if (param_declaration_list != nullptr) { Visit(*param_declaration_list); @@ -710,7 +710,7 @@ void IndexingFactsTreeExtractor::ExtractModuleOrInterfaceOrProgramHeader( // Extracting module ports e.g. (input a, input b). // Ports are treated as children of the module. - const SyntaxTreeNode* port_list = + const SyntaxTreeNode *port_list = GetModulePortDeclarationList(module_declaration_node); if (port_list == nullptr) { @@ -729,30 +729,30 @@ void IndexingFactsTreeExtractor::ExtractModuleOrInterfaceOrProgramHeader( // The boolean is used to determine whether this the fact for this variable // should be a reference or a defintiion. bool has_propagated_type = false; - for (const auto& port : port_list->children()) { + for (const auto &port : port_list->children()) { if (port->Kind() == SymbolKind::kLeaf) continue; - const SyntaxTreeNode& port_node = SymbolCastToNode(*port); + const SyntaxTreeNode &port_node = SymbolCastToNode(*port); const auto tag = static_cast(port_node.Tag().tag); if (tag == NodeEnum::kPortDeclaration) { has_propagated_type = true; ExtractModulePort(port_node, has_propagated_type); } else if (tag == NodeEnum::kPort) { - const SyntaxTreeNode* ref_port = GetPortReferenceFromPort(port_node); + const SyntaxTreeNode *ref_port = GetPortReferenceFromPort(port_node); if (ref_port) ExtractModulePort(*ref_port, has_propagated_type); } } } void IndexingFactsTreeExtractor::ExtractModulePort( - const SyntaxTreeNode& module_port_node, bool has_propagated_type) { + const SyntaxTreeNode &module_port_node, bool has_propagated_type) { const auto tag = static_cast(module_port_node.Tag().tag); // For extracting cases like: // module m(input a, input b); if (tag == NodeEnum::kPortDeclaration) { - const SyntaxTreeLeaf* leaf = + const SyntaxTreeLeaf *leaf = GetIdentifierFromPortDeclaration(module_port_node); if (!leaf) return; @@ -762,7 +762,7 @@ void IndexingFactsTreeExtractor::ExtractModulePort( } else if (tag == NodeEnum::kPortReference) { // For extracting Non-ANSI style ports: // module m(a, b); - const SyntaxTreeLeaf* leaf = + const SyntaxTreeLeaf *leaf = GetIdentifierFromPortReference(module_port_node); if (!leaf) return; @@ -795,7 +795,7 @@ void IndexingFactsTreeExtractor::ExtractModulePort( } // Extract unpacked and packed dimensions. - for (const auto& child : module_port_node.children()) { + for (const auto &child : module_port_node.children()) { if (child == nullptr || child->Kind() == SymbolKind::kLeaf) { continue; } @@ -804,7 +804,7 @@ void IndexingFactsTreeExtractor::ExtractModulePort( continue; } if (tag == NodeEnum::kDataType) { - const SyntaxTreeNode* data_type = GetTypeIdentifierFromDataType(*child); + const SyntaxTreeNode *data_type = GetTypeIdentifierFromDataType(*child); // If not null this is a non primitive type and should create // kDataTypeReference node for it. // This data_type may be some class or interface type. @@ -828,8 +828,8 @@ void IndexingFactsTreeExtractor::ExtractModulePort( } void IndexingFactsTreeExtractor::ExtractModuleNamedPort( - const SyntaxTreeNode& actual_named_port) { - const SyntaxTreeLeaf* named_port = GetActualNamedPortName(actual_named_port); + const SyntaxTreeNode &actual_named_port) { + const SyntaxTreeLeaf *named_port = GetActualNamedPortName(actual_named_port); if (!named_port) return; IndexingFactNode actual_port_node( IndexingNodeData(IndexingFactType::kModuleNamedPort, @@ -837,7 +837,7 @@ void IndexingFactsTreeExtractor::ExtractModuleNamedPort( { const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &actual_port_node); - const Symbol* paren_group = GetActualNamedPortParenGroup(actual_named_port); + const Symbol *paren_group = GetActualNamedPortParenGroup(actual_named_port); if (paren_group != nullptr) { paren_group->Accept(this); } @@ -848,8 +848,8 @@ void IndexingFactsTreeExtractor::ExtractModuleNamedPort( } void IndexingFactsTreeExtractor::ExtractInputOutputDeclaration( - const SyntaxTreeNode& identifier_unpacked_dimension) { - const SyntaxTreeLeaf* port_name_leaf = + const SyntaxTreeNode &identifier_unpacked_dimension) { + const SyntaxTreeLeaf *port_name_leaf = GetSymbolIdentifierFromIdentifierUnpackedDimensions( identifier_unpacked_dimension); @@ -861,8 +861,8 @@ void IndexingFactsTreeExtractor::ExtractInputOutputDeclaration( } void IndexingFactsTreeExtractor::ExtractModuleOrInterfaceOrProgramEnd( - const SyntaxTreeNode& module_declaration_node) { - const SyntaxTreeLeaf* module_name = + const SyntaxTreeNode &module_declaration_node) { + const SyntaxTreeLeaf *module_name = GetModuleEndLabel(module_declaration_node); if (module_name != nullptr) { @@ -872,10 +872,10 @@ void IndexingFactsTreeExtractor::ExtractModuleOrInterfaceOrProgramEnd( } void IndexingFactsTreeExtractor::ExtractModuleInstantiation( - const SyntaxTreeNode& data_declaration_node, - const std::vector& gate_instances) { + const SyntaxTreeNode &data_declaration_node, + const std::vector &gate_instances) { // Extract module type name. - const Symbol* type = + const Symbol *type = GetTypeIdentifierFromDataDeclaration(data_declaration_node); if (type == nullptr) { return; @@ -895,17 +895,17 @@ void IndexingFactsTreeExtractor::ExtractModuleInstantiation( IndexingFactNode function_node( IndexingNodeData{IndexingFactType::kFunctionCall}); { - const verible::Symbol* instantiation_base = GetSubtreeAsSymbol( + const verible::Symbol *instantiation_base = GetSubtreeAsSymbol( data_declaration_node, NodeEnum::kDataDeclaration, 1); if (!instantiation_base) return; - const verible::Symbol* type = GetSubtreeAsSymbol( + const verible::Symbol *type = GetSubtreeAsSymbol( *instantiation_base, NodeEnum::kInstantiationBase, 0); - const verible::Symbol* reference = + const verible::Symbol *reference = GetSubtreeAsSymbol(*type, NodeEnum::kInstantiationType, 0); if (reference->Tag().tag == (int)NodeEnum::kReference && SymbolCastToNode(*reference).children().size() > 1) { - const auto& children = SymbolCastToNode(*reference).children(); - for (auto& child : + const auto &children = SymbolCastToNode(*reference).children(); + for (auto &child : verible::make_range(children.begin() + 1, children.end())) { if (child->Tag().tag == (int)NodeEnum::kHierarchyExtension) { Visit(verible::SymbolCastToNode(*child)); @@ -914,7 +914,7 @@ void IndexingFactsTreeExtractor::ExtractModuleInstantiation( } } MoveAndDeleteLastExtractedNode(&function_node); - const SyntaxTreeNode* paren_group = + const SyntaxTreeNode *paren_group = GetParenGroupFromModuleInstantiation(*gate_instances[0].match); if (paren_group) { const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, @@ -932,11 +932,11 @@ void IndexingFactsTreeExtractor::ExtractModuleInstantiation( // Loop through each instance and associate each declared id with the same // type and create its corresponding facts tree node. - for (const TreeSearchMatch& instance : gate_instances) { + for (const TreeSearchMatch &instance : gate_instances) { IndexingFactNode module_instance_node( IndexingNodeData{IndexingFactType::kModuleInstance}); - const TokenInfo* variable_name = + const TokenInfo *variable_name = GetModuleInstanceNameTokenInfoFromGateInstance(*instance.match); if (variable_name) { module_instance_node.Value().AppendAnchor( @@ -946,7 +946,7 @@ void IndexingFactsTreeExtractor::ExtractModuleInstantiation( { const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &module_instance_node); - const SyntaxTreeNode* paren_group = + const SyntaxTreeNode *paren_group = GetParenGroupFromModuleInstantiation(*instance.match); if (paren_group) Visit(*paren_group); } @@ -958,16 +958,16 @@ void IndexingFactsTreeExtractor::ExtractModuleInstantiation( } void IndexingFactsTreeExtractor::ExtractNetDeclaration( - const SyntaxTreeNode& net_declaration_node) { + const SyntaxTreeNode &net_declaration_node) { // Nets are treated as children of the enclosing parent. // Net declarations may declare multiple instances sharing the same type in // a single statement. - const std::vector identifiers = + const std::vector identifiers = GetIdentifiersFromNetDeclaration(net_declaration_node); // Loop through each instance and associate each declared id with the same // type. - for (const TokenInfo* wire_token_info : identifiers) { + for (const TokenInfo *wire_token_info : identifiers) { facts_tree_context_.top().Children().emplace_back( IndexingNodeData(IndexingFactType::kVariableDefinition, Anchor(*wire_token_info, FileContent()))); @@ -975,21 +975,21 @@ void IndexingFactsTreeExtractor::ExtractNetDeclaration( } void IndexingFactsTreeExtractor::ExtractPackageDeclaration( - const SyntaxTreeNode& package_declaration_node) { + const SyntaxTreeNode &package_declaration_node) { IndexingFactNode package_node(IndexingNodeData{IndexingFactType::kPackage}); { const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &package_node); // Extract package name. - const SyntaxTreeLeaf* pname = GetPackageNameLeaf(package_declaration_node); + const SyntaxTreeLeaf *pname = GetPackageNameLeaf(package_declaration_node); if (pname) { facts_tree_context_.top().Value().AppendAnchor( Anchor(pname->get(), FileContent())); } // Extract package name after endpackage if exists. - const SyntaxTreeLeaf* package_end_name = + const SyntaxTreeLeaf *package_end_name = GetPackageNameEndLabel(package_declaration_node); if (package_end_name != nullptr) { @@ -998,7 +998,7 @@ void IndexingFactsTreeExtractor::ExtractPackageDeclaration( } // Visit package body it exists. - const Symbol* package_item_list = + const Symbol *package_item_list = GetPackageItemList(package_declaration_node); if (package_item_list != nullptr) { package_item_list->Accept(this); @@ -1009,8 +1009,8 @@ void IndexingFactsTreeExtractor::ExtractPackageDeclaration( } void IndexingFactsTreeExtractor::ExtractMacroDefinition( - const SyntaxTreeNode& preprocessor_definition) { - const SyntaxTreeLeaf* macro_name = GetMacroName(preprocessor_definition); + const SyntaxTreeNode &preprocessor_definition) { + const SyntaxTreeLeaf *macro_name = GetMacroName(preprocessor_definition); if (!macro_name) return; IndexingFactNode macro_node(IndexingNodeData( IndexingFactType::kMacro, Anchor(macro_name->get(), FileContent()))); @@ -1019,8 +1019,8 @@ void IndexingFactsTreeExtractor::ExtractMacroDefinition( const std::vector args = FindAllMacroDefinitionsArgs(preprocessor_definition); - for (const TreeSearchMatch& arg : args) { - const SyntaxTreeLeaf* macro_arg_name = GetMacroArgName(*arg.match); + for (const TreeSearchMatch &arg : args) { + const SyntaxTreeLeaf *macro_arg_name = GetMacroArgName(*arg.match); if (macro_arg_name) { macro_node.Children().emplace_back( IndexingNodeData(IndexingFactType::kVariableDefinition, @@ -1031,7 +1031,7 @@ void IndexingFactsTreeExtractor::ExtractMacroDefinition( facts_tree_context_.top().Children().push_back(std::move(macro_node)); } -Anchor GetMacroAnchorFromTokenInfo(const TokenInfo& macro_token_info, +Anchor GetMacroAnchorFromTokenInfo(const TokenInfo ¯o_token_info, absl::string_view file_content) { // Strip the prefix "`". // e.g. @@ -1044,8 +1044,8 @@ Anchor GetMacroAnchorFromTokenInfo(const TokenInfo& macro_token_info, } void IndexingFactsTreeExtractor::ExtractMacroCall( - const SyntaxTreeNode& macro_call) { - const TokenInfo* macro_call_name_token = GetMacroCallId(macro_call); + const SyntaxTreeNode ¯o_call) { + const TokenInfo *macro_call_name_token = GetMacroCallId(macro_call); if (!macro_call_name_token) return; IndexingFactNode macro_node(IndexingNodeData( IndexingFactType::kMacroCall, @@ -1055,7 +1055,7 @@ void IndexingFactsTreeExtractor::ExtractMacroCall( const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, ¯o_node); - const SyntaxTreeNode* macro_call_args = GetMacroCallArgs(macro_call); + const SyntaxTreeNode *macro_call_args = GetMacroCallArgs(macro_call); if (macro_call_args) Visit(*macro_call_args); } @@ -1063,15 +1063,15 @@ void IndexingFactsTreeExtractor::ExtractMacroCall( } void IndexingFactsTreeExtractor::ExtractMacroReference( - const SyntaxTreeLeaf& macro_identifier) { + const SyntaxTreeLeaf ¯o_identifier) { facts_tree_context_.top().Children().emplace_back(IndexingNodeData( IndexingFactType::kMacroCall, GetMacroAnchorFromTokenInfo(macro_identifier.get(), FileContent()))); } void IndexingFactsTreeExtractor::ExtractClassConstructor( - const SyntaxTreeNode& class_constructor) { - const SyntaxTreeLeaf* new_keyword = + const SyntaxTreeNode &class_constructor) { + const SyntaxTreeLeaf *new_keyword = GetNewKeywordFromClassConstructor(class_constructor); if (!new_keyword) return; IndexingFactNode constructor_node( @@ -1086,7 +1086,7 @@ void IndexingFactsTreeExtractor::ExtractClassConstructor( ExtractFunctionOrTaskOrConstructorPort(class_constructor); // Extract constructor body. - const SyntaxTreeNode* constructor_body = + const SyntaxTreeNode *constructor_body = GetClassConstructorStatementList(class_constructor); if (constructor_body) Visit(*constructor_body); } @@ -1095,12 +1095,12 @@ void IndexingFactsTreeExtractor::ExtractClassConstructor( } void IndexingFactsTreeExtractor::ExtractPureVirtualFunction( - const SyntaxTreeNode& function_prototype) { + const SyntaxTreeNode &function_prototype) { IndexingFactNode function_node( IndexingNodeData{IndexingFactType::kFunctionOrTaskForwardDeclaration}); // Extract function header. - const SyntaxTreeNode* function_header = + const SyntaxTreeNode *function_header = GetFunctionPrototypeHeader(function_prototype); if (function_header) ExtractFunctionHeader(*function_header, &function_node); @@ -1108,24 +1108,24 @@ void IndexingFactsTreeExtractor::ExtractPureVirtualFunction( } void IndexingFactsTreeExtractor::ExtractPureVirtualTask( - const SyntaxTreeNode& task_prototype) { + const SyntaxTreeNode &task_prototype) { IndexingFactNode task_node( IndexingNodeData{IndexingFactType::kFunctionOrTaskForwardDeclaration}); // Extract task header. - const SyntaxTreeNode* task_header = GetTaskPrototypeHeader(task_prototype); + const SyntaxTreeNode *task_header = GetTaskPrototypeHeader(task_prototype); if (task_header) ExtractTaskHeader(*task_header, &task_node); facts_tree_context_.top().Children().push_back(std::move(task_node)); } void IndexingFactsTreeExtractor::ExtractFunctionDeclaration( - const SyntaxTreeNode& function_declaration_node) { + const SyntaxTreeNode &function_declaration_node) { IndexingFactNode function_node( IndexingNodeData{IndexingFactType::kFunctionOrTask}); // Extract function header. - const SyntaxTreeNode* function_header = + const SyntaxTreeNode *function_header = GetFunctionHeader(function_declaration_node); if (function_header) ExtractFunctionHeader(*function_header, &function_node); @@ -1133,7 +1133,7 @@ void IndexingFactsTreeExtractor::ExtractFunctionDeclaration( // Extract function body. const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &function_node); - const SyntaxTreeNode* function_body = + const SyntaxTreeNode *function_body = GetFunctionBlockStatementList(function_declaration_node); if (function_body) Visit(*function_body); } @@ -1142,18 +1142,18 @@ void IndexingFactsTreeExtractor::ExtractFunctionDeclaration( } void IndexingFactsTreeExtractor::ExtractTaskDeclaration( - const SyntaxTreeNode& task_declaration_node) { + const SyntaxTreeNode &task_declaration_node) { IndexingFactNode task_node( IndexingNodeData{IndexingFactType::kFunctionOrTask}); // Extract task header. - const SyntaxTreeNode* task_header = GetTaskHeader(task_declaration_node); + const SyntaxTreeNode *task_header = GetTaskHeader(task_declaration_node); if (task_header) ExtractTaskHeader(*task_header, &task_node); { // Extract task body. const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &task_node); - const SyntaxTreeNode* task_body = + const SyntaxTreeNode *task_body = GetTaskStatementList(task_declaration_node); if (task_body) Visit(*task_body); } @@ -1162,9 +1162,9 @@ void IndexingFactsTreeExtractor::ExtractTaskDeclaration( } void IndexingFactsTreeExtractor::ExtractFunctionHeader( - const SyntaxTreeNode& function_header, IndexingFactNode* function_node) { + const SyntaxTreeNode &function_header, IndexingFactNode *function_node) { // Extract function name. - const Symbol* function_name = GetFunctionHeaderId(function_header); + const Symbol *function_name = GetFunctionHeaderId(function_header); if (function_name == nullptr) { return; } @@ -1172,7 +1172,7 @@ void IndexingFactsTreeExtractor::ExtractFunctionHeader( MoveAndDeleteLastExtractedNode(function_node); { - IndexingFactNode& function_node_ref = *function_node; + IndexingFactNode &function_node_ref = *function_node; const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &function_node_ref); // Extract function ports. @@ -1181,9 +1181,9 @@ void IndexingFactsTreeExtractor::ExtractFunctionHeader( } void IndexingFactsTreeExtractor::ExtractTaskHeader( - const SyntaxTreeNode& task_header, IndexingFactNode* task_node) { + const SyntaxTreeNode &task_header, IndexingFactNode *task_node) { // Extract task name. - const Symbol* task_name = GetTaskHeaderId(task_header); + const Symbol *task_name = GetTaskHeaderId(task_header); if (task_name == nullptr) { return; } @@ -1191,7 +1191,7 @@ void IndexingFactsTreeExtractor::ExtractTaskHeader( MoveAndDeleteLastExtractedNode(task_node); { - IndexingFactNode& task_node_ref = *task_node; + IndexingFactNode &task_node_ref = *task_node; const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &task_node_ref); // Extract task ports. @@ -1200,15 +1200,15 @@ void IndexingFactsTreeExtractor::ExtractTaskHeader( } void IndexingFactsTreeExtractor::ExtractFunctionOrTaskOrConstructorPort( - const SyntaxTreeNode& function_declaration_node) { + const SyntaxTreeNode &function_declaration_node) { const std::vector ports = FindAllTaskFunctionPortDeclarations(function_declaration_node); - for (const TreeSearchMatch& port : ports) { - const Symbol* port_type = GetTypeOfTaskFunctionPortItem(*port.match); + for (const TreeSearchMatch &port : ports) { + const Symbol *port_type = GetTypeOfTaskFunctionPortItem(*port.match); if (port_type != nullptr) { // port variable name. - const SyntaxTreeLeaf* port_identifier = + const SyntaxTreeLeaf *port_identifier = GetIdentifierFromTaskFunctionPortItem(*port.match); if (!port_identifier) continue; @@ -1218,7 +1218,7 @@ void IndexingFactsTreeExtractor::ExtractFunctionOrTaskOrConstructorPort( Anchor(port_identifier->get(), FileContent()))); // if this port has struct/union/enum data type. - const SyntaxTreeNode* struct_type = + const SyntaxTreeNode *struct_type = GetStructOrUnionOrEnumTypeFromDataType(*port_type); if (struct_type != nullptr) { @@ -1234,7 +1234,7 @@ void IndexingFactsTreeExtractor::ExtractFunctionOrTaskOrConstructorPort( continue; } - const SyntaxTreeNode* type_identifier = + const SyntaxTreeNode *type_identifier = GetTypeIdentifierFromDataType(*port_type); if (type_identifier == nullptr) { @@ -1245,13 +1245,13 @@ void IndexingFactsTreeExtractor::ExtractFunctionOrTaskOrConstructorPort( const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &variable_node); - const SyntaxTreeNode* packed_dim = + const SyntaxTreeNode *packed_dim = GetPackedDimensionFromDataType(*port_type); if (packed_dim != nullptr) { packed_dim->Accept(this); } - const SyntaxTreeNode* unpacked_dimension = + const SyntaxTreeNode *unpacked_dimension = GetUnpackedDimensionsFromTaskFunctionPortItem(*port.match); if (unpacked_dimension) unpacked_dimension->Accept(this); } @@ -1276,13 +1276,13 @@ void IndexingFactsTreeExtractor::ExtractFunctionOrTaskOrConstructorPort( const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &type_node); - const SyntaxTreeNode* packed_dim = + const SyntaxTreeNode *packed_dim = GetPackedDimensionFromDataType(*port_type); if (packed_dim != nullptr) { packed_dim->Accept(this); } - const SyntaxTreeNode* unpacked_dimension = + const SyntaxTreeNode *unpacked_dimension = GetUnpackedDimensionsFromTaskFunctionPortItem(*port.match); if (unpacked_dimension) unpacked_dimension->Accept(this); } @@ -1293,7 +1293,7 @@ void IndexingFactsTreeExtractor::ExtractFunctionOrTaskOrConstructorPort( } void IndexingFactsTreeExtractor::ExtractFunctionOrTaskCall( - const SyntaxTreeNode& function_call_node) { + const SyntaxTreeNode &function_call_node) { // check if this node contains an actual call if (!function_call_node.children().empty() && SymbolCastToNode(*function_call_node.children()[0]) @@ -1306,7 +1306,7 @@ void IndexingFactsTreeExtractor::ExtractFunctionOrTaskCall( // Extract function or task name. // It can be single or preceeded with a pkg or class names. - const SyntaxTreeNode* identifier = + const SyntaxTreeNode *identifier = GetIdentifiersFromFunctionCall(function_call_node); if (identifier == nullptr) { return; @@ -1316,15 +1316,15 @@ void IndexingFactsTreeExtractor::ExtractFunctionOrTaskCall( { // These will resolve since `GetIdentifiersFromFunctionCall` would return // nullptr if they were not present and that triggers a return above. - const verible::Symbol* reference_call_base = nullptr; + const verible::Symbol *reference_call_base = nullptr; reference_call_base = GetSubtreeAsSymbol(function_call_node, NodeEnum::kFunctionCall, 0); - const verible::Symbol* reference = GetSubtreeAsSymbol( + const verible::Symbol *reference = GetSubtreeAsSymbol( *reference_call_base, NodeEnum::kReferenceCallBase, 0); if (reference->Tag().tag == (int)NodeEnum::kReference) { if (SymbolCastToNode(*reference).children().size() > 1) { - const auto& children = SymbolCastToNode(*reference).children(); - for (auto& child : + const auto &children = SymbolCastToNode(*reference).children(); + for (auto &child : verible::make_range(children.begin() + 1, children.end())) { if (child->Tag().tag == (int)NodeEnum::kHierarchyExtension) { Visit(verible::SymbolCastToNode(*child)); @@ -1346,7 +1346,7 @@ void IndexingFactsTreeExtractor::ExtractFunctionOrTaskCall( { const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &function_node); - const SyntaxTreeNode* arguments = GetParenGroupFromCall(function_call_node); + const SyntaxTreeNode *arguments = GetParenGroupFromCall(function_call_node); // Extract function or task parameters. if (arguments) Visit(*arguments); } @@ -1355,7 +1355,7 @@ void IndexingFactsTreeExtractor::ExtractFunctionOrTaskCall( } void IndexingFactsTreeExtractor::ExtractMethodCallExtension( - const SyntaxTreeNode& call_extension_node) { + const SyntaxTreeNode &call_extension_node) { IndexingFactNode function_node( IndexingNodeData{IndexingFactType::kFunctionCall}); @@ -1370,7 +1370,7 @@ void IndexingFactsTreeExtractor::ExtractMethodCallExtension( } { - const SyntaxTreeLeaf* fun_call = + const SyntaxTreeLeaf *fun_call = GetFunctionCallNameFromCallExtension(call_extension_node); if (fun_call) { function_node.Value().AppendAnchor( @@ -1381,7 +1381,7 @@ void IndexingFactsTreeExtractor::ExtractMethodCallExtension( { const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &function_node); - const SyntaxTreeNode* arguments = + const SyntaxTreeNode *arguments = GetParenGroupFromCallExtension(call_extension_node); // parameters. if (arguments) Visit(*arguments); @@ -1391,7 +1391,7 @@ void IndexingFactsTreeExtractor::ExtractMethodCallExtension( } void IndexingFactsTreeExtractor::ExtractMemberExtension( - const SyntaxTreeNode& hierarchy_extension_node) { + const SyntaxTreeNode &hierarchy_extension_node) { IndexingFactNode member_node( IndexingNodeData{IndexingFactType::kMemberReference}); @@ -1400,7 +1400,7 @@ void IndexingFactsTreeExtractor::ExtractMemberExtension( MoveAndDeleteLastExtractedNode(&member_node); { - const verible::SyntaxTreeLeaf* unqualified = + const verible::SyntaxTreeLeaf *unqualified = GetUnqualifiedIdFromHierarchyExtension(hierarchy_extension_node); // member name if (unqualified) { @@ -1413,34 +1413,34 @@ void IndexingFactsTreeExtractor::ExtractMemberExtension( } void IndexingFactsTreeExtractor::ExtractClassDeclaration( - const SyntaxTreeNode& class_declaration) { + const SyntaxTreeNode &class_declaration) { IndexingFactNode class_node(IndexingNodeData{IndexingFactType::kClass}); { const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &class_node); // Extract class name. - const SyntaxTreeLeaf* class_name = GetClassName(class_declaration); + const SyntaxTreeLeaf *class_name = GetClassName(class_declaration); if (class_name) { facts_tree_context_.top().Value().AppendAnchor( Anchor(class_name->get(), FileContent())); } // Extract class name after endclass. - const SyntaxTreeLeaf* class_end_name = GetClassEndLabel(class_declaration); + const SyntaxTreeLeaf *class_end_name = GetClassEndLabel(class_declaration); if (class_end_name != nullptr) { facts_tree_context_.top().Value().AppendAnchor( Anchor(class_end_name->get(), FileContent())); } - const SyntaxTreeNode* param_list = + const SyntaxTreeNode *param_list = GetParamDeclarationListFromClassDeclaration(class_declaration); if (param_list != nullptr) { Visit(*param_list); } - const SyntaxTreeNode* extended_class = GetExtendedClass(class_declaration); + const SyntaxTreeNode *extended_class = GetExtendedClass(class_declaration); if (extended_class != nullptr) { IndexingFactNode extends_node( IndexingNodeData{IndexingFactType::kExtends}); @@ -1462,7 +1462,7 @@ void IndexingFactsTreeExtractor::ExtractClassDeclaration( } // Visit class body. - const SyntaxTreeNode* class_item_list = GetClassItemList(class_declaration); + const SyntaxTreeNode *class_item_list = GetClassItemList(class_declaration); if (class_item_list) Visit(*class_item_list); } @@ -1470,12 +1470,12 @@ void IndexingFactsTreeExtractor::ExtractClassDeclaration( } void IndexingFactsTreeExtractor::ExtractClassInstances( - const SyntaxTreeNode& data_declaration_node, - const std::vector& class_instances) { + const SyntaxTreeNode &data_declaration_node, + const std::vector &class_instances) { IndexingFactNode type_node( IndexingNodeData{IndexingFactType::kDataTypeReference}); - const Symbol* type = + const Symbol *type = GetTypeIdentifierFromDataDeclaration(data_declaration_node); if (type == nullptr) { return; @@ -1491,7 +1491,7 @@ void IndexingFactsTreeExtractor::ExtractClassInstances( // // Loop through each instance and associate each declared id with the same // type and create its corresponding facts tree node. - for (const TreeSearchMatch& instance : class_instances) { + for (const TreeSearchMatch &instance : class_instances) { IndexingFactNode class_instance_node( IndexingNodeData{IndexingFactType::kClassInstance}); @@ -1507,8 +1507,8 @@ void IndexingFactsTreeExtractor::ExtractClassInstances( } void IndexingFactsTreeExtractor::ExtractRegisterVariable( - const SyntaxTreeNode& register_variable) { - const TokenInfo* instance_name = + const SyntaxTreeNode ®ister_variable) { + const TokenInfo *instance_name = GetInstanceNameTokenInfoFromRegisterVariable(register_variable); if (!instance_name) return; @@ -1519,11 +1519,11 @@ void IndexingFactsTreeExtractor::ExtractRegisterVariable( { const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &variable_node); - const SyntaxTreeNode* unpacked_dimension = + const SyntaxTreeNode *unpacked_dimension = GetUnpackedDimensionFromRegisterVariable(register_variable); if (unpacked_dimension) Visit(*unpacked_dimension); - const SyntaxTreeNode* expression = + const SyntaxTreeNode *expression = GetTrailingExpressionFromRegisterVariable(register_variable); if (expression != nullptr) { const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, @@ -1537,8 +1537,8 @@ void IndexingFactsTreeExtractor::ExtractRegisterVariable( } void IndexingFactsTreeExtractor::ExtractVariableDeclarationAssignment( - const SyntaxTreeNode& variable_declaration_assignment) { - const SyntaxTreeLeaf* unqualified_id = + const SyntaxTreeNode &variable_declaration_assignment) { + const SyntaxTreeLeaf *unqualified_id = GetUnqualifiedIdFromVariableDeclarationAssignment( variable_declaration_assignment); if (!unqualified_id) return; @@ -1549,12 +1549,12 @@ void IndexingFactsTreeExtractor::ExtractVariableDeclarationAssignment( { const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &variable_node); - const SyntaxTreeNode* unpacked_dimension = + const SyntaxTreeNode *unpacked_dimension = GetUnpackedDimensionFromVariableDeclarationAssign( variable_declaration_assignment); if (unpacked_dimension) Visit(*unpacked_dimension); - const SyntaxTreeNode* expression = + const SyntaxTreeNode *expression = GetTrailingExpressionFromVariableDeclarationAssign( variable_declaration_assignment); if (expression != nullptr) { @@ -1568,8 +1568,8 @@ void IndexingFactsTreeExtractor::ExtractVariableDeclarationAssignment( } void IndexingFactsTreeExtractor::ExtractUnqualifiedId( - const SyntaxTreeNode& unqualified_id) { - const SyntaxTreeLeaf* identifier = AutoUnwrapIdentifier(unqualified_id); + const SyntaxTreeNode &unqualified_id) { + const SyntaxTreeLeaf *identifier = AutoUnwrapIdentifier(unqualified_id); if (identifier == nullptr) { return; } @@ -1585,7 +1585,7 @@ void IndexingFactsTreeExtractor::ExtractUnqualifiedId( ExtractSymbolIdentifier(*identifier); MoveAndDeleteLastExtractedNode(&variable_reference); - const SyntaxTreeNode* param_list = + const SyntaxTreeNode *param_list = GetParamListFromUnqualifiedId(unqualified_id); if (param_list != nullptr) { const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, @@ -1604,11 +1604,11 @@ void IndexingFactsTreeExtractor::ExtractUnqualifiedId( } void IndexingFactsTreeExtractor::ExtractParamDeclaration( - const SyntaxTreeNode& param_declaration) { + const SyntaxTreeNode ¶m_declaration) { IndexingFactNode param_node( IndexingNodeData{IndexingFactType::kParamDeclaration}); - const SyntaxTreeNode* type_assignment = + const SyntaxTreeNode *type_assignment = GetTypeAssignmentFromParamDeclaration(param_declaration); // Parameters can be in two cases: @@ -1619,7 +1619,7 @@ void IndexingFactsTreeExtractor::ExtractParamDeclaration( ->get(), FileContent())); - const SyntaxTreeNode* expression = + const SyntaxTreeNode *expression = GetExpressionFromTypeAssignment(*type_assignment); if (expression != nullptr) { const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, @@ -1629,7 +1629,7 @@ void IndexingFactsTreeExtractor::ExtractParamDeclaration( } else { // 2nd => parameter int x; // Extract Param name. - const TokenInfo* parameter_name = GetParameterNameToken(param_declaration); + const TokenInfo *parameter_name = GetParameterNameToken(param_declaration); if (!parameter_name) return; param_node.Value().AppendAnchor(Anchor(*parameter_name, FileContent())); @@ -1637,7 +1637,7 @@ void IndexingFactsTreeExtractor::ExtractParamDeclaration( const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, ¶m_node); - const Symbol* assign_expression = + const Symbol *assign_expression = GetParamAssignExpression(param_declaration); if (assign_expression != nullptr && @@ -1652,8 +1652,8 @@ void IndexingFactsTreeExtractor::ExtractParamDeclaration( } void IndexingFactsTreeExtractor::ExtractParamByName( - const SyntaxTreeNode& param_by_name) { - const verible::SyntaxTreeLeaf* named_param = + const SyntaxTreeNode ¶m_by_name) { + const verible::SyntaxTreeLeaf *named_param = GetNamedParamFromActualParam(param_by_name); if (!named_param) return; IndexingFactNode named_param_node( @@ -1663,7 +1663,7 @@ void IndexingFactsTreeExtractor::ExtractParamByName( { const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &named_param_node); - const SyntaxTreeNode* paren_group = + const SyntaxTreeNode *paren_group = GetParenGroupFromActualParam(param_by_name); if (paren_group != nullptr) { Visit(*paren_group); @@ -1674,8 +1674,8 @@ void IndexingFactsTreeExtractor::ExtractParamByName( } void IndexingFactsTreeExtractor::ExtractPackageImport( - const SyntaxTreeNode& package_import_item) { - const SyntaxTreeLeaf* package_name = + const SyntaxTreeNode &package_import_item) { + const SyntaxTreeLeaf *package_name = GetImportedPackageName(package_import_item); if (!package_name) return; IndexingNodeData package_import_data( @@ -1685,7 +1685,7 @@ void IndexingFactsTreeExtractor::ExtractPackageImport( // Get the name of the imported item (if exists). // e.g pkg::var1 ==> return var1. // will be nullptr in case of pkg::*. - const SyntaxTreeLeaf* imported_item = + const SyntaxTreeLeaf *imported_item = GeImportedItemNameFromPackageImportItem(package_import_item); if (imported_item != nullptr) { package_import_data.AppendAnchor( @@ -1700,21 +1700,21 @@ void IndexingFactsTreeExtractor::ExtractPackageImport( // deleted. // Defining this here because the following function is the only place in the // codebase that needs this workaround. -static IndexingNodeData CopyNodeData(const IndexingNodeData& src) { +static IndexingNodeData CopyNodeData(const IndexingNodeData &src) { IndexingNodeData copy(src.GetIndexingFactType()); - for (const auto& anchor : src.Anchors()) { + for (const auto &anchor : src.Anchors()) { copy.AppendAnchor(Anchor(anchor)); // copy } return copy; } void IndexingFactsTreeExtractor::ExtractQualifiedId( - const SyntaxTreeNode& qualified_id) { + const SyntaxTreeNode &qualified_id) { IndexingNodeData member_reference_data(IndexingFactType::kMemberReference); // Get all the variable names in the qualified id. // e.g. split "A#(...)::B#(...)" into components "A#(...)" and "B#(...)" - for (const auto& child : qualified_id.children()) { + for (const auto &child : qualified_id.children()) { if (child == nullptr || NodeEnum(child->Tag().tag) != NodeEnum::kUnqualifiedId) { continue; @@ -1722,7 +1722,7 @@ void IndexingFactsTreeExtractor::ExtractQualifiedId( member_reference_data.AppendAnchor( Anchor(AutoUnwrapIdentifier(*child)->get(), FileContent())); - const SyntaxTreeNode* param_list = GetParamListFromUnqualifiedId(*child); + const SyntaxTreeNode *param_list = GetParamListFromUnqualifiedId(*child); if (param_list != nullptr) { // Create a copy from the current "member_reference" node to be used for // this param reference. @@ -1749,10 +1749,10 @@ void IndexingFactsTreeExtractor::ExtractQualifiedId( } void IndexingFactsTreeExtractor::ExtractForInitialization( - const SyntaxTreeNode& for_initialization) { + const SyntaxTreeNode &for_initialization) { // Extracts the variable name from for initialization. // e.g from "int i = 0"; ==> extracts "i". - const SyntaxTreeLeaf* variable_name = + const SyntaxTreeLeaf *variable_name = GetVariableNameFromForInitialization(for_initialization); if (variable_name) { facts_tree_context_.top().Children().emplace_back( @@ -1762,7 +1762,7 @@ void IndexingFactsTreeExtractor::ExtractForInitialization( // Extracts the data the in case it contains packed or unpacked dimension. // e.g bit [x : y] var [x : y]. - const SyntaxTreeNode* data_type_node = + const SyntaxTreeNode *data_type_node = GetDataTypeFromForInitialization(for_initialization); if (data_type_node != nullptr) { Visit(*data_type_node); @@ -1770,7 +1770,7 @@ void IndexingFactsTreeExtractor::ExtractForInitialization( // Extracts the RHS of the declaration. // e.g int i = x; ==> extracts "x". - const SyntaxTreeNode* expression = + const SyntaxTreeNode *expression = GetExpressionFromForInitialization(for_initialization); if (expression) Visit(*expression); } @@ -1782,9 +1782,9 @@ absl::string_view StripOuterQuotes(absl::string_view text) { } void IndexingFactsTreeExtractor::ExtractInclude( - const SyntaxTreeNode& preprocessor_include) { + const SyntaxTreeNode &preprocessor_include) { VLOG(1) << __FUNCTION__; - const SyntaxTreeLeaf* included_filename = + const SyntaxTreeLeaf *included_filename = GetFileFromPreprocessorInclude(preprocessor_include); if (included_filename == nullptr) { return; @@ -1796,7 +1796,7 @@ void IndexingFactsTreeExtractor::ExtractInclude( const absl::string_view filename_unquoted = StripOuterQuotes(filename_text); VLOG(1) << "got: `include \"" << filename_unquoted << "\""; - VerilogProject* const project = extraction_state_->project; + VerilogProject *const project = extraction_state_->project; // Open this file (could be first time, or previously opened). const auto status_or_file = project->OpenIncludedFile(filename_unquoted); @@ -1811,7 +1811,7 @@ void IndexingFactsTreeExtractor::ExtractInclude( return; } - VerilogSourceFile* const included_file = *status_or_file; + VerilogSourceFile *const included_file = *status_or_file; if (included_file == nullptr) return; VLOG(1) << "opened include file: " << included_file->ResolvedPath(); @@ -1849,8 +1849,8 @@ void IndexingFactsTreeExtractor::ExtractInclude( } void IndexingFactsTreeExtractor::ExtractEnumName( - const SyntaxTreeNode& enum_name) { - const SyntaxTreeLeaf* symbol_id = GetSymbolIdentifierFromEnumName(enum_name); + const SyntaxTreeNode &enum_name) { + const SyntaxTreeLeaf *symbol_id = GetSymbolIdentifierFromEnumName(enum_name); if (!symbol_id) return; IndexingFactNode enum_node(IndexingNodeData( IndexingFactType::kConstant, Anchor(symbol_id->get(), FileContent()))); @@ -1860,7 +1860,7 @@ void IndexingFactsTreeExtractor::ExtractEnumName( // e.g enum {RED[x] = 1, OLD=y} => explores "[x]", "=y". { const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &enum_node); - for (const auto& child : enum_name.children()) { + for (const auto &child : enum_name.children()) { if (child == nullptr || child->Kind() == SymbolKind::kLeaf) { continue; } @@ -1872,9 +1872,9 @@ void IndexingFactsTreeExtractor::ExtractEnumName( } void IndexingFactsTreeExtractor::ExtractEnumTypeDeclaration( - const SyntaxTreeNode& enum_type_declaration) { + const SyntaxTreeNode &enum_type_declaration) { // Extract enum type name. - const SyntaxTreeLeaf* enum_type_name = + const SyntaxTreeLeaf *enum_type_name = GetIdentifierFromTypeDeclaration(enum_type_declaration); if (!enum_type_name) return; facts_tree_context_.top().Children().emplace_back( @@ -1882,7 +1882,7 @@ void IndexingFactsTreeExtractor::ExtractEnumTypeDeclaration( Anchor(enum_type_name->get(), FileContent()))); // Explore the children of this enum type to extract. - for (const auto& child : enum_type_declaration.children()) { + for (const auto &child : enum_type_declaration.children()) { if (child == nullptr || child->Kind() == SymbolKind::kLeaf) { continue; } @@ -1891,7 +1891,7 @@ void IndexingFactsTreeExtractor::ExtractEnumTypeDeclaration( } void IndexingFactsTreeExtractor::ExtractStructUnionTypeDeclaration( - const SyntaxTreeNode& type_declaration, const SyntaxTreeNode& struct_type) { + const SyntaxTreeNode &type_declaration, const SyntaxTreeNode &struct_type) { IndexingFactNode struct_type_node(IndexingNodeData( IndexingFactType::kStructOrUnion, Anchor( @@ -1910,8 +1910,8 @@ void IndexingFactsTreeExtractor::ExtractStructUnionTypeDeclaration( } void IndexingFactsTreeExtractor::ExtractStructUnionDeclaration( - const SyntaxTreeNode& struct_type, - const std::vector& variables_matched) { + const SyntaxTreeNode &struct_type, + const std::vector &variables_matched) { VLOG(2) << __FUNCTION__; // Dummy data type to hold the extracted struct members because there is no // data type here. Its temporary children will be moved out before this @@ -1926,20 +1926,20 @@ void IndexingFactsTreeExtractor::ExtractStructUnionDeclaration( Visit(struct_type); } - for (const TreeSearchMatch& variable : variables_matched) { + for (const TreeSearchMatch &variable : variables_matched) { // Extract this variable. // This can be kRegisterVariable or kVariableDeclarationAssign. variable.match->Accept(this); CHECK(!facts_tree_context_.top().Children().empty()); - IndexingFactNode& recent(facts_tree_context_.top().Children().back()); + IndexingFactNode &recent(facts_tree_context_.top().Children().back()); // Append the struct members to be a children of this variable. // TODO(fangism): move instead of copying chidren // However, std::move-ing each child in the loop crashes, // and so does recent.AdoptSubtreesFrom(&struct_node). recent.Children().reserve(struct_node.Children().size()); - for (const auto& child : struct_node.Children()) { + for (const auto &child : struct_node.Children()) { recent.Children().push_back(child); // copy } } @@ -1947,7 +1947,7 @@ void IndexingFactsTreeExtractor::ExtractStructUnionDeclaration( } void IndexingFactsTreeExtractor::ExtractDataTypeImplicitIdDimensions( - const SyntaxTreeNode& data_type_implicit_id_dimensions) { + const SyntaxTreeNode &data_type_implicit_id_dimensions) { // This node has 2 cases: // 1st case: // typedef struct { @@ -1962,7 +1962,7 @@ void IndexingFactsTreeExtractor::ExtractDataTypeImplicitIdDimensions( // } my_struct; // In this case var_name should contain "xx" inside it. - std::pair variable_name = + std::pair variable_name = GetSymbolIdentifierFromDataTypeImplicitIdDimensions( data_type_implicit_id_dimensions); if (!variable_name.first) return; @@ -1972,7 +1972,7 @@ void IndexingFactsTreeExtractor::ExtractDataTypeImplicitIdDimensions( Anchor(variable_name.first->get(), FileContent()))); if (variable_name.second == 1) { - const SyntaxTreeLeaf* type_identifier = + const SyntaxTreeLeaf *type_identifier = GetNonprimitiveTypeOfDataTypeImplicitDimensions( data_type_implicit_id_dimensions); @@ -1988,7 +1988,7 @@ void IndexingFactsTreeExtractor::ExtractDataTypeImplicitIdDimensions( { const IndexingFactsTreeContext::AutoPop p(&facts_tree_context_, &variable_node); - for (const auto& child : data_type_implicit_id_dimensions.children()) { + for (const auto &child : data_type_implicit_id_dimensions.children()) { if (child == nullptr || child->Kind() == SymbolKind::kLeaf) { continue; } @@ -2001,20 +2001,20 @@ void IndexingFactsTreeExtractor::ExtractDataTypeImplicitIdDimensions( } void IndexingFactsTreeExtractor::ExtractTypeDeclaration( - const SyntaxTreeNode& type_declaration) { - const SyntaxTreeNode* type = + const SyntaxTreeNode &type_declaration) { + const SyntaxTreeNode *type = GetReferencedTypeOfTypeDeclaration(type_declaration); if (type == nullptr) return; // Look for enum/struct/union in the referenced type. const auto tag = static_cast(type->Tag().tag); if (tag != NodeEnum::kDataType) return; - const SyntaxTreeNode* primitive = + const SyntaxTreeNode *primitive = GetStructOrUnionOrEnumTypeFromDataType(*type); if (primitive == nullptr) { // Then this is a user-defined type. // Extract type name. - const SyntaxTreeLeaf* type_name = + const SyntaxTreeLeaf *type_name = GetIdentifierFromTypeDeclaration(type_declaration); if (type_name == nullptr) return; @@ -2044,7 +2044,7 @@ void IndexingFactsTreeExtractor::ExtractTypeDeclaration( } void IndexingFactsTreeExtractor::ExtractAnonymousScope( - const SyntaxTreeNode& node) { + const SyntaxTreeNode &node) { IndexingFactNode temp_scope_node(IndexingNodeData( IndexingFactType::kAnonymousScope, // Generate unique id for this scope. @@ -2060,14 +2060,14 @@ void IndexingFactsTreeExtractor::ExtractAnonymousScope( } void IndexingFactsTreeExtractor::MoveAndDeleteLastExtractedNode( - IndexingFactNode* new_node) { + IndexingFactNode *new_node) { // Terminate if there is no parent or the parent has no children. if (facts_tree_context_.empty() || is_leaf(facts_tree_context_.top())) { return; } // Get The last extracted child. - IndexingFactNode& previous_node = facts_tree_context_.top().Children().back(); + IndexingFactNode &previous_node = facts_tree_context_.top().Children().back(); // Fill the anchors of the previous node to the current node. new_node->Value().SwapAnchors(&previous_node.Value()); diff --git a/verilog/tools/kythe/indexing_facts_tree_extractor.h b/verilog/tools/kythe/indexing_facts_tree_extractor.h index 75d79b18c..b5b10ffba 100644 --- a/verilog/tools/kythe/indexing_facts_tree_extractor.h +++ b/verilog/tools/kythe/indexing_facts_tree_extractor.h @@ -31,9 +31,9 @@ namespace kythe { // The returned tree will have the files as children and they will retain their // original ordering from the file list. IndexingFactNode ExtractFiles(absl::string_view file_list_path, - VerilogProject* project, - const std::vector& file_names, - std::vector* errors = nullptr); + VerilogProject *project, + const std::vector &file_names, + std::vector *errors = nullptr); } // namespace kythe } // namespace verilog diff --git a/verilog/tools/kythe/indexing_facts_tree_extractor_test.cc b/verilog/tools/kythe/indexing_facts_tree_extractor_test.cc index c59dcd051..6b13ff1a2 100644 --- a/verilog/tools/kythe/indexing_facts_tree_extractor_test.cc +++ b/verilog/tools/kythe/indexing_facts_tree_extractor_test.cc @@ -64,12 +64,12 @@ struct TestFileEntry { // Points to a successfully opened source file that corresponds to test_file_ // opened as a translation unit. - const VerilogSourceFile* const source_file = nullptr; + const VerilogSourceFile *const source_file = nullptr; TestFileEntry( absl::string_view code_text, absl::string_view temp_dir, - const std::function& - file_opener, + const std::function + &file_opener, absl::string_view override_basename = "") : origin_text(code_text), temp_file(temp_dir, origin_text, override_basename), @@ -98,20 +98,20 @@ class SimpleTestProject : public TempDir, public VerilogProject { public: // 'code_text' is the contents of the single translation unit in this project explicit SimpleTestProject(absl::string_view code_text, - const std::vector& include_paths = {}) + const std::vector &include_paths = {}) : VerilogProject(temp_dir_, include_paths, /*corpus=*/"unittest", /*populate_string_maps=*/false), code_text_(code_text), translation_unit_(code_text, temp_dir_, [this](absl::string_view full_file_name) - -> const VerilogSourceFile* { + -> const VerilogSourceFile * { /* VerilogProject base class is already fully * initialized */ return *OpenTranslationUnit( verible::file::Basename(full_file_name)); }) {} - const TestFileEntry& XUnit() const { return translation_unit_; } + const TestFileEntry &XUnit() const { return translation_unit_; } absl::string_view OnlyFileName() const { return translation_unit_.temp_file.filename(); @@ -136,10 +136,10 @@ class SimpleTestProject : public TempDir, public VerilogProject { }; } - std::vector& Errors() { return errors_; } + std::vector &Errors() { return errors_; } // This printer only works well for tests cases with one translation unit. - PrintableIndexingFactNode TreePrinter(const IndexingFactNode& n) const { + PrintableIndexingFactNode TreePrinter(const IndexingFactNode &n) const { return PrintableIndexingFactNode(n, code_text_); } @@ -161,12 +161,12 @@ class IncludeTestProject : protected SimpleTestProject { IncludeTestProject(absl::string_view code_text, absl::string_view include_file_basename, absl::string_view include_text, - const std::vector& include_paths = {}) + const std::vector &include_paths = {}) : SimpleTestProject(code_text, include_paths), include_file_( include_text, temp_dir_, [this]( - absl::string_view full_file_name) -> const VerilogSourceFile* { + absl::string_view full_file_name) -> const VerilogSourceFile * { /* VerilogProject base class is already fully initialized */ return *OpenIncludedFile(verible::file::Basename(full_file_name)); }, @@ -177,7 +177,7 @@ class IncludeTestProject : protected SimpleTestProject { using SimpleTestProject::Extract; using SimpleTestProject::XUnit; - const TestFileEntry& IncludeFile() const { return include_file_; } + const TestFileEntry &IncludeFile() const { return include_file_; } private: // The one and only one included file in the test. @@ -225,7 +225,7 @@ TEST(FactsTreeExtractor, EqualOperatorTest) { Anchor(absl::string_view("foo")), })); - const auto P = [&code_text](const IndexingFactNode& n) { + const auto P = [&code_text](const IndexingFactNode &n) { return PrintableIndexingFactNode(n, code_text); }; { @@ -262,7 +262,7 @@ TEST(FactsTreeExtractor, EmptyCSTTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -275,7 +275,7 @@ TEST(FactsTreeExtractor, ParseErrorTest) { "module unfinished", // syntax error }; - for (const auto& code_text : code_texts) { + for (const auto &code_text : code_texts) { SimpleTestProject project(code_text); const auto facts_tree = project.Extract(); const std::vector errors(project.Errors()); @@ -303,7 +303,7 @@ TEST(FactsTreeExtractor, EmptyModuleTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -353,7 +353,7 @@ TEST(FactsTreeExtractor, PropagatedUserDefinedTypeInModulePort) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -400,7 +400,7 @@ TEST(FactsTreeExtractor, OneLocalNetTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -453,7 +453,7 @@ TEST(FactsTreeExtractor, OneModuleInstanceTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -521,7 +521,7 @@ TEST(FactsTreeExtractor, TwoModuleInstanceTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } // namespace @@ -581,7 +581,7 @@ TEST(FactsTreeExtractor, MultipleModuleInstancesInTheSameDeclarationTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } // namespace @@ -623,7 +623,7 @@ TEST(FactsTreeExtractor, ModuleWithPortsTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -694,7 +694,7 @@ TEST(FactsTreeExtractor, ModuleDimensionTypePortsTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -754,7 +754,7 @@ TEST(FactsTreeExtractor, ModuleWithPortsNonANSIStyleTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -796,7 +796,7 @@ TEST(FactsTreeExtractor, ClassParams) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -859,7 +859,7 @@ TEST(FactsTreeExtractor, QualifiedVariableType) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -901,7 +901,7 @@ TEST(FactsTreeExtractor, ClassTypeParams) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -1070,7 +1070,7 @@ TEST(FactsTreeExtractor, ModuleInstanceWithActualNamedPorts) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -1138,7 +1138,7 @@ TEST(FactsTreeExtractor, ModuleInstanceWitStarExpandedPorts) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -1198,7 +1198,7 @@ TEST(FactsTreeExtractor, ModuleWithPortsDataTypeForwarding) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -1440,7 +1440,7 @@ TEST(FactsTreeExtractor, PrimitiveTypeExtraction) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -1498,7 +1498,7 @@ TEST(FactsTreeExtractor, MultiSignalDeclaration) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -1595,7 +1595,7 @@ TEST(FactsTreeExtractor, ModuleInstanceWithPortsTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } // namespace @@ -1630,7 +1630,7 @@ TEST(FactsTreeExtractor, WireTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -1655,7 +1655,7 @@ TEST(FactsTreeExtractor, ClassTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -1693,7 +1693,7 @@ TEST(FactsTreeExtractor, CLassWithinModuleTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -1733,7 +1733,7 @@ TEST(FactsTreeExtractor, NestedClassTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -1808,7 +1808,7 @@ TEST(FactsTreeExtractor, OneClassInstanceTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -1901,7 +1901,7 @@ TEST(FactsTreeExtractor, ClassMemberAccess) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -1938,7 +1938,7 @@ TEST(FactsTreeExtractor, FunctionAndTaskDeclarationNoArgs) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -2007,7 +2007,7 @@ TEST(FactsTreeExtractor, FunctionAndTaskDeclarationWithArgs) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -2064,7 +2064,7 @@ TEST(FactsTreeExtractor, ClassMember) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -2129,7 +2129,7 @@ TEST(FactsTreeExtractor, FunctionAndTaskCallNoArgs) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -2348,7 +2348,7 @@ TEST(FactsTreeExtractor, FunctionClassCall) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -2379,7 +2379,7 @@ TEST(FactsTreeExtractor, ThisAsFunctionCall) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -2458,7 +2458,7 @@ TEST(FactsTreeExtractor, MacroDefinitionTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -2613,7 +2613,7 @@ TEST(FactsTreeExtractor, MacroCallTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -2697,7 +2697,7 @@ TEST(PackageImportTest, PackageAndImportedItemName) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -2765,7 +2765,7 @@ TEST(PackageImportTest, PackageDirectMemberReference) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -2881,7 +2881,7 @@ TEST(PackageImportTest, ClassInstanceWithMultiParams) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -2916,7 +2916,7 @@ TEST(PackageImportTest, UserDefinedType) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -2967,7 +2967,7 @@ TEST(PackageImportTest, SelectVariableDimension) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -3002,7 +3002,7 @@ TEST(PackageImportTest, ClassParameterType) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -3054,7 +3054,7 @@ TEST(PackageImportTest, ClassInstanceWithParams) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -3085,7 +3085,7 @@ TEST(PackageImportTest, PackageTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -3189,7 +3189,7 @@ TEST(FactsTreeExtractor, ForLoopInitializations) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -3242,7 +3242,7 @@ TEST(FactsTreeExtractor, ClassExtends) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -3344,7 +3344,7 @@ TEST(FactsTreeExtractor, ParameterExtraction) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -3446,7 +3446,7 @@ TEST(FactsTreeExtractor, InterfaceParameterExtraction) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -3489,7 +3489,7 @@ TEST(FactsTreeExtractor, ClassAsPort) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -3591,7 +3591,7 @@ TEST(FactsTreeExtractor, ProgramParameterExtraction) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -3699,7 +3699,7 @@ TEST(FactsTreeExtractor, PackedAndUnpackedDimension) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4112,7 +4112,7 @@ TEST(FactsTreeExtractor, EnumTest) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4156,7 +4156,7 @@ TEST(FactsTreeExtractor, NonLiteralIncludeSafeFail) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4199,7 +4199,7 @@ TEST(FactsTreeExtractor, StructInModule) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4249,7 +4249,7 @@ TEST(FactsTreeExtractor, ClassConstructor) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4292,7 +4292,7 @@ TEST(FactsTreeExtractor, StructInPackage) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4335,7 +4335,7 @@ TEST(FactsTreeExtractor, UnionInModule) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4378,7 +4378,7 @@ TEST(FactsTreeExtractor, UnionInPackage) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4421,7 +4421,7 @@ TEST(FactsTreeExtractor, UnionTypeInPackage) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4464,7 +4464,7 @@ TEST(FactsTreeExtractor, UnionTypenModule) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4507,7 +4507,7 @@ TEST(FactsTreeExtractor, StructTypeInPackage) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4550,7 +4550,7 @@ TEST(FactsTreeExtractor, StructTypedefModule) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4593,7 +4593,7 @@ TEST(FactsTreeExtractor, DataTypeReferenceInUnionType) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4636,7 +4636,7 @@ TEST(FactsTreeExtractor, StructInUnionType) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4679,7 +4679,7 @@ TEST(FactsTreeExtractor, StructInUnion) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4722,7 +4722,7 @@ TEST(FactsTreeExtractor, UnionInStructType) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4765,7 +4765,7 @@ TEST(FactsTreeExtractor, UnionInStruct) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4833,7 +4833,7 @@ TEST(FactsTreeExtractor, TypedVariable) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4875,7 +4875,7 @@ TEST(FactsTreeExtractor, FunctionNameAsQualifiedId) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4918,7 +4918,7 @@ TEST(FactsTreeExtractor, PureVirtualFunction) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -4961,7 +4961,7 @@ TEST(FactsTreeExtractor, ExternFunction) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -5004,7 +5004,7 @@ TEST(FactsTreeExtractor, ExternTask) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -5047,7 +5047,7 @@ TEST(FactsTreeExtractor, PureVirtualTask) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -5097,7 +5097,7 @@ TEST(FactsTreeExtractor, VirtualDataDeclaration) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -5165,7 +5165,7 @@ TEST(FactsTreeExtractor, FunctionNamedArgument) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -5231,7 +5231,7 @@ TEST(FactsTreeExtractor, FunctionPortPackedAndUnpackedDimsensions) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -5276,7 +5276,7 @@ TEST(FactsTreeExtractor, UserDefinedTypeFunctionPort) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -5321,7 +5321,7 @@ TEST(FactsTreeExtractor, StructFunctionPort) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } @@ -5374,7 +5374,7 @@ TEST(FactsTreeExtractor, NestedStructFunctionPort) { const auto facts_tree = project.Extract(); const auto result_pair = DeepEqual(facts_tree, expected); - const auto P = [&project](const T& t) { return project.TreePrinter(t); }; + const auto P = [&project](const T &t) { return project.TreePrinter(t); }; EXPECT_EQ(result_pair.left, nullptr) << P(*result_pair.left); EXPECT_EQ(result_pair.right, nullptr) << P(*result_pair.right); } diff --git a/verilog/tools/kythe/indexing_facts_tree_test.cc b/verilog/tools/kythe/indexing_facts_tree_test.cc index dba82bc8e..a0ba9de17 100644 --- a/verilog/tools/kythe/indexing_facts_tree_test.cc +++ b/verilog/tools/kythe/indexing_facts_tree_test.cc @@ -32,7 +32,7 @@ class TestAnchor : public Anchor { public: // Forward all constructors template - explicit TestAnchor(Args&&... args) : Anchor(std::forward(args)...) {} + explicit TestAnchor(Args &&...args) : Anchor(std::forward(args)...) {} }; TEST(AnchorTest, DebugStringUsingOffsets) { diff --git a/verilog/tools/kythe/kythe_facts.cc b/verilog/tools/kythe/kythe_facts.cc index d1c7328f8..5621e87b0 100644 --- a/verilog/tools/kythe/kythe_facts.cc +++ b/verilog/tools/kythe/kythe_facts.cc @@ -48,7 +48,7 @@ size_t CombineHash(size_t existing, size_t addition) { // res[2] = hash(0, name[0], name[1]) // ... // res[N] = hash(0, name[0], name[1], ..., name[N]) -std::vector RollingHash(const std::vector& names) { +std::vector RollingHash(const std::vector &names) { if (names.size() <= 1) { return {0}; // Global scope } @@ -84,12 +84,12 @@ SignatureDigest Signature::Digest() const { return SignatureDigest{.rolling_hash = RollingHash(Names())}; } -bool VName::operator==(const VName& other) const { +bool VName::operator==(const VName &other) const { return path == other.path && root == other.root && corpus == other.corpus && signature == other.signature && language == other.language; } -std::ostream& VName::FormatJSON(std::ostream& stream, bool debug, +std::ostream &VName::FormatJSON(std::ostream &stream, bool debug, int indentation) const { // Output new line only in debug mode. const std::string separator = debug ? "\n" : ""; @@ -105,16 +105,16 @@ std::ostream& VName::FormatJSON(std::ostream& stream, bool debug, return stream; } -std::ostream& operator<<(std::ostream& stream, const VName& vname) { +std::ostream &operator<<(std::ostream &stream, const VName &vname) { return vname.FormatJSON(stream, /*debug=*/true); } -bool Fact::operator==(const Fact& other) const { +bool Fact::operator==(const Fact &other) const { return fact_value == other.fact_value && fact_name == other.fact_name && node_vname == other.node_vname; } -std::ostream& Fact::FormatJSON(std::ostream& stream, bool debug, +std::ostream &Fact::FormatJSON(std::ostream &stream, bool debug, int indentation) const { // Output new line only in debug mode. const std::string separator = debug ? "\n" : ""; @@ -134,16 +134,16 @@ std::ostream& Fact::FormatJSON(std::ostream& stream, bool debug, return stream; } -std::ostream& operator<<(std::ostream& stream, const Fact& fact) { +std::ostream &operator<<(std::ostream &stream, const Fact &fact) { return fact.FormatJSON(stream, /*debug=*/true); } -bool Edge::operator==(const Edge& other) const { +bool Edge::operator==(const Edge &other) const { return edge_name == other.edge_name && source_node == other.source_node && target_node == other.target_node; } -std::ostream& Edge::FormatJSON(std::ostream& stream, bool debug, +std::ostream &Edge::FormatJSON(std::ostream &stream, bool debug, int indentation) const { // Output new line only in debug mode. const std::string separator = debug ? "\n" : ""; @@ -164,7 +164,7 @@ std::ostream& Edge::FormatJSON(std::ostream& stream, bool debug, return stream << verible::Spacer(indentation) << "}"; } -std::ostream& operator<<(std::ostream& stream, const Edge& edge) { +std::ostream &operator<<(std::ostream &stream, const Edge &edge) { return edge.FormatJSON(stream, /*debug=*/true); } diff --git a/verilog/tools/kythe/kythe_facts.h b/verilog/tools/kythe/kythe_facts.h index addc6abd6..548fef11b 100644 --- a/verilog/tools/kythe/kythe_facts.h +++ b/verilog/tools/kythe/kythe_facts.h @@ -33,18 +33,18 @@ struct SignatureDigest { size_t Hash() const { return rolling_hash.back(); } - bool operator==(const SignatureDigest& d) const { + bool operator==(const SignatureDigest &d) const { return rolling_hash.size() == d.rolling_hash.size() && rolling_hash.back() == d.rolling_hash.back(); } - friend std::ostream& operator<<(std::ostream& os, const SignatureDigest& d) { + friend std::ostream &operator<<(std::ostream &os, const SignatureDigest &d) { os << "{.Hash=" << d.Hash() << "}"; return os; } }; template -H AbslHashValue(H state, const SignatureDigest& d) { +H AbslHashValue(H state, const SignatureDigest &d) { return H::combine(std::move(state), d.rolling_hash); } @@ -53,15 +53,15 @@ class Signature { public: explicit Signature(absl::string_view name = "") : names_({name}) {} - Signature(const Signature& parent, absl::string_view name) + Signature(const Signature &parent, absl::string_view name) : names_(parent.Names()) { names_.push_back(name); } - bool operator==(const Signature& other) const { + bool operator==(const Signature &other) const { return names_ == other.names_; } - bool operator!=(const Signature& other) const { return !(*this == other); } + bool operator!=(const Signature &other) const { return !(*this == other); } // Returns the signature concatenated as a string. std::string ToString() const; @@ -69,7 +69,7 @@ class Signature { // Returns the signature concatenated as a string in base 64. std::string ToBase64() const; - const std::vector& Names() const { return names_; } + const std::vector &Names() const { return names_; } // Returns signature's short form for fast and lightweight comparision. SignatureDigest Digest() const; @@ -88,15 +88,15 @@ class Signature { std::vector names_; }; template -H AbslHashValue(H state, const Signature& v) { +H AbslHashValue(H state, const Signature &v) { return H::combine(std::move(state), v.Names()); } // Node vector name for kythe facts. struct VName { - bool operator==(const VName& other) const; + bool operator==(const VName &other) const; - std::ostream& FormatJSON(std::ostream&, bool debug, + std::ostream &FormatJSON(std::ostream &, bool debug, int indentation = 0) const; // Path for the file the VName is extracted from. absl::string_view path; @@ -114,24 +114,24 @@ struct VName { absl::string_view language = kDefaultKytheLanguage; }; template -H AbslHashValue(H state, const VName& v) { +H AbslHashValue(H state, const VName &v) { return H::combine(std::move(state), v.path, v.root, v.signature, v.corpus); } -std::ostream& operator<<(std::ostream&, const VName&); +std::ostream &operator<<(std::ostream &, const VName &); // Facts for kythe. // For more information: // https://www.kythe.io/docs/kythe-storage.html#_a_id_termfact_a_fact // https://www.kythe.io/docs/schema/writing-an-indexer.html#_modeling_kythe_entries struct Fact { - Fact(const VName& vname, absl::string_view name, absl::string_view value) + Fact(const VName &vname, absl::string_view name, absl::string_view value) : node_vname(vname), fact_name(name), fact_value(value) {} - bool operator==(const Fact& other) const; - bool operator!=(const Fact& other) const { return !(*this == other); } + bool operator==(const Fact &other) const; + bool operator!=(const Fact &other) const { return !(*this == other); } - std::ostream& FormatJSON(std::ostream&, bool debug, + std::ostream &FormatJSON(std::ostream &, bool debug, int indentation = 0) const; // The VName of the node this fact is about. const VName node_vname; @@ -144,23 +144,23 @@ struct Fact { const std::string fact_value; }; template -H AbslHashValue(H state, const Fact& v) { +H AbslHashValue(H state, const Fact &v) { return H::combine(std::move(state), v.node_vname, v.fact_name, v.fact_value); } -std::ostream& operator<<(std::ostream&, const Fact&); +std::ostream &operator<<(std::ostream &, const Fact &); // Edges for kythe. // For more information: // https://www.kythe.io/docs/schema/writing-an-indexer.html#_modeling_kythe_entries struct Edge { - Edge(const VName& source, absl::string_view name, const VName& target) + Edge(const VName &source, absl::string_view name, const VName &target) : source_node(source), edge_name(name), target_node(target) {} - bool operator==(const Edge& other) const; - bool operator!=(const Edge& other) const { return !(*this == other); } + bool operator==(const Edge &other) const; + bool operator!=(const Edge &other) const { return !(*this == other); } - std::ostream& FormatJSON(std::ostream&, bool debug, + std::ostream &FormatJSON(std::ostream &, bool debug, int indentation = 0) const; // The VName of the source node of this edge. @@ -174,12 +174,12 @@ struct Edge { const VName target_node; }; template -H AbslHashValue(H state, const Edge& v) { +H AbslHashValue(H state, const Edge &v) { return H::combine(std::move(state), v.source_node, v.target_node, v.edge_name); } -std::ostream& operator<<(std::ostream&, const Edge&); +std::ostream &operator<<(std::ostream &, const Edge &); } // namespace kythe } // namespace verilog diff --git a/verilog/tools/kythe/kythe_facts_extractor.cc b/verilog/tools/kythe/kythe_facts_extractor.cc index 7225103fa..4fc7ae9ec 100644 --- a/verilog/tools/kythe/kythe_facts_extractor.cc +++ b/verilog/tools/kythe/kythe_facts_extractor.cc @@ -42,7 +42,7 @@ namespace { // Returns the file path of the file from the given indexing facts tree node // tagged with kFile. -absl::string_view GetFilePathFromRoot(const IndexingFactNode& root) { +absl::string_view GetFilePathFromRoot(const IndexingFactNode &root) { CHECK_EQ(root.Value().GetIndexingFactType(), IndexingFactType::kFile); return root.Value().Anchors()[0].Text(); } @@ -57,8 +57,8 @@ absl::string_view GetFilePathFromRoot(const IndexingFactNode& root) { class KytheFactsExtractor { public: KytheFactsExtractor(absl::string_view file_path, absl::string_view corpus, - KytheOutput* facts_output, - ScopeResolver* previous_files_scopes) + KytheOutput *facts_output, + ScopeResolver *previous_files_scopes) : file_path_(file_path), corpus_(corpus), facts_output_(facts_output), @@ -76,15 +76,15 @@ class KytheFactsExtractor { // module bar(); // wire x; ==> "bar#x" // endmodule: bar - class VNameContext : public verible::AutoPopStack { + class VNameContext : public verible::AutoPopStack { public: - using base_type = verible::AutoPopStack; + using base_type = verible::AutoPopStack; // member class to handle push and pop of stack safely using AutoPop = base_type::AutoPop; // returns the top VName of the stack - const VName& top() const { return *ABSL_DIE_IF_NULL(base_type::top()); } + const VName &top() const { return *ABSL_DIE_IF_NULL(base_type::top()); } }; // Returns the full path of the current source file. @@ -96,127 +96,127 @@ class KytheFactsExtractor { public: // Extracts kythe facts from the given IndexingFactsTree root. The result is // written to Kythe output. - void ExtractFile(const IndexingFactNode&); + void ExtractFile(const IndexingFactNode &); private: // Resolves the tag of the given node and directs the flow to the appropriate // function to extract kythe facts for that node. Returns true if any Kythe // fact was created. - bool IndexingFactNodeTagResolver(const IndexingFactNode&); + bool IndexingFactNodeTagResolver(const IndexingFactNode &); // Determines whether to create a scope for this node or not and visits the // children. - void VisitAutoConstructScope(const IndexingFactNode& node, - const VName& vname); + void VisitAutoConstructScope(const IndexingFactNode &node, + const VName &vname); // Add the given VName to vnames_context (to be used in scope relative // signatures) and visits the children of the given node creating a new scope // for the given node. - void VisitUsingVName(const IndexingFactNode& node, const VName&); + void VisitUsingVName(const IndexingFactNode &node, const VName &); // Directs the flow to the children of the given node. - void Visit(const IndexingFactNode& node); + void Visit(const IndexingFactNode &node); // Determines whether or not to create a child of edge between the current // node and the previous node. - void CreateChildOfEdge(IndexingFactType, const VName&); + void CreateChildOfEdge(IndexingFactType, const VName &); // Returns the scope of the parent's type. E.g. in case `my_class // my_instance`, `my_instance` gets the definition scope from `my_class` so // that `my_instance.method()` can be resolved as `method` exists in the // `my_class`s scope. std::optional GetParentTypeScope( - const IndexingFactNode& node) const; + const IndexingFactNode &node) const; //================================================================= // Declare* methods create facts (some edges) and may introduce new scopes. // Reference* methods only create edges, and may not modify scopes' contents. // Extracts kythe facts from file node and returns it VName. - VName DeclareFile(const IndexingFactNode&); + VName DeclareFile(const IndexingFactNode &); // Extracts kythe facts for a reference to some user defined data type like // class or module. - void ReferenceDataType(const IndexingFactNode&); + void ReferenceDataType(const IndexingFactNode &); // Extracts kythe facts for a constant like member in enums. - VName DeclareConstant(const IndexingFactNode&); + VName DeclareConstant(const IndexingFactNode &); // Extracts kythe facts for structs or unions. - VName DeclareStructOrUnion(const IndexingFactNode&); + VName DeclareStructOrUnion(const IndexingFactNode &); // Extracts kythe facts for a type declaration. - VName DeclareTypedef(const IndexingFactNode&); + VName DeclareTypedef(const IndexingFactNode &); // Extracts kythe facts from interface node and returns it VName. - VName DeclareInterface(const IndexingFactNode& interface_fact_node); + VName DeclareInterface(const IndexingFactNode &interface_fact_node); // Extracts kythe facts from program node and returns it VName. - VName DeclareProgram(const IndexingFactNode& program_fact_node); + VName DeclareProgram(const IndexingFactNode &program_fact_node); // Extracts kythe facts from module named port node e.g("m(.in1(a))"). - void ReferenceModuleNamedPort(const IndexingFactNode&); + void ReferenceModuleNamedPort(const IndexingFactNode &); // Extracts kythe facts from named param // e.g module_type #(.N(x)) extracts "N"; - void ReferenceNamedParam(const IndexingFactNode&); + void ReferenceNamedParam(const IndexingFactNode &); // Extracts kythe facts from module node and returns it VName. - VName DeclareModule(const IndexingFactNode&); + VName DeclareModule(const IndexingFactNode &); // Extracts kythe facts from class node and returns it VName. - VName DeclareClass(const IndexingFactNode&); + VName DeclareClass(const IndexingFactNode &); // Extracts kythe facts from class extends node. - void ReferenceExtendsInheritance(const IndexingFactNode&); + void ReferenceExtendsInheritance(const IndexingFactNode &); // Extracts kythe facts from module instance, class instance, variable // definition and param declaration nodes and returns its VName. - VName DeclareVariable(const IndexingFactNode& node); + VName DeclareVariable(const IndexingFactNode &node); // Extracts kythe facts from a module port reference node. - void ReferenceVariable(const IndexingFactNode& node); + void ReferenceVariable(const IndexingFactNode &node); // Creates a new anonymous scope for if conditions and loops. - VName DeclareAnonymousScope(const IndexingFactNode& temp_scope); + VName DeclareAnonymousScope(const IndexingFactNode &temp_scope); // Extracts kythe facts from a function or task node and returns its VName. - VName DeclareFunctionOrTask(const IndexingFactNode& function_fact_node); + VName DeclareFunctionOrTask(const IndexingFactNode &function_fact_node); // Extracts kythe facts from a function or task call node. void ReferenceFunctionOrTaskCall( - const IndexingFactNode& function_call_fact_node); + const IndexingFactNode &function_call_fact_node); // Extracts kythe facts from a package declaration node and returns its VName. - VName DeclarePackage(const IndexingFactNode& node); + VName DeclarePackage(const IndexingFactNode &node); // Extracts kythe facts from package import node. - void ReferencePackageImport(const IndexingFactNode& node); + void ReferencePackageImport(const IndexingFactNode &node); // Extracts kythe facts from a macro definition node and returns its VName. - VName DeclareMacroDefinition(const IndexingFactNode& macro_definition_node); + VName DeclareMacroDefinition(const IndexingFactNode ¯o_definition_node); // Extracts kythe facts from a macro call node. - void ReferenceMacroCall(const IndexingFactNode& macro_call_node); + void ReferenceMacroCall(const IndexingFactNode ¯o_call_node); // Extracts kythe facts from a "`include" node. - void ReferenceIncludeFile(const IndexingFactNode& include_node); + void ReferenceIncludeFile(const IndexingFactNode &include_node); // Extracts kythe facts from member reference statement. // e.g pkg::member or class::member or class.member // The names are treated as anchors e.g: // pkg::member => {Anchor(pkg), Anchor(member)} // pkg::class_name::var => {Anchor(pkg), Anchor(class_name), Anchor(var)} - void ReferenceMember(const IndexingFactNode& member_reference_node); + void ReferenceMember(const IndexingFactNode &member_reference_node); //============ end of Declare*, Reference* methods =================== // Create "ref" edges that point from the given anchor to the given // definition. - void CreateAnchorReference(const Anchor& anchor, const VName& definition); + void CreateAnchorReference(const Anchor &anchor, const VName &definition); // Generates an anchor VName for kythe. - VName CreateAnchor(const Anchor&); + VName CreateAnchor(const Anchor &); // Appends the signatures of previous containing scope vname to make // signatures unique relative to scopes. @@ -225,14 +225,14 @@ class KytheFactsExtractor { // Generates fact strings for Kythe facts. // Schema for this fact can be found here: // https://kythe.io/docs/schema/writing-an-indexer.html - void CreateFact(const VName& vname, absl::string_view name, + void CreateFact(const VName &vname, absl::string_view name, absl::string_view value); // Generates edge strings for Kythe edges. // Schema for this edge can be found here: // https://kythe.io/docs/schema/writing-an-indexer.html - void CreateEdge(const VName& source, absl::string_view name, - const VName& target); + void CreateEdge(const VName &source, absl::string_view name, + const VName &target); // Holds the hashes of the output Kythe facts and edges (for deduplication). absl::flat_hash_set seen_kythe_hashes_; @@ -244,7 +244,7 @@ class KytheFactsExtractor { absl::string_view corpus_; // Output for produced Kythe facts. Not owned. - KytheOutput* const facts_output_; + KytheOutput *const facts_output_; // Keeps track of VNames of ancestors as the visitor traverses the facts // tree. @@ -252,7 +252,7 @@ class KytheFactsExtractor { // Keeps track and saves the explored scopes. Used to resolve symbols to their // definition. - ScopeResolver* const scope_resolver_; + ScopeResolver *const scope_resolver_; // Location signature backing store. // Inside signatures, we record locations as string_views, @@ -262,9 +262,9 @@ class KytheFactsExtractor { absl::node_hash_set signature_locations_; }; -void StreamKytheFactsEntries(KytheOutput* kythe_output, - const IndexingFactNode& file_list, - const VerilogProject& project) { +void StreamKytheFactsEntries(KytheOutput *kythe_output, + const IndexingFactNode &file_list, + const VerilogProject &project) { VLOG(1) << __FUNCTION__; // TODO(fangism): re-implement root-level symbol lookup with a proper // project-wide symbol table, for efficient lookup. @@ -274,7 +274,7 @@ void StreamKytheFactsEntries(KytheOutput* kythe_output, // Process each file in the original listed order. ScopeResolver scope_resolver(Signature("")); - for (const IndexingFactNode& root : file_list.Children()) { + for (const IndexingFactNode &root : file_list.Children()) { scope_resolver.SetCurrentScope(Signature("")); const absl::Time extraction_start = absl::Now(); // 'root' corresponds to the fact tree for a particular file. @@ -295,7 +295,7 @@ void StreamKytheFactsEntries(KytheOutput* kythe_output, VLOG(1) << "end of " << __FUNCTION__; } -void KytheFactsExtractor::ExtractFile(const IndexingFactNode& root) { +void KytheFactsExtractor::ExtractFile(const IndexingFactNode &root) { // root corresponds to the indexing tree for a single file. // Fixed-point analysis: Repeat fact extraction until no new facts are found. @@ -306,12 +306,12 @@ void KytheFactsExtractor::ExtractFile(const IndexingFactNode& root) { } std::optional KytheFactsExtractor::GetParentTypeScope( - const IndexingFactNode& node) const { + const IndexingFactNode &node) const { absl::string_view node_name = node.Value().Anchors()[0].Text(); if (node.Parent() == nullptr) { return std::nullopt; } - const auto& parent_anchors = node.Parent()->Value().Anchors(); + const auto &parent_anchors = node.Parent()->Value().Anchors(); if (parent_anchors.empty()) { VLOG(2) << "GetParentTypeScope for " << node_name << " FAILED -- no parent"; return std::nullopt; @@ -319,7 +319,7 @@ std::optional KytheFactsExtractor::GetParentTypeScope( SignatureDigest focused_scope = scope_resolver_->CurrentScopeDigest(); std::optional parent_type = std::nullopt; - for (const auto& parent_anchor : parent_anchors) { + for (const auto &parent_anchor : parent_anchors) { parent_type = scope_resolver_->FindScopeAndDefinition(parent_anchor.Text(), focused_scope); if (!parent_type) { @@ -340,7 +340,7 @@ std::optional KytheFactsExtractor::GetParentTypeScope( } bool KytheFactsExtractor::IndexingFactNodeTagResolver( - const IndexingFactNode& node) { + const IndexingFactNode &node) { const size_t previously_extracted_facts_num = seen_kythe_hashes_.size(); const auto tag = node.Value().GetIndexingFactType(); @@ -483,7 +483,7 @@ bool KytheFactsExtractor::IndexingFactNodeTagResolver( } void KytheFactsExtractor::CreateChildOfEdge(IndexingFactType tag, - const VName& vname) { + const VName &vname) { // Determines whether to create a child of edge to the parent node or not. switch (tag) { case IndexingFactType::kFile: @@ -508,8 +508,8 @@ void KytheFactsExtractor::CreateChildOfEdge(IndexingFactType tag, } } -void KytheFactsExtractor::VisitAutoConstructScope(const IndexingFactNode& node, - const VName& vname) { +void KytheFactsExtractor::VisitAutoConstructScope(const IndexingFactNode &node, + const VName &vname) { const auto tag = node.Value().GetIndexingFactType(); // Must be copied (as Visit() can change the current scope). @@ -550,8 +550,8 @@ void KytheFactsExtractor::VisitAutoConstructScope(const IndexingFactNode& node, scope_resolver_->SetCurrentScope(current_scope); } -void KytheFactsExtractor::VisitUsingVName(const IndexingFactNode& node, - const VName& vname) { +void KytheFactsExtractor::VisitUsingVName(const IndexingFactNode &node, + const VName &vname) { const VNameContext::AutoPop vnames_auto_pop(&vnames_context_, &vname); // Must be copied (as Visit() can change the current scope). const Signature current_scope = scope_resolver_->CurrentScope(); @@ -559,19 +559,19 @@ void KytheFactsExtractor::VisitUsingVName(const IndexingFactNode& node, scope_resolver_->SetCurrentScope(current_scope); } -void KytheFactsExtractor::Visit(const IndexingFactNode& node) { - for (const IndexingFactNode& child : node.Children()) { +void KytheFactsExtractor::Visit(const IndexingFactNode &node) { + for (const IndexingFactNode &child : node.Children()) { IndexingFactNodeTagResolver(child); } } -VName KytheFactsExtractor::DeclareFile(const IndexingFactNode& file_fact_node) { +VName KytheFactsExtractor::DeclareFile(const IndexingFactNode &file_fact_node) { VName file_vname = {.path = FilePath(), .root = "", .signature = Signature(""), .corpus = Corpus(), .language = kEmptyKytheLanguage}; - const auto& anchors(file_fact_node.Value().Anchors()); + const auto &anchors(file_fact_node.Value().Anchors()); CHECK_GE(anchors.size(), 2); const absl::string_view code_text = file_fact_node.Value().Anchors()[1].Text(); @@ -586,9 +586,9 @@ VName KytheFactsExtractor::DeclareFile(const IndexingFactNode& file_fact_node) { } VName KytheFactsExtractor::DeclareModule( - const IndexingFactNode& module_fact_node) { - const auto& anchors = module_fact_node.Value().Anchors(); - const Anchor& module_name = anchors[0]; + const IndexingFactNode &module_fact_node) { + const auto &anchors = module_fact_node.Value().Anchors(); + const Anchor &module_name = anchors[0]; VName module_vname = { .path = FilePath(), .root = "", @@ -602,7 +602,7 @@ VName KytheFactsExtractor::DeclareModule( CreateEdge(module_name_anchor, kEdgeDefinesBinding, module_vname); if (anchors.size() > 1) { - const Anchor& module_end_label = anchors[1]; + const Anchor &module_end_label = anchors[1]; const VName module_end_label_anchor = CreateAnchor(module_end_label); CreateEdge(module_end_label_anchor, kEdgeRef, module_vname); } @@ -611,9 +611,9 @@ VName KytheFactsExtractor::DeclareModule( } VName KytheFactsExtractor::DeclareProgram( - const IndexingFactNode& program_fact_node) { - const auto& anchors = program_fact_node.Value().Anchors(); - const Anchor& program_name = anchors[0]; + const IndexingFactNode &program_fact_node) { + const auto &anchors = program_fact_node.Value().Anchors(); + const Anchor &program_name = anchors[0]; VName program_vname = { .path = FilePath(), @@ -627,7 +627,7 @@ VName KytheFactsExtractor::DeclareProgram( CreateEdge(program_name_anchor, kEdgeDefinesBinding, program_vname); if (anchors.size() > 1) { - const Anchor& program_end_label = anchors[1]; + const Anchor &program_end_label = anchors[1]; const VName program_end_label_anchor = CreateAnchor(program_end_label); CreateEdge(program_end_label_anchor, kEdgeRef, program_vname); } @@ -636,9 +636,9 @@ VName KytheFactsExtractor::DeclareProgram( } VName KytheFactsExtractor::DeclareInterface( - const IndexingFactNode& interface_fact_node) { - const auto& anchors = interface_fact_node.Value().Anchors(); - const Anchor& interface_name = anchors[0]; + const IndexingFactNode &interface_fact_node) { + const auto &anchors = interface_fact_node.Value().Anchors(); + const Anchor &interface_name = anchors[0]; VName interface_vname = { .path = FilePath(), @@ -651,7 +651,7 @@ VName KytheFactsExtractor::DeclareInterface( CreateEdge(interface_name_anchor, kEdgeDefinesBinding, interface_vname); if (anchors.size() > 1) { - const Anchor& interface_end_label = anchors[1]; + const Anchor &interface_end_label = anchors[1]; const VName interface_end_label_anchor = CreateAnchor(interface_end_label); CreateEdge(interface_end_label_anchor, kEdgeRef, interface_vname); } @@ -660,11 +660,11 @@ VName KytheFactsExtractor::DeclareInterface( } void KytheFactsExtractor::ReferenceDataType( - const IndexingFactNode& data_type_reference) { - const auto& anchors = data_type_reference.Value().Anchors(); + const IndexingFactNode &data_type_reference) { + const auto &anchors = data_type_reference.Value().Anchors(); SignatureDigest focused_scope = scope_resolver_->CurrentScopeDigest(); - for (const auto& anchor : anchors) { + for (const auto &anchor : anchors) { const std::optional type = scope_resolver_->FindScopeAndDefinition(anchor.Text(), focused_scope); if (!type) { @@ -676,8 +676,8 @@ void KytheFactsExtractor::ReferenceDataType( } VName KytheFactsExtractor::DeclareTypedef( - const IndexingFactNode& type_declaration) { - const auto& anchor = type_declaration.Value().Anchors()[0]; + const IndexingFactNode &type_declaration) { + const auto &anchor = type_declaration.Value().Anchors()[0]; VName type_vname = {.path = FilePath(), .root = "", .signature = CreateScopeRelativeSignature(anchor.Text()), @@ -691,9 +691,9 @@ VName KytheFactsExtractor::DeclareTypedef( } void KytheFactsExtractor::ReferenceNamedParam( - const IndexingFactNode& named_param_node) { + const IndexingFactNode &named_param_node) { // Get the anchors. - const auto& param_name = named_param_node.Value().Anchors()[0]; + const auto ¶m_name = named_param_node.Value().Anchors()[0]; std::optional param_name_type = std::nullopt; const auto parent_type = GetParentTypeScope(named_param_node); if (parent_type) { @@ -715,8 +715,8 @@ void KytheFactsExtractor::ReferenceNamedParam( } void KytheFactsExtractor::ReferenceModuleNamedPort( - const IndexingFactNode& named_port_node) { - const auto& port_name = named_port_node.Value().Anchors()[0]; + const IndexingFactNode &named_port_node) { + const auto &port_name = named_port_node.Value().Anchors()[0]; std::optional port_name_type = std::nullopt; const auto parent_type = GetParentTypeScope(named_port_node); @@ -745,10 +745,10 @@ void KytheFactsExtractor::ReferenceModuleNamedPort( } VName KytheFactsExtractor::DeclareVariable( - const IndexingFactNode& variable_definition_node) { - const auto& anchors = variable_definition_node.Value().Anchors(); + const IndexingFactNode &variable_definition_node) { + const auto &anchors = variable_definition_node.Value().Anchors(); CHECK(!anchors.empty()); - const Anchor& anchor = anchors[0]; + const Anchor &anchor = anchors[0]; VName variable_vname = { .path = FilePath(), .root = "", @@ -764,11 +764,11 @@ VName KytheFactsExtractor::DeclareVariable( } void KytheFactsExtractor::ReferenceVariable( - const IndexingFactNode& variable_reference_node) { - const auto& anchors = variable_reference_node.Value().Anchors(); + const IndexingFactNode &variable_reference_node) { + const auto &anchors = variable_reference_node.Value().Anchors(); SignatureDigest focused_scope = scope_resolver_->CurrentScopeDigest(); - for (const auto& anchor : anchors) { + for (const auto &anchor : anchors) { const auto type = scope_resolver_->FindScopeAndDefinition(anchor.Text(), focused_scope); if (!type) { @@ -780,9 +780,9 @@ void KytheFactsExtractor::ReferenceVariable( } VName KytheFactsExtractor::DeclarePackage( - const IndexingFactNode& package_declaration_node) { - const auto& anchors = package_declaration_node.Value().Anchors(); - const Anchor& package_name = anchors[0]; + const IndexingFactNode &package_declaration_node) { + const auto &anchors = package_declaration_node.Value().Anchors(); + const Anchor &package_name = anchors[0]; VName package_vname = { .path = FilePath(), @@ -795,7 +795,7 @@ VName KytheFactsExtractor::DeclarePackage( CreateEdge(package_name_anchor, kEdgeDefinesBinding, package_vname); if (anchors.size() > 1) { - const Anchor& package_end_label = anchors[1]; + const Anchor &package_end_label = anchors[1]; const VName package_end_label_anchor = CreateAnchor(package_end_label); CreateEdge(package_end_label_anchor, kEdgeRef, package_vname); } @@ -804,8 +804,8 @@ VName KytheFactsExtractor::DeclarePackage( } VName KytheFactsExtractor::DeclareMacroDefinition( - const IndexingFactNode& macro_definition_node) { - const Anchor& macro_name = macro_definition_node.Value().Anchors()[0]; + const IndexingFactNode ¯o_definition_node) { + const Anchor ¯o_name = macro_definition_node.Value().Anchors()[0]; // The signature is relative to the global scope so no relative signature // created here. @@ -822,8 +822,8 @@ VName KytheFactsExtractor::DeclareMacroDefinition( } void KytheFactsExtractor::ReferenceMacroCall( - const IndexingFactNode& macro_call_node) { - const Anchor& macro_name = macro_call_node.Value().Anchors()[0]; + const IndexingFactNode ¯o_call_node) { + const Anchor ¯o_name = macro_call_node.Value().Anchors()[0]; const VName macro_vname_anchor = CreateAnchor(macro_name); // The signature is relative to the global scope so no relative signature @@ -838,7 +838,7 @@ void KytheFactsExtractor::ReferenceMacroCall( } VName KytheFactsExtractor::DeclareFunctionOrTask( - const IndexingFactNode& function_fact_node) { + const IndexingFactNode &function_fact_node) { // TODO(hzeller): null check added. Underlying issue // needs more investigation; was encountered at // https://chipsalliance.github.io/sv-tests-results/?v=veribleextractor+ivtest+regress-vlg_pr1628300_iv @@ -847,7 +847,7 @@ VName KytheFactsExtractor::DeclareFunctionOrTask( return VName(); } - const auto& function_name = function_fact_node.Value().Anchors()[0]; + const auto &function_name = function_fact_node.Value().Anchors()[0]; VName function_vname = { .path = FilePath(), @@ -889,7 +889,7 @@ VName KytheFactsExtractor::DeclareFunctionOrTask( // IndexingFactsTree. if (function_type && scope_resolver_->CurrentScopeDigest() == function_type->instantiation_scope) { - const VName& overridden_function_vname = function_type->vname; + const VName &overridden_function_vname = function_type->vname; CreateEdge(function_vname, kEdgeOverrides, overridden_function_vname); // Delete the overriden base class function from the current scope so that @@ -903,11 +903,11 @@ VName KytheFactsExtractor::DeclareFunctionOrTask( } void KytheFactsExtractor::ReferenceFunctionOrTaskCall( - const IndexingFactNode& function_call_fact_node) { - const auto& anchors = function_call_fact_node.Value().Anchors(); + const IndexingFactNode &function_call_fact_node) { + const auto &anchors = function_call_fact_node.Value().Anchors(); std::optional last_type = std::nullopt; - for (const auto& anchor : anchors) { + for (const auto &anchor : anchors) { const std::optional type = last_type ? scope_resolver_->FindScopeAndDefinition( anchor.Text(), last_type->type_scope) @@ -928,9 +928,9 @@ void KytheFactsExtractor::ReferenceFunctionOrTaskCall( } VName KytheFactsExtractor::DeclareClass( - const IndexingFactNode& class_fact_node) { - const auto& anchors = class_fact_node.Value().Anchors(); - const Anchor& class_name = anchors[0]; + const IndexingFactNode &class_fact_node) { + const auto &anchors = class_fact_node.Value().Anchors(); + const Anchor &class_name = anchors[0]; VName class_vname = { .path = FilePath(), @@ -944,7 +944,7 @@ VName KytheFactsExtractor::DeclareClass( CreateEdge(class_name_anchor, kEdgeDefinesBinding, class_vname); if (anchors.size() > 1) { - const Anchor& class_end_label = anchors[1]; + const Anchor &class_end_label = anchors[1]; const VName class_end_label_anchor = CreateAnchor(class_end_label); CreateEdge(class_end_label_anchor, kEdgeRef, class_vname); } @@ -953,11 +953,11 @@ VName KytheFactsExtractor::DeclareClass( } void KytheFactsExtractor::ReferenceExtendsInheritance( - const IndexingFactNode& extends_node) { - const auto& anchors = extends_node.Value().Anchors(); + const IndexingFactNode &extends_node) { + const auto &anchors = extends_node.Value().Anchors(); std::optional last_type = std::nullopt; - for (const auto& anchor : anchors) { + for (const auto &anchor : anchors) { const auto type = scope_resolver_->FindScopeAndDefinition(anchor.Text()); if (type) { CreateAnchorReference(anchor, type->vname); @@ -967,7 +967,7 @@ void KytheFactsExtractor::ReferenceExtendsInheritance( if (last_type) { // Create kythe facts for extends. - const VName& derived_class_vname = vnames_context_.top(); + const VName &derived_class_vname = vnames_context_.top(); CreateEdge(derived_class_vname, kEdgeExtends, last_type->vname); // Append the members of the parent class as members of the current class's @@ -977,13 +977,13 @@ void KytheFactsExtractor::ReferenceExtendsInheritance( } void KytheFactsExtractor::ReferencePackageImport( - const IndexingFactNode& import_fact_node) { + const IndexingFactNode &import_fact_node) { // TODO(minatoma): remove the imported vnames before exporting the scope as // imports aren't intended to be accessible from outside the enclosing parent. // Alternatively, maintain separate sets: exported, non-exported, or provide // an attribute to distinguish. - const auto& anchors = import_fact_node.Value().Anchors(); - const Anchor& package_name_anchor = anchors[0]; + const auto &anchors = import_fact_node.Value().Anchors(); + const Anchor &package_name_anchor = anchors[0]; const std::optional package_name_anchor_type = scope_resolver_->FindScopeAndDefinition(package_name_anchor.Text()); @@ -997,7 +997,7 @@ void KytheFactsExtractor::ReferencePackageImport( // case of import pkg::my_variable. if (anchors.size() > 1) { - const Anchor& imported_item_name = anchors[1]; + const Anchor &imported_item_name = anchors[1]; const auto imported_item_name_type = scope_resolver_->FindScopeAndDefinition( imported_item_name.Text(), package_name_anchor_type->type_scope); @@ -1021,16 +1021,16 @@ void KytheFactsExtractor::ReferencePackageImport( } void KytheFactsExtractor::ReferenceMember( - const IndexingFactNode& member_reference_node) { + const IndexingFactNode &member_reference_node) { // Resolve pkg::class::member case. `pkg` must be in scope, but `class` is in // `pkg`s scope, while `member` is in `class`es scope. - const auto& anchors = member_reference_node.Value().Anchors(); + const auto &anchors = member_reference_node.Value().Anchors(); if (anchors.empty()) { return; } SignatureDigest focused_scope = scope_resolver_->CurrentScopeDigest(); - for (const auto& anchor : anchors) { + for (const auto &anchor : anchors) { const std::optional type = scope_resolver_->FindScopeAndDefinition(anchor.Text(), focused_scope); if (!type) { @@ -1044,11 +1044,11 @@ void KytheFactsExtractor::ReferenceMember( } void KytheFactsExtractor::ReferenceIncludeFile( - const IndexingFactNode& include_node) { - const auto& anchors = include_node.Value().Anchors(); + const IndexingFactNode &include_node) { + const auto &anchors = include_node.Value().Anchors(); CHECK_GE(anchors.size(), 2); - const Anchor& file_name = anchors[0]; - const Anchor& file_path = anchors[1]; + const Anchor &file_name = anchors[0]; + const Anchor &file_path = anchors[1]; const VName file_vname = {.path = file_path.Text(), .root = "", @@ -1068,16 +1068,16 @@ void KytheFactsExtractor::ReferenceIncludeFile( // Create child of edge between the parent and the member of the included // file. - const auto& included_file_content = + const auto &included_file_content = scope_resolver_->ListScopeMembers(included_file_scope->type_scope); - for (const auto& ref : included_file_content) { + for (const auto &ref : included_file_content) { CreateEdge(ref, kEdgeChildOf, vnames_context_.top()); } } VName KytheFactsExtractor::DeclareAnonymousScope( - const IndexingFactNode& temp_scope) { - const auto& scope_id = temp_scope.Value().Anchors()[0]; + const IndexingFactNode &temp_scope) { + const auto &scope_id = temp_scope.Value().Anchors()[0]; VName vname = {.path = FilePath(), .root = "", .signature = CreateScopeRelativeSignature(scope_id.Text()), @@ -1085,8 +1085,8 @@ VName KytheFactsExtractor::DeclareAnonymousScope( return vname; } -VName KytheFactsExtractor::DeclareConstant(const IndexingFactNode& constant) { - const auto& anchor = constant.Value().Anchors()[0]; +VName KytheFactsExtractor::DeclareConstant(const IndexingFactNode &constant) { + const auto &anchor = constant.Value().Anchors()[0]; VName constant_vname = { .path = FilePath(), .root = "", @@ -1101,9 +1101,9 @@ VName KytheFactsExtractor::DeclareConstant(const IndexingFactNode& constant) { } VName KytheFactsExtractor::DeclareStructOrUnion( - const IndexingFactNode& struct_node) { - const auto& anchors = struct_node.Value().Anchors(); - const Anchor& struct_name = anchors[0]; + const IndexingFactNode &struct_node) { + const auto &anchors = struct_node.Value().Anchors(); + const Anchor &struct_name = anchors[0]; VName struct_vname = { .path = FilePath(), @@ -1118,13 +1118,13 @@ VName KytheFactsExtractor::DeclareStructOrUnion( return struct_vname; } -void KytheFactsExtractor::CreateAnchorReference(const Anchor& anchor, - const VName& definition) { +void KytheFactsExtractor::CreateAnchorReference(const Anchor &anchor, + const VName &definition) { CreateEdge(CreateAnchor(anchor), kEdgeRef, definition); } -VName KytheFactsExtractor::CreateAnchor(const Anchor& anchor) { - const auto& anchor_range = anchor.SourceTextRange(); +VName KytheFactsExtractor::CreateAnchor(const Anchor &anchor) { + const auto &anchor_range = anchor.SourceTextRange(); if (!anchor_range) { LOG(ERROR) << "Anchor not set! This is a bug. Skipping this Anchor. File: " << FilePath() << " Anchor text: " << anchor.Text(); @@ -1160,7 +1160,7 @@ Signature KytheFactsExtractor::CreateScopeRelativeSignature( return Signature(vnames_context_.top().signature, signature); } -void KytheFactsExtractor::CreateFact(const VName& vname, +void KytheFactsExtractor::CreateFact(const VName &vname, absl::string_view fact_name, absl::string_view fact_value) { Fact fact(vname, fact_name, fact_value); @@ -1171,9 +1171,9 @@ void KytheFactsExtractor::CreateFact(const VName& vname, } } -void KytheFactsExtractor::CreateEdge(const VName& source_node, +void KytheFactsExtractor::CreateEdge(const VName &source_node, absl::string_view edge_name, - const VName& target_node) { + const VName &target_node) { Edge edge(source_node, edge_name, target_node); auto hash = absl::HashOf(edge); if (!seen_kythe_hashes_.contains(hash)) { @@ -1182,20 +1182,20 @@ void KytheFactsExtractor::CreateEdge(const VName& source_node, } } -std::ostream& KytheFactsPrinter::PrintJsonStream(std::ostream& stream) const { +std::ostream &KytheFactsPrinter::PrintJsonStream(std::ostream &stream) const { // TODO(fangism): Print function should not be doing extraction work. class Printer final : public KytheOutput { public: - explicit Printer(std::ostream& stream) : stream_(stream) {} - void Emit(const Fact& fact) final { + explicit Printer(std::ostream &stream) : stream_(stream) {} + void Emit(const Fact &fact) final { fact.FormatJSON(stream_, /*debug=*/false) << std::endl; } - void Emit(const Edge& edge) final { + void Emit(const Edge &edge) final { edge.FormatJSON(stream_, /*debug=*/false) << std::endl; } private: - std::ostream& stream_; + std::ostream &stream_; } printer(stream); StreamKytheFactsEntries(&printer, file_list_facts_tree_, *project_); @@ -1203,24 +1203,24 @@ std::ostream& KytheFactsPrinter::PrintJsonStream(std::ostream& stream) const { return stream; } -std::ostream& KytheFactsPrinter::PrintJson(std::ostream& stream) const { +std::ostream &KytheFactsPrinter::PrintJson(std::ostream &stream) const { // TODO(fangism): Print function should not be doing extraction work. class Printer final : public KytheOutput { public: - explicit Printer(std::ostream& stream) : stream_(stream) {} - void Emit(const Fact& fact) final { + explicit Printer(std::ostream &stream) : stream_(stream) {} + void Emit(const Fact &fact) final { if (add_comma_) stream_ << "," << std::endl; fact.FormatJSON(stream_, /*debug=*/true) << std::endl; add_comma_ = true; } - void Emit(const Edge& edge) final { + void Emit(const Edge &edge) final { if (add_comma_) stream_ << "," << std::endl; edge.FormatJSON(stream_, /*debug=*/true) << std::endl; add_comma_ = true; } private: - std::ostream& stream_; + std::ostream &stream_; bool add_comma_ = false; } printer(stream); @@ -1231,8 +1231,8 @@ std::ostream& KytheFactsPrinter::PrintJson(std::ostream& stream) const { return stream; } -std::ostream& operator<<(std::ostream& stream, - const KytheFactsPrinter& kythe_facts_printer) { +std::ostream &operator<<(std::ostream &stream, + const KytheFactsPrinter &kythe_facts_printer) { if (kythe_facts_printer.debug_) { kythe_facts_printer.PrintJson(stream); } else { diff --git a/verilog/tools/kythe/kythe_facts_extractor.h b/verilog/tools/kythe/kythe_facts_extractor.h index f59b101da..31b61ff82 100644 --- a/verilog/tools/kythe/kythe_facts_extractor.h +++ b/verilog/tools/kythe/kythe_facts_extractor.h @@ -29,41 +29,41 @@ namespace kythe { // Usage: stream << KytheFactsPrinter(IndexingFactNode); class KytheFactsPrinter { public: - KytheFactsPrinter(const IndexingFactNode& file_list_facts_tree, - const VerilogProject& project, bool debug = false) + KytheFactsPrinter(const IndexingFactNode &file_list_facts_tree, + const VerilogProject &project, bool debug = false) : file_list_facts_tree_(file_list_facts_tree), project_(&project), debug_(debug) {} // Print Kythe facts as a stream of JSON entries (one per line). Note: single // facts are well formatted JSON, but the overall output isn't! - std::ostream& PrintJsonStream(std::ostream&) const; + std::ostream &PrintJsonStream(std::ostream &) const; // Print Kythe facts as a single, well formatted & human readable JSON. - std::ostream& PrintJson(std::ostream&) const; + std::ostream &PrintJson(std::ostream &) const; - friend std::ostream& operator<<(std::ostream& stream, - const KytheFactsPrinter& kythe_facts_printer); + friend std::ostream &operator<<(std::ostream &stream, + const KytheFactsPrinter &kythe_facts_printer); private: // The root of the indexing facts tree to extract kythe facts from. - const IndexingFactNode& file_list_facts_tree_; + const IndexingFactNode &file_list_facts_tree_; // This project manages the opening and path resolution of referenced files. - const VerilogProject* const project_; + const VerilogProject *const project_; // When debugging is enabled, print human-readable un-encoded text. const bool debug_; }; -std::ostream& operator<<(std::ostream&, const KytheFactsPrinter&); +std::ostream &operator<<(std::ostream &, const KytheFactsPrinter &); // Output sink interface for producing the Kythe output. class KytheOutput { public: // Output all Kythe facts from the indexing data. - virtual void Emit(const Fact& fact) = 0; - virtual void Emit(const Edge& edge) = 0; + virtual void Emit(const Fact &fact) = 0; + virtual void Emit(const Edge &edge) = 0; virtual ~KytheOutput() = default; }; @@ -73,9 +73,9 @@ class KytheOutput { // Currently, the file_list must be dependency-ordered for best results, that // is, definitions of symbols should be encountered earlier in the file list // than references to those symbols. -void StreamKytheFactsEntries(KytheOutput* kythe_output, - const IndexingFactNode& file_list_facts_tree, - const VerilogProject& project); +void StreamKytheFactsEntries(KytheOutput *kythe_output, + const IndexingFactNode &file_list_facts_tree, + const VerilogProject &project); } // namespace kythe } // namespace verilog diff --git a/verilog/tools/kythe/kythe_proto_output.cc b/verilog/tools/kythe/kythe_proto_output.cc index 51a0ddcff..a2b807dca 100644 --- a/verilog/tools/kythe/kythe_proto_output.cc +++ b/verilog/tools/kythe/kythe_proto_output.cc @@ -29,7 +29,7 @@ using ::google::protobuf::io::FileOutputStream; using ::kythe::proto::Entry; // Returns the VName representation in Kythe's storage proto format. -::kythe::proto::VName ConvertVnameToProto(const VName& vname) { +::kythe::proto::VName ConvertVnameToProto(const VName &vname) { ::kythe::proto::VName proto_vname; *proto_vname.mutable_signature() = vname.signature.ToString(); *proto_vname.mutable_corpus() = std::string{vname.corpus}; @@ -40,7 +40,7 @@ ::kythe::proto::VName ConvertVnameToProto(const VName& vname) { } // Returns the Fact representation in Kythe's storage proto format. -Entry ConvertEdgeToEntry(const Edge& edge) { +Entry ConvertEdgeToEntry(const Edge &edge) { Entry entry; entry.set_fact_name("/"); *entry.mutable_edge_kind() = std::string{edge.edge_name}; @@ -50,7 +50,7 @@ Entry ConvertEdgeToEntry(const Edge& edge) { } // Returns the Fact representation in Kythe's storage proto format. -Entry ConvertFactToEntry(const Fact& fact) { +Entry ConvertFactToEntry(const Fact &fact) { Entry entry; *entry.mutable_fact_name() = std::string{fact.fact_name}; *entry.mutable_fact_value() = fact.fact_value; @@ -59,7 +59,7 @@ Entry ConvertFactToEntry(const Fact& fact) { } // Output entry to the stream. -void OutputProto(const Entry& entry, FileOutputStream* stream) { +void OutputProto(const Entry &entry, FileOutputStream *stream) { CodedOutputStream coded_stream(stream); coded_stream.WriteVarint32(entry.ByteSizeLong()); entry.SerializeToCodedStream(&coded_stream); @@ -70,10 +70,10 @@ void OutputProto(const Entry& entry, FileOutputStream* stream) { KytheProtoOutput::KytheProtoOutput(int fd) : out_(fd) {} KytheProtoOutput::~KytheProtoOutput() { out_.Close(); } -void KytheProtoOutput::Emit(const Fact& fact) { +void KytheProtoOutput::Emit(const Fact &fact) { OutputProto(ConvertFactToEntry(fact), &out_); } -void KytheProtoOutput::Emit(const Edge& edge) { +void KytheProtoOutput::Emit(const Edge &edge) { OutputProto(ConvertEdgeToEntry(edge), &out_); } diff --git a/verilog/tools/kythe/kythe_proto_output.h b/verilog/tools/kythe/kythe_proto_output.h index 23a90be7d..192bec3d3 100644 --- a/verilog/tools/kythe/kythe_proto_output.h +++ b/verilog/tools/kythe/kythe_proto_output.h @@ -28,8 +28,8 @@ class KytheProtoOutput final : public KytheOutput { ~KytheProtoOutput() final; // Output Kythe facts from the indexing data in proto format. - void Emit(const Fact& fact) final; - void Emit(const Edge& edge) final; + void Emit(const Fact &fact) final; + void Emit(const Edge &edge) final; private: ::google::protobuf::io::FileOutputStream out_; diff --git a/verilog/tools/kythe/kzip_creator.cc b/verilog/tools/kythe/kzip_creator.cc index 34454e619..55bbcf1eb 100644 --- a/verilog/tools/kythe/kzip_creator.cc +++ b/verilog/tools/kythe/kzip_creator.cc @@ -37,10 +37,10 @@ constexpr absl::string_view kFileRoot = "root/files/"; std::string SHA256Digest(absl::string_view content) { std::array buf; - ::SHA256(reinterpret_cast(content.data()), + ::SHA256(reinterpret_cast(content.data()), content.size(), buf.data()); - return absl::BytesToHexString( - absl::string_view(reinterpret_cast(buf.data()), buf.size())); + return absl::BytesToHexString(absl::string_view( + reinterpret_cast(buf.data()), buf.size())); } constexpr int kKZipCompressionLevel = 9; @@ -66,7 +66,7 @@ std::string KzipCreator::AddSourceFile(absl::string_view path, } absl::Status KzipCreator::AddCompilationUnit( - const ::kythe::proto::IndexedCompilation& unit) { + const ::kythe::proto::IndexedCompilation &unit) { std::string content; if (!unit.SerializeToString(&content)) { return absl::InternalError("Failed to serialize the compilation unit"); diff --git a/verilog/tools/kythe/kzip_creator.h b/verilog/tools/kythe/kzip_creator.h index ef98116aa..7b61dc8b8 100644 --- a/verilog/tools/kythe/kzip_creator.h +++ b/verilog/tools/kythe/kzip_creator.h @@ -39,7 +39,7 @@ class KzipCreator final { // Adds compilation unit to the Kzip. absl::Status AddCompilationUnit( - const ::kythe::proto::IndexedCompilation& unit); + const ::kythe::proto::IndexedCompilation &unit); private: std::unique_ptr zip_file_; diff --git a/verilog/tools/kythe/scope_resolver.cc b/verilog/tools/kythe/scope_resolver.cc index c94057024..b371e0945 100644 --- a/verilog/tools/kythe/scope_resolver.cc +++ b/verilog/tools/kythe/scope_resolver.cc @@ -26,7 +26,7 @@ namespace verilog { namespace kythe { -void ScopeResolver::SetCurrentScope(const Signature& scope) { +void ScopeResolver::SetCurrentScope(const Signature &scope) { if (current_scope_ == scope && !current_scope_digest_.rolling_hash.empty()) { return; } @@ -38,7 +38,7 @@ void ScopeResolver::SetCurrentScope(const Signature& scope) { VLOG(2) << "Set scope to: " << ScopeDebug(scope.Digest()); } -void ScopeResolver::RemoveDefinitionFromCurrentScope(const VName& vname) { +void ScopeResolver::RemoveDefinitionFromCurrentScope(const VName &vname) { absl::string_view name = vname.signature.Names().back(); auto scopes = variable_to_scoped_vname_.find(name); if (scopes == variable_to_scoped_vname_.end()) { @@ -59,7 +59,7 @@ void ScopeResolver::RemoveDefinitionFromCurrentScope(const VName& vname) { if (current_scope_names == scope_to_vnames_.end()) { return; } - auto& vnames = current_scope_names->second; + auto &vnames = current_scope_names->second; for (auto iter = vnames.begin(); iter != vnames.end(); ++iter) { if (*iter == vname) { vnames.erase(iter); @@ -69,13 +69,13 @@ void ScopeResolver::RemoveDefinitionFromCurrentScope(const VName& vname) { } void ScopeResolver::AppendScopeToCurrentScope( - const SignatureDigest& source_scope) { + const SignatureDigest &source_scope) { AppendScopeToScope(source_scope, CurrentScopeDigest()); } void ScopeResolver::AppendScopeToScope( - const SignatureDigest& source_scope, - const SignatureDigest& destination_scope) { + const SignatureDigest &source_scope, + const SignatureDigest &destination_scope) { auto scope_vnames = scope_to_vnames_.find(source_scope); if (scope_vnames == scope_to_vnames_.end()) { VLOG(2) << "Can't find scope " << ScopeDebug(source_scope) @@ -87,7 +87,7 @@ void ScopeResolver::AppendScopeToScope( return; } - for (const auto& vn : scope_vnames->second) { + for (const auto &vn : scope_vnames->second) { const std::optional vn_type = FindScopeAndDefinition(vn.signature.Names().back(), source_scope); if (!vn_type) { @@ -101,12 +101,12 @@ void ScopeResolver::AppendScopeToScope( } } -void ScopeResolver::AddDefinitionToCurrentScope(const VName& new_member) { +void ScopeResolver::AddDefinitionToCurrentScope(const VName &new_member) { AddDefinitionToCurrentScope(new_member, new_member.signature.Digest()); } void ScopeResolver::AddDefinitionToCurrentScope( - const VName& new_member, const SignatureDigest& type_scope) { + const VName &new_member, const SignatureDigest &type_scope) { // Remove the existing definition -- overwrite it with the new which has // updated information about types. RemoveDefinitionFromCurrentScope(new_member); @@ -120,7 +120,7 @@ void ScopeResolver::AddDefinitionToCurrentScope( } std::optional ScopeResolver::FindScopeAndDefinition( - absl::string_view name, const SignatureDigest& scope_focus) { + absl::string_view name, const SignatureDigest &scope_focus) { VLOG(2) << "Find definition for '" << name << "' within scope " << ScopeDebug(scope_focus); auto scope = variable_to_scoped_vname_.find(name); @@ -129,8 +129,8 @@ std::optional ScopeResolver::FindScopeAndDefinition( << ScopeDebug(scope_focus) << " (unregistered name)"; return {}; } - const ScopedVname* match = nullptr; - for (auto& scope_member : scope->second) { + const ScopedVname *match = nullptr; + for (auto &scope_member : scope->second) { SignatureDigest digest = scope_member.instantiation_scope; if (scope_focus.rolling_hash.size() < digest.rolling_hash.size() || (match != nullptr && @@ -161,8 +161,8 @@ std::optional ScopeResolver::FindScopeAndDefinition( return FindScopeAndDefinition(name, CurrentScopeDigest()); } -const absl::flat_hash_set& ScopeResolver::ListScopeMembers( - const SignatureDigest& scope_digest) const { +const absl::flat_hash_set &ScopeResolver::ListScopeMembers( + const SignatureDigest &scope_digest) const { const static absl::flat_hash_set kEmptyMemberList; auto scope = scope_to_vnames_.find(scope_digest); if (scope == scope_to_vnames_.end()) { @@ -171,7 +171,7 @@ const absl::flat_hash_set& ScopeResolver::ListScopeMembers( return scope->second; } -std::string ScopeResolver::ScopeDebug(const SignatureDigest& scope) const { +std::string ScopeResolver::ScopeDebug(const SignatureDigest &scope) const { if (!enable_debug_) { return "UNKNOWN (debug off)"; } diff --git a/verilog/tools/kythe/scope_resolver.h b/verilog/tools/kythe/scope_resolver.h index bd219b1b4..0acbbc5fb 100644 --- a/verilog/tools/kythe/scope_resolver.h +++ b/verilog/tools/kythe/scope_resolver.h @@ -38,14 +38,14 @@ struct ScopedVname { // type_scope in case this VName is a type definition). SignatureDigest instantiation_scope; VName vname; - bool operator==(const ScopedVname& other) const { + bool operator==(const ScopedVname &other) const { return type_scope == other.type_scope && instantiation_scope == other.instantiation_scope && vname == other.vname; } }; template -H AbslHashValue(H state, const ScopedVname& v) { +H AbslHashValue(H state, const ScopedVname &v) { return H::combine(std::move(state), v.type_scope, v.instantiation_scope, v.vname.signature.Digest()); } @@ -79,18 +79,18 @@ H AbslHashValue(H state, const ScopedVname& v) { // up and comparing the substrings). class ScopeResolver { public: - explicit ScopeResolver(const Signature& top_scope) { + explicit ScopeResolver(const Signature &top_scope) { SetCurrentScope(top_scope); } - ScopeResolver(const ScopeResolver&) = delete; - ScopeResolver(ScopeResolver&&) = delete; - ScopeResolver& operator=(const ScopeResolver&) = delete; - ScopeResolver& operator=(ScopeResolver&&) = delete; + ScopeResolver(const ScopeResolver &) = delete; + ScopeResolver(ScopeResolver &&) = delete; + ScopeResolver &operator=(const ScopeResolver &) = delete; + ScopeResolver &operator=(ScopeResolver &&) = delete; - void SetCurrentScope(const Signature& scope); + void SetCurrentScope(const Signature &scope); - const Signature& CurrentScope() { return current_scope_; } + const Signature &CurrentScope() { return current_scope_; } // Returns the scope and definition of the symbol under the given name. The // search is restricted to the current scope. @@ -99,34 +99,34 @@ class ScopeResolver { // Returns the scope and definition of the symbol under the given name. The // search is restricted to the provided scope. std::optional FindScopeAndDefinition( - absl::string_view name, const SignatureDigest& scope); + absl::string_view name, const SignatureDigest &scope); static SignatureDigest GlobalScope() { return Signature("").Digest(); } // Adds the members of the given scope to the current scope. - void AppendScopeToCurrentScope(const SignatureDigest& source_scope); + void AppendScopeToCurrentScope(const SignatureDigest &source_scope); // Adds the members of the source scope to the destination scope. - void AppendScopeToScope(const SignatureDigest& source_scope, - const SignatureDigest& destination_scope); + void AppendScopeToScope(const SignatureDigest &source_scope, + const SignatureDigest &destination_scope); // Removes the given VName from the current scope. - void RemoveDefinitionFromCurrentScope(const VName& vname); + void RemoveDefinitionFromCurrentScope(const VName &vname); // Adds a definition & its type to the current scope. - void AddDefinitionToCurrentScope(const VName& new_member, - const SignatureDigest& type_scope); + void AddDefinitionToCurrentScope(const VName &new_member, + const SignatureDigest &type_scope); // Adds a definition without external type to the current scope. - void AddDefinitionToCurrentScope(const VName& new_member); + void AddDefinitionToCurrentScope(const VName &new_member); - const absl::flat_hash_set& ListScopeMembers( - const SignatureDigest& scope_digest) const; + const absl::flat_hash_set &ListScopeMembers( + const SignatureDigest &scope_digest) const; // Returns human readable description of the scope. - std::string ScopeDebug(const SignatureDigest& scope) const; + std::string ScopeDebug(const SignatureDigest &scope) const; - const SignatureDigest& CurrentScopeDigest() const { + const SignatureDigest &CurrentScopeDigest() const { return current_scope_digest_; } diff --git a/verilog/tools/kythe/verilog_extractor_indexing_fact_type.cc b/verilog/tools/kythe/verilog_extractor_indexing_fact_type.cc index 18d428a26..4f562289b 100644 --- a/verilog/tools/kythe/verilog_extractor_indexing_fact_type.cc +++ b/verilog/tools/kythe/verilog_extractor_indexing_fact_type.cc @@ -37,7 +37,7 @@ std::string IndexingFactTypeEnumToString(IndexingFactType indexing_fact_type) { } } -std::ostream& operator<<(std::ostream& stream, const IndexingFactType& e) { +std::ostream &operator<<(std::ostream &stream, const IndexingFactType &e) { return stream << IndexingFactTypeEnumToString(e); } diff --git a/verilog/tools/kythe/verilog_extractor_indexing_fact_type.h b/verilog/tools/kythe/verilog_extractor_indexing_fact_type.h index 19850d8b0..87edf8f80 100644 --- a/verilog/tools/kythe/verilog_extractor_indexing_fact_type.h +++ b/verilog/tools/kythe/verilog_extractor_indexing_fact_type.h @@ -60,7 +60,7 @@ enum class IndexingFactType { // definition, returns a string stating this. std::string IndexingFactTypeEnumToString(IndexingFactType indexing_fact_type); -std::ostream& operator<<(std::ostream& stream, const IndexingFactType& e); +std::ostream &operator<<(std::ostream &stream, const IndexingFactType &e); } // namespace verilog diff --git a/verilog/tools/kythe/verilog_kythe_extractor.cc b/verilog/tools/kythe/verilog_kythe_extractor.cc index a0746b412..d2582f850 100644 --- a/verilog/tools/kythe/verilog_kythe_extractor.cc +++ b/verilog/tools/kythe/verilog_kythe_extractor.cc @@ -48,7 +48,7 @@ enum class PrintMode { kNone, }; -static const verible::EnumNameMap& PrintModeStringMap() { +static const verible::EnumNameMap &PrintModeStringMap() { static const verible::EnumNameMap kPrintModeStringMap({ {"json", PrintMode::kJSON}, {"json_debug", PrintMode::kJSONDebug}, @@ -58,17 +58,17 @@ static const verible::EnumNameMap& PrintModeStringMap() { return kPrintModeStringMap; } -static std::ostream& operator<<(std::ostream& stream, PrintMode mode) { +static std::ostream &operator<<(std::ostream &stream, PrintMode mode) { return PrintModeStringMap().Unparse(mode, stream); } -static bool AbslParseFlag(absl::string_view text, PrintMode* mode, - std::string* error) { +static bool AbslParseFlag(absl::string_view text, PrintMode *mode, + std::string *error) { return PrintModeStringMap().Parse(text, mode, error, "--print_kythe_facts value"); } -static std::string AbslUnparseFlag(const PrintMode& mode) { +static std::string AbslUnparseFlag(const PrintMode &mode) { std::ostringstream stream; stream << mode; return stream.str(); @@ -114,7 +114,7 @@ namespace kythe { // Prints Kythe facts in proto format to stdout. static void PrintKytheFactsProtoEntries( - const IndexingFactNode& file_list_facts_tree, const VerilogProject& project, + const IndexingFactNode &file_list_facts_tree, const VerilogProject &project, int fd) { KytheProtoOutput proto_output(fd); StreamKytheFactsEntries(&proto_output, file_list_facts_tree, project); @@ -122,19 +122,19 @@ static void PrintKytheFactsProtoEntries( // Just collect the facts, but don't print anything. Mostly useful for // debugging error checking or performance. -static void KytheFactsNullPrinter(const IndexingFactNode& file_list_facts_tree, - const VerilogProject& project) { +static void KytheFactsNullPrinter(const IndexingFactNode &file_list_facts_tree, + const VerilogProject &project) { class NullPrinter final : public KytheOutput { public: - void Emit(const Fact& fact) final {} - void Emit(const Edge& edge) final {} + void Emit(const Fact &fact) final {} + void Emit(const Edge &edge) final {} } printer; StreamKytheFactsEntries(&printer, file_list_facts_tree, project); } static std::vector ExtractTranslationUnits( - absl::string_view file_list_path, VerilogProject* project, - const std::vector& file_names) { + absl::string_view file_list_path, VerilogProject *project, + const std::vector &file_names) { std::vector errors; const verilog::kythe::IndexingFactNode file_list_facts_tree( verilog::kythe::ExtractFiles(file_list_path, project, file_names, @@ -172,7 +172,7 @@ static std::vector ExtractTranslationUnits( } // namespace kythe } // namespace verilog -int main(int argc, char** argv) { +int main(int argc, char **argv) { const auto usage = absl::StrCat("usage: ", argv[0], " [options] --file_list_path FILE\n", R"( Extracts kythe indexing facts from the given SystemVerilog source files. @@ -198,7 +198,7 @@ Output: Produces Indexing Facts for kythe (http://kythe.io). LOG(ERROR) << "Error while reading file list: " << status; return 1; } - const std::vector& file_paths(file_list.file_paths); + const std::vector &file_paths(file_list.file_paths); // List of the directories for where to look for included files. std::vector include_dir_paths = @@ -218,7 +218,7 @@ Output: Produces Indexing Facts for kythe (http://kythe.io). LOG(ERROR) << "Encountered some issues while indexing files (could result " "in missing indexing data):" << std::endl; - for (const auto& error : errors) { + for (const auto &error : errors) { LOG(ERROR) << error.message(); } // TODO(ikr): option to cause any errors to exit non-zero, like diff --git a/verilog/tools/kythe/verilog_kythe_kzip_writer.cc b/verilog/tools/kythe/verilog_kythe_kzip_writer.cc index 731c898e4..a3a5064a5 100644 --- a/verilog/tools/kythe/verilog_kythe_kzip_writer.cc +++ b/verilog/tools/kythe/verilog_kythe_kzip_writer.cc @@ -44,7 +44,7 @@ ABSL_RETIRED_FLAG( "The absolute location which we prepend to the files in the file " "list (where listed files are relative to)."); -int main(int argc, char** argv) { +int main(int argc, char **argv) { const auto usage = absl::StrCat("usage: ", argv[0], " [options] --filelist_path FILE " R"( @@ -82,10 +82,10 @@ Output: Produces Kythe KZip (https://kythe.io/docs/kythe-kzip.html). } // Normalize the file list absl::string_view filelist_root = verible::file::Dirname(filelist_path); - for (std::string& file_path : filelist.file_paths) { + for (std::string &file_path : filelist.file_paths) { file_path = verible::file::JoinPath(filelist_root, file_path); } - for (std::string& include : filelist.preprocessing.include_dirs) { + for (std::string &include : filelist.preprocessing.include_dirs) { include = verible::file::JoinPath(filelist_root, include); } @@ -95,21 +95,21 @@ Output: Produces Kythe KZip (https://kythe.io/docs/kythe-kzip.html). compilation.mutable_index()->add_revisions(code_revision); } - auto* unit = compilation.mutable_unit(); + auto *unit = compilation.mutable_unit(); *unit->mutable_v_name()->mutable_corpus() = absl::GetFlag(FLAGS_corpus); *unit->mutable_v_name()->mutable_language() = "verilog"; *unit->add_argument() = "--f=filelist"; // Construct Verible project - const std::vector& file_paths(filelist.file_paths); + const std::vector &file_paths(filelist.file_paths); verilog::kythe::KzipCreator kzip(output_path); const std::string filelist_digest = kzip.AddSourceFile("filelist", filelist.ToString()); - auto* filelist_input = unit->add_required_input(); + auto *filelist_input = unit->add_required_input(); *filelist_input->mutable_info()->mutable_path() = "filelist"; *filelist_input->mutable_info()->mutable_digest() = filelist_digest; - for (const std::string& file_path : file_paths) { + for (const std::string &file_path : file_paths) { auto content_or = verible::file::GetContentAsString(file_path); if (!content_or.ok()) { LOG(ERROR) << "Failed to open " << file_path @@ -117,7 +117,7 @@ Output: Produces Kythe KZip (https://kythe.io/docs/kythe-kzip.html). continue; } const std::string digest = kzip.AddSourceFile(file_path, *content_or); - auto* file_input = unit->add_required_input(); + auto *file_input = unit->add_required_input(); *file_input->mutable_info()->mutable_path() = file_path; *file_input->mutable_info()->mutable_digest() = digest; *file_input->mutable_v_name()->mutable_path() = file_path; diff --git a/verilog/tools/ls/autoexpand_test.cc b/verilog/tools/ls/autoexpand_test.cc index 9d95fb9a1..6b3d0fe13 100644 --- a/verilog/tools/ls/autoexpand_test.cc +++ b/verilog/tools/ls/autoexpand_test.cc @@ -34,12 +34,12 @@ using verible::lsp::TextEdit; // Generate a specific code action and extract text edits from it std::vector AutoExpandCodeActionToTextEdits( - SymbolTableHandler* symbol_table_handler, const BufferTracker* tracker, + SymbolTableHandler *symbol_table_handler, const BufferTracker *tracker, Range range, absl::string_view title) { CodeActionParams p = {.textDocument = {tracker->current()->uri()}, .range = range}; nlohmann::json changes; - for (const CodeAction& action : + for (const CodeAction &action : GenerateAutoExpandCodeActions(symbol_table_handler, tracker, p)) { if (action.title == title) { EXPECT_TRUE(changes.empty()); @@ -52,11 +52,11 @@ std::vector AutoExpandCodeActionToTextEdits( // Generate text edits from a full AUTO expansion std::vector GenerateFullAutoExpandTextEdits( - SymbolTableHandler* symbol_table_handler, const BufferTracker* tracker) { + SymbolTableHandler *symbol_table_handler, const BufferTracker *tracker) { EXPECT_TRUE(tracker); const auto current = tracker->current(); EXPECT_TRUE(current); - const TextStructureView& text_structure = current->parser().Data(); + const TextStructureView &text_structure = current->parser().Data(); return AutoExpandCodeActionToTextEdits( symbol_table_handler, tracker, {.start = {.line = 0}, @@ -66,8 +66,8 @@ std::vector GenerateFullAutoExpandTextEdits( // Determines how TextTextEdits* should test a function struct TestRun { - using EditFn = - std::function(SymbolTableHandler*, BufferTracker*)>; + using EditFn = std::function(SymbolTableHandler *, + BufferTracker *)>; const EditFn edit_fn = GenerateFullAutoExpandTextEdits; // Function that // generates text // edits to check @@ -107,12 +107,12 @@ std::string Format(const absl::string_view filename, // effect void TestTextEditsWithProject( - const std::vector& project_file_contents, + const std::vector &project_file_contents, absl::string_view text_before, const absl::string_view text_golden, std::deque runs = TestRun::defaultRuns()) { if (runs.empty()) return; - const auto& run = runs.front(); - static const char* TESTED_FILENAME = "<>"; + const auto &run = runs.front(); + static const char *TESTED_FILENAME = "<>"; // Create a Verilog project with the given project file contents const std::shared_ptr proj = std::make_shared(".", std::vector()); @@ -145,14 +145,14 @@ void TestTextEditsWithProject( // valid. // Note: according to the spec, TextEdits should never overlap. std::sort(edits.rbegin(), edits.rend(), - [](const TextEdit& first, const TextEdit& second) { + [](const TextEdit &first, const TextEdit &second) { if (first.range.end.line == second.range.start.line) { return first.range.end.character < second.range.start.character; } return first.range.end.line < second.range.start.line; }); // Apply the text edits - for (const TextEdit& edit : edits) { + for (const TextEdit &edit : edits) { buffer.ApplyChange(TextDocumentContentChangeEvent{ .range = edit.range, .has_range = true, .text = edit.newText}); } @@ -180,7 +180,7 @@ void TestTextEditsWithProject( // Same as above, without the project file parameter void TestTextEdits(const absl::string_view text_before, const absl::string_view text_golden, - const std::deque& runs = TestRun::defaultRuns()) { + const std::deque &runs = TestRun::defaultRuns()) { TestTextEditsWithProject({}, text_before, text_golden, runs); } @@ -2112,15 +2112,15 @@ module foo ( /*AUTOARG*/ endmodule )", {TestRun{.edit_fn = - [](SymbolTableHandler* symbol_table_handler, - BufferTracker* tracker) { + [](SymbolTableHandler *symbol_table_handler, + BufferTracker *tracker) { return AutoExpandCodeActionToTextEdits( symbol_table_handler, tracker, {.start = {.line = 0}, .end = {.line = 16}}, "Expand all AUTOs in file"); }}, - TestRun{.edit_fn = [](SymbolTableHandler* symbol_table_handler, - BufferTracker* tracker) { + TestRun{.edit_fn = [](SymbolTableHandler *symbol_table_handler, + BufferTracker *tracker) { return AutoExpandCodeActionToTextEdits( symbol_table_handler, tracker, {.start = {.line = 7}, .end = {.line = 8}}, @@ -3377,8 +3377,8 @@ module bar ( /*AUTOARG*/); endmodule )", {TestRun{.edit_fn = - [](SymbolTableHandler* symbol_table_handler, - BufferTracker* tracker) { + [](SymbolTableHandler *symbol_table_handler, + BufferTracker *tracker) { return AutoExpandCodeActionToTextEdits( symbol_table_handler, tracker, {.start = {.line = 0}, .end = {.line = 10}}, @@ -3487,8 +3487,8 @@ module bar ( /*AUTOARG*/ /*AUTOREG*/ endmodule )", - TestRun{.edit_fn = [](SymbolTableHandler* symbol_table_handler, - BufferTracker* tracker) { + TestRun{.edit_fn = [](SymbolTableHandler *symbol_table_handler, + BufferTracker *tracker) { return AutoExpandCodeActionToTextEdits( symbol_table_handler, tracker, {.start = {.line = 1}, .end = {.line = 1}}, @@ -3573,8 +3573,8 @@ module qux ( endmodule )", {TestRun{.edit_fn = - [](SymbolTableHandler* symbol_table_handler, - BufferTracker* tracker) { + [](SymbolTableHandler *symbol_table_handler, + BufferTracker *tracker) { return AutoExpandCodeActionToTextEdits( symbol_table_handler, tracker, {.start = {.line = 1}, .end = {.line = 3}}, diff --git a/verilog/tools/obfuscator/verilog_obfuscate.cc b/verilog/tools/obfuscator/verilog_obfuscate.cc index 5f18c6288..72e1691c7 100644 --- a/verilog/tools/obfuscator/verilog_obfuscate.cc +++ b/verilog/tools/obfuscator/verilog_obfuscate.cc @@ -68,7 +68,7 @@ static constexpr absl::string_view kBuiltinFunctions[] = { "pow", "sin", "sinh", "sqrt", "tan", "tanh", }; -int main(int argc, char** argv) { +int main(int argc, char **argv) { const auto usage = absl::StrCat("usage: ", argv[0], " [options] < original > output\n" R"( @@ -85,8 +85,8 @@ Output is written to stdout. const bool decode = absl::GetFlag(FLAGS_decode); subst.set_decode_mode(decode); - const auto& load_map_file = absl::GetFlag(FLAGS_load_map); - const auto& save_map_file = absl::GetFlag(FLAGS_save_map); + const auto &load_map_file = absl::GetFlag(FLAGS_load_map); + const auto &save_map_file = absl::GetFlag(FLAGS_save_map); if (!load_map_file.empty()) { absl::StatusOr load_map_content_or = verible::file::GetContentAsString(load_map_file); @@ -124,7 +124,7 @@ Output is written to stdout. std::cerr << status.message(); return 1; } - for (auto const& preserved_name : preserved) { + for (auto const &preserved_name : preserved) { subst.encode(preserved_name, preserved_name); } } diff --git a/verilog/tools/project/project_tool.cc b/verilog/tools/project/project_tool.cc index f49da388d..0fd72955b 100644 --- a/verilog/tools/project/project_tool.cc +++ b/verilog/tools/project/project_tool.cc @@ -63,7 +63,7 @@ struct VerilogProjectConfig { // See --file_list_root above. std::string file_list_root; - absl::Status LoadFromCommandline(const SubcommandArgsRange& args) { + absl::Status LoadFromCommandline(const SubcommandArgsRange &args) { const std::vector cmdline{args.begin(), args.end()}; auto status = AppendFileListFromCommandline(cmdline, &file_list); if (!status.ok()) return status; @@ -92,7 +92,7 @@ struct VerilogProjectConfig { // TODO: refactor this for re-use with tools/kythe/verilog_kythe_extractor.cc. struct ProjectSymbols { // From global absl flags. - const VerilogProjectConfig& config; + const VerilogProjectConfig &config; // This object must outlive 'symbol_table' (maintained by struct-ordering). std::unique_ptr project; @@ -100,14 +100,14 @@ struct ProjectSymbols { // Unified symbol table. std::unique_ptr symbol_table; - explicit ProjectSymbols(const VerilogProjectConfig& config) + explicit ProjectSymbols(const VerilogProjectConfig &config) : config(config) {} // no copy, no move, no assign - ProjectSymbols(const ProjectSymbols&) = delete; - ProjectSymbols(ProjectSymbols&&) = delete; - ProjectSymbols& operator=(const ProjectSymbols&) = delete; - ProjectSymbols& operator=(ProjectSymbols&&) = delete; + ProjectSymbols(const ProjectSymbols &) = delete; + ProjectSymbols(ProjectSymbols &&) = delete; + ProjectSymbols &operator=(const ProjectSymbols &) = delete; + ProjectSymbols &operator=(ProjectSymbols &&) = delete; // Initializes a project, and opens listed files. absl::Status Load() { @@ -116,7 +116,7 @@ struct ProjectSymbols { // Error-out early if any files failed to open. project = std::make_unique( config.file_list_root, config.file_list.preprocessing.include_dirs); - for (const auto& file : config.file_list.file_paths) { + for (const auto &file : config.file_list.file_paths) { const auto open_status = project->OpenTranslationUnit(file); if (!open_status.ok()) return open_status.status(); } @@ -127,35 +127,35 @@ struct ProjectSymbols { } // Builds symbol table. - void Build(std::vector* build_statuses) { + void Build(std::vector *build_statuses) { VLOG(1) << __FUNCTION__; // For now, ingest files in the order they were listed. // Without conflicting definitions in files, this order should not matter. - for (const auto& file : config.file_list.file_paths) { + for (const auto &file : config.file_list.file_paths) { symbol_table->BuildSingleTranslationUnit(file, build_statuses); } } // Resolves symbols. - void Resolve(std::vector* resolve_statuses) const { + void Resolve(std::vector *resolve_statuses) const { symbol_table->Resolve(resolve_statuses); } }; static std::string JoinStatusMessages( - const std::vector& statuses) { + const std::vector &statuses) { return absl::StrCat( "[combined statuses]:\n", absl::StrJoin( - statuses, "\n", [](std::string* out, const absl::Status& status) { + statuses, "\n", [](std::string *out, const absl::Status &status) { out->append(status.message().begin(), status.message().end()); })); } -static absl::Status BuildAndShowSymbolTable(const SubcommandArgsRange& args, - std::istream& ins, - std::ostream& outs, - std::ostream& errs) { +static absl::Status BuildAndShowSymbolTable(const SubcommandArgsRange &args, + std::istream &ins, + std::ostream &outs, + std::ostream &errs) { VLOG(1) << __FUNCTION__; // Load configuration. VerilogProjectConfig config; @@ -182,8 +182,8 @@ static absl::Status BuildAndShowSymbolTable(const SubcommandArgsRange& args, } static absl::Status ResolveAndShowSymbolReferences( - const SubcommandArgsRange& args, std::istream& ins, std::ostream& outs, - std::ostream& errs) { + const SubcommandArgsRange &args, std::istream &ins, std::ostream &outs, + std::ostream &errs) { VLOG(1) << __FUNCTION__; // Load configuration. VerilogProjectConfig config; @@ -212,9 +212,9 @@ static absl::Status ResolveAndShowSymbolReferences( return absl::OkStatus(); } -static absl::Status ShowFileDependencies(const SubcommandArgsRange& args, - std::istream& ins, std::ostream& outs, - std::ostream& errs) { +static absl::Status ShowFileDependencies(const SubcommandArgsRange &args, + std::istream &ins, std::ostream &outs, + std::ostream &errs) { VLOG(1) << __FUNCTION__; // Load configuration. VerilogProjectConfig config; @@ -283,10 +283,10 @@ Project options, including source file list. // TODO: symbol table name-completion demo }; -int main(int argc, char* argv[]) { +int main(int argc, char *argv[]) { // Create a registry of subcommands (locally, rather than as a static global). verible::SubcommandRegistry commands; - for (const auto& entry : kCommands) { + for (const auto &entry : kCommands) { const auto status = commands.RegisterCommand(entry.first, entry.second); if (!status.ok()) { std::cerr << status.message() << std::endl; @@ -310,7 +310,7 @@ int main(int argc, char* argv[]) { // subcommand args start at [2] const SubcommandArgsRange command_args(args.cbegin() + 2, args.cend()); - const auto& sub = commands.GetSubcommandEntry(args[1]); + const auto &sub = commands.GetSubcommandEntry(args[1]); // Run the subcommand. const auto status = sub.main(command_args, std::cin, std::cout, std::cerr); if (!status.ok()) { diff --git a/verilog/tools/syntax/verilog_syntax.cc b/verilog/tools/syntax/verilog_syntax.cc index 1b8cdaeb4..702a25207 100644 --- a/verilog/tools/syntax/verilog_syntax.cc +++ b/verilog/tools/syntax/verilog_syntax.cc @@ -64,7 +64,7 @@ enum class LanguageMode { kVerilogLibraryMap, }; -static const verible::EnumNameMap& LanguageModeStringMap() { +static const verible::EnumNameMap &LanguageModeStringMap() { static const verible::EnumNameMap kLanguageModeStringMap({ {"auto", LanguageMode::kAutoDetect}, {"sv", LanguageMode::kSystemVerilog}, @@ -73,16 +73,16 @@ static const verible::EnumNameMap& LanguageModeStringMap() { return kLanguageModeStringMap; } -static std::ostream& operator<<(std::ostream& stream, LanguageMode mode) { +static std::ostream &operator<<(std::ostream &stream, LanguageMode mode) { return LanguageModeStringMap().Unparse(mode, stream); } -static bool AbslParseFlag(absl::string_view text, LanguageMode* mode, - std::string* error) { +static bool AbslParseFlag(absl::string_view text, LanguageMode *mode, + std::string *error) { return LanguageModeStringMap().Parse(text, mode, error, "--flag value"); } -static std::string AbslUnparseFlag(const LanguageMode& mode) { +static std::string AbslUnparseFlag(const LanguageMode &mode) { std::ostringstream stream; stream << mode; return stream.str(); @@ -121,9 +121,9 @@ using verible::TextStructureView; using verilog::VerilogAnalyzer; static std::unique_ptr ParseWithLanguageMode( - const std::shared_ptr& content, + const std::shared_ptr &content, absl::string_view filename, - const verilog::VerilogPreprocess::Config& preprocess_config) { + const verilog::VerilogPreprocess::Config &preprocess_config) { switch (absl::GetFlag(FLAGS_lang)) { case LanguageMode::kAutoDetect: return VerilogAnalyzer::AnalyzeAutomaticMode(content, filename, @@ -143,8 +143,8 @@ static std::unique_ptr ParseWithLanguageMode( } // Prints all tokens in view that are not matched in root. -static void VerifyParseTree(const TextStructureView& text_structure) { - const ConcreteSyntaxTree& root = text_structure.SyntaxTree(); +static void VerifyParseTree(const TextStructureView &text_structure) { + const ConcreteSyntaxTree &root = text_structure.SyntaxTree(); if (root == nullptr) return; // TODO(fangism): this seems like a good method for TextStructureView. ParserVerifier verifier(*root, text_structure.GetTokenStreamView()); @@ -154,13 +154,13 @@ static void VerifyParseTree(const TextStructureView& text_structure) { std::cout << std::endl << "All tokens matched." << std::endl; } else { std::cout << std::endl << "Unmatched Tokens:" << std::endl; - for (const auto& token : unmatched) { + for (const auto &token : unmatched) { std::cout << token << std::endl; } } } -static bool ShouldIncludeTokenText(const verible::TokenInfo& token) { +static bool ShouldIncludeTokenText(const verible::TokenInfo &token) { const verilog_tokentype tokentype = static_cast(token.token_enum()); absl::string_view type_str = verilog::TokenTypeToString(tokentype); @@ -173,10 +173,10 @@ static bool ShouldIncludeTokenText(const verible::TokenInfo& token) { } static int AnalyzeOneFile( - const std::shared_ptr& content, + const std::shared_ptr &content, absl::string_view filename, - const verilog::VerilogPreprocess::Config& preprocess_config, - json* json_out) { + const verilog::VerilogPreprocess::Config &preprocess_config, + json *json_out) { int exit_status = 0; const auto analyzer = ParseWithLanguageMode(content, filename, preprocess_config); @@ -193,7 +193,7 @@ static int AnalyzeOneFile( const std::vector syntax_error_messages( analyzer->LinterTokenErrorMessages( absl::GetFlag(FLAGS_show_diagnostic_context))); - for (const auto& message : syntax_error_messages) { + for (const auto &message : syntax_error_messages) { std::cout << message << std::endl; ++error_count; if (error_limit != 0 && error_count >= error_limit) break; @@ -206,13 +206,13 @@ static int AnalyzeOneFile( } const bool parse_ok = parse_status.ok(); - std::function token_translator; + std::function token_translator; if (!absl::GetFlag(FLAGS_export_json)) { - token_translator = [](std::ostream& stream, int e) { + token_translator = [](std::ostream &stream, int e) { stream << verilog::verilog_symbol_name(e); }; } else { - token_translator = [](std::ostream& stream, int e) { + token_translator = [](std::ostream &stream, int e) { stream << verilog::TokenTypeToString(static_cast(e)); }; } @@ -222,13 +222,13 @@ static int AnalyzeOneFile( if (absl::GetFlag(FLAGS_printtokens)) { if (!absl::GetFlag(FLAGS_export_json)) { std::cout << std::endl << "Lexed and filtered tokens:" << std::endl; - for (const auto& t : analyzer->Data().GetTokenStreamView()) { + for (const auto &t : analyzer->Data().GetTokenStreamView()) { t->ToStream(std::cout, context) << std::endl; } } else { - json& tokens = (*json_out)["tokens"] = json::array(); - const auto& token_stream = analyzer->Data().GetTokenStreamView(); - for (const auto& t : token_stream) { + json &tokens = (*json_out)["tokens"] = json::array(); + const auto &token_stream = analyzer->Data().GetTokenStreamView(); + for (const auto &t : token_stream) { tokens.push_back( verible::ToJson(*t, context, ShouldIncludeTokenText(*t))); } @@ -239,21 +239,21 @@ static int AnalyzeOneFile( if (absl::GetFlag(FLAGS_printrawtokens)) { if (!absl::GetFlag(FLAGS_export_json)) { std::cout << std::endl << "All lexed tokens:" << std::endl; - for (const auto& t : analyzer->Data().TokenStream()) { + for (const auto &t : analyzer->Data().TokenStream()) { t.ToStream(std::cout, context) << std::endl; } } else { - json& tokens = (*json_out)["rawtokens"] = json::array(); - const auto& token_stream = analyzer->Data().TokenStream(); - for (const auto& t : token_stream) { + json &tokens = (*json_out)["rawtokens"] = json::array(); + const auto &token_stream = analyzer->Data().TokenStream(); + for (const auto &t : token_stream) { tokens.push_back( verible::ToJson(t, context, ShouldIncludeTokenText(t))); } } } - const auto& text_structure = analyzer->Data(); - const auto& syntax_tree = text_structure.SyntaxTree(); + const auto &text_structure = analyzer->Data(); + const auto &syntax_tree = text_structure.SyntaxTree(); // check for printtree flag, and print tree if on if (absl::GetFlag(FLAGS_printtree) && syntax_tree != nullptr) { @@ -284,7 +284,7 @@ static int AnalyzeOneFile( return exit_status; } -int main(int argc, char** argv) { +int main(int argc, char **argv) { const auto usage = absl::StrCat("usage: ", argv[0], " [options] [...]"); const auto args = verible::InitCommandLine(usage, &argc, &argv); diff --git a/verilog/transform/obfuscate.cc b/verilog/transform/obfuscate.cc index 3b6918a59..0071d7e1c 100644 --- a/verilog/transform/obfuscate.cc +++ b/verilog/transform/obfuscate.cc @@ -50,12 +50,12 @@ std::string RandomEqualLengthSymbolIdentifier(absl::string_view in) { // or use a shuffle/permutation to guarantee collision-free reversibility. static void ObfuscateVerilogCodeInternal(absl::string_view content, - std::ostream* output, - IdentifierObfuscator* subst) { + std::ostream *output, + IdentifierObfuscator *subst) { VLOG(1) << __FUNCTION__; verilog::VerilogLexer lexer(content); for (;;) { - const verible::TokenInfo& token(lexer.DoNextToken()); + const verible::TokenInfo &token(lexer.DoNextToken()); if (token.isEOF()) break; switch (token.token_enum()) { case verilog_tokentype::SymbolIdentifier: @@ -109,7 +109,7 @@ static absl::Status ReversibilityError(absl::string_view original, // Internal consistency check that decoding restores original text. static absl::Status VerifyDecoding(absl::string_view original, absl::string_view encoded, - const verible::Obfuscator& subst) { + const verible::Obfuscator &subst) { VLOG(1) << __FUNCTION__; // Skip if original transformation was already decoding. if (subst.is_decoding()) return absl::OkStatus(); @@ -156,8 +156,8 @@ static absl::Status VerifyEquivalence(absl::string_view original, } absl::Status ObfuscateVerilogCode(absl::string_view content, - std::ostream* output, - IdentifierObfuscator* subst) { + std::ostream *output, + IdentifierObfuscator *subst) { VLOG(1) << __FUNCTION__; std::ostringstream buffer; ObfuscateVerilogCodeInternal(content, &buffer, subst); diff --git a/verilog/transform/obfuscate.h b/verilog/transform/obfuscate.h index 3a3fcc987..7b350e0ea 100644 --- a/verilog/transform/obfuscate.h +++ b/verilog/transform/obfuscate.h @@ -34,8 +34,8 @@ std::string RandomEqualLengthSymbolIdentifier(absl::string_view in); // arguments and macro definition bodies. // Returned status signals success or possible an internal error. absl::Status ObfuscateVerilogCode(absl::string_view content, - std::ostream* output, - verible::IdentifierObfuscator* subst); + std::ostream *output, + verible::IdentifierObfuscator *subst); } // namespace verilog diff --git a/verilog/transform/obfuscate_test.cc b/verilog/transform/obfuscate_test.cc index 4bc051d8d..a5e954ccf 100644 --- a/verilog/transform/obfuscate_test.cc +++ b/verilog/transform/obfuscate_test.cc @@ -38,7 +38,7 @@ TEST(ObfuscateVerilogCodeTest, PreloadedSubstitutions) { {"bbb", "BBB"}, {"ccc", "CCC"}, }; - for (const auto& sub : subs) { + for (const auto &sub : subs) { ASSERT_TRUE(ob.encode(sub.first, sub.second)); } const std::pair kTestCases[] = { @@ -95,7 +95,7 @@ TEST(ObfuscateVerilogCodeTest, PreloadedSubstitutions) { " // comment2\n", }, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { std::ostringstream output; const auto status = ObfuscateVerilogCode(test.first, &output, &ob); EXPECT_TRUE(status.ok()) << "Unexpected error: " << status.message(); @@ -110,7 +110,7 @@ TEST(ObfuscateVerilogCodeTest, InputLexicalError) { "`define FOO 911badid\n", "`FOO(`)\n", }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { IdentifierObfuscator ob(RandomEqualLengthSymbolIdentifier); std::ostringstream output; const auto status = ObfuscateVerilogCode(test, &output, &ob); diff --git a/verilog/transform/strip_comments.cc b/verilog/transform/strip_comments.cc index 7309d42c7..0757ea0b8 100644 --- a/verilog/transform/strip_comments.cc +++ b/verilog/transform/strip_comments.cc @@ -36,29 +36,29 @@ using verible::TokenInfo; // Replace non-newline characters with a single char, like . // Tabs are considered non-newline characters. -static void ReplaceNonNewlines(absl::string_view text, std::ostream* output, +static void ReplaceNonNewlines(absl::string_view text, std::ostream *output, char replacement) { if (text.empty()) return; const std::vector lines( absl::StrSplit(text, absl::ByChar('\n'))); // no newline before first element *output << Spacer(lines.front().size(), replacement); - for (const auto& line : verible::make_range(lines.begin() + 1, lines.end())) { + for (const auto &line : verible::make_range(lines.begin() + 1, lines.end())) { *output << '\n' << Spacer(line.size(), replacement); } } -void StripVerilogComments(absl::string_view content, std::ostream* output, +void StripVerilogComments(absl::string_view content, std::ostream *output, char replacement) { VLOG(1) << __FUNCTION__; verilog::VerilogLexer lexer(content); - const TokenInfo::Context context(content, [](std::ostream& stream, int e) { + const TokenInfo::Context context(content, [](std::ostream &stream, int e) { stream << verilog_symbol_name(e); }); for (;;) { - const verible::TokenInfo& token(lexer.DoNextToken()); + const verible::TokenInfo &token(lexer.DoNextToken()); if (token.isEOF()) break; VLOG(2) << "token: " << verible::TokenWithContext{token, context}; diff --git a/verilog/transform/strip_comments.h b/verilog/transform/strip_comments.h index a4150e0a3..d6513049b 100644 --- a/verilog/transform/strip_comments.h +++ b/verilog/transform/strip_comments.h @@ -33,7 +33,7 @@ namespace verilog { // This preserves byte offsets and line numbers of all unchanged text. // This option is good for visibility. // All lexical errors are ignored. -void StripVerilogComments(absl::string_view content, std::ostream* output, +void StripVerilogComments(absl::string_view content, std::ostream *output, char replacement = '\0'); } // namespace verilog diff --git a/verilog/transform/strip_comments_test.cc b/verilog/transform/strip_comments_test.cc index 818a4af9b..1913197d4 100644 --- a/verilog/transform/strip_comments_test.cc +++ b/verilog/transform/strip_comments_test.cc @@ -307,7 +307,7 @@ TEST(StripVerilogCommentsTest, Various) { "`define DEF `MACRO(/*...*/)\n", }, }; - for (const auto& test : kTestCases) { + for (const auto &test : kTestCases) { { std::ostringstream stream; StripVerilogComments(test.input, &stream, '\0');