Debian Codegraph @

internal/expect/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 /*
6 Package expect provides support for interpreting structured comments in Go
7 source code (including go.mod and go.work files) as test expectations.
8
9 This is primarily intended for writing tests of things that process Go source
10 files, although it does not directly depend on the testing package.
11
12 Collect notes with the Extract or Parse functions, and use the
13 MatchBefore function to find matches within the lines the comments were on.
14
15 The interpretation of the notes depends on the application.
16 For example, the test suite for a static checking tool might
17 use a @diag note to indicate an expected diagnostic:
18
19 fmt.Printf("%s", 1) //@ diag("%s wants a string, got int")
20
21 By contrast, the test suite for a source code navigation tool
22 might use notes to indicate the positions of features of
23 interest, the actions to be performed by the test,
24 and their expected outcomes:
25
26 var x = 1 //@ x_decl
27 ...
28 print(x) //@ definition("x", x_decl)
29 print(x) //@ typeof("x", "int")
30
31 # Note comment syntax
32
33 Note comments always start with the special marker @, which must be the
34 very first character after the comment opening pair, so //@ or /*@ with no
35 spaces.
36
37 This is followed by a comma separated list of notes.
38
39 A note always starts with an identifier, which is optionally followed by an
40 argument list. The argument list is surrounded with parentheses and contains a
41 comma-separated list of arguments.
42 The empty parameter list and the missing parameter list are distinguishable if
43 needed; they result in a nil or an empty list in the Args parameter respectively.
44
45 Arguments may be positional, such as f(value), or named, such as f(name=value).
46 Positional arguments must appear before named arguments.
47 Names may not be repeated.
48
49 Argument values may be either identifiers or literals.
50 The literals supported are the basic value literals, of string, float, integer
51 true, false or nil. All the literals match the standard go conventions, with
52 all bases of integers, and both quote and backtick strings.
53 There is one extra literal type, which is a string literal preceded by the
54 identifier "re" which is compiled to a regular expression.
55 */
56 package expect
57
58 import (
59 "bytes"
60 "fmt"
61 "go/token"
62 "regexp"
63 )
64
65 // Note is a parsed note from an expect comment.
66 // It knows the position of the start of the comment, and the name and
67 // arguments that make up the note.
68 type Note struct {
69 Pos token.Pos // The position at which the note identifier appears
70 Name string // the name associated with the note
71 Args []any // positional arguments (non-nil if parens were present)
72 NamedArgs map[string]any // named arguments (or nil if none)
73 }
74
75 // ReadFile is the type of a function that can provide file contents for a
76 // given filename.
77 // This is used in MatchBefore to look up the content of the file in order to
78 // find the line to match the pattern against.
79 type ReadFile func(filename string) ([]byte, error)
80
81 // MatchBefore attempts to match a pattern in the line before the supplied pos.
82 // It uses the token.File and the ReadFile to work out the contents of the line
83 // that end is part of, and then matches the pattern against the content of the
84 // start of that line up to the supplied position.
85 // The pattern may be either a simple string, []byte or a *regexp.Regexp.
86 // MatchBefore returns the range of the line that matched the pattern, and
87 // invalid positions if there was no match, or an error if the line could not be
88 // found.
89 func MatchBefore(f *token.File, readFile ReadFile, end token.Pos, pattern any) (token.Pos, token.Pos, error) {
90 content, err := readFile(f.Name())
91 if err != nil {
92 return token.NoPos, token.NoPos, fmt.Errorf("invalid file: %v", err)
93 }
94 position := f.Position(end)
95 startOffset := f.Offset(f.LineStart(position.Line))
96 endOffset := f.Offset(end)
97 line := content[startOffset:endOffset]
98 matchStart, matchEnd := -1, -1
99 switch pattern := pattern.(type) {
100 case string:
101 bytePattern := []byte(pattern)
102 matchStart = bytes.Index(line, bytePattern)
103 if matchStart >= 0 {
104 matchEnd = matchStart + len(bytePattern)
105 }
106 case []byte:
107 matchStart = bytes.Index(line, pattern)
108 if matchStart >= 0 {
109 matchEnd = matchStart + len(pattern)
110 }
111 case *regexp.Regexp:
112 match := pattern.FindIndex(line)
113 if len(match) > 0 {
114 matchStart = match[0]
115 matchEnd = match[1]
116 }
117 }
118 if matchStart < 0 {
119 return token.NoPos, token.NoPos, nil
120 }
121 return f.Pos(startOffset + matchStart), f.Pos(startOffset + matchEnd), nil
122 }