codeveto 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codeveto/__init__.py +3 -0
- codeveto/__main__.py +8 -0
- codeveto/ai/__init__.py +19 -0
- codeveto/ai/harness.py +303 -0
- codeveto/ai/packets.py +855 -0
- codeveto/ai/policy.py +222 -0
- codeveto/ai/prompt.py +101 -0
- codeveto/ai/providers/__init__.py +178 -0
- codeveto/ai/providers/claude.py +247 -0
- codeveto/ai/providers/openai_compat.py +246 -0
- codeveto/ai/runner.py +293 -0
- codeveto/ai/verify.py +324 -0
- codeveto/anchor.py +211 -0
- codeveto/cli.py +247 -0
- codeveto/cli_explain.py +49 -0
- codeveto/cli_hook.py +31 -0
- codeveto/cli_init.py +254 -0
- codeveto/cli_mcp.py +29 -0
- codeveto/cli_packets.py +35 -0
- codeveto/cli_publish.py +29 -0
- codeveto/cli_review.py +362 -0
- codeveto/cli_rules.py +78 -0
- codeveto/cli_verify.py +47 -0
- codeveto/config.py +1229 -0
- codeveto/data/README.md +16 -0
- codeveto/data/ai-wire.schema.json +53 -0
- codeveto/data/prompts/system.md +57 -0
- codeveto/data/report-v1.schema.json +268 -0
- codeveto/data/templates/forgejo-codeveto.yml +104 -0
- codeveto/data/templates/github-codeveto.yml +18 -0
- codeveto/embedded.py +311 -0
- codeveto/engine.py +1570 -0
- codeveto/git.py +1549 -0
- codeveto/globs.py +348 -0
- codeveto/integrations/__init__.py +1 -0
- codeveto/integrations/hooks.py +327 -0
- codeveto/integrations/mcp.py +770 -0
- codeveto/integrations/mcp_ai.py +77 -0
- codeveto/integrations/prepush.py +222 -0
- codeveto/jsonsafe.py +60 -0
- codeveto/languages.py +539 -0
- codeveto/lexers.py +2560 -0
- codeveto/model.py +372 -0
- codeveto/publish/__init__.py +28 -0
- codeveto/publish/action.py +330 -0
- codeveto/publish/common.py +84 -0
- codeveto/publish/diff.py +208 -0
- codeveto/publish/event.py +241 -0
- codeveto/publish/forgejo.py +184 -0
- codeveto/publish/github.py +380 -0
- codeveto/publish/http.py +263 -0
- codeveto/publish/pull.py +218 -0
- codeveto/publish/untrusted.py +110 -0
- codeveto/py.typed +0 -0
- codeveto/redact.py +113 -0
- codeveto/render/__init__.py +64 -0
- codeveto/render/agent.py +43 -0
- codeveto/render/github.py +101 -0
- codeveto/render/json.py +23 -0
- codeveto/render/markdown.py +208 -0
- codeveto/render/safe.py +249 -0
- codeveto/render/sarif.py +217 -0
- codeveto/render/text.py +210 -0
- codeveto/report.py +252 -0
- codeveto/rules/__init__.py +84 -0
- codeveto/rules/agent.py +2972 -0
- codeveto/rules/base.py +1026 -0
- codeveto/rules/ci.py +1708 -0
- codeveto/rules/config.py +493 -0
- codeveto/rules/deps.py +1693 -0
- codeveto/rules/docker.py +479 -0
- codeveto/rules/examples/__init__.py +148 -0
- codeveto/rules/examples/agent.py +839 -0
- codeveto/rules/examples/ci.py +1046 -0
- codeveto/rules/examples/config.py +191 -0
- codeveto/rules/examples/deps.py +369 -0
- codeveto/rules/examples/docker.py +157 -0
- codeveto/rules/examples/go.py +241 -0
- codeveto/rules/examples/hygiene.py +466 -0
- codeveto/rules/examples/js.py +462 -0
- codeveto/rules/examples/python.py +595 -0
- codeveto/rules/examples/rust.py +268 -0
- codeveto/rules/examples/secrets.py +561 -0
- codeveto/rules/examples/security.py +608 -0
- codeveto/rules/examples/shell.py +174 -0
- codeveto/rules/examples/sql.py +194 -0
- codeveto/rules/examples/tests.py +497 -0
- codeveto/rules/go.py +328 -0
- codeveto/rules/hygiene.py +1094 -0
- codeveto/rules/js.py +768 -0
- codeveto/rules/python.py +1642 -0
- codeveto/rules/rust.py +209 -0
- codeveto/rules/secrets.py +1335 -0
- codeveto/rules/security.py +3680 -0
- codeveto/rules/shell.py +867 -0
- codeveto/rules/sql.py +629 -0
- codeveto/rules/tests.py +1404 -0
- codeveto/schema.py +384 -0
- codeveto/statements.py +607 -0
- codeveto/worktree.py +1176 -0
- codeveto/yamlish.py +1179 -0
- codeveto-0.1.0.dist-info/METADATA +253 -0
- codeveto-0.1.0.dist-info/RECORD +106 -0
- codeveto-0.1.0.dist-info/WHEEL +4 -0
- codeveto-0.1.0.dist-info/entry_points.txt +2 -0
- codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
codeveto/statements.py
ADDED
|
@@ -0,0 +1,607 @@
|
|
|
1
|
+
"""Logical statements over lexed text (``FileContext.statements()``, SPEC 5.3).
|
|
2
|
+
|
|
3
|
+
A :class:`Statement` is a source range that rules can treat as one unit:
|
|
4
|
+
|
|
5
|
+
- Python: AST node ranges. A simple statement is whole; a compound statement
|
|
6
|
+
contributes its header (decorators included) up to its first body
|
|
7
|
+
statement, then its bodies recurse, and clause lines between bodies
|
|
8
|
+
(``else:``, ``except E:``, ``case x:``) are statements of their own. Without
|
|
9
|
+
an AST (a syntax error, or a lone CR that would shift AST line numbers) the
|
|
10
|
+
lexer-based bracket joining below is used.
|
|
11
|
+
- C family: bracket-balanced. ``;`` ends a statement (except inside a Go
|
|
12
|
+
``if``/``for``/``switch`` header), so does a block ``{`` (inclusive) or a
|
|
13
|
+
closing ``}``; an object or struct literal's braces stay inside their
|
|
14
|
+
statement. A brace opens a block after ``)``, ``=>`` or a name (in
|
|
15
|
+
JavaScript/TypeScript not after ``return`` and similar keywords; in Go and
|
|
16
|
+
Rust only when the statement starts with a block keyword such as ``if``,
|
|
17
|
+
``fn`` or ``struct``). JavaScript, TypeScript, Go and Kotlin also end a
|
|
18
|
+
statement at a line break unless the line ends with an operator or the next
|
|
19
|
+
line starts with ``.``, ``?.``, ``&&`` or ``||``; Java and Rust do not.
|
|
20
|
+
- Shell and Dockerfile: physical lines joined by line continuations, trailing
|
|
21
|
+
``|``/``&&``/``||``, multi-line strings and heredoc bodies.
|
|
22
|
+
- YAML: physical lines joined by multi-line strings and block scalar bodies.
|
|
23
|
+
- TOML: lines joined by multi-line strings and open brackets.
|
|
24
|
+
- SQL: ``;``-separated.
|
|
25
|
+
- Everything else: physical lines, joined by multi-line strings.
|
|
26
|
+
|
|
27
|
+
A statement longer than :data:`MAX_LINES` lines or :data:`MAX_CHARS`
|
|
28
|
+
characters is split into chunks marked ``truncated``.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import ast
|
|
34
|
+
import bisect
|
|
35
|
+
import re
|
|
36
|
+
from dataclasses import dataclass
|
|
37
|
+
|
|
38
|
+
from codeveto import lexers
|
|
39
|
+
from codeveto.lexers import LexResult, LineIndex, StringSpan
|
|
40
|
+
|
|
41
|
+
__all__ = ["MAX_CHARS", "MAX_LINES", "Statement", "split"]
|
|
42
|
+
|
|
43
|
+
MAX_LINES = 64
|
|
44
|
+
MAX_CHARS = 16_000
|
|
45
|
+
|
|
46
|
+
_WS = " \t\r\n\f\v"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True, slots=True)
|
|
50
|
+
class Statement:
|
|
51
|
+
"""One logical statement.
|
|
52
|
+
|
|
53
|
+
``text`` and ``masked`` are the same slice (``start..end``) of the source
|
|
54
|
+
and of the masked source. ``line_starts`` holds the offsets within ``text``
|
|
55
|
+
where each line of the statement begins (the first is ``0``).
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
start_line: int
|
|
59
|
+
end_line: int
|
|
60
|
+
text: str
|
|
61
|
+
masked: str
|
|
62
|
+
start: int
|
|
63
|
+
end: int
|
|
64
|
+
line_starts: tuple[int, ...]
|
|
65
|
+
truncated: bool = False
|
|
66
|
+
|
|
67
|
+
def line_of(self, offset: int) -> int:
|
|
68
|
+
"""1-based file line of ``offset``, an index into ``text``."""
|
|
69
|
+
return self.start_line + bisect.bisect_right(self.line_starts, offset) - 1
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# --- Building statements from ranges ---------------------------------------------------
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class _Builder:
|
|
76
|
+
def __init__(self, text: str, masked: str, code: str, index: LineIndex) -> None:
|
|
77
|
+
self.text = text
|
|
78
|
+
self.masked = masked
|
|
79
|
+
# The flat view (comments blanked, strings opaque) decides trimming and
|
|
80
|
+
# emptiness, so comment-only ranges are skipped and strings count.
|
|
81
|
+
self.code = code
|
|
82
|
+
self.index = index
|
|
83
|
+
self.out: list[Statement] = []
|
|
84
|
+
|
|
85
|
+
def add(self, start: int, end: int) -> None:
|
|
86
|
+
code = self.code
|
|
87
|
+
end = min(end, len(code))
|
|
88
|
+
while start < end and code[start] in _WS:
|
|
89
|
+
start += 1
|
|
90
|
+
while end > start and code[end - 1] in _WS:
|
|
91
|
+
end -= 1
|
|
92
|
+
if start >= end:
|
|
93
|
+
return
|
|
94
|
+
first = self.index.line_of(start)
|
|
95
|
+
last = self.index.line_of(end - 1)
|
|
96
|
+
if last - first + 1 <= MAX_LINES and end - start <= MAX_CHARS:
|
|
97
|
+
self.out.append(self._make(start, end, first, last, truncated=False))
|
|
98
|
+
return
|
|
99
|
+
self._split(start, end)
|
|
100
|
+
|
|
101
|
+
def _split(self, start: int, end: int) -> None:
|
|
102
|
+
text = self.text
|
|
103
|
+
cursor = start
|
|
104
|
+
while cursor < end:
|
|
105
|
+
stop = cursor
|
|
106
|
+
lines = 0
|
|
107
|
+
while stop < end and lines < MAX_LINES:
|
|
108
|
+
nl = text.find("\n", stop, end)
|
|
109
|
+
line_end = end if nl < 0 else nl + 1
|
|
110
|
+
if line_end - cursor > MAX_CHARS:
|
|
111
|
+
if lines == 0:
|
|
112
|
+
stop = cursor + MAX_CHARS # one overlong line: cut it
|
|
113
|
+
break
|
|
114
|
+
stop = line_end
|
|
115
|
+
lines += 1
|
|
116
|
+
piece_end = stop
|
|
117
|
+
while piece_end > cursor and text[piece_end - 1] in "\r\n":
|
|
118
|
+
piece_end -= 1
|
|
119
|
+
if piece_end > cursor:
|
|
120
|
+
first = self.index.line_of(cursor)
|
|
121
|
+
last = self.index.line_of(piece_end - 1)
|
|
122
|
+
self.out.append(self._make(cursor, piece_end, first, last, truncated=True))
|
|
123
|
+
cursor = stop
|
|
124
|
+
|
|
125
|
+
def _make(self, start: int, end: int, first: int, last: int, *, truncated: bool) -> Statement:
|
|
126
|
+
starts = [0]
|
|
127
|
+
text = self.text
|
|
128
|
+
i = text.find("\n", start, end)
|
|
129
|
+
while i >= 0:
|
|
130
|
+
if i + 1 < end:
|
|
131
|
+
starts.append(i + 1 - start)
|
|
132
|
+
i = text.find("\n", i + 1, end)
|
|
133
|
+
return Statement(
|
|
134
|
+
start_line=first,
|
|
135
|
+
end_line=last,
|
|
136
|
+
text=text[start:end],
|
|
137
|
+
masked=self.masked[start:end],
|
|
138
|
+
start=start,
|
|
139
|
+
end=end,
|
|
140
|
+
line_starts=tuple(starts),
|
|
141
|
+
truncated=truncated,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
def done(self) -> tuple[Statement, ...]:
|
|
145
|
+
self.out.sort(key=lambda s: (s.start, s.end))
|
|
146
|
+
return tuple(self.out)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _joining_newlines(text: str, result: LexResult) -> frozenset[int]:
|
|
150
|
+
"""Line breaks right before a delimiter-less string body (heredoc, block scalar)."""
|
|
151
|
+
joins: set[int] = set()
|
|
152
|
+
for span in result.spans:
|
|
153
|
+
if (
|
|
154
|
+
isinstance(span, StringSpan)
|
|
155
|
+
and span.start == span.content_start
|
|
156
|
+
and span.start > 0
|
|
157
|
+
and text[span.start - 1] == "\n"
|
|
158
|
+
):
|
|
159
|
+
joins.add(span.start - 1)
|
|
160
|
+
return frozenset(joins)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _flat(code: str, result: LexResult) -> str:
|
|
164
|
+
"""``code`` with every top-level string turned into one opaque token.
|
|
165
|
+
|
|
166
|
+
Each string becomes a run of ``_`` (line breaks included), so brackets,
|
|
167
|
+
operators and line breaks inside it never split or join statements, and
|
|
168
|
+
a statement that is only a string is not empty.
|
|
169
|
+
"""
|
|
170
|
+
out: list[str] = []
|
|
171
|
+
last = 0
|
|
172
|
+
for span in result.spans:
|
|
173
|
+
if not isinstance(span, StringSpan) or span.end <= last:
|
|
174
|
+
continue
|
|
175
|
+
a = max(span.start, last)
|
|
176
|
+
out.append(code[last:a])
|
|
177
|
+
out.append("_" * (span.end - a))
|
|
178
|
+
last = span.end
|
|
179
|
+
out.append(code[last:])
|
|
180
|
+
return "".join(out)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
# --- Line-oriented families --------------------------------------------------------------
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _lines(
|
|
187
|
+
b: _Builder,
|
|
188
|
+
flat: str,
|
|
189
|
+
*,
|
|
190
|
+
joins: frozenset[int] = frozenset(),
|
|
191
|
+
brackets: bool = False,
|
|
192
|
+
shell_esc: str | None = None,
|
|
193
|
+
pipes: bool = False,
|
|
194
|
+
skip_blank_continuations: bool = False,
|
|
195
|
+
) -> None:
|
|
196
|
+
"""Physical lines of ``flat``, joined where the statement goes on.
|
|
197
|
+
|
|
198
|
+
Every character is visited a bounded number of times: the last
|
|
199
|
+
non-blank character of the statement is tracked while walking forward,
|
|
200
|
+
so a long run of blank lines after an escape costs linear time.
|
|
201
|
+
"""
|
|
202
|
+
n = len(flat)
|
|
203
|
+
start = 0
|
|
204
|
+
depth = 0
|
|
205
|
+
i = 0
|
|
206
|
+
last_sig = -1 # last non-blank index of the current statement
|
|
207
|
+
esc_parity: tuple[int, bool] = (-1, False)
|
|
208
|
+
while i < n:
|
|
209
|
+
nl = flat.find("\n", i)
|
|
210
|
+
if nl < 0:
|
|
211
|
+
nl = n
|
|
212
|
+
if brackets:
|
|
213
|
+
for c in flat[i:nl]:
|
|
214
|
+
if c in "([{":
|
|
215
|
+
depth += 1
|
|
216
|
+
elif c in ")]}" and depth:
|
|
217
|
+
depth -= 1
|
|
218
|
+
k = nl - 1
|
|
219
|
+
while k >= i and flat[k] in _BLANK:
|
|
220
|
+
k -= 1
|
|
221
|
+
line_sig = k if k >= i else -1
|
|
222
|
+
if line_sig >= 0:
|
|
223
|
+
last_sig = line_sig
|
|
224
|
+
if nl >= n:
|
|
225
|
+
break
|
|
226
|
+
join = nl in joins or (brackets and depth > 0)
|
|
227
|
+
if not join and shell_esc is not None:
|
|
228
|
+
if skip_blank_continuations:
|
|
229
|
+
# Dockerfile: whitespace may follow the escape, and blank and
|
|
230
|
+
# comment lines inside a continuation are skipped.
|
|
231
|
+
k = last_sig if last_sig >= start else -1
|
|
232
|
+
else:
|
|
233
|
+
k = nl - 1
|
|
234
|
+
if k >= i and flat[k] == "\r":
|
|
235
|
+
k -= 1
|
|
236
|
+
if k < i:
|
|
237
|
+
k = -1
|
|
238
|
+
if k >= 0 and flat[k] == shell_esc:
|
|
239
|
+
if esc_parity[0] != k:
|
|
240
|
+
esc_parity = (k, _odd_run(flat, k, start, shell_esc))
|
|
241
|
+
join = esc_parity[1]
|
|
242
|
+
elif pipes and line_sig >= 0:
|
|
243
|
+
c = flat[line_sig]
|
|
244
|
+
join = c == "|" or (c == "&" and line_sig > i and flat[line_sig - 1] == "&")
|
|
245
|
+
if not join:
|
|
246
|
+
b.add(start, nl)
|
|
247
|
+
start = nl + 1
|
|
248
|
+
last_sig = -1
|
|
249
|
+
i = nl + 1
|
|
250
|
+
b.add(start, n)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
_BLANK = " \t\r\f\v"
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _odd_run(flat: str, k: int, floor: int, esc: str) -> bool:
|
|
257
|
+
"""Is the escape at ``k`` the last of an odd run (so not itself escaped)?"""
|
|
258
|
+
run = 0
|
|
259
|
+
while k - run >= floor and flat[k - run] == esc:
|
|
260
|
+
run += 1
|
|
261
|
+
return run % 2 == 1
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _sql(b: _Builder, flat: str) -> None:
|
|
265
|
+
start = 0
|
|
266
|
+
i = flat.find(";")
|
|
267
|
+
while i >= 0:
|
|
268
|
+
b.add(start, i + 1)
|
|
269
|
+
start = i + 1
|
|
270
|
+
i = flat.find(";", start)
|
|
271
|
+
b.add(start, len(flat))
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
# --- C family -------------------------------------------------------------------------
|
|
275
|
+
|
|
276
|
+
_JS_KEYWORD_EXPR = frozenset(
|
|
277
|
+
{"return", "yield", "await", "case", "typeof", "in", "of", "new", "delete", "void", "throw"}
|
|
278
|
+
)
|
|
279
|
+
_LINE_END_OPS = frozenset("=+-*%&|^<>?,.!~")
|
|
280
|
+
_ASI_LANGUAGES = frozenset({"javascript", "typescript", "go", "kotlin"})
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _is_word(c: str) -> bool:
|
|
284
|
+
return (c.isascii() and (c.isalnum() or c in "_$")) or c >= "\x80"
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
# Go and Rust write struct literals as ``Name{`` / ``Name {``; a brace after a
|
|
288
|
+
# name opens a block only in a statement led by one of these keywords.
|
|
289
|
+
_BLOCK_KEYWORDS = {
|
|
290
|
+
"go": frozenset(
|
|
291
|
+
{"if", "for", "switch", "select", "func", "else", "type", "struct", "interface"}
|
|
292
|
+
),
|
|
293
|
+
"rust": frozenset(
|
|
294
|
+
{
|
|
295
|
+
"fn",
|
|
296
|
+
"impl",
|
|
297
|
+
"if",
|
|
298
|
+
"else",
|
|
299
|
+
"match",
|
|
300
|
+
"loop",
|
|
301
|
+
"while",
|
|
302
|
+
"for",
|
|
303
|
+
"struct",
|
|
304
|
+
"enum",
|
|
305
|
+
"mod",
|
|
306
|
+
"trait",
|
|
307
|
+
"unsafe",
|
|
308
|
+
"union",
|
|
309
|
+
"extern",
|
|
310
|
+
"async",
|
|
311
|
+
"macro_rules",
|
|
312
|
+
"where",
|
|
313
|
+
"move",
|
|
314
|
+
}
|
|
315
|
+
),
|
|
316
|
+
}
|
|
317
|
+
_WORD = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
class _Leading:
|
|
321
|
+
"""Cache of "does the statement at ``start`` begin with a block keyword?"."""
|
|
322
|
+
|
|
323
|
+
def __init__(self, flat: str, language: str) -> None:
|
|
324
|
+
self.flat = flat
|
|
325
|
+
self.keywords = _BLOCK_KEYWORDS.get(language, frozenset())
|
|
326
|
+
self.start = -1
|
|
327
|
+
self.value = False
|
|
328
|
+
|
|
329
|
+
def __call__(self, start: int, stop: int) -> bool:
|
|
330
|
+
if start != self.start:
|
|
331
|
+
self.start = start
|
|
332
|
+
self.value = False
|
|
333
|
+
for count, m in enumerate(_WORD.finditer(self.flat, start, stop)):
|
|
334
|
+
if m.group() in self.keywords:
|
|
335
|
+
self.value = True
|
|
336
|
+
break
|
|
337
|
+
if count >= 5:
|
|
338
|
+
break
|
|
339
|
+
return self.value
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
_GO_HEADERS = frozenset({"if", "for", "switch", "select", "else"})
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _go_header(flat: str, start: int, stop: int) -> bool:
|
|
346
|
+
# In Go, ";" mostly separates the parts of an if/for/switch header,
|
|
347
|
+
# which stays one statement up to its "{".
|
|
348
|
+
m = _WORD.search(flat, start, stop)
|
|
349
|
+
return m is not None and m.group() in _GO_HEADERS
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _block_brace(flat: str, i: int, k: int, floor: int, language: str, leading: _Leading) -> bool:
|
|
353
|
+
"""Does the ``{`` at ``i`` open a block (rather than an object or struct literal)?
|
|
354
|
+
|
|
355
|
+
``k`` is the last non-blank index before it in the statement (or ``-1``).
|
|
356
|
+
"""
|
|
357
|
+
if k < floor:
|
|
358
|
+
return True
|
|
359
|
+
c = flat[k]
|
|
360
|
+
if c == ")":
|
|
361
|
+
return True
|
|
362
|
+
if c == ">" and k > floor and flat[k - 1] == "=":
|
|
363
|
+
return True
|
|
364
|
+
if language in _BLOCK_KEYWORDS:
|
|
365
|
+
# Go and Rust: a statement led by a block keyword opens a block
|
|
366
|
+
# ("for i := 0; i < n; i++ {", "if v[0] {"), unless the brace sits
|
|
367
|
+
# where a value goes; otherwise "Name{" is a struct literal.
|
|
368
|
+
if c in "=,(:":
|
|
369
|
+
return False
|
|
370
|
+
if language == "rust" and c == "|":
|
|
371
|
+
return True # a closure body: |x| { ... }
|
|
372
|
+
return leading(floor, i)
|
|
373
|
+
if _is_word(c):
|
|
374
|
+
s = k
|
|
375
|
+
while s > floor and _is_word(flat[s - 1]):
|
|
376
|
+
s -= 1
|
|
377
|
+
word = flat[s : k + 1]
|
|
378
|
+
if language in ("javascript", "typescript"):
|
|
379
|
+
return word not in _JS_KEYWORD_EXPR
|
|
380
|
+
return True
|
|
381
|
+
return c in ";}"
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _c_family(b: _Builder, flat: str, language: str) -> None:
|
|
385
|
+
n = len(flat)
|
|
386
|
+
asi = language in _ASI_LANGUAGES
|
|
387
|
+
leading = _Leading(flat, language)
|
|
388
|
+
scopes: list[list[str]] = [[]]
|
|
389
|
+
start: int | None = None
|
|
390
|
+
last_sig = -1 # last non-blank index of the current statement
|
|
391
|
+
next_sig = -1 # first non-blank index after the latest line break looked at
|
|
392
|
+
i = 0
|
|
393
|
+
while i < n:
|
|
394
|
+
c = flat[i]
|
|
395
|
+
if start is None:
|
|
396
|
+
if c in _WS:
|
|
397
|
+
i += 1
|
|
398
|
+
continue
|
|
399
|
+
start = i
|
|
400
|
+
last_sig = -1
|
|
401
|
+
cur = scopes[-1]
|
|
402
|
+
if c in "([":
|
|
403
|
+
cur.append(c)
|
|
404
|
+
elif c in ")]":
|
|
405
|
+
if cur:
|
|
406
|
+
cur.pop()
|
|
407
|
+
elif c == "{":
|
|
408
|
+
if _block_brace(flat, i, last_sig, start, language, leading):
|
|
409
|
+
b.add(start, i + 1)
|
|
410
|
+
start = None
|
|
411
|
+
scopes.append([])
|
|
412
|
+
else:
|
|
413
|
+
cur.append("{")
|
|
414
|
+
elif c == "}":
|
|
415
|
+
if cur and cur[-1] == "{":
|
|
416
|
+
cur.pop()
|
|
417
|
+
elif not cur and len(scopes) > 1:
|
|
418
|
+
b.add(start, i)
|
|
419
|
+
scopes.pop()
|
|
420
|
+
# "}" alone on its line is a statement; "});" or "} else {" go on.
|
|
421
|
+
j = i + 1
|
|
422
|
+
while j < n and flat[j] in " \t\r":
|
|
423
|
+
j += 1
|
|
424
|
+
if j >= n or flat[j] == "\n":
|
|
425
|
+
b.add(i, i + 1)
|
|
426
|
+
start = None
|
|
427
|
+
else:
|
|
428
|
+
start = i
|
|
429
|
+
last_sig = i
|
|
430
|
+
i += 1
|
|
431
|
+
continue
|
|
432
|
+
elif c == ";" and not cur and not (language == "go" and _go_header(flat, start, i)):
|
|
433
|
+
b.add(start, i + 1)
|
|
434
|
+
start = None
|
|
435
|
+
i += 1
|
|
436
|
+
continue
|
|
437
|
+
elif c == "\n" and not cur and asi:
|
|
438
|
+
if next_sig <= i:
|
|
439
|
+
j = i + 1
|
|
440
|
+
while j < n and flat[j] in _WS:
|
|
441
|
+
j += 1
|
|
442
|
+
next_sig = j
|
|
443
|
+
if not _continues(flat, start, last_sig, next_sig):
|
|
444
|
+
b.add(start, i)
|
|
445
|
+
start = None
|
|
446
|
+
i += 1
|
|
447
|
+
continue
|
|
448
|
+
if c not in _WS:
|
|
449
|
+
last_sig = i
|
|
450
|
+
i += 1
|
|
451
|
+
if start is not None:
|
|
452
|
+
b.add(start, n)
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def _continues(flat: str, start: int, k: int, j: int) -> bool:
|
|
456
|
+
"""Does the statement go on past a line break?
|
|
457
|
+
|
|
458
|
+
``k`` is its last non-blank index (or ``-1``); ``j`` is the first
|
|
459
|
+
non-blank index after the break.
|
|
460
|
+
"""
|
|
461
|
+
if k < start:
|
|
462
|
+
return False
|
|
463
|
+
c = flat[k]
|
|
464
|
+
if c in _LINE_END_OPS:
|
|
465
|
+
# An operator at the end of the line continues it, except x++ / x--.
|
|
466
|
+
return not (c in "+-" and k > start and flat[k - 1] == c)
|
|
467
|
+
if j >= len(flat):
|
|
468
|
+
return False
|
|
469
|
+
nxt = flat[j]
|
|
470
|
+
if nxt == "." and not flat.startswith("...", j):
|
|
471
|
+
return True
|
|
472
|
+
return flat.startswith(("?.", "?:", "??", "&&", "||"), j)
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
# --- Python ---------------------------------------------------------------------------
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
class _PyOffsets:
|
|
479
|
+
"""AST (line, UTF-8 byte column) to ``str`` offsets."""
|
|
480
|
+
|
|
481
|
+
def __init__(self, text: str, index: LineIndex) -> None:
|
|
482
|
+
self.text = text
|
|
483
|
+
self.index = index
|
|
484
|
+
self.lines = text.split("\n")
|
|
485
|
+
self.cache: dict[int, bool] = {}
|
|
486
|
+
|
|
487
|
+
def at(self, line: int, col: int) -> int:
|
|
488
|
+
base = self.index.line_start(line)
|
|
489
|
+
if line == 1 and self.text.startswith("\ufeff"):
|
|
490
|
+
base += 1 # the AST was parsed without the byte order mark
|
|
491
|
+
row = self.lines[line - 1]
|
|
492
|
+
if line == 1:
|
|
493
|
+
row = row.removeprefix("\ufeff")
|
|
494
|
+
ascii_row = self.cache.get(line)
|
|
495
|
+
if ascii_row is None:
|
|
496
|
+
ascii_row = row.isascii()
|
|
497
|
+
self.cache[line] = ascii_row
|
|
498
|
+
if ascii_row:
|
|
499
|
+
return base + col
|
|
500
|
+
return base + len(row.encode("utf-8", "surrogateescape")[:col].decode("utf-8", "ignore"))
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def _blocks(node: ast.AST) -> list[list[ast.stmt]]:
|
|
504
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
505
|
+
return [node.body]
|
|
506
|
+
if isinstance(node, (ast.If, ast.For, ast.AsyncFor, ast.While)):
|
|
507
|
+
return [node.body, node.orelse]
|
|
508
|
+
if isinstance(node, (ast.With, ast.AsyncWith)):
|
|
509
|
+
return [node.body]
|
|
510
|
+
if isinstance(node, (ast.Try, ast.TryStar)):
|
|
511
|
+
return [node.body, *[h.body for h in node.handlers], node.orelse, node.finalbody]
|
|
512
|
+
if isinstance(node, ast.Match):
|
|
513
|
+
return [c.body for c in node.cases]
|
|
514
|
+
return []
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def _python(b: _Builder, tree: ast.Module, text: str, index: LineIndex) -> None:
|
|
518
|
+
pos = _PyOffsets(text, index)
|
|
519
|
+
|
|
520
|
+
def start_of(node: ast.stmt) -> int:
|
|
521
|
+
decorators = getattr(node, "decorator_list", None)
|
|
522
|
+
if decorators:
|
|
523
|
+
first = decorators[0]
|
|
524
|
+
line_start = index.line_start(first.lineno)
|
|
525
|
+
at = text.rfind("@", line_start, pos.at(first.lineno, first.col_offset))
|
|
526
|
+
return at if at >= 0 else pos.at(first.lineno, first.col_offset)
|
|
527
|
+
return pos.at(node.lineno, node.col_offset)
|
|
528
|
+
|
|
529
|
+
def end_of(node: ast.stmt) -> int:
|
|
530
|
+
line = node.end_lineno or node.lineno
|
|
531
|
+
col = node.end_col_offset if node.end_col_offset is not None else 0
|
|
532
|
+
return pos.at(line, col)
|
|
533
|
+
|
|
534
|
+
# Explicit work stack: deep nesting cannot overflow the interpreter stack.
|
|
535
|
+
work: list[ast.stmt] = list(reversed(tree.body))
|
|
536
|
+
while work:
|
|
537
|
+
node = work.pop()
|
|
538
|
+
blocks = [blk for blk in _blocks(node) if blk]
|
|
539
|
+
start = start_of(node)
|
|
540
|
+
if not blocks:
|
|
541
|
+
b.add(start, end_of(node))
|
|
542
|
+
continue
|
|
543
|
+
if isinstance(node, ast.Match):
|
|
544
|
+
header_end = index.line_start(node.cases[0].pattern.lineno)
|
|
545
|
+
else:
|
|
546
|
+
header_end = start_of(blocks[0][0])
|
|
547
|
+
b.add(start, header_end)
|
|
548
|
+
cursor = header_end
|
|
549
|
+
children: list[ast.stmt] = []
|
|
550
|
+
for k, block in enumerate(blocks):
|
|
551
|
+
first = start_of(block[0])
|
|
552
|
+
if k > 0 or isinstance(node, ast.Match):
|
|
553
|
+
b.add(cursor, first) # "else:", "except E:", "case x:" and the like
|
|
554
|
+
children.extend(block)
|
|
555
|
+
cursor = end_of(block[-1])
|
|
556
|
+
work.extend(reversed(children))
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
# --- Entry point ----------------------------------------------------------------------
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def split(
|
|
563
|
+
text: str | None,
|
|
564
|
+
language: str,
|
|
565
|
+
result: LexResult,
|
|
566
|
+
masked: str,
|
|
567
|
+
*,
|
|
568
|
+
python_ast: ast.Module | None = None,
|
|
569
|
+
path: str | None = None,
|
|
570
|
+
) -> tuple[Statement, ...]:
|
|
571
|
+
"""The logical statements of ``text`` (see the module docstring)."""
|
|
572
|
+
if not text:
|
|
573
|
+
return ()
|
|
574
|
+
index = LineIndex(text)
|
|
575
|
+
flat = _flat(lexers.code_only(text, result), result)
|
|
576
|
+
if text.startswith("\ufeff"):
|
|
577
|
+
flat = " " + flat[1:] # a byte order mark is whitespace, never statement text
|
|
578
|
+
b = _Builder(text, masked, flat, index)
|
|
579
|
+
fam = lexers.family(language, path)
|
|
580
|
+
if language == "python" and fam == "python":
|
|
581
|
+
lone_cr = "\r" in text and text.replace("\r\n", "").count("\r") > 0
|
|
582
|
+
if python_ast is not None and not lone_cr:
|
|
583
|
+
_python(b, python_ast, text, index)
|
|
584
|
+
else:
|
|
585
|
+
_lines(b, flat, brackets=True, shell_esc="\\")
|
|
586
|
+
return b.done()
|
|
587
|
+
if fam == "c" or (fam == "sfc" and language in ("javascript", "typescript")):
|
|
588
|
+
_c_family(b, flat, language)
|
|
589
|
+
elif fam == "shell":
|
|
590
|
+
_lines(b, flat, joins=_joining_newlines(text, result), shell_esc="\\", pipes=True)
|
|
591
|
+
elif fam == "dockerfile":
|
|
592
|
+
_lines(
|
|
593
|
+
b,
|
|
594
|
+
flat,
|
|
595
|
+
joins=_joining_newlines(text, result),
|
|
596
|
+
shell_esc=lexers.docker_escape(text),
|
|
597
|
+
skip_blank_continuations=True,
|
|
598
|
+
)
|
|
599
|
+
elif fam == "yaml":
|
|
600
|
+
_lines(b, flat, joins=_joining_newlines(text, result))
|
|
601
|
+
elif fam == "toml":
|
|
602
|
+
_lines(b, flat, brackets=True)
|
|
603
|
+
elif fam == "sql":
|
|
604
|
+
_sql(b, flat)
|
|
605
|
+
else:
|
|
606
|
+
_lines(b, flat)
|
|
607
|
+
return b.done()
|