From 72f2e0bf6de7ef4a34315541b8da70247f5ec563 Mon Sep 17 00:00:00 2001 From: Josh Baum Date: Fri, 7 Aug 2020 15:54:09 -0400 Subject: [PATCH] internal/lsp: limit code action false positives for extract to variable Instead of only checking whether the selection is an AST expression in canExtractVariable, we now also check what kind of AST expression it is. This limits the frequency of situations where the lightbulb appears (canExtractVariable succeeds), but nothing can be extracted (extractVariable fails). Change-Id: I1e63c982e482bb72df48b414bdb4e8037140afdb Reviewed-on: https://go-review.googlesource.com/c/tools/+/247408 Run-TryBot: Josh Baum TryBot-Result: Gobot Gobot Reviewed-by: Rebecca Stambler --- internal/lsp/source/extract.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/internal/lsp/source/extract.go b/internal/lsp/source/extract.go index 9076e8a5cb..11fb10e199 100644 --- a/internal/lsp/source/extract.go +++ b/internal/lsp/source/extract.go @@ -94,7 +94,12 @@ func canExtractVariable(rng span.Range, file *ast.File) (ast.Expr, []ast.Node, b if !ok { return nil, nil, false, fmt.Errorf("node is not an expression") } - return expr, path, true, nil + switch expr.(type) { + case *ast.BasicLit, *ast.CompositeLit, *ast.IndexExpr, + *ast.SliceExpr, *ast.UnaryExpr, *ast.BinaryExpr, *ast.SelectorExpr: + return expr, path, true, nil + } + return nil, nil, false, fmt.Errorf("cannot extract an %T to a variable", expr) } // Calculate indentation for insertion.