ai-editor-tree-engine-dev 1.0.176__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 (121) hide show
  1. ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
  2. ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
  3. ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
  4. ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
  5. ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
  6. tree_engine/PUBLIC_API.md +161 -0
  7. tree_engine/__init__.py +327 -0
  8. tree_engine/checks/__init__.py +60 -0
  9. tree_engine/checks/builtin/__init__.py +5 -0
  10. tree_engine/checks/builtin/compile_check.py +53 -0
  11. tree_engine/checks/builtin/csv_syntax.py +51 -0
  12. tree_engine/checks/builtin/docstrings.py +211 -0
  13. tree_engine/checks/builtin/encoding.py +55 -0
  14. tree_engine/checks/builtin/fleet_rules.py +227 -0
  15. tree_engine/checks/builtin/format_syntax.py +82 -0
  16. tree_engine/checks/builtin/jsonl_syntax.py +49 -0
  17. tree_engine/checks/builtin/shipped.py +52 -0
  18. tree_engine/checks/builtin/syntax.py +118 -0
  19. tree_engine/checks/builtin/xml_wellformed.py +51 -0
  20. tree_engine/checks/chain.py +332 -0
  21. tree_engine/checks/external/__init__.py +5 -0
  22. tree_engine/checks/external/_base.py +61 -0
  23. tree_engine/checks/external/bandit.py +53 -0
  24. tree_engine/checks/external/black.py +48 -0
  25. tree_engine/checks/external/flake8.py +38 -0
  26. tree_engine/checks/external/isort.py +38 -0
  27. tree_engine/checks/external/mypy.py +45 -0
  28. tree_engine/checks/external/ruff.py +45 -0
  29. tree_engine/checks/external/runner.py +197 -0
  30. tree_engine/checks/model.py +110 -0
  31. tree_engine/checks/options.py +73 -0
  32. tree_engine/checks/plugin.py +171 -0
  33. tree_engine/checks/registry.py +349 -0
  34. tree_engine/core/address.py +376 -0
  35. tree_engine/core/identifier_map.py +266 -0
  36. tree_engine/core/identity.py +226 -0
  37. tree_engine/core/instrumentation.py +399 -0
  38. tree_engine/core/integrity.py +341 -0
  39. tree_engine/core/integrity_full.py +382 -0
  40. tree_engine/core/journal.py +260 -0
  41. tree_engine/core/journal_compose.py +571 -0
  42. tree_engine/core/live_tree.py +785 -0
  43. tree_engine/core/locking.py +188 -0
  44. tree_engine/core/move.py +585 -0
  45. tree_engine/core/move_references.py +323 -0
  46. tree_engine/core/node_types.py +408 -0
  47. tree_engine/core/nodes.py +348 -0
  48. tree_engine/core/offsets.py +24 -0
  49. tree_engine/core/operations.py +825 -0
  50. tree_engine/core/plugin_boundary.py +160 -0
  51. tree_engine/core/position_map.py +263 -0
  52. tree_engine/core/position_transfer.py +512 -0
  53. tree_engine/core/range_refresh.py +366 -0
  54. tree_engine/core/reference_cache.py +360 -0
  55. tree_engine/core/references.py +223 -0
  56. tree_engine/core/reparse.py +378 -0
  57. tree_engine/core/short_id.py +296 -0
  58. tree_engine/core/subtree_apply.py +397 -0
  59. tree_engine/core/subtree_copy.py +399 -0
  60. tree_engine/core/transactions.py +397 -0
  61. tree_engine/core/trivia.py +396 -0
  62. tree_engine/core/updates.py +398 -0
  63. tree_engine/core/validation.py +377 -0
  64. tree_engine/errors.py +104 -0
  65. tree_engine/exceptions.py +376 -0
  66. tree_engine/facade.py +4524 -0
  67. tree_engine/plugins/_statements.py +369 -0
  68. tree_engine/plugins/bsl/block_edit.py +449 -0
  69. tree_engine/plugins/bsl/blocks.py +127 -0
  70. tree_engine/plugins/bsl/checker.py +297 -0
  71. tree_engine/plugins/bsl/dialects.py +303 -0
  72. tree_engine/plugins/bsl/generator.py +481 -0
  73. tree_engine/plugins/bsl/import_map.py +995 -0
  74. tree_engine/plugins/bsl/plugin.py +452 -0
  75. tree_engine/plugins/contract.py +355 -0
  76. tree_engine/plugins/cpp/import_map.py +505 -0
  77. tree_engine/plugins/cpp/languages.py +99 -0
  78. tree_engine/plugins/cpp/plugin.py +501 -0
  79. tree_engine/plugins/csv_format.py +676 -0
  80. tree_engine/plugins/detachable.py +156 -0
  81. tree_engine/plugins/fallback.py +421 -0
  82. tree_engine/plugins/ini_format.py +330 -0
  83. tree_engine/plugins/json_format.py +813 -0
  84. tree_engine/plugins/json_pointer.py +203 -0
  85. tree_engine/plugins/jsonl_format.py +392 -0
  86. tree_engine/plugins/markdown_format.py +748 -0
  87. tree_engine/plugins/onec_query_format.py +61 -0
  88. tree_engine/plugins/parse_position.py +54 -0
  89. tree_engine/plugins/plain_text.py +1543 -0
  90. tree_engine/plugins/python/export_map.py +306 -0
  91. tree_engine/plugins/python/import_map.py +429 -0
  92. tree_engine/plugins/python/plugin.py +1710 -0
  93. tree_engine/plugins/registry.py +497 -0
  94. tree_engine/plugins/scan.py +87 -0
  95. tree_engine/plugins/selection.py +228 -0
  96. tree_engine/plugins/sql_format.py +61 -0
  97. tree_engine/plugins/toml_format.py +1072 -0
  98. tree_engine/plugins/xml_format.py +911 -0
  99. tree_engine/plugins/yaml/builder.py +49 -0
  100. tree_engine/plugins/yaml/emitter.py +225 -0
  101. tree_engine/plugins/yaml/flow.py +227 -0
  102. tree_engine/plugins/yaml/plugin.py +458 -0
  103. tree_engine/plugins/yaml/ranges.py +52 -0
  104. tree_engine/plugins/yaml/reader.py +359 -0
  105. tree_engine/plugins/yaml/scanner.py +298 -0
  106. tree_engine/query/adapter.py +283 -0
  107. tree_engine/query/engine.py +853 -0
  108. tree_engine/query/inspection.py +498 -0
  109. tree_engine/query/outline.py +288 -0
  110. tree_engine/query/predicates.py +263 -0
  111. tree_engine/query/rendered_lines.py +46 -0
  112. tree_engine/query/results.py +206 -0
  113. tree_engine/query/selector.py +400 -0
  114. tree_engine/query/xml_query.py +747 -0
  115. tree_engine/storage/codec.py +400 -0
  116. tree_engine/storage/document_bridge.py +579 -0
  117. tree_engine/storage/file_txn.py +459 -0
  118. tree_engine/storage/history.py +106 -0
  119. tree_engine/storage/lifecycle.py +622 -0
  120. tree_engine/storage/schema.py +403 -0
  121. tree_engine/storage/session_guard.py +398 -0
