@@ -453,15 +453,24 @@ func FinalizeRemovals(file *ast.File) {
453453
454454 file .Imports = squeeze (file .Imports )
455455
456+ rebuildFileComments (file )
457+ }
458+
459+ // rebuildFileComments will rebuild the top level comments
460+ // group for the given file using the comments found in the file.
461+ func rebuildFileComments (file * ast.File ) {
456462 file .Comments = nil // clear this first so ast.Inspect doesn't walk it.
457- remComments := []* ast.CommentGroup {}
463+ comments := []* ast.CommentGroup {}
464+ if file .Doc != nil {
465+ comments = append (comments , file .Doc )
466+ }
458467 ast .Inspect (file , func (n ast.Node ) bool {
459468 if cg , ok := n .(* ast.CommentGroup ); ok {
460- remComments = append (remComments , cg )
469+ comments = append (comments , cg )
461470 }
462471 return true
463472 })
464- file .Comments = remComments
473+ file .Comments = comments
465474}
466475
467476// ConcatenateFiles will concatenate the given tailing files onto the
@@ -488,7 +497,11 @@ func ConcatenateFiles(file *ast.File, tails ...*ast.File) error {
488497 if file .Name .Name != tail .Name .Name {
489498 return fmt .Errorf ("can not concatenate files with different package names: %q != %q" , file .Name .Name , tail .Name .Name )
490499 }
500+ if file .GoVersion != tail .GoVersion {
501+ return fmt .Errorf ("can not concatenate files with different Go versions: %q != %q" , file .GoVersion , tail .GoVersion )
502+ }
491503
504+ // Concatenate the imports.
492505 for _ , imp := range tail .Imports {
493506 path := imp .Path .Value
494507 if oldImp , ok := imports [path ]; ok {
@@ -503,15 +516,33 @@ func ConcatenateFiles(file *ast.File, tails ...*ast.File) error {
503516 imports [imp .Path .Value ] = imp
504517 }
505518
519+ // Concatenate the declarations.
506520 file .Decls = append (file .Decls , tail .Decls ... )
507- file .Comments = append (file .Comments , tail .Comments ... )
521+
522+ // Concatenate the document comments.
523+ if tail .Doc != nil {
524+ if file .Doc == nil {
525+ file .Doc = tail .Doc
526+ } else {
527+ file .Doc .List = append (file .Doc .List , tail .Doc .List ... )
528+ }
529+ }
530+
531+ // Concatenate the unresolved identifier and update scope.
532+ // Both of these are deprecated. See Object.
533+ // We just join them to attempt to keep the file in a valid state.
508534 file .Unresolved = append (file .Unresolved , tail .Unresolved ... )
509535 for name , obj := range tail .Scope .Objects {
510536 if _ , ok := file .Scope .Objects [name ]; ok {
511537 return fmt .Errorf ("can not concatenate files with duplicate object names: %q" , name )
512538 }
513539 file .Scope .Objects [name ] = obj
514540 }
541+
542+ // Update the file end to the new end.
543+ file .FileEnd = tail .FileEnd
515544 }
545+
546+ rebuildFileComments (file )
516547 return nil
517548}
0 commit comments