@@ -93,6 +93,7 @@ func ExtractToNewFile(ctx context.Context, snapshot *cache.Snapshot, fh file.Han
93
93
return nil , fmt .Errorf ("%s: %w" , errorPrefix , err )
94
94
}
95
95
96
+ // Expand the selection, and compute the portion to extract.
96
97
start , end , firstSymbol , ok := selectedToplevelDecls (pgf , start , end )
97
98
if ! ok {
98
99
return nil , fmt .Errorf ("invalid selection" )
@@ -109,7 +110,20 @@ func ExtractToNewFile(ctx context.Context, snapshot *cache.Snapshot, fh file.Han
109
110
spaces := len (rest ) - len (bytes .TrimLeft (rest , " \t \n " ))
110
111
end += token .Pos (spaces )
111
112
pgf .CheckPos (end ) // #70553
112
- // Inv: end is valid wrt pgf.Tok.
113
+ if ! (start <= end ) {
114
+ bug .Reportf ("start: not before end" )
115
+ }
116
+ // Inv: end is valid wrt pgf.Tok; env >= start.
117
+ fileStart := pgf .File .FileStart
118
+ pgf .CheckPos (fileStart ) // #70553
119
+ if ! (0 <= start - fileStart ) {
120
+ bug .Reportf ("start: out of bounds" )
121
+ }
122
+ if ! (int (end - fileStart ) <= len (pgf .Src )) {
123
+ bug .Reportf ("end: out of bounds" )
124
+ }
125
+ // Inv: 0 <= start-fileStart <= end-fileStart <= len(Src).
126
+ src := pgf .Src [start - fileStart : end - fileStart ]
113
127
114
128
replaceRange , err := pgf .PosRange (start , end )
115
129
if err != nil {
@@ -176,9 +190,7 @@ func ExtractToNewFile(ctx context.Context, snapshot *cache.Snapshot, fh file.Han
176
190
return nil , fmt .Errorf ("%s: %w" , errorPrefix , err )
177
191
}
178
192
179
- fileStart := pgf .File .FileStart
180
- pgf .CheckPos (fileStart ) // #70553
181
- buf .Write (pgf .Src [start - fileStart : end - fileStart ])
193
+ buf .Write (src )
182
194
183
195
newFileContent , err := format .Source (buf .Bytes ())
184
196
if err != nil {
0 commit comments