@@ -406,6 +406,18 @@ func squeeze[E ast.Node, S ~[]E](s S) S {
406406 return s [:dest ]
407407}
408408
409+ func updateFileComments (file * ast.File ) {
410+ file .Comments = nil // clear this first so ast.Inspect doesn't walk it.
411+ remComments := []* ast.CommentGroup {}
412+ ast .Inspect (file , func (n ast.Node ) bool {
413+ if cg , ok := n .(* ast.CommentGroup ); ok {
414+ remComments = append (remComments , cg )
415+ }
416+ return true
417+ })
418+ file .Comments = remComments
419+ }
420+
409421// FinalizeRemovals fully removes any declaration, specification, imports
410422// that have been set to nil. This will also remove any unassociated comment
411423// groups, including the comments from removed code.
@@ -454,7 +466,8 @@ func FinalizeRemovals(file *ast.File) {
454466 }
455467
456468 file .Imports = squeeze (file .Imports )
457- file .Comments = nil
469+
470+ updateFileComments (file )
458471}
459472
460473// ConcatenateFiles will concatenate the given tailing files onto the
@@ -478,13 +491,7 @@ func FinalizeRemovals(file *ast.File) {
478491// - The tails will not be modified, however the nodes from the tails will be
479492// added into the target file so modifications to the tails after
480493// concatenation could cause the target file to be in an invalid state.
481- // - This will set the deprecated Unresolved fields to nil, see [ast.Object].
482- // - This will set the deprecated Scope to nil, see [ast.Object].
483- // - This will set the full list of Comments to nil.
484- // The full list of Comments expects the comments to use Pos that follow
485- // sequentially when formatting. That may not be the case after
486- // concatenation. By removing the full list tools like Format will use the
487- // comments on the nodes instead.
494+ // - This will not modify the deprecated Unresolved or file Scope fields.
488495// - Any comments on import declarations will be lost since the imports will
489496// be merged into a single new import declaration. The comments on the
490497// individual import specs will be preserved.
@@ -573,11 +580,6 @@ func ConcatenateFiles(file *ast.File, tails ...*ast.File) error {
573580 }
574581 file .Decls = decls
575582
576- // Remove the full comments list since they are no longer valid.
577- file .Comments = nil
578-
579- // Remove the deprecated fields from the file, see [ast.Object].
580- file .Unresolved = nil
581- file .Scope = nil
583+ updateFileComments (file )
582584 return nil
583585}
0 commit comments