Debian Codegraph @

internal/packagestest/expect.go

raw symbols SCIP
1 // Copyright 2018 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 packagestest
6
7 import (
8 "fmt"
9 "go/token"
10 "os"
11 "path/filepath"
12 "reflect"
13 "regexp"
14 "strings"
15
16 "golang.org/x/tools/go/packages"
17 "golang.org/x/tools/internal/astutil"
18 "golang.org/x/tools/internal/expect"
19 )
20
21 const (
22 markMethod = "mark"
23 eofIdentifier = "EOF"
24 )
25
26 // Expect invokes the supplied methods for all expectation notes found in
27 // the exported source files.
28 //
29 // All exported go source files are parsed to collect the expectation
30 // notes.
31 // See the documentation for expect.Parse for how the notes are collected
32 // and parsed.
33 //
34 // The methods are supplied as a map of name to function, and those functions
35 // will be matched against the expectations by name.
36 // Notes with no matching function will be skipped, and functions with no
37 // matching notes will not be invoked.
38 // If there are no registered markers yet, a special pass will be run first
39 // which adds any markers declared with @mark(Name, pattern) or @name. These
40 // call the Mark method to add the marker to the global set.
41 // You can register the "mark" method to override these in your own call to
42 // Expect. The bound Mark function is usable directly in your method map, so
43 //
44 // exported.Expect(map[string]interface{}{"mark": exported.Mark})
45 //
46 // replicates the built in behavior.
47 //
48 // # Method invocation
49 //
50 // When invoking a method the expressions in the parameter list need to be
51 // converted to values to be passed to the method.
52 // There are a very limited set of types the arguments are allowed to be.
53 //
54 // expect.Note : passed the Note instance being evaluated.
55 // string : can be supplied either a string literal or an identifier.
56 // int : can only be supplied an integer literal.
57 // *regexp.Regexp : can only be supplied a regular expression literal
58 // token.Pos : has a file position calculated as described below.
59 // token.Position : has a file position calculated as described below.
60 // expect.Range: has a start and end position as described below.
61 // interface{} : will be passed any value
62 //
63 // # Position calculation
64 //
65 // There is some extra handling when a parameter is being coerced into a
66 // token.Pos, token.Position or Range type argument.
67 //
68 // If the parameter is an identifier, it will be treated as the name of an
69 // marker to look up (as if markers were global variables).
70 //
71 // If it is a string or regular expression, then it will be passed to
72 // expect.MatchBefore to look up a match in the line at which it was declared.
73 //
74 // It is safe to call this repeatedly with different method sets, but it is
75 // not safe to call it concurrently.
76 func (e *Exported) Expect(methods map[string]any) error {
77 if err := e.getNotes(); err != nil {
78 return err
79 }
80 if err := e.getMarkers(); err != nil {
81 return err
82 }
83 var err error
84 ms := make(map[string]method, len(methods))
85 for name, f := range methods {
86 mi := method{f: reflect.ValueOf(f)}
87 mi.converters = make([]converter, mi.f.Type().NumIn())
88 for i := 0; i < len(mi.converters); i++ {
89 mi.converters[i], err = e.buildConverter(mi.f.Type().In(i))
90 if err != nil {
91 return fmt.Errorf("invalid method %v: %v", name, err)
92 }
93 }
94 ms[name] = mi
95 }
96 for _, n := range e.notes {
97 if n.Args == nil {
98 // simple identifier form, convert to a call to mark
99 n = &expect.Note{
100 Pos: n.Pos,
101 Name: markMethod,
102 Args: []any{n.Name, n.Name},
103 }
104 }
105 mi, ok := ms[n.Name]
106 if !ok {
107 continue
108 }
109 params := make([]reflect.Value, len(mi.converters))
110 args := n.Args
111 for i, convert := range mi.converters {
112 params[i], args, err = convert(n, args)
113 if err != nil {
114 return fmt.Errorf("%v: %v", e.ExpectFileSet.Position(n.Pos), err)
115 }
116 }
117 if len(args) > 0 {
118 return fmt.Errorf("%v: unwanted args got %+v extra", e.ExpectFileSet.Position(n.Pos), args)
119 }
120 //TODO: catch the error returned from the method
121 mi.f.Call(params)
122 }
123 return nil
124 }
125
126 // Mark adds a new marker to the known set.
127 func (e *Exported) Mark(name string, r astutil.Range) {
128 if e.markers == nil {
129 e.markers = make(map[string]astutil.Range)
130 }
131 e.markers[name] = r
132 }
133
134 func (e *Exported) getNotes() error {
135 if e.notes != nil {
136 return nil
137 }
138 notes := []*expect.Note{}
139 var dirs []string
140 for _, module := range e.written {
141 for _, filename := range module {
142 dirs = append(dirs, filepath.Dir(filename))
143 }
144 }
145 for filename := range e.Config.Overlay {
146 dirs = append(dirs, filepath.Dir(filename))
147 }
148 pkgs, err := packages.Load(e.Config, dirs...)
149 if err != nil {
150 return fmt.Errorf("unable to load packages for directories %s: %v", dirs, err)
151 }
152 seen := make(map[token.Position]struct{})
153 for _, pkg := range pkgs {
154 for _, filename := range pkg.GoFiles {
155 content, err := e.FileContents(filename)
156 if err != nil {
157 return err
158 }
159 l, err := expect.Parse(e.ExpectFileSet, filename, content)
160 if err != nil {
161 return fmt.Errorf("failed to extract expectations: %v", err)
162 }
163 for _, note := range l {
164 pos := e.ExpectFileSet.Position(note.Pos)
165 if _, ok := seen[pos]; ok {
166 continue
167 }
168 notes = append(notes, note)
169 seen[pos] = struct{}{}
170 }
171 }
172 }
173 if _, ok := e.written[e.primary]; !ok {
174 e.notes = notes
175 return nil
176 }
177 // Check go.mod markers regardless of mode, we need to do this so that our marker count
178 // matches the counts in the summary.txt.golden file for the test directory.
179 if gomod, found := e.written[e.primary]["go.mod"]; found {
180 // If we are in Modules mode, then we need to check the contents of the go.mod.temp.
181 if e.Exporter == Modules {
182 gomod += ".temp"
183 }
184 l, err := goModMarkers(e, gomod)
185 if err != nil {
186 return fmt.Errorf("failed to extract expectations for go.mod: %v", err)
187 }
188 notes = append(notes, l...)
189 }
190 e.notes = notes
191 return nil
192 }
193
194 func goModMarkers(e *Exported, gomod string) ([]*expect.Note, error) {
195 if _, err := os.Stat(gomod); os.IsNotExist(err) {
196 // If there is no go.mod file, we want to be able to continue.
197 return nil, nil
198 }
199 content, err := e.FileContents(gomod)
200 if err != nil {
201 return nil, err
202 }
203 if e.Exporter == GOPATH {
204 return expect.Parse(e.ExpectFileSet, gomod, content)
205 }
206 gomod = strings.TrimSuffix(gomod, ".temp")
207 // If we are in Modules mode, copy the original contents file back into go.mod
208 if err := os.WriteFile(gomod, content, 0644); err != nil {
209 return nil, nil
210 }
211 return expect.Parse(e.ExpectFileSet, gomod, content)
212 }
213
214 func (e *Exported) getMarkers() error {
215 if e.markers != nil {
216 return nil
217 }
218 // set markers early so that we don't call getMarkers again from Expect
219 e.markers = make(map[string]astutil.Range)
220 return e.Expect(map[string]any{
221 markMethod: e.Mark,
222 })
223 }
224
225 var (
226 noteType = reflect.TypeFor[*expect.Note]()
227 identifierType = reflect.TypeFor[expect.Identifier]()
228 posType = reflect.TypeFor[token.Pos]()
229 positionType = reflect.TypeFor[token.Position]()
230 rangeType = reflect.TypeFor[astutil.Range]()
231 fsetType = reflect.TypeFor[*token.FileSet]()
232 regexType = reflect.TypeFor[*regexp.Regexp]()
233 exportedType = reflect.TypeFor[*Exported]()
234 )
235
236 // converter converts from a marker's argument parsed from the comment to
237 // reflect values passed to the method during Invoke.
238 // It takes the args remaining, and returns the args it did not consume.
239 // This allows a converter to consume 0 args for well known types, or multiple
240 // args for compound types.
241 type converter func(*expect.Note, []any) (reflect.Value, []any, error)
242
243 // method is used to track information about Invoke methods that is expensive to
244 // calculate so that we can work it out once rather than per marker.
245 type method struct {
246 f reflect.Value // the reflect value of the passed in method
247 converters []converter // the parameter converters for the method
248 }
249
250 // buildConverter works out what function should be used to go from an ast expressions to a reflect
251 // value of the type expected by a method.
252 // It is called when only the target type is know, it returns converters that are flexible across
253 // all supported expression types for that target type.
254 func (e *Exported) buildConverter(pt reflect.Type) (converter, error) {
255 switch {
256 case pt == noteType:
257 return func(n *expect.Note, args []any) (reflect.Value, []any, error) {
258 return reflect.ValueOf(n), args, nil
259 }, nil
260 case pt == fsetType:
261 return func(n *expect.Note, args []any) (reflect.Value, []any, error) {
262 return reflect.ValueOf(e.ExpectFileSet), args, nil
263 }, nil
264 case pt == exportedType:
265 return func(n *expect.Note, args []any) (reflect.Value, []any, error) {
266 return reflect.ValueOf(e), args, nil
267 }, nil
268 case pt == posType:
269 return func(n *expect.Note, args []any) (reflect.Value, []any, error) {
270 r, remains, err := e.rangeConverter(n, args)
271 if err != nil {
272 return reflect.Value{}, nil, err
273 }
274 return reflect.ValueOf(r.Start), remains, nil
275 }, nil
276 case pt == positionType:
277 return func(n *expect.Note, args []any) (reflect.Value, []any, error) {
278 r, remains, err := e.rangeConverter(n, args)
279 if err != nil {
280 return reflect.Value{}, nil, err
281 }
282 return reflect.ValueOf(e.ExpectFileSet.Position(r.Start)), remains, nil
283 }, nil
284 case pt == rangeType:
285 return func(n *expect.Note, args []any) (reflect.Value, []any, error) {
286 r, remains, err := e.rangeConverter(n, args)
287 if err != nil {
288 return reflect.Value{}, nil, err
289 }
290 return reflect.ValueOf(r), remains, nil
291 }, nil
292 case pt == identifierType:
293 return func(n *expect.Note, args []any) (reflect.Value, []any, error) {
294 if len(args) < 1 {
295 return reflect.Value{}, nil, fmt.Errorf("missing argument")
296 }
297 arg := args[0]
298 args = args[1:]
299 switch arg := arg.(type) {
300 case expect.Identifier:
301 return reflect.ValueOf(arg), args, nil
302 default:
303 return reflect.Value{}, nil, fmt.Errorf("cannot convert %v to string", arg)
304 }
305 }, nil
306
307 case pt == regexType:
308 return func(n *expect.Note, args []any) (reflect.Value, []any, error) {
309 if len(args) < 1 {
310 return reflect.Value{}, nil, fmt.Errorf("missing argument")
311 }
312 arg := args[0]
313 args = args[1:]
314 if _, ok := arg.(*regexp.Regexp); !ok {
315 return reflect.Value{}, nil, fmt.Errorf("cannot convert %v to *regexp.Regexp", arg)
316 }
317 return reflect.ValueOf(arg), args, nil
318 }, nil
319
320 case pt.Kind() == reflect.String:
321 return func(n *expect.Note, args []any) (reflect.Value, []any, error) {
322 if len(args) < 1 {
323 return reflect.Value{}, nil, fmt.Errorf("missing argument")
324 }
325 arg := args[0]
326 args = args[1:]
327 switch arg := arg.(type) {
328 case expect.Identifier:
329 return reflect.ValueOf(string(arg)), args, nil
330 case string:
331 return reflect.ValueOf(arg), args, nil
332 default:
333 return reflect.Value{}, nil, fmt.Errorf("cannot convert %v to string", arg)
334 }
335 }, nil
336 case pt.Kind() == reflect.Int64:
337 return func(n *expect.Note, args []any) (reflect.Value, []any, error) {
338 if len(args) < 1 {
339 return reflect.Value{}, nil, fmt.Errorf("missing argument")
340 }
341 arg := args[0]
342 args = args[1:]
343 switch arg := arg.(type) {
344 case int64:
345 return reflect.ValueOf(arg), args, nil
346 default:
347 return reflect.Value{}, nil, fmt.Errorf("cannot convert %v to int", arg)
348 }
349 }, nil
350 case pt.Kind() == reflect.Bool:
351 return func(n *expect.Note, args []any) (reflect.Value, []any, error) {
352 if len(args) < 1 {
353 return reflect.Value{}, nil, fmt.Errorf("missing argument")
354 }
355 arg := args[0]
356 args = args[1:]
357 b, ok := arg.(bool)
358 if !ok {
359 return reflect.Value{}, nil, fmt.Errorf("cannot convert %v to bool", arg)
360 }
361 return reflect.ValueOf(b), args, nil
362 }, nil
363 case pt.Kind() == reflect.Slice:
364 return func(n *expect.Note, args []any) (reflect.Value, []any, error) {
365 converter, err := e.buildConverter(pt.Elem())
366 if err != nil {
367 return reflect.Value{}, nil, err
368 }
369 result := reflect.MakeSlice(reflect.SliceOf(pt.Elem()), 0, len(args))
370 for range args {
371 value, remains, err := converter(n, args)
372 if err != nil {
373 return reflect.Value{}, nil, err
374 }
375 result = reflect.Append(result, value)
376 args = remains
377 }
378 return result, args, nil
379 }, nil
380 default:
381 if pt.Kind() == reflect.Interface && pt.NumMethod() == 0 {
382 return func(n *expect.Note, args []any) (reflect.Value, []any, error) {
383 if len(args) < 1 {
384 return reflect.Value{}, nil, fmt.Errorf("missing argument")
385 }
386 return reflect.ValueOf(args[0]), args[1:], nil
387 }, nil
388 }
389 return nil, fmt.Errorf("param has unexpected type %v (kind %v)", pt, pt.Kind())
390 }
391 }
392
393 func (e *Exported) rangeConverter(n *expect.Note, args []any) (astutil.Range, []any, error) {
394 tokFile := e.ExpectFileSet.File(n.Pos)
395 if len(args) < 1 {
396 return astutil.Range{}, nil, fmt.Errorf("missing argument")
397 }
398 arg := args[0]
399 args = args[1:]
400 switch arg := arg.(type) {
401 case expect.Identifier:
402 // handle the special identifiers
403 switch arg {
404 case eofIdentifier:
405 // end of file identifier
406 eof := tokFile.Pos(tokFile.Size())
407 return newRange(tokFile, eof, eof), args, nil
408 default:
409 // look up a marker by name
410 mark, ok := e.markers[string(arg)]
411 if !ok {
412 return astutil.Range{}, nil, fmt.Errorf("cannot find marker %v", arg)
413 }
414 return mark, args, nil
415 }
416 case string:
417 start, end, err := expect.MatchBefore(tokFile, e.FileContents, n.Pos, arg)
418 if err != nil {
419 return astutil.Range{}, nil, err
420 }
421 if !start.IsValid() {
422 return astutil.Range{}, nil, fmt.Errorf("%v: pattern %s did not match", tokFile.Position(n.Pos), arg)
423 }
424 return newRange(tokFile, start, end), args, nil
425 case *regexp.Regexp:
426 start, end, err := expect.MatchBefore(tokFile, e.FileContents, n.Pos, arg)
427 if err != nil {
428 return astutil.Range{}, nil, err
429 }
430 if !start.IsValid() {
431 return astutil.Range{}, nil, fmt.Errorf("%v: pattern %s did not match", tokFile.Position(n.Pos), arg)
432 }
433 return newRange(tokFile, start, end), args, nil
434 default:
435 return astutil.Range{}, nil, fmt.Errorf("cannot convert %v to pos", arg)
436 }
437 }
438
439 // newRange creates a new Range from two valid positions within the specified token.File.
440 func newRange(file *token.File, start, end token.Pos) astutil.Range {
441 fileBase := file.Base()
442 fileEnd := fileBase + file.Size()
443 if !start.IsValid() {
444 panic("invalid start token.Pos")
445 }
446 if !end.IsValid() {
447 panic("invalid end token.Pos")
448 }
449 if int(start) < fileBase || int(start) > fileEnd {
450 panic(fmt.Sprintf("invalid start: %d not in [%d, %d]", start, fileBase, fileEnd))
451 }
452 if int(end) < fileBase || int(end) > fileEnd {
453 panic(fmt.Sprintf("invalid end: %d not in [%d, %d]", end, fileBase, fileEnd))
454 }
455 if start > end {
456 panic("invalid start: greater than end")
457 }
458 return astutil.RangeOf(start, end)
459 }