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

     1  // Copyright 2020 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 analysisinternal provides gopls' internal analyses with a
     6  // number of helper functions that operate on typed syntax trees.
     7  package analysisinternal
     8  
     9  import (
    10  	"bytes"
    11  	"cmp"
    12  	"fmt"
    13  	"go/ast"
    14  	"go/printer"
    15  	"go/scanner"
    16  	"go/token"
    17  	"go/types"
    18  	"iter"
    19  	pathpkg "path"
    20  	"slices"
    21  	"strings"
    22  
    23  	"golang.org/x/tools/go/analysis"
    24  	"golang.org/x/tools/go/ast/inspector"
    25  	"golang.org/x/tools/internal/typesinternal"
    26  )
    27  
    28  // Deprecated: this heuristic is ill-defined.
    29  // TODO(adonovan): move to sole use in gopls/internal/cache.
    30  func TypeErrorEndPos(fset *token.FileSet, src []byte, start token.Pos) token.Pos {
    31  	// Get the end position for the type error.
    32  	file := fset.File(start)
    33  	if file == nil {
    34  		return start
    35  	}
    36  	if offset := file.PositionFor(start, false).Offset; offset > len(src) {
    37  		return start
    38  	} else {
    39  		src = src[offset:]
    40  	}
    41  
    42  	// Attempt to find a reasonable end position for the type error.
    43  	//
    44  	// TODO(rfindley): the heuristic implemented here is unclear. It looks like
    45  	// it seeks the end of the primary operand starting at start, but that is not
    46  	// quite implemented (for example, given a func literal this heuristic will
    47  	// return the range of the func keyword).
    48  	//
    49  	// We should formalize this heuristic, or deprecate it by finally proposing
    50  	// to add end position to all type checker errors.
    51  	//
    52  	// Nevertheless, ensure that the end position at least spans the current
    53  	// token at the cursor (this was golang/go#69505).
    54  	end := start
    55  	{
    56  		var s scanner.Scanner
    57  		fset := token.NewFileSet()
    58  		f := fset.AddFile("", fset.Base(), len(src))
    59  		s.Init(f, src, nil /* no error handler */, scanner.ScanComments)
    60  		pos, tok, lit := s.Scan()
    61  		if tok != token.SEMICOLON && token.Pos(f.Base()) <= pos && pos <= token.Pos(f.Base()+f.Size()) {
    62  			off := file.Offset(pos) + len(lit)
    63  			src = src[off:]
    64  			end += token.Pos(off)
    65  		}
    66  	}
    67  
    68  	// Look for bytes that might terminate the current operand. See note above:
    69  	// this is imprecise.
    70  	if width := bytes.IndexAny(src, " \n,():;[]+-*/"); width > 0 {
    71  		end += token.Pos(width)
    72  	}
    73  	return end
    74  }
    75  
    76  // WalkASTWithParent walks the AST rooted at n. The semantics are
    77  // similar to ast.Inspect except it does not call f(nil).
    78  func WalkASTWithParent(n ast.Node, f func(n ast.Node, parent ast.Node) bool) {
    79  	var ancestors []ast.Node
    80  	ast.Inspect(n, func(n ast.Node) (recurse bool) {
    81  		if n == nil {
    82  			ancestors = ancestors[:len(ancestors)-1]
    83  			return false
    84  		}
    85  
    86  		var parent ast.Node
    87  		if len(ancestors) > 0 {
    88  			parent = ancestors[len(ancestors)-1]
    89  		}
    90  		ancestors = append(ancestors, n)
    91  		return f(n, parent)
    92  	})
    93  }
    94  
    95  // MatchingIdents finds the names of all identifiers in 'node' that match any of the given types.
    96  // 'pos' represents the position at which the identifiers may be inserted. 'pos' must be within
    97  // the scope of each of identifier we select. Otherwise, we will insert a variable at 'pos' that
    98  // is unrecognized.
    99  func MatchingIdents(typs []types.Type, node ast.Node, pos token.Pos, info *types.Info, pkg *types.Package) map[types.Type][]string {
   100  
   101  	// Initialize matches to contain the variable types we are searching for.
   102  	matches := make(map[types.Type][]string)
   103  	for _, typ := range typs {
   104  		if typ == nil {
   105  			continue // TODO(adonovan): is this reachable?
   106  		}
   107  		matches[typ] = nil // create entry
   108  	}
   109  
   110  	seen := map[types.Object]struct{}{}
   111  	ast.Inspect(node, func(n ast.Node) bool {
   112  		if n == nil {
   113  			return false
   114  		}
   115  		// Prevent circular definitions. If 'pos' is within an assignment statement, do not
   116  		// allow any identifiers in that assignment statement to be selected. Otherwise,
   117  		// we could do the following, where 'x' satisfies the type of 'f0':
   118  		//
   119  		// x := fakeStruct{f0: x}
   120  		//
   121  		if assign, ok := n.(*ast.AssignStmt); ok && pos > assign.Pos() && pos <= assign.End() {
   122  			return false
   123  		}
   124  		if n.End() > pos {
   125  			return n.Pos() <= pos
   126  		}
   127  		ident, ok := n.(*ast.Ident)
   128  		if !ok || ident.Name == "_" {
   129  			return true
   130  		}
   131  		obj := info.Defs[ident]
   132  		if obj == nil || obj.Type() == nil {
   133  			return true
   134  		}
   135  		if _, ok := obj.(*types.TypeName); ok {
   136  			return true
   137  		}
   138  		// Prevent duplicates in matches' values.
   139  		if _, ok = seen[obj]; ok {
   140  			return true
   141  		}
   142  		seen[obj] = struct{}{}
   143  		// Find the scope for the given position. Then, check whether the object
   144  		// exists within the scope.
   145  		innerScope := pkg.Scope().Innermost(pos)
   146  		if innerScope == nil {
   147  			return true
   148  		}
   149  		_, foundObj := innerScope.LookupParent(ident.Name, pos)
   150  		if foundObj != obj {
   151  			return true
   152  		}
   153  		// The object must match one of the types that we are searching for.
   154  		// TODO(adonovan): opt: use typeutil.Map?
   155  		if names, ok := matches[obj.Type()]; ok {
   156  			matches[obj.Type()] = append(names, ident.Name)
   157  		} else {
   158  			// If the object type does not exactly match
   159  			// any of the target types, greedily find the first
   160  			// target type that the object type can satisfy.
   161  			for typ := range matches {
   162  				if equivalentTypes(obj.Type(), typ) {
   163  					matches[typ] = append(matches[typ], ident.Name)
   164  				}
   165  			}
   166  		}
   167  		return true
   168  	})
   169  	return matches
   170  }
   171  
   172  func equivalentTypes(want, got types.Type) bool {
   173  	if types.Identical(want, got) {
   174  		return true
   175  	}
   176  	// Code segment to help check for untyped equality from (golang/go#32146).
   177  	if rhs, ok := want.(*types.Basic); ok && rhs.Info()&types.IsUntyped > 0 {
   178  		if lhs, ok := got.Underlying().(*types.Basic); ok {
   179  			return rhs.Info()&types.IsConstType == lhs.Info()&types.IsConstType
   180  		}
   181  	}
   182  	return types.AssignableTo(want, got)
   183  }
   184  
   185  // A ReadFileFunc is a function that returns the
   186  // contents of a file, such as [os.ReadFile].
   187  type ReadFileFunc = func(filename string) ([]byte, error)
   188  
   189  // CheckedReadFile returns a wrapper around a Pass.ReadFile
   190  // function that performs the appropriate checks.
   191  func CheckedReadFile(pass *analysis.Pass, readFile ReadFileFunc) ReadFileFunc {
   192  	return func(filename string) ([]byte, error) {
   193  		if err := CheckReadable(pass, filename); err != nil {
   194  			return nil, err
   195  		}
   196  		return readFile(filename)
   197  	}
   198  }
   199  
   200  // CheckReadable enforces the access policy defined by the ReadFile field of [analysis.Pass].
   201  func CheckReadable(pass *analysis.Pass, filename string) error {
   202  	if slices.Contains(pass.OtherFiles, filename) ||
   203  		slices.Contains(pass.IgnoredFiles, filename) {
   204  		return nil
   205  	}
   206  	for _, f := range pass.Files {
   207  		if pass.Fset.File(f.FileStart).Name() == filename {
   208  			return nil
   209  		}
   210  	}
   211  	return fmt.Errorf("Pass.ReadFile: %s is not among OtherFiles, IgnoredFiles, or names of Files", filename)
   212  }
   213  
   214  // AddImport checks whether this file already imports pkgpath and
   215  // that import is in scope at pos. If so, it returns the name under
   216  // which it was imported and a zero edit. Otherwise, it adds a new
   217  // import of pkgpath, using a name derived from the preferred name,
   218  // and returns the chosen name, a prefix to be concatenated with member
   219  // to form a qualified name, and the edit for the new import.
   220  //
   221  // In the special case that pkgpath is dot-imported then member, the
   222  // identifier for which the import is being added, is consulted. If
   223  // member is not shadowed at pos, AddImport returns (".", "", nil).
   224  // (AddImport accepts the caller's implicit claim that the imported
   225  // package declares member.)
   226  //
   227  // It does not mutate its arguments.
   228  func AddImport(info *types.Info, file *ast.File, preferredName, pkgpath, member string, pos token.Pos) (name, prefix string, newImport []analysis.TextEdit) {
   229  	// Find innermost enclosing lexical block.
   230  	scope := info.Scopes[file].Innermost(pos)
   231  	if scope == nil {
   232  		panic("no enclosing lexical block")
   233  	}
   234  
   235  	// Is there an existing import of this package?
   236  	// If so, are we in its scope? (not shadowed)
   237  	for _, spec := range file.Imports {
   238  		pkgname := info.PkgNameOf(spec)
   239  		if pkgname != nil && pkgname.Imported().Path() == pkgpath {
   240  			name = pkgname.Name()
   241  			if name == "." {
   242  				// The scope of ident must be the file scope.
   243  				if s, _ := scope.LookupParent(member, pos); s == info.Scopes[file] {
   244  					return name, "", nil
   245  				}
   246  			} else if _, obj := scope.LookupParent(name, pos); obj == pkgname {
   247  				return name, name + ".", nil
   248  			}
   249  		}
   250  	}
   251  
   252  	// We must add a new import.
   253  	// Ensure we have a fresh name.
   254  	newName := FreshName(scope, pos, preferredName)
   255  
   256  	// Create a new import declaration either before the first existing
   257  	// declaration (which must exist), including its comments; or
   258  	// inside the declaration, if it is an import group.
   259  	//
   260  	// Use a renaming import whenever the preferred name is not
   261  	// available, or the chosen name does not match the last
   262  	// segment of its path.
   263  	newText := fmt.Sprintf("%q", pkgpath)
   264  	if newName != preferredName || newName != pathpkg.Base(pkgpath) {
   265  		newText = fmt.Sprintf("%s %q", newName, pkgpath)
   266  	}
   267  	decl0 := file.Decls[0]
   268  	var before ast.Node = decl0
   269  	switch decl0 := decl0.(type) {
   270  	case *ast.GenDecl:
   271  		if decl0.Doc != nil {
   272  			before = decl0.Doc
   273  		}
   274  	case *ast.FuncDecl:
   275  		if decl0.Doc != nil {
   276  			before = decl0.Doc
   277  		}
   278  	}
   279  	// If the first decl is an import group, add this new import at the end.
   280  	if gd, ok := before.(*ast.GenDecl); ok && gd.Tok == token.IMPORT && gd.Rparen.IsValid() {
   281  		pos = gd.Rparen
   282  		// if it's a std lib, we should append it at the beginning of import group.
   283  		// otherwise we may see the std package is put at the last behind a 3rd module which doesn't follow our convention.
   284  		// besides, gofmt doesn't help in this case.
   285  		if IsStdPackage(pkgpath) && len(gd.Specs) != 0 {
   286  			pos = gd.Specs[0].Pos()
   287  			newText += "\n\t"
   288  		} else {
   289  			newText = "\t" + newText + "\n"
   290  		}
   291  	} else {
   292  		pos = before.Pos()
   293  		newText = "import " + newText + "\n\n"
   294  	}
   295  	return newName, newName + ".", []analysis.TextEdit{{
   296  		Pos:     pos,
   297  		End:     pos,
   298  		NewText: []byte(newText),
   299  	}}
   300  }
   301  
   302  // FreshName returns the name of an identifier that is undefined
   303  // at the specified position, based on the preferred name.
   304  func FreshName(scope *types.Scope, pos token.Pos, preferred string) string {
   305  	newName := preferred
   306  	for i := 0; ; i++ {
   307  		if _, obj := scope.LookupParent(newName, pos); obj == nil {
   308  			break // fresh
   309  		}
   310  		newName = fmt.Sprintf("%s%d", preferred, i)
   311  	}
   312  	return newName
   313  }
   314  
   315  // Format returns a string representation of the node n.
   316  func Format(fset *token.FileSet, n ast.Node) string {
   317  	var buf strings.Builder
   318  	printer.Fprint(&buf, fset, n) // ignore errors
   319  	return buf.String()
   320  }
   321  
   322  // Imports returns true if path is imported by pkg.
   323  func Imports(pkg *types.Package, path string) bool {
   324  	for _, imp := range pkg.Imports() {
   325  		if imp.Path() == path {
   326  			return true
   327  		}
   328  	}
   329  	return false
   330  }
   331  
   332  // IsTypeNamed reports whether t is (or is an alias for) a
   333  // package-level defined type with the given package path and one of
   334  // the given names. It returns false if t is nil.
   335  //
   336  // This function avoids allocating the concatenation of "pkg.Name",
   337  // which is important for the performance of syntax matching.
   338  func IsTypeNamed(t types.Type, pkgPath string, names ...string) bool {
   339  	if named, ok := types.Unalias(t).(*types.Named); ok {
   340  		tname := named.Obj()
   341  		return tname != nil &&
   342  			typesinternal.IsPackageLevel(tname) &&
   343  			tname.Pkg().Path() == pkgPath &&
   344  			slices.Contains(names, tname.Name())
   345  	}
   346  	return false
   347  }
   348  
   349  // IsPointerToNamed reports whether t is (or is an alias for) a pointer to a
   350  // package-level defined type with the given package path and one of the given
   351  // names. It returns false if t is not a pointer type.
   352  func IsPointerToNamed(t types.Type, pkgPath string, names ...string) bool {
   353  	r := typesinternal.Unpointer(t)
   354  	if r == t {
   355  		return false
   356  	}
   357  	return IsTypeNamed(r, pkgPath, names...)
   358  }
   359  
   360  // IsFunctionNamed reports whether obj is a package-level function
   361  // defined in the given package and has one of the given names.
   362  // It returns false if obj is nil.
   363  //
   364  // This function avoids allocating the concatenation of "pkg.Name",
   365  // which is important for the performance of syntax matching.
   366  func IsFunctionNamed(obj types.Object, pkgPath string, names ...string) bool {
   367  	f, ok := obj.(*types.Func)
   368  	return ok &&
   369  		typesinternal.IsPackageLevel(obj) &&
   370  		f.Pkg().Path() == pkgPath &&
   371  		f.Type().(*types.Signature).Recv() == nil &&
   372  		slices.Contains(names, f.Name())
   373  }
   374  
   375  // IsMethodNamed reports whether obj is a method defined on a
   376  // package-level type with the given package and type name, and has
   377  // one of the given names. It returns false if obj is nil.
   378  //
   379  // This function avoids allocating the concatenation of "pkg.TypeName.Name",
   380  // which is important for the performance of syntax matching.
   381  func IsMethodNamed(obj types.Object, pkgPath string, typeName string, names ...string) bool {
   382  	if fn, ok := obj.(*types.Func); ok {
   383  		if recv := fn.Type().(*types.Signature).Recv(); recv != nil {
   384  			_, T := typesinternal.ReceiverNamed(recv)
   385  			return T != nil &&
   386  				IsTypeNamed(T, pkgPath, typeName) &&
   387  				slices.Contains(names, fn.Name())
   388  		}
   389  	}
   390  	return false
   391  }
   392  
   393  // ValidateFixes validates the set of fixes for a single diagnostic.
   394  // Any error indicates a bug in the originating analyzer.
   395  //
   396  // It updates fixes so that fixes[*].End.IsValid().
   397  //
   398  // It may be used as part of an analysis driver implementation.
   399  func ValidateFixes(fset *token.FileSet, a *analysis.Analyzer, fixes []analysis.SuggestedFix) error {
   400  	fixMessages := make(map[string]bool)
   401  	for i := range fixes {
   402  		fix := &fixes[i]
   403  		if fixMessages[fix.Message] {
   404  			return fmt.Errorf("analyzer %q suggests two fixes with same Message (%s)", a.Name, fix.Message)
   405  		}
   406  		fixMessages[fix.Message] = true
   407  		if err := validateFix(fset, fix); err != nil {
   408  			return fmt.Errorf("analyzer %q suggests invalid fix (%s): %v", a.Name, fix.Message, err)
   409  		}
   410  	}
   411  	return nil
   412  }
   413  
   414  // validateFix validates a single fix.
   415  // Any error indicates a bug in the originating analyzer.
   416  //
   417  // It updates fix so that fix.End.IsValid().
   418  func validateFix(fset *token.FileSet, fix *analysis.SuggestedFix) error {
   419  
   420  	// Stably sort edits by Pos. This ordering puts insertions
   421  	// (end = start) before deletions (end > start) at the same
   422  	// point, but uses a stable sort to preserve the order of
   423  	// multiple insertions at the same point.
   424  	slices.SortStableFunc(fix.TextEdits, func(x, y analysis.TextEdit) int {
   425  		if sign := cmp.Compare(x.Pos, y.Pos); sign != 0 {
   426  			return sign
   427  		}
   428  		return cmp.Compare(x.End, y.End)
   429  	})
   430  
   431  	var prev *analysis.TextEdit
   432  	for i := range fix.TextEdits {
   433  		edit := &fix.TextEdits[i]
   434  
   435  		// Validate edit individually.
   436  		start := edit.Pos
   437  		file := fset.File(start)
   438  		if file == nil {
   439  			return fmt.Errorf("no token.File for TextEdit.Pos (%v)", edit.Pos)
   440  		}
   441  		fileEnd := token.Pos(file.Base() + file.Size())
   442  		if end := edit.End; end.IsValid() {
   443  			if end < start {
   444  				return fmt.Errorf("TextEdit.Pos (%v) > TextEdit.End (%v)", edit.Pos, edit.End)
   445  			}
   446  			endFile := fset.File(end)
   447  			if endFile != file && end < fileEnd+10 {
   448  				// Relax the checks below in the special case when the end position
   449  				// is only slightly beyond EOF, as happens when End is computed
   450  				// (as in ast.{Struct,Interface}Type) rather than based on
   451  				// actual token positions. In such cases, truncate end to EOF.
   452  				//
   453  				// This is a workaround for #71659; see:
   454  				// https://github.com/golang/go/issues/71659#issuecomment-2651606031
   455  				// A better fix would be more faithful recording of token
   456  				// positions (or their absence) in the AST.
   457  				edit.End = fileEnd
   458  				continue
   459  			}
   460  			if endFile == nil {
   461  				return fmt.Errorf("no token.File for TextEdit.End (%v; File(start).FileEnd is %d)", end, file.Base()+file.Size())
   462  			}
   463  			if endFile != file {
   464  				return fmt.Errorf("edit #%d spans files (%v and %v)",
   465  					i, file.Position(edit.Pos), endFile.Position(edit.End))
   466  			}
   467  		} else {
   468  			edit.End = start // update the SuggestedFix
   469  		}
   470  		if eof := fileEnd; edit.End > eof {
   471  			return fmt.Errorf("end is (%v) beyond end of file (%v)", edit.End, eof)
   472  		}
   473  
   474  		// Validate the sequence of edits:
   475  		// properly ordered, no overlapping deletions
   476  		if prev != nil && edit.Pos < prev.End {
   477  			xpos := fset.Position(prev.Pos)
   478  			xend := fset.Position(prev.End)
   479  			ypos := fset.Position(edit.Pos)
   480  			yend := fset.Position(edit.End)
   481  			return fmt.Errorf("overlapping edits to %s (%d:%d-%d:%d and %d:%d-%d:%d)",
   482  				xpos.Filename,
   483  				xpos.Line, xpos.Column,
   484  				xend.Line, xend.Column,
   485  				ypos.Line, ypos.Column,
   486  				yend.Line, yend.Column,
   487  			)
   488  		}
   489  		prev = edit
   490  	}
   491  
   492  	return nil
   493  }
   494  
   495  // CanImport reports whether one package is allowed to import another.
   496  //
   497  // TODO(adonovan): allow customization of the accessibility relation
   498  // (e.g. for Bazel).
   499  func CanImport(from, to string) bool {
   500  	// TODO(adonovan): better segment hygiene.
   501  	if to == "internal" || strings.HasPrefix(to, "internal/") {
   502  		// Special case: only std packages may import internal/...
   503  		// We can't reliably know whether we're in std, so we
   504  		// use a heuristic on the first segment.
   505  		first, _, _ := strings.Cut(from, "/")
   506  		if strings.Contains(first, ".") {
   507  			return false // example.com/foo ∉ std
   508  		}
   509  		if first == "testdata" {
   510  			return false // testdata/foo ∉ std
   511  		}
   512  	}
   513  	if strings.HasSuffix(to, "/internal") {
   514  		return strings.HasPrefix(from, to[:len(to)-len("/internal")])
   515  	}
   516  	if i := strings.LastIndex(to, "/internal/"); i >= 0 {
   517  		return strings.HasPrefix(from, to[:i])
   518  	}
   519  	return true
   520  }
   521  
   522  // DeleteStmt returns the edits to remove stmt if it is contained
   523  // in a BlockStmt, CaseClause, CommClause, or is the STMT in switch STMT; ... {...}
   524  // The report function abstracts gopls' bug.Report.
   525  func DeleteStmt(fset *token.FileSet, astFile *ast.File, stmt ast.Stmt, report func(string, ...any)) []analysis.TextEdit {
   526  	// TODO: pass in the cursor to a ast.Stmt. callers should provide the Cursor
   527  	insp := inspector.New([]*ast.File{astFile})
   528  	root := insp.Root()
   529  	cstmt, ok := root.FindNode(stmt)
   530  	if !ok {
   531  		report("%s not found in file", stmt.Pos())
   532  		return nil
   533  	}
   534  	// some paranoia
   535  	if !stmt.Pos().IsValid() || !stmt.End().IsValid() {
   536  		report("%s: stmt has invalid position", stmt.Pos())
   537  		return nil
   538  	}
   539  
   540  	// if the stmt is on a line by itself delete the whole line
   541  	// otherwise just delete the statement.
   542  
   543  	// this logic would be a lot simpler with the file contents, and somewhat simpler
   544  	// if the cursors included the comments.
   545  
   546  	tokFile := fset.File(stmt.Pos())
   547  	lineOf := tokFile.Line
   548  	stmtStartLine, stmtEndLine := lineOf(stmt.Pos()), lineOf(stmt.End())
   549  
   550  	var from, to token.Pos
   551  	// bounds of adjacent syntax/comments on same line, if any
   552  	limits := func(left, right token.Pos) {
   553  		if lineOf(left) == stmtStartLine {
   554  			from = left
   555  		}
   556  		if lineOf(right) == stmtEndLine {
   557  			to = right
   558  		}
   559  	}
   560  	// TODO(pjw): there are other places a statement might be removed:
   561  	// IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .
   562  	// (removing the blocks requires more rewriting than this routine would do)
   563  	// CommCase   = "case" ( SendStmt | RecvStmt ) | "default" .
   564  	// (removing the stmt requires more rewriting, and it's unclear what the user means)
   565  	switch parent := cstmt.Parent().Node().(type) {
   566  	case *ast.SwitchStmt:
   567  		limits(parent.Switch, parent.Body.Lbrace)
   568  	case *ast.TypeSwitchStmt:
   569  		limits(parent.Switch, parent.Body.Lbrace)
   570  		if parent.Assign == stmt {
   571  			return nil // don't let the user break the type switch
   572  		}
   573  	case *ast.BlockStmt:
   574  		limits(parent.Lbrace, parent.Rbrace)
   575  	case *ast.CommClause:
   576  		limits(parent.Colon, cstmt.Parent().Parent().Node().(*ast.BlockStmt).Rbrace)
   577  		if parent.Comm == stmt {
   578  			return nil // maybe the user meant to remove the entire CommClause?
   579  		}
   580  	case *ast.CaseClause:
   581  		limits(parent.Colon, cstmt.Parent().Parent().Node().(*ast.BlockStmt).Rbrace)
   582  	case *ast.ForStmt:
   583  		limits(parent.For, parent.Body.Lbrace)
   584  
   585  	default:
   586  		return nil // not one of ours
   587  	}
   588  
   589  	if prev, found := cstmt.PrevSibling(); found && lineOf(prev.Node().End()) == stmtStartLine {
   590  		from = prev.Node().End() // preceding statement ends on same line
   591  	}
   592  	if next, found := cstmt.NextSibling(); found && lineOf(next.Node().Pos()) == stmtEndLine {
   593  		to = next.Node().Pos() // following statement begins on same line
   594  	}
   595  	// and now for the comments
   596  Outer:
   597  	for _, cg := range astFile.Comments {
   598  		for _, co := range cg.List {
   599  			if lineOf(co.End()) < stmtStartLine {
   600  				continue
   601  			} else if lineOf(co.Pos()) > stmtEndLine {
   602  				break Outer // no more are possible
   603  			}
   604  			if lineOf(co.End()) == stmtStartLine && co.End() < stmt.Pos() {
   605  				if !from.IsValid() || co.End() > from {
   606  					from = co.End()
   607  					continue // maybe there are more
   608  				}
   609  			}
   610  			if lineOf(co.Pos()) == stmtEndLine && co.Pos() > stmt.End() {
   611  				if !to.IsValid() || co.Pos() < to {
   612  					to = co.Pos()
   613  					continue // maybe there are more
   614  				}
   615  			}
   616  		}
   617  	}
   618  	// if either from or to is valid, just remove the statement
   619  	// otherwise remove the line
   620  	edit := analysis.TextEdit{Pos: stmt.Pos(), End: stmt.End()}
   621  	if from.IsValid() || to.IsValid() {
   622  		// remove just the statement.
   623  		// we can't tell if there is a ; or whitespace right after the statement
   624  		// ideally we'd like to remove the former and leave the latter
   625  		// (if gofmt has run, there likely won't be a ;)
   626  		// In type switches we know there's a semicolon somewhere after the statement,
   627  		// but the extra work for this special case is not worth it, as gofmt will fix it.
   628  		return []analysis.TextEdit{edit}
   629  	}
   630  	// remove the whole line
   631  	for lineOf(edit.Pos) == stmtStartLine {
   632  		edit.Pos--
   633  	}
   634  	edit.Pos++ // get back tostmtStartLine
   635  	for lineOf(edit.End) == stmtEndLine {
   636  		edit.End++
   637  	}
   638  	return []analysis.TextEdit{edit}
   639  }
   640  
   641  // Comments returns an iterator over the comments overlapping the specified interval.
   642  func Comments(file *ast.File, start, end token.Pos) iter.Seq[*ast.Comment] {
   643  	// TODO(adonovan): optimize use binary O(log n) instead of linear O(n) search.
   644  	return func(yield func(*ast.Comment) bool) {
   645  		for _, cg := range file.Comments {
   646  			for _, co := range cg.List {
   647  				if co.Pos() > end {
   648  					return
   649  				}
   650  				if co.End() < start {
   651  					continue
   652  				}
   653  
   654  				if !yield(co) {
   655  					return
   656  				}
   657  			}
   658  		}
   659  	}
   660  }
   661  
   662  // IsStdPackage reports whether the specified package path belongs to a
   663  // package in the standard library (including internal dependencies).
   664  func IsStdPackage(path string) bool {
   665  	// A standard package has no dot in its first segment.
   666  	// (It may yet have a dot, e.g. "vendor/golang.org/x/foo".)
   667  	slash := strings.IndexByte(path, '/')
   668  	if slash < 0 {
   669  		slash = len(path)
   670  	}
   671  	return !strings.Contains(path[:slash], ".") && path != "testdata"
   672  }
   673  
   674  // Range returns an [analysis.Range] for the specified start and end positions.
   675  func Range(pos, end token.Pos) analysis.Range {
   676  	return tokenRange{pos, end}
   677  }
   678  
   679  // tokenRange is an implementation of the [analysis.Range] interface.
   680  type tokenRange struct{ StartPos, EndPos token.Pos }
   681  
   682  func (r tokenRange) Pos() token.Pos { return r.StartPos }
   683  func (r tokenRange) End() token.Pos { return r.EndPos }
   684  

View as plain text