Debian Codegraph @

gopls/internal/golang/embeddirective.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 "errors"
9 "fmt"
10 "io/fs"
11 "path/filepath"
12 "strconv"
13 "strings"
14 "unicode"
15 "unicode/utf8"
16
17 "golang.org/x/tools/gopls/internal/protocol"
18 )
19
20 // ErrNoEmbed is returned by EmbedDefinition when no embed
21 // directive is found at a particular position.
22 // As such it indicates that other definitions could be worth checking.
23 var ErrNoEmbed = errors.New("no embed directive found")
24
25 // embedDefinition finds a file matching the embed directive at pos in the mapped file.
26 // If there is no embed directive at pos, returns [ErrNoEmbed].
27 // If multiple files match the embed pattern, one is picked at random.
28 func embedDefinition(m *protocol.Mapper, rng protocol.Range) ([]protocol.Location, error) {
29 pattern, _ := parseEmbedDirective(m, rng)
30 if pattern == "" {
31 return nil, ErrNoEmbed
32 }
33 pattern = filepath.FromSlash(pattern) // Match requires OS separators
34
35 errFound := errors.New("found")
36
37 // Find the first matching file.
38 var match string
39 dir := m.URI.DirPath()
40 err := filepath.WalkDir(dir, func(abs string, d fs.DirEntry, e error) error {
41 if e != nil {
42 return e
43 }
44 rel, err := filepath.Rel(dir, abs)
45 if err != nil {
46 return err
47 }
48 ok, err := filepath.Match(pattern, rel)
49 if err != nil {
50 return err
51 }
52 if ok && !d.IsDir() {
53 match = abs
54 return errFound
55 }
56 return nil
57 })
58 if err != nil && !errors.Is(err, errFound) {
59 return nil, err // bad pattern or I/O error
60 }
61 if match == "" {
62 return nil, fmt.Errorf("%q does not match any files in %q", pattern, dir)
63 }
64 return []protocol.Location{{URI: protocol.URIFromPath(match)}}, nil
65 }
66
67 // parseEmbedDirective attempts to parse a go:embed directive argument that
68 // contains the given range.
69 // If successful it returns the directive argument (a UNIX-style glob
70 // pattern) and its range, else zero values are returned.
71 func parseEmbedDirective(m *protocol.Mapper, rng protocol.Range) (string, protocol.Range) {
72 if rng.Start.Line != rng.End.Line {
73 return "", protocol.Range{}
74 }
75
76 lineStart, err := m.PositionOffset(protocol.Position{Line: rng.Start.Line, Character: 0})
77 if err != nil {
78 return "", protocol.Range{}
79 }
80 lineEnd, err := m.PositionOffset(protocol.Position{Line: rng.Start.Line + 1, Character: 0})
81 if err != nil {
82 return "", protocol.Range{}
83 }
84
85 text := string(m.Content[lineStart:lineEnd])
86 if !strings.HasPrefix(text, "//go:embed") {
87 return "", protocol.Range{}
88 }
89 text = text[len("//go:embed"):]
90 offset := lineStart + len("//go:embed")
91
92 // Find the first pattern in text that covers the offset of the pos we are looking for.
93 startOffset, endOffset, err := m.RangeOffsets(rng)
94 if err != nil {
95 return "", protocol.Range{}
96 }
97
98 patterns, err := parseGoEmbed(text, offset)
99 if err != nil {
100 return "", protocol.Range{}
101 }
102
103 for _, p := range patterns {
104 if p.startOffset <= startOffset && endOffset <= p.endOffset {
105 // Found our match.
106 rng, err := m.OffsetRange(p.startOffset, p.endOffset)
107 if err != nil {
108 return "", protocol.Range{}
109 }
110 return p.pattern, rng
111 }
112 }
113
114 return "", protocol.Range{}
115 }
116
117 type fileEmbed struct {
118 pattern string
119 startOffset int
120 endOffset int
121 }
122
123 // parseGoEmbed patterns that come after the directive.
124 //
125 // Copied and adapted from go/build/read.go.
126 // Replaced token.Position with start/end offset (including quotes if present).
127 func parseGoEmbed(args string, offset int) ([]fileEmbed, error) {
128 trimBytes := func(n int) {
129 offset += n
130 args = args[n:]
131 }
132 trimSpace := func() {
133 trim := strings.TrimLeftFunc(args, unicode.IsSpace)
134 trimBytes(len(args) - len(trim))
135 }
136
137 var list []fileEmbed
138 for trimSpace(); args != ""; trimSpace() {
139 var path string
140 pathOffset := offset
141 Switch:
142 switch args[0] {
143 default:
144 i := len(args)
145 for j, c := range args {
146 if unicode.IsSpace(c) {
147 i = j
148 break
149 }
150 }
151 path = args[:i]
152 trimBytes(i)
153
154 case '`':
155 var ok bool
156 path, _, ok = strings.Cut(args[1:], "`")
157 if !ok {
158 return nil, fmt.Errorf("invalid quoted string in //go:embed: %s", args)
159 }
160 trimBytes(1 + len(path) + 1)
161
162 case '"':
163 i := 1
164 for ; i < len(args); i++ {
165 if args[i] == '\\' {
166 i++
167 continue
168 }
169 if args[i] == '"' {
170 q, err := strconv.Unquote(args[:i+1])
171 if err != nil {
172 return nil, fmt.Errorf("invalid quoted string in //go:embed: %s", args[:i+1])
173 }
174 path = q
175 trimBytes(i + 1)
176 break Switch
177 }
178 }
179 if i >= len(args) {
180 return nil, fmt.Errorf("invalid quoted string in //go:embed: %s", args)
181 }
182 }
183
184 if args != "" {
185 r, _ := utf8.DecodeRuneInString(args)
186 if !unicode.IsSpace(r) {
187 return nil, fmt.Errorf("invalid quoted string in //go:embed: %s", args)
188 }
189 }
190 list = append(list, fileEmbed{
191 pattern: path,
192 startOffset: pathOffset,
193 endOffset: offset,
194 })
195 }
196 return list, nil
197 }