From e9ba607bf531c5e5b223a54c164714b6b00411a6 Mon Sep 17 00:00:00 2001 From: Robert Griesemer Date: Tue, 11 Oct 2011 21:49:53 -0700 Subject: [PATCH] gofmt: fix a couple of crashes, disallow rewrites for incomplete programs The current implementation of formatting for incomplete programs cannot tolerate program rewrites; ignore -rewrite in that case with a warning message (temporary solution). Fix a couple of crashes that were introduced recently. Fixes #2348. R=rsc CC=golang-dev https://golang.org/cl/5233054 --- src/cmd/gofmt/gofmt.go | 19 ++++++++++++++----- src/cmd/gofmt/rewrite.go | 3 ++- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/cmd/gofmt/gofmt.go b/src/cmd/gofmt/gofmt.go index 1c0efb6db7f..6ce99113edd 100644 --- a/src/cmd/gofmt/gofmt.go +++ b/src/cmd/gofmt/gofmt.go @@ -107,7 +107,11 @@ func processFile(filename string, in io.Reader, out io.Writer, stdin bool) os.Er } if rewrite != nil { - file = rewrite(file) + if adjust == nil { + file = rewrite(file) + } else { + fmt.Fprintf(os.Stderr, "warning: rewrite ignored for incomplete programs\n") + } } if *simplifyAST { @@ -119,7 +123,10 @@ func processFile(filename string, in io.Reader, out io.Writer, stdin bool) os.Er if err != nil { return err } - res := adjust(src, buf.Bytes()) + res := buf.Bytes() + if adjust != nil { + res = adjust(src, res) + } if !bytes.Equal(src, res) { // formatting has changed @@ -252,8 +259,7 @@ func parse(filename string, src []byte, stdin bool) (*ast.File, func(orig, src [ // Try as whole source file. file, err := parser.ParseFile(fset, filename, src, parserMode) if err == nil { - adjust := func(orig, src []byte) []byte { return src } - return file, adjust, nil + return file, nil, nil } // If the error is that the source file didn't begin with a // package line and this is standard input, fall through to @@ -318,7 +324,10 @@ func cutSpace(b []byte) (before, middle, after []byte) { for j > 0 && (b[j-1] == ' ' || b[j-1] == '\t' || b[j-1] == '\n') { j-- } - return b[:i], b[i:j], b[j:] + if i <= j { + return b[:i], b[i:j], b[j:] + } + return nil, nil, b[j:] } // matchSpace reformats src to use the same space context as orig. diff --git a/src/cmd/gofmt/rewrite.go b/src/cmd/gofmt/rewrite.go index 3d74dea0f11..8f65ef1ff1e 100644 --- a/src/cmd/gofmt/rewrite.go +++ b/src/cmd/gofmt/rewrite.go @@ -85,7 +85,8 @@ func setValue(x, y reflect.Value) { } defer func() { if x := recover(); x != nil { - if s, ok := x.(string); ok && strings.HasPrefix(s, "type mismatch") { + if s, ok := x.(string); ok && + (strings.Contains(s, "type mismatch") || strings.Contains(s, "not assignable")) { // x cannot be set to y - ignore this rewrite return }