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:
cflmyandCursor committed 2026-08-06 17:52:33 +08:00
1 parent 92d88fe761
commit 63e5be80ab
116 files changed
+2226 -559

No files matched your search

+142 -6
View File
@@ -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
View File
@@ -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]