1 // Copyright 2020 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.
20 "golang.org/x/tools/internal/lsp"
21 "golang.org/x/tools/internal/lsp/protocol"
22 "golang.org/x/tools/internal/lsp/source"
23 "golang.org/x/tools/internal/span"
26 // generate semantic tokens and interpolate them in the file
28 // The output is the input file decorated with comments showing the
29 // syntactic tokens. The comments are stylized:
30 // /*<arrow><length>,<token type>,[<modifiers]*/
31 // For most occurrences, the comment comes just before the token it
32 // describes, and arrow is a right arrow. If the token is inside a string
33 // the comment comes just after the string, and the arrow is a left arrow.
34 // <length> is the length of the token in runes, <token type> is one
35 // of the supported semantic token types, and <modifiers. is a
36 // (possibly empty) list of token type modifiers.
38 // There are 3 coordinate systems for lines and character offsets in lines
39 // LSP (what's returned from semanticTokens()):
40 // 0-based: the first line is line 0, the first character of a line
41 // is character 0, and characters are counted as UTF-16 code points
42 // gopls (and Go error messages):
43 // 1-based: the first line is line1, the first chararcter of a line
44 // is character 0, and characters are counted as bytes
45 // internal (as used in marks, and lines:=bytes.Split(buf, '\n'))
46 // 0-based: lines and character positions are 1 less than in
47 // the gopls coordinate system
53 var colmap *protocol.ColumnMapper
55 func (c *semtok) Name() string { return "semtok" }
56 func (c *semtok) Usage() string { return "<filename>" }
57 func (c *semtok) ShortHelp() string { return "show semantic tokens for the specified file" }
58 func (c *semtok) DetailedHelp(f *flag.FlagSet) {
60 _, f, l, ok := runtime.Caller(i)
64 log.Printf("%d: %s:%d", i, f, l)
66 fmt.Fprint(f.Output(), `
67 Example: show the semantic tokens for this file:
69 $ gopls semtok internal/lsp/cmd/semtok.go
74 // Run performs the semtok on the files specified by args and prints the
75 // results to stdout in the format described above.
76 func (c *semtok) Run(ctx context.Context, args ...string) error {
78 return fmt.Errorf("expected one file name, got %d", len(args))
80 // perhaps simpler if app had just had a FlagSet member
81 origOptions := c.app.options
82 c.app.options = func(opts *source.Options) {
84 opts.SemanticTokens = true
86 conn, err := c.app.connect(ctx)
90 defer conn.terminate(ctx)
91 uri := span.URIFromPath(args[0])
92 file := conn.AddFile(ctx, uri)
97 resp, err := conn.semanticTokens(ctx, uri)
101 buf, err := ioutil.ReadFile(args[0])
105 fset := token.NewFileSet()
106 f, err := parser.ParseFile(fset, args[0], buf, 0)
108 log.Printf("parsing %s failed %v", args[0], err)
111 tok := fset.File(f.Pos())
113 // can't happen; just parsed this file
114 return fmt.Errorf("can't find %s in fset", args[0])
116 tc := span.NewContentConverter(args[0], buf)
117 colmap = &protocol.ColumnMapper{
118 URI: span.URI(args[0]),
122 err = decorate(file.uri.Filename(), resp.Data)
130 line, offset int // 1-based, from RangeSpan
131 len int // bytes, not runes
136 // prefixes for semantic token comments
139 SemanticRight = "/*⇒"
142 func markLine(m mark, lines [][]byte) {
143 l := lines[m.line-1] // mx is 1-based
144 length := utf8.RuneCount(l[m.offset-1 : m.offset-1+m.len])
145 splitAt := m.offset - 1
147 if m.typ == "namespace" && m.offset-1+m.len < len(l) && l[m.offset-1+m.len] == '"' {
148 // it is the last component of an import spec
149 // cannot put a comment inside a string
150 insert = fmt.Sprintf("%s%d,namespace,[]*/", SemanticLeft, length)
151 splitAt = m.offset + m.len
153 // be careful not to generate //*
155 if splitAt-1 >= 0 && l[splitAt-1] == '/' {
158 insert = fmt.Sprintf("%s%s%d,%s,%v*/", spacer, SemanticRight, length, m.typ, m.mods)
160 x := append([]byte(insert), l[splitAt:]...)
161 l = append(l[:splitAt], x...)
165 func decorate(file string, result []uint32) error {
166 buf, err := ioutil.ReadFile(file)
170 marks := newMarks(result)
174 lines := bytes.Split(buf, []byte{'\n'})
175 for i := len(marks) - 1; i >= 0; i-- {
179 os.Stdout.Write(bytes.Join(lines, []byte{'\n'}))
183 func newMarks(d []uint32) []mark {
185 // the following two loops could be merged, at the cost
186 // of making the logic slightly more complicated to understand
187 // first, convert from deltas to absolute, in LSP coordinates
188 lspLine := make([]uint32, len(d)/5)
189 lspChar := make([]uint32, len(d)/5)
190 var line, char uint32
191 for i := 0; 5*i < len(d); i++ {
192 lspLine[i] = line + d[5*i+0]
196 lspChar[i] = char + d[5*i+1]
200 // second, convert to gopls coordinates
201 for i := 0; 5*i < len(d); i++ {
202 pr := protocol.Range{
203 Start: protocol.Position{
205 Character: lspChar[i],
207 End: protocol.Position{
209 Character: lspChar[i] + d[5*i+2],
212 spn, err := colmap.RangeSpan(pr)
217 line: spn.Start().Line(),
218 offset: spn.Start().Column(),
219 len: spn.End().Column() - spn.Start().Column(),
220 typ: lsp.SemType(int(d[5*i+3])),
221 mods: lsp.SemMods(int(d[5*i+4])),