From 0ff5c3e98b5b59ef3186d5b75b42834a414419c4 Mon Sep 17 00:00:00 2001 From: Greg Oledzki Date: Tue, 30 Jun 2026 15:04:09 +0200 Subject: [PATCH 1/2] Remove excessive comments --- rewrite-go/cmd/explore/main.go | 14 ----- rewrite-go/cmd/rpc/main.go | 44 --------------- rewrite-go/pkg/format/auto_format.go | 4 -- rewrite-go/pkg/format/blank_lines.go | 2 - rewrite-go/pkg/format/spaces.go | 2 - rewrite-go/pkg/format/tabs_and_indents.go | 2 - rewrite-go/pkg/matcher/method_matcher.go | 8 --- rewrite-go/pkg/matcher/type_utils.go | 6 --- rewrite-go/pkg/parser/go_parser.go | 12 ----- rewrite-go/pkg/parser/gomod_lst.go | 1 - rewrite-go/pkg/parser/gomod_parser.go | 1 - rewrite-go/pkg/parser/project_importer.go | 4 -- rewrite-go/pkg/parser/type_mapper.go | 6 --- rewrite-go/pkg/preconditions/preconditions.go | 2 - rewrite-go/pkg/preconditions/search.go | 2 - rewrite-go/pkg/printer/go_printer.go | 4 -- rewrite-go/pkg/printer/gomod_printer.go | 1 - rewrite-go/pkg/printer/marker_printer.go | 18 ------- .../pkg/printer/print_output_capture.go | 5 -- rewrite-go/pkg/recipe/data_table.go | 11 ---- rewrite-go/pkg/recipe/execution_context.go | 4 -- rewrite-go/pkg/recipe/golang/activate.go | 1 - rewrite-go/pkg/recipe/golang/add_import.go | 2 - .../pkg/recipe/golang/annotation_service.go | 1 - .../pkg/recipe/golang/change_method_name.go | 1 - rewrite-go/pkg/recipe/golang/change_type.go | 1 - rewrite-go/pkg/recipe/golang/find_methods.go | 1 - rewrite-go/pkg/recipe/golang/find_types.go | 1 - .../pkg/recipe/golang/internal/imports.go | 2 - .../pkg/recipe/golang/naming_service.go | 7 +-- rewrite-go/pkg/recipe/golang/remove_import.go | 2 - .../pkg/recipe/golang/rename_package.go | 2 - rewrite-go/pkg/recipe/installer/installer.go | 8 --- rewrite-go/pkg/recipe/recipe.go | 54 ++----------------- rewrite-go/pkg/recipe/registry.go | 21 +------- rewrite-go/pkg/recipe/scanning_recipe.go | 1 - rewrite-go/pkg/rpc/go_receiver.go | 9 ---- rewrite-go/pkg/rpc/go_sender.go | 2 - rewrite-go/pkg/rpc/gomod_codec.go | 6 --- rewrite-go/pkg/rpc/java_receiver.go | 2 - rewrite-go/pkg/rpc/java_sender.go | 2 - rewrite-go/pkg/rpc/java_type_receiver.go | 2 - rewrite-go/pkg/rpc/java_type_sender.go | 14 ----- rewrite-go/pkg/rpc/padding_rpc.go | 7 --- rewrite-go/pkg/rpc/receive_queue.go | 8 --- rewrite-go/pkg/rpc/reference.go | 4 -- rewrite-go/pkg/rpc/rpc_object_data.go | 3 -- rewrite-go/pkg/rpc/send_queue.go | 14 ----- rewrite-go/pkg/rpc/space_rpc.go | 11 ---- rewrite-go/pkg/rpc/value_types.go | 4 -- rewrite-go/pkg/template/capture.go | 16 ------ rewrite-go/pkg/template/comparator.go | 3 -- rewrite-go/pkg/template/go_pattern.go | 10 ---- rewrite-go/pkg/template/go_template.go | 10 ---- rewrite-go/pkg/template/match_result.go | 6 --- rewrite-go/pkg/template/placeholder.go | 1 - rewrite-go/pkg/template/substitution.go | 1 - rewrite-go/pkg/template/template_recipe.go | 20 ------- rewrite-go/pkg/tree/golang/go.go | 32 ----------- .../pkg/tree/golang/go_resolution_result.go | 7 --- rewrite-go/pkg/tree/golang/markers.go | 2 - rewrite-go/pkg/tree/java/j.go | 37 ------------- rewrite-go/pkg/tree/java/java_type.go | 16 ------ rewrite-go/pkg/tree/java/markers.go | 12 ----- rewrite-go/pkg/tree/java/padding.go | 2 - rewrite-go/pkg/tree/java/parse_error.go | 2 - rewrite-go/pkg/tree/java/space.go | 11 ---- rewrite-go/pkg/tree/java/tree.go | 4 -- rewrite-go/pkg/visitor/cursor.go | 2 - rewrite-go/pkg/visitor/go_visitor.go | 4 -- rewrite-go/pkg/visitor/java_type_visitor.go | 1 - 71 files changed, 7 insertions(+), 538 deletions(-) diff --git a/rewrite-go/cmd/explore/main.go b/rewrite-go/cmd/explore/main.go index aed57b5318d..bffc815e0ce 100644 --- a/rewrite-go/cmd/explore/main.go +++ b/rewrite-go/cmd/explore/main.go @@ -43,9 +43,7 @@ type Greeter struct { Prefix string } -// Greet returns a greeting for the given name. func (g *Greeter) Greet(name string) string { - // Trim whitespace from the name name = strings.TrimSpace(name) if name == "" { return g.Prefix + "World" @@ -67,8 +65,6 @@ func main() { fmt.Fprintf(os.Stderr, "Parse error: %v\n", err) os.Exit(1) } - - // --- Section 1: AST dump with positions --- fmt.Println("=== AST Nodes ===") fmt.Println() depth := 0 @@ -89,8 +85,6 @@ func main() { depth++ return true }) - - // --- Section 2: Type checking --- fmt.Println() fmt.Println("=== Type Information ===") fmt.Println() @@ -102,7 +96,6 @@ func main() { Uses: make(map[*ast.Ident]types.Object), } - // Type-check (will have errors due to nil importer, but populates info for local types) _, _ = conf.Check("main", fset, []*ast.File{file}, info) fmt.Println("-- Definitions --") @@ -125,8 +118,6 @@ func main() { obj.Type(), fset.Position(obj.Pos()), ) } - - // --- Section 3: Comment associations --- fmt.Println() fmt.Println("=== Comment Map ===") fmt.Println() @@ -143,8 +134,6 @@ func main() { } } } - - // --- Section 4: Whitespace reconstruction --- fmt.Println() fmt.Println("=== Whitespace Between Tokens ===") fmt.Println() @@ -155,7 +144,6 @@ func main() { src := []byte(sampleSource) tokenFile := fset.File(file.Pos()) - // Collect all positions in order by walking the AST var positions []struct { pos token.Pos name string @@ -173,7 +161,6 @@ func main() { return true }) - // Show whitespace gaps between consecutive node start positions fmt.Println("First 10 whitespace gaps between nodes:") shown := 0 for i := 1; i < len(positions) && shown < 10; i++ { @@ -181,7 +168,6 @@ func main() { endOffset := tokenFile.Offset(positions[i].pos) if endOffset > startOffset { between := string(src[startOffset:endOffset]) - // Only show gaps that contain whitespace beyond the node's own text if strings.ContainsAny(between, " \t\n") { fmt.Printf(" Between %s and %s:\n", positions[i-1].name, positions[i].name) fmt.Printf(" raw: %q\n", between) diff --git a/rewrite-go/cmd/rpc/main.go b/rewrite-go/cmd/rpc/main.go index 88dde700bae..ba402df3eb2 100644 --- a/rewrite-go/cmd/rpc/main.go +++ b/rewrite-go/cmd/rpc/main.go @@ -51,7 +51,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/visitor" ) -// jsonRPCRequest represents an incoming JSON-RPC 2.0 message (request or response). type jsonRPCRequest struct { JSONRPC string `json:"jsonrpc"` ID json.RawMessage `json:"id"` @@ -60,7 +59,6 @@ type jsonRPCRequest struct { Result json.RawMessage `json:"result"` // present in responses } -// jsonRPCResponse represents an outgoing JSON-RPC 2.0 response. type jsonRPCResponse struct { JSONRPC string `json:"jsonrpc"` ID json.RawMessage `json:"id"` @@ -68,14 +66,12 @@ type jsonRPCResponse struct { Error *rpcError `json:"error,omitempty"` } -// rpcError is the error object in a JSON-RPC response. type rpcError struct { Code int `json:"code"` Message string `json:"message"` Data string `json:"data,omitempty"` } -// server holds the RPC state. type server struct { localObjects map[string]any remoteObjects map[string]any // forward direction: tracks what Java has from Go @@ -113,11 +109,9 @@ type server struct { // remote object id (the `p` value in Visit/Generate/BatchVisit). preparedContexts map[string]*recipe.ExecutionContext - // Tracing toggles for GetObject traceReceive bool traceSend bool - // Server configuration from CLI flags (see serverConfig) metricsCsv string configuredDataTableStore recipe.DataTableStore @@ -146,7 +140,6 @@ type server struct { recipeWorkspaceCleanup func() } -// serverConfig holds CLI-driven configuration applied to the server at startup. type serverConfig struct { logFile string traceRpcMessages bool @@ -249,7 +242,6 @@ func newServer(cfg serverConfig) *server { return s } -// closeMetrics flushes and closes the metrics CSV writer if open. Idempotent. func (s *server) closeMetrics() { s.metricsMu.Lock() defer s.metricsMu.Unlock() @@ -358,9 +350,7 @@ func main() { } } -// readMessage reads a Content-Length framed JSON-RPC message from stdin. func (s *server) readMessage() (*jsonRPCRequest, error) { - // Read Content-Length header headerLine, err := s.reader.ReadString('\n') if err != nil { return nil, err @@ -375,12 +365,10 @@ func (s *server) readMessage() (*jsonRPCRequest, error) { return nil, fmt.Errorf("invalid content length: %s", lengthStr) } - // Read empty separator line if _, err := s.reader.ReadString('\n'); err != nil { return nil, err } - // Read content body body := make([]byte, contentLength) if _, err := io.ReadFull(s.reader, body); err != nil { return nil, err @@ -393,7 +381,6 @@ func (s *server) readMessage() (*jsonRPCRequest, error) { return &req, nil } -// writeMessage writes a Content-Length framed JSON-RPC message to stdout. func (s *server) writeMessage(resp *jsonRPCResponse) error { body, err := json.Marshal(resp) if err != nil { @@ -476,7 +463,6 @@ func (s *server) handleRequest(req *jsonRPCRequest) *jsonRPCResponse { } } -// handleGetLanguages returns the supported language types. func (s *server) handleGetLanguages() []string { return []string{ "org.openrewrite.golang.tree.Go$CompilationUnit", @@ -511,13 +497,11 @@ type parseInput struct { } func (p *parseInput) UnmarshalJSON(data []byte) error { - // Try bare string first (Java PathInput serializes as @JsonValue string) var s string if err := json.Unmarshal(data, &s); err == nil { p.Path = s return nil } - // Otherwise unmarshal as a structured object type alias parseInput var a alias if err := json.Unmarshal(data, &a); err != nil { @@ -527,8 +511,6 @@ func (p *parseInput) UnmarshalJSON(data []byte) error { return nil } -// handleParse parses Go source files and returns their IDs. -// // When req.Module + req.GoModContent are set, the handler builds a // ProjectImporter from the parsed go.mod (requires) plus every .go input // in the batch (siblings) and uses it for type attribution. Inputs in the @@ -692,7 +674,6 @@ func (s *server) handleParse(params json.RawMessage) (any, *rpcError) { goModByIdx[r.idx] = gm } - // Emit results in input order. ids := make([]string, 0, len(req.Inputs)) for _, r := range resolvedInputs { if cu, ok := cuByIdx[r.idx]; ok && cu != nil { @@ -721,13 +702,11 @@ func (s *server) handleParse(params json.RawMessage) (any, *rpcError) { return ids, nil } -// getObjectRequest is the parameter type for GetObject. type getObjectRequest struct { ID string `json:"id"` SourceFileType string `json:"sourceFileType"` } -// handleGetObject serializes a local object for transfer to Java. func (s *server) handleGetObject(params json.RawMessage) (any, *rpcError) { var req getObjectRequest if err := json.Unmarshal(params, &req); err != nil { @@ -747,7 +726,6 @@ func (s *server) handleGetObject(params json.RawMessage) (any, *rpcError) { // between the reverse direction (Java→Go) and forward direction (Go→Java). localRefs := make(map[uintptr]int) - // Collect all batches into a single result var result []rpc.RpcObjectData q := rpc.NewSendQueue(s.batchSize, func(batch []rpc.RpcObjectData) { result = append(result, batch...) @@ -762,13 +740,11 @@ func (s *server) handleGetObject(params json.RawMessage) (any, *rpcError) { q.Put(rpc.RpcObjectData{State: rpc.EndOfObject}) q.Flush() - // Update remote tracking s.remoteObjects[req.ID] = obj return result, nil } -// printRequest is the parameter type for Print. type printRequest struct { TreeID string `json:"treeId"` SourcePath string `json:"sourcePath"` @@ -776,20 +752,17 @@ type printRequest struct { MarkerPrinter *string `json:"markerPrinter"` } -// handlePrint retrieves a tree from Java and prints it to source. func (s *server) handlePrint(params json.RawMessage) (any, *rpcError) { var req printRequest if err := json.Unmarshal(params, &req); err != nil { return nil, &rpcError{Code: -32602, Message: fmt.Sprintf("Invalid params: %v", err)} } - // Get the object from Java via bidirectional RPC obj := s.getObjectFromJava(req.TreeID, req.SourceFileType) if obj == nil { return "", nil } - // Map markerPrinter from the request to the Go MarkerPrinter mp := mapMarkerPrinter(req.MarkerPrinter) if cu, ok := obj.(*golang.CompilationUnit); ok { @@ -811,7 +784,6 @@ func (s *server) handlePrint(params json.RawMessage) (any, *rpcError) { return "", &rpcError{Code: -32603, Message: "Object is not a Tree"} } -// mapMarkerPrinter maps the RPC marker printer string to the Go MarkerPrinter. func mapMarkerPrinter(mp *string) printer.MarkerPrinter { if mp == nil { return nil @@ -843,7 +815,6 @@ func (s *server) getObjectFromJava(id string, sourceFileType string) any { before = s.localObjects[id] } - // fetchBatch sends a GetObject request to Java and reads one batch of RpcObjectData. fetchBatch := func() []rpc.RpcObjectData { reqParams := getObjectRequest{ID: id, SourceFileType: sourceFileType} paramsJSON, _ := json.Marshal(reqParams) @@ -1023,7 +994,6 @@ func (s *server) handleInstallRecipes(params json.RawMessage) (any, *rpcError) { }, nil } -// handleReset clears all cached state. func (s *server) handleReset() bool { s.localObjects = make(map[string]any) s.remoteObjects = make(map[string]any) @@ -1210,7 +1180,6 @@ func parseOrderedColumns(raw json.RawMessage) ([]recipe.ColumnValue, error) { return cols, nil } -// marketplaceRow matches Java's GetMarketplaceResponse.Row. type marketplaceRow struct { Descriptor marketplaceDescriptor `json:"descriptor"` CategoryPaths [][]marketplaceCategory `json:"categoryPaths"` @@ -1219,7 +1188,6 @@ type marketplaceRow struct { PackageName *string `json:"packageName"` } -// marketplaceDescriptor matches Java's RecipeDescriptor (minimal fields). type marketplaceDescriptor struct { Name string `json:"name"` DisplayName string `json:"displayName"` @@ -1248,7 +1216,6 @@ type marketplaceOption struct { Valid []any `json:"valid"` } -// marketplaceCategory matches Java's CategoryDescriptor. type marketplaceCategory struct { DisplayName string `json:"displayName"` PackageName string `json:"packageName"` @@ -1463,7 +1430,6 @@ func nonNil(s []string) []string { return s } -// prepareRecipeRequest is the parameter type for PrepareRecipe. type prepareRecipeRequest struct { ID string `json:"id"` Options map[string]any `json:"options"` @@ -1652,7 +1618,6 @@ func (s *server) prepareInstance(instance recipe.Recipe, name string) (prepareRe // operands (a list of nested wire entries). Returns ok=false when the // condition can't be serialized (e.g. an opaque local TreeVisitor with // no recipe identity) — the caller leaves the wrapper intact so the -// gate runs Go-side as a fallback. func preconditionWireEntry(condition preconditions.CheckArg) (map[string]any, bool) { switch c := condition.(type) { case *preconditions.RecipeRef: @@ -1676,7 +1641,6 @@ func preconditionWireEntry(condition preconditions.CheckArg) (map[string]any, bo } } -// visitRequest is the parameter type for Visit. type visitRequest struct { Visitor string `json:"visitor"` TreeID string `json:"treeId"` @@ -1685,12 +1649,10 @@ type visitRequest struct { Cursor []string `json:"cursor"` } -// visitResponse is the response type for Visit. type visitResponse struct { Modified bool `json:"modified"` } -// handleVisit applies a prepared recipe's visitor to a tree. func (s *server) handleVisit(params json.RawMessage) (any, *rpcError) { var req visitRequest if err := json.Unmarshal(params, &req); err != nil { @@ -1797,13 +1759,11 @@ func (s *server) handleVisit(params json.RawMessage) (any, *rpcError) { return &visitResponse{Modified: modified}, nil } -// generateRequest is the parameter type for Generate. type generateRequest struct { ID string `json:"id"` PID *string `json:"p"` } -// generateResponse is the response type for Generate. type generateResponse struct { IDs []string `json:"ids"` SourceFileTypes []string `json:"sourceFileTypes"` @@ -2032,13 +1992,11 @@ func sourceFileTypeFor(t java.Tree) string { return "" } -// traceGetObjectRequest is the parameter type for TraceGetObject. type traceGetObjectRequest struct { Receive bool `json:"receive"` Send bool `json:"send"` } -// handleTraceGetObject toggles tracing for GetObject calls. func (s *server) handleTraceGetObject(params json.RawMessage) (any, *rpcError) { var req traceGetObjectRequest if err := json.Unmarshal(params, &req); err != nil { @@ -2052,14 +2010,12 @@ func (s *server) handleTraceGetObject(params json.RawMessage) (any, *rpcError) { return true, nil } -// parseProjectRequest is the parameter type for ParseProject. type parseProjectRequest struct { ProjectPath string `json:"projectPath"` Exclusions []string `json:"exclusions"` RelativeTo *string `json:"relativeTo"` } -// parseProjectResponseItem describes a parsed source file. type parseProjectResponseItem struct { ID string `json:"id"` SourceFileType string `json:"sourceFileType"` diff --git a/rewrite-go/pkg/format/auto_format.go b/rewrite-go/pkg/format/auto_format.go index 27df86365a2..927d0c8f591 100644 --- a/rewrite-go/pkg/format/auto_format.go +++ b/rewrite-go/pkg/format/auto_format.go @@ -47,10 +47,6 @@ type AutoFormatVisitor struct { stopAfter java.Tree } -// NewAutoFormatVisitor returns a composer visitor that, on its first -// Visit, queues the four per-responsibility passes via DoAfterVisit. -// The recipe runner's after-visit drain runs them in order. Each pass -// sees the partially-normalized tree from its predecessors. func NewAutoFormatVisitor(stopAfter java.Tree) *AutoFormatVisitor { return visitor.Init(&AutoFormatVisitor{stopAfter: stopAfter}) } diff --git a/rewrite-go/pkg/format/blank_lines.go b/rewrite-go/pkg/format/blank_lines.go index 7e597d27918..dd908f888f7 100644 --- a/rewrite-go/pkg/format/blank_lines.go +++ b/rewrite-go/pkg/format/blank_lines.go @@ -39,8 +39,6 @@ type BlankLinesVisitor struct { stopAfterTracker } -// NewBlankLinesVisitor returns a visitor configured with the given -// stopAfter bound. Pass nil to format the entire visited tree. func NewBlankLinesVisitor(stopAfter java.Tree) *BlankLinesVisitor { return visitor.Init(&BlankLinesVisitor{ stopAfterTracker: stopAfterTracker{stopAfter: stopAfter}, diff --git a/rewrite-go/pkg/format/spaces.go b/rewrite-go/pkg/format/spaces.go index b92aaf0d5f0..eba7562d201 100644 --- a/rewrite-go/pkg/format/spaces.go +++ b/rewrite-go/pkg/format/spaces.go @@ -41,8 +41,6 @@ type SpacesVisitor struct { stopAfterTracker } -// NewSpacesVisitor returns a visitor configured with the given -// stopAfter bound. Pass nil to format the entire visited tree. func NewSpacesVisitor(stopAfter java.Tree) *SpacesVisitor { return visitor.Init(&SpacesVisitor{ stopAfterTracker: stopAfterTracker{stopAfter: stopAfter}, diff --git a/rewrite-go/pkg/format/tabs_and_indents.go b/rewrite-go/pkg/format/tabs_and_indents.go index aa5e03ab253..f69924dde86 100644 --- a/rewrite-go/pkg/format/tabs_and_indents.go +++ b/rewrite-go/pkg/format/tabs_and_indents.go @@ -47,8 +47,6 @@ type TabsAndIndentsVisitor struct { depth int } -// NewTabsAndIndentsVisitor returns a visitor configured with the given -// stopAfter bound. Pass nil to format the entire visited tree. func NewTabsAndIndentsVisitor(stopAfter java.Tree) *TabsAndIndentsVisitor { return visitor.Init(&TabsAndIndentsVisitor{ stopAfterTracker: stopAfterTracker{stopAfter: stopAfter}, diff --git a/rewrite-go/pkg/matcher/method_matcher.go b/rewrite-go/pkg/matcher/method_matcher.go index 3610b0cf8b1..89338f4e1e2 100644 --- a/rewrite-go/pkg/matcher/method_matcher.go +++ b/rewrite-go/pkg/matcher/method_matcher.go @@ -23,8 +23,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/tree/java" ) -// MethodMatcher matches method invocations against an AspectJ-style pattern. -// // Pattern format: "DeclaringType MethodName(ArgType1, ArgType2, ..)" // // Examples: @@ -45,12 +43,10 @@ type MethodMatcher struct { matchesAnyArgs bool // true when pattern is (..) } -// argMatcher matches a single argument type. type argMatcher interface { matches(t java.JavaType) bool } -// typeArgMatcher matches a specific type by FQN pattern. type typeArgMatcher struct { pattern *regexp.Regexp raw string @@ -65,12 +61,10 @@ func (m *typeArgMatcher) matches(t java.JavaType) bool { return m.pattern.MatchString(fqn) } -// wildcardArgMatcher matches any type (the ".." wildcard). type wildcardArgMatcher struct{} func (m *wildcardArgMatcher) matches(t java.JavaType) bool { return true } -// NewMethodMatcher creates a MethodMatcher from the given pattern string. // Pattern format: "DeclaringType MethodName(ArgTypes)" func NewMethodMatcher(pattern string) *MethodMatcher { pattern = strings.TrimSpace(pattern) @@ -126,7 +120,6 @@ func NewMethodMatcher(pattern string) *MethodMatcher { return mm } -// Matches checks if the given MethodInvocation matches this pattern. func (m *MethodMatcher) Matches(mi *java.MethodInvocation) bool { // Match method name if m.methodNamePattern != nil && !m.methodNamePattern.MatchString(mi.Name.Name) { @@ -172,7 +165,6 @@ func (m *MethodMatcher) Matches(mi *java.MethodInvocation) bool { return true } -// MatchesMethod checks if a JavaTypeMethod matches this pattern. func (m *MethodMatcher) MatchesMethod(mt *java.JavaTypeMethod) bool { if mt == nil { return false diff --git a/rewrite-go/pkg/matcher/type_utils.go b/rewrite-go/pkg/matcher/type_utils.go index 754fdf163e6..2f70c6a66d6 100644 --- a/rewrite-go/pkg/matcher/type_utils.go +++ b/rewrite-go/pkg/matcher/type_utils.go @@ -41,7 +41,6 @@ func GetFullyQualifiedName(t java.JavaType) string { return "" } -// IsOfClassType checks if the type has the exact fully qualified name. func IsOfClassType(t java.JavaType, fqn string) bool { return GetFullyQualifiedName(t) == fqn } @@ -101,12 +100,10 @@ func Implements(t java.JavaType, interfaceFQN string) bool { return IsAssignableTo(t, interfaceFQN) } -// IsError checks if the type is the Go built-in `error` interface. func IsError(t java.JavaType) bool { return IsOfClassType(t, "error") } -// IsString checks if the type is the Go `string` type. func IsString(t java.JavaType) bool { if t == nil { return false @@ -117,7 +114,6 @@ func IsString(t java.JavaType) bool { return IsOfClassType(t, "string") } -// IsNumeric checks if the type is a numeric type (int, float, etc.). func IsNumeric(t java.JavaType) bool { if t == nil { return false @@ -138,7 +134,6 @@ func IsNumeric(t java.JavaType) bool { return false } -// IsInt checks if the type is a Go integer type (int, int8…int64, uint…uintptr, byte, rune). func IsInt(t java.JavaType) bool { if p, ok := t.(*java.JavaTypePrimitive); ok { switch p.Keyword { @@ -157,7 +152,6 @@ func IsInt(t java.JavaType) bool { return false } -// IsBool checks if the type is the Go `bool` type. func IsBool(t java.JavaType) bool { if p, ok := t.(*java.JavaTypePrimitive); ok { return p.Keyword == "boolean" || p.Keyword == "bool" diff --git a/rewrite-go/pkg/parser/go_parser.go b/rewrite-go/pkg/parser/go_parser.go index a6780d73053..6b3c9eb9d7b 100644 --- a/rewrite-go/pkg/parser/go_parser.go +++ b/rewrite-go/pkg/parser/go_parser.go @@ -34,7 +34,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/tree/java" ) -// GoParser parses Go source code into OpenRewrite LST nodes. type GoParser struct { // Importer resolves imported packages for type checking. // Defaults to importer.Default() which resolves stdlib packages. @@ -72,7 +71,6 @@ type FileInput struct { Content string } -// Parse parses a single Go source file and returns its CompilationUnit. // Convenience wrapper around ParsePackage for the common one-file case; // type attribution that depends on sibling files in the same package // won't resolve here. Use ParsePackage when sibling files matter. @@ -179,7 +177,6 @@ func PackageNameOf(path, content string) string { return f.Name.Name } -// parseContext holds the state needed during AST-to-LST mapping. type parseContext struct { src []byte fset *token.FileSet @@ -235,8 +232,6 @@ func (ctx *parseContext) mapFile(file *ast.File, sourcePath string) *golang.Comp // Package name identifier pkgName := ctx.mapIdent(file.Name) paddedPkgName := java.RightPadded[*java.Identifier]{Element: pkgName} - - // Imports var imports *java.Container[*java.Import] imports = ctx.mapImports(file) @@ -251,8 +246,6 @@ func (ctx *parseContext) mapFile(file *ast.File, sourcePath string) *golang.Comp stmts = append(stmts, java.RightPadded[java.Statement]{Element: stmt}) } } - - // EOF eof := java.EmptySpace if ctx.cursor < len(ctx.src) { eof = java.ParseSpace(string(ctx.src[ctx.cursor:])) @@ -1932,7 +1925,6 @@ func (ctx *parseContext) mapBasicLit(lit *ast.BasicLit) *java.Literal { // hoistLeftPrefix detaches the leading whitespace from a node's first child // so it can be attached to the enclosing (outermost) element instead, per the // OpenRewrite convention that whitespace belongs to the outermost element. -// It returns the removed prefix and the child with an empty prefix. func hoistLeftPrefix[T java.J](node T) (java.Space, T) { prefix := node.GetPrefix() if prefix.Whitespace == "" && len(prefix.Comments) == 0 { @@ -3246,7 +3238,6 @@ func (ctx *parseContext) mapEllipsis(expr *ast.Ellipsis) java.Expression { } } -// findNextFrom finds the next occurrence of ch starting from a given offset. func (ctx *parseContext) findNextFrom(ch byte, from int) int { for i := from; i < len(ctx.src); i++ { if ctx.src[i] == ch { @@ -3301,7 +3292,6 @@ func mapBinaryOp(op token.Token) java.BinaryOperator { } } -// findNext returns the byte offset of the next occurrence of ch from the current cursor. func (ctx *parseContext) findNext(ch byte) int { for i := ctx.cursor; i < len(ctx.src); i++ { if ctx.src[i] == ch { @@ -3381,7 +3371,6 @@ func (ctx *parseContext) findNextPositionOf(ch byte, before int) int { return -1 } -// findNextString finds the next occurrence of s from the current cursor. func (ctx *parseContext) findNextString(s string) int { idx := strings.Index(string(ctx.src[ctx.cursor:]), s) if idx < 0 { @@ -3390,7 +3379,6 @@ func (ctx *parseContext) findNextString(s string) int { return ctx.cursor + idx } -// prefixString returns the raw source between cursor and pos, for debugging. func (ctx *parseContext) prefixString(pos token.Pos) string { if !pos.IsValid() { return "" diff --git a/rewrite-go/pkg/parser/gomod_lst.go b/rewrite-go/pkg/parser/gomod_lst.go index 81d715570c8..3fcac800eba 100644 --- a/rewrite-go/pkg/parser/gomod_lst.go +++ b/rewrite-go/pkg/parser/gomod_lst.go @@ -23,7 +23,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/tree/java" ) -// ParseGoModFile parses go.mod content into a lossless golang.GoMod LST. // Mirrors org.openrewrite.golang.GoModParser on the Java side (the LST // path, not the legacy PlainText+marker path). // diff --git a/rewrite-go/pkg/parser/gomod_parser.go b/rewrite-go/pkg/parser/gomod_parser.go index a2201235f6c..a66516047fb 100644 --- a/rewrite-go/pkg/parser/gomod_parser.go +++ b/rewrite-go/pkg/parser/gomod_parser.go @@ -26,7 +26,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/tree/golang" ) -// ParseGoMod parses go.mod content into a golang.GoResolutionResult. // Mirrors org.openrewrite.golang.GoModParser on the Java side. func ParseGoMod(path, content string) (*golang.GoResolutionResult, error) { f, err := modfile.Parse(path, []byte(content), nil) diff --git a/rewrite-go/pkg/parser/project_importer.go b/rewrite-go/pkg/parser/project_importer.go index 628a5047cc2..5ac4345c734 100644 --- a/rewrite-go/pkg/parser/project_importer.go +++ b/rewrite-go/pkg/parser/project_importer.go @@ -85,7 +85,6 @@ type projectFile struct { content string } -// NewProjectImporter creates an importer rooted at the given module path. // Pass importer.Default() (or nil for the same default) as the stdlib // fallback. Project root is unset and must be configured via // SetProjectRoot for vendor walking to find anything. @@ -123,7 +122,6 @@ func (p *ProjectImporter) AddReplace(oldPath, newPath, newVersion string) { p.replaces[oldPath] = replaceTarget{NewPath: newPath, NewVersion: newVersion} } -// AddRequire registers a module path declared in go.mod's `require` list. // Imports of this path (or any sub-path under it) that aren't already // satisfied by AddSource'd sibling sources resolve to a stub // *types.Package — non-nil, with the right path and name, but with an @@ -150,7 +148,6 @@ func (p *ProjectImporter) AddSource(relPath, content string) { p.sources[importPath] = append(p.sources[importPath], projectFile{path: relPath, content: content}) } -// Import implements types.Importer. func (p *ProjectImporter) Import(importPath string) (*types.Package, error) { if cached, ok := p.cache[importPath]; ok { return cached, nil @@ -274,7 +271,6 @@ func readGoFilesIn(dir string) ([]projectFile, error) { return out, nil } -// parsePackage parses + type-checks a sibling package's files. func (p *ProjectImporter) parsePackage(importPath string, files []projectFile) (*types.Package, error) { asts := make([]*ast.File, 0, len(files)) for _, f := range files { diff --git a/rewrite-go/pkg/parser/type_mapper.go b/rewrite-go/pkg/parser/type_mapper.go index 2aef225b2b0..50e6675299f 100644 --- a/rewrite-go/pkg/parser/type_mapper.go +++ b/rewrite-go/pkg/parser/type_mapper.go @@ -40,7 +40,6 @@ func newTypeMapper() *typeMapper { } } -// mapType converts a go/types.Type to a java.JavaType. func (m *typeMapper) mapType(t types.Type) java.JavaType { if t == nil { return nil @@ -218,8 +217,6 @@ func (m *typeMapper) mapSignature(sig *types.Signature, name string, declaringTy TypeParameters: tupleParams, } } - - // Parameters params := sig.Params() for i := 0; i < params.Len(); i++ { p := params.At(i) @@ -327,7 +324,6 @@ func flagsForObject(obj *types.TypeName) int64 { return flagsForExported(obj.Name()) } -// flagsForExported returns Public (1) if the name starts with an uppercase letter. func flagsForExported(name string) int64 { if len(name) > 0 && unicode.IsUpper(rune(name[0])) { return 1 // Java Flag.Public @@ -384,7 +380,6 @@ func (m *typeMapper) mapObjectToVariable(obj types.Object) *java.JavaTypeVariabl } } -// ownerType returns the JavaType of the object's owner (declaring type). func (m *typeMapper) ownerType(v *types.Var) java.JavaType { if !v.IsField() { return nil @@ -454,7 +449,6 @@ func isUnresolved(obj types.Object) bool { return obj == nil } -// isBlankIdent returns true if the identifier is "_". func isBlankIdent(name string) bool { return strings.TrimSpace(name) == "_" } diff --git a/rewrite-go/pkg/preconditions/preconditions.go b/rewrite-go/pkg/preconditions/preconditions.go index 8c5af257a28..321f6bffe2c 100644 --- a/rewrite-go/pkg/preconditions/preconditions.go +++ b/rewrite-go/pkg/preconditions/preconditions.go @@ -167,8 +167,6 @@ func runVisitor(v recipe.TreeVisitor, t java.Tree, p any) bool { return result != t } -// Check wraps an editor with a precondition gate. -// // Argument shapes accepted as the gate (CheckArg): // - recipe.TreeVisitor — runs in-process as the gate // - recipe.Recipe — its Editor() is used as the gate diff --git a/rewrite-go/pkg/preconditions/search.go b/rewrite-go/pkg/preconditions/search.go index d1cc13b0f26..e61a4f91645 100644 --- a/rewrite-go/pkg/preconditions/search.go +++ b/rewrite-go/pkg/preconditions/search.go @@ -35,8 +35,6 @@ func isSourceFile(t java.Tree) bool { return ok } -// IsSourceFileVisitor matches SourceFile trees by path glob. -// // Mirrors org.openrewrite.FindSourceFiles. Used as the LocalVisitor // bundled with the *RecipeRef returned by HasSourcePath so unit tests // without an active RPC connection still see real filtering. diff --git a/rewrite-go/pkg/printer/go_printer.go b/rewrite-go/pkg/printer/go_printer.go index 5cd36ea61ec..af44759eb24 100644 --- a/rewrite-go/pkg/printer/go_printer.go +++ b/rewrite-go/pkg/printer/go_printer.go @@ -22,7 +22,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/visitor" ) -// GoPrinter prints an OpenRewrite LST back to Go source code. type GoPrinter struct { visitor.GoVisitor } @@ -282,7 +281,6 @@ func (p *GoPrinter) VisitMethodDeclaration(md *java.MethodDeclaration, param any return md } -// VisitGoMethodDeclaration prints a method declaration with a receiver. The // wrapper owns the prefix and the receiver, but both are emitted by the inner // declaration's VisitMethodDeclaration (which sources them via the cursor), // keeping the receiver correctly positioned between `func` and the name and the @@ -304,7 +302,6 @@ func (p *GoPrinter) methodDeclarationWrapper() (*golang.MethodDeclaration, bool) return wrapper, ok } -// VisitStatementWithInit prints an if/switch carrying an init clause. The // wrapper owns the prefix and the init statement, but both are emitted by the // inner statement's VisitIf/VisitSwitch (which source them via the cursor), // keeping `;` correctly positioned between the keyword and the condition. @@ -691,7 +688,6 @@ func (p *GoPrinter) VisitForEachControl(control *java.ForEachControl, param any) return control } -// VisitAnnotation prints an Annotation in struct-tag form // (`key:"value"`) — including its leading whitespace via Prefix. // Backtick wrapping is the VariableDeclarations printer's job for // struct-field context; this method only emits the annotation's own diff --git a/rewrite-go/pkg/printer/gomod_printer.go b/rewrite-go/pkg/printer/gomod_printer.go index e5d646ee079..53e7fad42d7 100644 --- a/rewrite-go/pkg/printer/gomod_printer.go +++ b/rewrite-go/pkg/printer/gomod_printer.go @@ -22,7 +22,6 @@ import ( // PrintGoMod renders a GoMod LST back to source. Because every byte of // whitespace and every comment is preserved on the tree, an unmodified -// GoMod prints to exactly the bytes it was parsed from. func PrintGoMod(gm *golang.GoMod) string { return printGoMod(gm, NewPrintOutputCapture()) } diff --git a/rewrite-go/pkg/printer/marker_printer.go b/rewrite-go/pkg/printer/marker_printer.go index 3ed0c4c40f5..7db52a27133 100644 --- a/rewrite-go/pkg/printer/marker_printer.go +++ b/rewrite-go/pkg/printer/marker_printer.go @@ -22,10 +22,8 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/tree/java" ) -// CommentWrapper wraps marker output in a language-appropriate comment syntax. type CommentWrapper func(output string) string -// GoCommentWrapper wraps marker output in Go block comment syntax: /*~~(output)~~>*/ func GoCommentWrapper(output string) string { if output == "" { return "/*~~>*/" @@ -37,32 +35,22 @@ func GoCommentWrapper(output string) string { // are rendered in printed output. Go-specific markers (ShortVarDecl, GroupedImport, etc.) // are handled directly by the printer's visit methods. type MarkerPrinter interface { - // BeforePrefix returns text to emit before a node's prefix space. BeforePrefix(marker java.Marker, wrapper CommentWrapper) string - // BeforeSyntax returns text to emit after a node's prefix but before its syntax. BeforeSyntax(marker java.Marker, wrapper CommentWrapper) string - // AfterSyntax returns text to emit after a node's syntax. AfterSyntax(marker java.Marker, wrapper CommentWrapper) string } -// --- Predefined MarkerPrinter implementations --- - -// DefaultMarkerPrinter prints SearchResult and Markup markers as comments before syntax. var DefaultMarkerPrinter MarkerPrinter = defaultMarkerPrinter{} -// SearchOnlyMarkerPrinter prints only SearchResult markers (ignores Markup). var SearchOnlyMarkerPrinter MarkerPrinter = searchOnlyMarkerPrinter{} -// FencedMarkerPrinter wraps markers with {{uuid}} delimiters before and after syntax. var FencedMarkerPrinter MarkerPrinter = fencedMarkerPrinter{} // SanitizedMarkerPrinter strips all markers from output. var SanitizedMarkerPrinter MarkerPrinter = sanitizedMarkerPrinter{} -// --- defaultMarkerPrinter --- - type defaultMarkerPrinter struct{} func (defaultMarkerPrinter) BeforePrefix(marker java.Marker, wrapper CommentWrapper) string { @@ -89,8 +77,6 @@ func (defaultMarkerPrinter) AfterSyntax(marker java.Marker, wrapper CommentWrapp return "" } -// --- searchOnlyMarkerPrinter --- - type searchOnlyMarkerPrinter struct{} func (searchOnlyMarkerPrinter) BeforePrefix(marker java.Marker, wrapper CommentWrapper) string { @@ -111,8 +97,6 @@ func (searchOnlyMarkerPrinter) AfterSyntax(marker java.Marker, wrapper CommentWr return "" } -// --- fencedMarkerPrinter --- - type fencedMarkerPrinter struct{} func (fencedMarkerPrinter) BeforePrefix(marker java.Marker, wrapper CommentWrapper) string { @@ -141,8 +125,6 @@ func isFenceable(marker java.Marker) bool { return false } -// --- sanitizedMarkerPrinter --- - type sanitizedMarkerPrinter struct{} func (sanitizedMarkerPrinter) BeforePrefix(marker java.Marker, wrapper CommentWrapper) string { diff --git a/rewrite-go/pkg/printer/print_output_capture.go b/rewrite-go/pkg/printer/print_output_capture.go index 99a50883b40..859759fccaa 100644 --- a/rewrite-go/pkg/printer/print_output_capture.go +++ b/rewrite-go/pkg/printer/print_output_capture.go @@ -28,12 +28,10 @@ type PrintOutputCapture struct { markerPrinter MarkerPrinter } -// NewPrintOutputCapture creates a PrintOutputCapture with no marker printer. func NewPrintOutputCapture() *PrintOutputCapture { return &PrintOutputCapture{} } -// NewPrintOutputCaptureWithMarkers creates a PrintOutputCapture with the given MarkerPrinter. func NewPrintOutputCaptureWithMarkers(mp MarkerPrinter) *PrintOutputCapture { return &PrintOutputCapture{markerPrinter: mp} } @@ -46,7 +44,6 @@ func (p *PrintOutputCapture) String() string { return p.buf.String() } -// BeforePrefix emits marker output before a node's prefix space. func (p *PrintOutputCapture) BeforePrefix(markers java.Markers) { if p.markerPrinter == nil { return @@ -58,7 +55,6 @@ func (p *PrintOutputCapture) BeforePrefix(markers java.Markers) { } } -// BeforeSyntax emits marker output after a node's prefix but before its syntax. func (p *PrintOutputCapture) BeforeSyntax(markers java.Markers) { if p.markerPrinter == nil { return @@ -70,7 +66,6 @@ func (p *PrintOutputCapture) BeforeSyntax(markers java.Markers) { } } -// AfterSyntax emits marker output after a node's syntax. func (p *PrintOutputCapture) AfterSyntax(markers java.Markers) { if p.markerPrinter == nil { return diff --git a/rewrite-go/pkg/recipe/data_table.go b/rewrite-go/pkg/recipe/data_table.go index afc6a92a0c5..e5c1133b17b 100644 --- a/rewrite-go/pkg/recipe/data_table.go +++ b/rewrite-go/pkg/recipe/data_table.go @@ -32,8 +32,6 @@ import ( // DataTableStore is installed. Mirrors JS DATA_TABLE_STORE. const DataTableStoreKey = "org.openrewrite.dataTables.store" -// DataTableLike is the type-erased view of a DataTable that DataTableStore -// implementations work against. Generic DataTable[Row] satisfies this. type DataTableLike interface { Descriptor() DataTableDescriptor InstanceName() string @@ -96,16 +94,11 @@ func (dt *DataTable[Row]) InsertRow(ctx *ExecutionContext, row Row) { } } -// --- InMemoryDataTableStore --- - type bucket struct { dt DataTableLike rows []any } -// InMemoryDataTableStore holds rows in memory keyed by (dataTableName, group). -// Rows can be read back via GetRows. Default for tests and recipes that -// don't need disk-backed output. type InMemoryDataTableStore struct { mu sync.Mutex buckets map[string]*bucket @@ -162,8 +155,6 @@ func (s *InMemoryDataTableStore) GetDataTables() []DataTableLike { return out } -// --- CsvDataTableStore --- - var nonAlnum = regexp.MustCompile(`[^a-z0-9]`) var dashRun = regexp.MustCompile(`-+`) var leadingTrailingDash = regexp.MustCompile(`^-|-$`) @@ -192,7 +183,6 @@ type ColumnValue struct { Value string } -// CsvDataTableStore writes rows directly to raw .csv files, one per (recipe, dataTable, group). type CsvDataTableStore struct { outputDir string prefixColumns []ColumnValue @@ -217,7 +207,6 @@ func NewCsvDataTableStoreWithColumns(outputDir string, prefix, suffix []ColumnVa }, nil } -// Close is a no-op: each row is written with its own short-lived append handle. func (s *CsvDataTableStore) Close() {} // fileKey mirrors Java's CsvDataTableStore.fileKey exactly so a table shared by diff --git a/rewrite-go/pkg/recipe/execution_context.go b/rewrite-go/pkg/recipe/execution_context.go index d8f9bf4f8e4..0d743d9e39a 100644 --- a/rewrite-go/pkg/recipe/execution_context.go +++ b/rewrite-go/pkg/recipe/execution_context.go @@ -26,21 +26,18 @@ type ExecutionContext struct { messages map[string]any } -// NewExecutionContext creates a new ExecutionContext. func NewExecutionContext() *ExecutionContext { return &ExecutionContext{ messages: make(map[string]any), } } -// PutMessage stores a value by key. func (ctx *ExecutionContext) PutMessage(key string, value any) { ctx.mu.Lock() defer ctx.mu.Unlock() ctx.messages[key] = value } -// GetMessage retrieves a value by key. func (ctx *ExecutionContext) GetMessage(key string) (any, bool) { ctx.mu.RLock() defer ctx.mu.RUnlock() @@ -48,7 +45,6 @@ func (ctx *ExecutionContext) GetMessage(key string) (any, bool) { return v, ok } -// GetMessageOrDefault retrieves a value by key, or returns the default if not found. func (ctx *ExecutionContext) GetMessageOrDefault(key string, defaultValue any) any { ctx.mu.RLock() defer ctx.mu.RUnlock() diff --git a/rewrite-go/pkg/recipe/golang/activate.go b/rewrite-go/pkg/recipe/golang/activate.go index b12ecb220fd..5ae30c2e180 100644 --- a/rewrite-go/pkg/recipe/golang/activate.go +++ b/rewrite-go/pkg/recipe/golang/activate.go @@ -18,7 +18,6 @@ package golang import "github.com/openrewrite/rewrite/rewrite-go/pkg/recipe" -// Activate registers all Go recipes with the given registry. func Activate(r *recipe.Registry) { golangCategory := recipe.CategoryDescriptor{DisplayName: "Go"} searchCategory := recipe.CategoryDescriptor{DisplayName: "Search"} diff --git a/rewrite-go/pkg/recipe/golang/add_import.go b/rewrite-go/pkg/recipe/golang/add_import.go index 93904708fb7..d89c76e86d1 100644 --- a/rewrite-go/pkg/recipe/golang/add_import.go +++ b/rewrite-go/pkg/recipe/golang/add_import.go @@ -24,8 +24,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/visitor" ) -// AddImport adds an `import` statement to a Go compilation unit. -// // Mirrors the Java AddImport recipe with full surface parity (per the // C1 directive in the eng review): // diff --git a/rewrite-go/pkg/recipe/golang/annotation_service.go b/rewrite-go/pkg/recipe/golang/annotation_service.go index e22b82c4903..fb2dbb7c469 100644 --- a/rewrite-go/pkg/recipe/golang/annotation_service.go +++ b/rewrite-go/pkg/recipe/golang/annotation_service.go @@ -80,7 +80,6 @@ type AnnotationMatcher struct { pattern string } -// NewAnnotationMatcher constructs a matcher for the given pattern. // See AnnotationMatcher for pattern semantics. func NewAnnotationMatcher(pattern string) AnnotationMatcher { return AnnotationMatcher{pattern: pattern} diff --git a/rewrite-go/pkg/recipe/golang/change_method_name.go b/rewrite-go/pkg/recipe/golang/change_method_name.go index 755561bf1f4..27297e0ae7b 100644 --- a/rewrite-go/pkg/recipe/golang/change_method_name.go +++ b/rewrite-go/pkg/recipe/golang/change_method_name.go @@ -18,7 +18,6 @@ package golang import "github.com/openrewrite/rewrite/rewrite-go/pkg/recipe" -// ChangeMethodName renames method invocations matching a pattern. // Delegates to the Java ChangeMethodName recipe via RPC. type ChangeMethodName struct { recipe.Base diff --git a/rewrite-go/pkg/recipe/golang/change_type.go b/rewrite-go/pkg/recipe/golang/change_type.go index 928c58099de..bdd0e6d2a32 100644 --- a/rewrite-go/pkg/recipe/golang/change_type.go +++ b/rewrite-go/pkg/recipe/golang/change_type.go @@ -18,7 +18,6 @@ package golang import "github.com/openrewrite/rewrite/rewrite-go/pkg/recipe" -// ChangeType changes a Go type reference from one fully qualified name to another. // Delegates to the Java ChangeType recipe via RPC. type ChangeType struct { recipe.Base diff --git a/rewrite-go/pkg/recipe/golang/find_methods.go b/rewrite-go/pkg/recipe/golang/find_methods.go index 77ef11567b4..1d601dc72f4 100644 --- a/rewrite-go/pkg/recipe/golang/find_methods.go +++ b/rewrite-go/pkg/recipe/golang/find_methods.go @@ -18,7 +18,6 @@ package golang import "github.com/openrewrite/rewrite/rewrite-go/pkg/recipe" -// FindMethods finds all method invocations matching a pattern. // Delegates to the Java FindMethods recipe via RPC. type FindMethods struct { recipe.Base diff --git a/rewrite-go/pkg/recipe/golang/find_types.go b/rewrite-go/pkg/recipe/golang/find_types.go index beecbc19505..e4bc9b6058b 100644 --- a/rewrite-go/pkg/recipe/golang/find_types.go +++ b/rewrite-go/pkg/recipe/golang/find_types.go @@ -18,7 +18,6 @@ package golang import "github.com/openrewrite/rewrite/rewrite-go/pkg/recipe" -// FindTypes finds all references to a given type. // Delegates to the Java FindTypes recipe via RPC. type FindTypes struct { recipe.Base diff --git a/rewrite-go/pkg/recipe/golang/internal/imports.go b/rewrite-go/pkg/recipe/golang/internal/imports.go index 37f82e0794b..c01378eb5a2 100644 --- a/rewrite-go/pkg/recipe/golang/internal/imports.go +++ b/rewrite-go/pkg/recipe/golang/internal/imports.go @@ -45,7 +45,6 @@ const ( Local ) -// ImportPath returns the unquoted import path of an Import (e.g. "fmt"). // Returns "" when Qualid isn't a Literal (defensive — shouldn't happen // for well-formed Go source). // @@ -82,7 +81,6 @@ func AliasName(imp *java.Import) string { return imp.Alias.Element.Name } -// FindImport returns the first import in cu whose path equals importPath. // Returns nil if no match. func FindImport(cu *golang.CompilationUnit, importPath string) *java.Import { if cu == nil || cu.Imports == nil { diff --git a/rewrite-go/pkg/recipe/golang/naming_service.go b/rewrite-go/pkg/recipe/golang/naming_service.go index 36b0aa1935a..028cf35e23f 100644 --- a/rewrite-go/pkg/recipe/golang/naming_service.go +++ b/rewrite-go/pkg/recipe/golang/naming_service.go @@ -109,21 +109,16 @@ func (s *NamingService) IsPredeclared(name string) bool { // spec. Update when the language adds new builtins (e.g. `min` / // `max` / `clear` were added in 1.21). var predeclaredIdentifiers = map[string]struct{}{ - // Types. "any": {}, "bool": {}, "byte": {}, "comparable": {}, "complex64": {}, "complex128": {}, "error": {}, "float32": {}, "float64": {}, "int": {}, "int8": {}, "int16": {}, "int32": {}, "int64": {}, "rune": {}, "string": {}, "uint": {}, "uint8": {}, "uint16": {}, "uint32": {}, "uint64": {}, "uintptr": {}, - - // Constants. "true": {}, "false": {}, "iota": {}, // Zero value. - "nil": {}, - - // Functions. + "nil": {}, "append": {}, "cap": {}, "clear": {}, "close": {}, "complex": {}, "copy": {}, "delete": {}, "imag": {}, "len": {}, "make": {}, "max": {}, "min": {}, "new": {}, "panic": {}, "print": {}, diff --git a/rewrite-go/pkg/recipe/golang/remove_import.go b/rewrite-go/pkg/recipe/golang/remove_import.go index 615e6844eb3..049f548fc74 100644 --- a/rewrite-go/pkg/recipe/golang/remove_import.go +++ b/rewrite-go/pkg/recipe/golang/remove_import.go @@ -24,8 +24,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/visitor" ) -// RemoveImport deletes a single import from a Go compilation unit. -// // Matches by import path: any form (regular, aliased, dot, or blank) // that imports PackagePath is removed. If the imports container becomes // empty as a result, it is nil-ed out so the printer doesn't emit an diff --git a/rewrite-go/pkg/recipe/golang/rename_package.go b/rewrite-go/pkg/recipe/golang/rename_package.go index 9ce151f4143..9253cb8a364 100644 --- a/rewrite-go/pkg/recipe/golang/rename_package.go +++ b/rewrite-go/pkg/recipe/golang/rename_package.go @@ -27,8 +27,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/visitor" ) -// RenamePackage renames a Go package across a project. -// // On every visited compilation unit: // - If the file's `package` declaration matches the last segment of // OldPackagePath AND the file is in the renamed package, the diff --git a/rewrite-go/pkg/recipe/installer/installer.go b/rewrite-go/pkg/recipe/installer/installer.go index 84f0e011d79..df017d2005d 100644 --- a/rewrite-go/pkg/recipe/installer/installer.go +++ b/rewrite-go/pkg/recipe/installer/installer.go @@ -31,7 +31,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/recipe" ) -// RecipeModuleInfo holds information about an installed recipe module. type RecipeModuleInfo struct { ImportPath string // ActivatePkg is the full Go import path of the package that contains @@ -50,7 +49,6 @@ type Installer struct { Logger func(string, ...any) // optional logger } -// NewInstaller creates an Installer rooted at the given workspace directory. // The caller is responsible for choosing (and, where appropriate, cleaning // up) the directory; the installer does not impose a default location. func NewInstaller(workspaceDir string) *Installer { @@ -59,7 +57,6 @@ func NewInstaller(workspaceDir string) *Installer { } } -// ensureWorkspace creates the workspace directory and initializes go.mod if needed. func (inst *Installer) ensureWorkspace() error { if err := os.MkdirAll(inst.WorkspaceDir, 0755); err != nil { return fmt.Errorf("create workspace: %w", err) @@ -345,7 +342,6 @@ func generateHelper(path string, modulePath string) error { }) } -// goCmd runs a go command in the workspace directory. func (inst *Installer) goCmd(args ...string) error { return inst.goCmdEnv(nil, args...) } @@ -388,12 +384,10 @@ func isProxyFetchError(err error) bool { strings.Contains(msg, "Not Found") } -// addReplace adds a replace directive to the workspace go.mod. func (inst *Installer) addReplace(modulePath, localPath string) error { return inst.goCmd("mod", "edit", "-replace="+modulePath+"="+localPath) } -// addRequire adds a require directive to the workspace go.mod. func (inst *Installer) addRequire(modulePath, version string) error { return inst.goCmd("mod", "edit", "-require="+modulePath+"@"+version) } @@ -435,7 +429,6 @@ func findActivatePackage(moduleDir, modulePath string) (string, error) { return activatePkg, nil } -// readModulePath reads the module path from a go.mod file in the given directory. func readModulePath(dir string) (string, error) { data, err := os.ReadFile(filepath.Join(dir, "go.mod")) if err != nil { @@ -512,7 +505,6 @@ func (inst *Installer) propagateReplaces(moduleDir string) error { return nil } -// readResolvedVersion reads the resolved version of a module from the workspace go.mod. func (inst *Installer) readResolvedVersion(modulePath string) string { data, err := os.ReadFile(filepath.Join(inst.WorkspaceDir, "go.mod")) if err != nil { diff --git a/rewrite-go/pkg/recipe/recipe.go b/rewrite-go/pkg/recipe/recipe.go index 3d02cf8bae2..97070e44f86 100644 --- a/rewrite-go/pkg/recipe/recipe.go +++ b/rewrite-go/pkg/recipe/recipe.go @@ -33,49 +33,36 @@ type TreeVisitor interface { // Recipe defines a source code transformation. type Recipe interface { - // Name returns the fully qualified recipe name (e.g., "org.openrewrite.golang.ChangePackageName"). Name() string - // DisplayName returns a human-readable name for display in UIs. DisplayName() string - // Description returns a markdown-enabled description of the recipe's purpose. Description() string - // Tags returns categorization tags (e.g., "cleanup", "security"). May be nil. Tags() []string - // EstimatedEffortPerOccurrence returns the estimated manual effort per change. EstimatedEffortPerOccurrence() time.Duration - // Editor returns the visitor that performs the transformation. // Returns nil for recipes that only compose sub-recipes via RecipeList. Editor() TreeVisitor - // RecipeList returns sub-recipes that run as part of this recipe. May be nil. RecipeList() []Recipe - // Options returns descriptors for this recipe's configurable options. Options() []OptionDescriptor - // DataTables returns descriptors for any DataTable rows this recipe emits. // May be nil. The runtime for writing rows is provided by the DataTable // type and DataTableStore (separate from these descriptors). DataTables() []DataTableDescriptor - // Maintainers returns the people responsible for the recipe. May be nil. Maintainers() []Maintainer - // Contributors returns the people who have contributed code or design. // May be nil. Contributors() []Contributor - // Examples returns before/after examples illustrating the recipe. // May be nil. Examples() []Example } -// Base provides default implementations for optional Recipe methods. // Embed it in your recipe struct to avoid implementing every method: // // type MyRecipe struct { @@ -100,39 +87,21 @@ func (Base) Examples() []Example { return nil } type DelegatesTo interface { Recipe - // JavaRecipeName returns the fully qualified Java recipe name - // (e.g., "org.openrewrite.java.ChangeType"). JavaRecipeName() string - // JavaOptions returns options to configure the Java recipe, keyed by option name. JavaOptions() map[string]any } -// OptionDescriptor describes a configurable option on a recipe. type OptionDescriptor struct { - // Name is the programmatic name (e.g., "oldPackageName"). - Name string - - // DisplayName is the human-readable label. + Name string DisplayName string - - // Description explains the option's purpose. Description string - - // Example shows a sample value. - Example string - - // Required indicates the option must be set. - Required bool - - // Valid lists allowed values (nil means any value is accepted). - Valid []string - - // Value is the current value, if set. - Value any + Example string + Required bool + Valid []string + Value any } -// Option creates a required OptionDescriptor with the given name, display name, and description. // Use the fluent With* methods to customize further: // // recipe.Option("oldName", "Old name", "The identifier to rename.").WithValue(r.OldName) @@ -142,19 +111,14 @@ func Option(name, displayName, description string) OptionDescriptor { return OptionDescriptor{Name: name, DisplayName: displayName, Description: description, Required: true} } -// WithValue sets the current value of the option. func (o OptionDescriptor) WithValue(v any) OptionDescriptor { o.Value = v; return o } -// WithExample sets an example value for the option. func (o OptionDescriptor) WithExample(e string) OptionDescriptor { o.Example = e; return o } -// WithValid sets the allowed values for the option. func (o OptionDescriptor) WithValid(v ...string) OptionDescriptor { o.Valid = v; return o } -// AsOptional marks the option as not required. func (o OptionDescriptor) AsOptional() OptionDescriptor { o.Required = false; return o } -// TypeName returns a Java-style type name derived from the option's Value. // Used to populate the marketplace option `type` wire field. func (o OptionDescriptor) TypeName() string { if o.Value == nil { @@ -176,7 +140,6 @@ func (o OptionDescriptor) TypeName() string { } } -// DataTableDescriptor describes a DataTable a recipe emits. type DataTableDescriptor struct { Name string DisplayName string @@ -184,7 +147,6 @@ type DataTableDescriptor struct { Columns []ColumnDescriptor } -// ColumnDescriptor describes a column within a DataTable. type ColumnDescriptor struct { Name string DisplayName string @@ -192,28 +154,24 @@ type ColumnDescriptor struct { Type string // e.g. "String", "Integer", "Long" } -// Maintainer represents a recipe maintainer. type Maintainer struct { Name string Email string Logo string } -// Contributor represents someone who has contributed to the recipe. type Contributor struct { Name string Email string LineCount int } -// Example is a before/after example illustrating the recipe. type Example struct { Description string Sources []ExampleSource Parameters []string } -// ExampleSource is one before/after pair within an Example. type ExampleSource struct { Before string After string @@ -221,8 +179,6 @@ type ExampleSource struct { Language string } -// RecipeDescriptor provides metadata about a recipe for display and serialization. -// // Note: the Preconditions field carries declarative-recipe metadata // (the Java RecipeDescriptor.preconditions list, for YAML // DeclarativeRecipe). Runtime precondition gates are expressed via the diff --git a/rewrite-go/pkg/recipe/registry.go b/rewrite-go/pkg/recipe/registry.go index ef20f98117d..d1d4f33e9a2 100644 --- a/rewrite-go/pkg/recipe/registry.go +++ b/rewrite-go/pkg/recipe/registry.go @@ -22,21 +22,15 @@ import ( "sync" ) -// CategoryDescriptor describes a recipe category for hierarchical organization. type CategoryDescriptor struct { DisplayName string Description string } -// RecipeConstructor creates a new Recipe instance, optionally configured with options. type RecipeConstructor func(options map[string]any) Recipe -// Registration holds a recipe constructor and its category path. type Registration struct { - // Descriptor provides metadata about the recipe. - Descriptor RecipeDescriptor - - // Constructor creates new instances of the recipe with the given options. + Descriptor RecipeDescriptor Constructor RecipeConstructor // Categories is the category path from shallowest to deepest @@ -44,14 +38,12 @@ type Registration struct { Categories []CategoryDescriptor } -// Category is a node in the recipe category tree. type Category struct { CategoryDescriptor Recipes []Registration Subcategories []*Category } -// Registry holds all registered recipes organized by category. // Create one with NewRegistry and populate it via Activate: // // registry := recipe.NewRegistry() @@ -69,7 +61,6 @@ type Registry struct { subByName map[string]*Registration } -// Activator is a function that registers recipes with a registry. // Each module provides an Activate function that the caller passes // to Registry.Activate: // @@ -85,7 +76,6 @@ type Registry struct { // registry.Activate(cleanup.Activate, security.Activate) type Activator func(registry *Registry) -// NewRegistry creates an empty registry. func NewRegistry() *Registry { return &Registry{ byName: make(map[string]*Registration), @@ -93,7 +83,6 @@ func NewRegistry() *Registry { } } -// Register adds a recipe to the registry. // The prototype is used to extract the recipe descriptor. A constructor is // automatically derived via reflection: it creates a new instance of the // prototype's type and sets exported fields from the options map. Option @@ -150,13 +139,10 @@ func (r *Registry) registerSubRecipes(rec Recipe) { } } -// RegisterDescriptor registers a recipe from its descriptor (used for dynamically loaded recipes). -// The constructor returns nil since the recipe implementation lives in the external module. func (r *Registry) RegisterDescriptor(desc RecipeDescriptor) { r.RegisterWithCategories(desc, nil) } -// RegisterWithCategories registers a recipe descriptor with its category path. func (r *Registry) RegisterWithCategories(desc RecipeDescriptor, categories []CategoryDescriptor) { r.mu.Lock() defer r.mu.Unlock() @@ -183,7 +169,6 @@ func (r *Registry) RegisterWithCategories(desc RecipeDescriptor, categories []Ca r.byName[desc.Name] = reg } -// FindRecipe looks up a registration by fully qualified recipe name. func (r *Registry) FindRecipe(name string) (*Registration, bool) { r.mu.RLock() defer r.mu.RUnlock() @@ -196,7 +181,6 @@ func (r *Registry) FindRecipe(name string) (*Registration, bool) { return reg, ok } -// AllRecipes returns descriptors for all registered recipes. func (r *Registry) AllRecipes() []RecipeDescriptor { r.mu.RLock() defer r.mu.RUnlock() @@ -207,7 +191,6 @@ func (r *Registry) AllRecipes() []RecipeDescriptor { return result } -// AllRegistrations returns the full registrations (descriptor + categories) for all recipes. func (r *Registry) AllRegistrations() []Registration { r.mu.RLock() defer r.mu.RUnlock() @@ -218,14 +201,12 @@ func (r *Registry) AllRegistrations() []Registration { return result } -// Categories returns the top-level categories. func (r *Registry) Categories() []*Category { r.mu.RLock() defer r.mu.RUnlock() return r.root.Subcategories } -// Activate runs the given activators against this registry. // Each activator calls Register to add its recipes. This is the // single entry point for populating a registry. // diff --git a/rewrite-go/pkg/recipe/scanning_recipe.go b/rewrite-go/pkg/recipe/scanning_recipe.go index 6b41a34de30..34a9c8990ba 100644 --- a/rewrite-go/pkg/recipe/scanning_recipe.go +++ b/rewrite-go/pkg/recipe/scanning_recipe.go @@ -56,7 +56,6 @@ type ScanningRecipe interface { Generate(acc any, ctx *ExecutionContext) []java.Tree } -// ScanningBase provides default implementations for optional ScanningRecipe methods. // Embed it in your scanning recipe struct. type ScanningBase struct { Base diff --git a/rewrite-go/pkg/rpc/go_receiver.go b/rewrite-go/pkg/rpc/go_receiver.go index c93a2b6021f..5337f367fe3 100644 --- a/rewrite-go/pkg/rpc/go_receiver.go +++ b/rewrite-go/pkg/rpc/go_receiver.go @@ -23,7 +23,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/visitor" ) -// GoReceiver deserializes Go AST nodes via the visitor pattern. // Mirrors org.openrewrite.golang.internal.rpc.GolangReceiver, which // extends JavaReceiver, which extends JavaVisitor. // @@ -36,7 +35,6 @@ type GoReceiver struct { JavaReceiver } -// NewGoReceiver creates a GoReceiver ready to deserialize trees. func NewGoReceiver() *GoReceiver { gr := &GoReceiver{} gr.typeReceiver = NewJavaTypeReceiver() @@ -61,8 +59,6 @@ func (r *GoReceiver) Visit(t java.Tree, p any) java.Tree { return r.GoVisitor.Visit(t, p) } -// --- G nodes --- - // receiveParseError deserializes a ParseError matching Java's ParseError.rpcReceive field order: // id, markers, sourcePath, charsetName, charsetBomMarked, checksum, fileAttributes, text. // @@ -135,7 +131,6 @@ func (r *GoReceiver) VisitCompilationUnit(cu *golang.CompilationUnit, p any) jav cu.Statements[i] = coerceToStatementRP(s) } } - // EOF cu.EOF = receiveValue(q, cu.EOF, func(e java.Space) any { return receiveSpace(e, q) }) return cu } @@ -443,7 +438,6 @@ func (r *GoReceiver) VisitMultiAssignment(ma *golang.MultiAssignment, p any) jav q := p.(*ReceiveQueue) c := *ma // shallow copy to avoid mutating remoteObjects baseline ma = &c - // Variables beforeVars := make([]any, len(ma.Variables)) for i, v := range ma.Variables { beforeVars[i] = v @@ -455,11 +449,9 @@ func (r *GoReceiver) VisitMultiAssignment(ma *golang.MultiAssignment, p any) jav ma.Variables[i] = coerceToExpressionRP(v) } } - // Operator if result := q.Receive(ma.Operator, func(v any) any { return receiveLeftPadded(r, q, v) }); result != nil { ma.Operator = result.(java.LeftPadded[java.Space]) } - // Values beforeVals := make([]any, len(ma.Values)) for i, v := range ma.Values { beforeVals[i] = v @@ -518,7 +510,6 @@ func (r *GoReceiver) VisitCommClause(cc *golang.CommClause, p any) java.J { cc = &c cc.Comm = receiveValue(q, cc.Comm, func(e java.Statement) any { return r.Visit(e, q) }) cc.Colon = receiveValue(q, cc.Colon, func(e java.Space) any { return receiveSpace(e, q) }) - // Body beforeBody := make([]any, len(cc.Body)) for i, s := range cc.Body { beforeBody[i] = s diff --git a/rewrite-go/pkg/rpc/go_sender.go b/rewrite-go/pkg/rpc/go_sender.go index 53d9197b142..4da130cf15b 100644 --- a/rewrite-go/pkg/rpc/go_sender.go +++ b/rewrite-go/pkg/rpc/go_sender.go @@ -62,8 +62,6 @@ func (s *GoSender) Visit(t java.Tree, p any) java.Tree { return s.GoVisitor.Visit(t, p) } -// --- G nodes --- - func (s *GoSender) VisitCompilationUnit(cu *golang.CompilationUnit, p any) java.J { q := p.(*SendQueue) q.GetAndSend(cu, func(v any) any { return v.(*golang.CompilationUnit).SourcePath }, nil) diff --git a/rewrite-go/pkg/rpc/gomod_codec.go b/rewrite-go/pkg/rpc/gomod_codec.go index f55c1de592e..91ea1ccc72d 100644 --- a/rewrite-go/pkg/rpc/gomod_codec.go +++ b/rewrite-go/pkg/rpc/gomod_codec.go @@ -44,8 +44,6 @@ func init() { RegisterFactory("org.openrewrite.golang.tree.GoMod$Value", func() any { return &golang.GoModValue{} }) } -// --- send --- - func sendGoMod(gm *golang.GoMod, q *SendQueue) { q.GetAndSend(gm, func(v any) any { return v.(*golang.GoMod).Ident.String() }, nil) q.GetAndSend(gm, func(v any) any { return v.(*golang.GoMod).Prefix }, @@ -122,8 +120,6 @@ func sendGoModValue(val *golang.GoModValue, q *SendQueue) { q.GetAndSend(val, func(v any) any { return v.(*golang.GoModValue).Text }, nil) } -// --- receive --- - func receiveGoMod(gm *golang.GoMod, q *ReceiveQueue) *golang.GoMod { gm.Ident = recvGoModID(q, gm.Ident) gm.Prefix = recvGoModSpace(q, gm.Prefix) @@ -222,8 +218,6 @@ func recvGoModValue(baseline any, q *ReceiveQueue) any { return v } -// --- shared helpers --- - func recvGoModID(q *ReceiveQueue, before uuid.UUID) uuid.UUID { idStr := receiveScalar[string](q, before.String()) if idStr != "" { diff --git a/rewrite-go/pkg/rpc/java_receiver.go b/rewrite-go/pkg/rpc/java_receiver.go index 5cf647266e6..e7c7ab2a14c 100644 --- a/rewrite-go/pkg/rpc/java_receiver.go +++ b/rewrite-go/pkg/rpc/java_receiver.go @@ -116,8 +116,6 @@ func (r *JavaReceiver) receiveType(before java.JavaType, q *ReceiveQueue) java.J return result.(java.JavaType) } -// --- J nodes --- - func (r *JavaReceiver) VisitIdentifier(id *java.Identifier, p any) java.J { q := p.(*ReceiveQueue) c := *id // shallow copy to avoid mutating remoteObjects baseline diff --git a/rewrite-go/pkg/rpc/java_sender.go b/rewrite-go/pkg/rpc/java_sender.go index 823f5784578..b51f3bcbff4 100644 --- a/rewrite-go/pkg/rpc/java_sender.go +++ b/rewrite-go/pkg/rpc/java_sender.go @@ -81,8 +81,6 @@ func (s *JavaSender) visitType(t java.JavaType, q *SendQueue) { s.typeSender.Visit(t, q) } -// --- J nodes --- - func (s *JavaSender) VisitIdentifier(id *java.Identifier, p any) java.J { q := p.(*SendQueue) // annotations (list) diff --git a/rewrite-go/pkg/rpc/java_type_receiver.go b/rewrite-go/pkg/rpc/java_type_receiver.go index 0df990dc284..d380d4a2aea 100644 --- a/rewrite-go/pkg/rpc/java_type_receiver.go +++ b/rewrite-go/pkg/rpc/java_type_receiver.go @@ -21,14 +21,12 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/visitor" ) -// JavaTypeReceiver deserializes JavaType objects from the receive queue. // Field ordering MUST match JavaTypeReceiver.java exactly. // Embeds JavaTypeVisitor for dispatch; override methods deserialize each type. type JavaTypeReceiver struct { visitor.JavaTypeVisitor } -// NewJavaTypeReceiver creates a JavaTypeReceiver with virtual dispatch wired. func NewJavaTypeReceiver() *JavaTypeReceiver { r := &JavaTypeReceiver{} r.Self = r // wire virtual dispatch diff --git a/rewrite-go/pkg/rpc/java_type_sender.go b/rewrite-go/pkg/rpc/java_type_sender.go index e76369c3009..7df4f25de81 100644 --- a/rewrite-go/pkg/rpc/java_type_sender.go +++ b/rewrite-go/pkg/rpc/java_type_sender.go @@ -23,21 +23,18 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/visitor" ) -// JavaTypeSender serializes JavaType objects into the send queue. // Field ordering MUST match JavaTypeSender.java exactly. // Embeds JavaTypeVisitor for dispatch; override methods serialize each type. type JavaTypeSender struct { visitor.JavaTypeVisitor } -// NewJavaTypeSender creates a JavaTypeSender with virtual dispatch wired. func NewJavaTypeSender() *JavaTypeSender { s := &JavaTypeSender{} s.Self = s // wire virtual dispatch return s } -// VisitAnnotation matches JavaTypeSender.visitAnnotation func (s *JavaTypeSender) VisitAnnotation(a *java.JavaTypeAnnotation, p any) java.JavaType { q := p.(*SendQueue) q.GetAndSend(a, func(v any) any { return AsRef(v.(*java.JavaTypeAnnotation).Type) }, @@ -97,7 +94,6 @@ func (s *JavaTypeSender) visitAnnotationElementValue(v java.JavaTypeAnnotationEl } } -// VisitMultiCatch matches JavaTypeSender.visitMultiCatch func (s *JavaTypeSender) VisitMultiCatch(mc *java.JavaTypeMultiCatch, p any) java.JavaType { q := p.(*SendQueue) q.GetAndSendListAsRef(mc, @@ -107,7 +103,6 @@ func (s *JavaTypeSender) VisitMultiCatch(mc *java.JavaTypeMultiCatch, p any) jav return mc } -// VisitIntersection matches JavaTypeSender.visitIntersection func (s *JavaTypeSender) VisitIntersection(is *java.JavaTypeIntersection, p any) java.JavaType { q := p.(*SendQueue) q.GetAndSendListAsRef(is, @@ -117,7 +112,6 @@ func (s *JavaTypeSender) VisitIntersection(is *java.JavaTypeIntersection, p any) return is } -// VisitClass matches JavaTypeSender.visitClass field order exactly: // flagsBitMap, kind, fullyQualifiedName, typeParameters, supertype, owningClass, // annotations, interfaces, members, methods func (s *JavaTypeSender) VisitClass(c *java.JavaTypeClass, p any) java.JavaType { @@ -181,7 +175,6 @@ func (s *JavaTypeSender) visitClassFields(parent any, q *SendQueue) { func(v any) { s.Visit(v.(java.JavaType), q) }) } -// VisitParameterized matches JavaTypeSender.visitParameterized func (s *JavaTypeSender) VisitParameterized(pt *java.JavaTypeParameterized, p any) java.JavaType { q := p.(*SendQueue) q.GetAndSend(pt, func(v any) any { return AsRef(v.(*java.JavaTypeParameterized).Type) }, @@ -193,7 +186,6 @@ func (s *JavaTypeSender) VisitParameterized(pt *java.JavaTypeParameterized, p an return pt } -// VisitGenericTypeVariable matches JavaTypeSender.visitGenericTypeVariable func (s *JavaTypeSender) VisitGenericTypeVariable(g *java.JavaTypeGenericTypeVariable, p any) java.JavaType { q := p.(*SendQueue) q.GetAndSend(g, func(v any) any { return v.(*java.JavaTypeGenericTypeVariable).Name }, nil) @@ -205,7 +197,6 @@ func (s *JavaTypeSender) VisitGenericTypeVariable(g *java.JavaTypeGenericTypeVar return g } -// VisitArray matches JavaTypeSender.visitArray func (s *JavaTypeSender) VisitArray(a *java.JavaTypeArray, p any) java.JavaType { q := p.(*SendQueue) q.GetAndSend(a, func(v any) any { return AsRef(v.(*java.JavaTypeArray).ElemType) }, @@ -217,14 +208,12 @@ func (s *JavaTypeSender) VisitArray(a *java.JavaTypeArray, p any) java.JavaType return a } -// VisitPrimitive matches JavaTypeSender.visitPrimitive func (s *JavaTypeSender) VisitPrimitive(pr *java.JavaTypePrimitive, p any) java.JavaType { q := p.(*SendQueue) q.GetAndSend(pr, func(v any) any { return v.(*java.JavaTypePrimitive).Keyword }, nil) return pr } -// VisitMethod matches JavaTypeSender.visitMethod field order exactly: // declaringType, name, flagsBitMap, returnType, parameterNames, parameterTypes, // thrownExceptions, annotations, defaultValue, declaredFormalTypeNames func (s *JavaTypeSender) VisitMethod(m *java.JavaTypeMethod, p any) java.JavaType { @@ -262,7 +251,6 @@ func (s *JavaTypeSender) VisitMethod(m *java.JavaTypeMethod, p any) java.JavaTyp return m } -// VisitVariable matches JavaTypeSender.visitVariable func (s *JavaTypeSender) VisitVariable(v *java.JavaTypeVariable, p any) java.JavaType { q := p.(*SendQueue) q.GetAndSend(v, func(x any) any { return x.(*java.JavaTypeVariable).Name }, nil) @@ -277,8 +265,6 @@ func (s *JavaTypeSender) VisitVariable(v *java.JavaTypeVariable, p any) java.Jav return v } -// Helper functions to convert typed slices to []any - func javaTypeSlice(types []java.JavaType) []any { if types == nil { return nil diff --git a/rewrite-go/pkg/rpc/padding_rpc.go b/rewrite-go/pkg/rpc/padding_rpc.go index dfbee3a5fcf..29b1bdf3620 100644 --- a/rewrite-go/pkg/rpc/padding_rpc.go +++ b/rewrite-go/pkg/rpc/padding_rpc.go @@ -37,7 +37,6 @@ func sendRightPadded(s Sender, rp any, q *SendQueue) { // After space q.GetAndSend(rp, func(v any) any { return rightPaddedAfter(v) }, func(v any) { sendSpace(v.(java.Space), q) }) - // Markers q.GetAndSend(rp, func(v any) any { return rightPaddedMarkers(v) }, func(v any) { SendMarkersCodec(v.(java.Markers), q) }) } @@ -51,7 +50,6 @@ func sendRightPaddedBool(elem bool, after java.Space, markers java.Markers, q *S q.Put(RpcObjectData{State: Add, Value: elem}) // After: Space q.Send(after, nil, func(v any) { sendSpace(v.(java.Space), q) }) - // Markers q.Send(markers, nil, func(v any) { SendMarkersCodec(v.(java.Markers), q) }) } @@ -74,7 +72,6 @@ func sendLeftPadded(s Sender, lp any, q *SendQueue) { // Primitives (strings, enums, bools) are sent as raw values with nil onChange q.GetAndSend(lp, func(v any) any { return leftPaddedElement(v) }, nil) } - // Markers q.GetAndSend(lp, func(v any) any { return leftPaddedMarkers(v) }, func(v any) { SendMarkersCodec(v.(java.Markers), q) }) } @@ -90,14 +87,11 @@ func sendContainer(s Sender, c any, q *SendQueue) { func(v any) []any { return containerElements(v) }, func(v any) any { return containerElementID(v) }, func(v any) { sendRightPadded(s, v, q) }) - // Markers q.GetAndSend(c, func(v any) any { return containerMarkers(v) }, func(v any) { SendMarkersCodec(v.(java.Markers), q) }) } -// receiveRightPadded deserializes a RightPadded element. func receiveRightPadded(r Receiver, q *ReceiveQueue, before any) any { - // Element elem := q.Receive(rightPaddedElement(before), func(v any) any { if _, ok := v.(java.J); ok { return r.Visit(v.(java.Tree), q) @@ -108,7 +102,6 @@ func receiveRightPadded(r Receiver, q *ReceiveQueue, before any) any { afterSpace := q.Receive(rightPaddedAfter(before), func(v any) any { return receiveSpace(v.(java.Space), q) }) - // Markers markers := q.Receive(rightPaddedMarkers(before), func(v any) any { return receiveMarkersCodec(q, v.(java.Markers)) }) diff --git a/rewrite-go/pkg/rpc/receive_queue.go b/rewrite-go/pkg/rpc/receive_queue.go index bae003c662a..0a1ba0d344a 100644 --- a/rewrite-go/pkg/rpc/receive_queue.go +++ b/rewrite-go/pkg/rpc/receive_queue.go @@ -26,14 +26,12 @@ import ( var defaultReceiver = NewGoReceiver() -// ReceiveQueue deserializes RpcObjectData messages from the RPC channel. type ReceiveQueue struct { batch []RpcObjectData refs map[int]any pull func() []RpcObjectData } -// NewReceiveQueue creates a new ReceiveQueue. func NewReceiveQueue(refs map[int]any, pull func() []RpcObjectData) *ReceiveQueue { return &ReceiveQueue{ refs: refs, @@ -47,7 +45,6 @@ func (q *ReceiveQueue) PeekBatch() []RpcObjectData { return q.batch } -// Take returns the next message from the queue, pulling a new batch if needed. func (q *ReceiveQueue) Take() RpcObjectData { if len(q.batch) == 0 { q.batch = q.pull() @@ -140,7 +137,6 @@ func (q *ReceiveQueue) Receive(before any, onChange func(any) any) any { } } -// ReceiveAndGet reads a value and applies a mapping function for ADD/CHANGE. func (q *ReceiveQueue) ReceiveAndGet(before any, mapping func(any) any) any { after := q.Receive(before, nil) if after != nil && after != before { @@ -189,7 +185,6 @@ func receiveScalar[T any](q *ReceiveQueue, before T) T { return convertTo[T](result) } -// convertTo converts a value to the desired type, handling JSON number conversions. func convertTo[T any](v any) T { if t, ok := v.(T); ok { return t @@ -212,7 +207,6 @@ func convertTo[T any](v any) T { return v.(T) } -// ReceiveList reads a list from the queue with position-based tracking. func (q *ReceiveQueue) ReceiveList(before []any, onChange func(any) any) []any { msg := q.Take() @@ -253,7 +247,6 @@ func (q *ReceiveQueue) ReceiveList(before []any, onChange func(any) any) []any { } } -// toInt converts a value to int, handling both int and float64 (from JSON). func toInt(v any) int { switch n := v.(type) { case int: @@ -270,7 +263,6 @@ func toInt(v any) int { // Factory registry for creating empty instances by Java class name. var factories = map[string]func() any{} -// RegisterFactory registers a factory for creating instances of a Java class. func RegisterFactory(javaClassName string, factory func() any) { factories[javaClassName] = factory } diff --git a/rewrite-go/pkg/rpc/reference.go b/rewrite-go/pkg/rpc/reference.go index 41525ae0f2b..032649730d2 100644 --- a/rewrite-go/pkg/rpc/reference.go +++ b/rewrite-go/pkg/rpc/reference.go @@ -18,12 +18,10 @@ package rpc import "reflect" -// Reference wraps a value to indicate it should be ref-tracked during RPC serialization. type Reference struct { Value any } -// AsRef wraps a value in a Reference for ref tracking. // Returns nil if the value is nil (including typed nil pointers/interfaces). func AsRef(v any) any { if isNilValue(v) { @@ -32,7 +30,6 @@ func AsRef(v any) any { return &Reference{Value: v} } -// isNilValue checks if a value is nil, handling both untyped nil and typed nil pointers/interfaces. func isNilValue(v any) bool { if v == nil { return true @@ -63,7 +60,6 @@ func GetValueNonNull(maybeRef any) any { return v } -// IsRef reports whether the given value is a Reference. func IsRef(v any) bool { _, ok := v.(*Reference) return ok diff --git a/rewrite-go/pkg/rpc/rpc_object_data.go b/rewrite-go/pkg/rpc/rpc_object_data.go index fdf6aa740dc..cafa4a2b11c 100644 --- a/rewrite-go/pkg/rpc/rpc_object_data.go +++ b/rewrite-go/pkg/rpc/rpc_object_data.go @@ -18,7 +18,6 @@ package rpc import "encoding/json" -// State represents the state of an RPC object data message. type State int const ( @@ -57,7 +56,6 @@ type RpcObjectData struct { Ref *int `json:"ref,omitempty"` } -// MarshalJSON implements custom JSON marshaling for RpcObjectData. func (d RpcObjectData) MarshalJSON() ([]byte, error) { type Alias struct { State string `json:"state"` @@ -73,7 +71,6 @@ func (d RpcObjectData) MarshalJSON() ([]byte, error) { }) } -// ParseObjectData converts a JSON-decoded map to an RpcObjectData. func ParseObjectData(m map[string]any) RpcObjectData { d := RpcObjectData{} if s, ok := m["state"].(string); ok { diff --git a/rewrite-go/pkg/rpc/send_queue.go b/rewrite-go/pkg/rpc/send_queue.go index 9344e02ac97..a41b8f4b73a 100644 --- a/rewrite-go/pkg/rpc/send_queue.go +++ b/rewrite-go/pkg/rpc/send_queue.go @@ -24,7 +24,6 @@ import ( var defaultSender = NewGoSender() -// SendQueue serializes objects into RpcObjectData messages for RPC transmission. // It tracks refs for deduplication and maintains a "before" state for delta encoding. type SendQueue struct { batchSize int @@ -34,7 +33,6 @@ type SendQueue struct { before any } -// NewSendQueue creates a new SendQueue. func NewSendQueue(batchSize int, drain func([]RpcObjectData), refs map[uintptr]int) *SendQueue { return &SendQueue{ batchSize: batchSize, @@ -44,7 +42,6 @@ func NewSendQueue(batchSize int, drain func([]RpcObjectData), refs map[uintptr]i } } -// Put adds a message to the batch, flushing if the batch is full. func (q *SendQueue) Put(data RpcObjectData) { q.batch = append(q.batch, data) if len(q.batch) == q.batchSize { @@ -52,7 +49,6 @@ func (q *SendQueue) Put(data RpcObjectData) { } } -// Flush sends the accumulated batch and clears it. func (q *SendQueue) Flush() { if len(q.batch) == 0 { return @@ -63,7 +59,6 @@ func (q *SendQueue) Flush() { q.batch = q.batch[:0] } -// GetAndSend extracts a value from parent (and before), compares them, and sends the delta. func (q *SendQueue) GetAndSend(parent any, getter func(any) any, onChange func(any)) { after := getter(parent) var before any @@ -73,12 +68,10 @@ func (q *SendQueue) GetAndSend(parent any, getter func(any) any, onChange func(a q.Send(after, before, onChange) } -// GetAndSendList extracts a list from parent and sends it with position tracking. func (q *SendQueue) GetAndSendList(parent any, getter func(any) []any, id func(any) any, onChange func(any)) { q.getAndSendList(parent, getter, id, onChange, false) } -// GetAndSendListAsRef is like GetAndSendList but wraps items in ref tracking. func (q *SendQueue) GetAndSendListAsRef(parent any, getter func(any) []any, id func(any) any, onChange func(any)) { q.getAndSendList(parent, getter, id, onChange, true) } @@ -95,7 +88,6 @@ func (q *SendQueue) getAndSendList(parent any, getter func(any) []any, id func(a q.sendList(after, before, id, onChange, asRef) } -// Send compares after and before values and emits the appropriate state message. func (q *SendQueue) Send(after, before any, onChange func(any)) { afterVal := GetValue(after) beforeVal := GetValue(before) @@ -240,7 +232,6 @@ func (q *SendQueue) doChange(after, before any, onChange func(any)) { } } -// ptrKey returns a uintptr for use as a map key, based on pointer identity. func ptrKey(v any) uintptr { if v == nil { return 0 @@ -253,7 +244,6 @@ func ptrKey(v any) uintptr { return 0 } -// sameIdentity checks if two values are the same object (pointer identity). func sameIdentity(a, b any) bool { aNil := isNilValue(a) bNil := isNilValue(b) @@ -281,7 +271,6 @@ func sameIdentity(a, b any) bool { return reflect.DeepEqual(a, b) } -// sameType checks if two values have the same concrete type. func sameType(a, b any) bool { if isNilValue(a) || isNilValue(b) { return false @@ -289,7 +278,6 @@ func sameType(a, b any) bool { return reflect.TypeOf(a) == reflect.TypeOf(b) } -// anySlice converts a []any to an any (to distinguish nil slice from empty slice). func anySlice(s []any) any { if s == nil { return nil @@ -297,7 +285,6 @@ func anySlice(s []any) any { return s } -// getValueType returns the Java class name for a value, or nil if it's a primitive. func getValueType(v any) *string { if v == nil { return nil @@ -326,7 +313,6 @@ func getValueType(v any) *string { // valueTypeMap maps Go types to their Java class names for RPC wire format. var valueTypeMap = map[reflect.Type]string{} -// RegisterValueType registers a Go type -> Java class name mapping for RPC serialization. func RegisterValueType(goType reflect.Type, javaClassName string) { valueTypeMap[goType] = javaClassName } diff --git a/rewrite-go/pkg/rpc/space_rpc.go b/rewrite-go/pkg/rpc/space_rpc.go index 0d6e981eca3..ac5141b5201 100644 --- a/rewrite-go/pkg/rpc/space_rpc.go +++ b/rewrite-go/pkg/rpc/space_rpc.go @@ -22,7 +22,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/tree/java" ) -// nilableString converts a *string to an any, returning nil if the pointer is nil. func nilableString(s *string) any { if s == nil { return nil @@ -41,10 +40,8 @@ func emptyAsNil(s string) any { return s } -// sendSpace serializes a Space to the send queue. // Matches JavaSender.visitSpace field order: comments (list), whitespace. func sendSpace(s java.Space, q *SendQueue) { - // Comments list: id = text + suffix q.GetAndSendList(s, func(v any) []any { sp := v.(java.Space) @@ -67,17 +64,13 @@ func sendSpace(s java.Space, q *SendQueue) { q.GetAndSend(c, func(x any) any { return x.(java.Comment).Multiline }, nil) q.GetAndSend(c, func(x any) any { return x.(java.Comment).Text }, nil) q.GetAndSend(c, func(x any) any { return x.(java.Comment).Suffix }, nil) - // Markers - use codec callback to match Java's Markers codec behavior q.GetAndSend(c, func(x any) any { return x.(java.Comment).Markers }, func(v any) { SendMarkersCodec(v.(java.Markers), q) }) }) - // Whitespace q.GetAndSend(s, func(v any) any { return v.(java.Space).Whitespace }, nil) } -// receiveSpace deserializes a Space from the receive queue. func receiveSpace(before java.Space, q *ReceiveQueue) java.Space { - // Comments list commentsAny := make([]any, len(before.Comments)) for i, c := range before.Comments { commentsAny[i] = c @@ -112,10 +105,8 @@ func receiveSpace(before java.Space, q *ReceiveQueue) java.Space { return java.Space{Comments: comments, Whitespace: whitespace} } -// SendMarkersCodec serializes Markers fields like Java's Markers.rpcSend codec. // Sends: ID (uuid string), then marker entries list as ref. func SendMarkersCodec(m java.Markers, q *SendQueue) { - // ID q.GetAndSend(m, func(v any) any { return v.(java.Markers).ID.String() }, nil) // Entries list (as ref) — matches Java's Markers.rpcSend protocol. q.GetAndSendListAsRef(m, @@ -295,9 +286,7 @@ func sendMarkerCodecFields(v any, q *SendQueue) { } } -// receiveMarkersCodec deserializes Markers fields like Java's Markers.rpcReceive codec. func receiveMarkersCodec(q *ReceiveQueue, before java.Markers) java.Markers { - // ID idStr := receiveScalar[string](q, before.ID.String()) id := before.ID if idStr != "" && idStr != before.ID.String() { diff --git a/rewrite-go/pkg/rpc/value_types.go b/rewrite-go/pkg/rpc/value_types.go index f6dead60c91..12ec53ecc64 100644 --- a/rewrite-go/pkg/rpc/value_types.go +++ b/rewrite-go/pkg/rpc/value_types.go @@ -97,8 +97,6 @@ func init() { RegisterValueType(reflect.TypeOf((*java.TypeCast)(nil)), "org.openrewrite.java.tree.J$TypeCast") RegisterValueType(reflect.TypeOf((*java.ControlParentheses)(nil)), "org.openrewrite.java.tree.J$ControlParentheses") RegisterValueType(reflect.TypeOf((*java.Import)(nil)), "org.openrewrite.java.tree.J$Import") - - // ParseError RegisterValueType(reflect.TypeOf((*java.ParseError)(nil)), "org.openrewrite.tree.ParseError") // Non-tree types that Java needs valueType for @@ -220,8 +218,6 @@ func init() { RegisterFactory("org.openrewrite.java.tree.J$TypeCast", func() any { return &java.TypeCast{ID: uuid.New()} }) RegisterFactory("org.openrewrite.java.tree.J$ControlParentheses", func() any { return &java.ControlParentheses{ID: uuid.New()} }) RegisterFactory("org.openrewrite.java.tree.J$Import", func() any { return &java.Import{ID: uuid.New()} }) - - // ParseError RegisterFactory("org.openrewrite.tree.ParseError", func() any { return &java.ParseError{Ident: uuid.New()} }) RegisterFactory("org.openrewrite.ParseExceptionResult", func() any { return java.ParseExceptionResult{} }) diff --git a/rewrite-go/pkg/template/capture.go b/rewrite-go/pkg/template/capture.go index 5482e6afc9a..22f35e73dbb 100644 --- a/rewrite-go/pkg/template/capture.go +++ b/rewrite-go/pkg/template/capture.go @@ -28,7 +28,6 @@ const ( CaptureStatement // statement position ) -// Capture represents a named placeholder in a pattern or template. // It defines what kind of AST subtree can be matched and optionally // constrains the match by Go type name. type Capture struct { @@ -40,51 +39,38 @@ type Capture struct { maxCount int // maximum items for variadic (-1 = unlimited) } -// Name returns the capture's name. func (c *Capture) Name() string { return c.name } -// Kind returns the capture's syntactic kind. func (c *Capture) Kind() CaptureKind { return c.kind } -// TypeName returns the optional Go type constraint. func (c *Capture) TypeName() string { return c.typeName } -// IsVariadic returns true if this capture matches zero or more items. func (c *Capture) IsVariadic() bool { return c.variadic } -// MinCount returns the minimum number of items for variadic captures. func (c *Capture) MinCount() int { return c.minCount } -// MaxCount returns the maximum number of items for variadic captures (-1 = unlimited). func (c *Capture) MaxCount() int { return c.maxCount } -// Placeholder returns the placeholder identifier used in scaffold source code. func (c *Capture) Placeholder() string { return ToPlaceholder(c.name) } -// String returns the placeholder identifier, making Capture usable with fmt.Sprintf. func (c *Capture) String() string { return c.Placeholder() } -// Expr creates a capture for an expression position. func Expr(name string) *Capture { return &Capture{name: name, kind: CaptureExpression, maxCount: -1} } -// Stmt creates a capture for a statement position. func Stmt(name string) *Capture { return &Capture{name: name, kind: CaptureStatement, maxCount: -1} } -// TypeExpr creates a capture for a type position. func TypeExpr(name string) *Capture { return &Capture{name: name, kind: CaptureType, maxCount: -1} } -// Ident creates a capture for an identifier/name position. func Ident(name string) *Capture { return &Capture{name: name, kind: CaptureName, maxCount: -1} } -// WithType returns a copy of the capture with a type constraint. // The type name is used in the scaffold preamble for type-attributed matching. func (c *Capture) WithType(typeName string) *Capture { cp := *c @@ -92,7 +78,6 @@ func (c *Capture) WithType(typeName string) *Capture { return &cp } -// Variadic returns a copy of the capture configured to match multiple items. // min and max set bounds (-1 for max means unlimited). func (c *Capture) Variadic(min, max int) *Capture { cp := *c @@ -102,7 +87,6 @@ func (c *Capture) Variadic(min, max int) *Capture { return &cp } -// captureMap builds a name -> Capture lookup from a slice of captures. func captureMap(captures []*Capture) map[string]*Capture { m := make(map[string]*Capture, len(captures)) for _, c := range captures { diff --git a/rewrite-go/pkg/template/comparator.go b/rewrite-go/pkg/template/comparator.go index 9d90c924243..0825bc7d077 100644 --- a/rewrite-go/pkg/template/comparator.go +++ b/rewrite-go/pkg/template/comparator.go @@ -49,7 +49,6 @@ func (c *patternComparator) match(pattern, candidate java.J) *MatchResult { return nil } -// matchNode compares two nodes structurally, handling placeholder binding. func (c *patternComparator) matchNode(pattern, candidate java.J) bool { if pattern == nil && candidate == nil { return true @@ -380,8 +379,6 @@ func (c *patternComparator) matchProperties(pattern, candidate java.J) bool { } } -// --- Helper methods for optional and list comparisons --- - func (c *patternComparator) matchOptionalNode(pattern, candidate java.J) bool { if pattern == nil && candidate == nil { return true diff --git a/rewrite-go/pkg/template/go_pattern.go b/rewrite-go/pkg/template/go_pattern.go index f1d5d26496c..5afdfb5a957 100644 --- a/rewrite-go/pkg/template/go_pattern.go +++ b/rewrite-go/pkg/template/go_pattern.go @@ -64,7 +64,6 @@ func (p *GoPattern) Match(candidate java.J, cursor *visitor.Cursor) *MatchResult return cmp.match(patternTree, candidate) } -// Matches returns true if this pattern matches the candidate. func (p *GoPattern) Matches(candidate java.J, cursor *visitor.Cursor) bool { return p.Match(candidate, cursor) != nil } @@ -77,9 +76,6 @@ func (p *GoPattern) getTree() (java.J, error) { return p.cached, p.parseErr } -// --- Pattern builder --- - -// PatternBuilder constructs a GoPattern with fluent configuration. type PatternBuilder struct { code string captures []*Capture @@ -87,34 +83,28 @@ type PatternBuilder struct { kind ScaffoldKind } -// Expression creates a PatternBuilder for matching an expression. func Expression(code string) *PatternBuilder { return &PatternBuilder{code: code, kind: ScaffoldExpression} } -// Statement creates a PatternBuilder for matching a statement. func StatementPattern(code string) *PatternBuilder { return &PatternBuilder{code: code, kind: ScaffoldStatement} } -// TopLevel creates a PatternBuilder for matching a top-level declaration. func TopLevel(code string) *PatternBuilder { return &PatternBuilder{code: code, kind: ScaffoldTopLevel} } -// Captures adds captures to the builder. func (b *PatternBuilder) Captures(caps ...*Capture) *PatternBuilder { b.captures = append(b.captures, caps...) return b } -// Imports adds required imports for the pattern code. func (b *PatternBuilder) Imports(pkgs ...string) *PatternBuilder { b.imports = append(b.imports, pkgs...) return b } -// Build creates the GoPattern. func (b *PatternBuilder) Build() *GoPattern { return &GoPattern{ code: b.code, diff --git a/rewrite-go/pkg/template/go_template.go b/rewrite-go/pkg/template/go_template.go index a27d7710bda..094c022ee86 100644 --- a/rewrite-go/pkg/template/go_template.go +++ b/rewrite-go/pkg/template/go_template.go @@ -67,9 +67,6 @@ func (t *GoTemplate) getTree() (java.J, error) { return t.cached, t.parseErr } -// --- Template builder --- - -// TemplateBuilder constructs a GoTemplate with fluent configuration. type TemplateBuilder struct { code string captures []*Capture @@ -77,35 +74,29 @@ type TemplateBuilder struct { kind ScaffoldKind } -// ExpressionTemplate creates a TemplateBuilder for producing an expression. func ExpressionTemplate(code string) *TemplateBuilder { return &TemplateBuilder{code: code, kind: ScaffoldExpression} } -// StatementTemplate creates a TemplateBuilder for producing a statement. func StatementTemplate(code string) *TemplateBuilder { return &TemplateBuilder{code: code, kind: ScaffoldStatement} } -// TopLevelTemplate creates a TemplateBuilder for producing a top-level declaration. func TopLevelTemplate(code string) *TemplateBuilder { return &TemplateBuilder{code: code, kind: ScaffoldTopLevel} } -// Captures adds captures to the builder. func (b *TemplateBuilder) Captures(caps ...*Capture) *TemplateBuilder { b.captures = append(b.captures, caps...) return b } -// Imports adds imports to the synthetic source used to parse the template. // It does not edit imports in the source file being rewritten. func (b *TemplateBuilder) Imports(pkgs ...string) *TemplateBuilder { b.imports = append(b.imports, pkgs...) return b } -// Build creates the GoTemplate. func (b *TemplateBuilder) Build() *GoTemplate { return &GoTemplate{ code: b.code, @@ -123,7 +114,6 @@ func Rewrite(before *GoPattern, after *GoTemplate) *RewriteVisitor { return v } -// RewriteVisitor applies a pattern match + template replacement on every node. type RewriteVisitor struct { visitor.GoVisitor before *GoPattern diff --git a/rewrite-go/pkg/template/match_result.go b/rewrite-go/pkg/template/match_result.go index 4fd6249c98b..b6e79ead524 100644 --- a/rewrite-go/pkg/template/match_result.go +++ b/rewrite-go/pkg/template/match_result.go @@ -18,12 +18,10 @@ package template import "github.com/openrewrite/rewrite/rewrite-go/pkg/tree/java" -// MatchResult holds the captured AST nodes from a successful pattern match. type MatchResult struct { bindings map[string]any // single: java.J, variadic: []java.J } -// NewMatchResult creates a MatchResult from binding pairs. func NewMatchResult() *MatchResult { return &MatchResult{bindings: make(map[string]any)} } @@ -38,13 +36,11 @@ func (m *MatchResult) bindList(name string, values []java.J) { m.bindings[name] = values } -// Has returns true if a binding exists for the given capture name. func (m *MatchResult) Has(name string) bool { _, ok := m.bindings[name] return ok } -// Get returns the single captured node for the given name, or nil if not bound. func (m *MatchResult) Get(name string) java.J { v, ok := m.bindings[name] if !ok { @@ -56,7 +52,6 @@ func (m *MatchResult) Get(name string) java.J { return nil } -// GetList returns the variadic captured nodes for the given name. func (m *MatchResult) GetList(name string) []java.J { v, ok := m.bindings[name] if !ok { @@ -72,7 +67,6 @@ func (m *MatchResult) GetList(name string) []java.J { return nil } -// GetCapture returns the captured node for the given Capture, or nil. func (m *MatchResult) GetCapture(c *Capture) java.J { return m.Get(c.Name()) } diff --git a/rewrite-go/pkg/template/placeholder.go b/rewrite-go/pkg/template/placeholder.go index 4c7d91ef8fc..08e131d5b0f 100644 --- a/rewrite-go/pkg/template/placeholder.go +++ b/rewrite-go/pkg/template/placeholder.go @@ -40,7 +40,6 @@ func FromPlaceholder(identifier string) (string, bool) { return name, true } -// IsPlaceholder returns true if the identifier is a template placeholder. func IsPlaceholder(identifier string) bool { return strings.HasPrefix(identifier, placeholderPrefix) && strings.HasSuffix(identifier, placeholderSuffix) && diff --git a/rewrite-go/pkg/template/substitution.go b/rewrite-go/pkg/template/substitution.go index a5de781dacc..0f1c837cb27 100644 --- a/rewrite-go/pkg/template/substitution.go +++ b/rewrite-go/pkg/template/substitution.go @@ -63,7 +63,6 @@ func substitute(templateTree java.J, values *MatchResult) java.J { return result.(java.J) } -// setPrefix creates a copy of the node with the given prefix Space. func setPrefix(j java.J, prefix java.Space) java.J { switch n := j.(type) { case *java.Identifier: diff --git a/rewrite-go/pkg/template/template_recipe.go b/rewrite-go/pkg/template/template_recipe.go index 7fa84a34579..1553f226e2f 100644 --- a/rewrite-go/pkg/template/template_recipe.go +++ b/rewrite-go/pkg/template/template_recipe.go @@ -26,12 +26,8 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/visitor" ) -// --- Functional builder API --- - -// RecipeOption configures a template recipe via NewRecipe. type RecipeOption func(*templateRecipeConfig) -// BeforeOption configures a single before-pattern. type BeforeOption func(*beforeSpec) type beforeSpec struct { @@ -62,22 +58,18 @@ type templateRecipeConfig struct { kind *ScaffoldKind // global override } -// RecipeName sets the fully qualified recipe name. func RecipeName(name string) RecipeOption { return func(c *templateRecipeConfig) { c.name = name } } -// WithDisplayName sets the human-readable display name. func WithDisplayName(name string) RecipeOption { return func(c *templateRecipeConfig) { c.displayName = name } } -// WithDescription sets the recipe description. func WithDescription(desc string) RecipeOption { return func(c *templateRecipeConfig) { c.description = desc } } -// WithTags sets categorization tags. func WithTags(tags ...string) RecipeOption { return func(c *templateRecipeConfig) { c.tags = tags } } @@ -94,7 +86,6 @@ func WithBefore(code string, opts ...BeforeOption) RecipeOption { } } -// WithAfter sets the after-template code. func WithAfter(code string, opts ...BeforeOption) RecipeOption { return func(c *templateRecipeConfig) { c.afterCode = code @@ -154,8 +145,6 @@ func SourceImport(path string, alias *string) BeforeOption { } } -// NewRecipe creates a recipe.Recipe from declarative before/after templates. -// // Example: // // s := template.Expr("s") @@ -177,14 +166,12 @@ func NewRecipe(opts ...RecipeOption) recipe.Recipe { func buildRecipe(cfg *templateRecipeConfig) recipe.Recipe { caps := cfg.captures - // Build before patterns var befores []*GoPattern for _, bs := range cfg.befores { kind := resolveKind(bs.kind, cfg.kind, bs.code) befores = append(befores, buildPattern(bs.code, caps, bs.imports, kind)) } - // Build after template afterKind := resolveKind(cfg.afterKind, cfg.kind, cfg.afterCode) after := buildTemplate(cfg.afterCode, caps, cfg.afterImports, afterKind) @@ -250,8 +237,6 @@ func detectScaffoldKind(code string) ScaffoldKind { return ScaffoldExpression } -// --- Multi-before visitor --- - // templateRecipeVisitor tries each before pattern in order; first match wins. type templateRecipeVisitor struct { visitor.GoVisitor @@ -296,8 +281,6 @@ func (v *templateRecipeVisitor) Visit(t java.Tree, p any) java.Tree { return result } -// --- Built recipe (returned by NewRecipe) --- - type builtTemplateRecipe struct { name string displayName string @@ -319,8 +302,6 @@ func (r *builtTemplateRecipe) Maintainers() []recipe.Maintainer { ret func (r *builtTemplateRecipe) Contributors() []recipe.Contributor { return nil } func (r *builtTemplateRecipe) Examples() []recipe.Example { return nil } -// --- Embeddable TemplateRecipe struct --- - // TemplateRecipe is an embeddable base type for struct-based template recipes. // Embed it and call Init() to wire up the before/after patterns. // @@ -366,7 +347,6 @@ func (tr *TemplateRecipe) InitTemplate(opts ...RecipeOption) { tr.editor = newTemplateRecipeVisitor(befores, after, cfg.sourceImports) } -// Editor returns the auto-generated visitor. func (tr *TemplateRecipe) Editor() recipe.TreeVisitor { return tr.editor } diff --git a/rewrite-go/pkg/tree/golang/go.go b/rewrite-go/pkg/tree/golang/go.go index aac1e397dbe..7ce25f2282d 100644 --- a/rewrite-go/pkg/tree/golang/go.go +++ b/rewrite-go/pkg/tree/golang/go.go @@ -22,7 +22,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/tree/java" ) -// CompilationUnit represents a Go source file. type CompilationUnit struct { ID uuid.UUID Prefix java.Space @@ -76,7 +75,6 @@ func (n *CompilationUnit) WithEOF(eof java.Space) *CompilationUnit { return &c } -// Go represents a `go expr` statement (goroutine launch). type GoStmt struct { ID uuid.UUID Prefix java.Space @@ -100,7 +98,6 @@ func (n *GoStmt) WithMarkers(markers java.Markers) *GoStmt { return &c } -// Defer represents a `defer expr` statement. type Defer struct { ID uuid.UUID Prefix java.Space @@ -124,7 +121,6 @@ func (n *Defer) WithMarkers(markers java.Markers) *Defer { return &c } -// Send represents a channel send statement: `ch <- value`. type Send struct { ID uuid.UUID Prefix java.Space @@ -149,7 +145,6 @@ func (n *Send) WithMarkers(markers java.Markers) *Send { return &c } -// Goto represents a `goto label` statement. type Goto struct { ID uuid.UUID Prefix java.Space @@ -173,7 +168,6 @@ func (n *Goto) WithMarkers(markers java.Markers) *Goto { return &c } -// Fallthrough represents a `fallthrough` statement in a switch case. type Fallthrough struct { ID uuid.UUID Prefix java.Space @@ -196,7 +190,6 @@ func (n *Fallthrough) WithMarkers(markers java.Markers) *Fallthrough { return &c } -// Composite represents a composite literal: `Type{elem1, elem2}`. type Composite struct { ID uuid.UUID Prefix java.Space @@ -221,7 +214,6 @@ func (n *Composite) WithMarkers(markers java.Markers) *Composite { return &c } -// KeyValue represents a `key: value` pair in composite literals. type KeyValue struct { ID uuid.UUID Prefix java.Space @@ -246,7 +238,6 @@ func (n *KeyValue) WithMarkers(markers java.Markers) *KeyValue { return &c } -// Slice represents a slice expression: `a[low:high]` or `a[low:high:max]`. type Slice struct { ID uuid.UUID Prefix java.Space @@ -303,7 +294,6 @@ func (n *ArrayType) WithMarkers(markers java.Markers) *ArrayType { return &c } -// MapType represents a map type expression: `map[K]V`. type MapType struct { ID uuid.UUID Prefix java.Space @@ -329,7 +319,6 @@ func (n *MapType) WithMarkers(markers java.Markers) *MapType { return &c } -// ChanDir represents the direction of a channel type. type ChanDir int const ( @@ -338,7 +327,6 @@ const ( ChanRecvOnly // <-chan T ) -// PointerType represents a pointer type expression: `*T`. type PointerType struct { ID uuid.UUID Prefix java.Space @@ -362,7 +350,6 @@ func (n *PointerType) WithMarkers(markers java.Markers) *PointerType { return &c } -// Channel represents a channel type expression: `chan T`, `chan<- T`, `<-chan T`. type Channel struct { ID uuid.UUID Prefix java.Space @@ -387,7 +374,6 @@ func (n *Channel) WithMarkers(markers java.Markers) *Channel { return &c } -// FuncType represents a function type expression: `func(int) string`. type FuncType struct { ID uuid.UUID Prefix java.Space @@ -412,7 +398,6 @@ func (n *FuncType) WithMarkers(markers java.Markers) *FuncType { return &c } -// StructType represents a struct type expression: `struct { fields }`. type StructType struct { ID uuid.UUID Prefix java.Space @@ -436,7 +421,6 @@ func (n *StructType) WithMarkers(markers java.Markers) *StructType { return &c } -// InterfaceType represents an interface type expression: `interface { methods }`. type InterfaceType struct { ID uuid.UUID Prefix java.Space @@ -460,7 +444,6 @@ func (n *InterfaceType) WithMarkers(markers java.Markers) *InterfaceType { return &c } -// TypeList represents a parenthesized list of return types: `(int, error)` or `(n int, err error)`. // Used for multiple (or single parenthesized) return values in function signatures. // Elements are VariableDeclarations, each with optional name and type. type TypeList struct { @@ -545,7 +528,6 @@ func (n *UnderlyingType) WithMarkers(markers java.Markers) *UnderlyingType { return &c } -// TypeDecl represents a `type Name Type` declaration. // Covers: `type Foo struct{...}`, `type Foo interface{...}`, `type Foo int`, `type Foo = Bar`. // For grouped declarations `type ( ... )`, Specs is non-nil and Name/Definition are unused. type TypeDecl struct { @@ -588,7 +570,6 @@ func (n *TypeDecl) WithTypeParameters(tps *java.TypeParameters) *TypeDecl { return &c } -// DeclKind is the keyword introducing a grouped declaration block. type DeclKind int const ( @@ -665,7 +646,6 @@ type ImportBlock struct { func (b ImportBlock) ID() uuid.UUID { return b.Ident } -// ChanDirMarker stores whitespace around the direction operator in a channel type. // For send channels (`chan <- T`), Before holds the space before `<-`. // For recv channels (`<- chan T`), Before holds the space before `chan`. type ChanDirMarker struct { @@ -675,7 +655,6 @@ type ChanDirMarker struct { func (c ChanDirMarker) ID() uuid.UUID { return c.Ident } -// MultiAssignment represents a multi-value assignment: `x, y = 1, 2` or `x, y := f()`. type MultiAssignment struct { ID uuid.UUID Prefix java.Space @@ -791,7 +770,6 @@ func (n *StatementWithInit) WithMarkers(markers java.Markers) *StatementWithInit return &c } -// CommClause represents a communication clause in a select statement. // `case <-ch:` or `case ch <- val:` or `case v := <-ch:` or `default:`. type CommClause struct { ID uuid.UUID @@ -818,7 +796,6 @@ func (n *CommClause) WithMarkers(markers java.Markers) *CommClause { return &c } -// StatementExpression wraps a Statement so it can appear in expression contexts. // Used for Go function literals which are parsed as MethodDeclaration (a Statement) // but can appear in return statements, assignments, and call arguments. type StatementExpression struct { @@ -881,7 +858,6 @@ const ( Receive // <- ) -// String returns the Java enum-constant name (Go.Unary.Type) for the wire. // Unlike java.UnaryOperator.String() these are faithful 1:1 mappings, so the // operator survives a Java round-trip without collapsing to "Not". func (op UnaryOperator) String() string { @@ -897,7 +873,6 @@ func (op UnaryOperator) String() string { } } -// ParseUnaryOperator converts a Go.Unary.Type enum name back to the operator. func ParseUnaryOperator(s string) UnaryOperator { switch s { case "AddressOf": @@ -911,7 +886,6 @@ func ParseUnaryOperator(s string) UnaryOperator { } } -// Unary represents a Go-specific prefix unary expression: `&x`, `*p`, `<-ch`. type Unary struct { ID uuid.UUID Prefix java.Space @@ -945,7 +919,6 @@ const ( BinAndNot BinaryOperator = iota + 1 // &^ ) -// String returns the Java enum-constant name (Go.Binary.Type) for the wire. func (op BinaryOperator) String() string { switch op { case BinAndNot: @@ -955,7 +928,6 @@ func (op BinaryOperator) String() string { } } -// ParseBinaryOperator converts a Go.Binary.Type enum name back to the operator. func ParseBinaryOperator(s string) BinaryOperator { switch s { case "AndNot": @@ -965,7 +937,6 @@ func ParseBinaryOperator(s string) BinaryOperator { } } -// Binary represents a Go-specific binary expression: `a &^ b`. type Binary struct { ID uuid.UUID Prefix java.Space @@ -999,7 +970,6 @@ const ( AssignAndNot AssignmentOperator = iota + 1 // &^= ) -// String returns the Java enum-constant name (Go.AssignmentOperation.Type). func (op AssignmentOperator) String() string { switch op { case AssignAndNot: @@ -1009,7 +979,6 @@ func (op AssignmentOperator) String() string { } } -// ParseAssignmentOperator converts a Go.AssignmentOperation.Type enum name back. func ParseAssignmentOperator(s string) AssignmentOperator { switch s { case "AndNot": @@ -1019,7 +988,6 @@ func ParseAssignmentOperator(s string) AssignmentOperator { } } -// AssignmentOperation represents a Go-specific compound assignment: `a &^= b`. type AssignmentOperation struct { ID uuid.UUID Prefix java.Space diff --git a/rewrite-go/pkg/tree/golang/go_resolution_result.go b/rewrite-go/pkg/tree/golang/go_resolution_result.go index f6dd545c0ba..dc324ae467e 100644 --- a/rewrite-go/pkg/tree/golang/go_resolution_result.go +++ b/rewrite-go/pkg/tree/golang/go_resolution_result.go @@ -38,7 +38,6 @@ type GoResolutionResult struct { func (m GoResolutionResult) ID() uuid.UUID { return m.Ident } -// FindRequire returns the require entry for a module, or nil. func (m GoResolutionResult) FindRequire(modulePath string) *GoRequire { for i := range m.Requires { if m.Requires[i].ModulePath == modulePath { @@ -48,7 +47,6 @@ func (m GoResolutionResult) FindRequire(modulePath string) *GoRequire { return nil } -// FindResolved returns the resolved dependency for a module, or nil. func (m GoResolutionResult) FindResolved(modulePath string) *GoResolvedDependency { for i := range m.ResolvedDependencies { if m.ResolvedDependencies[i].ModulePath == modulePath { @@ -58,7 +56,6 @@ func (m GoResolutionResult) FindResolved(modulePath string) *GoResolvedDependenc return nil } -// GoRequire is one entry in the go.mod `require` list. type GoRequire struct { ModulePath string Version string @@ -75,7 +72,6 @@ type GoReplace struct { NewVersion string } -// GoExclude is one entry in the go.mod `exclude` list. type GoExclude struct { ModulePath string Version string @@ -88,7 +84,6 @@ type GoRetract struct { Rationale string // empty if no `// ...` comment } -// GoResolvedDependency is one entry from go.sum. type GoResolvedDependency struct { ModulePath string Version string @@ -96,8 +91,6 @@ type GoResolvedDependency struct { GoModHash string } -// NewGoResolutionResult creates a GoResolutionResult marker with a fresh UUID. -// // The directive slices are initialized to empty (non-nil) values. Go has no // way to declare a slice non-nullable at the type level, so this constructor is // the single chokepoint that guarantees it: a nil slice would be serialized by diff --git a/rewrite-go/pkg/tree/golang/markers.go b/rewrite-go/pkg/tree/golang/markers.go index 24e7ade2aeb..293adb817e4 100644 --- a/rewrite-go/pkg/tree/golang/markers.go +++ b/rewrite-go/pkg/tree/golang/markers.go @@ -42,12 +42,10 @@ type Semicolon struct { func (m Semicolon) ID() uuid.UUID { return m.Ident } -// NewSemicolon creates a Semicolon marker with a fresh UUID. func NewSemicolon() Semicolon { return Semicolon{Ident: uuid.New()} } -// NewGoProject creates a GoProject marker with a new UUID. func NewGoProject(projectName string) GoProject { return GoProject{Ident: uuid.New(), ProjectName: projectName} } diff --git a/rewrite-go/pkg/tree/java/j.go b/rewrite-go/pkg/tree/java/j.go index dc2db42a007..8479cc090d3 100644 --- a/rewrite-go/pkg/tree/java/j.go +++ b/rewrite-go/pkg/tree/java/j.go @@ -18,7 +18,6 @@ package java import "github.com/google/uuid" -// Identifier represents a name reference in source code. type Identifier struct { ID uuid.UUID Prefix Space @@ -66,7 +65,6 @@ func (n *Identifier) WithFieldType(ft *JavaTypeVariable) *Identifier { return &c } -// Literal represents a literal value (string, number, boolean, etc.). type Literal struct { ID uuid.UUID Prefix Space @@ -117,7 +115,6 @@ func (n *Literal) WithSource(source string) *Literal { return &c } -// BinaryOperator represents the operator in a binary expression. type BinaryOperator int const ( @@ -144,7 +141,6 @@ const ( AndNot // Go-specific: &^ ) -// String returns the Java enum name for this BinaryOperator. func (op BinaryOperator) String() string { switch op { case Add: @@ -190,7 +186,6 @@ func (op BinaryOperator) String() string { } } -// ParseBinaryOperator converts a Java enum name to a BinaryOperator. func ParseBinaryOperator(s string) BinaryOperator { switch s { case "Addition": @@ -234,7 +229,6 @@ func ParseBinaryOperator(s string) BinaryOperator { } } -// Binary represents a binary expression like `a + b`. type Binary struct { ID uuid.UUID Prefix Space @@ -273,7 +267,6 @@ func (n *Binary) WithRight(right Expression) *Binary { return &c } -// Block represents a brace-delimited block of statements. type Block struct { ID uuid.UUID Prefix Space @@ -379,8 +372,6 @@ func (n *If) WithThen(then *Block) *If { return &c } -// Else represents an else clause of an if statement. -// This matches Java's J.If.Else for RPC wire format compatibility. type Else struct { ID uuid.UUID Prefix Space @@ -403,7 +394,6 @@ func (n *Else) WithMarkers(markers Markers) *Else { return &c } -// Assignment represents an assignment statement like `x = expr`. type Assignment struct { ID uuid.UUID Prefix Space @@ -436,7 +426,6 @@ func (n *Assignment) WithVariable(variable Expression) *Assignment { return &c } -// AssignmentOperation represents a compound assignment like `x += expr`. type AssignmentOperation struct { ID uuid.UUID Prefix Space @@ -463,7 +452,6 @@ const ( AndNotAssign // &^= (Go-specific) ) -// String returns the Java enum name for this AssignmentOperator. func (op AssignmentOperator) String() string { switch op { case AddAssign: @@ -493,7 +481,6 @@ func (op AssignmentOperator) String() string { } } -// ParseAssignmentOperator converts a Java enum name to an AssignmentOperator. func ParseAssignmentOperator(s string) AssignmentOperator { switch s { case "Addition": @@ -544,7 +531,6 @@ func (n *AssignmentOperation) WithVariable(variable Expression) *AssignmentOpera return &c } -// MethodDeclaration represents a function or method declaration. type MethodDeclaration struct { ID uuid.UUID Prefix Space @@ -689,7 +675,6 @@ func (n *ForLoop) WithBody(body *Block) *ForLoop { return &c } -// ForControl holds the init, condition, and update of a for loop. // When Init is non-nil, this is a 3-clause loop with semicolons; // Init.After and Condition.After capture whitespace around semicolons. // When Init is nil and Condition is non-nil, it's a condition-only loop (no semicolons). @@ -718,7 +703,6 @@ func (n *ForControl) WithMarkers(markers Markers) *ForControl { return &c } -// ForEachLoop represents a for-range loop: `for k, v := range expr { body }` type ForEachLoop struct { ID uuid.UUID Prefix Space @@ -815,7 +799,6 @@ func (n *Switch) WithBody(body *Block) *Switch { return &c } -// Case represents a case or default clause in a switch statement. type Case struct { ID uuid.UUID Prefix Space @@ -840,7 +823,6 @@ func (n *Case) WithMarkers(markers Markers) *Case { return &c } -// Break represents a break statement with optional label. type Break struct { ID uuid.UUID Prefix Space @@ -864,7 +846,6 @@ func (n *Break) WithMarkers(markers Markers) *Break { return &c } -// Continue represents a continue statement with optional label. type Continue struct { ID uuid.UUID Prefix Space @@ -888,7 +869,6 @@ func (n *Continue) WithMarkers(markers Markers) *Continue { return &c } -// Label represents a labeled statement: `label: stmt`. type Label struct { ID uuid.UUID Prefix Space @@ -913,7 +893,6 @@ func (n *Label) WithMarkers(markers Markers) *Label { return &c } -// Annotation represents annotation metadata attached to a declaration. // Mirrors org.openrewrite.java.tree.J.Annotation. // // Java has first-class `@Annotation(args)` syntax. Go has no `@`, but @@ -975,7 +954,6 @@ func (n *Annotation) WithArguments(arguments *Container[Expression]) *Annotation return &c } -// Empty represents an empty statement or expression placeholder. type Empty struct { ID uuid.UUID Prefix Space @@ -993,7 +971,6 @@ func (n *Empty) WithPrefix(prefix Space) *Empty { return &c } -// Unary represents a unary expression like `-x` or `!y`. type Unary struct { ID uuid.UUID Prefix Space @@ -1020,7 +997,6 @@ const ( Tilde // ~ (approximate type constraint, Go-specific) ) -// String returns the Java enum name for this UnaryOperator. func (op UnaryOperator) String() string { switch op { case Negate: @@ -1052,7 +1028,6 @@ func (op UnaryOperator) String() string { } } -// ParseUnaryOperator converts a Java enum name to a UnaryOperator. func ParseUnaryOperator(s string) UnaryOperator { switch s { case "PreIncrement": @@ -1111,7 +1086,6 @@ func (n *Unary) WithOperand(operand Expression) *Unary { return &c } -// FieldAccess represents a field or method access like `obj.Field`. type FieldAccess struct { ID uuid.UUID Prefix Space @@ -1143,7 +1117,6 @@ func (n *FieldAccess) WithTarget(target Expression) *FieldAccess { return &c } -// MethodInvocation represents a function or method call like `f(args)`. type MethodInvocation struct { ID uuid.UUID Prefix Space @@ -1184,7 +1157,6 @@ func (n *MethodInvocation) WithTypeParameters(typeParameters *Container[Expressi return &c } -// VariableDeclarations represents one or more variable declarations. // Grouped declarations `var ( ... )` / `const ( ... )` are modeled by // golang.DeclarationBlock, whose elements are single VariableDeclarations. type VariableDeclarations struct { @@ -1219,7 +1191,6 @@ func (n *VariableDeclarations) WithLeadingAnnotations(anns []*Annotation) *Varia return &c } -// VariableDeclarator represents a single variable with optional initializer. type VariableDeclarator struct { ID uuid.UUID Prefix Space @@ -1249,7 +1220,6 @@ func (n *VariableDeclarator) WithName(name *Identifier) *VariableDeclarator { return &c } -// ArrayType represents a variable-length array (slice) type like `[]T`. // Mirrors Java's J.ArrayType, which has no length slot. Go's fixed-size arrays // `[N]T` carry an inline length expression and map to golang.ArrayType instead. type ArrayType struct { @@ -1277,7 +1247,6 @@ func (n *ArrayType) WithMarkers(markers Markers) *ArrayType { return &c } -// Parentheses wraps an expression in parentheses: `(expr)`. type Parentheses struct { ID uuid.UUID Prefix Space @@ -1301,7 +1270,6 @@ func (n *Parentheses) WithMarkers(markers Markers) *Parentheses { return &c } -// TypeCast represents a type assertion or type cast: `x.(T)` in Go. type TypeCast struct { ID uuid.UUID Prefix Space @@ -1326,7 +1294,6 @@ func (n *TypeCast) WithMarkers(markers Markers) *TypeCast { return &c } -// ControlParentheses wraps an expression in parentheses for control flow. type ControlParentheses struct { ID uuid.UUID Prefix Space @@ -1350,7 +1317,6 @@ func (n *ControlParentheses) WithMarkers(markers Markers) *ControlParentheses { return &c } -// ArrayAccess represents an index expression like `a[i]` or `m[key]`. type ArrayAccess struct { ID uuid.UUID Prefix Space @@ -1360,7 +1326,6 @@ type ArrayAccess struct { Type JavaType // the result type (nullable) } -// ArrayDimension represents the `[index]` part of an array access. type ArrayDimension struct { ID uuid.UUID Prefix Space @@ -1399,7 +1364,6 @@ func (n *ArrayDimension) WithMarkers(markers Markers) *ArrayDimension { return &c } -// ParameterizedType represents a generic type instantiation like `List[string]`. type ParameterizedType struct { ID uuid.UUID Prefix Space @@ -1425,7 +1389,6 @@ func (n *ParameterizedType) WithMarkers(markers Markers) *ParameterizedType { return &c } -// Import represents a single import declaration. type Import struct { ID uuid.UUID Prefix Space diff --git a/rewrite-go/pkg/tree/java/java_type.go b/rewrite-go/pkg/tree/java/java_type.go index 25b28059f3a..ef5b95c3caa 100644 --- a/rewrite-go/pkg/tree/java/java_type.go +++ b/rewrite-go/pkg/tree/java/java_type.go @@ -18,12 +18,10 @@ package java import "fmt" -// JavaType is the interface for all Java type representations used for type attribution. type JavaType interface { isJavaType() } -// FullyQualified is a JavaType with a fully qualified name. type FullyQualified interface { JavaType GetFullyQualifiedName() string @@ -47,14 +45,12 @@ const ( JavaTypeUnknownKind = "org.openrewrite.java.tree.JavaType$Unknown" ) -// JavaTypePrimitive represents a primitive type like int, boolean, etc. type JavaTypePrimitive struct { Keyword string } func (*JavaTypePrimitive) isJavaType() {} -// JavaTypeClass represents a class, interface, enum, or annotation type. type JavaTypeClass struct { FlagsBitMap int64 Kind string @@ -88,7 +84,6 @@ type JavaTypeShallowClass struct { func (*JavaTypeShallowClass) isJavaType() {} -// JavaTypeParameterized represents a parameterized type like List. type JavaTypeParameterized struct { Type FullyQualified TypeParameters []JavaType @@ -103,7 +98,6 @@ func (p *JavaTypeParameterized) GetFullyQualifiedName() string { return "" } -// JavaTypeGenericTypeVariable represents a generic type variable like T extends Comparable. type JavaTypeGenericTypeVariable struct { Name string Variance string @@ -112,7 +106,6 @@ type JavaTypeGenericTypeVariable struct { func (*JavaTypeGenericTypeVariable) isJavaType() {} -// JavaTypeArray represents an array type. type JavaTypeArray struct { ElemType JavaType Annotations []FullyQualified @@ -120,7 +113,6 @@ type JavaTypeArray struct { func (*JavaTypeArray) isJavaType() {} -// JavaTypeMethod represents a method type signature. type JavaTypeMethod struct { DeclaringType FullyQualified Name string @@ -136,7 +128,6 @@ type JavaTypeMethod struct { func (*JavaTypeMethod) isJavaType() {} -// JavaTypeVariable represents a variable type. type JavaTypeVariable struct { Name string Owner JavaType @@ -146,7 +137,6 @@ type JavaTypeVariable struct { func (*JavaTypeVariable) isJavaType() {} -// JavaTypeAnnotation represents an annotation type reference. type JavaTypeAnnotation struct { Type FullyQualified Values []JavaTypeAnnotationElementValue @@ -154,7 +144,6 @@ type JavaTypeAnnotation struct { func (*JavaTypeAnnotation) isJavaType() {} -// JavaTypeAnnotationElementValue is the interface for annotation element values. // One of *JavaTypeAnnotationSingleElementValue or *JavaTypeAnnotationArrayElementValue. type JavaTypeAnnotationElementValue interface { isJavaTypeAnnotationElementValue() @@ -174,7 +163,6 @@ func (*JavaTypeAnnotationSingleElementValue) isJavaTypeAnnotationElementValue() func (s *JavaTypeAnnotationSingleElementValue) GetElement() JavaType { return s.Element } -// JavaTypeAnnotationArrayElementValue is an array of annotation element values. type JavaTypeAnnotationArrayElementValue struct { Element JavaType ConstantValues []any @@ -185,26 +173,22 @@ func (*JavaTypeAnnotationArrayElementValue) isJavaTypeAnnotationElementValue() { func (a *JavaTypeAnnotationArrayElementValue) GetElement() JavaType { return a.Element } -// JavaTypeMultiCatch represents a multi-catch type (e.g., IOException | SQLException). type JavaTypeMultiCatch struct { ThrowableTypes []JavaType } func (*JavaTypeMultiCatch) isJavaType() {} -// JavaTypeIntersection represents an intersection type (e.g., Serializable & Comparable). type JavaTypeIntersection struct { Bounds []JavaType } func (*JavaTypeIntersection) isJavaType() {} -// JavaTypeUnknown represents an unknown or unresolved type. type JavaTypeUnknown struct{} func (*JavaTypeUnknown) isJavaType() {} -// UnknownType is the singleton instance of JavaTypeUnknown. var UnknownType = &JavaTypeUnknown{} // TypeSignature computes a string signature for a JavaType, used for list identity diff --git a/rewrite-go/pkg/tree/java/markers.go b/rewrite-go/pkg/tree/java/markers.go index 9c87c8d88dd..bd4301bf807 100644 --- a/rewrite-go/pkg/tree/java/markers.go +++ b/rewrite-go/pkg/tree/java/markers.go @@ -23,7 +23,6 @@ type Marker interface { ID() uuid.UUID } -// Markers holds a collection of Marker instances attached to a tree node. type Markers struct { ID uuid.UUID Entries []Marker @@ -40,8 +39,6 @@ type GenericMarker struct { func (m GenericMarker) ID() uuid.UUID { return m.Ident } -// SearchResultMarker represents a SearchResult marker from Java. -// It implements RpcCodec on the Java side, sending 2 sub-fields (id, description). type SearchResultMarker struct { Ident uuid.UUID Description string @@ -49,7 +46,6 @@ type SearchResultMarker struct { func (m SearchResultMarker) ID() uuid.UUID { return m.Ident } -// FindMarker returns a pointer to the first marker of type T, or nil if not found. func FindMarker[T any](markers Markers) *T { for _, m := range markers.Entries { if t, ok := m.(T); ok { @@ -59,7 +55,6 @@ func FindMarker[T any](markers Markers) *T { return nil } -// HasMarker reports whether a marker of type T exists in the markers collection. func HasMarker[T any](markers Markers) bool { for _, m := range markers.Entries { if _, ok := m.(T); ok { @@ -69,7 +64,6 @@ func HasMarker[T any](markers Markers) bool { return false } -// AddMarker returns a new Markers with the given marker appended. func AddMarker(markers Markers, marker Marker) Markers { entries := make([]Marker, len(markers.Entries)+1) copy(entries, markers.Entries) @@ -77,8 +71,6 @@ func AddMarker(markers Markers, marker Marker) Markers { return Markers{ID: markers.ID, Entries: entries} } -// --- Cross-cutting markers used by the recipe framework --- - // SearchResult is a marker indicating that a search recipe found a match. // It is rendered as a comment in printed output (e.g., /*~~(description)~~>*/). type SearchResult struct { @@ -133,22 +125,18 @@ type Semicolon struct { func (m Semicolon) ID() uuid.UUID { return m.Ident } -// NewSemicolon creates a Semicolon marker with a fresh UUID. func NewSemicolon() Semicolon { return Semicolon{Ident: uuid.New()} } -// NewGoProject creates a GoProject marker with a new UUID. func NewGoProject(projectName string) GoProject { return GoProject{Ident: uuid.New(), ProjectName: projectName} } -// NewSearchResult creates a SearchResult marker with a new UUID. func NewSearchResult(description string) SearchResult { return SearchResult{Ident: uuid.New(), Description: description} } -// NewMarkup creates a Markup marker with the given level and message. func NewMarkup(level MarkupLevel, message, detail string) Markup { return Markup{Ident: uuid.New(), Level: level, Message: message, Detail: detail} } diff --git a/rewrite-go/pkg/tree/java/padding.go b/rewrite-go/pkg/tree/java/padding.go index ee8a39e5c05..09110abfc41 100644 --- a/rewrite-go/pkg/tree/java/padding.go +++ b/rewrite-go/pkg/tree/java/padding.go @@ -16,7 +16,6 @@ package java -// RightPadded wraps an element with trailing whitespace/comments. // Used for list elements where whitespace appears after the element // (e.g., before a comma or closing delimiter). type RightPadded[T any] struct { @@ -25,7 +24,6 @@ type RightPadded[T any] struct { Markers Markers } -// LeftPadded wraps an element with preceding whitespace/comments. // Used for operators and delimiters where whitespace appears before // the element (e.g., the space before an operator in a binary expression). type LeftPadded[T any] struct { diff --git a/rewrite-go/pkg/tree/java/parse_error.go b/rewrite-go/pkg/tree/java/parse_error.go index b0aafda3094..ad3880266ce 100644 --- a/rewrite-go/pkg/tree/java/parse_error.go +++ b/rewrite-go/pkg/tree/java/parse_error.go @@ -18,7 +18,6 @@ package java import "github.com/google/uuid" -// ParseError represents a source file that failed to parse. // Mirrors org.openrewrite.tree.ParseError on the Java side. type ParseError struct { Ident uuid.UUID @@ -38,7 +37,6 @@ type ParseError struct { // dispatch. func (*ParseError) IsTree() {} -// NewParseError creates a ParseError from a source path, source text, and error. func NewParseError(sourcePath string, source string, err error) *ParseError { marker := ParseExceptionResult{ Ident: uuid.New(), diff --git a/rewrite-go/pkg/tree/java/space.go b/rewrite-go/pkg/tree/java/space.go index 3adbdd22219..d29c72a31ec 100644 --- a/rewrite-go/pkg/tree/java/space.go +++ b/rewrite-go/pkg/tree/java/space.go @@ -18,7 +18,6 @@ package java import "strings" -// Comment represents a comment in source code. type Comment struct { Kind CommentKind Text string @@ -34,20 +33,16 @@ const ( BlockComment ) -// Space represents whitespace and comments that appear before a syntax element. // This is the fundamental unit of formatting preservation in OpenRewrite. type Space struct { Comments []Comment Whitespace string } -// EmptySpace is the zero-value Space with no whitespace or comments. var EmptySpace = Space{} -// SingleSpace is a Space containing exactly one space character. var SingleSpace = Space{Whitespace: " "} -// IsEmpty returns true if this Space has no whitespace and no comments. func (s Space) IsEmpty() bool { return s.Whitespace == "" && len(s.Comments) == 0 } @@ -74,10 +69,8 @@ func ParseSpace(raw string) Space { return EmptySpace } - // Find where the first comment starts firstComment := findCommentStart(raw, 0) if firstComment == len(raw) { - // No comments, just whitespace return Space{Whitespace: raw} } @@ -87,7 +80,6 @@ func ParseSpace(raw string) Space { for i < len(raw) { if i+1 < len(raw) && raw[i] == '/' && raw[i+1] == '/' { - // Line comment: from // to end of line (not including \n) end := strings.IndexByte(raw[i:], '\n') var text string if end < 0 { @@ -97,13 +89,11 @@ func ParseSpace(raw string) Space { text = raw[i : i+end] i = i + end // i now points at \n } - // Suffix: consume until next comment or end suffixEnd := findCommentStart(raw, i) suffix := raw[i:suffixEnd] i = suffixEnd comments = append(comments, Comment{Kind: LineComment, Text: text, Suffix: suffix}) } else if i+1 < len(raw) && raw[i] == '/' && raw[i+1] == '*' { - // Block comment: from /* to */ end := strings.Index(raw[i+2:], "*/") var text string if end < 0 { @@ -114,7 +104,6 @@ func ParseSpace(raw string) Space { i = i + 2 + end + 2 } multiline := strings.Contains(text, "\n") - // Suffix: consume until next comment or end suffixEnd := findCommentStart(raw, i) suffix := raw[i:suffixEnd] i = suffixEnd diff --git a/rewrite-go/pkg/tree/java/tree.go b/rewrite-go/pkg/tree/java/tree.go index ea17fe4ad45..aa2a5a2a2ed 100644 --- a/rewrite-go/pkg/tree/java/tree.go +++ b/rewrite-go/pkg/tree/java/tree.go @@ -18,7 +18,6 @@ package java import "github.com/google/uuid" -// Tree is the root interface for all LST nodes. type Tree interface{ IsTree() } // J is the interface for all Java-like AST nodes that carry a prefix @@ -50,19 +49,16 @@ type J interface { GetMarkers() Markers } -// Expression is a J node that evaluates to a value. type Expression interface { J IsExpression() } -// Statement is a J node that can appear at statement level. type Statement interface { J IsStatement() } -// SourceFile is a J node representing an entire source file. type SourceFile interface { J IsSourceFile() diff --git a/rewrite-go/pkg/visitor/cursor.go b/rewrite-go/pkg/visitor/cursor.go index 63a3e2a910a..e68ea3c6d88 100644 --- a/rewrite-go/pkg/visitor/cursor.go +++ b/rewrite-go/pkg/visitor/cursor.go @@ -34,7 +34,6 @@ func NewCursor(parent *Cursor, value java.Tree) *Cursor { func (c *Cursor) Parent() *Cursor { return c.parent } func (c *Cursor) Value() java.Tree { return c.value } -// PutMessage stores a value on this cursor's frame, keyed by name. // Mirrors Java Cursor.putMessage(String, Object). func (c *Cursor) PutMessage(key string, value any) { if c.messages == nil { @@ -120,7 +119,6 @@ func (c *Cursor) PutMessageOnFirstEnclosing(match func(t java.Tree) bool, key st } } -// BuildChain constructs a cursor chain from a list of tree values, root first. // Returns nil for an empty input. Used by the RPC layer to reconstruct the // cursor from a Visit request's `cursor` field (a list of tree IDs whose // values have already been fetched in order). diff --git a/rewrite-go/pkg/visitor/go_visitor.go b/rewrite-go/pkg/visitor/go_visitor.go index 99e13794401..700f35863cc 100644 --- a/rewrite-go/pkg/visitor/go_visitor.go +++ b/rewrite-go/pkg/visitor/go_visitor.go @@ -362,8 +362,6 @@ type VisitorI interface { // Ensure GoVisitor satisfies VisitorI. var _ VisitorI = (*GoVisitor)(nil) -// --- Default visit implementations --- - // PreVisit is the per-node hook called by Visit() before dispatching // to the type-specific Visit* method. The default implementation is // the identity function. RPC senders/receivers override it to @@ -1169,8 +1167,6 @@ func (v *GoVisitor) visitMarkers(markers java.Markers, p any) java.Markers { return markers } -// --- Helper functions --- - func visitAndCast[T java.Tree](v *GoVisitor, t java.Tree, p any) T { result := v.self().Visit(t, p) if result == nil { diff --git a/rewrite-go/pkg/visitor/java_type_visitor.go b/rewrite-go/pkg/visitor/java_type_visitor.go index 80abac9aa4d..34670d6c2ff 100644 --- a/rewrite-go/pkg/visitor/java_type_visitor.go +++ b/rewrite-go/pkg/visitor/java_type_visitor.go @@ -86,7 +86,6 @@ func (v *JavaTypeVisitor) Visit(javaType java.JavaType, p any) java.JavaType { } } -// VisitList visits a list of JavaTypes. func (v *JavaTypeVisitor) VisitList(javaTypes []java.JavaType, p any) []java.JavaType { if javaTypes == nil { return nil From eb2a7d405b1d6c5ec44b01b5b4cb5fdce4cfa0bb Mon Sep 17 00:00:00 2001 From: Greg Oledzki Date: Tue, 30 Jun 2026 15:17:44 +0200 Subject: [PATCH 2/2] Remove excessive comments --- rewrite-go/cmd/rpc/prepare_recipe_test.go | 2 -- rewrite-go/cmd/rpc/whole_tree_test.go | 5 +++-- rewrite-go/pkg/matcher/matcher_test.go | 6 ------ .../pkg/recipe/golang/naming_service.go | 7 ++++++- .../pkg/recipe/installer/installer_test.go | 8 ++++---- .../pkg/rpc/go_receiver_imports_test.go | 3 --- rewrite-go/pkg/rpc/padding_rpc_test.go | 7 ------- rewrite-go/pkg/rpc/receive_value_test.go | 1 - .../pkg/template/template_recipe_test.go | 4 ---- rewrite-go/pkg/template/template_test.go | 19 ------------------- rewrite-go/pkg/test/java_rpc.go | 2 -- rewrite-go/pkg/test/spec.go | 9 --------- rewrite-go/test/annotation_service_test.go | 1 - rewrite-go/test/assignment_test.go | 1 - rewrite-go/test/auto_format_test.go | 12 ------------ rewrite-go/test/gomod_recipe_test.go | 10 +++------- rewrite-go/test/import_recipes_test.go | 9 --------- rewrite-go/test/recipe_test.go | 7 ------- rewrite-go/test/type_attribution_test.go | 1 - rewrite-go/test/visitor_test.go | 3 --- 20 files changed, 16 insertions(+), 101 deletions(-) diff --git a/rewrite-go/cmd/rpc/prepare_recipe_test.go b/rewrite-go/cmd/rpc/prepare_recipe_test.go index eb32ccf2c4d..448a244d183 100644 --- a/rewrite-go/cmd/rpc/prepare_recipe_test.go +++ b/rewrite-go/cmd/rpc/prepare_recipe_test.go @@ -24,7 +24,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/recipe" ) -// prepareRecipe runs the PrepareRecipe handler and returns the per-instance id. func prepareRecipe(t *testing.T, s *server, id string) string { t.Helper() params, err := json.Marshal(prepareRecipeRequest{ID: id}) @@ -38,7 +37,6 @@ func prepareRecipe(t *testing.T, s *server, id string) string { return resp.(prepareRecipeResponse).ID } -// visit runs the Visit handler for the given "phase:recipeId" visitor. func visit(t *testing.T, s *server, visitor string) (any, *rpcError) { t.Helper() params, err := json.Marshal(visitRequest{Visitor: visitor, TreeID: "tree-1", SourceFileType: "Go"}) diff --git a/rewrite-go/cmd/rpc/whole_tree_test.go b/rewrite-go/cmd/rpc/whole_tree_test.go index 35d18f13ea5..e87f59ef254 100644 --- a/rewrite-go/cmd/rpc/whole_tree_test.go +++ b/rewrite-go/cmd/rpc/whole_tree_test.go @@ -51,7 +51,9 @@ type goCompositeInvalidChild struct{ recipe.Base } func (*goCompositeInvalidChild) Name() string { return "org.openrewrite.go.test.CompositeInvalid" } func (*goCompositeInvalidChild) DisplayName() string { return "Composite invalid" } -func (*goCompositeInvalidChild) Description() string { return "A composite whose child lacks a required option." } +func (*goCompositeInvalidChild) Description() string { + return "A composite whose child lacks a required option." +} func (*goCompositeInvalidChild) RecipeList() []recipe.Recipe { return []recipe.Recipe{&goReqOptRecipe{}} } @@ -95,7 +97,6 @@ func TestPrepareRecipeValidatesChildRequiredOptions(t *testing.T) { } } -// PrepareRecipe returns the whole prepared tree (recipeList) so the host builds it locally. func TestPrepareRecipeReturnsWholeChildTree(t *testing.T) { s, _ := newTestServer(t) s.registry.Register(&goCompositeRecipe{}) diff --git a/rewrite-go/pkg/matcher/matcher_test.go b/rewrite-go/pkg/matcher/matcher_test.go index 66fb4ac9be9..cbee3865cbf 100644 --- a/rewrite-go/pkg/matcher/matcher_test.go +++ b/rewrite-go/pkg/matcher/matcher_test.go @@ -24,8 +24,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/visitor" ) -// --- TypeUtils tests --- - func TestGetFullyQualifiedName(t *testing.T) { tests := []struct { name string @@ -108,8 +106,6 @@ func TestAsClass(t *testing.T) { } } -// --- MethodMatcher tests --- - func TestGlobToRegexp(t *testing.T) { tests := []struct { pattern string @@ -235,8 +231,6 @@ func TestMethodMatcherMatchesMethod(t *testing.T) { } } -// --- Integration test: MethodMatcher against parsed Go code --- - func TestMethodMatcherOnParsedCode(t *testing.T) { p := parser.NewGoParser() cu, err := p.Parse("test.go", `package main diff --git a/rewrite-go/pkg/recipe/golang/naming_service.go b/rewrite-go/pkg/recipe/golang/naming_service.go index 028cf35e23f..36b0aa1935a 100644 --- a/rewrite-go/pkg/recipe/golang/naming_service.go +++ b/rewrite-go/pkg/recipe/golang/naming_service.go @@ -109,16 +109,21 @@ func (s *NamingService) IsPredeclared(name string) bool { // spec. Update when the language adds new builtins (e.g. `min` / // `max` / `clear` were added in 1.21). var predeclaredIdentifiers = map[string]struct{}{ + // Types. "any": {}, "bool": {}, "byte": {}, "comparable": {}, "complex64": {}, "complex128": {}, "error": {}, "float32": {}, "float64": {}, "int": {}, "int8": {}, "int16": {}, "int32": {}, "int64": {}, "rune": {}, "string": {}, "uint": {}, "uint8": {}, "uint16": {}, "uint32": {}, "uint64": {}, "uintptr": {}, + + // Constants. "true": {}, "false": {}, "iota": {}, // Zero value. - "nil": {}, + "nil": {}, + + // Functions. "append": {}, "cap": {}, "clear": {}, "close": {}, "complex": {}, "copy": {}, "delete": {}, "imag": {}, "len": {}, "make": {}, "max": {}, "min": {}, "new": {}, "panic": {}, "print": {}, diff --git a/rewrite-go/pkg/recipe/installer/installer_test.go b/rewrite-go/pkg/recipe/installer/installer_test.go index 2663b72fafa..f035622cec8 100644 --- a/rewrite-go/pkg/recipe/installer/installer_test.go +++ b/rewrite-go/pkg/recipe/installer/installer_test.go @@ -91,7 +91,7 @@ go 1.25 require ( github.com/foo/bar v1.2.3 ) -` + ` inst := &Installer{WorkspaceDir: writeGoMod(t, goMod)} // when @@ -112,7 +112,7 @@ go 1.25 require ( github.com/foo/bar v1.2.3 // indirect ) -` + ` inst := &Installer{WorkspaceDir: writeGoMod(t, goMod)} // when @@ -131,7 +131,7 @@ func TestReadResolvedVersion_SingleLineRequire(t *testing.T) { go 1.25 require github.com/foo/bar v1.2.3 -` + ` inst := &Installer{WorkspaceDir: writeGoMod(t, goMod)} // when @@ -153,7 +153,7 @@ require ( github.com/foo/barbaz v0.9.9 github.com/foo/bar v1.2.3 ) -` + ` inst := &Installer{WorkspaceDir: writeGoMod(t, goMod)} // when diff --git a/rewrite-go/pkg/rpc/go_receiver_imports_test.go b/rewrite-go/pkg/rpc/go_receiver_imports_test.go index cba39cda3d7..a65c07c522f 100644 --- a/rewrite-go/pkg/rpc/go_receiver_imports_test.go +++ b/rewrite-go/pkg/rpc/go_receiver_imports_test.go @@ -39,7 +39,6 @@ import ( // is built as Container[T] directly — no inference, no guessing for empty // containers, no raw cross-instantiation assertion. -// makeImport returns an *Import shaped like a Go import (Qualid is a string Literal). func makeImport(path string) *java.Import { return &java.Import{ ID: uuid.New(), @@ -98,8 +97,6 @@ func TestRawCastPanics_ContainerImportFromExpression(t *testing.T) { }) } -// ----- Full send->receive round trip through VisitCompilationUnit (Print path) ----- - func TestCompilationUnitRoundTrip_EmptyImports(t *testing.T) { // given: a CU with a non-nil but EMPTY imports container — this is what // triggered the production panic (empty container receives as Expression). diff --git a/rewrite-go/pkg/rpc/padding_rpc_test.go b/rewrite-go/pkg/rpc/padding_rpc_test.go index a180d7b4ad4..73596b85fbc 100644 --- a/rewrite-go/pkg/rpc/padding_rpc_test.go +++ b/rewrite-go/pkg/rpc/padding_rpc_test.go @@ -35,7 +35,6 @@ import ( // pre-fix; the "Coerce…" tests demonstrate the same input flowing through // the coerce helpers without panicking. -// makeIdent returns an *Identifier (which implements Expression only). func makeIdent(name string) *java.Identifier { return &java.Identifier{ID: uuid.New(), Name: name} } @@ -60,8 +59,6 @@ func expectPanic(t *testing.T, label string, fn func()) { t.Fatalf("%s: unreachable — fn returned without panic", label) } -// ----- Group 1: RightPadded[Statement] vs RightPadded[Expression] ----- - func TestCoerceToStatementRP_AcceptsExpressionVariant(t *testing.T) { // given: a RightPadded[Expression] wrapping a *MethodInvocation // (exactly what Java emits for a for-loop init expression that @@ -97,8 +94,6 @@ func TestRawCastPanics_RightPaddedStatementFromExpression(t *testing.T) { }) } -// ----- Group 2: LeftPadded[*Identifier] from LeftPadded[Expression] ----- - func TestCoerceLeftPaddedIdent_AcceptsExpressionVariant(t *testing.T) { // given: a LeftPadded[Expression] wrapping an *Identifier — the shape // Java emits for FieldAccess.name and Import.alias. @@ -128,8 +123,6 @@ func TestRawCastPanics_LeftPaddedIdentFromExpression(t *testing.T) { }) } -// ----- Group 4: coerceRightPaddedTyped[T] element coercion ----- -// // receiveContainerTyped[T] builds Container[T] by running each received element // through coerceRightPaddedTyped[T], so these element-level tests lock in the // guarantees the deleted coerceContainerStatement/coerceContainerExpression/ diff --git a/rewrite-go/pkg/rpc/receive_value_test.go b/rewrite-go/pkg/rpc/receive_value_test.go index 5005b95f6d6..03cc33f0d38 100644 --- a/rewrite-go/pkg/rpc/receive_value_test.go +++ b/rewrite-go/pkg/rpc/receive_value_test.go @@ -22,7 +22,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/tree/java" ) -// queueOf returns a ReceiveQueue that yields the given messages once. func queueOf(msgs ...RpcObjectData) *ReceiveQueue { delivered := false return NewReceiveQueue(make(map[int]any), func() []RpcObjectData { diff --git a/rewrite-go/pkg/template/template_recipe_test.go b/rewrite-go/pkg/template/template_recipe_test.go index 044b1443318..d5d6a3b70b7 100644 --- a/rewrite-go/pkg/template/template_recipe_test.go +++ b/rewrite-go/pkg/template/template_recipe_test.go @@ -46,7 +46,6 @@ func TestDetectScaffoldKind(t *testing.T) { } func TestNewRecipeSimpleRewrite(t *testing.T) { - // Replace identifier `x` with `y` r := NewRecipe( RecipeName("test.ReplaceXWithY"), WithDisplayName("Replace x with y"), @@ -112,7 +111,6 @@ func TestNewRecipeNoChangeWhenNoMatch(t *testing.T) { } func TestNewRecipeMultipleBefores(t *testing.T) { - // Replace both `1 + 2` and `2 + 1` with `3` r := NewRecipe( RecipeName("test.OnePlusTwo"), WithDisplayName("Simplify 1+2"), @@ -123,7 +121,6 @@ func TestNewRecipeMultipleBefores(t *testing.T) { spec := test.NewRecipeSpec().WithRecipe(r) - // First alternative matches spec.RewriteRun(t, test.Golang(` package main @@ -148,7 +145,6 @@ func TestNewRecipeMultipleBeforeSecondMatches(t *testing.T) { spec := test.NewRecipeSpec().WithRecipe(r) - // Second alternative matches spec.RewriteRun(t, test.Golang(` package main diff --git a/rewrite-go/pkg/template/template_test.go b/rewrite-go/pkg/template/template_test.go index 26b8a717d92..59743de5ebf 100644 --- a/rewrite-go/pkg/template/template_test.go +++ b/rewrite-go/pkg/template/template_test.go @@ -87,17 +87,14 @@ func TestParseScaffoldExpression(t *testing.T) { } func TestPatternMatchIdentifier(t *testing.T) { - // Parse source containing identifier "x" p := parser.NewGoParser() cu, err := p.Parse("test.go", "package main\n\nvar y = x\n") if err != nil { t.Fatal(err) } - // Build a pattern that matches identifier "x" pat := Expression("x").Build() - // Find the identifier "x" in the parsed tree var found java.J v := visitor.Init(&identFinder{target: "x", found: &found}) v.Visit(cu, nil) @@ -113,17 +110,14 @@ func TestPatternMatchIdentifier(t *testing.T) { } func TestPatternNoMatch(t *testing.T) { - // Parse source containing identifier "y" p := parser.NewGoParser() cu, err := p.Parse("test.go", "package main\n\nvar z = y\n") if err != nil { t.Fatal(err) } - // Build a pattern that matches identifier "x" pat := Expression("x").Build() - // Find identifier "y" in the tree var found java.J v := visitor.Init(&identFinder{target: "y", found: &found}) v.Visit(cu, nil) @@ -139,20 +133,17 @@ func TestPatternNoMatch(t *testing.T) { } func TestPatternMatchWithCapture(t *testing.T) { - // Parse: 1 + 2 p := parser.NewGoParser() cu, err := p.Parse("test.go", "package main\n\nvar x = 1 + 2\n") if err != nil { t.Fatal(err) } - // Pattern: + 2 expr := Expr("expr") pat := Expression(fmt.Sprintf("%s + 2", expr)). Captures(expr). Build() - // Find the binary expression var found java.J v := visitor.Init(&binaryFinder{found: &found}) v.Visit(cu, nil) @@ -180,7 +171,6 @@ func TestPatternMatchWithCapture(t *testing.T) { } func TestRewriteVisitor(t *testing.T) { - // Recipe that rewrites `x` identifiers to `y` pat := Expression("x").Build() tmpl := ExpressionTemplate("y").Build() rewriter := Rewrite(pat, tmpl) @@ -201,7 +191,6 @@ func TestRewriteVisitor(t *testing.T) { } func TestRewriteBinaryExpression(t *testing.T) { - // Recipe that rewrites `1 + 2` to `3` pat := Expression("1 + 2").Build() tmpl := ExpressionTemplate("3").Build() rewriter := Rewrite(pat, tmpl) @@ -222,7 +211,6 @@ func TestRewriteBinaryExpression(t *testing.T) { } func TestRewriteWithCapture(t *testing.T) { - // Recipe that rewrites ` + 0` to `` expr := Expr("expr") pat := Expression(fmt.Sprintf("%s + 0", expr)). Captures(expr). @@ -248,7 +236,6 @@ func TestRewriteWithCapture(t *testing.T) { } func TestPatternNoChangeWhenNoMatch(t *testing.T) { - // Pattern that matches `1 + 2` should not change `3 + 4` pat := Expression("1 + 2").Build() tmpl := ExpressionTemplate("99").Build() rewriter := Rewrite(pat, tmpl) @@ -265,7 +252,6 @@ func TestPatternNoChangeWhenNoMatch(t *testing.T) { } func TestRewritePreservesFormatting(t *testing.T) { - // Rewriting should preserve the original node's prefix (whitespace). pat := Expression("x").Build() tmpl := ExpressionTemplate("y").Build() rewriter := Rewrite(pat, tmpl) @@ -326,8 +312,6 @@ func TestPatternMatchGoUnary(t *testing.T) { } } -// --- Test helpers --- - type rewriteRecipeWithVisitor struct { recipe.Base visitor recipe.TreeVisitor @@ -338,7 +322,6 @@ func (r *rewriteRecipeWithVisitor) DisplayName() string { return "Test Re func (r *rewriteRecipeWithVisitor) Description() string { return "Test rewrite recipe" } func (r *rewriteRecipeWithVisitor) Editor() recipe.TreeVisitor { return r.visitor } -// identFinder walks the tree to find the first Identifier with the given name. type identFinder struct { visitor.GoVisitor target string @@ -352,7 +335,6 @@ func (v *identFinder) VisitIdentifier(ident *java.Identifier, p any) java.J { return v.GoVisitor.VisitIdentifier(ident, p) } -// goUnaryFinder walks the tree to find the first Go-specific Unary expression. type goUnaryFinder struct { visitor.GoVisitor found *java.J @@ -365,7 +347,6 @@ func (v *goUnaryFinder) VisitGoUnary(u *golang.Unary, p any) java.J { return v.GoVisitor.VisitGoUnary(u, p) } -// binaryFinder walks the tree to find the first Binary expression. type binaryFinder struct { visitor.GoVisitor found *java.J diff --git a/rewrite-go/pkg/test/java_rpc.go b/rewrite-go/pkg/test/java_rpc.go index 07a037f4297..0f576c4bd10 100644 --- a/rewrite-go/pkg/test/java_rpc.go +++ b/rewrite-go/pkg/test/java_rpc.go @@ -230,14 +230,12 @@ func (c *JavaRpcClient) readMessage() (*jsonRPCResponse, error) { } } -// RecipeEntry describes a recipe for the marketplace CSV. type RecipeEntry struct { Name string PackageName string Version string } -// DefaultJavaRecipes returns the common Java recipes used for testing. func DefaultJavaRecipes() []RecipeEntry { return []RecipeEntry{ {Name: "org.openrewrite.java.ChangeType", PackageName: "org.openrewrite:rewrite-java", Version: "8.73.0"}, diff --git a/rewrite-go/pkg/test/spec.go b/rewrite-go/pkg/test/spec.go index a68e24d16fe..731efe2b8cd 100644 --- a/rewrite-go/pkg/test/spec.go +++ b/rewrite-go/pkg/test/spec.go @@ -31,7 +31,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/visitor" ) -// SourceSpec describes a Go source file for testing. type SourceSpec struct { Before string After *string // nil means no change expected (parse-print idempotence only) @@ -335,7 +334,6 @@ func Golang(before string, after ...string) SourceSpec { return spec } -// GolangRaw creates a SourceSpec from raw Go source (no indent trimming). func GolangRaw(before string, after ...string) SourceSpec { spec := SourceSpec{ Before: before, @@ -362,7 +360,6 @@ func TrimIndent(s string) string { lines = lines[:len(lines)-1] } - // Find minimum indentation across non-empty lines minIndent := math.MaxInt for _, line := range lines { if strings.TrimSpace(line) == "" { @@ -395,13 +392,11 @@ func ValidateSpaces(root java.Tree) []string { return (&recipes.WhitespaceValidationService{}).Validate(root) } -// JavaRecipeConfig holds config for a Java-delegated recipe test. type JavaRecipeConfig struct { RecipeName string Options map[string]any } -// RecipeSpec configures a test run. type RecipeSpec struct { CheckParsePrintIdempotence bool Recipe recipe.Recipe @@ -410,14 +405,12 @@ type RecipeSpec struct { MarkerPrinter printer.MarkerPrinter // printer for cross-cutting markers in recipe output; defaults to printer.DefaultMarkerPrinter } -// NewRecipeSpec creates a new RecipeSpec with default settings. func NewRecipeSpec() *RecipeSpec { return &RecipeSpec{ CheckParsePrintIdempotence: true, } } -// WithRecipe sets the recipe to apply during the test run. func (spec *RecipeSpec) WithRecipe(r recipe.Recipe) *RecipeSpec { spec.Recipe = r return spec @@ -433,7 +426,6 @@ func (spec *RecipeSpec) WithJavaRecipe(recipeName string, options map[string]any return spec } -// WithJavaRpcClient sets the Java RPC client for recipe delegation. func (spec *RecipeSpec) WithJavaRpcClient(client *JavaRpcClient) *RecipeSpec { spec.JavaRpcClient = client return spec @@ -627,7 +619,6 @@ func (spec *RecipeSpec) rewriteGoMod(t *testing.T, src SourceSpec) { } } -// runRecipe applies a recipe (including composite recipes with sub-recipes) to a tree. func runRecipe(r recipe.Recipe, t java.Tree) java.Tree { ctx := recipe.NewExecutionContext() diff --git a/rewrite-go/test/annotation_service_test.go b/rewrite-go/test/annotation_service_test.go index 9553d6acb87..f3e515af1e1 100644 --- a/rewrite-go/test/annotation_service_test.go +++ b/rewrite-go/test/annotation_service_test.go @@ -96,7 +96,6 @@ func TestAnnotationService_AllAnnotations_ViaCursor(t *testing.T) { md := parseAndFindMethod(t, src, "slow") svc := &recipes.AnnotationService{} - // Build a cursor positioned AT the MethodDeclaration. c := buildCursor(md) anns := svc.AllAnnotations(c) if len(anns) != 1 { diff --git a/rewrite-go/test/assignment_test.go b/rewrite-go/test/assignment_test.go index 441288d90a0..898ca876492 100644 --- a/rewrite-go/test/assignment_test.go +++ b/rewrite-go/test/assignment_test.go @@ -116,7 +116,6 @@ func TestParseMultiAssignFromFunc(t *testing.T) { `)) } -// ident builds a bare identifier expression for the visitor fixtures. func ident(name string) java.Expression { return &java.Identifier{ID: uuid.New(), Name: name} } diff --git a/rewrite-go/test/auto_format_test.go b/rewrite-go/test/auto_format_test.go index a82f63e0c77..8b7647a9ce5 100644 --- a/rewrite-go/test/auto_format_test.go +++ b/rewrite-go/test/auto_format_test.go @@ -46,8 +46,6 @@ func applyVisitor(t *testing.T, src string, v recipe.TreeVisitor) string { return printer.Print(final) } -// ---- Service registry ---- - func TestAutoFormatService_RegisteredOnInit(t *testing.T) { svc := recipe.Service[*recipes.AutoFormatService](nil) if svc == nil { @@ -55,8 +53,6 @@ func TestAutoFormatService_RegisteredOnInit(t *testing.T) { } } -// ---- RemoveTrailingWhitespaceVisitor ---- - func TestRemoveTrailingWhitespace_StripsTrailingTabsFromLines(t *testing.T) { src := "package main \n\nfunc main() {}\n" out := applyVisitor(t, src, format.NewRemoveTrailingWhitespaceVisitor(nil)) @@ -66,8 +62,6 @@ func TestRemoveTrailingWhitespace_StripsTrailingTabsFromLines(t *testing.T) { } } -// ---- BlankLinesVisitor ---- - // Regression: the leading blank line above the first statement of a // block lives on the *leftmost descendant* of that statement (e.g. // Variable.Prefix), not on Asg.Prefix. The visitor walks the leftmost @@ -145,8 +139,6 @@ func main() { } } -// ---- TabsAndIndentsVisitor ---- - func TestTabsAndIndents_ReindentsFunctionBody(t *testing.T) { src := "package main\n\nfunc main() {\n\t\t a := 1\n\t_ = a\n}\n" want := "package main\n\nfunc main() {\n\ta := 1\n\t_ = a\n}\n" @@ -181,8 +173,6 @@ func main() { } } -// ---- SpacesVisitor ---- - func TestSpaces_NormalizesBinaryOperatorSpacing(t *testing.T) { src := `package main @@ -286,8 +276,6 @@ func main() { } } -// ---- AutoFormatVisitor (composition) ---- - func TestAutoFormat_FullPipelineEndToEnd(t *testing.T) { // Combines: trailing whitespace on `func main() {`, blank line at // start of body, wrong indent on nested block + its body, diff --git a/rewrite-go/test/gomod_recipe_test.go b/rewrite-go/test/gomod_recipe_test.go index 5bfa4f2376e..2da9db96fad 100644 --- a/rewrite-go/test/gomod_recipe_test.go +++ b/rewrite-go/test/gomod_recipe_test.go @@ -26,8 +26,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/visitor" ) -// --- Sample refactoring recipe that rewrites the `go` directive version --- - type changeGoVersion struct { recipe.Base NewVersion string @@ -35,7 +33,9 @@ type changeGoVersion struct { func (r *changeGoVersion) Name() string { return "org.openrewrite.golang.test.ChangeGoVersion" } func (r *changeGoVersion) DisplayName() string { return "Change the go directive version" } -func (r *changeGoVersion) Description() string { return "Rewrites the `go` directive to a new version." } +func (r *changeGoVersion) Description() string { + return "Rewrites the `go` directive to a new version." +} func (r *changeGoVersion) Editor() recipe.TreeVisitor { return visitor.Init(&changeGoVersionVisitor{newVersion: r.NewVersion}) @@ -54,8 +54,6 @@ func (v *changeGoVersionVisitor) VisitGoModDirective(d *golang.GoModDirective, p return d } -// --- Sample search recipe that marks the module path --- - type findModulePath struct { recipe.Base } @@ -83,8 +81,6 @@ func (v *findModulePathVisitor) VisitGoModDirective(d *golang.GoModDirective, p return d } -// --- Tests --- - func TestGoModRecipeSetGoVersion(t *testing.T) { spec := test.NewRecipeSpec().WithRecipe(&changeGoVersion{NewVersion: "1.22"}) spec.RewriteRun(t, diff --git a/rewrite-go/test/import_recipes_test.go b/rewrite-go/test/import_recipes_test.go index 11abc4d7f7f..af856da2107 100644 --- a/rewrite-go/test/import_recipes_test.go +++ b/rewrite-go/test/import_recipes_test.go @@ -23,11 +23,8 @@ import ( . "github.com/openrewrite/rewrite/rewrite-go/pkg/test" ) -// strPtr returns a pointer to s for use as an Alias option. func strPtr(s string) *string { return &s } -// ---- AddImport ---- - func TestAddImport_NoOpWhenAlreadyImported(t *testing.T) { spec := NewRecipeSpec().WithRecipe(&recipes.AddImport{PackagePath: "fmt"}) spec.RewriteRun(t, @@ -154,8 +151,6 @@ func TestAddImport_AliasedFormDoesNotMatchRegular(t *testing.T) { ) } -// ---- RemoveImport ---- - func TestRemoveImport_DeletesMatching(t *testing.T) { spec := NewRecipeSpec().WithRecipe(&recipes.RemoveImport{PackagePath: "strings"}) before := ` @@ -193,8 +188,6 @@ func TestRemoveImport_NoOpWhenAbsent(t *testing.T) { ) } -// ---- RemoveUnusedImports ---- - func TestRemoveUnusedImports_DropsUnreferenced(t *testing.T) { spec := NewRecipeSpec().WithRecipe(&recipes.RemoveUnusedImports{}) before := ` @@ -252,8 +245,6 @@ func TestRemoveUnusedImports_NoOpWhenAllUsed(t *testing.T) { ) } -// ---- OrderImports ---- - func TestOrderImports_IdempotentOnAlreadyOrdered(t *testing.T) { spec := NewRecipeSpec().WithRecipe(&recipes.OrderImports{}) spec.RewriteRun(t, diff --git a/rewrite-go/test/recipe_test.go b/rewrite-go/test/recipe_test.go index cef0ebb994e..815abdff452 100644 --- a/rewrite-go/test/recipe_test.go +++ b/rewrite-go/test/recipe_test.go @@ -28,8 +28,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/visitor" ) -// --- Sample search recipe that marks identifiers named "foo" --- - type findFoo struct { recipe.Base } @@ -56,8 +54,6 @@ func (v *findFooVisitor) VisitIdentifier(ident *java.Identifier, p any) java.J { return ident } -// --- Sample refactoring recipe that renames "foo" to "bar" --- - type renameFooToBar struct { recipe.Base } @@ -82,8 +78,6 @@ func (v *renameFooToBarVisitor) VisitIdentifier(ident *java.Identifier, p any) j return ident } -// --- Tests --- - func TestRecipeRename(t *testing.T) { spec := test.NewRecipeSpec().WithRecipe(&renameFooToBar{}) spec.RewriteRun(t, @@ -206,7 +200,6 @@ func TestRegistryActivate(t *testing.T) { reg.Activate(activateSearch, activateRefactoring) - // Find by name found, ok := reg.FindRecipe("org.openrewrite.golang.test.FindFoo") if !ok { t.Fatal("expected to find FindFoo recipe") diff --git a/rewrite-go/test/type_attribution_test.go b/rewrite-go/test/type_attribution_test.go index 44ee2acab63..9ba33a564d8 100644 --- a/rewrite-go/test/type_attribution_test.go +++ b/rewrite-go/test/type_attribution_test.go @@ -258,7 +258,6 @@ func main() { } func TestTypeAttributionGracefulDegradation(t *testing.T) { - // Parse with unresolvable import — should not error, just have nil types p := parser.NewGoParser() cu, err := p.Parse("test.go", `package main diff --git a/rewrite-go/test/visitor_test.go b/rewrite-go/test/visitor_test.go index 763c2ec72a3..613c0b0f7be 100644 --- a/rewrite-go/test/visitor_test.go +++ b/rewrite-go/test/visitor_test.go @@ -24,7 +24,6 @@ import ( "github.com/openrewrite/rewrite/rewrite-go/pkg/visitor" ) -// deletingVisitor returns nil for Return nodes, exercising the nil guard in visitAndCast/visitExpression. type deletingVisitor struct { visitor.GoVisitor } @@ -49,7 +48,6 @@ func TestVisitorReturningNilDoesNotPanic(t *testing.T) { } } -// importCountingVisitor counts how many Import nodes are visited. type importCountingVisitor struct { visitor.GoVisitor count int @@ -75,7 +73,6 @@ func TestVisitorVisitsImports(t *testing.T) { } } -// identCountingVisitor counts how many Identifier nodes are visited. type identCountingVisitor struct { visitor.GoVisitor names []string