"""Recursive-descent parser and static validator for jq programs."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from .errors import CompileError
from .lexer import Token, tokenize
@dataclass(frozen=True, slots=True)
class Node:
kind: str
value: Any = None
children: tuple["Node", ...] = ()
@dataclass(frozen=True, slots=True)
class Program:
source: str
tokens: tuple[Token, ...]
tree: Node | None = None
_OPS = {"DEFINEDOR": (1, "//"), "OR": (2, "or"), "AND": (3, "and"),
"EQ": (4, "=="), "NEQ": (4, "!="), "<": (4, "<"), ">": (4, ">"),
"LESSEQ": (4, "<="), "GREATEREQ": (4, ">="), "+": (5, "+"),
"-": (5, "-"), "*": (6, "*"), "/": (6, "/"), "%": (6, "%"),
"=": (0, "="), "SETPIPE": (0, "|="), "SETPLUS": (0, "+="),
"SETMINUS": (0, "-="), "SETMULT": (0, "*="), "SETDIV": (0, "/="),
"SETMOD": (0, "%="), "SETDEFINEDOR": (0, "//=")}
_KEYWORDS = {"AS", "DEF", "MODULE", "IMPORT", "INCLUDE", "IF", "THEN", "ELSE",
"ELSE_IF", "REDUCE", "FOREACH", "END", "AND", "OR", "TRY", "CATCH",
"LABEL", "BREAK"}
class _Parser:
def __init__(self, source: str, tokens: tuple[Token, ...]):
self.source, self.tokens, self.pos = source, tokens, 0
self.scopes: list[set[str]] = [set()]
self.labels: list[set[str]] = []
self.functions: dict[str, int] = {}
self.filter_params: list[set[str]] = []
def current(self) -> Token | None:
return self.tokens[self.pos] if self.pos < len(self.tokens) else None
def accept(self, kind: str) -> Token | None:
if self.current() and self.current().kind == kind:
token = self.current(); self.pos += 1; return token
return None
def expect(self, kind: str, message: str | None = None) -> Token:
token = self.accept(kind)
if token is None:
got = self.current(); place = "end of input" if got is None else f"{got.kind!r} at {got.line}:{got.column}"
raise CompileError(message or f"expected {kind!r}, got {place}")
return token
def fail(self, message: str, token: Token | None = None) -> CompileError:
token = token or self.current()
return CompileError(message if token is None else f"{message} at {token.line}:{token.column}")
def bound(self, name: str) -> bool:
return any(name in scope for scope in reversed(self.scopes))
def parse(self) -> Node:
directives = []
while self.current() and self.current().kind in {"MODULE", "IMPORT", "INCLUDE", "DEF"}:
directives.append(self.parse_function() if self.current().kind == "DEF" else self.parse_directive())
if self.current() is None: raise self.fail("program is empty")
query = self.query()
if self.current(): raise self.fail("unexpected token")
return Node("program", children=tuple(directives + [query]))
def parse_directive(self) -> Node:
tok = self.current(); self.pos += 1
if tok.kind == "MODULE":
metadata = self.query(); self.expect(";", "module directive requires ';'")
if metadata.kind != "object": raise self.fail("module metadata must be a constant object", tok)
return Node("module", children=(metadata,))
path = self.string()
if path.kind != "string" or len(path.children) != 1 or path.children[0].kind != "literal":
raise self.fail("module path must be a constant string", tok)
if tok.kind == "IMPORT":
self.expect("AS", "import requires 'as'"); alias = self.expect("BINDING").value
else: alias = None
self.expect(";", "import/include directive requires ';'")
return Node(tok.kind.lower(), alias, (path,))
def parse_function(self) -> Node:
self.expect("DEF"); name = self.expect("IDENT").value; params = []
if self.accept("(") and not self.accept(")"):
while True:
tok = self.current()
if not tok or tok.kind not in {"IDENT", "BINDING"}: raise self.fail("expected function parameter")
self.pos += 1; params.append(("$" if tok.kind == "BINDING" else "") + tok.value)
if self.accept(")"): break
self.expect(";", "function parameters are separated by ';'")
self.expect(":", "function definition requires ':'"); self.functions[name] = len(params)
self.scopes.append({name.lstrip("$") for name in params})
self.filter_params.append({name for name in params if not name.startswith("$")})
body = self.query(); self.filter_params.pop(); self.scopes.pop()
self.expect(";", "function definition requires ';'")
return Node("function", (name, tuple(params)), (body,))
def query(self) -> Node:
if self.current() and self.current().kind == "DEF":
definition = self.parse_function()
return Node("def", children=(definition, self.query()))
left = self.pipe_expr()
if self.accept("AS"):
patterns = [self.pattern()]
while self.accept("ALTERNATION"):
patterns.append(self.pattern())
pattern = patterns[0] if len(patterns) == 1 else Node("pattern_alt", children=tuple(patterns))
self.expect("|", "binding requires '|'")
self.scopes.append(self.names(pattern)); right = self.query(); self.scopes.pop()
if left.kind == "pipe":
left = Node("pipe", children=(left.children[0], Node("bind", children=(left.children[1], pattern, right))))
return left
return Node("bind", children=(left, pattern, right))
return left
def pipe_expr(self) -> Node:
"""Parse pipes below comma expressions.
jq applies a pipe to the complete comma expression on its left, so
``a,b | f`` means ``(a,b) | f``. Keeping this level separate from
``query`` also makes the same rule apply inside array constructors.
"""
left = self.comma_expr()
if self.accept("|"):
return Node("pipe", children=(left, self.pipe_expr()))
return left
def comma_expr(self) -> Node:
left = self.expr()
if self.accept(","):
if self.current() and self.current().kind == "DEF":
definition = self.parse_function()
right = Node("def", children=(definition, self.query()))
else:
right = self.comma_expr()
return Node("comma", children=(left, right))
return left
def expr(self, minimum: int = 0) -> Node:
left = self.term()
while self.current() and self.current().kind in _OPS and _OPS[self.current().kind][0] >= minimum:
tok = self.current(); precedence, spelling = _OPS[tok.kind]; self.pos += 1
right = self.expr(precedence + (0 if precedence == 0 else 1)); left = Node("binary", spelling, (left, right))
return left
def term(self) -> Node:
node = self.atom()
while True:
if node.kind == "dot" and self.current() and self.current().kind in {"QQSTRING_START", "FORMAT"}:
node = Node("index", children=(node, self.string())); continue
if self.accept("?"): node = Node("optional", children=(node,)); continue
if self.accept("["):
if self.accept("]"): node = Node("each", children=(node,)); continue
first = Node("null") if self.accept(":") else self.query()
if first.kind == "null":
last = self.query(); self.expect("]")
node = Node("slice", children=(node, first, last)); continue
if self.accept(":"):
last = Node("null") if self.accept("]") else self.query()
if last.kind != "null": self.expect("]")
node = Node("slice", children=(node, first, last))
else: self.expect("]"); node = Node("index", children=(node, first))
continue
if self.accept("."):
if self.accept("["):
if self.accept("]"): node = Node("each", children=(node,))
else:
value = self.query(); self.expect("]"); node = Node("index", children=(node, value))
elif self.current() and self.current().kind in {"QQSTRING_START", "FORMAT"}:
node = Node("index", children=(node, self.string()))
else:
raise self.fail("expected field name after '.'")
continue
field = self.accept("FIELD")
if field: node = Node("index", field.value, (node, Node("literal", field.value))); continue
break
return node
def atom(self) -> Node:
tok = self.current()
if tok is None: raise self.fail("expected expression")
if tok.kind == "-": self.pos += 1; return Node("negate", children=(self.term(),))
if tok.kind == "LITERAL": self.pos += 1; return Node("literal", tok.value)
if tok.kind == "FIELD": self.pos += 1; return Node("index", tok.value, (Node("dot"), Node("literal", tok.value)))
if tok.kind == ".": self.pos += 1; return Node("dot")
if tok.kind == "REC": self.pos += 1; return Node("recurse")
if tok.kind == "BINDING":
self.pos += 1
if tok.value == "ENV": return Node("env_variable")
if not self.bound(tok.value): raise self.fail(f"unknown variable ${tok.value}", tok)
return Node("variable", tok.value)
if tok.kind == "LOC":
self.pos += 1
return Node("loc", ("<top-level>", tok.line))
if tok.kind == "FORMAT":
self.pos += 1
if self.current() and self.current().kind == "QQSTRING_START":
formatted = self.string()
return Node("string", tok.value, formatted.children)
return Node("format", tok.value, (Node("dot"),))
if tok.kind == "QQSTRING_START": return self.string()
if tok.kind == "IDENT":
self.pos += 1; name = tok.value
if name in {"true", "false", "null"}: return Node("literal", {"true": True, "false": False, "null": None}[name])
if any(name in params for params in reversed(self.filter_params)):
return Node("filter_param", name)
args = []
if self.accept("(") and not self.accept(")"):
while True:
args.append(self.query())
if self.accept(")"): break
self.expect(";", "function arguments are separated by ';'")
if name in self.functions and self.functions[name] != len(args):
raise self.fail("function arity mismatch", tok)
return Node("call", (name, len(args)), tuple(args))
if tok.kind == "(": self.pos += 1; value = self.query(); self.expect(")"); return value
if tok.kind == "[":
self.pos += 1
if self.accept("]"): return Node("array")
value = self.query(); self.expect("]"); return Node("array", children=(value,))
if tok.kind == "{": return self.object()
if tok.kind == "IF": return self.if_expr()
if tok.kind in {"TRY", "REDUCE", "FOREACH", "LABEL", "BREAK"}: return self.control()
raise self.fail("expected expression", tok)
def string(self) -> Node:
fmt = None
if self.accept("FORMAT"): fmt = self.tokens[self.pos - 1].value
self.expect("QQSTRING_START"); parts = []
while self.current() and self.current().kind != "QQSTRING_END":
text = self.accept("QQSTRING_TEXT")
if text: parts.append(Node("literal", text.value)); continue
if self.accept("QQSTRING_INTERP_START"):
parts.append(self.query()); self.expect("QQSTRING_INTERP_END"); continue
raise self.fail("invalid string interpolation")
self.expect("QQSTRING_END"); return Node("string", fmt, tuple(parts))
def object(self) -> Node:
self.expect("{"); pairs = []
if self.accept("}"): return Node("object")
while True:
tok = self.current()
if not tok: raise self.fail("unterminated object")
if tok.kind == "BINDING":
# `{ $x }` is shorthand for `{ x: $x }`: the dollar name is
# removed from the object key, while the value remains a
# variable lookup.
self.pos += 1; key = Node("literal", tok.value)
shorthand_value = Node("variable", tok.value)
elif tok.kind == "LOC":
self.pos += 1; key = Node("literal", "__loc__")
elif tok.kind in {"IDENT"} or tok.kind in _KEYWORDS:
self.pos += 1; key = Node("literal", tok.value)
elif tok.kind == "QQSTRING_START": key = self.string()
elif tok.kind == "(":
self.pos += 1; key = self.query(); self.expect(")")
if key.kind == "literal" and not isinstance(key.value, str): raise self.fail("constant object key must be a string", tok)
else: raise self.fail("invalid object key", tok)
# DictExpr in jq uses expression precedence; a comma here separates
# object entries rather than becoming a generator in the value.
if tok.kind == "BINDING" and self.current() and self.current().kind == ":":
self.pos += 1
key = Node("variable", tok.value)
value = self.expr()
else:
value = self.expr() if self.accept(":") else (
Node("loc", ("<top-level>", tok.line)) if tok.kind == "LOC"
else shorthand_value if tok.kind == "BINDING"
else Node("index", children=(Node("dot"), key))
)
while self.accept("|"):
value = Node("pipe", children=(value, self.expr()))
pairs.append(Node("pair", children=(key, value)))
if self.accept("}"): break
self.expect(",", "object entries are separated by ','")
return Node("object", children=tuple(pairs))
def pattern(self) -> Node:
tok = self.current()
if tok and tok.kind == "BINDING": self.pos += 1; return Node("pattern", tok.value)
if tok and tok.kind in {"[", "{"}:
opener = tok.kind; closer = "]" if opener == "[" else "}"; self.pos += 1; items = []
if not self.accept(closer):
while True:
if opener == "{" and self.current() and self.current().kind in ({"IDENT", "BINDING"} | _KEYWORDS):
key = self.current(); self.pos += 1
key_name = ("$" if key.kind == "BINDING" else "") + key.value
if self.accept(":"): items.append(Node("object_pattern", key_name, (self.pattern(),)))
else:
name = key.value.lstrip("$")
items.append(Node("object_pattern", ("$" if key.kind == "BINDING" else "") + name, (Node("pattern", name),)))
elif opener == "{" and self.current() and self.current().kind == "QQSTRING_START":
key = self.string()
if key.kind != "string" or len(key.children) != 1 or key.children[0].kind != "literal":
raise self.fail("object pattern key must be constant")
key_name = key.children[0].value
self.expect(":")
items.append(Node("object_pattern", key_name, (self.pattern(),)))
elif opener == "{" and self.current() and self.current().kind == "(":
self.pos += 1
key = self.query()
self.expect(")")
if key.kind == "literal" and not isinstance(key.value, str):
raise self.fail("object pattern key must be a string")
self.expect(":")
items.append(Node("computed_object_pattern", key, (self.pattern(),)))
else: items.append(self.pattern())
if self.accept(closer): break
self.expect(",")
if not items:
raise self.fail("empty binding pattern", tok)
return Node("pattern_group", opener, tuple(items))
raise self.fail("expected binding pattern", tok)
def names(self, node: Node) -> set[str]:
if node.kind == "pattern": return {node.value}
if node.kind == "object_pattern":
return {node.value.lstrip("$")} | self.names(node.children[0])
return {n for child in node.children for n in self.names(child)}
def if_expr(self) -> Node:
self.expect("IF"); values = [self.query()]; self.expect("THEN"); values.append(self.query())
while self.accept("ELSE_IF"): values.append(self.query()); self.expect("THEN"); values.append(self.query())
if self.accept("ELSE"): values.append(self.query())
else: values.append(Node("dot"))
self.expect("END"); return Node("if", children=tuple(values))
def control(self) -> Node:
tok = self.current(); self.pos += 1
if tok.kind == "BREAK":
name = self.expect("BINDING").value
if not any(name in labels for labels in self.labels): raise self.fail(f"break to unknown label ${name}", tok)
return Node("break", name)
if tok.kind == "LABEL":
name = self.expect("BINDING").value; self.expect("|"); self.labels.append({name}); body = self.query(); self.labels.pop()
return Node("label", name, (body,))
if tok.kind == "TRY":
# ``//`` binds outside an unparenthesized try body, so that
# ``try error // fallback`` can recover through the alternative.
body = self.expr(2); handler = self.expr(6) if self.accept("CATCH") else Node("backtrack")
return Node("try", children=(body, handler))
stream = self.expr(); self.expect("AS"); pattern = self.pattern(); self.expect("(")
self.scopes.append(self.names(pattern))
initial = self.query(); self.expect(";"); update = self.query(); extra = Node("null")
if self.accept(";"): extra = self.query()
self.scopes.pop(); self.expect(")")
if tok.kind == "FOREACH" and extra.kind == "null":
extra = Node("identity")
return Node(tok.kind.lower(), children=(stream, pattern, initial, update, extra))
def parse(source: str) -> Program:
"""Parse source into an AST, raising :class:`CompileError` on syntax or scope errors."""
if not isinstance(source, str): raise CompileError("source must be text")
try:
tokens = tuple(tokenize(source)); tree = _Parser(source, tokens).parse()
except CompileError: raise
except (TypeError, ValueError, IndexError) as exc: raise CompileError("unable to parse source") from exc
return Program(source, tokens, tree)
Run artifact