@@ -9,6 +9,7 @@ package tokeninternal
99import (
1010 "fmt"
1111 "go/token"
12+ "slices"
1213 "sort"
1314 "sync"
1415 "sync/atomic"
@@ -18,7 +19,29 @@ import (
1819// AddExistingFiles adds the specified files to the FileSet if they
1920// are not already present. It panics if any pair of files in the
2021// resulting FileSet would overlap.
22+ //
23+ // TODO(adonovan): add this a method to FileSet; see
24+ // https://github.com/golang/go/issues/73205
2125func AddExistingFiles (fset * token.FileSet , files []* token.File ) {
26+
27+ // This function cannot be implemented as:
28+ //
29+ // for _, file := range files {
30+ // if prev := fset.File(token.Pos(file.Base())); prev != nil {
31+ // if prev != file {
32+ // panic("FileSet contains a different file at the same base")
33+ // }
34+ // continue
35+ // }
36+ // file2 := fset.AddFile(file.Name(), file.Base(), file.Size())
37+ // file2.SetLines(file.Lines())
38+ // }
39+ //
40+ // because all calls to AddFile must be in increasing order.
41+ // AddExistingFiles lets us augment an existing FileSet
42+ // sequentially, so long as all sets of files have disjoint
43+ // ranges.
44+
2245 // Punch through the FileSet encapsulation.
2346 type tokenFileSet struct {
2447 // This type remained essentially consistent from go1.16 to go1.21.
@@ -83,23 +106,13 @@ func AddExistingFiles(fset *token.FileSet, files []*token.File) {
83106// of their Base.
84107func FileSetFor (files ... * token.File ) * token.FileSet {
85108 fset := token .NewFileSet ()
86- for _ , f := range files {
87- f2 := fset .AddFile (f .Name (), f .Base (), f .Size ())
88- f2 .SetLines (f .Lines ())
89- }
109+ AddExistingFiles (fset , files )
90110 return fset
91111}
92112
93113// CloneFileSet creates a new FileSet holding all files in fset. It does not
94114// create copies of the token.Files in fset: they are added to the resulting
95115// FileSet unmodified.
96116func CloneFileSet (fset * token.FileSet ) * token.FileSet {
97- var files []* token.File
98- fset .Iterate (func (f * token.File ) bool {
99- files = append (files , f )
100- return true
101- })
102- newFileSet := token .NewFileSet ()
103- AddExistingFiles (newFileSet , files )
104- return newFileSet
117+ return FileSetFor (slices .Collect (fset .Iterate )... )
105118}
0 commit comments