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.
5 // TODO(gri): This file and the file src/go/format/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.
21 // parse parses src, which was read from the named file,
22 // as a Go source file, declaration, or statement list.
23 func parse(fset *token.FileSet, filename string, src []byte, fragmentOk bool) (
25 sourceAdj func(src []byte, indent int) []byte,
29 // Try as whole source file.
30 file, err = parser.ParseFile(fset, filename, src, parserMode)
31 // If there's no error, return. If the error is that the source file didn't begin with a
32 // package line and source fragments are ok, fall through to
33 // try as a source fragment. Stop and return on any other error.
34 if err == nil || !fragmentOk || !strings.Contains(err.Error(), "expected 'package'") {
38 // If this is a declaration list, make it a source file
39 // by inserting a package clause.
40 // Insert using a ;, not a newline, so that the line numbers
41 // in psrc match the ones in src.
42 psrc := append([]byte("package p;"), src...)
43 file, err = parser.ParseFile(fset, filename, psrc, parserMode)
45 sourceAdj = func(src []byte, indent int) []byte {
46 // Remove the package clause.
47 // Gofmt has turned the ; into a \n.
48 src = src[indent+len("package p\n"):]
49 return bytes.TrimSpace(src)
53 // If the error is that the source file didn't begin with a
54 // declaration, fall through to try as a statement list.
55 // Stop and return on any other error.
56 if !strings.Contains(err.Error(), "expected declaration") {
60 // If this is a statement list, make it a source file
61 // by inserting a package clause and turning the list
62 // into a function body. This handles expressions too.
63 // Insert using a ;, not a newline, so that the line numbers
64 // in fsrc match the ones in src. Add an extra '\n' before the '}'
65 // to make sure comments are flushed before the '}'.
66 fsrc := append(append([]byte("package p; func _() {"), src...), '\n', '\n', '}')
67 file, err = parser.ParseFile(fset, filename, fsrc, parserMode)
69 sourceAdj = func(src []byte, indent int) []byte {
70 // Cap adjusted indent to zero.
74 // Remove the wrapping.
75 // Gofmt has turned the ; into a \n\n.
76 // There will be two non-blank lines with indent, hence 2*indent.
77 src = src[2*indent+len("package p\n\nfunc _() {"):]
78 // Remove only the "}\n" suffix: remaining whitespaces will be trimmed anyway
79 src = src[:len(src)-len("}\n")]
80 return bytes.TrimSpace(src)
82 // Gofmt has also indented the function body one level.
83 // Adjust that with indentAdj.
87 // Succeeded, or out of options.
91 // format formats the given package file originally obtained from src
92 // and adjusts the result based on the original source via sourceAdj
97 sourceAdj func(src []byte, indent int) []byte,
102 if sourceAdj == nil {
103 // Complete source file.
105 err := cfg.Fprint(&buf, fset, file)
109 return buf.Bytes(), nil
112 // Partial source file.
113 // Determine and prepend leading space.
115 for j < len(src) && isSpace(src[j]) {
117 i = j + 1 // byte offset of last line in leading space
122 res = append(res, src[:i]...)
124 // Determine and prepend indentation of first code line.
125 // Spaces are ignored unless there are no tabs,
126 // in which case spaces count as one tab.
129 for _, b := range src[i:j] {
137 if indent == 0 && hasSpace {
140 for i := 0; i < indent; i++ {
141 res = append(res, '\t')
144 // Format the source.
145 // Write it without any leading and trailing space.
146 cfg.Indent = indent + indentAdj
148 err := cfg.Fprint(&buf, fset, file)
152 out := sourceAdj(buf.Bytes(), cfg.Indent)
154 // If the adjusted output is empty, the source
155 // was empty but (possibly) for white space.
156 // The result is the incoming source.
161 // Otherwise, append output to leading space.
162 res = append(res, out...)
164 // Determine and append trailing space.
166 for i > 0 && isSpace(src[i-1]) {
169 return append(res, src[i:]...), nil
172 // isSpace reports whether the byte is a space character.
173 // isSpace defines a space as being among the following bytes: ' ', '\t', '\n' and '\r'.
174 func isSpace(b byte) bool {
175 return b == ' ' || b == '\t' || b == '\n' || b == '\r'