| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package golang |
| 6 |
|
| 7 |
import ( |
| 8 |
"go/ast" |
| 9 |
"go/token" |
| 10 |
"strconv" |
| 11 |
"strings" |
| 12 |
|
| 13 |
"golang.org/x/tools/go/ast/astutil" |
| 14 |
"golang.org/x/tools/gopls/internal/protocol" |
| 15 |
"golang.org/x/tools/gopls/internal/util/bug" |
| 16 |
"golang.org/x/tools/gopls/internal/util/safetoken" |
| 17 |
"golang.org/x/tools/internal/diff" |
| 18 |
) |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
func convertStringLiteral(req *codeActionsRequest) { |
| 27 |
path, _ := astutil.PathEnclosingInterval(req.pgf.File, req.start, req.end) |
| 28 |
lit, ok := path[0].(*ast.BasicLit) |
| 29 |
if !ok || lit.Kind != token.STRING { |
| 30 |
return |
| 31 |
} |
| 32 |
|
| 33 |
str, err := strconv.Unquote(lit.Value) |
| 34 |
if err != nil { |
| 35 |
return |
| 36 |
} |
| 37 |
|
| 38 |
interpreted := lit.Value[0] == '"' |
| 39 |
|
| 40 |
if interpreted && !strconv.CanBackquote(strings.ReplaceAll(str, "\n", "")) { |
| 41 |
return |
| 42 |
} |
| 43 |
|
| 44 |
var ( |
| 45 |
title string |
| 46 |
newText string |
| 47 |
) |
| 48 |
if interpreted { |
| 49 |
title = "Convert to raw string literal" |
| 50 |
newText = "`" + str + "`" |
| 51 |
} else { |
| 52 |
title = "Convert to interpreted string literal" |
| 53 |
newText = strconv.Quote(str) |
| 54 |
} |
| 55 |
|
| 56 |
start, end, err := safetoken.Offsets(req.pgf.Tok, lit.Pos(), lit.End()) |
| 57 |
if err != nil { |
| 58 |
bug.Reportf("failed to get string literal offset by token.Pos:%v", err) |
| 59 |
return |
| 60 |
} |
| 61 |
edits := []diff.Edit{{ |
| 62 |
Start: start, |
| 63 |
End: end, |
| 64 |
New: newText, |
| 65 |
}} |
| 66 |
textedits, err := protocol.EditsFromDiffEdits(req.pgf.Mapper, edits) |
| 67 |
if err != nil { |
| 68 |
bug.Reportf("failed to convert diff.Edit to protocol.TextEdit:%v", err) |
| 69 |
return |
| 70 |
} |
| 71 |
req.addEditAction(title, nil, protocol.DocumentChangeEdit(req.fh, textedits)) |
| 72 |
} |