Add v0.2 surface syntax, writeback/subtask stdlib, and view input deferral.
Use + for parameters, ordered-list branches, backtick identifiers, and quoted strings with escapes. Add writeback and subtask host libs, optional parameter defaults, narrative-bold comment fix, and defer view execution until preset stdin is submitted. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
92d88fe761
commit
63e5be80ab
116 files changed
+2226
-559
No files matched your search
+7
-1
@@ -10,13 +10,19 @@ pub struct Module {
|
||||
pub functions: Vec<Function>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Param {
|
||||
pub name: String,
|
||||
pub default: Option<Expr>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Function {
|
||||
pub name: String,
|
||||
/// Heading depth 1–6. Level 1 = object/type; level ≥ 2 = function/method.
|
||||
pub level: u8,
|
||||
pub span: Span,
|
||||
pub params: Vec<String>,
|
||||
pub params: Vec<Param>,
|
||||
pub body: Vec<Stmt>,
|
||||
pub children: Vec<Function>,
|
||||
}
|
||||
|
||||
+15
-11
@@ -5,7 +5,7 @@ use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::ast::{
|
||||
Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Stmt, UnaryOp,
|
||||
Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Param, Stmt, UnaryOp,
|
||||
};
|
||||
use crate::bytecode::{FnChunk, Op, Program};
|
||||
use crate::diagnostics::{bail_at, Span};
|
||||
@@ -15,7 +15,7 @@ struct FlatFun {
|
||||
name: String,
|
||||
level: u8,
|
||||
parent: Option<usize>,
|
||||
params: Vec<String>,
|
||||
params: Vec<Param>,
|
||||
body: Vec<Stmt>,
|
||||
children: Vec<usize>,
|
||||
span: Span,
|
||||
@@ -110,7 +110,7 @@ fn compile_function(fn_id: usize, flat: &[FlatFun], path: Option<&Path>) -> Resu
|
||||
let fun = &flat[fn_id];
|
||||
let mut locals = HashMap::new();
|
||||
for (i, p) in fun.params.iter().enumerate() {
|
||||
locals.insert(p.clone(), i as u8);
|
||||
locals.insert(p.name.clone(), i as u8);
|
||||
}
|
||||
let is_method = fun
|
||||
.parent
|
||||
@@ -130,11 +130,11 @@ fn compile_function(fn_id: usize, flat: &[FlatFun], path: Option<&Path>) -> Resu
|
||||
fn_id,
|
||||
chunk: FnChunk {
|
||||
name: fun.name.clone(),
|
||||
params: fun.params.clone(),
|
||||
params: fun.params.iter().map(|p| p.name.clone()).collect(),
|
||||
code: Vec::new(),
|
||||
spans: Vec::new(),
|
||||
constants: Vec::new(),
|
||||
locals: fun.params.clone(),
|
||||
locals: fun.params.iter().map(|p| p.name.clone()).collect(),
|
||||
},
|
||||
locals,
|
||||
stmt_span: fun.span,
|
||||
@@ -530,7 +530,7 @@ impl<'a> FnCompiler<'a> {
|
||||
|
||||
match self.resolve_call(&call.callee) {
|
||||
Ok(fid) => {
|
||||
let params = self.flat[fid].params.clone();
|
||||
let params = &self.flat[fid].params;
|
||||
let mut named: HashMap<String, &Expr> = HashMap::new();
|
||||
let mut positionals = Vec::new();
|
||||
for a in &call.args {
|
||||
@@ -542,14 +542,16 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
}
|
||||
let mut pos_i = 0;
|
||||
for p in ¶ms {
|
||||
if let Some(e) = named.get(p) {
|
||||
for p in params {
|
||||
if let Some(e) = named.get(&p.name) {
|
||||
self.compile_expr(e)?;
|
||||
} else if pos_i < positionals.len() {
|
||||
self.compile_expr(positionals[pos_i])?;
|
||||
pos_i += 1;
|
||||
} else if let Some(def) = &p.default {
|
||||
self.compile_expr(def)?;
|
||||
} else {
|
||||
return Err(self.err(format!("missing argument for parameter `{p}`")));
|
||||
return Err(self.err(format!("missing argument for parameter `{}`", p.name)));
|
||||
}
|
||||
}
|
||||
if pos_i < positionals.len() {
|
||||
@@ -647,13 +649,15 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
let mut pos_i = 0;
|
||||
for p in ¶ms {
|
||||
if let Some(e) = named.get(p) {
|
||||
if let Some(e) = named.get(&p.name) {
|
||||
self.compile_expr(e)?;
|
||||
} else if pos_i < positionals.len() {
|
||||
self.compile_expr(positionals[pos_i])?;
|
||||
pos_i += 1;
|
||||
} else if let Some(def) = &p.default {
|
||||
self.compile_expr(def)?;
|
||||
} else {
|
||||
return Err(self.err(format!("missing argument for parameter `{p}`")));
|
||||
return Err(self.err(format!("missing argument for parameter `{}`", p.name)));
|
||||
}
|
||||
}
|
||||
if pos_i < positionals.len() {
|
||||
|
||||
@@ -357,6 +357,7 @@ impl Vm {
|
||||
slots,
|
||||
});
|
||||
self.host.push_call_frame(&fname);
|
||||
self.host.push_call_site_line(span.line);
|
||||
}
|
||||
Op::TagInstance(idx) => {
|
||||
let type_name = match fun.constants.get(idx as usize) {
|
||||
@@ -422,6 +423,7 @@ impl Vm {
|
||||
slots,
|
||||
});
|
||||
self.host.push_call_frame(&fname);
|
||||
self.host.push_call_site_line(span.line);
|
||||
}
|
||||
Op::PluginCall(name_idx, argc) => {
|
||||
let argc = argc as usize;
|
||||
@@ -509,11 +511,13 @@ impl Vm {
|
||||
slots,
|
||||
});
|
||||
self.host.push_call_frame(&fname);
|
||||
self.host.push_call_site_line(span.line);
|
||||
}
|
||||
Op::Return => {
|
||||
let ret = pop(&mut stack).unwrap_or(Value::None);
|
||||
frames.pop();
|
||||
self.host.pop_call_frame();
|
||||
self.host.pop_call_site_line();
|
||||
if frames.is_empty() {
|
||||
return Ok(ret);
|
||||
}
|
||||
|
||||
+62
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::host::{agent_rt, foreign, fs, json, math, net, plugin, sys, time, HostContext};
|
||||
use crate::host::{agent_rt, foreign, fs, json, math, net, plugin, subtask, sys, time, writeback, HostContext};
|
||||
use crate::value::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -92,6 +92,15 @@ pub enum HostFn {
|
||||
AgentHistoryAppend = 81,
|
||||
FormatToolsForLlm = 82,
|
||||
ToolAllowed = 83,
|
||||
WritebackRecord = 84,
|
||||
WritebackGet = 85,
|
||||
WritebackClear = 86,
|
||||
WritebackList = 87,
|
||||
SubtaskSpawn = 88,
|
||||
SubtaskPoll = 89,
|
||||
SubtaskJoin = 90,
|
||||
SubtaskKill = 91,
|
||||
SubtaskWaitAll = 92,
|
||||
}
|
||||
|
||||
impl HostFn {
|
||||
@@ -180,6 +189,15 @@ impl HostFn {
|
||||
81 => Self::AgentHistoryAppend,
|
||||
82 => Self::FormatToolsForLlm,
|
||||
83 => Self::ToolAllowed,
|
||||
84 => Self::WritebackRecord,
|
||||
85 => Self::WritebackGet,
|
||||
86 => Self::WritebackClear,
|
||||
87 => Self::WritebackList,
|
||||
88 => Self::SubtaskSpawn,
|
||||
89 => Self::SubtaskPoll,
|
||||
90 => Self::SubtaskJoin,
|
||||
91 => Self::SubtaskKill,
|
||||
92 => Self::SubtaskWaitAll,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -272,6 +290,15 @@ impl HostFn {
|
||||
"host_agent_history_append" | "agent_history_append" => Self::AgentHistoryAppend,
|
||||
"host_format_tools_for_llm" | "format_tools_for_llm" => Self::FormatToolsForLlm,
|
||||
"host_tool_allowed" | "tool_allowed" => Self::ToolAllowed,
|
||||
"host_writeback_record" | "writeback_record" => Self::WritebackRecord,
|
||||
"host_writeback_get" | "writeback_get" => Self::WritebackGet,
|
||||
"host_writeback_clear" | "writeback_clear" => Self::WritebackClear,
|
||||
"host_writeback_list" | "writeback_list" => Self::WritebackList,
|
||||
"host_subtask_spawn" | "subtask_spawn" => Self::SubtaskSpawn,
|
||||
"host_subtask_poll" | "subtask_poll" => Self::SubtaskPoll,
|
||||
"host_subtask_join" | "subtask_join" => Self::SubtaskJoin,
|
||||
"host_subtask_kill" | "subtask_kill" => Self::SubtaskKill,
|
||||
"host_subtask_wait_all" | "subtask_wait_all" => Self::SubtaskWaitAll,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -365,6 +392,15 @@ impl HostFn {
|
||||
Self::AgentHistoryAppend => "host_agent_history_append",
|
||||
Self::FormatToolsForLlm => "host_format_tools_for_llm",
|
||||
Self::ToolAllowed => "host_tool_allowed",
|
||||
Self::WritebackRecord => "host_writeback_record",
|
||||
Self::WritebackGet => "host_writeback_get",
|
||||
Self::WritebackClear => "host_writeback_clear",
|
||||
Self::WritebackList => "host_writeback_list",
|
||||
Self::SubtaskSpawn => "host_subtask_spawn",
|
||||
Self::SubtaskPoll => "host_subtask_poll",
|
||||
Self::SubtaskJoin => "host_subtask_join",
|
||||
Self::SubtaskKill => "host_subtask_kill",
|
||||
Self::SubtaskWaitAll => "host_subtask_wait_all",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -417,6 +453,12 @@ impl HostFn {
|
||||
Self::AgentHistoryAppend => &["id", "item"],
|
||||
Self::FormatToolsForLlm => &["tools"],
|
||||
Self::ToolAllowed => &["tools", "name"],
|
||||
Self::WritebackRecord => &["value"],
|
||||
Self::WritebackGet | Self::WritebackClear => &[],
|
||||
Self::WritebackList => &[],
|
||||
Self::SubtaskSpawn => &["path"],
|
||||
Self::SubtaskPoll | Self::SubtaskJoin | Self::SubtaskKill => &["id"],
|
||||
Self::SubtaskWaitAll => &[],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,6 +476,8 @@ impl HostFn {
|
||||
Self::PlotConic => &["b", "h", "k", "path", "grid"],
|
||||
Self::ForeignSetCmd => &["args"],
|
||||
Self::ForeignRun | Self::ForeignRunLang => &["stdin"],
|
||||
Self::WritebackRecord | Self::WritebackGet | Self::WritebackClear => &["at_end"],
|
||||
Self::SubtaskSpawn => &["args"],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
@@ -632,6 +676,23 @@ pub fn call_host(
|
||||
require(bound, "tools")?,
|
||||
require(bound, "name")?,
|
||||
),
|
||||
HostFn::WritebackRecord => writeback::record(
|
||||
ctx,
|
||||
require(bound, "value")?,
|
||||
bound.get("at_end"),
|
||||
),
|
||||
HostFn::WritebackGet => writeback::get(ctx, bound.get("at_end")),
|
||||
HostFn::WritebackClear => writeback::clear(ctx, bound.get("at_end")),
|
||||
HostFn::WritebackList => writeback::list(ctx),
|
||||
HostFn::SubtaskSpawn => subtask::spawn(
|
||||
ctx,
|
||||
require(bound, "path")?,
|
||||
bound.get("args"),
|
||||
),
|
||||
HostFn::SubtaskPoll => subtask::poll(ctx, require(bound, "id")?),
|
||||
HostFn::SubtaskJoin => subtask::join(ctx, require(bound, "id")?),
|
||||
HostFn::SubtaskKill => subtask::kill(ctx, require(bound, "id")?),
|
||||
HostFn::SubtaskWaitAll => subtask::wait_all(ctx),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+26
-1
@@ -12,8 +12,10 @@ mod json;
|
||||
pub mod math;
|
||||
mod net;
|
||||
pub mod plugin;
|
||||
pub mod subtask;
|
||||
mod sys;
|
||||
mod time;
|
||||
pub mod writeback;
|
||||
|
||||
pub use dispatch::{call_host, HostFn};
|
||||
pub use fs::path_under_root;
|
||||
@@ -21,6 +23,7 @@ pub use plugin::PluginState;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Child;
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
@@ -52,7 +55,7 @@ pub struct PlotArtifact {
|
||||
pub svg: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug)]
|
||||
pub struct HostContext {
|
||||
pub caps: HostCaps,
|
||||
pub fs_root: Option<PathBuf>,
|
||||
@@ -78,6 +81,11 @@ pub struct HostContext {
|
||||
pub agent_seq: u64,
|
||||
/// Last statement line (updated by interpreters for `host_call_site`).
|
||||
pub current_line: u32,
|
||||
/// Entry-file line of each active user call (for writeback anchoring).
|
||||
pub call_site_lines: Vec<u32>,
|
||||
/// OS subprocess subtasks (`lib/subtask`).
|
||||
pub subtasks: HashMap<u64, Child>,
|
||||
pub subtask_seq: u64,
|
||||
}
|
||||
|
||||
impl Default for HostContext {
|
||||
@@ -99,10 +107,19 @@ impl Default for HostContext {
|
||||
agent_histories: HashMap::new(),
|
||||
agent_seq: 0,
|
||||
current_line: 1,
|
||||
call_site_lines: Vec::new(),
|
||||
subtasks: HashMap::new(),
|
||||
subtask_seq: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HostContext {
|
||||
fn drop(&mut self) {
|
||||
subtask::kill_all(self);
|
||||
}
|
||||
}
|
||||
|
||||
impl HostContext {
|
||||
pub fn for_run(path: Option<&Path>, caps: HostCaps, argv: Vec<String>) -> Self {
|
||||
let mut ctx = Self::default();
|
||||
@@ -142,6 +159,14 @@ impl HostContext {
|
||||
self.caps.net
|
||||
}
|
||||
|
||||
pub fn push_call_site_line(&mut self, line: u32) {
|
||||
self.call_site_lines.push(line);
|
||||
}
|
||||
|
||||
pub fn pop_call_site_line(&mut self) {
|
||||
self.call_site_lines.pop();
|
||||
}
|
||||
|
||||
pub fn allow_plugin(&self) -> bool {
|
||||
self.caps.plugin
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! OS subprocess subtasks (`marqdo run` children); parent exit kills all children.
|
||||
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
|
||||
match v {
|
||||
Value::Text(s) => Ok(s.as_str()),
|
||||
_ => Err(format!("{label} must be text")),
|
||||
}
|
||||
}
|
||||
|
||||
fn child_id(_ctx: &HostContext, id: &Value) -> Result<u64, String> {
|
||||
match id {
|
||||
Value::Int(n) if *n > 0 => Ok(*n as u64),
|
||||
_ => Err("subtask id must be positive int".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kill_all(ctx: &mut HostContext) {
|
||||
for (_, mut child) in ctx.subtasks.drain() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spawn(
|
||||
ctx: &mut HostContext,
|
||||
path: &Value,
|
||||
args: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
if !ctx.caps.exec {
|
||||
return Err("subtask spawn disabled (exec capability off)".into());
|
||||
}
|
||||
let rel = as_text(path, "path")?;
|
||||
let file = if std::path::Path::new(rel).is_absolute() {
|
||||
std::path::PathBuf::from(rel)
|
||||
} else {
|
||||
ctx.cwd.join(rel)
|
||||
};
|
||||
let exe = std::env::current_exe().map_err(|e| format!("subtask: current_exe: {e}"))?;
|
||||
let mut cmd = Command::new(&exe);
|
||||
cmd.arg("run").arg(&file);
|
||||
cmd.current_dir(&ctx.cwd);
|
||||
cmd.stdin(Stdio::null());
|
||||
if let Some(Value::List(items)) = args {
|
||||
for item in items {
|
||||
cmd.arg(as_text(item, "arg")?);
|
||||
}
|
||||
}
|
||||
let child = cmd
|
||||
.spawn()
|
||||
.map_err(|e| format!("subtask spawn {}: {e}", file.display()))?;
|
||||
ctx.subtask_seq = ctx.subtask_seq.wrapping_add(1);
|
||||
let id = ctx.subtask_seq;
|
||||
ctx.subtasks.insert(id, child);
|
||||
Ok(Value::Int(id as i64))
|
||||
}
|
||||
|
||||
pub fn poll(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
|
||||
let id = child_id(ctx, id)?;
|
||||
let child = ctx
|
||||
.subtasks
|
||||
.get_mut(&id)
|
||||
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
|
||||
match child.try_wait().map_err(|e| format!("subtask poll: {e}"))? {
|
||||
None => Ok(Value::Map(vec![("status".into(), Value::Text("running".into()))])),
|
||||
Some(status) => {
|
||||
let code = status.code().unwrap_or(-1);
|
||||
let st = if status.success() {
|
||||
"done"
|
||||
} else {
|
||||
"failed"
|
||||
};
|
||||
Ok(Value::Map(vec![
|
||||
("status".into(), Value::Text(st.into())),
|
||||
("code".into(), Value::Int(code as i64)),
|
||||
]))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn join(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
|
||||
let id = child_id(ctx, id)?;
|
||||
let mut child = ctx
|
||||
.subtasks
|
||||
.remove(&id)
|
||||
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
|
||||
let status = child
|
||||
.wait()
|
||||
.map_err(|e| format!("subtask join: {e}"))?;
|
||||
Ok(Value::Int(status.code().unwrap_or(-1) as i64))
|
||||
}
|
||||
|
||||
pub fn kill(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
|
||||
let id = child_id(ctx, id)?;
|
||||
let mut child = ctx
|
||||
.subtasks
|
||||
.remove(&id)
|
||||
.ok_or_else(|| format!("subtask: unknown id {id}"))?;
|
||||
child.kill().map_err(|e| format!("subtask kill: {e}"))?;
|
||||
let _ = child.wait();
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
pub fn wait_all(ctx: &mut HostContext) -> Result<Value, String> {
|
||||
let ids: Vec<u64> = ctx.subtasks.keys().copied().collect();
|
||||
let mut codes = Vec::new();
|
||||
for id in ids {
|
||||
let code = join(ctx, &Value::Int(id as i64))?;
|
||||
codes.push(code);
|
||||
}
|
||||
Ok(Value::List(codes))
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
//! Jupyter-style output persistence in `.mq.md` (`<!-- marqdo-out … -->`).
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
const MAGIC: &str = "marqdo-out";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct BlockSpan {
|
||||
start: usize,
|
||||
end: usize,
|
||||
body: String,
|
||||
start_line: u32,
|
||||
}
|
||||
|
||||
fn display_value(v: &Value) -> String {
|
||||
match v {
|
||||
Value::Text(s) => s.clone(),
|
||||
other => other.as_display(),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_truthy(v: Option<&Value>) -> bool {
|
||||
match v {
|
||||
None | Some(Value::None) => false,
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(Value::Int(n)) => *n != 0,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn call_line(ctx: &HostContext) -> Result<u32, String> {
|
||||
ctx.call_site_lines
|
||||
.last()
|
||||
.copied()
|
||||
.ok_or_else(|| "writeback: no call site line".into())
|
||||
}
|
||||
|
||||
fn line_number_at(source: &str, byte: usize) -> u32 {
|
||||
source[..byte.min(source.len())]
|
||||
.bytes()
|
||||
.filter(|b| *b == b'\n')
|
||||
.count() as u32
|
||||
+ 1
|
||||
}
|
||||
|
||||
fn format_block(body: &str) -> String {
|
||||
format!("<!-- {MAGIC}\n{body}\n-->")
|
||||
}
|
||||
|
||||
fn parse_one_block(block: &str, start_byte: usize, source: &str) -> Option<BlockSpan> {
|
||||
let inner = block
|
||||
.strip_prefix("<!--")?
|
||||
.strip_suffix("-->")?
|
||||
.trim();
|
||||
if !inner.contains(MAGIC) {
|
||||
return None;
|
||||
}
|
||||
let mut lines: Vec<&str> = inner.lines().collect();
|
||||
if lines.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let header = lines.remove(0).trim();
|
||||
if !header.split_whitespace().any(|t| t == MAGIC) {
|
||||
return None;
|
||||
}
|
||||
let body = lines.join("\n");
|
||||
let end = start_byte + block.len();
|
||||
Some(BlockSpan {
|
||||
start: start_byte,
|
||||
end,
|
||||
body,
|
||||
start_line: line_number_at(source, start_byte),
|
||||
})
|
||||
}
|
||||
|
||||
fn scan_blocks(source: &str) -> Vec<BlockSpan> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i < source.len() {
|
||||
let rest = &source[i..];
|
||||
let Some(start) = rest.find("<!--") else {
|
||||
break;
|
||||
};
|
||||
let abs = i + start;
|
||||
let after = &source[abs..];
|
||||
if !after.contains(MAGIC) {
|
||||
i = abs + 4;
|
||||
continue;
|
||||
}
|
||||
let Some(end_rel) = after.find("-->") else {
|
||||
break;
|
||||
};
|
||||
let block = &after[..end_rel + 3];
|
||||
if let Some(b) = parse_one_block(block, abs, source) {
|
||||
out.push(b);
|
||||
}
|
||||
i = abs + end_rel + 3;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn strip_span(source: &str, start: usize, end: usize) -> String {
|
||||
let mut out = String::with_capacity(source.len());
|
||||
out.push_str(&source[..start]);
|
||||
out.push_str(&source[end..]);
|
||||
out
|
||||
}
|
||||
|
||||
fn line_start_byte(source: &str, line_no: u32) -> Option<usize> {
|
||||
if line_no == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut cur = 1u32;
|
||||
for (i, b) in source.bytes().enumerate() {
|
||||
if cur == line_no {
|
||||
return Some(i);
|
||||
}
|
||||
if b == b'\n' {
|
||||
cur += 1;
|
||||
}
|
||||
}
|
||||
if cur == line_no {
|
||||
Some(source.len())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn line_end_byte(source: &str, line_no: u32) -> Option<usize> {
|
||||
let start = line_start_byte(source, line_no)?;
|
||||
let rest = &source[start..];
|
||||
match rest.find('\n') {
|
||||
Some(off) => Some(start + off + 1),
|
||||
None => Some(source.len()),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_blank_line(source: &str, line_no: u32) -> bool {
|
||||
let start = match line_start_byte(source, line_no) {
|
||||
Some(s) => s,
|
||||
None => return true,
|
||||
};
|
||||
let end = line_end_byte(source, line_no).unwrap_or(source.len());
|
||||
source[start..end].trim().is_empty()
|
||||
}
|
||||
|
||||
fn find_adjacent_block(source: &str, after_line: u32) -> Option<BlockSpan> {
|
||||
let mut line = after_line.saturating_add(1);
|
||||
let total = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
|
||||
while line <= total && is_blank_line(source, line) {
|
||||
line += 1;
|
||||
}
|
||||
for b in scan_blocks(source) {
|
||||
if b.start_line == line {
|
||||
return Some(b);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn is_eof_block(source: &str, block: &BlockSpan) -> bool {
|
||||
source[block.end..].trim().is_empty()
|
||||
}
|
||||
|
||||
fn find_eof_block(source: &str) -> Option<BlockSpan> {
|
||||
scan_blocks(source)
|
||||
.into_iter()
|
||||
.rev()
|
||||
.find(|b| is_eof_block(source, b))
|
||||
}
|
||||
|
||||
fn insert_after_line(source: &str, line_no: u32, block: &str) -> Result<String, String> {
|
||||
let insert_at = line_end_byte(source, line_no)
|
||||
.ok_or_else(|| format!("writeback: line {line_no} out of range"))?;
|
||||
let mut out = String::with_capacity(source.len() + block.len() + 2);
|
||||
out.push_str(&source[..insert_at]);
|
||||
if !block.starts_with('\n') && !source[..insert_at].ends_with('\n') {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str(block);
|
||||
if !block.ends_with('\n') {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str(&source[insert_at..]);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn append_eof(source: &str, block: &str) -> String {
|
||||
let mut trimmed = source.trim_end().to_string();
|
||||
if !trimmed.is_empty() {
|
||||
trimmed.push('\n');
|
||||
}
|
||||
trimmed.push_str(block);
|
||||
if !block.ends_with('\n') {
|
||||
trimmed.push('\n');
|
||||
}
|
||||
trimmed
|
||||
}
|
||||
|
||||
fn persist(ctx: &mut HostContext, source: &str) -> Result<(), String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("writeback disabled (fs_write capability off)".into());
|
||||
}
|
||||
let path = ctx
|
||||
.entry_path
|
||||
.as_ref()
|
||||
.ok_or_else(|| "writeback: no entry file".to_string())?;
|
||||
std::fs::write(path, source).map_err(|e| format!("writeback write {}: {e}", path.display()))?;
|
||||
ctx.entry_source = Some(source.to_string());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn anchor_line_above(source: &str, block_start_line: u32) -> u32 {
|
||||
let mut line = block_start_line.saturating_sub(1);
|
||||
while line > 0 && is_blank_line(source, line) {
|
||||
line -= 1;
|
||||
}
|
||||
line.max(1)
|
||||
}
|
||||
|
||||
pub fn record(
|
||||
ctx: &mut HostContext,
|
||||
value: &Value,
|
||||
at_end: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
let body = display_value(value);
|
||||
let source = ctx
|
||||
.entry_source
|
||||
.as_deref()
|
||||
.ok_or_else(|| "writeback: no entry source".to_string())?;
|
||||
let next = if is_truthy(at_end) {
|
||||
let stripped = find_eof_block(source)
|
||||
.map(|b| strip_span(source, b.start, b.end))
|
||||
.unwrap_or_else(|| source.to_string());
|
||||
append_eof(&stripped, &format_block(&body))
|
||||
} else {
|
||||
let line = call_line(ctx)?;
|
||||
let stripped = find_adjacent_block(source, line)
|
||||
.map(|b| strip_span(source, b.start, b.end))
|
||||
.unwrap_or_else(|| source.to_string());
|
||||
insert_after_line(&stripped, line, &format_block(&body))?
|
||||
};
|
||||
persist(ctx, &next)?;
|
||||
Ok(Value::Text(body))
|
||||
}
|
||||
|
||||
pub fn get(ctx: &HostContext, at_end: Option<&Value>) -> Result<Value, String> {
|
||||
let source = ctx
|
||||
.entry_source
|
||||
.as_deref()
|
||||
.ok_or_else(|| "writeback: no entry source".to_string())?;
|
||||
let body = if is_truthy(at_end) {
|
||||
find_eof_block(source).map(|b| b.body)
|
||||
} else {
|
||||
let line = call_line(ctx)?;
|
||||
find_adjacent_block(source, line).map(|b| b.body)
|
||||
};
|
||||
Ok(match body {
|
||||
Some(s) => Value::Text(s),
|
||||
None => Value::None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn clear(ctx: &mut HostContext, at_end: Option<&Value>) -> Result<Value, String> {
|
||||
let source = ctx
|
||||
.entry_source
|
||||
.as_deref()
|
||||
.ok_or_else(|| "writeback: no entry source".to_string())?;
|
||||
let next = if is_truthy(at_end) {
|
||||
find_eof_block(source)
|
||||
.map(|b| strip_span(source, b.start, b.end))
|
||||
.unwrap_or_else(|| source.to_string())
|
||||
} else {
|
||||
let line = call_line(ctx)?;
|
||||
find_adjacent_block(source, line)
|
||||
.map(|b| strip_span(source, b.start, b.end))
|
||||
.unwrap_or_else(|| source.to_string())
|
||||
};
|
||||
if next != source {
|
||||
persist(ctx, &next)?;
|
||||
}
|
||||
Ok(Value::None)
|
||||
}
|
||||
|
||||
pub fn list(ctx: &HostContext) -> Result<Value, String> {
|
||||
let source = ctx
|
||||
.entry_source
|
||||
.as_deref()
|
||||
.ok_or_else(|| "writeback: no entry source".to_string())?;
|
||||
let items: Vec<Value> = scan_blocks(source)
|
||||
.into_iter()
|
||||
.map(|b| {
|
||||
let anchor = anchor_line_above(source, b.start_line);
|
||||
let at_eof = is_eof_block(source, &b);
|
||||
Value::Map(vec![
|
||||
("line".into(), Value::Int(anchor as i64)),
|
||||
("body".into(), Value::Text(b.body)),
|
||||
("at_end".into(), Value::Bool(at_eof)),
|
||||
])
|
||||
})
|
||||
.collect();
|
||||
Ok(Value::List(items))
|
||||
}
|
||||
|
||||
/// Map statement line → body for adjacent blocks; EOF blocks use key `0`.
|
||||
pub fn writeback_map(source: &str) -> HashMap<u32, String> {
|
||||
let mut map = HashMap::new();
|
||||
for b in scan_blocks(source) {
|
||||
if is_eof_block(source, &b) {
|
||||
map.insert(0, b.body);
|
||||
} else {
|
||||
map.insert(anchor_line_above(source, b.start_line), b.body);
|
||||
}
|
||||
}
|
||||
map
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_and_insert_adjacent() {
|
||||
let src = "# main\n\n*`x` = 1*\n";
|
||||
let block = format_block("1");
|
||||
let next = insert_after_line(src, 3, &block).unwrap();
|
||||
assert!(next.contains("marqdo-out"));
|
||||
assert!(!next.contains("@line"));
|
||||
let blocks = scan_blocks(&next);
|
||||
assert_eq!(blocks.len(), 1);
|
||||
assert_eq!(blocks[0].body, "1");
|
||||
let replaced = strip_span(&next, blocks[0].start, blocks[0].end);
|
||||
assert!(!replaced.contains("marqdo-out"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writeback_map_uses_line_above() {
|
||||
let src = "# main\n\n*`x` = 1*\n<!-- marqdo-out\n42\n-->\n\n> print text=tail\n";
|
||||
let map = writeback_map(src);
|
||||
assert_eq!(map.get(&3), Some(&"42".to_string()));
|
||||
}
|
||||
}
|
||||
+78
-8
@@ -5,7 +5,7 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::ast::{
|
||||
Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Stmt, UnaryOp,
|
||||
Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Param, Stmt, UnaryOp,
|
||||
};
|
||||
use crate::builtin::{
|
||||
builtin_at, builtin_int, builtin_join, builtin_len, builtin_split, builtin_str, builtin_trim,
|
||||
@@ -161,8 +161,8 @@ impl Interpreter {
|
||||
env.set(k.clone(), v.clone());
|
||||
}
|
||||
for p in &fun.params {
|
||||
if env.get(p).is_none() {
|
||||
env.set(p.clone(), Value::None);
|
||||
if env.get(&p.name).is_none() {
|
||||
env.set(p.name.clone(), Value::None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -456,7 +456,7 @@ impl Interpreter {
|
||||
}
|
||||
|
||||
if let Some(recv_name) = &call.receiver {
|
||||
return self.eval_method_call(module, env, recv_name, &call.callee, &ev_args);
|
||||
return self.eval_method_call(module, fun, env, recv_name, &call.callee, &ev_args);
|
||||
}
|
||||
|
||||
match call.callee.as_str() {
|
||||
@@ -607,13 +607,17 @@ impl Interpreter {
|
||||
let target = lookup_function(module, fun, &call.callee)
|
||||
.ok_or_else(|| self.err(format!("unknown function `{}`", call.callee)))?;
|
||||
|
||||
let bound = bind_args(&target.params, &ev_args, false).map_err(|m| self.err(m))?;
|
||||
let bound = bind_function_args(self, module, fun, env, &target.params, &ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let mut call_env = Env::new();
|
||||
for (k, v) in bound {
|
||||
call_env.set(k, v);
|
||||
}
|
||||
|
||||
let result = self.run_function(module, target, call_env, &[])?;
|
||||
self.host.push_call_site_line(self.host.current_line);
|
||||
let result = self.run_function(module, target, call_env, &[]);
|
||||
self.host.pop_call_site_line();
|
||||
let result = result?;
|
||||
if target.is_object() {
|
||||
Ok(tag_instance(&target.name, result))
|
||||
} else {
|
||||
@@ -624,6 +628,7 @@ impl Interpreter {
|
||||
fn eval_method_call(
|
||||
&mut self,
|
||||
module: &Module,
|
||||
fun: &Function,
|
||||
env: &mut Env,
|
||||
recv_name: &str,
|
||||
method: &str,
|
||||
@@ -642,14 +647,18 @@ impl Interpreter {
|
||||
.iter()
|
||||
.find(|c| c.name == method)
|
||||
.ok_or_else(|| self.err(format!("unknown method `{type_name}.{method}`")))?;
|
||||
let bound = bind_args(&target.params, ev_args, false).map_err(|m| self.err(m))?;
|
||||
let bound = bind_function_args(self, module, fun, env, &target.params, ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let mut call_env = Env::new();
|
||||
for (k, v) in bound {
|
||||
call_env.set(k, v);
|
||||
}
|
||||
call_env.set("自".into(), recv.clone());
|
||||
call_env.set("self".into(), recv);
|
||||
self.run_function(module, target, call_env, &[])
|
||||
self.host.push_call_site_line(self.host.current_line);
|
||||
let result = self.run_function(module, target, call_env, &[]);
|
||||
self.host.pop_call_site_line();
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -684,6 +693,67 @@ fn tag_instance(type_name: &str, value: Value) -> Value {
|
||||
}
|
||||
|
||||
/// Bind evaluated args onto parameter names. Err is a plain message (caller adds span/path).
|
||||
fn bind_function_args(
|
||||
interp: &mut Interpreter,
|
||||
module: &Module,
|
||||
caller: &Function,
|
||||
caller_env: &mut Env,
|
||||
params: &[Param],
|
||||
args: &[EvArg],
|
||||
allow_missing: bool,
|
||||
) -> std::result::Result<HashMap<String, Value>, String> {
|
||||
let mut named: HashMap<String, Value> = HashMap::new();
|
||||
let mut positionals = Vec::new();
|
||||
for a in args {
|
||||
match a {
|
||||
EvArg::Positional(v) => positionals.push(v.clone()),
|
||||
EvArg::Named(k, v) => {
|
||||
if named.contains_key(k) {
|
||||
return Err(format!("duplicate named argument `{k}`"));
|
||||
}
|
||||
named.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut out: HashMap<String, Value> = HashMap::new();
|
||||
let mut used_named = HashSet::new();
|
||||
let mut pos_i = 0usize;
|
||||
|
||||
for p in params {
|
||||
if let Some(v) = named.get(&p.name) {
|
||||
out.insert(p.name.clone(), v.clone());
|
||||
used_named.insert(p.name.clone());
|
||||
} else if pos_i < positionals.len() {
|
||||
out.insert(p.name.clone(), positionals[pos_i].clone());
|
||||
pos_i += 1;
|
||||
} else if let Some(def) = &p.default {
|
||||
let v = interp
|
||||
.eval_expr(module, caller, caller_env, def)
|
||||
.map_err(|e| e.to_string())?;
|
||||
out.insert(p.name.clone(), v);
|
||||
} else if !allow_missing {
|
||||
return Err(format!("missing argument for parameter `{}`", p.name));
|
||||
}
|
||||
}
|
||||
|
||||
if pos_i < positionals.len() {
|
||||
return Err(format!(
|
||||
"too many positional arguments ({} extra)",
|
||||
positionals.len() - pos_i
|
||||
));
|
||||
}
|
||||
|
||||
for (k, v) in named {
|
||||
if !used_named.contains(&k) && !out.contains_key(&k) {
|
||||
out.insert(k, v);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Bind evaluated args onto parameter names (host / plugin functions).
|
||||
fn bind_args(
|
||||
params: &[String],
|
||||
args: &[EvArg],
|
||||
|
||||
+60
-1
@@ -11,6 +11,8 @@ use std::fmt;
|
||||
pub enum LineKind {
|
||||
Blank,
|
||||
Comment,
|
||||
/// Jupyter-style persisted output (`<!-- marqdo-out … -->`).
|
||||
Writeback,
|
||||
Code,
|
||||
}
|
||||
|
||||
@@ -19,6 +21,7 @@ impl fmt::Display for LineKind {
|
||||
match self {
|
||||
LineKind::Blank => write!(f, "Blank"),
|
||||
LineKind::Comment => write!(f, "Comment"),
|
||||
LineKind::Writeback => write!(f, "Writeback"),
|
||||
LineKind::Code => write!(f, "Code"),
|
||||
}
|
||||
}
|
||||
@@ -40,6 +43,25 @@ fn is_code_starter(c: char) -> bool {
|
||||
) || c.is_ascii_digit()
|
||||
}
|
||||
|
||||
/// `*` / `**` lines that are Marqdo executable (statement / return / else), not narrative Markdown.
|
||||
fn is_marqdo_star_line(trimmed: &str) -> bool {
|
||||
if trimmed == "*" || trimmed == "****" {
|
||||
return true;
|
||||
}
|
||||
if trimmed.starts_with("**") {
|
||||
if trimmed.trim() == "** **" {
|
||||
return true;
|
||||
}
|
||||
if let Some(rest) = trimmed.strip_prefix("**") {
|
||||
if let Some(pos) = rest.find("**") {
|
||||
return rest[pos + 2..].trim().is_empty();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
trimmed.starts_with('*') && trimmed.ends_with('*') && trimmed.len() >= 2
|
||||
}
|
||||
|
||||
/// Classify a single logical line (no trailing newline required).
|
||||
///
|
||||
/// This is the **paragraph-start** rule only. Prefer [`classify_source`] for
|
||||
@@ -49,9 +71,11 @@ pub fn classify_line(text: &str) -> LineKind {
|
||||
if trimmed.chars().all(|c| c.is_whitespace()) {
|
||||
return LineKind::Blank;
|
||||
}
|
||||
let trimmed = text.trim();
|
||||
let first = trimmed.chars().find(|c| !c.is_whitespace());
|
||||
match first {
|
||||
None => LineKind::Blank,
|
||||
Some('*') if !is_marqdo_star_line(trimmed) => LineKind::Comment,
|
||||
Some(c) if is_code_starter(c) => LineKind::Code,
|
||||
Some(_) => LineKind::Comment,
|
||||
}
|
||||
@@ -74,12 +98,18 @@ pub fn classify_source(source: &str) -> Vec<ClassifiedLine> {
|
||||
let mut in_comment_paragraph = false;
|
||||
let mut in_math_fence = false;
|
||||
let mut in_md_fence = false;
|
||||
let mut in_writeback = false;
|
||||
|
||||
for (i, text) in lines.into_iter().enumerate() {
|
||||
let base = classify_line(text);
|
||||
let trimmed = text.trim();
|
||||
let structural = is_structural_code_line(trimmed);
|
||||
let kind = if in_math_fence {
|
||||
let kind = if in_writeback {
|
||||
if trimmed.contains("-->") {
|
||||
in_writeback = false;
|
||||
}
|
||||
LineKind::Writeback
|
||||
} else if in_math_fence {
|
||||
if trimmed == "$$" {
|
||||
in_math_fence = false;
|
||||
}
|
||||
@@ -94,6 +124,13 @@ pub fn classify_source(source: &str) -> Vec<ClassifiedLine> {
|
||||
in_md_fence = true;
|
||||
in_comment_paragraph = false;
|
||||
LineKind::Comment
|
||||
} else if trimmed.starts_with("<!--") && trimmed.contains("marqdo-out") {
|
||||
in_writeback = true;
|
||||
in_comment_paragraph = false;
|
||||
if trimmed.contains("-->") {
|
||||
in_writeback = false;
|
||||
}
|
||||
LineKind::Writeback
|
||||
} else {
|
||||
match base {
|
||||
LineKind::Blank => {
|
||||
@@ -109,6 +146,7 @@ pub fn classify_source(source: &str) -> Vec<ClassifiedLine> {
|
||||
LineKind::Code
|
||||
}
|
||||
LineKind::Code if in_comment_paragraph => LineKind::Comment,
|
||||
LineKind::Writeback => LineKind::Writeback,
|
||||
LineKind::Code => {
|
||||
// Multi-line math fence opener (not same-line `$$…$$`).
|
||||
if trimmed == "$$" {
|
||||
@@ -196,6 +234,27 @@ mod tests {
|
||||
assert_eq!(classify_line("`x` = 1"), LineKind::Code);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrative_bold_in_comment_paragraph() {
|
||||
let src = "说明如下:\n\n**强调信息**是什么什么\n\n> print text=ok\n";
|
||||
let lines = classify_source(src);
|
||||
assert_eq!(lines[0].kind, LineKind::Comment);
|
||||
assert_eq!(lines[1].kind, LineKind::Blank);
|
||||
assert_eq!(lines[2].kind, LineKind::Comment, "bold prose is comment");
|
||||
assert_eq!(lines[3].kind, LineKind::Blank);
|
||||
assert_eq!(lines[4].kind, LineKind::Code);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writeback_block_classified() {
|
||||
let src = "*`x` = 1*\n<!-- marqdo-out @line=1\n3\n-->\n";
|
||||
let lines = classify_source(src);
|
||||
assert_eq!(lines[0].kind, LineKind::Code);
|
||||
assert_eq!(lines[1].kind, LineKind::Writeback);
|
||||
assert_eq!(lines[2].kind, LineKind::Writeback);
|
||||
assert_eq!(lines[3].kind, LineKind::Writeback);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraph_comment_keeps_backtick_continuation() {
|
||||
let src = "采用了\n`.mq.md`的双层后缀\n\n> print text=ok\n";
|
||||
|
||||
+142
-6
@@ -286,6 +286,9 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
return Ok(e);
|
||||
}
|
||||
if self.eat("\"") {
|
||||
return self.parse_quoted_string();
|
||||
}
|
||||
if self.eat("`") {
|
||||
let start = self.i;
|
||||
while let Some(c) = self.peek_char() {
|
||||
@@ -345,7 +348,7 @@ impl<'a> Parser<'a> {
|
||||
{
|
||||
let start = self.i;
|
||||
while let Some(c) = self.peek_char() {
|
||||
if c.is_whitespace() || matches!(c, '=' | '+' | '-' | '*' | '/' | '<' | '>' | '(' | ')' | '`' | '|' | ',')
|
||||
if c.is_whitespace() || matches!(c, '=' | '+' | '-' | '*' | '/' | '<' | '>' | '(' | ')' | '`' | '|' | ',' | '"')
|
||||
{
|
||||
break;
|
||||
}
|
||||
@@ -356,6 +359,70 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
bail!("unexpected expression input: {:?}", self.rest());
|
||||
}
|
||||
|
||||
/// `"..."` string with `\n` `\t` `\r` `\\` `\"` and `` `var` `` interpolation.
|
||||
fn parse_quoted_string(&mut self) -> Result<Expr> {
|
||||
use crate::ast::InterpPart;
|
||||
let mut parts: Vec<InterpPart> = Vec::new();
|
||||
let mut lit = String::new();
|
||||
loop {
|
||||
let Some(c) = self.peek_char() else {
|
||||
bail!("unterminated \" string");
|
||||
};
|
||||
if c == '"' {
|
||||
self.bump_char();
|
||||
break;
|
||||
}
|
||||
if c == '\\' {
|
||||
self.bump_char();
|
||||
let esc = self.peek_char().ok_or_else(|| anyhow::anyhow!("dangling \\ in string"))?;
|
||||
self.bump_char();
|
||||
lit.push(match esc {
|
||||
'n' => '\n',
|
||||
't' => '\t',
|
||||
'r' => '\r',
|
||||
'\\' => '\\',
|
||||
'"' => '"',
|
||||
other => bail!("unknown escape \\{other} in string"),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if c == '`' {
|
||||
if !lit.is_empty() {
|
||||
parts.push(InterpPart::Lit(std::mem::take(&mut lit)));
|
||||
}
|
||||
self.bump_char();
|
||||
let start = self.i;
|
||||
while let Some(ch) = self.peek_char() {
|
||||
if ch == '`' {
|
||||
break;
|
||||
}
|
||||
self.bump_char();
|
||||
}
|
||||
let name = self.src[start..self.i].to_string();
|
||||
if !self.eat("`") {
|
||||
bail!("unterminated `name` in string");
|
||||
}
|
||||
parts.push(InterpPart::Var(name));
|
||||
continue;
|
||||
}
|
||||
lit.push(c);
|
||||
self.bump_char();
|
||||
}
|
||||
if !lit.is_empty() {
|
||||
parts.push(InterpPart::Lit(lit));
|
||||
}
|
||||
if parts.is_empty() {
|
||||
return Ok(Expr::Literal(Literal::Text(String::new())));
|
||||
}
|
||||
if parts.len() == 1 {
|
||||
return Ok(match parts.remove(0) {
|
||||
InterpPart::Lit(t) => Expr::Literal(Literal::Text(t)),
|
||||
InterpPart::Var(n) => Expr::Var(n),
|
||||
});
|
||||
}
|
||||
Ok(Expr::Interp(parts))
|
||||
}
|
||||
}
|
||||
|
||||
fn is_word_end(s: &str, len: usize) -> bool {
|
||||
@@ -468,6 +535,11 @@ fn try_named_arg(s: &str) -> Option<(String, &str)> {
|
||||
|
||||
fn split_first_token(s: &str) -> (&str, &str) {
|
||||
let s = s.trim_start();
|
||||
if s.starts_with('"') {
|
||||
if let Some(end) = end_of_quoted_string(s) {
|
||||
return (&s[..end], &s[end..]);
|
||||
}
|
||||
}
|
||||
if s.starts_with('`') {
|
||||
// `` `name` `` as one token
|
||||
if let Some(end) = s[1..].find('`') {
|
||||
@@ -482,14 +554,36 @@ fn split_first_token(s: &str) -> (&str, &str) {
|
||||
}
|
||||
|
||||
fn find_next_arg_boundary(after_eq: &str) -> usize {
|
||||
// Look for ` <ident>=` pattern not inside backticks (UTF-8 safe).
|
||||
// Look for ` <ident>=` pattern not inside backticks or quoted strings.
|
||||
let mut in_bt = false;
|
||||
for (i, c) in after_eq.char_indices() {
|
||||
if c == '`' {
|
||||
in_bt = !in_bt;
|
||||
let mut in_str = false;
|
||||
let mut chars = after_eq.char_indices().peekable();
|
||||
while let Some((i, c)) = chars.next() {
|
||||
if in_str {
|
||||
if c == '\\' {
|
||||
chars.next();
|
||||
continue;
|
||||
}
|
||||
if c == '"' {
|
||||
in_str = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !in_bt && c.is_whitespace() {
|
||||
if in_bt {
|
||||
if c == '`' {
|
||||
in_bt = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if c == '`' {
|
||||
in_bt = true;
|
||||
continue;
|
||||
}
|
||||
if c == '"' {
|
||||
in_str = true;
|
||||
continue;
|
||||
}
|
||||
if c.is_whitespace() {
|
||||
let rest = &after_eq[i..];
|
||||
let trimmed = rest.trim_start();
|
||||
let skipped = rest.len() - trimmed.len();
|
||||
@@ -509,6 +603,28 @@ fn find_next_arg_boundary(after_eq: &str) -> usize {
|
||||
after_eq.len()
|
||||
}
|
||||
|
||||
/// Byte index after a leading `"..."` token (opening quote included in slice).
|
||||
fn end_of_quoted_string(s: &str) -> Option<usize> {
|
||||
if !s.starts_with('"') {
|
||||
return None;
|
||||
}
|
||||
let mut escaped = false;
|
||||
for (i, c) in s.char_indices().skip(1) {
|
||||
if escaped {
|
||||
escaped = false;
|
||||
continue;
|
||||
}
|
||||
if c == '\\' {
|
||||
escaped = true;
|
||||
continue;
|
||||
}
|
||||
if c == '"' {
|
||||
return Some(i + c.len_utf8());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Parse `> callee args` call expression/statement text (without leading `>`).
|
||||
pub fn parse_call_after_gt(after_gt: &str) -> Result<CallExpr> {
|
||||
let (call, _) = parse_call_tail(after_gt.trim())?;
|
||||
@@ -527,6 +643,26 @@ mod tests {
|
||||
assert!(matches!(e, Expr::Binary { op: BinaryOp::Add, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quoted_string_escapes() {
|
||||
let e = parse_expr("\"a\\nb\"").unwrap();
|
||||
assert!(matches!(
|
||||
e,
|
||||
Expr::Literal(Literal::Text(ref s)) if s == "a\nb"
|
||||
));
|
||||
let e = parse_expr("\"hi `x`!\"").unwrap();
|
||||
assert!(matches!(e, Expr::Interp(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_token_no_escape() {
|
||||
let e = parse_expr("a\\nb").unwrap();
|
||||
assert!(matches!(
|
||||
e,
|
||||
Expr::Literal(Literal::Text(ref s)) if s == "a\\nb"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chinese_logic_and_literals() {
|
||||
let e = parse_expr("`a` 且 非 `b`").unwrap();
|
||||
|
||||
+78
-17
@@ -63,7 +63,7 @@ impl<'a> Cursor<'a> {
|
||||
fn skip_noise(&mut self) -> bool {
|
||||
while let Some(l) = self.peek() {
|
||||
match l.kind {
|
||||
LineKind::Blank | LineKind::Comment => {
|
||||
LineKind::Blank | LineKind::Comment | LineKind::Writeback => {
|
||||
self.i += 1;
|
||||
}
|
||||
LineKind::Code => return true,
|
||||
@@ -179,7 +179,7 @@ impl<'a> Cursor<'a> {
|
||||
}
|
||||
|
||||
// Nested params mid-body shouldn't happen; treat `-` as control flow.
|
||||
if trimmed.starts_with('+') || is_ordered_branch(trimmed) {
|
||||
if is_ordered_branch(trimmed) {
|
||||
fun.body.push(self.parse_branch()?);
|
||||
continue;
|
||||
}
|
||||
@@ -495,9 +495,7 @@ impl<'a> Cursor<'a> {
|
||||
break;
|
||||
}
|
||||
let trimmed = l.text.trim();
|
||||
let cond_src = if let Some(rest) = trimmed.strip_prefix('+') {
|
||||
rest.trim()
|
||||
} else if let Some(rest) = strip_ordered(trimmed) {
|
||||
let cond_src = if let Some(rest) = strip_ordered(trimmed) {
|
||||
rest
|
||||
} else {
|
||||
break;
|
||||
@@ -571,7 +569,7 @@ impl<'a> Cursor<'a> {
|
||||
if is_heading(trimmed) {
|
||||
break;
|
||||
}
|
||||
if trimmed.starts_with('+') || is_ordered_branch(trimmed) {
|
||||
if is_ordered_branch(trimmed) {
|
||||
// Nested branch inside body
|
||||
body.push(self.parse_branch()?);
|
||||
continue;
|
||||
@@ -618,34 +616,59 @@ fn try_parse_inline_formula(rhs: &str) -> Result<Option<Expr>> {
|
||||
bail!("incomplete inline formula (expected `$$…$$` on one line)");
|
||||
}
|
||||
|
||||
fn parse_param_line(trimmed: &str) -> Option<String> {
|
||||
let rest = trimmed.strip_prefix('-')?.trim();
|
||||
if rest.is_empty() || rest.contains('`') || rest.contains('[') || rest.contains('=') {
|
||||
fn parse_backtick_ident(s: &str) -> Option<String> {
|
||||
let s = s.trim();
|
||||
if !s.starts_with('`') {
|
||||
return None;
|
||||
}
|
||||
if rest.split_whitespace().count() != 1 {
|
||||
let inner = &s[1..];
|
||||
let end = inner.find('`')?;
|
||||
let name = &inner[..end];
|
||||
if name.is_empty() || s.len() != end + 2 {
|
||||
return None;
|
||||
}
|
||||
// Reject if looks like comparison / operator expr
|
||||
if rest.contains('>') || rest.contains('<') || rest.contains('+') || rest.contains('*') {
|
||||
Some(name.to_string())
|
||||
}
|
||||
|
||||
fn parse_param_line(trimmed: &str) -> Option<crate::ast::Param> {
|
||||
use crate::ast::Param;
|
||||
let rest = trimmed.strip_prefix('+')?.trim();
|
||||
if rest.is_empty() || !rest.starts_with('`') {
|
||||
return None;
|
||||
}
|
||||
Some(rest.to_string())
|
||||
let end_tick = rest[1..].find('`')?;
|
||||
let name = rest[1..end_tick + 1].to_string();
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let after = rest[end_tick + 2..].trim();
|
||||
let default = if let Some(def_s) = after.strip_prefix('=') {
|
||||
let def_s = def_s.trim();
|
||||
if def_s.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(parse_value_or_interp(def_s).ok()?)
|
||||
} else if after.is_empty() {
|
||||
None
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
Some(Param { name, default })
|
||||
}
|
||||
|
||||
fn parse_foreach_header(rest: &str) -> Option<(String, String)> {
|
||||
// [item](collection)
|
||||
// [`item`](`collection`)
|
||||
let rest = rest.trim();
|
||||
if !rest.starts_with('[') {
|
||||
return None;
|
||||
}
|
||||
let end_item = rest.find(']')?;
|
||||
let item = rest[1..end_item].to_string();
|
||||
let item = parse_backtick_ident(&rest[1..end_item])?;
|
||||
let after = rest[end_item + 1..].trim_start();
|
||||
if !after.starts_with('(') || !after.ends_with(')') {
|
||||
return None;
|
||||
}
|
||||
let coll = after[1..after.len() - 1].to_string();
|
||||
let coll = parse_backtick_ident(&after[1..after.len() - 1])?;
|
||||
Some((item, coll))
|
||||
}
|
||||
|
||||
@@ -762,7 +785,45 @@ mod tests {
|
||||
let main = m.functions.iter().find(|f| f.name == "main").unwrap();
|
||||
assert_eq!(main.children.len(), 1);
|
||||
assert_eq!(main.children[0].name, "问候");
|
||||
assert_eq!(main.children[0].params, vec!["谁".to_string()]);
|
||||
assert_eq!(main.children[0].params[0].name, "谁");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_optional_param_default() {
|
||||
let src = "# main\n\n## f\n + `a`\n + `b`=Hi\n\n> print text=`a`\n";
|
||||
let m = parse_source(src).unwrap();
|
||||
let f = &m.functions[0].children[0];
|
||||
assert_eq!(f.params.len(), 2);
|
||||
assert_eq!(f.params[0].name, "a");
|
||||
assert_eq!(f.params[1].name, "b");
|
||||
assert!(matches!(
|
||||
f.params[1].default,
|
||||
Some(Expr::Literal(Literal::Text(ref s))) if s == "Hi"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_foreach_backtick_ids() {
|
||||
let src = "# main\n\n- [`x`](`xs`)\n > print text=`x`\n";
|
||||
let m = parse_source(src).unwrap();
|
||||
match &m.functions[0].body[0] {
|
||||
Stmt::ForEach { item, collection, .. } => {
|
||||
assert_eq!(item, "x");
|
||||
assert_eq!(collection, "xs");
|
||||
}
|
||||
other => panic!("expected foreach, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_branch_rejects_plus_arm() {
|
||||
let src = "# main\n\n+ `x` > 0\n > print text=ok\n";
|
||||
let err = parse_source(src).unwrap_err();
|
||||
let msg = format!("{err}");
|
||||
assert!(
|
||||
msg.contains("unrecognized") || msg.contains("empty branch"),
|
||||
"{msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+30
-10
@@ -250,6 +250,7 @@ h1.page {
|
||||
vertical-align: middle;
|
||||
}
|
||||
.status-pill.ok { background: var(--surface); color: var(--muted); }
|
||||
.status-pill.pending { background: var(--surface); color: var(--ink); border-color: var(--ink); }
|
||||
.status-pill.fail { background: var(--ink); color: #fff; border-color: var(--ink); }
|
||||
section.block { margin: 2rem 0; }
|
||||
section.block > h2 {
|
||||
@@ -469,6 +470,17 @@ section.block > h2 {
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.output-card {
|
||||
border-left: 3px solid #2563eb;
|
||||
background: #f8fafc;
|
||||
}
|
||||
.output-card .output-body {
|
||||
margin: 0.35rem 0 0;
|
||||
padding: 0.5rem 0.65rem;
|
||||
font: 0.85rem/1.45 var(--mono);
|
||||
white-space: pre-wrap;
|
||||
color: #0f172a;
|
||||
}
|
||||
.code-head {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
@@ -968,18 +980,26 @@ pub fn page_index(files: &[PathBuf], only: Option<&Path>, links: &LinkMode) -> S
|
||||
|
||||
pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkMode) -> String {
|
||||
let nav = nav_html(files, Some(rel), links);
|
||||
let status = if vm.ok { "ok" } else { "fail" };
|
||||
let status_label = if vm.ok { "ok" } else { "fail" };
|
||||
let out_text = if vm.ok {
|
||||
if vm.stdout.is_empty() {
|
||||
"(no stdout)".into()
|
||||
} else {
|
||||
escape(&vm.stdout)
|
||||
}
|
||||
let (status, status_label, out_text) = if vm.awaiting_input {
|
||||
(
|
||||
"pending",
|
||||
"input",
|
||||
"Fill preset input below, then click <strong>Run with input</strong>.".to_string(),
|
||||
)
|
||||
} else if vm.ok {
|
||||
(
|
||||
"ok",
|
||||
"ok",
|
||||
if vm.stdout.is_empty() {
|
||||
"(no stdout)".into()
|
||||
} else {
|
||||
escape(&vm.stdout)
|
||||
},
|
||||
)
|
||||
} else if vm.stderr.is_empty() {
|
||||
"(skipped)".into()
|
||||
("fail", "fail", "(skipped)".into())
|
||||
} else {
|
||||
escape(&vm.stderr)
|
||||
("fail", "fail", escape(&vm.stderr))
|
||||
};
|
||||
let stdin_panel = if vm.input_prompts.is_empty() {
|
||||
String::new()
|
||||
|
||||
+49
-14
@@ -17,7 +17,7 @@ use std::process::Command;
|
||||
use anyhow::{bail, Context, Result};
|
||||
use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
|
||||
|
||||
use crate::input_feed::{effective_stdin, split_stdin_text};
|
||||
use crate::input_feed::{effective_stdin, extract_frontmatter_stdin, split_stdin_text};
|
||||
use crate::view::debug_page::{build_debug_model, page_debug};
|
||||
use crate::view::html::{escape, page_file, page_index, LinkMode};
|
||||
use crate::view::render::{collect_input_prompts, render_module_structure, FileViewModel};
|
||||
@@ -309,25 +309,30 @@ pub(crate) fn build_file_view(
|
||||
),
|
||||
};
|
||||
let effective = effective_stdin(&source, stdin_lines);
|
||||
let awaiting_input = awaiting_preset_input(&input_prompts, stdin_lines, &source);
|
||||
// Same host caps as `marqdo run`. Soft exit + sleep clamp only.
|
||||
let mut opts = RunOptions::default();
|
||||
opts.stdin_lines = effective.clone();
|
||||
opts.sleep_limit_ms = if live { Some(30_000) } else { Some(0) };
|
||||
// Optional: sandbox to the whole view tree so sibling folders are reachable.
|
||||
opts.fs_root = Some(root.root.clone());
|
||||
let (stdout, stderr, ok, plots) = match run_file_capture(abs, &opts) {
|
||||
Ok(cap) => (
|
||||
cap.stdout,
|
||||
String::new(),
|
||||
true,
|
||||
cap.plots.into_iter().map(|p| p.svg).collect(),
|
||||
),
|
||||
Err(e) => (
|
||||
String::new(),
|
||||
tidy_user_error(&format!("{e:#}"), abs, rel),
|
||||
false,
|
||||
Vec::new(),
|
||||
),
|
||||
let (stdout, stderr, ok, plots) = if awaiting_input {
|
||||
(String::new(), String::new(), true, Vec::new())
|
||||
} else {
|
||||
match run_file_capture(abs, &opts) {
|
||||
Ok(cap) => (
|
||||
cap.stdout,
|
||||
String::new(),
|
||||
true,
|
||||
cap.plots.into_iter().map(|p| p.svg).collect(),
|
||||
),
|
||||
Err(e) => (
|
||||
String::new(),
|
||||
tidy_user_error(&format!("{e:#}"), abs, rel),
|
||||
false,
|
||||
Vec::new(),
|
||||
),
|
||||
}
|
||||
};
|
||||
Ok(FileViewModel {
|
||||
rel_path: rel.to_string(),
|
||||
@@ -339,10 +344,22 @@ pub(crate) fn build_file_view(
|
||||
ok,
|
||||
preset_stdin: effective.join("\n"),
|
||||
input_prompts,
|
||||
awaiting_input,
|
||||
plots,
|
||||
})
|
||||
}
|
||||
|
||||
/// Defer execution until the view preset-input form supplies lines (no query stdin, no FM stdin).
|
||||
pub(crate) fn awaiting_preset_input(
|
||||
input_prompts: &[String],
|
||||
stdin_lines: &[String],
|
||||
source: &str,
|
||||
) -> bool {
|
||||
!input_prompts.is_empty()
|
||||
&& stdin_lines.is_empty()
|
||||
&& extract_frontmatter_stdin(source).is_empty()
|
||||
}
|
||||
|
||||
/// Prefer view-relative paths and strip Windows `\\?\` noise in error text.
|
||||
fn tidy_user_error(msg: &str, abs: &Path, rel: &str) -> String {
|
||||
use crate::diagnostics::display_path;
|
||||
@@ -544,3 +561,21 @@ fn open_url(url: &str) -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::awaiting_preset_input;
|
||||
|
||||
#[test]
|
||||
fn awaiting_input_when_no_stdin_source() {
|
||||
let src = include_str!("../../tests/keywords/input.mq.md");
|
||||
assert!(awaiting_preset_input(&["Name: ".into()], &[], src));
|
||||
assert!(!awaiting_preset_input(&["Name: ".into()], &["Ada".into()], src));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn not_awaiting_when_frontmatter_stdin() {
|
||||
let src = "---\nstdin: Ada\n---\n\n# main\n\n*`n` = > input*\n";
|
||||
assert!(!awaiting_preset_input(&["p".into()], &[], src));
|
||||
}
|
||||
}
|
||||
+32
-10
@@ -3,9 +3,12 @@
|
||||
//! Comments are not in the AST; they are interleaved from classified source lines.
|
||||
//! Expressions are shown in surface syntax, never Rust `Debug`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::ast::{
|
||||
Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Stmt, UnaryOp,
|
||||
};
|
||||
use crate::host::writeback;
|
||||
use crate::lex::{classify_source, ClassifiedLine, LineKind};
|
||||
use crate::view::html::escape;
|
||||
use pulldown_cmark::{html, Options, Parser};
|
||||
@@ -32,6 +35,8 @@ pub struct FileViewModel {
|
||||
/// One entry per `input` / `输入` call (prompt text; may be empty).
|
||||
/// Empty vec → page does not use input; hide the preset form.
|
||||
pub input_prompts: Vec<String>,
|
||||
/// Live view: program uses `input` but no stdin yet — execution deferred until form submit.
|
||||
pub awaiting_input: bool,
|
||||
/// SVG plots from math lib (embedded in Execution).
|
||||
pub plots: Vec<String>,
|
||||
}
|
||||
@@ -163,6 +168,7 @@ pub fn render_module_structure_mode(
|
||||
mode: StructureMode,
|
||||
) -> String {
|
||||
let lines = classify_source(source);
|
||||
let writebacks = writeback::writeback_map(source);
|
||||
let mut out = String::new();
|
||||
|
||||
if !module.imports.is_empty() {
|
||||
@@ -193,7 +199,7 @@ pub fn render_module_structure_mode(
|
||||
if i > 0 {
|
||||
out.push_str(&emit_comments(&lines, cursor, fun.span.line));
|
||||
}
|
||||
let (html, next) = render_fun(fun, &lines, 0, "", mode);
|
||||
let (html, next) = render_fun(fun, &lines, 0, "", mode, &writebacks);
|
||||
out.push_str(&html);
|
||||
cursor = next;
|
||||
}
|
||||
@@ -294,8 +300,7 @@ fn emit_comments(lines: &[ClassifiedLine], from_line: u32, before_line: u32) ->
|
||||
paragraph.push(text.to_string());
|
||||
}
|
||||
}
|
||||
LineKind::Blank => flush(&mut paragraph, &mut s),
|
||||
LineKind::Code => flush(&mut paragraph, &mut s),
|
||||
LineKind::Blank | LineKind::Writeback | LineKind::Code => flush(&mut paragraph, &mut s),
|
||||
}
|
||||
}
|
||||
flush(&mut paragraph, &mut s);
|
||||
@@ -320,6 +325,7 @@ fn render_fun(
|
||||
depth: usize,
|
||||
parent_path: &str,
|
||||
mode: StructureMode,
|
||||
writebacks: &HashMap<u32, String>,
|
||||
) -> (String, u32) {
|
||||
let fn_path = fn_path(parent_path, &fun.name);
|
||||
let mut s = String::new();
|
||||
@@ -338,7 +344,7 @@ fn render_fun(
|
||||
if !fun.params.is_empty() {
|
||||
s.push_str("<div class=\"params\">");
|
||||
for p in &fun.params {
|
||||
s.push_str(&format!("<span class=\"chip\">{}</span>", escape(p)));
|
||||
s.push_str(&format!("<span class=\"chip\">{}</span>", escape(&p.name)));
|
||||
}
|
||||
s.push_str("</div>");
|
||||
}
|
||||
@@ -375,14 +381,14 @@ fn render_fun(
|
||||
let stmt = &fun.body[bi];
|
||||
let start = stmt_start(stmt);
|
||||
s.push_str(&emit_comments(lines, cursor, start));
|
||||
let (html, end) = render_stmt(stmt, lines, mode);
|
||||
let (html, end) = render_stmt(stmt, lines, mode, writebacks);
|
||||
s.push_str(&html);
|
||||
cursor = end;
|
||||
bi += 1;
|
||||
} else {
|
||||
let child = &fun.children[ci];
|
||||
s.push_str(&emit_comments(lines, cursor, child.span.line));
|
||||
let (html, end) = render_fun(child, lines, depth + 1, &fn_path, mode);
|
||||
let (html, end) = render_fun(child, lines, depth + 1, &fn_path, mode, writebacks);
|
||||
s.push_str(&format!("<div class=\"nested\">{html}</div>"));
|
||||
cursor = end;
|
||||
ci += 1;
|
||||
@@ -427,7 +433,22 @@ fn stmt_end_line(stmt: &Stmt) -> u32 {
|
||||
}
|
||||
}
|
||||
|
||||
fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine], mode: StructureMode) -> (String, u32) {
|
||||
fn output_card(line: u32, writebacks: &HashMap<u32, String>) -> String {
|
||||
match writebacks.get(&line) {
|
||||
Some(body) => format!(
|
||||
r#"<div class="card output-card"><span class="badge">output</span><pre class="output-body">{}</pre></div>"#,
|
||||
escape(body)
|
||||
),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn render_stmt(
|
||||
stmt: &Stmt,
|
||||
lines: &[ClassifiedLine],
|
||||
mode: StructureMode,
|
||||
writebacks: &HashMap<u32, String>,
|
||||
) -> (String, u32) {
|
||||
let end = stmt_end_line(stmt);
|
||||
let line = stmt_start(stmt);
|
||||
let inner = match stmt {
|
||||
@@ -509,7 +530,7 @@ fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine], mode: StructureMode) -> (S
|
||||
for st in &arm.body {
|
||||
let start = stmt_start(st);
|
||||
body.push_str(&emit_comments(lines, arm_cursor, start));
|
||||
let (h, e) = render_stmt(st, lines, mode);
|
||||
let (h, e) = render_stmt(st, lines, mode, writebacks);
|
||||
body.push_str(&h);
|
||||
arm_cursor = e;
|
||||
}
|
||||
@@ -529,7 +550,7 @@ fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine], mode: StructureMode) -> (S
|
||||
for st in body {
|
||||
let start = stmt_start(st);
|
||||
body_html.push_str(&emit_comments(lines, cursor, start));
|
||||
let (h, e) = render_stmt(st, lines, mode);
|
||||
let (h, e) = render_stmt(st, lines, mode, writebacks);
|
||||
body_html.push_str(&h);
|
||||
cursor = e;
|
||||
}
|
||||
@@ -551,7 +572,7 @@ fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine], mode: StructureMode) -> (S
|
||||
for st in body {
|
||||
let start = stmt_start(st);
|
||||
body_html.push_str(&emit_comments(lines, cursor, start));
|
||||
let (h, e) = render_stmt(st, lines, mode);
|
||||
let (h, e) = render_stmt(st, lines, mode, writebacks);
|
||||
body_html.push_str(&h);
|
||||
cursor = e;
|
||||
}
|
||||
@@ -559,6 +580,7 @@ fn render_stmt(stmt: &Stmt, lines: &[ClassifiedLine], mode: StructureMode) -> (S
|
||||
body_html
|
||||
}
|
||||
};
|
||||
let inner = format!("{}{}", inner, output_card(line, writebacks));
|
||||
(stmt_shell(line, &inner, mode), end)
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user