@furongjun1999/dsh-memory 0.8.1 → 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.
Files changed (717) hide show
  1. package/README.md +662 -659
  2. package/codebuddy/README.md +1 -1
  3. package/data/policy.json +38 -27
  4. package/docs/README.md +18 -2
  5. package/docs/discipline/harnesses.yaml +1 -1
  6. package/docs/discipline/templates/spec.txt.tmpl +23 -0
  7. package/docs//350/247/204/350/214/203/AI/347/274/226/347/250/213/351/200/232/347/224/250/350/247/204/350/214/203.md +179 -0
  8. package/docs//350/247/204/350/214/203/AI/347/274/226/347/250/213/351/200/232/347/224/250/350/247/204/350/214/203_/347/201/265/346/236/242/351/200/202/351/205/215.md +45 -0
  9. package/docs//350/247/204/350/214/203/AI/347/274/226/347/250/213/351/200/232/347/224/250/350/247/204/350/214/203_/350/207/252/346/243/200/346/270/205/345/215/225.md +69 -0
  10. package/dsh/README.md +1 -1
  11. package/dsh/cordis.yml.example +139 -139
  12. package/hive/README.md +705 -0
  13. package/hive/id_charset_blocks.txt +147 -0
  14. package/lib/bridge.d.ts +3 -0
  15. package/lib/bridge.js +32 -11
  16. package/lib/cli.js +14 -17
  17. package/lib/hooks.d.ts +37 -3
  18. package/lib/hooks.js +176 -24
  19. package/lib/index.d.ts +2 -2
  20. package/lib/index.js +29 -6
  21. package/lib/init.js +21 -21
  22. package/lib/lib/datapath.d.ts +56 -0
  23. package/lib/lib/datapath.js +102 -9
  24. package/lib/lib/hook_audit.d.ts +0 -1
  25. package/lib/lib/hook_audit.js +51 -3
  26. package/lib/lib/mdcg_client.d.ts +4 -1
  27. package/lib/lib/mdcg_client.js +10 -2
  28. package/lib/lib/mutual.js +61 -15
  29. package/lib/lib/prompt_safety.js +28 -2
  30. package/lib/lib/roleplay_web.js +30 -2
  31. package/lib/lib/token_store.d.ts +25 -6
  32. package/lib/lib/token_store.js +224 -33
  33. package/lib/tools.d.ts +15 -2
  34. package/lib/tools.js +44 -4
  35. package/md_cg/_guard_kit.py +121 -0
  36. package/md_cg/admission.py +718 -718
  37. package/md_cg/anchor.py +114 -0
  38. package/md_cg/audit.py +37 -7
  39. package/md_cg/autonomy.py +433 -288
  40. package/md_cg/autonomy_modes.py +781 -642
  41. package/md_cg/bench_beir_bm25.py +154 -0
  42. package/md_cg/bench_beir_scifact.py +170 -0
  43. package/md_cg/bench_bm25_blockmax.py +134 -0
  44. package/md_cg/bench_bm25_incremental.py +246 -0
  45. package/md_cg/bench_ccg_heading.py +118 -0
  46. package/md_cg/bench_csre_correctness.py +145 -0
  47. package/md_cg/bench_excerpt_budget.py +94 -0
  48. package/md_cg/bench_fuzzy_substrings.py +299 -0
  49. package/md_cg/bench_memory_rsi.py +358 -0
  50. package/md_cg/bench_memory_rsi_latency.py +82 -0
  51. package/md_cg/bench_memory_rsi_public.py +116 -0
  52. package/md_cg/bench_memory_rsi_tools.py +229 -0
  53. package/md_cg/bench_rrf_candidates.py +212 -0
  54. package/md_cg/bench_rrf_public.py +100 -0
  55. package/md_cg/bench_text_projections.py +221 -0
  56. package/md_cg/bench_timeanchor.py +357 -0
  57. package/md_cg/bm25.py +601 -0
  58. package/md_cg/branches.py +404 -327
  59. package/md_cg/build_postings.py +74 -73
  60. package/md_cg/ccgc.py +4 -2
  61. package/md_cg/chain.py +573 -379
  62. package/md_cg/coldverify.py +531 -292
  63. package/md_cg/condaccept.py +263 -0
  64. package/md_cg/condgate.py +308 -0
  65. package/md_cg/config_registry.py +329 -0
  66. package/md_cg/config_registry_bulk.py +482 -0
  67. package/md_cg/config_registry_guard.py +487 -0
  68. package/md_cg/config_render.py +354 -0
  69. package/md_cg/config_validate.py +455 -0
  70. package/md_cg/conformance.py +747 -726
  71. package/md_cg/conformance_core.py +753 -0
  72. package/md_cg/consistency.py +1278 -955
  73. package/md_cg/consolidate.py +1793 -1633
  74. package/md_cg/crypto.py +346 -24
  75. package/md_cg/datapath.py +137 -12
  76. package/md_cg/eval_common.py +522 -575
  77. package/md_cg/evidence.py +946 -585
  78. package/md_cg/evidence_delivery.py +101 -0
  79. package/md_cg/experience_consolidation.py +317 -0
  80. package/md_cg/export.py +329 -222
  81. package/md_cg/forgetting.py +1050 -922
  82. package/md_cg/freshness.py +601 -548
  83. package/md_cg/fsutil.py +1120 -824
  84. package/md_cg/goal_gen.py +458 -0
  85. package/md_cg/hotcache.py +107 -9
  86. package/md_cg/hyperedge.py +262 -251
  87. package/md_cg/identity.py +573 -391
  88. package/md_cg/imgskill.py +1712 -0
  89. package/md_cg/insight.py +540 -521
  90. package/md_cg/interface_schema.py +146 -0
  91. package/md_cg/interop.py +20 -0
  92. package/md_cg/judgment_manifest.py +24 -1
  93. package/md_cg/lifecycle.py +426 -345
  94. package/md_cg/links.py +27 -6
  95. package/md_cg/logref.py +332 -327
  96. package/md_cg/mcp_server.py +5227 -4449
  97. package/md_cg/mdcg.py +1301 -203
  98. package/md_cg/mdcos.py +7108 -5440
  99. package/md_cg/memory_rsi.py +308 -0
  100. package/md_cg/metacognition.py +726 -591
  101. package/md_cg/nodefile.py +151 -3
  102. package/md_cg/op_table.py +1128 -0
  103. package/md_cg/postings.py +524 -300
  104. package/md_cg/predict.py +1103 -1100
  105. package/md_cg/probe_memory_rsi.py +95 -0
  106. package/md_cg/probe_memory_rsi_mcp.py +66 -0
  107. package/md_cg/protect.py +654 -494
  108. package/md_cg/protocol.py +492 -411
  109. package/md_cg/provenance.py +606 -600
  110. package/md_cg/qmd.py +477 -0
  111. package/md_cg/qmd_llm.py +334 -0
  112. package/md_cg/query_excerpt.py +171 -0
  113. package/md_cg/queue_health.py +130 -0
  114. package/md_cg/reach.py +470 -453
  115. package/md_cg/readcache.py +115 -3
  116. package/md_cg/reconcile.py +239 -228
  117. package/md_cg/refindex.py +1191 -1042
  118. package/md_cg/refine.py +613 -604
  119. package/md_cg/retrieve.py +128 -0
  120. package/md_cg/review_cli.py +204 -26
  121. package/md_cg/revise.py +140 -0
  122. package/md_cg/rollback.py +657 -420
  123. package/md_cg/rollback_cli.py +124 -104
  124. package/md_cg/rotate.py +347 -0
  125. package/md_cg/routing.py +490 -429
  126. package/md_cg/rrf_candidates.py +204 -0
  127. package/md_cg/run_tests.py +19 -1
  128. package/md_cg/scrub.py +177 -23
  129. package/md_cg/security.py +269 -17
  130. package/md_cg/self_state.py +1053 -1029
  131. package/md_cg/self_surface.py +50 -0
  132. package/md_cg/semantic/canonical.py +144 -144
  133. package/md_cg/semantic/export_en_zh_map.py +2 -2
  134. package/md_cg/semantic/zh_en_atoms.py +141 -139
  135. package/md_cg/session5.py +106 -0
  136. package/md_cg/signer.py +76 -2
  137. package/md_cg/sleep.py +1779 -1583
  138. package/md_cg/sources.py +1091 -833
  139. package/md_cg/state_events.py +75 -10
  140. package/md_cg/state_slots.py +312 -221
  141. package/md_cg/stg.py +85 -18
  142. package/md_cg/stgidx.py +537 -281
  143. package/md_cg/subgraph.py +851 -729
  144. package/md_cg/sustain.py +458 -19
  145. package/md_cg/task_memory.py +367 -0
  146. package/md_cg/test_action_derive.py +210 -203
  147. package/md_cg/test_audit_heartbeat_20261015.py +417 -0
  148. package/md_cg/test_audit_protection_20261015.py +483 -0
  149. package/md_cg/test_audit_rotate_parity.py +280 -0
  150. package/md_cg/test_audit_state_20261015.py +253 -0
  151. package/md_cg/test_audit_write_20261015.py +161 -0
  152. package/md_cg/test_auto_defaults.py +43 -4
  153. package/md_cg/test_autonomy_emotion.py +328 -0
  154. package/md_cg/test_autonomy_modes.py +2013 -1973
  155. package/md_cg/test_b1_foreign_read.py +245 -0
  156. package/md_cg/test_bm25.py +438 -0
  157. package/md_cg/test_bm25_hydration_refill.py +265 -0
  158. package/md_cg/test_bm25_incremental.py +241 -0
  159. package/md_cg/test_bm25_incremental_mutations.py +160 -0
  160. package/md_cg/test_bm25_mutations.py +205 -0
  161. package/md_cg/test_bm25_pool_view.py +196 -0
  162. package/md_cg/test_boot_openblas_guard.py +218 -197
  163. package/md_cg/test_boundary_hit.py +1 -1
  164. package/md_cg/test_branches_sensitivity.py +375 -0
  165. package/md_cg/test_c8_search_rrf_gates.py +1 -1
  166. package/md_cg/test_canonical_timezones.py +211 -0
  167. package/md_cg/test_ccg_heading_parser.py +73 -0
  168. package/md_cg/test_chain_best_first.py +403 -0
  169. package/md_cg/test_chain_candidate_scope.py +227 -0
  170. package/md_cg/test_cn_recall_grams.py +206 -0
  171. package/md_cg/test_code_kind_forbidden.py +101 -0
  172. package/md_cg/test_coldverify_drain.py +127 -0
  173. package/md_cg/test_condaccept.py +156 -0
  174. package/md_cg/test_condgate.py +141 -0
  175. package/md_cg/test_config_registry.py +55 -0
  176. package/md_cg/test_crypto_rotate.py +257 -0
  177. package/md_cg/test_csre_correctness.py +297 -0
  178. package/md_cg/test_csre_index_import_guard.py +161 -0
  179. package/md_cg/test_csre_mutations.py +34 -0
  180. package/md_cg/test_csre_session.py +69 -0
  181. package/md_cg/test_curiosity_budget.py +468 -0
  182. package/md_cg/test_d17_autostart_toolface.py +453 -0
  183. package/md_cg/test_datapath_tilde_home.py +271 -0
  184. package/md_cg/test_derived_cache_generations.py +256 -0
  185. package/md_cg/test_evidence_delivery_compact.py +54 -0
  186. package/md_cg/test_exact_text_cache.py +191 -0
  187. package/md_cg/test_excerpt_budget.py +188 -0
  188. package/md_cg/test_experience_consolidation.py +112 -0
  189. package/md_cg/test_export_default_collision.py +138 -0
  190. package/md_cg/test_export_snapshots.py +322 -0
  191. package/md_cg/test_fuzzy_substring_equivalence.py +127 -0
  192. package/md_cg/test_gain_gate.py +16 -5
  193. package/md_cg/test_goal_gen.py +355 -0
  194. package/md_cg/test_h2_session_view_norm.py +251 -233
  195. package/md_cg/test_h4_sustain_snapshot.py +1490 -1387
  196. package/md_cg/test_heartbeat_ledger.py +557 -0
  197. package/md_cg/test_hierarchy_audit_graph.py +237 -0
  198. package/md_cg/test_i50c_meta_passthrough.py +628 -608
  199. package/md_cg/test_i50e_readside_protection.py +658 -656
  200. package/md_cg/test_identity_attribution.py +96 -2
  201. package/md_cg/test_identity_contract.py +329 -0
  202. package/md_cg/test_imgskill.py +1444 -0
  203. package/md_cg/test_index_snapshot_shape.py +240 -0
  204. package/md_cg/test_interop_judgment.py +258 -228
  205. package/md_cg/test_issue111_gate_order.py +77 -0
  206. package/md_cg/test_issue111_scoring_contract.py +87 -0
  207. package/md_cg/test_issue121_calibration_bounds.py +293 -0
  208. package/md_cg/test_issue128_session_env_authority.py +246 -0
  209. package/md_cg/test_issue130_rrf_rank_credibility.py +217 -0
  210. package/md_cg/test_issue131_postings_content_staleness.py +424 -0
  211. package/md_cg/test_issue145_sleep_no_silent_rollback.py +168 -0
  212. package/md_cg/test_issue146_frontmatter_quarantine.py +428 -0
  213. package/md_cg/test_issue147_pack_id_escape.py +378 -0
  214. package/md_cg/test_issue148_merge_downgrade_leak.py +192 -0
  215. package/md_cg/test_issue149_accel_default_face.py +249 -0
  216. package/md_cg/test_issue150_empty_query_terms.py +328 -0
  217. package/md_cg/test_issue151_153_157_write_cache_index.py +152 -0
  218. package/md_cg/test_issue151b_base_add_importance_guard.py +166 -0
  219. package/md_cg/test_issue152_sealed_postings.py +309 -0
  220. package/md_cg/test_issue152b_decrypt_cache.py +218 -0
  221. package/md_cg/test_issue153b_cache_alias_and_canon.py +236 -0
  222. package/md_cg/test_issue153b_index_generation_invalidation.py +143 -0
  223. package/md_cg/test_issue157b_index_remainder.py +344 -0
  224. package/md_cg/test_issue189_conclusion_bidirectional.py +223 -0
  225. package/md_cg/test_issue190_tidy_idempotent.py +806 -0
  226. package/md_cg/test_issue191_import_trust.py +382 -0
  227. package/md_cg/test_issue192_move_layer_indices_guard.py +258 -0
  228. package/md_cg/test_issue193_consistency_knowledge_guard.py +524 -0
  229. package/md_cg/test_issue193_write_scope.py +378 -0
  230. package/md_cg/test_issue197_rank_credibility_property.py +201 -0
  231. package/md_cg/test_issue211_export_target.py +325 -0
  232. package/md_cg/test_issue212_writeface_gaps.py +349 -0
  233. package/md_cg/test_issue214_reject_sensitivity.py +267 -0
  234. package/md_cg/test_issue215_condition_source_gap.py +272 -0
  235. package/md_cg/test_issue216_clash_routes.py +214 -0
  236. package/md_cg/test_issue217_slot_routes.py +248 -0
  237. package/md_cg/test_issue218_postcondition_value_blind.py +222 -0
  238. package/md_cg/test_issue225_consistency_torn_log.py +433 -0
  239. package/md_cg/test_issue245_swarm_traversal.py +366 -0
  240. package/md_cg/test_issue258_pack_sensitivity.py +468 -0
  241. package/md_cg/test_issue265_coldverify_multiproc.py +438 -0
  242. package/md_cg/test_issue274_read_node_id_none.py +341 -0
  243. package/md_cg/test_issue275_layer_param.py +250 -0
  244. package/md_cg/test_issue277_node_id_traversal.py +384 -0
  245. package/md_cg/test_issue278_neg_separated_tension.py +271 -0
  246. package/md_cg/test_issue278_neg_window.py +294 -0
  247. package/md_cg/test_issue278_negative_layering.py +83 -0
  248. package/md_cg/test_issue279_signers_path_guard.py +652 -0
  249. package/md_cg/test_issue284_skip_not_pass.py +291 -0
  250. package/md_cg/test_issue294_flywheel_sensitivity.py +573 -0
  251. package/md_cg/test_issue295_sleep_root_binding.py +589 -0
  252. package/md_cg/test_issue297_rewrite_sensitivity.py +454 -0
  253. package/md_cg/test_issue298_consistency_ledger_sensitivity.py +421 -0
  254. package/md_cg/test_issue301_baseline_corpus_gate.py +245 -0
  255. package/md_cg/test_issue303_design_boundaries.py +262 -0
  256. package/md_cg/test_issue313_writelimit_sensitivity.py +404 -0
  257. package/md_cg/test_issue315_merge_branch_sensitivity.py +384 -0
  258. package/md_cg/test_issue315_sensitivity_passthrough_guard.py +514 -0
  259. package/md_cg/test_issue319_tenant_unregistered_bypass.py +257 -0
  260. package/md_cg/test_issue320_vstate_requires_verify.py +279 -0
  261. package/md_cg/test_issue321_mcp_deep_json.py +305 -0
  262. package/md_cg/test_issue322_node_write_lock.py +727 -0
  263. package/md_cg/test_issue323_aggregate_segment_boundary.py +365 -0
  264. package/md_cg/test_issue324_write_size_fields.py +215 -0
  265. package/md_cg/test_issue325_audit_poison.py +230 -0
  266. package/md_cg/test_issue326_append_jsonl_oserror.py +464 -0
  267. package/md_cg/test_issue326_ingest_auto_whitelist.py +331 -0
  268. package/md_cg/test_issue326_key_perms.py +355 -0
  269. package/md_cg/test_issue326_twin_parser_parity.py +323 -0
  270. package/md_cg/test_issue326_vm_call_frame.py +569 -0
  271. package/md_cg/test_issue345_writelimit_effective_sens.py +234 -0
  272. package/md_cg/test_issue346_overwrite_sensitivity_gate.py +424 -0
  273. package/md_cg/test_issue346_review_overwrite_guard.py +509 -0
  274. package/md_cg/test_issue348_insight_verify_op.py +200 -0
  275. package/md_cg/test_issue348_merge_rmw_lock.py +345 -0
  276. package/md_cg/test_issue350_casefold_collision.py +236 -0
  277. package/md_cg/test_issue351_ingest_root_fallback.py +202 -0
  278. package/md_cg/test_issue352_imgaudit.py +418 -0
  279. package/md_cg/test_issue352_pathsjson.py +537 -0
  280. package/md_cg/test_issue352_refindex.py +412 -0
  281. package/md_cg/test_issue352_rollback.py +604 -0
  282. package/md_cg/test_issue352_vstateinherit.py +196 -0
  283. package/md_cg/test_issue354_p1_writelimit_type.py +522 -0
  284. package/md_cg/test_issue354_p2_datapath_clock.py +381 -0
  285. package/md_cg/test_issue354_p2_writelimit_toctou.py +327 -0
  286. package/md_cg/test_issue354_rust_index_containment.py +571 -0
  287. package/md_cg/test_issue354_rust_wal_containment.py +606 -0
  288. package/md_cg/test_issue358_truncation_observable.py +247 -0
  289. package/md_cg/test_issue360_tidy_private_excerpt.py +196 -0
  290. package/md_cg/test_issue361_blindspot_not_silent_drop.py +494 -0
  291. package/md_cg/test_issue362_neg_condition.py +468 -0
  292. package/md_cg/test_issue363_lexical_idf.py +275 -0
  293. package/md_cg/test_issue370_readcache_assembly.py +488 -0
  294. package/md_cg/test_issue375_state_slot_retire.py +325 -0
  295. package/md_cg/test_issue376_heartbeat_failed.py +293 -0
  296. package/md_cg/test_issue377_layer_protect_stamp.py +324 -0
  297. package/md_cg/test_issue378_protected_floor.py +310 -0
  298. package/md_cg/test_issue383_state_event_write_gate.py +462 -0
  299. package/md_cg/test_issue397_sens_eff_wiring.py +435 -0
  300. package/md_cg/test_issue398_toolface_op_parity.py +511 -0
  301. package/md_cg/test_issue399_hive_json_shape.py +317 -0
  302. package/md_cg/test_issue400_hive_dirty_args.py +450 -0
  303. package/md_cg/test_issue401_wisdom_codegen.py +295 -0
  304. package/md_cg/test_issue404_heal_receipt.py +390 -0
  305. package/md_cg/test_issue405_git_pathspec.py +333 -0
  306. package/md_cg/test_issue408_eface_registry.py +291 -0
  307. package/md_cg/test_issue409_compact_index_completeness.py +509 -0
  308. package/md_cg/test_issue410_verify_demote_write.py +366 -0
  309. package/md_cg/test_issue411_scrub_idempotence.py +575 -0
  310. package/md_cg/test_issue412_discipline_producer_parity.py +312 -0
  311. package/md_cg/test_issue413_preimage_failclosed.py +239 -0
  312. package/md_cg/test_issue413_preimage_twin.py +340 -0
  313. package/md_cg/test_issue414_write_args_parity.py +613 -0
  314. package/md_cg/test_issue415_deps_gate_probe.py +358 -0
  315. package/md_cg/test_issue416_entry_key_subset.py +525 -0
  316. package/md_cg/test_issue417_twophase_merge_landed.py +423 -0
  317. package/md_cg/test_issue418_identity_role_type_gate.py +188 -0
  318. package/md_cg/test_issue418_role_type_gate.py +265 -0
  319. package/md_cg/test_issue419_pii_redaction.py +642 -0
  320. package/md_cg/test_issue424_merge_confirm_sensitivity.py +381 -0
  321. package/md_cg/test_issue425_ingest_library_path.py +331 -0
  322. package/md_cg/test_issue426a_dedup_receipt.py +242 -0
  323. package/md_cg/test_issue426b_root_clash_invisible.py +270 -0
  324. package/md_cg/test_issue426c_enqueue_not_silent.py +346 -0
  325. package/md_cg/test_issue426e_restore_overwrite_live.py +310 -0
  326. package/md_cg/test_issue426f_paths_gbk_failclosed.py +301 -0
  327. package/md_cg/test_issue427_serve_status_shape.py +191 -0
  328. package/md_cg/test_issue431_432_468_protect_single_point.py +322 -0
  329. package/md_cg/test_issue433_outlook_threshold_single_point.py +278 -0
  330. package/md_cg/test_issue434_435_float_gate.py +90 -0
  331. package/md_cg/test_issue439_sibling_sensitivity_inherit.py +448 -0
  332. package/md_cg/test_issue43_default_policy.py +874 -865
  333. package/md_cg/test_issue443a_state_event_length_gate.py +94 -0
  334. package/md_cg/test_issue443b_audit_record_length_gate.py +83 -0
  335. package/md_cg/test_issue443c_self_state_imgskill_length_gate.py +77 -0
  336. package/md_cg/test_issue444_scrub_evidence_plaintext.py +281 -0
  337. package/md_cg/test_issue445_metacognition_ledger_gate.py +454 -0
  338. package/md_cg/test_issue446_453_403_verified_evidence.py +382 -0
  339. package/md_cg/test_issue446_is_encrypted_envelope.py +166 -0
  340. package/md_cg/test_issue447_recent_sens_failclosed.py +270 -0
  341. package/md_cg/test_issue450_sensitivity_fallback_reason.py +51 -0
  342. package/md_cg/test_issue450_writegate_unknown_sens.py +203 -0
  343. package/md_cg/test_issue451_audit_actor.py +313 -0
  344. package/md_cg/test_issue452_ingest_root_hint.py +238 -0
  345. package/md_cg/test_issue452_ingest_root_sensitivity.py +299 -0
  346. package/md_cg/test_issue463_ghost_prune_guard.py +259 -0
  347. package/md_cg/test_issue466_basis_registry.py +469 -0
  348. package/md_cg/test_issue467_identity_sensitivity.py +204 -0
  349. package/md_cg/test_issue467_identity_sensitivity_parity.py +361 -0
  350. package/md_cg/test_issue469_scrub_override_passthrough.py +126 -0
  351. package/md_cg/test_issue470_wal_event_durable.py +427 -0
  352. package/md_cg/test_issue471_identity_readable.py +137 -0
  353. package/md_cg/test_issue472_audit_chain.py +91 -0
  354. package/md_cg/test_issue472_prune_ledger.py +106 -0
  355. package/md_cg/test_issue472_rollback_degraded.py +82 -0
  356. package/md_cg/test_issue491_compose_sandbox.py +460 -0
  357. package/md_cg/test_issue492_dup_readout_opt_in.py +292 -0
  358. package/md_cg/test_issue498_merge_trace_stale_index.py +280 -0
  359. package/md_cg/test_issue511_scoreboard_bad_files.py +256 -0
  360. package/md_cg/test_issue521_rotate_lock_suffix.py +110 -0
  361. package/md_cg/test_issue522_review_record_sensitivity.py +267 -0
  362. package/md_cg/test_issue524_orphan_noise_no_demote.py +88 -0
  363. package/md_cg/test_issue525_read_null_semantics.py +52 -0
  364. package/md_cg/test_issue538_hook_condition_space.py +97 -0
  365. package/md_cg/test_issue540_path_guard_whitespace.py +126 -0
  366. package/md_cg/test_issue541_tidy_protect_gate.py +141 -0
  367. package/md_cg/test_issue542_tenant_root_same.py +153 -0
  368. package/md_cg/test_issue543_issue_authorization.py +147 -0
  369. package/md_cg/test_issue544_sandbox_reflection_gate.py +175 -0
  370. package/md_cg/test_issue545_charset_vs_size_diagnostic.py +77 -0
  371. package/md_cg/test_issue546_ledger_concurrency.py +81 -0
  372. package/md_cg/test_issue547_append_jsonl_whitelist.py +115 -0
  373. package/md_cg/test_issue547_audit_durable.py +96 -0
  374. package/md_cg/test_issue549_durable_append.py +143 -0
  375. package/md_cg/test_issue557_r1_credential_value_forms.py +76 -0
  376. package/md_cg/test_issue557_r2_write_entries_size_gate.py +84 -0
  377. package/md_cg/test_issue557_r3_pem_block_redaction.py +75 -0
  378. package/md_cg/test_issue559_refine_prefix.py +70 -0
  379. package/md_cg/test_issue561_pending_review.py +109 -0
  380. package/md_cg/test_issue562_retired_faces.py +150 -0
  381. package/md_cg/test_issue66_scrub_semantics.py +107 -0
  382. package/md_cg/test_issue67_scrub_control_pool.py +233 -0
  383. package/md_cg/test_issue69_audit_boundary.py +129 -0
  384. package/md_cg/test_issue71_queue_backlog.py +377 -0
  385. package/md_cg/test_issue72_coldverify_controlled_drain.py +420 -0
  386. package/md_cg/test_issue73_doc_chapter_refs.py +326 -0
  387. package/md_cg/test_issue75_neural_failure.py +582 -0
  388. package/md_cg/test_issue78_export_concurrency.py +334 -0
  389. package/md_cg/test_issue80_residual_flush.py +169 -0
  390. package/md_cg/test_issue82_credential_rules.py +271 -0
  391. package/md_cg/test_issue82_layer_and_size.py +120 -0
  392. package/md_cg/test_issue84_portability.py +95 -0
  393. package/md_cg/test_issue85_export_overwrite.py +113 -0
  394. package/md_cg/test_issue86_runtime_revoke.py +110 -0
  395. package/md_cg/test_issue87_default_sensitivity_single.py +201 -0
  396. package/md_cg/test_issue88_conclusion_face.py +280 -0
  397. package/md_cg/test_issue88_execution_conflicts.py +87 -0
  398. package/md_cg/test_issue89_zero_score.py +169 -0
  399. package/md_cg/test_issue89a_score_cap_tiebreak.py +279 -0
  400. package/md_cg/test_issue91_verifier_sandbox.py +314 -0
  401. package/md_cg/test_issue91_verifier_timeout.py +528 -0
  402. package/md_cg/test_issue93_remember_redaction.py +282 -0
  403. package/md_cg/test_issue96_key_fallback.py +102 -0
  404. package/md_cg/test_issue98_tenant_root.py +104 -0
  405. package/md_cg/test_jsonl_commit_watermark.py +221 -0
  406. package/md_cg/test_live_validity_cache.py +256 -0
  407. package/md_cg/test_logref.py +1141 -1109
  408. package/md_cg/test_mcp_call_argument_types.py +99 -0
  409. package/md_cg/test_md_access_parity.py +330 -255
  410. package/md_cg/test_md_cg_no_hive_dep.py +140 -0
  411. package/md_cg/test_memory_rsi.py +215 -0
  412. package/md_cg/test_memory_rsi_adversarial.py +91 -0
  413. package/md_cg/test_mode_parity.py +1413 -1393
  414. package/md_cg/test_mutation_residue.py +120 -0
  415. package/md_cg/test_mutation_rollback.py +835 -805
  416. package/md_cg/test_n123_derive_expiry_chain.py +210 -205
  417. package/md_cg/test_n130_verify_falsified_protect.py +185 -185
  418. package/md_cg/test_n209_verify_write_face_gates.py +466 -461
  419. package/md_cg/test_n230_dirty_replay.py +52 -9
  420. package/md_cg/test_n62_tenant_bind_failclosed.py +200 -200
  421. package/md_cg/test_neg_coverage_budget.py +500 -0
  422. package/md_cg/test_neg_tail_honesty.py +733 -663
  423. package/md_cg/test_p0.py +16 -2
  424. package/md_cg/test_p14_root_fallback.py +373 -0
  425. package/md_cg/test_p1x_ref_root.py +47 -10
  426. package/md_cg/test_p21_tokens.py +294 -293
  427. package/md_cg/test_p24_evidence.py +232 -227
  428. package/md_cg/test_p26_refindex.py +20 -3
  429. package/md_cg/test_p27_docindex.py +792 -777
  430. package/md_cg/test_p28_refcheck.py +1053 -1032
  431. package/md_cg/test_p29_session_ingest_export.py +6 -0
  432. package/md_cg/test_p2_mcp.py +474 -453
  433. package/md_cg/test_p2_six_elements.py +476 -463
  434. package/md_cg/test_p3.py +370 -261
  435. package/md_cg/test_p33_ccg_wiring.py +300 -293
  436. package/md_cg/test_p3_legacy_closure.py +438 -433
  437. package/md_cg/test_p40_refine_worklist.py +244 -241
  438. package/md_cg/test_p47_session_view.py +25 -9
  439. package/md_cg/test_p4_freshness.py +781 -774
  440. package/md_cg/test_p83_jsonrpc_parse_error.py +124 -0
  441. package/md_cg/test_p9c_dedup_hints.py +288 -283
  442. package/md_cg/test_policy_required_ccg.py +444 -432
  443. package/md_cg/test_postings_digest_memo.py +139 -0
  444. package/md_cg/test_predict_beta.py +138 -135
  445. package/md_cg/test_qmd.py +500 -0
  446. package/md_cg/test_query_excerpt.py +209 -0
  447. package/md_cg/test_reach.py +456 -378
  448. package/md_cg/test_reach_snapshot_admission.py +218 -0
  449. package/md_cg/test_readcache_prodpath.py +4 -0
  450. package/md_cg/test_recall_face_guards.py +854 -812
  451. package/md_cg/test_recall_metadata.py +422 -0
  452. package/md_cg/test_retr_s5.py +312 -213
  453. package/md_cg/test_retr_score_once.py +14 -2
  454. package/md_cg/test_review_cli_attribution.py +11 -7
  455. package/md_cg/test_review_queue_batch.py +123 -0
  456. package/md_cg/test_review_queue_index.py +130 -0
  457. package/md_cg/test_rrf_candidates.py +292 -0
  458. package/md_cg/test_rrf_qualified_topk.py +214 -0
  459. package/md_cg/test_rrf_unique_votes.py +218 -0
  460. package/md_cg/test_s1_ast_judge.py +110 -0
  461. package/md_cg/test_scrub_ledger.py +413 -0
  462. package/md_cg/test_security_audit_b26.py +34 -3
  463. package/md_cg/test_security_audit_v21.py +1 -2
  464. package/md_cg/test_sensitivity_predicate_single_point.py +184 -0
  465. package/md_cg/test_session5_identity.py +93 -0
  466. package/md_cg/test_session_attribution_consistency.py +813 -0
  467. package/md_cg/test_session_identity_tristate.py +486 -0
  468. package/md_cg/test_sleep_p1.py +35 -3
  469. package/md_cg/test_state_event_op.py +521 -514
  470. package/md_cg/test_state_projection_streaming.py +136 -0
  471. package/md_cg/test_stg_interval_candidates.py +280 -0
  472. package/md_cg/test_stg_time_blocks.py +239 -0
  473. package/md_cg/test_stgidx_index_parity.py +1024 -1020
  474. package/md_cg/test_subgraph_bounded_bfs.py +227 -0
  475. package/md_cg/test_sustain_bounded.py +652 -624
  476. package/md_cg/test_task_memory.py +394 -0
  477. package/md_cg/test_text_projection_mutations.py +101 -0
  478. package/md_cg/test_time_anchor.py +421 -0
  479. package/md_cg/test_time_core_lint.py +1024 -975
  480. package/md_cg/test_tool_face.py +200 -189
  481. package/md_cg/test_trust_bounded_frontier.py +248 -0
  482. package/md_cg/test_trust_edge_reachability.py +405 -0
  483. package/md_cg/test_w5_path_fingerprint.py +381 -0
  484. package/md_cg/test_w7_redlines.py +659 -0
  485. package/md_cg/test_write_return_shape.py +919 -0
  486. package/md_cg/test_writepipe.py +228 -226
  487. package/md_cg/timeanchor.py +534 -0
  488. package/md_cg/tokens.py +68 -5
  489. package/md_cg/tool_face.py +273 -260
  490. package/md_cg/trust.py +1114 -1030
  491. package/md_cg/twophase.py +303 -231
  492. package/md_cg/weights.py +642 -638
  493. package/md_cg/whitebox.py +536 -527
  494. package/md_cg/whitebox_kb/aeis_core/core.py +5026 -5026
  495. package/md_cg/whitebox_kb/wisdom/chat_engine.py +1504 -1506
  496. package/md_cg/whitebox_kb/wisdom/code_compose.py +876 -837
  497. package/md_cg/whitebox_kb/wisdom/compiler_code_units.py +3040 -3033
  498. package/md_cg/whitebox_kb/wisdom/compose_engine.py +1634 -1633
  499. package/md_cg/whitebox_kb/wisdom/core/condition_vm.py +318 -298
  500. package/md_cg/whitebox_kb/wisdom/core/parser.py +1082 -1065
  501. package/md_cg/whitebox_kb/wisdom/csre.py +412 -264
  502. package/md_cg/whitebox_kb/wisdom/csre_session.py +97 -0
  503. package/md_cg/whitebox_kb/wisdom/md_access.py +490 -470
  504. package/md_cg/whitebox_kb/wisdom/migrate_wisdom.py +497 -476
  505. package/md_cg/whitebox_kb/wisdom/mini_python.py +995 -958
  506. package/md_cg/whitebox_kb/wisdom/navigate.py +249 -248
  507. package/md_cg/whitebox_kb/wisdom/net_units.py +2900 -2895
  508. package/md_cg/whitebox_kb/wisdom/neural_retrieve.py +100 -10
  509. package/md_cg/whitebox_kb/wisdom/semantic_translate.py +4060 -4054
  510. package/md_cg/whitebox_kb/wisdom/test_ecosystem_assembly.py +158 -158
  511. package/md_cg/whitebox_kb/wisdom/test_safe_module_proxy.py +147 -0
  512. package/md_cg/whitebox_kb/wisdom/verifier.py +1918 -1297
  513. package/md_cg/writelimit.py +584 -390
  514. package/md_cg/writepipe.py +1337 -826
  515. package/package.json +14 -9
  516. package/scripts/workspace_index.py +328 -0
  517. package/src/bridge.ts +34 -11
  518. package/src/cli.ts +75 -65
  519. package/src/hooks.ts +932 -776
  520. package/src/index.ts +30 -7
  521. package/src/init.ts +362 -361
  522. package/src/lib/datapath.ts +419 -326
  523. package/src/lib/hook_audit.ts +42 -3
  524. package/src/lib/mdcg_client.ts +469 -461
  525. package/src/lib/mutual.ts +481 -432
  526. package/src/lib/prompt_safety.ts +178 -149
  527. package/src/lib/roleplay_web.ts +30 -2
  528. package/src/lib/token_store.ts +274 -52
  529. package/src/tools.ts +271 -223
  530. package/zcode/README.md +1 -1
  531. package/docs/GBrain/345/217/257/345/200/237/351/211/264/347/202/271_/347/201/265/346/236/242/350/220/275/347/202/271/344/272/244/346/216/245_20260919.md +0 -169
  532. package/docs/Pi/345/217/257/345/255/246/344/271/240/344/274/230/347/202/271_/347/201/265/346/236/242/345/244/247/350/204/221/346/224/271/350/277/233/344/272/244/346/216/245_20260915.md +0 -144
  533. package/docs/eval/AGI/344/270/203/347/273/264/350/257/204/345/210/206/346/212/245/345/221/212_md_cg_v1.0.md +0 -299
  534. package/docs/eval/AGI/344/270/203/347/273/264/350/257/204/345/210/206/346/212/245/345/221/212_md_cg_v2.0.md +0 -239
  535. package/docs/eval/AGI/344/270/203/347/273/264/350/257/204/345/210/206/346/212/245/345/221/212_/345/205/255/345/256/266/350/256/260/345/277/206/347/263/273/347/273/237/345/220/214/345/260/272/345/256/236/346/265/213_v3.1.md +0 -340
  536. package/docs/eval/DSH/346/227/245/345/277/227/347/264/242/345/274/225v2_/345/217/202/350/200/203dsh-TUI_v1.0.md +0 -248
  537. package/docs/eval/DSH/346/227/245/345/277/227/347/264/242/345/274/225/346/225/210/346/236/234/351/252/214/350/257/201_v1.0.md +0 -209
  538. package/docs/eval/DSH/347/253/257/347/274/272/351/231/267/344/270/223/351/241/271_v1.0.md +0 -254
  539. package/docs/eval/N225_/347/264/242/345/274/225/346/227/245/345/277/227/351/235/236/345/257/271/350/261/241/350/243/205/350/275/275/351/235/242/347/261/273/345/236/213/351/227/270_v1.0.md +0 -418
  540. package/docs/eval/P1b2_/350/257/273/351/235/242/344/273/243/351/231/205/344/277/256/345/244/215_v1.0.md +0 -124
  541. package/docs/eval/bench_lingshu_self/bench_self.py +0 -140
  542. package/docs/eval/bench_lingshu_self/self_bench_result.json +0 -404
  543. package/docs/eval/bench_lingshu_self//347/201/265/346/236/242/350/207/252/345/272/223/347/253/257/345/210/260/347/253/257/346/243/200/347/264/242/345/256/236/346/265/213_v1.0.md +0 -38
  544. package/docs/eval/cons200_/345/206/262/347/252/201/346/243/200/346/265/213/351/200/211/351/235/242_/345/256/236/346/226/275/350/256/260/345/275/225_v1.0.md +0 -223
  545. package/docs/eval/cons200_/345/206/262/347/252/201/346/243/200/346/265/213/351/200/211/351/235/242_/345/256/236/346/226/275/350/256/260/345/275/225_v1.1.md +0 -340
  546. package/docs/eval/issue43_/351/273/230/350/256/244/347/255/226/347/225/245/344/270/216/351/224/256/347/261/273/345/236/213/351/227/270_v1.1.md +0 -441
  547. package/docs/eval/issue43_/351/273/230/350/256/244/347/255/226/347/225/245/345/212/240/350/275/275/344/270/216/345/207/255/346/215/256/346/230/216/346/226/207/351/230/237/345/210/227_v1.0.md +0 -398
  548. package/docs/eval/issue50_/345/205/203/346/225/260/346/215/256/351/200/217/344/274/240/344/270/216/345/205/234/345/272/225_/344/277/256/345/244/215/350/256/260/345/275/225_v1.0.md +0 -437
  549. package/docs/eval/issue50_/345/215/212/351/207/215/345/244/215/345/276/205/345/256/232/345/244/215/346/240/270_/344/277/256/345/244/215/350/256/260/345/275/225_v1.0.md +0 -488
  550. package/docs/eval/issue50_/345/276/205/345/256/232/345/244/215/346/240/270/345/205/245/351/230/237_/344/277/256/345/244/215/350/256/260/345/275/225_v1.0.md +0 -428
  551. package/docs/eval/issue50_/350/257/273/351/235/242/344/277/235/346/212/244/345/217/252/350/256/244/346/230/276/345/274/217/346/235/245/346/272/220_/344/277/256/345/244/215/350/256/260/345/275/225_v1.0.md +0 -271
  552. package/docs/eval/issue50_/351/207/215/350/246/201/345/272/246/345/220/214/346/272/220/344/270/216/344/277/235/346/212/244/350/257/255/344/271/211_/344/277/256/345/244/215/350/256/260/345/275/225_v1.0.md +0 -306
  553. package/docs/eval/issue51_/344/270/200/351/224/256/345/256/211/350/243/205/345/244/261/350/264/245_/345/275/222/345/261/236/345/210/244/345/256/232_v1.0.md +0 -58
  554. package/docs/eval/issue52_/346/235/241/344/273/266/345/205/210/350/241/214/344/270/216/346/210/252/346/226/255/345/217/257/350/247/202/346/265/213_/344/277/256/345/244/215/350/256/260/345/275/225_v1.0.md +0 -360
  555. package/docs/eval/issue64_replay_check_/346/240/270/351/252/214/344/270/216/344/277/256/345/244/215_v1.0.md +0 -284
  556. package/docs/eval/issue65_session_recall_/344/274/232/350/257/235/351/232/224/347/246/273_/346/240/270/351/252/214/344/270/216/344/277/256/345/244/215_v1.0.md +0 -329
  557. package/docs/eval//344/270/211/346/241/243/350/207/252/346/262/273_/346/255/245/351/252/244/342/221/241/346/241/243/344/275/215/345/215/225/344/270/200/345/205/245/345/217/243_/350/220/275/347/240/201/350/256/260/345/275/225_v1.0.md +0 -651
  558. package/docs/eval//344/270/211/346/241/243/350/207/252/346/262/273_/346/255/245/351/252/244/342/221/242/345/217/230/346/233/264/345/215/225/344/270/216/345/233/236/346/273/232/345/216/237/350/257/255_/350/220/275/347/240/201/350/256/260/345/275/225_v1.0.md +0 -439
  559. package/docs/eval//344/270/211/346/241/243/350/207/252/346/262/273_/346/255/245/351/252/244/342/221/243/345/207/206/345/205/245/350/257/273/346/225/260_/350/220/275/347/240/201/350/256/260/345/275/225_v1.0.md +0 -1337
  560. package/docs/eval//344/270/211/346/241/243/350/207/252/346/262/273_/346/255/245/351/252/244/342/221/244/346/224/266/345/256/230/344/270/216/345/205/250/351/223/276/351/252/214/346/224/266_/350/220/275/347/240/201/350/256/260/345/275/225_v1.0.md +0 -1817
  561. package/docs/eval//344/270/215/345/217/257/351/235/240/346/200/247/350/220/275/345/234/260_P0_v1.0.md +0 -185
  562. package/docs/eval//344/274/230/345/214/226/347/254/254/344/270/200/346/211/271_/346/216/245/347/272/277/344/270/216/347/255/211/344/273/267/345/217/230/346/215/242_v1.0.md +0 -498
  563. package/docs/eval//344/274/230/345/214/226/347/254/254/344/270/211/346/211/271_/351/227/250/347/246/201/350/275/254/346/255/243/344/270/216/350/260/203/345/272/246/346/255/242/350/241/200/344/270/216/351/227/250/346/216/247/346/224/266/345/217/243_v1.0.md +0 -669
  564. package/docs/eval//344/274/230/345/214/226/347/254/254/344/272/214/346/211/271_/344/276/235/350/265/226/351/200/217/344/274/240/344/270/216/345/257/271/346/213/215/345/217/243/345/276/204/344/270/216/350/264/237/347/274/223/345/255/230_v1.0.md +0 -683
  565. package/docs/eval//345/207/272/350/264/247/351/235/242/345/206/222/347/203/237_/350/277/233/350/264/247/351/227/250/347/246/201_v1.0.md +0 -460
  566. package/docs/eval//345/217/221/345/270/20306_/344/270/200/351/224/256/351/205/215/347/275/256/344/270/216DSH0172_v1.0.md +0 -171
  567. package/docs/eval//345/217/221/345/270/20307_/345/244/226/351/203/250/346/212/245/345/221/212/345/233/233/346/211/271/344/277/256/345/244/215/344/270/216/346/217/222/344/273/266/351/235/242/345/212/240/345/233/272_v1.0.md +0 -209
  568. package/docs/eval//345/217/221/345/270/20308_/350/207/252/350/277/255/344/273/243/344/270/216/347/235/241/347/234/240_/345/233/276/346/243/200/347/264/242/350/267/257/344/270/216/346/235/203/351/207/215_v1.0.md +0 -97
  569. package/docs/eval//345/217/221/345/270/20309_/346/243/200/347/264/242/351/235/242/344/270/211/346/211/271/346/224/266/345/217/243_v1.0.md +0 -66
  570. package/docs/eval//345/217/221/345/270/20310_/350/257/273/351/235/242/346/215/237/345/235/217UTF8/345/256/266/346/227/217/346/224/266/345/217/243_v1.0.md +0 -71
  571. package/docs/eval//345/217/221/345/270/20311_/345/244/226/346/212/245/345/205/255/350/277/236/344/277/256/344/270/216/344/270/226/347/225/214/346/250/241/345/236/213/345/272/225/345/272/247_v1.0.md +0 -91
  572. package/docs/eval//345/217/221/345/270/20312_/344/270/226/347/225/214/346/250/241/345/236/213/345/212/237/350/203/275/347/253/257_v1.0.md +0 -108
  573. package/docs/eval//345/217/221/345/270/20313_/344/270/212/344/270/213/346/226/207/350/207/252/347/256/241/347/220/206/346/234/272/345/210/266_v1.0.md +0 -114
  574. package/docs/eval//345/217/221/345/270/20314_/350/272/253/344/275/223/303/227/350/204/221/347/273/204/345/220/210_v1.0.md +0 -160
  575. package/docs/eval//345/217/221/345/270/20315_/344/274/232/350/257/235/351/232/224/347/246/273/344/277/256/345/244/215/344/270/216/350/272/253/344/275/223/345/272/223/345/261/225/347/244/272_v1.0.md +0 -88
  576. package/docs/eval//345/256/236/351/252/214/346/226/271/346/241/210_/345/255/246/344/271/240/351/227/255/347/216/257AB/344/270/216/346/250/252/350/257/204_v1.0.md +0 -174
  577. package/docs/eval//345/275/222/344/270/200/345/261/202/347/274/272/347/234/201/347/277/273/345/205/263_/344/277/256/345/244/215/350/256/260/345/275/225_v1.0.md +0 -458
  578. package/docs/eval//346/200/247/350/203/275/344/270/223/351/241/271_/345/206/267/346/237/245/350/257/242/344/270/216/345/206/205/345/255/230_v1.0.md +0 -218
  579. package/docs/eval//346/225/205/351/232/234/346/263/250/345/205/245/345/256/236/346/265/213_v1.0.md +0 -432
  580. package/docs/eval//346/250/252/350/257/204_/345/205/255/345/256/266100/351/242/230/344/270/255/350/213/261/345/217/214/346/237/245_v1.0.md +0 -223
  581. package/docs/eval//347/224/250/346/210/267/350/243/201/345/206/263/345/244/204/347/275/256_/347/254/254/344/270/200/346/211/271_v1.0.md +0 -195
  582. package/docs/eval//347/224/250/346/210/267/350/243/201/345/206/263/345/244/204/347/275/256_/347/254/254/344/272/214/346/211/271B6_/346/234/254/346/234/272/350/267/257/345/276/204/347/233/270/345/257/271/345/214/226_v1.0.md +0 -78
  583. package/docs/eval//347/253/257/345/210/260/347/253/257LoCoMoQA/345/220/214/345/217/243/345/276/204/345/257/271/347/205/247_v1.0.md +0 -100
  584. package/docs/eval//347/253/257/345/210/260/347/253/257/345/271/262/346/211/260/346/261/240/350/257/204/346/265/213_/347/241/256/345/256/232/346/200/247/350/243/201/345/206/263vsLLM_judge_v1.1.md +0 -197
  585. package/docs/eval//347/254/2543/345/261/202stg/347/273/223/346/236/204/347/264/242/345/274/225_/345/256/236/346/226/275/350/256/260/345/275/225_v1.0.md +0 -250
  586. package/docs/eval//347/254/254/344/270/211/346/226/271/351/252/214/350/257/201/346/212/245/345/221/212_LoCoMo_/347/201/265/346/236/242_.png +0 -0
  587. package/docs/eval//347/254/254/344/270/211/346/226/271/351/252/214/350/257/201/346/212/245/345/221/212_/347/201/265/346/236/242_vs_dejavu_/347/273/237/344/270/200/350/257/204/345/210/206_v7.md +0 -202
  588. package/docs/eval//347/274/226/347/240/201/351/235/242/345/211/215/347/275/256_/345/205/245/345/217/243/350/207/252/344/277/235/350/257/201UTF8/344/270/216/346/226/207/346/234/254open/345/256/210/345/215/253_v1.0.md +0 -646
  589. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v1.md +0 -156
  590. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v10.md +0 -210
  591. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v11.md +0 -227
  592. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v12.md +0 -203
  593. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v13.md +0 -233
  594. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v14.md +0 -191
  595. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v15.md +0 -213
  596. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v16.md +0 -214
  597. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v17.md +0 -199
  598. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v18.md +0 -183
  599. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v19.md +0 -207
  600. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v2.md +0 -156
  601. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v20.md +0 -283
  602. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v21.md +0 -224
  603. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v22.md +0 -223
  604. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v23.md +0 -293
  605. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v24.md +0 -303
  606. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v25.md +0 -230
  607. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v26.md +0 -196
  608. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v27.md +0 -259
  609. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v28.md +0 -217
  610. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v29.md +0 -270
  611. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v3.md +0 -152
  612. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v30.md +0 -231
  613. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v31.md +0 -281
  614. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v4.md +0 -128
  615. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v5.md +0 -114
  616. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v6.md +0 -192
  617. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v7.md +0 -187
  618. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v8.md +0 -207
  619. package/docs/eval//347/274/272/351/231/267/346/214/226/346/216/230_/350/207/252/344/270/273/350/277/255/344/273/243_v9.md +0 -203
  620. package/docs/eval//350/257/255/344/271/211/346/227/266/347/251/272/345/233/276/350/241/245/345/205/250_P1_/346/212/275/345/217/226/345/231/250v4_/344/270/211/347/216/207/350/257/273/346/225/260_v1.0.md +0 -231
  621. package/docs/eval//351/262/270/345/250/230/344/270/203/347/261/273/347/212/266/346/200/201/350/277/275/350/270/252_v1.0.md +0 -176
  622. package/docs/hive//344/270/273/344/273/243/347/220/206/345/255/220/344/273/243/347/220/206/350/256/260/345/277/206/346/236/266/346/236/204/350/256/276/350/256/241.md +0 -385
  623. package/docs/hive//344/273/244/347/211/214/344/270/216/350/247/222/350/211/262/346/235/203/350/201/214/345/210/206/347/246/273_v0.1.md +0 -165
  624. package/docs/hive//344/273/244/347/211/214/350/257/255/344/271/211/344/277/256/346/255/243_/344/273/262/350/243/201/344/275/215_v0.1.md +0 -76
  625. package/docs/hive//345/244/232/347/253/257harness/351/200/232/344/277/241/345/245/221/347/272/246_v0.1.md +0 -42
  626. package/docs/hive//345/255/220/344/273/243/347/220/206/351/205/215/347/275/256/346/240/207/345/207/206_v0.5.md +0 -236
  627. package/docs/hive//345/256/211/345/205/250/345/256/241/350/256/241/345/256/236/351/224/232_v0.1.md +0 -202
  628. package/docs/hive//346/243/200/347/264/242/346/224/266/346/225/233/345/256/236/346/265/213/344/270/216S1b/350/256/276/350/256/241_v0.1.md +0 -43
  629. package/docs/hive//346/243/200/347/264/242/347/256/227/346/263/225/345/217/243/345/276/204/345/257/271/347/205/247_v0.1.md +0 -210
  630. package/docs/hive//346/243/200/347/264/242/350/267/257/345/276/204/344/270/216/350/256/244/347/237/245/347/273/223/346/236/204/345/245/221/347/272/246_v0.1.md +0 -152
  631. package/docs/hive//350/234/202/345/267/242M6_ingest/345/256/236/346/226/275/350/256/241/345/210/222_v0.1.md +0 -47
  632. package/docs/hive//350/234/202/345/267/242/345/217/214/345/256/236/344/276/213/344/272/222/351/252/214_/350/256/276/350/256/241/345/256/232/347/250/277.md +0 -519
  633. package/docs/hive//350/234/202/345/267/242/345/267/245/344/275/234/350/256/260/345/277/206_/351/241/271/347/233/256/350/256/241/345/210/222.md +0 -85
  634. package/docs/hive//350/234/202/345/267/242/350/256/276/350/256/241_/347/220/206/350/256/272/345/257/271/351/275/220_v0.1.md +0 -191
  635. package/docs/hive//350/234/202/345/267/242/350/277/255/344/273/243_/345/256/217/350/247/202/344/270/216/347/276/244/344/275/223/350/260/203/345/272/246_v0.1.md +0 -90
  636. package/docs/images/lingshu-moonlight-covenant-poster-preview.jpg +0 -0
  637. package/docs/images/lingshu-moonlight-covenant-poster.png +0 -0
  638. package/docs/mdcg/D_meta_/345/267/245/347/250/213/345/214/226/346/226/271/346/241/210_v0.2.md +0 -216
  639. package/docs/mdcg/README/350/257/246/347/273/206/347/211/210_v0.4.10.md +0 -746
  640. package/docs/mdcg/guardrail-charter.md +0 -164
  641. package/docs/mdcg/lingshu_tutorial.html +0 -14956
  642. package/docs/mdcg/memory-assessment.html +0 -923
  643. package/docs/mdcg/memory_score.html +0 -213
  644. package/docs/mdcg/memory_score.png +0 -0
  645. package/docs/mdcg/release_v0.3.0.md +0 -36
  646. package/docs/mdcg/release_v0.4.11.md +0 -49
  647. package/docs/mdcg/release_v0.4.5.md +0 -55
  648. package/docs/mdcg/tool_table_v0.3.0.md +0 -117
  649. package/docs/mdcg//344/270/226/347/225/214/346/250/241/345/236/213/345/212/237/350/203/275/347/253/257_/344/275/277/347/224/250/344/270/216/350/277/220/347/273/264_v1.0.md +0 -384
  650. package/docs/mdcg//344/273/243/347/240/201/350/257/204/345/256/241/344/270/216/346/235/241/344/273/266/345/214/226/346/263/250/351/207/212_/345/245/221/347/272/246_v0.1.md +0 -82
  651. package/docs/mdcg//345/205/250/345/272/223/344/273/243/347/240/201/350/257/204/345/256/241/344/270/216/346/235/241/344/273/266/345/214/226/346/263/250/351/207/212_/350/256/241/345/210/222_v0.1.md +0 -600
  652. package/docs/mdcg//345/212/237/350/203/275/350/260/203/347/224/250/346/230/240/345/260/204/350/241/250_v0.1.md +0 -266
  653. package/docs/mdcg//345/215/225/345/205/203/350/207/252/346/210/221/351/224/232/347/202/271_/347/263/273/347/273/237/346/217/220/347/244/272/350/257/215/346/240/207/345/207/206_v0.3.md +0 -275
  654. package/docs/mdcg//345/217/221/345/270/203/351/227/250/347/246/201/351/223/276_v0.1.md +0 -134
  655. package/docs/mdcg//346/272/220/347/240/201/347/272/247/346/236/266/346/236/204/345/256/241/350/256/241_GPT/346/211/271/350/257/204/345/257/271/347/205/247_v1.0.md +0 -130
  656. package/docs/mdcg//347/201/265/346/236/24282/345/267/245/345/205/267_/345/212/237/350/203/275/346/225/264/347/220/206/344/270/216/350/277/201/347/247/273/346/230/240/345/260/204_v0.1.md +0 -278
  657. package/docs/mdcg//347/201/265/346/236/242MCP/345/267/245/345/205/267/346/200/273/350/241/250_v3.4.md +0 -164
  658. package/docs/mdcg//347/201/265/346/236/242_/350/207/252/346/210/221/345/261/202/345/256/232/344/271/211.md +0 -43
  659. package/docs/mdcg//347/201/265/346/236/242/344/270/211/345/261/202/346/213/206/345/210/206/350/247/204/345/210/222_v0.1.md +0 -181
  660. package/docs/mdcg//347/201/265/346/236/242/350/256/260/345/277/206/345/212/250/350/257/215/345/215/217/350/256/256_v1.0-draft.md +0 -177
  661. package/docs/mdcg//347/216/257/344/272/214_/347/231/275/347/256/261/345/241/253/345/205/205/346/265/201/346/260/264/347/272/277_v0.1.md +0 -31
  662. package/docs/mdcg//347/235/241/347/234/240/345/221/250/346/234/237_/350/277/220/347/273/264/345/211/215/346/217/220/344/270/216/347/273/264/346/212/244/346/214/207/345/215/227_v1.0.md +0 -337
  663. package/docs/mdcg//347/274/272/345/217/243/345/215/225_P0/346/224/266/345/217/243_v0.1.md +0 -270
  664. package/docs/mdcg//350/256/244/347/237/245/345/233/276_G4-G8/347/274/272/345/217/243/350/243/201/345/256/232/345/215/225_v0.1.md +0 -491
  665. package/docs/mdcg//350/256/244/347/237/245/345/233/276_MD/347/233/256/345/275/225/346/226/271/346/241/210_v0.1.md +0 -552
  666. package/docs/mdcg//350/256/244/347/237/245/345/233/276_/346/235/241/344/273/266/347/251/272/351/227/264/345/220/210/346/210/220/344/270/216/347/224/237/346/225/210/346/235/241/344/273/266/345/217/243/345/276/204_v0.1.md +0 -340
  667. package/docs/mdcg//350/256/244/347/237/245/345/233/276_/347/264/242/345/274/225/344/270/216/345/267/245/347/250/213/350/247/204/350/214/203/345/214/226_/350/256/241/345/210/222_v0.1.md +0 -624
  668. package/docs/mdcg//350/256/244/347/237/245/345/233/276/344/275/234/344/270/272/350/256/260/345/277/206/346/223/215/344/275/234/347/263/273/347/273/237_/350/257/204/344/274/260/344/270/216/350/267/257/347/272/277_v0.1.md +0 -94
  669. package/docs/mdcg//350/256/260/345/277/206/346/223/215/344/275/234/347/263/273/347/273/237_MdCGOS/344/270/216MCP/346/216/245/345/205/245_v0.1.md +0 -281
  670. package/docs/mdcg//350/267/250/347/253/257/351/252/214/350/257/201/344/270/216/345/220/214/346/255/245/345/215/217/350/256/256_v0.1.md +0 -93
  671. package/docs/plans/GridWorld/346/234/200/345/260/217/351/227/255/347/216/257/350/247/204/346/240/274_v0.1.md +0 -176
  672. package/docs/plans/stg/346/235/241/344/273/266/345/214/226/344/270/216/347/273/223/346/236/204/347/264/242/345/274/225_/350/256/276/350/256/241_v0.1.md +0 -124
  673. package/docs/plans//345/205/250/344/270/255/346/226/207/347/274/226/347/240/201/344/270/216/350/234/202/345/267/242/344/273/273/345/212/241/346/240/207/350/257/206/345/245/221/347/272/246_v2.0.md +0 -220
  674. package/docs/plans//345/221/275/345/220/215/346/262/273/347/220/206_/351/241/271/347/233/256/350/256/241/345/210/222.md +0 -81
  675. package/docs/plans//345/244/232/344/270/273/344/275/223/344/270/226/347/225/214/346/250/241/345/236/213_/345/257/271/351/275/220/350/257/204/344/274/260/344/270/216/350/220/275/345/234/260/350/256/276/350/256/241_v0.1.md +0 -141
  676. package/docs/plans//347/201/265/346/236/242/350/272/253/344/275/223/303/227/350/204/221_/344/270/226/347/225/214/346/250/241/345/236/213/345/257/271/346/216/245/350/256/276/350/256/241_v0.1.md +0 -119
  677. package/docs/plans//347/234/237/346/272/220/347/264/242/345/274/225_/351/200/232/347/224/250/346/234/272/345/210/266_v0.3.md +0 -227
  678. package/docs/plans//347/235/241/347/234/240/344/270/216/350/207/252/350/277/255/344/273/243_/345/212/237/350/203/275/344/274/230/345/214/226/350/256/276/350/256/241_v0.4.md +0 -547
  679. package/docs/plans//347/237/245/350/257/206/345/233/276/350/260/261/351/241/271/347/233/256_/344/272/244/346/216/245/346/226/207/346/241/243_20260914.md +0 -308
  680. package/docs/plans//350/234/202/345/267/242/346/250/241/345/236/213/345/257/206/351/222/245/351/205/215/347/275/256/351/235/242_v1.0.md +0 -385
  681. package/docs/plans//350/256/260/345/277/206/350/207/252/345/244/204/347/220/206/344/270/211/346/241/243/350/207/252/346/262/273_/350/256/276/350/256/241_v0.2.md +0 -207
  682. package/docs/plans//350/257/255/344/271/211/346/227/266/347/251/272/345/233/276/350/241/245/345/205/250_/344/270/226/347/225/214/346/250/241/345/236/213/345/212/237/350/203/275/347/253/257_/350/256/276/350/256/241_v0.1.md +0 -107
  683. package/docs/promo/bilibili-cover.jpg +0 -0
  684. package/docs/promo/promo-visual-1.png +0 -0
  685. package/docs/promo/promo-visual-2.png +0 -0
  686. package/docs/promo/promo-visual-3.png +0 -0
  687. package/docs/promo/promo-visual-4.png +0 -0
  688. package/docs/promo/promo-visual-5.png +0 -0
  689. package/docs/swarm//350/234/202/347/276/244/344/272/222/350/201/224_v0.1.md +0 -704
  690. package/docs/swarm//350/234/202/347/276/244/345/220/214/351/224/231/346/243/200/346/265/213/345/256/236/351/252/214/345/215/217/350/256/256_v0.1.md +0 -242
  691. package/docs/swarm//350/234/202/347/276/244/345/244/232/346/231/272/350/203/275/344/275/223_/344/275/277/347/224/250/346/212/245/345/221/212_20260913.md +0 -68
  692. package/docs/swarm//350/234/202/347/276/244/345/244/232/346/231/272/350/203/275/344/275/223_/345/212/237/350/203/275/350/257/264/346/230/216_v0.6.md +0 -130
  693. package/docs/swarm//350/234/202/347/276/244/347/233/262/345/214/272/346/240/207/350/256/260_v1.0.md +0 -89
  694. package/docs/theory//344/270/215/345/217/257/351/235/240/345/256/232/347/220/206/344/270/216/345/244/261/346/225/210/344/274/230/345/205/210/346/241/206/346/236/266_v0.3.md +0 -365
  695. package/docs/theory//344/277/241/346/201/257/345/267/256/344/270/272/344/273/200/344/271/210/345/277/205/347/204/266/345/255/230/345/234/250/344/270/224/350/207/252/347/204/266/346/211/251/345/244/247.md +0 -239
  696. package/docs/theory//345/215/225/347/272/277/347/250/213/344/270/216/346/263/250/346/204/217/345/212/233/351/233/206/344/270/255_/346/227/240/344/272/211/350/256/256/347/220/206/350/256/272/346/226/207/346/241/243_v1.0.md +0 -129
  697. package/docs/theory//345/271/266/345/217/221/345/277/205/347/204/266/346/200/247/347/220/206/350/256/272_v0.2.md +0 -134
  698. package/docs/theory//346/231/272/350/203/275/347/232/204/345/205/254/347/220/206/345/214/226/345/237/272/347/237/263.md +0 -789
  699. package/docs/theory//346/231/272/350/203/275/347/232/204/350/256/244/347/237/245/350/277/207/347/250/213.md +0 -379
  700. package/docs/theory//346/231/272/350/203/275/350/256/2723.4.md +0 -5260
  701. package/docs/theory//346/246/202/345/277/265/345/210/206/345/261/202/345/257/271/351/275/220/350/241/250_v0.1.md +0 -145
  702. package/docs/theory//347/220/206/350/256/272_/346/234/272/345/210/266_/344/273/243/347/240/201_/345/256/236/351/252/214_/347/274/272/345/217/243/347/237/251/351/230/265_v0.1.md +0 -144
  703. package/docs/theory//347/220/206/350/256/272/344/273/223/346/213/206/345/210/206/344/270/216/347/231/275/347/256/261/347/237/245/350/257/206/345/272/223/345/206/205/350/277/201_v0.1.md +0 -198
  704. package/docs/theory//347/231/275/347/256/261/346/231/272/350/203/275/346/230/257/344/273/200/344/271/210/357/274/237.md +0 -812
  705. package/docs/theory//347/231/275/347/256/261/346/231/272/350/203/275/347/263/273/345/210/227/302/267/347/254/254/344/272/224/347/257/207/357/274/232/350/256/251AI/347/234/237/346/255/243/350/243/205/344/270/212/350/256/260/345/277/206.md +0 -421
  706. package/docs/theory//350/256/244/347/237/245/344/273/243/347/220/206/344/270/216/346/224/266/346/225/233/347/273/223/346/236/204_/346/235/241/344/273/266/350/256/272/351/207/215/346/236/204_v0.1.md +0 -221
  707. package/docs/world_model//344/270/226/347/225/214/346/250/241/345/236/213_/347/245/236/347/273/217/347/275/221/347/273/234/345/272/225/345/261/202/346/236/266/346/236/204_v1.0.md +0 -237
  708. package/docs//344/270/215/345/217/257/351/235/240/346/200/247/347/220/206/350/256/272_v0.1.md +0 -343
  709. package/docs//345/217/221/345/270/203/344/273/266/345/233/236/346/272/257/350/257/264/346/230/216_v0.1.md +0 -82
  710. package/docs//345/255/230/347/256/227/344/270/200/344/275/223/346/236/266/346/236/204/345/255/246/344/271/240_/345/244/226/351/203/250/347/220/206/350/256/272/345/257/271/347/205/247/344/270/216/350/267/257/347/272/277/344/272/244/346/216/245_20260916.md +0 -98
  711. package/docs//345/255/230/347/256/227/344/270/200/344/275/223/347/245/236/347/273/217/347/275/221/347/273/234/346/236/266/346/236/204_/346/200/273/347/272/262/344/270/216/344/272/244/346/216/245_20260916.md +0 -109
  712. package/docs//347/201/265/346/236/242/350/207/252/346/210/221/346/224/271/350/277/233/345/267/245/344/275/234/350/256/241/345/210/222_/345/244/226/351/203/250/347/240/224/347/251/266/347/263/273/345/210/227/345/220/270/346/224/266_v1_20260919.md +0 -286
  713. package/docs//347/231/275/347/256/261/345/214/226/347/272/262/351/242/206_/344/270/211/351/241/271/347/233/256/345/255/246/344/271/240/346/200/273/346/236/266/346/236/204/344/270/216Ghidra/344/272/244/346/216/245_20260916.md +0 -104
  714. package/docs//347/247/244_/350/256/260/345/277/206/347/263/273/347/273/237/350/257/204/346/265/213/350/247/204/350/214/203_v2.1.md +0 -225
  715. package/docs//350/256/260/345/277/206/347/263/273/347/273/237/345/215/263/347/231/275/347/256/261/345/214/226/346/231/272/350/203/275_/346/236/266/346/236/204/345/257/271/347/205/247_v0.2.md +0 -121
  716. package/docs//350/256/260/345/277/206/347/263/273/347/273/237/345/215/263/347/231/275/347/256/261/345/214/226/346/231/272/350/203/275_/346/236/266/346/236/204/345/257/271/347/205/247_v0.3.md +0 -117
  717. package/docs//350/256/260/345/277/206/350/257/204/345/256/241/347/263/273/347/273/237_/347/253/213/351/241/271/350/256/276/350/256/241/344/270/216/346/226/275/345/267/245/344/272/244/346/216/245_20260915.md +0 -183
