1// Copyright 2018 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
5package span_test
6
7import (
8	"fmt"
9	"go/token"
10	"path"
11	"testing"
12
13	"golang.org/x/tools/internal/span"
14)
15
16var testdata = []struct {
17	uri     string
18	content []byte
19}{
20	{"/a.go", []byte(`
21// file a.go
22package test
23`)},
24	{"/b.go", []byte(`
25//
26//
27// file b.go
28package test`)},
29	{"/c.go", []byte(`
30// file c.go
31package test`)},
32}
33
34var tokenTests = []span.Span{
35	span.New(span.URIFromPath("/a.go"), span.NewPoint(1, 1, 0), span.Point{}),
36	span.New(span.URIFromPath("/a.go"), span.NewPoint(3, 7, 20), span.NewPoint(3, 7, 20)),
37	span.New(span.URIFromPath("/b.go"), span.NewPoint(4, 9, 15), span.NewPoint(4, 13, 19)),
38	span.New(span.URIFromPath("/c.go"), span.NewPoint(4, 1, 26), span.Point{}),
39}
40
41func TestToken(t *testing.T) {
42	fset := token.NewFileSet()
43	files := map[span.URI]*token.File{}
44	for _, f := range testdata {
45		file := fset.AddFile(f.uri, -1, len(f.content))
46		file.SetLinesForContent(f.content)
47		files[span.URIFromPath(f.uri)] = file
48	}
49	for _, test := range tokenTests {
50		f := files[test.URI()]
51		c := span.NewTokenConverter(fset, f)
52		t.Run(path.Base(f.Name()), func(t *testing.T) {
53			checkToken(t, c, span.New(
54				test.URI(),
55				span.NewPoint(test.Start().Line(), test.Start().Column(), 0),
56				span.NewPoint(test.End().Line(), test.End().Column(), 0),
57			), test)
58			checkToken(t, c, span.New(
59				test.URI(),
60				span.NewPoint(0, 0, test.Start().Offset()),
61				span.NewPoint(0, 0, test.End().Offset()),
62			), test)
63		})
64	}
65}
66
67func checkToken(t *testing.T, c *span.TokenConverter, in, expect span.Span) {
68	rng, err := in.Range(c)
69	if err != nil {
70		t.Error(err)
71	}
72	gotLoc, err := rng.Span()
73	if err != nil {
74		t.Error(err)
75	}
76	expected := fmt.Sprintf("%+v", expect)
77	got := fmt.Sprintf("%+v", gotLoc)
78	if expected != got {
79		t.Errorf("For %v expected %q got %q", in, expected, got)
80	}
81}
82