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.
Files changed (106) hide show
  1. codeveto/__init__.py +3 -0
  2. codeveto/__main__.py +8 -0
  3. codeveto/ai/__init__.py +19 -0
  4. codeveto/ai/harness.py +303 -0
  5. codeveto/ai/packets.py +855 -0
  6. codeveto/ai/policy.py +222 -0
  7. codeveto/ai/prompt.py +101 -0
  8. codeveto/ai/providers/__init__.py +178 -0
  9. codeveto/ai/providers/claude.py +247 -0
  10. codeveto/ai/providers/openai_compat.py +246 -0
  11. codeveto/ai/runner.py +293 -0
  12. codeveto/ai/verify.py +324 -0
  13. codeveto/anchor.py +211 -0
  14. codeveto/cli.py +247 -0
  15. codeveto/cli_explain.py +49 -0
  16. codeveto/cli_hook.py +31 -0
  17. codeveto/cli_init.py +254 -0
  18. codeveto/cli_mcp.py +29 -0
  19. codeveto/cli_packets.py +35 -0
  20. codeveto/cli_publish.py +29 -0
  21. codeveto/cli_review.py +362 -0
  22. codeveto/cli_rules.py +78 -0
  23. codeveto/cli_verify.py +47 -0
  24. codeveto/config.py +1229 -0
  25. codeveto/data/README.md +16 -0
  26. codeveto/data/ai-wire.schema.json +53 -0
  27. codeveto/data/prompts/system.md +57 -0
  28. codeveto/data/report-v1.schema.json +268 -0
  29. codeveto/data/templates/forgejo-codeveto.yml +104 -0
  30. codeveto/data/templates/github-codeveto.yml +18 -0
  31. codeveto/embedded.py +311 -0
  32. codeveto/engine.py +1570 -0
  33. codeveto/git.py +1549 -0
  34. codeveto/globs.py +348 -0
  35. codeveto/integrations/__init__.py +1 -0
  36. codeveto/integrations/hooks.py +327 -0
  37. codeveto/integrations/mcp.py +770 -0
  38. codeveto/integrations/mcp_ai.py +77 -0
  39. codeveto/integrations/prepush.py +222 -0
  40. codeveto/jsonsafe.py +60 -0
  41. codeveto/languages.py +539 -0
  42. codeveto/lexers.py +2560 -0
  43. codeveto/model.py +372 -0
  44. codeveto/publish/__init__.py +28 -0
  45. codeveto/publish/action.py +330 -0
  46. codeveto/publish/common.py +84 -0
  47. codeveto/publish/diff.py +208 -0
  48. codeveto/publish/event.py +241 -0
  49. codeveto/publish/forgejo.py +184 -0
  50. codeveto/publish/github.py +380 -0
  51. codeveto/publish/http.py +263 -0
  52. codeveto/publish/pull.py +218 -0
  53. codeveto/publish/untrusted.py +110 -0
  54. codeveto/py.typed +0 -0
  55. codeveto/redact.py +113 -0
  56. codeveto/render/__init__.py +64 -0
  57. codeveto/render/agent.py +43 -0
  58. codeveto/render/github.py +101 -0
  59. codeveto/render/json.py +23 -0
  60. codeveto/render/markdown.py +208 -0
  61. codeveto/render/safe.py +249 -0
  62. codeveto/render/sarif.py +217 -0
  63. codeveto/render/text.py +210 -0
  64. codeveto/report.py +252 -0
  65. codeveto/rules/__init__.py +84 -0
  66. codeveto/rules/agent.py +2972 -0
  67. codeveto/rules/base.py +1026 -0
  68. codeveto/rules/ci.py +1708 -0
  69. codeveto/rules/config.py +493 -0
  70. codeveto/rules/deps.py +1693 -0
  71. codeveto/rules/docker.py +479 -0
  72. codeveto/rules/examples/__init__.py +148 -0
  73. codeveto/rules/examples/agent.py +839 -0
  74. codeveto/rules/examples/ci.py +1046 -0
  75. codeveto/rules/examples/config.py +191 -0
  76. codeveto/rules/examples/deps.py +369 -0
  77. codeveto/rules/examples/docker.py +157 -0
  78. codeveto/rules/examples/go.py +241 -0
  79. codeveto/rules/examples/hygiene.py +466 -0
  80. codeveto/rules/examples/js.py +462 -0
  81. codeveto/rules/examples/python.py +595 -0
  82. codeveto/rules/examples/rust.py +268 -0
  83. codeveto/rules/examples/secrets.py +561 -0
  84. codeveto/rules/examples/security.py +608 -0
  85. codeveto/rules/examples/shell.py +174 -0
  86. codeveto/rules/examples/sql.py +194 -0
  87. codeveto/rules/examples/tests.py +497 -0
  88. codeveto/rules/go.py +328 -0
  89. codeveto/rules/hygiene.py +1094 -0
  90. codeveto/rules/js.py +768 -0
  91. codeveto/rules/python.py +1642 -0
  92. codeveto/rules/rust.py +209 -0
  93. codeveto/rules/secrets.py +1335 -0
  94. codeveto/rules/security.py +3680 -0
  95. codeveto/rules/shell.py +867 -0
  96. codeveto/rules/sql.py +629 -0
  97. codeveto/rules/tests.py +1404 -0
  98. codeveto/schema.py +384 -0
  99. codeveto/statements.py +607 -0
  100. codeveto/worktree.py +1176 -0
  101. codeveto/yamlish.py +1179 -0
  102. codeveto-0.1.0.dist-info/METADATA +253 -0
  103. codeveto-0.1.0.dist-info/RECORD +106 -0
  104. codeveto-0.1.0.dist-info/WHEEL +4 -0
  105. codeveto-0.1.0.dist-info/entry_points.txt +2 -0
  106. codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
