Debian Codegraph @

gopls/internal/test/marker/marker_test.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 package marker
6
7 // This file defines the marker test framework.
8 // See doc.go for extensive documentation.
9
10 import (
11 "bytes"
12 "context"
13 "encoding/json"
14 "flag"
15 "fmt"
16 "go/token"
17 "go/types"
18 "io/fs"
19 "log"
20 "net/http/httptest"
21 "os"
22 "path"
23 "path/filepath"
24 "reflect"
25 "regexp"
26 "runtime"
27 "slices"
28 "sort"
29 "strings"
30 "testing"
31
32 "github.com/google/go-cmp/cmp"
33 "github.com/google/go-cmp/cmp/cmpopts"
34 "github.com/modelcontextprotocol/go-sdk/mcp"
35 "golang.org/x/tools/gopls/internal/cache"
36 "golang.org/x/tools/gopls/internal/debug"
37 "golang.org/x/tools/gopls/internal/lsprpc"
38 internalmcp "golang.org/x/tools/gopls/internal/mcp"
39 "golang.org/x/tools/gopls/internal/protocol"
40 "golang.org/x/tools/gopls/internal/test/compare"
41 "golang.org/x/tools/gopls/internal/test/integration"
42 "golang.org/x/tools/gopls/internal/test/integration/fake"
43 "golang.org/x/tools/gopls/internal/util/bug"
44 "golang.org/x/tools/gopls/internal/util/safetoken"
45 "golang.org/x/tools/internal/diff"
46 "golang.org/x/tools/internal/expect"
47 "golang.org/x/tools/internal/gocommand"
48 "golang.org/x/tools/internal/jsonrpc2"
49 "golang.org/x/tools/internal/jsonrpc2/servertest"
50 "golang.org/x/tools/internal/testenv"
51 "golang.org/x/tools/txtar"
52 )
53
54 var update = flag.Bool("update", false, "if set, update test data during marker tests")
55
56 func TestMain(m *testing.M) {
57 // golang/go#54461: enable additional debugging around hanging Go commands.
58 gocommand.DebugHangingGoCommands = true
59
60 bug.PanicOnBugs = true
61 testenv.ExitIfSmallMachine()
62 // Disable GOPACKAGESDRIVER, as it can cause spurious test failures.
63 os.Setenv("GOPACKAGESDRIVER", "off") // ignore error
64 integration.FilterToolchainPathAndGOROOT()
65 os.Exit(m.Run())
66 }
67
68 // Test runs the marker tests from the testdata directory.
69 //
70 // See package documentation for details on how marker tests work.
71 //
72 // These tests were inspired by (and in many places copied from) a previous
73 // iteration of the marker tests built on top of the packagestest framework.
74 // Key design decisions motivating this reimplementation are as follows:
75 // - The old tests had a single global session, causing interaction at a
76 // distance and several awkward workarounds.
77 // - The old tests could not be safely parallelized, because certain tests
78 // manipulated the server options
79 // - Relatedly, the old tests did not have a logic grouping of assertions into
80 // a single unit, resulting in clusters of files serving clusters of
81 // entangled assertions.
82 // - The old tests used locations in the source as test names and as the
83 // identity of golden content, meaning that a single edit could change the
84 // name of an arbitrary number of subtests, and making it difficult to
85 // manually edit golden content.
86 // - The old tests did not hew closely to LSP concepts, resulting in, for
87 // example, each marker implementation doing its own position
88 // transformations, and inventing its own mechanism for configuration.
89 // - The old tests had an ad-hoc session initialization process. The integration
90 // test environment has had more time devoted to its initialization, and has a
91 // more convenient API.
92 // - The old tests lacked documentation, and often had failures that were hard
93 // to understand. By starting from scratch, we can revisit these aspects.
94 func Test(t *testing.T) {
95 if testing.Short() {
96 builder := os.Getenv("GO_BUILDER_NAME")
97 // Note that HasPrefix(builder, "darwin-" only matches legacy builders.
98 // LUCI builder names start with x_tools-goN.NN.
99 // We want to exclude solaris on both legacy and LUCI builders, as
100 // it is timing out.
101 if strings.HasPrefix(builder, "darwin-") || strings.Contains(builder, "solaris") {
102 t.Skip("golang/go#64473: skipping with -short: this test is too slow on darwin and solaris builders")
103 }
104 if strings.HasSuffix(builder, "freebsd-amd64-race") {
105 t.Skip("golang/go#71731: the marker tests are too slow to run on the amd64-race builder")
106 }
107 }
108 // The marker tests must be able to run go/packages.Load.
109 testenv.NeedsGoPackages(t)
110
111 const dir = "testdata"
112 tests, err := loadMarkerTests(dir)
113 if err != nil {
114 t.Fatal(err)
115 }
116
117 // Opt: use a shared cache.
118 cache := cache.New(nil)
119
120 for _, test := range tests {
121 t.Run(test.name, func(t *testing.T) {
122 t.Parallel()
123
124 if test.skipReason != "" {
125 t.Skip(test.skipReason)
126 }
127 if slices.Contains(test.skipGOOS, runtime.GOOS) {
128 t.Skipf("skipping on %s due to -skip_goos", runtime.GOOS)
129 }
130 if slices.Contains(test.skipGOARCH, runtime.GOARCH) {
131 t.Skipf("skipping on %s due to -skip_goarch", runtime.GOARCH)
132 }
133
134 // TODO(rfindley): it may be more useful to have full support for build
135 // constraints.
136 if test.minGoVersion != "" {
137 var go1point int
138 if _, err := fmt.Sscanf(test.minGoVersion, "go1.%d", &go1point); err != nil {
139 t.Fatalf("parsing -min_go version: %v", err)
140 }
141 testenv.NeedsGo1Point(t, go1point)
142 }
143 if test.maxGoVersion != "" {
144 // A max Go version may be useful when (e.g.) a recent go/types
145 // fix makes it impossible to reproduce a certain older crash.
146 var go1point int
147 if _, err := fmt.Sscanf(test.maxGoVersion, "go1.%d", &go1point); err != nil {
148 t.Fatalf("parsing -max_go version: %v", err)
149 }
150 testenv.SkipAfterGo1Point(t, go1point)
151 }
152 if test.minGoCommandVersion != "" {
153 var go1point int
154 if _, err := fmt.Sscanf(test.minGoCommandVersion, "go1.%d", &go1point); err != nil {
155 t.Fatalf("parsing -min_go_command version: %v", err)
156 }
157 testenv.NeedsGoCommand1Point(t, go1point)
158 }
159 if test.maxGoCommandVersion != "" {
160 var go1point int
161 if _, err := fmt.Sscanf(test.maxGoCommandVersion, "go1.%d", &go1point); err != nil {
162 t.Fatalf("parsing -max_go_command version: %v", err)
163 }
164 testenv.SkipAfterGoCommand1Point(t, go1point)
165 }
166 if test.cgo {
167 if os.Getenv("CGO_ENABLED") == "0" {
168 // NeedsTool causes the test to fail if cgo is available but disabled
169 // on the current platform through the environment. I'm not sure why it
170 // behaves this way, but if CGO_ENABLED=0 is set, we want to skip.
171 t.Skip("skipping due to CGO_ENABLED=0")
172 }
173 testenv.NeedsTool(t, "cgo")
174 }
175
176 config := fake.EditorConfig{
177 Settings: test.settings,
178 CapabilitiesJSON: test.capabilities,
179 Env: test.env,
180 }
181
182 if _, ok := config.Settings["diagnosticsDelay"]; !ok {
183 if config.Settings == nil {
184 config.Settings = make(map[string]any)
185 }
186 config.Settings["diagnosticsDelay"] = "10ms"
187 }
188
189 // inv: config.Settings != nil
190
191 run := &markerTestRun{
192 test: test,
193 env: newEnv(t, cache, test.files, test.proxyFiles, test.writeGoSum, config, test.mcp),
194 settings: config.Settings,
195 values: make(map[expect.Identifier]any),
196 diags: make(map[protocol.Location][]protocol.Diagnostic),
197 extraNotes: make(map[protocol.DocumentURI]map[string][]*expect.Note),
198 }
199 defer run.env.Close()
200
201 // Support built-in pseudo-locations here.
202 // fmtLoc coerces "got" Locations to these forms
203 // so they can be compared without depending
204 // on line numbers in external files.
205 //
206 // (We could actually define "builtin:int" etc
207 // with the correct file/line/col for each
208 // builtin symbol, but that doesn't seem to be
209 // where the bugs are.)
210 run.values["BUILTIN"] = protocol.Location{
211 URI: "file:///pseudo/builtin/builtin.go",
212 }
213 run.values["UNSAFE"] = protocol.Location{
214 URI: "file:///pseudo/unsafe/unsafe.go",
215 }
216
217 // Open all files so that we operate consistently with LSP clients, and
218 // (pragmatically) so that we have a Mapper available via the fake
219 // editor.
220 //
221 // This also allows avoiding mutating the editor state in tests.
222 for file := range test.files {
223 run.env.OpenFile(file)
224 }
225
226 allDiags := make(map[string][]protocol.Diagnostic)
227 if run.env.Editor.ServerCapabilities().DiagnosticProvider != nil {
228 for name := range test.files {
229 // golang/go#53275: support pull diagnostics for go.mod and go.work
230 // files.
231 if strings.HasSuffix(name, ".go") {
232 allDiags[name] = run.env.Diagnostics(name)
233 }
234 }
235 } else {
236 // Wait for the didOpen notifications to be processed, then collect
237 // diagnostics.
238
239 run.env.AfterChange()
240 var diags map[string]*protocol.PublishDiagnosticsParams
241 run.env.AfterChange(integration.ReadAllDiagnostics(&diags))
242 for path, params := range diags {
243 allDiags[path] = params.Diagnostics
244 }
245 }
246
247 for path, diags := range allDiags {
248 uri := run.env.Sandbox.Workdir.URI(path)
249 for _, diag := range diags {
250 loc := protocol.Location{
251 URI: uri,
252 Range: protocol.Range{
253 Start: diag.Range.Start,
254 End: diag.Range.Start, // ignore end positions
255 },
256 }
257 run.diags[loc] = append(run.diags[loc], diag)
258 }
259 }
260
261 var markers []marker
262 for _, note := range test.notes {
263 mark := marker{run: run, note: note}
264 if fn, ok := valueMarkerFuncs[note.Name]; ok {
265 fn(mark)
266 } else if _, ok := actionMarkerFuncs[note.Name]; ok {
267 markers = append(markers, mark) // save for later
268 } else {
269 uri := mark.uri()
270 if run.extraNotes[uri] == nil {
271 run.extraNotes[uri] = make(map[string][]*expect.Note)
272 }
273 run.extraNotes[uri][note.Name] = append(run.extraNotes[uri][note.Name], note)
274 }
275 }
276
277 // Invoke each remaining marker in the test.
278 for _, mark := range markers {
279 actionMarkerFuncs[mark.note.Name](mark)
280 }
281
282 // Any remaining (un-eliminated) diagnostics are an error.
283 if !test.ignoreExtraDiags {
284 for loc, diags := range run.diags {
285 for _, diag := range diags {
286 // Note that loc is collapsed (start==end).
287 // For formatting, show the exact span.
288 exactLoc := protocol.Location{
289 URI: loc.URI,
290 Range: diag.Range,
291 }
292 t.Errorf("%s: unexpected diagnostic: %q", run.fmtLoc(exactLoc), diag.Message)
293 }
294 }
295 }
296
297 // TODO(rfindley): use these for whole-file marker tests.
298 for uri, extras := range run.extraNotes {
299 for name, extra := range extras {
300 if len(extra) > 0 {
301 t.Errorf("%s: %d unused %q markers", run.env.Sandbox.Workdir.URIToPath(uri), len(extra), name)
302 }
303 }
304 }
305
306 // Now that all markers have executed, check whether there where any
307 // unexpected error logs.
308 // This guards against noisiness: see golang/go#66746)
309 if !test.errorsOK {
310 run.env.AfterChange(integration.NoErrorLogs())
311 }
312
313 formatted, err := formatTest(test)
314 if err != nil {
315 t.Errorf("formatTest: %v", err)
316 } else if *update {
317 filename := filepath.Join(dir, test.name)
318 if err := os.WriteFile(filename, formatted, 0o644); err != nil {
319 t.Error(err)
320 }
321 } else if !t.Failed() {
322 // Verify that the testdata has not changed.
323 //
324 // Only check this if the test hasn't already failed, otherwise we'd
325 // report duplicate mismatches of golden data.
326 // Otherwise, verify that formatted content matches.
327 if diff := compare.NamedText("formatted", "on-disk", string(formatted), string(test.content)); diff != "" {
328 // at this point, the txtar file created by the test and the expected txtar file on the
329 // disk differ. The differences are irrelevant if they are only the contents
330 // of files from a unified diff. These files are dependent on which diff algorithm was used,
331 // so instead checkDiffs has already checked that they correctly express the difference between
332 // the test input and the test output. (If the test code uses the diff that created them, then
333 // they would not differ, but that diff algorithms has been replaced.)
334 checkDifferences(t, test.content, formatted)
335 }
336 }
337 })
338 }
339
340 if abs, err := filepath.Abs(dir); err == nil && t.Failed() {
341 t.Logf("(Filenames are relative to %s.)", abs)
342 }
343 }
344
345 // checkDifferences reports whether the txtars in result and disk
346 // differ, other than in the contents of golden files containing unified diffs
347 func checkDifferences(t *testing.T, result, disk []byte) {
348 got := txtar.Parse(result) // the computed slice of file retains the ordering in result
349 want := txtar.Parse(disk)
350 for i, tf := range got.Files {
351 if i >= len(want.Files) {
352 t.Errorf("test failed to create file %s", tf.Name)
353 continue
354 }
355 // if they are both golden files (name starts with @) and both unified diffs
356 // (both start with @@, then the difference is insignificant)
357 ff := want.Files[i]
358 if strings.HasPrefix(tf.Name, "@") && strings.HasPrefix(ff.Name, "@") && tf.Name == ff.Name &&
359 bytes.HasPrefix(tf.Data, []byte("@@")) && bytes.HasPrefix(ff.Data, []byte("@@")) {
360 continue
361 }
362 if !bytes.Equal(tf.Data, ff.Data) {
363 t.Errorf("%s differs, got:%q want:%q", tf.Name, tf.Data, ff.Data)
364 }
365 }
366 }
367
368 // A marker holds state for the execution of a single @marker
369 // annotation in the source.
370 type marker struct {
371 run *markerTestRun
372 note *expect.Note
373 }
374
375 // ctx returns the mark context.
376 func (m marker) ctx() context.Context { return m.run.env.Ctx }
377
378 // T returns the testing.TB for this mark.
379 func (m marker) T() testing.TB { return m.run.env.TB }
380
381 // server returns the LSP server for the marker test run.
382 func (m marker) editor() *fake.Editor { return m.run.env.Editor }
383
384 // server returns the LSP server for the marker test run.
385 func (m marker) server() protocol.Server { return m.run.env.Editor.Server }
386
387 // uri returns the URI of the file containing the marker.
388 func (mark marker) uri() protocol.DocumentURI {
389 return mark.run.env.Sandbox.Workdir.URI(mark.run.test.fset.File(mark.note.Pos).Name())
390 }
391
392 // document returns a protocol.TextDocumentIdentifier for the current file.
393 func (mark marker) document() protocol.TextDocumentIdentifier {
394 return protocol.TextDocumentIdentifier{URI: mark.uri()}
395 }
396
397 // path returns the relative path to the file containing the marker.
398 func (mark marker) path() string {
399 return mark.run.env.Sandbox.Workdir.RelPath(mark.run.test.fset.File(mark.note.Pos).Name())
400 }
401
402 // mapper returns a *protocol.Mapper for the current file.
403 func (mark marker) mapper() *protocol.Mapper {
404 mapper, err := mark.editor().Mapper(mark.path())
405 if err != nil {
406 mark.T().Fatalf("failed to get mapper for current mark: %v", err)
407 }
408 return mapper
409 }
410
411 // errorf reports a formatted error with a prefix indicating the position of
412 // the marker note.
413 //
414 // It formats the error message using mark.sprintf.
415 func (mark marker) errorf(format string, args ...any) {
416 mark.T().Helper()
417 msg := mark.sprintf(format, args...)
418 // TODO(adonovan): consider using fmt.Fprintf(os.Stderr)+t.Fail instead of
419 // t.Errorf to avoid reporting uninteresting positions in the Go source of
420 // the driver. However, this loses the order of stderr wrt "FAIL: TestFoo"
421 // subtest dividers.
422 mark.T().Errorf("%s: %s", mark.run.fmtPos(mark.note.Pos), msg)
423 }
424
425 // valueMarkerFunc returns a wrapper around a function that allows it to be
426 // called during the processing of value markers (e.g. @value(v, 123)) with marker
427 // arguments converted to function parameters. The provided function's first
428 // parameter must be of type 'marker', and it must return a value.
429 //
430 // Unlike action markers, which are executed for actions such as test
431 // assertions, value markers are all evaluated first, and each computes
432 // a value that is recorded by its identifier, which is the marker's first
433 // argument. These values may be referred to from an action marker by
434 // this identifier, e.g. @action(... , v, ...).
435 //
436 // For example, given a fn with signature
437 //
438 // func(mark marker, label, details, kind string) CompletionItem
439 //
440 // The result of valueMarkerFunc can associated with @item notes, and invoked
441 // as follows:
442 //
443 // //@item(FooCompletion, "Foo", "func() int", "func")
444 //
445 // The provided fn should not mutate the test environment.
446 func valueMarkerFunc(fn any) func(marker) {
447 ftype := reflect.TypeOf(fn)
448 if ftype.NumIn() == 0 || ftype.In(0) != markerType {
449 panic(fmt.Sprintf("value marker function %#v must accept marker as its first argument", ftype))
450 }
451 if ftype.NumOut() != 1 {
452 panic(fmt.Sprintf("value marker function %#v must have exactly 1 result", ftype))
453 }
454
455 return func(mark marker) {
456 if len(mark.note.Args) == 0 || !is[expect.Identifier](mark.note.Args[0]) {
457 mark.errorf("first argument to a value marker function must be an identifier")
458 return
459 }
460 id := mark.note.Args[0].(expect.Identifier)
461 if alt, ok := mark.run.values[id]; ok {
462 mark.errorf("%s already declared as %T", id, alt)
463 return
464 }
465 args := append([]any{mark}, mark.note.Args[1:]...)
466 argValues, err := convertArgs(mark, ftype, args)
467 if err != nil {
468 mark.errorf("%v", err)
469 return
470 }
471 results := reflect.ValueOf(fn).Call(argValues)
472 mark.run.values[id] = results[0].Interface()
473 }
474 }
475
476 // actionMarkerFunc returns a wrapper around a function that allows it to be
477 // called during the processing of action markers (e.g. @action("abc", 123))
478 // with marker arguments converted to function parameters. The provided
479 // function's first parameter must be of type 'marker', and it must not return
480 // any values. Any named arguments that may be used by the marker func must be
481 // listed in allowedNames.
482 //
483 // The provided fn should not mutate the test environment.
484 func actionMarkerFunc(fn any, allowedNames ...string) func(marker) {
485 ftype := reflect.TypeOf(fn)
486 if ftype.NumIn() == 0 || ftype.In(0) != markerType {
487 panic(fmt.Sprintf("action marker function %#v must accept marker as its first argument", ftype))
488 }
489 if ftype.NumOut() != 0 {
490 panic(fmt.Sprintf("action marker function %#v cannot have results", ftype))
491 }
492
493 var allowed map[string]bool
494 if len(allowedNames) > 0 {
495 allowed = make(map[string]bool)
496 for _, name := range allowedNames {
497 allowed[name] = true
498 }
499 }
500
501 return func(mark marker) {
502 for name := range mark.note.NamedArgs {
503 if !allowed[name] {
504 mark.errorf("unexpected named argument %q", name)
505 }
506 }
507
508 args := append([]any{mark}, mark.note.Args...)
509 argValues, err := convertArgs(mark, ftype, args)
510 if err != nil {
511 mark.errorf("%v", err)
512 return
513 }
514 reflect.ValueOf(fn).Call(argValues)
515 }
516 }
517
518 func convertArgs(mark marker, ftype reflect.Type, args []any) ([]reflect.Value, error) {
519 var (
520 argValues []reflect.Value
521 pnext int // next param index
522 p reflect.Type // current param
523 )
524 for i, arg := range args {
525 if i < ftype.NumIn() {
526 p = ftype.In(pnext)
527 pnext++
528 } else if p == nil || !ftype.IsVariadic() {
529 // The actual number of arguments expected by the mark varies, depending
530 // on whether this is a value marker or an action marker.
531 //
532 // Since this error indicates a bug, probably OK to have an imprecise
533 // error message here.
534 return nil, fmt.Errorf("too many arguments to %s", mark.note.Name)
535 }
536 elemType := p
537 if ftype.IsVariadic() && pnext == ftype.NumIn() {
538 elemType = p.Elem()
539 }
540 var v reflect.Value
541 if id, ok := arg.(expect.Identifier); ok && id == "_" {
542 v = reflect.Zero(elemType)
543 } else {
544 a, err := convert(mark, arg, elemType)
545 if err != nil {
546 return nil, err
547 }
548 v = reflect.ValueOf(a)
549 }
550 argValues = append(argValues, v)
551 }
552 // Check that we have sufficient arguments. If the function is variadic, we
553 // do not need arguments for the final parameter.
554 if pnext < ftype.NumIn()-1 || pnext == ftype.NumIn()-1 && !ftype.IsVariadic() {
555 // Same comment as above: OK to be vague here.
556 return nil, fmt.Errorf("not enough arguments to %s", mark.note.Name)
557 }
558 return argValues, nil
559 }
560
561 // namedArg returns the named argument for name, or the default value.
562 func namedArg[T any](mark marker, name string, dflt T) T {
563 if v, ok := mark.note.NamedArgs[name]; ok {
564 if e, ok := v.(T); ok {
565 return e
566 } else {
567 v, err := convert(mark, v, reflect.TypeOf(dflt))
568 if err != nil {
569 mark.errorf("invalid value for %q: could not convert %v (%T) to %T", name, v, v, dflt)
570 return dflt
571 }
572 return v.(T)
573 }
574 }
575 return dflt
576 }
577
578 func namedArgFunc[T any](mark marker, name string, f func(marker, any) (T, error), dflt T) T {
579 if v, ok := mark.note.NamedArgs[name]; ok {
580 if v2, err := f(mark, v); err == nil {
581 return v2
582 } else {
583 mark.errorf("invalid value for %q: %v: %v", name, v, err)
584 }
585 }
586 return dflt
587 }
588
589 // is reports whether arg is a T.
590 func is[T any](arg any) bool {
591 _, ok := arg.(T)
592 return ok
593 }
594
595 // Supported value marker functions. See [valueMarkerFunc] for more details.
596 var valueMarkerFuncs = map[string]func(marker){
597 "loc": valueMarkerFunc(locMarker),
598 "item": valueMarkerFunc(completionItemMarker),
599 "hiloc": valueMarkerFunc(highlightLocationMarker),
600 "defloc": valueMarkerFunc(defLocMarker),
601 }
602
603 // Supported action marker functions. See [actionMarkerFunc] for more details.
604 //
605 // See doc.go for marker documentation.
606 var actionMarkerFuncs = map[string]func(marker){
607 "acceptcompletion": actionMarkerFunc(acceptCompletionMarker),
608 "codeaction": actionMarkerFunc(codeActionMarker, "end", "diag", "action", "result", "edit", "err", "answers"),
609 "codelenses": actionMarkerFunc(codeLensesMarker),
610 "complete": actionMarkerFunc(completeMarker),
611 "def": actionMarkerFunc(defMarker),
612 "diag": actionMarkerFunc(diagMarker, "exact"),
613 "documentlink": actionMarkerFunc(documentLinkMarker),
614 "foldingrange": actionMarkerFunc(foldingRangeMarker),
615 "format": actionMarkerFunc(formatMarker),
616 "highlight": actionMarkerFunc(highlightMarker),
617 "highlightall": actionMarkerFunc(highlightAllMarker),
618 "hover": actionMarkerFunc(hoverMarker),
619 "hovererr": actionMarkerFunc(hoverErrMarker),
620 "implementation": actionMarkerFunc(implementationMarker, "err"),
621 "incomingcalls": actionMarkerFunc(incomingCallsMarker),
622 "inlayhints": actionMarkerFunc(inlayhintsMarker),
623 "outgoingcalls": actionMarkerFunc(outgoingCallsMarker),
624 "preparerename": actionMarkerFunc(prepareRenameMarker, "span"),
625 "rank": actionMarkerFunc(rankMarker),
626 "refs": actionMarkerFunc(refsMarker),
627 "rename": actionMarkerFunc(renameMarker),
628 "renameerr": actionMarkerFunc(renameErrMarker),
629 "selectionrange": actionMarkerFunc(selectionRangeMarker),
630 "signature": actionMarkerFunc(signatureMarker),
631 "snippet": actionMarkerFunc(snippetMarker),
632 "subtypes": actionMarkerFunc(subtypesMarker),
633 "supertypes": actionMarkerFunc(supertypesMarker),
634 "quickfix": actionMarkerFunc(quickfixMarker),
635 "quickfixerr": actionMarkerFunc(quickfixErrMarker),
636 "symbol": actionMarkerFunc(symbolMarker),
637 "token": actionMarkerFunc(tokenMarker),
638 "typedef": actionMarkerFunc(typedefMarker, "err"),
639 "workspacesymbol": actionMarkerFunc(workspaceSymbolMarker),
640 "mcptool": actionMarkerFunc(mcpToolMarker, "location", "output"),
641 }
642
643 // markerTest holds all the test data extracted from a test txtar archive.
644 //
645 // See the documentation for RunMarkerTests for more information on the archive
646 // format.
647 type markerTest struct {
648 name string // relative path to the txtar file in the testdata dir
649 fset *token.FileSet // fileset used for parsing notes
650 content []byte // raw test content
651 archive *txtar.Archive // original test archive
652 settings map[string]any // gopls settings
653 capabilities []byte // content of capabilities.json file
654 env map[string]string // editor environment
655 proxyFiles map[string][]byte // proxy content
656 files map[string][]byte // data files from the archive (excluding special files)
657 notes []*expect.Note // extracted notes from data files
658 golden map[expect.Identifier]*Golden // extracted golden content, by identifier name
659
660 skipReason string // the skip reason extracted from the "skip" archive file
661 flags []string // flags extracted from the special "flags" archive file.
662
663 // Parsed flags values. See the flag definitions below for documentation.
664 minGoVersion, maxGoVersion string // min/max version of Go runtime
665 minGoCommandVersion, maxGoCommandVersion string // min/max version of ambient go command
666
667 cgo bool
668 writeGoSum []string
669 skipGOOS []string
670 skipGOARCH []string
671 ignoreExtraDiags bool
672 filterBuiltins bool
673 filterKeywords bool
674 errorsOK bool
675 mcp bool
676 }
677
678 // flagSet returns the flagset used for parsing the special "flags" file in the
679 // test archive.
680 func (t *markerTest) flagSet() *flag.FlagSet {
681 flags := flag.NewFlagSet(t.name, flag.ContinueOnError)
682 flags.StringVar(&t.minGoVersion, "min_go", "", "if set, the minimum go1.X version required for this test")
683 flags.StringVar(&t.maxGoVersion, "max_go", "", "if set, the maximum go1.X version required for this test")
684 flags.StringVar(&t.minGoCommandVersion, "min_go_command", "", "if set, the minimum go1.X go command version required for this test")
685 flags.StringVar(&t.maxGoCommandVersion, "max_go_command", "", "if set, the maximum go1.X go command version required for this test")
686 flags.BoolVar(&t.cgo, "cgo", false, "if set, requires cgo (both the cgo tool and CGO_ENABLED=1)")
687 flags.Var((*stringListValue)(&t.writeGoSum), "write_sumfile", "if set, write the sumfile for these directories")
688 flags.Var((*stringListValue)(&t.skipGOOS), "skip_goos", "if set, skip this test on these GOOS values")
689 flags.Var((*stringListValue)(&t.skipGOARCH), "skip_goarch", "if set, skip this test on these GOARCH values")
690 flags.BoolVar(&t.ignoreExtraDiags, "ignore_extra_diags", false, "if set, suppress errors for unmatched diagnostics")
691 flags.BoolVar(&t.filterBuiltins, "filter_builtins", true, "if set, filter builtins from completion results")
692 flags.BoolVar(&t.filterKeywords, "filter_keywords", true, "if set, filter keywords from completion results")
693 flags.BoolVar(&t.errorsOK, "errors_ok", false, "if set, Error level log messages are acceptable in this test")
694 flags.BoolVar(&t.mcp, "mcp", false, "if set, enable model context protocol client and server in this test")
695 return flags
696 }
697
698 // stringListValue implements flag.Value.
699 type stringListValue []string
700
701 func (l *stringListValue) Set(s string) error {
702 if s != "" {
703 for d := range strings.SplitSeq(s, ",") {
704 *l = append(*l, strings.TrimSpace(d))
705 }
706 }
707 return nil
708 }
709
710 func (l stringListValue) String() string {
711 return strings.Join([]string(l), ",")
712 }
713
714 func (mark *marker) getGolden(id expect.Identifier) *Golden {
715 t := mark.run.test
716 golden, ok := t.golden[id]
717 // If there was no golden content for this identifier, we must create one
718 // to handle the case where -update is set: we need a place to store
719 // the updated content.
720 if !ok {
721 golden = &Golden{id: id}
722
723 // TODO(adonovan): the separation of markerTest (the
724 // static aspects) from markerTestRun (the dynamic
725 // ones) is evidently bogus because here we modify
726 // markerTest during execution. Let's merge the two.
727 t.golden[id] = golden
728 }
729 if golden.firstReference == "" {
730 golden.firstReference = mark.path()
731 }
732 return golden
733 }
734
735 // Golden holds extracted golden content for a single @<name> prefix.
736 //
737 // When -update is set, golden captures the updated golden contents for later
738 // writing.
739 type Golden struct {
740 id expect.Identifier
741 firstReference string // file name first referencing this golden content
742 data map[string][]byte // key "" => @id itself
743 updated map[string][]byte
744 }
745
746 // Get returns golden content for the given name, which corresponds to the
747 // relative path following the golden prefix @<name>/. For example, to access
748 // the content of @foo/path/to/result.json from the Golden associated with
749 // @foo, name should be "path/to/result.json".
750 //
751 // If -update is set, the given update function will be called to get the
752 // updated golden content that should be written back to testdata.
753 //
754 // Marker functions must use this method instead of accessing data entries
755 // directly otherwise the -update operation will delete those entries.
756 //
757 // TODO(rfindley): rethink the logic here. We may want to separate Get and Set,
758 // and not delete golden content that isn't set.
759 func (g *Golden) Get(t testing.TB, name string, updated []byte) ([]byte, bool) {
760 if existing, ok := g.updated[name]; ok {
761 // Multiple tests may reference the same golden data, but if they do they
762 // must agree about its expected content.
763 if diff := compare.NamedText("existing", "updated", string(existing), string(updated)); diff != "" {
764 t.Errorf("conflicting updates for golden data %s/%s:\n%s", g.id, name, diff)
765 }
766 }
767 if g.updated == nil {
768 g.updated = make(map[string][]byte)
769 }
770 g.updated[name] = updated
771 if *update {
772 return updated, true
773 }
774
775 res, ok := g.data[name]
776 return res, ok
777 }
778
779 // loadMarkerTests walks the given dir looking for .txt files, which it
780 // interprets as a txtar archive.
781 //
782 // See the documentation for RunMarkerTests for more details on the test data
783 // archive.
784 // The optional only parameter contains fragments of the test names to be loaded.
785 // If it is missing, all the tests are loaded. (Useful for faster debugging.)
786 func loadMarkerTests(dir string, only ...string) ([]*markerTest, error) {
787 var tests []*markerTest
788 var use *regexp.Regexp
789 if len(only) > 0 {
790 var err error
791 use, err = regexp.Compile(strings.Join(only, "|"))
792 if err != nil {
793 return nil, err
794 }
795 } else {
796 use = regexp.MustCompile(".")
797 }
798 err := filepath.WalkDir(dir, func(path string, _ fs.DirEntry, err error) error {
799 if strings.HasSuffix(path, ".txt") {
800 if !use.MatchString(path) {
801 return nil
802 }
803 content, err := os.ReadFile(path)
804 if err != nil {
805 return err
806 }
807
808 name := filepath.ToSlash(strings.TrimPrefix(path, dir+string(filepath.Separator)))
809 test, err := loadMarkerTest(name, content)
810 if err != nil {
811 return fmt.Errorf("%s: %v", path, err)
812 }
813 tests = append(tests, test)
814 }
815 return err
816 })
817 return tests, err
818 }
819
820 func loadMarkerTest(name string, content []byte) (*markerTest, error) {
821 archive := txtar.Parse(content)
822 if len(archive.Files) == 0 {
823 return nil, fmt.Errorf("txtar file has no '-- filename --' sections")
824 }
825 if bytes.Contains(archive.Comment, []byte("\n-- ")) {
826 // This check is conservative, but the comment is only a comment.
827 return nil, fmt.Errorf("ill-formed '-- filename --' header in comment")
828 }
829 test := &markerTest{
830 name: name,
831 fset: token.NewFileSet(),
832 content: content,
833 archive: archive,
834 files: make(map[string][]byte),
835 golden: make(map[expect.Identifier]*Golden),
836 }
837 seen := make(map[string]bool)
838 for _, file := range archive.Files {
839 if seen[file.Name] {
840 return nil, fmt.Errorf("duplicate archive section %q", file.Name)
841 }
842 seen[file.Name] = true
843 switch {
844 case file.Name == "skip":
845 reason := strings.ReplaceAll(string(file.Data), "\n", " ")
846 reason = strings.TrimSpace(reason)
847 test.skipReason = reason
848
849 case file.Name == "flags":
850 test.flags = strings.Fields(string(file.Data))
851
852 case file.Name == "settings.json":
853 if err := json.Unmarshal(file.Data, &test.settings); err != nil {
854 return nil, err
855 }
856
857 case file.Name == "capabilities.json":
858 test.capabilities = file.Data // lazily unmarshalled by the editor
859
860 case file.Name == "env":
861 test.env = make(map[string]string)
862 fields := strings.Fields(string(file.Data))
863 for _, field := range fields {
864 key, value, ok := strings.Cut(field, "=")
865 if !ok {
866 return nil, fmt.Errorf("env vars must be formatted as var=value, got %q", field)
867 }
868 test.env[key] = value
869 }
870
871 case strings.HasPrefix(file.Name, "@"): // golden content
872 idstring, name, _ := strings.Cut(file.Name[len("@"):], "/")
873 id := expect.Identifier(idstring)
874 // Note that a file.Name of just "@id" gives (id, name) = ("id", "").
875 if _, ok := test.golden[id]; !ok {
876 test.golden[id] = &Golden{
877 id: id,
878 data: make(map[string][]byte),
879 }
880 }
881 test.golden[id].data[name] = file.Data
882
883 case strings.HasPrefix(file.Name, "proxy/"):
884 name := file.Name[len("proxy/"):]
885 if test.proxyFiles == nil {
886 test.proxyFiles = make(map[string][]byte)
887 }
888 test.proxyFiles[name] = file.Data
889
890 default: // ordinary file content
891 notes, err := expect.Parse(test.fset, file.Name, file.Data)
892 if err != nil {
893 return nil, fmt.Errorf("parsing notes in %q: %v", file.Name, err)
894 }
895
896 // Reject common misspelling: "// @mark".
897 // TODO(adonovan): permit "// @" within a string. Detect multiple spaces.
898 if i := bytes.Index(file.Data, []byte("// @")); i >= 0 {
899 line := 1 + bytes.Count(file.Data[:i], []byte("\n"))
900 return nil, fmt.Errorf("%s:%d: unwanted space before marker (// @)", file.Name, line)
901 }
902
903 // The 'go list' command doesn't work correctly with modules named
904 // testdata", so don't allow it as a module name (golang/go#65406).
905 // (Otherwise files within it will end up in an ad hoc
906 // package, "command-line-arguments/$TMPDIR/...".)
907 if filepath.Base(file.Name) == "go.mod" &&
908 bytes.Contains(file.Data, []byte("module testdata")) {
909 return nil, fmt.Errorf("'testdata' is not a valid module name")
910 }
911
912 test.notes = append(test.notes, notes...)
913 test.files[file.Name] = file.Data
914 }
915
916 // Print a warning if we see what looks like "-- filename --"
917 // without the second "--". It's not necessarily wrong,
918 // but it should almost never appear in our test inputs.
919 if bytes.Contains(file.Data, []byte("\n-- ")) {
920 log.Printf("ill-formed '-- filename --' header in %s?", file.Name)
921 }
922 }
923
924 // Parse flags after loading files, as they may have been set by the "flags" file.
925 set := test.flagSet()
926 if err := set.Parse(test.flags); err != nil {
927 return nil, fmt.Errorf("parsing flags: %v", err)
928 }
929 if set.NArg() > 0 {
930 return nil, fmt.Errorf("surplus arguments after flags: %q", set.Args())
931 }
932
933 return test, nil
934 }
935
936 // formatTest formats the test as a txtar archive.
937 func formatTest(test *markerTest) ([]byte, error) {
938 arch := &txtar.Archive{
939 Comment: test.archive.Comment,
940 }
941
942 updatedGolden := make(map[string][]byte)
943 firstReferences := make(map[string]string)
944 for id, g := range test.golden {
945 for name, data := range g.updated {
946 filename := "@" + path.Join(string(id), name) // name may be ""
947 updatedGolden[filename] = data
948 firstReferences[filename] = g.firstReference
949 }
950 }
951
952 // Preserve the original ordering of archive files.
953 for _, file := range test.archive.Files {
954 switch file.Name {
955 // Preserve configuration files exactly as they were. They must have parsed
956 // if we got this far.
957 case "skip", "flags", "settings.json", "capabilities.json", "env":
958 arch.Files = append(arch.Files, file)
959 default:
960 if _, ok := test.files[file.Name]; ok { // ordinary file
961 arch.Files = append(arch.Files, file)
962 } else if strings.HasPrefix(file.Name, "proxy/") { // proxy file
963 arch.Files = append(arch.Files, file)
964 } else if data, ok := updatedGolden[file.Name]; ok { // golden file
965 arch.Files = append(arch.Files, txtar.File{Name: file.Name, Data: data})
966 delete(updatedGolden, file.Name)
967 }
968 }
969 }
970
971 // ...but insert new golden files after their first reference.
972 var newGoldenFiles []txtar.File
973 for filename, data := range updatedGolden {
974 // TODO(rfindley): it looks like this implicitly removes trailing newlines
975 // from golden content. Is there any way to fix that? Perhaps we should
976 // just make the diff tolerant of missing newlines?
977 newGoldenFiles = append(newGoldenFiles, txtar.File{Name: filename, Data: data})
978 }
979 // Sort new golden files lexically.
980 sort.Slice(newGoldenFiles, func(i, j int) bool {
981 return newGoldenFiles[i].Name < newGoldenFiles[j].Name
982 })
983 for _, g := range newGoldenFiles {
984 insertAt := len(arch.Files)
985 if firstRef := firstReferences[g.Name]; firstRef != "" {
986 for i, f := range arch.Files {
987 if f.Name == firstRef {
988 // Insert alphabetically among golden files following the test file.
989 for i++; i < len(arch.Files); i++ {
990 f := arch.Files[i]
991 if !strings.HasPrefix(f.Name, "@") || f.Name >= g.Name {
992 insertAt = i
993 break
994 }
995 }
996 break
997 }
998 }
999 }
1000 arch.Files = slices.Insert(arch.Files, insertAt, g)
1001 }
1002
1003 return txtar.Format(arch), nil
1004 }
1005
1006 // newEnv creates a new environment for a marker test.
1007 //
1008 // TODO(rfindley): simplify and refactor the construction of testing
1009 // environments across integration tests, marker tests, and benchmarks.
1010 func newEnv(t *testing.T, cache *cache.Cache, files, proxyFiles map[string][]byte, writeGoSum []string, config fake.EditorConfig, enableMCP bool) *integration.Env {
1011 sandbox, err := fake.NewSandbox(&fake.SandboxConfig{
1012 RootDir: t.TempDir(),
1013 Files: files,
1014 ProxyFiles: proxyFiles,
1015 })
1016 if err != nil {
1017 t.Fatal(err)
1018 }
1019
1020 for _, dir := range writeGoSum {
1021 if _, err := sandbox.RunGoCommand(context.Background(), dir, "list", []string{"-mod=mod", "..."}, []string{"GOWORK=off"}, true); err != nil {
1022 t.Fatal(err)
1023 }
1024 }
1025
1026 // Put a debug instance in the context to prevent logging to stderr.
1027 // See associated TODO in runner.go: we should revisit this pattern.
1028 ctx := context.Background()
1029 ctx = debug.WithInstance(ctx, "")
1030
1031 awaiter := integration.NewAwaiter(sandbox.Workdir)
1032
1033 ss := lsprpc.NewStreamServer(cache, false, nil)
1034
1035 var mcpServer *httptest.Server
1036 if enableMCP {
1037 mcpServer = httptest.NewServer(internalmcp.HTTPHandler(ss, false, nil))
1038 }
1039
1040 server := servertest.NewPipeServer(ss, jsonrpc2.NewRawStream)
1041 editor, err := fake.NewEditor(sandbox, config).Connect(ctx, server, awaiter.Hooks())
1042 if err != nil {
1043 sandbox.Close() // ignore error
1044 t.Fatal(err)
1045 }
1046
1047 if err := awaiter.Await(ctx, integration.OnceMet(
1048 integration.InitialWorkspaceLoad,
1049 integration.NoShownMessage(""),
1050 )); err != nil {
1051 sandbox.Close() // ignore error
1052 t.Fatal(err)
1053 }
1054
1055 var mcpSession *mcp.ClientSession
1056 if enableMCP {
1057 client := mcp.NewClient(&mcp.Implementation{Name: "test", Version: "v1.0.0"}, nil)
1058 mcpSession, err = client.Connect(ctx, &mcp.SSEClientTransport{Endpoint: mcpServer.URL}, nil)
1059 if err != nil {
1060 t.Fatalf("fail to connect to mcp server: %v", err)
1061 }
1062 }
1063
1064 return &integration.Env{
1065 TB: t,
1066 Ctx: ctx,
1067 Editor: editor,
1068 Sandbox: sandbox,
1069 Awaiter: awaiter,
1070 MCPSession: mcpSession,
1071 MCPServer: mcpServer,
1072 }
1073 }
1074
1075 // A markerTestRun holds the state of one run of a marker test archive.
1076 type markerTestRun struct {
1077 test *markerTest
1078 env *integration.Env
1079 settings map[string]any
1080
1081 // Collected information.
1082 // Each @diag/@quickfix marker eliminates an entry from diags.
1083 values map[expect.Identifier]any
1084 diags map[protocol.Location][]protocol.Diagnostic // diagnostics by position; location end == start
1085
1086 // Notes that weren't associated with a top-level marker func. They may be
1087 // consumed by another marker (e.g. @codelenses collects @codelens markers).
1088 // Any notes that aren't consumed are flagged as an error.
1089 extraNotes map[protocol.DocumentURI]map[string][]*expect.Note
1090 }
1091
1092 // sprintf returns a formatted string after applying pre-processing to
1093 // arguments of the following types:
1094 // - token.Pos: formatted using (*markerTestRun).fmtPos
1095 // - protocol.Location: formatted using (*markerTestRun).fmtLoc
1096 func (c *marker) sprintf(format string, args ...any) string {
1097 if false {
1098 _ = fmt.Sprintf(format, args...) // enable vet printf checker
1099 }
1100 var args2 []any
1101 for _, arg := range args {
1102 switch arg := arg.(type) {
1103 case token.Pos:
1104 args2 = append(args2, c.run.fmtPos(arg))
1105 case protocol.Location:
1106 args2 = append(args2, c.run.fmtLoc(arg))
1107 default:
1108 args2 = append(args2, arg)
1109 }
1110 }
1111 return fmt.Sprintf(format, args2...)
1112 }
1113
1114 // fmtPos formats the given pos in the context of the test, using
1115 // archive-relative paths for files and including the line number in the full
1116 // archive file.
1117 func (run *markerTestRun) fmtPos(pos token.Pos) string {
1118 file := run.test.fset.File(pos)
1119 if file == nil {
1120 run.env.TB.Errorf("position %d not in test fileset", pos)
1121 return "<invalid location>"
1122 }
1123 m, err := run.env.Editor.Mapper(file.Name())
1124 if err != nil {
1125 run.env.TB.Errorf("%s", err)
1126 return "<invalid location>"
1127 }
1128 loc, err := m.PosLocation(file, pos, pos)
1129 if err != nil {
1130 run.env.TB.Errorf("Mapper(%s).PosLocation failed: %v", file.Name(), err)
1131 }
1132 return run.fmtLoc(loc)
1133 }
1134
1135 // fmtLoc formats the given location in the context of the test, using
1136 // archive-relative paths for files and including the line number in the full
1137 // archive file.
1138 func (run *markerTestRun) fmtLoc(loc protocol.Location) string {
1139 if loc == (protocol.Location{}) {
1140 run.env.TB.Errorf("unable to find %s in test archive", loc)
1141 return "<invalid location>"
1142 }
1143
1144 // Format builtin locations as "file:///pseudo/builtin/builtin.go:0:0",
1145 // which is the predefined BUILTIN marker; ditto UNSAFE.
1146 if strings.HasSuffix(string(loc.URI), "src/unsafe/unsafe.go") ||
1147 strings.HasSuffix(string(loc.URI), "src/builtin/builtin.go") {
1148 name := filepath.Base(filepath.Dir(loc.URI.Path())) // "unsafe" or "builtin"
1149 loc.URI = protocol.DocumentURI("file:///pseudo/" + name + "/" + name + ".go")
1150 loc.Range = protocol.Range{}
1151 }
1152
1153 lines := bytes.Count(run.test.archive.Comment, []byte("\n"))
1154 var name string
1155 for _, f := range run.test.archive.Files {
1156 lines++ // -- separator --
1157 uri := run.env.Sandbox.Workdir.URI(f.Name)
1158 if uri == loc.URI {
1159 name = f.Name
1160 break
1161 }
1162 lines += bytes.Count(f.Data, []byte("\n"))
1163 }
1164 if name == "" {
1165 // Fall back to formatting the "lsp" location.
1166 // These will be in UTF-16, but we probably don't need to clarify that,
1167 // since it will be implied by the file:// URI format.
1168 return summarizeLoc(string(loc.URI),
1169 int(loc.Range.Start.Line), int(loc.Range.Start.Character),
1170 int(loc.Range.End.Line), int(loc.Range.End.Character))
1171 }
1172 name, startLine, startCol, endLine, endCol := run.mapLocation(loc)
1173 innerSpan := summarizeLoc(name, startLine, startCol, endLine, endCol)
1174 outerSpan := summarizeLoc(run.test.name, lines+startLine, startCol, lines+endLine, endCol)
1175 return fmt.Sprintf("%s (%s)", innerSpan, outerSpan)
1176 }
1177
1178 // mapLocation returns the relative path and utf8 span of the corresponding
1179 // location, which must be a valid location in an archive file.
1180 func (run *markerTestRun) mapLocation(loc protocol.Location) (name string, startLine, startCol, endLine, endCol int) {
1181 // Note: Editor.Mapper fails if loc.URI is not open, but we always open all
1182 // archive files, so this is probably OK.
1183 //
1184 // In the future, we may want to have the editor read contents from disk if
1185 // the URI is not open.
1186 name = run.env.Sandbox.Workdir.URIToPath(loc.URI)
1187 m, err := run.env.Editor.Mapper(name)
1188 if err != nil {
1189 run.env.TB.Errorf("internal error: %v", err)
1190 return
1191 }
1192 start, end, err := m.RangeOffsets(loc.Range)
1193 if err != nil {
1194 run.env.TB.Errorf("error formatting location %s: %v", loc, err)
1195 return
1196 }
1197 startLine, startCol = m.OffsetLineCol8(start)
1198 endLine, endCol = m.OffsetLineCol8(end)
1199 return name, startLine, startCol, endLine, endCol
1200 }
1201
1202 // fmtLocForGolden is like fmtLoc, but chooses more succinct and stable
1203 // formatting, such as would be used for formatting locations in Golden
1204 // content.
1205 func (run *markerTestRun) fmtLocForGolden(loc protocol.Location) string {
1206 if loc == (protocol.Location{}) {
1207 return "<invalid location>"
1208 }
1209 name := run.env.Sandbox.Workdir.URIToPath(loc.URI)
1210 // Note: we check IsAbs on filepaths rather than the slash-ified name for
1211 // accurate handling of windows drive letters.
1212 if filepath.IsAbs(filepath.FromSlash(name)) {
1213 // Don't format any position information in this case, since it will be
1214 // volatile.
1215 return "<external>"
1216 }
1217 return summarizeLoc(run.mapLocation(loc))
1218 }
1219
1220 // summarizeLoc formats a summary of the given location, in the form
1221 //
1222 // <name>:<startLine>:<startCol>[-[<endLine>:]endCol]
1223 func summarizeLoc(name string, startLine, startCol, endLine, endCol int) string {
1224 span := fmt.Sprintf("%s:%d:%d", name, startLine, startCol)
1225 if startLine != endLine || startCol != endCol {
1226 span += "-"
1227 if endLine != startLine {
1228 span += fmt.Sprintf("%d:", endLine)
1229 }
1230 span += fmt.Sprintf("%d", endCol)
1231 }
1232 return span
1233 }
1234
1235 // ---- converters ----
1236
1237 // Types with special handling.
1238 var (
1239 goldenType = reflect.TypeFor[*Golden]()
1240 markerType = reflect.TypeFor[marker]()
1241 stringMatcherType = reflect.TypeFor[stringMatcher]()
1242 )
1243
1244 // Custom conversions.
1245 //
1246 // These functions are called after valueMarkerFuncs have run to convert
1247 // arguments into the desired parameter types.
1248 //
1249 // Converters should return an error rather than calling marker.errorf().
1250 var customConverters = map[reflect.Type]func(marker, any) (any, error){
1251 reflect.TypeFor[protocol.Location](): converter(convertLocation),
1252 reflect.TypeFor[completionLabel](): converter(convertCompletionLabel),
1253 }
1254
1255 // converter transforms a typed argument conversion function to an untyped
1256 // conversion function.
1257 func converter[T any](f func(marker, any) (T, error)) func(marker, any) (any, error) {
1258 return func(m marker, arg any) (any, error) {
1259 return f(m, arg)
1260 }
1261 }
1262
1263 func convert(mark marker, arg any, paramType reflect.Type) (any, error) {
1264 // Handle stringMatcher and golden parameters before resolving identifiers,
1265 // because golden content lives in a separate namespace from other
1266 // identifiers.
1267 // TODO(rfindley): simplify by flattening the namespace. This interacts
1268 // poorly with named argument resolution.
1269 switch paramType {
1270 case stringMatcherType:
1271 return convertStringMatcher(mark, arg)
1272 case goldenType:
1273 id, ok := arg.(expect.Identifier)
1274 if !ok {
1275 return nil, fmt.Errorf("invalid input type %T: golden key must be an identifier", arg)
1276 }
1277 return mark.getGolden(id), nil
1278 }
1279 if id, ok := arg.(expect.Identifier); ok {
1280 if arg2, ok := mark.run.values[id]; ok {
1281 arg = arg2
1282 }
1283 }
1284 if converter, ok := customConverters[paramType]; ok {
1285 arg2, err := converter(mark, arg)
1286 if err != nil {
1287 return nil, err
1288 }
1289 arg = arg2
1290 }
1291 if reflect.TypeOf(arg).AssignableTo(paramType) {
1292 return arg, nil // no conversion required
1293 }
1294 return nil, fmt.Errorf("cannot convert %v (%T) to %s", arg, arg, paramType)
1295 }
1296
1297 // convertNamedArgLocation is a workaround for converting locations referenced
1298 // by a named argument. See the TODO in [convert]: this wouldn't be necessary
1299 // if we flattened the namespace such that golden content lived in the same
1300 // namespace as values.
1301 func convertNamedArgLocation(mark marker, arg any) (protocol.Location, error) {
1302 if id, ok := arg.(expect.Identifier); ok {
1303 if v, ok := mark.run.values[id]; ok {
1304 if loc, ok := v.(protocol.Location); ok {
1305 return loc, nil
1306 }
1307 return protocol.Location{}, fmt.Errorf("invalid location value %v", v)
1308 }
1309 }
1310 return convertLocation(mark, arg)
1311 }
1312
1313 // convertLocation converts a string or regexp argument into the protocol
1314 // location corresponding to the first position of the string (or first match
1315 // of the regexp) in the line preceding the note.
1316 func convertLocation(mark marker, arg any) (protocol.Location, error) {
1317 // matchContent is used to match the given argument against the file content
1318 // starting at the marker line.
1319 var matchContent func([]byte) (int, int, error)
1320
1321 switch arg := arg.(type) {
1322 case protocol.Location:
1323 return arg, nil // nothing to do
1324 case string:
1325 matchContent = func(content []byte) (int, int, error) {
1326 idx := bytes.Index(content, []byte(arg))
1327 if idx < 0 {
1328 return 0, 0, fmt.Errorf("substring %q not found", arg)
1329 }
1330 return idx, idx + len(arg), nil
1331 }
1332 case *regexp.Regexp:
1333 matchContent = func(content []byte) (int, int, error) {
1334 matches := arg.FindSubmatchIndex(content)
1335 if len(matches) == 0 {
1336 return 0, 0, fmt.Errorf("no match for regexp %q", arg)
1337 }
1338 switch len(matches) {
1339 case 2:
1340 // no subgroups: return the range of the regexp expression
1341 return matches[0], matches[1], nil
1342 case 4:
1343 // one subgroup: return its range
1344 return matches[2], matches[3], nil
1345 default:
1346 return 0, 0, fmt.Errorf("invalid location regexp %q: expect either 0 or 1 subgroups, got %d", arg, len(matches)/2-1)
1347 }
1348 }
1349 default:
1350 return protocol.Location{}, fmt.Errorf("cannot convert argument type %T to location (must be a string or regexp to match the preceding line)", arg)
1351 }
1352
1353 // Now use matchFunc to match a range starting on the marker line.
1354
1355 file := mark.run.test.fset.File(mark.note.Pos)
1356 posn := safetoken.Position(file, mark.note.Pos)
1357 lineStart := file.LineStart(posn.Line)
1358 lineStartOff, lineEndOff, err := safetoken.Offsets(file, lineStart, mark.note.Pos)
1359 if err != nil {
1360 return protocol.Location{}, err
1361 }
1362 m := mark.mapper()
1363 start, end, err := matchContent(m.Content[lineStartOff:])
1364 if err != nil {
1365 return protocol.Location{}, err
1366 }
1367 startOff, endOff := lineStartOff+start, lineStartOff+end
1368 if startOff > lineEndOff {
1369 // The start of the match must be between the start of the line and the
1370 // marker position (inclusive).
1371 return protocol.Location{}, fmt.Errorf("no matching range found starting on the current line")
1372 }
1373 return m.OffsetLocation(startOff, endOff)
1374 }
1375
1376 // completionLabel is a special parameter type that may be converted from a
1377 // string literal, or extracted from a completion item.
1378 //
1379 // See [convertCompletionLabel].
1380 type completionLabel string
1381
1382 // convertCompletionLabel coerces an argument to a [completionLabel] parameter
1383 // type.
1384 //
1385 // If the arg is a string, it is trivially converted. If the arg is a
1386 // completionItem, its label is extracted.
1387 //
1388 // This allows us to stage a migration of the "snippet" marker to a simpler
1389 // model where the completion label can just be listed explicitly.
1390 func convertCompletionLabel(mark marker, arg any) (completionLabel, error) {
1391 switch arg := arg.(type) {
1392 case string:
1393 return completionLabel(arg), nil
1394 case completionItem:
1395 return completionLabel(arg.Label), nil
1396 default:
1397 return "", fmt.Errorf("cannot convert argument type %T to completion label (must be a string or completion item)", arg)
1398 }
1399 }
1400
1401 // convertStringMatcher converts a string, regexp, or identifier
1402 // argument into a stringMatcher. The string is a substring of the
1403 // expected error, the regexp is a pattern than matches the expected
1404 // error, and the identifier is a golden file containing the expected
1405 // error.
1406 func convertStringMatcher(mark marker, arg any) (stringMatcher, error) {
1407 switch arg := arg.(type) {
1408 case string:
1409 return stringMatcher{substr: arg}, nil
1410 case *regexp.Regexp:
1411 return stringMatcher{pattern: arg}, nil
1412 case expect.Identifier:
1413 golden := mark.getGolden(arg)
1414 return stringMatcher{golden: golden}, nil
1415 default:
1416 return stringMatcher{}, fmt.Errorf("cannot convert %T to wantError (want: string, regexp, or identifier)", arg)
1417 }
1418 }
1419
1420 // A stringMatcher represents an expectation of a specific string value.
1421 //
1422 // It may be indicated in one of three ways, in 'expect' notation:
1423 // - an identifier 'foo', to compare (exactly) with the contents of the golden
1424 // section @foo;
1425 // - a pattern expression re"ab.*c", to match against a regular expression;
1426 // - a string literal "abc", to check for a substring.
1427 type stringMatcher struct {
1428 golden *Golden
1429 pattern *regexp.Regexp
1430 substr string
1431 }
1432
1433 // empty reports whether the receiver is an empty stringMatcher.
1434 func (sm stringMatcher) empty() bool {
1435 return sm.golden == nil && sm.pattern == nil && sm.substr == ""
1436 }
1437
1438 func (sm stringMatcher) String() string {
1439 if sm.golden != nil {
1440 return fmt.Sprintf("content from @%s entry", sm.golden.id)
1441 } else if sm.pattern != nil {
1442 return fmt.Sprintf("content matching %#q", sm.pattern)
1443 } else {
1444 return fmt.Sprintf("content with substring %q", sm.substr)
1445 }
1446 }
1447
1448 // checkErr asserts that the given error matches the stringMatcher's expectations.
1449 func (sm stringMatcher) checkErr(mark marker, err error) {
1450 if err == nil {
1451 mark.errorf("@%s succeeded unexpectedly, want %v", mark.note.Name, sm)
1452 return
1453 }
1454 sm.check(mark, err.Error())
1455 }
1456
1457 // check asserts that the given content matches the stringMatcher's expectations.
1458 func (sm stringMatcher) check(mark marker, got string) {
1459 if sm.golden != nil {
1460 compareGolden(mark, []byte(got), sm.golden)
1461 } else if sm.pattern != nil {
1462 // Content must match the regular expression pattern.
1463 if !sm.pattern.MatchString(got) {
1464 mark.errorf("got %q, does not match pattern %#q", got, sm.pattern)
1465 }
1466 } else if !strings.Contains(got, sm.substr) {
1467 // Content must contain the expected substring.
1468 mark.errorf("got %q, want substring %q", got, sm.substr)
1469 }
1470 }
1471
1472 // checkChangedFiles compares the files changed by an operation with their expected (golden) state.
1473 func checkChangedFiles(mark marker, changed map[string][]byte, golden *Golden) {
1474 // Check changed files match expectations.
1475 for filename, got := range changed {
1476 if want, ok := golden.Get(mark.T(), filename, got); !ok {
1477 mark.errorf("%s: unexpected change to file %s; got:\n%s",
1478 mark.note.Name, filename, got)
1479 } else if string(got) != string(want) {
1480 mark.errorf("%s: wrong file content for %s:\n-- got --\n%s\n-- want --\n%s\n-- diff --\n%s",
1481 mark.note.Name, filename, got, want,
1482 compare.Bytes(want, got))
1483 }
1484 }
1485
1486 // Report unmet expectations.
1487 for filename := range golden.data {
1488 if _, ok := changed[filename]; !ok {
1489 want, _ := golden.Get(mark.T(), filename, nil)
1490 mark.errorf("%s: missing change to file %s; want:\n%s",
1491 mark.note.Name, filename, want)
1492 }
1493 }
1494 }
1495
1496 // checkDiffs checks that the diff content stored in the given golden
1497 // directory converts the original contents into the changed contents.
1498 // (It does _not_ check that the diff has a specific notation, as
1499 // there are many valid ways to notate the same patch and we do not
1500 // want tests to break whenever our diff algorithm evolves.)
1501 func checkDiffs(mark marker, changed map[string][]byte, golden *Golden) {
1502 for name, after := range changed {
1503 before := mark.run.env.FileContent(name)
1504 edits := diff.Lines(before, string(after))
1505 d, err := diff.ToUnified("before", "after", before, edits, 0)
1506 if err != nil {
1507 // Can't happen: edits are consistent.
1508 log.Fatalf("internal error in diff.ToUnified: %v", err)
1509 }
1510 // Trim the unified header from diffs, as it is unnecessary and repetitive.
1511 // (an artifact of ToUnified, but not stored in the marker files)
1512 difflines := strings.Split(d, "\n")
1513 var got string
1514 if len(difflines) >= 2 && strings.HasPrefix(difflines[1], "+++") {
1515 got = strings.Join(difflines[2:], "\n")
1516 } else {
1517 got = d // "" in packagedecl.txt:147
1518 }
1519 // the call to Get is so that the -update flag will update the test.
1520 // normally it just returns 'got'.
1521 tdiffs, ok := golden.Get(mark.T(), name, []byte(got))
1522 if !ok {
1523 mark.errorf("%s: unexpected change to file %s; got diff:\n%s",
1524 mark.note.Name, name, got)
1525 return
1526 }
1527 want, err := diff.ApplyUnified(string(tdiffs), before)
1528 if err != nil {
1529 mark.errorf("in @%s golden section %s: %v; actual diff:\n%s",
1530 mark.note.Name, name, err, d)
1531 }
1532 if string(after) != want {
1533 mark.errorf("%s: got:\n%s\nwant:\n%s", mark.note.Name, after, want)
1534 }
1535 }
1536
1537 // Report unmet expectations.
1538 for filename := range golden.data {
1539 if _, ok := changed[filename]; !ok {
1540 want, _ := golden.Get(mark.T(), filename, nil)
1541 mark.errorf("%s: missing change to file %s; want:\n%s",
1542 mark.note.Name, filename, want)
1543 }
1544 }
1545 }
1546
1547 // ---- marker functions ----
1548
1549 // TODO(rfindley): consolidate documentation of these markers. They are already
1550 // documented above, so much of the documentation here is redundant.
1551
1552 // completionItem is a simplified summary of a completion item.
1553 type completionItem struct {
1554 Label, Detail, Kind, Documentation string
1555 }
1556
1557 func completionItemMarker(mark marker, label string, other ...string) completionItem {
1558 if len(other) > 3 {
1559 mark.errorf("too many arguments to @item: expect at most 4")
1560 }
1561 item := completionItem{
1562 Label: label,
1563 }
1564 if len(other) > 0 {
1565 item.Detail = other[0]
1566 }
1567 if len(other) > 1 {
1568 item.Kind = other[1]
1569 }
1570 if len(other) > 2 {
1571 item.Documentation = other[2]
1572 }
1573 return item
1574 }
1575
1576 func rankMarker(mark marker, src protocol.Location, items ...completionLabel) {
1577 // Separate positive and negative items (expectations).
1578 var pos, neg []completionLabel
1579 for _, item := range items {
1580 if strings.HasPrefix(string(item), "!") {
1581 neg = append(neg, item)
1582 } else {
1583 pos = append(pos, item)
1584 }
1585 }
1586
1587 // Collect results that are present in items, preserving their order.
1588 list := mark.run.env.Completion(src)
1589 var got []string
1590 for _, g := range list.Items {
1591 for _, w := range pos {
1592 if g.Label == string(w) {
1593 got = append(got, g.Label)
1594 break
1595 }
1596 }
1597 for _, w := range neg {
1598 if g.Label == string(w[len("!"):]) {
1599 mark.errorf("got unwanted completion: %s", g.Label)
1600 break
1601 }
1602 }
1603 }
1604 var want []string
1605 for _, w := range pos {
1606 want = append(want, string(w))
1607 }
1608 if diff := cmp.Diff(want, got); diff != "" {
1609 mark.errorf("completion rankings do not match (-want +got):\n%s", diff)
1610 }
1611 }
1612
1613 func snippetMarker(mark marker, src protocol.Location, label completionLabel, want string) {
1614 list := mark.run.env.Completion(src)
1615 var (
1616 found bool
1617 got string
1618 all []string // for errors
1619 )
1620 items := filterBuiltinsAndKeywords(mark, list.Items)
1621 for _, i := range items {
1622 all = append(all, i.Label)
1623 if i.Label == string(label) {
1624 found = true
1625 if i.TextEdit != nil {
1626 if edit, err := protocol.SelectCompletionTextEdit(i, false); err == nil {
1627 got = edit.NewText
1628 }
1629 }
1630 break
1631 }
1632 }
1633 if !found {
1634 mark.errorf("no completion item found matching %s (got: %v)", label, all)
1635 return
1636 }
1637 if got != want {
1638 mark.errorf("snippets do not match: got:\n%q\nwant:\n%q", got, want)
1639 }
1640 }
1641
1642 // completeMarker implements the @complete marker, running
1643 // textDocument/completion at the given src location and asserting that the
1644 // results match the expected results.
1645 func completeMarker(mark marker, src protocol.Location, want ...completionItem) {
1646 list := mark.run.env.Completion(src)
1647 items := filterBuiltinsAndKeywords(mark, list.Items)
1648 var got []completionItem
1649 for i, item := range items {
1650 simplified := completionItem{
1651 Label: item.Label,
1652 Detail: item.Detail,
1653 Kind: fmt.Sprint(item.Kind),
1654 }
1655 if item.Documentation != nil {
1656 switch v := item.Documentation.Value.(type) {
1657 case string:
1658 simplified.Documentation = v
1659 case protocol.MarkupContent:
1660 simplified.Documentation = strings.TrimSpace(v.Value) // trim newlines
1661 }
1662 }
1663 // Support short-hand notation: if Detail, Kind, or Documentation are omitted from the
1664 // item, don't match them.
1665 if i < len(want) {
1666 if want[i].Detail == "" {
1667 simplified.Detail = ""
1668 }
1669 if want[i].Kind == "" {
1670 simplified.Kind = ""
1671 }
1672 if want[i].Documentation == "" {
1673 simplified.Documentation = ""
1674 }
1675 }
1676 got = append(got, simplified)
1677 }
1678 if len(want) == 0 {
1679 want = nil // got is nil if empty
1680 }
1681 if diff := cmp.Diff(want, got); diff != "" {
1682 mark.errorf("Completion(...) returned unexpected results (-want +got):\n%s", diff)
1683 }
1684 }
1685
1686 // filterBuiltinsAndKeywords filters out builtins and keywords from completion
1687 // results.
1688 //
1689 // It over-approximates, and does not detect if builtins are shadowed.
1690 func filterBuiltinsAndKeywords(mark marker, items []protocol.CompletionItem) []protocol.CompletionItem {
1691 keep := 0
1692 for _, item := range items {
1693 if mark.run.test.filterKeywords && item.Kind == protocol.KeywordCompletion {
1694 continue
1695 }
1696 if mark.run.test.filterBuiltins && types.Universe.Lookup(item.Label) != nil {
1697 continue
1698 }
1699 items[keep] = item
1700 keep++
1701 }
1702 return items[:keep]
1703 }
1704
1705 // acceptCompletionMarker implements the @acceptCompletion marker, running
1706 // textDocument/completion at the given src location and accepting the
1707 // candidate with the given label. The resulting source must match the provided
1708 // golden content.
1709 func acceptCompletionMarker(mark marker, src protocol.Location, label string, golden *Golden) {
1710 list := mark.run.env.Completion(src)
1711 var selected *protocol.CompletionItem
1712 for _, item := range list.Items {
1713 if item.Label == label {
1714 selected = &item
1715 break
1716 }
1717 }
1718 if selected == nil {
1719 mark.errorf("Completion(...) did not return an item labeled %q", label)
1720 return
1721 }
1722 edit, err := protocol.SelectCompletionTextEdit(*selected, false)
1723 if err != nil {
1724 mark.errorf("Completion(...) did not return a valid edit: %v", err)
1725 return
1726 }
1727 filename := mark.path()
1728 mapper := mark.mapper()
1729 patched, _, err := protocol.ApplyEdits(mapper, append([]protocol.TextEdit{edit}, selected.AdditionalTextEdits...))
1730 if err != nil {
1731 mark.errorf("ApplyProtocolEdits failed: %v", err)
1732 return
1733 }
1734 changes := map[string][]byte{filename: patched}
1735 // Check the file state.
1736 checkChangedFiles(mark, changes, golden)
1737 }
1738
1739 // defMarker implements the @def marker, running textDocument/definition at
1740 // the given location and asserting that there the results match want.
1741 func defMarker(mark marker, loc protocol.Location, want ...protocol.Location) {
1742 env := mark.run.env
1743 got, err := env.Editor.Definitions(env.Ctx, loc)
1744 if err != nil {
1745 mark.errorf("definition request failed: %v", err)
1746 return
1747 }
1748
1749 if err := compareLocations(mark, got, want); err != nil {
1750 mark.errorf("def failed: %v", err)
1751 }
1752 }
1753
1754 // typedefMarker implements the @typedef marker.
1755 func typedefMarker(mark marker, loc protocol.Location, want ...protocol.Location) {
1756 wantErr := namedArgFunc(mark, "err", convertStringMatcher, stringMatcher{})
1757
1758 env := mark.run.env
1759 got, err := env.Editor.TypeDefinitions(env.Ctx, loc)
1760 if err != nil && wantErr.empty() {
1761 mark.errorf("typeDefinition at %s failed: %v", loc, err)
1762 return
1763 }
1764 if !wantErr.empty() {
1765 wantErr.checkErr(mark, err)
1766 return
1767 }
1768
1769 if err := compareLocations(mark, got, want); err != nil {
1770 mark.errorf("typedef failed: %v", err)
1771 }
1772 }
1773
1774 func foldingRangeMarker(mark marker, g *Golden) {
1775 env := mark.run.env
1776 ranges, err := mark.server().FoldingRange(env.Ctx, &protocol.FoldingRangeParams{
1777 TextDocument: mark.document(),
1778 })
1779 if err != nil {
1780 mark.errorf("foldingRange failed: %v", err)
1781 return
1782 }
1783 var edits []protocol.TextEdit
1784 insert := func(line, char uint32, text string) {
1785 pos := protocol.Position{Line: line, Character: char}
1786 edits = append(edits, protocol.TextEdit{
1787 Range: protocol.Range{
1788 Start: pos,
1789 End: pos,
1790 },
1791 NewText: text,
1792 })
1793 }
1794 for i, rng := range ranges {
1795 // We assume the server populates these optional fields.
1796 insert(*rng.StartLine, *rng.StartCharacter, fmt.Sprintf("<%d kind=%q>", i, rng.Kind))
1797 insert(*rng.EndLine, *rng.EndCharacter, fmt.Sprintf("</%d>", i))
1798 }
1799 filename := mark.path()
1800 mapper, err := env.Editor.Mapper(filename)
1801 if err != nil {
1802 mark.errorf("Editor.Mapper(%s) failed: %v", filename, err)
1803 return
1804 }
1805 got, _, err := protocol.ApplyEdits(mapper, edits)
1806 if err != nil {
1807 mark.errorf("ApplyProtocolEdits failed: %v", err)
1808 return
1809 }
1810 want, _ := g.Get(mark.T(), "", got)
1811 if diff := compare.Bytes(want, got); diff != "" {
1812 mark.errorf("foldingRange mismatch:\n%s", diff)
1813 }
1814 }
1815
1816 // formatMarker implements the @format marker.
1817 func formatMarker(mark marker, golden *Golden) {
1818 edits, err := mark.server().Formatting(mark.ctx(), &protocol.DocumentFormattingParams{
1819 TextDocument: mark.document(),
1820 })
1821 var got []byte
1822 if err != nil {
1823 got = []byte(err.Error() + "\n") // all golden content is newline terminated
1824 } else {
1825 env := mark.run.env
1826 filename := mark.path()
1827 mapper, err := env.Editor.Mapper(filename)
1828 if err != nil {
1829 mark.errorf("Editor.Mapper(%s) failed: %v", filename, err)
1830 }
1831
1832 got, _, err = protocol.ApplyEdits(mapper, edits)
1833 if err != nil {
1834 mark.errorf("ApplyProtocolEdits failed: %v", err)
1835 return
1836 }
1837 }
1838
1839 compareGolden(mark, got, golden)
1840 }
1841
1842 func highlightLocationMarker(mark marker, loc protocol.Location, kindName expect.Identifier) protocol.DocumentHighlight {
1843 var kind protocol.DocumentHighlightKind
1844 switch kindName {
1845 case "read":
1846 kind = protocol.Read
1847 case "write":
1848 kind = protocol.Write
1849 case "text":
1850 kind = protocol.Text
1851 default:
1852 mark.errorf("invalid highlight kind: %q", kindName)
1853 }
1854
1855 return protocol.DocumentHighlight{
1856 Range: loc.Range,
1857 Kind: kind,
1858 }
1859 }
1860
1861 func sortDocumentHighlights(s []protocol.DocumentHighlight) {
1862 sort.Slice(s, func(i, j int) bool {
1863 return protocol.CompareRange(s[i].Range, s[j].Range) < 0
1864 })
1865 }
1866
1867 // highlightAllMarker makes textDocument/highlight
1868 // requests at locations of equivalence classes. Given input
1869 // highlightall(X1, X2, ..., Xn), the marker checks
1870 // highlight(X1) = highlight(X2) = ... = highlight(Xn) = {X1, X2, ..., Xn}.
1871 // It is not the general rule for all highlighting, and use @highlight
1872 // for asymmetric cases.
1873 //
1874 // TODO(b/288111111): this is a bit of a hack. We should probably
1875 // have a more general way of testing that a function is idempotent.
1876 func highlightAllMarker(mark marker, all ...protocol.DocumentHighlight) {
1877 sortDocumentHighlights(all)
1878 for _, src := range all {
1879 loc := mark.uri().Location(src.Range)
1880 got := mark.run.env.DocumentHighlight(loc)
1881 sortDocumentHighlights(got)
1882
1883 if d := cmp.Diff(all, got); d != "" {
1884 mark.errorf("DocumentHighlight(%v) mismatch (-want +got):\n%s", loc, d)
1885 }
1886 }
1887 }
1888
1889 func highlightMarker(mark marker, src protocol.DocumentHighlight, dsts ...protocol.DocumentHighlight) {
1890 loc := mark.uri().Location(src.Range)
1891 got := mark.run.env.DocumentHighlight(loc)
1892
1893 sortDocumentHighlights(got)
1894 sortDocumentHighlights(dsts)
1895
1896 if diff := cmp.Diff(dsts, got, cmpopts.EquateEmpty()); diff != "" {
1897 mark.errorf("DocumentHighlight(%v) mismatch (-want +got):\n%s", src, diff)
1898 }
1899 }
1900
1901 func hoverMarker(mark marker, src, dst protocol.Location, sc stringMatcher) {
1902 content, gotDst := mark.run.env.Hover(src)
1903 if gotDst != dst {
1904 mark.errorf("hover location does not match:\n\tgot: %s\n\twant %s)", mark.run.fmtLoc(gotDst), mark.run.fmtLoc(dst))
1905 }
1906 gotMD := ""
1907 if content != nil {
1908 gotMD = content.Value
1909
1910 // Normalize the absolute path for cross-platform consistency before
1911 // replacement. This ensures Windows paths (e.g., "C:/...") become
1912 // "/C:/..." to match Unix-like paths.
1913 abs := mark.run.env.Sandbox.Workdir.RootURI().Path()
1914 if protocol.IsWindowsDrivePath(abs) {
1915 abs = "/" + abs
1916 }
1917 gotMD = strings.ReplaceAll(gotMD, filepath.ToSlash(abs), "$WORKDIR")
1918 }
1919 sc.check(mark, gotMD)
1920 }
1921
1922 func hoverErrMarker(mark marker, src protocol.Location, em stringMatcher) {
1923 _, _, err := mark.editor().Hover(mark.ctx(), src)
1924 em.checkErr(mark, err)
1925 }
1926
1927 // locMarker implements the @loc marker.
1928 func locMarker(mark marker, loc protocol.Location) protocol.Location { return loc }
1929
1930 // defLocMarker implements the @defloc marker, which binds a location to the
1931 // (first) result of a jump-to-definition request.
1932 func defLocMarker(mark marker, loc protocol.Location) protocol.Location {
1933 return mark.run.env.FirstDefinition(loc)
1934 }
1935
1936 // diagMarker implements the @diag marker. It eliminates diagnostics from
1937 // the observed set in mark.test.
1938 func diagMarker(mark marker, loc protocol.Location, re *regexp.Regexp) {
1939 exact := namedArg(mark, "exact", false)
1940 if _, ok := removeDiagnostic(mark, loc, exact, re); !ok {
1941 mark.errorf("no diagnostic at %v matches %q", loc, re)
1942 }
1943 }
1944
1945 // removeDiagnostic looks for a diagnostic matching loc at the given position.
1946 //
1947 // If found, it returns (diag, true), and eliminates the matched diagnostic
1948 // from the unmatched set.
1949 //
1950 // If not found, it returns (protocol.Diagnostic{}, false).
1951 func removeDiagnostic(mark marker, loc protocol.Location, matchEnd bool, re *regexp.Regexp) (protocol.Diagnostic, bool) {
1952 key := loc
1953 key.Range.End = key.Range.Start // diagnostics ignore end position.
1954 diags := mark.run.diags[key]
1955 for i, diag := range diags {
1956 if re.MatchString(diag.Message) && (!matchEnd || diag.Range.End == loc.Range.End) {
1957 mark.run.diags[key] = slices.Delete(diags, i, i+1)
1958 return diag, true
1959 }
1960 }
1961 return protocol.Diagnostic{}, false
1962 }
1963
1964 // renameMarker implements the @rename(location, new, golden) marker.
1965 func renameMarker(mark marker, loc protocol.Location, newName string, golden *Golden) {
1966 changed, err := rename(mark.run.env, loc, newName)
1967 if err != nil {
1968 mark.errorf("rename failed: %v. (Use @renameerr for expected errors.)", err)
1969 return
1970 }
1971 checkDiffs(mark, changed, golden)
1972 }
1973
1974 // renameErrMarker implements the @renamererr(location, new, error) marker.
1975 func renameErrMarker(mark marker, loc protocol.Location, newName string, wantErr stringMatcher) {
1976 _, err := rename(mark.run.env, loc, newName)
1977 wantErr.checkErr(mark, err)
1978 }
1979
1980 func selectionRangeMarker(mark marker, loc protocol.Location, g *Golden) {
1981 ranges, err := mark.server().SelectionRange(mark.ctx(), &protocol.SelectionRangeParams{
1982 TextDocument: mark.document(),
1983 Positions: []protocol.Position{loc.Range.Start},
1984 })
1985 if err != nil {
1986 mark.errorf("SelectionRange failed: %v", err)
1987 return
1988 }
1989 var buf bytes.Buffer
1990 m := mark.mapper()
1991 for i, path := range ranges {
1992 fmt.Fprintf(&buf, "Ranges %d:", i)
1993 rng := path
1994 for {
1995 s, e, err := m.RangeOffsets(rng.Range)
1996 if err != nil {
1997 mark.errorf("RangeOffsets failed: %v", err)
1998 return
1999 }
2000
2001 var snippet string
2002 if e-s < 30 {
2003 snippet = string(m.Content[s:e])
2004 } else {
2005 snippet = string(m.Content[s:s+15]) + "..." + string(m.Content[e-15:e])
2006 }
2007
2008 fmt.Fprintf(&buf, "\n\t%v %q", rng.Range, strings.ReplaceAll(snippet, "\n", "\\n"))
2009
2010 if rng.Parent == nil {
2011 break
2012 }
2013 rng = *rng.Parent
2014 }
2015 buf.WriteRune('\n')
2016 }
2017 compareGolden(mark, buf.Bytes(), g)
2018 }
2019
2020 func tokenMarker(mark marker, loc protocol.Location, tokenType, mod string) {
2021 tokens := mark.run.env.SemanticTokensRange(loc)
2022 if len(tokens) != 1 {
2023 mark.errorf("got %d tokens, want 1", len(tokens))
2024 return
2025 }
2026 tok := tokens[0]
2027 if tok.TokenType != tokenType {
2028 mark.errorf("token type = %q, want %q", tok.TokenType, tokenType)
2029 }
2030 if tok.Mod != mod {
2031 mark.errorf("token mod = %q, want %q", tok.Mod, mod)
2032 }
2033 }
2034
2035 func signatureMarker(mark marker, src protocol.Location, label string, active int64) {
2036 got := mark.run.env.SignatureHelp(src)
2037 var gotLabels []string // for better error messages
2038 if got != nil {
2039 for _, s := range got.Signatures {
2040 gotLabels = append(gotLabels, s.Label)
2041 }
2042 }
2043 if label == "" {
2044 // A null result is expected.
2045 // (There's no point having a @signatureerr marker
2046 // because the server handler suppresses all errors.)
2047 if got != nil && len(gotLabels) > 0 {
2048 mark.errorf("signatureHelp = %v, want 0 signatures", gotLabels)
2049 }
2050 return
2051 }
2052 if got == nil || len(got.Signatures) != 1 {
2053 mark.errorf("signatureHelp = %v, want exactly 1 signature", gotLabels)
2054 return
2055 }
2056 if got := gotLabels[0]; got != label {
2057 mark.errorf("signatureHelp: got label %q, want %q", got, label)
2058 }
2059 gotActiveParameter := int64(-1) // => missing
2060 if got.ActiveParameter != nil {
2061 gotActiveParameter = int64(*got.ActiveParameter)
2062 }
2063 if gotActiveParameter != active {
2064 mark.errorf("signatureHelp: got active parameter %d, want %d", gotActiveParameter, active)
2065 }
2066 }
2067
2068 // rename returns the new contents of the files that would be modified
2069 // by renaming the identifier at loc to newName.
2070 func rename(env *integration.Env, loc protocol.Location, newName string) (map[string][]byte, error) {
2071 // We call Server.Rename directly, instead of
2072 // env.Editor.Rename(env.Ctx, loc, newName)
2073 // to isolate Rename from PrepareRename, and because we don't
2074 // want to modify the file system in a scenario with multiple
2075 // @rename markers.
2076
2077 wsedit, err := env.Editor.Server.Rename(env.Ctx, &protocol.RenameParams{
2078 TextDocumentPositionParams: protocol.LocationTextDocumentPositionParams(loc),
2079 NewName: newName,
2080 })
2081 if err != nil {
2082 return nil, err
2083 }
2084 return changedFiles(env, wsedit.DocumentChanges)
2085 }
2086
2087 // changedFiles applies the given sequence of document changes to the
2088 // editor buffer content, recording the final contents in the returned map.
2089 // The actual editor state is not changed.
2090 // Deleted files are indicated by a content of []byte(nil).
2091 //
2092 // See also:
2093 // - Editor.applyWorkspaceEdit ../integration/fake/editor.go for the
2094 // implementation of this operation used in normal testing.
2095 // - client.applyWorkspaceEdit in ../../../cmd/cmd.go for the
2096 // CLI variant.
2097 func changedFiles(env *integration.Env, changes []protocol.DocumentChange) (map[string][]byte, error) {
2098 uriToPath := env.Sandbox.Workdir.URIToPath
2099
2100 // latest maps each updated file name to a mapper holding its
2101 // current contents, or nil if the file has been deleted.
2102 latest := make(map[protocol.DocumentURI]*protocol.Mapper)
2103
2104 // read reads a file. It returns an error if the file never
2105 // existed or was deleted.
2106 read := func(uri protocol.DocumentURI) (*protocol.Mapper, error) {
2107 if m, ok := latest[uri]; ok {
2108 if m == nil {
2109 return nil, fmt.Errorf("read: file %s was deleted", uri)
2110 }
2111 return m, nil
2112 }
2113 return env.Editor.Mapper(uriToPath(uri))
2114 }
2115
2116 // write (over)writes a file. A nil content indicates a deletion.
2117 write := func(uri protocol.DocumentURI, content []byte) {
2118 var m *protocol.Mapper
2119 if content != nil {
2120 m = protocol.NewMapper(uri, content)
2121 }
2122 latest[uri] = m
2123 }
2124
2125 // Process the sequence of changes.
2126 for _, change := range changes {
2127 switch {
2128 case change.TextDocumentEdit != nil:
2129 uri := change.TextDocumentEdit.TextDocument.URI
2130 m, err := read(uri)
2131 if err != nil {
2132 return nil, err // missing
2133 }
2134 patched, _, err := protocol.ApplyEdits(m, protocol.AsTextEdits(change.TextDocumentEdit.Edits))
2135 if err != nil {
2136 return nil, err // bad edit
2137 }
2138 write(uri, patched)
2139
2140 case change.RenameFile != nil:
2141 old := change.RenameFile.OldURI
2142 new := change.RenameFile.NewURI
2143 info, err := os.Stat(old.Path())
2144 if err != nil {
2145 return nil, err
2146 }
2147 if info.IsDir() {
2148 // Walk through all the files in the old directory and copy
2149 // their content to the new directory.
2150 // TODO(mkalil): This currently only handles renaming the file's
2151 // innermost directory. Need to handle renames of outer directories
2152 // directories when implementing package move refactoring.
2153 for _, file := range env.ListFiles(old.Path()) {
2154 oldFile := protocol.URIFromPath(path.Join(old.Path(), path.Base(file)))
2155 m, err := read(oldFile)
2156 if err != nil {
2157 return nil, err // missing
2158 }
2159 write(oldFile, nil)
2160
2161 newFile := protocol.URIFromPath(path.Join(new.Path(), path.Base(file)))
2162 if _, err := read(oldFile); err == nil {
2163 return nil, fmt.Errorf("RenameFile: destination %s exists", new)
2164 }
2165 write(newFile, m.Content)
2166 }
2167 } else {
2168 m, err := read(old)
2169 if err != nil {
2170 return nil, err // missing
2171 }
2172 write(old, nil)
2173
2174 if _, err := read(old); err == nil {
2175 return nil, fmt.Errorf("RenameFile: destination %s exists", new)
2176 }
2177 write(new, m.Content)
2178 }
2179
2180 case change.CreateFile != nil:
2181 uri := change.CreateFile.URI
2182 if _, err := read(uri); err == nil {
2183 return nil, fmt.Errorf("CreateFile %s: file exists", uri)
2184 }
2185 write(uri, []byte("")) // initially empty
2186
2187 case change.DeleteFile != nil:
2188 uri := change.DeleteFile.URI
2189 if _, err := read(uri); err != nil {
2190 // The specified URI could be a file or a directory.
2191 files := env.ListFiles(uriToPath(uri))
2192 if files == nil {
2193 return nil, fmt.Errorf("DeleteFile %s: file does not exist", uri)
2194 }
2195 if len(files) > 0 {
2196 // Directory is not empty. If "Recursive" is true, we delete
2197 // every file in the folder. Otherwise, we continue without
2198 // deleting the directory.
2199 if change.DeleteFile.Options != nil && change.DeleteFile.Options.Recursive {
2200 for _, f := range files {
2201 write(protocol.URIFromPath(f), nil)
2202 }
2203 }
2204 continue
2205 }
2206 }
2207 write(uri, nil)
2208
2209 default:
2210 return nil, fmt.Errorf("invalid DocumentChange")
2211 }
2212 }
2213
2214 // Convert into result form.
2215 result := make(map[string][]byte)
2216 for uri, mapper := range latest {
2217 var content []byte
2218 if mapper != nil {
2219 content = mapper.Content
2220 }
2221 result[uriToPath(uri)] = content
2222 }
2223
2224 return result, nil
2225 }
2226
2227 // codeLensesMarker runs the @codelenses() marker, collecting @codelens marks
2228 // in the current file and comparing with the result of the
2229 // textDocument/codeLens RPC.
2230 func codeLensesMarker(mark marker) {
2231 type codeLens struct {
2232 Range protocol.Range
2233 Title string
2234 }
2235
2236 lenses := mark.run.env.CodeLens(mark.path())
2237 var got []codeLens
2238 for _, lens := range lenses {
2239 title := ""
2240 if lens.Command != nil {
2241 title = lens.Command.Title
2242 }
2243 got = append(got, codeLens{lens.Range, title})
2244 }
2245
2246 var want []codeLens
2247 mark.consumeExtraNotes("codelens", actionMarkerFunc(func(_ marker, loc protocol.Location, title string) {
2248 want = append(want, codeLens{loc.Range, title})
2249 }))
2250
2251 for _, s := range [][]codeLens{got, want} {
2252 sort.Slice(s, func(i, j int) bool {
2253 li, lj := s[i], s[j]
2254 if c := protocol.CompareRange(li.Range, lj.Range); c != 0 {
2255 return c < 0
2256 }
2257 return li.Title < lj.Title
2258 })
2259 }
2260
2261 if diff := cmp.Diff(want, got); diff != "" {
2262 mark.errorf("codelenses: unexpected diff (-want +got):\n%s", diff)
2263 }
2264 }
2265
2266 func documentLinkMarker(mark marker, g *Golden) {
2267 var b bytes.Buffer
2268 links := mark.run.env.DocumentLink(mark.path())
2269 for _, l := range links {
2270 if l.Target == nil {
2271 mark.errorf("%s: nil link target", l.Range)
2272 continue
2273 }
2274 loc := mark.uri().Location(l.Range)
2275 fmt.Fprintln(&b, mark.run.fmtLocForGolden(loc), *l.Target)
2276 }
2277
2278 compareGolden(mark, b.Bytes(), g)
2279 }
2280
2281 // consumeExtraNotes runs the provided func for each extra note with the given
2282 // name, and deletes all matching notes.
2283 func (mark marker) consumeExtraNotes(name string, f func(marker)) {
2284 uri := mark.uri()
2285 notes := mark.run.extraNotes[uri][name]
2286 delete(mark.run.extraNotes[uri], name)
2287
2288 for _, note := range notes {
2289 f(marker{run: mark.run, note: note})
2290 }
2291 }
2292
2293 // quickfixMarker implements the @quickfix(location, regexp,
2294 // kind, golden) marker. It acts like @diag(location, regexp), to set
2295 // the expectation of a diagnostic, but then it applies the "quickfix"
2296 // code action (which must be unique) suggested by the matched diagnostic.
2297 func quickfixMarker(mark marker, loc protocol.Location, re *regexp.Regexp, golden *Golden) {
2298 loc.Range.End = loc.Range.Start // diagnostics ignore end position.
2299 // Find and remove the matching diagnostic.
2300 diag, ok := removeDiagnostic(mark, loc, false, re)
2301 if !ok {
2302 mark.errorf("no diagnostic at %v matches %q", loc, re)
2303 return
2304 }
2305
2306 // Apply the fix it suggests.
2307 changed, err := codeAction(mark, loc.URI, diag.Range, "quickfix", &diag)
2308 if err != nil {
2309 mark.errorf("quickfix failed: %v. (Use @quickfixerr for expected errors.)", err)
2310 return
2311 }
2312
2313 // Check the file state.
2314 checkDiffs(mark, changed, golden)
2315 }
2316
2317 func quickfixErrMarker(mark marker, loc protocol.Location, re *regexp.Regexp, wantErr stringMatcher) {
2318 loc.Range.End = loc.Range.Start // diagnostics ignore end position.
2319 // Find and remove the matching diagnostic.
2320 diag, ok := removeDiagnostic(mark, loc, false, re)
2321 if !ok {
2322 mark.errorf("no diagnostic at %v matches %q", loc, re)
2323 return
2324 }
2325
2326 // Apply the fix it suggests.
2327 _, err := codeAction(mark, loc.URI, diag.Range, "quickfix", &diag)
2328 wantErr.checkErr(mark, err)
2329 }
2330
2331 // refsMarker implements the @refs marker.
2332 func refsMarker(mark marker, src protocol.Location, want ...protocol.Location) {
2333 refs := func(includeDeclaration bool, want []protocol.Location) error {
2334 got, err := mark.server().References(mark.ctx(), &protocol.ReferenceParams{
2335 TextDocumentPositionParams: protocol.LocationTextDocumentPositionParams(src),
2336 Context: protocol.ReferenceContext{
2337 IncludeDeclaration: includeDeclaration,
2338 },
2339 })
2340 if err != nil {
2341 return err
2342 }
2343
2344 return compareLocations(mark, got, want)
2345 }
2346
2347 for _, includeDeclaration := range []bool{false, true} {
2348 // Ignore first 'want' location if we didn't request the declaration.
2349 // TODO(adonovan): don't assume a single declaration:
2350 // there may be >1 if corresponding methods are considered.
2351 want := want
2352 if !includeDeclaration && len(want) > 0 {
2353 want = want[1:]
2354 }
2355 if err := refs(includeDeclaration, want); err != nil {
2356 mark.errorf("refs(includeDeclaration=%t) failed: %v",
2357 includeDeclaration, err)
2358 }
2359 }
2360 }
2361
2362 // implementationMarker implements the @implementation marker.
2363 func implementationMarker(mark marker, src protocol.Location, want ...protocol.Location) {
2364 wantErr := namedArgFunc(mark, "err", convertStringMatcher, stringMatcher{})
2365
2366 got, err := mark.server().Implementation(mark.ctx(), &protocol.ImplementationParams{
2367 TextDocumentPositionParams: protocol.LocationTextDocumentPositionParams(src),
2368 })
2369 if err != nil && wantErr.empty() {
2370 mark.errorf("implementation at %s failed: %v", src, err)
2371 return
2372 }
2373 if !wantErr.empty() {
2374 wantErr.checkErr(mark, err)
2375 return
2376 }
2377 if err := compareLocations(mark, got, want); err != nil {
2378 mark.errorf("implementation: %v", err)
2379 }
2380 }
2381
2382 func mcpToolMarker(mark marker, tool string, rawArgs string) {
2383 if !mark.run.test.mcp {
2384 mark.errorf("mcp not enabled: add -mcp")
2385 return
2386 }
2387 args := make(map[string]any)
2388 if err := json.Unmarshal([]byte(rawArgs), &args); err != nil {
2389 mark.errorf("fail to unmarshal arguments to map[string]any: %v", err)
2390 return
2391 }
2392
2393 // substitutePaths replaces instances of $WORKDIR in string or []string values with
2394 // the actual working directory.
2395 var substitutePaths func(any) any
2396 substitutePaths = func(v any) any {
2397 switch v := v.(type) {
2398 case string:
2399 return strings.ReplaceAll(v, "$WORKDIR", mark.run.env.Sandbox.Workdir.RootURI().Path())
2400
2401 case []any:
2402 for i, e := range v {
2403 if _, ok := e.(string); ok {
2404 v[i] = substitutePaths(e).(string)
2405 }
2406 }
2407 }
2408 return v
2409 }
2410 // Hack: replace '$WORKDIR' in string arguments with the actual sandbox
2411 // working directory.
2412 for k, v := range args {
2413 args[k] = substitutePaths(v)
2414 }
2415
2416 if loc := namedArg(mark, "location", protocol.Location{}); loc != (protocol.Location{}) {
2417 args["location"] = loc
2418 }
2419
2420 res, err := mark.run.env.MCPSession.CallTool(mark.ctx(), &mcp.CallToolParams{
2421 Name: tool,
2422 Arguments: args,
2423 })
2424 if err != nil {
2425 mark.errorf("failed to call mcp tool: %v", err)
2426 return
2427 }
2428
2429 var buf bytes.Buffer
2430 for i, c := range res.Content {
2431 text, ok := c.(*mcp.TextContent)
2432 if !ok {
2433 mark.errorf("unsupported return content[%v] type: %T", i, c)
2434 continue
2435 }
2436 buf.WriteString(text.Text)
2437 }
2438 if !bytes.HasSuffix(buf.Bytes(), []byte{'\n'}) {
2439 buf.WriteString("\n") // all golden content is newline terminated
2440 }
2441
2442 got := buf.String()
2443 // For portability, replace all (potential) filepath separators with "/".
2444 got = strings.ReplaceAll(got, string(filepath.Separator), "/")
2445 // To ensure consistent unified diff output, the working directory path
2446 // is replaced with "$WORKDIR". This addresses cases where MCP tools
2447 // include absolute file paths in generated diffs.
2448 got = strings.ReplaceAll(got, filepath.ToSlash(mark.run.env.Sandbox.Workdir.RootURI().Path()), "$WORKDIR")
2449
2450 output := namedArg(mark, "output", expect.Identifier(""))
2451 golden := mark.getGolden(output)
2452 want, _ := golden.Get(mark.T(), "", []byte(got))
2453 if diff := compare.Text(string(want), got); diff != "" {
2454 mark.errorf("unexpected mcp tools call %s return: diff:\n%s", tool, diff)
2455 }
2456 }
2457
2458 func incomingCallsMarker(mark marker, src protocol.Location, want ...protocol.Location) {
2459 getCalls := func(item protocol.CallHierarchyItem) ([]protocol.Location, error) {
2460 calls, err := mark.server().IncomingCalls(mark.ctx(), &protocol.CallHierarchyIncomingCallsParams{Item: item})
2461 if err != nil {
2462 return nil, err
2463 }
2464 var locs []protocol.Location
2465 for _, call := range calls {
2466 locs = append(locs, call.From.URI.Location(call.From.Range))
2467 }
2468 return locs, nil
2469 }
2470 callHierarchy(mark, src, getCalls, want)
2471 }
2472
2473 func outgoingCallsMarker(mark marker, src protocol.Location, want ...protocol.Location) {
2474 getCalls := func(item protocol.CallHierarchyItem) ([]protocol.Location, error) {
2475 calls, err := mark.server().OutgoingCalls(mark.ctx(), &protocol.CallHierarchyOutgoingCallsParams{Item: item})
2476 if err != nil {
2477 return nil, err
2478 }
2479 var locs []protocol.Location
2480 for _, call := range calls {
2481 locs = append(locs, call.To.URI.Location(call.To.Range))
2482 }
2483 return locs, nil
2484 }
2485 callHierarchy(mark, src, getCalls, want)
2486 }
2487
2488 type callHierarchyFunc = func(protocol.CallHierarchyItem) ([]protocol.Location, error)
2489
2490 func callHierarchy(mark marker, src protocol.Location, getCalls callHierarchyFunc, want []protocol.Location) {
2491 items, err := mark.server().PrepareCallHierarchy(mark.ctx(), &protocol.CallHierarchyPrepareParams{
2492 TextDocumentPositionParams: protocol.LocationTextDocumentPositionParams(src),
2493 })
2494 if err != nil {
2495 mark.errorf("PrepareCallHierarchy failed: %v", err)
2496 return
2497 }
2498 if nitems := len(items); nitems != 1 {
2499 mark.errorf("PrepareCallHierarchy returned %d items, want exactly 1", nitems)
2500 return
2501 }
2502 item := items[0]
2503 if loc := item.URI.Location(item.Range); loc != src {
2504 mark.errorf("PrepareCallHierarchy found call %v, want %v", loc, src)
2505 return
2506 }
2507 calls, err := getCalls(items[0])
2508 if err != nil {
2509 mark.errorf("call hierarchy failed: %v", err)
2510 return
2511 }
2512 if err := compareLocations(mark, calls, want); err != nil {
2513 mark.errorf("%s failed: %v", mark.note.Name, err)
2514 }
2515 }
2516
2517 func inlayhintsMarker(mark marker, g *Golden) {
2518 hints := mark.run.env.InlayHints(mark.path())
2519
2520 // Map inlay hints to text edits.
2521 edits := make([]protocol.TextEdit, len(hints))
2522 for i, hint := range hints {
2523 var paddingLeft, paddingRight string
2524 if hint.PaddingLeft {
2525 paddingLeft = " "
2526 }
2527 if hint.PaddingRight {
2528 paddingRight = " "
2529 }
2530 edits[i] = protocol.TextEdit{
2531 Range: protocol.Range{Start: hint.Position, End: hint.Position},
2532 NewText: fmt.Sprintf("<%s%s%s>", paddingLeft, hint.Label[0].Value, paddingRight),
2533 }
2534 }
2535
2536 m := mark.mapper()
2537 got, _, err := protocol.ApplyEdits(m, edits)
2538 if err != nil {
2539 mark.errorf("ApplyProtocolEdits: %v", err)
2540 return
2541 }
2542
2543 compareGolden(mark, got, g)
2544 }
2545
2546 func prepareRenameMarker(mark marker, src protocol.Location, placeholder string) {
2547 params := &protocol.PrepareRenameParams{
2548 TextDocumentPositionParams: protocol.LocationTextDocumentPositionParams(src),
2549 }
2550 got, err := mark.server().PrepareRename(mark.ctx(), params)
2551 if err != nil {
2552 mark.T().Fatal(err)
2553 }
2554 if placeholder == "" {
2555 if got != nil {
2556 mark.errorf("PrepareRename(...) = %v, want nil", got)
2557 }
2558 return
2559 }
2560
2561 want := &protocol.PrepareRenameResult{
2562 Placeholder: placeholder,
2563 }
2564 if span := namedArg(mark, "span", protocol.Location{}); span != (protocol.Location{}) {
2565 want.Range = span.Range
2566 } else {
2567 got.Range = protocol.Range{} // ignore Range
2568 }
2569 if diff := cmp.Diff(want, got); diff != "" {
2570 mark.errorf("mismatching PrepareRename result:\n%s", diff)
2571 }
2572 }
2573
2574 func subtypesMarker(mark marker, src protocol.Location, want ...protocol.Location) {
2575 typeHierarchy(mark, src, want, func(item protocol.TypeHierarchyItem) ([]protocol.TypeHierarchyItem, error) {
2576 return mark.server().Subtypes(mark.ctx(), &protocol.TypeHierarchySubtypesParams{Item: item})
2577 })
2578 }
2579
2580 func supertypesMarker(mark marker, src protocol.Location, want ...protocol.Location) {
2581 typeHierarchy(mark, src, want, func(item protocol.TypeHierarchyItem) ([]protocol.TypeHierarchyItem, error) {
2582 return mark.server().Supertypes(mark.ctx(), &protocol.TypeHierarchySupertypesParams{Item: item})
2583 })
2584 }
2585
2586 type typeHierarchyFunc = func(item protocol.TypeHierarchyItem) ([]protocol.TypeHierarchyItem, error)
2587
2588 func typeHierarchy(mark marker, src protocol.Location, want []protocol.Location, get typeHierarchyFunc) {
2589 items, err := mark.server().PrepareTypeHierarchy(mark.ctx(), &protocol.TypeHierarchyPrepareParams{
2590 TextDocumentPositionParams: protocol.LocationTextDocumentPositionParams(src),
2591 })
2592 if err != nil {
2593 mark.errorf("PrepareTypeHierarchy failed: %v", err)
2594 return
2595 }
2596 if nitems := len(items); nitems != 1 {
2597 mark.errorf("PrepareTypeHierarchy returned %d items, want exactly 1", nitems)
2598 return
2599 }
2600 if loc := (protocol.Location{URI: items[0].URI, Range: items[0].Range}); loc != src {
2601 mark.errorf("PrepareTypeHierarchy found type %v, want %v", loc, src)
2602 return
2603 }
2604 items, err = get(items[0])
2605 if err != nil {
2606 mark.errorf("type hierarchy failed: %v", err)
2607 return
2608 }
2609 got := []protocol.Location{} // non-nil; cmp.Diff cares
2610 for _, item := range items {
2611 got = append(got, item.URI.Location(item.Range))
2612 }
2613 if d := cmp.Diff(want, got); d != "" {
2614 mark.errorf("type hierarchy: unexpected results (-want +got):\n%s", d)
2615 }
2616 }
2617
2618 // symbolMarker implements the @symbol marker.
2619 func symbolMarker(mark marker, golden *Golden) {
2620 // Retrieve information about all symbols in this file.
2621 symbols, err := mark.server().DocumentSymbol(mark.ctx(), &protocol.DocumentSymbolParams{
2622 TextDocument: protocol.TextDocumentIdentifier{URI: mark.uri()},
2623 })
2624 if err != nil {
2625 mark.errorf("DocumentSymbol request failed: %v", err)
2626 return
2627 }
2628
2629 // Format symbols one per line, sorted (in effect) by first column, a dotted name.
2630 var lines []string
2631 for _, symbol := range symbols {
2632 // Each result element is a union of (legacy)
2633 // SymbolInformation and (new) DocumentSymbol,
2634 // so we ascertain which one and then transcode.
2635 data, err := json.Marshal(symbol)
2636 if err != nil {
2637 mark.T().Fatal(err)
2638 }
2639 if _, ok := symbol.(map[string]any)["location"]; ok {
2640 // This case is not reached because Editor initialization
2641 // enables HierarchicalDocumentSymbolSupport.
2642 // TODO(adonovan): test this too.
2643 var sym protocol.SymbolInformation
2644 if err := json.Unmarshal(data, &sym); err != nil {
2645 mark.T().Fatal(err)
2646 }
2647 mark.errorf("fake Editor doesn't support SymbolInformation")
2648
2649 } else {
2650 var sym protocol.DocumentSymbol // new hierarchical hotness
2651 if err := json.Unmarshal(data, &sym); err != nil {
2652 mark.T().Fatal(err)
2653 }
2654
2655 // Print each symbol in the response tree.
2656 var visit func(sym protocol.DocumentSymbol, prefix []string)
2657 visit = func(sym protocol.DocumentSymbol, prefix []string) {
2658 var out strings.Builder
2659 out.WriteString(strings.Join(prefix, "."))
2660 fmt.Fprintf(&out, " %q", sym.Detail)
2661 if delta := sym.Range.End.Line - sym.Range.Start.Line; delta > 0 {
2662 fmt.Fprintf(&out, " +%d lines", delta)
2663 }
2664 lines = append(lines, out.String())
2665
2666 for _, child := range sym.Children {
2667 visit(child, append(prefix, child.Name))
2668 }
2669 }
2670 visit(sym, []string{sym.Name})
2671 }
2672 }
2673 sort.Strings(lines)
2674 lines = append(lines, "") // match trailing newline in .txtar file
2675 got := []byte(strings.Join(lines, "\n"))
2676
2677 // Compare with golden.
2678 want, ok := golden.Get(mark.T(), "", got)
2679 if !ok {
2680 mark.errorf("%s: missing golden file @%s", mark.note.Name, golden.id)
2681 } else if diff := cmp.Diff(string(got), string(want)); diff != "" {
2682 mark.errorf("%s: unexpected output: got:\n%s\nwant:\n%s\ndiff:\n%s",
2683 mark.note.Name, got, want, diff)
2684 }
2685 }
2686
2687 // compareLocations returns an error message if got and want are not
2688 // the same set of locations. The marker is used only for fmtLoc.
2689 func compareLocations(mark marker, got, want []protocol.Location) error {
2690 toStrings := func(locs []protocol.Location) []string {
2691 strs := make([]string, len(locs))
2692 for i, loc := range locs {
2693 strs[i] = mark.run.fmtLoc(loc)
2694 }
2695 sort.Strings(strs)
2696 return strs
2697 }
2698 if diff := cmp.Diff(toStrings(want), toStrings(got)); diff != "" {
2699 return fmt.Errorf("incorrect result locations: (got %d, want %d):\n%s",
2700 len(got), len(want), diff)
2701 }
2702 return nil
2703 }
2704
2705 func workspaceSymbolMarker(mark marker, query string, golden *Golden) {
2706 params := &protocol.WorkspaceSymbolParams{
2707 Query: query,
2708 }
2709
2710 gotSymbols, err := mark.server().Symbol(mark.ctx(), params)
2711 if err != nil {
2712 mark.errorf("Symbol(%q) failed: %v", query, err)
2713 return
2714 }
2715 var got bytes.Buffer
2716 for _, s := range gotSymbols {
2717 // Omit the txtar position of the symbol location; otherwise edits to the
2718 // txtar archive lead to unexpected failures.
2719 loc := mark.run.fmtLocForGolden(s.Location)
2720 if loc == "" {
2721 loc = "<unknown>"
2722 }
2723 fmt.Fprintf(&got, "%s %s %s\n", loc, s.Name, s.Kind)
2724 }
2725
2726 compareGolden(mark, got.Bytes(), golden)
2727 }
2728
2729 // compareGolden compares the content of got with that of g.Get(""), reporting
2730 // errors on any mismatch.
2731 //
2732 // TODO(rfindley): use this helper in more places.
2733 func compareGolden(mark marker, got []byte, g *Golden) {
2734 want, ok := g.Get(mark.T(), "", got)
2735 if !ok {
2736 mark.errorf("missing golden file @%s", g.id)
2737 return
2738 }
2739 // Normalize newline termination: archive files (i.e. Golden content) can't
2740 // contain non-newline terminated files, except in the special case where the
2741 // file is completely empty.
2742 //
2743 // Note that txtar partitions a contiguous byte slice, so we must copy before
2744 // appending.
2745 normalize := func(s []byte) []byte {
2746 if n := len(s); n > 0 && s[n-1] != '\n' {
2747 s = append(s[:n:n], '\n') // don't mutate array
2748 }
2749 return s
2750 }
2751 got = normalize(got)
2752 want = normalize(want)
2753 if diff := compare.Bytes(want, got); diff != "" {
2754 mark.errorf("%s does not match @%s:\n%s", mark.note.Name, g.id, diff)
2755 }
2756 }