Run artifact

build/jq/jq_interpreter/lexer.py

"""Lexer for the jq source language."""

from collections.abc import Iterable, Iterator
from dataclasses import dataclass
import json
import math
import re
from decimal import Decimal
from typing import Any

from .errors import CompileError


@dataclass(frozen=True, slots=True)
class Token:
    """A jq token with its decoded value and one-based source location."""

    kind: str
    value: Any
    line: int
    column: int


_NUMBER = re.compile(r"(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?")
_IDENT = re.compile(r"(?:[A-Za-z_][A-Za-z_0-9]*::)*[A-Za-z_][A-Za-z_0-9]*")
_FIELD = re.compile(r"\.[A-Za-z_][A-Za-z_0-9]*")
_BINDING = re.compile(r"\$(?:[A-Za-z_][A-Za-z_0-9]*::)*[A-Za-z_][A-Za-z_0-9]*")
_FORMAT = re.compile(r"@[A-Za-z0-9_]+")
_WORDS = {
    "as": "AS", "import": "IMPORT", "include": "INCLUDE", "module": "MODULE",
    "def": "DEF", "if": "IF", "then": "THEN", "else": "ELSE", "elif": "ELSE_IF",
    "and": "AND", "or": "OR", "end": "END", "reduce": "REDUCE", "foreach": "FOREACH",
    "try": "TRY", "catch": "CATCH", "label": "LABEL", "break": "BREAK",
}
_MULTI = {
    "!=": "NEQ", "==": "EQ", "|=": "SETPIPE", "+=": "SETPLUS", "-=": "SETMINUS",
    "*=": "SETMULT", "/=": "SETDIV", "%=": "SETMOD", "//=": "SETDEFINEDOR",
    "<=": "LESSEQ", ">=": "GREATEREQ", "..": "REC", "?//": "ALTERNATION", "//": "DEFINEDOR",
}
_PUNCTUATION = set(".?=;,:|+-*/%$<>()[]{}")


