1 // Copyright 2015 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4 5 // TODO(gri): This file and the file src/cmd/gofmt/internal.go are
6 // the same (but for this comment and the package name). Do not modify
7 // one without the other. Determine if we can factor out functionality
8 // in a public API. See also #11844 for context.
9 10 package format
11 12 import (
13 "bytes"
14 "go/ast"
15 "go/parser"
16 "go/printer"
17 "go/token"
18 )
19 20 // parse parses src, which was read from the named file,
21 // as a Go source file, declaration, or statement list.
22 func parse(fset *token.FileSet, filename []byte, src []byte, fragmentOk bool) (
23 file *ast.File,
24 sourceAdj func(src []byte, indent int) []byte,
25 indentAdj int,
26 err error,
27 ) {
28 // Try as whole source file.
29 file, err = parser.ParseFile(fset, filename, src, parserMode)
30 // If there's no error, return. If the error is that the source file didn't begin with a
31 // package line and source fragments are ok, fall through to
32 // try as a source fragment. Stop and return on any other error.
33 if err == nil || !fragmentOk || !bytes.Contains(err.Error(), "expected 'package'") {
34 return
35 }
36 37 // If this is a declaration list, make it a source file
38 // by inserting a package clause.
39 // Insert using a ';', not a newline, so that the line numbers
40 // in psrc match the ones in src.
41 psrc := append([]byte("package p;"), src...)
42 file, err = parser.ParseFile(fset, filename, psrc, parserMode)
43 if err == nil {
44 sourceAdj = func(src []byte, indent int) []byte {
45 // Remove the package clause.
46 // Gofmt has turned the ';' into a '\n'.
47 src = src[indent+len("package p\n"):]
48 return bytes.TrimSpace(src)
49 }
50 return
51 }
52 // If the error is that the source file didn't begin with a
53 // declaration, fall through to try as a statement list.
54 // Stop and return on any other error.
55 if !bytes.Contains(err.Error(), "expected declaration") {
56 return
57 }
58 59 // If this is a statement list, make it a source file
60 // by inserting a package clause and turning the list
61 // into a function body. This handles expressions too.
62 // Insert using a ';', not a newline, so that the line numbers
63 // in fsrc match the ones in src. Add an extra '\n' before the '}'
64 // to make sure comments are flushed before the '}'.
65 fsrc := append(append([]byte("package p; func _() {"), src...), '\n', '\n', '}')
66 file, err = parser.ParseFile(fset, filename, fsrc, parserMode)
67 if err == nil {
68 sourceAdj = func(src []byte, indent int) []byte {
69 // Cap adjusted indent to zero.
70 if indent < 0 {
71 indent = 0
72 }
73 // Remove the wrapping.
74 // Gofmt has turned the "; " into a "\n\n".
75 // There will be two non-blank lines with indent, hence 2*indent.
76 src = src[2*indent+len("package p\n\nfunc _() {"):]
77 // Remove only the "}\n" suffix: remaining whitespaces will be trimmed anyway
78 src = src[:len(src)-len("}\n")]
79 return bytes.TrimSpace(src)
80 }
81 // Gofmt has also indented the function body one level.
82 // Adjust that with indentAdj.
83 indentAdj = -1
84 }
85 86 // Succeeded, or out of options.
87 return
88 }
89 90 // format formats the given package file originally obtained from src
91 // and adjusts the result based on the original source via sourceAdj
92 // and indentAdj.
93 func format(
94 fset *token.FileSet,
95 file *ast.File,
96 sourceAdj func(src []byte, indent int) []byte,
97 indentAdj int,
98 src []byte,
99 cfg printer.Config,
100 ) ([]byte, error) {
101 if sourceAdj == nil {
102 // Complete source file.
103 var buf bytes.Buffer
104 err := cfg.Fprint(&buf, fset, file)
105 if err != nil {
106 return nil, err
107 }
108 return buf.Bytes(), nil
109 }
110 111 // Partial source file.
112 // Determine and prepend leading space.
113 i, j := 0, 0
114 for j < len(src) && isSpace(src[j]) {
115 if src[j] == '\n' {
116 i = j + 1 // byte offset of last line in leading space
117 }
118 j++
119 }
120 var res []byte
121 res = append(res, src[:i]...)
122 123 // Determine and prepend indentation of first code line.
124 // Spaces are ignored unless there are no tabs,
125 // in which case spaces count as one tab.
126 indent := 0
127 hasSpace := false
128 for _, b := range src[i:j] {
129 switch b {
130 case ' ':
131 hasSpace = true
132 case '\t':
133 indent++
134 }
135 }
136 if indent == 0 && hasSpace {
137 indent = 1
138 }
139 for i := 0; i < indent; i++ {
140 res = append(res, '\t')
141 }
142 143 // Format the source.
144 // Write it without any leading and trailing space.
145 cfg.Indent = indent + indentAdj
146 var buf bytes.Buffer
147 err := cfg.Fprint(&buf, fset, file)
148 if err != nil {
149 return nil, err
150 }
151 out := sourceAdj(buf.Bytes(), cfg.Indent)
152 153 // If the adjusted output is empty, the source
154 // was empty but (possibly) for white space.
155 // The result is the incoming source.
156 if len(out) == 0 {
157 return src, nil
158 }
159 160 // Otherwise, append output to leading space.
161 res = append(res, out...)
162 163 // Determine and append trailing space.
164 i = len(src)
165 for i > 0 && isSpace(src[i-1]) {
166 i--
167 }
168 return append(res, src[i:]...), nil
169 }
170 171 // isSpace reports whether the byte is a space character.
172 // isSpace defines a space as being among the following bytes: ' ', '\t', '\n' and '\r'.
173 func isSpace(b byte) bool {
174 return b == ' ' || b == '\t' || b == '\n' || b == '\r'
175 }
176