From 85b1d37b140571d85fff5aa77655ab1fa223fb36 Mon Sep 17 00:00:00 2001 From: Dmitry Vyukov Date: Sat, 4 Jul 2020 12:36:42 +0200 Subject: tools/syz-linter: add check for comment format Update #1876 --- tools/syz-linter/linter.go | 17 +++++++++++++++++ tools/syz-linter/testdata/src/lintertest/lintertest.go | 11 +++++++++++ 2 files changed, 28 insertions(+) diff --git a/tools/syz-linter/linter.go b/tools/syz-linter/linter.go index c4b6837b2..6bc28b5cf 100644 --- a/tools/syz-linter/linter.go +++ b/tools/syz-linter/linter.go @@ -7,11 +7,13 @@ // See the following tutorial on adding custom golangci-lint linters: // https://golangci-lint.run/contributing/new-linters/ // See comments below and testdata/src/lintertest/lintertest.go for the actual checks we do. +// Note: if you change linter logic, you may need to run "rm -rf ~/.cache/golangci-lint". package main import ( "go/ast" "go/token" + "regexp" "strings" "golang.org/x/tools/go/analysis" @@ -39,6 +41,7 @@ func run(pass *analysis.Pass) (interface{}, error) { switch n := n.(type) { case *ast.Comment: checkMulitlineComments(pass, n) + checkCommentSpace(pass, n) case *ast.BinaryExpr: checkStringLenCompare(pass, n) } @@ -60,6 +63,20 @@ func checkMulitlineComments(pass *analysis.Pass, n *ast.Comment) { }) } +// checkCommentSpace warns about "//nospace", "// tabs and spaces" and similar. +func checkCommentSpace(pass *analysis.Pass, n *ast.Comment) { + if !strings.HasPrefix(n.Text, "//") || + allowedComments.MatchString(n.Text) { + return + } + pass.Report(analysis.Diagnostic{ + Pos: n.Pos(), + Message: "Use either //comment or //comment format for comments", + }) +} + +var allowedComments = regexp.MustCompile(`^//($| +[^ ]| +[^ ])`) + // checkStringLenCompare checks for string len comparisons with 0. // E.g.: if len(str) == 0 {} should be if str == "" {}. func checkStringLenCompare(pass *analysis.Pass, n *ast.BinaryExpr) { diff --git a/tools/syz-linter/testdata/src/lintertest/lintertest.go b/tools/syz-linter/testdata/src/lintertest/lintertest.go index b507bc1ee..2c70a97e8 100644 --- a/tools/syz-linter/testdata/src/lintertest/lintertest.go +++ b/tools/syz-linter/testdata/src/lintertest/lintertest.go @@ -17,3 +17,14 @@ func stringComparison() { } func returnString() string { return "foo" } + +// +// One space. +// Two spaces. +// One tab. +// Two tabs. +//No space. // want "Use either //comment or //comment format for comments" +// Tab and spaces. // want "Use either //comment or //comment format for comments" +// Space and tab. // want "Use either //comment or //comment format for comments" +func checkCommentSpace() { +} -- cgit mrf-deployment