Debian Codegraph @

gopls/internal/cmd/semantictokens.go

raw symbols SCIP
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.
4
5 package cmd
6
7 import (
8 "bytes"
9 "context"
10 "flag"
11 "fmt"
12 "log"
13 "os"
14 "slices"
15 "unicode/utf8"
16
17 "golang.org/x/tools/gopls/internal/protocol"
18 "golang.org/x/tools/gopls/internal/protocol/semtok"
19 "golang.org/x/tools/gopls/internal/settings"
20 )
21
22 // generate semantic tokens and interpolate them in the file
23
24 // The output is the input file decorated with comments showing the
25 // syntactic tokens. The comments are stylized:
26 // /*<arrow><length>,<token type>,[<modifiers]*/
27 // For most occurrences, the comment comes just before the token it
28 // describes, and arrow is a right arrow. If the token is inside a string
29 // the comment comes just after the string, and the arrow is a left arrow.
30 // <length> is the length of the token in runes, <token type> is one
31 // of the supported semantic token types, and <modifiers. is a
32 // (possibly empty) list of token type modifiers.
33
34 // There are 3 coordinate systems for lines and character offsets in lines
35 // LSP (what's returned from semanticTokens()):
36 // 0-based: the first line is line 0, the first character of a line
37 // is character 0, and characters are counted as UTF-16 code points
38 // gopls (and Go error messages):
39 // 1-based: the first line is line1, the first character of a line
40 // is character 0, and characters are counted as bytes
41 // internal (as used in marks, and lines:=bytes.Split(buf, '\n'))
42 // 0-based: lines and character positions are 1 less than in
43 // the gopls coordinate system
44
45 type semanticToken struct {
46 app *Application
47 }
48
49 func (c *semanticToken) Name() string { return "semtok" }
50 func (c *semanticToken) Parent() string { return c.app.Name() }
51 func (c *semanticToken) Usage() string { return "<filename>" }
52 func (c *semanticToken) ShortHelp() string { return "show semantic tokens for the specified file" }
53 func (c *semanticToken) DetailedHelp(f *flag.FlagSet) {
54 fmt.Fprint(f.Output(), `
55 Example: show the semantic tokens for this file:
56
57 $ gopls semtok internal/cmd/semtok.go
58 `)
59 printFlagDefaults(f)
60 }
61
62 // Run performs the semtok on the files specified by args and prints the
63 // results to stdout in the format described above.
64 func (c *semanticToken) Run(ctx context.Context, args ...string) error {
65 if len(args) != 1 {
66 return fmt.Errorf("expected one file name, got %d", len(args))
67 }
68 // perhaps simpler if app had just had a FlagSet member
69 origOptions := c.app.options
70 c.app.options = func(opts *settings.Options) {
71 if origOptions != nil {
72 origOptions(opts)
73 }
74 opts.SemanticTokens = true
75 }
76 cli, _, err := c.app.connect(ctx)
77 if err != nil {
78 return err
79 }
80 defer cli.terminate(ctx)
81 uri := protocol.URIFromPath(args[0])
82 file, err := cli.openFile(ctx, uri)
83 if err != nil {
84 return err
85 }
86
87 lines := bytes.Split(file.mapper.Content, []byte{'\n'})
88 params := &protocol.SemanticTokensRangeParams{
89 TextDocument: protocol.TextDocumentIdentifier{
90 URI: uri,
91 },
92 Range: protocol.Range{Start: protocol.Position{Line: 0, Character: 0},
93 End: protocol.Position{
94 Line: uint32(len(lines) - 1),
95 Character: uint32(len(lines[len(lines)-1]))},
96 },
97 }
98 resp, err := cli.server.SemanticTokensRange(ctx, params) // use Range to avoid limits on Full
99 if err != nil {
100 return err
101 }
102 legend := cli.initializeResult.Capabilities.SemanticTokensProvider.(protocol.SemanticTokensOptions).Legend
103 return decorate(legend, file, resp.Data)
104 }
105
106 // mark provides a human-readable representation of protocol.SemanticTokens.
107 // It translates token types and modifiers to strings instead of uint32 values.
108 type mark struct {
109 line, offset int // 1-based, from RangeSpan
110 len int // bytes, not runes
111 typ semtok.Type
112 mods []semtok.Modifier
113 }
114
115 // prefixes for semantic token comments
116 const (
117 SemanticLeft = "/*⇐"
118 SemanticRight = "/*⇒"
119 )
120
121 func markLine(m mark, lines [][]byte) {
122 l := lines[m.line-1] // mx is 1-based
123 length := utf8.RuneCount(l[m.offset-1 : m.offset-1+m.len])
124 splitAt := m.offset - 1
125 insert := ""
126 if m.typ == "namespace" && m.offset-1+m.len < len(l) && l[m.offset-1+m.len] == '"' {
127 // it is the last component of an import spec
128 // cannot put a comment inside a string
129 insert = fmt.Sprintf("%s%d,namespace,[]*/", SemanticLeft, length)
130 splitAt = m.offset + m.len
131 } else {
132 // be careful not to generate //*
133 spacer := ""
134 if splitAt-1 >= 0 && l[splitAt-1] == '/' {
135 spacer = " "
136 }
137 insert = fmt.Sprintf("%s%s%d,%s,%v*/", spacer, SemanticRight, length, m.typ, m.mods)
138 }
139 x := append([]byte(insert), l[splitAt:]...)
140 l = append(l[:splitAt], x...)
141 lines[m.line-1] = l
142 }
143
144 // decorate translates semantic token data (protocol.SemanticTokens) from its
145 // raw []uint32 format into a human-readable representation and prints it to stdout.
146 func decorate(legend protocol.SemanticTokensLegend, file *cmdFile, data []uint32) error {
147 marks := newMarks(legend, file, data)
148 if len(marks) == 0 {
149 return nil
150 }
151 lines := bytes.Split(file.mapper.Content, []byte{'\n'})
152 for _, mark := range slices.Backward(marks) {
153 markLine(mark, lines)
154 }
155 os.Stdout.Write(bytes.Join(lines, []byte{'\n'}))
156 return nil
157 }
158
159 func newMarks(legend protocol.SemanticTokensLegend, file *cmdFile, data []uint32) []mark {
160 ans := []mark{}
161 // the following two loops could be merged, at the cost
162 // of making the logic slightly more complicated to understand
163 // first, convert from deltas to absolute, in LSP coordinates
164 lspLine := make([]uint32, len(data)/5)
165 lspChar := make([]uint32, len(data)/5)
166 var line, char uint32
167 for i := 0; 5*i < len(data); i++ {
168 lspLine[i] = line + data[5*i+0]
169 if data[5*i+0] > 0 {
170 char = 0
171 }
172 lspChar[i] = char + data[5*i+1]
173 char = lspChar[i]
174 line = lspLine[i]
175 }
176 // second, convert to gopls coordinates
177 for i := 0; 5*i < len(data); i++ {
178 pr := protocol.Range{
179 Start: protocol.Position{
180 Line: lspLine[i],
181 Character: lspChar[i],
182 },
183 End: protocol.Position{
184 Line: lspLine[i],
185 Character: lspChar[i] + data[5*i+2],
186 },
187 }
188 spn, err := file.rangeSpan(pr)
189 if err != nil {
190 log.Fatal(err)
191 }
192
193 var mods []semtok.Modifier
194 {
195 n := int(data[5*i+4])
196 for i, mod := range legend.TokenModifiers {
197 if (n & (1 << i)) != 0 {
198 mods = append(mods, semtok.Modifier(mod))
199 }
200 }
201 }
202
203 m := mark{
204 line: spn.Start().Line(),
205 offset: spn.Start().Column(),
206 len: spn.End().Column() - spn.Start().Column(),
207 typ: semtok.Type(legend.TokenTypes[data[5*i+3]]),
208 mods: mods,
209 }
210 ans = append(ans, m)
211 }
212 return ans
213 }