internal/codescan/python.go
323 lines · 8373 bytes
17 symbols in this file
1package codescan
2
3import (
4 "regexp"
5 "slices"
6 "strings"
7)
8
9// joinedStringRule flags implicitly joined strings ("a" "b") anywhere inside
10// [...] or {...}. A missing comma only matters where the joined string is
11// itself an element of the list or set. Inside a call or a tuple within the
12// brackets, as in [r for r in conn.execute("select … " "from …")], the
13// strings are one argument split over lines on purpose.
14// joinedOutsideLists reads the source to tell those apart.
15const joinedStringRule = "python.lang.correctness.common-mistakes.string-concat-in-list"
16
17// keepJoined returns the lines of a Python file a string-concat-in-list hit
18// is kept on: every line but those joinedOutsideLists returns.
19func keepJoined(src []byte) (map[int]bool, bool) {
20 outside, ok := joinedOutsideLists(src)
21 if !ok {
22 return nil, false
23 }
24 keep := map[int]bool{}
25 for l := 1; l <= strings.Count(string(src), "\n")+1; l++ {
26 if !outside[l] {
27 keep[l] = true
28 }
29 }
30 return keep, true
31}
32
33// joinedOutsideLists returns the lines of a Python file where implicitly
34// joined strings start or continue with ( as their innermost bracket, or
35// none, and no joined string directly inside [ or { touches the line. ok is
36// false when the file does not read to the end with every string and
37// bracket closed.
38func joinedOutsideLists(src []byte) (lines map[int]bool, ok bool) {
39 s := string(src)
40 var brackets []byte
41 inList, outside := map[int]bool{}, map[int]bool{}
42 line := 1
43 // The string just read and whether only space, comments and line
44 // breaks have followed it: the start of a join.
45 prevEnd, prevLine := -1, 0
46 joinStart := 0
47 for i := 0; i < len(s); {
48 c := s[i]
49 switch {
50 case c == '\n':
51 line++
52 i++
53 continue
54 case c == ' ' || c == '\t' || c == '\r' || c == '\f':
55 i++
56 continue
57 case c == '\\' && i+1 < len(s) && s[i+1] == '\n':
58 line++
59 i += 2
60 continue
61 case c == '#':
62 if end := strings.IndexByte(s[i:], '\n'); end >= 0 {
63 i += end
64 } else {
65 i = len(s)
66 }
67 continue
68 }
69 if q, n := stringStart(s, i); n >= 0 {
70 end, l, ok := pyString(s, i+n, q, strings.ContainsAny(strings.ToLower(s[i:i+n]), "f"))
71 if !ok {
72 return nil, false
73 }
74 if prevEnd >= 0 {
75 if joinStart == 0 {
76 joinStart = prevLine
77 }
78 mark := outside
79 if len(brackets) > 0 && brackets[len(brackets)-1] != '(' {
80 mark = inList
81 }
82 for k := joinStart; k <= line+l; k++ {
83 mark[k] = true
84 }
85 } else {
86 joinStart = 0
87 }
88 prevEnd, prevLine = end, line
89 line += l
90 i = end
91 continue
92 }
93 prevEnd, joinStart = -1, 0
94 switch c {
95 case '(', '[', '{':
96 brackets = append(brackets, c)
97 case ')', ']', '}':
98 if len(brackets) == 0 || brackets[len(brackets)-1] != map[byte]byte{')': '(', ']': '[', '}': '{'}[c] {
99 return nil, false
100 }
101 brackets = brackets[:len(brackets)-1]
102 }
103 i++
104 }
105 if len(brackets) > 0 {
106 return nil, false
107 }
108 for l := range inList {
109 delete(outside, l)
110 }
111 return outside, true
112}
113
114// stringStart reports whether a string literal opens at i: its quote, and
115// the length of its prefix (r, b, u, f and pairs of them), or -1.
116func stringStart(s string, i int) (quote string, n int) {
117 j := i
118 for j < len(s) && j-i < 2 && strings.IndexByte("rRbBuUfF", s[j]) >= 0 {
119 j++
120 }
121 if j < len(s) && (s[j] == '"' || s[j] == '\'') {
122 if j > i && isIdentByte(s, i-1) {
123 return "", -1
124 }
125 q := s[j : j+1]
126 if strings.HasPrefix(s[j:], strings.Repeat(q, 3)) {
127 q = strings.Repeat(q, 3)
128 }
129 return q, j - i
130 }
131 return "", -1
132}
133
134func isIdentByte(s string, i int) bool {
135 if i < 0 {
136 return false
137 }
138 c := s[i]
139 return c == '_' || isLetter(c) || c >= '0' && c <= '9' || c >= 0x80
140}
141
142// pyString reads a string from i, the start of its quote q, to just past its
143// closing quote. lines is how many line breaks it spans. In an f-string the
144// expressions in braces are skipped with their own strings and brackets.
145func pyString(s string, i int, q string, f bool) (end, lines int, ok bool) {
146 j := i + len(q)
147 for j < len(s) {
148 c := s[j]
149 switch {
150 case strings.HasPrefix(s[j:], q):
151 return j + len(q), lines, true
152 case c == '\\':
153 if j+1 < len(s) && s[j+1] == '\n' {
154 lines++
155 }
156 j += 2
157 continue
158 case c == '\n':
159 if len(q) == 1 {
160 return 0, 0, false
161 }
162 lines++
163 case f && c == '{' && strings.HasPrefix(s[j:], "{{"):
164 j += 2
165 continue
166 case f && c == '{':
167 n, l, ok := fieldEnd(s, j+1)
168 if !ok {
169 return 0, 0, false
170 }
171 lines += l
172 j = n
173 continue
174 }
175 j++
176 }
177 return 0, 0, false
178}
179
180// fieldEnd reads an f-string replacement field from i, just past its {, to
181// just past its }.
182func fieldEnd(s string, i int) (end, lines int, ok bool) {
183 depth := 0
184 for i < len(s) {
185 c := s[i]
186 if q, n := stringStart(s, i); n >= 0 {
187 e, l, ok := pyString(s, i+n, q, strings.ContainsAny(strings.ToLower(s[i:i+n]), "f"))
188 if !ok {
189 return 0, 0, false
190 }
191 lines += l
192 i = e
193 continue
194 }
195 switch c {
196 case '\n':
197 lines++
198 case '(', '[', '{':
199 depth++
200 case ')', ']':
201 depth--
202 case '}':
203 if depth == 0 {
204 return i + 1, lines, true
205 }
206 depth--
207 }
208 i++
209 }
210 return 0, 0, false
211}
212
213// returnRules are about a return statement. Opengrep reads a lambda's body
214// as one, so a lambda in a module-level dict, or a sort key in __init__, is
215// reported as a return. returnLines reads the file for the lines that have
216// one.
217var returnRules = []string{
218 "python.lang.maintainability.return-not-in-function",
219 "python.lang.correctness.return-in-init",
220}
221
222// returnLines returns the lines of a Python file with the keyword return
223// outside strings and comments. ok is false when a string is not closed.
224func returnLines(src []byte) (lines map[int]bool, ok bool) {
225 s := string(src)
226 lines = map[int]bool{}
227 line := 1
228 for i := 0; i < len(s); {
229 c := s[i]
230 switch {
231 case c == '\n':
232 line++
233 i++
234 continue
235 case c == '#':
236 if end := strings.IndexByte(s[i:], '\n'); end >= 0 {
237 i += end
238 } else {
239 i = len(s)
240 }
241 continue
242 }
243 if q, n := stringStart(s, i); n >= 0 {
244 end, l, ok := pyString(s, i+n, q, strings.ContainsAny(strings.ToLower(s[i:i+n]), "f"))
245 if !ok {
246 return nil, false
247 }
248 line += l
249 i = end
250 continue
251 }
252 if c == '_' || isLetter(c) || c >= 0x80 {
253 j := i
254 for j < len(s) && isIdentByte(s, j) {
255 j++
256 }
257 if s[i:j] == "return" {
258 lines[line] = true
259 }
260 i = j
261 continue
262 }
263 i++
264 }
265 return lines, true
266}
267
268// attrCallRule flags x.is_name that is not called, asking whether is_name is
269// a method. Where the repository defines is_name only as an attribute or a
270// property, it is not one.
271const attrCallRule = "python.lang.maintainability.is-function-without-parentheses"
272
273// attrCallName is the name in the rule's message.
274var attrCallName = regexp.MustCompile(`^Is "(is_\w+)" a function`)
275
276var (
277 pyDef = regexp.MustCompile(`^(?:async[ \t]+)?def[ \t]+(is_\w+)[ \t]*\(`)
278 // An annotation starts the line; an assignment may be to self.is_name.
279 pyAttr = regexp.MustCompile(`^(is_\w+)[ \t]*(?::[^=]|:$|=[^=])|^[\w.]*\.(is_\w+)[ \t]*=[^=]`)
280)
281
282// pyNames are the is_ names a repository's Python files define: as methods,
283// by a def without a property decorator, and as attributes, by an
284// annotation, an assignment or a property.
285type pyNames struct {
286 methods, attrs map[string]bool
287}
288
289// add reads one file's definitions.
290func (n pyNames) add(src []byte) {
291 var decorators []string
292 for _, raw := range strings.Split(string(src), "\n") {
293 text := strings.TrimSpace(raw)
294 switch {
295 case text == "" || strings.HasPrefix(text, "#"):
296 continue
297 case strings.HasPrefix(text, "@"):
298 decorators = append(decorators, text)
299 continue
300 }
301 if m := pyDef.FindStringSubmatch(text); m != nil {
302 if slices.ContainsFunc(decorators, isProperty) {
303 n.attrs[m[1]] = true
304 } else {
305 n.methods[m[1]] = true
306 }
307 } else if m := pyAttr.FindStringSubmatch(text); m != nil {
308 n.attrs[m[1]+m[2]] = true
309 }
310 decorators = nil
311 }
312}
313
314func isProperty(decorator string) bool {
315 name, _, _ := strings.Cut(strings.TrimPrefix(decorator, "@"), "(")
316 return name == "property" || strings.HasSuffix(name, "cached_property") || strings.HasSuffix(name, ".setter")
317}
318
319// attribute reports whether the repository defines name as an attribute and
320// never as a method.
321func (n pyNames) attribute(name string) bool {
322 return n.attrs[name] && !n.methods[name]
323}