Source file src/cmd/vendor/golang.org/x/tools/internal/analysis/analyzerutil/version.go

     1  // Copyright 2025 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 analyzerutil
     6  
     7  import (
     8  	"go/ast"
     9  	"strings"
    10  
    11  	"golang.org/x/tools/go/analysis"
    12  	"golang.org/x/tools/internal/packagepath"
    13  	"golang.org/x/tools/internal/stdlib"
    14  	"golang.org/x/tools/internal/versions"
    15  )
    16  
    17  // FileUsesGoVersion reports whether the specified file may use features of the
    18  // specified version of Go (e.g. "go1.24").
    19  //
    20  // It returns false when version information is not available,
    21  // such as for parsed files that are ignored by the type checker.
    22  //
    23  // Tip: we recommend using this check "late", just before calling
    24  // pass.Report, rather than "early" (when entering each ast.File, or
    25  // each candidate node of interest, during the traversal), because the
    26  // operation is not free, yet is not a highly selective filter: the
    27  // fraction of files that pass most version checks is high and
    28  // increases over time.
    29  func FileUsesGoVersion(pass *analysis.Pass, file *ast.File, version string) (_res bool) {
    30  	fileVersion, ok := pass.TypesInfo.FileVersions[file]
    31  	if !ok {
    32  		return false // be conservative in the absence of information (e.g. IgnoredFiles)
    33  	}
    34  
    35  	// Standard packages that are part of toolchain bootstrapping
    36  	// are not considered to use a version of Go later than the
    37  	// current bootstrap toolchain version.
    38  	// The bootstrap rule does not cover tests,
    39  	// and some tests (e.g. debug/elf/file_test.go) rely on this.
    40  	pkgpath := pass.Pkg.Path()
    41  	if packagepath.IsStdPackage(pkgpath) &&
    42  		stdlib.IsBootstrapPackage(pkgpath) && // (excludes "*_test" external test packages)
    43  		!strings.HasSuffix(pass.Fset.File(file.Pos()).Name(), "_test.go") { // (excludes all tests)
    44  		fileVersion = stdlib.BootstrapVersion.String() // package must bootstrap
    45  	}
    46  
    47  	return !versions.Before(fileVersion, version)
    48  }
    49  

View as plain text