Interpreter: evaluate a tiny language
Picture
A rule is a named flag or two rules joined with AND. That is enough to express member AND active.
Predict
Should user rule text go directly into Python eval?
Walk through the small example
No, interpret a constrained grammar. Restrict the operations the rule is permitted to express.
Mental model and complete Python solution
Interpreter gives each grammar production an evaluation operation. Flag and And form a minimal boolean expression language; missing values are false by contract. User-facing systems need a parser that only builds allowed node types, validation, depth limits, and controlled context access. Trusted object construction here deliberately avoids parsing and arbitrary execution.
What the function promises: Expressions use trusted Flag and And nodes over a dictionary. A flag is enabled only when its value is exactly True.
class Flag:
def __init__(self, name):
self.name = name
def evaluate(self, context):
return context.get(self.name) is True
class And:
def __init__(self, left, right):
self.left, self.right = left, right
def evaluate(self, context):
return self.left.evaluate(context) and self.right.evaluate(context)
rule = And(Flag("member"), Flag("active"))
assert rule.evaluate({"member": True, "active": True})
assert not rule.evaluate({"member": True})
assert not rule.evaluate({"member": "yes", "active": True})
Work and storage: O(visited expression nodes), with short-circuiting and recursion proportional to depth.
When to recognize it: A larger language needs parsing, validation, and work limits. User text should not become unrestricted Python execution.
Check before applying it: Constrained languages still need limits on grammar, depth, work, and context access.
Change one rule
Rules may refer recursively to themselves. Does this tree evaluator suffice?
See what changes
No. Detect cycles or define a deliberate fixed-point interpretation. A finite-tree evaluator has no automatic semantics for recursive rules.
Connect
Composite: treat a tree uniformly: Represent a small grammar as an expression tree.
Design search and autocomplete: A search query language also needs bounded parsing and explicit operators.