Debian Codegraph @

gopls/internal/test/marker/doc.go

raw symbols SCIP
1 // Copyright 2023 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 /*
6 Package marker defines a framework for running "marker" tests, each
7 defined by a file in the testdata subdirectory.
8
9 Use this command to run the tests, from the gopls module:
10
11 $ go test ./internal/test/marker [-update]
12
13 A marker test uses the '//@' syntax of the x/tools/internal/expect package to
14 annotate source code with various information such as locations and arguments
15 of LSP operations to be executed by the test. The syntax following '@' is
16 parsed as a comma-separated list of Go-like function calls, which we refer to
17 as 'markers' (or sometimes 'marks'), for example
18
19 //@ foo(a, "b", 3), bar(0)
20
21 Unlike ordinary Go, the marker syntax also supports optional named arguments
22 using the syntax name=value. If provided, named arguments must appear after all
23 positional arguments, though their ordering with respect to other named
24 arguments does not matter. For example
25
26 //@ foo(a, "b", d=4, c=3)
27
28 Each marker causes a corresponding function to be called in the test. Some
29 markers are declarations; for example, @loc declares a name for a source
30 location. Others have effects, such as executing an LSP operation and asserting
31 that it behaved as expected. See the Marker types documentation below for the
32 list of all supported markers.
33
34 Each call argument is converted to the type of the corresponding parameter of
35 the designated function. The conversion logic may use the surrounding context,
36 such as the position or nearby text. See the Argument conversion section below
37 for the full set of special conversions. As a special case, the blank
38 identifier '_' is treated as the zero value of the parameter type.
39
40 The test runner collects test cases by searching the given directory for
41 files with the .txt extension. Each file is interpreted as a txtar archive,
42 which is extracted to a temporary directory. The relative path to the .txt
43 file is used as the subtest name. The preliminary section of the file
44 (before the first archive entry) is a free-form comment.
45
46 # Special files
47
48 There are several types of file within the test archive that are given special
49 treatment by the test runner:
50
51 - "skip": the presence of this file causes the test to be skipped, with
52 its content used as the skip message.
53
54 - "flags": this file is treated as a whitespace-separated list of flags
55 that configure the MarkerTest instance. Supported flags:
56
57 -{min,max}_go=go1.20 sets the {min,max}imum Go runtime version for the test
58 (inclusive).
59 -{min,max}_go_command=go1.20 sets the {min,max}imum Go command version for
60 the test (inclusive).
61 -cgo requires that CGO_ENABLED is set and the cgo tool is available.
62 -write_sumfile=a,b,c instructs the test runner to generate go.sum files
63 in these directories before running the test.
64 -skip_goos=a,b,c instructs the test runner to skip the test for the
65 listed GOOS values.
66 -skip_goarch=a,b,c does the same for GOARCH.
67 TODO(rfindley): using build constraint expressions for -skip_go{os,arch} would
68 be clearer.
69 -ignore_extra_diags suppresses errors for unmatched diagnostics
70 -filter_builtins=false disables the filtering of builtins from
71 completion results.
72 -filter_keywords=false disables the filtering of keywords from
73 completion results.
74 -errors_ok=true suppresses errors for Error level log entries.
75
76 TODO(rfindley): support flag values containing whitespace.
77
78 - "settings.json": this file is parsed as JSON, and used as the
79 session configuration (see gopls/doc/settings.md)
80
81 - "capabilities.json": this file is parsed as JSON client capabilities,
82 and applied as an overlay over the default editor client capabilities.
83 see https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#clientCapabilities
84 for more details.
85
86 - "env": this file is parsed as a list of VAR=VALUE fields specifying the
87 editor environment.
88
89 - Golden files: Within the archive, file names starting with '@' are
90 treated as "golden" content, and are not written to disk, but instead are
91 made available to test methods expecting an argument of type *Golden,
92 using the identifier following '@'. For example, if the first parameter of
93 Foo were of type *Golden, the test runner would convert the identifier a
94 in the call @foo(a, "b", 3) into a *Golden by collecting golden file
95 data starting with "@a/". As a special case, for tests that only need one
96 golden file, the data contained in the file "@a" is indexed in the *Golden
97 value by the empty string "".
98
99 - proxy files: any file starting with proxy/ is treated as a Go proxy
100 file. If present, these files are written to a separate temporary
101 directory and GOPROXY is set to file://<proxy directory>.
102
103 # Marker types
104
105 Markers are of two kinds: "value markers" and "action markers". Value markers
106 are processed in a first pass, and define named values that may be referred to
107 as arguments to action markers. For example, the @loc marker defines a named
108 location that may be used wherever a location is expected. Value markers cannot
109 refer to names defined by other value markers. Action markers are processed in
110 a second pass and perform some action such as testing an LSP operation.
111
112 Below, we list supported markers using function signatures, augmented with the
113 named argument support name=value, as described above. The types referred to in
114 the signatures below are described in the Argument conversion section.
115
116 Here is the list of supported value markers:
117
118 - loc(name, location): specifies the name for a location in the source. These
119 locations may be referenced by other markers. Naturally, the location
120 argument may be specified only as a string or regular expression in the
121 first pass.
122 The predeclared locations BUILTIN and UNSAFE match any location in the
123 GOROOT/src/{builtin/builtin,unsafe/unsafe}.go file, regardless of GOROOT.
124
125 - defloc(name, location): performs a textDocument/definition request at the
126 src location, and binds the result to the given name. This may be used to
127 refer to positions in the standard library.
128
129 - hiloc(name, location, kind): defines a documentHighlight value of the
130 given location and kind. Use its label in a @highlightall marker to
131 indicate the expected result of a highlight query.
132
133 - item(name, details, kind): defines a completionItem with the provided
134 fields. This information is not positional, and therefore @item markers
135 may occur anywhere in the source. Use in conjunction with @complete,
136 @snippet, or @rank.
137
138 TODO(rfindley): rethink whether floating @item annotations are the best
139 way to specify completion results.
140
141 Here is the list of supported action markers:
142
143 - acceptcompletion(location, label, golden): specifies that accepting the
144 completion candidate produced at the given location with provided label
145 results in the given golden state.
146
147 - codeaction(start location, kind string, diag=regexp, end=location, action=golden, edit=golden, result=golden, err=stringMatcher, answers=string)
148
149 Specifies a code action to request at the location, with given kind.
150 If diag is set, the code action must be associated with the given
151 diagnostic.
152 If end is set, the location is defined to be between start.Start and
153 end.End.
154 If answers is set, it is a JSON string mapping form field IDs to their
155 respective answer values (e.g. answers=`{"tags":"xml"}`), representing the
156 user's response to interactive refactoring dialogs.
157
158 Exactly one of action, edit, result, or err must be set:
159 If action is set, it is a golden reference to a JSON blob representing the
160 resolved code action, which is not applied.
161 If edit is set, it is a golden reference to the edits resulting from the
162 code action.
163 If result is set, it is a golden reference to the full set of changed files
164 resulting from the code action.
165 If err is set, it is expected to match the error resulting from applying
166 the code action.
167
168 - codelens(location, title): specifies that a codelens is expected at the
169 given location, with given title. Must be used in conjunction with
170 @codelenses.
171
172 - codelenses(): specifies that textDocument/codeLens should be run for the
173 current document, with results compared to the @codelens annotations in
174 the current document.
175
176 - complete(location, ...items): specifies expected completion results at
177 the given location. Must be used in conjunction with @item.
178
179 - diag(location, regexp, exact=bool): specifies an expected diagnostic
180 matching the given regexp at the given location. The test runner requires a
181 1:1 correspondence between observed diagnostics and diag annotations. The
182 diagnostics source and kind fields are ignored, to reduce fuss.
183
184 The specified location must match the start position of the diagnostic,
185 but end positions are ignored unless exact=true.
186
187 TODO(adonovan): in the older marker framework, the annotation asserted two
188 additional fields (source="compiler", kind="error"). Restore them using
189 optional named arguments.
190
191 - def(src, want ...location): performs a textDocument/definition request at
192 the src location, and checks that the resulting set of locations matches want.
193
194 - documentLink(golden): asserts that textDocument/documentLink returns
195 links as described by the golden file.
196
197 - foldingrange(golden): performs a textDocument/foldingRange for the
198 current document, and compare with the golden content, which is the
199 original source annotated with numbered tags delimiting the resulting
200 ranges (e.g. <1 kind="..."> ... </1>).
201
202 - format(golden): performs a textDocument/format request for the enclosing
203 file, and compare against the named golden file. If the formatting
204 request succeeds, the golden file must contain the resulting formatted
205 source. If the formatting request fails, the golden file must contain
206 the error message.
207
208 - highlightall(all ...documentHighlight): makes a textDocument/highlight
209 request at each location in "all" and checks that the result is "all".
210 In other words, given highlightall(X1, X2, ..., Xn), it checks that
211 highlight(X1) = highlight(X2) = ... = highlight(Xn) = {X1, X2, ..., Xn}.
212 In general, highlight sets are not equivalence classes; for asymmetric
213 cases, use @highlight instead.
214 Each element of "all" is the label of a @hiloc marker.
215
216 - highlight(src location, dsts ...documentHighlight): makes a
217 textDocument/highlight request at the given src location, which should
218 highlight the provided dst locations and kinds.
219
220 - hover(src, dst location, sm stringMatcher): performs a textDocument/hover
221 at the src location, and checks that the result is the dst location, with
222 matching hover content. Be careful to avoid self-satisfying hover markers:
223 if the hover content literally includes the marker comment itself,
224 it will always contain the expected string! A backslash escape may help.
225
226 - hovererr(src, sm stringMatcher): performs a textDocument/hover at the src
227 location, and checks that the error matches the given stringMatcher.
228
229 - implementation(src location, want ...location, err=stringMatcher):
230 makes a textDocument/implementation query at the src location and
231 checks that the resulting set of locations matches want. If err is
232 set, the implementation query must fail with the expected error.
233
234 - incomingcalls(src location, want ...location): makes a
235 callHierarchy/incomingCalls query at the src location, and checks that
236 the set of call.From locations matches want.
237 (These locations are the declarations of the functions enclosing
238 the calls, not the calls themselves.)
239
240 - outgoingcalls(src location, want ...location): makes a
241 callHierarchy/outgoingCalls query at the src location, and checks that
242 the set of call.To locations matches want.
243
244 - preparerename(src location, placeholder string, span=location): asserts
245 that a textDocument/prepareRename request at the src location has the given
246 placeholder text. If present, the optional span argument is verified to be
247 the span of the prepareRename result. If placeholder is "", this is treated
248 as a negative assertion and prepareRename should return nil.
249
250 - quickfix(location, regexp, golden): like diag, the location and
251 regexp identify an expected diagnostic, which must have exactly one
252 associated "quickfix" code action.
253 This action is executed for its editing effects on the source files.
254 Like rename, the golden directory contains the expected transformed files.
255
256 - quickfixerr(location, regexp, wantError): specifies that the
257 quickfix operation should fail with an error that matches the expectation.
258 (Failures in the computation to offer a fix do not generally result
259 in LSP errors, so this marker is not appropriate for testing them.)
260
261 - rank(location, ...string OR completionItem): executes a
262 textDocument/completion request at the given location, and verifies that
263 each expected completion item occurs in the results, in the expected order.
264 Items may be specified as string literal completion labels, or as
265 references to a completion item created with the @item marker.
266 Other unexpected completion items are allowed to occur in the results, and
267 are ignored. A "!" prefix on a label asserts that the symbol is not a
268 completion candidate.
269
270 - refs(location, want ...location): executes a textDocument/references request
271 at the first location and asserts that the resulting set of locations
272 matches want. The first want location must be the declaration (assumedly
273 unique).
274
275 - rename(location, new, golden): specifies a renaming of the
276 identifier at the specified location to the new name.
277 The golden directory contains the transformed files.
278
279 - renameerr(location, new, wantError): specifies a renaming that
280 fails with an error that matches the expectation.
281
282 - signature(location, label, active): specifies that
283 signatureHelp at the given location should match the provided string, with
284 the active parameter (an index) highlighted.
285
286 - snippet(location, string OR completionItem, snippet): executes a
287 textDocument/completion request at the location, and searches for a result
288 with label matching that its second argument, which may be a string literal
289 or a reference to a completion item created by the @item marker (in which
290 case the item's label is used). It checks that the resulting snippet
291 matches the provided snippet.
292
293 - subtypes (src location, want ...location),
294 supertypes(src location, want ...location):
295 execute a textDocument/prepareTypeHierarchy request at the src
296 location, followed by a typeHierarchy/{sub,super}types request on
297 the first response, and check that the result contains the list
298 of wanted locations in order.
299
300 - symbol(golden): makes a textDocument/documentSymbol request
301 for the enclosing file, formats the response with one symbol
302 per line, sorts it, and compares against the named golden file.
303 Each line is of the form:
304
305 dotted.symbol.name kind "detail" +n lines
306
307 where the "+n lines" part indicates that the declaration spans
308 several lines. The test otherwise makes no attempt to check
309 location information. There is no point to using more than one
310 @symbol marker in a given file.
311
312 - token(location, tokenType, mod): makes a textDocument/semanticTokens/range
313 request at the given location, and asserts that the result includes
314 exactly one token with the given token type and modifier string.
315
316 - typedef(src, want ...location, err=stringMatcher): performs a
317 textDocument/typeDefinition request at the src location, and checks that the
318 resulting set of locations matches want. If err is set, the type definition
319 query must fail with the expected error.
320
321 - workspacesymbol(query, golden): makes a workspace/symbol request for the
322 given query, formats the response with one symbol per line, and compares
323 against the named golden file. As workspace symbols are by definition a
324 workspace-wide request, the location of the workspace symbol marker does
325 not matter. Each line is of the form:
326
327 location name kind
328
329 - mcptool(name string, arg string, location=location, output=golden):
330 Executes an MCP tool call using the provided tool name and args (a
331 JSON-encoded value). Any string or []string values in the JSON input object
332 are modified to replace the substring '$WORKDIR' with the actual working
333 directory of the test. Furthermore, if 'location' is provided, it is used
334 to populate the 'location' property of the JSON input with the given LSP
335 source location. The test then asserts that the MCP server's response
336 matches the content of the golden file identified by output. For
337 portability, all filepath separators in the output are normalized to '/',
338 even if they occur outside of a path context.
339
340 # Expected locations
341 Marker tests that compare expected sets of locations (e.g. def, refs) only check
342 for set equality, so the order and cardinality of locations does not matter. Of
343 all markers that specify expected locations, only subtypes and supertypes check
344 for order.
345
346 # Argument conversion
347
348 Marker arguments are first parsed by the internal/expect package, which accepts
349 the following tokens as defined by the Go spec:
350 - string, int64, float64, and rune literals
351 - true and false
352 - nil
353 - identifiers (type expect.Identifier)
354 - regular expressions, denoted the two tokens re"abc" (type *regexp.Regexp)
355
356 These values are passed as arguments to the corresponding parameter of the
357 test function. Additional value conversions may occur for these argument ->
358 parameter type pairs:
359
360 - string->regexp: the argument is parsed as a regular expressions.
361
362 - string->location: the argument is converted to the location of the first
363 instance of the argument in the file content starting from the beginning of
364 the line containing the note. Multi-line matches are permitted, but the
365 match must begin before the note.
366
367 - regexp->location: the argument is converted to the location of the first
368 match for the argument in the file content starting from the beginning of
369 the line containing the note. Multi-line matches are permitted, but the
370 match must begin before the note. If the regular expression contains
371 exactly one subgroup, the position of the subgroup is used rather than the
372 position of the submatch.
373
374 - name->location: the argument is replaced by the named location.
375
376 - name->Golden: the argument is used to look up golden content prefixed by
377 @<argument>.
378
379 - {string,regexp,identifier}->stringMatcher: a stringMatcher type
380 specifies an expected string, either in the form of a substring
381 that must be present, a regular expression that it must match, or an
382 identifier (e.g. foo) such that the archive entry @foo exists and
383 contains the exact expected string.
384 stringMatchers are used by some markers to match positive results
385 (outputs) and by other markers to match error messages.
386
387 # Example
388
389 Here is a complete example:
390
391 This test checks hovering over constants.
392
393 -- a.go --
394 package a
395
396 const abc = 0x2a //@hover("b", "abc", abc),hover(" =", "abc", abc)
397
398 -- @abc --
399 ```go
400 const abc untyped int = 42
401 ```
402
403 @hover("b", "abc", abc),hover(" =", "abc", abc)
404
405 In this example, the @hover annotation tells the test runner to run the
406 hoverMarker function, which has parameters:
407
408 (mark marker, src, dst protocol.Location, g *Golden).
409
410 The first argument holds the test context, including fake editor with open
411 files, and sandboxed directory.
412
413 Argument converters translate the "b" and "abc" arguments into locations by
414 interpreting each one as a substring (or as a regular expression, if of the
415 form re"a|b") and finding the location of its first occurrence starting on the
416 preceding portion of the line, and the abc identifier into a the golden content
417 contained in the file @abc. Then the hoverMarker method executes a
418 textDocument/hover LSP request at the src position, and ensures the result
419 spans "abc", with the markdown content from @abc. (Note that the markdown
420 content includes the expect annotation as the doc comment.)
421
422 The next hover on the same line asserts the same result, but initiates the
423 hover immediately after "abc" in the source. This tests that we find the
424 preceding identifier when hovering.
425
426 # Updating golden files
427
428 To update golden content in the test archive, it is easier to regenerate
429 content automatically rather than edit it by hand. To do this, run the
430 tests with the -update flag. Only tests that actually run will be updated.
431
432 In some cases, golden content will vary by Go version (for example, gopls
433 produces different markdown at Go versions before the 1.19 go/doc update).
434 By convention, the golden content in test archives should match the output
435 at Go tip. Each test function can normalize golden content for older Go
436 versions.
437
438 Note that -update does not cause missing @diag or @loc markers to be added.
439
440 # TODO
441
442 - Rename the files .txtar.
443 - Eliminate all *err markers, preferring named arguments.
444 - In failed assertions, display locations using symbolic @loc names where available.
445 */
446 package marker