codeveto/lexers.py ADDED
@@ -0,0 +1,2560 @@
1
+ """String and comment span lexers per language family (SPEC 5.5).
2
+
3
+ :func:`lex` returns a :class:`LexResult`: the top-level :class:`StringSpan` and
4
+ :class:`CommentSpan` values of a text in source order. Offsets are absolute
5
+ ``str`` indices into the text (``end`` exclusive); :class:`LineIndex` maps them
6
+ to 1-based ``(line, column)`` in Git line numbering. A string's
7
+ ``interpolations`` are code ranges (f-string fields, template ``${}``, shell
8
+ ``$(...)``) that may hold nested spans of their own.
9
+
10
+ Every lexer is a hand-written, single-pass scanner with an explicit frame
11
+ stack: it never recurses on input nesting, never raises, and runs in time
12
+ linear in the input. Nesting deeper than :data:`MAX_DEPTH` stops the lexer.
13
+ Any unterminated construct or desync sets ``partial`` with an issue naming the
14
+ line, so a caller never masks text silently. Output depends only on the input
15
+ text (identifier characters are ASCII word characters plus every non-ASCII
16
+ code point, never the interpreter's Unicode tables), so it is identical on
17
+ every supported Python version.
18
+
19
+ Families: Python; C-family (JavaScript/TypeScript with regex literals and JSX,
20
+ Go, Rust, Java, Kotlin); shell and Dockerfile; YAML, TOML and
21
+ requirements-style hash comments; SQL; JSON and JSONC; Vue/Svelte ``<script>``
22
+ blocks. Markdown and plain text have no spans.
23
+
24
+ Conventions:
25
+
26
+ - JavaScript regex literals, JSX text and SQL quoted identifiers are code, not
27
+ spans; they are only recognised so that quotes and comment markers inside
28
+ them are skipped. JSX is recognised in every JavaScript file and in
29
+ ``.tsx``, at expression start only.
30
+ - An interpolation range is the code alone; its ``${``/``{``/``$(`` and closing
31
+ delimiters, a Python ``!r`` conversion and a format spec are string content.
32
+ - A heredoc or YAML block scalar has no opening delimiter: its span is the
33
+ body (``start == content_start``); a heredoc's span ends with its
34
+ delimiter line. Dockerfile ``RUN <<EOF`` bodies are heredoc spans too.
35
+ - Comment spans never include the line break or a CR before it.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import bisect
41
+ import re
42
+ from collections import deque
43
+ from collections.abc import Iterator
44
+ from dataclasses import dataclass
45
+ from typing import Literal, NamedTuple, cast
46
+
47
+ __all__ = [
48
+ "MAX_DEPTH",
49
+ "CommentKind",
50
+ "CommentSpan",
51
+ "Interp",
52
+ "LexResult",
53
+ "LineIndex",
54
+ "ScriptBlock",
55
+ "Span",
56
+ "StringKind",
57
+ "StringSpan",
58
+ "code_only",
59
+ "docker_escape",
60
+ "family",
61
+ "flatten",
62
+ "lex",
63
+ "mask",
64
+ "position",
65
+ "script_blocks",
66
+ ]
67
+
68
+ MAX_DEPTH = 64
69
+ """Deepest nesting of strings inside interpolations (and of JSX elements)."""
70
+
71
+ _MAX_ISSUES = 20
72
+
73
+ StringKind = Literal["plain", "raw", "template", "fstring", "tstring", "heredoc", "char", "regex"]
74
+ CommentKind = Literal["line", "block", "doc"]
75
+
76
+
77
+ # --- Span types ----------------------------------------------------------------
78
+
79
+
80
+ @dataclass(frozen=True, slots=True)
81
+ class Interp:
82
+ """A code range inside a string (``start``/``end`` exclude the delimiters)."""
83
+
84
+ start: int
85
+ end: int
86
+ spans: tuple[StringSpan | CommentSpan, ...] = ()
87
+
88
+
89
+ @dataclass(frozen=True, slots=True)
90
+ class StringSpan:
91
+ """A string literal: ``start..end`` with prefix and delimiters, content inside."""
92
+
93
+ kind: StringKind
94
+ start: int
95
+ end: int
96
+ content_start: int
97
+ content_end: int
98
+ interpolations: tuple[Interp, ...] = ()
99
+
100
+
101
+ @dataclass(frozen=True, slots=True)
102
+ class CommentSpan:
103
+ """A comment: ``start..end`` with its markers (never the line break)."""
104
+
105
+ kind: CommentKind
106
+ start: int
107
+ end: int
108
+ content_start: int
109
+ content_end: int
110
+
111
+
112
+ Span = StringSpan | CommentSpan
113
+
114
+
115
+ @dataclass(frozen=True, slots=True)
116
+ class LexResult:
117
+ """Top-level spans in source order.
118
+
119
+ ``regions`` lists the code ranges of a file that is mostly markup (Vue and
120
+ Svelte ``<script>`` contents); ``None`` means the whole text is code.
121
+ """
122
+
123
+ spans: tuple[Span, ...] = ()
124
+ partial: bool = False
125
+ issues: tuple[str, ...] = ()
126
+ regions: tuple[tuple[int, int], ...] | None = None
127
+
128
+
129
+ _EMPTY = LexResult()
130
+
131
+
132
+ class LineIndex:
133
+ """Maps ``str`` offsets to 1-based ``(line, column)`` in Git line numbering.
134
+
135
+ Lines split on LF; a CR before LF belongs to its line, and a final LF does
136
+ not start a new line. Offsets past the end map to the last line.
137
+ """
138
+
139
+ __slots__ = ("_length", "_starts")
140
+
141
+ def __init__(self, text: str) -> None:
142
+ starts = [0]
143
+ find = text.find
144
+ i = find("\n")
145
+ while i >= 0:
146
+ starts.append(i + 1)
147
+ i = find("\n", i + 1)
148
+ if len(starts) > 1 and starts[-1] == len(text):
149
+ starts.pop()
150
+ self._starts = starts
151
+ self._length = len(text)
152
+
153
+ @property
154
+ def line_count(self) -> int:
155
+ return len(self._starts) if self._length else 0
156
+
157
+ def line_of(self, offset: int) -> int:
158
+ """1-based line holding ``offset``."""
159
+ return bisect.bisect_right(self._starts, offset)
160
+
161
+ def position(self, offset: int) -> tuple[int, int]:
162
+ """1-based ``(line, column)`` of ``offset``."""
163
+ line = bisect.bisect_right(self._starts, offset)
164
+ return line, offset - self._starts[line - 1] + 1
165
+
166
+ def line_start(self, line: int) -> int:
167
+ """Offset of the first character of 1-based ``line``."""
168
+ return self._starts[line - 1]
169
+
170
+ def offset(self, line: int, column: int) -> int:
171
+ """Offset of 1-based ``(line, column)``."""
172
+ return self._starts[line - 1] + column - 1
173
+
174
+
175
+ def position(text: str, offset: int) -> tuple[int, int]:
176
+ """1-based ``(line, column)`` of ``offset`` in ``text`` (Git numbering)."""
177
+ return LineIndex(text).position(offset)
178
+
179
+
180
+ # --- Shared scanning helpers -------------------------------------------------------
181
+
182
+
183
+ def _is_word(c: str) -> bool:
184
+ # Deliberately independent of the Unicode database (stable across Pythons).
185
+ return ("a" <= c <= "z") or ("A" <= c <= "Z") or ("0" <= c <= "9") or c == "_" or c >= "\x80"
186
+
187
+
188
+ _JS_WORD_RUN = re.compile(r"[A-Za-z0-9_$\x80-\U0010ffff]+")
189
+ _HSPACE = re.compile(r"[ \t]*")
190
+ _SPACE = re.compile(r"[ \t\r\n\f\v]*")
191
+ _NON_BREAK = re.compile(r"[^\r\n]")
192
+
193
+
194
+ class _Abort(Exception):
195
+ """Nesting limit reached; the lexer stops at ``pos``."""
196
+
197
+ def __init__(self, pos: int) -> None:
198
+ super().__init__(pos)
199
+ self.pos = pos
200
+
201
+
202
+ class _Base:
203
+ def __init__(self, text: str, start: int, end: int, index: LineIndex | None) -> None:
204
+ self.text = text
205
+ self.start = start
206
+ self.end = end
207
+ self.out: list[Span] = []
208
+ self.issues: list[str] = []
209
+ self.partial = False
210
+ self._index = index
211
+
212
+ @property
213
+ def index(self) -> LineIndex:
214
+ if self._index is None:
215
+ self._index = LineIndex(self.text)
216
+ return self._index
217
+
218
+ def issue(self, offset: int, message: str) -> None:
219
+ self.partial = True
220
+ if len(self.issues) < _MAX_ISSUES:
221
+ self.issues.append(f"line {self.index.line_of(offset)}: {message}")
222
+ elif len(self.issues) == _MAX_ISSUES:
223
+ self.issues.append("further lexer issues omitted")
224
+
225
+ def eol(self, pos: int) -> int:
226
+ e = self.text.find("\n", pos, self.end)
227
+ return self.end if e < 0 else e
228
+
229
+ def trim_cr(self, lo: int, e: int) -> int:
230
+ return e - 1 if e > lo and self.text[e - 1] == "\r" else e
231
+
232
+ def esc_skip(self, j: int) -> int:
233
+ # A backslash escapes one character; before CRLF it escapes both.
234
+ return j + 3 if self.text.startswith("\r\n", j + 1) else j + 2
235
+
236
+ def line_comment(self, pos: int, marker: int, kind: CommentKind = "line") -> CommentSpan:
237
+ e = self.trim_cr(pos, self.eol(pos))
238
+ return CommentSpan(kind, pos, e, min(pos + marker, e), e)
239
+
240
+ def result(self) -> LexResult:
241
+ return LexResult(tuple(self.out), self.partial, tuple(self.issues))
242
+
243
+
244
+ _RX_CACHE: dict[str, re.Pattern[str]] = {}
245
+
246
+
247
+ def _rx(chars: str) -> re.Pattern[str]:
248
+ pattern = _RX_CACHE.get(chars)
249
+ if pattern is None:
250
+ pattern = re.compile("[" + "".join(re.escape(c) for c in chars) + "]")
251
+ _RX_CACHE[chars] = pattern
252
+ return pattern
253
+
254
+
255
+ def _scan_quoted(
256
+ lx: _Base,
257
+ pos: int,
258
+ quote: str,
259
+ *,
260
+ escapes: bool,
261
+ multiline: bool,
262
+ limit: int | None = None,
263
+ ) -> tuple[int, int, bool]:
264
+ """Scan a simple quoted body starting after the opening quote.
265
+
266
+ Returns ``(content_end, end, terminated)``; nothing past ``limit``.
267
+ """
268
+ text = lx.text
269
+ end = lx.end if limit is None else limit
270
+ rx = _rx(quote + ("\\" if escapes else "") + ("" if multiline else "\n"))
271
+ i = pos
272
+ while True:
273
+ m = rx.search(text, i, end)
274
+ if m is None:
275
+ return end, end, False
276
+ j = m.start()
277
+ c = text[j]
278
+ if c == "\\":
279
+ i = lx.esc_skip(j)
280
+ continue
281
+ if c == "\n":
282
+ e = lx.trim_cr(pos, j)
283
+ return e, e, False
284
+ return j, j + len(quote), True
285
+
286
+
287
+ # --- Python ----------------------------------------------------------------------
288
+
289
+ _PY_PREFIX_KIND: dict[str, StringKind] = {
290
+ "r": "raw",
291
+ "u": "plain",
292
+ "b": "plain",
293
+ "br": "raw",
294
+ "rb": "raw",
295
+ "f": "fstring",
296
+ "fr": "fstring",
297
+ "rf": "fstring",
298
+ "t": "tstring",
299
+ "tr": "tstring",
300
+ "rt": "tstring",
301
+ }
302
+ _PY_TOP = _rx("#'\"\\")
303
+ _PY_INTERP = _rx("#'\"\\(){}[]!:")
304
+
305
+
306
+ class _PyCode:
307
+ __slots__ = ("depth", "interp_start", "spans")
308
+
309
+ def __init__(self, interp_start: int | None, spans: list[Span]) -> None:
310
+ self.interp_start = interp_start
311
+ self.spans = spans
312
+ self.depth = 0
313
+
314
+
315
+ class _PyStr:
316
+ __slots__ = ("cstart", "fields", "fmt", "interps", "kind", "quote", "raw", "start", "triple")
317
+
318
+ def __init__(
319
+ self, kind: StringKind, start: int, cstart: int, quote: str, triple: bool, raw: bool
320
+ ) -> None:
321
+ self.kind = kind
322
+ self.start = start
323
+ self.cstart = cstart
324
+ self.quote = quote
325
+ self.triple = triple
326
+ self.raw = raw
327
+ self.fmt = kind in ("fstring", "tstring")
328
+ self.interps: list[Interp] = []
329
+ # Open replacement fields, innermost last: "expr" (code frame above),
330
+ # "tail" (after a !conversion) or "spec" (in the format spec).
331
+ self.fields: list[str] = []
332
+
333
+
334
+ # PEP 263 cookie; names Python reads like UTF-8 or Latin-1 are allowed.
335
+ _COOKIE = re.compile(r"[ \t\f]*#[^\r\n]*?coding[:=][ \t]*([-A-Za-z0-9_.]+)")
336
+ _COOKIE_BLANK = re.compile(r"[ \t\f]*(?:#[^\r\n]*)?\r?(?:\n|$)")
337
+ _SAFE_ENCODINGS = frozenset(
338
+ {
339
+ "utf-8",
340
+ "utf8",
341
+ "u8",
342
+ "utf",
343
+ "cp65001",
344
+ "iso-8859-1",
345
+ "iso8859-1",
346
+ "8859",
347
+ "latin1",
348
+ "l1",
349
+ "cp819",
350
+ "ascii",
351
+ "us-ascii",
352
+ "us",
353
+ "646",
354
+ "cp367",
355
+ "cp1252",
356
+ "windows-1252",
357
+ }
358
+ )
359
+
360
+
361
+ def _normal_encoding(name: str) -> str:
362
+ # As the tokenizer's get_normal_name: utf-8* and latin-1* spellings.
363
+ name = name.lower().replace("_", "-")
364
+ if name == "utf-8" or name.startswith("utf-8-"):
365
+ return "utf-8"
366
+ for latin in ("latin-1", "iso-8859-1", "iso-latin-1"):
367
+ if name == latin or name.startswith(latin + "-"):
368
+ return "iso-8859-1"
369
+ return name
370
+
371
+
372
+ def _cookie_issue(text: str, start: int) -> tuple[int, str] | None:
373
+ """An encoding cookie on line 1 or 2 that is not ASCII-compatible."""
374
+ pos = start
375
+ for _line in range(2):
376
+ nl = text.find("\n", pos, pos + 4096)
377
+ stop = len(text) if nl < 0 else nl
378
+ m = _COOKIE.match(text, pos, min(stop, pos + 4096))
379
+ if m is not None:
380
+ name = _normal_encoding(m.group(1))
381
+ if name not in _SAFE_ENCODINGS:
382
+ return pos, m.group(1)
383
+ return None
384
+ if nl < 0 or _COOKIE_BLANK.match(text, pos, nl + 1) is None:
385
+ return None # a code line ends the search for a cookie
386
+ pos = nl + 1
387
+ return None
388
+
389
+
390
+ class _PythonLexer(_Base):
391
+ def run(self) -> LexResult:
392
+ stack: list[_PyCode | _PyStr] = [_PyCode(None, self.out)]
393
+ pos = self.start
394
+ cookie = _cookie_issue(self.text, self.start)
395
+ if cookie is not None:
396
+ self.issue(
397
+ cookie[0],
398
+ f"encoding cookie {cookie[1][:40]!r}: Python decodes this file differently",
399
+ )
400
+ try:
401
+ pos = self._loop(stack, pos)
402
+ self._finish(stack, self.end, report=True)
403
+ except _Abort as stop:
404
+ self.issue(stop.pos, f"nesting deeper than {MAX_DEPTH}; lexing stopped")
405
+ self._finish(stack, stop.pos, report=False)
406
+ return self.result()
407
+
408
+ def _prefix(self, pos: int, floor: int) -> tuple[int, StringKind, bool]:
409
+ text = self.text
410
+ for size in (2, 1):
411
+ s = pos - size
412
+ if s < floor:
413
+ continue
414
+ word = text[s:pos]
415
+ if not word.isascii():
416
+ continue
417
+ kind = _PY_PREFIX_KIND.get(word.lower())
418
+ if kind is not None and (s == floor or not _is_word(text[s - 1])):
419
+ return s, kind, "r" in word.lower()
420
+ return pos, "plain", False
421
+
422
+ def _loop(self, stack: list[_PyCode | _PyStr], pos: int) -> int:
423
+ text, end = self.text, self.end
424
+ while pos < end:
425
+ fr = stack[-1]
426
+ if isinstance(fr, _PyCode):
427
+ interp = fr.interp_start is not None
428
+ m = (_PY_INTERP if interp else _PY_TOP).search(text, pos, end)
429
+ if m is None:
430
+ return end
431
+ pos = m.start()
432
+ c = text[pos]
433
+ if c == "#":
434
+ span = self.line_comment(pos, 1)
435
+ fr.spans.append(span)
436
+ pos = span.end
437
+ elif c == "\\":
438
+ pos = self.esc_skip(pos)
439
+ elif c in "'\"":
440
+ start, kind, raw = self._prefix(pos, self.start)
441
+ triple = text.startswith(c * 3, pos)
442
+ width = 3 if triple else 1
443
+ stack.append(_PyStr(kind, start, pos + width, c, triple, raw))
444
+ if len(stack) > 2 * MAX_DEPTH + 1:
445
+ raise _Abort(pos)
446
+ pos += width
447
+ elif c in "([{":
448
+ fr.depth += 1
449
+ pos += 1
450
+ elif c in ")]":
451
+ fr.depth = max(fr.depth - 1, 0)
452
+ pos += 1
453
+ elif c == "}":
454
+ if fr.depth:
455
+ fr.depth -= 1
456
+ else:
457
+ owner = self._close_interp(stack, pos)
458
+ owner.fields.pop()
459
+ pos += 1
460
+ elif c == "!":
461
+ if fr.depth == 0 and not text.startswith("=", pos + 1):
462
+ self._close_interp(stack, pos).fields[-1] = "tail"
463
+ pos += 1
464
+ else:
465
+ pos += 2 if text.startswith("=", pos + 1) else 1
466
+ else: # ":"
467
+ if fr.depth == 0:
468
+ self._close_interp(stack, pos).fields[-1] = "spec"
469
+ pos += 1
470
+ continue
471
+ pos = self._string(stack, fr, pos)
472
+ return pos
473
+
474
+ def _string(self, stack: list[_PyCode | _PyStr], s: _PyStr, pos: int) -> int:
475
+ text, end = self.text, self.end
476
+ mode = s.fields[-1] if s.fields else "content"
477
+ chars = s.quote + "\\\n"
478
+ if s.fmt:
479
+ chars += "{}"
480
+ if mode == "tail":
481
+ chars += ":"
482
+ m = _rx(chars).search(text, pos, end)
483
+ if m is None:
484
+ return end
485
+ pos = m.start()
486
+ c = text[pos]
487
+ if c == "\\":
488
+ if not s.raw and text.startswith("N{", pos + 1):
489
+ close = text.find("}", pos + 3, min(end, pos + 200))
490
+ if close >= 0 and "\n" not in text[pos:close]:
491
+ return close + 1
492
+ return self.esc_skip(pos)
493
+ if c == "\n":
494
+ if s.triple:
495
+ return pos + 1
496
+ self.issue(s.start, "unterminated string")
497
+ e = self.trim_cr(s.cstart, pos)
498
+ self._close_string(stack, e, e)
499
+ return pos
500
+ if c == s.quote:
501
+ if not s.triple:
502
+ self._close_string(stack, pos, pos + 1)
503
+ return pos + 1
504
+ if text.startswith(c * 3, pos):
505
+ if s.fields:
506
+ self.issue(s.start, "unterminated replacement field")
507
+ self._close_string(stack, pos, pos + 3)
508
+ return pos + 3
509
+ return pos + 1
510
+ if c == "{":
511
+ if mode == "content" and text.startswith("{{", pos):
512
+ return pos + 2
513
+ s.fields.append("expr")
514
+ stack.append(_PyCode(pos + 1, []))
515
+ if len(stack) > 2 * MAX_DEPTH + 1:
516
+ raise _Abort(pos)
517
+ return pos + 1
518
+ if c == "}":
519
+ if mode == "content":
520
+ return pos + 2 if text.startswith("}}", pos) else pos + 1
521
+ s.fields.pop()
522
+ return pos + 1
523
+ # ":" after a conversion starts the format spec.
524
+ s.fields[-1] = "spec"
525
+ return pos + 1
526
+
527
+ def _close_interp(self, stack: list[_PyCode | _PyStr], pos: int) -> _PyStr:
528
+ fr = cast("_PyCode", stack.pop())
529
+ owner = cast("_PyStr", stack[-1])
530
+ owner.interps.append(Interp(fr.interp_start or 0, pos, tuple(fr.spans)))
531
+ return owner
532
+
533
+ def _close_string(self, stack: list[_PyCode | _PyStr], cend: int, end: int) -> None:
534
+ s = cast("_PyStr", stack.pop())
535
+ parent = cast("_PyCode", stack[-1])
536
+ parent.spans.append(StringSpan(s.kind, s.start, end, s.cstart, cend, tuple(s.interps)))
537
+
538
+ def _finish(self, stack: list[_PyCode | _PyStr], at: int, *, report: bool) -> None:
539
+ while len(stack) > 1:
540
+ fr = stack[-1]
541
+ if isinstance(fr, _PyStr):
542
+ if report:
543
+ self.issue(fr.start, "unterminated string")
544
+ self._close_string(stack, max(at, fr.cstart), max(at, fr.cstart))
545
+ else:
546
+ if report:
547
+ self.issue(fr.interp_start or at, "unterminated replacement field")
548
+ self._close_interp(stack, at)
549
+
550
+
551
+ # --- C family: JavaScript/TypeScript, Go, Rust, Java, Kotlin -------------------------
552
+
553
+ _REGEX_KEYWORDS = frozenset(
554
+ {
555
+ "return",
556
+ "typeof",
557
+ "instanceof",
558
+ "in",
559
+ "of",
560
+ "new",
561
+ "delete",
562
+ "void",
563
+ "throw",
564
+ "case",
565
+ "do",
566
+ "else",
567
+ "yield",
568
+ "await",
569
+ }
570
+ )
571
+ _JSX_NAME = re.compile(r"[A-Za-z0-9_$.:\-\x80-\U0010ffff]+")
572
+ _NESTED_COMMENT = re.compile(r"/\*|\*/")
573
+ _REGEX_BODY = re.compile(r"[\\/\[\]\n]")
574
+ _KOTLIN_IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
575
+ _HEX = frozenset("0123456789abcdefABCDEF")
576
+
577
+
578
+ _CONTROL_HEADS = frozenset({"if", "while", "for", "with"})
579
+ _BLOCK_WORDS = frozenset({"else", "do"})
580
+ _DOLLAR_RUN = re.compile(r"\$+")
581
+
582
+
583
+ class _CCode:
584
+ __slots__ = (
585
+ "braces",
586
+ "ctrl_close",
587
+ "depth",
588
+ "fence",
589
+ "fence_prev",
590
+ "interp_start",
591
+ "kind",
592
+ "obj_close",
593
+ "parens",
594
+ "spans",
595
+ )
596
+
597
+ def __init__(self, kind: str, spans: list[Span], start: int) -> None:
598
+ self.kind = kind # "top" | "interp" | "jsx"
599
+ self.spans = spans
600
+ self.depth = 0
601
+ self.fence = start
602
+ self.fence_prev = "start"
603
+ self.interp_start = start if kind == "interp" else None
604
+ # For each open "(": does it start an if/while/for/with header? A "/"
605
+ # after the ")" closing such a header starts a regex.
606
+ self.parens: list[bool] = []
607
+ self.ctrl_close = -1
608
+ # For each open "{": does it open an object literal? A "/" after its
609
+ # "}" is a division; after a block's "}" it starts a regex.
610
+ self.braces: list[bool] = []
611
+ self.obj_close = -1
612
+
613
+
614
+ class _CStr:
615
+ __slots__ = ("cstart", "dollars", "interps", "kind", "start", "style")
616
+
617
+ def __init__(
618
+ self, kind: StringKind, start: int, cstart: int, style: str, dollars: int = 1
619
+ ) -> None:
620
+ self.kind = kind
621
+ self.start = start
622
+ self.cstart = cstart
623
+ self.style = style # "js" | "kt" | "kt-raw"
624
+ self.dollars = dollars # Kotlin multi-dollar strings: "$$" opens a template
625
+ self.interps: list[Interp] = []
626
+
627
+
628
+ class _JsxTag:
629
+ __slots__ = ("spans", "start")
630
+
631
+ def __init__(self, start: int, spans: list[Span]) -> None:
632
+ self.start = start
633
+ self.spans = spans
634
+
635
+
636
+ class _JsxKids(_JsxTag):
637
+ __slots__ = ()
638
+
639
+
640
+ _CFrame = _CCode | _CStr | _JsxTag
641
+
642
+
643
+ class _CLexer(_Base):
644
+ def __init__(
645
+ self,
646
+ text: str,
647
+ start: int,
648
+ end: int,
649
+ index: LineIndex | None,
650
+ lang: str,
651
+ *,
652
+ jsx: bool = False,
653
+ ) -> None:
654
+ super().__init__(text, start, end, index)
655
+ self.lang = lang
656
+ self.js = lang in ("javascript", "typescript")
657
+ self.ts = lang == "typescript"
658
+ self.jsx = jsx and self.js
659
+ self.nested = lang in ("rust", "kotlin")
660
+ self.no_regex_before = 0
661
+ code = "/'\"{}"
662
+ if lang in ("javascript", "typescript", "go"):
663
+ code += "`"
664
+ if self.js:
665
+ code += "()"
666
+ if self.jsx:
667
+ code += "<"
668
+ self.code_rx = _rx(code)
669
+
670
+ def run(self) -> LexResult:
671
+ stack: list[_CFrame] = [_CCode("top", self.out, self.start)]
672
+ begin = self.start
673
+ if self.js and self.text.startswith("#!", begin):
674
+ # A hashbang line is a comment to JavaScript engines.
675
+ span = self.line_comment(begin, 2)
676
+ self.out.append(span)
677
+ begin = span.end
678
+ stack[0].fence = begin
679
+ try:
680
+ self._loop(stack, begin)
681
+ self._finish(stack, self.end, report=True)
682
+ except _Abort as stop:
683
+ self.issue(stop.pos, f"nesting deeper than {MAX_DEPTH}; lexing stopped")
684
+ self._finish(stack, stop.pos, report=False)
685
+ if self.lang in ("java", "kotlin"):
686
+ self._unicode_escapes()
687
+ return self.result()
688
+
689
+ def _push(self, stack: list[_CFrame], frame: _CFrame, pos: int) -> None:
690
+ stack.append(frame)
691
+ if len(stack) > 2 * MAX_DEPTH + 1:
692
+ raise _Abort(pos)
693
+
694
+ # The token before ``pos`` decides whether "/" starts a regex and "<" JSX.
695
+ def _prev(self, fr: _CCode, pos: int, *, inner: bool = False) -> str:
696
+ text = self.text
697
+ k = pos - 1
698
+ fence = fr.fence
699
+ while k >= fence and text[k] in " \t\r\n\f\v":
700
+ k -= 1
701
+ if k < fence:
702
+ return fr.fence_prev
703
+ c = text[k]
704
+ if _is_word(c) or c == "$":
705
+ s = k
706
+ while s > fence and (_is_word(text[s - 1]) or text[s - 1] == "$"):
707
+ s -= 1
708
+ if s > fence and text[s - 1] == ".":
709
+ return "value" # a property name: obj.return, a.of
710
+ return "op" if text[s : k + 1] in _REGEX_KEYWORDS else "value"
711
+ if c == ")":
712
+ return "op" if k == fr.ctrl_close else "value"
713
+ if c == "]":
714
+ return "value"
715
+ if c == "}":
716
+ return "value" if k == fr.obj_close else "op"
717
+ if c in "+-" and k - 1 >= fence and text[k - 1] == c and not inner:
718
+ # Postfix after a value on the same line; prefix otherwise
719
+ # (a line break before "++" makes it prefix, by ASI).
720
+ before = k - 2
721
+ while before >= fence and text[before] in " \t\f\v":
722
+ before -= 1
723
+ if before >= fence and text[before] in "\r\n":
724
+ return "op"
725
+ return "value" if self._prev(fr, k - 1, inner=True) == "value" else "op"
726
+ return "op"
727
+
728
+ def _object_brace(self, fr: _CCode, pos: int) -> bool:
729
+ # A "{" where a value goes opens an object literal; after ")", "=>",
730
+ # a statement end or a block keyword it opens a block.
731
+ text = self.text
732
+ k = pos - 1
733
+ while k >= fr.fence and text[k] in " \t\r\n\f\v":
734
+ k -= 1
735
+ if k < fr.fence:
736
+ if fr.fence_prev == "start":
737
+ return fr.kind != "top" # "${ {a: 1} }" or "{ {a: 1} }" in JSX
738
+ return fr.fence_prev == "op"
739
+ c = text[k]
740
+ if c in ")};{" or (c == ">" and k > fr.fence and text[k - 1] == "="):
741
+ return False
742
+ if _is_word(c) or c == "$":
743
+ return self._word_before(fr, pos) in _REGEX_KEYWORDS - _BLOCK_WORDS
744
+ return True
745
+
746
+ def _word_before(self, fr: _CCode, pos: int) -> str:
747
+ text = self.text
748
+ k = pos - 1
749
+ while k >= fr.fence and text[k] in " \t\r\n\f\v":
750
+ k -= 1
751
+ s = k
752
+ while s >= fr.fence and (_is_word(text[s]) or text[s] == "$"):
753
+ s -= 1
754
+ return text[s + 1 : k + 1]
755
+
756
+ def _emit(self, fr: _CCode, span: Span, *, value: bool = True) -> int:
757
+ if value:
758
+ fr.fence = span.end
759
+ fr.fence_prev = "value"
760
+ fr.spans.append(span)
761
+ return span.end
762
+
763
+ def _loop(self, stack: list[_CFrame], pos: int) -> None:
764
+ end = self.end
765
+ while pos < end:
766
+ fr = stack[-1]
767
+ if isinstance(fr, _CCode):
768
+ pos = self._code(stack, fr, pos)
769
+ elif isinstance(fr, _CStr):
770
+ pos = self._template(stack, fr, pos)
771
+ elif isinstance(fr, _JsxKids):
772
+ pos = self._jsx_kids(stack, fr, pos)
773
+ else:
774
+ pos = self._jsx_tag(stack, fr, pos)
775
+
776
+ def _code(self, stack: list[_CFrame], fr: _CCode, pos: int) -> int:
777
+ text, end = self.text, self.end
778
+ m = self.code_rx.search(text, pos, end)
779
+ if m is None:
780
+ return end
781
+ pos = m.start()
782
+ c = text[pos]
783
+ if c == "/":
784
+ return self._slash(fr, pos)
785
+ if c == '"':
786
+ return self._dquote(stack, fr, pos)
787
+ if c == "'":
788
+ return self._squote(fr, pos)
789
+ if c == "`":
790
+ if self.lang == "go":
791
+ close = text.find("`", pos + 1, end)
792
+ if close < 0:
793
+ self.issue(pos, "unterminated raw string")
794
+ return self._emit(fr, StringSpan("raw", pos, end, pos + 1, end))
795
+ return self._emit(fr, StringSpan("raw", pos, close + 1, pos + 1, close))
796
+ self._push(stack, _CStr("template", pos, pos + 1, "js"), pos)
797
+ return pos + 1
798
+ if c == "(":
799
+ fr.parens.append(self._word_before(fr, pos) in _CONTROL_HEADS)
800
+ return pos + 1
801
+ if c == ")":
802
+ if fr.parens and fr.parens.pop():
803
+ fr.ctrl_close = pos
804
+ return pos + 1
805
+ if c == "{":
806
+ if self.js:
807
+ fr.braces.append(self._object_brace(fr, pos))
808
+ if fr.kind != "top":
809
+ fr.depth += 1
810
+ return pos + 1
811
+ if c == "}":
812
+ if fr.kind == "top" or fr.depth:
813
+ if fr.braces and fr.braces.pop():
814
+ fr.obj_close = pos
815
+ if fr.depth:
816
+ fr.depth -= 1
817
+ return pos + 1
818
+ stack.pop()
819
+ if fr.kind == "interp":
820
+ owner = cast("_CStr", stack[-1])
821
+ owner.interps.append(Interp(fr.interp_start or 0, pos, tuple(fr.spans)))
822
+ return pos + 1
823
+ # "<": JSX at expression start.
824
+ return self._jsx_open(stack, fr, pos)
825
+
826
+ def _slash(self, fr: _CCode, pos: int) -> int:
827
+ text, end = self.text, self.end
828
+ nxt = text[pos + 1 : pos + 2]
829
+ if nxt == "/":
830
+ kind: CommentKind = "line"
831
+ marker = 2
832
+ if self.lang == "rust" and (
833
+ (text.startswith("///", pos) and not text.startswith("////", pos))
834
+ or text.startswith("//!", pos)
835
+ ):
836
+ kind, marker = "doc", 3
837
+ span = self.line_comment(pos, marker, kind)
838
+ return self._comment(fr, span)
839
+ if nxt == "*":
840
+ kind = "block"
841
+ marker = 2
842
+ if (
843
+ self.lang != "go"
844
+ and text.startswith("/**", pos)
845
+ and not text.startswith("/**/", pos)
846
+ ):
847
+ if not (self.lang == "rust" and text.startswith("/***", pos)):
848
+ kind, marker = "doc", 3
849
+ elif self.lang == "rust" and text.startswith("/*!", pos):
850
+ kind, marker = "doc", 3
851
+ close = self._block_end(pos)
852
+ if close is None:
853
+ self.issue(pos, "unterminated block comment")
854
+ span = CommentSpan(kind, pos, end, min(pos + marker, end), end)
855
+ else:
856
+ span = CommentSpan(kind, pos, close + 2, pos + marker, close)
857
+ return self._comment(fr, span)
858
+ if self.js and pos >= self.no_regex_before and self._prev(fr, pos) != "value":
859
+ close = self._regex_end(pos)
860
+ if close is None:
861
+ # No regex closes on this line: later slashes on it are not
862
+ # tried again, which keeps a line of "/[" linear.
863
+ self.no_regex_before = self.eol(pos)
864
+ else:
865
+ e = close + 1
866
+ m = _JS_WORD_RUN.match(text, e, end)
867
+ if m is not None:
868
+ e = m.end()
869
+ return self._emit(fr, StringSpan("regex", pos, e, pos + 1, close))
870
+ return pos + 1
871
+
872
+ def _comment(self, fr: _CCode, span: CommentSpan) -> int:
873
+ # Comments are transparent to the regex/JSX decision: the token before
874
+ # the comment still decides what follows it.
875
+ if self.js:
876
+ fr.fence_prev = self._prev(fr, span.start)
877
+ fr.fence = span.end
878
+ fr.spans.append(span)
879
+ return span.end
880
+
881
+ def _block_end(self, pos: int) -> int | None:
882
+ text, end = self.text, self.end
883
+ if not self.nested:
884
+ close = text.find("*/", pos + 2, end)
885
+ return None if close < 0 else close
886
+ depth = 1
887
+ i = pos + 2
888
+ while True:
889
+ m = _NESTED_COMMENT.search(text, i, end)
890
+ if m is None:
891
+ return None
892
+ if m.group() == "/*":
893
+ depth += 1
894
+ else:
895
+ depth -= 1
896
+ if depth == 0:
897
+ return m.start()
898
+ i = m.end()
899
+
900
+ def _regex_end(self, pos: int) -> int | None:
901
+ text, end = self.text, self.end
902
+ i = pos + 1
903
+ in_class = False
904
+ while True:
905
+ m = _REGEX_BODY.search(text, i, end)
906
+ if m is None:
907
+ return None
908
+ j = m.start()
909
+ c = text[j]
910
+ if c == "\\":
911
+ if text[j + 1 : j + 2] in ("\n", "\r", ""):
912
+ return None
913
+ i = j + 2
914
+ elif c == "\n":
915
+ return None
916
+ elif c == "[":
917
+ in_class = True
918
+ i = j + 1
919
+ elif c == "]":
920
+ in_class = False
921
+ i = j + 1
922
+ elif in_class:
923
+ i = j + 1
924
+ else:
925
+ return j
926
+
927
+ def _rust_prefix(self, pos: int) -> tuple[str, int]:
928
+ # Letters right before ``pos`` that form a Rust string prefix.
929
+ text = self.text
930
+ for size in (2, 1):
931
+ s = pos - size
932
+ if s < self.start:
933
+ continue
934
+ word = text[s:pos]
935
+ if word in ("br", "cr", "r", "b", "c") and (
936
+ s == self.start or not _is_word(text[s - 1])
937
+ ):
938
+ return word, s
939
+ return "", pos
940
+
941
+ def _dquote(self, stack: list[_CFrame], fr: _CCode, pos: int) -> int:
942
+ text, end = self.text, self.end
943
+ lang = self.lang
944
+ if lang == "rust":
945
+ k = pos
946
+ while k > self.start and text[k - 1] == "#":
947
+ k -= 1
948
+ hashes = pos - k
949
+ prefix, pstart = self._rust_prefix(k)
950
+ if prefix in ("r", "br", "cr"):
951
+ delim = '"' + "#" * hashes
952
+ close = text.find(delim, pos + 1, end)
953
+ if close < 0:
954
+ self.issue(pstart, "unterminated raw string")
955
+ return self._emit(fr, StringSpan("raw", pstart, end, pos + 1, end))
956
+ return self._emit(fr, StringSpan("raw", pstart, close + len(delim), pos + 1, close))
957
+ start = pstart if hashes == 0 and prefix in ("b", "c") else pos
958
+ cend, e, ok = _scan_quoted(self, pos + 1, '"', escapes=True, multiline=True)
959
+ if not ok:
960
+ self.issue(start, "unterminated string")
961
+ return self._emit(fr, StringSpan("plain", start, e, pos + 1, cend))
962
+ if lang == "kotlin":
963
+ # A multi-dollar prefix ($$"...") makes "$$" the template opener.
964
+ k = pos
965
+ while k > self.start and text[k - 1] == "$":
966
+ k -= 1
967
+ dollars = pos - k if pos - k >= 2 else 1
968
+ start = k if dollars > 1 else pos
969
+ if text.startswith('"""', pos):
970
+ self._push(stack, _CStr("raw", start, pos + 3, "kt-raw", dollars), pos)
971
+ return pos + 3
972
+ self._push(stack, _CStr("plain", start, pos + 1, "kt", dollars), pos)
973
+ return pos + 1
974
+ if lang == "java" and text.startswith('"""', pos):
975
+ close = self._text_block_end(pos + 3)
976
+ if close is None:
977
+ self.issue(pos, "unterminated text block")
978
+ return self._emit(fr, StringSpan("plain", pos, end, pos + 3, end))
979
+ return self._emit(fr, StringSpan("plain", pos, close + 3, pos + 3, close))
980
+ cend, e, ok = _scan_quoted(self, pos + 1, '"', escapes=True, multiline=False)
981
+ if not ok:
982
+ self.issue(pos, "unterminated string")
983
+ return self._emit(fr, StringSpan("plain", pos, e, pos + 1, cend))
984
+
985
+ def _text_block_end(self, i: int) -> int | None:
986
+ text, end = self.text, self.end
987
+ rx = _rx('"\\')
988
+ while True:
989
+ m = rx.search(text, i, end)
990
+ if m is None:
991
+ return None
992
+ j = m.start()
993
+ if text[j] == "\\":
994
+ i = self.esc_skip(j)
995
+ elif text.startswith('"""', j):
996
+ return j
997
+ else:
998
+ i = j + 1
999
+
1000
+ def _squote(self, fr: _CCode, pos: int) -> int:
1001
+ text, end = self.text, self.end
1002
+ if self.js:
1003
+ cend, e, ok = _scan_quoted(self, pos + 1, "'", escapes=True, multiline=False)
1004
+ if not ok:
1005
+ self.issue(pos, "unterminated string")
1006
+ return self._emit(fr, StringSpan("plain", pos, e, pos + 1, cend))
1007
+ start = pos
1008
+ if self.lang == "rust":
1009
+ prefix, pstart = self._rust_prefix(pos)
1010
+ if prefix == "b":
1011
+ start = pstart
1012
+ nxt = text[pos + 1 : pos + 2]
1013
+ if nxt != "\\" and not (
1014
+ pos + 2 < end and text[pos + 2] == "'" and nxt not in ("\n", "\r", "")
1015
+ ):
1016
+ return pos + 1 # a lifetime or loop label
1017
+ cend, e, ok = _scan_quoted(self, pos + 1, "'", escapes=True, multiline=False)
1018
+ if not ok:
1019
+ self.issue(pos, "unterminated character literal")
1020
+ return self._emit(fr, StringSpan("char", start, e, pos + 1, cend))
1021
+
1022
+ def _template(self, stack: list[_CFrame], s: _CStr, pos: int) -> int:
1023
+ text, end = self.text, self.end
1024
+ style = s.style
1025
+ if style == "js":
1026
+ chars = "`\\$"
1027
+ elif style == "kt":
1028
+ chars = '"\\$\n'
1029
+ else:
1030
+ chars = '"$'
1031
+ m = _rx(chars).search(text, pos, end)
1032
+ if m is None:
1033
+ return end
1034
+ pos = m.start()
1035
+ c = text[pos]
1036
+ if c == "\\":
1037
+ return self.esc_skip(pos)
1038
+ if c == "$":
1039
+ if style == "js":
1040
+ if text.startswith("{", pos + 1):
1041
+ self._push(stack, _CCode("interp", [], pos + 2), pos)
1042
+ return pos + 2
1043
+ return pos + 1
1044
+ run = _DOLLAR_RUN.match(text, pos, end)
1045
+ after = pos + 1 if run is None else run.end()
1046
+ if after - pos < s.dollars:
1047
+ return after
1048
+ if text.startswith("{", after):
1049
+ self._push(stack, _CCode("interp", [], after + 1), pos)
1050
+ return after + 1
1051
+ m2 = _KOTLIN_IDENT.match(text, after, end)
1052
+ if m2 is not None:
1053
+ s.interps.append(Interp(after, m2.end()))
1054
+ return m2.end()
1055
+ return after
1056
+ if c == "\n":
1057
+ self.issue(s.start, "unterminated string")
1058
+ e = self.trim_cr(s.cstart, pos)
1059
+ self._close_str(stack, e, e)
1060
+ return pos
1061
+ if style == "kt-raw":
1062
+ if not text.startswith('"""', pos):
1063
+ return pos + 1
1064
+ run = pos + 3
1065
+ while run < end and text[run] == '"':
1066
+ run += 1
1067
+ self._close_str(stack, run - 3, run)
1068
+ return run
1069
+ self._close_str(stack, pos, pos + 1)
1070
+ return pos + 1
1071
+
1072
+ def _close_str(self, stack: list[_CFrame], cend: int, end: int) -> None:
1073
+ s = cast("_CStr", stack.pop())
1074
+ parent = cast("_CCode", stack[-1])
1075
+ self._emit(parent, StringSpan(s.kind, s.start, end, s.cstart, cend, tuple(s.interps)))
1076
+
1077
+ def _jsx_open(self, stack: list[_CFrame], fr: _CCode, pos: int) -> int:
1078
+ text, end = self.text, self.end
1079
+ if self._prev(fr, pos) == "value":
1080
+ return pos + 1
1081
+ nxt = text[pos + 1 : pos + 2]
1082
+ if nxt == ">":
1083
+ self._push(stack, _JsxKids(pos, fr.spans), pos)
1084
+ return pos + 2
1085
+ if not nxt or not (_is_word(nxt) or nxt == "$") or "0" <= nxt <= "9":
1086
+ return pos + 1
1087
+ m = _JSX_NAME.match(text, pos + 1, end)
1088
+ if m is None:
1089
+ return pos + 1
1090
+ f = _SPACE.match(text, m.end(), end).end() # type: ignore[union-attr]
1091
+ c2 = text[f : f + 1]
1092
+ if not c2 or not (c2 in ">/{" or _is_word(c2) or c2 == "$"):
1093
+ return pos + 1
1094
+ if self.ts and text.startswith("extends", f) and not _is_word(text[f + 7 : f + 8] or " "):
1095
+ return pos + 1
1096
+ self._push(stack, _JsxTag(pos, fr.spans), pos)
1097
+ return m.end()
1098
+
1099
+ def _jsx_done(self, stack: list[_CFrame], e: int) -> None:
1100
+ top = stack[-1]
1101
+ if isinstance(top, _CCode):
1102
+ top.fence = e
1103
+ top.fence_prev = "value"
1104
+
1105
+ def _jsx_tag(self, stack: list[_CFrame], fr: _JsxTag, pos: int) -> int:
1106
+ text, end = self.text, self.end
1107
+ m = _rx("{\"'/>").search(text, pos, end)
1108
+ if m is None:
1109
+ return end
1110
+ pos = m.start()
1111
+ c = text[pos]
1112
+ if c == "{":
1113
+ self._push(stack, _CCode("jsx", fr.spans, pos + 1), pos)
1114
+ return pos + 1
1115
+ if c in "\"'":
1116
+ close = text.find(c, pos + 1, end)
1117
+ if close < 0:
1118
+ self.issue(pos, "unterminated JSX attribute string")
1119
+ fr.spans.append(StringSpan("plain", pos, end, pos + 1, end))
1120
+ return end
1121
+ fr.spans.append(StringSpan("plain", pos, close + 1, pos + 1, close))
1122
+ return close + 1
1123
+ if c == "/":
1124
+ if text.startswith("/>", pos):
1125
+ stack.pop()
1126
+ self._jsx_done(stack, pos + 2)
1127
+ return pos + 2
1128
+ return pos + 1
1129
+ stack.pop()
1130
+ stack.append(_JsxKids(fr.start, fr.spans))
1131
+ return pos + 1
1132
+
1133
+ def _jsx_kids(self, stack: list[_CFrame], fr: _JsxKids, pos: int) -> int:
1134
+ text, end = self.text, self.end
1135
+ m = _rx("{<").search(text, pos, end)
1136
+ if m is None:
1137
+ return end
1138
+ pos = m.start()
1139
+ if text[pos] == "{":
1140
+ self._push(stack, _CCode("jsx", fr.spans, pos + 1), pos)
1141
+ return pos + 1
1142
+ nxt = text[pos + 1 : pos + 2]
1143
+ if nxt == "/":
1144
+ close = text.find(">", pos + 2, end)
1145
+ if close < 0:
1146
+ return end
1147
+ stack.pop()
1148
+ self._jsx_done(stack, close + 1)
1149
+ return close + 1
1150
+ if nxt == ">":
1151
+ self._push(stack, _JsxKids(pos, fr.spans), pos)
1152
+ return pos + 2
1153
+ if nxt and (_is_word(nxt) or nxt == "$"):
1154
+ m2 = _JSX_NAME.match(text, pos + 1, end)
1155
+ self._push(stack, _JsxTag(pos, fr.spans), pos)
1156
+ return pos + 1 if m2 is None else m2.end()
1157
+ return pos + 1
1158
+
1159
+ def _unicode_escapes(self) -> None:
1160
+ """Java (and Kotlin) read ``\\uXXXX`` escapes the lexer does not decode.
1161
+
1162
+ One outside a string or comment, or one decoding to a line break,
1163
+ quote, ``*``, ``/`` or backslash, can move a comment or string boundary
1164
+ the compiler sees, so the result is partial.
1165
+ """
1166
+ text, end = self.text, self.end
1167
+ pos = text.find("\\u", self.start, end)
1168
+ if pos < 0:
1169
+ return
1170
+ masked = mask(text, LexResult(tuple(self.out)))
1171
+ reported = 0
1172
+ while pos >= 0 and reported < 3:
1173
+ run = 1
1174
+ while pos - run >= self.start and text[pos - run] == "\\":
1175
+ run += 1
1176
+ u = pos + 1
1177
+ while u < end and text[u] == "u":
1178
+ u += 1
1179
+ digits = text[u : u + 4]
1180
+ if run % 2 == 1 and len(digits) == 4 and all(c in _HEX for c in digits):
1181
+ decoded = chr(int(digits, 16))
1182
+ if masked[pos] != " " or decoded in "\n\r\"'*/\\":
1183
+ self.issue(pos, f"\\u{digits} escape the compiler decodes before lexing")
1184
+ reported += 1
1185
+ pos = text.find("\\u", u, end)
1186
+
1187
+ def _finish(self, stack: list[_CFrame], at: int, *, report: bool) -> None:
1188
+ while len(stack) > 1:
1189
+ fr = stack[-1]
1190
+ if isinstance(fr, _CStr):
1191
+ if report:
1192
+ self.issue(fr.start, "unterminated string")
1193
+ e = max(at, fr.cstart)
1194
+ self._close_str(stack, e, e)
1195
+ elif isinstance(fr, _CCode):
1196
+ stack.pop()
1197
+ if fr.kind == "interp":
1198
+ if report:
1199
+ self.issue(fr.interp_start or at, "unterminated interpolation")
1200
+ owner = cast("_CStr", stack[-1])
1201
+ owner.interps.append(Interp(fr.interp_start or 0, at, tuple(fr.spans)))
1202
+ elif report:
1203
+ self.issue(fr.fence, "unterminated JSX expression")
1204
+ else:
1205
+ stack.pop()
1206
+ if report:
1207
+ self.issue(fr.start, "unterminated JSX element")
1208
+
1209
+
1210
+ # --- Shell and Dockerfile ---------------------------------------------------------
1211
+
1212
+ _HEREDOC_STOP = frozenset(" \t\r\n;&|<>()")
1213
+ _SHELL_WORD_START = frozenset(" \t\n;&|()<>`")
1214
+ _SHELL_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*|[0-9]|[@*#?$!\-]")
1215
+
1216
+
1217
+ _CASE_WORD = re.compile(r"(?<![A-Za-z0-9_$])(?:case|esac)(?![A-Za-z0-9_])")
1218
+
1219
+
1220
+ class _SCode:
1221
+ __slots__ = (
1222
+ "case_open",
1223
+ "case_scan",
1224
+ "depth",
1225
+ "docker",
1226
+ "interp_start",
1227
+ "kind",
1228
+ "limit",
1229
+ "shell",
1230
+ "spans",
1231
+ )
1232
+
1233
+ def __init__(
1234
+ self,
1235
+ kind: str,
1236
+ spans: list[Span],
1237
+ limit: int,
1238
+ *,
1239
+ interp_start: int | None = None,
1240
+ docker: bool = False,
1241
+ shell: bool = True,
1242
+ ) -> None:
1243
+ self.kind = kind # "top" | "cmd" | "arith" | "param" | "tick"
1244
+ self.spans = spans
1245
+ self.limit = limit
1246
+ self.interp_start = interp_start
1247
+ self.docker = docker
1248
+ self.shell = shell
1249
+ self.depth = 0
1250
+ # Inside $( ... ): open "case" statements, whose "pat)" does not close
1251
+ # the substitution, and how far the text was scanned for them.
1252
+ self.case_open = 0
1253
+ self.case_scan = -1
1254
+
1255
+
1256
+ class _SStr:
1257
+ __slots__ = ("close_at", "cstart", "docker", "interps", "kind", "limit", "shell", "start")
1258
+
1259
+ def __init__(
1260
+ self,
1261
+ kind: str,
1262
+ start: int,
1263
+ cstart: int,
1264
+ limit: int,
1265
+ *,
1266
+ close_at: int | None = None,
1267
+ docker: bool = False,
1268
+ shell: bool = True,
1269
+ ) -> None:
1270
+ self.kind = kind # "dq" | "heredoc"
1271
+ self.start = start
1272
+ self.cstart = cstart
1273
+ self.limit = limit # for a heredoc body: the start of its delimiter line
1274
+ self.close_at = close_at # for a heredoc body: the end of its delimiter line
1275
+ self.docker = docker
1276
+ self.shell = shell
1277
+ self.interps: list[Interp] = []
1278
+
1279
+
1280
+ _SFrame = _SCode | _SStr
1281
+
1282
+
1283
+ def _sink(fr: _SFrame) -> list[Span]:
1284
+ # Spans found in a shell frame go to the nearest code frame's list.
1285
+ if not isinstance(fr, _SCode):
1286
+ raise TypeError("a string frame holds interpolations, not spans")
1287
+ return fr.spans
1288
+
1289
+
1290
+ class _ShellLexer(_Base):
1291
+ """POSIX shell. :meth:`instruction` lexes one Dockerfile instruction body.
1292
+
1293
+ In Dockerfile mode (frames with ``docker`` set) an escape character before
1294
+ a line break continues the instruction, blank and comment lines inside a
1295
+ continuation are skipped, any other line break ends the instruction, and
1296
+ without ``shell`` (exec form, non-RUN instructions, non-POSIX shells) only
1297
+ quotes, ``$`` expansions in double quotes and heredocs are recognised.
1298
+ """
1299
+
1300
+ def __init__(self, text: str, start: int, end: int, index: LineIndex | None) -> None:
1301
+ super().__init__(text, start, end, index)
1302
+ self.pending: deque[tuple[str, bool, bool, int]] = deque()
1303
+ self.esc = "\\"
1304
+ self._eol_cache = (-1, -2)
1305
+
1306
+ def run(self) -> LexResult:
1307
+ stack: list[_SFrame] = [_SCode("top", self.out, self.end)]
1308
+ try:
1309
+ pos = self._loop(stack, self.start)
1310
+ self._close_above(stack, pos, report=True)
1311
+ self._report_pending()
1312
+ except _Abort as stop:
1313
+ self.issue(stop.pos, f"nesting deeper than {MAX_DEPTH}; lexing stopped")
1314
+ self._close_above(stack, stop.pos, report=False)
1315
+ return self.result()
1316
+
1317
+ def instruction(self, pos: int, *, shell: bool) -> int:
1318
+ """Lex one Dockerfile instruction body from ``pos``; return where the next starts."""
1319
+ stack: list[_SFrame] = [_SCode("top", self.out, self.end, docker=True, shell=shell)]
1320
+ try:
1321
+ pos = self._loop(stack, pos)
1322
+ self._close_above(stack, pos, report=True)
1323
+ except _Abort as stop:
1324
+ self.issue(stop.pos, f"nesting deeper than {MAX_DEPTH}; lexing stopped")
1325
+ self._close_above(stack, stop.pos, report=False)
1326
+ return self.end
1327
+ return pos
1328
+
1329
+ def _report_pending(self) -> None:
1330
+ for _delim, _strip, _quoted, op in self.pending:
1331
+ self.issue(op, "heredoc without a body")
1332
+ self.pending.clear()
1333
+
1334
+ def _push(self, stack: list[_SFrame], frame: _SFrame, pos: int) -> None:
1335
+ stack.append(frame)
1336
+ if len(stack) > 2 * MAX_DEPTH + 1:
1337
+ raise _Abort(pos)
1338
+
1339
+ def _chars(self, fr: _SFrame) -> str:
1340
+ esc = self.esc if fr.docker else "\\"
1341
+ if isinstance(fr, _SStr):
1342
+ if fr.kind == "heredoc":
1343
+ return "\\$`"
1344
+ chars = '"$' + esc + ("`" if fr.shell else "")
1345
+ elif fr.kind == "param":
1346
+ chars = "'\"${}" + esc + ("`" if fr.shell else "")
1347
+ elif fr.kind == "arith":
1348
+ chars = "'\"$`()" + esc
1349
+ elif not fr.shell:
1350
+ chars = "'\"<" + esc
1351
+ else:
1352
+ chars = "#'\"$`()<\n" + esc
1353
+ if fr.docker:
1354
+ chars += "\n"
1355
+ return chars
1356
+
1357
+ def _loop(self, stack: list[_SFrame], pos: int) -> int:
1358
+ text = self.text
1359
+ while True:
1360
+ fr = stack[-1]
1361
+ limit = fr.limit
1362
+ if pos >= limit:
1363
+ if len(stack) == 1:
1364
+ return pos
1365
+ pos = limit
1366
+ if isinstance(fr, _SStr) and fr.kind == "heredoc":
1367
+ pos = self._close_heredoc(stack, fr)
1368
+ continue
1369
+ if limit < self.end:
1370
+ # An expansion left open at the end of a heredoc body.
1371
+ self.issue(pos, "unterminated expansion in heredoc")
1372
+ self._close_one(stack, pos, pos)
1373
+ continue
1374
+ return pos
1375
+ m = _rx(self._chars(fr)).search(text, pos, limit)
1376
+ if m is None:
1377
+ pos = limit
1378
+ continue
1379
+ pos = m.start()
1380
+ c = text[pos]
1381
+ if fr.docker:
1382
+ if c == "\n":
1383
+ pos, done = self._docker_newline(stack, pos)
1384
+ if done:
1385
+ return pos
1386
+ continue
1387
+ if c == self.esc:
1388
+ sink = fr.spans if isinstance(fr, _SCode) else None
1389
+ cont = self._continuation(pos, sink)
1390
+ pos = self.esc_skip(pos) if cont is None else cont
1391
+ continue
1392
+ if isinstance(fr, _SStr):
1393
+ pos = self._dq(stack, fr, pos, c)
1394
+ else:
1395
+ pos = self._code(stack, fr, pos, c)
1396
+
1397
+ def _docker_newline(self, stack: list[_SFrame], pos: int) -> tuple[int, bool]:
1398
+ # A line break that is not continued ends the instruction; heredoc
1399
+ # bodies introduced on it follow.
1400
+ self._close_above(stack, self.trim_cr(self.start, pos), report=True)
1401
+ if self.pending:
1402
+ return self._heredoc(stack, pos), False
1403
+ return pos + 1, True
1404
+
1405
+ def _continuation(self, pos: int, sink: list[Span] | None) -> int | None:
1406
+ # ``sink`` receives the comment lines skipped; inside a quoted string
1407
+ # (``None``) they are part of the string's range.
1408
+ text, end = self.text, self.end
1409
+ m = _HSPACE.match(text, pos + 1, end)
1410
+ j = m.end() if m is not None else pos + 1
1411
+ if text.startswith("\r\n", j):
1412
+ j += 1
1413
+ if j >= end:
1414
+ return end
1415
+ if text[j] != "\n":
1416
+ return None
1417
+ return self._skip_continued(j + 1, sink)
1418
+
1419
+ def _skip_continued(self, p: int, sink: list[Span] | None) -> int:
1420
+ # Blank and comment lines inside a continuation are dropped by Docker.
1421
+ text, end = self.text, self.end
1422
+ while p < end:
1423
+ m = _HSPACE.match(text, p, end)
1424
+ j = m.end() if m is not None else p
1425
+ if text.startswith("\r\n", j):
1426
+ p = j + 2
1427
+ elif j < end and text[j] == "\n":
1428
+ p = j + 1
1429
+ elif j < end and text[j] == "#":
1430
+ if sink is not None:
1431
+ sink.append(self.line_comment(j, 1))
1432
+ p = min(self.eol(j) + 1, end)
1433
+ else:
1434
+ return p
1435
+ return p
1436
+
1437
+ def _in_case(self, fr: _SCode, pos: int) -> bool:
1438
+ """Is the ``)`` at ``pos`` a case pattern end inside this ``$( ... )``?
1439
+
1440
+ The frame's text is scanned once, incrementally, for ``case``/``esac``.
1441
+ """
1442
+ for m in _CASE_WORD.finditer(self.text, fr.case_scan, pos):
1443
+ fr.case_open += 1 if m.group() == "case" else -1
1444
+ fr.case_open = max(fr.case_open, 0)
1445
+ fr.case_scan = pos
1446
+ return fr.case_open > 0
1447
+
1448
+ def _child(self, fr: _SFrame, kind: str, interp_start: int | None) -> _SCode:
1449
+ spans: list[Span] = [] if interp_start is not None else _sink(fr)
1450
+ return _SCode(
1451
+ kind,
1452
+ spans,
1453
+ fr.limit,
1454
+ interp_start=interp_start,
1455
+ docker=fr.docker,
1456
+ shell=fr.shell,
1457
+ )
1458
+
1459
+ def _code(self, stack: list[_SFrame], fr: _SCode, pos: int, c: str) -> int:
1460
+ text = self.text
1461
+ if c == "\\":
1462
+ return self.esc_skip(pos)
1463
+ if c == "'":
1464
+ return self._single(fr, pos)
1465
+ if c == '"':
1466
+ frame = _SStr("dq", pos, pos + 1, fr.limit, docker=fr.docker, shell=fr.shell)
1467
+ self._push(stack, frame, pos)
1468
+ return pos + 1
1469
+ if c == "#":
1470
+ if pos == self.start or text[pos - 1] in _SHELL_WORD_START:
1471
+ span = self.line_comment(pos, 1)
1472
+ fr.spans.append(span)
1473
+ return span.end
1474
+ return pos + 1
1475
+ if c == "$":
1476
+ return self._dollar(stack, fr, pos)
1477
+ if c == "`":
1478
+ if fr.kind == "tick":
1479
+ self._close_one(stack, pos, pos + 1)
1480
+ else:
1481
+ self._push(stack, self._child(fr, "tick", None), pos)
1482
+ return pos + 1
1483
+ if c == "(":
1484
+ if fr.kind == "arith":
1485
+ fr.depth += 1
1486
+ return pos + 1
1487
+ if text.startswith("((", pos):
1488
+ self._push(stack, self._child(fr, "arith", None), pos)
1489
+ return pos + 2
1490
+ if fr.kind == "cmd":
1491
+ fr.depth += 1
1492
+ return pos + 1
1493
+ if c == ")":
1494
+ if fr.kind not in ("cmd", "arith"):
1495
+ return pos + 1
1496
+ if fr.depth:
1497
+ fr.depth -= 1
1498
+ return pos + 1
1499
+ if fr.kind == "cmd" and self._in_case(fr, pos):
1500
+ return pos + 1
1501
+ if fr.kind == "cmd":
1502
+ self._close_one(stack, pos, pos + 1)
1503
+ return pos + 1
1504
+ if text.startswith("))", pos):
1505
+ self._close_one(stack, pos, pos + 2)
1506
+ return pos + 2
1507
+ return pos + 1
1508
+ if c == "{":
1509
+ fr.depth += 1
1510
+ return pos + 1
1511
+ if c == "}":
1512
+ if fr.depth:
1513
+ fr.depth -= 1
1514
+ else:
1515
+ self._close_one(stack, pos, pos + 1)
1516
+ return pos + 1
1517
+ if c == "<":
1518
+ if not text.startswith("<<", pos):
1519
+ return pos + 1
1520
+ if text.startswith("<<<", pos):
1521
+ return pos + 3
1522
+ return self._heredoc_op(pos)
1523
+ # A line break: heredoc bodies start after the line that introduced them.
1524
+ if self.pending:
1525
+ return self._heredoc(stack, pos)
1526
+ return pos + 1
1527
+
1528
+ def _dollar(self, stack: list[_SFrame], fr: _SFrame, pos: int) -> int:
1529
+ text = self.text
1530
+ interp = isinstance(fr, _SStr)
1531
+ nxt = text[pos + 1 : pos + 2]
1532
+ if nxt == "(" and fr.shell:
1533
+ if text.startswith("((", pos + 1):
1534
+ self._push(stack, self._child(fr, "arith", pos + 3 if interp else None), pos)
1535
+ return pos + 3
1536
+ frame = self._child(fr, "cmd", pos + 2 if interp else None)
1537
+ frame.case_scan = pos + 2
1538
+ self._push(stack, frame, pos)
1539
+ return pos + 2
1540
+ if nxt == "{":
1541
+ self._push(stack, self._child(fr, "param", pos + 2 if interp else None), pos)
1542
+ return pos + 2
1543
+ if isinstance(fr, _SStr):
1544
+ m = _SHELL_NAME.match(text, pos + 1, fr.limit)
1545
+ if m is None:
1546
+ return pos + 1
1547
+ fr.interps.append(Interp(pos + 1, m.end()))
1548
+ return m.end()
1549
+ if nxt == "'" and fr.shell:
1550
+ cend, e, ok = _scan_quoted(
1551
+ self, pos + 2, "'", escapes=True, multiline=not fr.docker, limit=fr.limit
1552
+ )
1553
+ if not ok:
1554
+ self.issue(pos, "unterminated $'...' string")
1555
+ fr.spans.append(StringSpan("plain", pos, e, pos + 2, cend))
1556
+ return e
1557
+ if nxt == '"' and fr.shell:
1558
+ frame = _SStr("dq", pos, pos + 2, fr.limit, docker=fr.docker, shell=fr.shell)
1559
+ self._push(stack, frame, pos)
1560
+ return pos + 2
1561
+ return pos + 1
1562
+
1563
+ def _single(self, fr: _SCode, pos: int) -> int:
1564
+ text = self.text
1565
+ limit = fr.limit
1566
+ if not fr.docker:
1567
+ close = text.find("'", pos + 1, limit)
1568
+ if close < 0:
1569
+ self.issue(pos, "unterminated string")
1570
+ fr.spans.append(StringSpan("raw", pos, limit, pos + 1, limit))
1571
+ return limit
1572
+ fr.spans.append(StringSpan("raw", pos, close + 1, pos + 1, close))
1573
+ return close + 1
1574
+ # In a Dockerfile a quote cannot run past the end of its instruction.
1575
+ rx = _rx("'\n" + self.esc)
1576
+ i = pos + 1
1577
+ while True:
1578
+ m = rx.search(text, i, limit)
1579
+ if m is None:
1580
+ self.issue(pos, "unterminated string")
1581
+ fr.spans.append(StringSpan("raw", pos, limit, pos + 1, limit))
1582
+ return limit
1583
+ j = m.start()
1584
+ ch = text[j]
1585
+ if ch == "'":
1586
+ fr.spans.append(StringSpan("raw", pos, j + 1, pos + 1, j))
1587
+ return j + 1
1588
+ if ch == self.esc:
1589
+ cont = self._continuation(j, None)
1590
+ i = j + 1 if cont is None else cont
1591
+ continue
1592
+ self.issue(pos, "unterminated string")
1593
+ e = self.trim_cr(pos, j)
1594
+ fr.spans.append(StringSpan("raw", pos, e, pos + 1, e))
1595
+ return j
1596
+
1597
+ def _dq(self, stack: list[_SFrame], fr: _SStr, pos: int, c: str) -> int:
1598
+ if c == "\\":
1599
+ return self.esc_skip(pos)
1600
+ if c == '"':
1601
+ self._close_one(stack, pos, pos + 1)
1602
+ return pos + 1
1603
+ if c == "$":
1604
+ return self._dollar(stack, fr, pos)
1605
+ # "`" (command substitution).
1606
+ self._push(stack, self._child(fr, "tick", pos + 1), pos)
1607
+ return pos + 1
1608
+
1609
+ def _line_end(self, i: int) -> int:
1610
+ # The end of the line holding ``i``, cached so that many heredoc
1611
+ # operators on one long line cost linear time.
1612
+ lo, hi = self._eol_cache
1613
+ if not lo <= i <= hi:
1614
+ hi = self.eol(i)
1615
+ self._eol_cache = (i, hi)
1616
+ return hi
1617
+
1618
+ def _heredoc_op(self, pos: int) -> int:
1619
+ text, end = self.text, self.end
1620
+ i = pos + 2
1621
+ strip = text.startswith("-", i)
1622
+ if strip:
1623
+ i += 1
1624
+ m = _HSPACE.match(text, i, end)
1625
+ if m is not None:
1626
+ i = m.end()
1627
+ parts: list[str] = []
1628
+ quoted = False
1629
+ while i < end:
1630
+ c = text[i]
1631
+ if c in _HEREDOC_STOP:
1632
+ break
1633
+ if c in "'\"":
1634
+ close = text.find(c, i + 1, self._line_end(i))
1635
+ if close < 0:
1636
+ break
1637
+ parts.append(text[i + 1 : close])
1638
+ quoted = True
1639
+ i = close + 1
1640
+ elif c == "\\":
1641
+ if i + 1 < end and text[i + 1] not in "\r\n":
1642
+ parts.append(text[i + 1])
1643
+ quoted = True
1644
+ i += 2
1645
+ else:
1646
+ parts.append(c)
1647
+ i += 1
1648
+ word = "".join(parts)
1649
+ if word:
1650
+ self.pending.append((word, strip, quoted, pos))
1651
+ return i
1652
+
1653
+ def _heredoc(self, stack: list[_SFrame], pos: int) -> int:
1654
+ """At the line break ``pos``: lay out the next pending heredoc body."""
1655
+ text = self.text
1656
+ delim, strip, quoted, op = self.pending.popleft()
1657
+ fr = stack[-1]
1658
+ limit = fr.limit
1659
+ body = pos + 1
1660
+ p = body
1661
+ found: tuple[int, int] | None = None
1662
+ while p <= limit:
1663
+ e = text.find("\n", p, limit)
1664
+ if e < 0:
1665
+ e = limit
1666
+ line_end = self.trim_cr(p, e)
1667
+ line = text[p:line_end]
1668
+ if strip:
1669
+ line = line.lstrip("\t")
1670
+ if line == delim:
1671
+ found = (p, line_end)
1672
+ break
1673
+ if e >= limit:
1674
+ break
1675
+ p = e + 1
1676
+ if found is None:
1677
+ self.issue(op, "unterminated heredoc")
1678
+ content_end = close = limit
1679
+ else:
1680
+ content_end, close = found
1681
+ body = min(body, close)
1682
+ if quoted:
1683
+ _sink(fr).append(StringSpan("heredoc", body, close, body, content_end))
1684
+ return close
1685
+ frame = _SStr("heredoc", body, body, content_end, close_at=close)
1686
+ self._push(stack, frame, pos)
1687
+ return body
1688
+
1689
+ def _close_heredoc(self, stack: list[_SFrame], fr: _SStr) -> int:
1690
+ stack.pop()
1691
+ close = fr.limit if fr.close_at is None else fr.close_at
1692
+ span = StringSpan("heredoc", fr.start, close, fr.cstart, fr.limit, tuple(fr.interps))
1693
+ _sink(stack[-1]).append(span)
1694
+ return close
1695
+
1696
+ def _close_one(self, stack: list[_SFrame], at: int, after: int) -> None:
1697
+ fr = stack.pop()
1698
+ parent = stack[-1]
1699
+ if isinstance(fr, _SStr):
1700
+ if fr.kind == "heredoc":
1701
+ close = at if fr.close_at is None else fr.close_at
1702
+ span = StringSpan(
1703
+ "heredoc", fr.start, close, fr.cstart, min(at, close), tuple(fr.interps)
1704
+ )
1705
+ else:
1706
+ span = StringSpan("plain", fr.start, after, fr.cstart, at, tuple(fr.interps))
1707
+ _sink(parent).append(span)
1708
+ elif fr.interp_start is not None:
1709
+ end = max(at, fr.interp_start)
1710
+ cast("_SStr", parent).interps.append(Interp(fr.interp_start, end, tuple(fr.spans)))
1711
+
1712
+ def _close_above(self, stack: list[_SFrame], at: int, *, report: bool) -> None:
1713
+ while len(stack) > 1:
1714
+ fr = stack[-1]
1715
+ if isinstance(fr, _SStr):
1716
+ if report:
1717
+ what = "heredoc" if fr.kind == "heredoc" else "string"
1718
+ self.issue(fr.start, f"unterminated {what}")
1719
+ at = max(at, fr.cstart)
1720
+ else:
1721
+ if report:
1722
+ self.issue(fr.interp_start or at, "unterminated expansion")
1723
+ at = max(at, fr.interp_start or 0)
1724
+ self._close_one(stack, at, at)
1725
+
1726
+
1727
+ _DIRECTIVE = re.compile(r"#[ \t]*([A-Za-z]+)[ \t]*=[ \t]*([^ \t\r\n]*)")
1728
+ _DOCKER_WORD = re.compile(r"[A-Za-z]+")
1729
+ _DOCKER_SHELL_ARG = re.compile(r'[ \t]*\[[ \t]*"([^"\r\n]*)"')
1730
+ _POSIX_SHELLS = frozenset({"sh", "bash", "ash", "dash", "zsh", "ksh", "mksh", "busybox"})
1731
+ _SHELL_FORM = frozenset({"RUN", "CMD", "ENTRYPOINT", "HEALTHCHECK"})
1732
+
1733
+
1734
+ def docker_escape(text: str) -> str:
1735
+ """The Dockerfile escape character set by an ``# escape=`` directive (default ``\\``)."""
1736
+ esc = "\\"
1737
+ pos = 0
1738
+ while pos < len(text):
1739
+ m = _HSPACE.match(text, pos)
1740
+ j = m.end() if m is not None else pos
1741
+ if j >= len(text) or text[j] != "#":
1742
+ break
1743
+ d = _DIRECTIVE.match(text, j)
1744
+ if d is None:
1745
+ break
1746
+ if d.group(1).lower() == "escape" and d.group(2) in ("\\", "`"):
1747
+ esc = d.group(2)
1748
+ e = text.find("\n", j)
1749
+ if e < 0:
1750
+ break
1751
+ pos = e + 1
1752
+ return esc
1753
+
1754
+
1755
+ class _DockerLexer(_Base):
1756
+ def run(self) -> LexResult:
1757
+ text, end = self.text, self.end
1758
+ sh = _ShellLexer(text, self.start, end, self.index)
1759
+ sh.out = self.out
1760
+ directives = True
1761
+ posix = True
1762
+ pos = self.start
1763
+ while pos < end:
1764
+ m = _HSPACE.match(text, pos, end)
1765
+ j = m.end() if m is not None else pos
1766
+ if j >= end:
1767
+ break
1768
+ c = text[j]
1769
+ if c == "\n" or text.startswith("\r\n", j):
1770
+ directives = False
1771
+ nl = text.find("\n", j, end)
1772
+ pos = end if nl < 0 else nl + 1
1773
+ continue
1774
+ if c == "#":
1775
+ span = self.line_comment(j, 1)
1776
+ if directives:
1777
+ d = _DIRECTIVE.match(text, j, span.end)
1778
+ if d is None:
1779
+ directives = False
1780
+ elif d.group(1).lower() == "escape" and d.group(2) in ("\\", "`"):
1781
+ sh.esc = d.group(2)
1782
+ self.out.append(span)
1783
+ pos = min(self.eol(j) + 1, end)
1784
+ continue
1785
+ directives = False
1786
+ w = _DOCKER_WORD.match(text, j, end)
1787
+ word = w.group().upper() if w is not None else ""
1788
+ k = w.end() if w is not None else j
1789
+ if word == "ONBUILD":
1790
+ m2 = _HSPACE.match(text, k, end)
1791
+ k2 = m2.end() if m2 is not None else k
1792
+ w2 = _DOCKER_WORD.match(text, k2, end)
1793
+ if w2 is not None:
1794
+ word, k = w2.group().upper(), w2.end()
1795
+ m3 = _HSPACE.match(text, k, end)
1796
+ first = m3.end() if m3 is not None else k
1797
+ exec_form = text.startswith("[", first)
1798
+ if word == "SHELL":
1799
+ q = _DOCKER_SHELL_ARG.match(text, k, self.eol(k))
1800
+ if q is not None:
1801
+ name = q.group(1).replace("\\", "/").rsplit("/", 1)[-1].lower()
1802
+ posix = name.removesuffix(".exe") in _POSIX_SHELLS
1803
+ shell = word in _SHELL_FORM and not exec_form and posix and sh.esc == "\\"
1804
+ pos = max(sh.instruction(k, shell=shell), k + 1)
1805
+ sh._report_pending()
1806
+ self.partial = sh.partial
1807
+ self.issues = sh.issues
1808
+ self.out.sort(key=lambda s: s.start)
1809
+ return self.result()
1810
+
1811
+
1812
+ # --- Hash-comment formats, SQL, JSON ------------------------------------------------
1813
+
1814
+
1815
+ class _RequirementsLexer(_Base):
1816
+ """``#`` comments at line start or after whitespace; no strings."""
1817
+
1818
+ def run(self) -> LexResult:
1819
+ text, end = self.text, self.end
1820
+ pos = self.start
1821
+ while True:
1822
+ j = text.find("#", pos, end)
1823
+ if j < 0:
1824
+ break
1825
+ if j == self.start or text[j - 1] in " \t\n":
1826
+ span = self.line_comment(j, 1)
1827
+ self.out.append(span)
1828
+ pos = span.end
1829
+ else:
1830
+ pos = j + 1
1831
+ return self.result()
1832
+
1833
+
1834
+ class _TomlLexer(_Base):
1835
+ def run(self) -> LexResult:
1836
+ text, end = self.text, self.end
1837
+ rx = _rx("#\"'")
1838
+ pos = self.start
1839
+ while True:
1840
+ m = rx.search(text, pos, end)
1841
+ if m is None:
1842
+ break
1843
+ pos = m.start()
1844
+ c = text[pos]
1845
+ if c == "#":
1846
+ span = self.line_comment(pos, 1)
1847
+ self.out.append(span)
1848
+ pos = span.end
1849
+ continue
1850
+ if text.startswith(c * 3, pos):
1851
+ pos = self._multiline(pos, c)
1852
+ continue
1853
+ cend, e, ok = _scan_quoted(self, pos + 1, c, escapes=c == '"', multiline=False)
1854
+ if not ok:
1855
+ self.issue(pos, "unterminated string")
1856
+ self.out.append(StringSpan("plain" if c == '"' else "raw", pos, e, pos + 1, cend))
1857
+ pos = e
1858
+ return self.result()
1859
+
1860
+ def _multiline(self, pos: int, q: str) -> int:
1861
+ text, end = self.text, self.end
1862
+ rx = _rx(q + ("\\" if q == '"' else ""))
1863
+ i = pos + 3
1864
+ kind: StringKind = "plain" if q == '"' else "raw"
1865
+ while True:
1866
+ m = rx.search(text, i, end)
1867
+ if m is None:
1868
+ self.issue(pos, "unterminated multi-line string")
1869
+ self.out.append(StringSpan(kind, pos, end, pos + 3, end))
1870
+ return end
1871
+ j = m.start()
1872
+ if text[j] == "\\":
1873
+ i = self.esc_skip(j)
1874
+ continue
1875
+ if not text.startswith(q * 3, j):
1876
+ i = j + 1
1877
+ continue
1878
+ run = j + 3
1879
+ # Up to two quotes may sit right before the closing delimiter.
1880
+ while run < end and run - j < 5 and text[run] == q:
1881
+ run += 1
1882
+ self.out.append(StringSpan(kind, pos, run, pos + 3, run - 3))
1883
+ return run
1884
+
1885
+
1886
+ _SPACES = re.compile(r" *")
1887
+
1888
+
1889
+ class _YamlLexer(_Base):
1890
+ """YAML ``#`` comments (at line start or after whitespace), quoted scalars
1891
+ (only where a scalar may start, so ``key: don't`` is plain text) and block
1892
+ scalar bodies (``|``/``>``), whose interiors hold no comments.
1893
+ """
1894
+
1895
+ def run(self) -> LexResult:
1896
+ pos = self.start
1897
+ flow = 0
1898
+ plain: int | None = None
1899
+ while pos < self.end:
1900
+ pos, flow, block, plain = self._line(pos, flow, plain)
1901
+ if block is not None:
1902
+ pos = self._block_scalar(pos, *block)
1903
+ return self.result()
1904
+
1905
+ def _line(
1906
+ self, pos: int, flow: int, plain: int | None
1907
+ ) -> tuple[int, int, tuple[int, int] | None, int | None]:
1908
+ """Lex one line; ``plain`` is the parent indentation of a plain scalar
1909
+ the previous line left open (its more-indented continuation lines are
1910
+ plain text, so a quote there starts no string)."""
1911
+ text, end = self.text, self.end
1912
+ line_start = pos
1913
+ e = self.eol(pos)
1914
+ line_end = self.trim_cr(pos, e)
1915
+ k = _HSPACE.match(text, pos, line_end).end() # type: ignore[union-attr]
1916
+ indent = k - line_start
1917
+ if k >= line_end: # a blank line keeps a plain scalar open
1918
+ return (end if e >= end else e + 1), flow, None, plain
1919
+ marker = k == line_start and text.startswith(("---", "..."), k)
1920
+ continued = (
1921
+ flow == 0 and plain is not None and indent > plain and text[k] != "#" and not marker
1922
+ )
1923
+ value = not continued
1924
+ indicator = ""
1925
+ key_col = seq_col = token_col = -1
1926
+ last_plain = continued
1927
+ block: tuple[int, int] | None = None
1928
+ if (
1929
+ flow == 0
1930
+ and k == line_start
1931
+ and text.startswith(("---", "..."), k)
1932
+ and (k + 3 >= line_end or text[k + 3] in " \t")
1933
+ ):
1934
+ indicator = "doc"
1935
+ k += 3
1936
+ while k < line_end:
1937
+ c = text[k]
1938
+ if c in " \t":
1939
+ k += 1
1940
+ continue
1941
+ if c == "#" and (k == line_start or text[k - 1] in " \t"):
1942
+ self.out.append(CommentSpan("line", k, line_end, k + 1, line_end))
1943
+ break
1944
+ if value:
1945
+ last_plain = False
1946
+ if c in "'\"":
1947
+ token_col = k - line_start
1948
+ k = self._quoted(k, c)
1949
+ value = False
1950
+ if k > line_end:
1951
+ # The scalar ran over lines: go on with the line it ended on.
1952
+ line_start = text.rfind("\n", 0, k) + 1
1953
+ e = self.eol(k)
1954
+ line_end = self.trim_cr(line_start, e)
1955
+ continue
1956
+ if c in "|>" and flow == 0:
1957
+ if indicator == ":":
1958
+ parent = key_col
1959
+ elif indicator == "-":
1960
+ parent = seq_col
1961
+ elif indicator == "doc":
1962
+ parent = -1
1963
+ else:
1964
+ parent = indent - 1
1965
+ explicit = 0
1966
+ k += 1
1967
+ while k < line_end and text[k] in "+-123456789":
1968
+ if text[k] != "+" and text[k] != "-":
1969
+ explicit = int(text[k])
1970
+ k += 1
1971
+ block = (parent, explicit)
1972
+ value = False
1973
+ continue
1974
+ if c in "-?:" and flow == 0 and (k + 1 >= line_end or text[k + 1] in " \t"):
1975
+ if c == "-":
1976
+ seq_col = k - line_start
1977
+ indicator = "-"
1978
+ elif c == ":": # the value of an explicit "? key"
1979
+ key_col = k - line_start
1980
+ indicator = ":"
1981
+ k += 1
1982
+ continue
1983
+ if c in "[{":
1984
+ flow += 1
1985
+ k += 1
1986
+ continue
1987
+ if c in "&!":
1988
+ while k < line_end and text[k] not in " \t,[]{}":
1989
+ k += 1
1990
+ continue
1991
+ if flow and c in "]}":
1992
+ flow -= 1
1993
+ value = False
1994
+ k += 1
1995
+ continue
1996
+ if flow and c == ",":
1997
+ k += 1
1998
+ continue
1999
+ token_col = k - line_start
2000
+ value = False
2001
+ last_plain = flow == 0
2002
+ k += 1
2003
+ continue
2004
+ if c == ":" and (
2005
+ k + 1 >= line_end
2006
+ or text[k + 1] in " \t"
2007
+ or (flow and text[k + 1] in ",[]{}")
2008
+ or text[k - 1] in "'\""
2009
+ ):
2010
+ value = True
2011
+ indicator = ":"
2012
+ key_col = token_col
2013
+ k += 1
2014
+ continue
2015
+ if flow:
2016
+ if c == ",":
2017
+ value = True
2018
+ elif c in "[{":
2019
+ flow += 1
2020
+ value = True
2021
+ elif c in "]}":
2022
+ flow -= 1
2023
+ k += 1
2024
+ nxt = end if e >= end else e + 1
2025
+ if continued:
2026
+ keep = plain
2027
+ elif last_plain and not value and flow == 0:
2028
+ if indicator == ":":
2029
+ keep = key_col
2030
+ elif indicator == "-":
2031
+ keep = seq_col
2032
+ else:
2033
+ keep = indent - 1
2034
+ else:
2035
+ keep = None
2036
+ return nxt, flow, (block if flow == 0 else None), keep
2037
+
2038
+ def _quoted(self, k: int, q: str) -> int:
2039
+ text, end = self.text, self.end
2040
+ if q == '"':
2041
+ cend, e, ok = _scan_quoted(self, k + 1, '"', escapes=True, multiline=True)
2042
+ if not ok:
2043
+ self.issue(k, "unterminated quoted scalar")
2044
+ self.out.append(StringSpan("plain", k, e, k + 1, cend))
2045
+ return e
2046
+ i = k + 1
2047
+ while True:
2048
+ close = text.find("'", i, end)
2049
+ if close < 0:
2050
+ self.issue(k, "unterminated quoted scalar")
2051
+ self.out.append(StringSpan("raw", k, end, k + 1, end))
2052
+ return end
2053
+ if text.startswith("''", close):
2054
+ i = close + 2
2055
+ continue
2056
+ self.out.append(StringSpan("raw", k, close + 1, k + 1, close))
2057
+ return close + 1
2058
+
2059
+ def _block_scalar(self, pos: int, parent: int, explicit: int) -> int:
2060
+ """The body of a block scalar whose first line starts at ``pos``."""
2061
+ text, end = self.text, self.end
2062
+ content_indent = parent + explicit if explicit else -1
2063
+ p = pos
2064
+ last_end: int | None = None
2065
+ while p < end:
2066
+ e = self.eol(p)
2067
+ line_end = self.trim_cr(p, e)
2068
+ j = _SPACES.match(text, p, line_end).end() # type: ignore[union-attr]
2069
+ if _HSPACE.match(text, j, line_end).end() == line_end: # type: ignore[union-attr]
2070
+ p = e + 1
2071
+ continue
2072
+ indent = j - p
2073
+ if content_indent < 0:
2074
+ if indent <= parent:
2075
+ break
2076
+ content_indent = indent
2077
+ if indent < content_indent:
2078
+ break
2079
+ last_end = line_end
2080
+ p = e + 1
2081
+ if last_end is None:
2082
+ return pos
2083
+ self.out.append(StringSpan("raw", pos, last_end, pos, last_end))
2084
+ nl = text.find("\n", last_end, end)
2085
+ return end if nl < 0 else nl + 1
2086
+
2087
+
2088
+ _DOLLAR_TAG = re.compile(r"\$(?:[A-Za-z_\x80-\U0010ffff][A-Za-z0-9_\x80-\U0010ffff]*)?\$")
2089
+
2090
+
2091
+ class _SqlLexer(_Base):
2092
+ def run(self) -> LexResult:
2093
+ text, end = self.text, self.end
2094
+ rx = _rx("-/'\"`$")
2095
+ pos = self.start
2096
+ while True:
2097
+ m = rx.search(text, pos, end)
2098
+ if m is None:
2099
+ break
2100
+ pos = m.start()
2101
+ c = text[pos]
2102
+ if c == "-":
2103
+ if text.startswith("--", pos):
2104
+ span = self.line_comment(pos, 2)
2105
+ self.out.append(span)
2106
+ pos = span.end
2107
+ else:
2108
+ pos += 1
2109
+ elif c == "/":
2110
+ if text.startswith("/*", pos):
2111
+ pos = self._block(pos)
2112
+ else:
2113
+ pos += 1
2114
+ elif c == "'":
2115
+ prefix = pos
2116
+ escapes = False
2117
+ if (
2118
+ pos > self.start
2119
+ and text[pos - 1] in "Ee"
2120
+ and (pos - 1 == self.start or not _is_word(text[pos - 2]))
2121
+ ):
2122
+ prefix = pos - 1
2123
+ escapes = True
2124
+ pos = self._quoted(prefix, pos, escapes)
2125
+ elif c in '"`':
2126
+ close = self._doubled(pos + 1, c)
2127
+ if close is None:
2128
+ self.issue(pos, "unterminated quoted identifier")
2129
+ pos = end
2130
+ else:
2131
+ pos = close + 1
2132
+ else:
2133
+ pos = self._dollar(pos)
2134
+ return self.result()
2135
+
2136
+ def _doubled(self, i: int, q: str) -> int | None:
2137
+ text, end = self.text, self.end
2138
+ while True:
2139
+ close = text.find(q, i, end)
2140
+ if close < 0:
2141
+ return None
2142
+ if text.startswith(q * 2, close):
2143
+ i = close + 2
2144
+ continue
2145
+ return close
2146
+
2147
+ def _quoted(self, start: int, pos: int, escapes: bool) -> int:
2148
+ text, end = self.text, self.end
2149
+ rx = _rx("'\\" if escapes else "'")
2150
+ i = pos + 1
2151
+ flagged = False
2152
+ while True:
2153
+ m = rx.search(text, i, end)
2154
+ if m is None:
2155
+ self.issue(start, "unterminated string")
2156
+ self.out.append(StringSpan("plain", start, end, pos + 1, end))
2157
+ return end
2158
+ j = m.start()
2159
+ if text[j] == "\\":
2160
+ i = self.esc_skip(j)
2161
+ continue
2162
+ if not escapes and not flagged and text[j - 1] == "\\":
2163
+ run = 1
2164
+ while j - 1 - run > pos and text[j - 1 - run] == "\\":
2165
+ run += 1
2166
+ if run % 2 == 1:
2167
+ # MySQL reads \' as an escaped quote, standard SQL does not.
2168
+ self.issue(start, "backslash before a quote in a string; dialects differ")
2169
+ flagged = True
2170
+ if text.startswith("''", j):
2171
+ i = j + 2
2172
+ else:
2173
+ self.out.append(StringSpan("plain", start, j + 1, pos + 1, j))
2174
+ return j + 1
2175
+
2176
+ def _block(self, pos: int) -> int:
2177
+ text, end = self.text, self.end
2178
+ depth = 1
2179
+ i = pos + 2
2180
+ while True:
2181
+ m = _NESTED_COMMENT.search(text, i, end)
2182
+ if m is None:
2183
+ self.issue(pos, "unterminated block comment")
2184
+ self.out.append(CommentSpan("block", pos, end, pos + 2, end))
2185
+ return end
2186
+ if m.group() == "/*":
2187
+ depth += 1
2188
+ else:
2189
+ depth -= 1
2190
+ if depth == 0:
2191
+ self.out.append(CommentSpan("block", pos, m.end(), pos + 2, m.start()))
2192
+ return m.end()
2193
+ i = m.end()
2194
+
2195
+ def _dollar(self, pos: int) -> int:
2196
+ text, end = self.text, self.end
2197
+ if pos > self.start and (_is_word(text[pos - 1]) or text[pos - 1] == "$"):
2198
+ return pos + 1
2199
+ m = _DOLLAR_TAG.match(text, pos, end)
2200
+ if m is None:
2201
+ return pos + 1
2202
+ tag = m.group()
2203
+ close = text.find(tag, m.end(), end)
2204
+ if close < 0:
2205
+ self.issue(pos, "unterminated dollar-quoted string")
2206
+ self.out.append(StringSpan("raw", pos, end, m.end(), end))
2207
+ return end
2208
+ self.out.append(StringSpan("raw", pos, close + len(tag), m.end(), close))
2209
+ return close + len(tag)
2210
+
2211
+
2212
+ class _JsonLexer(_Base):
2213
+ def __init__(
2214
+ self, text: str, start: int, end: int, index: LineIndex | None, *, comments: bool
2215
+ ) -> None:
2216
+ super().__init__(text, start, end, index)
2217
+ self.comments = comments
2218
+
2219
+ def run(self) -> LexResult:
2220
+ text, end = self.text, self.end
2221
+ rx = _rx('"/' if self.comments else '"')
2222
+ pos = self.start
2223
+ while True:
2224
+ m = rx.search(text, pos, end)
2225
+ if m is None:
2226
+ break
2227
+ pos = m.start()
2228
+ if text[pos] == '"':
2229
+ cend, e, ok = _scan_quoted(self, pos + 1, '"', escapes=True, multiline=False)
2230
+ if not ok:
2231
+ self.issue(pos, "unterminated string")
2232
+ self.out.append(StringSpan("plain", pos, e, pos + 1, cend))
2233
+ pos = e
2234
+ elif text.startswith("//", pos):
2235
+ span = self.line_comment(pos, 2)
2236
+ self.out.append(span)
2237
+ pos = span.end
2238
+ elif text.startswith("/*", pos):
2239
+ close = text.find("*/", pos + 2, end)
2240
+ if close < 0:
2241
+ self.issue(pos, "unterminated block comment")
2242
+ self.out.append(CommentSpan("block", pos, end, pos + 2, end))
2243
+ pos = end
2244
+ else:
2245
+ self.out.append(CommentSpan("block", pos, close + 2, pos + 2, close))
2246
+ pos = close + 2
2247
+ else:
2248
+ pos += 1
2249
+ return self.result()
2250
+
2251
+
2252
+ # --- Vue and Svelte ------------------------------------------------------------------
2253
+
2254
+ _SFC_OPEN = re.compile(r"<!--|<script(?=[\s>/])", re.IGNORECASE)
2255
+ _SFC_CLOSE = re.compile(r"</script[ \t\r\n\f]*>", re.IGNORECASE)
2256
+ _ATTR_NAME = re.compile(r"[^\s=/>\"']+")
2257
+ _ATTR_VALUE = re.compile(r"[^\s>\"']+")
2258
+ _JS_LANGS = {"": "javascript", "js": "javascript", "javascript": "javascript", "jsx": "jsx"}
2259
+ _TS_LANGS = {"ts": "typescript", "typescript": "typescript", "tsx": "tsx"}
2260
+
2261
+
2262
+ def _script_tag(text: str, i: int) -> tuple[dict[str, str], int]:
2263
+ """Attributes of a ``<script`` tag from ``i``; return them and the index of ``>``.
2264
+
2265
+ The index is ``len(text)`` for an unterminated tag and points at ``/`` for
2266
+ a self-closing one.
2267
+ """
2268
+ end = len(text)
2269
+ attrs: dict[str, str] = {}
2270
+ while i < end:
2271
+ i = _SPACE.match(text, i).end() # type: ignore[union-attr]
2272
+ if i >= end or text[i] == ">" or text.startswith("/>", i):
2273
+ return attrs, i
2274
+ name = _ATTR_NAME.match(text, i)
2275
+ if name is None:
2276
+ i += 1
2277
+ continue
2278
+ i = _SPACE.match(text, name.end()).end() # type: ignore[union-attr]
2279
+ value = ""
2280
+ if text.startswith("=", i):
2281
+ i = _SPACE.match(text, i + 1).end() # type: ignore[union-attr]
2282
+ if i < end and text[i] in "\"'":
2283
+ close = text.find(text[i], i + 1)
2284
+ if close < 0:
2285
+ return attrs, end
2286
+ value = text[i + 1 : close]
2287
+ i = close + 1
2288
+ else:
2289
+ v = _ATTR_VALUE.match(text, i)
2290
+ if v is not None:
2291
+ value = v.group()
2292
+ i = v.end()
2293
+ attrs[name.group().lower()] = value
2294
+ return attrs, end
2295
+
2296
+
2297
+ class ScriptBlock(NamedTuple):
2298
+ """One ``<script>`` block of a Vue/Svelte file.
2299
+
2300
+ ``lang`` and ``type`` are the lower-cased attributes (``""`` when absent);
2301
+ ``content_end`` is ``-1`` for an unterminated block.
2302
+ """
2303
+
2304
+ content_start: int
2305
+ content_end: int
2306
+ lang: str
2307
+ tag_start: int
2308
+ type: str = ""
2309
+
2310
+ @property
2311
+ def is_code(self) -> bool:
2312
+ """Is the block JavaScript (no ``type``, or a JavaScript/module type)?"""
2313
+ return self.type.split(";", 1)[0].strip() in _JS_TYPES
2314
+
2315
+
2316
+ _JS_TYPES = frozenset(
2317
+ {
2318
+ "",
2319
+ "module",
2320
+ "text/javascript",
2321
+ "application/javascript",
2322
+ "text/ecmascript",
2323
+ "application/ecmascript",
2324
+ "text/jsx",
2325
+ "text/babel",
2326
+ "text/typescript",
2327
+ "application/typescript",
2328
+ }
2329
+ )
2330
+
2331
+
2332
+ def script_blocks(text: str) -> tuple[ScriptBlock, ...]:
2333
+ """Each ``<script>`` block; one inside an HTML comment does not count."""
2334
+ blocks: list[ScriptBlock] = []
2335
+ pos = 0
2336
+ end = len(text)
2337
+ while True:
2338
+ m = _SFC_OPEN.search(text, pos)
2339
+ if m is None:
2340
+ break
2341
+ if m.group() == "<!--":
2342
+ close = text.find("-->", m.end())
2343
+ if close < 0:
2344
+ break
2345
+ pos = close + 3
2346
+ continue
2347
+ attrs, i = _script_tag(text, m.end())
2348
+ lang = attrs.get("lang", "").lower()
2349
+ kind = attrs.get("type", "").lower()
2350
+ if i >= end:
2351
+ blocks.append(ScriptBlock(end, -1, lang, m.start(), kind))
2352
+ break
2353
+ if text.startswith("/>", i):
2354
+ pos = i + 2
2355
+ continue
2356
+ content = i + 1
2357
+ close_m = _SFC_CLOSE.search(text, content)
2358
+ if close_m is None:
2359
+ blocks.append(ScriptBlock(content, -1, lang, m.start(), kind))
2360
+ break
2361
+ blocks.append(ScriptBlock(content, close_m.start(), lang, m.start(), kind))
2362
+ pos = close_m.end()
2363
+ return tuple(blocks)
2364
+
2365
+
2366
+ _SHOWN_LANG = re.compile(r"[a-z0-9][a-z0-9+._-]{0,23}")
2367
+
2368
+
2369
+ def _lex_sfc(text: str, index: LineIndex) -> LexResult:
2370
+ spans: list[Span] = []
2371
+ issues: list[str] = []
2372
+ partial = False
2373
+ regions: list[tuple[int, int]] = []
2374
+ for block in script_blocks(text):
2375
+ start, stop, lang, tag = block[:4]
2376
+ if not block.is_code:
2377
+ continue # <script type="text/template"> and the like are markup
2378
+ end = len(text) if stop < 0 else stop
2379
+ if stop < 0:
2380
+ partial = True
2381
+ issues.append(f"line {index.line_of(tag)}: unterminated <script> block")
2382
+ flavour = _JS_LANGS.get(lang) or _TS_LANGS.get(lang)
2383
+ if flavour is None:
2384
+ partial = True
2385
+ # The attribute is file text: show it only when it is a short plain name.
2386
+ shown = repr(lang) if _SHOWN_LANG.fullmatch(lang) else "an unsupported value"
2387
+ issues.append(f"line {index.line_of(tag)}: <script lang={shown}> is not lexed")
2388
+ continue
2389
+ language = "typescript" if lang in _TS_LANGS else "javascript"
2390
+ jsx = flavour in ("jsx", "tsx") or language == "javascript"
2391
+ sub = _CLexer(text, start, end, index, language, jsx=jsx).run()
2392
+ spans.extend(sub.spans)
2393
+ issues.extend(sub.issues)
2394
+ partial = partial or sub.partial
2395
+ regions.append((start, end))
2396
+ return LexResult(tuple(spans), partial, tuple(issues[: _MAX_ISSUES + 1]), tuple(regions))
2397
+
2398
+
2399
+ # --- Dispatch ------------------------------------------------------------------------
2400
+
2401
+ _REQUIREMENTS = re.compile(r"(?:requirements|constraints)[^/]*\.txt")
2402
+
2403
+
2404
+ def family(language: str, path: str | None = None) -> str:
2405
+ """The lexer family used for ``language`` (and ``path``, when it matters)."""
2406
+ name = path.rsplit("/", 1)[-1] if path else ""
2407
+ if name.endswith((".vue", ".svelte")):
2408
+ return "sfc"
2409
+ if language == "text":
2410
+ return "requirements" if _REQUIREMENTS.fullmatch(name) else "none"
2411
+ return {
2412
+ "python": "python",
2413
+ "javascript": "c",
2414
+ "typescript": "c",
2415
+ "go": "c",
2416
+ "rust": "c",
2417
+ "java": "c",
2418
+ "kotlin": "c",
2419
+ "shell": "shell",
2420
+ "dockerfile": "dockerfile",
2421
+ "sql": "sql",
2422
+ "yaml": "yaml",
2423
+ "toml": "toml",
2424
+ "json": "json",
2425
+ "jsonc": "jsonc",
2426
+ }.get(language, "none")
2427
+
2428
+
2429
+ def lex(text: str, language: str, *, path: str | None = None) -> LexResult:
2430
+ """Lex ``text`` as ``language``; ``path`` selects JSX, Vue/Svelte and requirements.
2431
+
2432
+ Never raises: an internal failure is reported as a partial result.
2433
+ """
2434
+ if not text:
2435
+ return _EMPTY
2436
+ fam = family(language, path)
2437
+ if fam == "none":
2438
+ return _EMPTY
2439
+ index = LineIndex(text)
2440
+ end = len(text)
2441
+ # A leading byte order mark is whitespace: lexing starts after it.
2442
+ begin = 1 if text.startswith("\ufeff") else 0
2443
+ try:
2444
+ if fam == "sfc":
2445
+ return _lex_sfc(text, index)
2446
+ if fam == "python":
2447
+ return _PythonLexer(text, begin, end, index).run()
2448
+ if fam == "c":
2449
+ jsx = language == "javascript" or bool(path and path.endswith(".tsx"))
2450
+ return _CLexer(text, begin, end, index, language, jsx=jsx).run()
2451
+ if fam == "shell":
2452
+ return _ShellLexer(text, begin, end, index).run()
2453
+ if fam == "dockerfile":
2454
+ return _DockerLexer(text, begin, end, index).run()
2455
+ if fam == "sql":
2456
+ return _SqlLexer(text, begin, end, index).run()
2457
+ if fam == "yaml":
2458
+ return _YamlLexer(text, begin, end, index).run()
2459
+ if fam == "toml":
2460
+ return _TomlLexer(text, begin, end, index).run()
2461
+ if fam == "requirements":
2462
+ return _RequirementsLexer(text, begin, end, index).run()
2463
+ return _JsonLexer(text, begin, end, index, comments=fam == "jsonc").run()
2464
+ except Exception as exc: # the lexer must never raise on input
2465
+ return LexResult((), True, (f"internal lexer error ({type(exc).__name__}); not lexed",))
2466
+
2467
+
2468
+ # --- Consumers -----------------------------------------------------------------------
2469
+
2470
+
2471
+ def flatten(result: LexResult) -> tuple[tuple[StringSpan, ...], tuple[CommentSpan, ...]]:
2472
+ """Every string and comment span, nested ones included, each sorted by start."""
2473
+ strings: list[StringSpan] = []
2474
+ comments: list[CommentSpan] = []
2475
+ pending: list[Span] = list(result.spans)
2476
+ while pending:
2477
+ span = pending.pop()
2478
+ if isinstance(span, StringSpan):
2479
+ strings.append(span)
2480
+ for interp in span.interpolations:
2481
+ pending.extend(interp.spans)
2482
+ else:
2483
+ comments.append(span)
2484
+ strings.sort(key=lambda s: (s.start, s.end))
2485
+ comments.sort(key=lambda s: (s.start, s.end))
2486
+ return tuple(strings), tuple(comments)
2487
+
2488
+
2489
+ def _blank_ranges(
2490
+ spans: tuple[Span, ...], *, comments_whole: bool = False
2491
+ ) -> Iterator[tuple[int, int]]:
2492
+ """Sorted, disjoint ranges to blank: span contents minus interpolations.
2493
+
2494
+ Recursion depth is bounded by :data:`MAX_DEPTH`.
2495
+ """
2496
+ for span in spans:
2497
+ if isinstance(span, CommentSpan):
2498
+ if comments_whole:
2499
+ yield span.start, span.end
2500
+ else:
2501
+ yield span.content_start, span.content_end
2502
+ continue
2503
+ cursor = span.content_start
2504
+ for interp in span.interpolations:
2505
+ if interp.start > cursor:
2506
+ yield cursor, min(interp.start, span.content_end)
2507
+ yield from _blank_ranges(interp.spans, comments_whole=comments_whole)
2508
+ cursor = max(cursor, interp.end)
2509
+ if span.content_end > cursor:
2510
+ yield cursor, span.content_end
2511
+
2512
+
2513
+ def _apply_blanks(text: str, ranges: Iterator[tuple[int, int]]) -> str:
2514
+ out: list[str] = []
2515
+ last = 0
2516
+ for a, b in ranges:
2517
+ a = max(a, last)
2518
+ if b <= a:
2519
+ continue
2520
+ out.append(text[last:a])
2521
+ out.append(_NON_BREAK.sub(" ", text[a:b]))
2522
+ last = b
2523
+ out.append(text[last:])
2524
+ return "".join(out)
2525
+
2526
+
2527
+ def _outside(regions: tuple[tuple[int, int], ...], length: int) -> Iterator[tuple[int, int]]:
2528
+ cursor = 0
2529
+ for a, b in sorted(regions):
2530
+ if a > cursor:
2531
+ yield cursor, a
2532
+ cursor = max(cursor, b)
2533
+ if cursor < length:
2534
+ yield cursor, length
2535
+
2536
+
2537
+ def _merge(*iters: Iterator[tuple[int, int]]) -> Iterator[tuple[int, int]]:
2538
+ items = sorted(r for it in iters for r in it)
2539
+ yield from items
2540
+
2541
+
2542
+ def mask(text: str, result: LexResult) -> str:
2543
+ """``text`` with string and comment interiors blanked (newlines kept).
2544
+
2545
+ Delimiters stay, interpolation code stays visible (its own strings and
2546
+ comments blanked), and for markup files everything outside ``regions``
2547
+ is blanked. The result has the same length as ``text``.
2548
+ """
2549
+ ranges = _blank_ranges(result.spans)
2550
+ if result.regions is not None:
2551
+ ranges = _merge(ranges, _outside(result.regions, len(text)))
2552
+ return _apply_blanks(text, ranges)
2553
+
2554
+
2555
+ def code_only(text: str, result: LexResult) -> str:
2556
+ """Like :func:`mask`, but comments are blanked whole, markers included."""
2557
+ ranges = _blank_ranges(result.spans, comments_whole=True)
2558
+ if result.regions is not None:
2559
+ ranges = _merge(ranges, _outside(result.regions, len(text)))
2560
+ return _apply_blanks(text, ranges)