libtexpr 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.
libtexpr/__init__.py ADDED
@@ -0,0 +1,59 @@
1
+ """Placeholder expressions for templates written in Latin or Cyrillic.
2
+
3
+ ``Placeholder.parse`` turns ``ПОЛЕ * 2 | функция: арг`` into a :class:`Placeholder`; an
4
+ :class:`Engine` holding your registered functions validates and evaluates it.
5
+ """
6
+
7
+ from libtexpr.engine import (
8
+ Engine,
9
+ FieldType,
10
+ Function,
11
+ Issue,
12
+ IssueKind,
13
+ Param,
14
+ )
15
+ from libtexpr.errors import (
16
+ ArgumentError,
17
+ DivisionByZeroError,
18
+ DuplicateFunctionError,
19
+ EvalError,
20
+ FunctionError,
21
+ InvalidNumberError,
22
+ InvalidSignatureError,
23
+ LimitExceededError,
24
+ NotDateError,
25
+ NotNumericError,
26
+ ParseError,
27
+ RegistryError,
28
+ TexprError,
29
+ UnexpectedCharacterError,
30
+ UnexpectedTokenError,
31
+ UnknownFunctionError,
32
+ )
33
+ from libtexpr.syntax import Placeholder
34
+
35
+ __all__ = [
36
+ "ArgumentError",
37
+ "DivisionByZeroError",
38
+ "DuplicateFunctionError",
39
+ "Engine",
40
+ "EvalError",
41
+ "FieldType",
42
+ "Function",
43
+ "FunctionError",
44
+ "InvalidNumberError",
45
+ "InvalidSignatureError",
46
+ "Issue",
47
+ "IssueKind",
48
+ "LimitExceededError",
49
+ "NotDateError",
50
+ "NotNumericError",
51
+ "Param",
52
+ "ParseError",
53
+ "Placeholder",
54
+ "RegistryError",
55
+ "TexprError",
56
+ "UnexpectedCharacterError",
57
+ "UnexpectedTokenError",
58
+ "UnknownFunctionError",
59
+ ]
libtexpr/engine.py ADDED
@@ -0,0 +1,349 @@
1
+ import re
2
+ from collections.abc import Callable, Mapping
3
+ from dataclasses import dataclass
4
+ from datetime import date
5
+ from decimal import Decimal
6
+ from enum import Enum, auto
7
+ from typing import Any
8
+
9
+ from libtexpr.errors import (
10
+ ArgumentError,
11
+ DuplicateFunctionError,
12
+ FunctionError,
13
+ InvalidSignatureError,
14
+ NotDateError,
15
+ NotNumericError,
16
+ TexprError,
17
+ UnknownFunctionError,
18
+ )
19
+ from libtexpr.syntax import (
20
+ BinOp,
21
+ Call,
22
+ Node,
23
+ Placeholder,
24
+ is_field,
25
+ is_function_name,
26
+ )
27
+
28
+ # --- Constants ---
29
+
30
+
31
+ _SEPARATORS = str.maketrans({" ": None, " ": None, " ": None, ",": "."})
32
+ _NUMBER_RE = re.compile(r"[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)")
33
+ _DATE_RE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
34
+
35
+
36
+ # --- Types ---
37
+
38
+
39
+ type Value = str | Decimal | date
40
+ """The value a pipeline carries: ``str`` for TEXT, ``Decimal`` for NUMBER, ``date`` for DATE."""
41
+
42
+
43
+ class FieldType(Enum):
44
+ """Type of a field value or of a function's input/output.
45
+
46
+ The value of each member is the Python class a pipeline carries for that type.
47
+ """
48
+
49
+ TEXT = str
50
+ NUMBER = Decimal
51
+ DATE = date
52
+
53
+ def _coerce(self, value: Value) -> Value:
54
+ match self:
55
+ case FieldType.TEXT:
56
+ if isinstance(value, Decimal):
57
+ result: Value = _format_number(value)
58
+ elif isinstance(value, date):
59
+ result = value.isoformat()
60
+ else:
61
+ result = value
62
+ case FieldType.NUMBER:
63
+ result = _to_number(value)
64
+ case FieldType.DATE:
65
+ try:
66
+ result = (
67
+ date.fromisoformat(value.strip())
68
+ if isinstance(value, str) and _DATE_RE.fullmatch(value.strip())
69
+ else value
70
+ )
71
+ except ValueError:
72
+ result = ""
73
+ if not isinstance(result, date):
74
+ raise NotDateError(f"expected a date as YYYY-MM-DD, got {value!r}")
75
+ return result
76
+
77
+
78
+ @dataclass(frozen=True, slots=True)
79
+ class Param:
80
+ """One positional argument of a registered function.
81
+
82
+ ``choices`` lists the allowed literal values; empty means any word, number or field
83
+ reference. ``default`` is passed when the argument is omitted; ``None`` makes the
84
+ argument required.
85
+ """
86
+
87
+ choices: frozenset[str] = frozenset()
88
+ default: str | None = None
89
+
90
+
91
+ @dataclass(frozen=True, slots=True)
92
+ class Function:
93
+ """A function callable in a pipeline (``| name: arg, arg``), with its whole signature.
94
+
95
+ ``run(value, args)`` is the code. ``value`` has the Python type of ``input_type``
96
+ (TEXT ``str``, NUMBER ``Decimal``, DATE ``datetime.date``) and the result must have the
97
+ type of ``output_type``. ``args`` holds exactly one string per declared :class:`Param`:
98
+ field references already replaced by their data value, omitted arguments filled with
99
+ their default. An exception raised by ``run``, or a result of the wrong type, becomes
100
+ a :class:`FunctionError`.
101
+
102
+ ``validate`` type-checks pipelines with ``input_type`` and ``output_type``; ``evaluate``
103
+ converts the value to ``input_type`` before every call. Pass the function to
104
+ :meth:`Engine.register`.
105
+
106
+ Raises :class:`InvalidSignatureError` when built with a ``name`` that is not a
107
+ lowercase Latin or Cyrillic word, a required parameter after an optional one, or a default
108
+ outside its choices.
109
+ """
110
+
111
+ name: str
112
+ run: Callable[[Any, tuple[str, ...]], Any]
113
+ input_type: FieldType
114
+ output_type: FieldType
115
+ params: tuple[Param, ...] = ()
116
+
117
+ def __post_init__(self) -> None:
118
+ problems: list[str] = []
119
+ optional_seen = False
120
+
121
+ if not is_function_name(self.name):
122
+ problems.append(f"{self.name!r} is not a lowercase Latin or Cyrillic function name")
123
+ for index, param in enumerate(self.params, start=1):
124
+ if param.default is None and optional_seen:
125
+ problems.append(f"required parameter {index} follows an optional one")
126
+ if param.choices and param.default is not None and param.default not in param.choices:
127
+ problems.append(
128
+ f"default {param.default!r} of parameter {index} is not among its choices"
129
+ )
130
+ optional_seen = optional_seen or param.default is not None
131
+ if problems:
132
+ raise InvalidSignatureError("; ".join(problems))
133
+
134
+
135
+ class IssueKind(Enum):
136
+ UNKNOWN_FIELD = auto()
137
+ UNKNOWN_FUNCTION = auto()
138
+ TYPE_MISMATCH = auto()
139
+ BAD_ARGUMENT = auto()
140
+
141
+
142
+ @dataclass(frozen=True, slots=True)
143
+ class Issue:
144
+ """One problem found by :meth:`Engine.validate`."""
145
+
146
+ kind: IssueKind
147
+ message: str
148
+
149
+
150
+ # --- Value helpers ---
151
+
152
+
153
+ def _to_number(value: Value) -> Decimal:
154
+ """Read a number written the way field values are stored.
155
+
156
+ Accepts an optional sign, a comma or dot decimal separator and spaces / NBSP as
157
+ thousands separators (``"1 000,50"``). Raises :class:`NotNumericError` for anything
158
+ else; exponents, ``inf`` and ``nan`` are rejected.
159
+ """
160
+ cleaned = value.strip().translate(_SEPARATORS) if isinstance(value, str) else ""
161
+ parsed = Decimal(cleaned) if _NUMBER_RE.fullmatch(cleaned) else value
162
+ if not isinstance(parsed, Decimal):
163
+ raise NotNumericError(f"expected a number, got {value!r}")
164
+ return parsed
165
+
166
+
167
+ def _format_number(value: Decimal) -> str:
168
+ """Plain decimal notation without exponent or trailing zeros: ``2001``, ``15000.5``."""
169
+ text = format(value, "f")
170
+ if "." in text:
171
+ text = text.rstrip("0").rstrip(".")
172
+ return "0" if text == "-0" else text
173
+
174
+
175
+ # --- Argument checks ---
176
+
177
+
178
+ def _argument_problems(call: Call, fn: Function) -> list[str]:
179
+ problems: list[str] = []
180
+
181
+ if len(call.args) > len(fn.params):
182
+ problems.append(
183
+ f"{call.name!r} takes at most {len(fn.params)} arguments, got {len(call.args)}"
184
+ )
185
+ for index, param in enumerate(fn.params):
186
+ given = call.args[index] if index < len(call.args) else None
187
+ if given is None and param.default is None:
188
+ problems.append(f"{call.name!r} misses required argument {index + 1}")
189
+ elif (
190
+ given is not None and param.choices and (is_field(given) or given not in param.choices)
191
+ ):
192
+ problems.append(
193
+ f"argument {index + 1} of {call.name!r} must be one of "
194
+ f"{', '.join(sorted(param.choices))}; got {given!r}"
195
+ )
196
+ return problems
197
+
198
+
199
+ # --- Validation ---
200
+
201
+
202
+ def _check(node: Node, schema: Mapping[str, FieldType], issues: list[Issue]) -> FieldType:
203
+ result = FieldType.NUMBER
204
+
205
+ match node:
206
+ case str() if is_field(node):
207
+ result = schema.get(node, FieldType.TEXT)
208
+ if node not in schema:
209
+ issues.append(Issue(IssueKind.UNKNOWN_FIELD, f"unknown field {node}"))
210
+ case str():
211
+ result = FieldType.TEXT
212
+ case BinOp():
213
+ for side, operand in (("left", node.left), ("right", node.right)):
214
+ if _check(operand, schema, issues) is not FieldType.NUMBER:
215
+ issues.append(
216
+ Issue(
217
+ IssueKind.TYPE_MISMATCH,
218
+ f"{side} operand of {node.op.value!r} is not NUMBER",
219
+ )
220
+ )
221
+ return result
222
+
223
+
224
+ # --- Evaluation ---
225
+
226
+
227
+ def _numeric(node: Node, data: Mapping[str, str]) -> Decimal:
228
+ match node:
229
+ case Decimal():
230
+ result = node
231
+ case BinOp():
232
+ result = node.op.apply(_numeric(node.left, data), _numeric(node.right, data))
233
+ case str():
234
+ result = _to_number(_value(node, data))
235
+ return result
236
+
237
+
238
+ def _value(node: Node, data: Mapping[str, str]) -> Value:
239
+ match node:
240
+ case str() if is_field(node):
241
+ result = data.get(node, "")
242
+ case str():
243
+ result = node
244
+ case Decimal() | BinOp():
245
+ result = _numeric(node, data)
246
+ return result
247
+
248
+
249
+ # --- Engine ---
250
+
251
+
252
+ class Engine:
253
+ """Registered functions plus the operations that use them.
254
+
255
+ Register every function once at startup; ``validate``, ``evaluate`` and
256
+ ``render_text`` never change the engine and are safe to call from several threads.
257
+ """
258
+
259
+ def __init__(self) -> None:
260
+ self._functions: dict[str, Function] = {}
261
+
262
+ def register(self, function: Function) -> None:
263
+ """Make ``function`` callable in a pipeline under ``function.name``.
264
+
265
+ Raises :class:`DuplicateFunctionError` if the name is already taken.
266
+ """
267
+ if function.name in self._functions:
268
+ raise DuplicateFunctionError(f"function {function.name!r} is already registered")
269
+ self._functions[function.name] = function
270
+
271
+ def validate(self, placeholder: Placeholder, schema: Mapping[str, FieldType]) -> list[Issue]:
272
+ """Check ``placeholder`` against ``schema`` and the registered functions.
273
+
274
+ ``schema`` maps a field name (``"ПОЛЕ"``, ``"ДОЛГ.СУММА"``) to its type.
275
+
276
+ Returns every issue found, not only the first; an empty list means it can be
277
+ evaluated. After an unknown function the type flowing through the pipeline is
278
+ left unchanged, so later steps are still checked.
279
+ """
280
+ issues: list[Issue] = []
281
+ current = _check(placeholder.expr, schema, issues)
282
+
283
+ for call in placeholder.pipeline:
284
+ fn = self._functions.get(call.name)
285
+ if fn is None:
286
+ issues.append(Issue(IssueKind.UNKNOWN_FUNCTION, f"unknown function {call.name!r}"))
287
+ else:
288
+ if current is not fn.input_type:
289
+ issues.append(
290
+ Issue(
291
+ IssueKind.TYPE_MISMATCH,
292
+ f"{call.name!r} expects {fn.input_type.name}, got {current.name}",
293
+ )
294
+ )
295
+ issues.extend(
296
+ Issue(IssueKind.BAD_ARGUMENT, p) for p in _argument_problems(call, fn)
297
+ )
298
+ current = fn.output_type
299
+ for arg in call.args:
300
+ _check(arg, schema, issues)
301
+ return issues
302
+
303
+ def evaluate(self, placeholder: Placeholder, data: Mapping[str, str]) -> str:
304
+ """Compute ``placeholder`` for one row of ``data`` (same keys → raw value).
305
+
306
+ The result is always text: a number is written without exponent, a date as
307
+ ``YYYY-MM-DD``. A missing field is ``""``; where a number or date is needed it raises an :class:`EvalError`. Math runs on
308
+ :class:`~decimal.Decimal`. Raises an :class:`EvalError` subclass.
309
+ """
310
+ value = _value(placeholder.expr, data)
311
+ for call in placeholder.pipeline:
312
+ value = self._call(call, value, data)
313
+ return str(FieldType.TEXT._coerce(value))
314
+
315
+ def render_text(self, text: str, data: Mapping[str, str]) -> str:
316
+ """Replace every ``[...]`` in ``text`` with its value for ``data``.
317
+
318
+ A placeholder that fails to parse or evaluate is left exactly as written.
319
+ """
320
+
321
+ def replace(match: re.Match[str]) -> str:
322
+ try:
323
+ result = self.evaluate(Placeholder.parse(match.group(1)), data)
324
+ except TexprError:
325
+ result = match.group(0)
326
+ return result
327
+
328
+ return Placeholder.PATTERN.sub(replace, text)
329
+
330
+ def _call(self, call: Call, value: Value, data: Mapping[str, str]) -> Value:
331
+ fn = self._functions.get(call.name)
332
+ if fn is None:
333
+ raise UnknownFunctionError(f"unknown function {call.name!r}")
334
+ problems = _argument_problems(call, fn)
335
+ if problems:
336
+ raise ArgumentError("; ".join(problems))
337
+
338
+ given = tuple(data.get(a, "") if is_field(a) else a for a in call.args)
339
+ defaults = tuple(p.default for p in fn.params[len(given) :] if p.default is not None)
340
+ typed = fn.input_type._coerce(value)
341
+ try:
342
+ result = fn.run(typed, given + defaults)
343
+ except Exception as e:
344
+ raise FunctionError(f"{call.name!r} failed: {e}") from e
345
+ if not isinstance(result, fn.output_type.value):
346
+ raise FunctionError(
347
+ f"{call.name!r} returned {type(result).__name__}, declared {fn.output_type.name}"
348
+ )
349
+ return result
libtexpr/errors.py ADDED
@@ -0,0 +1,81 @@
1
+ # --- Base ---
2
+
3
+
4
+ class TexprError(Exception):
5
+ """Base class of every error raised by libtexpr."""
6
+
7
+
8
+ # --- Parse errors ---
9
+
10
+
11
+ class ParseError(TexprError):
12
+ """The placeholder text does not match the grammar.
13
+
14
+ ``position`` is the 0-based character offset where parsing failed.
15
+ """
16
+
17
+ def __init__(self, message: str, position: int) -> None:
18
+ super().__init__(f"{message} at position {position}")
19
+ self.position = position
20
+
21
+
22
+ class UnexpectedCharacterError(ParseError):
23
+ """A character no token can start with, e.g. ``$`` or a letter outside Latin and Cyrillic."""
24
+
25
+
26
+ class UnexpectedTokenError(ParseError):
27
+ """A valid token where the grammar does not allow it, e.g. an unclosed ``(``."""
28
+
29
+
30
+ class LimitExceededError(ParseError):
31
+ """The placeholder is longer than 500 characters or nests parentheses / unary minus deeper than 20 levels."""
32
+
33
+
34
+ class InvalidNumberError(ParseError):
35
+ """A digit sequence that is not a number, e.g. ``1.2.3``."""
36
+
37
+
38
+ # --- Eval errors ---
39
+
40
+
41
+ class EvalError(TexprError):
42
+ """A parsed placeholder could not be evaluated against the given data."""
43
+
44
+
45
+ class UnknownFunctionError(EvalError):
46
+ """The pipeline calls a function that is not registered."""
47
+
48
+
49
+ class ArgumentError(EvalError):
50
+ """A function got too many arguments, misses a required one, or got a value outside its choices."""
51
+
52
+
53
+ class NotNumericError(EvalError):
54
+ """A math operand did not resolve to a number."""
55
+
56
+
57
+ class NotDateError(EvalError):
58
+ """A value that must be a date is not written as ``YYYY-MM-DD``."""
59
+
60
+
61
+ class DivisionByZeroError(EvalError):
62
+ """The right operand of ``/`` is zero."""
63
+
64
+
65
+ class FunctionError(EvalError):
66
+ """A registered function raised; the original exception is in ``__cause__``."""
67
+
68
+
69
+ # --- Registry errors ---
70
+
71
+
72
+ class RegistryError(TexprError):
73
+ """A function registration was rejected."""
74
+
75
+
76
+ class DuplicateFunctionError(RegistryError):
77
+ """A function with the same name is already registered."""
78
+
79
+
80
+ class InvalidSignatureError(RegistryError):
81
+ """The function name cannot be written in a placeholder, or its parameters are inconsistent."""
libtexpr/py.typed ADDED
File without changes
libtexpr/syntax.py ADDED
@@ -0,0 +1,334 @@
1
+ import re
2
+ from collections.abc import Callable
3
+ from dataclasses import dataclass
4
+ from decimal import Decimal, InvalidOperation
5
+ from enum import Enum, auto
6
+ from functools import lru_cache
7
+ from typing import ClassVar, Self
8
+
9
+ from libtexpr.errors import (
10
+ DivisionByZeroError,
11
+ InvalidNumberError,
12
+ LimitExceededError,
13
+ NotNumericError,
14
+ UnexpectedCharacterError,
15
+ UnexpectedTokenError,
16
+ )
17
+
18
+ # --- AST ---
19
+
20
+
21
+ class Op(Enum):
22
+ ADD = "+"
23
+ SUB = "-"
24
+ MUL = "*"
25
+ DIV = "/"
26
+
27
+ def apply(self, left: Decimal, right: Decimal) -> Decimal:
28
+ try:
29
+ match self:
30
+ case Op.ADD:
31
+ result = left + right
32
+ case Op.SUB:
33
+ result = left - right
34
+ case Op.MUL:
35
+ result = left * right
36
+ case Op.DIV:
37
+ if right == 0:
38
+ raise DivisionByZeroError("division by zero")
39
+ result = left / right
40
+ except ArithmeticError as e:
41
+ raise NotNumericError(f"result of {self.value!r} is out of range") from e
42
+ return result
43
+
44
+
45
+ # What the parser puts in the tree, by what was written in the placeholder:
46
+ # ДОЛГ.СУММА -> "ДОЛГ.СУММА" field (told from a word by its uppercase first letter)
47
+ # краткий -> "краткий" literal word
48
+ # 2.5 -> Decimal("2.5") number
49
+ # ПОЛЕ * 2 -> BinOp(...) arithmetic
50
+ type Node = Decimal | str | BinOp
51
+
52
+
53
+ @dataclass(frozen=True, slots=True)
54
+ class BinOp:
55
+ op: Op
56
+ left: Node
57
+ right: Node
58
+
59
+
60
+ @dataclass(frozen=True, slots=True)
61
+ class Call:
62
+ name: str
63
+ args: tuple[str, ...]
64
+
65
+
66
+ # --- Placeholder ---
67
+
68
+
69
+ @dataclass(frozen=True, slots=True)
70
+ class Placeholder:
71
+ """A parsed placeholder. Build it with :meth:`parse`, never directly.
72
+
73
+ ``MAX_LENGTH`` and ``MAX_NESTING`` are the limits :meth:`parse` enforces, and ``PATTERN``
74
+ matches one bracketed placeholder in a text (group 1 is the text inside the brackets).
75
+ """
76
+
77
+ # Parentheses nest at most MAX_NESTING deep and a flat chain of operators fits in MAX_LENGTH,
78
+ # so the recursive parser and evaluator stay far below Python's recursion limit.
79
+ MAX_LENGTH: ClassVar[int] = 500
80
+ MAX_NESTING: ClassVar[int] = 20
81
+
82
+ PATTERN: ClassVar[re.Pattern[str]] = re.compile(r"\[([^\[\]]+)\]")
83
+
84
+ expr: Node
85
+ pipeline: tuple[Call, ...]
86
+
87
+ # Cached because a template is parsed again for every row it is rendered with.
88
+ @classmethod
89
+ @lru_cache(maxsize=2048)
90
+ def parse(cls, src: str) -> Self:
91
+ """Parse the text inside one ``[...]``, without the brackets.
92
+
93
+ Field names are UPPERCASE and may contain dots (``ПОЛЕ``, ``DEBT.AMOUNT``); function
94
+ names and bare words are lowercase. Letters are Latin or Cyrillic. Raises a :class:`ParseError`
95
+ subclass carrying the failing position. A text longer than ``MAX_LENGTH``, or
96
+ parentheses and unary minus nested deeper than ``MAX_NESTING``, raises
97
+ :class:`LimitExceededError`.
98
+ """
99
+ if len(src) > cls.MAX_LENGTH:
100
+ raise LimitExceededError(
101
+ f"placeholder longer than {cls.MAX_LENGTH} characters", cls.MAX_LENGTH
102
+ )
103
+ expr, pipeline = _Parser(_Token.tokenize(src)).placeholder()
104
+ return cls(expr, pipeline)
105
+
106
+ @staticmethod
107
+ def extract(text: str) -> list[str]:
108
+ """Return the inner text of every ``[...]`` in ``text``, in order, without parsing it.
109
+
110
+ Nested brackets are not supported: the innermost pair is taken. Feed each result to
111
+ :meth:`parse`; extracting first lets you report a syntax error per placeholder.
112
+ """
113
+ return Placeholder.PATTERN.findall(text)
114
+
115
+
116
+ # --- Characters ---
117
+
118
+
119
+ # Latin (with its accented letters) and Cyrillic: the alphabets names may be written in.
120
+ _LETTER = re.compile(r"[A-Za-z\u00C0-\u024F\u0400-\u052F]")
121
+
122
+
123
+ def _is_upper(ch: str) -> bool:
124
+ return ch.isupper() and _LETTER.match(ch) is not None
125
+
126
+
127
+ def _is_lower(ch: str) -> bool:
128
+ return ch.islower() and _LETTER.match(ch) is not None
129
+
130
+
131
+ def _is_digit(ch: str) -> bool:
132
+ return "0" <= ch <= "9"
133
+
134
+
135
+ def is_field(text: str) -> bool:
136
+ return _is_upper(text[0])
137
+
138
+
139
+ def is_function_name(text: str) -> bool:
140
+ return text != "" and _is_lower(text[0]) and all(_is_lower(c) or c == "_" for c in text)
141
+
142
+
143
+ # --- Tokens ---
144
+
145
+
146
+ class _Kind(Enum):
147
+ EOF = auto()
148
+ UPPER = auto()
149
+ LOWER = auto()
150
+ NUMBER = auto()
151
+ PIPE = auto()
152
+ COLON = auto()
153
+ COMMA = auto()
154
+ PLUS = auto()
155
+ MINUS = auto()
156
+ STAR = auto()
157
+ SLASH = auto()
158
+ LPAREN = auto()
159
+ RPAREN = auto()
160
+
161
+
162
+ @dataclass(frozen=True, slots=True)
163
+ class _Token:
164
+ PUNCTUATION: ClassVar[dict[str, _Kind]] = {
165
+ "|": _Kind.PIPE,
166
+ ":": _Kind.COLON,
167
+ ",": _Kind.COMMA,
168
+ "+": _Kind.PLUS,
169
+ "-": _Kind.MINUS,
170
+ "*": _Kind.STAR,
171
+ "/": _Kind.SLASH,
172
+ "(": _Kind.LPAREN,
173
+ ")": _Kind.RPAREN,
174
+ }
175
+
176
+ kind: _Kind
177
+ text: str
178
+ position: int
179
+
180
+ @classmethod
181
+ def tokenize(cls, src: str) -> list[Self]:
182
+ tokens: list[_Token] = []
183
+ i = 0
184
+
185
+ while i < len(src):
186
+ ch = src[i]
187
+ end = i + 1
188
+ if ch.isspace():
189
+ pass
190
+ elif ch in cls.PUNCTUATION:
191
+ tokens.append(cls(cls.PUNCTUATION[ch], ch, i))
192
+ elif _is_digit(ch):
193
+ end = cls._scan(src, i, lambda c: _is_digit(c) or c == ".")
194
+ tokens.append(cls(_Kind.NUMBER, src[i:end], i))
195
+ elif _is_upper(ch):
196
+ end = cls._scan(src, i, lambda c: _is_upper(c) or _is_digit(c) or c in "_.")
197
+ tokens.append(cls(_Kind.UPPER, src[i:end], i))
198
+ elif _is_lower(ch):
199
+ end = cls._scan(src, i, lambda c: _is_lower(c) or c == "_")
200
+ tokens.append(cls(_Kind.LOWER, src[i:end], i))
201
+ else:
202
+ raise UnexpectedCharacterError(f"unexpected character {ch!r}", i)
203
+ i = end
204
+
205
+ tokens.append(cls(_Kind.EOF, "", len(src)))
206
+ return tokens
207
+
208
+ def number(self) -> Decimal:
209
+ try:
210
+ return Decimal(self.text)
211
+ except InvalidOperation as e:
212
+ raise InvalidNumberError(f"invalid number {self.text!r}", self.position) from e
213
+
214
+ def expected(self, what: str) -> UnexpectedTokenError:
215
+ got = repr(self.text) if self.kind is not _Kind.EOF else "end of placeholder"
216
+ return UnexpectedTokenError(f"expected {what}, got {got}", self.position)
217
+
218
+ @staticmethod
219
+ def _scan(src: str, start: int, accept: Callable[[str], bool]) -> int:
220
+ end = start
221
+ while end < len(src) and accept(src[end]):
222
+ end += 1
223
+ return end
224
+
225
+
226
+ # --- Parser ---
227
+
228
+
229
+ class _Parser:
230
+ _ADDITIVE: ClassVar[dict[_Kind, Op]] = {_Kind.PLUS: Op.ADD, _Kind.MINUS: Op.SUB}
231
+ _MULTIPLICATIVE: ClassVar[dict[_Kind, Op]] = {_Kind.STAR: Op.MUL, _Kind.SLASH: Op.DIV}
232
+
233
+ def __init__(self, tokens: list[_Token]) -> None:
234
+ self._tokens = tokens
235
+ self._pos = 0
236
+ self._depth = 0
237
+
238
+ def placeholder(self) -> tuple[Node, tuple[Call, ...]]:
239
+ pipeline: list[Call] = []
240
+ expr = self._expr()
241
+ while self._take(_Kind.PIPE):
242
+ pipeline.append(self._call())
243
+ self._expect(_Kind.EOF, "'|' or end of placeholder")
244
+ return expr, tuple(pipeline)
245
+
246
+ @property
247
+ def _peek(self) -> _Token:
248
+ return self._tokens[self._pos]
249
+
250
+ def _advance(self) -> _Token:
251
+ token = self._peek
252
+ self._pos = min(self._pos + 1, len(self._tokens) - 1)
253
+ return token
254
+
255
+ def _take(self, kind: _Kind) -> bool:
256
+ taken = self._peek.kind is kind
257
+ if taken:
258
+ self._advance()
259
+ return taken
260
+
261
+ def _expect(self, kind: _Kind, what: str) -> _Token:
262
+ token = self._peek
263
+ if token.kind is not kind:
264
+ raise token.expected(what)
265
+ return self._advance()
266
+
267
+ def _expr(self) -> Node:
268
+ node = self._term()
269
+ while self._peek.kind in self._ADDITIVE:
270
+ node = BinOp(self._ADDITIVE[self._advance().kind], node, self._term())
271
+ return node
272
+
273
+ def _term(self) -> Node:
274
+ node = self._factor()
275
+ while self._peek.kind in self._MULTIPLICATIVE:
276
+ node = BinOp(self._MULTIPLICATIVE[self._advance().kind], node, self._factor())
277
+ return node
278
+
279
+ def _enter(self, token: _Token) -> None:
280
+ self._depth += 1
281
+ if self._depth > Placeholder.MAX_NESTING:
282
+ raise LimitExceededError(
283
+ f"nesting deeper than {Placeholder.MAX_NESTING} levels", token.position
284
+ )
285
+
286
+ def _factor(self) -> Node:
287
+ node: Node
288
+ token = self._advance()
289
+
290
+ match token.kind:
291
+ case _Kind.MINUS:
292
+ self._enter(token)
293
+ node = BinOp(Op.SUB, Decimal(0), self._factor())
294
+ self._depth -= 1
295
+ case _Kind.LPAREN:
296
+ self._enter(token)
297
+ node = self._expr()
298
+ self._expect(_Kind.RPAREN, "')'")
299
+ self._depth -= 1
300
+ case _Kind.NUMBER:
301
+ node = token.number()
302
+ case _Kind.UPPER:
303
+ node = token.text
304
+ case _Kind.LOWER:
305
+ node = token.text
306
+ case _:
307
+ raise token.expected("a value")
308
+ return node
309
+
310
+ def _call(self) -> Call:
311
+ args: list[str] = []
312
+ name = self._expect(_Kind.LOWER, "function name").text
313
+
314
+ if self._take(_Kind.COLON):
315
+ args.append(self._arg())
316
+ while self._take(_Kind.COMMA):
317
+ args.append(self._arg())
318
+ return Call(name, tuple(args))
319
+
320
+ def _arg(self) -> str:
321
+ arg: str
322
+ token = self._advance()
323
+
324
+ match token.kind:
325
+ case _Kind.UPPER:
326
+ arg = token.text
327
+ case _Kind.LOWER:
328
+ arg = token.text
329
+ case _Kind.NUMBER:
330
+ token.number()
331
+ arg = token.text
332
+ case _:
333
+ raise token.expected("an argument")
334
+ return arg
@@ -0,0 +1,152 @@
1
+ Metadata-Version: 2.4
2
+ Name: libtexpr
3
+ Version: 0.1.0
4
+ Summary: Placeholder expression engine for templates: [FIELD + 1 | function: arg] in Cyrillic or Latin
5
+ Keywords: template,placeholder,expression,parser,cyrillic,latin
6
+ Author: StafLoker
7
+ Author-email: StafLoker <dev.stafloker@gmail.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Natural Language :: English
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Topic :: Software Development :: Libraries
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.12
18
+ Project-URL: Homepage, https://github.com/StafLoker/libtexpr
19
+ Project-URL: Bug Tracker, https://github.com/StafLoker/libtexpr/issues
20
+ Description-Content-Type: text/markdown
21
+
22
+ <div align="center">
23
+ <h1><b>libtexpr</b></h1>
24
+ <p><i>~ Placeholder expressions for templates ~</i></p>
25
+ </div>
26
+
27
+ libtexpr is a Python library that parses and evaluates placeholders such as `[ДОЛГ.СУММА * 2 | деньги: кратко]` or `[DEBT.AMOUNT * 2 | money: short]`. It is for applications that fill data into document templates and let template authors write fields and functions in their own language: Cyrillic or Latin.
28
+
29
+ The library reads and checks a placeholder, then evaluates it for the given data. The functions themselves (declension, amount in words, date format) are written by the application: the library only calls them in order.
30
+
31
+ ## Quick start
32
+
33
+ ```bash
34
+ uv add libtexpr
35
+ ```
36
+
37
+ The function `деньги` formats a number; the placeholder computes a sum and applies the function.
38
+
39
+ ```python
40
+ from decimal import Decimal
41
+
42
+ from libtexpr import Engine, FieldType, Function, Param, Placeholder
43
+
44
+
45
+ def money(value: Decimal, args: tuple[str, ...]) -> str:
46
+ text = f"{value:,.2f}".replace(",", " ").replace(".", ",")
47
+ return text + (" руб." if args == ("кратко",) else " рублей")
48
+
49
+
50
+ engine = Engine()
51
+ engine.register(
52
+ Function(
53
+ "деньги",
54
+ money,
55
+ FieldType.NUMBER,
56
+ FieldType.TEXT,
57
+ (Param(frozenset({"кратко", "полно"}), default="кратко"),),
58
+ )
59
+ )
60
+
61
+ placeholder = Placeholder.parse("ДОЛГ.СУММА * 2 | деньги")
62
+ schema = {"ДОЛГ.СУММА": FieldType.NUMBER}
63
+ data = {"ДОЛГ.СУММА": "1 000,5"}
64
+
65
+ print(engine.validate(placeholder, schema))
66
+ print(engine.evaluate(placeholder, data))
67
+ print(engine.render_text("Сумма: [ДОЛГ.СУММА | деньги: полно]", data))
68
+ ```
69
+
70
+ Output:
71
+
72
+ ```
73
+ []
74
+ 2 001,00 руб.
75
+ Сумма: 1 000,50 рублей
76
+ ```
77
+
78
+ The empty list on the first line means there are no problems.
79
+
80
+ ## Syntax
81
+
82
+ A placeholder is a **value** followed by a chain of functions separated by `|`:
83
+
84
+ ```
85
+ [ value | function | function: argument, argument ]
86
+ ```
87
+
88
+ | Placeholder | What it does |
89
+ | ---------------------------------------- | -------------------------------------------------- |
90
+ | `[ПОЛЕ]` | takes the value of a field |
91
+ | `[ДОЛГ.СУММА]`, `[А.Б.В]` | a field name may contain dots, e.g. as a hierarchy |
92
+ | `[родился]` | a word as plain text |
93
+ | `[100]`, `[-ПОЛЕ]` | a number |
94
+ | `[(ДОЛГ.СУММА + ПЕНИ.СУММА) * 0.01]` | arithmetic: `+ - * /` and parentheses |
95
+ | `[ФИО.ПОЛНОЕ \| падеж: род]` | a function with an argument |
96
+ | `[ФИО.ПОЛНОЕ \| падеж: род \| инициалы]` | a chain: the result of one function feeds the next |
97
+ | `[ЧИСЛО.ДЕЛ \| число: текст, женский]` | several arguments separated by commas |
98
+ | `[родился \| согласуй: ФИО.ПОЛНОЕ]` | a function argument can be a field |
99
+ | `[DEBT.AMOUNT * 2 \| money: short]` | the same syntax in Latin |
100
+
101
+ Rules:
102
+
103
+ - A name in UPPERCASE letters is a field (`ПОЛЕ`, `DEBT`, `ДОЛГ.СУММА`, `DEBT.AMOUNT`). Functions and words are lowercase. Only Cyrillic and Latin letters are allowed; a name starts with a letter.
104
+ - An argument is a word, a number or a field. There is no arithmetic inside an argument.
105
+ - Arithmetic (`+ - * /`) is allowed only in the value, before the first function: the result of a function cannot go back into arithmetic. Compute first, then apply functions: `[А.Б * 2 | округлить: 1]`.
106
+ - In the template text the decimal part is written with a dot (`0.5`), because a comma separates arguments. In data a comma is accepted: `"1 000,5"`.
107
+ - There are no quoted strings, conditions, loops or nested calls `f(g(x))`: use the chain `x | g | f` instead.
108
+
109
+ A syntax error is a `ParseError` carrying the character position: `UnexpectedCharacterError` (for example `$` or a Greek letter), `UnexpectedTokenError` (for example an unclosed parenthesis), `InvalidNumberError`, `LimitExceededError`.
110
+
111
+ ## Functions and types
112
+
113
+ A function is described by `Function(name, run, input_type, output_type, params)`:
114
+
115
+ - `run(value, args)` is the code of the function. `args` holds exactly one string per `Param`: an omitted argument is replaced by its default, a field by its value from `data`.
116
+ - `Param(choices, default)` is one argument: the allowed words (empty means any) and the default value (`None` makes the argument required).
117
+ - A mistake in the description (a name that is not lowercase Latin or Cyrillic letters, a required parameter after an optional one) raises `InvalidSignatureError` as soon as the `Function` is created.
118
+
119
+ The value keeps its type between functions:
120
+
121
+ | `FieldType` | Python object |
122
+ | ----------- | ----------------- |
123
+ | `TEXT` | `str` |
124
+ | `NUMBER` | `decimal.Decimal` |
125
+ | `DATE` | `datetime.date` |
126
+
127
+ A `NUMBER → NUMBER` function receives and returns a `Decimal`. Before each call `evaluate` converts the value to the input type: text to a number (`NotNumericError`) and to an ISO 8601 date (`NotDateError`). The result of `evaluate` is always text. An exception inside `run`, or a result of the wrong type, becomes a `FunctionError`.
128
+
129
+ `validate` is stricter than `evaluate`: the type of the value must match the input type of the function. It returns **all** the problems it finds (`UNKNOWN_FIELD`, `UNKNOWN_FUNCTION`, `TYPE_MISMATCH`, `BAD_ARGUMENT`), so the template author learns about every mistake at once.
130
+
131
+ ## Limits
132
+
133
+ - A placeholder is at most 500 characters (`Placeholder.MAX_LENGTH`), and parentheses and unary minus nest at most 20 levels (`Placeholder.MAX_NESTING`); beyond that, `LimitExceededError`.
134
+ - Arithmetic runs in `Decimal`: `0.1 + 0.2` gives exactly `0.3`; division is exact to 28 significant digits.
135
+
136
+ ## Requirements
137
+
138
+ Python 3.12 or newer. No dependencies.
139
+
140
+ ## Development
141
+
142
+ ```bash
143
+ make test # tests
144
+ make lint # style check
145
+ make format # auto-format
146
+ ```
147
+
148
+ See [CONTRIBUTING.md](CONTRIBUTING.md) and [CHANGELOG.md](CHANGELOG.md).
149
+
150
+ ## License
151
+
152
+ [Apache License 2.0](LICENSE)
@@ -0,0 +1,9 @@
1
+ libtexpr/__init__.py,sha256=MzrJbjM_c_bEC0fvlJWmlDcsNdZVEQqQd_VCm0uGel4,1301
2
+ libtexpr/engine.py,sha256=DFumk7xCkluxHqJwITYcvqyoc2z12pyRNpnTJLVtMx8,12439
3
+ libtexpr/errors.py,sha256=SykjeNbAYlDDkKlgihAddeUi_RDZgtIwkmnnrWA_lm4,2124
4
+ libtexpr/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ libtexpr/syntax.py,sha256=kks1FdToz2K7A_ngipCwZsT0XwcVylAV408r5p4PV3M,10165
6
+ libtexpr-0.1.0.dist-info/licenses/LICENSE,sha256=tQ4z49YJlXFtzCyaaAAxxofwkPwiGGEmnmj5dFL8Wok,11340
7
+ libtexpr-0.1.0.dist-info/WHEEL,sha256=3NO1oYsF7mANFUWVdyEQLM-zmecczWWEmmF5rEbXrWk,80
8
+ libtexpr-0.1.0.dist-info/METADATA,sha256=tbH_dpJg_58jGc86UHkBG1GMuQmbqlefTW74ajy1UE8,7255
9
+ libtexpr-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.6
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 StafLoker
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.