| 1 | // Copyright 2025 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 astutil_test |
| 6 | |
| 7 | import ( |
| 8 | "go/ast" |
| 9 | "go/parser" |
| 10 | "go/token" |
| 11 | "slices" |
| 12 | "testing" |
| 13 | |
| 14 | "golang.org/x/tools/internal/astutil" |
| 15 | ) |
| 16 | |
| 17 | func TestComments(t *testing.T) { |
| 18 | src := ` |
| 19 | package main |
| 20 | |
| 21 | // A |
| 22 | func fn() { }` |
| 23 | var fset token.FileSet |
| 24 | f, err := parser.ParseFile(&fset, "", []byte(src), parser.ParseComments|parser.AllErrors) |
| 25 | if err != nil { |
| 26 | t.Fatal(err) |
| 27 | } |
| 28 | |
| 29 | commentA := f.Comments[0].List[0] |
| 30 | commentAMidPos := (commentA.Pos() + commentA.End()) / 2 |
| 31 | |
| 32 | want := []*ast.Comment{commentA} |
| 33 | testCases := []struct { |
| 34 | name string |
| 35 | start, end token.Pos |
| 36 | want []*ast.Comment |
| 37 | }{ |
| 38 | {name: "comment totally overlaps with given interval", start: f.Pos(), end: f.End(), want: want}, |
| 39 | {name: "interval from file start to mid of comment A", start: f.Pos(), end: commentAMidPos, want: want}, |
| 40 | {name: "interval from mid of comment A to file end", start: commentAMidPos, end: commentA.End(), want: want}, |
| 41 | {name: "interval from start of comment A to mid of comment A", start: commentA.Pos(), end: commentAMidPos, want: want}, |
| 42 | {name: "interval from mid of comment A to comment A end", start: commentAMidPos, end: commentA.End(), want: want}, |
| 43 | {name: "interval at the start of comment A", start: commentA.Pos(), end: commentA.Pos(), want: want}, |
| 44 | {name: "interval at the end of comment A", start: commentA.End(), end: commentA.End(), want: want}, |
| 45 | {name: "interval from file start to the front of comment A start", start: f.Pos(), end: commentA.Pos() - 1, want: nil}, |
| 46 | {name: "interval from the position after end of comment A to file end", start: commentA.End() + 1, end: f.End(), want: nil}, |
| 47 | } |
| 48 | for _, tc := range testCases { |
| 49 | t.Run(tc.name, func(t *testing.T) { |
| 50 | var got []*ast.Comment |
| 51 | for co := range astutil.Comments(f, tc.start, tc.end) { |
| 52 | got = append(got, co) |
| 53 | } |
| 54 | if !slices.Equal(got, tc.want) { |
| 55 | t.Errorf("%s: got %v, want %v", tc.name, got, tc.want) |
| 56 | } |
| 57 | }) |
| 58 | } |
| 59 | } |