解释器:明确文法、完整解析与受限执行
从文法构造表达式对象,拒绝未支持的语法,避免陈旧缓存。
本页展示最近一次实际本地Python命名测试结果,不是在线Python解释器。外部服务、真实硬件及完整来源语义仍分别验收。
| 检查项 | 实际结果 | 预期结果 |
|---|---|---|
| actual grammar 2+3*4 | 14 | 14 |
| actual grammar (2+3)*4 | 20 | 20 |
| actual grammar (x+3)*(y-2) | 39 | 39 |
| actual grammar -7 % 3 | 2 | 2 |
| actual grammar 7 / 2 | "Fraction(7, 2)" | "Fraction(7, 2)" |
| actual grammar +3-2 | 1 | 1 |
| initial context | 2 | 2 |
| same object changed context not stale cache | 10 | 10 |
| predicate x>5 | true | true |
| predicate x<5 | false | false |
| predicate x>=9 | true | true |
| predicate x<=9 | true | true |
| predicate x==9 | true | true |
| predicate x!=9 | false | false |
| predicate NOT (x < 5) AND x <= 9 | true | true |
| predicate True OR missing > 1 | true | true |
| predicate False AND missing > 1 | false | false |
| predicate 1 < x < 10 | true | true |
| missing variable explicit | "KeyError" | "KeyError" |
| zero division | "ZeroDivisionError" | "ZeroDivisionError" |
| zero modulo | "ZeroDivisionError" | "ZeroDivisionError" |
| reject syntax/capability '' | "ValueError" | "ValueError" |
| reject syntax/capability '2 3' | "ValueError" | "ValueError" |
| reject syntax/capability '(2+3' | "ValueError" | "ValueError" |
| reject syntax/capability '2+' | "ValueError" | "ValueError" |
| reject syntax/capability 'f()' | "ValueError" | "ValueError" |
| reject syntax/capability 'a.b' | "ValueError" | "ValueError" |
| reject syntax/capability 'a[0]' | "ValueError" | "ValueError" |
| reject syntax/capability '2**4' | "ValueError" | "ValueError" |
| reject syntax/capability '[x for x in y]' | "ValueError" | "ValueError" |
| reject syntax/capability "__import__('os')" | "ValueError" | "ValueError" |
| reject syntax/capability 'x=1' | "ValueError" | "ValueError" |
| arithmetic type boundary | "TypeError" | "TypeError" |
| logical bool boundary | "TypeError" | "TypeError" |
| large result bound | "ValueError" | "ValueError" |
| WHERE-like filter actual decision | ["Charlie"] | ["Charlie"] |
| rule engine output | {"eligible": true, "review": false} | {"eligible": true, "review": false} |
本章源码与生成文件
查看当前核心代码
from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *
def interpreter(c,out):
from fractions import Fraction
dsl=SmallDsl()
for text,expected in [("2+3*4",14),("(2+3)*4",20),("(x+3)*(y-2)",39),("-7 % 3",2),("7 / 2",Fraction(7,2)),("+3-2",1)]:c.eq("actual grammar "+text,dsl.evaluate(dsl.parse(text),{"x":10,"y":5}),expected)
context={"x":1};expression=dsl.parse("x+1");c.eq("initial context",dsl.evaluate(expression,context),2);context["x"]=9;c.eq("same object changed context not stale cache",dsl.evaluate(expression,context),10)
for text,expected in [("x>5",True),("x<5",False),("x>=9",True),("x<=9",True),("x==9",True),("x!=9",False),("NOT (x < 5) AND x <= 9",True),("True OR missing > 1",True),("False AND missing > 1",False),("1 < x < 10",True)]:c.eq("predicate "+text,dsl.evaluate(dsl.parse(text),context),expected)
c.raises("missing variable explicit",KeyError,lambda:dsl.evaluate(dsl.parse("missing+1"),{}));c.raises("zero division",ZeroDivisionError,lambda:dsl.evaluate(dsl.parse("1/0"),{}));c.raises("zero modulo",ZeroDivisionError,lambda:dsl.evaluate(dsl.parse("1%0"),{}))
for text in ("", "2 3", "(2+3", "2+", "f()", "a.b", "a[0]", "2**4", "[x for x in y]", "__import__('os')", "x=1"):
c.raises("reject syntax/capability "+repr(text),ValueError,lambda:dsl.parse(text))
c.raises("arithmetic type boundary",TypeError,lambda:dsl.evaluate(dsl.parse("x+1"),{"x":"text"}));c.raises("logical bool boundary",TypeError,lambda:dsl.evaluate(dsl.parse("x AND True"),{"x":1}));c.raises("large result bound",ValueError,lambda:dsl.evaluate(dsl.parse("10000000*10000000"),{}))
records=[{"name":"Alice","age":25,"department":"Engineering"},{"name":"Bob","age":30,"department":"Sales"},{"name":"Charlie","age":28,"department":"Engineering"}]
rule=dsl.parse("department == 'Engineering' AND age > 26");decision=[row["name"]for row in records if dsl.evaluate(rule,row)];c.eq("WHERE-like filter actual decision",decision,["Charlie"])
rules={"eligible":dsl.parse("age >= 18 AND score >= 60"),"review":dsl.parse("score < 60 OR NOT active")};sample={"age":20,"score":70,"active":True};result={name:dsl.evaluate(rule,sample)for name,rule in rules.items()};c.eq("rule engine output",result,{"eligible":True,"review":False});(out/"rule-decisions.json").write_text(json.dumps(result),encoding="utf8")
def run_case(out):
c=Checks()
interpreter(c,out)
return {"chapter":'python-interpreter',"checks":c.rows,"passed":True,"scope":"named owned all24chapter named cases only; full source coverage pending"}
if __name__ == "__main__":
output=Path(sys.argv[1]);output.mkdir(parents=True,exist_ok=False)
print(json.dumps(run_case(output),ensure_ascii=False,default=repr))