You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@dubbo.apache.org by al...@apache.org on 2026/04/28 03:41:23 UTC
(dubbo-go) branch develop updated: feat: add variadic RPC warnings and checks (#3294)
This is an automated email from the ASF dual-hosted git repository.
AlexStocks pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/dubbo-go.git
The following commit(s) were added to refs/heads/develop by this push:
new 15053b325 feat: add variadic RPC warnings and checks (#3294)
15053b325 is described below
commit 15053b3254afaf5dbab640293d1b33fdbe76a7f8
Author: 承潜 <29...@qq.com>
AuthorDate: Tue Apr 28 11:41:18 2026 +0800
feat: add variadic RPC warnings and checks (#3294)
* feat: add variadic RPC warnings and checks
---
Makefile | 6 +-
README.md | 6 +
README_CN.md | 6 +
common/rpc_service.go | 38 ++
common/rpc_service_test.go | 67 ++
config/service_config.go | 2 +
config/service_config_test.go | 64 ++
server/server.go | 10 +
server/server_test.go | 99 +++
tools/variadicrpccheck/helpers_test.go | 748 ++++++++++++++++++++++
tools/variadicrpccheck/main.go | 44 ++
tools/variadicrpccheck/main_test.go | 60 ++
tools/variadicrpccheck/scan.go | 1088 ++++++++++++++++++++++++++++++++
tools/variadicrpccheck/scan_test.go | 542 ++++++++++++++++
14 files changed, 2779 insertions(+), 1 deletion(-)
diff --git a/Makefile b/Makefile
index 94f0ebaec..e7e13d67c 100644
--- a/Makefile
+++ b/Makefile
@@ -26,7 +26,7 @@ MAKEFLAGS += --no-print-directory
CLI_DIR = tools/dubbogo-cli
IMPORTS_FORMATTER_DIR = tools/imports-formatter
-.PHONY: help test fmt clean lint check-fmt
+.PHONY: help test fmt clean lint check-fmt rpc-contract-check
help:
@echo "Available commands:"
@@ -34,6 +34,7 @@ help:
@echo " clean - Clean test generate files"
@echo " fmt - Format code"
@echo " lint - Run golangci-lint"
+ @echo " rpc-contract-check - Warn about variadic RPC contracts"
# Run unit tests
test: clean
@@ -67,6 +68,9 @@ lint: install-golangci-lint
go vet ./...
golangci-lint run ./... --timeout=10m
+rpc-contract-check:
+ GOTOOLCHAIN=go1.25.0+auto go run ./tools/variadicrpccheck ./...
+
install-golangci-lint:
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.7.2
diff --git a/README.md b/README.md
index b16fb5ba4..eaec0c425 100644
--- a/README.md
+++ b/README.md
@@ -140,6 +140,12 @@ A formatting tool for Dubbo-Go developers that organizes Go `import` blocks acco
For usage details, see the [imports-formatter README](https://github.com/dubbogo/tools?tab=readme-ov-file#imports-formatter).
+### variadicrpccheck
+
+A warning-only scanner that detects exported variadic RPC contracts and prints migration guidance for cross-language scenarios.
+
+Run `make rpc-contract-check` to use it locally.
+
## Ecosystem
- [dubbo-go-samples](https://github.com/apache/dubbo-go-samples)
- [dubbo-go-pixiu which acting as a proxy to solve Dubbo multi-language interoperability](https://github.com/apache/dubbo-go-pixiu)
diff --git a/README_CN.md b/README_CN.md
index 5a3b61fae..4069e297a 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -130,6 +130,12 @@ func main() {
有关使用详情,请参阅 [imports-formatter README](https://github.com/dubbogo/tools?tab=readme-ov-file#imports-formatter)。
+### variadicrpccheck
+
+一个 warning-only 的扫描工具,用于检测导出的 variadic RPC 接口定义,并给出跨语言场景下的迁移建议。
+
+可以通过 `make rpc-contract-check` 在本地运行。
+
## 生态系统
- [dubbo-go-samples](https://github.com/apache/dubbo-go-samples)
diff --git a/common/rpc_service.go b/common/rpc_service.go
index cc936d3c1..4f014f4cf 100644
--- a/common/rpc_service.go
+++ b/common/rpc_service.go
@@ -329,6 +329,44 @@ func isExportedOrBuiltinType(t reflect.Type) bool {
return isExported(t.Name()) || t.PkgPath() == ""
}
+// VariadicRPCMethodNames returns exported RPC method names whose final
+// parameter uses Go variadic syntax (...T). The detection reuses suiteMethod so
+// only methods Dubbo-go would export as RPC methods are included.
+func VariadicRPCMethodNames(svc RPCService) []string {
+ return variadicRPCMethodNames(reflect.TypeOf(svc))
+}
+
+// WarnVariadicRPCMethods emits guidance for exported variadic RPC methods while
+// keeping existing services compatible.
+func WarnVariadicRPCMethods(serviceName string, svc RPCService) {
+ methodNames := VariadicRPCMethodNames(svc)
+ if len(methodNames) == 0 {
+ return
+ }
+
+ logger.Warnf(
+ "Service %s exports variadic RPC method(s): %s. Existing services remain supported, but new cross-language or generic contracts should avoid variadic (...T); prefer []T, request structs, or Triple + Protobuf IDL.",
+ serviceName,
+ strings.Join(methodNames, ", "),
+ )
+}
+
+func variadicRPCMethodNames(typ reflect.Type) []string {
+ if typ == nil {
+ return nil
+ }
+
+ methodNames := make([]string, 0)
+ for i := 0; i < typ.NumMethod(); i++ {
+ method := typ.Method(i)
+ if suiteMethod(method) != nil && method.Type.IsVariadic() {
+ methodNames = append(methodNames, method.Name)
+ }
+ }
+
+ return methodNames
+}
+
// suitableMethods returns suitable Rpc methods of typ
func suitableMethods(typ reflect.Type) (string, map[string]*MethodType) {
methods := make(map[string]*MethodType)
diff --git a/common/rpc_service_test.go b/common/rpc_service_test.go
index 222142582..4762d3a27 100644
--- a/common/rpc_service_test.go
+++ b/common/rpc_service_test.go
@@ -19,11 +19,14 @@ package common
import (
"context"
+ "fmt"
"reflect"
"testing"
)
import (
+ gostlogger "github.com/dubbogo/gost/log/logger"
+
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -91,6 +94,37 @@ func (s *TestService1) Reference() string {
return referenceTestPathDistinct
}
+// VariadicRPCService exposes variadic RPC methods for detection tests.
+type VariadicRPCService struct{}
+
+func (s *VariadicRPCService) Fanout(ctx context.Context, names ...string) error {
+ return nil
+}
+
+func (s *VariadicRPCService) Merge(ctx context.Context, prefix string, values ...int) (any, error) {
+ return values, nil
+}
+
+func (s *VariadicRPCService) LocalOnly(values ...string) int {
+ return len(values)
+}
+
+// NonRPCVariadicService exposes only local variadic helpers.
+type NonRPCVariadicService struct{}
+
+func (s *NonRPCVariadicService) LocalOnly(values ...string) int {
+ return len(values)
+}
+
+type captureCommonWarnLogger struct {
+ gostlogger.Logger
+ warns []string
+}
+
+func (l *captureCommonWarnLogger) Warnf(template string, args ...any) {
+ l.warns = append(l.warns, fmt.Sprintf(template, args...))
+}
+
func TestServiceMapRegister(t *testing.T) {
// lowercase
s0 := &testService{}
@@ -220,6 +254,39 @@ func TestSuiteMethod(t *testing.T) {
assert.Nil(t, methodType)
}
+// Test VariadicRPCMethodNames returns exported variadic RPC methods only
+func TestVariadicRPCMethodNames(t *testing.T) {
+ t.Run("returns variadic rpc methods only", func(t *testing.T) {
+ assert.Equal(t, []string{"Fanout", "Merge"}, VariadicRPCMethodNames(&VariadicRPCService{}))
+ })
+
+ t.Run("ignores non-rpc variadic methods", func(t *testing.T) {
+ assert.Empty(t, VariadicRPCMethodNames(&NonRPCVariadicService{}))
+ })
+
+ t.Run("handles nil services", func(t *testing.T) {
+ assert.Empty(t, VariadicRPCMethodNames(nil))
+ })
+}
+
+func TestWarnVariadicRPCMethods(t *testing.T) {
+ prev := gostlogger.GetLogger()
+ capture := &captureCommonWarnLogger{Logger: prev}
+ gostlogger.SetLogger(capture)
+ t.Cleanup(func() {
+ gostlogger.SetLogger(prev)
+ })
+
+ WarnVariadicRPCMethods("com.example.VariadicService", &VariadicRPCService{})
+ require.Len(t, capture.warns, 1)
+ assert.Contains(t, capture.warns[0], "com.example.VariadicService")
+ assert.Contains(t, capture.warns[0], "Fanout, Merge")
+ assert.Contains(t, capture.warns[0], "[]T")
+
+ WarnVariadicRPCMethods("com.example.LocalOnlyService", &NonRPCVariadicService{})
+ assert.Len(t, capture.warns, 1)
+}
+
type ServiceWithoutRef struct{}
func TestGetReference(t *testing.T) {
diff --git a/config/service_config.go b/config/service_config.go
index bc6e658a3..635d46e57 100644
--- a/config/service_config.go
+++ b/config/service_config.go
@@ -241,6 +241,8 @@ func (s *ServiceConfig) Export() error {
return nil
}
+ common.WarnVariadicRPCMethods(s.Interface, s.rpcService)
+
regUrls := make([]*common.URL, 0)
if !s.NotRegister {
regUrls = LoadRegistries(s.RegistryIDs, s.RCRegistriesMap, common.PROVIDER)
diff --git a/config/service_config_test.go b/config/service_config_test.go
index 634b6562c..8624a51ea 100644
--- a/config/service_config_test.go
+++ b/config/service_config_test.go
@@ -19,11 +19,14 @@ package config
import (
"context"
+ "fmt"
"strings"
"testing"
)
import (
+ gostlogger "github.com/dubbogo/gost/log/logger"
+
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -48,6 +51,25 @@ func (hs *HelloService) JavaClassName() string {
return "org.apache.dubbo.HelloService"
}
+type VariadicHelloService struct{}
+
+func (hs *VariadicHelloService) Fanout(ctx context.Context, names ...string) error {
+ return nil
+}
+
+func (hs *VariadicHelloService) Reference() string {
+ return "VariadicHelloService"
+}
+
+type serviceConfigCaptureWarnLogger struct {
+ gostlogger.Logger
+ warns []string
+}
+
+func (l *serviceConfigCaptureWarnLogger) Warnf(template string, args ...any) {
+ l.warns = append(l.warns, fmt.Sprintf(template, args...))
+}
+
func TestNewServiceConfigBuilder(t *testing.T) {
SetProviderService(&HelloService{})
var serviceConfig = newEmptyServiceConfig()
@@ -125,3 +147,45 @@ func TestNewServiceConfigBuilder(t *testing.T) {
assert.NotNil(t, serviceConfig.rpcService)
})
}
+
+func TestServiceConfigExportWarnsOnVariadicRPCMethods(t *testing.T) {
+ prev := gostlogger.GetLogger()
+ capture := &serviceConfigCaptureWarnLogger{Logger: prev}
+ gostlogger.SetLogger(capture)
+ t.Cleanup(func() {
+ gostlogger.SetLogger(prev)
+ })
+
+ serviceConfig := newEmptyServiceConfig()
+ serviceConfig.Interface = "com.example.VariadicHelloService"
+ serviceConfig.NotRegister = true
+ serviceConfig.rpcService = &VariadicHelloService{}
+
+ err := serviceConfig.Export()
+ require.NoError(t, err)
+
+ warns := strings.Join(capture.warns, "\n")
+ assert.Contains(t, warns, serviceConfig.Interface)
+ assert.Contains(t, warns, "Fanout")
+}
+
+func TestServiceConfigExportDoesNotWarnOnNonVariadicRPCMethods(t *testing.T) {
+ prev := gostlogger.GetLogger()
+ capture := &serviceConfigCaptureWarnLogger{Logger: prev}
+ gostlogger.SetLogger(capture)
+ t.Cleanup(func() {
+ gostlogger.SetLogger(prev)
+ })
+
+ serviceConfig := newEmptyServiceConfig()
+ serviceConfig.Interface = "org.apache.dubbo.HelloService"
+ serviceConfig.NotRegister = true
+ serviceConfig.rpcService = &HelloService{}
+
+ err := serviceConfig.Export()
+ require.NoError(t, err)
+
+ for _, warn := range capture.warns {
+ assert.NotContains(t, warn, "variadic RPC method")
+ }
+}
diff --git a/server/server.go b/server/server.go
index cff53f39f..0bfcda53b 100644
--- a/server/server.go
+++ b/server/server.go
@@ -178,9 +178,19 @@ func (s *Server) genSvcOpts(handler any, info *common.ServiceInfo, opts ...Servi
newSvcOpts.Id = interfaceName
newSvcOpts.Implement(handler)
newSvcOpts.info = enhanceServiceInfo(info)
+ // Warn on exported variadic RPC methods without blocking registration.
+ common.WarnVariadicRPCMethods(serviceNameForWarning(interfaceName, svcConf.Interface), handler)
return newSvcOpts, nil
}
+// serviceNameForWarning prefers the configured interface name in warning output.
+func serviceNameForWarning(reference, configuredInterface string) string {
+ if configuredInterface != "" {
+ return configuredInterface
+ }
+ return reference
+}
+
// isNillable checks if a reflect.Value's kind supports nil checking.
func isNillable(v reflect.Value) bool {
switch v.Kind() {
diff --git a/server/server_test.go b/server/server_test.go
index 9a4e309a7..5372f35a3 100644
--- a/server/server_test.go
+++ b/server/server_test.go
@@ -19,6 +19,7 @@ package server
import (
"context"
+ "fmt"
"reflect"
"strconv"
"sync"
@@ -27,6 +28,8 @@ import (
)
import (
+ gostlogger "github.com/dubbogo/gost/log/logger"
+
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -432,6 +435,35 @@ func (m *mockServerRPCService) Reference() string {
return "com.example.MockService"
}
+// variadicServerRPCService exposes a variadic RPC method for warning tests.
+type variadicServerRPCService struct{}
+
+func (m *variadicServerRPCService) Broadcast(ctx context.Context, names ...string) error {
+ return nil
+}
+
+func (m *variadicServerRPCService) Reference() string {
+ return "com.example.VariadicService"
+}
+
+// NoReferenceVariadicServerRPCService relies on the default reference fallback
+// for warning-path tests.
+type NoReferenceVariadicServerRPCService struct{}
+
+func (m *NoReferenceVariadicServerRPCService) Broadcast(ctx context.Context, names ...string) error {
+ return nil
+}
+
+// captureWarnLogger records warning logs for assertions.
+type captureWarnLogger struct {
+ gostlogger.Logger
+ warns []string
+}
+
+func (l *captureWarnLogger) Warnf(template string, args ...any) {
+ l.warns = append(l.warns, fmt.Sprintf(template, args...))
+}
+
// Test concurrency: multiple goroutines registering services
func TestConcurrentServiceRegistration(t *testing.T) {
srv, err := NewServer()
@@ -494,6 +526,73 @@ func TestRegisterService(t *testing.T) {
assert.NotNil(t, svcOpts)
}
+// Test RegisterService warns on variadic RPC methods
+func TestRegisterServiceWarnsOnVariadicRPCMethods(t *testing.T) {
+ srv, err := NewServer()
+ require.NoError(t, err)
+
+ prev := gostlogger.GetLogger()
+ capture := &captureWarnLogger{Logger: prev}
+ gostlogger.SetLogger(capture)
+ t.Cleanup(func() {
+ gostlogger.SetLogger(prev)
+ })
+
+ handler := &variadicServerRPCService{}
+ err = srv.RegisterService(handler)
+ require.NoError(t, err)
+
+ svcOpts := srv.GetServiceOptions(handler.Reference())
+ assert.NotNil(t, svcOpts)
+ require.Len(t, capture.warns, 1)
+ assert.Contains(t, capture.warns[0], handler.Reference())
+ assert.Contains(t, capture.warns[0], "Broadcast")
+ assert.Contains(t, capture.warns[0], "[]T")
+}
+
+// Test RegisterService warns on variadic RPC methods even when the handler
+// uses the default reference name.
+func TestRegisterServiceWarnsOnVariadicRPCMethodsWithoutReference(t *testing.T) {
+ srv, err := NewServer()
+ require.NoError(t, err)
+
+ prev := gostlogger.GetLogger()
+ capture := &captureWarnLogger{Logger: prev}
+ gostlogger.SetLogger(capture)
+ t.Cleanup(func() {
+ gostlogger.SetLogger(prev)
+ })
+
+ handler := &NoReferenceVariadicServerRPCService{}
+ err = srv.RegisterService(handler)
+ require.NoError(t, err)
+
+ interfaceName := common.GetReference(handler)
+ svcOpts := srv.GetServiceOptions(interfaceName)
+ assert.NotNil(t, svcOpts)
+ require.Len(t, capture.warns, 1)
+ assert.Contains(t, capture.warns[0], interfaceName)
+ assert.Contains(t, capture.warns[0], "Broadcast")
+}
+
+// Test RegisterService does not warn on non-variadic RPC methods
+func TestRegisterServiceDoesNotWarnOnNonVariadicRPCMethods(t *testing.T) {
+ srv, err := NewServer()
+ require.NoError(t, err)
+
+ prev := gostlogger.GetLogger()
+ capture := &captureWarnLogger{Logger: prev}
+ gostlogger.SetLogger(capture)
+ t.Cleanup(func() {
+ gostlogger.SetLogger(prev)
+ })
+
+ handler := &mockServerRPCService{}
+ err = srv.RegisterService(handler)
+ require.NoError(t, err)
+ assert.Empty(t, capture.warns)
+}
+
// Test Register with handler that has method config
func TestRegisterWithMethodConfig(t *testing.T) {
srv, err := NewServer()
diff --git a/tools/variadicrpccheck/helpers_test.go b/tools/variadicrpccheck/helpers_test.go
new file mode 100644
index 000000000..c99dcce21
--- /dev/null
+++ b/tools/variadicrpccheck/helpers_test.go
@@ -0,0 +1,748 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package main
+
+import (
+ "go/ast"
+ "go/token"
+ "go/types"
+ "testing"
+)
+
+import (
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "golang.org/x/tools/go/packages"
+)
+
+func TestNormalizePatterns(t *testing.T) {
+ assert.Equal(t, []string{"./..."}, normalizePatterns(nil))
+ assert.Equal(t, []string{"./internal/..."}, normalizePatterns([]string{"./internal/..."}))
+}
+
+func TestSortFindings(t *testing.T) {
+ t.Run("sorts by filename", func(t *testing.T) {
+ findings := []Finding{
+ {Position: token.Position{Filename: "b.go", Line: 1, Column: 1}},
+ {Position: token.Position{Filename: "a.go", Line: 1, Column: 1}},
+ }
+
+ sortFindings(findings)
+ assert.Equal(t, "a.go", findings[0].Position.Filename)
+ })
+
+ t.Run("sorts by line", func(t *testing.T) {
+ findings := []Finding{
+ {Position: token.Position{Filename: "a.go", Line: 2, Column: 1}},
+ {Position: token.Position{Filename: "a.go", Line: 1, Column: 1}},
+ }
+
+ sortFindings(findings)
+ assert.Equal(t, 1, findings[0].Position.Line)
+ })
+
+ t.Run("sorts by column kind type and method", func(t *testing.T) {
+ findings := []Finding{
+ {Position: token.Position{Filename: "a.go", Line: 1, Column: 2}, Kind: "implementation", TypeName: "B", MethodName: "B"},
+ {Position: token.Position{Filename: "a.go", Line: 1, Column: 1}, Kind: "interface", TypeName: "A", MethodName: "A"},
+ }
+
+ sortFindings(findings)
+ assert.Equal(t, 1, findings[0].Position.Column)
+ })
+
+ t.Run("sorts by kind", func(t *testing.T) {
+ findings := []Finding{
+ {Position: token.Position{Filename: "a.go", Line: 1, Column: 1}, Kind: "implementation", TypeName: "A", MethodName: "A"},
+ {Position: token.Position{Filename: "a.go", Line: 1, Column: 1}, Kind: "interface", TypeName: "A", MethodName: "A"},
+ }
+
+ sortFindings(findings)
+ assert.Equal(t, "implementation", findings[0].Kind)
+ })
+
+ t.Run("sorts by type and method name", func(t *testing.T) {
+ findings := []Finding{
+ {Position: token.Position{Filename: "a.go", Line: 1, Column: 1}, Kind: "interface", TypeName: "B", MethodName: "B"},
+ {Position: token.Position{Filename: "a.go", Line: 1, Column: 1}, Kind: "interface", TypeName: "A", MethodName: "A"},
+ }
+
+ sortFindings(findings)
+ assert.Equal(t, "A", findings[0].TypeName)
+
+ findings = []Finding{
+ {Position: token.Position{Filename: "a.go", Line: 1, Column: 1}, Kind: "interface", TypeName: "A", MethodName: "B"},
+ {Position: token.Position{Filename: "a.go", Line: 1, Column: 1}, Kind: "interface", TypeName: "A", MethodName: "A"},
+ }
+
+ sortFindings(findings)
+ assert.Equal(t, "A", findings[0].MethodName)
+ })
+}
+
+func TestPackageAndSignatureHelpers(t *testing.T) {
+ t.Run("packageErrors handles nil empty and populated packages", func(t *testing.T) {
+ assert.Nil(t, packageErrors(nil))
+ assert.Nil(t, packageErrors(&packages.Package{}))
+ assert.Equal(t, []string{"-: load failed"}, packageErrors(&packages.Package{
+ Errors: []packages.Error{{Msg: "load failed"}},
+ }))
+ })
+
+ t.Run("typeQualifier returns package path", func(t *testing.T) {
+ assert.Empty(t, typeQualifier(nil))
+ assert.Equal(t, "example.com/test", typeQualifier(types.NewPackage("example.com/test", "test")))
+ })
+
+ t.Run("receiverTypeName unwraps supported receiver forms", func(t *testing.T) {
+ assert.Equal(t, "Svc", receiverTypeName(&ast.Ident{Name: "Svc"}))
+ assert.Equal(t, "Svc", receiverTypeName(&ast.StarExpr{X: &ast.Ident{Name: "Svc"}}))
+ assert.Equal(t, "Svc", receiverTypeName(&ast.IndexExpr{X: &ast.Ident{Name: "Svc"}}))
+ assert.Equal(t, "Svc", receiverTypeName(&ast.IndexListExpr{X: &ast.Ident{Name: "Svc"}}))
+ assert.Empty(t, receiverTypeName(&ast.ArrayType{}))
+ })
+}
+
+func TestTypeFilters(t *testing.T) {
+ pkg := types.NewPackage("example.com/test", "test")
+ exported := types.NewNamed(types.NewTypeName(token.NoPos, pkg, "Visible", nil), types.Typ[types.Int], nil)
+ unexported := types.NewNamed(types.NewTypeName(token.NoPos, pkg, "hidden", nil), types.Typ[types.Int], nil)
+ option := types.NewNamed(types.NewTypeName(token.NoPos, pkg, "ClientOption", nil), types.Typ[types.Int], nil)
+ callOptionAlias := types.NewAlias(types.NewTypeName(token.NoPos, pkg, "CallOption", nil), types.Typ[types.Int])
+
+ assert.True(t, isExportedOrBuiltinGoType(types.NewPointer(exported)))
+ assert.False(t, isExportedOrBuiltinGoType(unexported))
+ assert.True(t, isExportedOrBuiltinGoType(types.NewSlice(types.Typ[types.String])))
+ assert.True(t, isExportedOrBuiltinGoType(callOptionAlias))
+
+ assert.True(t, isExportedOrBuiltinTypeName(nil))
+ assert.True(t, isExportedOrBuiltinTypeName(types.Universe.Lookup("string").(*types.TypeName)))
+ assert.False(t, isExportedOrBuiltinTypeName(types.NewTypeName(token.NoPos, pkg, "hiddenType", nil)))
+
+ assert.True(t, isOptionLikeVariadic(types.NewSlice(option)))
+ assert.False(t, isOptionLikeVariadic(types.Typ[types.Int]))
+
+ assert.True(t, isOptionLikeType(types.NewPointer(option)))
+ assert.True(t, isOptionLikeType(callOptionAlias))
+ assert.False(t, isOptionLikeType(types.NewSlice(types.Typ[types.String])))
+}
+
+func TestVariadicSignatureChecks(t *testing.T) {
+ errorType := types.Universe.Lookup("error").Type()
+ pkg := types.NewPackage("example.com/test", "test")
+ exportedReply := types.NewNamed(types.NewTypeName(token.NoPos, pkg, "VisibleReply", nil), types.Typ[types.Int], nil)
+ unexportedReply := types.NewNamed(types.NewTypeName(token.NoPos, pkg, "hiddenReply", nil), types.Typ[types.Int], nil)
+ unexportedArg := types.NewNamed(types.NewTypeName(token.NoPos, pkg, "hiddenArg", nil), types.Typ[types.Int], nil)
+ option := types.NewNamed(types.NewTypeName(token.NoPos, pkg, "ClientOption", nil), types.Typ[types.Int], nil)
+
+ assert.False(t, isVariadicRPCSignature(nil))
+ assert.False(t, isVariadicRPCSignature(testSignature(false, []types.Type{types.NewSlice(types.Typ[types.String])}, []types.Type{errorType})))
+ assert.False(t, isVariadicRPCSignature(testSignature(true, []types.Type{types.NewSlice(types.Typ[types.String])}, nil)))
+ assert.False(t, isVariadicRPCSignature(testSignature(true, []types.Type{types.NewSlice(types.Typ[types.String])}, []types.Type{types.Typ[types.Int]})))
+ assert.False(t, isVariadicRPCSignature(testSignature(true, []types.Type{types.NewSlice(types.Typ[types.String])}, []types.Type{unexportedReply, errorType})))
+ assert.False(t, isVariadicRPCSignature(testSignature(true, []types.Type{unexportedArg, types.NewSlice(types.Typ[types.String])}, []types.Type{errorType})))
+ assert.False(t, isVariadicRPCSignature(testSignature(true, []types.Type{types.NewSlice(option)}, []types.Type{errorType})))
+ assert.True(t, isVariadicRPCSignature(testSignature(true, []types.Type{types.NewSlice(types.Typ[types.String])}, []types.Type{exportedReply, errorType})))
+}
+
+func TestAstAndTypeHelpers(t *testing.T) {
+ // Guard-path coverage keeps missing type info from turning registration tracing into false positives.
+ t.Run("recordRegisteredImplementationType and registeredTypeKeyForExpr handle guard paths", func(t *testing.T) {
+ analyzer := ®istrationAnalyzer{}
+ registeredTypes := make(map[registeredTypeKey]struct{})
+
+ analyzer.recordRegisteredImplementationType(nil, registeredTypes, &ast.Ident{Name: "svc"}, token.NoPos)
+ analyzer.recordRegisteredImplementationType(&packages.Package{}, registeredTypes, &ast.Ident{Name: "svc"}, token.NoPos)
+ assert.Empty(t, registeredTypes)
+
+ pkg := &packages.Package{TypesInfo: &types.Info{}}
+ _, ok := analyzer.registeredTypeKeyForExpr(pkg, &ast.BasicLit{}, token.NoPos, nil)
+ assert.False(t, ok)
+
+ localPkg := types.NewPackage("example.com/test", "test")
+ varObj := types.NewVar(token.NoPos, localPkg, "svc", types.NewInterfaceType(nil, nil))
+ ident := &ast.Ident{Name: "svc"}
+ pkg = &packages.Package{
+ Types: localPkg,
+ TypesInfo: &types.Info{
+ Uses: map[*ast.Ident]types.Object{ident: varObj},
+ },
+ }
+
+ _, ok = analyzer.registeredTypeKeyForExpr(pkg, &ast.Ident{Name: "missing"}, token.NoPos, nil)
+ assert.False(t, ok)
+
+ _, ok = analyzer.registeredTypeKeyForExpr(pkg, ident, token.NoPos, map[types.Object]struct{}{varObj: {}})
+ assert.False(t, ok)
+
+ analyzer.varInitializers = map[string]map[types.Object][]assignmentRef{
+ "example.com/test": {varObj: nil},
+ }
+ _, ok = analyzer.registeredTypeKeyForExpr(pkg, ident, token.NoPos, nil)
+ assert.False(t, ok)
+ })
+
+ t.Run("collectPackageFindings skips syntax entries without compiled files", func(t *testing.T) {
+ pkg := &packages.Package{
+ Syntax: []*ast.File{{}},
+ }
+ assert.Empty(t, collectPackageFindings(pkg, nil))
+ })
+
+ t.Run("embeddedInterfaceType handles nil missing and valid type info", func(t *testing.T) {
+ assert.Nil(t, embeddedInterfaceType(nil, &ast.Ident{Name: "Embedded"}))
+
+ expr := &ast.Ident{Name: "Missing"}
+ pkg := &packages.Package{TypesInfo: &types.Info{Types: map[ast.Expr]types.TypeAndValue{}}}
+ assert.Nil(t, embeddedInterfaceType(pkg, expr))
+
+ iface := types.NewInterfaceType(nil, nil)
+ iface.Complete()
+ validExpr := &ast.Ident{Name: "Embedded"}
+ pkg.TypesInfo.Types[validExpr] = types.TypeAndValue{Type: iface}
+ assert.Same(t, iface, embeddedInterfaceType(pkg, validExpr))
+ })
+
+ t.Run("interfaceTypeForSpec and signatureForIdent return false without type info", func(t *testing.T) {
+ pkg := &packages.Package{TypesInfo: &types.Info{Defs: map[*ast.Ident]types.Object{}}}
+ typeSpec := &ast.TypeSpec{Name: &ast.Ident{Name: "Service"}}
+ _, ok := interfaceTypeForSpec(pkg, typeSpec)
+ assert.False(t, ok)
+
+ _, ok = signatureForIdent(pkg, &ast.Ident{Name: "MultiArgs"})
+ assert.False(t, ok)
+
+ assert.Nil(t, typeSpecInterfaceFindings(pkg, typeSpec, &ast.InterfaceType{}))
+ })
+
+ t.Run("interfaceMethodFinding covers fallback and rejection cases", func(t *testing.T) {
+ fset := token.NewFileSet()
+ file := fset.AddFile("service.go", -1, 64)
+ typePos := file.Pos(1)
+ typeSpec := &ast.TypeSpec{Name: &ast.Ident{Name: "Service", NamePos: typePos}}
+ pkg := &packages.Package{Fset: fset}
+
+ finding, ok := interfaceMethodFinding(pkg, typeSpec, types.NewFunc(token.NoPos, nil, "hidden", testSignature(true, []types.Type{types.NewSlice(types.Typ[types.String])}, []types.Type{types.Universe.Lookup("error").Type()})), nil)
+ assert.False(t, ok)
+ assert.Equal(t, Finding{}, finding)
+
+ finding, ok = interfaceMethodFinding(pkg, typeSpec, types.NewFunc(token.NoPos, nil, "MultiArgs", testSignature(true, []types.Type{types.NewSlice(types.Typ[types.String])}, []types.Type{types.Universe.Lookup("error").Type()})), map[string]token.Pos{})
+ require.True(t, ok)
+ assert.Equal(t, "service.go", finding.Position.Filename)
+ assert.Equal(t, "Service", finding.TypeName)
+ assert.Equal(t, "MultiArgs", finding.MethodName)
+
+ finding, ok = interfaceMethodFinding(pkg, typeSpec, types.NewFunc(token.NoPos, nil, "Reference", testSignature(true, []types.Type{types.NewSlice(types.Typ[types.String])}, []types.Type{types.Universe.Lookup("error").Type()})), map[string]token.Pos{})
+ assert.False(t, ok)
+ assert.Equal(t, Finding{}, finding)
+ })
+
+ t.Run("collectImplementationFinding rejects invalid declarations", func(t *testing.T) {
+ pkg := &packages.Package{TypesInfo: &types.Info{Defs: map[*ast.Ident]types.Object{}}}
+
+ _, ok := collectImplementationFinding(pkg, &ast.FuncDecl{Name: &ast.Ident{Name: "MultiArgs"}}, nil)
+ assert.False(t, ok)
+
+ _, ok = collectImplementationFinding(pkg, &ast.FuncDecl{
+ Name: &ast.Ident{Name: "multiArgs"},
+ Recv: &ast.FieldList{List: []*ast.Field{{Type: &ast.Ident{Name: "Service"}}}},
+ }, nil)
+ assert.False(t, ok)
+
+ _, ok = collectImplementationFinding(pkg, &ast.FuncDecl{
+ Name: &ast.Ident{Name: "Reference"},
+ Recv: &ast.FieldList{List: []*ast.Field{{Type: &ast.Ident{Name: "Service"}}}},
+ }, nil)
+ assert.False(t, ok)
+
+ _, ok = collectImplementationFinding(pkg, &ast.FuncDecl{
+ Name: &ast.Ident{Name: "MultiArgs"},
+ Recv: &ast.FieldList{List: []*ast.Field{{Type: &ast.ArrayType{}}}},
+ }, nil)
+ assert.False(t, ok)
+
+ _, ok = collectImplementationFinding(pkg, &ast.FuncDecl{
+ Name: &ast.Ident{Name: "MultiArgs"},
+ Recv: &ast.FieldList{List: []*ast.Field{{Type: &ast.Ident{Name: "Service"}}}},
+ }, map[registeredTypeKey]struct{}{{pkgPath: "example.com/test", typeName: "Other"}: {}})
+ assert.False(t, ok)
+
+ _, ok = collectImplementationFinding(pkg, &ast.FuncDecl{
+ Name: &ast.Ident{Name: "MultiArgs"},
+ Recv: &ast.FieldList{List: []*ast.Field{{Type: &ast.Ident{Name: "Service"}}}},
+ }, map[registeredTypeKey]struct{}{{pkgPath: "", typeName: "Service"}: {}})
+ assert.False(t, ok)
+ })
+
+ // Wrapper-resolution helpers should fail closed when helper bodies or forwarded parameters cannot be resolved.
+ t.Run("wrapper resolution helpers cover cache and reject paths", func(t *testing.T) {
+ key := functionKey{pkgPath: "example.com/test", name: "Register"}
+ analyzer := newRegistrationAnalyzer(nil)
+
+ state, ok, done := analyzer.cachedWrapperResolution(key)
+ require.NotNil(t, state)
+ assert.False(t, ok)
+ assert.False(t, done)
+
+ state.resolved = true
+ state.argIndex = 2
+ state, ok, done = analyzer.cachedWrapperResolution(key)
+ require.NotNil(t, state)
+ assert.True(t, ok)
+ assert.True(t, done)
+ assert.Equal(t, 2, state.argIndex)
+
+ state.resolved = false
+ state.resolving = true
+ _, ok, done = analyzer.cachedWrapperResolution(key)
+ assert.False(t, ok)
+ assert.True(t, done)
+
+ state.resolving = false
+ _, ok, done = analyzer.cachedWrapperResolution(key)
+ assert.False(t, ok)
+ assert.False(t, done)
+
+ analyzer.wrapperResolutions[key] = &wrapperResolution{argIndex: 1, resolved: true}
+ idx, ok := analyzer.wrapperHandlerArgumentIndex(key)
+ require.True(t, ok)
+ assert.Equal(t, 1, idx)
+
+ assert.False(t, shouldSkipPackageFile(&packages.Package{CompiledGoFiles: []string{"service.go"}}, 0, func(string) bool { return false }))
+ assert.True(t, shouldSkipPackageFile(&packages.Package{}, 1, func(string) bool { return false }))
+ assert.True(t, shouldSkipPackageFile(&packages.Package{CompiledGoFiles: []string{"service.go"}}, 0, func(string) bool { return true }))
+
+ ref := functionDeclRef{
+ pkg: &packages.Package{TypesInfo: &types.Info{}},
+ decl: &ast.FuncDecl{
+ Name: &ast.Ident{Name: "Register"},
+ Type: &ast.FuncType{Params: &ast.FieldList{}},
+ Body: &ast.BlockStmt{List: []ast.Stmt{&ast.ExprStmt{X: &ast.CallExpr{Fun: &ast.Ident{Name: "Call"}}}}},
+ },
+ }
+ params := map[types.Object]int{}
+ state = &wrapperResolution{}
+ _, ok = analyzer.resolveWrapperHandlerArgument(ref, params, state)
+ assert.False(t, ok)
+
+ _, ok = analyzer.wrapperHandlerArgumentIndex(functionKey{pkgPath: "example.com/test", name: "Missing"})
+ assert.False(t, ok)
+
+ analyzer.functionDecls = map[functionKey]functionDeclRef{
+ key: {
+ pkg: &packages.Package{TypesInfo: &types.Info{}},
+ decl: &ast.FuncDecl{Name: &ast.Ident{Name: "Register"}, Body: &ast.BlockStmt{}},
+ },
+ }
+ delete(analyzer.wrapperResolutions, key)
+ _, ok = analyzer.wrapperHandlerArgumentIndex(key)
+ assert.False(t, ok)
+
+ analyzer.functionDecls[key] = functionDeclRef{
+ pkg: &packages.Package{TypesInfo: &types.Info{}},
+ decl: &ast.FuncDecl{Name: &ast.Ident{Name: "Register"}},
+ }
+ _, ok = analyzer.wrapperHandlerArgumentIndex(key)
+ assert.False(t, ok)
+
+ _, ok = analyzer.wrapperParamIndexFromCall(ref.pkg, params, &ast.CallExpr{Fun: &ast.BasicLit{}})
+ assert.False(t, ok)
+ configPkg := types.NewPackage("dubbo.apache.org/dubbo-go/v3/config", "config")
+ helperSel := &ast.SelectorExpr{X: &ast.Ident{Name: "config"}, Sel: &ast.Ident{Name: "SetProviderService"}}
+ helperPkg := &packages.Package{
+ TypesInfo: &types.Info{
+ Uses: map[*ast.Ident]types.Object{
+ helperSel.Sel: types.NewFunc(token.NoPos, configPkg, "SetProviderService", testSignature(false, nil, nil)),
+ },
+ },
+ }
+ _, ok = analyzer.wrapperParamIndexFromCall(helperPkg, params, &ast.CallExpr{Fun: helperSel, Args: []ast.Expr{&ast.BasicLit{}}})
+ assert.False(t, ok)
+ _, ok = analyzer.wrapperParamIndexFromCall(helperPkg, params, &ast.CallExpr{Fun: helperSel, Args: []ast.Expr{&ast.Ident{Name: "svc"}}})
+ assert.False(t, ok)
+ })
+
+ // Lock the method-style registration paths used by implementation tracing.
+ t.Run("selectedMethodHandlerArgumentIndex matches registration methods", func(t *testing.T) {
+ serverPkg := types.NewPackage("dubbo.apache.org/dubbo-go/v3/server", "server")
+ serverType := types.NewNamed(types.NewTypeName(token.NoPos, serverPkg, "Server", nil), types.NewStruct(nil, nil), nil)
+ serverType.AddMethod(types.NewFunc(token.NoPos, serverPkg, "RegisterService", testSignature(false, []types.Type{types.NewInterfaceType(nil, nil)}, []types.Type{types.Universe.Lookup("error").Type()})))
+ serverType.AddMethod(types.NewFunc(token.NoPos, serverPkg, "Register", testSignature(false, []types.Type{types.NewInterfaceType(nil, nil)}, []types.Type{types.Universe.Lookup("error").Type()})))
+ serviceOptionsType := types.NewNamed(types.NewTypeName(token.NoPos, serverPkg, "ServiceOptions", nil), types.NewStruct(nil, nil), nil)
+ serviceOptionsType.AddMethod(types.NewFunc(token.NoPos, serverPkg, "Implement", testSignature(false, []types.Type{types.NewInterfaceType(nil, nil)}, nil)))
+ proxyType := types.NewNamed(types.NewTypeName(token.NoPos, serverPkg, "Proxy", nil), types.NewStruct(nil, nil), nil)
+ proxyType.AddMethod(types.NewFunc(token.NoPos, serverPkg, "Implement", testSignature(false, []types.Type{types.NewInterfaceType(nil, nil)}, nil)))
+
+ configPkg := types.NewPackage("dubbo.apache.org/dubbo-go/v3/config", "config")
+ serviceConfigType := types.NewNamed(types.NewTypeName(token.NoPos, configPkg, "ServiceConfig", nil), types.NewStruct(nil, nil), nil)
+ serviceConfigType.AddMethod(types.NewFunc(token.NoPos, configPkg, "Implement", testSignature(false, []types.Type{types.NewInterfaceType(nil, nil)}, nil)))
+
+ commonPkg := types.NewPackage("dubbo.apache.org/dubbo-go/v3/common", "common")
+ serviceMapType := types.NewNamed(types.NewTypeName(token.NoPos, commonPkg, "serviceMap", nil), types.NewStruct(nil, nil), nil)
+ serviceMapType.AddMethod(types.NewFunc(token.NoPos, commonPkg, "Register", testSignature(false, []types.Type{types.NewInterfaceType(nil, nil), types.NewInterfaceType(nil, nil), types.NewInterfaceType(nil, nil), types.NewInterfaceType(nil, nil), types.NewInterfaceType(nil, nil)}, []types.Type{types.Universe.Lookup("error").Type()})))
+
+ idx, ok := selectedMethodHandlerArgumentIndex(types.NewMethodSet(types.NewPointer(serverType)).Lookup(serverPkg, "RegisterService"))
+ require.True(t, ok)
+ assert.Equal(t, 0, idx)
+
+ idx, ok = selectedMethodHandlerArgumentIndex(types.NewMethodSet(types.NewPointer(serverType)).Lookup(serverPkg, "Register"))
+ require.True(t, ok)
+ assert.Equal(t, 0, idx)
+
+ idx, ok = selectedMethodHandlerArgumentIndex(types.NewMethodSet(types.NewPointer(serviceOptionsType)).Lookup(serverPkg, "Implement"))
+ require.True(t, ok)
+ assert.Equal(t, 0, idx)
+
+ idx, ok = selectedMethodHandlerArgumentIndex(types.NewMethodSet(types.NewPointer(serviceConfigType)).Lookup(configPkg, "Implement"))
+ require.True(t, ok)
+ assert.Equal(t, 0, idx)
+
+ idx, ok = selectedMethodHandlerArgumentIndex(types.NewMethodSet(types.NewPointer(serviceMapType)).Lookup(commonPkg, "Register"))
+ require.True(t, ok)
+ assert.Equal(t, 4, idx)
+
+ _, ok = selectedMethodHandlerArgumentIndex(types.NewMethodSet(types.NewPointer(proxyType)).Lookup(serverPkg, "Implement"))
+ assert.False(t, ok)
+
+ otherPkg := types.NewPackage("example.com/other", "other")
+ otherType := types.NewNamed(types.NewTypeName(token.NoPos, otherPkg, "Service", nil), types.NewStruct(nil, nil), nil)
+ otherType.AddMethod(types.NewFunc(token.NoPos, otherPkg, "Call", testSignature(false, nil, nil)))
+ _, ok = selectedMethodHandlerArgumentIndex(types.NewMethodSet(types.NewPointer(otherType)).Lookup(otherPkg, "Call"))
+ assert.False(t, ok)
+ })
+
+ // Package-level helpers cover config registration, root dubbo helpers, and generated Register* entry points.
+ t.Run("calledObjectHandlerArgumentIndex matches config helpers and generated handlers", func(t *testing.T) {
+ analyzer := newRegistrationAnalyzer(nil)
+ configPkg := types.NewPackage("dubbo.apache.org/dubbo-go/v3/config", "config")
+ dubboPkg := types.NewPackage("dubbo.apache.org/dubbo-go/v3", "dubbo")
+
+ idx, ok := analyzer.calledObjectHandlerArgumentIndex(types.NewFunc(token.NoPos, configPkg, "SetProviderService", testSignature(false, []types.Type{types.NewInterfaceType(nil, nil)}, nil)))
+ require.True(t, ok)
+ assert.Equal(t, 0, idx)
+
+ idx, ok = analyzer.calledObjectHandlerArgumentIndex(types.NewFunc(token.NoPos, configPkg, "SetProviderServiceWithInfo", testSignature(false, []types.Type{types.NewInterfaceType(nil, nil), types.NewInterfaceType(nil, nil)}, nil)))
+ require.True(t, ok)
+ assert.Equal(t, 0, idx)
+
+ idx, ok = analyzer.calledObjectHandlerArgumentIndex(types.NewFunc(token.NoPos, dubboPkg, "SetProviderService", testSignature(false, []types.Type{types.NewInterfaceType(nil, nil)}, nil)))
+ require.True(t, ok)
+ assert.Equal(t, 0, idx)
+
+ idx, ok = analyzer.calledObjectHandlerArgumentIndex(types.NewFunc(token.NoPos, dubboPkg, "SetProviderServiceWithInfo", testSignature(false, []types.Type{types.NewInterfaceType(nil, nil), types.NewInterfaceType(nil, nil)}, nil)))
+ require.True(t, ok)
+ assert.Equal(t, 0, idx)
+
+ idx, ok = analyzer.calledObjectHandlerArgumentIndex(types.NewFunc(token.NoPos, types.NewPackage("example.com/test", "test"), "RegisterGreeterHandler", testSignature(false, []types.Type{types.NewInterfaceType(nil, nil), types.NewInterfaceType(nil, nil)}, nil)))
+ require.True(t, ok)
+ assert.Equal(t, 1, idx)
+
+ _, ok = analyzer.calledObjectHandlerArgumentIndex(types.NewFunc(token.NoPos, types.NewPackage("example.com/test", "test"), "Call", testSignature(false, nil, nil)))
+ assert.False(t, ok)
+ _, ok = analyzer.calledObjectHandlerArgumentIndex(nil)
+ assert.False(t, ok)
+ })
+
+ // handlerArgumentIndex is the bridge between AST call shapes and the registration allowlist above.
+ t.Run("handlerArgumentIndex dispatches selector ident and default calls", func(t *testing.T) {
+ analyzer := newRegistrationAnalyzer(nil)
+ serverPkg := types.NewPackage("dubbo.apache.org/dubbo-go/v3/server", "server")
+ serverType := types.NewNamed(types.NewTypeName(token.NoPos, serverPkg, "Server", nil), types.NewStruct(nil, nil), nil)
+ serverType.AddMethod(types.NewFunc(token.NoPos, serverPkg, "RegisterService", testSignature(false, []types.Type{types.NewInterfaceType(nil, nil)}, []types.Type{types.Universe.Lookup("error").Type()})))
+ selection := types.NewMethodSet(types.NewPointer(serverType)).Lookup(serverPkg, "RegisterService")
+ configPkg := types.NewPackage("dubbo.apache.org/dubbo-go/v3/config", "config")
+
+ selector := &ast.SelectorExpr{X: &ast.Ident{Name: "srv"}, Sel: &ast.Ident{Name: "RegisterService"}}
+ packageSelector := &ast.SelectorExpr{X: &ast.Ident{Name: "config"}, Sel: &ast.Ident{Name: "SetProviderService"}}
+ ident := &ast.Ident{Name: "RegisterGreeterHandler"}
+ pkg := &packages.Package{
+ TypesInfo: &types.Info{
+ Selections: map[*ast.SelectorExpr]*types.Selection{selector: selection},
+ Uses: map[*ast.Ident]types.Object{
+ packageSelector.Sel: types.NewFunc(token.NoPos, configPkg, "SetProviderService", testSignature(false, nil, nil)),
+ ident: types.NewFunc(token.NoPos, types.NewPackage("example.com/test", "test"), "RegisterGreeterHandler", testSignature(false, nil, nil)),
+ },
+ },
+ }
+
+ idx, ok := analyzer.handlerArgumentIndex(pkg, &ast.CallExpr{Fun: selector, Args: []ast.Expr{&ast.Ident{Name: "svc"}}})
+ require.True(t, ok)
+ assert.Equal(t, 0, idx)
+
+ idx, ok = analyzer.handlerArgumentIndex(pkg, &ast.CallExpr{Fun: ident, Args: []ast.Expr{&ast.Ident{Name: "srv"}, &ast.Ident{Name: "svc"}}})
+ require.True(t, ok)
+ assert.Equal(t, 1, idx)
+
+ idx, ok = analyzer.handlerArgumentIndex(pkg, &ast.CallExpr{Fun: packageSelector, Args: []ast.Expr{&ast.Ident{Name: "svc"}}})
+ require.True(t, ok)
+ assert.Equal(t, 0, idx)
+
+ _, ok = analyzer.handlerArgumentIndex(pkg, &ast.CallExpr{Fun: &ast.BasicLit{}})
+ assert.False(t, ok)
+ })
+
+ t.Run("registeredTypeKeyForType and packagePath keep only exported named types", func(t *testing.T) {
+ localPkg := types.NewPackage("example.com/test", "test")
+ otherPkg := types.NewPackage("example.com/other", "other")
+ exported := types.NewNamed(types.NewTypeName(token.NoPos, localPkg, "Service", nil), types.NewStruct(nil, nil), nil)
+ unexported := types.NewNamed(types.NewTypeName(token.NoPos, localPkg, "service", nil), types.NewStruct(nil, nil), nil)
+ imported := types.NewNamed(types.NewTypeName(token.NoPos, otherPkg, "Service", nil), types.NewStruct(nil, nil), nil)
+ alias := types.NewAlias(types.NewTypeName(token.NoPos, localPkg, "AliasService", nil), exported)
+ noPkg := types.NewNamed(types.NewTypeName(token.NoPos, nil, "Service", nil), types.NewStruct(nil, nil), nil)
+
+ key, ok := registeredTypeKeyForType(types.NewPointer(exported))
+ require.True(t, ok)
+ assert.Equal(t, registeredTypeKey{pkgPath: "example.com/test", typeName: "Service"}, key)
+
+ _, ok = registeredTypeKeyForType(unexported)
+ assert.False(t, ok)
+ key, ok = registeredTypeKeyForType(imported)
+ require.True(t, ok)
+ assert.Equal(t, registeredTypeKey{pkgPath: "example.com/other", typeName: "Service"}, key)
+ key, ok = registeredTypeKeyForType(alias)
+ require.True(t, ok)
+ assert.Equal(t, registeredTypeKey{pkgPath: "example.com/test", typeName: "Service"}, key)
+ _, ok = registeredTypeKeyForType(noPkg)
+ assert.False(t, ok)
+ _, ok = registeredTypeKeyForType(types.Typ[types.String])
+ assert.False(t, ok)
+ _, ok = registeredTypeKeyForType(nil)
+ assert.False(t, ok)
+
+ assert.Equal(t, "example.com/test", packagePath(&packages.Package{Types: localPkg}))
+ assert.Equal(t, "example.com/fallback", packagePath(&packages.Package{PkgPath: "example.com/fallback"}))
+ assert.Empty(t, packagePath(nil))
+ })
+
+ t.Run("registeredImplementationTypes ignores registration calls without handler args", func(t *testing.T) {
+ call := &ast.CallExpr{Fun: &ast.Ident{Name: "RegisterGreeterHandler"}}
+ file := &ast.File{Decls: []ast.Decl{
+ &ast.FuncDecl{
+ Name: &ast.Ident{Name: "register"},
+ Type: &ast.FuncType{Params: &ast.FieldList{}},
+ Body: &ast.BlockStmt{List: []ast.Stmt{&ast.ExprStmt{X: call}}},
+ },
+ }}
+ pkg := &packages.Package{
+ Syntax: []*ast.File{file},
+ CompiledGoFiles: []string{"service.go"},
+ TypesInfo: &types.Info{
+ Uses: map[*ast.Ident]types.Object{
+ call.Fun.(*ast.Ident): types.NewFunc(token.NoPos, types.NewPackage("example.com/test", "test"), "RegisterGreeterHandler", testSignature(false, nil, nil)),
+ },
+ },
+ }
+
+ assert.Empty(t, registeredImplementationTypes([]*packages.Package{pkg}))
+ })
+
+ // Generated Triple wrappers should participate in tracing, but generated contract methods should still stay silent.
+ t.Run("skip policy keeps triple helpers but still suppresses generated findings", func(t *testing.T) {
+ assert.True(t, shouldSkipFindingFile("generated.triple.go"))
+ assert.False(t, shouldSkipRegistrationFile("generated.triple.go"))
+ assert.True(t, shouldSkipRegistrationFile("generated.pb.go"))
+ assert.True(t, shouldSkipRegistrationFile("generated_test.go"))
+ })
+
+ // Interface-typed service vars should resolve to the concrete implementation visible at the registration site.
+ t.Run("registeredTypeKeyForExpr resolves interface typed variables", func(t *testing.T) {
+ localPkg := types.NewPackage("example.com/test", "test")
+ serviceType := types.NewNamed(types.NewTypeName(token.NoPos, localPkg, "Service", nil), types.NewStruct(nil, nil), nil)
+ varObj := types.NewVar(token.NoPos, localPkg, "svc", types.NewInterfaceType(nil, nil))
+ file := token.NewFileSet().AddFile("service.go", -1, 64)
+ ident := &ast.Ident{Name: "svc", NamePos: file.Pos(20)}
+ initExpr := &ast.UnaryExpr{Op: token.AND, X: &ast.CompositeLit{}}
+ pkg := &packages.Package{
+ Types: localPkg,
+ TypesInfo: &types.Info{
+ Types: map[ast.Expr]types.TypeAndValue{
+ initExpr: {Type: types.NewPointer(serviceType)},
+ },
+ Uses: map[*ast.Ident]types.Object{
+ ident: varObj,
+ },
+ },
+ }
+ analyzer := ®istrationAnalyzer{
+ varInitializers: map[string]map[types.Object][]assignmentRef{
+ "example.com/test": {varObj: {{pos: file.Pos(10), expr: initExpr}}},
+ },
+ }
+
+ key, ok := analyzer.registeredTypeKeyForExpr(pkg, ident, ident.Pos(), nil)
+ require.True(t, ok)
+ assert.Equal(t, registeredTypeKey{pkgPath: "example.com/test", typeName: "Service"}, key)
+ })
+
+ // Reassignments after registration must not override the concrete type used at the call site.
+ t.Run("latestAssignmentBefore uses the nearest assignment before the call site", func(t *testing.T) {
+ file := token.NewFileSet().AddFile("service.go", -1, 64)
+ assignments := []assignmentRef{
+ {pos: file.Pos(10), expr: &ast.Ident{Name: "First"}},
+ {pos: file.Pos(30), expr: &ast.Ident{Name: "Second"}},
+ }
+
+ assignment, ok := latestAssignmentBefore(assignments, file.Pos(20))
+ require.True(t, ok)
+ assert.Equal(t, "First", assignment.expr.(*ast.Ident).Name)
+
+ assignment, ok = latestAssignmentBefore(assignments, file.Pos(40))
+ require.True(t, ok)
+ assert.Equal(t, "Second", assignment.expr.(*ast.Ident).Name)
+ })
+
+ t.Run("recordAssignInitializers, appendInitializer, parameterIndexes, and functionKeyForObject handle edge cases", func(t *testing.T) {
+ localPkg := types.NewPackage("example.com/test", "test")
+ obj := types.NewVar(token.NoPos, localPkg, "svc", types.NewInterfaceType(nil, nil))
+ file := token.NewFileSet().AddFile("service.go", -1, 64)
+ assignIdent := &ast.Ident{Name: "svc", NamePos: file.Pos(10)}
+ assignFile := &ast.File{Decls: []ast.Decl{
+ &ast.FuncDecl{
+ Name: &ast.Ident{Name: "register"},
+ Type: &ast.FuncType{Params: &ast.FieldList{}},
+ Body: &ast.BlockStmt{List: []ast.Stmt{
+ &ast.AssignStmt{
+ Lhs: []ast.Expr{assignIdent},
+ Rhs: []ast.Expr{&ast.Ident{Name: "rhs"}},
+ },
+ &ast.AssignStmt{
+ Lhs: []ast.Expr{assignIdent},
+ Rhs: []ast.Expr{},
+ },
+ }},
+ },
+ }}
+ pkg := &packages.Package{
+ TypesInfo: &types.Info{
+ Uses: map[*ast.Ident]types.Object{assignIdent: obj},
+ },
+ }
+ initializers := map[types.Object][]assignmentRef{}
+ recordAssignInitializers(pkg, initializers, assignFile)
+ require.Len(t, initializers[obj], 1)
+ assert.Equal(t, file.Pos(10), initializers[obj][0].pos)
+
+ recordAssignInitializers(pkg, initializers, &ast.File{Decls: []ast.Decl{
+ &ast.FuncDecl{
+ Name: &ast.Ident{Name: "register2"},
+ Type: &ast.FuncType{Params: &ast.FieldList{}},
+ Body: &ast.BlockStmt{List: []ast.Stmt{
+ &ast.AssignStmt{
+ Lhs: []ast.Expr{&ast.SelectorExpr{X: &ast.Ident{Name: "svc"}, Sel: &ast.Ident{Name: "Field"}}},
+ Rhs: []ast.Expr{&ast.Ident{Name: "rhs"}},
+ },
+ }},
+ },
+ }})
+ require.Len(t, initializers[obj], 1)
+
+ appendInitializer(pkg, initializers, nil, token.NoPos, &ast.Ident{Name: "rhs"})
+ appendInitializer(pkg, initializers, &ast.Ident{Name: "missing"}, token.NoPos, &ast.Ident{Name: "rhs"})
+ require.Len(t, initializers[obj], 1)
+
+ assert.Empty(t, parameterIndexes(&packages.Package{}, &ast.FuncDecl{}))
+ assert.Empty(t, parameterIndexes(&packages.Package{}, &ast.FuncDecl{Type: &ast.FuncType{Params: &ast.FieldList{}}}))
+
+ paramName := &ast.Ident{Name: "svc"}
+ paramObj := types.NewVar(token.NoPos, localPkg, "svc", types.Typ[types.String])
+ params := parameterIndexes(&packages.Package{
+ TypesInfo: &types.Info{Defs: map[*ast.Ident]types.Object{paramName: paramObj}},
+ }, &ast.FuncDecl{
+ Type: &ast.FuncType{Params: &ast.FieldList{List: []*ast.Field{
+ {Type: &ast.Ident{Name: "string"}},
+ {Names: []*ast.Ident{paramName}, Type: &ast.Ident{Name: "string"}},
+ }}},
+ })
+ assert.Equal(t, 0, params[paramObj])
+
+ _, ok := functionKeyForObject(nil)
+ assert.False(t, ok)
+ _, ok = functionKeyForObject(types.NewVar(token.NoPos, localPkg, "svc", types.Typ[types.String]))
+ assert.False(t, ok)
+ _, ok = functionKeyForObject(types.NewFunc(token.NoPos, nil, "Call", testSignature(false, nil, nil)))
+ assert.False(t, ok)
+ })
+
+ t.Run("interfaceMethodPositions handles empty and embedded interfaces", func(t *testing.T) {
+ assert.Empty(t, interfaceMethodPositions(nil, nil))
+
+ fset := token.NewFileSet()
+ file := fset.AddFile("service.go", -1, 64)
+ methodPos := file.Pos(10)
+ embedPos := file.Pos(20)
+ embeddedExpr := &ast.Ident{Name: "Embedded", NamePos: embedPos}
+ iface := types.NewInterfaceType([]*types.Func{
+ types.NewFunc(token.NoPos, nil, "Broadcast", testSignature(true, []types.Type{types.NewSlice(types.Typ[types.String])}, []types.Type{types.Universe.Lookup("error").Type()})),
+ }, nil)
+ iface.Complete()
+
+ pkg := &packages.Package{
+ TypesInfo: &types.Info{
+ Types: map[ast.Expr]types.TypeAndValue{
+ embeddedExpr: {Type: iface},
+ },
+ },
+ }
+
+ positions := interfaceMethodPositions(pkg, &ast.InterfaceType{
+ Methods: &ast.FieldList{List: []*ast.Field{
+ {Names: []*ast.Ident{{Name: "Direct", NamePos: methodPos}}},
+ {Type: embeddedExpr},
+ }},
+ })
+ assert.Equal(t, methodPos, positions["Direct"])
+ assert.Equal(t, embedPos, positions["Broadcast"])
+ })
+
+ t.Run("recordEmbeddedMethodPositions ignores unresolved embedded interfaces", func(t *testing.T) {
+ positions := make(map[string]token.Pos)
+ recordEmbeddedMethodPositions(&packages.Package{
+ TypesInfo: &types.Info{Types: map[ast.Expr]types.TypeAndValue{}},
+ }, positions, &ast.Ident{Name: "Missing"})
+ assert.Empty(t, positions)
+ })
+}
+
+func TestScanReportsPackageLoadErrors(t *testing.T) {
+ oldPackagesLoad := packagesLoad
+ packagesLoad = func(cfg *packages.Config, patterns ...string) ([]*packages.Package, error) {
+ return nil, assert.AnError
+ }
+ t.Cleanup(func() {
+ packagesLoad = oldPackagesLoad
+ })
+
+ findings, err := Scan(".", []string{"./..."})
+ assert.Nil(t, findings)
+ require.ErrorIs(t, err, assert.AnError)
+}
+
+func testSignature(variadic bool, paramTypes []types.Type, resultTypes []types.Type) *types.Signature {
+ params := make([]*types.Var, 0, len(paramTypes))
+ for i, paramType := range paramTypes {
+ params = append(params, types.NewVar(token.NoPos, nil, string(rune('a'+i)), paramType))
+ }
+
+ results := make([]*types.Var, 0, len(resultTypes))
+ for i, resultType := range resultTypes {
+ results = append(results, types.NewVar(token.NoPos, nil, string(rune('r'+i)), resultType))
+ }
+
+ return types.NewSignatureType(nil, nil, nil, types.NewTuple(params...), types.NewTuple(results...), variadic)
+}
diff --git a/tools/variadicrpccheck/main.go b/tools/variadicrpccheck/main.go
new file mode 100644
index 000000000..881a91bc4
--- /dev/null
+++ b/tools/variadicrpccheck/main.go
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package main
+
+import (
+ "fmt"
+ "io"
+ "os"
+)
+
+var exitFunc = os.Exit
+
+func main() {
+ exitFunc(run(os.Stdout, os.Stderr, ".", os.Args[1:]))
+}
+
+// run prints every collected finding and always returns zero so the tool remains
+// guidance-only in local checks and CI. Package-load errors are still mirrored
+// to stderr to explain partial scan coverage.
+func run(stdout, stderr io.Writer, dir string, patterns []string) int {
+ findings, err := Scan(dir, patterns)
+ for _, finding := range findings {
+ _, _ = fmt.Fprintln(stdout, finding.String())
+ }
+ if err != nil {
+ _, _ = fmt.Fprintf(stderr, "variadicrpccheck: %v\n", err)
+ }
+ return 0
+}
diff --git a/tools/variadicrpccheck/main_test.go b/tools/variadicrpccheck/main_test.go
new file mode 100644
index 000000000..3d9495223
--- /dev/null
+++ b/tools/variadicrpccheck/main_test.go
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package main
+
+import (
+ "os"
+ "testing"
+)
+
+import (
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestMainUsesRunExitCode(t *testing.T) {
+ dir := t.TempDir()
+ writeTempFile(t, dir, goModFileName, variadicCheckModuleContent)
+ writeTempFile(t, dir, serviceFileName, `package sample
+
+func Echo(name string) string {
+ return name
+}
+`)
+
+ oldExitFunc := exitFunc
+ oldArgs := os.Args
+ oldWd, err := os.Getwd()
+ require.NoError(t, err)
+
+ var gotCode int
+ exitFunc = func(code int) {
+ gotCode = code
+ }
+ os.Args = []string{"variadicrpccheck", "./..."}
+ require.NoError(t, os.Chdir(dir))
+ t.Cleanup(func() {
+ exitFunc = oldExitFunc
+ os.Args = oldArgs
+ _ = os.Chdir(oldWd)
+ })
+
+ main()
+
+ assert.Equal(t, 0, gotCode)
+}
diff --git a/tools/variadicrpccheck/scan.go b/tools/variadicrpccheck/scan.go
new file mode 100644
index 000000000..a186a5ef0
--- /dev/null
+++ b/tools/variadicrpccheck/scan.go
@@ -0,0 +1,1088 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package main
+
+import (
+ "errors"
+ "fmt"
+ "go/ast"
+ "go/token"
+ "go/types"
+ "path/filepath"
+ "sort"
+ "strings"
+)
+
+import (
+ "golang.org/x/tools/go/packages"
+)
+
+var packagesLoad = packages.Load
+
+const (
+ dubboRootPkgPath = "dubbo.apache.org/dubbo-go/v3"
+ dubboCommonPkgPath = dubboRootPkgPath + "/common"
+ dubboConfigPkgPath = dubboRootPkgPath + "/config"
+ dubboServerPkgPath = dubboRootPkgPath + "/server"
+
+ serverServiceOptionsType = "*" + dubboServerPkgPath + ".ServiceOptions"
+ configServiceConfigType = "*" + dubboConfigPkgPath + ".ServiceConfig"
+)
+
+type registeredTypeKey struct {
+ pkgPath string
+ typeName string
+}
+
+type functionKey struct {
+ pkgPath string
+ name string
+}
+
+// functionDeclRef keeps the owning package with the helper body so wrapper
+// tracing can inspect forwarded parameters.
+type functionDeclRef struct {
+ pkg *packages.Package
+ decl *ast.FuncDecl
+}
+
+// assignmentRef records one initializer or reassignment with its source
+// position for call-site-sensitive lookup.
+type assignmentRef struct {
+ pos token.Pos
+ expr ast.Expr
+}
+
+type wrapperResolution struct {
+ argIndex int
+ resolving bool
+ resolved bool
+}
+
+type Finding struct {
+ Position token.Position
+ Kind string
+ TypeName string
+ MethodName string
+}
+
+// String renders warning-only output so callers can pipe the tool into CI logs
+// without any post-processing.
+func (f Finding) String() string {
+ return fmt.Sprintf(
+ "%s:%d:%d: warning: %s %s exports variadic RPC method %s; prefer []T, request structs, or Triple + Protobuf IDL",
+ f.Position.Filename,
+ f.Position.Line,
+ f.Position.Column,
+ f.Kind,
+ f.TypeName,
+ f.MethodName,
+ )
+}
+
+// Scan loads the requested packages, finds exported variadic RPC contracts,
+// keeps the output order stable, and returns any package-load errors together
+// with the findings collected before the error was seen.
+func Scan(dir string, patterns []string) ([]Finding, error) {
+ pkgs, err := loadPackages(dir, normalizePatterns(patterns))
+ if err != nil {
+ return nil, err
+ }
+
+ findings, loadErrs := collectFindingsAndErrors(pkgs)
+ sortFindings(findings)
+ if len(loadErrs) > 0 {
+ return findings, errors.New(strings.Join(loadErrs, "; "))
+ }
+
+ return findings, nil
+}
+
+// normalizePatterns falls back to the usual recursive package scan when the
+// caller does not pass an explicit pattern list.
+func normalizePatterns(patterns []string) []string {
+ if len(patterns) == 0 {
+ return []string{"./..."}
+ }
+ return patterns
+}
+
+// loadPackages asks go/packages for the syntax and type information needed to
+// inspect both interface declarations and concrete methods.
+func loadPackages(dir string, patterns []string) ([]*packages.Package, error) {
+ cfg := &packages.Config{
+ Mode: packages.NeedName |
+ packages.NeedFiles |
+ packages.NeedCompiledGoFiles |
+ packages.NeedSyntax |
+ packages.NeedTypes |
+ packages.NeedTypesInfo,
+ Dir: dir,
+ }
+ return packagesLoad(cfg, patterns...)
+}
+
+// collectFindingsAndErrors scans every loaded package and keeps loader errors
+// separate so we can still emit useful warnings before returning the error.
+func collectFindingsAndErrors(pkgs []*packages.Package) ([]Finding, []string) {
+ findings := make([]Finding, 0)
+ loadErrs := make([]string, 0)
+ registeredTypes := registeredImplementationTypes(pkgs)
+ for _, pkg := range pkgs {
+ loadErrs = append(loadErrs, packageErrors(pkg)...)
+ findings = append(findings, collectPackageFindings(pkg, registeredTypes)...)
+ }
+ return findings, loadErrs
+}
+
+// packageErrors flattens go/packages errors into strings so Scan can combine
+// them into one returned error value.
+func packageErrors(pkg *packages.Package) []string {
+ if pkg == nil || len(pkg.Errors) == 0 {
+ return nil
+ }
+
+ loadErrs := make([]string, 0, len(pkg.Errors))
+ for _, pkgErr := range pkg.Errors {
+ loadErrs = append(loadErrs, pkgErr.Error())
+ }
+ return loadErrs
+}
+
+// sortFindings keeps warning output stable across runs.
+func sortFindings(findings []Finding) {
+ sort.Slice(findings, func(i, j int) bool {
+ if findings[i].Position.Filename != findings[j].Position.Filename {
+ return findings[i].Position.Filename < findings[j].Position.Filename
+ }
+ if findings[i].Position.Line != findings[j].Position.Line {
+ return findings[i].Position.Line < findings[j].Position.Line
+ }
+ if findings[i].Position.Column != findings[j].Position.Column {
+ return findings[i].Position.Column < findings[j].Position.Column
+ }
+ if findings[i].Kind != findings[j].Kind {
+ return findings[i].Kind < findings[j].Kind
+ }
+ if findings[i].TypeName != findings[j].TypeName {
+ return findings[i].TypeName < findings[j].TypeName
+ }
+ return findings[i].MethodName < findings[j].MethodName
+ })
+}
+
+// collectPackageFindings walks compiled files so build tags and generated-file
+// selection stay aligned with the package loader.
+func collectPackageFindings(pkg *packages.Package, registeredTypes map[registeredTypeKey]struct{}) []Finding {
+ findings := make([]Finding, 0)
+ for fileIdx, file := range pkg.Syntax {
+ if fileIdx >= len(pkg.CompiledGoFiles) {
+ continue
+ }
+
+ filename := pkg.CompiledGoFiles[fileIdx]
+ if shouldSkipFindingFile(filename) {
+ continue
+ }
+
+ for _, decl := range file.Decls {
+ switch typedDecl := decl.(type) {
+ case *ast.GenDecl:
+ findings = append(findings, collectInterfaceFindings(pkg, typedDecl)...)
+ case *ast.FuncDecl:
+ if finding, ok := collectImplementationFinding(pkg, typedDecl, registeredTypes); ok {
+ findings = append(findings, finding)
+ }
+ }
+ }
+ }
+ return findings
+}
+
+// collectInterfaceFindings catches contract definitions before any concrete
+// implementation exists, including methods inherited through embedded
+// interfaces, which is where new cross-language APIs are often introduced.
+func collectInterfaceFindings(pkg *packages.Package, decl *ast.GenDecl) []Finding {
+ if decl.Tok != token.TYPE {
+ return nil
+ }
+
+ findings := make([]Finding, 0)
+ for _, spec := range decl.Specs {
+ typeSpec, iface, ok := exportedInterfaceSpec(spec)
+ if !ok {
+ continue
+ }
+
+ findings = append(findings, typeSpecInterfaceFindings(pkg, typeSpec, iface)...)
+ }
+
+ return findings
+}
+
+// exportedInterfaceSpec keeps only exported interface declarations and skips
+// unexported or non-interface type specs early.
+func exportedInterfaceSpec(spec ast.Spec) (*ast.TypeSpec, *ast.InterfaceType, bool) {
+ typeSpec, ok := spec.(*ast.TypeSpec)
+ if !ok || !typeSpec.Name.IsExported() {
+ return nil, nil, false
+ }
+
+ iface, ok := typeSpec.Type.(*ast.InterfaceType)
+ if !ok {
+ return nil, nil, false
+ }
+
+ return typeSpec, iface, true
+}
+
+// typeSpecInterfaceFindings runs the RPC-style variadic check for one exported
+// interface and preserves positions for both direct and embedded methods.
+func typeSpecInterfaceFindings(pkg *packages.Package, typeSpec *ast.TypeSpec, iface *ast.InterfaceType) []Finding {
+ ifaceType, ok := interfaceTypeForSpec(pkg, typeSpec)
+ if !ok {
+ return nil
+ }
+
+ methodPositions := interfaceMethodPositions(pkg, iface)
+ ifaceType.Complete()
+
+ findings := make([]Finding, 0, ifaceType.NumMethods())
+ for i := 0; i < ifaceType.NumMethods(); i++ {
+ if finding, ok := interfaceMethodFinding(pkg, typeSpec, ifaceType.Method(i), methodPositions); ok {
+ findings = append(findings, finding)
+ }
+ }
+ return findings
+}
+
+// interfaceTypeForSpec resolves the go/types interface backing one AST type
+// declaration so later checks can use normalized method signatures.
+func interfaceTypeForSpec(pkg *packages.Package, typeSpec *ast.TypeSpec) (*types.Interface, bool) {
+ obj := pkg.TypesInfo.Defs[typeSpec.Name]
+ if obj == nil {
+ return nil, false
+ }
+
+ ifaceType, ok := obj.Type().Underlying().(*types.Interface)
+ return ifaceType, ok
+}
+
+// interfaceMethodFinding returns one finding for an exported variadic RPC-style
+// interface method and falls back to the interface declaration position when a
+// more precise method position is unavailable.
+func interfaceMethodFinding(pkg *packages.Package, typeSpec *ast.TypeSpec, method *types.Func, methodPositions map[string]token.Pos) (Finding, bool) {
+ if !method.Exported() || !isCandidateRPCMethodName(method.Name()) {
+ return Finding{}, false
+ }
+
+ sig, ok := method.Type().(*types.Signature)
+ if !ok || !isVariadicRPCSignature(sig) {
+ return Finding{}, false
+ }
+
+ pos := methodPositions[method.Name()]
+ if !pos.IsValid() {
+ pos = typeSpec.Name.Pos()
+ }
+
+ return Finding{
+ Position: pkg.Fset.Position(pos),
+ Kind: "interface",
+ TypeName: typeSpec.Name.Name,
+ MethodName: method.Name(),
+ }, true
+}
+
+// collectImplementationFinding covers struct receiver methods used as direct
+// service implementations in non-interface registration flows.
+func collectImplementationFinding(pkg *packages.Package, decl *ast.FuncDecl, registeredTypes map[registeredTypeKey]struct{}) (Finding, bool) {
+ if decl.Recv == nil || len(decl.Recv.List) == 0 || !decl.Name.IsExported() {
+ return Finding{}, false
+ }
+ if !isCandidateRPCMethodName(decl.Name.Name) {
+ return Finding{}, false
+ }
+
+ receiverName := receiverTypeName(decl.Recv.List[0].Type)
+ if receiverName == "" || !ast.IsExported(receiverName) {
+ return Finding{}, false
+ }
+ if _, ok := registeredTypes[registeredTypeKey{pkgPath: packagePath(pkg), typeName: receiverName}]; !ok {
+ return Finding{}, false
+ }
+
+ sig, ok := signatureForIdent(pkg, decl.Name)
+ if !ok || !isVariadicRPCSignature(sig) {
+ return Finding{}, false
+ }
+
+ return Finding{
+ Position: pkg.Fset.Position(decl.Name.Pos()),
+ Kind: "implementation",
+ TypeName: receiverName,
+ MethodName: decl.Name.Name,
+ }, true
+}
+
+func signatureForIdent(pkg *packages.Package, ident *ast.Ident) (*types.Signature, bool) {
+ obj := pkg.TypesInfo.Defs[ident]
+ if obj == nil {
+ return nil, false
+ }
+
+ sig, ok := obj.Type().(*types.Signature)
+ return sig, ok
+}
+
+// registeredImplementationTypes collects exported concrete types that appear as
+// handlers in known registration or export calls across the loaded packages.
+func registeredImplementationTypes(pkgs []*packages.Package) map[registeredTypeKey]struct{} {
+ registeredTypes := make(map[registeredTypeKey]struct{})
+ analyzer := newRegistrationAnalyzer(pkgs)
+ for _, pkg := range pkgs {
+ analyzer.collectPackageRegistrations(pkg, registeredTypes)
+ }
+ return registeredTypes
+}
+
+// registrationAnalyzer holds the shared indexes used to trace concrete
+// implementation types through registration helpers and wrappers.
+type registrationAnalyzer struct {
+ functionDecls map[functionKey]functionDeclRef
+ wrapperResolutions map[functionKey]*wrapperResolution
+ varInitializers map[string]map[types.Object][]assignmentRef
+}
+
+// newRegistrationAnalyzer precomputes the indexes reused across registration
+// tracing.
+func newRegistrationAnalyzer(pkgs []*packages.Package) *registrationAnalyzer {
+ return ®istrationAnalyzer{
+ functionDecls: functionDecls(pkgs),
+ wrapperResolutions: make(map[functionKey]*wrapperResolution),
+ varInitializers: variableInitializers(pkgs),
+ }
+}
+
+// collectPackageRegistrations walks one package and records concrete handler
+// types used in known registration calls.
+func (a *registrationAnalyzer) collectPackageRegistrations(pkg *packages.Package, registeredTypes map[registeredTypeKey]struct{}) {
+ for fileIdx, file := range pkg.Syntax {
+ if shouldSkipPackageFile(pkg, fileIdx, shouldSkipRegistrationFile) {
+ continue
+ }
+ a.collectFileRegistrations(pkg, file, registeredTypes)
+ }
+}
+
+// collectFileRegistrations scans a single file for registration calls.
+func (a *registrationAnalyzer) collectFileRegistrations(pkg *packages.Package, file *ast.File, registeredTypes map[registeredTypeKey]struct{}) {
+ ast.Inspect(file, func(node ast.Node) bool {
+ call, ok := node.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+
+ handlerArg, ok := a.registrationHandlerArg(pkg, call)
+ if !ok {
+ return true
+ }
+
+ a.recordRegisteredImplementationType(pkg, registeredTypes, handlerArg, call.Pos())
+ return true
+ })
+}
+
+// registrationHandlerArg returns the AST expression that carries the service
+// implementation for a recognized registration call.
+func (a *registrationAnalyzer) registrationHandlerArg(pkg *packages.Package, call *ast.CallExpr) (ast.Expr, bool) {
+ argIndex, ok := a.handlerArgumentIndex(pkg, call)
+ if !ok || argIndex >= len(call.Args) {
+ return nil, false
+ }
+ return call.Args[argIndex], true
+}
+
+// handlerArgumentIndex returns the argument slot that carries the service
+// implementation for one known registration call shape.
+func (a *registrationAnalyzer) handlerArgumentIndex(pkg *packages.Package, call *ast.CallExpr) (int, bool) {
+ switch typedFun := call.Fun.(type) {
+ case *ast.SelectorExpr:
+ if selection := pkg.TypesInfo.Selections[typedFun]; selection != nil {
+ return selectedMethodHandlerArgumentIndex(selection)
+ }
+
+ obj := pkg.TypesInfo.Uses[typedFun.Sel]
+ return a.calledObjectHandlerArgumentIndex(obj)
+ case *ast.Ident:
+ obj := pkg.TypesInfo.Uses[typedFun]
+ return a.calledObjectHandlerArgumentIndex(obj)
+ default:
+ return 0, false
+ }
+}
+
+// selectedMethodHandlerArgumentIndex matches method-style registration paths
+// such as srv.RegisterService(...) and cfg.Implement(...).
+func selectedMethodHandlerArgumentIndex(selection *types.Selection) (int, bool) {
+ obj := selection.Obj()
+ if obj == nil || obj.Pkg() == nil {
+ return 0, false
+ }
+
+ path := obj.Pkg().Path()
+ name := obj.Name()
+ switch {
+ case path == dubboServerPkgPath && name == "Register":
+ return 0, true
+ case path == dubboServerPkgPath && name == "RegisterService":
+ return 0, true
+ case path == dubboServerPkgPath && name == "Implement":
+ return 0, types.TypeString(selection.Recv(), nil) == serverServiceOptionsType
+ case path == dubboConfigPkgPath && name == "Implement":
+ return 0, types.TypeString(selection.Recv(), nil) == configServiceConfigType
+ case path == dubboCommonPkgPath && name == "Register":
+ return 4, strings.HasSuffix(types.TypeString(selection.Recv(), nil), ".serviceMap")
+ default:
+ return 0, false
+ }
+}
+
+// calledObjectHandlerArgumentIndex matches package-level registration helpers
+// and generated Register*Handler entry points.
+func (a *registrationAnalyzer) calledObjectHandlerArgumentIndex(obj types.Object) (int, bool) {
+ if obj == nil {
+ return 0, false
+ }
+ if obj.Pkg() != nil {
+ switch obj.Pkg().Path() {
+ case dubboConfigPkgPath, dubboRootPkgPath:
+ switch obj.Name() {
+ case "SetProviderService":
+ return 0, true
+ case "SetProviderServiceWithInfo":
+ return 0, true
+ }
+ }
+ }
+
+ if strings.HasPrefix(obj.Name(), "Register") && strings.HasSuffix(obj.Name(), "Handler") {
+ return 1, true
+ }
+
+ if key, ok := functionKeyForObject(obj); ok {
+ if argIndex, ok := a.wrapperHandlerArgumentIndex(key); ok {
+ return argIndex, true
+ }
+ }
+
+ return 0, false
+}
+
+// recordRegisteredImplementationType stores the named concrete type behind one
+// registration argument when it resolves to an exported implementation.
+func (a *registrationAnalyzer) recordRegisteredImplementationType(pkg *packages.Package, registeredTypes map[registeredTypeKey]struct{}, expr ast.Expr, callPos token.Pos) {
+ if pkg == nil || pkg.TypesInfo == nil {
+ return
+ }
+
+ if key, ok := a.registeredTypeKeyForExpr(pkg, expr, callPos, nil); ok {
+ registeredTypes[key] = struct{}{}
+ }
+}
+
+// registeredTypeKeyForExpr resolves one registration argument to the concrete
+// exported type visible at that call site.
+func (a *registrationAnalyzer) registeredTypeKeyForExpr(pkg *packages.Package, expr ast.Expr, callPos token.Pos, seen map[types.Object]struct{}) (registeredTypeKey, bool) {
+ if key, ok := registeredTypeKeyForType(pkg.TypesInfo.TypeOf(expr)); ok {
+ return key, true
+ }
+
+ ident, ok := expr.(*ast.Ident)
+ if !ok {
+ return registeredTypeKey{}, false
+ }
+
+ obj := pkg.TypesInfo.ObjectOf(ident)
+ if obj == nil {
+ return registeredTypeKey{}, false
+ }
+
+ if seen == nil {
+ seen = make(map[types.Object]struct{})
+ }
+ if _, seenBefore := seen[obj]; seenBefore {
+ return registeredTypeKey{}, false
+ }
+ seen[obj] = struct{}{}
+
+ initExprs := a.varInitializers[packagePath(pkg)]
+ if initExprs == nil {
+ return registeredTypeKey{}, false
+ }
+
+ assignment, ok := latestAssignmentBefore(initExprs[obj], callPos)
+ if !ok {
+ return registeredTypeKey{}, false
+ }
+
+ return a.registeredTypeKeyForExpr(pkg, assignment.expr, assignment.pos, seen)
+}
+
+// wrapperHandlerArgumentIndex recognizes simple passthrough wrappers that
+// forward one parameter into a known registration helper.
+func (a *registrationAnalyzer) wrapperHandlerArgumentIndex(key functionKey) (int, bool) {
+ state, ok, done := a.cachedWrapperResolution(key)
+ if done {
+ return state.argIndex, ok
+ }
+
+ ref, ok := a.functionDecls[key]
+ if !ok || ref.decl == nil || ref.decl.Body == nil {
+ return 0, false
+ }
+
+ params := parameterIndexes(ref.pkg, ref.decl)
+ if len(params) == 0 {
+ return 0, false
+ }
+
+ state.resolving = true
+ defer func() {
+ state.resolving = false
+ }()
+
+ return a.resolveWrapperHandlerArgument(ref, params, state)
+}
+
+// cachedWrapperResolution avoids re-walking wrapper bodies once a helper has
+// been resolved or rejected.
+func (a *registrationAnalyzer) cachedWrapperResolution(key functionKey) (*wrapperResolution, bool, bool) {
+ state := a.wrapperResolutions[key]
+ if state == nil {
+ state = &wrapperResolution{}
+ a.wrapperResolutions[key] = state
+ return state, false, false
+ }
+ if state.resolved {
+ return state, true, true
+ }
+ if state.resolving {
+ return state, false, true
+ }
+ return state, false, false
+}
+
+// resolveWrapperHandlerArgument looks for the forwarded parameter that reaches
+// a known registration helper inside one wrapper body.
+func (a *registrationAnalyzer) resolveWrapperHandlerArgument(ref functionDeclRef, params map[types.Object]int, state *wrapperResolution) (int, bool) {
+ for _, stmt := range ref.decl.Body.List {
+ if paramIndex, ok := a.forwardedWrapperParamIndex(ref.pkg, params, stmt); ok {
+ state.argIndex = paramIndex
+ state.resolved = true
+ return paramIndex, true
+ }
+ }
+ return 0, false
+}
+
+// forwardedWrapperParamIndex searches one statement subtree for a forwarded
+// registration parameter.
+func (a *registrationAnalyzer) forwardedWrapperParamIndex(pkg *packages.Package, params map[types.Object]int, stmt ast.Node) (int, bool) {
+ paramIndex := 0
+ matched := false
+ ast.Inspect(stmt, func(node ast.Node) bool {
+ call, ok := node.(*ast.CallExpr)
+ if !ok || matched {
+ return !matched
+ }
+
+ idx, ok := a.wrapperParamIndexFromCall(pkg, params, call)
+ if !ok {
+ return true
+ }
+
+ paramIndex = idx
+ matched = true
+ return false
+ })
+ return paramIndex, matched
+}
+
+// wrapperParamIndexFromCall maps one nested registration call back to the
+// wrapper parameter it forwards.
+func (a *registrationAnalyzer) wrapperParamIndexFromCall(pkg *packages.Package, params map[types.Object]int, call *ast.CallExpr) (int, bool) {
+ handlerArg, ok := a.registrationHandlerArg(pkg, call)
+ if !ok {
+ return 0, false
+ }
+
+ ident, ok := handlerArg.(*ast.Ident)
+ if !ok {
+ return 0, false
+ }
+
+ obj := pkg.TypesInfo.ObjectOf(ident)
+ paramIndex, ok := params[obj]
+ if !ok {
+ return 0, false
+ }
+
+ return paramIndex, true
+}
+
+// functionDecls indexes package-level helpers that may wrap a known
+// registration path.
+func functionDecls(pkgs []*packages.Package) map[functionKey]functionDeclRef {
+ decls := make(map[functionKey]functionDeclRef)
+ for _, pkg := range pkgs {
+ collectPackageFunctionDecls(pkg, decls)
+ }
+ return decls
+}
+
+// collectPackageFunctionDecls indexes package-level helpers from one package.
+func collectPackageFunctionDecls(pkg *packages.Package, decls map[functionKey]functionDeclRef) {
+ for fileIdx, file := range pkg.Syntax {
+ if shouldSkipPackageFile(pkg, fileIdx, shouldSkipRegistrationFile) {
+ continue
+ }
+ collectFileFunctionDecls(pkg, file, decls)
+ }
+}
+
+// collectFileFunctionDecls records package-level helper declarations from one file.
+func collectFileFunctionDecls(pkg *packages.Package, file *ast.File, decls map[functionKey]functionDeclRef) {
+ for _, decl := range file.Decls {
+ recordFunctionDecl(pkg, decls, decl)
+ }
+}
+
+// recordFunctionDecl stores one package-level function under the stable key
+// used by wrapper tracing.
+func recordFunctionDecl(pkg *packages.Package, decls map[functionKey]functionDeclRef, decl ast.Decl) {
+ funcDecl, ok := decl.(*ast.FuncDecl)
+ if !ok || funcDecl.Recv != nil {
+ return
+ }
+
+ obj := pkg.TypesInfo.Defs[funcDecl.Name]
+ key, ok := functionKeyForObject(obj)
+ if !ok {
+ return
+ }
+
+ decls[key] = functionDeclRef{pkg: pkg, decl: funcDecl}
+}
+
+// variableInitializers stores ordered initializers and reassignments for
+// interface-typed handler variables.
+func variableInitializers(pkgs []*packages.Package) map[string]map[types.Object][]assignmentRef {
+ initializers := make(map[string]map[types.Object][]assignmentRef)
+ for _, pkg := range pkgs {
+ for fileIdx, file := range pkg.Syntax {
+ if shouldSkipPackageFile(pkg, fileIdx, shouldSkipRegistrationFile) {
+ continue
+ }
+
+ pkgInits := initializers[packagePath(pkg)]
+ if pkgInits == nil {
+ pkgInits = make(map[types.Object][]assignmentRef)
+ initializers[packagePath(pkg)] = pkgInits
+ }
+
+ recordValueSpecInitializers(pkg, pkgInits, file)
+ recordAssignInitializers(pkg, pkgInits, file)
+ }
+ }
+ return initializers
+}
+
+// recordValueSpecInitializers captures var declarations with explicit values
+// for later call-site lookup.
+func recordValueSpecInitializers(pkg *packages.Package, initializers map[types.Object][]assignmentRef, file *ast.File) {
+ ast.Inspect(file, func(node ast.Node) bool {
+ genDecl, ok := varGenDecl(node)
+ if !ok {
+ return true
+ }
+ recordVarDeclInitializers(pkg, initializers, genDecl)
+ return true
+ })
+}
+
+// varGenDecl keeps only var declarations for initializer indexing.
+func varGenDecl(node ast.Node) (*ast.GenDecl, bool) {
+ genDecl, ok := node.(*ast.GenDecl)
+ if !ok || genDecl.Tok != token.VAR {
+ return nil, false
+ }
+ return genDecl, true
+}
+
+// recordVarDeclInitializers records every explicit initializer from one var
+// declaration block.
+func recordVarDeclInitializers(pkg *packages.Package, initializers map[types.Object][]assignmentRef, genDecl *ast.GenDecl) {
+ for _, spec := range genDecl.Specs {
+ recordValueSpecInitializer(pkg, initializers, spec)
+ }
+}
+
+// recordValueSpecInitializer stores the initializer expressions for one value
+// spec when names and values line up.
+func recordValueSpecInitializer(pkg *packages.Package, initializers map[types.Object][]assignmentRef, spec ast.Spec) {
+ valueSpec, ok := spec.(*ast.ValueSpec)
+ if !ok || len(valueSpec.Values) != len(valueSpec.Names) {
+ return
+ }
+
+ for i, name := range valueSpec.Names {
+ appendInitializer(pkg, initializers, name, name.Pos(), valueSpec.Values[i])
+ }
+}
+
+// recordAssignInitializers appends later reassignments so call-site lookup can
+// choose the visible value.
+func recordAssignInitializers(pkg *packages.Package, initializers map[types.Object][]assignmentRef, file *ast.File) {
+ ast.Inspect(file, func(node ast.Node) bool {
+ assign, ok := node.(*ast.AssignStmt)
+ if !ok || len(assign.Lhs) != len(assign.Rhs) {
+ return true
+ }
+ for i, lhs := range assign.Lhs {
+ ident, ok := lhs.(*ast.Ident)
+ if !ok {
+ continue
+ }
+ appendInitializer(pkg, initializers, ident, ident.Pos(), assign.Rhs[i])
+ }
+ return true
+ })
+}
+
+// appendInitializer records one initializer or reassignment for later
+// call-site lookup.
+func appendInitializer(pkg *packages.Package, initializers map[types.Object][]assignmentRef, ident *ast.Ident, pos token.Pos, expr ast.Expr) {
+ if ident == nil {
+ return
+ }
+
+ if obj := pkg.TypesInfo.ObjectOf(ident); obj != nil {
+ initializers[obj] = append(initializers[obj], assignmentRef{pos: pos, expr: expr})
+ }
+}
+
+// shouldSkipPackageFile centralizes the compiled-file bounds check used by the
+// registration and helper indexes.
+func shouldSkipPackageFile(pkg *packages.Package, fileIdx int, skip func(string) bool) bool {
+ if fileIdx >= len(pkg.CompiledGoFiles) {
+ return true
+ }
+ return skip(pkg.CompiledGoFiles[fileIdx])
+}
+
+// latestAssignmentBefore returns the nearest initializer or reassignment
+// visible before the registration call site.
+func latestAssignmentBefore(assignments []assignmentRef, pos token.Pos) (assignmentRef, bool) {
+ for i := len(assignments) - 1; i >= 0; i-- {
+ if pos == token.NoPos || assignments[i].pos < pos {
+ return assignments[i], true
+ }
+ }
+ return assignmentRef{}, false
+}
+
+// parameterIndexes maps named parameters to their ordinal positions for
+// wrapper forwarding checks.
+func parameterIndexes(pkg *packages.Package, decl *ast.FuncDecl) map[types.Object]int {
+ params := make(map[types.Object]int)
+ if decl.Type == nil || decl.Type.Params == nil {
+ return params
+ }
+
+ index := 0
+ for _, field := range decl.Type.Params.List {
+ for _, name := range field.Names {
+ if obj := pkg.TypesInfo.Defs[name]; obj != nil {
+ params[obj] = index
+ }
+ index++
+ }
+ }
+ return params
+}
+
+// functionKeyForObject turns a package-level function object into the stable
+// lookup key used by wrapper tracing.
+func functionKeyForObject(obj types.Object) (functionKey, bool) {
+ if obj == nil || obj.Pkg() == nil {
+ return functionKey{}, false
+ }
+ _, ok := obj.(*types.Func)
+ if !ok {
+ return functionKey{}, false
+ }
+ return functionKey{pkgPath: obj.Pkg().Path(), name: obj.Name()}, true
+}
+
+// registeredTypeKeyForType unwraps aliases and pointers until it reaches the
+// exported named type that should be tracked for implementation findings.
+func registeredTypeKeyForType(typ types.Type) (registeredTypeKey, bool) {
+ for typ != nil {
+ typ = types.Unalias(typ)
+ switch typedType := typ.(type) {
+ case *types.Pointer:
+ typ = typedType.Elem()
+ case *types.Named:
+ obj := typedType.Obj()
+ if obj == nil || obj.Pkg() == nil {
+ return registeredTypeKey{}, false
+ }
+ if !token.IsExported(obj.Name()) {
+ return registeredTypeKey{}, false
+ }
+ return registeredTypeKey{pkgPath: obj.Pkg().Path(), typeName: obj.Name()}, true
+ default:
+ return registeredTypeKey{}, false
+ }
+ }
+ return registeredTypeKey{}, false
+}
+
+func packagePath(pkg *packages.Package) string {
+ if pkg != nil && pkg.Types != nil {
+ return pkg.Types.Path()
+ }
+ if pkg != nil {
+ return pkg.PkgPath
+ }
+ return ""
+}
+
+// interfaceMethodPositions maps exported method names to the source line we
+// want to report. Direct methods use their own line; embedded methods use the
+// local embedding line.
+func interfaceMethodPositions(pkg *packages.Package, iface *ast.InterfaceType) map[string]token.Pos {
+ positions := make(map[string]token.Pos)
+ if iface == nil || iface.Methods == nil {
+ return positions
+ }
+
+ for _, field := range iface.Methods.List {
+ recordInterfaceMethodPositions(pkg, positions, field)
+ }
+
+ return positions
+}
+
+// recordInterfaceMethodPositions handles one interface field entry, whether it
+// is a named method or an embedded interface.
+func recordInterfaceMethodPositions(pkg *packages.Package, positions map[string]token.Pos, field *ast.Field) {
+ if len(field.Names) == 1 {
+ recordNamedMethodPosition(positions, field.Names[0])
+ return
+ }
+
+ recordEmbeddedMethodPositions(pkg, positions, field.Type)
+}
+
+// recordNamedMethodPosition stores the declared position for one exported
+// method listed directly in the interface body.
+func recordNamedMethodPosition(positions map[string]token.Pos, methodName *ast.Ident) {
+ if methodName != nil && methodName.IsExported() {
+ positions[methodName.Name] = methodName.Pos()
+ }
+}
+
+// recordEmbeddedMethodPositions records exported methods contributed by an
+// embedded interface, but reports them at the local embedding site so the
+// warning points to the contract introduced in this file.
+func recordEmbeddedMethodPositions(pkg *packages.Package, positions map[string]token.Pos, expr ast.Expr) {
+ embeddedIface := embeddedInterfaceType(pkg, expr)
+ if embeddedIface == nil {
+ return
+ }
+
+ embeddedIface.Complete()
+ for i := 0; i < embeddedIface.NumMethods(); i++ {
+ method := embeddedIface.Method(i)
+ if method.Exported() {
+ recordEmbeddedMethodPosition(positions, method.Name(), expr.Pos())
+ }
+ }
+}
+
+// recordEmbeddedMethodPosition keeps the first local embedding position seen
+// for a method name when multiple embedded interfaces contribute it.
+func recordEmbeddedMethodPosition(positions map[string]token.Pos, methodName string, pos token.Pos) {
+ if _, exists := positions[methodName]; !exists {
+ positions[methodName] = pos
+ }
+}
+
+func embeddedInterfaceType(pkg *packages.Package, expr ast.Expr) *types.Interface {
+ if pkg == nil || pkg.TypesInfo == nil {
+ return nil
+ }
+
+ typedExpr, ok := pkg.TypesInfo.Types[expr]
+ if !ok || typedExpr.Type == nil {
+ return nil
+ }
+
+ iface, _ := typedExpr.Type.Underlying().(*types.Interface)
+ return iface
+}
+
+func receiverTypeName(expr ast.Expr) string {
+ switch typedExpr := expr.(type) {
+ case *ast.Ident:
+ return typedExpr.Name
+ case *ast.StarExpr:
+ return receiverTypeName(typedExpr.X)
+ case *ast.IndexExpr:
+ return receiverTypeName(typedExpr.X)
+ case *ast.IndexListExpr:
+ return receiverTypeName(typedExpr.X)
+ default:
+ return ""
+ }
+}
+
+// shouldSkipFindingFile filters generated and test sources so the tool focuses
+// reported findings on user-authored service contracts instead of stubs.
+func shouldSkipFindingFile(filename string) bool {
+ base := filepath.Base(filename)
+ return strings.HasSuffix(base, "_test.go") ||
+ strings.HasSuffix(base, ".pb.go") ||
+ strings.HasSuffix(base, ".triple.go")
+}
+
+// shouldSkipRegistrationFile keeps helper discovery out of tests and protobuf
+// stubs, but still allows generated Triple wrappers to participate in
+// registration tracing.
+func shouldSkipRegistrationFile(filename string) bool {
+ base := filepath.Base(filename)
+ return strings.HasSuffix(base, "_test.go") ||
+ strings.HasSuffix(base, ".pb.go")
+}
+
+func isCandidateRPCMethodName(methodName string) bool {
+ return methodName != "Reference" &&
+ methodName != "SetGRPCServer" &&
+ !strings.HasPrefix(methodName, "XXX")
+}
+
+// isVariadicRPCSignature mirrors the service-method shape closely enough to be
+// useful in CI, while excluding option-style variadics such as opts ...Option.
+func isVariadicRPCSignature(sig *types.Signature) bool {
+ if sig == nil || !sig.Variadic() {
+ return false
+ }
+
+ results := sig.Results()
+ if results == nil || (results.Len() != 1 && results.Len() != 2) {
+ return false
+ }
+ if types.TypeString(results.At(results.Len()-1).Type(), nil) != "error" {
+ return false
+ }
+ if results.Len() == 2 && !isExportedOrBuiltinGoType(results.At(0).Type()) {
+ return false
+ }
+
+ params := sig.Params()
+ for i := 0; i < params.Len(); i++ {
+ if !isExportedOrBuiltinGoType(params.At(i).Type()) {
+ return false
+ }
+ }
+
+ return !isOptionLikeVariadic(params.At(params.Len() - 1).Type())
+}
+
+// isExportedOrBuiltinGoType mirrors common.isExportedOrBuiltinType closely
+// enough for scanner parity: pointer wrappers are unwrapped, named types must
+// be exported unless they are builtins, and unnamed composite types are
+// accepted like reflect.Type.Name/PkgPath would be.
+func isExportedOrBuiltinGoType(typ types.Type) bool {
+ for {
+ ptr, ok := typ.(*types.Pointer)
+ if !ok {
+ break
+ }
+ typ = ptr.Elem()
+ }
+
+ switch typedType := typ.(type) {
+ case *types.Named:
+ return isExportedOrBuiltinTypeName(typedType.Obj())
+ case *types.Alias:
+ return isExportedOrBuiltinTypeName(typedType.Obj())
+ default:
+ return true
+ }
+}
+
+func isExportedOrBuiltinTypeName(obj *types.TypeName) bool {
+ if obj == nil {
+ return true
+ }
+ return token.IsExported(obj.Name()) || obj.Pkg() == nil
+}
+
+func isOptionLikeVariadic(paramType types.Type) bool {
+ sliceType, ok := paramType.(*types.Slice)
+ if !ok {
+ return false
+ }
+
+ return isOptionLikeType(sliceType.Elem())
+}
+
+func isOptionLikeType(typ types.Type) bool {
+ switch typedType := typ.(type) {
+ case *types.Pointer:
+ return isOptionLikeType(typedType.Elem())
+ case *types.Named:
+ return hasOptionLikeName(typedType.Obj().Name()) || hasOptionLikeSuffix(types.TypeString(typedType, typeQualifier))
+ case *types.Alias:
+ return hasOptionLikeName(typedType.Obj().Name()) || hasOptionLikeSuffix(types.TypeString(typedType, typeQualifier))
+ default:
+ return hasOptionLikeSuffix(types.TypeString(typ, typeQualifier))
+ }
+}
+
+func hasOptionLikeName(name string) bool {
+ return strings.HasSuffix(name, "Option") || strings.HasSuffix(name, "CallOption")
+}
+
+func hasOptionLikeSuffix(typeName string) bool {
+ return strings.HasSuffix(typeName, ".Option") ||
+ strings.HasSuffix(typeName, ".CallOption") ||
+ strings.HasSuffix(typeName, " Option") ||
+ strings.HasSuffix(typeName, " CallOption") ||
+ hasOptionLikeName(typeName)
+}
+
+func typeQualifier(pkg *types.Package) string {
+ if pkg == nil {
+ return ""
+ }
+ return pkg.Path()
+}
diff --git a/tools/variadicrpccheck/scan_test.go b/tools/variadicrpccheck/scan_test.go
new file mode 100644
index 000000000..79e679bd6
--- /dev/null
+++ b/tools/variadicrpccheck/scan_test.go
@@ -0,0 +1,542 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "testing"
+)
+
+import (
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+const (
+ goModFileName = "go.mod"
+ serviceFileName = "service.go"
+ variadicCheckModulePath = "example.com/variadicrpccheck"
+ variadicCheckModuleContent = "module example.com/variadicrpccheck\n\ngo 1.25.0\n"
+)
+
+func TestScanFindsVariadicRPCContracts(t *testing.T) {
+ dir := t.TempDir()
+ writeTempFile(t, dir, goModFileName, goModuleContentWithDubboGoReplace("example.com/variadicrpccheck", repoRoot(t)))
+ writeTempFile(t, dir, serviceFileName, `package sample
+
+import (
+ "context"
+
+ "dubbo.apache.org/dubbo-go/v3/server"
+)
+
+type Option struct{}
+type hidden struct{}
+
+type MultiArgsService interface {
+ MultiArgs(ctx context.Context, args ...string) error
+ Configure(opts ...Option) error
+}
+
+type VariadicService struct{}
+
+func (s *VariadicService) MultiArgs(ctx context.Context, args ...string) error {
+ return nil
+}
+
+func (s *VariadicService) Configure(opts ...Option) error {
+ return nil
+}
+
+type HiddenReplyService struct{}
+
+func (s *HiddenReplyService) MultiArgs(ctx context.Context, args ...string) (hidden, error) {
+ return hidden{}, nil
+}
+
+type HiddenArgService struct{}
+
+func (s *HiddenArgService) MultiArgs(ctx context.Context, arg hidden, args ...string) error {
+ return nil
+}
+
+type PlainService struct{}
+
+func (s *PlainService) Echo(ctx context.Context, arg string) error {
+ return nil
+}
+
+type Helper struct{}
+
+func (h *Helper) Merge(ctx context.Context, values ...string) error {
+ return nil
+}
+
+func register() {
+ var srv *server.Server
+ _ = srv.RegisterService(&VariadicService{})
+}
+`)
+ writeTempFile(t, dir, "generated.pb.go", `package sample
+
+import "context"
+
+type GeneratedService struct{}
+
+func (s *GeneratedService) MultiArgs(ctx context.Context, args ...string) error {
+ return nil
+}
+`)
+ writeTempFile(t, dir, "transport.triple.go", `package sample
+
+import "context"
+
+type TripleGeneratedService struct{}
+
+func (s *TripleGeneratedService) MultiArgs(ctx context.Context, args ...string) error {
+ return nil
+}
+`)
+ writeTempFile(t, dir, "ignored_test.go", `package sample
+
+import "context"
+
+type TestOnlyService struct{}
+
+func (s *TestOnlyService) MultiArgs(ctx context.Context, args ...string) error {
+ return nil
+}
+`)
+
+ findings, err := Scan(dir, []string{"./..."})
+ require.NoError(t, err)
+
+ got := make([]string, 0, len(findings))
+ for _, finding := range findings {
+ got = append(got, fmt.Sprintf("%s:%s:%s", finding.Kind, finding.TypeName, finding.MethodName))
+ }
+
+ assert.ElementsMatch(t, []string{
+ "implementation:VariadicService:MultiArgs",
+ "interface:MultiArgsService:MultiArgs",
+ }, got)
+}
+
+func TestScanFindsEmbeddedImportedVariadicInterface(t *testing.T) {
+ baseDir := t.TempDir()
+ writeTempFile(t, baseDir, goModFileName, goModuleContent("example.com/base"))
+ writeTempFile(t, baseDir, "base.go", `package base
+
+import "context"
+
+type BaseService interface {
+ MultiArgs(ctx context.Context, args ...string) error
+}
+ `)
+
+ dir := t.TempDir()
+ writeTempFile(t, dir, goModFileName, fmt.Sprintf(`%s
+
+ require example.com/base v0.0.0
+
+ replace example.com/base => %s
+`, goModuleContent("example.com/local"), baseDir))
+ writeTempFile(t, dir, serviceFileName, `package local
+
+import "example.com/base"
+
+type WrappedService interface {
+ base.BaseService
+}
+`)
+
+ findings, err := Scan(dir, []string{"./..."})
+ require.NoError(t, err)
+ require.Len(t, findings, 1)
+ assert.Equal(t, "interface", findings[0].Kind)
+ assert.Equal(t, "WrappedService", findings[0].TypeName)
+ assert.Equal(t, "MultiArgs", findings[0].MethodName)
+ assert.Equal(t, filepath.Join(dir, "service.go"), findings[0].Position.Filename)
+ assert.Equal(t, 6, findings[0].Position.Line)
+}
+
+func TestScanFindsRegisteredVariadicImplementationAcrossPackages(t *testing.T) {
+ dir := t.TempDir()
+ writeTempFile(t, dir, goModFileName, goModuleContentWithDubboGoReplace("example.com/crosspkg", repoRoot(t)))
+ writeTempFile(t, filepath.Join(dir, "service"), serviceFileName, `package service
+
+import "context"
+
+type VariadicService struct{}
+
+func (s *VariadicService) MultiArgs(ctx context.Context, args ...string) error {
+ return nil
+}
+
+type Helper struct{}
+
+func (h *Helper) Merge(ctx context.Context, values ...string) error {
+ return nil
+}
+`)
+ writeTempFile(t, filepath.Join(dir, "provider"), "provider.go", `package provider
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/server"
+ "example.com/crosspkg/service"
+)
+
+func register() {
+ var srv *server.Server
+ _ = srv.RegisterService(&service.VariadicService{})
+}
+`)
+
+ findings, err := Scan(dir, []string{"./..."})
+ require.NoError(t, err)
+ require.Len(t, findings, 1)
+ assert.Equal(t, "implementation", findings[0].Kind)
+ assert.Equal(t, "VariadicService", findings[0].TypeName)
+ assert.Equal(t, "MultiArgs", findings[0].MethodName)
+ assert.Equal(t, filepath.Join(dir, "service", "service.go"), findings[0].Position.Filename)
+}
+
+func TestScanFindsVariadicImplementationRegisteredViaSetProviderServiceWithInfo(t *testing.T) {
+ dir := t.TempDir()
+ writeTempFile(t, dir, goModFileName, goModuleContentWithDubboGoReplace("example.com/providerinfo", repoRoot(t)))
+ writeTempFile(t, filepath.Join(dir, "service"), serviceFileName, `package service
+
+import "context"
+
+type VariadicService struct{}
+
+func (s *VariadicService) MultiArgs(ctx context.Context, args ...string) error {
+ return nil
+}
+
+type Helper struct{}
+
+func (h *Helper) Merge(ctx context.Context, values ...string) error {
+ return nil
+}
+`)
+ writeTempFile(t, filepath.Join(dir, "provider"), "provider.go", `package provider
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/config"
+ "example.com/providerinfo/service"
+)
+
+func init() {
+ config.SetProviderServiceWithInfo(&service.VariadicService{}, nil)
+}
+`)
+
+ findings, err := Scan(dir, []string{"./..."})
+ require.NoError(t, err)
+ require.Len(t, findings, 1)
+ assert.Equal(t, "implementation", findings[0].Kind)
+ assert.Equal(t, "VariadicService", findings[0].TypeName)
+ assert.Equal(t, "MultiArgs", findings[0].MethodName)
+ assert.Equal(t, filepath.Join(dir, "service", "service.go"), findings[0].Position.Filename)
+}
+
+func TestScanFindsVariadicImplementationRegisteredViaRootSetProviderService(t *testing.T) {
+ dir := t.TempDir()
+ writeTempFile(t, dir, goModFileName, goModuleContentWithDubboGoReplace("example.com/rootprovider", repoRoot(t)))
+ writeTempFile(t, filepath.Join(dir, "service"), serviceFileName, `package service
+
+import "context"
+
+type VariadicService struct{}
+
+func (s *VariadicService) MultiArgs(ctx context.Context, args ...string) error {
+ return nil
+}
+`)
+ writeTempFile(t, filepath.Join(dir, "provider"), "provider.go", `package provider
+
+import (
+ dubbo "dubbo.apache.org/dubbo-go/v3"
+ "example.com/rootprovider/service"
+)
+
+func init() {
+ dubbo.SetProviderService(&service.VariadicService{})
+}
+`)
+
+ findings, err := Scan(dir, []string{"./..."})
+ require.NoError(t, err)
+ require.Len(t, findings, 1)
+ assert.Equal(t, "implementation", findings[0].Kind)
+ assert.Equal(t, "VariadicService", findings[0].TypeName)
+ assert.Equal(t, "MultiArgs", findings[0].MethodName)
+ assert.Equal(t, filepath.Join(dir, "service", "service.go"), findings[0].Position.Filename)
+}
+
+func TestScanFindsVariadicImplementationRegisteredViaGeneratedWrapper(t *testing.T) {
+ dir := t.TempDir()
+ writeTempFile(t, dir, goModFileName, goModuleContentWithDubboGoReplace("example.com/generatedwrapper", repoRoot(t)))
+ writeTempFile(t, filepath.Join(dir, "service"), serviceFileName, `package service
+
+import "context"
+
+type VariadicService struct{}
+
+func (s *VariadicService) MultiArgs(ctx context.Context, args ...string) error {
+ return nil
+}
+`)
+ writeTempFile(t, filepath.Join(dir, "generated"), "generated.go", `package generated
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/config"
+)
+
+func SetProviderService(srv common.RPCService) {
+ config.SetProviderServiceWithInfo(srv, nil)
+}
+`)
+ writeTempFile(t, filepath.Join(dir, "provider"), "provider.go", `package provider
+
+import (
+ "example.com/generatedwrapper/generated"
+ "example.com/generatedwrapper/service"
+)
+
+func init() {
+ generated.SetProviderService(&service.VariadicService{})
+}
+`)
+
+ findings, err := Scan(dir, []string{"./..."})
+ require.NoError(t, err)
+ require.Len(t, findings, 1)
+ assert.Equal(t, "implementation", findings[0].Kind)
+ assert.Equal(t, "VariadicService", findings[0].TypeName)
+ assert.Equal(t, "MultiArgs", findings[0].MethodName)
+ assert.Equal(t, filepath.Join(dir, "service", "service.go"), findings[0].Position.Filename)
+}
+
+func TestScanFindsVariadicImplementationRegisteredViaTripleWrapper(t *testing.T) {
+ dir := t.TempDir()
+ writeTempFile(t, dir, goModFileName, goModuleContentWithDubboGoReplace("example.com/triplewrapper", repoRoot(t)))
+ writeTempFile(t, filepath.Join(dir, "service"), serviceFileName, `package service
+
+import "context"
+
+type VariadicService struct{}
+
+func (s *VariadicService) MultiArgs(ctx context.Context, args ...string) error {
+ return nil
+}
+`)
+ writeTempFile(t, filepath.Join(dir, "generated"), "generated.triple.go", `package generated
+
+import (
+ dubbo "dubbo.apache.org/dubbo-go/v3"
+ "dubbo.apache.org/dubbo-go/v3/common"
+)
+
+func SetProviderService(srv common.RPCService) {
+ dubbo.SetProviderServiceWithInfo(srv, nil)
+}
+`)
+ writeTempFile(t, filepath.Join(dir, "provider"), "provider.go", `package provider
+
+import (
+ "example.com/triplewrapper/generated"
+ "example.com/triplewrapper/service"
+)
+
+func init() {
+ generated.SetProviderService(&service.VariadicService{})
+}
+`)
+
+ findings, err := Scan(dir, []string{"./..."})
+ require.NoError(t, err)
+ require.Len(t, findings, 1)
+ assert.Equal(t, "implementation", findings[0].Kind)
+ assert.Equal(t, "VariadicService", findings[0].TypeName)
+ assert.Equal(t, "MultiArgs", findings[0].MethodName)
+ assert.Equal(t, filepath.Join(dir, "service", "service.go"), findings[0].Position.Filename)
+}
+
+func TestScanFindsVariadicImplementationRegisteredViaInterfaceVariable(t *testing.T) {
+ dir := t.TempDir()
+ writeTempFile(t, dir, goModFileName, goModuleContentWithDubboGoReplace("example.com/interfacevar", repoRoot(t)))
+ writeTempFile(t, filepath.Join(dir, "service"), serviceFileName, `package service
+
+import "context"
+
+type VariadicService struct{}
+
+func (s *VariadicService) MultiArgs(ctx context.Context, args ...string) error {
+ return nil
+}
+`)
+ writeTempFile(t, filepath.Join(dir, "provider"), "provider.go", `package provider
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/config"
+ "example.com/interfacevar/service"
+)
+
+func init() {
+ var svc common.RPCService = &service.VariadicService{}
+ config.SetProviderServiceWithInfo(svc, nil)
+}
+`)
+
+ findings, err := Scan(dir, []string{"./..."})
+ require.NoError(t, err)
+ require.Len(t, findings, 1)
+ assert.Equal(t, "implementation", findings[0].Kind)
+ assert.Equal(t, "VariadicService", findings[0].TypeName)
+ assert.Equal(t, "MultiArgs", findings[0].MethodName)
+ assert.Equal(t, filepath.Join(dir, "service", "service.go"), findings[0].Position.Filename)
+}
+
+func TestScanUsesInterfaceVariableTypeAtRegistrationCallSite(t *testing.T) {
+ dir := t.TempDir()
+ writeTempFile(t, dir, goModFileName, goModuleContentWithDubboGoReplace("example.com/interfacevarreassign", repoRoot(t)))
+ writeTempFile(t, filepath.Join(dir, "service"), serviceFileName, `package service
+
+import "context"
+
+type FirstService struct{}
+
+func (s *FirstService) MultiArgs(ctx context.Context, args ...string) error {
+ return nil
+}
+
+type SecondService struct{}
+
+func (s *SecondService) MultiArgs(ctx context.Context, args ...string) error {
+ return nil
+}
+`)
+ writeTempFile(t, filepath.Join(dir, "provider"), "provider.go", `package provider
+
+import (
+ "dubbo.apache.org/dubbo-go/v3/common"
+ "dubbo.apache.org/dubbo-go/v3/config"
+ "example.com/interfacevarreassign/service"
+)
+
+func init() {
+ var svc common.RPCService = &service.FirstService{}
+ config.SetProviderServiceWithInfo(svc, nil)
+ svc = &service.SecondService{}
+}
+`)
+
+ findings, err := Scan(dir, []string{"./..."})
+ require.NoError(t, err)
+ require.Len(t, findings, 1)
+ assert.Equal(t, "implementation", findings[0].Kind)
+ assert.Equal(t, "FirstService", findings[0].TypeName)
+ assert.Equal(t, "MultiArgs", findings[0].MethodName)
+ assert.Equal(t, filepath.Join(dir, "service", "service.go"), findings[0].Position.Filename)
+}
+
+func TestRunPrintsWarningsButReturnsZero(t *testing.T) {
+ dir := t.TempDir()
+ writeTempFile(t, dir, goModFileName, goModuleContentWithDubboGoReplace("example.com/variadicrpccheck", repoRoot(t)))
+ writeTempFile(t, dir, serviceFileName, `package sample
+
+import (
+ "context"
+
+ "dubbo.apache.org/dubbo-go/v3/server"
+)
+
+type VariadicService struct{}
+
+func (s *VariadicService) MultiArgs(ctx context.Context, args ...string) error {
+ return nil
+}
+
+func register() {
+ var srv *server.Server
+ _ = srv.RegisterService(&VariadicService{})
+}
+`)
+
+ var stdout bytes.Buffer
+ var stderr bytes.Buffer
+ code := run(&stdout, &stderr, dir, []string{"./..."})
+
+ assert.Equal(t, 0, code)
+ assert.Contains(t, stdout.String(), "warning: implementation VariadicService exports variadic RPC method MultiArgs")
+ assert.Empty(t, stderr.String())
+}
+
+func TestRunReportsScanErrorButReturnsZero(t *testing.T) {
+ dir := t.TempDir()
+ writeTempFile(t, dir, goModFileName, variadicCheckModuleContent)
+ writeTempFile(t, dir, "broken.go", "package sample\n\nfunc broken(\n")
+
+ var stdout bytes.Buffer
+ var stderr bytes.Buffer
+ code := run(&stdout, &stderr, dir, []string{"./..."})
+
+ assert.Equal(t, 0, code)
+ assert.Empty(t, stdout.String())
+ assert.Contains(t, stderr.String(), "variadicrpccheck:")
+}
+
+func goModuleContent(modulePath string) string {
+ if modulePath == variadicCheckModulePath {
+ return variadicCheckModuleContent
+ }
+ return fmt.Sprintf("module %s\n\ngo 1.25.0\n", modulePath)
+}
+
+func goModuleContentWithDubboGoReplace(modulePath, dubboGoPath string) string {
+ return fmt.Sprintf(`module %s
+
+go 1.25.0
+
+require dubbo.apache.org/dubbo-go/v3 v3.0.0
+
+replace dubbo.apache.org/dubbo-go/v3 => %s
+`, modulePath, dubboGoPath)
+}
+
+func writeTempFile(t *testing.T, dir, name, content string) {
+ t.Helper()
+ path := filepath.Join(dir, name)
+ require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
+ require.NoError(t, os.WriteFile(path, []byte(content), 0o644))
+}
+
+func repoRoot(t *testing.T) string {
+ t.Helper()
+ _, filename, _, ok := runtime.Caller(0)
+ require.True(t, ok)
+ return filepath.Clean(filepath.Join(filepath.Dir(filename), "..", ".."))
+}