Source file src/go/format/format.go

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

View as plain text