Emit structured JSON --trace-eval events with source spans.
Tree walk logs enter_fn/stmt/leave_fn; bytecode logs op events for print/input/call/return, paving the way for view debug pause hooks. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
30cd39fd8f
commit
fd36b92224
8 files changed
+190
-14
No files matched your search
@@ -27,15 +27,17 @@ marqdo dump FILE --stage lines|tokens|ast|sema|all
|
||||
| `--dump-tokens` | 词法 | Token 流:`type lexeme line:col` |
|
||||
| `--dump-ast` | 语法 | S 表达式或缩进树(模块/函数/语句) |
|
||||
| `--dump-sema` | 语义 | 作用域、导入图、提升后的符号表 |
|
||||
| `--trace-eval` | 求值 | 进入/离开函数、绑定、分支臂选择、`print` 调用 |
|
||||
| `--dump-bytecode` | 字节码 | 反汇编 `Program`(见 [bytecode.md](bytecode.md)) |
|
||||
| `--trace-eval` | 求值 | **JSON 行**(stderr):语句级事件,含 `path` / `span`(`line:col`) |
|
||||
| `--dump-bytecode` | 字节码 | 反汇编 `Program`(指令旁带 `@line:col`;见 [bytecode.md](bytecode.md)) |
|
||||
| `--backend tree\|bytecode` | 执行后端 | 默认 `tree`;`bytecode` 走栈式 VM |
|
||||
| `--dump-all` | 以上全部 | 按管道顺序打印,段之间用横幅分隔 |
|
||||
|
||||
格式约定:
|
||||
|
||||
- 人类可读优先;段首统一:`=== marqdo: <stage> ===`
|
||||
- 可选 `--dump-format=text|json`(json 后置,text 先做)
|
||||
- dump 人类可读优先;段首统一:`=== marqdo: <stage> ===`
|
||||
- `--trace-eval`:每条事件一行 JSON,例如
|
||||
`{"event":"stmt","path":"…","span":"5:1","kind":"call","callee":"print"}`
|
||||
树遍历:`enter_fn` / `stmt` / `leave_fn`;字节码:`op`(`print`/`input`/`call`/`return`)。
|
||||
- 有 dump 时:若求值未实现,仍打印已实现阶段再以非 0 退出(便于 M1 只测 lines)
|
||||
|
||||
---
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **进行中**(P0 / P1a / P2-S0 / P1b 完成;下一:P2-S1 或 P3-D0) |
|
||||
| 状态 | **进行中**(P0–P1b / P2-S0 / P3-D0–D1 初版;下一:P3-D2 或 P2-S1) |
|
||||
| 日期 | 2026-08-04 |
|
||||
| 目标 | 交互 I/O、可信诊断、可生长标准库;view 渐进成为调试宿主 |
|
||||
| 相关 | [interpreter.md](interpreter.md) · [keywords.md](../design/keywords.md) · [pipeline-debug.md](../design/pipeline-debug.md) · [view.md](../design/view.md) |
|
||||
|
||||
@@ -6,6 +6,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::builtin::{builtin_int, builtin_len, builtin_str};
|
||||
use crate::bytecode::{Op, Program};
|
||||
use crate::debug::emit_trace;
|
||||
use crate::diagnostics::{bail_at, Span};
|
||||
use crate::input_feed::InputFeed;
|
||||
use crate::value::Value;
|
||||
@@ -15,6 +16,7 @@ pub struct Vm {
|
||||
capture: bool,
|
||||
pub captured_stdout: String,
|
||||
input: InputFeed,
|
||||
trace: bool,
|
||||
}
|
||||
|
||||
struct Frame {
|
||||
@@ -30,6 +32,7 @@ impl Vm {
|
||||
capture: false,
|
||||
captured_stdout: String::new(),
|
||||
input: InputFeed::new(false, Vec::new()),
|
||||
trace: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,6 +42,7 @@ impl Vm {
|
||||
capture: true,
|
||||
captured_stdout: String::new(),
|
||||
input: InputFeed::new(true, Vec::new()),
|
||||
trace: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +51,11 @@ impl Vm {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_trace(mut self, trace: bool) -> Self {
|
||||
self.trace = trace;
|
||||
self
|
||||
}
|
||||
|
||||
fn emit_line(&mut self, text: &str) {
|
||||
if self.capture {
|
||||
self.captured_stdout.push_str(text);
|
||||
@@ -102,6 +111,32 @@ impl Vm {
|
||||
let span = fun.spans.get(ip).copied().unwrap_or(Span::new(1, 1));
|
||||
frame.ip += 1;
|
||||
|
||||
if self.trace {
|
||||
match op {
|
||||
Op::Print | Op::Input | Op::Call(_, _) | Op::Return => {
|
||||
let kind = match op {
|
||||
Op::Print => "print",
|
||||
Op::Input => "input",
|
||||
Op::Call(_, _) => "call",
|
||||
Op::Return => "return",
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let ip_s = ip.to_string();
|
||||
emit_trace(
|
||||
self.path.as_deref(),
|
||||
Some(span),
|
||||
"op",
|
||||
&[
|
||||
("kind", kind),
|
||||
("fn", fun.name.as_str()),
|
||||
("ip", ip_s.as_str()),
|
||||
],
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
match op {
|
||||
Op::Constant(i) => stack.push(fun.constants[i as usize].clone()),
|
||||
Op::True => stack.push(Value::Bool(true)),
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
//! Pipeline dump helpers (see doc/design/pipeline-debug.md).
|
||||
|
||||
mod trace;
|
||||
|
||||
pub use crate::lex::format_lines_dump;
|
||||
pub use trace::emit_trace;
|
||||
@@ -0,0 +1,49 @@
|
||||
//! Structured eval trace (P3-D1): JSON lines on stderr.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::diagnostics::{display_path, Span};
|
||||
|
||||
/// Emit one JSON object line to stderr when tracing.
|
||||
pub fn emit_trace(path: Option<&Path>, span: Option<Span>, event: &str, fields: &[(&str, &str)]) {
|
||||
let mut out = String::from("{");
|
||||
out.push_str(&format!("\"event\":{}", json_str(event)));
|
||||
if let Some(p) = path {
|
||||
out.push_str(&format!(",\"path\":{}", json_str(&display_path(p))));
|
||||
}
|
||||
if let Some(sp) = span {
|
||||
out.push_str(&format!(",\"span\":{}", json_str(&sp.to_string())));
|
||||
}
|
||||
for (k, v) in fields {
|
||||
out.push_str(&format!(",\"{}\":{}", k, json_str(v)));
|
||||
}
|
||||
out.push('}');
|
||||
eprintln!("{out}");
|
||||
}
|
||||
|
||||
fn json_str(s: &str) -> String {
|
||||
let mut out = String::from("\"");
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn json_str_escapes() {
|
||||
assert_eq!(json_str("a\"b"), r#""a\"b""#);
|
||||
}
|
||||
}
|
||||
+60
-8
@@ -8,6 +8,7 @@ use crate::ast::{
|
||||
Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Stmt, UnaryOp,
|
||||
};
|
||||
use crate::builtin::{builtin_int, builtin_len, builtin_str};
|
||||
use crate::debug::emit_trace;
|
||||
use crate::diagnostics::{bail_at, Span};
|
||||
use crate::input_feed::InputFeed;
|
||||
use crate::value::Value;
|
||||
@@ -125,7 +126,12 @@ impl Interpreter {
|
||||
args: &[(String, Value)],
|
||||
) -> Result<Value> {
|
||||
if self.trace {
|
||||
eprintln!("enter fun {:?}", fun.name);
|
||||
emit_trace(
|
||||
self.path.as_deref(),
|
||||
Some(fun.span),
|
||||
"enter_fn",
|
||||
&[("fn", fun.name.as_str())],
|
||||
);
|
||||
}
|
||||
for (k, v) in args {
|
||||
env.set(k.clone(), v.clone());
|
||||
@@ -144,7 +150,13 @@ impl Interpreter {
|
||||
}
|
||||
}
|
||||
if self.trace {
|
||||
eprintln!("leave fun {:?} => {ret}", fun.name);
|
||||
let display = ret.as_display();
|
||||
emit_trace(
|
||||
self.path.as_deref(),
|
||||
Some(fun.span),
|
||||
"leave_fn",
|
||||
&[("fn", fun.name.as_str()), ("value", display.as_str())],
|
||||
);
|
||||
}
|
||||
Ok(ret)
|
||||
}
|
||||
@@ -161,7 +173,17 @@ impl Interpreter {
|
||||
self.current_span = *span;
|
||||
let v = self.eval_expr(module, fun, env, value)?;
|
||||
if self.trace {
|
||||
eprintln!(" assign {name} = {v:?} @{span}");
|
||||
let display = v.as_display();
|
||||
emit_trace(
|
||||
self.path.as_deref(),
|
||||
Some(*span),
|
||||
"stmt",
|
||||
&[
|
||||
("kind", "assign"),
|
||||
("name", name.as_str()),
|
||||
("value", display.as_str()),
|
||||
],
|
||||
);
|
||||
}
|
||||
env.set(name.clone(), v);
|
||||
Ok(None)
|
||||
@@ -170,14 +192,25 @@ impl Interpreter {
|
||||
self.current_span = *span;
|
||||
let v = self.eval_expr(module, fun, env, value)?;
|
||||
if self.trace {
|
||||
eprintln!(" return {v:?} @{span}");
|
||||
let display = v.as_display();
|
||||
emit_trace(
|
||||
self.path.as_deref(),
|
||||
Some(*span),
|
||||
"stmt",
|
||||
&[("kind", "return"), ("value", display.as_str())],
|
||||
);
|
||||
}
|
||||
Ok(Some(v))
|
||||
}
|
||||
Stmt::Call { call, span } => {
|
||||
self.current_span = *span;
|
||||
if self.trace {
|
||||
eprintln!(" call-stmt {} @{span}", call.callee);
|
||||
emit_trace(
|
||||
self.path.as_deref(),
|
||||
Some(*span),
|
||||
"stmt",
|
||||
&[("kind", "call"), ("callee", call.callee.as_str())],
|
||||
);
|
||||
}
|
||||
let _ = self.eval_call(module, fun, env, call)?;
|
||||
Ok(None)
|
||||
@@ -185,7 +218,12 @@ impl Interpreter {
|
||||
Stmt::Branch { arms, span } => {
|
||||
self.current_span = *span;
|
||||
if self.trace {
|
||||
eprintln!(" branch @{span}");
|
||||
emit_trace(
|
||||
self.path.as_deref(),
|
||||
Some(*span),
|
||||
"stmt",
|
||||
&[("kind", "branch")],
|
||||
);
|
||||
}
|
||||
for arm in arms {
|
||||
let take = match &arm.condition {
|
||||
@@ -210,7 +248,12 @@ impl Interpreter {
|
||||
} => {
|
||||
self.current_span = *span;
|
||||
if self.trace {
|
||||
eprintln!(" while @{span}");
|
||||
emit_trace(
|
||||
self.path.as_deref(),
|
||||
Some(*span),
|
||||
"stmt",
|
||||
&[("kind", "while")],
|
||||
);
|
||||
}
|
||||
let mut guard = 0u32;
|
||||
while self.eval_expr(module, fun, env, condition)?.truthy() {
|
||||
@@ -234,7 +277,16 @@ impl Interpreter {
|
||||
} => {
|
||||
self.current_span = *span;
|
||||
if self.trace {
|
||||
eprintln!(" foreach {item} in {collection} @{span}");
|
||||
emit_trace(
|
||||
self.path.as_deref(),
|
||||
Some(*span),
|
||||
"stmt",
|
||||
&[
|
||||
("kind", "foreach"),
|
||||
("item", item.as_str()),
|
||||
("collection", collection.as_str()),
|
||||
],
|
||||
);
|
||||
}
|
||||
let coll = env.get(collection).cloned().ok_or_else(|| {
|
||||
self.err(format!("undefined collection `{collection}`"))
|
||||
|
||||
+9
-1
@@ -141,8 +141,16 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
|
||||
if opts.dump_bytecode {
|
||||
print!("{}", program.disassemble());
|
||||
}
|
||||
let mut vm = Vm::new(Some(path)).with_stdin(opts.stdin_lines.clone());
|
||||
let mut vm = Vm::new(Some(path))
|
||||
.with_stdin(opts.stdin_lines.clone())
|
||||
.with_trace(opts.trace_eval);
|
||||
if opts.trace_eval {
|
||||
eprintln!("=== marqdo: trace-eval ({path_label}) ===");
|
||||
}
|
||||
vm.run(&program)?;
|
||||
if opts.trace_eval {
|
||||
eprintln!("=== marqdo: end trace-eval ===");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -380,6 +380,33 @@ fn bytecode_paragraph_comment() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trace_eval_json_tree() {
|
||||
let (code, stdout, stderr) = run(&["run", "tests/structure/hello.mq.md", "--trace-eval"]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
assert_eq!(stdout.trim_end(), "Hello World!");
|
||||
assert!(stderr.contains("\"event\":\"enter_fn\""), "{stderr}");
|
||||
assert!(stderr.contains("\"event\":\"stmt\""), "{stderr}");
|
||||
assert!(stderr.contains("\"span\":\"5:1\""), "{stderr}");
|
||||
assert!(stderr.contains("\"event\":\"leave_fn\""), "{stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trace_eval_json_bytecode() {
|
||||
let (code, stdout, stderr) = run(&[
|
||||
"run",
|
||||
"tests/structure/hello.mq.md",
|
||||
"--backend",
|
||||
"bytecode",
|
||||
"--trace-eval",
|
||||
]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
assert_eq!(stdout.trim_end(), "Hello World!");
|
||||
assert!(stderr.contains("\"event\":\"op\""), "{stderr}");
|
||||
assert!(stderr.contains("\"kind\":\"print\""), "{stderr}");
|
||||
assert!(stderr.contains("\"span\":\"5:1\""), "{stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_writes_yaml() {
|
||||
let dir = tempfile_dir("mq-cat");
|
||||
|
||||
Reference in new issue
Block a user