internal.go 5.0 KB

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