@@ -1,1065 +1,1082 @@
1
- """
2
- parser.py · 语法分析器 v2.0
3
- 将 Token 序列构建为抽象语法树(AST)
4
- 支持:条件语句、指令语句、九章算术结构
5
-
6
- v2.0 变更:
7
- - 新增 _merge_identifiers:合并紧密相连的 IDENTIFIER/NUMBER 序列
8
- - 修复"道 新信任路径"被切成多个操作数的问题
9
- - 支持"止 X 于 Y"结构中的多词 X
10
- """
11
-
12
- from enum import Enum, auto
13
- from dataclasses import dataclass, field
14
- from typing import List, Optional, Union, Any, Tuple
15
- from .lexer import Token, TokenType
16
-
17
-
18
- # =============================================================================
19
- # AST 节点类型
20
- # =============================================================================
21
-
22
- class NodeType(Enum):
23
- """AST 节点类型"""
24
-
25
- # === 顶层 ===
26
- PROGRAM = auto() # 整个程序
27
-
28
- # === 九章算术结构 ===
29
- WENYUE = auto() # 问曰
30
- DAYUE = auto() # 答曰
31
- SHUYUE = auto() # 术曰
32
- STEP = auto() # 步骤(序号.操作)
33
-
34
- # === 语句 ===
35
- CONDITION_STMT = auto() # 条件语句(若...则...)
36
- LOOP_STMT = auto() # 循环语句(当...执行...)
37
- BLOCK = auto() # 语句块(多条顺序语句)
38
- FUNC_DEF = auto() # 函数定义(定义 名(参数):语句)
39
- RETURN_STMT = auto() # 返回语句(返回 表达式)
40
- ASSIGN_STMT = auto() # 赋值语句
41
- INSTRUCTION_STMT = auto() # 指令语句(道德经助记符)
42
- OPERATION_STMT = auto() # 操作语句
43
-
44
- # === 表达式 ===
45
- BINARY_EXPR = auto() # 二元表达式
46
- UNARY_EXPR = auto() # 一元表达式
47
- IDENTIFIER = auto() # 标识符
48
- LITERAL = auto() # 字面量
49
- CALL_EXPR = auto() # 调用表达式
50
-
51
- # === 条件 ===
52
- COMPARISON = auto() # 比较表达式
53
-
54
-
55
- # =============================================================================
56
- # AST 节点定义
57
- # =============================================================================
58
-
59
- @dataclass
60
- class ASTNode:
61
- """AST 节点基类"""
62
- type: NodeType
63
- line: int = 1
64
- column: int = 1
65
- children: List['ASTNode'] = field(default_factory=list)
66
- value: Any = None
67
- attributes: dict = field(default_factory=dict)
68
-
69
- def add_child(self, child: 'ASTNode'):
70
- """追加子节点(None 直接忽略)。"""
71
- if child is not None:
72
- self.children.append(child)
73
-
74
- def __repr__(self) -> str:
75
- """AST 节点调试表示:类型与子节点概览。"""
76
- return f"ASTNode({self.type.name}, value={self.value!r}, children={len(self.children)})"
77
-
78
-
79
- @dataclass
80
- class ProgramNode(ASTNode):
81
- """程序根节点"""
82
- def __init__(self, line: int = 1, column: int = 1):
83
- """构造 ProgramNode:绑定本节点的声明字段与子结构。"""
84
- super().__init__(NodeType.PROGRAM, line, column)
85
- self.statements: List[ASTNode] = []
86
-
87
- def add_statement(self, stmt: ASTNode):
88
- """追加语句并同时挂入子树。"""
89
- if stmt is not None:
90
- self.statements.append(stmt)
91
- self.add_child(stmt)
92
-
93
-
94
- @dataclass
95
- class WenyueNode(ASTNode):
96
- """问曰节点"""
97
- def __init__(self, question: str, line: int = 1, column: int = 1):
98
- """构造 WenyueNode:绑定本节点的声明字段与子结构。"""
99
- super().__init__(NodeType.WENYUE, line, column)
100
- self.question = question
101
- self.value = question
102
-
103
-
104
- @dataclass
105
- class DayueNode(ASTNode):
106
- """答曰节点"""
107
- def __init__(self, answer: str, line: int = 1, column: int = 1):
108
- """构造 DayueNode:绑定本节点的声明字段与子结构。"""
109
- super().__init__(NodeType.DAYUE, line, column)
110
- self.answer = answer
111
- self.value = answer
112
-
113
-
114
- @dataclass
115
- class ShuyueNode(ASTNode):
116
- """术曰节点"""
117
- def __init__(self, line: int = 1, column: int = 1):
118
- """构造 ShuyueNode:绑定本节点的声明字段与子结构。"""
119
- super().__init__(NodeType.SHUYUE, line, column)
120
- self.steps: List['StepNode'] = []
121
-
122
- def add_step(self, step: 'StepNode'):
123
- """追加步骤节点并挂入子树。"""
124
- self.steps.append(step)
125
- self.add_child(step)
126
-
127
-
128
- @dataclass
129
- class StepNode(ASTNode):
130
- """步骤节点"""
131
- def __init__(self, step_num: int, statement: ASTNode, line: int = 1, column: int = 1):
132
- """构造 StepNode:绑定本节点的声明字段与子结构。"""
133
- super().__init__(NodeType.STEP, line, column)
134
- self.step_num = step_num
135
- self.statement = statement
136
- self.add_child(statement)
137
-
138
-
139
- @dataclass
140
- class ConditionStmtNode(ASTNode):
141
- """条件语句:若 [条件] 则 [操作] [否则 [操作]](body 可为语句列表)"""
142
- def __init__(self, condition: ASTNode, then_body, else_body=None,
143
- line: int = 1, column: int = 1):
144
- """构造 ConditionStmtNode:绑定本节点的声明字段与子结构。"""
145
- super().__init__(NodeType.CONDITION_STMT, line, column)
146
- self.condition = condition
147
- self.then_body = then_body
148
- self.else_body = else_body
149
- self.add_child(condition)
150
- self.add_child(then_body)
151
- if else_body is not None:
152
- self.add_child(else_body)
153
-
154
-
155
- @dataclass
156
- class LoopStmtNode(ASTNode):
157
- """循环语句:当 [条件] 执行 [操作](while 语义,body 可为语句列表)"""
158
- def __init__(self, condition: ASTNode, body, line: int = 1, column: int = 1):
159
- """构造 LoopStmtNode:绑定本节点的声明字段与子结构。"""
160
- super().__init__(NodeType.LOOP_STMT, line, column)
161
- self.condition = condition
162
- self.body = body
163
- self.add_child(condition)
164
- self.add_child(body)
165
-
166
-
167
- @dataclass
168
- class BlockNode(ASTNode):
169
- """语句块:多条顺序执行的语句(循环体/条件体多语句支持)"""
170
- def __init__(self, statements, line: int = 1, column: int = 1):
171
- """构造 BlockNode:绑定本节点的声明字段与子结构。"""
172
- super().__init__(NodeType.BLOCK, line, column)
173
- self.statements = statements
174
- for s in statements:
175
- self.add_child(s)
176
-
177
-
178
- @dataclass
179
- class FuncDefNode(ASTNode):
180
- """函数定义:定义 名(参数):语句(body 可为语句列表)"""
181
- def __init__(self, name: str, params: List[str], body, line: int = 1, column: int = 1):
182
- """构造 FuncDefNode:绑定本节点的声明字段与子结构。"""
183
- super().__init__(NodeType.FUNC_DEF, line, column)
184
- self.name = name
185
- self.params = params
186
- self.body = body
187
- self.add_child(body)
188
-
189
-
190
- @dataclass
191
- class ReturnStmtNode(ASTNode):
192
- """返回语句:返回 [表达式]"""
193
- def __init__(self, value: Optional[ASTNode], line: int = 1, column: int = 1):
194
- """构造 ReturnStmtNode:绑定本节点的声明字段与子结构。"""
195
- super().__init__(NodeType.RETURN_STMT, line, column)
196
- self.value = value
197
- if value:
198
- self.add_child(value)
199
-
200
-
201
- @dataclass
202
- class CallExprNode(ASTNode):
203
- """函数调用:名(参数1,参数2)"""
204
- def __init__(self, name: str, args: List[ASTNode], line: int = 1, column: int = 1):
205
- """构造 CallExprNode:绑定本节点的声明字段与子结构。"""
206
- super().__init__(NodeType.CALL_EXPR, line, column)
207
- self.name = name
208
- self.args = args
209
- for a in args:
210
- self.add_child(a)
211
-
212
-
213
- @dataclass
214
- class InstructionStmtNode(ASTNode):
215
- """指令语句:道德经助记符 + 操作数"""
216
- def __init__(self, instruction: TokenType, operands: List[ASTNode] = None,
217
- line: int = 1, column: int = 1):
218
- """构造 InstructionStmtNode:绑定本节点的声明字段与子结构。"""
219
- super().__init__(NodeType.INSTRUCTION_STMT, line, column)
220
- self.instruction = instruction
221
- self.operands = operands or []
222
- for op in self.operands:
223
- self.add_child(op)
224
-
225
-
226
- @dataclass
227
- class AssignStmtNode(ASTNode):
228
- """赋值语句:标识符 = 值"""
229
- def __init__(self, target: str, value: ASTNode, line: int = 1, column: int = 1):
230
- """构造 AssignStmtNode:绑定本节点的声明字段与子结构。"""
231
- super().__init__(NodeType.ASSIGN_STMT, line, column)
232
- self.target = target
233
- self.value_node = value
234
- self.add_child(value)
235
-
236
-
237
- @dataclass
238
- class BinaryExprNode(ASTNode):
239
- """二元表达式:左 操作符 右"""
240
- def __init__(self, left: ASTNode, operator: str, right: ASTNode,
241
- line: int = 1, column: int = 1):
242
- """构造 BinaryExprNode:绑定本节点的声明字段与子结构。"""
243
- super().__init__(NodeType.BINARY_EXPR, line, column)
244
- self.left = left
245
- self.operator = operator
246
- self.right = right
247
- self.add_child(left)
248
- self.add_child(right)
249
-
250
-
251
- @dataclass
252
- class ComparisonNode(ASTNode):
253
- """比较表达式"""
254
- def __init__(self, left: ASTNode, op: str, right: ASTNode,
255
- line: int = 1, column: int = 1):
256
- """构造 ComparisonNode:绑定本节点的声明字段与子结构。"""
257
- super().__init__(NodeType.COMPARISON, line, column)
258
- self.left = left
259
- self.op = op
260
- self.right = right
261
- self.add_child(left)
262
- self.add_child(right)
263
-
264
-
265
- @dataclass
266
- class IdentifierNode(ASTNode):
267
- """标识符"""
268
- def __init__(self, name: str, line: int = 1, column: int = 1):
269
- """构造 IdentifierNode:绑定本节点的声明字段与子结构。"""
270
- super().__init__(NodeType.IDENTIFIER, line, column)
271
- self.name = name
272
- self.value = name
273
-
274
-
275
- @dataclass
276
- class LiteralNode(ASTNode):
277
- """字面量"""
278
- def __init__(self, value: Union[str, float, int], literal_type: str,
279
- line: int = 1, column: int = 1):
280
- """构造 LiteralNode:绑定本节点的声明字段与子结构。"""
281
- super().__init__(NodeType.LITERAL, line, column)
282
- self.literal_value = value
283
- self.literal_type = literal_type # "number", "string"
284
- self.value = value
285
-
286
-
287
- # =============================================================================
288
- # 语法分析器
289
- # =============================================================================
290
-
291
- class Parser:
292
- """
293
- 语法分析器 v2.0
294
- 将 Token 序列构建为 AST
295
- """
296
-
297
- # 指令助记符集合
298
- INSTRUCTION_TOKENS = {
299
- TokenType.DAO, TokenType.DE, TokenType.ZIRAN,
300
- TokenType.WUWEI, TokenType.GU, TokenType.PIN,
301
- TokenType.ROU, TokenType.PU, TokenType.ZHI, TokenType.ZHIZU,
302
- }
303
-
304
- def __init__(self, tokens: List[Token], errors: List[str] = None):
305
- """构造 Parser:绑定本节点的声明字段与子结构。"""
306
- self.tokens = tokens
307
- self.pos = 0
308
- self.errors: List[str] = errors or []
309
- self.current_token = self.tokens[0] if tokens else None
310
-
311
- def parse(self) -> ProgramNode:
312
- """解析整个程序"""
313
- program = ProgramNode()
314
-
315
- while not self._is_at_end():
316
- if self._match(TokenType.NEWLINE, TokenType.SEMICOLON, TokenType.COMMA):
317
- continue
318
-
319
- stmt = self._parse_statement()
320
- if stmt:
321
- program.add_statement(stmt)
322
- # DEBUG
323
- # print(f" [parse] Added: type={stmt.type.name} value={stmt.value!r}")
324
- # if hasattr(stmt, 'operands'):
325
- # for j, op in enumerate(stmt.operands):
326
- # print(f" op{j}: {op.type.name} value={op.value!r}")
327
- else:
328
- # print(f" [parse] None at {self.current_token}")
329
- self._advance()
330
-
331
- return program
332
-
333
- # ---- 语句解析 ----
334
-
335
- def _parse_statement(self) -> Optional[ASTNode]:
336
- """解析单个语句"""
337
- token = self.current_token
338
-
339
- if token is None or token.type == TokenType.EOF:
340
- return None
341
-
342
- # 问曰 → 答曰 → 术曰(九章算术结构)
343
- if token.type == TokenType.WENYUE:
344
- return self._parse_wenyue_block()
345
-
346
- # 术曰 → 术曰块(可以独立出现)
347
- if token.type == TokenType.SHUYUE:
348
- return self._parse_shuyue_block()
349
-
350
- # 若 → 条件语句
351
- if token.type == TokenType.RUO:
352
- return self._parse_condition()
353
-
354
- # 当 → 循环语句(白箱循环语法:当 条件 执行 操作)
355
- if token.type == TokenType.DANG:
356
- return self._parse_loop()
357
-
358
- # 定义 → 函数定义(定义 名(参数):语句)
359
- if token.type == TokenType.DINGYI:
360
- return self._parse_func_def()
361
-
362
- # 返回 → 返回语句(返回 表达式)
363
- if token.type == TokenType.FANHUI:
364
- self._advance()
365
- val = self._parse_expression() if self.current_token else None
366
- return ReturnStmtNode(val,
367
- line=token.line, column=token.column)
368
-
369
- # 道德经助记符 → 指令语句
370
- if token.type in self.INSTRUCTION_TOKENS:
371
- return self._parse_instruction()
372
-
373
- # 标识符 → 可能是赋值
374
- if token.type == TokenType.IDENTIFIER:
375
- return self._parse_assign_or_call()
376
-
377
- # 句号结束
378
- if token.type == TokenType.PERIOD:
379
- self._advance()
380
- return None
381
-
382
- # 无法识别
383
- self.errors.append(
384
- f"L{token.line}:C{token.column} 无法解析的语句开头: '{token.value}' ({token.type.name})"
385
- )
386
- self._advance()
387
- return None
388
-
389
- def _parse_shuyue_block(self) -> Optional[ASTNode]:
390
- """
391
- 解析术曰块(独立形式):术曰:1。... 2。...
392
- 不依赖前面的问曰/答曰
393
- """
394
- self._consume(TokenType.SHUYUE, "期望 '术曰'")
395
-
396
- shuyue = ShuyueNode(line=self.current_token.line if self.current_token else 1,
397
- column=self.current_token.column if self.current_token else 1)
398
-
399
- # 解析步骤序列
400
- while not self._is_at_end():
401
- # 跳过分隔符
402
- while (self.current_token and
403
- self.current_token.type in (TokenType.SEMICOLON,
404
- TokenType.COMMA,
405
- TokenType.COLON)):
406
- self._advance()
407
-
408
- if self.current_token and self.current_token.type == TokenType.NUMBER:
409
- step_num = int(float(self.current_token.value))
410
- self._advance()
411
-
412
- if self.current_token and self.current_token.type == TokenType.PERIOD:
413
- self._advance()
414
-
415
- step_content = self._parse_step_content()
416
- if step_content:
417
- shuyue.add_step(StepNode(step_num, step_content,
418
- line=step_content.line,
419
- column=step_content.column))
420
- else:
421
- break
422
-
423
- return shuyue
424
-
425
- def _parse_wenyue_block(self) -> Optional[ASTNode]:
426
- """解析 问曰:... 答曰:... 术曰:... 结构"""
427
- # 问曰
428
- self._consume(TokenType.WENYUE, "期望 '问曰'")
429
- question_parts = self._collect_until(TokenType.DAYUE)
430
- question = "".join(p.value for p in question_parts).strip()
431
-
432
- # 答曰
433
- self._consume(TokenType.DAYUE, "期望 '答曰'")
434
- answer_parts = self._collect_until(TokenType.SHUYUE)
435
- answer = "".join(p.value for p in answer_parts).strip()
436
-
437
- # 术曰
438
- self._consume(TokenType.SHUYUE, "期望 '术曰'")
439
-
440
- # 用独立的术曰解析逻辑
441
- shuyue = ShuyueNode(line=self.current_token.line if self.current_token else 1,
442
- column=self.current_token.column if self.current_token else 1)
443
-
444
- while not self._is_at_end():
445
- # 跳过分隔符
446
- while (self.current_token and
447
- self.current_token.type in (TokenType.SEMICOLON,
448
- TokenType.COMMA,
449
- TokenType.COLON)):
450
- self._advance()
451
-
452
- if self.current_token and self.current_token.type == TokenType.NUMBER:
453
- step_num = int(float(self.current_token.value))
454
- self._advance()
455
-
456
- if self.current_token and self.current_token.type == TokenType.PERIOD:
457
- self._advance()
458
-
459
- step_content = self._parse_step_content()
460
- if step_content:
461
- shuyue.add_step(StepNode(step_num, step_content,
462
- line=step_content.line,
463
- column=step_content.column))
464
- else:
465
- break
466
-
467
- shuyue.attributes["question"] = question
468
- shuyue.attributes["answer"] = answer
469
-
470
- return shuyue
471
-
472
- def _parse_step_content(self) -> Optional[ASTNode]:
473
- """解析步骤内容"""
474
- if self.current_token and self.current_token.type == TokenType.RUO:
475
- return self._parse_condition()
476
- elif self.current_token and self.current_token.type == TokenType.DANG:
477
- return self._parse_loop()
478
- elif self.current_token and self.current_token.type == TokenType.DINGYI:
479
- return self._parse_func_def()
480
- elif self.current_token and self.current_token.type == TokenType.FANHUI:
481
- self._advance()
482
- val = self._parse_expression() if self.current_token else None
483
- return ReturnStmtNode(val, line=1, column=1)
484
- elif self.current_token and self.current_token.type in self.INSTRUCTION_TOKENS:
485
- return self._parse_instruction()
486
- elif self.current_token and self.current_token.type == TokenType.IDENTIFIER:
487
- # 可能是单个标识符或合并后的多词短语
488
- merged = self._merge_identifiers()
489
- return merged
490
- else:
491
- parts = []
492
- while (self.current_token and
493
- self.current_token.type not in (TokenType.NUMBER, TokenType.PERIOD) and
494
- not self._is_at_end()):
495
- parts.append(self.current_token.value)
496
- self._advance()
497
- if parts:
498
- return LiteralNode("".join(parts).strip(), "string",
499
- line=self.current_token.line if self.current_token else 1,
500
- column=self.current_token.column if self.current_token else 1)
501
- return None
502
-
503
- def _parse_condition(self) -> Optional[ASTNode]:
504
- """解析条件语句:若 [条件] 则 [操作] [否则 [操作]]"""
505
- start_line = self.current_token.line if self.current_token else 1
506
- start_col = self.current_token.column if self.current_token else 1
507
-
508
- self._consume(TokenType.RUO, "期望 '若'")
509
-
510
- condition = self._parse_comparison()
511
-
512
- self._skip_punctuation_before(TokenType.ZE)
513
-
514
- self._consume(TokenType.ZE, "期望 '则'")
515
-
516
- then_body = self._parse_single_statement()
517
-
518
- else_body = None
519
- # 跳过 then 与 否则 之间的分隔符(逗号/分号等)
520
- self._skip_punctuation_before(TokenType.FOUZE)
521
- if self.current_token and self.current_token.type == TokenType.FOUZE:
522
- self._advance()
523
- else_body = self._parse_single_statement()
524
-
525
- return ConditionStmtNode(condition, then_body, else_body, start_line, start_col)
526
-
527
- def _parse_loop(self) -> Optional[ASTNode]:
528
- """解析循环语句:当 [条件] 执行 [操作](while 语义)"""
529
- start_line = self.current_token.line if self.current_token else 1
530
- start_col = self.current_token.column if self.current_token else 1
531
-
532
- self._consume(TokenType.DANG, "期望 '当'")
533
-
534
- condition = self._parse_comparison()
535
-
536
- self._skip_punctuation_before(TokenType.ZHIXING)
537
-
538
- self._consume(TokenType.ZHIXING, "期望 '执行'")
539
-
540
- body = self._parse_statement_or_block()
541
-
542
- return LoopStmtNode(condition, body, start_line, start_col)
543
-
544
- def _parse_func_def(self) -> Optional[ASTNode]:
545
- """解析函数定义:定义 名(参数1,参数2):语句
546
- 参数在( )内,逗号分隔;返回 FuncDefNode(body 可为块)"""
547
- start_line = self.current_token.line if self.current_token else 1
548
- start_col = self.current_token.column if self.current_token else 1
549
-
550
- self._consume(TokenType.DINGYI, "期望 '定义'")
551
-
552
- # 函数名(标识符)
553
- if not (self.current_token and self.current_token.type == TokenType.IDENTIFIER):
554
- self.errors.append("定义后期望函数名")
555
- return None
556
- name = self.current_token.value
557
- self._advance()
558
-
559
- # 参数列表( )
560
- params = []
561
- if self.current_token and self.current_token.type == TokenType.LPAREN:
562
- self._advance()
563
- while (self.current_token and
564
- self.current_token.type != TokenType.RPAREN and
565
- not self._is_at_end()):
566
- if self.current_token.type == TokenType.IDENTIFIER:
567
- params.append(self.current_token.value)
568
- self._advance() # 跳过标识符/逗号/空格
569
- if self.current_token and self.current_token.type == TokenType.RPAREN:
570
- self._advance()
571
-
572
- # 冒号(可选分隔)
573
- if self.current_token and self.current_token.type == TokenType.COLON:
574
- self._advance()
575
-
576
- body = self._parse_single_statement()
577
-
578
- return FuncDefNode(name, params, body, start_line, start_col)
579
-
580
- def _skip_punctuation_before(self, *target_types: TokenType):
581
- """跳过标点符号"""
582
- while self.current_token and self.current_token.type in (
583
- TokenType.COMMA, TokenType.PERIOD, TokenType.SEMICOLON,
584
- TokenType.COLON, TokenType.QUESTION, TokenType.EXCLAM,
585
- ):
586
- self._advance()
587
-
588
- def _parse_statement_or_block(self) -> Any:
589
- """解析语句或块:返回语句列表(单语句=[stmt];分号/句号分隔多条)
590
- 块内多条语句:`则 语句1;语句2;...`(支持循环体/条件体多语句)"""
591
- stmts = []
592
- while True:
593
- stmt = self._parse_single_statement()
594
- if stmt is not None:
595
- stmts.append(stmt)
596
- # 分隔符:分号/句号 → 继续收下一条;否则块结束
597
- if self.current_token and self.current_token.type in (
598
- TokenType.SEMICOLON, TokenType.PERIOD, TokenType.COMMA):
599
- self._advance()
600
- # 分隔符后若是步骤号/块边界 → 块结束(九章算术步骤边界 1。…2。…)
601
- if (self.current_token and
602
- self.current_token.type in (TokenType.NUMBER, TokenType.SHUYUE)):
603
- break
604
- continue
605
- break
606
- if not stmts:
607
- return None
608
- if len(stmts) == 1:
609
- return stmts[0]
610
- return BlockNode(stmts, line=stmts[0].line, column=stmts[0].column)
611
-
612
- def _parse_single_statement(self) -> Optional[ASTNode]:
613
- """解析单条语句"""
614
- if self.current_token and self.current_token.type == TokenType.RUO:
615
- return self._parse_condition()
616
- elif self.current_token and self.current_token.type == TokenType.DANG:
617
- return self._parse_loop()
618
- elif self.current_token and self.current_token.type == TokenType.DINGYI:
619
- return self._parse_func_def()
620
- elif self.current_token and self.current_token.type == TokenType.FANHUI:
621
- self._advance()
622
- val = self._parse_expression() if self.current_token else None
623
- return ReturnStmtNode(val, line=1, column=1)
624
- elif self.current_token and self.current_token.type in self.INSTRUCTION_TOKENS:
625
- return self._parse_instruction()
626
- elif self.current_token and self.current_token.type == TokenType.IDENTIFIER:
627
- return self._parse_assign_or_call()
628
- else:
629
- parts = []
630
- # 停止条件:标点符号 + 语句开头关键字
631
- _STOP = (
632
- TokenType.PERIOD, TokenType.COMMA, TokenType.SEMICOLON,
633
- TokenType.WENYUE, TokenType.DAYUE, TokenType.SHUYUE,
634
- TokenType.RUO, TokenType.FOUZE, TokenType.DANG,
635
- TokenType.ZHIXING,
636
- )
637
- while (self.current_token and
638
- self.current_token.type not in _STOP and
639
- not self._is_at_end()):
640
- parts.append(self.current_token.value)
641
- self._advance()
642
- text = "".join(parts).strip()
643
- if text:
644
- return LiteralNode(text, "string")
645
- return None
646
-
647
- def _parse_instruction(self) -> Optional[ASTNode]:
648
- """
649
- 解析指令语句 v2.0
650
-
651
- 关键改进:使用 _merge_identifiers 合并紧密相连的
652
- IDENTIFIER/NUMBER 序列为一个逻辑操作数。
653
-
654
- 例:道 新信任路径 → 道 + [ID(新信任路径)]
655
- 例:柔 响应强度 → 柔 + [ID(响应强度)]
656
- 例:止情感权重于0.15 → 止 + [ID(情感权重)] + [Lit(0.15)]
657
- """
658
- instr_token = self.current_token
659
- instr_type = instr_token.type
660
- self._advance()
661
-
662
- operands = []
663
-
664
- # 停止条件:标点符号 + 语句开头关键字(防止跨语句吞噬)
665
- _INST_STOP = (
666
- TokenType.PERIOD, TokenType.COMMA, TokenType.SEMICOLON,
667
- TokenType.EOF,
668
- # 语句开头关键字 —— 遇到这些说明指令操作数已结束
669
- TokenType.WENYUE, # 问曰 → 新语句
670
- TokenType.DAYUE, # 答曰 → 新语句
671
- TokenType.SHUYUE, # 术曰 → 新语句
672
- TokenType.RUO, # 若 → 条件语句
673
- TokenType.FOUZE, # 否则 → 条件语句
674
- TokenType.DAO, # 道 → 指令(但不在操作数位置)
675
- TokenType.DE, # 德 → 指令
676
- TokenType.ZIRAN, # 自然 → 指令
677
- TokenType.WUWEI, # 无为 → 指令
678
- TokenType.GU, # 谷 → 指令
679
- TokenType.PIN, # 牝 → 指令
680
- TokenType.ROU, # 柔 → 指令
681
- TokenType.PU, # 朴 → 指令
682
- TokenType.ZHI, # 止 → 指令
683
- TokenType.ZHIZU, # 知足 → 指令
684
- )
685
-
686
- while (self.current_token and
687
- self.current_token.type not in _INST_STOP and
688
- not self._is_at_end()):
689
-
690
- tok = self.current_token
691
-
692
- if tok.type == TokenType.YU:
693
- # "于" → 后面跟数值
694
- self._advance()
695
- value = self._parse_numeric_value()
696
- if value is not None:
697
- operands.append(value)
698
- continue
699
-
700
- elif tok.type == TokenType.IDENTIFIER:
701
- # 合并后续紧密相连的 IDENTIFIER/NUMBER
702
- merged = self._merge_identifiers()
703
- operands.append(merged)
704
-
705
- elif tok.type == TokenType.NUMBER:
706
- operands.append(LiteralNode(float(tok.value), "number", tok.line, tok.column))
707
- self._advance()
708
-
709
- elif tok.type == TokenType.STRING:
710
- operands.append(LiteralNode(tok.value, "string", tok.line, tok.column))
711
- self._advance()
712
-
713
- else:
714
- self._advance()
715
-
716
- return InstructionStmtNode(instr_type, operands,
717
- line=instr_token.line,
718
- column=instr_token.column)
719
-
720
- def _merge_identifiers(self) -> ASTNode:
721
- """
722
- 合并从当前位置开始的紧密相连的 IDENTIFIER/NUMBER 序列
723
-
724
- 例:ID(新) ID(信任) ID(路径) → IdentifierNode("新信任路径")
725
- 例:ID(响应) ID(强度) → IdentifierNode("响应强度")
726
- 例:ID(累积) ID(信任值) → IdentifierNode("累积信任值")
727
-
728
- 判断标准:同一行、列号连续
729
- """
730
- start_tok = self.current_token
731
- parts = [start_tok.value]
732
- line = start_tok.line
733
- col = start_tok.column
734
- self._advance()
735
-
736
- while (self.current_token and
737
- self.current_token.line == line and
738
- self.current_token.type in (TokenType.IDENTIFIER, TokenType.NUMBER)):
739
- parts.append(self.current_token.value)
740
- self._advance()
741
-
742
- merged_name = "".join(parts)
743
- return IdentifierNode(merged_name, line, col)
744
-
745
- def _parse_numeric_value(self) -> Optional[ASTNode]:
746
- """解析数值(可能跨多个 token)"""
747
- if self.current_token is None:
748
- return None
749
-
750
- if self.current_token.type == TokenType.NUMBER:
751
- val = float(self.current_token.value)
752
- line, col = self.current_token.line, self.current_token.column
753
- self._advance()
754
- return LiteralNode(val, "number", line, col)
755
-
756
- if self.current_token.type == TokenType.IDENTIFIER:
757
- prefix = self.current_token.value
758
- line, col = self.current_token.line, self.current_token.column
759
- self._advance()
760
-
761
- if self.current_token and self.current_token.type == TokenType.PERIOD:
762
- self._advance()
763
- if self.current_token and self.current_token.type == TokenType.NUMBER:
764
- val = float(prefix + "." + self.current_token.value)
765
- self._advance()
766
- return LiteralNode(val, "number", line, col)
767
- else:
768
- try:
769
- return LiteralNode(float(prefix), "number", line, col)
770
- except ValueError:
771
- return IdentifierNode(prefix, line, col)
772
- elif self.current_token and self.current_token.type == TokenType.NUMBER:
773
- val = float(prefix + self.current_token.value)
774
- self._advance()
775
- return LiteralNode(val, "number", line, col)
776
- else:
777
- return IdentifierNode(prefix, line, col)
778
-
779
- return None
780
-
781
- def _parse_assign_or_call(self) -> Optional[ASTNode]:
782
- """解析赋值或调用
783
-
784
- 若后面紧跟 = 或 = → 赋值语句
785
- 若后面紧跟 ( → 函数调用表达式(名(参数))
786
- 否则 → 标识符表达式
787
- """
788
- ident = self.current_token.value
789
- line = self.current_token.line
790
- col = self.current_token.column
791
- self._advance()
792
-
793
- # 检查是否是赋值
794
- if self.current_token and self.current_token.type == TokenType.EQUALS:
795
- self._advance() # 跳过 =
796
- value_node = self._parse_expression()
797
- return AssignStmtNode(
798
- target=ident,
799
- value=value_node,
800
- line=line,
801
- column=col
802
- )
803
-
804
- # 函数调用:名(参数1,参数2)
805
- if self.current_token and self.current_token.type == TokenType.LPAREN:
806
- self._advance()
807
- args = []
808
- while (self.current_token and
809
- self.current_token.type != TokenType.RPAREN and
810
- not self._is_at_end()):
811
- # 参数可为表达式(n 减 1)/标识符/数值
812
- if self.current_token.type in (TokenType.IDENTIFIER,
813
- TokenType.NUMBER):
814
- args.append(self._parse_expression())
815
- else:
816
- self._advance()
817
- if self.current_token and self.current_token.type == TokenType.RPAREN:
818
- self._advance()
819
- return CallExprNode(ident, args, line, col)
820
-
821
- return IdentifierNode(ident, line, col)
822
-
823
- def _parse_comparison(self) -> ASTNode:
824
- """解析比较表达式"""
825
- left = self._parse_expression()
826
-
827
- if self.current_token and self.current_token.type in (
828
- TokenType.DENGYU, TokenType.DAYU, TokenType.XIAOYU,
829
- TokenType.WEI, TokenType.BUWEI,
830
- ):
831
- op_token = self.current_token
832
- op_map = {
833
- TokenType.DENGYU: "==",
834
- TokenType.DAYU: ">",
835
- TokenType.XIAOYU: "<",
836
- TokenType.WEI: "==",
837
- TokenType.BUWEI: "!=",
838
- }
839
- op = op_map.get(op_token.type, "==")
840
- self._advance()
841
-
842
- right = self._parse_numeric_value()
843
- if right is None:
844
- right = self._parse_expression()
845
- return ComparisonNode(left, op, right, line=op_token.line, column=op_token.column)
846
-
847
- return left
848
-
849
- def _parse_expression(self) -> ASTNode:
850
- """解析表达式(支持二元算术 + 括号优先:标识符/数值/(表达式) + 运算符 + 右)"""
851
- if self.current_token is None:
852
- return LiteralNode("", "string")
853
-
854
- if self.current_token.type == TokenType.LPAREN:
855
- # 括号优先: ( 表达式 )
856
- line = self.current_token.line
857
- col = self.current_token.column
858
- self._advance()
859
- inner = self._parse_expression()
860
- if self.current_token and self.current_token.type == TokenType.RPAREN:
861
- self._advance()
862
- return self._parse_binary_tail(inner)
863
-
864
- if self.current_token.type == TokenType.IDENTIFIER:
865
- # 若后跟 ( → 函数调用;否则合并多词短语
866
- if (self._peek_next() and
867
- self._peek_next().type == TokenType.LPAREN):
868
- name = self.current_token.value
869
- line = self.current_token.line
870
- col = self.current_token.column
871
- self._advance() # 消费函数名
872
- self._advance() # 消费 (
873
- args = []
874
- while (self.current_token and
875
- self.current_token.type != TokenType.RPAREN and
876
- not self._is_at_end()):
877
- if self.current_token.type in (TokenType.IDENTIFIER,
878
- TokenType.NUMBER):
879
- args.append(self._parse_expression())
880
- else:
881
- self._advance()
882
- if self.current_token and self.current_token.type == TokenType.RPAREN:
883
- self._advance()
884
- return self._parse_binary_tail(
885
- CallExprNode(name, args, line, col))
886
- left = self._merge_identifiers()
887
- return self._parse_binary_tail(left)
888
- elif self.current_token.type == TokenType.NUMBER:
889
- node = LiteralNode(float(self.current_token.value), "number",
890
- self.current_token.line,
891
- self.current_token.column)
892
- self._advance()
893
- return self._parse_binary_tail(node)
894
- elif self.current_token.type == TokenType.STRING:
895
- node = LiteralNode(self.current_token.value, "string",
896
- self.current_token.line,
897
- self.current_token.column)
898
- self._advance()
899
- return self._parse_binary_tail(node)
900
- else:
901
- parts = []
902
- # 停止条件:标点符号 + 语句开头关键字
903
- _EXPR_STOP = (
904
- TokenType.ZE, TokenType.FOUZE,
905
- TokenType.PERIOD, TokenType.COMMA, TokenType.SEMICOLON,
906
- TokenType.WENYUE, TokenType.DAYUE, TokenType.SHUYUE,
907
- TokenType.RUO, TokenType.DAO, TokenType.DE,
908
- TokenType.ZIRAN, TokenType.WUWEI, TokenType.GU,
909
- TokenType.PIN, TokenType.ROU, TokenType.PU,
910
- TokenType.ZHI, TokenType.ZHIZU,
911
- )
912
- while (self.current_token and
913
- self.current_token.type not in _EXPR_STOP and
914
- not self._is_at_end()):
915
- parts.append(self.current_token.value)
916
- self._advance()
917
- return LiteralNode("".join(parts).strip(), "string")
918
-
919
- def _parse_binary_tail(self, left: ASTNode) -> ASTNode:
920
- """解析二元算术尾部:left [+|-|*|/] right(右结合单级,满足循环体自增语义)"""
921
- if self.current_token and self.current_token.type in (
922
- TokenType.OP_ADD, TokenType.OP_SUB,
923
- TokenType.OP_MUL, TokenType.OP_DIV,
924
- ):
925
- op_token = self.current_token
926
- op_map = {
927
- TokenType.OP_ADD: "+", TokenType.OP_SUB: "-",
928
- TokenType.OP_MUL: "*", TokenType.OP_DIV: "/",
929
- }
930
- op = op_map[op_token.type]
931
- self._advance()
932
- right = self._parse_expression()
933
- return BinaryExprNode(left, op, right,
934
- line=op_token.line, column=op_token.column)
935
- return left
936
-
937
- # ---- 辅助方法 ----
938
-
939
- def _is_at_end(self) -> bool:
940
- """指针越界探测:True=已消费全部 token。"""
941
- return self.pos >= len(self.tokens) or (
942
- self.current_token is not None and self.current_token.type == TokenType.EOF
943
- )
944
-
945
- def _advance(self) -> Optional[Token]:
946
- """消费当前 token 并前进一格。"""
947
- if self.pos < len(self.tokens) - 1:
948
- self.pos += 1
949
- self.current_token = self.tokens[self.pos]
950
- elif self.pos == len(self.tokens) - 1:
951
- self.pos += 1
952
- self.current_token = None
953
- return self.current_token
954
-
955
- def _peek_next(self) -> Optional[Token]:
956
- """查看下一个 token(不消费)"""
957
- if self.pos < len(self.tokens) - 1:
958
- return self.tokens[self.pos + 1]
959
- return None
960
-
961
- def _match(self, *types: TokenType) -> bool:
962
- """类型相符即消费返回 True,否则 False。"""
963
- if self.current_token and self.current_token.type in types:
964
- self._advance()
965
- return True
966
- return False
967
-
968
- def _consume(self, token_type: TokenType, message: str) -> Optional[Token]:
969
- """消费当前 token:类型相符即前进返回,否则带行列定位报错。"""
970
- if self.current_token and self.current_token.type == token_type:
971
- token = self.current_token
972
- self._advance()
973
- return token
974
- else:
975
- loc = f"L{self.current_token.line}:C{self.current_token.column}" if self.current_token else "EOF"
976
- self.errors.append(f"{loc} {message},实际得到: '{self.current_token.value if self.current_token else 'EOF'}'")
977
- return None
978
-
979
- def _collect_until(self, *stop_types: TokenType) -> List[Token]:
980
- """收集 Token 直到遇到停止类型"""
981
- parts = []
982
- while (self.current_token and
983
- self.current_token.type not in stop_types and
984
- self.current_token.type != TokenType.EOF):
985
- if self.current_token.type == TokenType.COLON:
986
- self._advance()
987
- continue
988
- parts.append(self.current_token)
989
- self._advance()
990
- return parts
991
-
992
-
993
- # =============================================================================
994
- # 便捷函数
995
- # =============================================================================
996
-
997
- def parse_tokens(tokens: List[Token], errors: List[str] = None) -> ProgramNode:
998
- """便捷函数:将 Token 列表解析为 AST"""
999
- parser = Parser(tokens, errors or [])
1000
- return parser.parse()
1001
-
1002
-
1003
- def parse_source(source: str) -> tuple:
1004
- """便捷函数:从源代码直接解析为 AST"""
1005
- from .lexer import tokenize
1006
- tokens, lex_errors = tokenize(source)
1007
- ast = parse_tokens(tokens, [])
1008
- return ast, lex_errors, ast.errors if hasattr(ast, 'errors') else []
1009
-
1010
-
1011
- # =============================================================================
1012
- # 测试
1013
- # =============================================================================
1014
-
1015
- if __name__ == "__main__":
1016
- test_code = """若条件空间为伴侣,则止情感权重于0.15。
1017
- 道 新信任路径
1018
- 德 累积信任值
1019
- 问曰:如何验证信任?
1020
- 答曰:信任值大于0.7。
1021
- 术曰:1。柔 响应强度;2。自然 恢复默认;3。知足 验证单元。"""
1022
-
1023
- print("=" * 60)
1024
- print("语法分析器 v2.0 测试")
1025
- print("=" * 60)
1026
- print(f"源代码:\n{test_code}\n")
1027
-
1028
- from .lexer import tokenize
1029
- tokens, lex_errors = tokenize(test_code)
1030
-
1031
- if lex_errors:
1032
- print("词法错误:")
1033
- for e in lex_errors:
1034
- print(f" ❌ {e}")
1035
-
1036
- parser = Parser(tokens, [])
1037
- ast = parser.parse()
1038
-
1039
- print(f"\nAST 根节点:{ast.type.name}")
1040
- print(f"语句数量:{len(ast.statements)}")
1041
- print()
1042
-
1043
- for i, stmt in enumerate(ast.statements):
1044
- print(f" 语句{i+1}: {stmt.type.name}")
1045
- if stmt.type == NodeType.SHUYUE:
1046
- print(f" 问题: {stmt.attributes.get('question', '')}")
1047
- print(f" 答案: {stmt.attributes.get('answer', '')}")
1048
- for step in stmt.steps:
1049
- op_count = len(step.statement.children) if step.statement else 0
1050
- print(f" 步骤{step.step_num}: {step.statement.type.name if step.statement else 'None'}")
1051
- elif stmt.type == NodeType.INSTRUCTION_STMT:
1052
- op_names = []
1053
- for op in stmt.operands:
1054
- if hasattr(op, 'name'):
1055
- op_names.append(f"ID({op.name})")
1056
- elif hasattr(op, 'literal_value'):
1057
- op_names.append(f"Lit({op.literal_value})")
1058
- print(f" 操作数: [{', '.join(op_names)}]")
1059
-
1060
- if parser.errors:
1061
- print(f"\n语法错误:")
1062
- for e in parser.errors:
1063
- print(f" ❌ {e}")
1064
-
1065
- print(f"\n总计:{len(parser.errors)} 个语法错误")
1
+ """
2
+ parser.py · 语法分析器 v2.0
3
+ 将 Token 序列构建为抽象语法树(AST)
4
+ 支持:条件语句、指令语句、九章算术结构
5
+
6
+ v2.0 变更:
7
+ - 新增 _merge_identifiers:合并紧密相连的 IDENTIFIER/NUMBER 序列
8
+ - 修复"道 新信任路径"被切成多个操作数的问题
9
+ - 支持"止 X 于 Y"结构中的多词 X
10
+ """
11
+
12
+ from enum import Enum, auto
13
+ from dataclasses import dataclass, field
14
+ from typing import List, Optional, Union, Any, Tuple
15
+ from .lexer import Token, TokenType
16
+
17
+
18
+ # =============================================================================
19
+ # AST 节点类型
20
+ # =============================================================================
21
+
22
+ class NodeType(Enum):
23
+ """AST 节点类型"""
24
+
25
+ # === 顶层 ===
26
+ PROGRAM = auto() # 整个程序
27
+
28
+ # === 九章算术结构 ===
29
+ WENYUE = auto() # 问曰
30
+ DAYUE = auto() # 答曰
31
+ SHUYUE = auto() # 术曰
32
+ STEP = auto() # 步骤(序号.操作)
33
+
34
+ # === 语句 ===
35
+ CONDITION_STMT = auto() # 条件语句(若...则...)
36
+ LOOP_STMT = auto() # 循环语句(当...执行...)
37
+ BLOCK = auto() # 语句块(多条顺序语句)
38
+ FUNC_DEF = auto() # 函数定义(定义 名(参数):语句)
39
+ RETURN_STMT = auto() # 返回语句(返回 表达式)
40
+ ASSIGN_STMT = auto() # 赋值语句
41
+ INSTRUCTION_STMT = auto() # 指令语句(道德经助记符)
42
+ OPERATION_STMT = auto() # 操作语句
43
+
44
+ # === 表达式 ===
45
+ BINARY_EXPR = auto() # 二元表达式
46
+ UNARY_EXPR = auto() # 一元表达式
47
+ IDENTIFIER = auto() # 标识符
48
+ LITERAL = auto() # 字面量
49
+ CALL_EXPR = auto() # 调用表达式
50
+
51
+ # === 条件 ===
52
+ COMPARISON = auto() # 比较表达式
53
+
54
+
55
+ # =============================================================================
56
+ # AST 节点定义
57
+ # =============================================================================
58
+
59
+ @dataclass
60
+ class ASTNode:
61
+ """AST 节点基类"""
62
+ type: NodeType
63
+ line: int = 1
64
+ column: int = 1
65
+ children: List['ASTNode'] = field(default_factory=list)
66
+ value: Any = None
67
+ attributes: dict = field(default_factory=dict)
68
+
69
+ def add_child(self, child: 'ASTNode'):
70
+ """追加子节点(None 直接忽略)。"""
71
+ if child is not None:
72
+ self.children.append(child)
73
+
74
+ def __repr__(self) -> str:
75
+ """AST 节点调试表示:类型与子节点概览。"""
76
+ return f"ASTNode({self.type.name}, value={self.value!r}, children={len(self.children)})"
77
+
78
+
79
+ @dataclass
80
+ class ProgramNode(ASTNode):
81
+ """程序根节点"""
82
+ def __init__(self, line: int = 1, column: int = 1):
83
+ """构造 ProgramNode:绑定本节点的声明字段与子结构。"""
84
+ super().__init__(NodeType.PROGRAM, line, column)
85
+ self.statements: List[ASTNode] = []
86
+
87
+ def add_statement(self, stmt: ASTNode):
88
+ """追加语句并同时挂入子树。"""
89
+ if stmt is not None:
90
+ self.statements.append(stmt)
91
+ self.add_child(stmt)
92
+
93
+
94
+ @dataclass
95
+ class WenyueNode(ASTNode):
96
+ """问曰节点"""
97
+ def __init__(self, question: str, line: int = 1, column: int = 1):
98
+ """构造 WenyueNode:绑定本节点的声明字段与子结构。"""
99
+ super().__init__(NodeType.WENYUE, line, column)
100
+ self.question = question
101
+ self.value = question
102
+
103
+
104
+ @dataclass
105
+ class DayueNode(ASTNode):
106
+ """答曰节点"""
107
+ def __init__(self, answer: str, line: int = 1, column: int = 1):
108
+ """构造 DayueNode:绑定本节点的声明字段与子结构。"""
109
+ super().__init__(NodeType.DAYUE, line, column)
110
+ self.answer = answer
111
+ self.value = answer
112
+
113
+
114
+ @dataclass
115
+ class ShuyueNode(ASTNode):
116
+ """术曰节点"""
117
+ def __init__(self, line: int = 1, column: int = 1):
118
+ """构造 ShuyueNode:绑定本节点的声明字段与子结构。"""
119
+ super().__init__(NodeType.SHUYUE, line, column)
120
+ self.steps: List['StepNode'] = []
121
+
122
+ def add_step(self, step: 'StepNode'):
123
+ """追加步骤节点并挂入子树。"""
124
+ self.steps.append(step)
125
+ self.add_child(step)
126
+
127
+
128
+ @dataclass
129
+ class StepNode(ASTNode):
130
+ """步骤节点"""
131
+ def __init__(self, step_num: int, statement: ASTNode, line: int = 1, column: int = 1):
132
+ """构造 StepNode:绑定本节点的声明字段与子结构。"""
133
+ super().__init__(NodeType.STEP, line, column)
134
+ self.step_num = step_num
135
+ self.statement = statement
136
+ self.add_child(statement)
137
+
138
+
139
+ @dataclass
140
+ class ConditionStmtNode(ASTNode):
141
+ """条件语句:若 [条件] 则 [操作] [否则 [操作]](body 可为语句列表)"""
142
+ def __init__(self, condition: ASTNode, then_body, else_body=None,
143
+ line: int = 1, column: int = 1):
144
+ """构造 ConditionStmtNode:绑定本节点的声明字段与子结构。"""
145
+ super().__init__(NodeType.CONDITION_STMT, line, column)
146
+ self.condition = condition
147
+ self.then_body = then_body
148
+ self.else_body = else_body
149
+ self.add_child(condition)
150
+ self.add_child(then_body)
151
+ if else_body is not None:
152
+ self.add_child(else_body)
153
+
154
+
155
+ @dataclass
156
+ class LoopStmtNode(ASTNode):
157
+ """循环语句:当 [条件] 执行 [操作](while 语义,body 可为语句列表)"""
158
+ def __init__(self, condition: ASTNode, body, line: int = 1, column: int = 1):
159
+ """构造 LoopStmtNode:绑定本节点的声明字段与子结构。"""
160
+ super().__init__(NodeType.LOOP_STMT, line, column)
161
+ self.condition = condition
162
+ self.body = body
163
+ self.add_child(condition)
164
+ self.add_child(body)
165
+
166
+
167
+ @dataclass
168
+ class BlockNode(ASTNode):
169
+ """语句块:多条顺序执行的语句(循环体/条件体多语句支持)"""
170
+ def __init__(self, statements, line: int = 1, column: int = 1):
171
+ """构造 BlockNode:绑定本节点的声明字段与子结构。"""
172
+ super().__init__(NodeType.BLOCK, line, column)
173
+ self.statements = statements
174
+ for s in statements:
175
+ self.add_child(s)
176
+
177
+
178
+ @dataclass
179
+ class FuncDefNode(ASTNode):
180
+ """函数定义:定义 名(参数):语句(body 可为语句列表)"""
181
+ def __init__(self, name: str, params: List[str], body, line: int = 1, column: int = 1):
182
+ """构造 FuncDefNode:绑定本节点的声明字段与子结构。"""
183
+ super().__init__(NodeType.FUNC_DEF, line, column)
184
+ self.name = name
185
+ self.params = params
186
+ self.body = body
187
+ self.add_child(body)
188
+
189
+
190
+ @dataclass
191
+ class ReturnStmtNode(ASTNode):
192
+ """返回语句:返回 [表达式]"""
193
+ def __init__(self, value: Optional[ASTNode], line: int = 1, column: int = 1):
194
+ """构造 ReturnStmtNode:绑定本节点的声明字段与子结构。"""
195
+ super().__init__(NodeType.RETURN_STMT, line, column)
196
+ self.value = value
197
+ if value:
198
+ self.add_child(value)
199
+
200
+
201
+ @dataclass
202
+ class CallExprNode(ASTNode):
203
+ """函数调用:名(参数1,参数2)"""
204
+ def __init__(self, name: str, args: List[ASTNode], line: int = 1, column: int = 1):
205
+ """构造 CallExprNode:绑定本节点的声明字段与子结构。"""
206
+ super().__init__(NodeType.CALL_EXPR, line, column)
207
+ self.name = name
208
+ self.args = args
209
+ for a in args:
210
+ self.add_child(a)
211
+
212
+
213
+ @dataclass
214
+ class InstructionStmtNode(ASTNode):
215
+ """指令语句:道德经助记符 + 操作数"""
216
+ def __init__(self, instruction: TokenType, operands: List[ASTNode] = None,
217
+ line: int = 1, column: int = 1):
218
+ """构造 InstructionStmtNode:绑定本节点的声明字段与子结构。"""
219
+ super().__init__(NodeType.INSTRUCTION_STMT, line, column)
220
+ self.instruction = instruction
221
+ self.operands = operands or []
222
+ for op in self.operands:
223
+ self.add_child(op)
224
+
225
+
226
+ @dataclass
227
+ class AssignStmtNode(ASTNode):
228
+ """赋值语句:标识符 = 值"""
229
+ def __init__(self, target: str, value: ASTNode, line: int = 1, column: int = 1):
230
+ """构造 AssignStmtNode:绑定本节点的声明字段与子结构。"""
231
+ super().__init__(NodeType.ASSIGN_STMT, line, column)
232
+ self.target = target
233
+ self.value_node = value
234
+ self.add_child(value)
235
+
236
+
237
+ @dataclass
238
+ class BinaryExprNode(ASTNode):
239
+ """二元表达式:左 操作符 右"""
240
+ def __init__(self, left: ASTNode, operator: str, right: ASTNode,
241
+ line: int = 1, column: int = 1):
242
+ """构造 BinaryExprNode:绑定本节点的声明字段与子结构。"""
243
+ super().__init__(NodeType.BINARY_EXPR, line, column)
244
+ self.left = left
245
+ self.operator = operator
246
+ self.right = right
247
+ self.add_child(left)
248
+ self.add_child(right)
249
+
250
+
251
+ @dataclass
252
+ class ComparisonNode(ASTNode):
253
+ """比较表达式"""
254
+ def __init__(self, left: ASTNode, op: str, right: ASTNode,
255
+ line: int = 1, column: int = 1):
256
+ """构造 ComparisonNode:绑定本节点的声明字段与子结构。"""
257
+ super().__init__(NodeType.COMPARISON, line, column)
258
+ self.left = left
259
+ self.op = op
260
+ self.right = right
261
+ self.add_child(left)
262
+ self.add_child(right)
263
+
264
+
265
+ @dataclass
266
+ class IdentifierNode(ASTNode):
267
+ """标识符"""
268
+ def __init__(self, name: str, line: int = 1, column: int = 1):
269
+ """构造 IdentifierNode:绑定本节点的声明字段与子结构。"""
270
+ super().__init__(NodeType.IDENTIFIER, line, column)
271
+ self.name = name
272
+ self.value = name
273
+
274
+
275
+ @dataclass
276
+ class LiteralNode(ASTNode):
277
+ """字面量"""
278
+ def __init__(self, value: Union[str, float, int], literal_type: str,
279
+ line: int = 1, column: int = 1):
280
+ """构造 LiteralNode:绑定本节点的声明字段与子结构。"""
281
+ super().__init__(NodeType.LITERAL, line, column)
282
+ self.literal_value = value
283
+ self.literal_type = literal_type # "number", "string"
284
+ self.value = value
285
+
286
+
287
+ # =============================================================================
288
+ # 语法分析器
289
+ # =============================================================================
290
+
291
+ class Parser:
292
+ """
293
+ 语法分析器 v2.0
294
+ 将 Token 序列构建为 AST
295
+ """
296
+
297
+ # 指令助记符集合
298
+ INSTRUCTION_TOKENS = {
299
+ TokenType.DAO, TokenType.DE, TokenType.ZIRAN,
300
+ TokenType.WUWEI, TokenType.GU, TokenType.PIN,
301
+ TokenType.ROU, TokenType.PU, TokenType.ZHI, TokenType.ZHIZU,
302
+ }
303
+
304
+ def __init__(self, tokens: List[Token], errors: List[str] = None):
305
+ """构造 Parser:绑定本节点的声明字段与子结构。"""
306
+ self.tokens = tokens
307
+ self.pos = 0
308
+ self.errors: List[str] = errors or []
309
+ self.current_token = self.tokens[0] if tokens else None
310
+
311
+ def parse(self) -> ProgramNode:
312
+ """解析整个程序"""
313
+ program = ProgramNode()
314
+
315
+ while not self._is_at_end():
316
+ if self._match(TokenType.NEWLINE, TokenType.SEMICOLON, TokenType.COMMA):
317
+ continue
318
+
319
+ stmt = self._parse_statement()
320
+ if stmt:
321
+ program.add_statement(stmt)
322
+ # DEBUG
323
+ # print(f" [parse] Added: type={stmt.type.name} value={stmt.value!r}")
324
+ # if hasattr(stmt, 'operands'):
325
+ # for j, op in enumerate(stmt.operands):
326
+ # print(f" op{j}: {op.type.name} value={op.value!r}")
327
+ else:
328
+ # print(f" [parse] None at {self.current_token}")
329
+ self._advance()
330
+
331
+ return program
332
+
333
+ # ---- 语句解析 ----
334
+
335
+ def _parse_statement(self) -> Optional[ASTNode]:
336
+ """解析单个语句"""
337
+ token = self.current_token
338
+
339
+ if token is None or token.type == TokenType.EOF:
340
+ return None
341
+
342
+ # 问曰 → 答曰 → 术曰(九章算术结构)
343
+ if token.type == TokenType.WENYUE:
344
+ return self._parse_wenyue_block()
345
+
346
+ # 术曰 → 术曰块(可以独立出现)
347
+ if token.type == TokenType.SHUYUE:
348
+ return self._parse_shuyue_block()
349
+
350
+ # 若 → 条件语句
351
+ if token.type == TokenType.RUO:
352
+ return self._parse_condition()
353
+
354
+ # 当 → 循环语句(白箱循环语法:当 条件 执行 操作)
355
+ if token.type == TokenType.DANG:
356
+ return self._parse_loop()
357
+
358
+ # 定义 → 函数定义(定义 名(参数):语句)
359
+ if token.type == TokenType.DINGYI:
360
+ return self._parse_func_def()
361
+
362
+ # 返回 → 返回语句(返回 表达式)
363
+ if token.type == TokenType.FANHUI:
364
+ self._advance()
365
+ val = self._parse_expression() if self.current_token else None
366
+ return ReturnStmtNode(val,
367
+ line=token.line, column=token.column)
368
+
369
+ # 道德经助记符 → 指令语句
370
+ if token.type in self.INSTRUCTION_TOKENS:
371
+ return self._parse_instruction()
372
+
373
+ # 标识符 → 可能是赋值
374
+ if token.type == TokenType.IDENTIFIER:
375
+ return self._parse_assign_or_call()
376
+
377
+ # 句号结束
378
+ if token.type == TokenType.PERIOD:
379
+ self._advance()
380
+ return None
381
+
382
+ # 无法识别
383
+ self.errors.append(
384
+ f"L{token.line}:C{token.column} 无法解析的语句开头: '{token.value}' ({token.type.name})"
385
+ )
386
+ self._advance()
387
+ return None
388
+
389
+ def _parse_shuyue_block(self) -> Optional[ASTNode]:
390
+ """
391
+ 解析术曰块(独立形式):术曰:1。... 2。...
392
+ 不依赖前面的问曰/答曰
393
+ """
394
+ self._consume(TokenType.SHUYUE, "期望 '术曰'")
395
+
396
+ shuyue = ShuyueNode(line=self.current_token.line if self.current_token else 1,
397
+ column=self.current_token.column if self.current_token else 1)
398
+
399
+ # 解析步骤序列
400
+ while not self._is_at_end():
401
+ # 跳过分隔符
402
+ while (self.current_token and
403
+ self.current_token.type in (TokenType.SEMICOLON,
404
+ TokenType.COMMA,
405
+ TokenType.COLON)):
406
+ self._advance()
407
+
408
+ if self.current_token and self.current_token.type == TokenType.NUMBER:
409
+ step_num = int(float(self.current_token.value))
410
+ self._advance()
411
+
412
+ if self.current_token and self.current_token.type == TokenType.PERIOD:
413
+ self._advance()
414
+
415
+ step_content = self._parse_step_content()
416
+ if step_content:
417
+ shuyue.add_step(StepNode(step_num, step_content,
418
+ line=step_content.line,
419
+ column=step_content.column))
420
+ else:
421
+ break
422
+
423
+ return shuyue
424
+
425
+ def _parse_wenyue_block(self) -> Optional[ASTNode]:
426
+ """解析 问曰:... 答曰:... 术曰:... 结构"""
427
+ # 问曰
428
+ self._consume(TokenType.WENYUE, "期望 '问曰'")
429
+ question_parts = self._collect_until(TokenType.DAYUE)
430
+ question = "".join(p.value for p in question_parts).strip()
431
+
432
+ # 答曰
433
+ self._consume(TokenType.DAYUE, "期望 '答曰'")
434
+ answer_parts = self._collect_until(TokenType.SHUYUE)
435
+ answer = "".join(p.value for p in answer_parts).strip()
436
+
437
+ # 术曰
438
+ self._consume(TokenType.SHUYUE, "期望 '术曰'")
439
+
440
+ # 用独立的术曰解析逻辑
441
+ shuyue = ShuyueNode(line=self.current_token.line if self.current_token else 1,
442
+ column=self.current_token.column if self.current_token else 1)
443
+
444
+ while not self._is_at_end():
445
+ # 跳过分隔符
446
+ while (self.current_token and
447
+ self.current_token.type in (TokenType.SEMICOLON,
448
+ TokenType.COMMA,
449
+ TokenType.COLON)):
450
+ self._advance()
451
+
452
+ if self.current_token and self.current_token.type == TokenType.NUMBER:
453
+ step_num = int(float(self.current_token.value))
454
+ self._advance()
455
+
456
+ if self.current_token and self.current_token.type == TokenType.PERIOD:
457
+ self._advance()
458
+
459
+ step_content = self._parse_step_content()
460
+ if step_content:
461
+ shuyue.add_step(StepNode(step_num, step_content,
462
+ line=step_content.line,
463
+ column=step_content.column))
464
+ else:
465
+ break
466
+
467
+ shuyue.attributes["question"] = question
468
+ shuyue.attributes["answer"] = answer
469
+
470
+ return shuyue
471
+
472
+ def _parse_step_content(self) -> Optional[ASTNode]:
473
+ """解析步骤内容"""
474
+ if self.current_token and self.current_token.type == TokenType.RUO:
475
+ return self._parse_condition()
476
+ elif self.current_token and self.current_token.type == TokenType.DANG:
477
+ return self._parse_loop()
478
+ elif self.current_token and self.current_token.type == TokenType.DINGYI:
479
+ return self._parse_func_def()
480
+ elif self.current_token and self.current_token.type == TokenType.FANHUI:
481
+ self._advance()
482
+ val = self._parse_expression() if self.current_token else None
483
+ return ReturnStmtNode(val, line=1, column=1)
484
+ elif self.current_token and self.current_token.type in self.INSTRUCTION_TOKENS:
485
+ return self._parse_instruction()
486
+ elif self.current_token and self.current_token.type == TokenType.IDENTIFIER:
487
+ # 可能是单个标识符或合并后的多词短语
488
+ #
489
+ # issue #326-②(2026-10-14):本函数是 compiler/parser.py 的**孪生副本**,
490
+ # 而该处修复(2026-09-14)长期**未回移**——两条链对同一中文源码产出
491
+ # **不同字节码**:本副本原先无条件走 _merge_identifiers()(多词短语
492
+ # 合并),从不探视其后是否紧跟 = 或 (,于是「1。计数 = 0;」只留下裸
493
+ # 标识符 计数、`= 0` 被丢掉,且**不报错**——只降级为一条 warning
494
+ # 「L2 未编译语句类型: IDENTIFIER」,即静默错值(比崩溃更危险)。
495
+ # 实测复现:compiler/ 14 条指令(含 PUSH_CONST 0.0; STORE_NAME 计数),
496
+ # 本副本 12 条且初始化缺失。
497
+ # 回移 lookahead(与 compiler/parser.py 同款):下一个 token 是 = 或 (
498
+ # 则走 _parse_assign_or_call,否则保持原多词合并行为(「道 新信任路径」
499
+ # 等短语不受影响)。双链字节码等价性由守卫
500
+ # md_cg/test_issue326_twin_parser_parity.py 回归守护。
501
+ _nxt = self._peek_next()
502
+ if _nxt is not None and _nxt.type in (TokenType.EQUALS,
503
+ TokenType.LPAREN):
504
+ return self._parse_assign_or_call()
505
+ merged = self._merge_identifiers()
506
+ return merged
507
+ else:
508
+ parts = []
509
+ while (self.current_token and
510
+ self.current_token.type not in (TokenType.NUMBER, TokenType.PERIOD) and
511
+ not self._is_at_end()):
512
+ parts.append(self.current_token.value)
513
+ self._advance()
514
+ if parts:
515
+ return LiteralNode("".join(parts).strip(), "string",
516
+ line=self.current_token.line if self.current_token else 1,
517
+ column=self.current_token.column if self.current_token else 1)
518
+ return None
519
+
520
+ def _parse_condition(self) -> Optional[ASTNode]:
521
+ """解析条件语句:若 [条件] 则 [操作] [否则 [操作]]"""
522
+ start_line = self.current_token.line if self.current_token else 1
523
+ start_col = self.current_token.column if self.current_token else 1
524
+
525
+ self._consume(TokenType.RUO, "期望 '若'")
526
+
527
+ condition = self._parse_comparison()
528
+
529
+ self._skip_punctuation_before(TokenType.ZE)
530
+
531
+ self._consume(TokenType.ZE, "期望 '则'")
532
+
533
+ then_body = self._parse_single_statement()
534
+
535
+ else_body = None
536
+ # 跳过 then 与 否则 之间的分隔符(逗号/分号等)
537
+ self._skip_punctuation_before(TokenType.FOUZE)
538
+ if self.current_token and self.current_token.type == TokenType.FOUZE:
539
+ self._advance()
540
+ else_body = self._parse_single_statement()
541
+
542
+ return ConditionStmtNode(condition, then_body, else_body, start_line, start_col)
543
+
544
+ def _parse_loop(self) -> Optional[ASTNode]:
545
+ """解析循环语句:当 [条件] 执行 [操作](while 语义)"""
546
+ start_line = self.current_token.line if self.current_token else 1
547
+ start_col = self.current_token.column if self.current_token else 1
548
+
549
+ self._consume(TokenType.DANG, "期望 '当'")
550
+
551
+ condition = self._parse_comparison()
552
+
553
+ self._skip_punctuation_before(TokenType.ZHIXING)
554
+
555
+ self._consume(TokenType.ZHIXING, "期望 '执行'")
556
+
557
+ body = self._parse_statement_or_block()
558
+
559
+ return LoopStmtNode(condition, body, start_line, start_col)
560
+
561
+ def _parse_func_def(self) -> Optional[ASTNode]:
562
+ """解析函数定义:定义 名(参数1,参数2):语句
563
+ 参数在( )内,逗号分隔;返回 FuncDefNode(body 可为块)"""
564
+ start_line = self.current_token.line if self.current_token else 1
565
+ start_col = self.current_token.column if self.current_token else 1
566
+
567
+ self._consume(TokenType.DINGYI, "期望 '定义'")
568
+
569
+ # 函数名(标识符)
570
+ if not (self.current_token and self.current_token.type == TokenType.IDENTIFIER):
571
+ self.errors.append("定义后期望函数名")
572
+ return None
573
+ name = self.current_token.value
574
+ self._advance()
575
+
576
+ # 参数列表( )
577
+ params = []
578
+ if self.current_token and self.current_token.type == TokenType.LPAREN:
579
+ self._advance()
580
+ while (self.current_token and
581
+ self.current_token.type != TokenType.RPAREN and
582
+ not self._is_at_end()):
583
+ if self.current_token.type == TokenType.IDENTIFIER:
584
+ params.append(self.current_token.value)
585
+ self._advance() # 跳过标识符/逗号/空格
586
+ if self.current_token and self.current_token.type == TokenType.RPAREN:
587
+ self._advance()
588
+
589
+ # 冒号(可选分隔)
590
+ if self.current_token and self.current_token.type == TokenType.COLON:
591
+ self._advance()
592
+
593
+ body = self._parse_single_statement()
594
+
595
+ return FuncDefNode(name, params, body, start_line, start_col)
596
+
597
+ def _skip_punctuation_before(self, *target_types: TokenType):
598
+ """跳过标点符号"""
599
+ while self.current_token and self.current_token.type in (
600
+ TokenType.COMMA, TokenType.PERIOD, TokenType.SEMICOLON,
601
+ TokenType.COLON, TokenType.QUESTION, TokenType.EXCLAM,
602
+ ):
603
+ self._advance()
604
+
605
+ def _parse_statement_or_block(self) -> Any:
606
+ """解析语句或块:返回语句列表(单语句=[stmt];分号/句号分隔多条)
607
+ 块内多条语句:`则 语句1;语句2;...`(支持循环体/条件体多语句)"""
608
+ stmts = []
609
+ while True:
610
+ stmt = self._parse_single_statement()
611
+ if stmt is not None:
612
+ stmts.append(stmt)
613
+ # 分隔符:分号/句号 → 继续收下一条;否则块结束
614
+ if self.current_token and self.current_token.type in (
615
+ TokenType.SEMICOLON, TokenType.PERIOD, TokenType.COMMA):
616
+ self._advance()
617
+ # 分隔符后若是步骤号/块边界 → 块结束(九章算术步骤边界 1。…2。…)
618
+ if (self.current_token and
619
+ self.current_token.type in (TokenType.NUMBER, TokenType.SHUYUE)):
620
+ break
621
+ continue
622
+ break
623
+ if not stmts:
624
+ return None
625
+ if len(stmts) == 1:
626
+ return stmts[0]
627
+ return BlockNode(stmts, line=stmts[0].line, column=stmts[0].column)
628
+
629
+ def _parse_single_statement(self) -> Optional[ASTNode]:
630
+ """解析单条语句"""
631
+ if self.current_token and self.current_token.type == TokenType.RUO:
632
+ return self._parse_condition()
633
+ elif self.current_token and self.current_token.type == TokenType.DANG:
634
+ return self._parse_loop()
635
+ elif self.current_token and self.current_token.type == TokenType.DINGYI:
636
+ return self._parse_func_def()
637
+ elif self.current_token and self.current_token.type == TokenType.FANHUI:
638
+ self._advance()
639
+ val = self._parse_expression() if self.current_token else None
640
+ return ReturnStmtNode(val, line=1, column=1)
641
+ elif self.current_token and self.current_token.type in self.INSTRUCTION_TOKENS:
642
+ return self._parse_instruction()
643
+ elif self.current_token and self.current_token.type == TokenType.IDENTIFIER:
644
+ return self._parse_assign_or_call()
645
+ else:
646
+ parts = []
647
+ # 停止条件:标点符号 + 语句开头关键字
648
+ _STOP = (
649
+ TokenType.PERIOD, TokenType.COMMA, TokenType.SEMICOLON,
650
+ TokenType.WENYUE, TokenType.DAYUE, TokenType.SHUYUE,
651
+ TokenType.RUO, TokenType.FOUZE, TokenType.DANG,
652
+ TokenType.ZHIXING,
653
+ )
654
+ while (self.current_token and
655
+ self.current_token.type not in _STOP and
656
+ not self._is_at_end()):
657
+ parts.append(self.current_token.value)
658
+ self._advance()
659
+ text = "".join(parts).strip()
660
+ if text:
661
+ return LiteralNode(text, "string")
662
+ return None
663
+
664
+ def _parse_instruction(self) -> Optional[ASTNode]:
665
+ """
666
+ 解析指令语句 v2.0
667
+
668
+ 关键改进:使用 _merge_identifiers 合并紧密相连的
669
+ IDENTIFIER/NUMBER 序列为一个逻辑操作数。
670
+
671
+ 例:道 新信任路径 → 道 + [ID(新信任路径)]
672
+ 例:柔 响应强度 → 柔 + [ID(响应强度)]
673
+ 例:止情感权重于0.15 → 止 + [ID(情感权重)] + [Lit(0.15)]
674
+ """
675
+ instr_token = self.current_token
676
+ instr_type = instr_token.type
677
+ self._advance()
678
+
679
+ operands = []
680
+
681
+ # 停止条件:标点符号 + 语句开头关键字(防止跨语句吞噬)
682
+ _INST_STOP = (
683
+ TokenType.PERIOD, TokenType.COMMA, TokenType.SEMICOLON,
684
+ TokenType.EOF,
685
+ # 语句开头关键字 —— 遇到这些说明指令操作数已结束
686
+ TokenType.WENYUE, # 问曰 → 新语句
687
+ TokenType.DAYUE, # 答曰 → 新语句
688
+ TokenType.SHUYUE, # 术曰 → 新语句
689
+ TokenType.RUO, # 若 → 条件语句
690
+ TokenType.FOUZE, # 否则 → 条件语句
691
+ TokenType.DAO, # 道 → 指令(但不在操作数位置)
692
+ TokenType.DE, # 德 → 指令
693
+ TokenType.ZIRAN, # 自然 → 指令
694
+ TokenType.WUWEI, # 无为 → 指令
695
+ TokenType.GU, # 谷 → 指令
696
+ TokenType.PIN, # 牝 → 指令
697
+ TokenType.ROU, # 柔 → 指令
698
+ TokenType.PU, # 朴 → 指令
699
+ TokenType.ZHI, # 止 → 指令
700
+ TokenType.ZHIZU, # 知足 → 指令
701
+ )
702
+
703
+ while (self.current_token and
704
+ self.current_token.type not in _INST_STOP and
705
+ not self._is_at_end()):
706
+
707
+ tok = self.current_token
708
+
709
+ if tok.type == TokenType.YU:
710
+ # "于" → 后面跟数值
711
+ self._advance()
712
+ value = self._parse_numeric_value()
713
+ if value is not None:
714
+ operands.append(value)
715
+ continue
716
+
717
+ elif tok.type == TokenType.IDENTIFIER:
718
+ # 合并后续紧密相连的 IDENTIFIER/NUMBER
719
+ merged = self._merge_identifiers()
720
+ operands.append(merged)
721
+
722
+ elif tok.type == TokenType.NUMBER:
723
+ operands.append(LiteralNode(float(tok.value), "number", tok.line, tok.column))
724
+ self._advance()
725
+
726
+ elif tok.type == TokenType.STRING:
727
+ operands.append(LiteralNode(tok.value, "string", tok.line, tok.column))
728
+ self._advance()
729
+
730
+ else:
731
+ self._advance()
732
+
733
+ return InstructionStmtNode(instr_type, operands,
734
+ line=instr_token.line,
735
+ column=instr_token.column)
736
+
737
+ def _merge_identifiers(self) -> ASTNode:
738
+ """
739
+ 合并从当前位置开始的紧密相连的 IDENTIFIER/NUMBER 序列
740
+
741
+ 例:ID(新) ID(信任) ID(路径) → IdentifierNode("新信任路径")
742
+ 例:ID(响应) ID(强度) → IdentifierNode("响应强度")
743
+ 例:ID(累积) ID(信任值) → IdentifierNode("累积信任值")
744
+
745
+ 判断标准:同一行、列号连续
746
+ """
747
+ start_tok = self.current_token
748
+ parts = [start_tok.value]
749
+ line = start_tok.line
750
+ col = start_tok.column
751
+ self._advance()
752
+
753
+ while (self.current_token and
754
+ self.current_token.line == line and
755
+ self.current_token.type in (TokenType.IDENTIFIER, TokenType.NUMBER)):
756
+ parts.append(self.current_token.value)
757
+ self._advance()
758
+
759
+ merged_name = "".join(parts)
760
+ return IdentifierNode(merged_name, line, col)
761
+
762
+ def _parse_numeric_value(self) -> Optional[ASTNode]:
763
+ """解析数值(可能跨多个 token)"""
764
+ if self.current_token is None:
765
+ return None
766
+
767
+ if self.current_token.type == TokenType.NUMBER:
768
+ val = float(self.current_token.value)
769
+ line, col = self.current_token.line, self.current_token.column
770
+ self._advance()
771
+ return LiteralNode(val, "number", line, col)
772
+
773
+ if self.current_token.type == TokenType.IDENTIFIER:
774
+ prefix = self.current_token.value
775
+ line, col = self.current_token.line, self.current_token.column
776
+ self._advance()
777
+
778
+ if self.current_token and self.current_token.type == TokenType.PERIOD:
779
+ self._advance()
780
+ if self.current_token and self.current_token.type == TokenType.NUMBER:
781
+ val = float(prefix + "." + self.current_token.value)
782
+ self._advance()
783
+ return LiteralNode(val, "number", line, col)
784
+ else:
785
+ try:
786
+ return LiteralNode(float(prefix), "number", line, col)
787
+ except ValueError:
788
+ return IdentifierNode(prefix, line, col)
789
+ elif self.current_token and self.current_token.type == TokenType.NUMBER:
790
+ val = float(prefix + self.current_token.value)
791
+ self._advance()
792
+ return LiteralNode(val, "number", line, col)
793
+ else:
794
+ return IdentifierNode(prefix, line, col)
795
+
796
+ return None
797
+
798
+ def _parse_assign_or_call(self) -> Optional[ASTNode]:
799
+ """解析赋值或调用
800
+
801
+ 若后面紧跟 = 或 = → 赋值语句
802
+ 若后面紧跟 ( → 函数调用表达式(名(参数))
803
+ 否则 → 标识符表达式
804
+ """
805
+ ident = self.current_token.value
806
+ line = self.current_token.line
807
+ col = self.current_token.column
808
+ self._advance()
809
+
810
+ # 检查是否是赋值
811
+ if self.current_token and self.current_token.type == TokenType.EQUALS:
812
+ self._advance() # 跳过 =
813
+ value_node = self._parse_expression()
814
+ return AssignStmtNode(
815
+ target=ident,
816
+ value=value_node,
817
+ line=line,
818
+ column=col
819
+ )
820
+
821
+ # 函数调用:名(参数1,参数2)
822
+ if self.current_token and self.current_token.type == TokenType.LPAREN:
823
+ self._advance()
824
+ args = []
825
+ while (self.current_token and
826
+ self.current_token.type != TokenType.RPAREN and
827
+ not self._is_at_end()):
828
+ # 参数可为表达式(n 减 1)/标识符/数值
829
+ if self.current_token.type in (TokenType.IDENTIFIER,
830
+ TokenType.NUMBER):
831
+ args.append(self._parse_expression())
832
+ else:
833
+ self._advance()
834
+ if self.current_token and self.current_token.type == TokenType.RPAREN:
835
+ self._advance()
836
+ return CallExprNode(ident, args, line, col)
837
+
838
+ return IdentifierNode(ident, line, col)
839
+
840
+ def _parse_comparison(self) -> ASTNode:
841
+ """解析比较表达式"""
842
+ left = self._parse_expression()
843
+
844
+ if self.current_token and self.current_token.type in (
845
+ TokenType.DENGYU, TokenType.DAYU, TokenType.XIAOYU,
846
+ TokenType.WEI, TokenType.BUWEI,
847
+ ):
848
+ op_token = self.current_token
849
+ op_map = {
850
+ TokenType.DENGYU: "==",
851
+ TokenType.DAYU: ">",
852
+ TokenType.XIAOYU: "<",
853
+ TokenType.WEI: "==",
854
+ TokenType.BUWEI: "!=",
855
+ }
856
+ op = op_map.get(op_token.type, "==")
857
+ self._advance()
858
+
859
+ right = self._parse_numeric_value()
860
+ if right is None:
861
+ right = self._parse_expression()
862
+ return ComparisonNode(left, op, right, line=op_token.line, column=op_token.column)
863
+
864
+ return left
865
+
866
+ def _parse_expression(self) -> ASTNode:
867
+ """解析表达式(支持二元算术 + 括号优先:标识符/数值/(表达式) + 运算符 + 右)"""
868
+ if self.current_token is None:
869
+ return LiteralNode("", "string")
870
+
871
+ if self.current_token.type == TokenType.LPAREN:
872
+ # 括号优先: ( 表达式 )
873
+ line = self.current_token.line
874
+ col = self.current_token.column
875
+ self._advance()
876
+ inner = self._parse_expression()
877
+ if self.current_token and self.current_token.type == TokenType.RPAREN:
878
+ self._advance()
879
+ return self._parse_binary_tail(inner)
880
+
881
+ if self.current_token.type == TokenType.IDENTIFIER:
882
+ # 若后跟 ( → 函数调用;否则合并多词短语
883
+ if (self._peek_next() and
884
+ self._peek_next().type == TokenType.LPAREN):
885
+ name = self.current_token.value
886
+ line = self.current_token.line
887
+ col = self.current_token.column
888
+ self._advance() # 消费函数名
889
+ self._advance() # 消费 (
890
+ args = []
891
+ while (self.current_token and
892
+ self.current_token.type != TokenType.RPAREN and
893
+ not self._is_at_end()):
894
+ if self.current_token.type in (TokenType.IDENTIFIER,
895
+ TokenType.NUMBER):
896
+ args.append(self._parse_expression())
897
+ else:
898
+ self._advance()
899
+ if self.current_token and self.current_token.type == TokenType.RPAREN:
900
+ self._advance()
901
+ return self._parse_binary_tail(
902
+ CallExprNode(name, args, line, col))
903
+ left = self._merge_identifiers()
904
+ return self._parse_binary_tail(left)
905
+ elif self.current_token.type == TokenType.NUMBER:
906
+ node = LiteralNode(float(self.current_token.value), "number",
907
+ self.current_token.line,
908
+ self.current_token.column)
909
+ self._advance()
910
+ return self._parse_binary_tail(node)
911
+ elif self.current_token.type == TokenType.STRING:
912
+ node = LiteralNode(self.current_token.value, "string",
913
+ self.current_token.line,
914
+ self.current_token.column)
915
+ self._advance()
916
+ return self._parse_binary_tail(node)
917
+ else:
918
+ parts = []
919
+ # 停止条件:标点符号 + 语句开头关键字
920
+ _EXPR_STOP = (
921
+ TokenType.ZE, TokenType.FOUZE,
922
+ TokenType.PERIOD, TokenType.COMMA, TokenType.SEMICOLON,
923
+ TokenType.WENYUE, TokenType.DAYUE, TokenType.SHUYUE,
924
+ TokenType.RUO, TokenType.DAO, TokenType.DE,
925
+ TokenType.ZIRAN, TokenType.WUWEI, TokenType.GU,
926
+ TokenType.PIN, TokenType.ROU, TokenType.PU,
927
+ TokenType.ZHI, TokenType.ZHIZU,
928
+ )
929
+ while (self.current_token and
930
+ self.current_token.type not in _EXPR_STOP and
931
+ not self._is_at_end()):
932
+ parts.append(self.current_token.value)
933
+ self._advance()
934
+ return LiteralNode("".join(parts).strip(), "string")
935
+
936
+ def _parse_binary_tail(self, left: ASTNode) -> ASTNode:
937
+ """解析二元算术尾部:left [+|-|*|/] right(右结合单级,满足循环体自增语义)"""
938
+ if self.current_token and self.current_token.type in (
939
+ TokenType.OP_ADD, TokenType.OP_SUB,
940
+ TokenType.OP_MUL, TokenType.OP_DIV,
941
+ ):
942
+ op_token = self.current_token
943
+ op_map = {
944
+ TokenType.OP_ADD: "+", TokenType.OP_SUB: "-",
945
+ TokenType.OP_MUL: "*", TokenType.OP_DIV: "/",
946
+ }
947
+ op = op_map[op_token.type]
948
+ self._advance()
949
+ right = self._parse_expression()
950
+ return BinaryExprNode(left, op, right,
951
+ line=op_token.line, column=op_token.column)
952
+ return left
953
+
954
+ # ---- 辅助方法 ----
955
+
956
+ def _is_at_end(self) -> bool:
957
+ """指针越界探测:True=已消费全部 token。"""
958
+ return self.pos >= len(self.tokens) or (
959
+ self.current_token is not None and self.current_token.type == TokenType.EOF
960
+ )
961
+
962
+ def _advance(self) -> Optional[Token]:
963
+ """消费当前 token 并前进一格。"""
964
+ if self.pos < len(self.tokens) - 1:
965
+ self.pos += 1
966
+ self.current_token = self.tokens[self.pos]
967
+ elif self.pos == len(self.tokens) - 1:
968
+ self.pos += 1
969
+ self.current_token = None
970
+ return self.current_token
971
+
972
+ def _peek_next(self) -> Optional[Token]:
973
+ """查看下一个 token(不消费)"""
974
+ if self.pos < len(self.tokens) - 1:
975
+ return self.tokens[self.pos + 1]
976
+ return None
977
+
978
+ def _match(self, *types: TokenType) -> bool:
979
+ """类型相符即消费返回 True,否则 False。"""
980
+ if self.current_token and self.current_token.type in types:
981
+ self._advance()
982
+ return True
983
+ return False
984
+
985
+ def _consume(self, token_type: TokenType, message: str) -> Optional[Token]:
986
+ """消费当前 token:类型相符即前进返回,否则带行列定位报错。"""
987
+ if self.current_token and self.current_token.type == token_type:
988
+ token = self.current_token
989
+ self._advance()
990
+ return token
991
+ else:
992
+ loc = f"L{self.current_token.line}:C{self.current_token.column}" if self.current_token else "EOF"
993
+ self.errors.append(f"{loc} {message},实际得到: '{self.current_token.value if self.current_token else 'EOF'}'")
994
+ return None
995
+
996
+ def _collect_until(self, *stop_types: TokenType) -> List[Token]:
997
+ """收集 Token 直到遇到停止类型"""
998
+ parts = []
999
+ while (self.current_token and
1000
+ self.current_token.type not in stop_types and
1001
+ self.current_token.type != TokenType.EOF):
1002
+ if self.current_token.type == TokenType.COLON:
1003
+ self._advance()
1004
+ continue
1005
+ parts.append(self.current_token)
1006
+ self._advance()
1007
+ return parts
1008
+
1009
+
1010
+ # =============================================================================
1011
+ # 便捷函数
1012
+ # =============================================================================
1013
+
1014
+ def parse_tokens(tokens: List[Token], errors: List[str] = None) -> ProgramNode:
1015
+ """便捷函数:将 Token 列表解析为 AST"""
1016
+ parser = Parser(tokens, errors or [])
1017
+ return parser.parse()
1018
+
1019
+
1020
+ def parse_source(source: str) -> tuple:
1021
+ """便捷函数:从源代码直接解析为 AST"""
1022
+ from .lexer import tokenize
1023
+ tokens, lex_errors = tokenize(source)
1024
+ ast = parse_tokens(tokens, [])
1025
+ return ast, lex_errors, ast.errors if hasattr(ast, 'errors') else []
1026
+
1027
+
1028
+ # =============================================================================
1029
+ # 测试
1030
+ # =============================================================================
1031
+
1032
+ if __name__ == "__main__":
1033
+ test_code = """若条件空间为伴侣,则止情感权重于0.15。
1034
+ 道 新信任路径
1035
+ 德 累积信任值
1036
+ 问曰:如何验证信任?
1037
+ 答曰:信任值大于0.7。
1038
+ 术曰:1。柔 响应强度;2。自然 恢复默认;3。知足 验证单元。"""
1039
+
1040
+ print("=" * 60)
1041
+ print("语法分析器 v2.0 测试")
1042
+ print("=" * 60)
1043
+ print(f"源代码:\n{test_code}\n")
1044
+
1045
+ from .lexer import tokenize
1046
+ tokens, lex_errors = tokenize(test_code)
1047
+
1048
+ if lex_errors:
1049
+ print("词法错误:")
1050
+ for e in lex_errors:
1051
+ print(f" ❌ {e}")
1052
+
1053
+ parser = Parser(tokens, [])
1054
+ ast = parser.parse()
1055
+
1056
+ print(f"\nAST 根节点:{ast.type.name}")
1057
+ print(f"语句数量:{len(ast.statements)}")
1058
+ print()
1059
+
1060
+ for i, stmt in enumerate(ast.statements):
1061
+ print(f" 语句{i+1}: {stmt.type.name}")
1062
+ if stmt.type == NodeType.SHUYUE:
1063
+ print(f" 问题: {stmt.attributes.get('question', '')}")
1064
+ print(f" 答案: {stmt.attributes.get('answer', '')}")
1065
+ for step in stmt.steps:
1066
+ op_count = len(step.statement.children) if step.statement else 0
1067
+ print(f" 步骤{step.step_num}: {step.statement.type.name if step.statement else 'None'}")
1068
+ elif stmt.type == NodeType.INSTRUCTION_STMT:
1069
+ op_names = []
1070
+ for op in stmt.operands:
1071
+ if hasattr(op, 'name'):
1072
+ op_names.append(f"ID({op.name})")
1073
+ elif hasattr(op, 'literal_value'):
1074
+ op_names.append(f"Lit({op.literal_value})")
1075
+ print(f" 操作数: [{', '.join(op_names)}]")
1076
+
1077
+ if parser.errors:
1078
+ print(f"\n语法错误:")
1079
+ for e in parser.errors:
1080
+ print(f" ❌ {e}")
1081
+
1082
+ print(f"\n总计:{len(parser.errors)} 个语法错误")