parsefabric 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.
- parsefabric/__init__.py +79 -0
- parsefabric/_json.py +247 -0
- parsefabric/_summary_review.py +315 -0
- parsefabric/aggregation/__init__.py +30 -0
- parsefabric/aggregation/base.py +265 -0
- parsefabric/aggregation/codec.py +77 -0
- parsefabric/aggregation/evidence.py +667 -0
- parsefabric/aggregation/routing.py +161 -0
- parsefabric/aggregation/statistical.py +153 -0
- parsefabric/builtins/__init__.py +22 -0
- parsefabric/builtins/application_log.py +121 -0
- parsefabric/builtins/cli_output.py +159 -0
- parsefabric/builtins/code_detection.py +228 -0
- parsefabric/builtins/json_parser.py +140 -0
- parsefabric/builtins/mixed_content.py +655 -0
- parsefabric/builtins/python_traceback.py +120 -0
- parsefabric/builtins/timestamped_log.py +135 -0
- parsefabric/capabilities.py +109 -0
- parsefabric/compression.py +118 -0
- parsefabric/engine.py +462 -0
- parsefabric/errors.py +150 -0
- parsefabric/execution/__init__.py +15 -0
- parsefabric/execution/_executor.py +102 -0
- parsefabric/execution/async_backend.py +69 -0
- parsefabric/execution/base.py +143 -0
- parsefabric/execution/process_backend.py +41 -0
- parsefabric/execution/thread_backend.py +36 -0
- parsefabric/models.py +506 -0
- parsefabric/observability.py +252 -0
- parsefabric/parser/__init__.py +10 -0
- parsefabric/parser/_text.py +34 -0
- parsefabric/parser/async_parser.py +53 -0
- parsefabric/parser/base.py +205 -0
- parsefabric/parser/deterministic.py +219 -0
- parsefabric/parser/semantic.py +15 -0
- parsefabric/partitioning.py +172 -0
- parsefabric/patterns/__init__.py +19 -0
- parsefabric/patterns/base.py +98 -0
- parsefabric/patterns/exact.py +61 -0
- parsefabric/patterns/match.py +22 -0
- parsefabric/patterns/predicate.py +62 -0
- parsefabric/patterns/regex.py +78 -0
- parsefabric/patterns/structured.py +59 -0
- parsefabric/py.typed +0 -0
- parsefabric/registry.py +174 -0
- parsefabric/serialization.py +67 -0
- parsefabric/summarization.py +563 -0
- parsefabric-0.1.0.dist-info/METADATA +208 -0
- parsefabric-0.1.0.dist-info/RECORD +51 -0
- parsefabric-0.1.0.dist-info/WHEEL +4 -0
- parsefabric-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""Source-code detection with tree-sitter grammars.
|
|
2
|
+
|
|
3
|
+
A block of text is code in a language when that language's grammar parses it
|
|
4
|
+
without errors *and* every top-level node is a real construct (a definition,
|
|
5
|
+
declaration, statement, call, or assignment). Bare words, literals, JSON-like
|
|
6
|
+
values, and ``key: value`` lines also parse in several grammars, so they are
|
|
7
|
+
not code on their own.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import threading
|
|
13
|
+
from collections import OrderedDict
|
|
14
|
+
from collections.abc import Iterator, Sequence
|
|
15
|
+
|
|
16
|
+
import tree_sitter_language_pack as language_pack
|
|
17
|
+
from tree_sitter import Node, Parser
|
|
18
|
+
|
|
19
|
+
DEFAULT_CODE_LANGUAGES: tuple[str, ...] = (
|
|
20
|
+
"python",
|
|
21
|
+
"javascript",
|
|
22
|
+
"typescript",
|
|
23
|
+
"java",
|
|
24
|
+
"go",
|
|
25
|
+
"rust",
|
|
26
|
+
"c",
|
|
27
|
+
"cpp",
|
|
28
|
+
"sql",
|
|
29
|
+
)
|
|
30
|
+
"""Grammars that reject ordinary prose; checked in this order."""
|
|
31
|
+
|
|
32
|
+
# Grammars that accept plain sentences (``word word`` is a shell command, a Ruby
|
|
33
|
+
# call, or PHP template text), so they cannot tell code from prose.
|
|
34
|
+
_PROSE_ACCEPTING = frozenset({"bash", "shell", "sh", "zsh", "ruby", "php"})
|
|
35
|
+
_CACHE_SIZE = 4096
|
|
36
|
+
# Long blocks rarely repeat; caching only short texts bounds cache memory.
|
|
37
|
+
_CACHEABLE_LENGTH = 1024
|
|
38
|
+
_WRAPPERS = frozenset({"expression_statement"})
|
|
39
|
+
_STRONG_SUFFIXES = (
|
|
40
|
+
"_definition",
|
|
41
|
+
"_declaration",
|
|
42
|
+
"_statement",
|
|
43
|
+
"_item",
|
|
44
|
+
"_directive",
|
|
45
|
+
"_clause",
|
|
46
|
+
"call",
|
|
47
|
+
"call_expression",
|
|
48
|
+
"assignment",
|
|
49
|
+
"assignment_expression",
|
|
50
|
+
)
|
|
51
|
+
_WEAK = frozenset({"labeled_statement", "empty_statement", "expression_statement"})
|
|
52
|
+
_CALLS = frozenset({"call", "call_expression"})
|
|
53
|
+
_ASSIGNMENTS = frozenset(
|
|
54
|
+
{"assignment", "assignment_expression", "assignment_statement"}
|
|
55
|
+
)
|
|
56
|
+
_COMMENTS = frozenset({"comment", "line_comment", "block_comment"})
|
|
57
|
+
_SQL_STATEMENTS = frozenset(
|
|
58
|
+
{
|
|
59
|
+
"select",
|
|
60
|
+
"insert",
|
|
61
|
+
"update",
|
|
62
|
+
"delete",
|
|
63
|
+
"create_table",
|
|
64
|
+
"create_index",
|
|
65
|
+
"create_view",
|
|
66
|
+
"alter_table",
|
|
67
|
+
"drop_table",
|
|
68
|
+
"merge",
|
|
69
|
+
}
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _walk(node: Node) -> Iterator[Node]:
|
|
74
|
+
"""Yield a subtree in document order without recursion; deep input is safe."""
|
|
75
|
+
stack = [node]
|
|
76
|
+
while stack:
|
|
77
|
+
current = stack.pop()
|
|
78
|
+
yield current
|
|
79
|
+
stack.extend(reversed(current.children))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _first_keyword(node: Node) -> Node | None:
|
|
83
|
+
return next(
|
|
84
|
+
(item for item in _walk(node) if item.type.startswith("keyword_")), None
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _has_call(node: Node) -> bool:
|
|
89
|
+
return any(item.type in _CALLS for item in _walk(node))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _is_plain_assignment(node: Node) -> bool:
|
|
93
|
+
"""``key=value`` alone is a logfmt field as often as code, so it is weak."""
|
|
94
|
+
if node.type in _WRAPPERS and node.named_child_count == 1:
|
|
95
|
+
node = node.named_children[0]
|
|
96
|
+
return node.type in _ASSIGNMENTS and not _has_call(node)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _is_construct(node: Node, language: str, text: str) -> bool:
|
|
100
|
+
if language == "sql":
|
|
101
|
+
if node.type != "statement" or not any(
|
|
102
|
+
child.type in _SQL_STATEMENTS for child in node.named_children
|
|
103
|
+
):
|
|
104
|
+
return False
|
|
105
|
+
# ``select the order`` is valid SQL; real statements are terminated or
|
|
106
|
+
# written with upper-case keywords.
|
|
107
|
+
keyword = _first_keyword(node)
|
|
108
|
+
return text.rstrip().endswith(";") or (
|
|
109
|
+
keyword is not None and (keyword.text or b"").isupper()
|
|
110
|
+
)
|
|
111
|
+
if node.type in _WRAPPERS and node.named_child_count == 1:
|
|
112
|
+
node = node.named_children[0]
|
|
113
|
+
if node.type in _WEAK or node.named_child_count == 0:
|
|
114
|
+
return False # A lone ``pass``/``continue`` reads as a word, not code.
|
|
115
|
+
if node.type == "assignment" and node.child_by_field_name("right") is None:
|
|
116
|
+
return False # ``status: ok`` is a Python annotation, not code.
|
|
117
|
+
if node.type in _CALLS:
|
|
118
|
+
function = node.child_by_field_name("function")
|
|
119
|
+
arguments = node.child_by_field_name("arguments")
|
|
120
|
+
if (
|
|
121
|
+
function is not None
|
|
122
|
+
and arguments is not None
|
|
123
|
+
and function.end_byte != arguments.start_byte
|
|
124
|
+
):
|
|
125
|
+
return False # ``Total (approx)`` is prose, not a call.
|
|
126
|
+
return node.type.endswith(_STRONG_SUFFIXES) or node.type.startswith("preproc_")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class CodeDetector:
|
|
130
|
+
"""Detect which configured grammar, if any, parses a text block as code.
|
|
131
|
+
|
|
132
|
+
Grammars are tried in the configured order. Results for short texts are
|
|
133
|
+
kept in a bounded least-recently-used cache shared by all threads; each
|
|
134
|
+
thread uses its own tree-sitter parsers. Missing grammars are downloaded
|
|
135
|
+
when the detector is created.
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
languages: tree-sitter language names. Grammars that accept ordinary
|
|
139
|
+
prose (``bash``, ``shell``, ``sh``, ``zsh``, ``ruby``, ``php``)
|
|
140
|
+
are rejected.
|
|
141
|
+
|
|
142
|
+
Raises:
|
|
143
|
+
TypeError: If ``languages`` is not a sequence of names.
|
|
144
|
+
ValueError: If a language is unknown or accepts prose.
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
def __init__(self, languages: Sequence[str] = DEFAULT_CODE_LANGUAGES) -> None:
|
|
148
|
+
if isinstance(languages, str) or not all(
|
|
149
|
+
isinstance(language, str) and language for language in languages
|
|
150
|
+
):
|
|
151
|
+
raise TypeError("code languages must be a sequence of language names")
|
|
152
|
+
selected = tuple(dict.fromkeys(languages))
|
|
153
|
+
for language in selected:
|
|
154
|
+
if language in _PROSE_ACCEPTING:
|
|
155
|
+
raise ValueError(
|
|
156
|
+
f"{language!r} parses ordinary prose, so it cannot detect code"
|
|
157
|
+
)
|
|
158
|
+
if not language_pack.has_language(language):
|
|
159
|
+
raise ValueError(f"unknown tree-sitter language: {language!r}")
|
|
160
|
+
self._languages = selected
|
|
161
|
+
self._local = threading.local()
|
|
162
|
+
self._cache: OrderedDict[str, str | None] = OrderedDict()
|
|
163
|
+
self._cache_lock = threading.Lock()
|
|
164
|
+
if selected:
|
|
165
|
+
# Download missing grammars now, not in the middle of a parse.
|
|
166
|
+
language_pack.prefetch(list(selected))
|
|
167
|
+
|
|
168
|
+
@property
|
|
169
|
+
def languages(self) -> tuple[str, ...]:
|
|
170
|
+
"""Configured grammar names, in detection order."""
|
|
171
|
+
return self._languages
|
|
172
|
+
|
|
173
|
+
def _parsers(self) -> Iterator[tuple[str, Parser]]:
|
|
174
|
+
cache: dict[str, Parser] | None = getattr(self._local, "parsers", None)
|
|
175
|
+
if cache is None:
|
|
176
|
+
cache = self._local.parsers = {}
|
|
177
|
+
for language in self._languages:
|
|
178
|
+
parser = cache.get(language)
|
|
179
|
+
if parser is None:
|
|
180
|
+
parser = cache[language] = language_pack.get_parser(language)
|
|
181
|
+
yield language, parser
|
|
182
|
+
|
|
183
|
+
def detect(self, text: str) -> str | None:
|
|
184
|
+
"""Return the first configured language that parses ``text`` as code.
|
|
185
|
+
|
|
186
|
+
Args:
|
|
187
|
+
text: One or more lines.
|
|
188
|
+
|
|
189
|
+
Returns:
|
|
190
|
+
The language name, or ``None`` when ``text`` is not code in any
|
|
191
|
+
configured language.
|
|
192
|
+
"""
|
|
193
|
+
if not text.strip():
|
|
194
|
+
return None
|
|
195
|
+
cacheable = len(text) <= _CACHEABLE_LENGTH
|
|
196
|
+
if cacheable:
|
|
197
|
+
with self._cache_lock:
|
|
198
|
+
if text in self._cache:
|
|
199
|
+
self._cache.move_to_end(text)
|
|
200
|
+
return self._cache[text]
|
|
201
|
+
language = self._detect(text)
|
|
202
|
+
if cacheable:
|
|
203
|
+
with self._cache_lock:
|
|
204
|
+
self._cache[text] = language
|
|
205
|
+
self._cache.move_to_end(text)
|
|
206
|
+
if len(self._cache) > _CACHE_SIZE:
|
|
207
|
+
self._cache.popitem(last=False)
|
|
208
|
+
return language
|
|
209
|
+
|
|
210
|
+
def _detect(self, text: str) -> str | None:
|
|
211
|
+
data = (text if text.endswith("\n") else text + "\n").encode("utf-8")
|
|
212
|
+
for language, parser in self._parsers():
|
|
213
|
+
root = parser.parse(data).root_node
|
|
214
|
+
if root.has_error:
|
|
215
|
+
continue
|
|
216
|
+
nodes = [node for node in root.named_children if node.type not in _COMMENTS]
|
|
217
|
+
if (
|
|
218
|
+
nodes
|
|
219
|
+
and all(_is_construct(node, language, text) for node in nodes)
|
|
220
|
+
and not all(_is_plain_assignment(node) for node in nodes)
|
|
221
|
+
):
|
|
222
|
+
return language
|
|
223
|
+
return None
|
|
224
|
+
|
|
225
|
+
def __reduce__(self) -> tuple[type[CodeDetector], tuple[tuple[str, ...]]]:
|
|
226
|
+
# Rebuild through the validating constructor; parsers and the cache
|
|
227
|
+
# are per-process state and are never pickled.
|
|
228
|
+
return (CodeDetector, (self._languages,))
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""JSON document parser with explicit invalid-input results.
|
|
2
|
+
|
|
3
|
+
Decoding uses msgspec: it is strict RFC 8259 (``NaN`` and out-of-range numbers
|
|
4
|
+
such as ``1e400`` are invalid) and keeps integers of any size exact.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any, override
|
|
10
|
+
|
|
11
|
+
import msgspec
|
|
12
|
+
|
|
13
|
+
from parsefabric._json import MAX_JSON_DEPTH, copy_json
|
|
14
|
+
from parsefabric.capabilities import ParserCapabilities
|
|
15
|
+
from parsefabric.errors import ParseError, ParseIssue
|
|
16
|
+
from parsefabric.models import ParseContext, ParsedEvent, ParseResult
|
|
17
|
+
from parsefabric.parser import Parser
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _decode(text: str) -> Any:
|
|
21
|
+
try:
|
|
22
|
+
value = msgspec.json.decode(text)
|
|
23
|
+
except RecursionError as error:
|
|
24
|
+
raise ParseError(
|
|
25
|
+
f"JSON document nests deeper than {MAX_JSON_DEPTH} levels"
|
|
26
|
+
) from error
|
|
27
|
+
try:
|
|
28
|
+
return copy_json(value, "JSON document")
|
|
29
|
+
except ValueError as error:
|
|
30
|
+
raise ParseError(str(error)) from error
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class JSONParser(Parser):
|
|
34
|
+
"""Parse one JSON document, or an already-decoded JSON value, into one event.
|
|
35
|
+
|
|
36
|
+
Text and bytes produce a ``json_record`` event whose ``value`` attribute
|
|
37
|
+
is the decoded document and whose evidence spans the whole input. Invalid
|
|
38
|
+
JSON is not raised: the result holds an ``unparsed`` event with the text
|
|
39
|
+
and a `ParseIssue`. Values nested deeper than
|
|
40
|
+
`parsefabric.MAX_JSON_DEPTH` levels are invalid.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
@override
|
|
45
|
+
def name(self) -> str:
|
|
46
|
+
return "json"
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
@override
|
|
50
|
+
def version(self) -> str:
|
|
51
|
+
return "1"
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
@override
|
|
55
|
+
def capabilities(self) -> ParserCapabilities:
|
|
56
|
+
return ParserCapabilities(
|
|
57
|
+
deterministic=True,
|
|
58
|
+
incremental=True,
|
|
59
|
+
parallel_safe=True,
|
|
60
|
+
aggregatable=True,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
@override
|
|
64
|
+
async def parse(
|
|
65
|
+
self,
|
|
66
|
+
source: object,
|
|
67
|
+
context: ParseContext | None = None,
|
|
68
|
+
) -> ParseResult:
|
|
69
|
+
"""Parse JSON text, UTF-8 bytes, or an already-decoded JSON value.
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
source: JSON text or bytes, or a decoded JSON value.
|
|
73
|
+
context: Source description; ``source_offset`` shifts offsets.
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
A result with one ``json_record`` event, or one ``unparsed`` event
|
|
77
|
+
and an issue for invalid JSON text.
|
|
78
|
+
|
|
79
|
+
Raises:
|
|
80
|
+
ParseError: If text is not valid Unicode or a decoded value is not
|
|
81
|
+
JSON-compatible.
|
|
82
|
+
UnicodeDecodeError: If bytes are not valid UTF-8.
|
|
83
|
+
"""
|
|
84
|
+
start_offset = None
|
|
85
|
+
end_offset = None
|
|
86
|
+
line_number = None
|
|
87
|
+
if isinstance(source, (str, bytes)):
|
|
88
|
+
text = (
|
|
89
|
+
source.decode("utf-8", errors="strict")
|
|
90
|
+
if isinstance(source, bytes)
|
|
91
|
+
else source
|
|
92
|
+
)
|
|
93
|
+
try:
|
|
94
|
+
size = len(text.encode("utf-8"))
|
|
95
|
+
except UnicodeEncodeError as error:
|
|
96
|
+
raise ParseError("JSON text must be valid Unicode") from error
|
|
97
|
+
start_offset = (
|
|
98
|
+
context.source_offset if context and context.source_offset else 0
|
|
99
|
+
)
|
|
100
|
+
end_offset = start_offset + size
|
|
101
|
+
line_number = 1
|
|
102
|
+
try:
|
|
103
|
+
value = _decode(text)
|
|
104
|
+
except (msgspec.DecodeError, ParseError) as error:
|
|
105
|
+
event = self._with_parser_evidence(
|
|
106
|
+
ParsedEvent("unparsed", attributes={"text": text}),
|
|
107
|
+
context,
|
|
108
|
+
start_offset=start_offset,
|
|
109
|
+
end_offset=end_offset,
|
|
110
|
+
line_number=line_number,
|
|
111
|
+
)
|
|
112
|
+
return ParseResult(
|
|
113
|
+
events=(event,),
|
|
114
|
+
errors=(
|
|
115
|
+
ParseIssue.from_exception(
|
|
116
|
+
error, source_id=context.source_id if context else None
|
|
117
|
+
),
|
|
118
|
+
),
|
|
119
|
+
parser_name=self.name,
|
|
120
|
+
parser_version=self.version,
|
|
121
|
+
correlation_id=context.correlation_id if context else None,
|
|
122
|
+
)
|
|
123
|
+
else:
|
|
124
|
+
try:
|
|
125
|
+
value = copy_json(source, "JSON input")
|
|
126
|
+
except ValueError as error:
|
|
127
|
+
raise ParseError("input is not a JSON-compatible value") from error
|
|
128
|
+
event = self._with_parser_evidence(
|
|
129
|
+
ParsedEvent(event_type="json_record", attributes={"value": value}),
|
|
130
|
+
context,
|
|
131
|
+
start_offset=start_offset,
|
|
132
|
+
end_offset=end_offset,
|
|
133
|
+
line_number=line_number,
|
|
134
|
+
)
|
|
135
|
+
return ParseResult(
|
|
136
|
+
events=(event,),
|
|
137
|
+
parser_name=self.name,
|
|
138
|
+
parser_version=self.version,
|
|
139
|
+
correlation_id=context.correlation_id if context else None,
|
|
140
|
+
)
|