蓝色天空网 · mbsky.com 全部实例

解释器:明确文法、完整解析与受限执行

从文法构造表达式对象,拒绝未支持的语法,避免陈旧缓存。

本页展示最近一次实际本地Python命名测试结果,不是在线Python解释器。外部服务、真实硬件及完整来源语义仍分别验收。

Python 3.12.14 · 37 项实际检查 · 当前入口SHA256 f6ef3908c0e1820296945a8f4d391ed67d8a564b1e3d5554de33a24826e9db33

检查项实际结果预期结果
actual grammar 2+3*41414
actual grammar (2+3)*42020
actual grammar (x+3)*(y-2)3939
actual grammar -7 % 322
actual grammar 7 / 2"Fraction(7, 2)""Fraction(7, 2)"
actual grammar +3-211
initial context22
same object changed context not stale cache1010
predicate x>5truetrue
predicate x<5falsefalse
predicate x>=9truetrue
predicate x<=9truetrue
predicate x==9truetrue
predicate x!=9falsefalse
predicate NOT (x < 5) AND x <= 9truetrue
predicate True OR missing > 1truetrue
predicate False AND missing > 1falsefalse
predicate 1 < x < 10truetrue
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}

本章源码与生成文件

下载独立入口 共享实现 补充实例实现 本章结果JSON

查看当前核心代码
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))

上图是本站运行生成文件,不能当作来源原图已采集。