@furongjun1999/dsh-memory 0.9.6 → 0.9.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/policy.json +38 -38
- package/docs/discipline/templates/spec.txt.tmpl +1 -1
- package/dsh/cordis.yml.example +139 -139
- package/lib/hooks.d.ts +19 -0
- package/lib/hooks.js +29 -6
- package/lib/index.js +11 -2
- package/lib/lib/hook_audit.js +38 -2
- package/lib/lib/prompt_safety.js +14 -3
- package/lib/tools.d.ts +7 -0
- package/lib/tools.js +22 -1
- package/md_cg/_guard_kit.py +121 -121
- package/md_cg/anchor.py +114 -114
- package/md_cg/audit.py +15 -2
- package/md_cg/chain.py +3 -2
- package/md_cg/config_registry_guard.py +487 -487
- package/md_cg/conformance.py +747 -747
- package/md_cg/consolidate.py +1793 -1793
- package/md_cg/crypto.py +794 -794
- package/md_cg/hyperedge.py +262 -262
- package/md_cg/interface_schema.py +146 -146
- package/md_cg/lifecycle.py +426 -426
- package/md_cg/mdcos.py +12 -8
- package/md_cg/predict.py +1103 -1103
- package/md_cg/protect.py +654 -654
- package/md_cg/provenance.py +606 -606
- package/md_cg/queue_health.py +130 -130
- package/md_cg/refine.py +613 -613
- package/md_cg/retrieve.py +128 -128
- package/md_cg/revise.py +140 -140
- package/md_cg/rollback.py +657 -657
- package/md_cg/rollback_cli.py +124 -124
- package/md_cg/rotate.py +346 -346
- package/md_cg/routing.py +490 -490
- package/md_cg/self_surface.py +50 -50
- package/md_cg/semantic/canonical.py +144 -144
- package/md_cg/semantic/zh_en_atoms.py +141 -141
- package/md_cg/sources.py +1091 -1091
- package/md_cg/stg.py +3 -2
- package/md_cg/test_audit_rotate_parity.py +279 -279
- package/md_cg/test_autonomy_modes.py +2013 -2013
- package/md_cg/test_cn_recall_grams.py +206 -206
- package/md_cg/test_code_kind_forbidden.py +101 -0
- package/md_cg/test_condaccept.py +156 -156
- package/md_cg/test_condgate.py +141 -141
- package/md_cg/test_heartbeat_ledger.py +557 -557
- package/md_cg/test_i50e_readside_protection.py +658 -658
- package/md_cg/test_issue111_gate_order.py +76 -76
- package/md_cg/test_issue111_scoring_contract.py +86 -86
- package/md_cg/test_issue121_calibration_bounds.py +293 -293
- package/md_cg/test_issue145_sleep_no_silent_rollback.py +167 -167
- package/md_cg/test_issue147_pack_id_escape.py +378 -378
- package/md_cg/test_issue148_merge_downgrade_leak.py +192 -192
- package/md_cg/test_issue149_accel_default_face.py +248 -248
- package/md_cg/test_issue150_empty_query_terms.py +328 -328
- package/md_cg/test_issue151_153_157_write_cache_index.py +151 -151
- package/md_cg/test_issue152_sealed_postings.py +309 -309
- package/md_cg/test_issue153b_index_generation_invalidation.py +142 -142
- package/md_cg/test_issue157b_index_remainder.py +344 -344
- package/md_cg/test_issue189_conclusion_bidirectional.py +223 -223
- package/md_cg/test_issue191_import_trust.py +382 -382
- package/md_cg/test_issue193_write_scope.py +378 -378
- package/md_cg/test_issue212_writeface_gaps.py +349 -349
- package/md_cg/test_issue214_reject_sensitivity.py +266 -266
- package/md_cg/test_issue215_condition_source_gap.py +272 -272
- package/md_cg/test_issue216_clash_routes.py +214 -214
- package/md_cg/test_issue217_slot_routes.py +248 -248
- package/md_cg/test_issue218_postcondition_value_blind.py +222 -222
- package/md_cg/test_issue258_pack_sensitivity.py +468 -468
- package/md_cg/test_issue265_coldverify_multiproc.py +438 -438
- package/md_cg/test_issue274_read_node_id_none.py +341 -341
- package/md_cg/test_issue275_layer_param.py +250 -250
- package/md_cg/test_issue277_node_id_traversal.py +384 -384
- package/md_cg/test_issue278_neg_separated_tension.py +271 -271
- package/md_cg/test_issue278_neg_window.py +294 -294
- package/md_cg/test_issue278_negative_layering.py +83 -83
- package/md_cg/test_issue284_skip_not_pass.py +291 -291
- package/md_cg/test_issue294_flywheel_sensitivity.py +573 -573
- package/md_cg/test_issue301_baseline_corpus_gate.py +245 -245
- package/md_cg/test_issue303_design_boundaries.py +262 -262
- package/md_cg/test_issue315_merge_branch_sensitivity.py +383 -383
- package/md_cg/test_issue319_tenant_unregistered_bypass.py +256 -256
- package/md_cg/test_issue321_mcp_deep_json.py +304 -304
- package/md_cg/test_issue322_node_write_lock.py +727 -727
- package/md_cg/test_issue324_write_size_fields.py +214 -214
- package/md_cg/test_issue325_audit_poison.py +229 -229
- package/md_cg/test_issue326_ingest_auto_whitelist.py +331 -331
- package/md_cg/test_issue326_key_perms.py +355 -355
- package/md_cg/test_issue326_twin_parser_parity.py +323 -323
- package/md_cg/test_issue326_vm_call_frame.py +569 -569
- package/md_cg/test_issue345_writelimit_effective_sens.py +233 -233
- package/md_cg/test_issue346_overwrite_sensitivity_gate.py +424 -424
- package/md_cg/test_issue348_insight_verify_op.py +199 -199
- package/md_cg/test_issue348_merge_rmw_lock.py +345 -345
- package/md_cg/test_issue350_casefold_collision.py +235 -235
- package/md_cg/test_issue351_ingest_root_fallback.py +201 -201
- package/md_cg/test_issue352_imgaudit.py +418 -418
- package/md_cg/test_issue352_pathsjson.py +537 -537
- package/md_cg/test_issue352_refindex.py +412 -412
- package/md_cg/test_issue352_rollback.py +604 -604
- package/md_cg/test_issue354_p2_writelimit_toctou.py +327 -327
- package/md_cg/test_issue354_rust_index_containment.py +571 -571
- package/md_cg/test_issue354_rust_wal_containment.py +606 -606
- package/md_cg/test_issue358_truncation_observable.py +247 -247
- package/md_cg/test_issue360_tidy_private_excerpt.py +195 -195
- package/md_cg/test_issue361_blindspot_not_silent_drop.py +494 -494
- package/md_cg/test_issue362_neg_condition.py +468 -468
- package/md_cg/test_issue363_lexical_idf.py +275 -275
- package/md_cg/test_issue370_readcache_assembly.py +488 -488
- package/md_cg/test_issue376_heartbeat_failed.py +293 -293
- package/md_cg/test_issue377_layer_protect_stamp.py +324 -324
- package/md_cg/test_issue378_protected_floor.py +310 -310
- package/md_cg/test_issue383_state_event_write_gate.py +462 -462
- package/md_cg/test_issue397_sens_eff_wiring.py +435 -435
- package/md_cg/test_issue398_toolface_op_parity.py +511 -511
- package/md_cg/test_issue399_hive_json_shape.py +317 -317
- package/md_cg/test_issue401_wisdom_codegen.py +295 -295
- package/md_cg/test_issue404_heal_receipt.py +389 -389
- package/md_cg/test_issue409_compact_index_completeness.py +509 -509
- package/md_cg/test_issue410_verify_demote_write.py +366 -366
- package/md_cg/test_issue411_scrub_idempotence.py +575 -575
- package/md_cg/test_issue412_discipline_producer_parity.py +311 -311
- package/md_cg/test_issue413_preimage_failclosed.py +239 -239
- package/md_cg/test_issue413_preimage_twin.py +339 -339
- package/md_cg/test_issue415_deps_gate_probe.py +357 -357
- package/md_cg/test_issue416_entry_key_subset.py +525 -525
- package/md_cg/test_issue417_twophase_merge_landed.py +423 -423
- package/md_cg/test_issue425_ingest_library_path.py +331 -331
- package/md_cg/test_issue426c_enqueue_not_silent.py +346 -346
- package/md_cg/test_issue426e_restore_overwrite_live.py +310 -310
- package/md_cg/test_issue426f_paths_gbk_failclosed.py +301 -301
- package/md_cg/test_issue427_serve_status_shape.py +191 -191
- package/md_cg/test_issue431_432_468_protect_single_point.py +322 -322
- package/md_cg/test_issue433_outlook_threshold_single_point.py +278 -278
- package/md_cg/test_issue434_435_float_gate.py +90 -90
- package/md_cg/test_issue439_sibling_sensitivity_inherit.py +448 -448
- package/md_cg/test_issue43_default_policy.py +874 -874
- package/md_cg/test_issue444_scrub_evidence_plaintext.py +281 -281
- package/md_cg/test_issue445_metacognition_ledger_gate.py +454 -454
- package/md_cg/test_issue446_453_403_verified_evidence.py +382 -382
- package/md_cg/test_issue450_sensitivity_fallback_reason.py +51 -51
- package/md_cg/test_issue450_writegate_unknown_sens.py +203 -203
- package/md_cg/test_issue451_audit_actor.py +313 -313
- package/md_cg/test_issue452_ingest_root_sensitivity.py +299 -299
- package/md_cg/test_issue463_ghost_prune_guard.py +259 -259
- package/md_cg/test_issue466_basis_registry.py +469 -469
- package/md_cg/test_issue467_identity_sensitivity_parity.py +360 -360
- package/md_cg/test_issue469_scrub_override_passthrough.py +126 -126
- package/md_cg/test_issue470_wal_event_durable.py +427 -427
- package/md_cg/test_issue471_identity_readable.py +136 -136
- package/md_cg/test_issue472_audit_chain.py +90 -90
- package/md_cg/test_issue472_prune_ledger.py +105 -105
- package/md_cg/test_issue472_rollback_degraded.py +81 -81
- package/md_cg/test_issue491_compose_sandbox.py +460 -460
- package/md_cg/test_issue498_merge_trace_stale_index.py +280 -280
- package/md_cg/test_issue511_scoreboard_bad_files.py +256 -256
- package/md_cg/test_issue521_rotate_lock_suffix.py +110 -110
- package/md_cg/test_issue524_orphan_noise_no_demote.py +88 -88
- package/md_cg/test_issue525_read_null_semantics.py +52 -52
- package/md_cg/test_issue547_append_jsonl_whitelist.py +114 -114
- package/md_cg/test_issue547_audit_durable.py +96 -96
- package/md_cg/test_issue557_r2_write_entries_size_gate.py +83 -83
- package/md_cg/test_issue559_refine_prefix.py +69 -69
- package/md_cg/test_issue562_retired_faces.py +150 -0
- package/md_cg/test_issue71_queue_backlog.py +376 -376
- package/md_cg/test_issue72_coldverify_controlled_drain.py +420 -420
- package/md_cg/test_issue82_credential_rules.py +271 -271
- package/md_cg/test_issue91_verifier_sandbox.py +314 -314
- package/md_cg/test_issue93_remember_redaction.py +282 -282
- package/md_cg/test_logref.py +1141 -1141
- package/md_cg/test_md_access_parity.py +330 -330
- package/md_cg/test_md_cg_no_hive_dep.py +139 -139
- package/md_cg/test_mutation_residue.py +119 -119
- package/md_cg/test_mutation_rollback.py +835 -835
- package/md_cg/test_n123_derive_expiry_chain.py +210 -210
- package/md_cg/test_n209_verify_write_face_gates.py +466 -466
- package/md_cg/test_n62_tenant_bind_failclosed.py +200 -200
- package/md_cg/test_neg_tail_honesty.py +733 -733
- package/md_cg/test_p21_tokens.py +294 -294
- package/md_cg/test_p27_docindex.py +792 -792
- package/md_cg/test_p28_refcheck.py +1053 -1053
- package/md_cg/test_p2_six_elements.py +476 -476
- package/md_cg/test_p33_ccg_wiring.py +300 -300
- package/md_cg/test_p3_legacy_closure.py +438 -438
- package/md_cg/test_p40_refine_worklist.py +244 -244
- package/md_cg/test_p4_freshness.py +781 -781
- package/md_cg/test_p9c_dedup_hints.py +288 -288
- package/md_cg/test_policy_required_ccg.py +444 -444
- package/md_cg/test_retr_s5.py +312 -312
- package/md_cg/test_s1_ast_judge.py +109 -109
- package/md_cg/test_state_event_op.py +521 -521
- package/md_cg/test_stgidx_index_parity.py +1024 -1024
- package/md_cg/test_sustain_bounded.py +652 -652
- package/md_cg/test_trust_edge_reachability.py +405 -405
- package/md_cg/test_w7_redlines.py +659 -659
- package/md_cg/test_write_return_shape.py +919 -919
- package/md_cg/test_writepipe.py +228 -228
- package/md_cg/trust.py +1114 -1114
- package/md_cg/twophase.py +303 -303
- package/md_cg/whitebox.py +536 -536
- package/md_cg/whitebox_kb/wisdom/compose_engine.py +1634 -1634
- package/md_cg/whitebox_kb/wisdom/core/condition_vm.py +318 -318
- package/md_cg/whitebox_kb/wisdom/core/parser.py +1082 -1082
- package/md_cg/whitebox_kb/wisdom/md_access.py +490 -490
- package/md_cg/whitebox_kb/wisdom/migrate_wisdom.py +497 -497
- package/md_cg/whitebox_kb/wisdom/mini_python.py +995 -995
- package/md_cg/whitebox_kb/wisdom/net_units.py +2900 -2900
- package/md_cg/whitebox_kb/wisdom/semantic_translate.py +4060 -4060
- package/md_cg/writepipe.py +1337 -1337
- package/package.json +3 -2
- package/scripts/workspace_index.py +328 -0
- package/src/hooks.ts +30 -6
- package/src/index.ts +14 -5
- package/src/lib/hook_audit.ts +282 -256
- package/src/lib/mdcg_client.ts +469 -469
- package/src/lib/prompt_safety.ts +17 -3
- package/src/tools.ts +23 -1
|
@@ -1,995 +1,995 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""mini_python.py · Mini-Python 解释器(第六阶段 P1·机制训练场)
|
|
3
|
-
P1:词法 + 语法 + 表达式求值(对照 CPython 行为,P 线校准参考实现)
|
|
4
|
-
- or/and 返回操作数 + 短路;/ 返回 float;// % floor;** 右结合高优先级
|
|
5
|
-
- 除零抛 MiniPyError;链式比较;一元负号;-2**2 = -4
|
|
6
|
-
机制训练场:词法/AST/求值 机制供 C 线原生后端复用(语义不照抄——中文编译器走智能论语义)。
|
|
7
|
-
"""
|
|
8
|
-
import sys
|
|
9
|
-
import re
|
|
10
|
-
sys.stdout.reconfigure(encoding='utf-8')
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
class MiniPyError(Exception):
|
|
14
|
-
"""运行时错误(除零等)"""
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
# ============ 一、词法分析 ============
|
|
18
|
-
_TOKEN_RE = [
|
|
19
|
-
("STR", r"'[^']*'|\"[^\"]*\""),
|
|
20
|
-
("NUMBER", r"\d+\.\d+|\d+"),
|
|
21
|
-
("OP", r"\*\*|//|==|!=|<=|>=|\+=|-=|\*=|/=|[+\-*/%<>()=,\[\]{}:.]"),
|
|
22
|
-
("KEY", r"and|or|not|True|False|None|if|elif|else|while|def|return"),
|
|
23
|
-
("NAME", r"[A-Za-z_]\w*"),
|
|
24
|
-
("WS", r"\s+"),
|
|
25
|
-
]
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
def tokenize(src):
|
|
29
|
-
"""字符流 → token 列表(数字/运算符/关键字/括号)"""
|
|
30
|
-
tokens, i = [], 0
|
|
31
|
-
while i < len(src):
|
|
32
|
-
for kind, pat in _TOKEN_RE:
|
|
33
|
-
m = re.match(pat, src[i:])
|
|
34
|
-
if m:
|
|
35
|
-
text = m.group(0)
|
|
36
|
-
i += len(text)
|
|
37
|
-
if kind == "WS":
|
|
38
|
-
break
|
|
39
|
-
if kind == "STR":
|
|
40
|
-
tokens.append(("STRING", text[1:-1]))
|
|
41
|
-
elif kind == "KEY":
|
|
42
|
-
tokens.append((text.upper(), text))
|
|
43
|
-
elif kind == "NUMBER":
|
|
44
|
-
tokens.append(("NUMBER", float(text) if "." in text else int(text)))
|
|
45
|
-
elif kind == "NAME":
|
|
46
|
-
tokens.append(("NAME", text))
|
|
47
|
-
else:
|
|
48
|
-
tokens.append(("OP", text))
|
|
49
|
-
break
|
|
50
|
-
else:
|
|
51
|
-
raise SyntaxError(f"词法错误:未知字符 '{src[i]}'(位置 {i})")
|
|
52
|
-
tokens.append(("EOF", ""))
|
|
53
|
-
return tokens
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
# ============ 二、语法分析(递归下降,Python 优先级) ============
|
|
57
|
-
class Parser:
|
|
58
|
-
def __init__(self, tokens):
|
|
59
|
-
"""解析器初始化:持有词元流与位置指针。"""
|
|
60
|
-
self.tokens = tokens
|
|
61
|
-
self.pos = 0
|
|
62
|
-
|
|
63
|
-
def peek(self):
|
|
64
|
-
"""前瞻:返回当前 token 类型但不消费。"""
|
|
65
|
-
return self.tokens[self.pos]
|
|
66
|
-
|
|
67
|
-
def advance(self):
|
|
68
|
-
"""前进:消费并返回当前 token。"""
|
|
69
|
-
t = self.tokens[self.pos]
|
|
70
|
-
self.pos += 1
|
|
71
|
-
return t
|
|
72
|
-
|
|
73
|
-
def match(self, *texts):
|
|
74
|
-
"""尝试匹配:类型相符即消费返回 True,否则 False。"""
|
|
75
|
-
t = self.peek()
|
|
76
|
-
if t[1] in texts:
|
|
77
|
-
return self.advance()
|
|
78
|
-
return None
|
|
79
|
-
|
|
80
|
-
def _maybe_index(self, node):
|
|
81
|
-
"""索引后缀:obj[key] → ("index", obj, key)(P5 数据结构)"""
|
|
82
|
-
while self.peek()[1] == "[":
|
|
83
|
-
self.advance()
|
|
84
|
-
key = self.or_expr()
|
|
85
|
-
self.expect("]")
|
|
86
|
-
node = ("index", node, key)
|
|
87
|
-
return node
|
|
88
|
-
|
|
89
|
-
def _peek_eq(self):
|
|
90
|
-
"""后视:当前 NAME 后是否跟单个 =(kwarg 形态,区别于 ==)。"""
|
|
91
|
-
nxt = self.tokens[self.pos + 1] if self.pos + 1 < len(self.tokens) else None
|
|
92
|
-
return nxt is not None and nxt[0] == "OP" and nxt[1] == "="
|
|
93
|
-
|
|
94
|
-
def _parse_call_args(self):
|
|
95
|
-
"""调用参数列表:位置参数 + 关键字参数 k=v(V-P4 kwargs 第一批)。"""
|
|
96
|
-
args, kwargs = [], []
|
|
97
|
-
if self.peek()[1] != ")":
|
|
98
|
-
while True:
|
|
99
|
-
t = self.peek()
|
|
100
|
-
if t[0] == "NAME" and self._peek_eq(): # k=v
|
|
101
|
-
self.advance()
|
|
102
|
-
self.advance()
|
|
103
|
-
kwargs.append((t[1], self.or_expr()))
|
|
104
|
-
else:
|
|
105
|
-
args.append(self.or_expr())
|
|
106
|
-
if not self.match(","):
|
|
107
|
-
break
|
|
108
|
-
self.expect(")")
|
|
109
|
-
return args, kwargs
|
|
110
|
-
|
|
111
|
-
def _parse_suffixes(self, node, name=None):
|
|
112
|
-
"""后缀链统一:.attr / [idx] / (args)(V-P3:NAME 与字符串字面量共用)。
|
|
113
|
-
|
|
114
|
-
循环消化后缀使链式调用成立(s.strip().upper());调用结果再取下标
|
|
115
|
-
(f(x)[0])同样支持。obj.method(args) → ("method", obj, name, args);
|
|
116
|
-
name(args) → ("call", ...)。下标结果再调用(如 a[0](x))显式不支持
|
|
117
|
-
——原实现会静默错当 a(x)。
|
|
118
|
-
"""
|
|
119
|
-
while True:
|
|
120
|
-
t1 = self.peek()[1]
|
|
121
|
-
if t1 == ".":
|
|
122
|
-
self.advance()
|
|
123
|
-
attr = self.advance()
|
|
124
|
-
if attr[0] != "NAME":
|
|
125
|
-
raise SyntaxError(f"语法错误:'.' 后应为属性名,得到 '{attr[1]}'")
|
|
126
|
-
node = ("attr", node, attr[1])
|
|
127
|
-
elif t1 == "[":
|
|
128
|
-
self.advance()
|
|
129
|
-
key = self.or_expr()
|
|
130
|
-
self.expect("]")
|
|
131
|
-
node = ("index", node, key)
|
|
132
|
-
elif t1 == "(":
|
|
133
|
-
self.advance()
|
|
134
|
-
args, kwargs = self._parse_call_args()
|
|
135
|
-
if node[0] == "attr": # obj.method(args) → 方法调用节点
|
|
136
|
-
node = ("method", node[1], node[2], args, kwargs)
|
|
137
|
-
elif name is not None and node[0] == "name" and node[1] == name:
|
|
138
|
-
node = ("call", name, args, kwargs)
|
|
139
|
-
else:
|
|
140
|
-
raise SyntaxError("语法错误:该表达式不可调用(下标结果调用不支持)")
|
|
141
|
-
else:
|
|
142
|
-
break
|
|
143
|
-
return node
|
|
144
|
-
|
|
145
|
-
def expect(self, text):
|
|
146
|
-
t = self.peek()
|
|
147
|
-
if t[1] != text:
|
|
148
|
-
raise SyntaxError(f"语法错误:期望 '{text}',得到 '{t[1]}'")
|
|
149
|
-
return self.advance()
|
|
150
|
-
|
|
151
|
-
def parse(self):
|
|
152
|
-
node = self.or_expr()
|
|
153
|
-
if self.peek()[0] != "EOF":
|
|
154
|
-
raise SyntaxError(f"语法错误:意外的 token '{self.peek()[1]}'")
|
|
155
|
-
return node
|
|
156
|
-
|
|
157
|
-
def or_expr(self):
|
|
158
|
-
"""or 链:短路求值(左真返左,否则续右)——对照 CPython 语义。"""
|
|
159
|
-
node = self.and_expr()
|
|
160
|
-
while self.match("or"):
|
|
161
|
-
node = ("or", node, self.and_expr())
|
|
162
|
-
return node
|
|
163
|
-
|
|
164
|
-
def and_expr(self):
|
|
165
|
-
"""and 链:短路求值(左假返假,否则续右)。"""
|
|
166
|
-
node = self.not_expr()
|
|
167
|
-
while self.match("and"):
|
|
168
|
-
node = ("and", node, self.not_expr())
|
|
169
|
-
return node
|
|
170
|
-
|
|
171
|
-
def not_expr(self):
|
|
172
|
-
"""not 一元表达式求值。"""
|
|
173
|
-
if self.match("not"):
|
|
174
|
-
return ("not", self.not_expr())
|
|
175
|
-
return self.comparison()
|
|
176
|
-
|
|
177
|
-
def comparison(self):
|
|
178
|
-
"""比较链:== != < <= > >= in / not in(V-P4)。
|
|
179
|
-
|
|
180
|
-
issue #401:按 **CPython 语义** `a < b < c` ≡ `(a < b) and (b < c)`(逐对求值、
|
|
181
|
-
前一对为假即短路,**中间操作数只求值一次**)。修前每遇一个比较符就把已构造的
|
|
182
|
-
node 当左操作数再套一层 ⇒ 按**左结合**求值 `(a < b) < c` ⇒ 数值区间判断整类算错
|
|
183
|
-
(`0 <= 15 < 10` 恒 True)。链长 > 1 时产 `("chain", ops, operands)` 节点。
|
|
184
|
-
"""
|
|
185
|
-
first = self.arith()
|
|
186
|
-
ops, operands = [], [first]
|
|
187
|
-
while True:
|
|
188
|
-
t = self.peek()
|
|
189
|
-
if t[1] in ("==", "!=", "<", ">", "<=", ">="):
|
|
190
|
-
self.advance()
|
|
191
|
-
ops.append(t[1])
|
|
192
|
-
operands.append(self.arith())
|
|
193
|
-
elif t[1] == "in": # V-P4:成员运算符(in 为 NAME token)
|
|
194
|
-
self.advance()
|
|
195
|
-
ops.append("in")
|
|
196
|
-
operands.append(self.arith())
|
|
197
|
-
elif t[1] == "not" and self._peek_is_in(): # not in(KEY token)
|
|
198
|
-
self.advance()
|
|
199
|
-
self.advance() # 消费 in
|
|
200
|
-
ops.append("not in")
|
|
201
|
-
operands.append(self.arith())
|
|
202
|
-
else:
|
|
203
|
-
break
|
|
204
|
-
if not ops:
|
|
205
|
-
return first
|
|
206
|
-
if len(ops) == 1:
|
|
207
|
-
return (ops[0], operands[0], operands[1])
|
|
208
|
-
return ("chain", ops, operands)
|
|
209
|
-
|
|
210
|
-
def _peek_is_in(self):
|
|
211
|
-
"""后视:not 后是否跟 in(not in 运算符,区别于逻辑 not 前缀)。"""
|
|
212
|
-
nxt = self.tokens[self.pos + 1] if self.pos + 1 < len(self.tokens) else None
|
|
213
|
-
return nxt is not None and nxt[1] == "in"
|
|
214
|
-
|
|
215
|
-
def arith(self):
|
|
216
|
-
"""加减项:+ - 左结合。"""
|
|
217
|
-
node = self.term()
|
|
218
|
-
while True:
|
|
219
|
-
t = self.peek()
|
|
220
|
-
if t[1] in ("+", "-"):
|
|
221
|
-
self.advance()
|
|
222
|
-
node = (t[1], node, self.term())
|
|
223
|
-
else:
|
|
224
|
-
return node
|
|
225
|
-
|
|
226
|
-
def term(self):
|
|
227
|
-
"""乘除项:* / // % 左结合。"""
|
|
228
|
-
node = self.factor()
|
|
229
|
-
while True:
|
|
230
|
-
t = self.peek()
|
|
231
|
-
if t[1] in ("*", "/", "//", "%"):
|
|
232
|
-
self.advance()
|
|
233
|
-
node = (t[1], node, self.factor())
|
|
234
|
-
else:
|
|
235
|
-
return node
|
|
236
|
-
|
|
237
|
-
def factor(self):
|
|
238
|
-
"""一元因子:- 负号 / not 前缀。"""
|
|
239
|
-
if self.peek()[1] in ("-", "+"):
|
|
240
|
-
op = self.advance()[1]
|
|
241
|
-
return (op, self.factor()) # 一元负号在外层:-2**2 = -(2**2)
|
|
242
|
-
return self.power()
|
|
243
|
-
|
|
244
|
-
def power(self):
|
|
245
|
-
"""幂运算:** 右结合。"""
|
|
246
|
-
node = self.atom()
|
|
247
|
-
if self.match("**"):
|
|
248
|
-
return ("**", node, self.factor()) # 右结合
|
|
249
|
-
return node
|
|
250
|
-
|
|
251
|
-
def atom(self):
|
|
252
|
-
"""原子项:数字/字符串/名称/括号表达式/[列表]/字典字面量。"""
|
|
253
|
-
t = self.peek()
|
|
254
|
-
if t[0] == "NUMBER":
|
|
255
|
-
self.advance()
|
|
256
|
-
return ("num", t[1])
|
|
257
|
-
if t[0] == "STRING": # P5:字符串字面量(V-P3:后缀链与 NAME 统一)
|
|
258
|
-
self.advance()
|
|
259
|
-
return self._parse_suffixes(("str", t[1]))
|
|
260
|
-
if t[0] == "NAME": # 变量/函数调用/方法链(P3 + T4 后缀统一)
|
|
261
|
-
self.advance()
|
|
262
|
-
return self._parse_suffixes(("name", t[1]), name=t[1])
|
|
263
|
-
if t[1] == "[":
|
|
264
|
-
self.advance()
|
|
265
|
-
items = []
|
|
266
|
-
if self.peek()[1] != "]":
|
|
267
|
-
items.append(self.or_expr())
|
|
268
|
-
while self.match(","):
|
|
269
|
-
items.append(self.or_expr())
|
|
270
|
-
self.expect("]")
|
|
271
|
-
return self._maybe_index(("list", items))
|
|
272
|
-
if t[1] == "{":
|
|
273
|
-
self.advance()
|
|
274
|
-
pairs = []
|
|
275
|
-
if self.peek()[1] != "}":
|
|
276
|
-
k = self.or_expr()
|
|
277
|
-
self.expect(":")
|
|
278
|
-
v = self.or_expr()
|
|
279
|
-
pairs.append((k, v))
|
|
280
|
-
while self.match(","):
|
|
281
|
-
k = self.or_expr()
|
|
282
|
-
self.expect(":")
|
|
283
|
-
v = self.or_expr()
|
|
284
|
-
pairs.append((k, v))
|
|
285
|
-
self.expect("}")
|
|
286
|
-
return self._maybe_index(("dict", pairs))
|
|
287
|
-
if t[1] == "True":
|
|
288
|
-
self.advance()
|
|
289
|
-
return ("bool", True)
|
|
290
|
-
if t[1] == "False":
|
|
291
|
-
self.advance()
|
|
292
|
-
return ("bool", False)
|
|
293
|
-
if t[1] == "None":
|
|
294
|
-
self.advance()
|
|
295
|
-
return ("none", None)
|
|
296
|
-
if t[1] == "(":
|
|
297
|
-
self.advance()
|
|
298
|
-
node = self.or_expr()
|
|
299
|
-
self.expect(")")
|
|
300
|
-
return node
|
|
301
|
-
raise SyntaxError(f"语法错误:意外的 token '{t[1]}'")
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
# ============ 三、求值(对照 CPython 行为) ============
|
|
305
|
-
def is_truthy(v):
|
|
306
|
-
"""真值判定:对照 CPython 规则(None/False/0/空容器/空串为假)。"""
|
|
307
|
-
if v is None or v is False:
|
|
308
|
-
return False
|
|
309
|
-
if isinstance(v, (int, float)) and v == 0:
|
|
310
|
-
return False
|
|
311
|
-
if isinstance(v, (str, list, tuple, dict)) and len(v) == 0:
|
|
312
|
-
return False
|
|
313
|
-
return True
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
def eval_node(node, env=None):
|
|
317
|
-
"""AST 求值(P2:env 提供变量环境;name 节点从环境取值)"""
|
|
318
|
-
kind = node[0]
|
|
319
|
-
if kind == "num":
|
|
320
|
-
return node[1]
|
|
321
|
-
if kind == "str":
|
|
322
|
-
return node[1]
|
|
323
|
-
if kind == "bool":
|
|
324
|
-
return node[1]
|
|
325
|
-
if kind == "none":
|
|
326
|
-
return None
|
|
327
|
-
if kind == "name":
|
|
328
|
-
if env is not None:
|
|
329
|
-
try:
|
|
330
|
-
return env.get(node[1])
|
|
331
|
-
except MiniPyError:
|
|
332
|
-
pass
|
|
333
|
-
if node[1] in _BUILTINS: # V-P4:内置函数可作值引用(sorted(x, key=len))
|
|
334
|
-
return _BUILTINS[node[1]]
|
|
335
|
-
raise MiniPyError(f"NameError: name '{node[1]}' is not defined")
|
|
336
|
-
if kind == "or":
|
|
337
|
-
a = eval_node(node[1], env)
|
|
338
|
-
return a if is_truthy(a) else eval_node(node[2], env)
|
|
339
|
-
if kind == "and":
|
|
340
|
-
a = eval_node(node[1], env)
|
|
341
|
-
return eval_node(node[2], env) if is_truthy(a) else a
|
|
342
|
-
if kind == "not":
|
|
343
|
-
return not is_truthy(eval_node(node[1], env))
|
|
344
|
-
if kind == "chain":
|
|
345
|
-
# issue #401:`a < b < c` ≡ `(a<b) and (b<c)`——逐对求值、前一对假即短路,
|
|
346
|
-
# 中间操作数**只求值一次**(修前按左结合 `(a<b)<c`)。
|
|
347
|
-
_ops, _operands = node[1], node[2]
|
|
348
|
-
_prev = eval_node(_operands[0], env)
|
|
349
|
-
for _i, _op in enumerate(_ops):
|
|
350
|
-
_cur = eval_node(_operands[_i + 1], env)
|
|
351
|
-
if not is_truthy(_compare(_op, _prev, _cur)):
|
|
352
|
-
return False
|
|
353
|
-
_prev = _cur
|
|
354
|
-
return True
|
|
355
|
-
if kind in ("==", "!=", "<", ">", "<=", ">=", "in", "not in"):
|
|
356
|
-
return _compare(kind, eval_node(node[1], env), eval_node(node[2], env))
|
|
357
|
-
if kind in ("-", "+") and len(node) == 2: # 一元(先于二元判断)
|
|
358
|
-
v = eval_node(node[1], env)
|
|
359
|
-
return -v if kind == "-" else +v
|
|
360
|
-
if kind == "+":
|
|
361
|
-
return eval_node(node[1], env) + eval_node(node[2], env)
|
|
362
|
-
if kind == "-":
|
|
363
|
-
return eval_node(node[1], env) - eval_node(node[2], env)
|
|
364
|
-
if kind == "*":
|
|
365
|
-
return eval_node(node[1], env) * eval_node(node[2], env)
|
|
366
|
-
if kind == "/":
|
|
367
|
-
b = eval_node(node[2], env)
|
|
368
|
-
if b == 0:
|
|
369
|
-
raise MiniPyError("ZeroDivisionError: division by zero")
|
|
370
|
-
return eval_node(node[1], env) / b
|
|
371
|
-
if kind == "//":
|
|
372
|
-
b = eval_node(node[2], env)
|
|
373
|
-
if b == 0:
|
|
374
|
-
raise MiniPyError("ZeroDivisionError: integer division by zero")
|
|
375
|
-
a = eval_node(node[1], env)
|
|
376
|
-
return int(a // b) # floor(Python 语义)
|
|
377
|
-
if kind == "%":
|
|
378
|
-
b = eval_node(node[2], env)
|
|
379
|
-
if b == 0:
|
|
380
|
-
raise MiniPyError("ZeroDivisionError: modulo by zero")
|
|
381
|
-
return eval_node(node[1], env) % b
|
|
382
|
-
if kind == "**":
|
|
383
|
-
return eval_node(node[1], env) ** eval_node(node[2], env)
|
|
384
|
-
if kind == "attr": # T4:属性/方法访问(白名单内才放行)
|
|
385
|
-
obj = eval_node(node[1], env)
|
|
386
|
-
if node[2] not in _METHOD_WHITELIST:
|
|
387
|
-
raise MiniPyError(f"方法不在白名单: .{node[2]}(允许: {sorted(_METHOD_WHITELIST)})")
|
|
388
|
-
if not hasattr(obj, node[2]):
|
|
389
|
-
raise MiniPyError(f"对象无该方法: {type(obj).__name__}.{node[2]}")
|
|
390
|
-
return getattr(obj, node[2])
|
|
391
|
-
if kind == "method": # T4:obj.method(args) 调用(白名单校验)
|
|
392
|
-
obj = eval_node(node[1], env)
|
|
393
|
-
if node[2] not in _METHOD_WHITELIST:
|
|
394
|
-
raise MiniPyError(f"方法不在白名单: .{node[2]}(允许: {sorted(_METHOD_WHITELIST)})")
|
|
395
|
-
m = getattr(obj, node[2], None)
|
|
396
|
-
if not callable(m):
|
|
397
|
-
raise MiniPyError(f"不可调用: {type(obj).__name__}.{node[2]}")
|
|
398
|
-
args = [eval_node(a, env) for a in node[3]]
|
|
399
|
-
kw = {k: eval_node(v, env) for k, v in node[4]} if len(node) > 4 else {}
|
|
400
|
-
return m(*args, **kw)
|
|
401
|
-
if kind == "call": # 函数调用(P3:局部作用域 + 参数绑定 + return 捕获)
|
|
402
|
-
try:
|
|
403
|
-
f = env.get(node[1]) if env is not None else None
|
|
404
|
-
except MiniPyError:
|
|
405
|
-
f = None
|
|
406
|
-
builtin = _BUILTINS.get(node[1])
|
|
407
|
-
kw = {k: eval_node(v, env) for k, v in node[3]} if len(node) > 3 else {}
|
|
408
|
-
if not (isinstance(f, tuple) and f[0] == "func"):
|
|
409
|
-
if builtin is not None:
|
|
410
|
-
args = [eval_node(a, env) for a in node[2]]
|
|
411
|
-
return builtin(*args, **kw)
|
|
412
|
-
raise MiniPyError(f"NameError: name '{node[1]}' is not defined")
|
|
413
|
-
args = [eval_node(a, env) for a in node[2]]
|
|
414
|
-
_, params, body, def_env = f
|
|
415
|
-
local = bind_params(params, args, kw, def_env) # V-P4:默认值+kwargs 绑定
|
|
416
|
-
try:
|
|
417
|
-
for s in body:
|
|
418
|
-
exec_stmt(s, local)
|
|
419
|
-
except ReturnSignal as rs:
|
|
420
|
-
return rs.value
|
|
421
|
-
return None
|
|
422
|
-
if kind == "list": # P5:list 字面量
|
|
423
|
-
return [eval_node(e, env) for e in node[1]]
|
|
424
|
-
if kind == "dict": # P5:dict 字面量
|
|
425
|
-
return {eval_node(k, env): eval_node(v, env) for k, v in node[1]}
|
|
426
|
-
if kind == "index": # P5:obj[key]
|
|
427
|
-
obj = eval_node(node[1], env)
|
|
428
|
-
key = eval_node(node[2], env)
|
|
429
|
-
try:
|
|
430
|
-
return obj[key]
|
|
431
|
-
except (TypeError, IndexError, KeyError):
|
|
432
|
-
raise MiniPyError(f"索引错误:{obj!r}[{key!r}]")
|
|
433
|
-
raise MiniPyError(f"未知节点: {node}")
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
def _compare(op, a, b):
|
|
437
|
-
"""比较运算统一求值:==·!=·<·>·in·not in 分派(对照 CPython 类型提升)。"""
|
|
438
|
-
if op == "in": # V-P4:成员运算(str/list/tuple/dict 原生语义)
|
|
439
|
-
return a in b
|
|
440
|
-
if op == "not in":
|
|
441
|
-
return a not in b
|
|
442
|
-
return {"==": a == b, "!=": a != b, "<": a < b, ">": a > b,
|
|
443
|
-
"<=": a <= b, ">=": a >= b}[op]
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
def eval_expr(src):
|
|
447
|
-
"""表达式求值入口:源码 → 值(P1)"""
|
|
448
|
-
tokens = tokenize(src)
|
|
449
|
-
ast = Parser(tokens).parse()
|
|
450
|
-
return eval_node(ast)
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
# ============ P2:变量环境 + 控制流(赋值/if/while,缩进块) ============
|
|
454
|
-
# 语句树:("assign", name, expr) / ("if", cond, then[], else[]) /
|
|
455
|
-
# ("while", cond, body[]) / ("expr", expr)
|
|
456
|
-
# 缩进块解析:行 → (缩进, 语句) → 嵌套树
|
|
457
|
-
|
|
458
|
-
# 内置函数表(P4 补全 2026-08-27):对照 CPython 语义的最小白箱内置集
|
|
459
|
-
_BUILTINS = {
|
|
460
|
-
"range": lambda *a: list(range(*[int(x) for x in a])),
|
|
461
|
-
"len": len, "sum": sum, "abs": abs, "min": min, "max": max,
|
|
462
|
-
"int": int, "float": float, "str": str, "list": list, "sorted": sorted,
|
|
463
|
-
"print": print,
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
# 方法白名单(T4 起步 upper/split;V-P3 扩展 str 方法族 + V-P2 揭示 F4 需
|
|
467
|
-
# list.append / dict.get 容器方法原语——全部为 CPython 原生方法,getattr
|
|
468
|
-
# 分派直接对齐 CPython 语义。contains 不入列:str 无 .contains,应走 in
|
|
469
|
-
# 运算符(V-P4 挂账,涉及 for 头解析冲突需专项))
|
|
470
|
-
_METHOD_WHITELIST = {"upper", "split", "startswith", "endswith", "strip", "join",
|
|
471
|
-
"append", "get"}
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
class Env:
|
|
475
|
-
"""变量环境(P3:作用域链——局部 → 父环境)"""
|
|
476
|
-
def __init__(self, parent=None):
|
|
477
|
-
"""作用域帧构造:本地变量表 + 父链指向外层(链式查找)。"""
|
|
478
|
-
self.vars = {}
|
|
479
|
-
self.parent = parent
|
|
480
|
-
|
|
481
|
-
def get(self, name):
|
|
482
|
-
"""变量读取:沿父作用域链向上查找,未定义抛 NameError。"""
|
|
483
|
-
if name in self.vars:
|
|
484
|
-
return self.vars[name]
|
|
485
|
-
if self.parent:
|
|
486
|
-
return self.parent.get(name)
|
|
487
|
-
raise MiniPyError(f"NameError: name '{name}' is not defined")
|
|
488
|
-
|
|
489
|
-
def set(self, name, value):
|
|
490
|
-
"""变量赋值绑定到当前作用域。"""
|
|
491
|
-
self.vars[name] = value
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
def bind_params(params, args, kw, def_env):
|
|
495
|
-
"""V-P4 第三批:参数绑定(位置→关键字→默认值),AST 与 VM 共用。
|
|
496
|
-
|
|
497
|
-
params 元素 = (name, default_ast|None);默认值在定义环境 def_env 求值。
|
|
498
|
-
"""
|
|
499
|
-
from_dict = dict(kw or {})
|
|
500
|
-
values = {}
|
|
501
|
-
for i, (pname, dflt) in enumerate(params):
|
|
502
|
-
if i < len(args):
|
|
503
|
-
values[pname] = args[i]
|
|
504
|
-
elif pname in from_dict:
|
|
505
|
-
values[pname] = from_dict.pop(pname)
|
|
506
|
-
elif dflt is not None:
|
|
507
|
-
values[pname] = eval_node(dflt, def_env)
|
|
508
|
-
else:
|
|
509
|
-
raise MiniPyError(f"参数缺失: {pname}(无默认值且未传)")
|
|
510
|
-
if from_dict:
|
|
511
|
-
raise MiniPyError(f"未识别的关键字参数: {sorted(from_dict)}")
|
|
512
|
-
local = Env(def_env)
|
|
513
|
-
for k, v in values.items():
|
|
514
|
-
local.set(k, v)
|
|
515
|
-
return local
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
class ReturnSignal(Exception):
|
|
519
|
-
"""return 语句信号(P3)"""
|
|
520
|
-
def __init__(self, value):
|
|
521
|
-
"""常量值包装(字面量求值结果载体)。"""
|
|
522
|
-
self.value = value
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
# T4:复合赋值符(模块级预编译)
|
|
526
|
-
_AUG_RE = re.compile(r"(\w+)\s*(\+=|-=|\*=|/=)\s*(.+)$")
|
|
527
|
-
# T4:普通赋值行首形态(变量名 + 单个 =,排除 ==/<=/>=/!= 与字符串内等号)
|
|
528
|
-
_ASSIGN_RE = re.compile(r"([A-Za-z_]\w*)\s*=(?!=)")
|
|
529
|
-
# V-P2:下标赋值行首形态(obj[key] = value;[(.+)] 贪婪至最后一个 ])
|
|
530
|
-
_SUBASSIGN_RE = re.compile(r"([A-Za-z_]\w*)\s*\[(.+)\]\s*=(?!=)\s*(.+)$")
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
def parse_program(src):
|
|
534
|
-
"""源码 → 语句树(缩进决定嵌套)"""
|
|
535
|
-
lines = []
|
|
536
|
-
for raw in src.splitlines():
|
|
537
|
-
if not raw.strip() or raw.strip().startswith("#"):
|
|
538
|
-
continue
|
|
539
|
-
indent = len(raw) - len(raw.lstrip(" "))
|
|
540
|
-
lines.append((indent, raw.strip()))
|
|
541
|
-
# 缩进栈构建嵌套
|
|
542
|
-
def build(idx, indent):
|
|
543
|
-
stmts = []
|
|
544
|
-
while idx[0] < len(lines):
|
|
545
|
-
cur_indent, code = lines[idx[0]]
|
|
546
|
-
if cur_indent < indent:
|
|
547
|
-
break
|
|
548
|
-
if cur_indent > indent:
|
|
549
|
-
raise SyntaxError(f"意外的缩进:{code}")
|
|
550
|
-
idx[0] += 1
|
|
551
|
-
stmts.append(_parse_line(code, build, idx))
|
|
552
|
-
return stmts
|
|
553
|
-
|
|
554
|
-
def _parse_line(code, build, idx):
|
|
555
|
-
# T4:复合赋值 += -= *= /=(先于 = 检测,避免 "x += 1" 被 split("=",1) 误拆)
|
|
556
|
-
m_aug = _AUG_RE.match(code)
|
|
557
|
-
if m_aug:
|
|
558
|
-
return ("aug_assign", m_aug.group(1), m_aug.group(2),
|
|
559
|
-
Parser(tokenize(m_aug.group(3))).parse())
|
|
560
|
-
# 赋值(T4 修正:行首 \w+= 形态判定——字符串内等号/"=="不再误判为赋值)
|
|
561
|
-
m_assign = _ASSIGN_RE.match(code)
|
|
562
|
-
if m_assign:
|
|
563
|
-
return ("assign", m_assign.group(1),
|
|
564
|
-
Parser(tokenize(code[m_assign.end():])).parse())
|
|
565
|
-
# 下标赋值 obj[key] = value(V-P2:F4 字典/列表写入原语;贪婪匹配
|
|
566
|
-
# 最后一个 ] 使嵌套 key 如 a[b[1]] 正确拆分)
|
|
567
|
-
m_sub = _SUBASSIGN_RE.match(code)
|
|
568
|
-
if m_sub:
|
|
569
|
-
return ("index_assign", m_sub.group(1),
|
|
570
|
-
Parser(tokenize(m_sub.group(2))).parse(),
|
|
571
|
-
Parser(tokenize(m_sub.group(3))).parse())
|
|
572
|
-
# if/elif/else
|
|
573
|
-
if code.startswith("def "):
|
|
574
|
-
import re as _re
|
|
575
|
-
m = _re.match(r"def\s+(\w+)\s*\(([^)]*)\)\s*:", code)
|
|
576
|
-
name = m.group(1)
|
|
577
|
-
# V-P4 第三批:参数支持默认值 name=expr → (name, default_ast|None)
|
|
578
|
-
params = []
|
|
579
|
-
for p_raw in m.group(2).split(","):
|
|
580
|
-
p_raw = p_raw.strip()
|
|
581
|
-
if not p_raw:
|
|
582
|
-
continue
|
|
583
|
-
if "=" in p_raw:
|
|
584
|
-
pn, _, pv = p_raw.partition("=")
|
|
585
|
-
params.append((pn.strip(), Parser(tokenize(pv.strip())).parse()))
|
|
586
|
-
else:
|
|
587
|
-
params.append((p_raw, None))
|
|
588
|
-
body = build(idx, lines[idx[0]][0] if idx[0] < len(lines) else 0)
|
|
589
|
-
return ("funcdef", name, params, body)
|
|
590
|
-
if code.startswith("return "):
|
|
591
|
-
return ("return", Parser(tokenize(code[7:])).parse())
|
|
592
|
-
if code.startswith("if "):
|
|
593
|
-
cond = Parser(tokenize(code[3:].rstrip(":"))).parse()
|
|
594
|
-
then_indent = lines[idx[0]][0] if idx[0] < len(lines) else 0
|
|
595
|
-
then = build(idx, then_indent)
|
|
596
|
-
else_stmts = []
|
|
597
|
-
# else 配对:同缩进 else 行 → else 块
|
|
598
|
-
if idx[0] < len(lines) and lines[idx[0]][1].startswith("else"):
|
|
599
|
-
idx[0] += 1 # 消费 else 行
|
|
600
|
-
else_indent = lines[idx[0]][0] if idx[0] < len(lines) else 0
|
|
601
|
-
else_stmts = build(idx, else_indent)
|
|
602
|
-
return ("if", cond, then, else_stmts)
|
|
603
|
-
# P4 补全(2026-08-27 · 荣「求和=1.0」缺陷根治):for 语句
|
|
604
|
-
if code.startswith("for "):
|
|
605
|
-
import re as _re
|
|
606
|
-
m = _re.match(r"for\s+(\w+)\s+in\s+(.+):$", code)
|
|
607
|
-
if not m:
|
|
608
|
-
raise SyntaxError("for 语句格式:for 变量 in 可迭代对象:")
|
|
609
|
-
var = m.group(1)
|
|
610
|
-
iterable = Parser(tokenize(m.group(2))).parse()
|
|
611
|
-
body_indent = lines[idx[0]][0] if idx[0] < len(lines) else 0
|
|
612
|
-
body = build(idx, body_indent)
|
|
613
|
-
return ("for", var, iterable, body)
|
|
614
|
-
if code.startswith("while "):
|
|
615
|
-
cond = Parser(tokenize(code[6:].rstrip(":"))).parse()
|
|
616
|
-
body = build(idx, lines[idx[0]][0] if idx[0] < len(lines) else 0)
|
|
617
|
-
return ("while", cond, body)
|
|
618
|
-
if code.startswith(("else", "elif ")):
|
|
619
|
-
raise SyntaxError("else/elif 未与 if 配对(意外的 else 行)")
|
|
620
|
-
# 表达式语句
|
|
621
|
-
return ("expr", Parser(tokenize(code)).parse())
|
|
622
|
-
|
|
623
|
-
idx = [0]
|
|
624
|
-
return build(idx, 0)
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
def exec_stmt(stmt, env):
|
|
628
|
-
"""执行单条语句(if/while/funcdef 递归执行块)"""
|
|
629
|
-
kind = stmt[0]
|
|
630
|
-
if kind == "assign":
|
|
631
|
-
env.set(stmt[1], eval_node(stmt[2], env))
|
|
632
|
-
elif kind == "index_assign": # V-P2:下标写入 obj[key] = value(list/dict 原生语义)
|
|
633
|
-
obj = env.get(stmt[1])
|
|
634
|
-
key = eval_node(stmt[2], env)
|
|
635
|
-
try:
|
|
636
|
-
obj[key] = eval_node(stmt[3], env)
|
|
637
|
-
except IndexError:
|
|
638
|
-
raise MiniPyError(f"索引赋值越界:{obj!r}[{key!r}]")
|
|
639
|
-
except TypeError:
|
|
640
|
-
raise MiniPyError(f"类型不支持下标赋值:{type(obj).__name__}[{key!r}]")
|
|
641
|
-
elif kind == "aug_assign": # T4:x op= e → x = x op e(/= 除零对齐 / 语义)
|
|
642
|
-
cur = env.get(stmt[1])
|
|
643
|
-
rhs = eval_node(stmt[3], env)
|
|
644
|
-
op = stmt[2]
|
|
645
|
-
if op == "+=":
|
|
646
|
-
env.set(stmt[1], cur + rhs)
|
|
647
|
-
elif op == "-=":
|
|
648
|
-
env.set(stmt[1], cur - rhs)
|
|
649
|
-
elif op == "*=":
|
|
650
|
-
env.set(stmt[1], cur * rhs)
|
|
651
|
-
else:
|
|
652
|
-
if rhs == 0:
|
|
653
|
-
raise MiniPyError("ZeroDivisionError: division by zero")
|
|
654
|
-
env.set(stmt[1], cur / rhs)
|
|
655
|
-
elif kind == "funcdef":
|
|
656
|
-
# 函数对象 = 参数 + body + 定义环境(P4 闭包基础)
|
|
657
|
-
env.set(stmt[1], ("func", stmt[2], stmt[3], env))
|
|
658
|
-
elif kind == "return":
|
|
659
|
-
raise ReturnSignal(eval_node(stmt[1], env))
|
|
660
|
-
elif kind == "if":
|
|
661
|
-
if is_truthy(eval_node(stmt[1], env)):
|
|
662
|
-
for s in stmt[2]:
|
|
663
|
-
exec_stmt(s, env)
|
|
664
|
-
elif stmt[3]:
|
|
665
|
-
for s in stmt[3]:
|
|
666
|
-
exec_stmt(s, env)
|
|
667
|
-
elif kind == "while":
|
|
668
|
-
guard = 0
|
|
669
|
-
while is_truthy(eval_node(stmt[1], env)) and guard < 10000:
|
|
670
|
-
for s in stmt[2]:
|
|
671
|
-
exec_stmt(s, env)
|
|
672
|
-
guard += 1
|
|
673
|
-
elif kind == "for":
|
|
674
|
-
_, var, iter_node, body = stmt
|
|
675
|
-
iterable = eval_node(iter_node, env)
|
|
676
|
-
if isinstance(iterable, (list, tuple)):
|
|
677
|
-
items = list(iterable)
|
|
678
|
-
elif isinstance(iterable, str):
|
|
679
|
-
items = list(iterable)
|
|
680
|
-
elif hasattr(iterable, "__iter__"):
|
|
681
|
-
items = list(iterable)
|
|
682
|
-
else:
|
|
683
|
-
raise MiniPyError(f"for 迭代对象不可迭代: {type(iterable).__name__}")
|
|
684
|
-
for item in items[:10000]: # 步数上限对齐 while guard 纪律
|
|
685
|
-
env.set(var, item)
|
|
686
|
-
for s in body:
|
|
687
|
-
exec_stmt(s, env)
|
|
688
|
-
elif kind == "expr":
|
|
689
|
-
eval_node(stmt[1], env)
|
|
690
|
-
else:
|
|
691
|
-
raise MiniPyError(f"未知语句: {stmt}")
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
def run_program(src):
|
|
695
|
-
"""程序执行:源码 → Env(P2:变量/if/while)"""
|
|
696
|
-
env = Env()
|
|
697
|
-
for stmt in parse_program(src):
|
|
698
|
-
exec_stmt(stmt, env)
|
|
699
|
-
return env
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
# ============ P5:字节码 VM 雏形(栈机——机制供 C 线原生后端复用) ============
|
|
703
|
-
# 表达式 → 字节码指令 → 栈机执行(对照 eval_node 结果)
|
|
704
|
-
# 指令:PUSH_CONST/PUSH_LIST/PUSH_DICT/LOAD_NAME/ADD/SUB/MUL/DIV/FLOOR/MOD/POW/
|
|
705
|
-
# NEG/AND_OR/CMP_*/JUMP_IF_FALSE/JUMP(逻辑短路用跳转)
|
|
706
|
-
|
|
707
|
-
def compile_expr(node):
|
|
708
|
-
"""AST 表达式 → 字节码指令列表(栈机)"""
|
|
709
|
-
kind = node[0]
|
|
710
|
-
if kind == "num":
|
|
711
|
-
return [("PUSH_CONST", node[1])]
|
|
712
|
-
if kind == "str":
|
|
713
|
-
return [("PUSH_CONST", node[1])]
|
|
714
|
-
if kind == "bool":
|
|
715
|
-
return [("PUSH_CONST", node[1])]
|
|
716
|
-
if kind == "none":
|
|
717
|
-
return [("PUSH_CONST", None)]
|
|
718
|
-
if kind == "name":
|
|
719
|
-
return [("LOAD_NAME", node[1])]
|
|
720
|
-
if kind == "list":
|
|
721
|
-
code = []
|
|
722
|
-
for e in node[1]:
|
|
723
|
-
code.extend(compile_expr(e))
|
|
724
|
-
code.append(("PUSH_LIST", len(node[1])))
|
|
725
|
-
return code
|
|
726
|
-
if kind == "dict":
|
|
727
|
-
code = []
|
|
728
|
-
for k, v in node[1]:
|
|
729
|
-
code.extend(compile_expr(k))
|
|
730
|
-
code.extend(compile_expr(v))
|
|
731
|
-
code.append(("PUSH_DICT", len(node[1])))
|
|
732
|
-
return code
|
|
733
|
-
if kind == "index":
|
|
734
|
-
code = compile_expr(node[1]) + compile_expr(node[2])
|
|
735
|
-
code.append(("INDEX", None))
|
|
736
|
-
return code
|
|
737
|
-
if kind in ("-", "+") and len(node) == 2: # 一元
|
|
738
|
-
code = compile_expr(node[1])
|
|
739
|
-
if kind == "-":
|
|
740
|
-
code.append(("NEG", None))
|
|
741
|
-
return code
|
|
742
|
-
if kind in ("+", "-", "*", "/", "//", "%", "**"):
|
|
743
|
-
code = compile_expr(node[1]) + compile_expr(node[2])
|
|
744
|
-
code.append((_ARITH_VM[kind], None))
|
|
745
|
-
return code
|
|
746
|
-
if kind == "chain":
|
|
747
|
-
# issue #401:字节码面按 `and` 语义展开(逐对求值、前一对假即短路)。
|
|
748
|
-
# 说明:本面中间操作数会被求值两次(VM 无 DUP),仅对**有副作用**的操作数
|
|
749
|
-
# 可观测;需要严格单次求值请走树遍历面(eval_expr)。
|
|
750
|
-
_ops, _operands = node[1], node[2]
|
|
751
|
-
_acc = (_ops[0], _operands[0], _operands[1])
|
|
752
|
-
for _i in range(1, len(_ops)):
|
|
753
|
-
_acc = ("and", _acc,
|
|
754
|
-
(_ops[_i], _operands[_i], _operands[_i + 1]))
|
|
755
|
-
return compile_expr(_acc)
|
|
756
|
-
if kind in ("==", "!=", "<", ">", "<=", ">=", "in", "not in"):
|
|
757
|
-
code = compile_expr(node[1]) + compile_expr(node[2])
|
|
758
|
-
code.append((_CMP_VM[kind], None))
|
|
759
|
-
return code
|
|
760
|
-
if kind == "not":
|
|
761
|
-
return compile_expr(node[1]) + [("NOT", None)]
|
|
762
|
-
if kind == "or" or kind == "and":
|
|
763
|
-
# 短路:左值 → 真保留左值(or)/假保留左值(and)→ 否则求右值
|
|
764
|
-
right = compile_expr(node[2])
|
|
765
|
-
code = compile_expr(node[1])
|
|
766
|
-
jmp = "JUMP_IF_TRUE" if kind == "or" else "JUMP_IF_FALSE"
|
|
767
|
-
jmp_idx = len(code)
|
|
768
|
-
code.append((jmp, 0)) # 回填
|
|
769
|
-
code.append(("POP", None)) # 丢弃左值(不短路时)
|
|
770
|
-
code.extend(right)
|
|
771
|
-
code[jmp_idx] = (jmp, len(code)) # 短路目标 = 程序末尾(栈顶左值保留)
|
|
772
|
-
return code
|
|
773
|
-
if kind == "attr": # T4:VM 同步支持(双路对照)
|
|
774
|
-
return compile_expr(node[1]) + [("GET_ATTR", node[2])]
|
|
775
|
-
if kind == "method": # T4:obj + args → CALL_METHOD(方法名, 参数数)
|
|
776
|
-
code = compile_expr(node[1])
|
|
777
|
-
for a in node[3]:
|
|
778
|
-
code.extend(compile_expr(a))
|
|
779
|
-
code.append(("CALL_METHOD", (node[2], len(node[3]))))
|
|
780
|
-
return code
|
|
781
|
-
if kind == "call":
|
|
782
|
-
code = [("LOAD_NAME", node[1])]
|
|
783
|
-
for a in node[2]:
|
|
784
|
-
code.extend(compile_expr(a))
|
|
785
|
-
if len(node) > 3 and node[3]: # V-P4:kwargs 压 key,值 序列 + CALL_KW
|
|
786
|
-
for k, v in node[3]:
|
|
787
|
-
code.append(("PUSH_CONST", k))
|
|
788
|
-
code.extend(compile_expr(v))
|
|
789
|
-
code.append(("CALL_KW", (len(node[2]), len(node[3]))))
|
|
790
|
-
else:
|
|
791
|
-
code.append(("CALL", len(node[2])))
|
|
792
|
-
return code
|
|
793
|
-
if kind == "method":
|
|
794
|
-
if len(node) > 4 and node[4]:
|
|
795
|
-
raise MiniPyError("VM 暂不支持方法关键字参数(V-P4 第二批)")
|
|
796
|
-
raise MiniPyError(f"无法编译节点: {node}")
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
_ARITH_VM = {"+": "ADD", "-": "SUB", "*": "MUL", "/": "DIV",
|
|
800
|
-
"//": "FLOOR", "%": "MOD", "**": "POW"}
|
|
801
|
-
_CMP_VM = {"==": "CMP_EQ", "!=": "CMP_NE", "<": "CMP_LT", ">": "CMP_GT",
|
|
802
|
-
"<=": "CMP_LE", ">=": "CMP_GE",
|
|
803
|
-
"in": "CMP_IN", "not in": "CMP_NOT_IN"} # V-P4
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
class VM:
|
|
807
|
-
"""栈机执行(P5 雏形:算术/比较/逻辑短路/数据结构/调用)"""
|
|
808
|
-
def __init__(self, env):
|
|
809
|
-
"""VM 执行上下文:环境引用·操作数栈·调用帧序列。"""
|
|
810
|
-
self.env = env
|
|
811
|
-
self.stack = []
|
|
812
|
-
self.frames = [] # 调用帧(P5 简化:函数调用直接执行 body)
|
|
813
|
-
|
|
814
|
-
def run(self, code, max_steps=100000):
|
|
815
|
-
"""字节码 VM 执行主循环:取指分派,max_steps 上限防死循环。"""
|
|
816
|
-
ip = 0
|
|
817
|
-
while ip < len(code) and max_steps > 0:
|
|
818
|
-
op, arg = code[ip]
|
|
819
|
-
ip += 1
|
|
820
|
-
max_steps -= 1
|
|
821
|
-
if op == "PUSH_CONST":
|
|
822
|
-
self.stack.append(arg)
|
|
823
|
-
elif op == "LOAD_NAME":
|
|
824
|
-
try:
|
|
825
|
-
self.stack.append(self.env.get(arg))
|
|
826
|
-
except MiniPyError:
|
|
827
|
-
if arg in _BUILTINS: # V-P2:VM 路内置函数兜底(与 AST 路对齐)
|
|
828
|
-
self.stack.append(_BUILTINS[arg])
|
|
829
|
-
else:
|
|
830
|
-
raise
|
|
831
|
-
elif op == "PUSH_LIST":
|
|
832
|
-
items = self.stack[-arg:]
|
|
833
|
-
self.stack = self.stack[:-arg]
|
|
834
|
-
self.stack.append(items)
|
|
835
|
-
elif op == "PUSH_DICT":
|
|
836
|
-
pairs = self.stack[-arg * 2:]
|
|
837
|
-
self.stack = self.stack[:-arg * 2]
|
|
838
|
-
self.stack.append({pairs[i]: pairs[i + 1] for i in range(0, len(pairs), 2)})
|
|
839
|
-
elif op == "INDEX":
|
|
840
|
-
key, obj = self.stack.pop(), self.stack.pop()
|
|
841
|
-
self.stack.append(obj[key])
|
|
842
|
-
elif op == "ADD":
|
|
843
|
-
b, a = self.stack.pop(), self.stack.pop()
|
|
844
|
-
self.stack.append(a + b)
|
|
845
|
-
elif op == "SUB":
|
|
846
|
-
b, a = self.stack.pop(), self.stack.pop()
|
|
847
|
-
self.stack.append(a - b)
|
|
848
|
-
elif op == "MUL":
|
|
849
|
-
b, a = self.stack.pop(), self.stack.pop()
|
|
850
|
-
self.stack.append(a * b)
|
|
851
|
-
elif op == "DIV":
|
|
852
|
-
b, a = self.stack.pop(), self.stack.pop()
|
|
853
|
-
if b == 0:
|
|
854
|
-
raise MiniPyError("ZeroDivisionError")
|
|
855
|
-
self.stack.append(a / b)
|
|
856
|
-
elif op == "FLOOR":
|
|
857
|
-
b, a = self.stack.pop(), self.stack.pop()
|
|
858
|
-
if b == 0:
|
|
859
|
-
raise MiniPyError("ZeroDivisionError")
|
|
860
|
-
self.stack.append(int(a // b))
|
|
861
|
-
elif op == "MOD":
|
|
862
|
-
b, a = self.stack.pop(), self.stack.pop()
|
|
863
|
-
if b == 0:
|
|
864
|
-
raise MiniPyError("ZeroDivisionError")
|
|
865
|
-
self.stack.append(a % b)
|
|
866
|
-
elif op == "POW":
|
|
867
|
-
b, a = self.stack.pop(), self.stack.pop()
|
|
868
|
-
self.stack.append(a ** b)
|
|
869
|
-
elif op == "NOT":
|
|
870
|
-
self.stack.append(not is_truthy(self.stack.pop()))
|
|
871
|
-
elif op == "NEG":
|
|
872
|
-
self.stack.append(-self.stack.pop())
|
|
873
|
-
elif op.startswith("CMP_"):
|
|
874
|
-
b, a = self.stack.pop(), self.stack.pop()
|
|
875
|
-
_cmp_map = {"EQ": "==", "NE": "!=", "LT": "<", "GT": ">",
|
|
876
|
-
"LE": "<=", "GE": ">=", "IN": "in", "NOT_IN": "not in"}
|
|
877
|
-
self.stack.append(_compare(_cmp_map[op[4:]], a, b))
|
|
878
|
-
elif op == "JUMP_IF_TRUE":
|
|
879
|
-
if is_truthy(self.stack[-1]):
|
|
880
|
-
ip = arg
|
|
881
|
-
elif op == "JUMP_IF_FALSE":
|
|
882
|
-
if not is_truthy(self.stack[-1]):
|
|
883
|
-
ip = arg
|
|
884
|
-
elif op == "POP":
|
|
885
|
-
self.stack.pop()
|
|
886
|
-
elif op == "CALL":
|
|
887
|
-
args = self.stack[-arg:]
|
|
888
|
-
self.stack = self.stack[:-arg]
|
|
889
|
-
f = self.stack.pop() # 函数在参数之下(先压函数后压参数)
|
|
890
|
-
if isinstance(f, tuple) and f and f[0] == "func":
|
|
891
|
-
_, params, body, def_env = f
|
|
892
|
-
local = bind_params(params, args, None, def_env) # V-P4
|
|
893
|
-
try:
|
|
894
|
-
for s in body:
|
|
895
|
-
exec_stmt(s, local)
|
|
896
|
-
self.stack.append(None)
|
|
897
|
-
except ReturnSignal as rs:
|
|
898
|
-
self.stack.append(rs.value)
|
|
899
|
-
elif callable(f): # V-P2:内置函数(与 AST 路 _BUILTINS 分派对齐)
|
|
900
|
-
self.stack.append(f(*args))
|
|
901
|
-
else:
|
|
902
|
-
raise MiniPyError(f"不可调用: {f!r}")
|
|
903
|
-
elif op == "CALL_KW": # V-P4:带关键字参数调用(栈序 f, pos..., k1,v1,...)
|
|
904
|
-
n_pos, n_kw = arg
|
|
905
|
-
kw_items = self.stack[len(self.stack) - 2 * n_kw:]
|
|
906
|
-
self.stack = self.stack[:-2 * n_kw]
|
|
907
|
-
kwargs = {kw_items[2 * i]: kw_items[2 * i + 1] for i in range(n_kw)}
|
|
908
|
-
args = self.stack[-n_pos:] if n_pos else []
|
|
909
|
-
if n_pos:
|
|
910
|
-
self.stack = self.stack[:-n_pos]
|
|
911
|
-
f = self.stack.pop()
|
|
912
|
-
if isinstance(f, tuple) and f and f[0] == "func":
|
|
913
|
-
_, params, body, def_env = f
|
|
914
|
-
local = bind_params(params, args, kwargs, def_env) # V-P4
|
|
915
|
-
try:
|
|
916
|
-
for s in body:
|
|
917
|
-
exec_stmt(s, local)
|
|
918
|
-
self.stack.append(None)
|
|
919
|
-
except ReturnSignal as rs:
|
|
920
|
-
self.stack.append(rs.value)
|
|
921
|
-
continue
|
|
922
|
-
if callable(f):
|
|
923
|
-
self.stack.append(f(*args, **kwargs))
|
|
924
|
-
else:
|
|
925
|
-
raise MiniPyError(f"不可调用: {f!r}")
|
|
926
|
-
elif op == "GET_ATTR": # T4
|
|
927
|
-
obj = self.stack.pop()
|
|
928
|
-
if arg not in _METHOD_WHITELIST:
|
|
929
|
-
raise MiniPyError(f"方法不在白名单: .{arg}(允许: {sorted(_METHOD_WHITELIST)})")
|
|
930
|
-
if not hasattr(obj, arg):
|
|
931
|
-
raise MiniPyError(f"对象无该方法: {type(obj).__name__}.{arg}")
|
|
932
|
-
self.stack.append(getattr(obj, arg))
|
|
933
|
-
elif op == "CALL_METHOD": # T4:arg=(方法名, 参数数)
|
|
934
|
-
mname, n = arg
|
|
935
|
-
args = self.stack[len(self.stack) - n:] if n else []
|
|
936
|
-
if n:
|
|
937
|
-
self.stack = self.stack[:-n]
|
|
938
|
-
obj = self.stack.pop()
|
|
939
|
-
if mname not in _METHOD_WHITELIST:
|
|
940
|
-
raise MiniPyError(f"方法不在白名单: .{mname}(允许: {sorted(_METHOD_WHITELIST)})")
|
|
941
|
-
m = getattr(obj, mname, None)
|
|
942
|
-
if not callable(m):
|
|
943
|
-
raise MiniPyError(f"不可调用: {type(obj).__name__}.{mname}")
|
|
944
|
-
self.stack.append(m(*args))
|
|
945
|
-
else:
|
|
946
|
-
raise MiniPyError(f"未知指令: {op}")
|
|
947
|
-
return self.stack[-1] if self.stack else None
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
def eval_expr_vm(src, env=None):
|
|
951
|
-
"""字节码 VM 求值入口(P5:对照 eval_expr/eval_node)"""
|
|
952
|
-
env = env or Env()
|
|
953
|
-
ast = Parser(tokenize(src)).parse()
|
|
954
|
-
code = compile_expr(ast)
|
|
955
|
-
return VM(env).run(code)
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
if __name__ == "__main__":
|
|
959
|
-
print("=== Mini-Python P2:变量环境 + 控制流(对照 CPython)===\n")
|
|
960
|
-
prog = """
|
|
961
|
-
x = 0
|
|
962
|
-
while x < 5:
|
|
963
|
-
x = x + 1
|
|
964
|
-
if x == 5:
|
|
965
|
-
y = 10
|
|
966
|
-
else:
|
|
967
|
-
y = 0
|
|
968
|
-
"""
|
|
969
|
-
env = run_program(prog)
|
|
970
|
-
print(f"① 程序执行后: x={env.get('x')} y={env.get('y')}")
|
|
971
|
-
ok = env.get("x") == 5 and env.get("y") == 10
|
|
972
|
-
print(f"\n=== 判定 ===\n变量+控制流: {'✔ 循环/条件/赋值成立(对照 CPython)' if ok else '✘'}")
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
if __name__ == "__main__":
|
|
976
|
-
print("=== Mini-Python P1:表达式求值(对照 CPython)===\n")
|
|
977
|
-
cases = [
|
|
978
|
-
("2+3*4", 14), ("2**3**2", 512), ("-2**2", -4), ("4/2", 2.0),
|
|
979
|
-
("10//3", 3), ("-7//2", -4), ("-7%2", 1), ("3>2", True),
|
|
980
|
-
("not 1>2", True), ("0 or 5", 5), ("2 and 3", 3),
|
|
981
|
-
("True or 1/0", True), ("0 and 1/0", 0), ("2**-1", 0.5),
|
|
982
|
-
("1<2<3", True), ("0 <= 15 < 10", False), ("2 == 2 == 2", True),
|
|
983
|
-
("3 > 2 > 1", True), ("0 <= 5 <= 10", True), ("(2+3)*4", 20), ("-5+3", -2),
|
|
984
|
-
]
|
|
985
|
-
ok_n = 0
|
|
986
|
-
for src, expect in cases:
|
|
987
|
-
try:
|
|
988
|
-
got = eval_expr(src)
|
|
989
|
-
ok = got == expect and type(got) is type(expect)
|
|
990
|
-
if ok:
|
|
991
|
-
ok_n += 1
|
|
992
|
-
print(f"[{'✔' if ok else '✘'}] {src} = {got!r} (期望 {expect!r})")
|
|
993
|
-
except Exception as e:
|
|
994
|
-
print(f"[✘] {src} → 异常 {e}")
|
|
995
|
-
print(f"\n=== 判定 ===\n表达式求值: {ok_n}/{len(cases)}(对照 CPython 行为)")
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""mini_python.py · Mini-Python 解释器(第六阶段 P1·机制训练场)
|
|
3
|
+
P1:词法 + 语法 + 表达式求值(对照 CPython 行为,P 线校准参考实现)
|
|
4
|
+
- or/and 返回操作数 + 短路;/ 返回 float;// % floor;** 右结合高优先级
|
|
5
|
+
- 除零抛 MiniPyError;链式比较;一元负号;-2**2 = -4
|
|
6
|
+
机制训练场:词法/AST/求值 机制供 C 线原生后端复用(语义不照抄——中文编译器走智能论语义)。
|
|
7
|
+
"""
|
|
8
|
+
import sys
|
|
9
|
+
import re
|
|
10
|
+
sys.stdout.reconfigure(encoding='utf-8')
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class MiniPyError(Exception):
|
|
14
|
+
"""运行时错误(除零等)"""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# ============ 一、词法分析 ============
|
|
18
|
+
_TOKEN_RE = [
|
|
19
|
+
("STR", r"'[^']*'|\"[^\"]*\""),
|
|
20
|
+
("NUMBER", r"\d+\.\d+|\d+"),
|
|
21
|
+
("OP", r"\*\*|//|==|!=|<=|>=|\+=|-=|\*=|/=|[+\-*/%<>()=,\[\]{}:.]"),
|
|
22
|
+
("KEY", r"and|or|not|True|False|None|if|elif|else|while|def|return"),
|
|
23
|
+
("NAME", r"[A-Za-z_]\w*"),
|
|
24
|
+
("WS", r"\s+"),
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def tokenize(src):
|
|
29
|
+
"""字符流 → token 列表(数字/运算符/关键字/括号)"""
|
|
30
|
+
tokens, i = [], 0
|
|
31
|
+
while i < len(src):
|
|
32
|
+
for kind, pat in _TOKEN_RE:
|
|
33
|
+
m = re.match(pat, src[i:])
|
|
34
|
+
if m:
|
|
35
|
+
text = m.group(0)
|
|
36
|
+
i += len(text)
|
|
37
|
+
if kind == "WS":
|
|
38
|
+
break
|
|
39
|
+
if kind == "STR":
|
|
40
|
+
tokens.append(("STRING", text[1:-1]))
|
|
41
|
+
elif kind == "KEY":
|
|
42
|
+
tokens.append((text.upper(), text))
|
|
43
|
+
elif kind == "NUMBER":
|
|
44
|
+
tokens.append(("NUMBER", float(text) if "." in text else int(text)))
|
|
45
|
+
elif kind == "NAME":
|
|
46
|
+
tokens.append(("NAME", text))
|
|
47
|
+
else:
|
|
48
|
+
tokens.append(("OP", text))
|
|
49
|
+
break
|
|
50
|
+
else:
|
|
51
|
+
raise SyntaxError(f"词法错误:未知字符 '{src[i]}'(位置 {i})")
|
|
52
|
+
tokens.append(("EOF", ""))
|
|
53
|
+
return tokens
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# ============ 二、语法分析(递归下降,Python 优先级) ============
|
|
57
|
+
class Parser:
|
|
58
|
+
def __init__(self, tokens):
|
|
59
|
+
"""解析器初始化:持有词元流与位置指针。"""
|
|
60
|
+
self.tokens = tokens
|
|
61
|
+
self.pos = 0
|
|
62
|
+
|
|
63
|
+
def peek(self):
|
|
64
|
+
"""前瞻:返回当前 token 类型但不消费。"""
|
|
65
|
+
return self.tokens[self.pos]
|
|
66
|
+
|
|
67
|
+
def advance(self):
|
|
68
|
+
"""前进:消费并返回当前 token。"""
|
|
69
|
+
t = self.tokens[self.pos]
|
|
70
|
+
self.pos += 1
|
|
71
|
+
return t
|
|
72
|
+
|
|
73
|
+
def match(self, *texts):
|
|
74
|
+
"""尝试匹配:类型相符即消费返回 True,否则 False。"""
|
|
75
|
+
t = self.peek()
|
|
76
|
+
if t[1] in texts:
|
|
77
|
+
return self.advance()
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
def _maybe_index(self, node):
|
|
81
|
+
"""索引后缀:obj[key] → ("index", obj, key)(P5 数据结构)"""
|
|
82
|
+
while self.peek()[1] == "[":
|
|
83
|
+
self.advance()
|
|
84
|
+
key = self.or_expr()
|
|
85
|
+
self.expect("]")
|
|
86
|
+
node = ("index", node, key)
|
|
87
|
+
return node
|
|
88
|
+
|
|
89
|
+
def _peek_eq(self):
|
|
90
|
+
"""后视:当前 NAME 后是否跟单个 =(kwarg 形态,区别于 ==)。"""
|
|
91
|
+
nxt = self.tokens[self.pos + 1] if self.pos + 1 < len(self.tokens) else None
|
|
92
|
+
return nxt is not None and nxt[0] == "OP" and nxt[1] == "="
|
|
93
|
+
|
|
94
|
+
def _parse_call_args(self):
|
|
95
|
+
"""调用参数列表:位置参数 + 关键字参数 k=v(V-P4 kwargs 第一批)。"""
|
|
96
|
+
args, kwargs = [], []
|
|
97
|
+
if self.peek()[1] != ")":
|
|
98
|
+
while True:
|
|
99
|
+
t = self.peek()
|
|
100
|
+
if t[0] == "NAME" and self._peek_eq(): # k=v
|
|
101
|
+
self.advance()
|
|
102
|
+
self.advance()
|
|
103
|
+
kwargs.append((t[1], self.or_expr()))
|
|
104
|
+
else:
|
|
105
|
+
args.append(self.or_expr())
|
|
106
|
+
if not self.match(","):
|
|
107
|
+
break
|
|
108
|
+
self.expect(")")
|
|
109
|
+
return args, kwargs
|
|
110
|
+
|
|
111
|
+
def _parse_suffixes(self, node, name=None):
|
|
112
|
+
"""后缀链统一:.attr / [idx] / (args)(V-P3:NAME 与字符串字面量共用)。
|
|
113
|
+
|
|
114
|
+
循环消化后缀使链式调用成立(s.strip().upper());调用结果再取下标
|
|
115
|
+
(f(x)[0])同样支持。obj.method(args) → ("method", obj, name, args);
|
|
116
|
+
name(args) → ("call", ...)。下标结果再调用(如 a[0](x))显式不支持
|
|
117
|
+
——原实现会静默错当 a(x)。
|
|
118
|
+
"""
|
|
119
|
+
while True:
|
|
120
|
+
t1 = self.peek()[1]
|
|
121
|
+
if t1 == ".":
|
|
122
|
+
self.advance()
|
|
123
|
+
attr = self.advance()
|
|
124
|
+
if attr[0] != "NAME":
|
|
125
|
+
raise SyntaxError(f"语法错误:'.' 后应为属性名,得到 '{attr[1]}'")
|
|
126
|
+
node = ("attr", node, attr[1])
|
|
127
|
+
elif t1 == "[":
|
|
128
|
+
self.advance()
|
|
129
|
+
key = self.or_expr()
|
|
130
|
+
self.expect("]")
|
|
131
|
+
node = ("index", node, key)
|
|
132
|
+
elif t1 == "(":
|
|
133
|
+
self.advance()
|
|
134
|
+
args, kwargs = self._parse_call_args()
|
|
135
|
+
if node[0] == "attr": # obj.method(args) → 方法调用节点
|
|
136
|
+
node = ("method", node[1], node[2], args, kwargs)
|
|
137
|
+
elif name is not None and node[0] == "name" and node[1] == name:
|
|
138
|
+
node = ("call", name, args, kwargs)
|
|
139
|
+
else:
|
|
140
|
+
raise SyntaxError("语法错误:该表达式不可调用(下标结果调用不支持)")
|
|
141
|
+
else:
|
|
142
|
+
break
|
|
143
|
+
return node
|
|
144
|
+
|
|
145
|
+
def expect(self, text):
|
|
146
|
+
t = self.peek()
|
|
147
|
+
if t[1] != text:
|
|
148
|
+
raise SyntaxError(f"语法错误:期望 '{text}',得到 '{t[1]}'")
|
|
149
|
+
return self.advance()
|
|
150
|
+
|
|
151
|
+
def parse(self):
|
|
152
|
+
node = self.or_expr()
|
|
153
|
+
if self.peek()[0] != "EOF":
|
|
154
|
+
raise SyntaxError(f"语法错误:意外的 token '{self.peek()[1]}'")
|
|
155
|
+
return node
|
|
156
|
+
|
|
157
|
+
def or_expr(self):
|
|
158
|
+
"""or 链:短路求值(左真返左,否则续右)——对照 CPython 语义。"""
|
|
159
|
+
node = self.and_expr()
|
|
160
|
+
while self.match("or"):
|
|
161
|
+
node = ("or", node, self.and_expr())
|
|
162
|
+
return node
|
|
163
|
+
|
|
164
|
+
def and_expr(self):
|
|
165
|
+
"""and 链:短路求值(左假返假,否则续右)。"""
|
|
166
|
+
node = self.not_expr()
|
|
167
|
+
while self.match("and"):
|
|
168
|
+
node = ("and", node, self.not_expr())
|
|
169
|
+
return node
|
|
170
|
+
|
|
171
|
+
def not_expr(self):
|
|
172
|
+
"""not 一元表达式求值。"""
|
|
173
|
+
if self.match("not"):
|
|
174
|
+
return ("not", self.not_expr())
|
|
175
|
+
return self.comparison()
|
|
176
|
+
|
|
177
|
+
def comparison(self):
|
|
178
|
+
"""比较链:== != < <= > >= in / not in(V-P4)。
|
|
179
|
+
|
|
180
|
+
issue #401:按 **CPython 语义** `a < b < c` ≡ `(a < b) and (b < c)`(逐对求值、
|
|
181
|
+
前一对为假即短路,**中间操作数只求值一次**)。修前每遇一个比较符就把已构造的
|
|
182
|
+
node 当左操作数再套一层 ⇒ 按**左结合**求值 `(a < b) < c` ⇒ 数值区间判断整类算错
|
|
183
|
+
(`0 <= 15 < 10` 恒 True)。链长 > 1 时产 `("chain", ops, operands)` 节点。
|
|
184
|
+
"""
|
|
185
|
+
first = self.arith()
|
|
186
|
+
ops, operands = [], [first]
|
|
187
|
+
while True:
|
|
188
|
+
t = self.peek()
|
|
189
|
+
if t[1] in ("==", "!=", "<", ">", "<=", ">="):
|
|
190
|
+
self.advance()
|
|
191
|
+
ops.append(t[1])
|
|
192
|
+
operands.append(self.arith())
|
|
193
|
+
elif t[1] == "in": # V-P4:成员运算符(in 为 NAME token)
|
|
194
|
+
self.advance()
|
|
195
|
+
ops.append("in")
|
|
196
|
+
operands.append(self.arith())
|
|
197
|
+
elif t[1] == "not" and self._peek_is_in(): # not in(KEY token)
|
|
198
|
+
self.advance()
|
|
199
|
+
self.advance() # 消费 in
|
|
200
|
+
ops.append("not in")
|
|
201
|
+
operands.append(self.arith())
|
|
202
|
+
else:
|
|
203
|
+
break
|
|
204
|
+
if not ops:
|
|
205
|
+
return first
|
|
206
|
+
if len(ops) == 1:
|
|
207
|
+
return (ops[0], operands[0], operands[1])
|
|
208
|
+
return ("chain", ops, operands)
|
|
209
|
+
|
|
210
|
+
def _peek_is_in(self):
|
|
211
|
+
"""后视:not 后是否跟 in(not in 运算符,区别于逻辑 not 前缀)。"""
|
|
212
|
+
nxt = self.tokens[self.pos + 1] if self.pos + 1 < len(self.tokens) else None
|
|
213
|
+
return nxt is not None and nxt[1] == "in"
|
|
214
|
+
|
|
215
|
+
def arith(self):
|
|
216
|
+
"""加减项:+ - 左结合。"""
|
|
217
|
+
node = self.term()
|
|
218
|
+
while True:
|
|
219
|
+
t = self.peek()
|
|
220
|
+
if t[1] in ("+", "-"):
|
|
221
|
+
self.advance()
|
|
222
|
+
node = (t[1], node, self.term())
|
|
223
|
+
else:
|
|
224
|
+
return node
|
|
225
|
+
|
|
226
|
+
def term(self):
|
|
227
|
+
"""乘除项:* / // % 左结合。"""
|
|
228
|
+
node = self.factor()
|
|
229
|
+
while True:
|
|
230
|
+
t = self.peek()
|
|
231
|
+
if t[1] in ("*", "/", "//", "%"):
|
|
232
|
+
self.advance()
|
|
233
|
+
node = (t[1], node, self.factor())
|
|
234
|
+
else:
|
|
235
|
+
return node
|
|
236
|
+
|
|
237
|
+
def factor(self):
|
|
238
|
+
"""一元因子:- 负号 / not 前缀。"""
|
|
239
|
+
if self.peek()[1] in ("-", "+"):
|
|
240
|
+
op = self.advance()[1]
|
|
241
|
+
return (op, self.factor()) # 一元负号在外层:-2**2 = -(2**2)
|
|
242
|
+
return self.power()
|
|
243
|
+
|
|
244
|
+
def power(self):
|
|
245
|
+
"""幂运算:** 右结合。"""
|
|
246
|
+
node = self.atom()
|
|
247
|
+
if self.match("**"):
|
|
248
|
+
return ("**", node, self.factor()) # 右结合
|
|
249
|
+
return node
|
|
250
|
+
|
|
251
|
+
def atom(self):
|
|
252
|
+
"""原子项:数字/字符串/名称/括号表达式/[列表]/字典字面量。"""
|
|
253
|
+
t = self.peek()
|
|
254
|
+
if t[0] == "NUMBER":
|
|
255
|
+
self.advance()
|
|
256
|
+
return ("num", t[1])
|
|
257
|
+
if t[0] == "STRING": # P5:字符串字面量(V-P3:后缀链与 NAME 统一)
|
|
258
|
+
self.advance()
|
|
259
|
+
return self._parse_suffixes(("str", t[1]))
|
|
260
|
+
if t[0] == "NAME": # 变量/函数调用/方法链(P3 + T4 后缀统一)
|
|
261
|
+
self.advance()
|
|
262
|
+
return self._parse_suffixes(("name", t[1]), name=t[1])
|
|
263
|
+
if t[1] == "[":
|
|
264
|
+
self.advance()
|
|
265
|
+
items = []
|
|
266
|
+
if self.peek()[1] != "]":
|
|
267
|
+
items.append(self.or_expr())
|
|
268
|
+
while self.match(","):
|
|
269
|
+
items.append(self.or_expr())
|
|
270
|
+
self.expect("]")
|
|
271
|
+
return self._maybe_index(("list", items))
|
|
272
|
+
if t[1] == "{":
|
|
273
|
+
self.advance()
|
|
274
|
+
pairs = []
|
|
275
|
+
if self.peek()[1] != "}":
|
|
276
|
+
k = self.or_expr()
|
|
277
|
+
self.expect(":")
|
|
278
|
+
v = self.or_expr()
|
|
279
|
+
pairs.append((k, v))
|
|
280
|
+
while self.match(","):
|
|
281
|
+
k = self.or_expr()
|
|
282
|
+
self.expect(":")
|
|
283
|
+
v = self.or_expr()
|
|
284
|
+
pairs.append((k, v))
|
|
285
|
+
self.expect("}")
|
|
286
|
+
return self._maybe_index(("dict", pairs))
|
|
287
|
+
if t[1] == "True":
|
|
288
|
+
self.advance()
|
|
289
|
+
return ("bool", True)
|
|
290
|
+
if t[1] == "False":
|
|
291
|
+
self.advance()
|
|
292
|
+
return ("bool", False)
|
|
293
|
+
if t[1] == "None":
|
|
294
|
+
self.advance()
|
|
295
|
+
return ("none", None)
|
|
296
|
+
if t[1] == "(":
|
|
297
|
+
self.advance()
|
|
298
|
+
node = self.or_expr()
|
|
299
|
+
self.expect(")")
|
|
300
|
+
return node
|
|
301
|
+
raise SyntaxError(f"语法错误:意外的 token '{t[1]}'")
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
# ============ 三、求值(对照 CPython 行为) ============
|
|
305
|
+
def is_truthy(v):
|
|
306
|
+
"""真值判定:对照 CPython 规则(None/False/0/空容器/空串为假)。"""
|
|
307
|
+
if v is None or v is False:
|
|
308
|
+
return False
|
|
309
|
+
if isinstance(v, (int, float)) and v == 0:
|
|
310
|
+
return False
|
|
311
|
+
if isinstance(v, (str, list, tuple, dict)) and len(v) == 0:
|
|
312
|
+
return False
|
|
313
|
+
return True
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def eval_node(node, env=None):
|
|
317
|
+
"""AST 求值(P2:env 提供变量环境;name 节点从环境取值)"""
|
|
318
|
+
kind = node[0]
|
|
319
|
+
if kind == "num":
|
|
320
|
+
return node[1]
|
|
321
|
+
if kind == "str":
|
|
322
|
+
return node[1]
|
|
323
|
+
if kind == "bool":
|
|
324
|
+
return node[1]
|
|
325
|
+
if kind == "none":
|
|
326
|
+
return None
|
|
327
|
+
if kind == "name":
|
|
328
|
+
if env is not None:
|
|
329
|
+
try:
|
|
330
|
+
return env.get(node[1])
|
|
331
|
+
except MiniPyError:
|
|
332
|
+
pass
|
|
333
|
+
if node[1] in _BUILTINS: # V-P4:内置函数可作值引用(sorted(x, key=len))
|
|
334
|
+
return _BUILTINS[node[1]]
|
|
335
|
+
raise MiniPyError(f"NameError: name '{node[1]}' is not defined")
|
|
336
|
+
if kind == "or":
|
|
337
|
+
a = eval_node(node[1], env)
|
|
338
|
+
return a if is_truthy(a) else eval_node(node[2], env)
|
|
339
|
+
if kind == "and":
|
|
340
|
+
a = eval_node(node[1], env)
|
|
341
|
+
return eval_node(node[2], env) if is_truthy(a) else a
|
|
342
|
+
if kind == "not":
|
|
343
|
+
return not is_truthy(eval_node(node[1], env))
|
|
344
|
+
if kind == "chain":
|
|
345
|
+
# issue #401:`a < b < c` ≡ `(a<b) and (b<c)`——逐对求值、前一对假即短路,
|
|
346
|
+
# 中间操作数**只求值一次**(修前按左结合 `(a<b)<c`)。
|
|
347
|
+
_ops, _operands = node[1], node[2]
|
|
348
|
+
_prev = eval_node(_operands[0], env)
|
|
349
|
+
for _i, _op in enumerate(_ops):
|
|
350
|
+
_cur = eval_node(_operands[_i + 1], env)
|
|
351
|
+
if not is_truthy(_compare(_op, _prev, _cur)):
|
|
352
|
+
return False
|
|
353
|
+
_prev = _cur
|
|
354
|
+
return True
|
|
355
|
+
if kind in ("==", "!=", "<", ">", "<=", ">=", "in", "not in"):
|
|
356
|
+
return _compare(kind, eval_node(node[1], env), eval_node(node[2], env))
|
|
357
|
+
if kind in ("-", "+") and len(node) == 2: # 一元(先于二元判断)
|
|
358
|
+
v = eval_node(node[1], env)
|
|
359
|
+
return -v if kind == "-" else +v
|
|
360
|
+
if kind == "+":
|
|
361
|
+
return eval_node(node[1], env) + eval_node(node[2], env)
|
|
362
|
+
if kind == "-":
|
|
363
|
+
return eval_node(node[1], env) - eval_node(node[2], env)
|
|
364
|
+
if kind == "*":
|
|
365
|
+
return eval_node(node[1], env) * eval_node(node[2], env)
|
|
366
|
+
if kind == "/":
|
|
367
|
+
b = eval_node(node[2], env)
|
|
368
|
+
if b == 0:
|
|
369
|
+
raise MiniPyError("ZeroDivisionError: division by zero")
|
|
370
|
+
return eval_node(node[1], env) / b
|
|
371
|
+
if kind == "//":
|
|
372
|
+
b = eval_node(node[2], env)
|
|
373
|
+
if b == 0:
|
|
374
|
+
raise MiniPyError("ZeroDivisionError: integer division by zero")
|
|
375
|
+
a = eval_node(node[1], env)
|
|
376
|
+
return int(a // b) # floor(Python 语义)
|
|
377
|
+
if kind == "%":
|
|
378
|
+
b = eval_node(node[2], env)
|
|
379
|
+
if b == 0:
|
|
380
|
+
raise MiniPyError("ZeroDivisionError: modulo by zero")
|
|
381
|
+
return eval_node(node[1], env) % b
|
|
382
|
+
if kind == "**":
|
|
383
|
+
return eval_node(node[1], env) ** eval_node(node[2], env)
|
|
384
|
+
if kind == "attr": # T4:属性/方法访问(白名单内才放行)
|
|
385
|
+
obj = eval_node(node[1], env)
|
|
386
|
+
if node[2] not in _METHOD_WHITELIST:
|
|
387
|
+
raise MiniPyError(f"方法不在白名单: .{node[2]}(允许: {sorted(_METHOD_WHITELIST)})")
|
|
388
|
+
if not hasattr(obj, node[2]):
|
|
389
|
+
raise MiniPyError(f"对象无该方法: {type(obj).__name__}.{node[2]}")
|
|
390
|
+
return getattr(obj, node[2])
|
|
391
|
+
if kind == "method": # T4:obj.method(args) 调用(白名单校验)
|
|
392
|
+
obj = eval_node(node[1], env)
|
|
393
|
+
if node[2] not in _METHOD_WHITELIST:
|
|
394
|
+
raise MiniPyError(f"方法不在白名单: .{node[2]}(允许: {sorted(_METHOD_WHITELIST)})")
|
|
395
|
+
m = getattr(obj, node[2], None)
|
|
396
|
+
if not callable(m):
|
|
397
|
+
raise MiniPyError(f"不可调用: {type(obj).__name__}.{node[2]}")
|
|
398
|
+
args = [eval_node(a, env) for a in node[3]]
|
|
399
|
+
kw = {k: eval_node(v, env) for k, v in node[4]} if len(node) > 4 else {}
|
|
400
|
+
return m(*args, **kw)
|
|
401
|
+
if kind == "call": # 函数调用(P3:局部作用域 + 参数绑定 + return 捕获)
|
|
402
|
+
try:
|
|
403
|
+
f = env.get(node[1]) if env is not None else None
|
|
404
|
+
except MiniPyError:
|
|
405
|
+
f = None
|
|
406
|
+
builtin = _BUILTINS.get(node[1])
|
|
407
|
+
kw = {k: eval_node(v, env) for k, v in node[3]} if len(node) > 3 else {}
|
|
408
|
+
if not (isinstance(f, tuple) and f[0] == "func"):
|
|
409
|
+
if builtin is not None:
|
|
410
|
+
args = [eval_node(a, env) for a in node[2]]
|
|
411
|
+
return builtin(*args, **kw)
|
|
412
|
+
raise MiniPyError(f"NameError: name '{node[1]}' is not defined")
|
|
413
|
+
args = [eval_node(a, env) for a in node[2]]
|
|
414
|
+
_, params, body, def_env = f
|
|
415
|
+
local = bind_params(params, args, kw, def_env) # V-P4:默认值+kwargs 绑定
|
|
416
|
+
try:
|
|
417
|
+
for s in body:
|
|
418
|
+
exec_stmt(s, local)
|
|
419
|
+
except ReturnSignal as rs:
|
|
420
|
+
return rs.value
|
|
421
|
+
return None
|
|
422
|
+
if kind == "list": # P5:list 字面量
|
|
423
|
+
return [eval_node(e, env) for e in node[1]]
|
|
424
|
+
if kind == "dict": # P5:dict 字面量
|
|
425
|
+
return {eval_node(k, env): eval_node(v, env) for k, v in node[1]}
|
|
426
|
+
if kind == "index": # P5:obj[key]
|
|
427
|
+
obj = eval_node(node[1], env)
|
|
428
|
+
key = eval_node(node[2], env)
|
|
429
|
+
try:
|
|
430
|
+
return obj[key]
|
|
431
|
+
except (TypeError, IndexError, KeyError):
|
|
432
|
+
raise MiniPyError(f"索引错误:{obj!r}[{key!r}]")
|
|
433
|
+
raise MiniPyError(f"未知节点: {node}")
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _compare(op, a, b):
|
|
437
|
+
"""比较运算统一求值:==·!=·<·>·in·not in 分派(对照 CPython 类型提升)。"""
|
|
438
|
+
if op == "in": # V-P4:成员运算(str/list/tuple/dict 原生语义)
|
|
439
|
+
return a in b
|
|
440
|
+
if op == "not in":
|
|
441
|
+
return a not in b
|
|
442
|
+
return {"==": a == b, "!=": a != b, "<": a < b, ">": a > b,
|
|
443
|
+
"<=": a <= b, ">=": a >= b}[op]
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def eval_expr(src):
|
|
447
|
+
"""表达式求值入口:源码 → 值(P1)"""
|
|
448
|
+
tokens = tokenize(src)
|
|
449
|
+
ast = Parser(tokens).parse()
|
|
450
|
+
return eval_node(ast)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
# ============ P2:变量环境 + 控制流(赋值/if/while,缩进块) ============
|
|
454
|
+
# 语句树:("assign", name, expr) / ("if", cond, then[], else[]) /
|
|
455
|
+
# ("while", cond, body[]) / ("expr", expr)
|
|
456
|
+
# 缩进块解析:行 → (缩进, 语句) → 嵌套树
|
|
457
|
+
|
|
458
|
+
# 内置函数表(P4 补全 2026-08-27):对照 CPython 语义的最小白箱内置集
|
|
459
|
+
_BUILTINS = {
|
|
460
|
+
"range": lambda *a: list(range(*[int(x) for x in a])),
|
|
461
|
+
"len": len, "sum": sum, "abs": abs, "min": min, "max": max,
|
|
462
|
+
"int": int, "float": float, "str": str, "list": list, "sorted": sorted,
|
|
463
|
+
"print": print,
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
# 方法白名单(T4 起步 upper/split;V-P3 扩展 str 方法族 + V-P2 揭示 F4 需
|
|
467
|
+
# list.append / dict.get 容器方法原语——全部为 CPython 原生方法,getattr
|
|
468
|
+
# 分派直接对齐 CPython 语义。contains 不入列:str 无 .contains,应走 in
|
|
469
|
+
# 运算符(V-P4 挂账,涉及 for 头解析冲突需专项))
|
|
470
|
+
_METHOD_WHITELIST = {"upper", "split", "startswith", "endswith", "strip", "join",
|
|
471
|
+
"append", "get"}
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
class Env:
|
|
475
|
+
"""变量环境(P3:作用域链——局部 → 父环境)"""
|
|
476
|
+
def __init__(self, parent=None):
|
|
477
|
+
"""作用域帧构造:本地变量表 + 父链指向外层(链式查找)。"""
|
|
478
|
+
self.vars = {}
|
|
479
|
+
self.parent = parent
|
|
480
|
+
|
|
481
|
+
def get(self, name):
|
|
482
|
+
"""变量读取:沿父作用域链向上查找,未定义抛 NameError。"""
|
|
483
|
+
if name in self.vars:
|
|
484
|
+
return self.vars[name]
|
|
485
|
+
if self.parent:
|
|
486
|
+
return self.parent.get(name)
|
|
487
|
+
raise MiniPyError(f"NameError: name '{name}' is not defined")
|
|
488
|
+
|
|
489
|
+
def set(self, name, value):
|
|
490
|
+
"""变量赋值绑定到当前作用域。"""
|
|
491
|
+
self.vars[name] = value
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def bind_params(params, args, kw, def_env):
|
|
495
|
+
"""V-P4 第三批:参数绑定(位置→关键字→默认值),AST 与 VM 共用。
|
|
496
|
+
|
|
497
|
+
params 元素 = (name, default_ast|None);默认值在定义环境 def_env 求值。
|
|
498
|
+
"""
|
|
499
|
+
from_dict = dict(kw or {})
|
|
500
|
+
values = {}
|
|
501
|
+
for i, (pname, dflt) in enumerate(params):
|
|
502
|
+
if i < len(args):
|
|
503
|
+
values[pname] = args[i]
|
|
504
|
+
elif pname in from_dict:
|
|
505
|
+
values[pname] = from_dict.pop(pname)
|
|
506
|
+
elif dflt is not None:
|
|
507
|
+
values[pname] = eval_node(dflt, def_env)
|
|
508
|
+
else:
|
|
509
|
+
raise MiniPyError(f"参数缺失: {pname}(无默认值且未传)")
|
|
510
|
+
if from_dict:
|
|
511
|
+
raise MiniPyError(f"未识别的关键字参数: {sorted(from_dict)}")
|
|
512
|
+
local = Env(def_env)
|
|
513
|
+
for k, v in values.items():
|
|
514
|
+
local.set(k, v)
|
|
515
|
+
return local
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
class ReturnSignal(Exception):
|
|
519
|
+
"""return 语句信号(P3)"""
|
|
520
|
+
def __init__(self, value):
|
|
521
|
+
"""常量值包装(字面量求值结果载体)。"""
|
|
522
|
+
self.value = value
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
# T4:复合赋值符(模块级预编译)
|
|
526
|
+
_AUG_RE = re.compile(r"(\w+)\s*(\+=|-=|\*=|/=)\s*(.+)$")
|
|
527
|
+
# T4:普通赋值行首形态(变量名 + 单个 =,排除 ==/<=/>=/!= 与字符串内等号)
|
|
528
|
+
_ASSIGN_RE = re.compile(r"([A-Za-z_]\w*)\s*=(?!=)")
|
|
529
|
+
# V-P2:下标赋值行首形态(obj[key] = value;[(.+)] 贪婪至最后一个 ])
|
|
530
|
+
_SUBASSIGN_RE = re.compile(r"([A-Za-z_]\w*)\s*\[(.+)\]\s*=(?!=)\s*(.+)$")
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def parse_program(src):
|
|
534
|
+
"""源码 → 语句树(缩进决定嵌套)"""
|
|
535
|
+
lines = []
|
|
536
|
+
for raw in src.splitlines():
|
|
537
|
+
if not raw.strip() or raw.strip().startswith("#"):
|
|
538
|
+
continue
|
|
539
|
+
indent = len(raw) - len(raw.lstrip(" "))
|
|
540
|
+
lines.append((indent, raw.strip()))
|
|
541
|
+
# 缩进栈构建嵌套
|
|
542
|
+
def build(idx, indent):
|
|
543
|
+
stmts = []
|
|
544
|
+
while idx[0] < len(lines):
|
|
545
|
+
cur_indent, code = lines[idx[0]]
|
|
546
|
+
if cur_indent < indent:
|
|
547
|
+
break
|
|
548
|
+
if cur_indent > indent:
|
|
549
|
+
raise SyntaxError(f"意外的缩进:{code}")
|
|
550
|
+
idx[0] += 1
|
|
551
|
+
stmts.append(_parse_line(code, build, idx))
|
|
552
|
+
return stmts
|
|
553
|
+
|
|
554
|
+
def _parse_line(code, build, idx):
|
|
555
|
+
# T4:复合赋值 += -= *= /=(先于 = 检测,避免 "x += 1" 被 split("=",1) 误拆)
|
|
556
|
+
m_aug = _AUG_RE.match(code)
|
|
557
|
+
if m_aug:
|
|
558
|
+
return ("aug_assign", m_aug.group(1), m_aug.group(2),
|
|
559
|
+
Parser(tokenize(m_aug.group(3))).parse())
|
|
560
|
+
# 赋值(T4 修正:行首 \w+= 形态判定——字符串内等号/"=="不再误判为赋值)
|
|
561
|
+
m_assign = _ASSIGN_RE.match(code)
|
|
562
|
+
if m_assign:
|
|
563
|
+
return ("assign", m_assign.group(1),
|
|
564
|
+
Parser(tokenize(code[m_assign.end():])).parse())
|
|
565
|
+
# 下标赋值 obj[key] = value(V-P2:F4 字典/列表写入原语;贪婪匹配
|
|
566
|
+
# 最后一个 ] 使嵌套 key 如 a[b[1]] 正确拆分)
|
|
567
|
+
m_sub = _SUBASSIGN_RE.match(code)
|
|
568
|
+
if m_sub:
|
|
569
|
+
return ("index_assign", m_sub.group(1),
|
|
570
|
+
Parser(tokenize(m_sub.group(2))).parse(),
|
|
571
|
+
Parser(tokenize(m_sub.group(3))).parse())
|
|
572
|
+
# if/elif/else
|
|
573
|
+
if code.startswith("def "):
|
|
574
|
+
import re as _re
|
|
575
|
+
m = _re.match(r"def\s+(\w+)\s*\(([^)]*)\)\s*:", code)
|
|
576
|
+
name = m.group(1)
|
|
577
|
+
# V-P4 第三批:参数支持默认值 name=expr → (name, default_ast|None)
|
|
578
|
+
params = []
|
|
579
|
+
for p_raw in m.group(2).split(","):
|
|
580
|
+
p_raw = p_raw.strip()
|
|
581
|
+
if not p_raw:
|
|
582
|
+
continue
|
|
583
|
+
if "=" in p_raw:
|
|
584
|
+
pn, _, pv = p_raw.partition("=")
|
|
585
|
+
params.append((pn.strip(), Parser(tokenize(pv.strip())).parse()))
|
|
586
|
+
else:
|
|
587
|
+
params.append((p_raw, None))
|
|
588
|
+
body = build(idx, lines[idx[0]][0] if idx[0] < len(lines) else 0)
|
|
589
|
+
return ("funcdef", name, params, body)
|
|
590
|
+
if code.startswith("return "):
|
|
591
|
+
return ("return", Parser(tokenize(code[7:])).parse())
|
|
592
|
+
if code.startswith("if "):
|
|
593
|
+
cond = Parser(tokenize(code[3:].rstrip(":"))).parse()
|
|
594
|
+
then_indent = lines[idx[0]][0] if idx[0] < len(lines) else 0
|
|
595
|
+
then = build(idx, then_indent)
|
|
596
|
+
else_stmts = []
|
|
597
|
+
# else 配对:同缩进 else 行 → else 块
|
|
598
|
+
if idx[0] < len(lines) and lines[idx[0]][1].startswith("else"):
|
|
599
|
+
idx[0] += 1 # 消费 else 行
|
|
600
|
+
else_indent = lines[idx[0]][0] if idx[0] < len(lines) else 0
|
|
601
|
+
else_stmts = build(idx, else_indent)
|
|
602
|
+
return ("if", cond, then, else_stmts)
|
|
603
|
+
# P4 补全(2026-08-27 · 荣「求和=1.0」缺陷根治):for 语句
|
|
604
|
+
if code.startswith("for "):
|
|
605
|
+
import re as _re
|
|
606
|
+
m = _re.match(r"for\s+(\w+)\s+in\s+(.+):$", code)
|
|
607
|
+
if not m:
|
|
608
|
+
raise SyntaxError("for 语句格式:for 变量 in 可迭代对象:")
|
|
609
|
+
var = m.group(1)
|
|
610
|
+
iterable = Parser(tokenize(m.group(2))).parse()
|
|
611
|
+
body_indent = lines[idx[0]][0] if idx[0] < len(lines) else 0
|
|
612
|
+
body = build(idx, body_indent)
|
|
613
|
+
return ("for", var, iterable, body)
|
|
614
|
+
if code.startswith("while "):
|
|
615
|
+
cond = Parser(tokenize(code[6:].rstrip(":"))).parse()
|
|
616
|
+
body = build(idx, lines[idx[0]][0] if idx[0] < len(lines) else 0)
|
|
617
|
+
return ("while", cond, body)
|
|
618
|
+
if code.startswith(("else", "elif ")):
|
|
619
|
+
raise SyntaxError("else/elif 未与 if 配对(意外的 else 行)")
|
|
620
|
+
# 表达式语句
|
|
621
|
+
return ("expr", Parser(tokenize(code)).parse())
|
|
622
|
+
|
|
623
|
+
idx = [0]
|
|
624
|
+
return build(idx, 0)
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def exec_stmt(stmt, env):
|
|
628
|
+
"""执行单条语句(if/while/funcdef 递归执行块)"""
|
|
629
|
+
kind = stmt[0]
|
|
630
|
+
if kind == "assign":
|
|
631
|
+
env.set(stmt[1], eval_node(stmt[2], env))
|
|
632
|
+
elif kind == "index_assign": # V-P2:下标写入 obj[key] = value(list/dict 原生语义)
|
|
633
|
+
obj = env.get(stmt[1])
|
|
634
|
+
key = eval_node(stmt[2], env)
|
|
635
|
+
try:
|
|
636
|
+
obj[key] = eval_node(stmt[3], env)
|
|
637
|
+
except IndexError:
|
|
638
|
+
raise MiniPyError(f"索引赋值越界:{obj!r}[{key!r}]")
|
|
639
|
+
except TypeError:
|
|
640
|
+
raise MiniPyError(f"类型不支持下标赋值:{type(obj).__name__}[{key!r}]")
|
|
641
|
+
elif kind == "aug_assign": # T4:x op= e → x = x op e(/= 除零对齐 / 语义)
|
|
642
|
+
cur = env.get(stmt[1])
|
|
643
|
+
rhs = eval_node(stmt[3], env)
|
|
644
|
+
op = stmt[2]
|
|
645
|
+
if op == "+=":
|
|
646
|
+
env.set(stmt[1], cur + rhs)
|
|
647
|
+
elif op == "-=":
|
|
648
|
+
env.set(stmt[1], cur - rhs)
|
|
649
|
+
elif op == "*=":
|
|
650
|
+
env.set(stmt[1], cur * rhs)
|
|
651
|
+
else:
|
|
652
|
+
if rhs == 0:
|
|
653
|
+
raise MiniPyError("ZeroDivisionError: division by zero")
|
|
654
|
+
env.set(stmt[1], cur / rhs)
|
|
655
|
+
elif kind == "funcdef":
|
|
656
|
+
# 函数对象 = 参数 + body + 定义环境(P4 闭包基础)
|
|
657
|
+
env.set(stmt[1], ("func", stmt[2], stmt[3], env))
|
|
658
|
+
elif kind == "return":
|
|
659
|
+
raise ReturnSignal(eval_node(stmt[1], env))
|
|
660
|
+
elif kind == "if":
|
|
661
|
+
if is_truthy(eval_node(stmt[1], env)):
|
|
662
|
+
for s in stmt[2]:
|
|
663
|
+
exec_stmt(s, env)
|
|
664
|
+
elif stmt[3]:
|
|
665
|
+
for s in stmt[3]:
|
|
666
|
+
exec_stmt(s, env)
|
|
667
|
+
elif kind == "while":
|
|
668
|
+
guard = 0
|
|
669
|
+
while is_truthy(eval_node(stmt[1], env)) and guard < 10000:
|
|
670
|
+
for s in stmt[2]:
|
|
671
|
+
exec_stmt(s, env)
|
|
672
|
+
guard += 1
|
|
673
|
+
elif kind == "for":
|
|
674
|
+
_, var, iter_node, body = stmt
|
|
675
|
+
iterable = eval_node(iter_node, env)
|
|
676
|
+
if isinstance(iterable, (list, tuple)):
|
|
677
|
+
items = list(iterable)
|
|
678
|
+
elif isinstance(iterable, str):
|
|
679
|
+
items = list(iterable)
|
|
680
|
+
elif hasattr(iterable, "__iter__"):
|
|
681
|
+
items = list(iterable)
|
|
682
|
+
else:
|
|
683
|
+
raise MiniPyError(f"for 迭代对象不可迭代: {type(iterable).__name__}")
|
|
684
|
+
for item in items[:10000]: # 步数上限对齐 while guard 纪律
|
|
685
|
+
env.set(var, item)
|
|
686
|
+
for s in body:
|
|
687
|
+
exec_stmt(s, env)
|
|
688
|
+
elif kind == "expr":
|
|
689
|
+
eval_node(stmt[1], env)
|
|
690
|
+
else:
|
|
691
|
+
raise MiniPyError(f"未知语句: {stmt}")
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
def run_program(src):
|
|
695
|
+
"""程序执行:源码 → Env(P2:变量/if/while)"""
|
|
696
|
+
env = Env()
|
|
697
|
+
for stmt in parse_program(src):
|
|
698
|
+
exec_stmt(stmt, env)
|
|
699
|
+
return env
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
# ============ P5:字节码 VM 雏形(栈机——机制供 C 线原生后端复用) ============
|
|
703
|
+
# 表达式 → 字节码指令 → 栈机执行(对照 eval_node 结果)
|
|
704
|
+
# 指令:PUSH_CONST/PUSH_LIST/PUSH_DICT/LOAD_NAME/ADD/SUB/MUL/DIV/FLOOR/MOD/POW/
|
|
705
|
+
# NEG/AND_OR/CMP_*/JUMP_IF_FALSE/JUMP(逻辑短路用跳转)
|
|
706
|
+
|
|
707
|
+
def compile_expr(node):
|
|
708
|
+
"""AST 表达式 → 字节码指令列表(栈机)"""
|
|
709
|
+
kind = node[0]
|
|
710
|
+
if kind == "num":
|
|
711
|
+
return [("PUSH_CONST", node[1])]
|
|
712
|
+
if kind == "str":
|
|
713
|
+
return [("PUSH_CONST", node[1])]
|
|
714
|
+
if kind == "bool":
|
|
715
|
+
return [("PUSH_CONST", node[1])]
|
|
716
|
+
if kind == "none":
|
|
717
|
+
return [("PUSH_CONST", None)]
|
|
718
|
+
if kind == "name":
|
|
719
|
+
return [("LOAD_NAME", node[1])]
|
|
720
|
+
if kind == "list":
|
|
721
|
+
code = []
|
|
722
|
+
for e in node[1]:
|
|
723
|
+
code.extend(compile_expr(e))
|
|
724
|
+
code.append(("PUSH_LIST", len(node[1])))
|
|
725
|
+
return code
|
|
726
|
+
if kind == "dict":
|
|
727
|
+
code = []
|
|
728
|
+
for k, v in node[1]:
|
|
729
|
+
code.extend(compile_expr(k))
|
|
730
|
+
code.extend(compile_expr(v))
|
|
731
|
+
code.append(("PUSH_DICT", len(node[1])))
|
|
732
|
+
return code
|
|
733
|
+
if kind == "index":
|
|
734
|
+
code = compile_expr(node[1]) + compile_expr(node[2])
|
|
735
|
+
code.append(("INDEX", None))
|
|
736
|
+
return code
|
|
737
|
+
if kind in ("-", "+") and len(node) == 2: # 一元
|
|
738
|
+
code = compile_expr(node[1])
|
|
739
|
+
if kind == "-":
|
|
740
|
+
code.append(("NEG", None))
|
|
741
|
+
return code
|
|
742
|
+
if kind in ("+", "-", "*", "/", "//", "%", "**"):
|
|
743
|
+
code = compile_expr(node[1]) + compile_expr(node[2])
|
|
744
|
+
code.append((_ARITH_VM[kind], None))
|
|
745
|
+
return code
|
|
746
|
+
if kind == "chain":
|
|
747
|
+
# issue #401:字节码面按 `and` 语义展开(逐对求值、前一对假即短路)。
|
|
748
|
+
# 说明:本面中间操作数会被求值两次(VM 无 DUP),仅对**有副作用**的操作数
|
|
749
|
+
# 可观测;需要严格单次求值请走树遍历面(eval_expr)。
|
|
750
|
+
_ops, _operands = node[1], node[2]
|
|
751
|
+
_acc = (_ops[0], _operands[0], _operands[1])
|
|
752
|
+
for _i in range(1, len(_ops)):
|
|
753
|
+
_acc = ("and", _acc,
|
|
754
|
+
(_ops[_i], _operands[_i], _operands[_i + 1]))
|
|
755
|
+
return compile_expr(_acc)
|
|
756
|
+
if kind in ("==", "!=", "<", ">", "<=", ">=", "in", "not in"):
|
|
757
|
+
code = compile_expr(node[1]) + compile_expr(node[2])
|
|
758
|
+
code.append((_CMP_VM[kind], None))
|
|
759
|
+
return code
|
|
760
|
+
if kind == "not":
|
|
761
|
+
return compile_expr(node[1]) + [("NOT", None)]
|
|
762
|
+
if kind == "or" or kind == "and":
|
|
763
|
+
# 短路:左值 → 真保留左值(or)/假保留左值(and)→ 否则求右值
|
|
764
|
+
right = compile_expr(node[2])
|
|
765
|
+
code = compile_expr(node[1])
|
|
766
|
+
jmp = "JUMP_IF_TRUE" if kind == "or" else "JUMP_IF_FALSE"
|
|
767
|
+
jmp_idx = len(code)
|
|
768
|
+
code.append((jmp, 0)) # 回填
|
|
769
|
+
code.append(("POP", None)) # 丢弃左值(不短路时)
|
|
770
|
+
code.extend(right)
|
|
771
|
+
code[jmp_idx] = (jmp, len(code)) # 短路目标 = 程序末尾(栈顶左值保留)
|
|
772
|
+
return code
|
|
773
|
+
if kind == "attr": # T4:VM 同步支持(双路对照)
|
|
774
|
+
return compile_expr(node[1]) + [("GET_ATTR", node[2])]
|
|
775
|
+
if kind == "method": # T4:obj + args → CALL_METHOD(方法名, 参数数)
|
|
776
|
+
code = compile_expr(node[1])
|
|
777
|
+
for a in node[3]:
|
|
778
|
+
code.extend(compile_expr(a))
|
|
779
|
+
code.append(("CALL_METHOD", (node[2], len(node[3]))))
|
|
780
|
+
return code
|
|
781
|
+
if kind == "call":
|
|
782
|
+
code = [("LOAD_NAME", node[1])]
|
|
783
|
+
for a in node[2]:
|
|
784
|
+
code.extend(compile_expr(a))
|
|
785
|
+
if len(node) > 3 and node[3]: # V-P4:kwargs 压 key,值 序列 + CALL_KW
|
|
786
|
+
for k, v in node[3]:
|
|
787
|
+
code.append(("PUSH_CONST", k))
|
|
788
|
+
code.extend(compile_expr(v))
|
|
789
|
+
code.append(("CALL_KW", (len(node[2]), len(node[3]))))
|
|
790
|
+
else:
|
|
791
|
+
code.append(("CALL", len(node[2])))
|
|
792
|
+
return code
|
|
793
|
+
if kind == "method":
|
|
794
|
+
if len(node) > 4 and node[4]:
|
|
795
|
+
raise MiniPyError("VM 暂不支持方法关键字参数(V-P4 第二批)")
|
|
796
|
+
raise MiniPyError(f"无法编译节点: {node}")
|
|
797
|
+
|
|
798
|
+
|
|
799
|
+
_ARITH_VM = {"+": "ADD", "-": "SUB", "*": "MUL", "/": "DIV",
|
|
800
|
+
"//": "FLOOR", "%": "MOD", "**": "POW"}
|
|
801
|
+
_CMP_VM = {"==": "CMP_EQ", "!=": "CMP_NE", "<": "CMP_LT", ">": "CMP_GT",
|
|
802
|
+
"<=": "CMP_LE", ">=": "CMP_GE",
|
|
803
|
+
"in": "CMP_IN", "not in": "CMP_NOT_IN"} # V-P4
|
|
804
|
+
|
|
805
|
+
|
|
806
|
+
class VM:
|
|
807
|
+
"""栈机执行(P5 雏形:算术/比较/逻辑短路/数据结构/调用)"""
|
|
808
|
+
def __init__(self, env):
|
|
809
|
+
"""VM 执行上下文:环境引用·操作数栈·调用帧序列。"""
|
|
810
|
+
self.env = env
|
|
811
|
+
self.stack = []
|
|
812
|
+
self.frames = [] # 调用帧(P5 简化:函数调用直接执行 body)
|
|
813
|
+
|
|
814
|
+
def run(self, code, max_steps=100000):
|
|
815
|
+
"""字节码 VM 执行主循环:取指分派,max_steps 上限防死循环。"""
|
|
816
|
+
ip = 0
|
|
817
|
+
while ip < len(code) and max_steps > 0:
|
|
818
|
+
op, arg = code[ip]
|
|
819
|
+
ip += 1
|
|
820
|
+
max_steps -= 1
|
|
821
|
+
if op == "PUSH_CONST":
|
|
822
|
+
self.stack.append(arg)
|
|
823
|
+
elif op == "LOAD_NAME":
|
|
824
|
+
try:
|
|
825
|
+
self.stack.append(self.env.get(arg))
|
|
826
|
+
except MiniPyError:
|
|
827
|
+
if arg in _BUILTINS: # V-P2:VM 路内置函数兜底(与 AST 路对齐)
|
|
828
|
+
self.stack.append(_BUILTINS[arg])
|
|
829
|
+
else:
|
|
830
|
+
raise
|
|
831
|
+
elif op == "PUSH_LIST":
|
|
832
|
+
items = self.stack[-arg:]
|
|
833
|
+
self.stack = self.stack[:-arg]
|
|
834
|
+
self.stack.append(items)
|
|
835
|
+
elif op == "PUSH_DICT":
|
|
836
|
+
pairs = self.stack[-arg * 2:]
|
|
837
|
+
self.stack = self.stack[:-arg * 2]
|
|
838
|
+
self.stack.append({pairs[i]: pairs[i + 1] for i in range(0, len(pairs), 2)})
|
|
839
|
+
elif op == "INDEX":
|
|
840
|
+
key, obj = self.stack.pop(), self.stack.pop()
|
|
841
|
+
self.stack.append(obj[key])
|
|
842
|
+
elif op == "ADD":
|
|
843
|
+
b, a = self.stack.pop(), self.stack.pop()
|
|
844
|
+
self.stack.append(a + b)
|
|
845
|
+
elif op == "SUB":
|
|
846
|
+
b, a = self.stack.pop(), self.stack.pop()
|
|
847
|
+
self.stack.append(a - b)
|
|
848
|
+
elif op == "MUL":
|
|
849
|
+
b, a = self.stack.pop(), self.stack.pop()
|
|
850
|
+
self.stack.append(a * b)
|
|
851
|
+
elif op == "DIV":
|
|
852
|
+
b, a = self.stack.pop(), self.stack.pop()
|
|
853
|
+
if b == 0:
|
|
854
|
+
raise MiniPyError("ZeroDivisionError")
|
|
855
|
+
self.stack.append(a / b)
|
|
856
|
+
elif op == "FLOOR":
|
|
857
|
+
b, a = self.stack.pop(), self.stack.pop()
|
|
858
|
+
if b == 0:
|
|
859
|
+
raise MiniPyError("ZeroDivisionError")
|
|
860
|
+
self.stack.append(int(a // b))
|
|
861
|
+
elif op == "MOD":
|
|
862
|
+
b, a = self.stack.pop(), self.stack.pop()
|
|
863
|
+
if b == 0:
|
|
864
|
+
raise MiniPyError("ZeroDivisionError")
|
|
865
|
+
self.stack.append(a % b)
|
|
866
|
+
elif op == "POW":
|
|
867
|
+
b, a = self.stack.pop(), self.stack.pop()
|
|
868
|
+
self.stack.append(a ** b)
|
|
869
|
+
elif op == "NOT":
|
|
870
|
+
self.stack.append(not is_truthy(self.stack.pop()))
|
|
871
|
+
elif op == "NEG":
|
|
872
|
+
self.stack.append(-self.stack.pop())
|
|
873
|
+
elif op.startswith("CMP_"):
|
|
874
|
+
b, a = self.stack.pop(), self.stack.pop()
|
|
875
|
+
_cmp_map = {"EQ": "==", "NE": "!=", "LT": "<", "GT": ">",
|
|
876
|
+
"LE": "<=", "GE": ">=", "IN": "in", "NOT_IN": "not in"}
|
|
877
|
+
self.stack.append(_compare(_cmp_map[op[4:]], a, b))
|
|
878
|
+
elif op == "JUMP_IF_TRUE":
|
|
879
|
+
if is_truthy(self.stack[-1]):
|
|
880
|
+
ip = arg
|
|
881
|
+
elif op == "JUMP_IF_FALSE":
|
|
882
|
+
if not is_truthy(self.stack[-1]):
|
|
883
|
+
ip = arg
|
|
884
|
+
elif op == "POP":
|
|
885
|
+
self.stack.pop()
|
|
886
|
+
elif op == "CALL":
|
|
887
|
+
args = self.stack[-arg:]
|
|
888
|
+
self.stack = self.stack[:-arg]
|
|
889
|
+
f = self.stack.pop() # 函数在参数之下(先压函数后压参数)
|
|
890
|
+
if isinstance(f, tuple) and f and f[0] == "func":
|
|
891
|
+
_, params, body, def_env = f
|
|
892
|
+
local = bind_params(params, args, None, def_env) # V-P4
|
|
893
|
+
try:
|
|
894
|
+
for s in body:
|
|
895
|
+
exec_stmt(s, local)
|
|
896
|
+
self.stack.append(None)
|
|
897
|
+
except ReturnSignal as rs:
|
|
898
|
+
self.stack.append(rs.value)
|
|
899
|
+
elif callable(f): # V-P2:内置函数(与 AST 路 _BUILTINS 分派对齐)
|
|
900
|
+
self.stack.append(f(*args))
|
|
901
|
+
else:
|
|
902
|
+
raise MiniPyError(f"不可调用: {f!r}")
|
|
903
|
+
elif op == "CALL_KW": # V-P4:带关键字参数调用(栈序 f, pos..., k1,v1,...)
|
|
904
|
+
n_pos, n_kw = arg
|
|
905
|
+
kw_items = self.stack[len(self.stack) - 2 * n_kw:]
|
|
906
|
+
self.stack = self.stack[:-2 * n_kw]
|
|
907
|
+
kwargs = {kw_items[2 * i]: kw_items[2 * i + 1] for i in range(n_kw)}
|
|
908
|
+
args = self.stack[-n_pos:] if n_pos else []
|
|
909
|
+
if n_pos:
|
|
910
|
+
self.stack = self.stack[:-n_pos]
|
|
911
|
+
f = self.stack.pop()
|
|
912
|
+
if isinstance(f, tuple) and f and f[0] == "func":
|
|
913
|
+
_, params, body, def_env = f
|
|
914
|
+
local = bind_params(params, args, kwargs, def_env) # V-P4
|
|
915
|
+
try:
|
|
916
|
+
for s in body:
|
|
917
|
+
exec_stmt(s, local)
|
|
918
|
+
self.stack.append(None)
|
|
919
|
+
except ReturnSignal as rs:
|
|
920
|
+
self.stack.append(rs.value)
|
|
921
|
+
continue
|
|
922
|
+
if callable(f):
|
|
923
|
+
self.stack.append(f(*args, **kwargs))
|
|
924
|
+
else:
|
|
925
|
+
raise MiniPyError(f"不可调用: {f!r}")
|
|
926
|
+
elif op == "GET_ATTR": # T4
|
|
927
|
+
obj = self.stack.pop()
|
|
928
|
+
if arg not in _METHOD_WHITELIST:
|
|
929
|
+
raise MiniPyError(f"方法不在白名单: .{arg}(允许: {sorted(_METHOD_WHITELIST)})")
|
|
930
|
+
if not hasattr(obj, arg):
|
|
931
|
+
raise MiniPyError(f"对象无该方法: {type(obj).__name__}.{arg}")
|
|
932
|
+
self.stack.append(getattr(obj, arg))
|
|
933
|
+
elif op == "CALL_METHOD": # T4:arg=(方法名, 参数数)
|
|
934
|
+
mname, n = arg
|
|
935
|
+
args = self.stack[len(self.stack) - n:] if n else []
|
|
936
|
+
if n:
|
|
937
|
+
self.stack = self.stack[:-n]
|
|
938
|
+
obj = self.stack.pop()
|
|
939
|
+
if mname not in _METHOD_WHITELIST:
|
|
940
|
+
raise MiniPyError(f"方法不在白名单: .{mname}(允许: {sorted(_METHOD_WHITELIST)})")
|
|
941
|
+
m = getattr(obj, mname, None)
|
|
942
|
+
if not callable(m):
|
|
943
|
+
raise MiniPyError(f"不可调用: {type(obj).__name__}.{mname}")
|
|
944
|
+
self.stack.append(m(*args))
|
|
945
|
+
else:
|
|
946
|
+
raise MiniPyError(f"未知指令: {op}")
|
|
947
|
+
return self.stack[-1] if self.stack else None
|
|
948
|
+
|
|
949
|
+
|
|
950
|
+
def eval_expr_vm(src, env=None):
|
|
951
|
+
"""字节码 VM 求值入口(P5:对照 eval_expr/eval_node)"""
|
|
952
|
+
env = env or Env()
|
|
953
|
+
ast = Parser(tokenize(src)).parse()
|
|
954
|
+
code = compile_expr(ast)
|
|
955
|
+
return VM(env).run(code)
|
|
956
|
+
|
|
957
|
+
|
|
958
|
+
if __name__ == "__main__":
|
|
959
|
+
print("=== Mini-Python P2:变量环境 + 控制流(对照 CPython)===\n")
|
|
960
|
+
prog = """
|
|
961
|
+
x = 0
|
|
962
|
+
while x < 5:
|
|
963
|
+
x = x + 1
|
|
964
|
+
if x == 5:
|
|
965
|
+
y = 10
|
|
966
|
+
else:
|
|
967
|
+
y = 0
|
|
968
|
+
"""
|
|
969
|
+
env = run_program(prog)
|
|
970
|
+
print(f"① 程序执行后: x={env.get('x')} y={env.get('y')}")
|
|
971
|
+
ok = env.get("x") == 5 and env.get("y") == 10
|
|
972
|
+
print(f"\n=== 判定 ===\n变量+控制流: {'✔ 循环/条件/赋值成立(对照 CPython)' if ok else '✘'}")
|
|
973
|
+
|
|
974
|
+
|
|
975
|
+
if __name__ == "__main__":
|
|
976
|
+
print("=== Mini-Python P1:表达式求值(对照 CPython)===\n")
|
|
977
|
+
cases = [
|
|
978
|
+
("2+3*4", 14), ("2**3**2", 512), ("-2**2", -4), ("4/2", 2.0),
|
|
979
|
+
("10//3", 3), ("-7//2", -4), ("-7%2", 1), ("3>2", True),
|
|
980
|
+
("not 1>2", True), ("0 or 5", 5), ("2 and 3", 3),
|
|
981
|
+
("True or 1/0", True), ("0 and 1/0", 0), ("2**-1", 0.5),
|
|
982
|
+
("1<2<3", True), ("0 <= 15 < 10", False), ("2 == 2 == 2", True),
|
|
983
|
+
("3 > 2 > 1", True), ("0 <= 5 <= 10", True), ("(2+3)*4", 20), ("-5+3", -2),
|
|
984
|
+
]
|
|
985
|
+
ok_n = 0
|
|
986
|
+
for src, expect in cases:
|
|
987
|
+
try:
|
|
988
|
+
got = eval_expr(src)
|
|
989
|
+
ok = got == expect and type(got) is type(expect)
|
|
990
|
+
if ok:
|
|
991
|
+
ok_n += 1
|
|
992
|
+
print(f"[{'✔' if ok else '✘'}] {src} = {got!r} (期望 {expect!r})")
|
|
993
|
+
except Exception as e:
|
|
994
|
+
print(f"[✘] {src} → 异常 {e}")
|
|
995
|
+
print(f"\n=== 判定 ===\n表达式求值: {ok_n}/{len(cases)}(对照 CPython 行为)")
|