class _Scanner:
    def __init__(self, source: str):
        self.source, self.index, self.line, self.column = source, 0, 1, 1

    def position(self) -> tuple[int, int]:
        return self.line, self.column

    def advance(self, count: int = 1) -> str:
        text = self.source[self.index:self.index + count]
        for char in text:
            self.index += 1
            if char == "\n":
                self.line, self.column = self.line + 1, 1
            else:
                self.column += 1
        return text

    def error(self, message: str = "invalid character") -> CompileError:
        return CompileError(f"{message} at {self.line}:{self.column}")

    def skip_space_and_comments(self) -> None:
        while self.index < len(self.source):
            if self.source[self.index] in " \r\n\t":
                self.advance()
                continue
            if self.source[self.index] != "#":
                return
            self.advance()
            while self.index < len(self.source):
                char = self.source[self.index]
                if char == "\n":
                    self.advance()
                    break
                if char == "\\":
                    if self.source.startswith("\\\r\n", self.index):
                        self.advance(3)
                    elif self.source.startswith("\\\n", self.index) or self.source.startswith("\\\\", self.index):
                        self.advance(2)
                    else:
                        self.advance()
                else:
                    self.advance()

    def scan(self, stop: str | None = None) -> Iterator[Token]:
        while True:
            self.skip_space_and_comments()
            if self.index >= len(self.source):
                if stop is not None:
                    raise self.error(f"unterminated delimiter {stop!r}")
                return
            if stop is not None and self.source[self.index] == stop:
                return
            line, column = self.position()
            text = self.source[self.index:]
            if text.startswith('"'):
                yield from self.scan_string()
                continue
            matched = next((op for op in sorted(_MULTI, key=len, reverse=True) if text.startswith(op)), None)
            if matched:
                self.advance(len(matched))
                yield Token(_MULTI[matched], matched, line, column)
                continue
            if text.startswith("$__loc__") and not re.match(r"[A-Za-z0-9_]", text[8:9]):
                self.advance(8)
                yield Token("LOC", "$__loc__", line, column)
                continue
            match = _FORMAT.match(text)
            if match:
                spelling = match.group(); self.advance(len(spelling))
                yield Token("FORMAT", spelling[1:], line, column); continue
            match = _NUMBER.match(text)
            if match:
                spelling = match.group(); self.advance(len(spelling))
                try: value = json.loads(spelling)
                except json.JSONDecodeError:
                    try: value = float(spelling)
                    except ValueError as exc: raise self.error("invalid number") from exc
                if isinstance(value, float) and math.isinf(value):
                    exponent = int(re.search(r"[eE]([+-]?\d+)$", spelling).group(1))
                    value = (Decimal(spelling) if abs(exponent) > 1_000_000
                             else math.copysign(float.fromhex("0x1.fffffffffffffp+1023"), value))
                yield Token("LITERAL", value, line, column); continue
            match = _BINDING.match(text)
            if match:
                spelling = match.group(); self.advance(len(spelling))
                yield Token("BINDING", spelling[1:], line, column); continue
            match = _FIELD.match(text)
            if match:
                spelling = match.group(); self.advance(len(spelling))
                yield Token("FIELD", spelling[1:], line, column); continue
            match = _IDENT.match(text)
            if match:
                spelling = match.group(); self.advance(len(spelling))
                yield Token(_WORDS.get(spelling, "IDENT"), spelling, line, column); continue
            char = self.source[self.index]
            if char in "([{":
                self.advance(); yield Token(char, char, line, column)
                yield from self.scan_delimited({"(": ")", "[": "]", "{": "}"}[char]); continue
            if char in ")]}":
                if stop == char: return
                raise self.error("mismatched delimiter")
            if char in _PUNCTUATION:
                self.advance(); yield Token(char, char, line, column); continue
            raise self.error()

    def scan_delimited(self, closing: str) -> Iterator[Token]:
        yield from self.scan(stop=closing)
        if self.index >= len(self.source): raise self.error(f"unterminated delimiter {closing!r}")
        line, column = self.position(); self.advance()
        yield Token(closing, closing, line, column)

    def scan_string(self) -> Iterator[Token]:
        line, column = self.position(); self.advance()
        yield Token("QQSTRING_START", '"', line, column)
        text_start = self.position(); parts: list[str] = []

        def emit_text() -> Iterator[Token]:
            if parts:
                value = "".join(parts); parts.clear()
                yield Token("QQSTRING_TEXT", value, text_start[0], text_start[1])

        while self.index < len(self.source):
            char = self.source[self.index]
            if char == '"':
                yield from emit_text(); end_line, end_column = self.position(); self.advance()
                yield Token("QQSTRING_END", '"', end_line, end_column); return
            if char == "\\":
                if self.source.startswith("\\(", self.index):
                    yield from emit_text(); start_line, start_column = self.position(); self.advance(2)
                    yield Token("QQSTRING_INTERP_START", "\\(", start_line, start_column)
                    yield from self.scan_interpolation(); text_start = self.position(); continue
                escape_line, escape_column = self.position()
                if self.index + 1 >= len(self.source): raise self.error("unterminated string escape")
                if self.source.startswith("\\u", self.index):
                    spelling = self.source[self.index:self.index + 6]
                    if not re.fullmatch(r"\\u[0-9a-fA-F]{4}", spelling):
                        raise self.error("invalid string escape")
                else:
                    spelling = self.source[self.index:self.index + 2]
                    if spelling[1] not in '"\\/bfnrt':
                        raise CompileError(f"invalid string escape at {escape_line}:{escape_column}")
                try: parts.append(json.loads('"' + spelling + '"'))
                except json.JSONDecodeError as exc:
                    raise CompileError(f"invalid string escape at {escape_line}:{escape_column}") from exc
                self.advance(len(spelling)); continue
            if char in "\r\n": raise self.error("unterminated string")
            parts.append(char); self.advance()
        raise self.error("unterminated string")

    def scan_interpolation(self) -> Iterator[Token]:
        yield from self.scan(stop=")")
        if self.index >= len(self.source): raise self.error("unterminated interpolation")
        line, column = self.position(); self.advance()
        yield Token("QQSTRING_INTERP_END", ")", line, column)


def tokenize(source: str) -> Iterable[Token]:
    """Yield jq tokens, rejecting invalid characters and unbalanced syntax."""
    if not isinstance(source, str): raise TypeError("source must be text")
    return _Scanner(source).scan()