golang.org/x/tools@v0.21.1-0.20240520172518-788d39e776b1/internal/versions/types_go122.go (about)

     1  // Copyright 2023 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  //go:build go1.22
     6  // +build go1.22
     7  
     8  package versions
     9  
    10  import (
    11  	"go/ast"
    12  	"go/types"
    13  )
    14  
    15  // FileVersion returns a file's Go version.
    16  // The reported version is an unknown Future version if a
    17  // version cannot be determined.
    18  func FileVersion(info *types.Info, file *ast.File) string {
    19  	// In tools built with Go >= 1.22, the Go version of a file
    20  	// follow a cascades of sources:
    21  	// 1) types.Info.FileVersion, which follows the cascade:
    22  	//   1.a) file version (ast.File.GoVersion),
    23  	//   1.b) the package version (types.Config.GoVersion), or
    24  	// 2) is some unknown Future version.
    25  	//
    26  	// File versions require a valid package version to be provided to types
    27  	// in Config.GoVersion. Config.GoVersion is either from the package's module
    28  	// or the toolchain (go run). This value should be provided by go/packages
    29  	// or unitchecker.Config.GoVersion.
    30  	if v := info.FileVersions[file]; IsValid(v) {
    31  		return v
    32  	}
    33  	// Note: we could instead return runtime.Version() [if valid].
    34  	// This would act as a max version on what a tool can support.
    35  	return Future
    36  }
    37  
    38  // InitFileVersions initializes info to record Go versions for Go files.
    39  func InitFileVersions(info *types.Info) {
    40  	info.FileVersions = make(map[*ast.File]string)
    41  }