@@ -0,0 +1,297 @@
1
+ """The BSL syntax checker, declared by the BSL format plugin (``checker_plugin``, TODO f166b8c9 D-CH, D-CI).
2
+
3
+ Diagnostics are ``Diagnostic(tool="syntax", code="SYNTAX-BSL", severity=error)`` with a 1-based line and
4
+ character column. They come from two sources and from nothing else (no grammar is invented):
5
+
6
+ 1. the parse tree of the pinned ``tree-sitter-bsl`` 0.1.6: every ``MISSING`` node and every ``ERROR`` node.
7
+ An ``ERROR`` the plugin deliberately tolerates as valid 1C text (a stray ``;`` run, balanced stray
8
+ parentheses of a grouping expression, a single ``&`` line, a single mis-tokenized statement that holds
9
+ no block keyword) is not a finding. The position is the node's own.
10
+ 2. the block structure the plugin itself enforces (:mod:`tree_engine.plugins.bsl.import_map`): a
11
+ preprocessor opener without closer, a closer without opener, a branch outside a conditional, a block
12
+ whose opener and closer are not siblings, a control structure without its keywords.
13
+
14
+ The checker reads the source only; it never touches the filesystem.
15
+
16
+ Author: Vasiliy Zdanovskiy
17
+ email: vasilyvz@gmail.com
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
23
+
24
+ from tree_engine.checks.model import Diagnostic, Severity
25
+ from tree_engine.checks.plugin import CheckerMetadata, CheckerPlugin, CheckRequest, KIND_BUILTIN
26
+ from tree_engine.plugins.bsl import import_map
27
+ from tree_engine.plugins.detachable import BSL_PLUGIN_SPEC
28
+
29
+ __all__ = ["BslSyntaxChecker"]
30
+
31
+ CODE = "SYNTAX-BSL"
32
+
33
+ #: Opening keyword token -> the closing token that must follow it.
34
+ _OPENERS = {
35
+ "PROCEDURE_KEYWORD": "ENDPROCEDURE_KEYWORD",
36
+ "FUNCTION_KEYWORD": "ENDFUNCTION_KEYWORD",
37
+ "IF_KEYWORD": "ENDIF_KEYWORD",
38
+ "WHILE_KEYWORD": "ENDDO_KEYWORD",
39
+ "FOR_KEYWORD": "ENDDO_KEYWORD",
40
+ "TRY_KEYWORD": "ENDTRY_KEYWORD",
41
+ }
42
+ _CLOSERS = frozenset(_OPENERS.values())
43
+ _STRUCTURE_TOKENS = frozenset(_OPENERS) | _CLOSERS | {
44
+ "THEN_KEYWORD", "ELSE_KEYWORD", "ELSIF_KEYWORD", "EXCEPT_KEYWORD", "DO_KEYWORD",
45
+ "PREPROC_IF_KEYWORD", "PREPROC_ELSIF_KEYWORD", "PREPROC_ELSE_KEYWORD", "PREPROC_ENDIF_KEYWORD",
46
+ "PREPROC_REGION_KEYWORD", "PREPROC_ENDREGION_KEYWORD",
47
+ }
48
+ _CLOSER_NAME = {
49
+ "ENDPROCEDURE_KEYWORD": "КонецПроцедуры",
50
+ "ENDFUNCTION_KEYWORD": "КонецФункции",
51
+ "ENDIF_KEYWORD": "КонецЕсли",
52
+ "ENDDO_KEYWORD": "КонецЦикла",
53
+ "ENDTRY_KEYWORD": "КонецПопытки",
54
+ }
55
+ _OPENER_NAME = {
56
+ "PROCEDURE_KEYWORD": "Процедура",
57
+ "FUNCTION_KEYWORD": "Функция",
58
+ "IF_KEYWORD": "Если",
59
+ "WHILE_KEYWORD": "Пока",
60
+ "FOR_KEYWORD": "Для",
61
+ "TRY_KEYWORD": "Попытка",
62
+ }
63
+
64
+
65
+ class BslSyntaxChecker(CheckerPlugin):
66
+ """Syntax and block-structure diagnostics of one BSL module."""
67
+
68
+ _METADATA = CheckerMetadata(
69
+ check_id="bsl_syntax",
70
+ kind=KIND_BUILTIN,
71
+ contract_version="1",
72
+ file_extensions=tuple(BSL_PLUGIN_SPEC.file_extensions),
73
+ format_ids=("bsl",),
74
+ default_timeout_s=30.0,
75
+ )
76
+
77
+ @property
78
+ def metadata(self) -> CheckerMetadata:
79
+ return self._METADATA
80
+
81
+ def check(self, request: CheckRequest) -> List[Diagnostic]:
82
+ source = request.source
83
+ data = source.encode("utf-8") if isinstance(source, str) else bytes(source)
84
+ findings = _findings(data)
85
+ seen = set()
86
+ out: List[Diagnostic] = []
87
+ for offset, message in findings:
88
+ line, column = _position(data, offset)
89
+ key = (line, column, message)
90
+ if key in seen:
91
+ continue
92
+ seen.add(key)
93
+ out.append(
94
+ Diagnostic(
95
+ tool="syntax", code=CODE, severity=Severity.ERROR, message=message,
96
+ path=request.path, line=line, column=column,
97
+ )
98
+ )
99
+ out.sort(key=lambda d: (d.line, d.column))
100
+ return out
101
+
102
+
103
+ def _position(data: bytes, offset: int) -> Tuple[int, int]:
104
+ """1-based line and character column of a byte offset."""
105
+ offset = max(0, min(offset, len(data)))
106
+ line = data.count(b"\n", 0, offset) + 1
107
+ start = data.rfind(b"\n", 0, offset) + 1
108
+ return line, len(data[start:offset].decode("utf-8", errors="ignore")) + 1
109
+
110
+
111
+ def _parse(data: bytes) -> Any:
112
+ import ai_editor_tree_sitter_bsl as tree_sitter_bsl
113
+ from tree_sitter import Language, Parser
114
+
115
+ return Parser(Language(tree_sitter_bsl.language())).parse(data).root_node
116
+
117
+
118
+ def _findings(data: bytes) -> List[Tuple[int, str]]:
119
+ root = _parse(data)
120
+ found: List[Tuple[int, str]] = []
121
+ if root.has_error:
122
+ errors, missing = _collect(root)
123
+ for node in missing:
124
+ found.append((node.start_byte, f"missing {node.type!r}"))
125
+ found.extend(_error_findings(errors, data))
126
+ problem = import_map.structure_problem(root)
127
+ if problem is not None:
128
+ found.append(problem)
129
+ return found
130
+
131
+
132
+ def _collect(root: Any) -> Tuple[List[Any], List[Any]]:
133
+ errors: List[Any] = []
134
+ missing: List[Any] = []
135
+ stack = [root]
136
+ while stack:
137
+ node = stack.pop()
138
+ if getattr(node, "is_missing", False):
139
+ missing.append(node)
140
+ if node.type == "ERROR":
141
+ errors.append(node)
142
+ continue
143
+ stack.extend(reversed(node.children))
144
+ errors.sort(key=lambda n: n.start_byte)
145
+ return errors, missing
146
+
147
+
148
+ def _tokens(node: Any) -> List[Any]:
149
+ out: List[Any] = []
150
+ stack = [node]
151
+ while stack:
152
+ current = stack.pop()
153
+ if not current.children:
154
+ out.append(current)
155
+ else:
156
+ stack.extend(reversed(current.children))
157
+ return out
158
+
159
+
160
+ _BLANK_AFTER_AMPERSAND = (
161
+ "blank after '&' is not allowed in a compilation directive or annotation; write the name directly after '&'"
162
+ )
163
+
164
+
165
+ def _error_findings(errors: Sequence[Any], data: bytes) -> List[Tuple[int, str]]:
166
+ found: List[Tuple[int, str]] = []
167
+ parens: Dict[int, List[Any]] = {}
168
+ for node in errors:
169
+ text = node.text or b""
170
+ types = {t.type for t in _tokens(node)}
171
+ if types & _STRUCTURE_TOKENS:
172
+ found.extend(_structure_findings(node))
173
+ continue
174
+ if text and all(byte in b";()" for byte in text):
175
+ if b"(" in text or b")" in text:
176
+ parens.setdefault(node.parent.id if node.parent is not None else 0, []).append(node)
177
+ continue # a stray ``;`` run: valid 1C text the grammar cannot place
178
+ if text[:2] in (b"& ", b"&\t"):
179
+ found.append((node.start_byte, _BLANK_AFTER_AMPERSAND))
180
+ continue
181
+ if import_map._is_self_contained_mistokenized_statement(text):
182
+ continue
183
+ if text.lstrip()[:1] in (b",", b")") and _statement_balance(data, node.start_byte) == 0:
184
+ continue # the tail of an argument list after a grouping the grammar cannot place
185
+ found.append((node.start_byte, f"syntax error near {text[:24].decode('utf-8', errors='replace')!r}"))
186
+ for group in parens.values():
187
+ for node in group:
188
+ balance = _statement_balance(data, node.start_byte)
189
+ if balance != 0:
190
+ found.append((node.start_byte, "unclosed parenthesis" if balance > 0 else "unbalanced parenthesis"))
191
+ break
192
+ return found
193
+
194
+
195
+ _END_WORDS = ("тогда", "цикл", "иначе", "попытка", "исключение", "then", "do", "else", "try", "except")
196
+
197
+
198
+ def _code_view(text: str) -> str:
199
+ """``text`` with string literals (multi-line ones included) and ``//`` comments blanked; same line count."""
200
+ out: List[str] = []
201
+ index, size = 0, len(text)
202
+ in_string = False
203
+ while index < size:
204
+ ch = text[index]
205
+ if in_string:
206
+ if ch == '"':
207
+ if text[index + 1: index + 2] == '"':
208
+ out.append("\x01\x01")
209
+ index += 2
210
+ continue
211
+ in_string = False
212
+ out.append("\x01")
213
+ elif ch == "\n":
214
+ rest = text[index + 1:].lstrip(" \t")
215
+ if not rest.startswith("|"):
216
+ in_string = False # an unterminated literal ends with its line
217
+ out.append("\n")
218
+ else:
219
+ out.append("\x01")
220
+ elif ch == '"':
221
+ in_string = True
222
+ out.append("\x01")
223
+ elif ch == "/" and text[index + 1: index + 2] == "/":
224
+ while index < size and text[index] != "\n":
225
+ index += 1
226
+ out.append(" ")
227
+ continue
228
+ else:
229
+ out.append(ch)
230
+ index += 1
231
+ return "".join(out)
232
+
233
+
234
+ def _strip_line(line: str) -> str:
235
+ return line.strip()
236
+
237
+
238
+ def _ends_statement(code: str) -> bool:
239
+ low = code.lower()
240
+ return (not code) or code.endswith(";") or code.startswith(("#", "&")) or low.endswith(_END_WORDS)
241
+
242
+
243
+ def _statement_balance(data: bytes, offset: int) -> int:
244
+ """Open minus close parentheses of the logical statement holding ``offset``."""
245
+ lines = _code_view(data.decode("utf-8", errors="replace")).split("\n")
246
+ row = data.count(b"\n", 0, offset)
247
+ row = min(row, len(lines) - 1)
248
+ first = row
249
+ while first > 0 and not _ends_statement(_strip_line(lines[first - 1])):
250
+ first -= 1
251
+ last = row
252
+ while last < len(lines) - 1 and not _ends_statement(_strip_line(lines[last])):
253
+ last += 1
254
+ text = "\n".join(_strip_line(line) for line in lines[first: last + 1])
255
+ return text.count("(") - text.count(")")
256
+
257
+
258
+ def _structure_findings(node: Any) -> List[Tuple[int, str]]:
259
+ """Name the unmatched block keywords inside one ``ERROR`` span."""
260
+ tokens = [t for t in _tokens(node) if t.type in _STRUCTURE_TOKENS and t.type != "ERROR"]
261
+ found: List[Tuple[int, str]] = []
262
+ stack: List[Any] = []
263
+ for token in tokens:
264
+ kind = token.type
265
+ if kind in _OPENERS:
266
+ stack.append(token)
267
+ elif kind in _CLOSERS:
268
+ matched = False
269
+ while stack:
270
+ opener = stack.pop()
271
+ if _OPENERS[opener.type] == kind:
272
+ matched = True
273
+ _check_inner(opener, token, tokens, found)
274
+ break
275
+ found.append((opener.start_byte, f"{_OPENER_NAME[opener.type]} without {_CLOSER_NAME[_OPENERS[opener.type]]}"))
276
+ if not matched:
277
+ found.append((token.start_byte, f"{_CLOSER_NAME[kind]} without a matching opening keyword"))
278
+ elif kind in ("ELSE_KEYWORD", "ELSIF_KEYWORD") and not any(o.type == "IF_KEYWORD" for o in stack):
279
+ found.append((token.start_byte, "Иначе/ИначеЕсли outside Если"))
280
+ elif kind == "EXCEPT_KEYWORD" and not any(o.type == "TRY_KEYWORD" for o in stack):
281
+ found.append((token.start_byte, "Исключение outside Попытка"))
282
+ for opener in stack:
283
+ found.append((opener.start_byte, f"{_OPENER_NAME[opener.type]} without {_CLOSER_NAME[_OPENERS[opener.type]]}"))
284
+ if not found:
285
+ found.append((node.start_byte, f"syntax error near {(node.text or b'')[:24].decode('utf-8', errors='replace')!r}"))
286
+ return found
287
+
288
+
289
+ def _check_inner(opener: Any, closer: Any, tokens: Sequence[Any], found: List[Tuple[int, str]]) -> None:
290
+ """The keywords a matched pair must hold between them (``Тогда``, ``Цикл``, ``Исключение``)."""
291
+ inner = {t.type for t in tokens if opener.end_byte <= t.start_byte < closer.start_byte}
292
+ if opener.type == "IF_KEYWORD" and "THEN_KEYWORD" not in inner:
293
+ found.append((opener.start_byte, "Если without Тогда"))
294
+ elif opener.type in ("WHILE_KEYWORD", "FOR_KEYWORD") and "DO_KEYWORD" not in inner:
295
+ found.append((opener.start_byte, f"{_OPENER_NAME[opener.type]} without Цикл"))
296
+ elif opener.type == "TRY_KEYWORD" and "EXCEPT_KEYWORD" not in inner:
297
+ found.append((opener.start_byte, "Попытка without Исключение"))
@@ -0,0 +1,303 @@
1
+ """BSL/1C keyword dialect tables and normalization helpers (concept C-015).
2
+
3
+ BSL ("1C:Enterprise" built-in language) is written in one of two keyword
4
+ dialects -- Russian or English -- chosen per source document, never mixed
5
+ within a construct. Both dialects are recognized on IMPORT and a document's
6
+ own dialect is restored exactly on generation, by a single translator
7
+ ({p047}: "Russian and English keywords are supported by one translator").
8
+ This module is the single source of truth for that mapping: it owns every
9
+ BSL keyword spelling and every annotation prefix spelling, in both
10
+ dialects, plus the pure normalization functions that convert between a raw
11
+ written token and a canonical, dialect-independent construct label.
12
+
13
+ Covered constructs, per the governing HRS fragments:
14
+
15
+ * the procedure keyword (``Процедура`` / ``Procedure``, {p047});
16
+ * the function keyword (``Функция`` / ``Function``, {p047});
17
+ * the export keyword (``Экспорт`` / ``Export``, {p044}, {p047});
18
+ * the variable-declaration keyword (``Перем`` / ``Var``, {iblr}, {p047});
19
+ * the ``Знач``/``Val`` by-value parameter passing-mode modifier ({p115});
20
+ * annotation prefixes such as ``&НаСервере``/``&AtServer`` and
21
+ ``&НаКлиенте``/``&AtClient`` ({an01}, {p047}).
22
+
23
+ Non-goals, per this step's brief: this module defines no tree-sitter
24
+ integration, no format-plugin machinery, and no common-model node
25
+ construction. It is pure keyword data and string normalization, usable as-
26
+ is by ``import_map.py`` (BSL source text -> common model, a sibling not yet
27
+ merged) and ``generator.py`` (common model -> BSL source text, a sibling
28
+ not yet merged) so neither one hard-codes its own copy of these keyword
29
+ strings. It depends only on the standard library.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ from typing import Dict, FrozenSet, Mapping, Optional
35
+
36
+ __all__ = [
37
+ "Dialect",
38
+ "RUSSIAN",
39
+ "ENGLISH",
40
+ "DIALECTS",
41
+ "PROCEDURE",
42
+ "FUNCTION",
43
+ "EXPORT",
44
+ "VAR",
45
+ "BY_VALUE",
46
+ "RUSSIAN_KEYWORDS",
47
+ "ENGLISH_KEYWORDS",
48
+ "AT_SERVER",
49
+ "AT_CLIENT",
50
+ "AT_SERVER_NO_CONTEXT",
51
+ "AT_CLIENT_AT_SERVER_NO_CONTEXT",
52
+ "ANNOTATION_PREFIXES",
53
+ "normalize_dialect",
54
+ "get_canonical_keyword",
55
+ "keyword_for_target_dialect",
56
+ "is_by_value_modifier",
57
+ "is_annotation_prefix",
58
+ "get_annotation_form",
59
+ ]
60
+
61
+ # ---------------------------------------------------------------------------
62
+ # Dialects
63
+ # ---------------------------------------------------------------------------
64
+
65
+ #: A dialect label is always one of the two canonical strings below; kept as
66
+ #: a plain ``str`` alias (not an ``enum``) so it composes cheaply with the
67
+ #: common model's own plain-string field values.
68
+ Dialect = str
69
+
70
+ RUSSIAN: Dialect = "russian"
71
+ ENGLISH: Dialect = "english"
72
+
73
+ #: Every recognized canonical dialect label, for validation and iteration.
74
+ DIALECTS: FrozenSet[Dialect] = frozenset({RUSSIAN, ENGLISH})
75
+
76
+ # Aliases a caller (a CLI flag, a document-metadata field, ...) might supply
77
+ # for "Russian" or "English"; deliberately generous so callers never have to
78
+ # guess the one true spelling. Keys are matched case-insensitively.
79
+ _DIALECT_ALIASES: Mapping[str, Dialect] = {
80
+ "russian": RUSSIAN,
81
+ "ru": RUSSIAN,
82
+ "rus": RUSSIAN,
83
+ "ru-ru": RUSSIAN,
84
+ "русский": RUSSIAN,
85
+ "рус": RUSSIAN,
86
+ "english": ENGLISH,
87
+ "en": ENGLISH,
88
+ "eng": ENGLISH,
89
+ "en-us": ENGLISH,
90
+ "английский": ENGLISH,
91
+ "англ": ENGLISH,
92
+ }
93
+
94
+
95
+ def normalize_dialect(name: str) -> Dialect:
96
+ """Map a user-provided dialect name to the canonical ``russian`` or
97
+ ``english`` label.
98
+
99
+ Matching is case- and whitespace-insensitive and accepts the common
100
+ aliases in :data:`_DIALECT_ALIASES` (``"ru"``, ``"en"``, the Russian
101
+ words for the dialect names, ...), so callers never need to guess which
102
+ exact spelling this module expects.
103
+
104
+ Raises :class:`ValueError` if ``name`` is not a recognized dialect.
105
+ """
106
+
107
+ if not isinstance(name, str):
108
+ raise ValueError(f"dialect name must be a str, got {type(name).__name__}")
109
+ key = name.strip().lower()
110
+ if key in DIALECTS:
111
+ return key
112
+ try:
113
+ return _DIALECT_ALIASES[key]
114
+ except KeyError:
115
+ raise ValueError(f"unknown BSL dialect: {name!r}") from None
116
+
117
+
118
+ # ---------------------------------------------------------------------------
119
+ # Keyword tables
120
+ # ---------------------------------------------------------------------------
121
+
122
+ # Canonical, dialect-independent construct labels. These are the shared
123
+ # representation every dialect's written keyword normalizes to, and the
124
+ # lookup key ``keyword_for_target_dialect`` accepts to render a keyword back
125
+ # into a chosen dialect's written form.
126
+ PROCEDURE = "procedure"
127
+ FUNCTION = "function"
128
+ EXPORT = "export"
129
+ VAR = "var"
130
+ BY_VALUE = "by_value"
131
+
132
+ #: Russian dialect keyword table: canonical label -> written Russian form.
133
+ RUSSIAN_KEYWORDS: Mapping[str, str] = {
134
+ PROCEDURE: "Процедура",
135
+ FUNCTION: "Функция",
136
+ EXPORT: "Экспорт",
137
+ VAR: "Перем",
138
+ BY_VALUE: "Знач",
139
+ }
140
+
141
+ #: English dialect keyword table: canonical label -> written English form.
142
+ ENGLISH_KEYWORDS: Mapping[str, str] = {
143
+ PROCEDURE: "Procedure",
144
+ FUNCTION: "Function",
145
+ EXPORT: "Export",
146
+ VAR: "Var",
147
+ BY_VALUE: "Val",
148
+ }
149
+
150
+ _KEYWORD_TABLES: Mapping[Dialect, Mapping[str, str]] = {
151
+ RUSSIAN: RUSSIAN_KEYWORDS,
152
+ ENGLISH: ENGLISH_KEYWORDS,
153
+ }
154
+
155
+ # Reverse lookup per dialect, built once: lower-cased written form ->
156
+ # canonical label. BSL keywords are themselves case-insensitive in 1C, so
157
+ # normalization is case-insensitive on the written side.
158
+ _KEYWORD_REVERSE: Dict[Dialect, Dict[str, str]] = {
159
+ dialect: {written.lower(): canonical for canonical, written in table.items()}
160
+ for dialect, table in _KEYWORD_TABLES.items()
161
+ }
162
+
163
+ # Flat set of every by-value modifier spelling (both dialects), lower-cased,
164
+ # for case-insensitive membership tests independent of which dialect a
165
+ # caller happens to be working in.
166
+ _BY_VALUE_TOKENS: FrozenSet[str] = frozenset(
167
+ table[BY_VALUE].lower() for table in _KEYWORD_TABLES.values()
168
+ )
169
+
170
+
171
+ def get_canonical_keyword(token: str, dialect: Dialect) -> Optional[str]:
172
+ """Normalize a raw keyword token written in ``dialect`` to its
173
+ canonical, dialect-independent construct label (one of
174
+ :data:`PROCEDURE`, :data:`FUNCTION`, :data:`EXPORT`, :data:`VAR`,
175
+ :data:`BY_VALUE`).
176
+
177
+ Matching is case-insensitive, mirroring BSL's own case-insensitive
178
+ keywords. Returns ``None`` when ``token`` is not a recognized keyword in
179
+ ``dialect`` -- this is a lookup miss, not an error, since callers use it
180
+ to probe arbitrary source tokens.
181
+ """
182
+
183
+ resolved = normalize_dialect(dialect)
184
+ return _KEYWORD_REVERSE[resolved].get(token.strip().lower())
185
+
186
+
187
+ def keyword_for_target_dialect(canonical: str, dialect: Dialect) -> str:
188
+ """Map a canonical keyword label back to its written form in
189
+ ``dialect``.
190
+
191
+ This is the inverse of :func:`get_canonical_keyword`: for any
192
+ ``canonical`` in {:data:`PROCEDURE`, :data:`FUNCTION`, :data:`EXPORT`,
193
+ :data:`VAR`, :data:`BY_VALUE`}, ``get_canonical_keyword`` applied to
194
+ this function's own result (in the same dialect) returns ``canonical``
195
+ again unchanged -- the round trip {p047}/{p115} generation relies on.
196
+
197
+ Raises :class:`ValueError` if ``canonical`` is not a known canonical
198
+ keyword label.
199
+ """
200
+
201
+ resolved = normalize_dialect(dialect)
202
+ table = _KEYWORD_TABLES[resolved]
203
+ try:
204
+ return table[canonical]
205
+ except KeyError:
206
+ raise ValueError(f"unknown canonical BSL keyword: {canonical!r}") from None
207
+
208
+
209
+ def is_by_value_modifier(token: str) -> bool:
210
+ """Identify whether ``token`` is the by-value parameter passing-mode
211
+ modifier -- ``Знач`` in the Russian dialect or ``Val`` in the English
212
+ dialect ({p115}) -- in either dialect and in any case variant.
213
+
214
+ Deliberately dialect-agnostic (unlike :func:`get_canonical_keyword`,
215
+ which requires the caller to already know the dialect): a parameter
216
+ list is scanned token-by-token before its document's dialect need be
217
+ settled, so both spellings are checked at once.
218
+ """
219
+
220
+ return token.strip().lower() in _BY_VALUE_TOKENS
221
+
222
+
223
+ # ---------------------------------------------------------------------------
224
+ # Annotation prefixes
225
+ # ---------------------------------------------------------------------------
226
+
227
+ # Canonical, dialect-independent annotation labels. Kept as a table
228
+ # separate from the plain-keyword table above: annotations are a distinct
229
+ # BSL construct ({an01}) with their own written forms, never merged with
230
+ # the procedure/function/export/var/by-value keyword set.
231
+ AT_SERVER = "at_server"
232
+ AT_CLIENT = "at_client"
233
+ AT_SERVER_NO_CONTEXT = "at_server_no_context"
234
+ AT_CLIENT_AT_SERVER_NO_CONTEXT = "at_client_at_server_no_context"
235
+
236
+ #: Canonical annotation label -> {dialect -> written form}. The Russian
237
+ #: ampersand-``На`` forms and the English ampersand-``At`` forms are the two
238
+ #: canonical written variants ({p047}); every entry covers both.
239
+ ANNOTATION_PREFIXES: Mapping[str, Mapping[Dialect, str]] = {
240
+ AT_SERVER: {RUSSIAN: "&НаСервере", ENGLISH: "&AtServer"},
241
+ AT_CLIENT: {RUSSIAN: "&НаКлиенте", ENGLISH: "&AtClient"},
242
+ AT_SERVER_NO_CONTEXT: {
243
+ RUSSIAN: "&НаСервереБезКонтекста",
244
+ ENGLISH: "&AtServerNoContext",
245
+ },
246
+ AT_CLIENT_AT_SERVER_NO_CONTEXT: {
247
+ RUSSIAN: "&НаКлиентеНаСервереБезКонтекста",
248
+ ENGLISH: "&AtClientAtServerNoContext",
249
+ },
250
+ }
251
+
252
+ # Reverse lookup: lower-cased written form (either dialect) -> canonical
253
+ # annotation label, built once for O(1) matching.
254
+ _ANNOTATION_REVERSE: Dict[str, str] = {
255
+ written.lower(): canonical
256
+ for canonical, forms in ANNOTATION_PREFIXES.items()
257
+ for written in forms.values()
258
+ }
259
+
260
+
261
+ def is_annotation_prefix(token: str, dialect: Optional[Dialect] = None) -> Optional[str]:
262
+ """Match ``token`` against the known BSL annotation prefixes in either
263
+ dialect (``&НаСервере``/``&AtServer``, ``&НаКлиенте``/``&AtClient``,
264
+ ...), per {an01}/{p047}.
265
+
266
+ Matching is case-insensitive. Returns the matched canonical annotation
267
+ label (e.g. :data:`AT_SERVER`) on a hit -- truthy and directly usable as
268
+ the dialect-independent value to store on an annotation node -- or
269
+ ``None`` on a miss. Pass ``dialect`` to require the match to come from
270
+ that specific dialect's written forms only; omit it (the default) to
271
+ match either dialect, which is what a translator that has not yet
272
+ settled a document's dialect needs.
273
+ """
274
+
275
+ normalized = token.strip().lower()
276
+ if dialect is None:
277
+ return _ANNOTATION_REVERSE.get(normalized)
278
+ resolved = normalize_dialect(dialect)
279
+ for canonical, forms in ANNOTATION_PREFIXES.items():
280
+ if forms[resolved].lower() == normalized:
281
+ return canonical
282
+ return None
283
+
284
+
285
+ def get_annotation_form(canonical: str, dialect: Dialect) -> str:
286
+ """Render the annotation identified by ``canonical`` (e.g.
287
+ :data:`AT_SERVER`) in its written form for ``dialect``.
288
+
289
+ This is the inverse of :func:`is_annotation_prefix`: for any known
290
+ ``canonical``, ``is_annotation_prefix`` applied to this function's own
291
+ result (restricted to the same ``dialect``) returns ``canonical``
292
+ again unchanged, the round trip code generation relies on to restore a
293
+ document's own annotation dialect exactly ({p047}, {p105}).
294
+
295
+ Raises :class:`ValueError` if ``canonical`` is not a known canonical
296
+ annotation label.
297
+ """
298
+
299
+ resolved = normalize_dialect(dialect)
300
+ try:
301
+ return ANNOTATION_PREFIXES[canonical][resolved]
302
+ except KeyError:
303
+ raise ValueError(f"unknown canonical BSL annotation: {canonical!r}") from None