github.com/goplus/gox@v1.14.13-0.20240308130321-6ff7f61cfae8/internal/go/format/format.go (about)

     1  // Copyright 2012 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  // Package format implements standard formatting of Go source.
     6  //
     7  // Note that formatting of Go source code changes over time, so tools relying on
     8  // consistent formatting should execute a specific version of the gofmt binary
     9  // instead of using this package. That way, the formatting will be stable, and
    10  // the tools won't need to be recompiled each time gofmt changes.
    11  //
    12  // For example, pre-submit checks that use this package directly would behave
    13  // differently depending on what Go version each developer uses, causing the
    14  // check to be inherently fragile.
    15  package format
    16  
    17  import (
    18  	"bytes"
    19  	"fmt"
    20  	"go/ast"
    21  	"go/parser"
    22  	"go/token"
    23  	"io"
    24  
    25  	"github.com/goplus/gox/internal/go/printer"
    26  )
    27  
    28  // Keep these in sync with cmd/gofmt/gofmt.go.
    29  const (
    30  	tabWidth    = 8
    31  	printerMode = printer.UseSpaces | printer.TabIndent | printerNormalizeNumbers
    32  
    33  	// printerNormalizeNumbers means to canonicalize number literal prefixes
    34  	// and exponents while printing. See https://golang.org/doc/go1.13#gofmt.
    35  	//
    36  	// This value is defined in go/printer specifically for go/format and cmd/gofmt.
    37  	printerNormalizeNumbers = 1 << 30
    38  )
    39  
    40  var config = printer.Config{Mode: printerMode, Tabwidth: tabWidth}
    41  
    42  const parserMode = parser.ParseComments
    43  
    44  // Node formats node in canonical gofmt style and writes the result to dst.
    45  //
    46  // The node type must be *ast.File, *printer.CommentedNode, []ast.Decl,
    47  // []ast.Stmt, or assignment-compatible to ast.Expr, ast.Decl, ast.Spec,
    48  // or ast.Stmt. Node does not modify node. Imports are not sorted for
    49  // nodes representing partial source files (for instance, if the node is
    50  // not an *ast.File or a *printer.CommentedNode not wrapping an *ast.File).
    51  //
    52  // The function may return early (before the entire result is written)
    53  // and return a formatting error, for instance due to an incorrect AST.
    54  //
    55  func Node(dst io.Writer, fset *token.FileSet, node interface{}) error {
    56  	// Determine if we have a complete source file (file != nil).
    57  	var file *ast.File
    58  	var cnode *printer.CommentedNode
    59  	switch n := node.(type) {
    60  	case *ast.File:
    61  		file = n
    62  	case *printer.CommentedNode:
    63  		if f, ok := n.Node.(*ast.File); ok {
    64  			file = f
    65  			cnode = n
    66  		}
    67  	}
    68  
    69  	// Sort imports if necessary.
    70  	if file != nil && hasUnsortedImports(file) {
    71  		// Make a copy of the AST because ast.SortImports is destructive.
    72  		// TODO(gri) Do this more efficiently.
    73  		var buf bytes.Buffer
    74  		err := config.Fprint(&buf, fset, file)
    75  		if err != nil {
    76  			return err
    77  		}
    78  		file, err = parser.ParseFile(fset, "", buf.Bytes(), parserMode)
    79  		if err != nil {
    80  			// We should never get here. If we do, provide good diagnostic.
    81  			return fmt.Errorf("format.Node internal error (%s)", err)
    82  		}
    83  		ast.SortImports(fset, file)
    84  
    85  		// Use new file with sorted imports.
    86  		node = file
    87  		if cnode != nil {
    88  			node = &printer.CommentedNode{Node: file, Comments: cnode.Comments}
    89  		}
    90  	}
    91  
    92  	return config.Fprint(dst, fset, node)
    93  }
    94  
    95  // Source formats src in canonical gofmt style and returns the result
    96  // or an (I/O or syntax) error. src is expected to be a syntactically
    97  // correct Go source file, or a list of Go declarations or statements.
    98  //
    99  // If src is a partial source file, the leading and trailing space of src
   100  // is applied to the result (such that it has the same leading and trailing
   101  // space as src), and the result is indented by the same amount as the first
   102  // line of src containing code. Imports are not sorted for partial source files.
   103  //
   104  func Source(src []byte) ([]byte, error) {
   105  	fset := token.NewFileSet()
   106  	file, sourceAdj, indentAdj, err := parse(fset, "", src, true)
   107  	if err != nil {
   108  		return nil, err
   109  	}
   110  
   111  	if sourceAdj == nil {
   112  		// Complete source file.
   113  		// TODO(gri) consider doing this always.
   114  		ast.SortImports(fset, file)
   115  	}
   116  
   117  	return format(fset, file, sourceAdj, indentAdj, src, config)
   118  }
   119  
   120  func hasUnsortedImports(file *ast.File) bool {
   121  	for _, d := range file.Decls {
   122  		d, ok := d.(*ast.GenDecl)
   123  		if !ok || d.Tok != token.IMPORT {
   124  			// Not an import declaration, so we're done.
   125  			// Imports are always first.
   126  			return false
   127  		}
   128  		if d.Lparen.IsValid() {
   129  			// For now assume all grouped imports are unsorted.
   130  			// TODO(gri) Should check if they are sorted already.
   131  			return true
   132  		}
   133  		// Ungrouped imports are sorted by default.
   134  	}
   135  	return false
   136  }