]> Cypherpunks repositories - gostls13.git/commitdiff
gofmt/main: Added removal of empty declaration groups.
authorSimon Whitehead <chemnova@gmail.com>
Tue, 1 Jul 2014 16:32:03 +0000 (09:32 -0700)
committerRobert Griesemer <gri@golang.org>
Tue, 1 Jul 2014 16:32:03 +0000 (09:32 -0700)
Fixes #7631.

LGTM=gri
R=golang-codereviews, bradfitz, gri
CC=golang-codereviews
https://golang.org/cl/101410046

src/cmd/gofmt/gofmt_test.go
src/cmd/gofmt/simplify.go
src/cmd/gofmt/testdata/emptydecl.golden [new file with mode: 0644]
src/cmd/gofmt/testdata/emptydecl.input [new file with mode: 0644]

index b9335b8f3db8f61636fd905026b7fad0da5aedaa..b767a6bf553f56338e2cda62a827a37fb9c2d549 100644 (file)
@@ -87,8 +87,9 @@ var tests = []struct {
        {"testdata/stdin*.input", "-stdin"},
        {"testdata/comments.input", ""},
        {"testdata/import.input", ""},
-       {"testdata/crlf.input", ""},       // test case for issue 3961; see also TestCRLF
-       {"testdata/typeswitch.input", ""}, // test case for issue 4470
+       {"testdata/crlf.input", ""},        // test case for issue 3961; see also TestCRLF
+       {"testdata/typeswitch.input", ""},  // test case for issue 4470
+       {"testdata/emptydecl.input", "-s"}, // test case for issue 7631
 }
 
 func TestRewrite(t *testing.T) {
index 45d000d675e8cdbccf155d4351765b20698cc1ff..b1556be74e43072a034a764c0366c678da017054 100644 (file)
@@ -117,5 +117,34 @@ func simplify(f *ast.File) {
                }
        }
 
+       // remove empty declarations such as "const ()", etc
+       removeEmptyDeclGroups(f)
+
        ast.Walk(&s, f)
 }
+
+func removeEmptyDeclGroups(f *ast.File) {
+       i := 0
+       for _, d := range f.Decls {
+               if g, ok := d.(*ast.GenDecl); !ok || !isEmpty(f, g) {
+                       f.Decls[i] = d
+                       i++
+               }
+       }
+       f.Decls = f.Decls[:i]
+}
+
+func isEmpty(f *ast.File, g *ast.GenDecl) bool {
+       if g.Doc != nil || g.Specs != nil {
+               return false
+       }
+
+       for _, c := range f.Comments {
+               // if there is a comment in the declaration, it is not considered empty
+               if g.Pos() <= c.Pos() && c.End() <= g.End() {
+                       return false
+               }
+       }
+
+       return true
+}
diff --git a/src/cmd/gofmt/testdata/emptydecl.golden b/src/cmd/gofmt/testdata/emptydecl.golden
new file mode 100644 (file)
index 0000000..9fe62c9
--- /dev/null
@@ -0,0 +1,10 @@
+package main
+
+// Keep this declaration
+var ()
+
+const (
+// Keep this declaration
+)
+
+func main() {}
diff --git a/src/cmd/gofmt/testdata/emptydecl.input b/src/cmd/gofmt/testdata/emptydecl.input
new file mode 100644 (file)
index 0000000..d1cab00
--- /dev/null
@@ -0,0 +1,12 @@
+package main
+
+// Keep this declaration
+var ()
+
+const (
+// Keep this declaration
+)
+
+type ()
+
+func main() {}
\ No newline at end of file