Skip to content

Commit 46a0401

Browse files
committed
gopls: eliminate the hooks package
Simplify some of the legacy indirection that used to be required when the bulk of gopls' implementation lived in the x/tools module. We no longer need to set hooks on the settings.Options; hooked-in implementations can simply be statically linked. Remove the settings.Hooks type, and pull the thread as far as it will go, cleaning up a bunch of unnecessary indirection. As a result, we no longer need the hooks package. Change-Id: Ifd71da13174af4b7bc733f97774830ec1d98a2bc Reviewed-on: https://go-review.googlesource.com/c/tools/+/578039 LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Alan Donovan <[email protected]>
1 parent e388fff commit 46a0401

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

47 files changed

+338
-450
lines changed

gopls/doc/generate.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ func loadAPI() (*settings.APIJSON, error) {
111111
defaults := settings.DefaultOptions()
112112
api := &settings.APIJSON{
113113
Options: map[string][]*settings.OptionJSON{},
114-
Analyzers: loadAnalyzers(defaults.DefaultAnalyzers), // no staticcheck analyzers
114+
Analyzers: loadAnalyzers(settings.DefaultAnalyzers), // no staticcheck analyzers
115115
}
116116

117117
api.Commands, err = loadCommands()
@@ -508,17 +508,17 @@ func loadLenses(commands []*settings.CommandJSON) []*settings.LensJSON {
508508
func loadAnalyzers(m map[string]*settings.Analyzer) []*settings.AnalyzerJSON {
509509
var sorted []string
510510
for _, a := range m {
511-
sorted = append(sorted, a.Analyzer.Name)
511+
sorted = append(sorted, a.Analyzer().Name)
512512
}
513513
sort.Strings(sorted)
514514
var json []*settings.AnalyzerJSON
515515
for _, name := range sorted {
516516
a := m[name]
517517
json = append(json, &settings.AnalyzerJSON{
518-
Name: a.Analyzer.Name,
519-
Doc: a.Analyzer.Doc,
520-
URL: a.Analyzer.URL,
521-
Default: a.Enabled,
518+
Name: a.Analyzer().Name,
519+
Doc: a.Analyzer().Doc,
520+
URL: a.Analyzer().URL,
521+
Default: a.EnabledByDefault(),
522522
})
523523
}
524524
return json

gopls/internal/cache/analysis.go

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -192,30 +192,30 @@ func (s *Snapshot) Analyze(ctx context.Context, pkgs map[PackageID]*metadata.Pac
192192
// Filter and sort enabled root analyzers.
193193
// A disabled analyzer may still be run if required by another.
194194
toSrc := make(map[*analysis.Analyzer]*settings.Analyzer)
195-
var enabled []*analysis.Analyzer // enabled subset + transitive requirements
195+
var enabledAnalyzers []*analysis.Analyzer // enabled subset + transitive requirements
196196
for _, a := range analyzers {
197-
if a.IsEnabled(s.Options()) {
198-
toSrc[a.Analyzer] = a
199-
enabled = append(enabled, a.Analyzer)
197+
if enabled, ok := s.Options().Analyses[a.Analyzer().Name]; enabled || !ok && a.EnabledByDefault() {
198+
toSrc[a.Analyzer()] = a
199+
enabledAnalyzers = append(enabledAnalyzers, a.Analyzer())
200200
}
201201
}
202-
sort.Slice(enabled, func(i, j int) bool {
203-
return enabled[i].Name < enabled[j].Name
202+
sort.Slice(enabledAnalyzers, func(i, j int) bool {
203+
return enabledAnalyzers[i].Name < enabledAnalyzers[j].Name
204204
})
205205
analyzers = nil // prevent accidental use
206206

207-
enabled = requiredAnalyzers(enabled)
207+
enabledAnalyzers = requiredAnalyzers(enabledAnalyzers)
208208

209209
// Perform basic sanity checks.
210210
// (Ideally we would do this only once.)
211-
if err := analysis.Validate(enabled); err != nil {
211+
if err := analysis.Validate(enabledAnalyzers); err != nil {
212212
return nil, fmt.Errorf("invalid analyzer configuration: %v", err)
213213
}
214214

215215
stableNames := make(map[*analysis.Analyzer]string)
216216

217217
var facty []*analysis.Analyzer // facty subset of enabled + transitive requirements
218-
for _, a := range enabled {
218+
for _, a := range enabledAnalyzers {
219219
// TODO(adonovan): reject duplicate stable names (very unlikely).
220220
stableNames[a] = stableName(a)
221221

@@ -317,7 +317,7 @@ func (s *Snapshot) Analyze(ctx context.Context, pkgs map[PackageID]*metadata.Pac
317317
if err != nil {
318318
return nil, err
319319
}
320-
root.analyzers = enabled
320+
root.analyzers = enabledAnalyzers
321321
roots = append(roots, root)
322322
}
323323

@@ -451,7 +451,7 @@ func (s *Snapshot) Analyze(ctx context.Context, pkgs map[PackageID]*metadata.Pac
451451
// results, we should propagate the per-action errors.
452452
var results []*Diagnostic
453453
for _, root := range roots {
454-
for _, a := range enabled {
454+
for _, a := range enabledAnalyzers {
455455
// Skip analyzers that were added only to
456456
// fulfil requirements of the original set.
457457
srcAnalyzer, ok := toSrc[a]

gopls/internal/cache/errors.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,7 @@ func toSourceDiagnostic(srcAnalyzer *settings.Analyzer, gobDiag *gobDiagnostic)
279279
related = append(related, protocol.DiagnosticRelatedInformation(gobRelated))
280280
}
281281

282-
severity := srcAnalyzer.Severity
282+
severity := srcAnalyzer.Severity()
283283
if severity == 0 {
284284
severity = protocol.SeverityWarning
285285
}
@@ -293,15 +293,15 @@ func toSourceDiagnostic(srcAnalyzer *settings.Analyzer, gobDiag *gobDiagnostic)
293293
Source: DiagnosticSource(gobDiag.Source),
294294
Message: gobDiag.Message,
295295
Related: related,
296-
Tags: srcAnalyzer.Tag,
296+
Tags: srcAnalyzer.Tags(),
297297
}
298298

299299
// We cross the set of fixes (whether edit- or command-based)
300300
// with the set of kinds, as a single fix may represent more
301301
// than one kind of action (e.g. refactor, quickfix, fixall),
302302
// each corresponding to a distinct client UI element
303303
// or operation.
304-
kinds := srcAnalyzer.ActionKinds
304+
kinds := srcAnalyzer.ActionKinds()
305305
if len(kinds) == 0 {
306306
kinds = []protocol.CodeActionKind{protocol.QuickFix}
307307
}

gopls/internal/cmd/capabilities_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ func TestCapabilities(t *testing.T) {
4040
}
4141
defer os.RemoveAll(tmpDir)
4242

43-
app := New(nil)
43+
app := New()
4444

4545
params := &protocol.ParamInitialize{}
4646
params.RootURI = protocol.URIFromPath(tmpDir)

gopls/internal/cmd/check.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,9 @@ func (c *check) Run(ctx context.Context, args ...string) error {
4545
// false. Investigate.
4646
origOptions := c.app.options
4747
c.app.options = func(opts *settings.Options) {
48-
origOptions(opts)
48+
if origOptions != nil {
49+
origOptions(opts)
50+
}
4951
opts.RelatedInformationSupported = true
5052
}
5153

gopls/internal/cmd/cmd.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,9 +95,8 @@ func (app *Application) verbose() bool {
9595
}
9696

9797
// New returns a new Application ready to run.
98-
func New(options func(*settings.Options)) *Application {
98+
func New() *Application {
9999
app := &Application{
100-
options: options,
101100
OCAgent: "off", //TODO: Remove this line to default the exporter to on
102101

103102
Serve: Serve{

gopls/internal/cmd/codelens.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,9 @@ func (r *codelens) Run(ctx context.Context, args ...string) error {
7474
// See golang.LensFuncs().
7575
origOptions := r.app.options
7676
r.app.options = func(opts *settings.Options) {
77-
origOptions(opts)
77+
if origOptions != nil {
78+
origOptions(opts)
79+
}
7880
if opts.Codelenses == nil {
7981
opts.Codelenses = make(map[string]bool)
8082
}

gopls/internal/cmd/help_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ const appName = "gopls"
3232

3333
func TestHelpFiles(t *testing.T) {
3434
testenv.NeedsGoBuild(t) // This is a lie. We actually need the source code.
35-
app := cmd.New(nil)
35+
app := cmd.New()
3636
ctx := context.Background()
3737
for _, page := range append(app.Commands(), app) {
3838
t.Run(page.Name(), func(t *testing.T) {
@@ -65,7 +65,7 @@ func TestHelpFiles(t *testing.T) {
6565

6666
func TestVerboseHelp(t *testing.T) {
6767
testenv.NeedsGoBuild(t) // This is a lie. We actually need the source code.
68-
app := cmd.New(nil)
68+
app := cmd.New()
6969
ctx := context.Background()
7070
var buf bytes.Buffer
7171
s := flag.NewFlagSet(appName, flag.ContinueOnError)

gopls/internal/cmd/info.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919

2020
"golang.org/x/tools/gopls/internal/debug"
2121
"golang.org/x/tools/gopls/internal/filecache"
22+
licensespkg "golang.org/x/tools/gopls/internal/licenses"
2223
"golang.org/x/tools/gopls/internal/settings"
2324
"golang.org/x/tools/gopls/internal/util/browser"
2425
goplsbug "golang.org/x/tools/gopls/internal/util/bug"
@@ -301,12 +302,11 @@ gopls also includes software made available under these licenses:
301302
`
302303

303304
func (l *licenses) Run(ctx context.Context, args ...string) error {
304-
opts := settings.DefaultOptions(l.app.options)
305305
txt := licensePreamble
306-
if opts.LicensesText == "" {
306+
if licensespkg.Text == "" {
307307
txt += "(development gopls, license information not available)"
308308
} else {
309-
txt += opts.LicensesText
309+
txt += licensespkg.Text
310310
}
311311
fmt.Fprint(os.Stdout, txt)
312312
return nil

gopls/internal/cmd/integration_test.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ import (
4040

4141
"golang.org/x/tools/gopls/internal/cmd"
4242
"golang.org/x/tools/gopls/internal/debug"
43-
"golang.org/x/tools/gopls/internal/hooks"
4443
"golang.org/x/tools/gopls/internal/protocol"
4544
"golang.org/x/tools/gopls/internal/util/bug"
4645
"golang.org/x/tools/gopls/internal/version"
@@ -1060,7 +1059,7 @@ func goplsMain() {
10601059
version.VersionOverride = v
10611060
}
10621061

1063-
tool.Main(context.Background(), cmd.New(hooks.Options), os.Args[1:])
1062+
tool.Main(context.Background(), cmd.New(), os.Args[1:])
10641063
}
10651064

10661065
// writeTree extracts a txtar archive into a new directory and returns its path.

gopls/internal/cmd/semantictokens.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,9 @@ func (c *semtok) Run(ctx context.Context, args ...string) error {
6666
// perhaps simpler if app had just had a FlagSet member
6767
origOptions := c.app.options
6868
c.app.options = func(opts *settings.Options) {
69-
origOptions(opts)
69+
if origOptions != nil {
70+
origOptions(opts)
71+
}
7072
opts.SemanticTokens = true
7173
}
7274
conn, err := c.app.connect(ctx, nil)

gopls/internal/golang/diagnostics.go

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,24 +19,18 @@ import (
1919
//
2020
// If the provided tracker is non-nil, it may be used to provide notifications
2121
// of the ongoing analysis pass.
22+
//
23+
// TODO(rfindley): merge this with snapshot.Analyze.
2224
func Analyze(ctx context.Context, snapshot *cache.Snapshot, pkgIDs map[PackageID]*metadata.Package, tracker *progress.Tracker) (map[protocol.DocumentURI][]*cache.Diagnostic, error) {
2325
// Exit early if the context has been canceled. This also protects us
2426
// from a race on Options, see golang/go#36699.
2527
if ctx.Err() != nil {
2628
return nil, ctx.Err()
2729
}
2830

29-
options := snapshot.Options()
30-
categories := []map[string]*settings.Analyzer{
31-
options.DefaultAnalyzers,
32-
options.StaticcheckAnalyzers,
33-
}
34-
35-
var analyzers []*settings.Analyzer
36-
for _, cat := range categories {
37-
for _, a := range cat {
38-
analyzers = append(analyzers, a)
39-
}
31+
analyzers := maps.Values(settings.DefaultAnalyzers)
32+
if snapshot.Options().Staticcheck {
33+
analyzers = append(analyzers, maps.Values(settings.StaticcheckAnalyzers)...)
4034
}
4135

4236
analysisDiagnostics, err := snapshot.Analyze(ctx, pkgIDs, analyzers, tracker)

gopls/internal/golang/format.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"golang.org/x/tools/gopls/internal/cache/parsego"
2222
"golang.org/x/tools/gopls/internal/file"
2323
"golang.org/x/tools/gopls/internal/protocol"
24+
"golang.org/x/tools/gopls/internal/settings"
2425
"golang.org/x/tools/gopls/internal/util/safetoken"
2526
"golang.org/x/tools/internal/diff"
2627
"golang.org/x/tools/internal/event"
@@ -66,7 +67,7 @@ func Format(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) ([]pr
6667

6768
// Apply additional formatting, if any is supported. Currently, the only
6869
// supported additional formatter is gofumpt.
69-
if format := snapshot.Options().GofumptFormat; snapshot.Options().Gofumpt && format != nil {
70+
if format := settings.GofumptFormat; snapshot.Options().Gofumpt && format != nil {
7071
// gofumpt can customize formatting based on language version and module
7172
// path, if available.
7273
//

gopls/internal/hooks/hooks.go

Lines changed: 0 additions & 20 deletions
This file was deleted.

gopls/internal/hooks/gen-licenses.sh renamed to gopls/internal/licenses/gen-licenses.sh

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@ cat > $tempfile <<END
1616
// license that can be found in the LICENSE file.
1717
1818
//go:generate ./gen-licenses.sh licenses.go
19-
package hooks
19+
package licenses
2020
21-
const licensesText = \`
21+
const Text = \`
2222
END
2323

2424
# List all the modules gopls depends on, except other golang.org modules, which
@@ -35,4 +35,4 @@ for mod in $mods; do
3535
done
3636

3737
echo "\`" >> $tempfile
38-
mv $tempfile $output
38+
mv $tempfile $output

gopls/internal/hooks/licenses.go renamed to gopls/internal/licenses/licenses.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
// license that can be found in the LICENSE file.
44

55
//go:generate ./gen-licenses.sh licenses.go
6-
package hooks
6+
package licenses
77

8-
const licensesText = `
8+
const Text = `
99
-- github.com/BurntSushi/toml COPYING --
1010
1111
The MIT License (MIT)

gopls/internal/hooks/licenses_test.go renamed to gopls/internal/licenses/licenses_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// Use of this source code is governed by a BSD-style
33
// license that can be found in the LICENSE file.
44

5-
package hooks
5+
package licenses_test
66

77
import (
88
"bytes"
@@ -42,6 +42,6 @@ func TestLicenses(t *testing.T) {
4242
t.Fatal(err)
4343
}
4444
if !bytes.Equal(got, want) {
45-
t.Error("combined license text needs updating. Run: `go generate ./internal/hooks` from the gopls module.")
45+
t.Error("combined license text needs updating. Run: `go generate ./internal/licenses` from the gopls module.")
4646
}
4747
}

gopls/internal/server/link.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
"golang.org/x/tools/gopls/internal/util/safetoken"
2626
"golang.org/x/tools/internal/event"
2727
"golang.org/x/tools/internal/event/tag"
28+
"mvdan.cc/xurls/v2"
2829
)
2930

3031
func (s *server) DocumentLink(ctx context.Context, params *protocol.DocumentLinkParams) (links []protocol.DocumentLink, err error) {
@@ -87,7 +88,7 @@ func modLinks(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) ([]
8788
}
8889

8990
// Get all the links that are contained in the comments of the file.
90-
urlRegexp := snapshot.Options().URLRegexp
91+
urlRegexp := xurls.Relaxed()
9192
for _, expr := range pm.File.Syntax.Stmt {
9293
comments := expr.Comment()
9394
if comments == nil {
@@ -159,7 +160,7 @@ func goLinks(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) ([]p
159160
}
160161
}
161162

162-
urlRegexp := snapshot.Options().URLRegexp
163+
urlRegexp := xurls.Relaxed()
163164

164165
// Gather links found in string literals.
165166
var str []*ast.BasicLit

gopls/internal/server/workspace.go

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -93,13 +93,7 @@ func (s *server) DidChangeConfiguration(ctx context.Context, _ *protocol.DidChan
9393
return err
9494
}
9595

96-
// Ignore hooks for the purposes of equality.
97-
sameOptions := reflect.DeepEqual(folder.Options.ClientOptions, opts.ClientOptions) &&
98-
reflect.DeepEqual(folder.Options.ServerOptions, opts.ServerOptions) &&
99-
reflect.DeepEqual(folder.Options.UserOptions, opts.UserOptions) &&
100-
reflect.DeepEqual(folder.Options.InternalOptions, opts.InternalOptions)
101-
102-
if !sameOptions {
96+
if !reflect.DeepEqual(folder.Options, opts) {
10397
changed = true
10498
}
10599
folderOpts[folder.Dir] = opts

0 commit comments

Comments
 (0)