"""
**File:** ``grammar.py``
**Region:** ``ds-common-placeholder-py-lib``
Description
-----------
Single-pass scanner for the ``standard`` grammar (contract §3). Splits a
string into text and placeholders and parses each placeholder into an AST.
"""
from __future__ import annotations
import math
import re
from dataclasses import dataclass
from typing import Any
from .errors import ErrorCode, PlaceholderError
_NAME = re.compile(r"[A-Za-z0-9_]+")
# A path segment also allows "-" and ":", so ids such as UUIDs and task names
# like READ::POSTGRESQL can be used as keys. "." separates segments.
_SEGMENT = re.compile(r"[A-Za-z0-9_:-]+")
# A namespace is any name that starts with a letter or "_". Which namespaces
# exist is decided by the context, not by the grammar.
_NAMESPACE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
_WHITESPACE = " \t\r\n"
BLANK = " \t\n\r\f\v"
"""Characters a blank string consists of (contract §8.2). ASCII only, so every
implementation agrees."""
_QUOTES = "'\""
[docs]
@dataclass(frozen=True)
class Literal:
"""A string argument."""
value: str
LOOKUP = "lookup"
"""The function that reads a reference: ``@{lookup, owner.settings.tz}`` is
``@{owner.settings.tz}``; ``@{lookup, owner}`` reads the whole namespace."""
FORMATS = ("str", "json", "int", "float", "bool")
"""``lookup``'s optional format, its last argument: the value as text
(``str``), as compact JSON text (``json``), or as a whole number, a number or
a boolean (``int``, ``float``, ``bool``). A default cannot be one of these
words. Without a format a default is text."""
TYPES = ("int", "float", "bool")
"""The formats that give the value a JSON type."""
_FLOAT = re.compile(r"-?[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?")
_WHOLE = re.compile(r"-?[0-9]+")
_MAX_DIGITS = 4000 # Python refuses to convert longer digit strings
[docs]
def to_type(value: Any, fmt: str) -> Any:
"""*value* as the JSON type *fmt* names (``int``, ``float``, ``bool``):
already that type, or text that spells it (``"3"``, ``"2.5"``,
``"true"``). Nothing is guessed: ``"yes"`` is not a boolean.
Raises:
ValueError: *value* is not, or does not spell, that type.
"""
ok = not isinstance(value, bool) if fmt != "bool" else isinstance(value, bool)
if fmt == "bool":
if ok:
return value
if value in ("true", "false"):
return value == "true"
elif ok and isinstance(value, int):
if fmt == "int":
return value
try:
return float(value)
except OverflowError:
pass # too large for a float: not one
elif ok and isinstance(value, float) and math.isfinite(value):
if fmt == "float":
return value
if value.is_integer():
return int(value)
elif ok and isinstance(value, str):
if fmt == "int" and len(value) <= _MAX_DIGITS and _WHOLE.fullmatch(value):
return int(value)
if fmt == "float" and len(value) <= _MAX_DIGITS and _FLOAT.fullmatch(value) and math.isfinite(float(value)):
return float(value)
raise ValueError(f"not {'an' if fmt == 'int' else 'a'} {fmt}")
NOT_READ_WHOLE = frozenset({"tasks"})
"""Namespaces ``lookup`` cannot read whole: ``tasks`` is every task's output,
unbounded, so a read names a task (``tasks.<id>``)."""
[docs]
@dataclass(frozen=True)
class Reference:
"""``<namespace>.<path>``, or ``@{lookup, <namespace>[.<path>][, <default>][, <format>]}``
(an empty *path* is the whole namespace). *default* is the text read
when there is no value."""
namespace: str
path: tuple[str, ...]
format: str | None = None
default: str | None = None
[docs]
@dataclass(frozen=True)
class Call:
"""``<name>`` or ``<name>, <arg>, …``. An argument written as a
placeholder, ``@{f, @{g, x}}``, is the expression it holds: a
:class:`Call`, a :class:`Reference` (``@{lookup, …}``), or a
:class:`Literal` (``@{'…'}``)."""
name: str
args: tuple[Literal | Reference | Call, ...]
Expr = Reference | Call | Literal
"""A placeholder's expression. A :class:`Literal` is a quoted text,
``@{'@{'}``: the way to write ``@{`` as text."""
MAX_DEPTH = 16
"""How deep placeholders can be nested: ``@{a, @{b, @{c}}}`` is depth 2."""
[docs]
@dataclass(frozen=True)
class Text:
"""Plain text. It never contains ``@{``: that always starts a
placeholder."""
value: str
[docs]
@dataclass(frozen=True)
class Placeholder:
"""One ``@{…}`` and its offsets in the scanned string."""
expr: Expr
raw: str
start: int
end: int
Segment = Text | Placeholder
[docs]
def escape(text: str) -> str:
"""Write *text* so that resolving it gives exactly *text*: every ``@{``
becomes the placeholder ``@{'@{'}``, which resolves to ``@{``. Use it
for a value from outside that must be taken literally, such as a
caller's override of a declared variable.
Args:
text: Any string.
Returns:
*text*, with no ``@{`` left that would start a placeholder.
"""
return text.replace("@{", "@{'@{'}")
[docs]
def parse_path(path: str) -> tuple[str, ...]:
"""Read a path to a value in a JSON document, written like a reference:
keys separated by ``.``, an array item by its index, and a key with other
characters in quotes (``tasks.0.settings.'a.b'``).
Args:
path: The path.
Returns:
Its keys, in order (array indexes as strings).
Raises:
TypeError: If *path* is not a string.
ValueError: If *path* is not such a path.
"""
if not isinstance(path, str):
raise TypeError(f"a path must be a string, not {type(path).__name__}")
text = "@{" + path + "}"
scanner = _Scanner(text, 0)
try:
items = scanner.items()
except PlaceholderError:
items = []
if (
len(items) != 1
or isinstance(items[0], _Nested)
or scanner.pos != len(text)
or any(not part or (not quoted and not _SEGMENT.fullmatch(part)) for part, quoted in items[0])
):
raise ValueError(f"not a path: {path!r}")
return tuple(part for part, _ in items[0])
[docs]
def write(expr: Expr) -> str:
"""The placeholder text of *expr*: parsing it gives *expr* back. Every
literal is written quoted, so a value with ``,``, ``}`` or ``@{`` in it
stays one literal.
Args:
expr: A parsed expression.
Returns:
``@{…}``.
"""
if isinstance(expr, Literal):
return "@{" + _quote(expr.value) + "}"
if isinstance(expr, Reference):
if expr.format is None and expr.default is None and expr.path:
return "@{" + _path_text(expr) + "}"
default = f", {_quote(expr.default)}" if expr.default is not None else ""
fmt = f", {expr.format}" if expr.format is not None else ""
return "@{" + LOOKUP + ", " + _path_text(expr) + default + fmt + "}"
return "@{" + "".join([expr.name, *(", " + _arg_text(arg) for arg in expr.args)]) + "}"
def _quote(text: str) -> str:
return "'" + text.replace("'", "''") + "'"
def _path_text(ref: Reference) -> str:
return ".".join([ref.namespace, *(part if _SEGMENT.fullmatch(part) else _quote(part) for part in ref.path)])
def _arg_text(arg: Literal | Reference | Call) -> str:
if isinstance(arg, Literal):
return _quote(arg.value)
if isinstance(arg, Reference) and arg.format is None and arg.default is None and arg.path:
return _path_text(arg)
return write(arg)
[docs]
def reference_text(ref: Reference) -> str:
"""*ref* as written in a path: ``owner.settings.'a b'``; a whole
namespace is its name."""
return _path_text(ref)
[docs]
def namespaces(expr: Expr) -> frozenset[str]:
"""Every namespace *expr* reads, nested placeholders included."""
if isinstance(expr, Reference):
return frozenset({expr.namespace})
if isinstance(expr, Call):
return frozenset().union(*(namespaces(arg) for arg in expr.args))
return frozenset()
[docs]
def calls(expr: Expr) -> list[Call]:
"""Every call in *expr*, outermost first, nested ones included."""
if not isinstance(expr, Call):
return []
found = [expr]
for arg in expr.args:
found.extend(calls(arg))
return found
[docs]
def parse(text: str) -> list[Segment]:
"""Split *text* into text and placeholder segments.
Args:
text: The string to scan.
Returns:
The segments in order. Adjacent text is merged.
Raises:
PlaceholderError: ``syntax`` for any malformed ``@{…}``.
"""
segments: list[Segment] = []
buf: list[str] = []
i = 0
n = len(text)
while i < n:
if text.startswith("@{", i):
if buf:
segments.append(Text("".join(buf)))
buf = []
placeholder = _Scanner(text, i).scan()
segments.append(placeholder)
i = placeholder.end
else:
buf.append(text[i])
i += 1
if buf:
segments.append(Text("".join(buf)))
return segments
@dataclass(frozen=True)
class _Nested:
"""A placeholder written as a whole item, scanned but not yet built: the
placeholder around it is checked first, so its own error is reported
before any error inside the nested one."""
scanner: _Scanner
items: list[Item]
end: int
def expr(self) -> Expr:
return self.scanner.expression(self.items, self.end)
Item = list[tuple[str, bool]] | _Nested
"""One comma-separated item: its dot-separated parts, each a
``(text, quoted)`` pair, or a placeholder written as the whole item."""
class _Scanner:
def __init__(self, text: str, start: int, depth: int = 0) -> None:
self.text = text
self.start = start
self.pos = start + 2
self.depth = depth
def error(self, message: str, end: int | None = None) -> PlaceholderError:
raw = self.text[self.start : end if end is not None else len(self.text)]
return PlaceholderError(ErrorCode.SYNTAX, message, placeholder=raw)
def scan(self) -> Placeholder:
items = self.items()
end = self.pos
return Placeholder(self.expression(items, end), self.text[self.start : end], self.start, end)
def items(self) -> list[Item]:
"""Read the comma-separated items up to the closing ``}``."""
items: list[Item] = []
while True:
self.skip_whitespace()
items.append(self.item())
self.skip_whitespace()
if self.pos >= len(self.text):
raise self.error("unclosed placeholder")
ch = self.text[self.pos]
self.pos += 1
if ch == "}":
break
if ch != ",":
raise self.error("expected ',' or '}'", self.pos)
return items
def skip_whitespace(self) -> None:
while self.pos < len(self.text) and self.text[self.pos] in _WHITESPACE:
self.pos += 1
def item(self) -> Item:
"""Read one comma-separated item as its dot-separated parts, each
``(text, quoted)``. A quote starts a part only at the start of the
item or right after a dot: ``owner.settings.'company.key'``. An item
that starts with ``@{`` is a nested placeholder, and must be the
whole item."""
if self.pos >= len(self.text):
raise self.error("unclosed placeholder")
if self.text.startswith("@{", self.pos):
if self.depth >= MAX_DEPTH:
raise self.error(f"placeholders nested more than {MAX_DEPTH} deep")
scanner = _Scanner(self.text, self.pos, self.depth + 1)
items = scanner.items()
self.pos = scanner.pos
return _Nested(scanner, items, scanner.pos)
parts: list[tuple[str, bool]] = []
while True:
if self.pos < len(self.text) and self.text[self.pos] in _QUOTES:
parts.append((self.quoted(self.text[self.pos]), True))
else:
begin = self.pos
while self.pos < len(self.text):
ch = self.text[self.pos]
if ch in _WHITESPACE or ch in ",}." or ch in _QUOTES:
break
if self.text.startswith("@{", self.pos):
raise self.error("a nested placeholder must be a whole argument")
self.pos += 1
parts.append((self.text[begin : self.pos], False))
if self.pos < len(self.text) and self.text[self.pos] == ".":
self.pos += 1
continue
break
if parts == [("", False)]:
raise self.error("empty expression or argument", min(self.pos + 1, len(self.text)))
return parts
def quoted(self, quote: str) -> str:
self.pos += 1
out: list[str] = []
while self.pos < len(self.text):
ch = self.text[self.pos] # inside quotes "@{" is text
if ch == quote:
if self.text.startswith(quote * 2, self.pos):
out.append(quote)
self.pos += 2
continue
self.pos += 1
return "".join(out)
out.append(ch)
self.pos += 1
raise self.error("unclosed quote")
def expression(self, items: list[Item], end: int) -> Expr:
head = items[0]
if isinstance(head, _Nested):
raise self.error("a placeholder is not a function name: it can only be an argument", end)
if len(head) > 1:
if len(items) > 1:
raise self.error("a reference takes no arguments", end)
return self.reference(head, end)
name, quoted = head[0]
if quoted:
if len(items) > 1:
raise self.error("a quoted text takes no arguments", end)
return Literal(name)
if not _NAME.fullmatch(name):
raise self.error("invalid function name", end)
if name == LOOKUP:
return self.lookup(items[1:], end)
args: list[Literal | Reference | Call] = []
for parts in items[1:]:
if isinstance(parts, _Nested):
args.append(parts.expr()) # its value is the argument, never re-scanned
elif len(parts) == 1:
args.append(Literal(parts[0][0]))
elif any(quoted for _, quoted in parts):
# A quoted segment only makes sense in a reference.
args.append(self.reference(parts, end))
else:
# A bare name.path is a reference; quote it to pass it as text.
text = ".".join(part for part, _ in parts)
args.append(self.reference(parts, end) if _is_reference(text) else Literal(text))
return Call(name, tuple(args))
def lookup(self, args: list[Item], end: int) -> Reference:
"""``lookup``: its first argument is a path, read as it is written
(never resolved first), an optional default and an optional format."""
raw = self.text[self.start : end]
if not 1 <= len(args) <= 3:
raise PlaceholderError(
ErrorCode.ARITY,
f"lookup takes a path, an optional default and an optional format, got {len(args)} arguments",
placeholder=raw,
)
written = [arg for arg in args if not isinstance(arg, _Nested)]
if len(written) != len(args):
raise PlaceholderError(
ErrorCode.ARGUMENT, "lookup's path, default and format are written out, not placeholders", placeholder=raw
)
ref = self.reference(written[0], end)
if not ref.path and ref.namespace in NOT_READ_WHOLE:
raise PlaceholderError(
ErrorCode.ARGUMENT, f"lookup cannot read all of {ref.namespace}: name one, {ref.namespace}.<id>", placeholder=raw
)
rest = written[1:]
fmt = default = None
# A last argument that is str or json is the format; anything else is
# the default.
if rest and len(rest[-1]) == 1 and rest[-1][0][0] in FORMATS:
fmt = rest.pop()[0][0]
if len(rest) == 1:
default = ".".join(part for part, _ in rest[0])
elif rest:
raise PlaceholderError(
ErrorCode.ARGUMENT,
f"lookup takes at most one default, then an optional format ({', '.join(FORMATS)})",
placeholder=raw,
)
if default is not None and not default.strip(BLANK):
raise PlaceholderError(ErrorCode.ARGUMENT, "lookup's default cannot be blank", placeholder=raw)
if default is not None and fmt in TYPES:
try:
to_type(default, fmt)
except ValueError:
raise PlaceholderError(
ErrorCode.ARGUMENT, f"lookup's default {default!r} is not a valid {fmt}", placeholder=raw
) from None
return Reference(ref.namespace, ref.path, fmt, default)
def reference(self, parts: list[tuple[str, bool]], end: int) -> Reference:
namespace, quoted = parts[0]
if quoted or not _NAMESPACE.fullmatch(namespace):
raise self.error("invalid reference", end)
for part, part_quoted in parts[1:]:
if not part or (not part_quoted and not _SEGMENT.fullmatch(part)):
raise self.error("invalid reference", end)
return Reference(namespace, tuple(part for part, _ in parts[1:]))
def _is_reference(text: str) -> bool:
"""``<namespace>.<segment>[.<segment>…]``."""
parts = text.split(".")
return len(parts) > 1 and _NAMESPACE.fullmatch(parts[0]) is not None and all(_SEGMENT.fullmatch(part) for part in parts[1:])