Add bilingual public docs, keyword aliases, and frontmatter stdin for view.
English/Chinese user pages sit side by side; L0 builtins and lib/ text|表 dual APIs land with gold coverage. Capture/view input demos use stdin:/输入: so static export and first page load succeed. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
fd36b92224
commit
a5d30c00b3
68 files changed
+1812
-241
No files matched your search
@@ -0,0 +1,89 @@
|
||||
//! Canonical names and Chinese aliases for L0 keywords / builtins / params.
|
||||
//!
|
||||
//! See `doc/design/keywords-i18n.md`. No language mode — aliases are equivalent.
|
||||
|
||||
/// Map a literal / logic keyword to its English canonical form, if reserved.
|
||||
pub fn canonical_keyword(name: &str) -> Option<&'static str> {
|
||||
match name {
|
||||
"True" | "真" => Some("True"),
|
||||
"False" | "假" => Some("False"),
|
||||
"None" | "空" => Some("None"),
|
||||
"and" | "且" => Some("and"),
|
||||
"or" | "或" => Some("or"),
|
||||
"not" | "非" => Some("not"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_reserved_keyword(name: &str) -> bool {
|
||||
canonical_keyword(name).is_some()
|
||||
}
|
||||
|
||||
/// Map a builtin callee (EN or ZH alias) to its English canonical name.
|
||||
/// Host primitives without ZH L0 aliases only match English.
|
||||
pub fn canonical_builtin(name: &str) -> Option<&'static str> {
|
||||
match name {
|
||||
"print" | "打印" => Some("print"),
|
||||
"input" | "输入" => Some("input"),
|
||||
"len" | "长度" => Some("len"),
|
||||
"str" | "文本" => Some("str"),
|
||||
"int" | "整数" => Some("int"),
|
||||
"type" => Some("type"),
|
||||
"trim" => Some("trim"),
|
||||
"split" => Some("split"),
|
||||
"join" => Some("join"),
|
||||
"at" => Some("at"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalize a named-argument key for a builtin to the English param name.
|
||||
pub fn canonical_param(builtin: &str, param: &str) -> String {
|
||||
let b = canonical_builtin(builtin).unwrap_or(builtin);
|
||||
match (b, param) {
|
||||
("print", "text" | "内容") => "text".into(),
|
||||
("input", "prompt" | "提示") => "prompt".into(),
|
||||
("len" | "str" | "int" | "type" | "trim", "value" | "值") => "value".into(),
|
||||
("split" | "join", "value" | "值") => "value".into(),
|
||||
("split" | "join", "sep" | "分隔") => "sep".into(),
|
||||
("at", "value" | "值") => "value".into(),
|
||||
("at", "index" | "下标") => "index".into(),
|
||||
_ => param.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rewrite callee + named args to English canonical forms when this is a builtin.
|
||||
/// Returns the callee to dispatch on (canonical builtin or original user/fn name).
|
||||
pub fn normalize_call_callee_and_args(callee: &str, args: &mut [crate::ast::Arg]) -> String {
|
||||
match canonical_builtin(callee) {
|
||||
Some(canon) => {
|
||||
for a in args.iter_mut() {
|
||||
if let crate::ast::Arg::Named { name, .. } = a {
|
||||
*name = canonical_param(canon, name);
|
||||
}
|
||||
}
|
||||
canon.to_string()
|
||||
}
|
||||
None => callee.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn keyword_aliases() {
|
||||
assert_eq!(canonical_keyword("真"), Some("True"));
|
||||
assert_eq!(canonical_keyword("且"), Some("and"));
|
||||
assert!(is_reserved_keyword("空"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_aliases() {
|
||||
assert_eq!(canonical_builtin("打印"), Some("print"));
|
||||
assert_eq!(canonical_builtin("长度"), Some("len"));
|
||||
assert_eq!(canonical_param("打印", "内容"), "text");
|
||||
assert_eq!(canonical_param("print", "内容"), "text");
|
||||
}
|
||||
}
|
||||
@@ -30,3 +30,81 @@ pub fn builtin_int(v: &Value) -> Result<i64, String> {
|
||||
_ => Err("int needs int, bool, or text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `type`: type tag as text (`none` / `bool` / `int` / `text` / `list`).
|
||||
pub fn builtin_type(v: &Value) -> Value {
|
||||
Value::Text(
|
||||
match v {
|
||||
Value::None => "none",
|
||||
Value::Bool(_) => "bool",
|
||||
Value::Int(_) => "int",
|
||||
Value::Text(_) => "text",
|
||||
Value::List(_) => "list",
|
||||
}
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
|
||||
/// `trim`: strip leading/trailing Unicode whitespace from text.
|
||||
pub fn builtin_trim(v: &Value) -> Result<Value, String> {
|
||||
match v {
|
||||
Value::Text(s) => Ok(Value::Text(s.trim().to_string())),
|
||||
_ => Err("trim needs text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `split`: split text by separator → list of text parts.
|
||||
pub fn builtin_split(value: &Value, sep: &Value) -> Result<Value, String> {
|
||||
let text = match value {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("split needs text value".into()),
|
||||
};
|
||||
let sep = match sep {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("split needs text sep".into()),
|
||||
};
|
||||
if sep.is_empty() {
|
||||
return Err("split sep must not be empty".into());
|
||||
}
|
||||
let parts: Vec<Value> = text
|
||||
.split(sep)
|
||||
.map(|p| Value::Text(p.to_string()))
|
||||
.collect();
|
||||
Ok(Value::List(parts))
|
||||
}
|
||||
|
||||
/// `join`: join list elements with separator → text.
|
||||
pub fn builtin_join(value: &Value, sep: &Value) -> Result<Value, String> {
|
||||
let items = match value {
|
||||
Value::List(xs) => xs,
|
||||
_ => return Err("join needs list value".into()),
|
||||
};
|
||||
let sep = match sep {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("join needs text sep".into()),
|
||||
};
|
||||
let mut out = String::new();
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push_str(sep);
|
||||
}
|
||||
out.push_str(&item.as_display());
|
||||
}
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
/// `at`: list element at index (0-based); out of range → None.
|
||||
pub fn builtin_at(value: &Value, index: &Value) -> Result<Value, String> {
|
||||
let xs = match value {
|
||||
Value::List(xs) => xs,
|
||||
_ => return Err("at needs list value".into()),
|
||||
};
|
||||
let i = match index {
|
||||
Value::Int(n) => *n,
|
||||
_ => return Err("at needs int index".into()),
|
||||
};
|
||||
if i < 0 || (i as usize) >= xs.len() {
|
||||
return Ok(Value::None);
|
||||
}
|
||||
Ok(xs[i as usize].clone())
|
||||
}
|
||||
+78
-14
@@ -120,6 +120,40 @@ impl<'a> FnCompiler<'a> {
|
||||
self.chunk.spans.push(self.stmt_span);
|
||||
}
|
||||
|
||||
fn named_or_first<'b>(&self, call: &'b CallExpr, name: &str) -> Option<&'b Expr> {
|
||||
call.args
|
||||
.iter()
|
||||
.find_map(|a| match a {
|
||||
Arg::Named { name: n, value } if n == name => Some(value),
|
||||
_ => None,
|
||||
})
|
||||
.or_else(|| {
|
||||
call.args.iter().find_map(|a| match a {
|
||||
Arg::Positional(e) => Some(e),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn named_or_pos<'b>(&self, call: &'b CallExpr, name: &str, pos: usize) -> Option<&'b Expr> {
|
||||
if let Some(e) = call.args.iter().find_map(|a| match a {
|
||||
Arg::Named { name: n, value } if n == name => Some(value),
|
||||
_ => None,
|
||||
}) {
|
||||
return Some(e);
|
||||
}
|
||||
let mut i = 0usize;
|
||||
for a in &call.args {
|
||||
if let Arg::Positional(e) = a {
|
||||
if i == pos {
|
||||
return Some(e);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn here(&self) -> u16 {
|
||||
self.chunk.code.len() as u16
|
||||
}
|
||||
@@ -286,6 +320,10 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
|
||||
fn compile_call(&mut self, call: &CallExpr, as_stmt: bool) -> Result<()> {
|
||||
let mut call = call.clone();
|
||||
call.callee =
|
||||
crate::aliases::normalize_call_callee_and_args(&call.callee, &mut call.args);
|
||||
|
||||
match call.callee.as_str() {
|
||||
"print" => {
|
||||
let text_expr = call
|
||||
@@ -335,27 +373,18 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
"len" | "str" | "int" => {
|
||||
"len" | "str" | "int" | "type" | "trim" => {
|
||||
let name = call.callee.as_str();
|
||||
let value_expr = call
|
||||
.args
|
||||
.iter()
|
||||
.find_map(|a| match a {
|
||||
Arg::Named { name, value } if name == "value" => Some(value),
|
||||
_ => None,
|
||||
})
|
||||
.or_else(|| {
|
||||
call.args.iter().find_map(|a| match a {
|
||||
Arg::Positional(e) => Some(e),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
let value_expr = self
|
||||
.named_or_first(&call, "value")
|
||||
.ok_or_else(|| self.err(format!("{name} requires value")))?;
|
||||
self.compile_expr(value_expr)?;
|
||||
self.emit(match name {
|
||||
"len" => Op::Len,
|
||||
"str" => Op::Str,
|
||||
"int" => Op::Int,
|
||||
"type" => Op::TypeOf,
|
||||
"trim" => Op::Trim,
|
||||
_ => unreachable!(),
|
||||
});
|
||||
if as_stmt {
|
||||
@@ -363,6 +392,41 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
"split" | "join" => {
|
||||
let name = call.callee.as_str();
|
||||
let value_expr = self
|
||||
.named_or_pos(&call, "value", 0)
|
||||
.ok_or_else(|| self.err(format!("{name} requires value")))?;
|
||||
let sep_expr = self
|
||||
.named_or_pos(&call, "sep", 1)
|
||||
.ok_or_else(|| self.err(format!("{name} requires sep")))?;
|
||||
self.compile_expr(value_expr)?;
|
||||
self.compile_expr(sep_expr)?;
|
||||
self.emit(match name {
|
||||
"split" => Op::Split,
|
||||
"join" => Op::Join,
|
||||
_ => unreachable!(),
|
||||
});
|
||||
if as_stmt {
|
||||
self.emit(Op::Pop);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
"at" => {
|
||||
let value_expr = self
|
||||
.named_or_pos(&call, "value", 0)
|
||||
.ok_or_else(|| self.err("at requires value"))?;
|
||||
let index_expr = self
|
||||
.named_or_pos(&call, "index", 1)
|
||||
.ok_or_else(|| self.err("at requires index"))?;
|
||||
self.compile_expr(value_expr)?;
|
||||
self.compile_expr(index_expr)?;
|
||||
self.emit(Op::GetIndex);
|
||||
if as_stmt {
|
||||
self.emit(Op::Pop);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,14 @@ pub enum Op {
|
||||
Str,
|
||||
/// Pop value → push int (or fail).
|
||||
Int,
|
||||
/// Pop value → push type name text.
|
||||
TypeOf,
|
||||
/// Pop text → push trimmed text.
|
||||
Trim,
|
||||
/// Pop sep, then value → push list of text parts.
|
||||
Split,
|
||||
/// Pop sep, then list → push joined text.
|
||||
Join,
|
||||
GetIndex,
|
||||
/// Call function by index; argc values are on the stack (param order).
|
||||
Call(u16, u8),
|
||||
|
||||
+26
-10
@@ -4,7 +4,10 @@ use anyhow::Result;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::builtin::{builtin_int, builtin_len, builtin_str};
|
||||
use crate::builtin::{
|
||||
builtin_at, builtin_int, builtin_join, builtin_len, builtin_split, builtin_str, builtin_trim,
|
||||
builtin_type,
|
||||
};
|
||||
use crate::bytecode::{Op, Program};
|
||||
use crate::debug::emit_trace;
|
||||
use crate::diagnostics::{bail_at, Span};
|
||||
@@ -218,8 +221,9 @@ impl Vm {
|
||||
let text = prompt.as_display();
|
||||
self.emit_prompt(&text);
|
||||
let line = self.input.read_line().map_err(|e| {
|
||||
if e.to_string().contains("input is not available") {
|
||||
self.err_at(span, "input is not available under capture / view")
|
||||
let msg = e.to_string();
|
||||
if msg.contains("input needs a line") {
|
||||
self.err_at(span, msg)
|
||||
} else {
|
||||
e
|
||||
}
|
||||
@@ -249,16 +253,28 @@ impl Vm {
|
||||
let n = builtin_int(&v).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(Value::Int(n));
|
||||
}
|
||||
Op::TypeOf => {
|
||||
let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(builtin_type(&v));
|
||||
}
|
||||
Op::Trim => {
|
||||
let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(builtin_trim(&v).map_err(|m| self.err_at(span, m))?);
|
||||
}
|
||||
Op::Split => {
|
||||
let sep = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
let value = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(builtin_split(&value, &sep).map_err(|m| self.err_at(span, m))?);
|
||||
}
|
||||
Op::Join => {
|
||||
let sep = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
let value = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(builtin_join(&value, &sep).map_err(|m| self.err_at(span, m))?);
|
||||
}
|
||||
Op::GetIndex => {
|
||||
let idx = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
let list = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
match (list, idx) {
|
||||
(Value::List(xs), Value::Int(i)) if i >= 0 && (i as usize) < xs.len() => {
|
||||
stack.push(xs[i as usize].clone());
|
||||
}
|
||||
(Value::List(_), Value::Int(_)) => stack.push(Value::None),
|
||||
_ => return Err(self.err_at(span, "GetIndex needs list and int")),
|
||||
}
|
||||
stack.push(builtin_at(&list, &idx).map_err(|m| self.err_at(span, m))?);
|
||||
}
|
||||
Op::Call(fid, argc) => {
|
||||
let fid = fid as usize;
|
||||
|
||||
+152
-2
@@ -1,4 +1,4 @@
|
||||
//! Preset stdin lines for `input` (CLI `--stdin-file`, view form, tests).
|
||||
//! Preset stdin lines for `input` (CLI `--stdin-file`, view form, frontmatter, tests).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::fs;
|
||||
@@ -23,6 +23,127 @@ pub fn load_stdin_file(path: &Path) -> Result<Vec<String>> {
|
||||
Ok(split_stdin_text(&text))
|
||||
}
|
||||
|
||||
/// Prefer explicit override (CLI / view form); else frontmatter `stdin:` / `输入:`.
|
||||
pub fn effective_stdin(source: &str, override_lines: &[String]) -> Vec<String> {
|
||||
if !override_lines.is_empty() {
|
||||
return override_lines.to_vec();
|
||||
}
|
||||
extract_frontmatter_stdin(source)
|
||||
}
|
||||
|
||||
/// Read demo / preset lines from YAML-ish frontmatter.
|
||||
///
|
||||
/// Supported shapes:
|
||||
/// - `stdin: Alice` / `输入: 小明`
|
||||
/// - block scalar:
|
||||
/// ```text
|
||||
/// stdin: |
|
||||
/// Alice
|
||||
/// Bob
|
||||
/// ```
|
||||
/// - list:
|
||||
/// ```text
|
||||
/// stdin:
|
||||
/// - Alice
|
||||
/// - Bob
|
||||
/// ```
|
||||
pub fn extract_frontmatter_stdin(source: &str) -> Vec<String> {
|
||||
let source = source.strip_prefix('\u{feff}').unwrap_or(source);
|
||||
let lines: Vec<&str> = source.lines().collect();
|
||||
if lines.first().map(|l| l.trim()) != Some("---") {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut i = 1usize;
|
||||
while i < lines.len() {
|
||||
let raw = lines[i];
|
||||
let t = raw.trim();
|
||||
if t == "---" {
|
||||
break;
|
||||
}
|
||||
|
||||
let (key, rest) = match split_fm_key(t) {
|
||||
Some(pair) => pair,
|
||||
None => {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if key != "stdin" && key != "输入" {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let rest = rest.trim();
|
||||
if rest == "|" || rest == "|-" || rest == "|+" {
|
||||
i += 1;
|
||||
let mut out = Vec::new();
|
||||
while i < lines.len() {
|
||||
let body = lines[i];
|
||||
let bt = body.trim();
|
||||
if bt == "---" || (!body.starts_with(' ') && !body.starts_with('\t') && !bt.is_empty())
|
||||
{
|
||||
break;
|
||||
}
|
||||
if bt.is_empty() && (body.is_empty() || body.chars().all(|c| c == ' ' || c == '\t')) {
|
||||
out.push(String::new());
|
||||
} else {
|
||||
out.push(strip_block_indent(body));
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if rest.is_empty() {
|
||||
i += 1;
|
||||
let mut out = Vec::new();
|
||||
while i < lines.len() {
|
||||
let body = lines[i];
|
||||
let bt = body.trim();
|
||||
if bt == "---" {
|
||||
break;
|
||||
}
|
||||
if let Some(item) = bt.strip_prefix("- ") {
|
||||
out.push(item.trim().trim_matches('"').to_string());
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if bt == "-" {
|
||||
out.push(String::new());
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
// end of list (next key or blank then key)
|
||||
if !body.starts_with(' ') && !body.starts_with('\t') && !bt.is_empty() {
|
||||
break;
|
||||
}
|
||||
if bt.is_empty() {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return vec![rest.trim_matches('"').to_string()];
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn split_fm_key(t: &str) -> Option<(&str, &str)> {
|
||||
let (k, v) = t.split_once(':')?;
|
||||
let k = k.trim();
|
||||
if k.is_empty() || k.starts_with('>') {
|
||||
return None;
|
||||
}
|
||||
Some((k, v))
|
||||
}
|
||||
|
||||
fn strip_block_indent(line: &str) -> String {
|
||||
let s = line.strip_prefix(" ").or_else(|| line.strip_prefix('\t')).unwrap_or(line);
|
||||
s.trim_end_matches('\r').to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct InputFeed {
|
||||
queue: VecDeque<String>,
|
||||
@@ -43,7 +164,9 @@ impl InputFeed {
|
||||
return Ok(line);
|
||||
}
|
||||
if self.capture {
|
||||
anyhow::bail!("input is not available under capture / view");
|
||||
anyhow::bail!(
|
||||
"input needs a line (frontmatter stdin:/输入:, view Preset input, or --stdin-file)"
|
||||
);
|
||||
}
|
||||
let mut line = String::new();
|
||||
io::stdin().lock().read_line(&mut line)?;
|
||||
@@ -75,6 +198,33 @@ mod tests {
|
||||
assert_eq!(cap.stdout.trim_end(), "Name:Hello Alice!");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capture_uses_frontmatter_stdin() {
|
||||
let src = "---\ntitle: t\nstdin: Ada\n---\n\n# main\n\n*`n` = > input*\n\n> print text=`n`\n";
|
||||
let dir = std::env::temp_dir().join("marqdo-fm-stdin-test");
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
let path = dir.join("fm.mq.md");
|
||||
fs::write(&path, src).unwrap();
|
||||
let cap = run_file_capture(&path, &RunOptions::default()).expect("fm stdin");
|
||||
assert_eq!(cap.stdout.trim_end(), "Ada");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_block_and_list() {
|
||||
assert_eq!(
|
||||
extract_frontmatter_stdin("---\nstdin: |\n a\n b\n---\n"),
|
||||
vec!["a".to_string(), "b".to_string()]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_frontmatter_stdin("---\n输入:\n - 甲\n - 乙\n---\n"),
|
||||
vec!["甲".to_string(), "乙".to_string()]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_frontmatter_stdin("---\nstdin: Zoe\n---\n"),
|
||||
vec!["Zoe".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_keeps_blank_middle_lines() {
|
||||
assert_eq!(
|
||||
|
||||
+63
-3
@@ -7,7 +7,10 @@ use std::path::{Path, PathBuf};
|
||||
use crate::ast::{
|
||||
Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Stmt, UnaryOp,
|
||||
};
|
||||
use crate::builtin::{builtin_int, builtin_len, builtin_str};
|
||||
use crate::builtin::{
|
||||
builtin_at, builtin_int, builtin_join, builtin_len, builtin_split, builtin_str, builtin_trim,
|
||||
builtin_type,
|
||||
};
|
||||
use crate::debug::emit_trace;
|
||||
use crate::diagnostics::{bail_at, Span};
|
||||
use crate::input_feed::InputFeed;
|
||||
@@ -388,6 +391,13 @@ impl Interpreter {
|
||||
env: &mut Env,
|
||||
call: &CallExpr,
|
||||
) -> Result<Value> {
|
||||
let mut call = call.clone();
|
||||
let callee = crate::aliases::normalize_call_callee_and_args(
|
||||
&call.callee,
|
||||
&mut call.args,
|
||||
);
|
||||
call.callee = callee;
|
||||
|
||||
let mut ev_args = Vec::new();
|
||||
for arg in &call.args {
|
||||
match arg {
|
||||
@@ -423,8 +433,9 @@ impl Interpreter {
|
||||
.unwrap_or_default();
|
||||
self.emit_prompt(&prompt);
|
||||
let line = self.input.read_line().map_err(|e| {
|
||||
if e.to_string().contains("input is not available") {
|
||||
self.err("input is not available under capture / view")
|
||||
let msg = e.to_string();
|
||||
if msg.contains("input needs a line") {
|
||||
self.err(msg)
|
||||
} else {
|
||||
e
|
||||
}
|
||||
@@ -457,6 +468,55 @@ impl Interpreter {
|
||||
let n = builtin_int(v).map_err(|m| self.err(m))?;
|
||||
return Ok(Value::Int(n));
|
||||
}
|
||||
"type" => {
|
||||
let bound = bind_args(&["value".into()], &ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let v = bound
|
||||
.get("value")
|
||||
.ok_or_else(|| self.err("type requires value"))?;
|
||||
return Ok(builtin_type(v));
|
||||
}
|
||||
"trim" => {
|
||||
let bound = bind_args(&["value".into()], &ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let v = bound
|
||||
.get("value")
|
||||
.ok_or_else(|| self.err("trim requires value"))?;
|
||||
return builtin_trim(v).map_err(|m| self.err(m));
|
||||
}
|
||||
"split" => {
|
||||
let bound = bind_args(&["value".into(), "sep".into()], &ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let value = bound
|
||||
.get("value")
|
||||
.ok_or_else(|| self.err("split requires value"))?;
|
||||
let sep = bound
|
||||
.get("sep")
|
||||
.ok_or_else(|| self.err("split requires sep"))?;
|
||||
return builtin_split(value, sep).map_err(|m| self.err(m));
|
||||
}
|
||||
"join" => {
|
||||
let bound = bind_args(&["value".into(), "sep".into()], &ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let value = bound
|
||||
.get("value")
|
||||
.ok_or_else(|| self.err("join requires value"))?;
|
||||
let sep = bound
|
||||
.get("sep")
|
||||
.ok_or_else(|| self.err("join requires sep"))?;
|
||||
return builtin_join(value, sep).map_err(|m| self.err(m));
|
||||
}
|
||||
"at" => {
|
||||
let bound = bind_args(&["value".into(), "index".into()], &ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let value = bound
|
||||
.get("value")
|
||||
.ok_or_else(|| self.err("at requires value"))?;
|
||||
let index = bound
|
||||
.get("index")
|
||||
.ok_or_else(|| self.err("at requires index"))?;
|
||||
return builtin_at(value, index).map_err(|m| self.err(m));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
|
||||
+9
-5
@@ -3,6 +3,7 @@
|
||||
//! Pipeline: load → line classify → parse → tree-walk eval | bytecode VM.
|
||||
//! CLI also offers `view` for AST-backed browsing.
|
||||
|
||||
pub mod aliases;
|
||||
pub mod ast;
|
||||
pub mod builtin;
|
||||
pub mod bytecode;
|
||||
@@ -93,6 +94,7 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
|
||||
bail!("{} is empty", path.display());
|
||||
}
|
||||
|
||||
let stdin_lines = crate::input_feed::effective_stdin(&source, &opts.stdin_lines);
|
||||
let path_label = path.display().to_string();
|
||||
|
||||
if opts.dump_lines {
|
||||
@@ -127,7 +129,7 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
|
||||
match opts.backend {
|
||||
Backend::Tree => {
|
||||
let mut interp = Interpreter::new(Some(path), opts.trace_eval)
|
||||
.with_stdin(opts.stdin_lines.clone());
|
||||
.with_stdin(stdin_lines.clone());
|
||||
if opts.trace_eval {
|
||||
eprintln!("=== marqdo: trace-eval ({path_label}) ===");
|
||||
}
|
||||
@@ -142,7 +144,7 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
|
||||
print!("{}", program.disassemble());
|
||||
}
|
||||
let mut vm = Vm::new(Some(path))
|
||||
.with_stdin(opts.stdin_lines.clone())
|
||||
.with_stdin(stdin_lines)
|
||||
.with_trace(opts.trace_eval);
|
||||
if opts.trace_eval {
|
||||
eprintln!("=== marqdo: trace-eval ({path_label}) ===");
|
||||
@@ -165,11 +167,13 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
|
||||
|
||||
/// Run and capture stdout (used by `view` and tests).
|
||||
pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
|
||||
let source = std::fs::read_to_string(path)
|
||||
.map_err(|e| anyhow::anyhow!("failed to read {}: {e}", path.display()))?;
|
||||
let stdin_lines = crate::input_feed::effective_stdin(&source, &opts.stdin_lines);
|
||||
let module = load_module(path)?;
|
||||
match opts.backend {
|
||||
Backend::Tree => {
|
||||
let mut interp = Interpreter::with_capture(Some(path), false)
|
||||
.with_stdin(opts.stdin_lines.clone());
|
||||
let mut interp = Interpreter::with_capture(Some(path), false).with_stdin(stdin_lines);
|
||||
let value = interp.run_module(&module)?;
|
||||
Ok(RunCapture {
|
||||
stdout: interp.captured_stdout,
|
||||
@@ -178,7 +182,7 @@ pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
|
||||
}
|
||||
Backend::Bytecode => {
|
||||
let program = compile_module(Some(path), &module)?;
|
||||
let mut vm = Vm::with_capture(Some(path)).with_stdin(opts.stdin_lines.clone());
|
||||
let mut vm = Vm::with_capture(Some(path)).with_stdin(stdin_lines);
|
||||
let value = vm.run(&program)?;
|
||||
Ok(RunCapture {
|
||||
stdout: vm.captured_stdout,
|
||||
|
||||
+74
-2
@@ -1,6 +1,7 @@
|
||||
//! Load `.mq.md` files and merge frontmatter imports.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::env;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
@@ -30,7 +31,7 @@ fn load_module_inner(path: &Path, visited: &mut HashSet<PathBuf>) -> Result<Modu
|
||||
let base = path.parent().unwrap_or_else(|| Path::new("."));
|
||||
let imports = module.imports.clone();
|
||||
for rel in imports {
|
||||
let dep_path = base.join(&rel);
|
||||
let dep_path = resolve_import(base, &rel)?;
|
||||
let dep = load_module_inner(&dep_path, visited)?;
|
||||
for fun in dep.functions {
|
||||
merge_top_level(&mut module.functions, fun);
|
||||
@@ -40,6 +41,60 @@ fn load_module_inner(path: &Path, visited: &mut HashSet<PathBuf>) -> Result<Modu
|
||||
Ok(module)
|
||||
}
|
||||
|
||||
/// Resolve an import path: relative to the importer first; `lib/…` and `std/…`
|
||||
/// also search official library roots (`MARQDO_LIB`, `./lib`, near the binary).
|
||||
pub fn resolve_import(from_dir: &Path, rel: &str) -> Result<PathBuf> {
|
||||
let rel = rel.replace('\\', "/");
|
||||
let direct = from_dir.join(&rel);
|
||||
if direct.is_file() {
|
||||
return Ok(direct);
|
||||
}
|
||||
|
||||
let normalized = if let Some(rest) = rel.strip_prefix("std/") {
|
||||
format!("lib/{rest}")
|
||||
} else {
|
||||
rel.clone()
|
||||
};
|
||||
|
||||
if let Some(remainder) = normalized.strip_prefix("lib/") {
|
||||
for root in lib_search_roots() {
|
||||
let as_lib_dir = root.join(remainder);
|
||||
if as_lib_dir.is_file() {
|
||||
return Ok(as_lib_dir);
|
||||
}
|
||||
let as_repo_root = root.join("lib").join(remainder);
|
||||
if as_repo_root.is_file() {
|
||||
return Ok(as_repo_root);
|
||||
}
|
||||
}
|
||||
bail!(
|
||||
"cannot resolve library import `{rel}` (set MARQDO_LIB or keep a lib/ next to the project)"
|
||||
);
|
||||
}
|
||||
|
||||
Ok(direct)
|
||||
}
|
||||
|
||||
fn lib_search_roots() -> Vec<PathBuf> {
|
||||
let mut roots = Vec::new();
|
||||
if let Ok(h) = env::var("MARQDO_LIB") {
|
||||
roots.push(PathBuf::from(h));
|
||||
}
|
||||
if let Ok(cwd) = env::current_dir() {
|
||||
roots.push(cwd.join("lib"));
|
||||
roots.push(cwd);
|
||||
}
|
||||
if let Ok(exe) = env::current_exe() {
|
||||
if let Some(dir) = exe.parent() {
|
||||
roots.push(dir.join("lib"));
|
||||
roots.push(dir.join("../lib"));
|
||||
roots.push(dir.join("../../lib"));
|
||||
roots.push(dir.join("../../../lib"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn attach_path(path: &Path, err: anyhow::Error) -> anyhow::Error {
|
||||
if let Some(d) = err.downcast_ref::<Diagnostic>() {
|
||||
if d.path.is_none() {
|
||||
@@ -47,7 +102,6 @@ fn attach_path(path: &Path, err: anyhow::Error) -> anyhow::Error {
|
||||
}
|
||||
return err;
|
||||
}
|
||||
// Legacy `line:col: message` from parse bail!
|
||||
let msg = err.to_string();
|
||||
if let Some((loc, rest)) = msg.split_once(": ") {
|
||||
if let Some((line_s, col_s)) = loc.split_once(':') {
|
||||
@@ -66,3 +120,21 @@ fn merge_top_level(into: &mut Vec<Function>, fun: Function) {
|
||||
into.push(fun);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn resolve_lib_from_cwd() {
|
||||
let cwd = env::current_dir().unwrap();
|
||||
let lib_text = cwd.join("lib").join("text.mq.md");
|
||||
if !lib_text.is_file() {
|
||||
return;
|
||||
}
|
||||
let p = resolve_import(Path::new("tests/keywords"), "lib/text.mq.md").unwrap();
|
||||
assert!(p.ends_with("text.mq.md"));
|
||||
let p2 = resolve_import(Path::new("tests/keywords"), "std/text.mq.md").unwrap();
|
||||
assert!(p2.ends_with("text.mq.md"));
|
||||
}
|
||||
}
|
||||
+44
-24
@@ -129,16 +129,24 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Eat English or Chinese logic keyword with word-boundary check.
|
||||
fn eat_logic_kw(&mut self, en: &str, zh: &str) -> bool {
|
||||
if self.starts_with(en) && is_word_end(self.rest(), en.len()) {
|
||||
self.i += en.len();
|
||||
return true;
|
||||
}
|
||||
if self.starts_with(zh) && is_word_end(self.rest(), zh.len()) {
|
||||
self.i += zh.len();
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn parse_or(&mut self) -> Result<Expr> {
|
||||
let mut left = self.parse_and()?;
|
||||
loop {
|
||||
self.skip_ws();
|
||||
if self.eat("or") {
|
||||
// ensure word boundary
|
||||
if self.peek_char().map(|c| c.is_alphanumeric() || c == '_').unwrap_or(false) {
|
||||
self.i -= 2;
|
||||
break;
|
||||
}
|
||||
if self.eat_logic_kw("or", "或") {
|
||||
let right = self.parse_and()?;
|
||||
left = Expr::Binary {
|
||||
op: BinaryOp::Or,
|
||||
@@ -156,11 +164,7 @@ impl<'a> Parser<'a> {
|
||||
let mut left = self.parse_cmp()?;
|
||||
loop {
|
||||
self.skip_ws();
|
||||
if self.eat("and") {
|
||||
if self.peek_char().map(|c| c.is_alphanumeric() || c == '_').unwrap_or(false) {
|
||||
self.i -= 3;
|
||||
break;
|
||||
}
|
||||
if self.eat_logic_kw("and", "且") {
|
||||
let right = self.parse_cmp()?;
|
||||
left = Expr::Binary {
|
||||
op: BinaryOp::And,
|
||||
@@ -255,16 +259,12 @@ impl<'a> Parser<'a> {
|
||||
|
||||
fn parse_unary(&mut self) -> Result<Expr> {
|
||||
self.skip_ws();
|
||||
if self.eat("not") {
|
||||
if self.peek_char().map(|c| c.is_alphanumeric() || c == '_').unwrap_or(false) {
|
||||
self.i -= 3;
|
||||
} else {
|
||||
let expr = self.parse_unary()?;
|
||||
return Ok(Expr::Unary {
|
||||
op: UnaryOp::Not,
|
||||
expr: Box::new(expr),
|
||||
});
|
||||
}
|
||||
if self.eat_logic_kw("not", "非") {
|
||||
let expr = self.parse_unary()?;
|
||||
return Ok(Expr::Unary {
|
||||
op: UnaryOp::Not,
|
||||
expr: Box::new(expr),
|
||||
});
|
||||
}
|
||||
if self.eat("-") {
|
||||
let expr = self.parse_unary()?;
|
||||
@@ -312,14 +312,26 @@ impl<'a> Parser<'a> {
|
||||
self.i += 4;
|
||||
return Ok(Expr::Literal(Literal::Bool(true)));
|
||||
}
|
||||
if self.starts_with("真") && is_word_end(self.rest(), '真'.len_utf8()) {
|
||||
self.i += '真'.len_utf8();
|
||||
return Ok(Expr::Literal(Literal::Bool(true)));
|
||||
}
|
||||
if self.starts_with("False") && is_word_end(self.rest(), 5) {
|
||||
self.i += 5;
|
||||
return Ok(Expr::Literal(Literal::Bool(false)));
|
||||
}
|
||||
if self.starts_with("假") && is_word_end(self.rest(), '假'.len_utf8()) {
|
||||
self.i += '假'.len_utf8();
|
||||
return Ok(Expr::Literal(Literal::Bool(false)));
|
||||
}
|
||||
if self.starts_with("None") && is_word_end(self.rest(), 4) {
|
||||
self.i += 4;
|
||||
return Ok(Expr::Literal(Literal::None));
|
||||
}
|
||||
if self.starts_with("空") && is_word_end(self.rest(), '空'.len_utf8()) {
|
||||
self.i += '空'.len_utf8();
|
||||
return Ok(Expr::Literal(Literal::None));
|
||||
}
|
||||
if self.peek_char().map(|c| c.is_ascii_digit()).unwrap_or(false) {
|
||||
let start = self.i;
|
||||
while self.peek_char().map(|c| c.is_ascii_digit()).unwrap_or(false) {
|
||||
@@ -485,8 +497,16 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interp_hello() {
|
||||
let e = parse_value_or_interp("Hello `谁`!").unwrap();
|
||||
assert!(matches!(e, Expr::Interp(_)));
|
||||
fn chinese_logic_and_literals() {
|
||||
let e = parse_expr("`a` 且 非 `b`").unwrap();
|
||||
assert!(matches!(e, Expr::Binary { op: BinaryOp::And, .. }));
|
||||
assert!(matches!(
|
||||
parse_expr("真").unwrap(),
|
||||
Expr::Literal(Literal::Bool(true))
|
||||
));
|
||||
assert!(matches!(
|
||||
parse_expr("空").unwrap(),
|
||||
Expr::Literal(Literal::None)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -248,6 +248,9 @@ impl<'a> Cursor<'a> {
|
||||
return Ok(None);
|
||||
};
|
||||
let name = rest[..end].to_string();
|
||||
if crate::aliases::is_reserved_keyword(&name) {
|
||||
bail!("{span}: `{name}` is a reserved keyword");
|
||||
}
|
||||
let after = rest[end + 1..].trim_start();
|
||||
if !after.starts_with('=') {
|
||||
return Ok(None);
|
||||
@@ -419,6 +422,9 @@ fn parse_assign_or_expr_stmt(inner: &str, span: Span) -> Result<Stmt> {
|
||||
if let Some(rest) = inner.strip_prefix('`') {
|
||||
if let Some(end) = rest.find('`') {
|
||||
let name = rest[..end].to_string();
|
||||
if crate::aliases::is_reserved_keyword(&name) {
|
||||
bail!("{span}: `{name}` is a reserved keyword");
|
||||
}
|
||||
let after = rest[end + 1..].trim_start();
|
||||
if let Some(rhs) = after.strip_prefix('=') {
|
||||
let rhs = rhs.trim();
|
||||
|
||||
+12
-2
@@ -624,14 +624,24 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM
|
||||
LinkMode::Live => format!(
|
||||
r#"<form class="stdin-form" method="get" action="/file">
|
||||
<input type="hidden" name="path" value="{path}"/>
|
||||
<label for="stdin">Preset input <span class="hint">one line per input call</span></label>
|
||||
<label for="stdin">Preset input <span class="hint">one line per <code>input</code>; overrides frontmatter <code>stdin:</code> / <code>输入:</code></span></label>
|
||||
<textarea id="stdin" name="stdin" rows="3" placeholder="Alice">{stdin}</textarea>
|
||||
<button type="submit">Run with input</button>
|
||||
</form>"#,
|
||||
path = escape(rel),
|
||||
stdin = escape(&vm.preset_stdin),
|
||||
),
|
||||
LinkMode::Static { .. } => String::new(),
|
||||
LinkMode::Static { .. } => {
|
||||
if vm.preset_stdin.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(
|
||||
r#"<p class="hint">Demo stdin from frontmatter (static export cannot re-run interactively):</p>
|
||||
<pre class="source" style="margin-bottom:0.75rem">{stdin}</pre>"#,
|
||||
stdin = escape(&vm.preset_stdin),
|
||||
)
|
||||
}
|
||||
}
|
||||
};
|
||||
let title = Path::new(rel)
|
||||
.file_name()
|
||||
|
||||
+11
-10
@@ -14,7 +14,7 @@ use std::process::Command;
|
||||
use anyhow::{bail, Context, Result};
|
||||
use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
|
||||
|
||||
use crate::input_feed::split_stdin_text;
|
||||
use crate::input_feed::{effective_stdin, split_stdin_text};
|
||||
use crate::view::html::{escape, page_file, page_index, LinkMode};
|
||||
use crate::view::render::{render_module_structure, FileViewModel};
|
||||
use crate::{run_file_capture, RunOptions};
|
||||
@@ -172,8 +172,9 @@ pub(crate) fn build_file_view(
|
||||
escape(&tidy_user_error(&format!("{e:#}"), abs, rel))
|
||||
),
|
||||
};
|
||||
let effective = effective_stdin(&source, stdin_lines);
|
||||
let opts = RunOptions {
|
||||
stdin_lines: stdin_lines.to_vec(),
|
||||
stdin_lines: effective.clone(),
|
||||
..RunOptions::default()
|
||||
};
|
||||
let (stdout, stderr, ok) = match run_file_capture(abs, &opts) {
|
||||
@@ -191,7 +192,7 @@ pub(crate) fn build_file_view(
|
||||
stdout,
|
||||
stderr,
|
||||
ok,
|
||||
preset_stdin: stdin_lines.join("\n"),
|
||||
preset_stdin: effective.join("\n"),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -277,33 +278,33 @@ fn query_param<'a>(query: &'a str, key: &str) -> Option<String> {
|
||||
}
|
||||
|
||||
fn urlencoding_decode(s: &str) -> String {
|
||||
// Minimal decode for %XX and +
|
||||
let mut out = String::new();
|
||||
// Minimal decode for %XX and + (UTF-8 byte sequences, not Latin-1 chars).
|
||||
let mut out = Vec::new();
|
||||
let bytes = s.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'+' => {
|
||||
out.push(' ');
|
||||
out.push(b' ');
|
||||
i += 1;
|
||||
}
|
||||
b'%' if i + 2 < bytes.len() => {
|
||||
let hex = &s[i + 1..i + 3];
|
||||
if let Ok(v) = u8::from_str_radix(hex, 16) {
|
||||
out.push(v as char);
|
||||
out.push(v);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push('%');
|
||||
out.push(b'%');
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
c => {
|
||||
out.push(c as char);
|
||||
out.push(c);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
fn files_json(files: &[PathBuf]) -> String {
|
||||
|
||||
Reference in new issue
Block a user