Debian Codegraph @

gopls/internal/golang/change_quote.go

raw symbols SCIP
1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
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 // convertStringLiteral reports whether we can convert between raw and interpreted
21 // string literals in the [start, end) range, along with a CodeAction containing the edits.
22 //
23 // Only the following conditions are true, the action in result is valid
24 // - [start, end) is enclosed by a string literal
25 // - if the string is interpreted string, need check whether the convert is allowed
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 // Not all "..." strings can be represented as `...` strings.
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 }