diff --git a/extensions/kvlang/language-configuration.json b/extensions/kvlang/language-configuration.json index c2bfe7e5..674e87a3 100644 --- a/extensions/kvlang/language-configuration.json +++ b/extensions/kvlang/language-configuration.json @@ -1,14 +1,12 @@ { - "comments": { "lineComment": "#" }, + "comments": { "lineComment": "//", "blockComment": ["/*", "*/"] }, "brackets": [ ["(", ")"], ["[", "]"], ["{", "}"] ], "autoClosingPairs": [ - ["\"\"\"", "\"\"\""], ["\"", "\""], - ["`", "`"], ["'", "'"], ["(", ")"], ["[", "]"], diff --git a/extensions/kvlang/syntaxes/kvlang.tmLanguage.json b/extensions/kvlang/syntaxes/kvlang.tmLanguage.json index a320937c..2b2891e4 100644 --- a/extensions/kvlang/syntaxes/kvlang.tmLanguage.json +++ b/extensions/kvlang/syntaxes/kvlang.tmLanguage.json @@ -4,9 +4,9 @@ "fileTypes": [], "patterns": [ { "include": "#line_comment" }, - { "include": "#string_triple" }, - { "include": "#string_double" }, + { "include": "#block_comment" }, { "include": "#string_raw" }, + { "include": "#string_double" }, { "include": "#keypath_single" }, { "include": "#keyword" }, { "include": "#type" }, @@ -17,23 +17,27 @@ ], "repository": { "line_comment": { - "name": "comment.line.kvlang", - "match": "(#|//).*$" + "name": "comment.line.double-slash.kvlang", + "match": "//.*$" }, - "string_triple": { - "name": "string.quoted.triple.kvlang", - "begin": "\"\"\"", - "end": "\"\"\"" + "block_comment": { + "name": "comment.block.kvlang", + "begin": "/\\*", + "end": "\\*/", + "patterns": [{ "include": "#block_comment" }] + }, + "string_raw": { + "name": "string.quoted.raw.kvlang", + "begin": "r(#*)\"", + "end": "\"\\1" }, "string_double": { "name": "string.quoted.double.kvlang", "begin": "\"", - "end": "\"" - }, - "string_raw": { - "name": "string.quoted.raw.kvlang", - "begin": "`", - "end": "`" + "end": "\"", + "patterns": [ + { "name": "constant.character.escape.kvlang", "match": "\\\\." } + ] }, "keypath_single": { "name": "string.quoted.single.kvlang", @@ -42,7 +46,7 @@ }, "keyword": { "name": "keyword.control.kvlang", - "match": "\\b(rwfunc|rwir|if|else|for|while|break|continue|return)\\b" + "match": "\\b(rwfunc|rwir|lib|if|else|for|while|break|continue|return)\\b" }, "block_label": { "name": "entity.name.label.kvlang", @@ -50,7 +54,7 @@ }, "type": { "name": "storage.type.kvlang", - "match": "\\b(int8|int16|int32|int64|uint8|uint16|uint32|uint64|float32|float64|bool|charbyte)\\b" + "match": "\\b(int8|int16|int32|int64|uint8|uint16|uint32|uint64|float32|float64|bool|char|utf8|utf32|object|stringkeymap)\\b" }, "number": { "name": "constant.numeric.kvlang", @@ -58,7 +62,7 @@ }, "operator": { "name": "keyword.operator.kvlang", - "match": "[+\\-*/%]|==|!=|<=|>=|<|>|&&|\\|\\||!" + "match": "[+\\-×÷%]|==|!=|<=|>=|<|>|&&|\\|\\||!" }, "arrow": { "name": "keyword.operator.arrow.kvlang", diff --git a/layout/src/ast.rs b/layout/src/ast.rs index 3d9ef556..fdcaa317 100644 --- a/layout/src/ast.rs +++ b/layout/src/ast.rs @@ -213,7 +213,7 @@ pub struct Expr { pub op: String, // 算子/函数名("" = 叶节点) pub args: Vec, // 操作数(叶节点为空) pub val: String, // 叶节点值 - pub quote: u8, // 0=非字符串, '"'=双引号, '`'=反引号 + pub quote: u8, // 0=非字符串, '"'=字符串(转义或原始,由 lit 区分) pub lit: LitKind, // 字面量类型(仅叶节点有意义) } @@ -248,7 +248,7 @@ pub fn raw_str(v: &str) -> Expr { op: String::new(), args: Vec::new(), val: v.to_string(), - quote: b'`', + quote: b'"', lit: LitKind::LitRawString, } } @@ -312,10 +312,10 @@ impl Expr { fn string_prec(&self, outer_prec: i32) -> String { if self.is_leaf() { if self.quote != 0 { - if self.quote == b'"' { - return format!("\"{}\"", escape_string(&self.val)); + if self.lit == LitKind::LitRawString { + return raw_string_lit(&self.val); } - return format!("`{}`", self.val); + return format!("\"{}\"", escape_string(&self.val)); } return self.val.clone(); } @@ -799,6 +799,29 @@ fn escape_string(s: &str) -> String { b } +/// 把值渲染为 Rust 原始字符串 `r#"..."#`,井号数取最小可行值(保证内容不与闭合定界符冲突)。 +fn raw_string_lit(v: &str) -> String { + let bytes = v.as_bytes(); + let mut n = 0usize; + let mut k = 0; + while k < bytes.len() { + if bytes[k] == b'"' { + let mut h = 0; + let mut j = k + 1; + while j < bytes.len() && bytes[j] == b'#' { + h += 1; + j += 1; + } + if h + 1 > n { + n = h + 1; + } + } + k += 1; + } + let hashes = "#".repeat(n); + format!("r{hashes}\"{v}\"{hashes}") +} + fn is_operator_char(c: u8) -> bool { symbol::scanner_one_char_ops().contains(&c) } diff --git a/layout/src/code.rs b/layout/src/code.rs index 140735d2..5dc128c7 100644 --- a/layout/src/code.rs +++ b/layout/src/code.rs @@ -197,7 +197,7 @@ pub fn dump(kv: &mut Kv, lib: &str) -> String { let mut out = String::new(); emit_node(&mut out, &root, ""); for d in decls { - out.push_str("# "); + out.push_str("// "); out.push_str(&d); out.push('\n'); } @@ -342,12 +342,12 @@ fn emit_func(out: &mut String, f: &DumpFunc, indent: &str) { out.push('\n'); } out.push_str(indent); - out.push_str("# "); + out.push_str("// "); out.push_str(&f.dir); out.push('\n'); for s in &f.slots { out.push_str(indent); - out.push_str("# "); + out.push_str("// "); out.push_str(s); out.push('\n'); } diff --git a/layout/src/parser.rs b/layout/src/parser.rs index ccc6bca6..96723b86 100644 --- a/layout/src/parser.rs +++ b/layout/src/parser.rs @@ -1356,7 +1356,7 @@ impl Parser { if t.quote == b'"' { return Some(ast::str_lit(&v)); } - if t.quote == b'`' { + if t.quote == b'r' { return Some(ast::raw_str(&v)); } if !v.is_empty() && v.as_bytes()[0] == b'/' { diff --git a/layout/src/scanner.rs b/layout/src/scanner.rs index a130d4de..b02c2902 100644 --- a/layout/src/scanner.rs +++ b/layout/src/scanner.rs @@ -115,7 +115,7 @@ pub struct Token { pub kind: Kind, pub value: String, pub pos: Pos, - pub quote: u8, // 0=无, '"'=", '`'=` + pub quote: u8, // 0=无, '"'=转义串 "...", 'r'=原始串 r#"..."# } impl Token { @@ -188,28 +188,58 @@ fn scan_quoted(src: &[u8], mut i: usize, quote: u8) -> (String, usize) { (String::from_utf8_lossy(&b).into_owned(), src.len()) } -/// 三引号字符串 `"""..."""` —— 跨行,转义(对标 Python triple-quote)。 -/// 起始 `i` 指向开头的第一个 `"`,返回(内容,闭合 `"""` 之后的字节下标)。 -fn scan_triple_quoted(src: &[u8], mut i: usize) -> (String, usize) { - i += 3; - let mut b: Vec = Vec::new(); - while i < src.len() { - let c = src[i]; - if c == b'\\' { - i += 1; - if i < src.len() { - b.push(escaped_byte(src[i])); - i += 1; +/// Rust 原始字符串 `r"..."` / `r#"..."#` / `r##"..."##` … —— 跨行,零转义。 +/// `i` 指向 `r`。成功返回(内容, 闭合之后下标, true);非 raw 形式返回 (_, i, false)。 +fn scan_raw(src: &[u8], i: usize) -> (String, usize, bool) { + let mut j = i + 1; + let mut hashes = 0usize; + while j < src.len() && src[j] == b'#' { + hashes += 1; + j += 1; + } + if j >= src.len() || src[j] != b'"' { + return (String::new(), i, false); + } + let content_start = j + 1; + let mut k = content_start; + while k < src.len() { + if src[k] == b'"' { + let mut h = 0; + while h < hashes && k + 1 + h < src.len() && src[k + 1 + h] == b'#' { + h += 1; + } + if h == hashes { + let val = String::from_utf8_lossy(&src[content_start..k]).into_owned(); + return (val, k + 1 + hashes, true); } + } + k += 1; + } + ( + String::from_utf8_lossy(&src[content_start..]).into_owned(), + src.len(), + true, + ) +} + +/// Rust 块注释 `/* ... */`(可嵌套)。`i` 指向第一个 `/`,返回(整段含定界符, 之后下标)。 +fn scan_block_comment(src: &[u8], i: usize) -> (String, usize) { + let mut j = i + 2; + let mut depth = 1usize; + while j < src.len() && depth > 0 { + if j + 1 < src.len() && src[j] == b'/' && src[j + 1] == b'*' { + depth += 1; + j += 2; continue; } - if c == b'"' && i + 2 < src.len() && src[i + 1] == b'"' && src[i + 2] == b'"' { - return (String::from_utf8_lossy(&b).into_owned(), i + 3); + if j + 1 < src.len() && src[j] == b'*' && src[j + 1] == b'/' { + depth -= 1; + j += 2; + continue; } - b.push(c); - i += 1; + j += 1; } - (String::from_utf8_lossy(&b).into_owned(), src.len()) + (String::from_utf8_lossy(&src[i..j]).into_owned(), j) } /// 跨行字面量消费后同步 line/line_start(字面量内部换行不产生 Newline Token,但行号需前进)。 @@ -321,65 +351,26 @@ pub fn scan(src: &str) -> Vec { i += 1; continue; } - // # 行注释 - if c == b'#' { - let p = pos(i, line, line_start); - let start = i; - while i < src.len() && src[i] != b'\n' { - i += 1; - } - tokens.push(Token { - kind: Kind::Comment, - value: String::from_utf8_lossy(&src[start..i]).into_owned(), - pos: p, - quote: 0, - }); - prev_newline = false; - continue; - } - prev_newline = false; let p = pos(i, line, line_start); - // 反引号原始字符串 `...` — 跨行,零转义(对标 Go raw string) - if c == b'`' { - let next = if let Some(end) = find_byte(&src[i + 1..], b'`') { + // Rust 原始字符串 r"..." / r#"..."# — 跨行,零转义 + if c == b'r' { + let (val, next, ok) = scan_raw(src, i); + if ok { tokens.push(Token { kind: Kind::Literal, - value: String::from_utf8_lossy(&src[i + 1..i + 1 + end]).into_owned(), + value: val, pos: p, - quote: b'`', + quote: b'r', }); - i + end + 2 - } else { - tokens.push(Token { - kind: Kind::Literal, - value: String::from_utf8_lossy(&src[i + 1..]).into_owned(), - pos: p, - quote: b'`', - }); - src.len() - }; - advance_line_count(src, i, next, &mut line, &mut line_start); - i = next; - continue; - } - - // 三引号字符串 """...""" — 跨行,转义(对标 Python triple-quote) - if c == b'"' && i + 2 < src.len() && src[i + 1] == b'"' && src[i + 2] == b'"' { - let (val, next) = scan_triple_quoted(src, i); - tokens.push(Token { - kind: Kind::Literal, - value: val, - pos: p, - quote: b'"', - }); - advance_line_count(src, i, next, &mut line, &mut line_start); - i = next; - continue; + advance_line_count(src, i, next, &mut line, &mut line_start); + i = next; + continue; + } } - // 引号字符串 + // 引号字符串 "..." — 跨行,转义 if c == b'\'' || c == b'"' { let (val, next) = scan_quoted(src, i, c); let quote = if c == b'"' { b'"' } else { 0 }; @@ -389,6 +380,7 @@ pub fn scan(src: &str) -> Vec { pos: p, quote, }); + advance_line_count(src, i, next, &mut line, &mut line_start); i = next; continue; } @@ -446,12 +438,31 @@ pub fn scan(src: &str) -> Vec { continue; } - // '/' — // 注释 或 绝对路径字面量 或 除法算子 + // '/' — // 行注释 或 /* */ 块注释 或 绝对路径字面量 或 除法算子 if c == b'/' { if i + 1 < src.len() && src[i + 1] == b'/' { + let start = i; while i < src.len() && src[i] != b'\n' { i += 1; } + tokens.push(Token { + kind: Kind::Comment, + value: String::from_utf8_lossy(&src[start..i]).into_owned(), + pos: p, + quote: 0, + }); + continue; + } + if i + 1 < src.len() && src[i + 1] == b'*' { + let (val, next) = scan_block_comment(src, i); + tokens.push(Token { + kind: Kind::Comment, + value: val, + pos: p, + quote: 0, + }); + advance_line_count(src, i, next, &mut line, &mut line_start); + i = next; continue; } if i + 1 < src.len() && is_abs_path_start(src[i + 1]) { @@ -610,7 +621,3 @@ pub fn scan(src: &str) -> Vec { tokens.push(Token::eof(pos(i, line, line_start))); tokens } - -fn find_byte(s: &[u8], b: u8) -> Option { - s.iter().position(|&x| x == b) -} diff --git a/runtime-rwirext_example/go/json/tutorial/json.kv b/runtime-rwirext_example/go/json/tutorial/json.kv index 437f51bd..4fbe3e6f 100644 --- a/runtime-rwirext_example/go/json/tutorial/json.kv +++ b/runtime-rwirext_example/go/json/tutorial/json.kv @@ -1,22 +1,22 @@ -# json: json.to / json.from 外部执行器(rwirext)—— KV 子树 ↔ JSON -# extern: 需先启动 redis 与 json rwirext 两个外部进程 -# 1) make kvspace # 起 redis 并清空 kvspace -# 2) go build -o /tmp/json-rwirext ./rwirext/json/cmd/ && /tmp/json-rwirext & -# 3) ./kvlang tutorial/10-rwirext/json.kv -# 语义: json·to(rootkey) 把 rootkey 整棵子树读成 map[string]any 再 json.Marshal; -# json·from(json) 反序列化 JSON 写回子树。目录→嵌套对象;compact 数组([]T)与 -# 散 key 数组(name[0]..name[N-1])统一序列化为 JSON 数组。 -# 期望输出: -# j = {"active":true,"age":42,"cont":[10,20,30],"grp":{"c":1,"d":2},"name":"alice","nested":{"level1":{"count":3,"flags":[true,false,true],"level2":"deep"},"list":[1,2,3]},"scat":[10,20,30],"score":3.14} -# name = alice -# c = 1 -# cont = [10, 20, 30] -# scat = [10, 20, 30] -# len = 3 3 -# level2 = deep -# count = 3 -# flags = [true, false, true] -# list = [1, 2, 3] +// json: json.to / json.from 外部执行器(rwirext)—— KV 子树 ↔ JSON +// extern: 需先启动 redis 与 json rwirext 两个外部进程 +// 1) make kvspace # 起 redis 并清空 kvspace +// 2) go build -o /tmp/json-rwirext ./rwirext/json/cmd/ && /tmp/json-rwirext & +// 3) ./kvlang tutorial/10-rwirext/json.kv +// 语义: json·to(rootkey) 把 rootkey 整棵子树读成 map[string]any 再 json.Marshal; +// json·from(json) 反序列化 JSON 写回子树。目录→嵌套对象;compact 数组([]T)与 +// 散 key 数组(name[0]..name[N-1])统一序列化为 JSON 数组。 +// 期望输出: +// j = {"active":true,"age":42,"cont":[10,20,30],"grp":{"c":1,"d":2},"name":"alice","nested":{"level1":{"count":3,"flags":[true,false,true],"level2":"deep"},"list":[1,2,3]},"scat":[10,20,30],"score":3.14} +// name = alice +// c = 1 +// cont = [10, 20, 30] +// scat = [10, 20, 30] +// len = 3 3 +// level2 = deep +// count = 3 +// flags = [true, false, true] +// list = [1, 2, 3] rwfunc main() -> () { 42 -> /data·age "alice" -> /data·name diff --git a/runtime-rwirext_example/go/json/tutorial/json_local.kv b/runtime-rwirext_example/go/json/tutorial/json_local.kv index 4349cd42..b1091a31 100644 --- a/runtime-rwirext_example/go/json/tutorial/json_local.kv +++ b/runtime-rwirext_example/go/json/tutorial/json_local.kv @@ -1,15 +1,15 @@ -# json_local: 局部变量 object/stringkeymap → json 转换 -# extern: 需先启动 redis 与 json rwirext 两个外部进程 -# 1) make kvspace # 起 redis 并清空 kvspace -# 2) go build -o /tmp/json-rwirext ./rwirext/json/cmd/ && /tmp/json-rwirext & -# 3) ./kvlang tutorial/10-rwirext/json_local.kv -# 语义: json·to 接受局部 object/stringkeymap 变量(resolve 到帧槽路径后序列化)。 -# object 局部变量({} + kv·set)→ JSON 对象;stringkeymap 局部变量({..} 散 key -# 数组)→ JSON 数组。散 key 数组成员名是坐标段 "[i]"。 -# 期望输出: -# profile = {"active":true,"age":42,"name":"alice","nums":[1,2,3],"score":3.14} -# map = [10,20,30] -# tags = ["a","b","c"] +// json_local: 局部变量 object/stringkeymap → json 转换 +// extern: 需先启动 redis 与 json rwirext 两个外部进程 +// 1) make kvspace # 起 redis 并清空 kvspace +// 2) go build -o /tmp/json-rwirext ./rwirext/json/cmd/ && /tmp/json-rwirext & +// 3) ./kvlang tutorial/10-rwirext/json_local.kv +// 语义: json·to 接受局部 object/stringkeymap 变量(resolve 到帧槽路径后序列化)。 +// object 局部变量({} + kv·set)→ JSON 对象;stringkeymap 局部变量({..} 散 key +// 数组)→ JSON 数组。散 key 数组成员名是坐标段 "[i]"。 +// 期望输出: +// profile = {"active":true,"age":42,"name":"alice","nums":[1,2,3],"score":3.14} +// map = [10,20,30] +// tags = ["a","b","c"] rwfunc main() -> () { profile = {} kv·set(profile, "name", "alice") diff --git a/runtime-rwirext_example/go/json/tutorial/json_roundtrip.kv b/runtime-rwirext_example/go/json/tutorial/json_roundtrip.kv index e41e1c96..4bac8dba 100644 --- a/runtime-rwirext_example/go/json/tutorial/json_roundtrip.kv +++ b/runtime-rwirext_example/go/json/tutorial/json_roundtrip.kv @@ -1,12 +1,12 @@ -# json: json.to / json.from 往返(object / stringkeymap 承载复杂结构) -# extern: 需先启动 redis 与 json rwirext 两个外部进程 -# 1) redis-server --port 6379 -# 2) ./bin/json-rwirext & -# 3) ./bin/kvlang <本文件> -# 语义: json·from(json) 把 JSON 反序列化进 KV 树(对象→object、数组→stringkeymap、 -# null→None 空字节);json·to(root) 把 KV 子树序列化回 JSON,二者无损等价。 -# 期望输出: -# roundtrip = {"a":[1,{"b":"x"}],"list":[{"x":1},{"y":2}],"mixed":[1,"a",true,null,3.14],"n":null,"s":["a","b"]} +// json: json.to / json.from 往返(object / stringkeymap 承载复杂结构) +// extern: 需先启动 redis 与 json rwirext 两个外部进程 +// 1) redis-server --port 6379 +// 2) ./bin/json-rwirext & +// 3) ./bin/kvlang <本文件> +// 语义: json·from(json) 把 JSON 反序列化进 KV 树(对象→object、数组→stringkeymap、 +// null→None 空字节);json·to(root) 把 KV 子树序列化回 JSON,二者无损等价。 +// 期望输出: +// roundtrip = {"a":[1,{"b":"x"}],"list":[{"x":1},{"y":2}],"mixed":[1,"a",true,null,3.14],"n":null,"s":["a","b"]} rwfunc main() -> () { json·from("{\"a\":[1,{\"b\":\"x\"}],\"list\":[{\"x\":1},{\"y\":2}],\"mixed\":[1,\"a\",true,null,3.14],\"n\":null,\"s\":[\"a\",\"b\"]}") -> /t json·to(/t) -> out diff --git a/runtime-rwirext_example/py/numpy/tutorial/01-creation.kv b/runtime-rwirext_example/py/numpy/tutorial/01-creation.kv index 293836b0..930182d8 100644 --- a/runtime-rwirext_example/py/numpy/tutorial/01-creation.kv +++ b/runtime-rwirext_example/py/numpy/tutorial/01-creation.kv @@ -1,15 +1,15 @@ -# numpy 第一类:创建与初始化 -# extern: 需 numpy 扩展引擎驱动 -# python runtime-rwirext_example/py/numpy/numpy.py tutorial/14-numpy/01-creation.kv -# 语义: ndarray 不是新类型,就是 [dims]dtype——shape 用一维数组字面量给出。 -# numpy.rand 输出随机,故不列入期望输出。 -# 期望输出: -# zeros: [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] -# ones: [1.0, 1.0, 1.0] -# full: [[5.0, 5.0], [5.0, 5.0]] -# eye: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] -# arange: [0, 1, 2, 3, 4] -# linspace: [0.0, 0.25, 0.5, 0.75, 1.0] +// numpy 第一类:创建与初始化 +// extern: 需 numpy 扩展引擎驱动 +// python runtime-rwirext_example/py/numpy/numpy.py tutorial/14-numpy/01-creation.kv +// 语义: ndarray 不是新类型,就是 [dims]dtype——shape 用一维数组字面量给出。 +// numpy.rand 输出随机,故不列入期望输出。 +// 期望输出: +// zeros: [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] +// ones: [1.0, 1.0, 1.0] +// full: [[5.0, 5.0], [5.0, 5.0]] +// eye: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] +// arange: [0, 1, 2, 3, 4] +// linspace: [0.0, 0.25, 0.5, 0.75, 1.0] lib demo { rwfunc main() -> () { numpy.zeros([2, 3]) -> z diff --git a/runtime-rwirext_example/py/numpy/tutorial/02-elementwise.kv b/runtime-rwirext_example/py/numpy/tutorial/02-elementwise.kv index f6f04405..c832c891 100644 --- a/runtime-rwirext_example/py/numpy/tutorial/02-elementwise.kv +++ b/runtime-rwirext_example/py/numpy/tutorial/02-elementwise.kv @@ -1,15 +1,15 @@ -# numpy 第二类:elementwise(逐元素) -# extern: 需 numpy 扩展引擎驱动 -# python runtime-rwirext_example/py/numpy/numpy.py tutorial/14-numpy/02-elementwise.kv -# 期望输出: -# add: [5.0, 5.0, 5.0, 5.0] -# sub: [-3.0, -1.0, 1.0, 3.0] -# mul: [4.0, 6.0, 6.0, 4.0] -# div: [0.25, 0.6666666666666666, 1.5, 4.0] -# maximum: [4.0, 3.0, 3.0, 4.0] -# neg: [-1.0, -2.0, -3.0, -4.0] -# sqrt: [1.0, 1.4142135623730951, 1.7320508075688772, 2.0] -# pow2: [1.0, 4.0, 9.0, 16.0] +// numpy 第二类:elementwise(逐元素) +// extern: 需 numpy 扩展引擎驱动 +// python runtime-rwirext_example/py/numpy/numpy.py tutorial/14-numpy/02-elementwise.kv +// 期望输出: +// add: [5.0, 5.0, 5.0, 5.0] +// sub: [-3.0, -1.0, 1.0, 3.0] +// mul: [4.0, 6.0, 6.0, 4.0] +// div: [0.25, 0.6666666666666666, 1.5, 4.0] +// maximum: [4.0, 3.0, 3.0, 4.0] +// neg: [-1.0, -2.0, -3.0, -4.0] +// sqrt: [1.0, 1.4142135623730951, 1.7320508075688772, 2.0] +// pow2: [1.0, 4.0, 9.0, 16.0] lib demo { rwfunc main() -> () { a:[]float64 = [1.0, 2.0, 3.0, 4.0] diff --git a/runtime-rwirext_example/py/numpy/tutorial/03-linalg.kv b/runtime-rwirext_example/py/numpy/tutorial/03-linalg.kv index 905fa1ea..92c10e85 100644 --- a/runtime-rwirext_example/py/numpy/tutorial/03-linalg.kv +++ b/runtime-rwirext_example/py/numpy/tutorial/03-linalg.kv @@ -1,12 +1,12 @@ -# numpy 第三类:matmul(矩阵乘) -# extern: 需 numpy 扩展引擎驱动 -# python runtime-rwirext_example/py/numpy/numpy.py tutorial/14-numpy/03-linalg.kv -# 二维矩阵由一维 arange 经 reshape 得到——ndarray 就是 [dims]dtype,秩由算子产生。 -# 期望输出: -# a: [[0, 1, 2], [3, 4, 5]] -# b: [[0, 1], [2, 3], [4, 5]] -# matmul: [[10, 13], [28, 40]] -# dot: 32.0 +// numpy 第三类:matmul(矩阵乘) +// extern: 需 numpy 扩展引擎驱动 +// python runtime-rwirext_example/py/numpy/numpy.py tutorial/14-numpy/03-linalg.kv +// 二维矩阵由一维 arange 经 reshape 得到——ndarray 就是 [dims]dtype,秩由算子产生。 +// 期望输出: +// a: [[0, 1, 2], [3, 4, 5]] +// b: [[0, 1], [2, 3], [4, 5]] +// matmul: [[10, 13], [28, 40]] +// dot: 32.0 lib demo { rwfunc main() -> () { numpy.arange(6) -> r diff --git a/runtime-rwirext_example/py/numpy/tutorial/04-reduce.kv b/runtime-rwirext_example/py/numpy/tutorial/04-reduce.kv index 52b0ac7e..25930bed 100644 --- a/runtime-rwirext_example/py/numpy/tutorial/04-reduce.kv +++ b/runtime-rwirext_example/py/numpy/tutorial/04-reduce.kv @@ -1,13 +1,13 @@ -# numpy 第四类:reduce(归约) -# extern: 需 numpy 扩展引擎驱动 -# python runtime-rwirext_example/py/numpy/numpy.py tutorial/14-numpy/04-reduce.kv -# 期望输出: -# m: [[0, 1, 2], [3, 4, 5]] -# sum: 15 -# prod: 0 -# max: 5 -# min: 0 -# mean: 2.5 +// numpy 第四类:reduce(归约) +// extern: 需 numpy 扩展引擎驱动 +// python runtime-rwirext_example/py/numpy/numpy.py tutorial/14-numpy/04-reduce.kv +// 期望输出: +// m: [[0, 1, 2], [3, 4, 5]] +// sum: 15 +// prod: 0 +// max: 5 +// min: 0 +// mean: 2.5 lib demo { rwfunc main() -> () { numpy.arange(6) -> r diff --git a/runtime-rwirext_example/py/numpy/tutorial/05-manipulation.kv b/runtime-rwirext_example/py/numpy/tutorial/05-manipulation.kv index 9125d7db..08ad3a9d 100644 --- a/runtime-rwirext_example/py/numpy/tutorial/05-manipulation.kv +++ b/runtime-rwirext_example/py/numpy/tutorial/05-manipulation.kv @@ -1,12 +1,12 @@ -# numpy 第五类:manipulation(形状变换) -# extern: 需 numpy 扩展引擎驱动 -# python runtime-rwirext_example/py/numpy/numpy.py tutorial/14-numpy/05-manipulation.kv -# 期望输出: -# m: [[0, 1, 2], [3, 4, 5]] -# transpose: [[0, 3], [1, 4], [2, 5]] -# ravel: [0, 3, 1, 4, 2, 5] -# concatenate: [1, 2, 3, 4, 5, 6] -# stack: [[1, 2, 3], [4, 5, 6]] +// numpy 第五类:manipulation(形状变换) +// extern: 需 numpy 扩展引擎驱动 +// python runtime-rwirext_example/py/numpy/numpy.py tutorial/14-numpy/05-manipulation.kv +// 期望输出: +// m: [[0, 1, 2], [3, 4, 5]] +// transpose: [[0, 3], [1, 4], [2, 5]] +// ravel: [0, 3, 1, 4, 2, 5] +// concatenate: [1, 2, 3, 4, 5, 6] +// stack: [[1, 2, 3], [4, 5, 6]] lib demo { rwfunc main() -> () { numpy.arange(6) -> r diff --git a/runtime-rwirext_example/py/numpy/tutorial/06-pipeline.kv b/runtime-rwirext_example/py/numpy/tutorial/06-pipeline.kv index b9cce8a0..7e7bfc47 100644 --- a/runtime-rwirext_example/py/numpy/tutorial/06-pipeline.kv +++ b/runtime-rwirext_example/py/numpy/tutorial/06-pipeline.kv @@ -1,15 +1,15 @@ -# numpy 综合:一个线性层 y = relu(W·x + b),串起五大类算子 -# extern: 需 numpy 扩展引擎驱动 -# python runtime-rwirext_example/py/numpy/numpy.py tutorial/14-numpy/06-pipeline.kv -# 创建(arange/reshape/ones/zeros) → matmul → elementwise(add/maximum) → reduce(sum/mean) -# 期望输出: -# W: [[0, 1, 2], [3, 4, 5]] -# x: [0, 1, 2] -# W.x: [5, 14] -# z = W.x + b: [6.0, 15.0] -# y = relu(z): [6.0, 15.0] -# sum(y): 21.0 -# mean(y): 10.5 +// numpy 综合:一个线性层 y = relu(W·x + b),串起五大类算子 +// extern: 需 numpy 扩展引擎驱动 +// python runtime-rwirext_example/py/numpy/numpy.py tutorial/14-numpy/06-pipeline.kv +// 创建(arange/reshape/ones/zeros) → matmul → elementwise(add/maximum) → reduce(sum/mean) +// 期望输出: +// W: [[0, 1, 2], [3, 4, 5]] +// x: [0, 1, 2] +// W.x: [5, 14] +// z = W.x + b: [6.0, 15.0] +// y = relu(z): [6.0, 15.0] +// sum(y): 21.0 +// mean(y): 10.5 lib demo { rwfunc main() -> () { numpy.arange(6) -> a diff --git a/stdlib/http.kv b/stdlib/http.kv index f708c443..bddca05b 100644 --- a/stdlib/http.kv +++ b/stdlib/http.kv @@ -1,8 +1,8 @@ -# 欢迎加入kvspace世界 -# lib http —— 网络抓取标准库。rwir 只有 http·call(method, header, url, body); -# get/post/put/del 都是 rwfunc 封装(kv 源码,可寻址/可自改)。 -# 字符串类型恒 []char/utf32(kvlang 字面量默认编码)。header 是 "K: V\nK2: V2" 原文块, -# 空串 = 无 header;body 空串 = 无请求体。 +// 欢迎加入kvspace世界 +// lib http —— 网络抓取标准库。rwir 只有 http·call(method, header, url, body); +// get/post/put/del 都是 rwfunc 封装(kv 源码,可寻址/可自改)。 +// 字符串类型恒 []char/utf32(kvlang 字面量默认编码)。header 是 "K: V\nK2: V2" 原文块, +// 空串 = 无 header;body 空串 = 无请求体。 lib http { rwfunc get(url:[]char/utf32) -> (resp:[]char/utf32) { diff --git a/stdlib/kv.kv b/stdlib/kv.kv index a208039f..91ab7dd9 100644 --- a/stdlib/kv.kv +++ b/stdlib/kv.kv @@ -1,7 +1,7 @@ -# 欢迎加入kvspace世界 -# lib kv —— KV 空间便利库。native rwir:kv·get/set/del/deltree/list/listlen; -# rwfunc 补充:has(存在检测)、get_or(缺省回退)、set_default(幂等写)。 -# /___kv_stdlib_null___ 为内部 sentinel 路径,用户不得写入。 +// 欢迎加入kvspace世界 +// lib kv —— KV 空间便利库。native rwir:kv·get/set/del/deltree/list/listlen; +// rwfunc 补充:has(存在检测)、get_or(缺省回退)、set_default(幂等写)。 +// /___kv_stdlib_null___ 为内部 sentinel 路径,用户不得写入。 lib kv { rwfunc has(path:[]char/utf32) -> (result:bool) { diff --git a/stdlib/kvlang/deepdive/01-storage-compute-separation-kv-tree.kv b/stdlib/kvlang/deepdive/01-storage-compute-separation-kv-tree.kv index 94d5bc3f..a4f755e6 100644 --- a/stdlib/kvlang/deepdive/01-storage-compute-separation-kv-tree.kv +++ b/stdlib/kvlang/deepdive/01-storage-compute-separation-kv-tree.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/01_storage_compute_separation_kv_tree { - """# 存、算、控制流严格分离的 kv 树计算架构 + r#"# 存、算、控制流严格分离的 kv 树计算架构 ## 存、算、控制流严格分离 @@ -64,5 +64,5 @@ kvspace 元存(slot → XValue) 理由:原子单位从"raw 字节区间"上移到"XValue",使每次读写均为单 key 的原子替换,消除并发 RMW 竞态,与"元存全局公有"定位一致。 -""" -> /lib/kvlang/deepdive/01_storage_compute_separation_kv_tree +"# -> /lib/kvlang/deepdive/01_storage_compute_separation_kv_tree } diff --git a/stdlib/kvlang/deepdive/02-everything-is-plaintext.kv b/stdlib/kvlang/deepdive/02-everything-is-plaintext.kv index 203a56ad..a561a175 100644 --- a/stdlib/kvlang/deepdive/02-everything-is-plaintext.kv +++ b/stdlib/kvlang/deepdive/02-everything-is-plaintext.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/02_everything_is_plaintext { - """# 一切皆明文 + r#"# 一切皆明文 ## 一切皆明文 @@ -38,5 +38,5 @@ kvlang:XValue 带 kind "int64" /vthread/7/.pc .status .rootfunc 直接 Get ### 代价与补偿 明文化贯彻到 kvlang 的方方面面——PC 是字符串而非整数、opcode 是 `"+"` 而非单字节、指针是路径而非地址——这天然损失了解释执行的速度。但 kvlang 的定位是**调度层**,最耗时的 tensor 计算不在 kvlang 内执行:op-gpu 将计算编译为 GPU kernel(TileLang → AOT `.so` → dlopen),通过 GPU 硬件加速弥补。透明性在调度层兑现,算力在扩展引擎层找回。 -""" -> /lib/kvlang/deepdive/02_everything_is_plaintext +"# -> /lib/kvlang/deepdive/02_everything_is_plaintext } diff --git a/stdlib/kvlang/deepdive/03-program-as-datastructure-func-data.kv b/stdlib/kvlang/deepdive/03-program-as-datastructure-func-data.kv index c76753f9..247cae6c 100644 --- a/stdlib/kvlang/deepdive/03-program-as-datastructure-func-data.kv +++ b/stdlib/kvlang/deepdive/03-program-as-datastructure-func-data.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/03_program_as_datastructure_func_data { - """# 程序 = 数据结构 + 函数 + 数据 + r#"# 程序 = 数据结构 + 函数 + 数据 ## 程序 = 数据结构 + 函数 + 数据 @@ -9,5 +9,5 @@ Niklaus Wirth 的经典公式「程序 = 数据结构 + 算法」将程序员的 kvlang 的主张:**程序 = 数据结构 + 函数 + 数据**。数据结构不再由用户自定义——kvlang 的全部数据结构都是 builtin:`struct`(键族前缀),compact 形态数组(`[N]T`,元素连续打包进单个 XValue),stringkeymap 形态数组(`{...}`,元素散落 `base·i` 独立键),链表(`/n0·val`、`/n0·next` 平坦键,路径字符串作指针)。使用者只需声明 `lib`、编写 `rwfunc`,数据自然落地到 `/lib/` 与 `/vthread/` 及用户自定义路径。 键族是 kvlang 唯一的数据结构机制,上层全部收敛为函数(rwfunc/rwir)与数据(kvspace slot)的组合。以 kvspace 树形路径为统一地址空间,同一语法同时承担 VM 指令、高级语言、编译器 IR 三种职能。 -""" -> /lib/kvlang/deepdive/03_program_as_datastructure_func_data +"# -> /lib/kvlang/deepdive/03_program_as_datastructure_func_data } diff --git a/stdlib/kvlang/deepdive/04-four-level-code-hierarchy.kv b/stdlib/kvlang/deepdive/04-four-level-code-hierarchy.kv index 2611f6eb..e01ff5f9 100644 --- a/stdlib/kvlang/deepdive/04-four-level-code-hierarchy.kv +++ b/stdlib/kvlang/deepdive/04-four-level-code-hierarchy.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/04_four_level_code_hierarchy { - """# 代码四级层次 + r"# 代码四级层次 kvlang 中所有代码组织为四个层级,从宏观到微观,每层在 kvspace 树中有对应路径。 @@ -48,5 +48,5 @@ kvlang 中所有代码组织为四个层级,从宏观到微观,每层在 kvs | rwfunc | `rwfunc` | `/lib///` | `/vthread//[N,0]/` | | scope | `scope` | `/lib///_while_N/` | `/vthread//[N,0]/_while_N/` | | rwir | `rwir` | `/lib/`(扩展);native 内联 C 表不落盘 | — | -""" -> /lib/kvlang/deepdive/04_four_level_code_hierarchy +" -> /lib/kvlang/deepdive/04_four_level_code_hierarchy } diff --git a/stdlib/kvlang/deepdive/grammar/kvlang-bnf-grammar.kv b/stdlib/kvlang/deepdive/grammar/kvlang-bnf-grammar.kv index 5a916463..893ce04c 100644 --- a/stdlib/kvlang/deepdive/grammar/kvlang-bnf-grammar.kv +++ b/stdlib/kvlang/deepdive/grammar/kvlang-bnf-grammar.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/grammar/kvlang_bnf_grammar { - """# kvlang 语法 (BNF) + r##"# kvlang 语法 (BNF) > 锚定于 kvlang-deep-dive(根设计文档)——每次 deep-dive 更新后需验证本文与实现一致。 @@ -15,13 +15,15 @@ float = integer [ "." integer ] [ ("e" | "E") [ "+" | "-" ] integer ] path = "/" ident { ("/" | ".") ident | "·" "[" integer { "," integer } "]" } (* 绝对路径字面量;/ 分隔段,. 为子键,· [i,j] 为 strkeymap 坐标段 *) -string = '"' { char } '"' - | \""" { char } \""" +string = '"' { char | escape } '"' + | "r" { "#" } '"' { char } '"' { "#" } | "'" { char } "'" - | "`" { char } "`" - (* 双引号/三引号/单引号支持 \ 转义;反引号为原始字符串(零转义) *) -comment = "#" { char } newline (* 产生 Comment token *) - | "//" { char } newline (* 词法层丢弃,不产生 token *) + (* 双引号:\ 转义(\n \t \" \\ …),可直接跨行。 + r"…" 原始串(零转义);开头 N 个 # 时须以 " 后接同样 N 个 # 闭合, + 故 r#"…"# 内容可含 ",# 越多可嵌套越深。单引号为 char/keypath。 + 无三引号、无反引号原始串——完全对齐 Rust。 *) +comment = "//" { char } newline (* 行注释 *) + | "/*" { char | comment } "*/" (* 块注释,可嵌套;无 # 注释 *) ``` ## 程序结构 @@ -183,5 +185,5 @@ builtin_call = ("print" | "println" (* s[i] 读返单字符字符串, 越界返 ""; s[i]="X" 单字符替换写回新串 *) (* + 作用在 string∧string → 拼接 *) ``` -""" -> /lib/kvlang/deepdive/grammar/kvlang_bnf_grammar +"## -> /lib/kvlang/deepdive/grammar/kvlang_bnf_grammar } diff --git a/stdlib/kvlang/deepdive/kvspace/00-design-and-implementation.kv b/stdlib/kvlang/deepdive/kvspace/00-design-and-implementation.kv index 17b06c01..df9a5936 100644 --- a/stdlib/kvlang/deepdive/kvspace/00-design-and-implementation.kv +++ b/stdlib/kvlang/deepdive/kvspace/00-design-and-implementation.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/kvspace/00_design_and_implementation { - """# KVSpace 基础模型 + r#"# KVSpace 基础模型 ## 设计美学 @@ -59,5 +59,5 @@ ExtIndex 是写时复制叠加层:`ExtIndex("/merge/", "/base/")` 后,读 `/ **路径工具**:`JoinPath` 拼路径避免 `//`;`SepPath` 拆前缀+末段。 **常量集中管理**:所有路径/分隔符/kind 字符串在 `runtime/src/const.h`(C)与 `layout/src/keytree.rs`(Rust),禁止散落硬编码。 -""" -> /lib/kvlang/deepdive/kvspace/00_design_and_implementation +"# -> /lib/kvlang/deepdive/kvspace/00_design_and_implementation } diff --git a/stdlib/kvlang/deepdive/kvspace/01-address-space.kv b/stdlib/kvlang/deepdive/kvspace/01-address-space.kv index 24c0c2bc..78c9e0ef 100644 --- a/stdlib/kvlang/deepdive/kvspace/01-address-space.kv +++ b/stdlib/kvlang/deepdive/kvspace/01-address-space.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/kvspace/01_address_space { - """# 地址空间 + r#"# 地址空间 > 本章讲述 kvlang **使用** kvspace 的过程设计与约束,而非 kvspace 自身的设计实现。 @@ -42,5 +42,5 @@ kvspace 存储两类数据:**基础数据类型**(int、float、bool、strin | 集群节点共享内存 | 大张量、激活值(heap-plat 管理生命周期) | | GPU 显存 | 计算张量(op-plat 在设备侧持有句柄) | | 文件系统/对象存储 | 模型权重、检查点、数据集 | -""" -> /lib/kvlang/deepdive/kvspace/01_address_space +"# -> /lib/kvlang/deepdive/kvspace/01_address_space } diff --git a/stdlib/kvlang/deepdive/kvspace/02-addressing-model-and-naming.kv b/stdlib/kvlang/deepdive/kvspace/02-addressing-model-and-naming.kv index a5fdf104..54352ced 100644 --- a/stdlib/kvlang/deepdive/kvspace/02-addressing-model-and-naming.kv +++ b/stdlib/kvlang/deepdive/kvspace/02-addressing-model-and-naming.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/kvspace/02_addressing_model_and_naming { - """# 寻址模型与命名 + r#"# 寻址模型与命名 ## 寻址模型:KV 路径 vs 内存地址 @@ -72,5 +72,5 @@ kvlang 没有 `&` 取址运算符——**代码中对象的变量名,本身就 全局变量 `/counter` 零成本——绝对指针不经过帧前缀拼接。数组能作为参数传递——`flattenNestedCalls` 将 `[1,2,3]` 展开为临时变量,再将临时变量(持有 XValue)作为普通参数传递。 **参数不得同名(fix-032)**:变量名即指针——同一帧内两个同名参数将指向同一个 kvspace 位置。读参列表内部、写参列表内部、以及读写列表之间均不可同名。`rwfunc f(A:int64) -> (A:int64)` 签名非法。layout 的 `checkParamDup` 阻断源码路径,C runtime 兜底非法签名。 -""" -> /lib/kvlang/deepdive/kvspace/02_addressing_model_and_naming +"# -> /lib/kvlang/deepdive/kvspace/02_addressing_model_and_naming } diff --git a/stdlib/kvlang/deepdive/kvspace/03-instruction-layout-format.kv b/stdlib/kvlang/deepdive/kvspace/03-instruction-layout-format.kv index b0556324..164c3a5f 100644 --- a/stdlib/kvlang/deepdive/kvspace/03-instruction-layout-format.kv +++ b/stdlib/kvlang/deepdive/kvspace/03-instruction-layout-format.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/kvspace/03_instruction_layout_format { - """# 代码指令的布局格式 + r#"# 代码指令的布局格式 > 签名参数/返回值的 `type` 用**签名类型表达式**(并集 `A|B`、通配 `any`、高维 shape `[2,3]`、动态维 `?`),BNF 见 `grammar.bnf`。 @@ -100,5 +100,5 @@ frameRoot/[1,0] → ext→ "+" ← 指令 | 参数模型 | 寄存器/栈槽传值 | Ptr 链:name→slot→arg→value(3 跳) | **`=` 操作码是值拷贝,不是函数调用**:`a -> b` 编码为 `[s0,0]="="`(值拷贝),函数调用 opcode 位是 `call`,ExtIndex 发生在调用处理函数内部。二者在 KV 层无歧义,opcode 位永远不放变量引用。 -""" -> /lib/kvlang/deepdive/kvspace/03_instruction_layout_format +"# -> /lib/kvlang/deepdive/kvspace/03_instruction_layout_format } diff --git a/stdlib/kvlang/deepdive/kvspace/04-system-variables.kv b/stdlib/kvlang/deepdive/kvspace/04-system-variables.kv index 12bca203..ffebaddf 100644 --- a/stdlib/kvlang/deepdive/kvspace/04-system-variables.kv +++ b/stdlib/kvlang/deepdive/kvspace/04-system-variables.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/kvspace/04_system_variables { - """# 系统变量 + r#"# 系统变量 ## `X/‥var` 影子键 @@ -62,5 +62,5 @@ VM 运行时为它管理的对象生成**内置变量(系统变量)**,以 1. **零冲突的专属命名空间**。用户成员语法只产生 `·` 中点键,标识符禁止 `‥` 开头;用户侧永远造不出 `‥` 序列。若系统变量也用 `·` 拼接,则需维护保留字表,且动态键注入可能命中系统键。 2. **生命周期绑定**。`X/‥var` 在 X 的 `/` 子树内,`DelTree(X)` 连带清除全部系统变量;用户键族 `X·*` 由前缀删除管理。两个删除平面各归其主。 3. **统一公理**。任何 kvspace 对象 X:VM 元数据在 `X/‥名`(引擎保留),帧根 extindex 指向 `/lib/` 代码区,用户数据在 `X·名`(成员),子级在 `X/名`(结构)。 -""" -> /lib/kvlang/deepdive/kvspace/04_system_variables +"# -> /lib/kvlang/deepdive/kvspace/04_system_variables } diff --git a/stdlib/kvlang/deepdive/kvspace/05-key-system-and-array-access.kv b/stdlib/kvlang/deepdive/kvspace/05-key-system-and-array-access.kv index a50f0caf..f781a502 100644 --- a/stdlib/kvlang/deepdive/kvspace/05-key-system-and-array-access.kv +++ b/stdlib/kvlang/deepdive/kvspace/05-key-system-and-array-access.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/kvspace/05_key_system_and_array_access { - """# key 系统与数组访问 + r#"# key 系统与数组访问 ## 背景:分隔符语义化 @@ -147,5 +147,5 @@ body = [M B raw] M = raw_len,offset = HeadLen() - compact 多维 `[256,256]uint8` 的 row-major 排布约定(与 op-gpu tensor 连续布局对齐)。 - stringkeymap 形态随机访问:元素散落 `base·i` 子 key,`for-in`/`kv·get` 可遍历,但 `arr[i]`/`ndarray·numel` 随机访问尚未打通;需随机访问的数值数组用 compact 形态。 - 扩展存储句柄 body 的位置 schema(device 枚举、shm_name/offset、fd、GPU ptr 的统一编码)。 -""" -> /lib/kvlang/deepdive/kvspace/05_key_system_and_array_access +"# -> /lib/kvlang/deepdive/kvspace/05_key_system_and_array_access } diff --git a/stdlib/kvlang/deepdive/layout/01-instruction-architecture.kv b/stdlib/kvlang/deepdive/layout/01-instruction-architecture.kv index 1264f149..fa3b4113 100644 --- a/stdlib/kvlang/deepdive/layout/01-instruction-architecture.kv +++ b/stdlib/kvlang/deepdive/layout/01-instruction-architecture.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/layout/01_instruction_architecture { - """# Instruction Architecture(指令架构) + r#"# Instruction Architecture(指令架构) ## 指令分类 @@ -135,5 +135,5 @@ kvcpu 沿 s1 轴向两侧扩展,直到遇到空 key 停止,参数数量**隐 | 参数数量 | opcode 内编码 arity | 隐式:扫描到空 key 停止 | | 数据流方向 | 单向(操作数 → 结果) | 符号编码(负=读, 正=写) | | 可观察性 | 字节不可独立寻址 | 每个槽是独立 KV key,可单独 Get/Watch | -""" -> /lib/kvlang/deepdive/layout/01_instruction_architecture +"# -> /lib/kvlang/deepdive/layout/01_instruction_architecture } diff --git a/stdlib/kvlang/deepdive/layout/02-functions.kv b/stdlib/kvlang/deepdive/layout/02-functions.kv index b4c3f548..f459e099 100644 --- a/stdlib/kvlang/deepdive/layout/02-functions.kv +++ b/stdlib/kvlang/deepdive/layout/02-functions.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/layout/02_functions { - """# 函数 + r#"# 函数 > 签名参数/返回值的 `type` 用签名类型表达式(并集 `A|B`、通配 `any`、高维 shape `[2,3]`、动态维 `?`),见 `grammar.bnf`。 @@ -49,5 +49,5 @@ rwfunc sum(arr) -> (acc:int64) { acc + arr[0] -> acc } - 字面量写槽(数字/引号串开头)→ warn「unexpected token in write slot position」 - 写槽后紧跟 `(` → warn「function call on same line as write slot」 - 合法写槽:裸名、`/abs`、`base·名` -""" -> /lib/kvlang/deepdive/layout/02_functions +"# -> /lib/kvlang/deepdive/layout/02_functions } diff --git a/stdlib/kvlang/deepdive/layout/03-control-flow.kv b/stdlib/kvlang/deepdive/layout/03-control-flow.kv index 2a16dd61..4b95434f 100644 --- a/stdlib/kvlang/deepdive/layout/03-control-flow.kv +++ b/stdlib/kvlang/deepdive/layout/03-control-flow.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/layout/03_control_flow { - """# 控制流:Scope 帧模型 + r"# 控制流:Scope 帧模型 # Part 1: Layout @@ -137,5 +137,5 @@ scope 帧隐式 return:读 `.returnpc` → DelTree 自身 → 返回父上下 | scope 指令查找 | — | **Decode scope 前缀 key** + 父帧 extindex | | 返回地址 | 硬件栈 | **`.returnpc`** 显式记录 | | 崩溃恢复 | 内存栈,死即全失 | PC + frameRoot 落 KV——重启续跑 | -""" -> /lib/kvlang/deepdive/layout/03_control_flow +" -> /lib/kvlang/deepdive/layout/03_control_flow } diff --git a/stdlib/kvlang/deepdive/layout/04-layout-pipeline.kv b/stdlib/kvlang/deepdive/layout/04-layout-pipeline.kv index 9e6ff2ba..1406a97a 100644 --- a/stdlib/kvlang/deepdive/layout/04-layout-pipeline.kv +++ b/stdlib/kvlang/deepdive/layout/04-layout-pipeline.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/layout/04_layout_pipeline { - """# Layout Pipeline(layout 流水线) + r#"# Layout Pipeline(layout 流水线) ## kvlang 流水线 @@ -33,5 +33,5 @@ kvlang:无字节码数组,无整数 PC,控制流通过 KV 路径跳转; ## AST 类型标记——`quote` 字段 `Expr.quote` 区分字符串字面量和变量名(替代旧的 `"` 前缀 hack)。`flat()` 在 KV 传输层对字符串字面量加 `"` 前缀,数字字面量不加引号。 -""" -> /lib/kvlang/deepdive/layout/04_layout_pipeline +"# -> /lib/kvlang/deepdive/layout/04_layout_pipeline } diff --git a/stdlib/kvlang/deepdive/layout/05-diagnostic-output.kv b/stdlib/kvlang/deepdive/layout/05-diagnostic-output.kv index 07d7933c..75de20e7 100644 --- a/stdlib/kvlang/deepdive/layout/05-diagnostic-output.kv +++ b/stdlib/kvlang/deepdive/layout/05-diagnostic-output.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/layout/05_diagnostic_output { - """# Diagnostic Output(诊断输出规范) + r"# Diagnostic Output(诊断输出规范) ## 诊断输出架构(Rust layout + C runtime) @@ -22,5 +22,5 @@ lib kvlang/deepdive/layout/05_diagnostic_output { ## 原则 诊断(layout 报错/运行时错误)走各层的诊断接口;stdout 结果(`print` 输出、格式化内容、命令成功状态)不加前缀直接输出。 -""" -> /lib/kvlang/deepdive/layout/05_diagnostic_output +" -> /lib/kvlang/deepdive/layout/05_diagnostic_output } diff --git a/stdlib/kvlang/deepdive/layout/06-layout-rwir.kv b/stdlib/kvlang/deepdive/layout/06-layout-rwir.kv index c6da465f..161a5ede 100644 --- a/stdlib/kvlang/deepdive/layout/06-layout-rwir.kv +++ b/stdlib/kvlang/deepdive/layout/06-layout-rwir.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/layout/06_layout_rwir { - """# Layoutrwir: 装载与执行 + r#"# Layoutrwir: 装载与执行 ## lib 树与装载 @@ -49,5 +49,5 @@ lib kvlang/deepdive/layout/06_layout_rwir { ## `=` 操作码 `a -> b` 编码为 `[s0,0]="="`(值拷贝)。函数调用 opcode 位为 `call`。opcode 槽位永远不放变量引用。 -""" -> /lib/kvlang/deepdive/layout/06_layout_rwir +"# -> /lib/kvlang/deepdive/layout/06_layout_rwir } diff --git a/stdlib/kvlang/deepdive/layout/07-rwir-and-lib-data.kv b/stdlib/kvlang/deepdive/layout/07-rwir-and-lib-data.kv index d13dbdde..837bda41 100644 --- a/stdlib/kvlang/deepdive/layout/07-rwir-and-lib-data.kv +++ b/stdlib/kvlang/deepdive/layout/07-rwir-and-lib-data.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/layout/07_rwir_and_lib_data { - """# rwir 与 lib 数据:注册布局 + r#"# rwir 与 lib 数据:注册布局 > 签名参数/返回值的 `type` 用签名类型表达式(并集 `A|B`、通配 `any`、高维 shape `[2,3]`、动态维 `?`),见 `grammar.bnf`。 @@ -82,5 +82,5 @@ rwir myop(A:int64, B:int64) -> (C:int64) | `runtime/src/rwirext.c` | `kvlang_rwirextRegister(opcode, nr, nw, sig)` → `/lib/` | | `runtime/src/kvcpu.c` | execute 循环 `load_def_reads` + `check_read_types` 内联类型匹配 | | `runtime/src/type_expr.c` | `kvlang_rwirextTypeValid`(装载校验)+ `kvlang_rwirextTypeMatch`(运行时匹配) | -""" -> /lib/kvlang/deepdive/layout/07_rwir_and_lib_data +"# -> /lib/kvlang/deepdive/layout/07_rwir_and_lib_data } diff --git a/stdlib/kvlang/deepdive/reference/01-how-to-design-a-language.kv b/stdlib/kvlang/deepdive/reference/01-how-to-design-a-language.kv index bbf1f14c..8174d64b 100644 --- a/stdlib/kvlang/deepdive/reference/01-how-to-design-a-language.kv +++ b/stdlib/kvlang/deepdive/reference/01-how-to-design-a-language.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/reference/01_how_to_design_a_language { - """# reference篇-01: 如何设计编程语言 + r#"# reference篇-01: 如何设计编程语言 编程语言设计:核心准则、设计约束与系统性避坑规范 @@ -117,5 +117,5 @@ lib kvlang/deepdive/reference/01_how_to_design_a_language { - 通过扩展机制(rwir/rwext)实现算子融合;layout层只做检查与布局,runtime层只做解释执行 该类项目的核心价值在于重新定义程序执行与状态存储的底层范式。 -""" -> /lib/kvlang/deepdive/reference/01_how_to_design_a_language +"# -> /lib/kvlang/deepdive/reference/01_how_to_design_a_language } diff --git a/stdlib/kvlang/deepdive/runtime/01-type-system.kv b/stdlib/kvlang/deepdive/runtime/01-type-system.kv index 65f4007f..de7e1b85 100644 --- a/stdlib/kvlang/deepdive/runtime/01-type-system.kv +++ b/stdlib/kvlang/deepdive/runtime/01-type-system.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/runtime/01_type_system { - """# Type System(类型系统) + r#"# Type System(类型系统) ## 类型系统 @@ -132,5 +132,5 @@ u <- char/ascii(t) # 拒非 ASCII 码点 → TypeError 隐式 coerce 会使控制流条件取决于运行时 kind,agent 无法静态判定控制流走向。强制显式比较使 br 指令的 cond 槽永远是 bool。 **实现**:`kvlangXvalueAsBool`(`xvalue.c`)仅接受 `kind=="bool"`,其他 kind 直接 panic。 -""" -> /lib/kvlang/deepdive/runtime/01_type_system +"# -> /lib/kvlang/deepdive/runtime/01_type_system } diff --git a/stdlib/kvlang/deepdive/runtime/02-member-access-and-data-structures.kv b/stdlib/kvlang/deepdive/runtime/02-member-access-and-data-structures.kv index 841bd163..82abe618 100644 --- a/stdlib/kvlang/deepdive/runtime/02-member-access-and-data-structures.kv +++ b/stdlib/kvlang/deepdive/runtime/02-member-access-and-data-structures.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/runtime/02_member_access_and_data_structures { - """# Member Access and Data Structures(成员访问与数据结构) + r#"# Member Access and Data Structures(成员访问与数据结构) ## 两个索引符号:`[]` 与 `·` @@ -73,5 +73,5 @@ xv·set(a, 2, 99) -> a # 显式写,等价 ``` 下标写用赋值式 `a[i] = v`;`->` 形式的写槽不能带下标(`v -> a[i]` 被 layout 拒绝),改用 `a[i] = v` 或 `xv·set`。 -""" -> /lib/kvlang/deepdive/runtime/02_member_access_and_data_structures +"# -> /lib/kvlang/deepdive/runtime/02_member_access_and_data_structures } diff --git a/stdlib/kvlang/deepdive/runtime/03-debugging-and-observability.kv b/stdlib/kvlang/deepdive/runtime/03-debugging-and-observability.kv index b9c25e8f..64bf110b 100644 --- a/stdlib/kvlang/deepdive/runtime/03-debugging-and-observability.kv +++ b/stdlib/kvlang/deepdive/runtime/03-debugging-and-observability.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/runtime/03_debugging_and_observability { - """# Debugging and Observability(调试与可观测性) + r#"# Debugging and Observability(调试与可观测性) ## 调试模型:暂停即落盘,观察即读 kvspace @@ -95,5 +95,5 @@ kvlang dump prog.kv # 4. 对照源码与槽位 kvspace set /vthread//‥status string:running kvlang run # 5. 恢复到结束 ``` -""" -> /lib/kvlang/deepdive/runtime/03_debugging_and_observability +"# -> /lib/kvlang/deepdive/runtime/03_debugging_and_observability } diff --git a/stdlib/kvlang/deepdive/runtime/04-function-call-builtin.kv b/stdlib/kvlang/deepdive/runtime/04-function-call-builtin.kv index 88f85a4f..6af05ee7 100644 --- a/stdlib/kvlang/deepdive/runtime/04-function-call-builtin.kv +++ b/stdlib/kvlang/deepdive/runtime/04-function-call-builtin.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/runtime/04_function_call_builtin { - """# 函数调用(layout → runtime) + r#"# 函数调用(layout → runtime) ## 三种调用形态,收敛到同一 KV key @@ -76,5 +76,5 @@ native 算子按类别注册于 `runtime/src/builtin*.c`(无独立包目录) - 带 `·` 的方法:`string·* xv·* kv·* ndarray·* array·* vthread·* time·* random·intn`、`debugger`、`print`/`println` kind 的字节宽由 `kvlangXvalueElemSize(kind)` 决定(char/utf8=1,int32/float32=4,int64/float64=8 …),数组与字符串的元素访问据此零拷贝定位。 -""" -> /lib/kvlang/deepdive/runtime/04_function_call_builtin +"# -> /lib/kvlang/deepdive/runtime/04_function_call_builtin } diff --git a/stdlib/kvlang/deepdive/runtime/05-rwirext-extension-runtime.kv b/stdlib/kvlang/deepdive/runtime/05-rwirext-extension-runtime.kv index d9376618..ba6d1ff9 100644 --- a/stdlib/kvlang/deepdive/runtime/05-rwirext-extension-runtime.kv +++ b/stdlib/kvlang/deepdive/runtime/05-rwirext-extension-runtime.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/runtime/05_rwirext_extension_runtime { - """# runtime篇-05: rwirext 扩展运行时 + r#"# runtime篇-05: rwirext 扩展运行时 > 状态:与实现同步。代码:`runtime/src/rwirext.c`(C 扩展 ABI)、`runtime-rwirext_example/rust/term`(Rust term)、`runtime-rwirext_example/go/json`(Go json)。C runtime 侧实现见 [[runtime篇-06-C运行时与后端抽象]]。 @@ -115,5 +115,5 @@ Rust runtime(runtime-rs)中,就地 rwir(print/json/http)直接在 `dri | `/ext/` | 在哪、怎么执行(拓扑) | 存储/计算/通信注册 | 无状态扩展运行时(term/json)只写 `/lib/`;有状态扩展引擎(op-gpu/heap-plat)写 `/lib/` + `/ext/`。handoff 协议一致,后者多一次 `/ext/` 查表定位引擎。 -""" -> /lib/kvlang/deepdive/runtime/05_rwirext_extension_runtime +"# -> /lib/kvlang/deepdive/runtime/05_rwirext_extension_runtime } diff --git a/stdlib/kvlang/deepdive/runtime/06-c-runtime-and-backend-abstraction.kv b/stdlib/kvlang/deepdive/runtime/06-c-runtime-and-backend-abstraction.kv index 7bc66f40..75ce4dda 100644 --- a/stdlib/kvlang/deepdive/runtime/06-c-runtime-and-backend-abstraction.kv +++ b/stdlib/kvlang/deepdive/runtime/06-c-runtime-and-backend-abstraction.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/runtime/06_c_runtime_and_backend_abstraction { - """# runtime篇-06: C 运行时与后端抽象 + r#"# runtime篇-06: C 运行时与后端抽象 > 状态:与实现同步。代码:`kvlang/runtime/`(纯 C)、`kvlang/runtime-rwirext_example/rust/term/`、`kvlang/runtime-rwirext_example/go/json/`、`kvlang/runtime-rwirext_example/py/numpy/`、`array2d/kvspace-c/`(SHM)、`array2d/kvspace-durable/`(fs/redis)。 @@ -77,5 +77,5 @@ kvspaceNewPtr / NewChar / NewBool / NewInt64 / NewFloat64 Go runtime 为 136/136 baseline(`goheap://` 进程内,无 RTT/文件 I/O)。 **后端存储布局差异(非语义 bug)**:fs 后端(`kvspace-durable/src/fs`)把成员分隔符 `·`(OBJ_SEP)编码为 `·/`——尾中点目录 + `/` 目录边界,故限定名 `/lib/math·sum` 在 fs 上呈嵌套目录 `lib/math·/sum`,而 redis/shm 后端存为扁平单键 `/lib/math·sum`。读写经对称编解码还原(`·/`↔`·`),三后端语义一致。 -""" -> /lib/kvlang/deepdive/runtime/06_c_runtime_and_backend_abstraction +"# -> /lib/kvlang/deepdive/runtime/06_c_runtime_and_backend_abstraction } diff --git a/stdlib/kvlang/deepdive/runtime/07-signature-type-expression.kv b/stdlib/kvlang/deepdive/runtime/07-signature-type-expression.kv index 7e70be6c..4f8e19d8 100644 --- a/stdlib/kvlang/deepdive/runtime/07-signature-type-expression.kv +++ b/stdlib/kvlang/deepdive/runtime/07-signature-type-expression.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 +// 欢迎加入kvspace世界 lib kvlang/deepdive/runtime/07_signature_type_expression { - """# runtime篇-07: 签名类型表达式(多态 + 高维数组) + r#"# runtime篇-07: 签名类型表达式(多态 + 高维数组) > 状态:设计定稿。代码:签名字符串存 `/lib/·`(kind=`defrwfunc`/`defrwir`),参数类型即本文件的「类型表达式」。 @@ -131,5 +131,5 @@ func matchAtom(atom, kind string, ndim int, dims []int32) bool { **扩展 op** 经 `kvlang_rwirextRegister(opcode, nr, nw, sig)` 注册,runtime 把 `sig` 按方括号感知切分为各参 kindexpr、做 `kvlang_rwirextKindexprValid` 校验(拒绝 `path` 等非 kind),并按上述定义体格式写入 `/lib/`(kind=`defrwir`)。 **运行时内联匹配**:execute 循环走到 `isothersrwir` 派发前,按 opcode 从 `/lib/` 取定义体、解出读参 kindexpr,对每个已解析实参(kind/ndim/dims)跑 `kvlang_rwirextKindexprMatch`;变参 `...` 把尾随实参全部对末 kindexpr 判定。任一失配 → `TypeError` 写 vthread 错误并停机。 -""" -> /lib/kvlang/deepdive/runtime/07_signature_type_expression +"# -> /lib/kvlang/deepdive/runtime/07_signature_type_expression } diff --git a/stdlib/kvlang/kvlangbrief.kv b/stdlib/kvlang/kvlangbrief.kv index 7ac10b23..86dadcab 100644 --- a/stdlib/kvlang/kvlangbrief.kv +++ b/stdlib/kvlang/kvlangbrief.kv @@ -1,21 +1,28 @@ -# 欢迎加入kvspace世界 -# kvlang 语法速览 —— 也是 KV 树里的数据。 -# 本文件在 kvlang stdlib,runtime-rs 启动时 layout&run:顶层写语句包进 kvlang·init, -# 执行后把整份速览作为字符串落在 /lib/kvlang/kvlangbrief。 -# 之后 byteseek 的 llm·call 生成 kv 代码时,把这份速览拼进系统提示。 +// 欢迎加入kvspace世界 +// kvlang 语法速览 —— 也是 KV 树里的数据。 +// 本文件在 kvlang stdlib,runtime-rs 启动时 layout&run:顶层写语句包进 kvlang·init, +// 执行后把整份速览作为字符串落在 /lib/kvlang/kvlangbrief。 +// 之后 byteseek 的 llm·call 生成 kv 代码时,把这份速览拼进系统提示。 lib kvlang { - """# kvlang 速览 + r###"# kvlang 速览 kvlang 是一门全新语言,语法以下面示例为准,不要套用其它语言直觉。 +## 注释与字符串(对齐 Rust) +- 注释:`//` 行注释、`/* … */` 块注释(可嵌套)。**没有 `#` 注释**。 +- 字符串三形式: + - `"…"` 转义串(`\n \t \" \\` 等生效,可直接跨行)。 + - `r"…"` 原始串(零转义,内容不含 `"`)。 + - `r#"…"#` / `r##"…"##` 原始串带井号栏,内容可含 `"`;井号越多可嵌套越深。**没有 `"""` 三引号、没有反引号串**。 + ## 程序结构 文件入口约定是 `rwfunc test() -> () { … }`——`kvlang xxx.kv` 会自动运行 `test`,**不要**再手写 `test()` 调用。其它函数(含习惯叫的 `main`)必须被 `test` 直接或间接调用才会执行。 ```kv rwfunc test() -> () { - total = 0 # = 等价 <-,写左边这个槽 - 1 -> i # -> 写右边这个槽 + total = 0 // = 等价 <-,写左边这个槽 + 1 -> i // -> 写右边这个槽 while (i <= 5) { total <- total + i; i + 1 -> i } - println(total) # 15 + println(total) // 15 } ``` @@ -35,8 +42,8 @@ rwfunc sum(arr:[]int64) -> (acc:int64) { while (i < ndarray·numel(arr)) { xv·at(arr,i) -> e; acc + e -> acc; i + 1 -> i } } rwfunc test() -> () { - mylib·add(3,4) -> s; println(s) # 7 - a:[]int64 = [1,2,3,4,5]; sum(a) -> t; println(t) # 15 + mylib·add(3,4) -> s; println(s) // 7 + a:[]int64 = [1,2,3,4,5]; sum(a) -> t; println(t) // 15 } ``` @@ -49,15 +56,15 @@ rwfunc test() -> () { - **compact**(`[...]`):定长同类型元素连续打包进**单个 XValue**(head kind=元素类型),支持 `xv·at`/`ndarray·numel`/下标随机访问;多维 `[256,256]uint8` 即 ndarray/tensor。 - **stringkeymap**(`{...}`):每元素落 `base·i` 独立 key(head kind=`stringkeymap`),变长/可增长,**字符串数组、可追加数组走这里**,用 `for-in` 遍历(`w:[]char/utf8 = {"foo","bar"}`)。 ```kv -a:[]int64 = [7,2,9,4] # ✅ compact:`[]` 前缀才是数组,裸 kind 是标量;写成 a:int64=[...] 会报错 -ndarray·numel(a) -> n # 4 -xv·at(a,2) -> e # 9(0 起) -xv·set(a,1,99) -> a # 改元素:a=[7,99,9,4] +a:[]int64 = [7,2,9,4] // ✅ compact:`[]` 前缀才是数组,裸 kind 是标量;写成 a:int64=[...] 会报错 +ndarray·numel(a) -> n // 4 +xv·at(a,2) -> e // 9(0 起) +xv·set(a,1,99) -> a // 改元素:a=[7,99,9,4] ``` 遍历/聚合用 `while + ndarray·numel + xv·at`。求最大值: ```kv xv·at(a,0) -> hi; 1 -> i -while (i < ndarray·numel(a)) { xv·at(a,i) -> e; if (e > hi) { e -> hi }; i + 1 -> i } # hi=9 +while (i < ndarray·numel(a)) { xv·at(a,i) -> e; if (e > hi) { e -> hi }; i + 1 -> i } // hi=9 ``` ## 容器:stringkeymap / object(关键:`[]` 是数组专用,容器成员绝不用 `[]`) @@ -66,21 +73,21 @@ while (i < ndarray·numel(a)) { xv·at(a,i) -> e; if (e > hi) { e -> hi }; i + 1 key 侧恒 `[]char/` 字符串键,或 `[标量,…]` 元组键(如 `[int64]`、`[int32,int32]`,物理以字符串格式落 key);value 可递归嵌套(`[]char/utf8·[]char/utf8·int64`)。 - **object**:异构命名成员(类 struct/record)。 ```kv -d:[]char/utf8·int64 = {} # 空 map 必须标类型 -d·a = 10; d·b = 20 # 成员写(命名成员在 d·a) -kv·get(d, "a") -> x # 取值;缺失返回 None -k = "a"; d·*k -> v # 动态键:读 d·a -kv·set(d, k, 99) -> _ # 动态键写 -m:[int64]·int64 = {} # 整型键 map(key 落字符串) +d:[]char/utf8·int64 = {} // 空 map 必须标类型 +d·a = 10; d·b = 20 // 成员写(命名成员在 d·a) +kv·get(d, "a") -> x // 取值;缺失返回 None +k = "a"; d·*k -> v // 动态键:读 d·a +kv·set(d, k, 99) -> _ // 动态键写 +m:[int64]·int64 = {} // 整型键 map(key 落字符串) kv·set(m, 0, 7) -> _; kv·get(m, 0) -> e -rec:object = {} # 异构命名成员 +rec:object = {} // 异构命名成员 rec·name = "kv"; rec·ver = 1 ``` **容器成员一律走 `·` / `kv·get` / `kv·set`,绝不用 `[]`**——`[]` 只索引 compact array(见「数组」),对容器用 `[]` 会 layout 报错。 ```kv -/n1:object = {} # 跨函数共享的数据放绝对路径 +/n1:object = {} // 跨函数共享的数据放绝对路径 /n1·val = 1; /n1·next = "/n2" -"/n1" -> p; p·val -> v # ✅ 引号=路径串(指针)·member 解引用;不加引号 /n1 读的是值非路径 +"/n1" -> p; p·val -> v // ✅ 引号=路径串(指针)·member 解引用;不加引号 /n1 读的是值非路径 ``` ## 扩展世界:`@` 前缀 kindexpr @@ -98,12 +105,12 @@ rec·name = "kv"; rec·ver = 1 `print` / `println` 可用(扩展 rwir)。字符串用 `+` 拼接: ```kv s = "hello" -string·len(s) -> n # 5 -string·char(s,1) -> c # 'e'(读第 i 个字符) -string·slice(s,0,2) -> p # "he" -string·find(s,"ll") -> i # 2(找不到返回 -1) -# 替换第 i 个字符:用 slice 拼接,不要用 string·char(s,i)=x -string·slice(s,0,1) + "a" -> t; string·slice(s,2,5) -> u; t + u -> r # "hallo" +string·len(s) -> n // 5 +string·char(s,1) -> c // 'e'(读第 i 个字符) +string·slice(s,0,2) -> p // "he" +string·find(s,"ll") -> i // 2(找不到返回 -1) +// 替换第 i 个字符:用 slice 拼接,不要用 string·char(s,i)=x +string·slice(s,0,1) + "a" -> t; string·slice(s,2,5) -> u; t + u -> r // "hallo" ``` **`+` 只在同类别内成立(数值 vs 字符不可混)**:两边都是字符=拼接,两边都是数值=相加;数值与字符跨类别会 TypeError。 @@ -112,28 +119,28 @@ string·slice(s,0,1) + "a" -> t; string·slice(s,2,5) -> u; t + u -> r # "hall 打印带标签的数字,用 `println` 多参数(自动空格分隔),**不要**拼字符串: ```kv n = 42 -println("answer =", n) # answer = 42(✅ 两个参数) -# "answer = " + n -> s; println(s) # ❌ TypeError:char + int +println("answer =", n) // answer = 42(✅ 两个参数) +// "answer = " + n -> s; println(s) // ❌ TypeError:char + int ``` ## 自举:代码即数据(生成/校验/入库/运行) kv 代码是 KV 树里的数据,可运行时自产自运行: ```kv -kvlanglayout·vet(src) -> v # 校验源码:合法 "ok",否则错误信息 -kvlanglayout·format(src) -> f # 规范化源码(parse → 格式化文本) -kvlanglayout·layout(src) -> e # 源码入库 /lib:成功空串,失败 "error: …" -kvlanglayout·dump("/lib") -> d # /lib 子树导出为可运行源码(含 # 槽位注释) -vthread·call("pkg·func") # 在当前 vthread 直接调用已入库函数到结束再续跑(裸名 = /lib/<名>) -vthread·create("pkg·func") -> vid # 新开独立子 vthread(只创建不运行),返回 vid 句柄 -vthread·run(vid) # 驱动某 vid(由 create 得到)到结束——参数是 vid,不是函数名 +kvlanglayout·vet(src) -> v // 校验源码:合法 "ok",否则错误信息 +kvlanglayout·format(src) -> f // 规范化源码(parse → 格式化文本) +kvlanglayout·layout(src) -> e // 源码入库 /lib:成功空串,失败 "error: …" +kvlanglayout·dump("/lib") -> d // /lib 子树导出为可运行源码(含 // 槽位注释) +vthread·call("pkg·func") // 在当前 vthread 直接调用已入库函数到结束再续跑(裸名 = /lib/<名>) +vthread·create("pkg·func") -> vid // 新开独立子 vthread(只创建不运行),返回 vid 句柄 +vthread·run(vid) // 驱动某 vid(由 create 得到)到结束——参数是 vid,不是函数名 ``` ## 调试 / 暂停 ```kv -debugger() # 内联断点:执行到此暂停(status 置 paused) -vthread·setstatus("paused") # 等价:设 vthread 状态(paused 即停住) +debugger() // 内联断点:执行到此暂停(status 置 paused) +vthread·setstatus("paused") // 等价:设 vthread 状态(paused 即停住) ``` 暂停后由外部把 `/vthread/{vid}/·status` 改回 `running` 续跑。 -""" -> /lib/kvlang/kvlangbrief +"### -> /lib/kvlang/kvlangbrief } diff --git a/stdlib/math.kv b/stdlib/math.kv index e55d37b6..766db90c 100644 --- a/stdlib/math.kv +++ b/stdlib/math.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 -# lib math —— 数学常量(常量成员式)。绝对路径赋值,math·init 落值;读侧同样用绝对路径: -# /lib/math·Pi -> p 或 kv·get("/lib/math·Pi") -> p +// 欢迎加入kvspace世界 +// lib math —— 数学常量(常量成员式)。绝对路径赋值,math·init 落值;读侧同样用绝对路径: +// /lib/math·Pi -> p 或 kv·get("/lib/math·Pi") -> p lib math { /lib/math·Pi = 3.141592653589793 diff --git a/stdlib/string.kv b/stdlib/string.kv index ff471f53..b3e00343 100644 --- a/stdlib/string.kv +++ b/stdlib/string.kv @@ -1,8 +1,8 @@ -# 欢迎加入kvspace世界 -# lib string —— 字符串便利标准库。string native rwir 提供 len/char/ord/cmp/concat/find/slice -# 及 strconv 家族 formatint/formatuint/parseint/parseuint(base 2..36,对齐 Go strconv); -# 以下 rwfunc 封装常用组合操作(判断 / 变换)。 -# 字符串类型恒 []char/utf32(kvlang 字面量默认编码)。 +// 欢迎加入kvspace世界 +// lib string —— 字符串便利标准库。string native rwir 提供 len/char/ord/cmp/concat/find/slice +// 及 strconv 家族 formatint/formatuint/parseint/parseuint(base 2..36,对齐 Go strconv); +// 以下 rwfunc 封装常用组合操作(判断 / 变换)。 +// 字符串类型恒 []char/utf32(kvlang 字面量默认编码)。 lib string { rwfunc eq(a:[]char/utf32, b:[]char/utf32) -> (r:bool) { diff --git a/stdlib/time.kv b/stdlib/time.kv index 79498201..15dcadc2 100644 --- a/stdlib/time.kv +++ b/stdlib/time.kv @@ -1,6 +1,6 @@ -# 欢迎加入kvspace世界 -# lib time —— 时间标准库便利函数。native rwir: now/sub/add/before/after; -# since/equal/elapsed_ns 是 rwfunc 封装(kv 源码,可寻址/可自改)。 +// 欢迎加入kvspace世界 +// lib time —— 时间标准库便利函数。native rwir: now/sub/add/before/after; +// since/equal/elapsed_ns 是 rwfunc 封装(kv 源码,可寻址/可自改)。 lib time { rwfunc since(t:time) -> (dur:duration) { diff --git a/stdlib/time/duration.kv b/stdlib/time/duration.kv index ebdc68a7..a3c5772f 100644 --- a/stdlib/time/duration.kv +++ b/stdlib/time/duration.kv @@ -1,7 +1,7 @@ -# 欢迎加入kvspace世界 -# lib time/duration —— 时长标准库便利函数。native rwir: nanos/millis/seconds/minutes/hours/ -# as_nanos/as_millis/as_seconds/as_minutes/as_hours/add/sub/before/after; -# days/as_days/is_zero/equal/max/min 是 rwfunc 封装(kv 源码,可寻址/可自改)。 +// 欢迎加入kvspace世界 +// lib time/duration —— 时长标准库便利函数。native rwir: nanos/millis/seconds/minutes/hours/ +// as_nanos/as_millis/as_seconds/as_minutes/as_hours/add/sub/before/after; +// days/as_days/is_zero/equal/max/min 是 rwfunc 封装(kv 源码,可寻址/可自改)。 lib time/duration { rwfunc days(n:int64) -> (dur:duration) { diff --git a/stdlib/xv.kv b/stdlib/xv.kv index 278a9635..e5165924 100644 --- a/stdlib/xv.kv +++ b/stdlib/xv.kv @@ -1,7 +1,7 @@ -# 欢迎加入kvspace世界 -# lib xv —— 数组操作便利库。native rwir:xv·at/set/reshape/reinterpret; -# rwfunc 补充:swap(交换两下标元素,返回新数组)、first(取首元素)。 -# 当前仅支持 []int64;xv 无长度原语,通用遍历类组合受限。 +// 欢迎加入kvspace世界 +// lib xv —— 数组操作便利库。native rwir:xv·at/set/reshape/reinterpret; +// rwfunc 补充:swap(交换两下标元素,返回新数组)、first(取首元素)。 +// 当前仅支持 []int64;xv 无长度原语,通用遍历类组合受限。 lib xv { rwfunc swap(arr:[]int64, i:int64, j:int64) -> (result:[]int64) { diff --git a/tutorial/01-basics/arith.kv b/tutorial/01-basics/arith.kv index 82b1e9c4..448b070f 100644 --- a/tutorial/01-basics/arith.kv +++ b/tutorial/01-basics/arith.kv @@ -1,14 +1,14 @@ -# 期望输出: -# add: 13 -# sub: 7 -# mul: 30 -# mul(×): 30 -# div: 3 -# div(÷): 3 -# mod: 1 -# pow: 32.0 -# sqrt: 12.0 -# sqrt(√): 12.0 +// 期望输出: +// add: 13 +// sub: 7 +// mul: 30 +// mul(×): 30 +// div: 3 +// div(÷): 3 +// mod: 1 +// pow: 32.0 +// sqrt: 12.0 +// sqrt(√): 12.0 rwfunc test() -> () { t0 <- time·now() 10 + 3 -> add_r @@ -17,9 +17,9 @@ rwfunc test() -> () { 10 - 3 -> sub_r println("sub:", sub_r) - mul_r = 10 × 3 # = 等价于 <- + mul_r = 10 × 3 // = 等价于 <- println("mul:", mul_r) - mul_r2 = 10 × 3 # = 等价于 <- + mul_r2 = 10 × 3 // = 等价于 <- println("mul(×):", mul_r2) 10 ÷ 3 -> div_r @@ -33,9 +33,9 @@ rwfunc test() -> () { pow_r <- pow(2, 5) println("pow:", pow_r) - sqrt_r = sqrt(144) # = 等价于 <- + sqrt_r = sqrt(144) // = 等价于 <- println("sqrt:", sqrt_r) - sqrt_r2 = √(144) # = 等价于 <- + sqrt_r2 = √(144) // = 等价于 <- println("sqrt(√):", sqrt_r2) t1 <- time·now() diff --git a/tutorial/01-basics/cast.kv b/tutorial/01-basics/cast.kv index b55eaf5c..ff2627a0 100644 --- a/tutorial/01-basics/cast.kv +++ b/tutorial/01-basics/cast.kv @@ -1,56 +1,56 @@ -# cast: 全谱类型转换——12 种 cast 算子,float→int 截断向零,变量级 cast -# 期望输出: -# -128 -# 32767 -# 2147483647 -# 9223372036854775807 -# 255 -# 65535 -# 4294967295 -# 18446744073709551615 -# 3.14 -# 3.1415927 -# 3.141592653589793 -# 3 -# 3 -# -2 -# 0 -# 42 -# 42 -# 42 -# 42 -# 42 +// cast: 全谱类型转换——12 种 cast 算子,float→int 截断向零,变量级 cast +// 期望输出: +// -128 +// 32767 +// 2147483647 +// 9223372036854775807 +// 255 +// 65535 +// 4294967295 +// 18446744073709551615 +// 3.14 +// 3.1415927 +// 3.141592653589793 +// 3 +// 3 +// -2 +// 0 +// 42 +// 42 +// 42 +// 42 +// 42 rwfunc test() -> () { - # ── int8/16/32/64 ── - int8(127) + int8(1) -> i8 # = 等价于 <-(回绕到 -128) + // ── int8/16/32/64 ── + int8(127) + int8(1) -> i8 // = 等价于 <-(回绕到 -128) println(i8) println(int16(32767)) println(int32(2147483647)) println(int64(9223372036854775807)) - # ── uint8/16/32/64 ── + // ── uint8/16/32/64 ── println(uint8(255)) println(uint16(65535)) println(uint32(4294967295)) println(uint64(18446744073709551615)) - # ── float32 ──(精度域:~7 位有效数字) + // ── float32 ──(精度域:~7 位有效数字) a <- float32(3.14) println(a) println(float32(3.141592653589793)) - # ── float64 ── - b = float64(3.141592653589793) # = 等价于 <- + // ── float64 ── + b = float64(3.141592653589793) // = 等价于 <- println(b) - # ── float→int 截断向零 ── - b -> f64 # = 等价于 <- + // ── float→int 截断向零 ── + b -> f64 // = 等价于 <- println(int64(f64)) println(int32(3.9)) println(int32(-2.7)) println(int64(0.5)) - # ── 变量级 cast(非字面量)── + // ── 变量级 cast(非字面量)── 42.9 -> x println(int8(x)) println(int16(x)) diff --git a/tutorial/01-basics/float_literal.kv b/tutorial/01-basics/float_literal.kv index 4636e476..85905d84 100644 --- a/tutorial/01-basics/float_literal.kv +++ b/tutorial/01-basics/float_literal.kv @@ -1,5 +1,5 @@ -# 期望输出 -# 6.28 +// 期望输出 +// 6.28 rwfunc test() -> () { 3.14 -> pi pi + pi -> x diff --git a/tutorial/01-basics/hello.kv b/tutorial/01-basics/hello.kv index d13f4f6b..99aa4145 100644 --- a/tutorial/01-basics/hello.kv +++ b/tutorial/01-basics/hello.kv @@ -1,5 +1,5 @@ -# 期望输出: -# hello kvlang +// 期望输出: +// hello kvlang rwfunc test() -> () { t0 <- time·now() println("hello kvlang") diff --git a/tutorial/01-basics/kv_tree.kv b/tutorial/01-basics/kv_tree.kv index 8a39e399..b54f35af 100644 --- a/tutorial/01-basics/kv_tree.kv +++ b/tutorial/01-basics/kv_tree.kv @@ -1,10 +1,10 @@ -# 期望输出: -# v= 42 -# has_data= true -# x= 42 -# n= 2 -# numel= 3 dim= 1 -# shape0= 3 +// 期望输出: +// v= 42 +// has_data= true +// x= 42 +// n= 2 +// numel= 3 dim= 1 +// shape0= 3 rwfunc test() -> () { kv·set("/tmp/kvt·data", 42) kv·get("/tmp/kvt·data") -> v diff --git a/tutorial/01-basics/none.kv b/tutorial/01-basics/none.kv index bec45fe2..050bc945 100644 --- a/tutorial/01-basics/none.kv +++ b/tutorial/01-basics/none.kv @@ -1,14 +1,14 @@ -# 变量名即地址,未赋值即 None -# -# 期望输出 -# before -# after -# 42 +// 变量名即地址,未赋值即 None +// +// 期望输出 +// before +// after +// 42 rwfunc test() -> () { println("before") - x -> y # x 未赋值 → None,y ← None - println(y) # None → 输出空行 + x -> y // x 未赋值 → None,y ← None + println(y) // None → 输出空行 println("after") - 42 -> x # 显式赋值 + 42 -> x // 显式赋值 println(x) } diff --git a/tutorial/01-basics/numtypes.kv b/tutorial/01-basics/numtypes.kv index 36fc0db3..bfa36b05 100644 --- a/tutorial/01-basics/numtypes.kv +++ b/tutorial/01-basics/numtypes.kv @@ -1,22 +1,22 @@ -# numtypes: 全谱数字类型创建/转换算子(fix-021) -# 语义: int8/16/32/64、uint8/16/32/64、float32/float64 十个算子既创建也转换; -# int/float 是 int64/float64 别名。float→int 截断向零;窄化=补码回绕(同 Go/Rust as、C 转换); -# 窄类型进入算术后提升至 int64/float64 运算域(C 整型提升风格),TLV kind 保持声明精度落盘 -# 期望输出: -# 3.0 -# 0 -# 44 -# 255 -# 4464 -# -2147483648 -# 4294967295 -# 18446744073709551615 -# 0.1 -# 16777216.0 -# 45 -# -2 +// numtypes: 全谱数字类型创建/转换算子(fix-021) +// 语义: int8/16/32/64、uint8/16/32/64、float32/float64 十个算子既创建也转换; +// int/float 是 int64/float64 别名。float→int 截断向零;窄化=补码回绕(同 Go/Rust as、C 转换); +// 窄类型进入算术后提升至 int64/float64 运算域(C 整型提升风格),TLV kind 保持声明精度落盘 +// 期望输出: +// 3.0 +// 0 +// 44 +// 255 +// 4464 +// -2147483648 +// 4294967295 +// 18446744073709551615 +// 0.1 +// 16777216.0 +// 45 +// -2 rwfunc test() -> () { - f = float32(3) # = 等价于 <- + f = float32(3) // = 等价于 <- println(f) i <- int8(0.1) println(i) @@ -29,7 +29,7 @@ rwfunc test() -> () { println(uint32(-1)) println(uint64(18446744073709551615)) - p32 = float32(0.1) # = 等价于 <-(float32 精度域) + p32 = float32(0.1) // = 等价于 <-(float32 精度域) println(p32) println(float32(16777217)) diff --git a/tutorial/01-basics/precision.kv b/tutorial/01-basics/precision.kv index 9860f35d..477d8b9d 100644 --- a/tutorial/01-basics/precision.kv +++ b/tutorial/01-basics/precision.kv @@ -1,30 +1,30 @@ -# precision: 数字精度与类型提升 -# 语义: int64 与 float64 是数值运算域;int64 op int64 → 原生 int64 运算与比较,绝不经 float64 中转(fix-020,对齐 C/Go/Rust); -# 任一侧 float → float64 提升(混合比较为 C 式 double 提升) -# 期望输出: -# 5 -# 5.5 -# 3.0 -# 3.0 -# 3 -# 3 -# -4 -# -4 -# 3.5 -# 3.5 -# 1 -# 3 -# 7.0 -# 1000.0 -# 0.025 -# 0.30000000000000004 -# true -# 9223372036854775807 -# 9223372036854775806 -# 9007199254740993 -# false +// precision: 数字精度与类型提升 +// 语义: int64 与 float64 是数值运算域;int64 op int64 → 原生 int64 运算与比较,绝不经 float64 中转(fix-020,对齐 C/Go/Rust); +// 任一侧 float → float64 提升(混合比较为 C 式 double 提升) +// 期望输出: +// 5 +// 5.5 +// 3.0 +// 3.0 +// 3 +// 3 +// -4 +// -4 +// 3.5 +// 3.5 +// 1 +// 3 +// 7.0 +// 1000.0 +// 0.025 +// 0.30000000000000004 +// true +// 9223372036854775807 +// 9223372036854775806 +// 9007199254740993 +// false rwfunc test() -> () { - a = 2 + 3 # = 等价于 <- + a = 2 + 3 // = 等价于 <- println(a) b <- 2 + 3.5 println(b) @@ -33,8 +33,8 @@ rwfunc test() -> () { println(c_m) println(c) - q = 7 ÷ 2 # = 等价于 <-(整除:两侧均 int) - q_m = 7 ÷ 2 # = 等价于 <-(整除:两侧均 int) + q = 7 ÷ 2 // = 等价于 <-(整除:两侧均 int) + q_m = 7 ÷ 2 // = 等价于 <-(整除:两侧均 int) println(q_m) println(q) -9 ÷ 2 -> qz @@ -45,7 +45,7 @@ rwfunc test() -> () { fq_m <- 7.0 ÷ 2 println(fq_m) println(fq) - r = 7 % 3 # = 等价于 <- + r = 7 % 3 // = 等价于 <- println(r) ti <- int64(3.99) @@ -53,7 +53,7 @@ rwfunc test() -> () { float64(7) -> tf println(tf) - sci = 1e3 # = 等价于 <-(科学计数法字面量恒为 float) + sci = 1e3 // = 等价于 <-(科学计数法字面量恒为 float) println(sci) small <- 2.5e-2 println(small) @@ -61,7 +61,7 @@ rwfunc test() -> () { 0.1 + 0.2 -> sum println(sum) - eq = 3 == 3.0 # = 等价于 <-(跨类型数值比较:值提升后相等) + eq = 3 == 3.0 // = 等价于 <-(跨类型数值比较:值提升后相等) println(eq) big <- 9223372036854775807 @@ -69,7 +69,7 @@ rwfunc test() -> () { big - 1 -> bm println(bm) - precise = 9007199254740993 + 0 # = 等价于 <-(2^53+1:int 算术不经 float,精度保真) + precise = 9007199254740993 + 0 // = 等价于 <-(2^53+1:int 算术不经 float,精度保真) println(precise) same <- big == 9223372036854775806 println(same) diff --git a/tutorial/01-basics/random.kv b/tutorial/01-basics/random.kv index 07244ae9..aa8ae127 100644 --- a/tutorial/01-basics/random.kv +++ b/tutorial/01-basics/random.kv @@ -1,10 +1,10 @@ -# random: 随机数生成(crypto/rand 真随机,非伪随机) -# 语义: random·uint64() 返回随机 uint64;random·int63() 返回非负 int64(≤ 2^63-1); -# random·intn(n) 返回 [0, n) 的 uint64 -# 期望输出: -# int63 >= 0: true -# intn in [0,100): true -# two randoms differ: true +// random: 随机数生成(crypto/rand 真随机,非伪随机) +// 语义: random·uint64() 返回随机 uint64;random·int63() 返回非负 int64(≤ 2^63-1); +// random·intn(n) 返回 [0, n) 的 uint64 +// 期望输出: +// int63 >= 0: true +// intn in [0,100): true +// two randoms differ: true rwfunc test() -> () { n <- random·int63() println("int63 >= 0:", n >= 0) diff --git a/tutorial/01-basics/strict_types.kv b/tutorial/01-basics/strict_types.kv index ab03bcff..9d0ec2f6 100644 --- a/tutorial/01-basics/strict_types.kv +++ b/tutorial/01-basics/strict_types.kv @@ -1,34 +1,34 @@ -# strict_types: 严格类型检查——所有算子仅接受预期类型 -# 对应修复: todo-033(删除 asFloat/asInt 隐式转换、删除 int/float 别名、cmp 字符串回退) -# 语义: 算子入口严格 guards 类型,跨类型/非预期类型 → TypeError -# 期望输出: -# 8 -# 3 -# 2.5 -# 2.5 -# 1 -# 1 -# -2 -# 7 -# true -# false -# true -# 8.0 -# 8.0 -# 3 -# 8.0 -# 1.0 -# 3 -# abc -# -1 -# true +// strict_types: 严格类型检查——所有算子仅接受预期类型 +// 对应修复: todo-033(删除 asFloat/asInt 隐式转换、删除 int/float 别名、cmp 字符串回退) +// 语义: 算子入口严格 guards 类型,跨类型/非预期类型 → TypeError +// 期望输出: +// 8 +// 3 +// 2.5 +// 2.5 +// 1 +// 1 +// -2 +// 7 +// true +// false +// true +// 8.0 +// 8.0 +// 3 +// 8.0 +// 1.0 +// 3 +// abc +// -1 +// true rwfunc test() -> () { - # 算术 — 同类型 int64 - 5 + 3 -> a # = 等价于 <- + // 算术 — 同类型 int64 + 5 + 3 -> a // = 等价于 <- println(a) 7 - 2 - 2 -> b println(b) - # 算术 — 混合 int+float(float 提升) + // 算术 — 混合 int+float(float 提升) 7.5 ÷ 3 -> c 7.5 ÷ 3 -> c_m println(c_m) @@ -36,24 +36,24 @@ rwfunc test() -> () { 7 % 3 -> d println(d) - # 位运算 — 仅整数 - 5 & 3 -> e # = 等价于 <- + // 位运算 — 仅整数 + 5 & 3 -> e // = 等价于 <- println(e) neg(2) -> f println(f) 3 | 4 -> g println(g) - # 比较 — 同类型 - 5 > 3 -> h # = 等价于 <- + // 比较 — 同类型 + 5 > 3 -> h // = 等价于 <- println(h) 3 > 5 -> i println(i) - # 比较 — C 式 double 提升 + // 比较 — C 式 double 提升 3 == 3.0 -> j println(j) - # 数学函数 — 仅数字 + // 数学函数 — 仅数字 sqrt(64.0) -> k √(64.0) -> k_m println(k_m) @@ -65,19 +65,19 @@ rwfunc test() -> () { log(exp(1.0)) -> n println(n) - # min/max — 全数字(max 嵌套 fold) + // min/max — 全数字(max 嵌套 fold) max(max(1, 3), 2) -> o println(o) - # 字符串拼接 - "a" + "bc" -> p # = 等价于 <- + // 字符串拼接 + "a" + "bc" -> p // = 等价于 <- println(p) - # 字符串比较(C 语义) + // 字符串比较(C 语义) string·cmp("a", "b") -> q println(q) - # bool 显式比较 - true == true -> r # = 等价于 <- + // bool 显式比较 + true == true -> r // = 等价于 <- println(r) } diff --git a/tutorial/01-basics/strings.kv b/tutorial/01-basics/strings.kv index 08a4af5e..9d6c0bf3 100644 --- a/tutorial/01-basics/strings.kv +++ b/tutorial/01-basics/strings.kv @@ -1,23 +1,23 @@ -# string: 字符串索引读写、+ 拼接、C 风格 API(fix-025) -# 语义: s[i] 读返单字符字符串(动态阵营,可与 "a" 直接比较),越界返 ""; -# s[i] = "X" 单字符替换后整串回写(C 直觉 + 值语义);+ 拼接(4/5 阵营); -# strcmp 返 -1/0/1(C 语义),strstr 返首次下标、未找到 -1(C 名 + 索引语义) -# 期望输出: -# e -# Hello -# kvlang -# Hello kvlang -# 12 -# -1 -# 0 -# 6 -# -1 -# l -# 108 +// string: 字符串索引读写、+ 拼接、C 风格 API(fix-025) +// 语义: s[i] 读返单字符字符串(动态阵营,可与 "a" 直接比较),越界返 ""; +// s[i] = "X" 单字符替换后整串回写(C 直觉 + 值语义);+ 拼接(4/5 阵营); +// strcmp 返 -1/0/1(C 语义),strstr 返首次下标、未找到 -1(C 名 + 索引语义) +// 期望输出: +// e +// Hello +// kvlang +// Hello kvlang +// 12 +// -1 +// 0 +// 6 +// -1 +// l +// 108 rwfunc test() -> () { - s = "hello" # = 等价于 <- + s = "hello" // = 等价于 <- println(s[1]) - s[0] = "H" # = 等价于 <- + s[0] = "H" // = 等价于 <- println(s) t <- "kv" + "lang" diff --git a/tutorial/01-basics/strings_escape.kv b/tutorial/01-basics/strings_escape.kv index f74c8f5d..913ca132 100644 --- a/tutorial/01-basics/strings_escape.kv +++ b/tutorial/01-basics/strings_escape.kv @@ -1,5 +1,5 @@ -# 期望输出 -# hello "world" +// 期望输出 +// hello "world" rwfunc test() -> () { "hello \"world\"" -> s println(s) diff --git a/tutorial/01-basics/time.kv b/tutorial/01-basics/time.kv index 4a5ca460..fe41c814 100644 --- a/tutorial/01-basics/time.kv +++ b/tutorial/01-basics/time.kv @@ -1,15 +1,15 @@ -# time: 时间与 duration 类型 -# 期望输出: -# before -# after -# t0 < t1: true -# t0 > t1: false -# delta >= 0 ns: true -# delta ms = -# delta s = 0 -# t0 + delta == t1: true -# 1000 ms -# 1 s = 1000000000 ns +// time: 时间与 duration 类型 +// 期望输出: +// before +// after +// t0 < t1: true +// t0 > t1: false +// delta >= 0 ns: true +// delta ms = +// delta s = 0 +// t0 + delta == t1: true +// 1000 ms +// 1 s = 1000000000 ns rwfunc test() -> () { println("before") t0 <- time·now() @@ -26,7 +26,7 @@ rwfunc test() -> () { delta <- time·sub(t1, t0) print("delta >= 0 ns: ") - zero = time/duration·nanos(0) # = 等价于 <- + zero = time/duration·nanos(0) // = 等价于 <- println(time/duration·before(zero, delta)) ms <- time/duration·as_millis(delta) @@ -43,7 +43,7 @@ rwfunc test() -> () { b <- not(time·after(sum, t1)) println(and(a, b)) - 1000 -> n # = 等价于 <- + 1000 -> n // = 等价于 <- print(n) println(" ms") diff --git a/tutorial/01-basics/type_narrowing.kv b/tutorial/01-basics/type_narrowing.kv index 543fffd0..b6db8692 100644 --- a/tutorial/01-basics/type_narrowing.kv +++ b/tutorial/01-basics/type_narrowing.kv @@ -1,57 +1,57 @@ -# type_narrowing: 算术结果类型窄化——保留输入位宽,不复全消灭为 int64/float64 -# 修复: fix-034。旧实现 int8+int8→int64、float32+float32→float64、uint8+uint8→int64, -# 类型信息在第一次算术后即消灭。现在同类型→同类型、混合→向更宽提升。 -# 期望输出: -# -128 -# 0 -# 16777216.0 -# 200 -# 12 -# 12.0 -# 1 -# -9223372036854775807 -# 10000 -# 10000 +// type_narrowing: 算术结果类型窄化——保留输入位宽,不复全消灭为 int64/float64 +// 修复: fix-034。旧实现 int8+int8→int64、float32+float32→float64、uint8+uint8→int64, +// 类型信息在第一次算术后即消灭。现在同类型→同类型、混合→向更宽提升。 +// 期望输出: +// -128 +// 0 +// 16777216.0 +// 200 +// 12 +// 12.0 +// 1 +// -9223372036854775807 +// 10000 +// 10000 rwfunc test() -> () { - # int8(127) + int8(1) → -128(int8 回绕证明结果仍是 int8。若是 int64 则为 128) + // int8(127) + int8(1) → -128(int8 回绕证明结果仍是 int8。若是 int64 则为 128) int8(127) + int8(1) -> a println(a) - # uint8(255) + uint8(1) → 0(uint8 回绕证明 unsigned 语义保留) + // uint8(255) + uint8(1) → 0(uint8 回绕证明 unsigned 语义保留) uint8(255) + uint8(1) -> b println(b) - # float32(16777216) + float32(1) → 16777216(float32 精度不可表示 16777217,证明结果未升级 float64) + // float32(16777216) + float32(1) → 16777216(float32 精度不可表示 16777217,证明结果未升级 float64) float32(16777216) + float32(1) -> c println(c) - # int8(100) × int16(2) → 200(混合宽度向更宽提升→int16) + // int8(100) × int16(2) → 200(混合宽度向更宽提升→int16) int8(100) × int16(2) -> d int8(100) × int16(2) -> d_m println(d_m) println(d) - # int8(120) ÷ int8(10) → 12(整数整除 C/Go/Rust 阵营,结果窄化回 int8) + // int8(120) ÷ int8(10) → 12(整数整除 C/Go/Rust 阵营,结果窄化回 int8) int8(120) ÷ int8(10) -> e int8(120) ÷ int8(10) -> e_m println(e_m) println(e) - # int8(120) ÷ float32(10) → 12.0(含浮点→浮除,窄化回 float32) + // int8(120) ÷ float32(10) → 12.0(含浮点→浮除,窄化回 float32) int8(120) ÷ float32(10) -> f int8(120) ÷ float32(10) -> f_m println(f_m) println(f) - # int8(7) % int16(3) → 1(模运算窄化回更宽 int16) + // int8(7) % int16(3) → 1(模运算窄化回更宽 int16) int8(7) % int16(3) -> g println(g) - # neg(int64_max) − 纯整数路径,不经 float64(fix-020+fix-034) + // neg(int64_max) − 纯整数路径,不经 float64(fix-020+fix-034) neg(9223372036854775807) -> h println(h) - # int32(100) × int32(100) → 10000(同类型→同类型 int32) + // int32(100) × int32(100) → 10000(同类型→同类型 int32) int32(100) × int32(100) -> i int32(100) × int32(100) -> i_m println(i_m) diff --git a/tutorial/01-basics/unary_plus.kv b/tutorial/01-basics/unary_plus.kv index 4b40e351..31884421 100644 --- a/tutorial/01-basics/unary_plus.kv +++ b/tutorial/01-basics/unary_plus.kv @@ -1,5 +1,5 @@ -# 期望输出 -# 42 +// 期望输出 +// 42 rwfunc test() -> () { +42 -> x println(x) diff --git a/tutorial/01-basics/vars.kv b/tutorial/01-basics/vars.kv index 351073f5..6de65a07 100644 --- a/tutorial/01-basics/vars.kv +++ b/tutorial/01-basics/vars.kv @@ -1,9 +1,9 @@ -# 期望输出: -# x = 42 -# y = 50 +// 期望输出: +// x = 42 +// y = 50 rwfunc test() -> () { x <- 42 println("x =", x) - y = x + 8 # = 等价于 <- + y = x + 8 // = 等价于 <- println("y =", y) } diff --git a/tutorial/02-func/accumulator.kv b/tutorial/02-func/accumulator.kv index 47e9c960..b7f57559 100644 --- a/tutorial/02-func/accumulator.kv +++ b/tutorial/02-func/accumulator.kv @@ -1,14 +1,14 @@ -# accumulator: 累加器的角色归位(fix-027 推论) -# 语义: 累加器的最终值是调用方要的 → 它是输出 → 声明为写参。 -# 写参零值起步(显式初始化),体内可读可写,return 映射给调用方 -# ——等价于 Go 的命名返回值 func sum(arr []int) (acc int)。 -# 递归形态则相反:acc 是传给下一层的输入 → 读参,本层只读(算新值传下层)。 -# 期望输出: -# 10 -# 10 +// accumulator: 累加器的角色归位(fix-027 推论) +// 语义: 累加器的最终值是调用方要的 → 它是输出 → 声明为写参。 +// 写参零值起步(显式初始化),体内可读可写,return 映射给调用方 +// ——等价于 Go 的命名返回值 func sum(arr []int) (acc int)。 +// 递归形态则相反:acc 是传给下一层的输入 → 读参,本层只读(算新值传下层)。 +// 期望输出: +// 10 +// 10 rwfunc sum(arr:[]int64) -> (acc:int64) { - n = ndarray·numel(arr) # = 等价于 <- - 0 -> acc # 显式初始化累加器(strict null:write parm 首读为 null,拒绝 null 算术) + n = ndarray·numel(arr) // = 等价于 <- + 0 -> acc // 显式初始化累加器(strict null:write parm 首读为 null,拒绝 null 算术) 0 -> i while (i < n) { acc + arr[i] -> acc diff --git a/tutorial/02-func/scope_isolation.kv b/tutorial/02-func/scope_isolation.kv index fc665eb4..c707b761 100644 --- a/tutorial/02-func/scope_isolation.kv +++ b/tutorial/02-func/scope_isolation.kv @@ -1,17 +1,17 @@ -# scope_isolation: 帧隔离验证 SI-1~SI-3 -# 期望输出: -# PASS SI-1a: x=5 returns 5 -# PASS SI-1b: x=10 returns 10 -# PASS SI-2a: S= 8 D= 2 -# PASS SI-2b: S= 15 D= 5 -# PASS SI-3: chain = 10 +// scope_isolation: 帧隔离验证 SI-1~SI-3 +// 期望输出: +// PASS SI-1a: x=5 returns 5 +// PASS SI-1b: x=10 returns 10 +// PASS SI-2a: S= 8 D= 2 +// PASS SI-2b: S= 15 D= 5 +// PASS SI-3: chain = 10 rwfunc id_val(x:int64) -> (R:int64) { x + 0 -> R } rwfunc sum_diff(A:int64, B:int64) -> (S:int64, D:int64) { S <- A + B - D = A - B # = 等价于 <- + D = A - B // = 等价于 <- } rwfunc chain_call(a:int64, b:int64) -> (r:int64) { @@ -21,7 +21,7 @@ rwfunc chain_call(a:int64, b:int64) -> (r:int64) { rwfunc test() -> () { v1 <- id_val(5) println("PASS SI-1a: x=5 returns", v1) - v2 = id_val(10) # = 等价于 <- + v2 = id_val(10) // = 等价于 <- println("PASS SI-1b: x=10 returns", v2) sum_diff(5, 3) -> (s1, d1) println("PASS SI-2a: S=", s1, "D=", d1) diff --git a/tutorial/02-func/tco_depth.kv b/tutorial/02-func/tco_depth.kv index a7131dca..0df6c382 100644 --- a/tutorial/02-func/tco_depth.kv +++ b/tutorial/02-func/tco_depth.kv @@ -1,13 +1,13 @@ -# tco_depth: TCO 验证 TCO-1~TCO-2 -# 期望输出: -# sum = 5050 -# fact = 3628800 +// tco_depth: TCO 验证 TCO-1~TCO-2 +// 期望输出: +// sum = 5050 +// fact = 3628800 rwfunc sum_while(N:int64) -> (total:int64) { - total = 0 # = 等价于 <- + total = 0 // = 等价于 <- 1 -> i while (i <= N) { total <- total + i - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } } @@ -17,7 +17,7 @@ rwfunc tailrec_fact(N:int64, acc:int64) -> (r:int64) { } else { acc1 <- acc × N acc1_m <- acc × N - n1 = N - 1 # = 等价于 <- + n1 = N - 1 // = 等价于 <- tailrec_fact(n1, acc1) -> r } } @@ -25,7 +25,7 @@ rwfunc tailrec_fact(N:int64, acc:int64) -> (r:int64) { rwfunc test() -> () { s <- sum_while(100) println("sum =", s) - f = tailrec_fact(10, 1) # = 等价于 <- + f = tailrec_fact(10, 1) // = 等价于 <- println("fact =", f) s -> /last_tco_sum /last_tco_fact <- f diff --git a/tutorial/03-control/classify.kv b/tutorial/03-control/classify.kv index 1caf7342..d3ef9a57 100644 --- a/tutorial/03-control/classify.kv +++ b/tutorial/03-control/classify.kv @@ -1,10 +1,10 @@ -# classify: 成绩分档 -# 算法: 嵌套 if,score=85 → grade=B -# 期望输出: -# grade = B +// classify: 成绩分档 +// 算法: 嵌套 if,score=85 → grade=B +// 期望输出: +// grade = B rwfunc classify(score:int64) -> (grade:[]char/utf32) { if (score >= 90) { - grade = "A" # = 等价于 <- + grade = "A" // = 等价于 <- } else { if (score >= 80) { "B" -> grade @@ -13,7 +13,7 @@ rwfunc classify(score:int64) -> (grade:[]char/utf32) { grade <- "C" } else { if (score >= 60) { - grade = "D" # = 等价于 <- + grade = "D" // = 等价于 <- } else { "F" -> grade } @@ -26,5 +26,5 @@ rwfunc test() -> () { ans <- classify(85) println("grade =", ans) - /last_grade = ans # = 等价于 <- + /last_grade = ans // = 等价于 <- } diff --git a/tutorial/03-control/for.kv b/tutorial/03-control/for.kv index 35a12f24..e17fc30e 100644 --- a/tutorial/03-control/for.kv +++ b/tutorial/03-control/for.kv @@ -1,28 +1,28 @@ -# cels_to_fahr: 摄氏转华氏温度表(K&R C §1.2) -# 算法: for 遍历器 + 浮点运算 -# 来源: C 语言 K&R §1.2 "The For Statement" -# 期望输出: -# 0 F = -17.77777777777778 C -# 300 F = 148.88888888888889 C +// cels_to_fahr: 摄氏转华氏温度表(K&R C §1.2) +// 算法: for 遍历器 + 浮点运算 +// 来源: C 语言 K&R §1.2 "The For Statement" +// 期望输出: +// 0 F = -17.77777777777778 C +// 300 F = 148.88888888888889 C rwfunc test() -> () { data·0 <- 0 - data·1 = 20 # = 等价于 <- + data·1 = 20 // = 等价于 <- 40 -> data·2 data·3 <- 60 - data·4 = 80 # = 等价于 <- + data·4 = 80 // = 等价于 <- 100 -> data·5 data·6 <- 120 - data·7 = 140 # = 等价于 <- + data·7 = 140 // = 等价于 <- 160 -> data·8 data·9 <- 180 - data·10 = 200 # = 等价于 <- + data·10 = 200 // = 等价于 <- 220 -> data·11 data·12 <- 240 - data·13 = 260 # = 等价于 <- + data·13 = 260 // = 等价于 <- 280 -> data·14 data·15 <- 300 for (fahr in data) { - factor = 5.0 ÷ 9.0 # = 等价于 <- + factor = 5.0 ÷ 9.0 // = 等价于 <- fahr - 32 -> diff cels <- factor × diff println(fahr, "F =", cels, "C") diff --git a/tutorial/03-control/guess.kv b/tutorial/03-control/guess.kv index 7bde76f9..6f50db99 100644 --- a/tutorial/03-control/guess.kv +++ b/tutorial/03-control/guess.kv @@ -1,20 +1,20 @@ -# guess_number: 二分查找猜数字(Python Tutorial §4.4) -# 算法: while 循环 + 二分查找,在 [1,100] 中找 target=73 -# 来源: Python Tutorial §4.4 -# 期望输出: -# found 73 in 6 guesses +// guess_number: 二分查找猜数字(Python Tutorial §4.4) +// 算法: while 循环 + 二分查找,在 [1,100] 中找 target=73 +// 来源: Python Tutorial §4.4 +// 期望输出: +// found 73 in 6 guesses rwfunc guess_number() -> () { 73 -> target lo <- 1 - hi = 100 # = 等价于 <- + hi = 100 // = 等价于 <- 0 -> tries found <- 0 while (found == 0) { - s = lo + hi # = 等价于 <- + s = lo + hi // = 等价于 <- s ÷ 2 -> mid_float s ÷ 2 -> mid_float_m mid <- int64(mid_float) - tries = tries + 1 # = 等价于 <- + tries = tries + 1 // = 等价于 <- println("guess #", tries, ":", mid) mid == target -> hit @@ -22,7 +22,7 @@ rwfunc guess_number() -> () { found <- 1 println(" correct!") } else { - too_low = mid < target # = 等价于 <- + too_low = mid < target // = 等价于 <- if (too_low) { mid + 1 -> lo @@ -34,7 +34,7 @@ rwfunc guess_number() -> () { } } println("found", target, "in", tries, "guesses") - /last_guesses = tries # = 等价于 <- + /last_guesses = tries // = 等价于 <- } rwfunc test() -> () { diff --git a/tutorial/03-control/if.kv b/tutorial/03-control/if.kv index 516f9a4e..136d6030 100644 --- a/tutorial/03-control/if.kv +++ b/tutorial/03-control/if.kv @@ -1,6 +1,6 @@ -# 期望输出: -# abs(-5) = 5 -# false +// 期望输出: +// abs(-5) = 5 +// false lib my { rwfunc abs(x:int64) -> (r:int64) { if (x < 0) { @@ -13,14 +13,14 @@ lib my { rwfunc test() -> () { - a = my·abs(-5) # = 等价于 <- + a = my·abs(-5) // = 等价于 <- println("abs(-5) =", a) my·abs(3) -> b println("abs(3) =", b) c <- my·abs(-10) println("abs(-10) =", c) - d = b >= 90 # = 等价于 <- - d_m = b ≥ 90 # = 等价于 <- + d = b >= 90 // = 等价于 <- + d_m = b ≥ 90 // = 等价于 <- println(d_m) println(d) a -> /last_abs diff --git a/tutorial/03-control/while.kv b/tutorial/03-control/while.kv index 3808ddb9..072efa76 100644 --- a/tutorial/03-control/while.kv +++ b/tutorial/03-control/while.kv @@ -1,10 +1,10 @@ -# 期望输出: -# sum(1..10) = 55 -# first div7 in [1,20] = 7 -# sum odds(1..10) = 25 +// 期望输出: +// sum(1..10) = 55 +// first div7 in [1,20] = 7 +// sum odds(1..10) = 25 rwfunc sum_to(n:int64) -> (total:int64) { total <- 0 - i = 1 # = 等价于 <- + i = 1 // = 等价于 <- while (i <= n) { total + i -> total i <- i + 1 @@ -12,17 +12,17 @@ rwfunc sum_to(n:int64) -> (total:int64) { } rwfunc first_div7(n:int64) -> (result:int64) { - result = 0 # = 等价于 <- + result = 0 // = 等价于 <- 1 -> i while (i <= n) { rem <- i % 7 - hit = rem == 0 # = 等价于 <- + hit = rem == 0 // = 等价于 <- if (hit) { i -> result i <- n + 1 } else { - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } } } @@ -31,14 +31,14 @@ rwfunc sum_odds(n:int64) -> (total:int64) { 0 -> total i <- 1 while (i <= n) { - rem = i % 2 # = 等价于 <- + rem = i % 2 // = 等价于 <- rem == 1 -> is_odd if (is_odd) { total <- total + i } - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } } @@ -48,7 +48,7 @@ rwfunc test() -> () { println("sum(1..10) =", a) b <- first_div7(20) println("first div7 in [1,20] =", b) - c = sum_odds(10) # = 等价于 <- + c = sum_odds(10) // = 等价于 <- println("sum odds(1..10) =", c) a + b -> ab /last_sum <- ab + c diff --git a/tutorial/04-ndarray/continuous.kv b/tutorial/04-ndarray/continuous.kv index c40f9634..ff086274 100644 --- a/tutorial/04-ndarray/continuous.kv +++ b/tutorial/04-ndarray/continuous.kv @@ -1,10 +1,10 @@ -# continuous: 连续数组 []int64(一个 XValue,元素连续打包) -# 语义: [] = 同构定长连续数组;at/set/len 整存整取,元素在内存内下标访问 -# 期望输出: -# len = 4 -# [0] = 10 -# after set: 10 99 30 -# sum = 179 +// continuous: 连续数组 []int64(一个 XValue,元素连续打包) +// 语义: [] = 同构定长连续数组;at/set/len 整存整取,元素在内存内下标访问 +// 期望输出: +// len = 4 +// [0] = 10 +// after set: 10 99 30 +// sum = 179 rwfunc test() -> () { a:[]int64 = [10, 20, 30, 40] ndarray·numel(a) -> n diff --git a/tutorial/04-ndarray/for_compact.kv b/tutorial/04-ndarray/for_compact.kv index e9178df2..b81b5684 100644 --- a/tutorial/04-ndarray/for_compact.kv +++ b/tutorial/04-ndarray/for_compact.kv @@ -1,10 +1,10 @@ -# for_compact: for 遍历器直接迭代连续数组 []int64(单 XValue 打包) -# 语义: for (x in arr) 对 compact 数组按元素下标迭代,无需散 key -# 期望输出: -# 10 -# 20 -# 30 -# sum = 60 +// for_compact: for 遍历器直接迭代连续数组 []int64(单 XValue 打包) +// 语义: for (x in arr) 对 compact 数组按元素下标迭代,无需散 key +// 期望输出: +// 10 +// 20 +// 30 +// sum = 60 rwfunc test() -> () { a:[]int64 = [10, 20, 30] total = 0 diff --git a/tutorial/04-ndarray/geo_coord.kv b/tutorial/04-ndarray/geo_coord.kv index 5b6ae906..4489d072 100644 --- a/tutorial/04-ndarray/geo_coord.kv +++ b/tutorial/04-ndarray/geo_coord.kv @@ -1,8 +1,8 @@ -# 经纬度坐标:二维散 key 数组,坐标段 [lat,lng] 带小数点 -# 语义: 成员分隔符是 ·(middot),小数点仍是 .(dot);geo·[39.9,116.4] 是带小数的数组 key -# 期望输出: -# [39.9,116.4] -> Beijing -# [31.23,121.47] -> Shanghai +// 经纬度坐标:二维散 key 数组,坐标段 [lat,lng] 带小数点 +// 语义: 成员分隔符是 ·(middot),小数点仍是 .(dot);geo·[39.9,116.4] 是带小数的数组 key +// 期望输出: +// [39.9,116.4] -> Beijing +// [31.23,121.47] -> Shanghai rwfunc test() -> () { geo·[39.9,116.4] <- "Beijing" geo·[31.23,121.47] <- "Shanghai" diff --git a/tutorial/04-ndarray/map_coord.kv b/tutorial/04-ndarray/map_coord.kv index 2dde4718..aad66e46 100644 --- a/tutorial/04-ndarray/map_coord.kv +++ b/tutorial/04-ndarray/map_coord.kv @@ -1,8 +1,8 @@ -# strkeymap_coord: stringkeymap 坐标段访问 a·[i] -# 语义: {..} 创建 1 维散 key map,成员名是坐标段 "[i]",a·[i] 走 kv·get -# 期望输出: -# a[0] = 10 -# a[2] = 30 +// strkeymap_coord: stringkeymap 坐标段访问 a·[i] +// 语义: {..} 创建 1 维散 key map,成员名是坐标段 "[i]",a·[i] 走 kv·get +// 期望输出: +// a[0] = 10 +// a[2] = 30 rwfunc test() -> () { a = {10, 20, 30} a·[0] -> v0 diff --git a/tutorial/04-ndarray/separated.kv b/tutorial/04-ndarray/separated.kv index 690c9fb5..d24c66fa 100644 --- a/tutorial/04-ndarray/separated.kv +++ b/tutorial/04-ndarray/separated.kv @@ -1,21 +1,21 @@ -# separated: 散 key 数组(元素分散在 b·[0]..b·[N-1] 各自 key,按坐标段寻址) -# 语义: 字面量初始化默认 compact;array·scatter 把 compact 转散 key,array·compact 反向 -# 散 key 元素访问用 b·[i](走 kv·get),compact 用 b[i](走 xv·at) -# 期望输出: -# ndarray·numel(b) = 3 -# b[0] = 10 -# b[2] = 30 -# ndarray·numel(c) = 3 -# c[0] = 10 +// separated: 散 key 数组(元素分散在 b·[0]..b·[N-1] 各自 key,按坐标段寻址) +// 语义: 字面量初始化默认 compact;array·scatter 把 compact 转散 key,array·compact 反向 +// 散 key 元素访问用 b·[i](走 kv·get),compact 用 b[i](走 xv·at) +// 期望输出: +// ndarray·numel(b) = 3 +// b[0] = 10 +// b[2] = 30 +// ndarray·numel(c) = 3 +// c[0] = 10 rwfunc test() -> () { - a:[]int64 = [10, 20, 30] # 字面量初始化 → compact - b <- array·scatter(a) # 显式 scatter:compact a → 散 key b(b·[0]..b·[2]) + a:[]int64 = [10, 20, 30] // 字面量初始化 → compact + b <- array·scatter(a) // 显式 scatter:compact a → 散 key b(b·[0]..b·[2]) ndarray·numel(b) -> n1 println("ndarray·numel(b) =", n1) - println("b[0] =", b·[0]) # 散 key 元素访问 ·[i] + println("b[0] =", b·[0]) // 散 key 元素访问 ·[i] println("b[2] =", b·[2]) - c <- array·compact(b) # 显式 compact:散 key b → compact c + c <- array·compact(b) // 显式 compact:散 key b → compact c ndarray·numel(c) -> n2 println("ndarray·numel(c) =", n2) - println("c[0] =", c[0]) # compact 元素访问 [i] + println("c[0] =", c[0]) // compact 元素访问 [i] } diff --git a/tutorial/04-ndarray/sparse_literal.kv b/tutorial/04-ndarray/sparse_literal.kv index 659071ea..b5dbfdc7 100644 --- a/tutorial/04-ndarray/sparse_literal.kv +++ b/tutorial/04-ndarray/sparse_literal.kv @@ -1,12 +1,12 @@ -# sparse_literal: 花括号 {..} 字面量 = 散 key 数组(每元素落 base·i 独立 key) -# 括号规约: [1,2,3] = compact 定长打包进单 XValue;{1,2,3} = 散 key,变长/可增长 -# 语义: {..} 只作赋值右值或 for-in 源;for (x in nums) 遍历散 key 元素 -# 期望输出: -# 10 -# 20 -# 30 -# 40 -# sum = 100 +// sparse_literal: 花括号 {..} 字面量 = 散 key 数组(每元素落 base·i 独立 key) +// 括号规约: [1,2,3] = compact 定长打包进单 XValue;{1,2,3} = 散 key,变长/可增长 +// 语义: {..} 只作赋值右值或 for-in 源;for (x in nums) 遍历散 key 元素 +// 期望输出: +// 10 +// 20 +// 30 +// 40 +// sum = 100 rwfunc test() -> () { nums = {10, 20, 30, 40} total = 0 diff --git a/tutorial/04-ndarray/string_array.kv b/tutorial/04-ndarray/string_array.kv index 6bdc62db..a2fbeb94 100644 --- a/tutorial/04-ndarray/string_array.kv +++ b/tutorial/04-ndarray/string_array.kv @@ -1,13 +1,13 @@ -# string_array: 字符串数组必须用花括号 {..} 散 key(compact [..] 只容定长元素) -# 规约: 变长字符串成员不能进 compact [..](layout 阶段报错),必须走散 key {..} -# 语义: for (s in names) 遍历散 key 字符串,逐个 println -# 期望输出: -# apple -# banana -# cherry -# -- inline -- -# x -# y +// string_array: 字符串数组必须用花括号 {..} 散 key(compact [..] 只容定长元素) +// 规约: 变长字符串成员不能进 compact [..](layout 阶段报错),必须走散 key {..} +// 语义: for (s in names) 遍历散 key 字符串,逐个 println +// 期望输出: +// apple +// banana +// cherry +// -- inline -- +// x +// y rwfunc test() -> () { names = {"apple", "banana", "cherry"} for (s in names) { diff --git a/tutorial/04-ndarray/subscript_write.kv b/tutorial/04-ndarray/subscript_write.kv index 85e21cf1..29a72887 100644 --- a/tutorial/04-ndarray/subscript_write.kv +++ b/tutorial/04-ndarray/subscript_write.kv @@ -1,9 +1,9 @@ -# subscript_write: 右箭头下标写 value -> a[i] / a[i,j](读侧 a[i]→xv·at 的对称,#63) -# 语义: value -> a[idx...] 脱糖为 xv·set(a, idx..., value) -> a;layout 不判维数,交给 runtime -# 期望输出: -# a = 99 20 77 -# m[1,0] = 7 -# m[0,1] = 2 +// subscript_write: 右箭头下标写 value -> a[i] / a[i,j](读侧 a[i]→xv·at 的对称,#63) +// 语义: value -> a[idx...] 脱糖为 xv·set(a, idx..., value) -> a;layout 不判维数,交给 runtime +// 期望输出: +// a = 99 20 77 +// m[1,0] = 7 +// m[0,1] = 2 rwfunc test() -> () { a:[]int64 = [10, 20, 30] 99 -> a[0] diff --git a/tutorial/04-ndarray/xv_meta.kv b/tutorial/04-ndarray/xv_meta.kv index 12568981..8dbdeb2b 100644 --- a/tutorial/04-ndarray/xv_meta.kv +++ b/tutorial/04-ndarray/xv_meta.kv @@ -1,7 +1,7 @@ -# 期望输出: -# array kindexpr= [4]int64 bodylen= 32 -# scalar kindexpr= int64 bodylen= 8 -# string kindexpr= [2]char/utf8 bodylen= 2 +// 期望输出: +// array kindexpr= [4]int64 bodylen= 32 +// scalar kindexpr= int64 bodylen= 8 +// string kindexpr= [2]char/utf8 bodylen= 2 rwfunc test() -> () { a:[]int64 = [10, 20, 30, 40] xv·kindexpr(a) -> ka diff --git a/tutorial/04-ndarray/xv_reinterpret.kv b/tutorial/04-ndarray/xv_reinterpret.kv index 180c8dd0..7392018a 100644 --- a/tutorial/04-ndarray/xv_reinterpret.kv +++ b/tutorial/04-ndarray/xv_reinterpret.kv @@ -1,8 +1,8 @@ -# 期望输出: -# before: [3]int64 24 -# as-bytes: [24]uint8 24 -# xv·reinterpret 原样保留 body 字节(bodylen 不变),只替换 kindexpr; -# 3 个 int64(24 字节)重解释为 24 个 uint8。 +// 期望输出: +// before: [3]int64 24 +// as-bytes: [24]uint8 24 +// xv·reinterpret 原样保留 body 字节(bodylen 不变),只替换 kindexpr; +// 3 个 int64(24 字节)重解释为 24 个 uint8。 rwfunc test() -> () { a:[]int64 = [1, 2, 3] xv·kindexpr(a) -> k0 diff --git a/tutorial/04-ndarray/xv_shape.kv b/tutorial/04-ndarray/xv_shape.kv index 62d0533b..10f57be2 100644 --- a/tutorial/04-ndarray/xv_shape.kv +++ b/tutorial/04-ndarray/xv_shape.kv @@ -1,8 +1,8 @@ -# 期望输出: -# numel= 4 dim= 1 -# shape0= 4 -# at1= 20 -# set1= 99 +// 期望输出: +// numel= 4 dim= 1 +// shape0= 4 +// at1= 20 +// set1= 99 rwfunc test() -> () { a:[]int64 = [10, 20, 30, 40] ndarray·numel(a) -> n diff --git a/tutorial/05-dict/kv_has_string_key.kv b/tutorial/05-dict/kv_has_string_key.kv index c96b6524..0db0e6f9 100644 --- a/tutorial/05-dict/kv_has_string_key.kv +++ b/tutorial/05-dict/kv_has_string_key.kv @@ -1,5 +1,5 @@ -# 期望输出 -# true +// 期望输出 +// true rwfunc test() -> () { /tmp/kvhas_test·data = 42 kv·get(/tmp/kvhas_test, "data") != None -> ok diff --git a/tutorial/05-dict/literal.kv b/tutorial/05-dict/literal.kv index 8895abd1..3d1f2116 100644 --- a/tutorial/05-dict/literal.kv +++ b/tutorial/05-dict/literal.kv @@ -1,9 +1,9 @@ -# literal: 字典字面量与成员访问 -# 语义: { k=v; ... } 创建 dict 目录;base·key 成员访问;has 检查存在性 -# 期望输出: -# h·x = 1 -# h·z = 42 -# has x: true +// literal: 字典字面量与成员访问 +// 语义: { k=v; ... } 创建 dict 目录;base·key 成员访问;has 检查存在性 +// 期望输出: +// h·x = 1 +// h·z = 42 +// has x: true rwfunc test() -> () { h = {x=1; y=2} h·x -> v diff --git a/tutorial/06-algo/collatz.kv b/tutorial/06-algo/collatz.kv index 4bfaa7ab..4a45f851 100644 --- a/tutorial/06-algo/collatz.kv +++ b/tutorial/06-algo/collatz.kv @@ -1,13 +1,13 @@ -# collatz: Collatz 猜想步数 -# 算法: while + 条件分支,start=27 -# 期望输出: -# steps = 111 +// collatz: Collatz 猜想步数 +// 算法: while + 条件分支,start=27 +// 期望输出: +// steps = 111 rwfunc collatz(n:int64) -> (steps:int64) { n -> nv 0 -> steps while (nv > 1) { mod <- nv % 2 - even = mod == 0 # = 等价于 <- + even = mod == 0 // = 等价于 <- if (even) { nv ÷ 2 -> nv @@ -15,7 +15,7 @@ rwfunc collatz(n:int64) -> (steps:int64) { } else { t <- nv × 3 t_m <- nv × 3 - nv = t + 1 # = 等价于 <- + nv = t + 1 // = 等价于 <- } steps + 1 -> steps @@ -26,5 +26,5 @@ rwfunc test() -> () { ans <- collatz(27) println("steps =", ans) - /last_steps = ans # = 等价于 <- + /last_steps = ans // = 等价于 <- } diff --git a/tutorial/06-algo/factorial.kv b/tutorial/06-algo/factorial.kv index 533fc571..fb40b3cb 100644 --- a/tutorial/06-algo/factorial.kv +++ b/tutorial/06-algo/factorial.kv @@ -1,12 +1,12 @@ -# factorial: 迭代阶乘 -# 算法: while 循环累乘,计算 10! = 3628800 -# 期望输出: -# fact = 3628800 +// factorial: 迭代阶乘 +// 算法: while 循环累乘,计算 10! = 3628800 +// 期望输出: +// fact = 3628800 rwfunc factorial(n:int64) -> (result:int64) { 1 -> result i <- 1 while (i <= n) { - result = result × i # = 等价于 <- + result = result × i // = 等价于 <- i + 1 -> i } } diff --git a/tutorial/06-algo/fibonacci.kv b/tutorial/06-algo/fibonacci.kv index 768fe7db..97e72914 100644 --- a/tutorial/06-algo/fibonacci.kv +++ b/tutorial/06-algo/fibonacci.kv @@ -1,21 +1,21 @@ -# fibonacci: 迭代斐波那契数列 -# 算法: while 循环 + 临时交换,计算 fib(10) = 55 -# 期望输出: -# fib = 55 +// fibonacci: 迭代斐波那契数列 +// 算法: while 循环 + 临时交换,计算 fib(10) = 55 +// 期望输出: +// fib = 55 rwfunc fibonacci(n:int64) -> (result:int64) { if (n <= 1) { n -> result } else { a <- 0 - b = 1 # = 等价于 <- + b = 1 // = 等价于 <- 2 -> i while (i <= n) { c <- a + b - a = b # = 等价于 <- + a = b // = 等价于 <- c -> b i <- i + 1 } - result = b # = 等价于 <- + result = b // = 等价于 <- } } diff --git a/tutorial/06-algo/fizzbuzz.kv b/tutorial/06-algo/fizzbuzz.kv index 1e814760..ea4ec409 100644 --- a/tutorial/06-algo/fizzbuzz.kv +++ b/tutorial/06-algo/fizzbuzz.kv @@ -1,15 +1,15 @@ -# fizzbuzz: FizzBuzz 1-15(else if 多路分支) -# 期望输出: -# 1 -# Fizz -# Buzz -# FizzBuzz +// fizzbuzz: FizzBuzz 1-15(else if 多路分支) +// 期望输出: +// 1 +// Fizz +// Buzz +// FizzBuzz rwfunc fizzbuzz(N:int64) -> () { - i = 1 # = 等价于 <- + i = 1 // = 等价于 <- while (i <= N) { i % 3 -> m3 m5 <- i % 5 - d3 = m3 == 0 # = 等价于 <- + d3 = m3 == 0 // = 等价于 <- m5 == 0 -> d5 fb <- d3 && d5 @@ -27,7 +27,7 @@ rwfunc fizzbuzz(N:int64) -> () { } } - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } } diff --git a/tutorial/06-algo/gcd.kv b/tutorial/06-algo/gcd.kv index 57798d86..a61ba149 100644 --- a/tutorial/06-algo/gcd.kv +++ b/tutorial/06-algo/gcd.kv @@ -1,13 +1,13 @@ -# gcd: 欧几里得最大公约数(尾递归) -# 算法: gcd(48, 18) = 6 -# 期望输出: -# gcd = 6 +// gcd: 欧几里得最大公约数(尾递归) +// 算法: gcd(48, 18) = 6 +// 期望输出: +// gcd = 6 rwfunc gcd(A:int64, B:int64) -> (R:int64) { if (B == 0) { A -> R } else { rem <- A % B - R = gcd(B, rem) # = 等价于 <- + R = gcd(B, rem) // = 等价于 <- } } diff --git a/tutorial/06-algo/map_reduce.kv b/tutorial/06-algo/map_reduce.kv index 0b1919b8..f5a75562 100644 --- a/tutorial/06-algo/map_reduce.kv +++ b/tutorial/06-algo/map_reduce.kv @@ -1,30 +1,30 @@ -# map_reduce: filter + map + reduce(MDN JS Array) -# 算法: for 遍历器筛选奇数 + 累加平方 -# 期望输出: -# odd squares count: 5 -# sum of squares: 165 +// map_reduce: filter + map + reduce(MDN JS Array) +// 算法: for 遍历器筛选奇数 + 累加平方 +// 期望输出: +// odd squares count: 5 +// sum of squares: 165 rwfunc test() -> () { - nums·0 = 1 # = 等价于 <- + nums·0 = 1 // = 等价于 <- 3 -> nums·1 nums·2 <- 5 - nums·3 = 7 # = 等价于 <- + nums·3 = 7 // = 等价于 <- 9 -> nums·4 nums·5 <- 2 - nums·6 = 4 # = 等价于 <- + nums·6 = 4 // = 等价于 <- 6 -> nums·7 nums·8 <- 8 - nums·9 = 10 # = 等价于 <- + nums·9 = 10 // = 等价于 <- 0 -> count total <- 0 for (n in nums) { - rem = n % 2 # = 等价于 <- + rem = n % 2 // = 等价于 <- rem == 1 -> is_odd if (is_odd) { println(" keep:", n) sq <- n × n sq_m <- n × n - total = total + sq # = 等价于 <- + total = total + sq // = 等价于 <- count + 1 -> count } else { println(" skip:", n) diff --git a/tutorial/06-algo/power.kv b/tutorial/06-algo/power.kv index 9d3bfb1d..7f28f529 100644 --- a/tutorial/06-algo/power.kv +++ b/tutorial/06-algo/power.kv @@ -1,14 +1,14 @@ -# power: 快速幂(循环实现) -# 算法: 循环 while + 条件更新,计算 2^10 = 1024 -# 期望输出: -# result = 1024 +// power: 快速幂(循环实现) +// 算法: 循环 while + 条件更新,计算 2^10 = 1024 +// 期望输出: +// result = 1024 rwfunc power(base:int64, exp:int64) -> (result:int64) { - result = 1 # = 等价于 <- + result = 1 // = 等价于 <- 0 -> e while (e < exp) { result <- result × base result_m <- result × base - e = e + 1 # = 等价于 <- + e = e + 1 // = 等价于 <- } } diff --git a/tutorial/06-algo/prime_sieve.kv b/tutorial/06-algo/prime_sieve.kv index b8ab0693..84ee1e2c 100644 --- a/tutorial/06-algo/prime_sieve.kv +++ b/tutorial/06-algo/prime_sieve.kv @@ -1,22 +1,22 @@ -# prime_sieve: 试除法求质数(Rust The Book §3.5) -# 算法: 嵌套 while,找出 <=200 的质数 -# 期望输出: -# prime: 2 -# prime: 199 -# total primes up to 200 = 46 +// prime_sieve: 试除法求质数(Rust The Book §3.5) +// 算法: 嵌套 while,找出 <=200 的质数 +// 期望输出: +// prime: 2 +// prime: 199 +// total primes up to 200 = 46 rwfunc prime_sieve(limit:int64) -> () { println("primes up to", limit) - count = 0 # = 等价于 <- + count = 0 // = 等价于 <- 2 -> n while (n <= limit) { is_prime <- true - d = 2 # = 等价于 <- + d = 2 // = 等价于 <- while (d < n) { n % d -> rem divisible <- rem == 0 if (divisible) { - is_prime = false # = 等价于 <- + is_prime = false // = 等价于 <- break } else { d <- d + 1 @@ -25,7 +25,7 @@ rwfunc prime_sieve(limit:int64) -> () { if (is_prime) { println(" prime:", n) - count = count + 1 # = 等价于 <- + count = count + 1 // = 等价于 <- } n + 1 -> n diff --git a/tutorial/06-algo/recursion.kv b/tutorial/06-algo/recursion.kv index d14b8e94..879afa44 100644 --- a/tutorial/06-algo/recursion.kv +++ b/tutorial/06-algo/recursion.kv @@ -1,26 +1,26 @@ -# 期望输出: -# fib(10) = 34 -# fact(10) = 3628800 +// 期望输出: +// fib(10) = 34 +// fact(10) = 3628800 rwfunc fib(n:int64) -> (a:int64, b:int64) { if (n <= 1) { - a = 0 # = 等价于 <- + a = 0 // = 等价于 <- 1 -> b } else { n1 <- n - 1 fib(n1) -> (a, b) - x = a + b # = 等价于 <- + x = a + b // = 等价于 <- b -> a b <- x } } rwfunc factorial(n:int64) -> (r:int64) { - r = 1 # = 等价于 <- + r = 1 // = 等价于 <- 1 -> i while (i <= n) { r <- r × i r_m <- r × i - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } } @@ -30,5 +30,5 @@ rwfunc test() -> () { factorial(10) -> ans println("fact(10) =", ans) /last_fib <- f - /last_fact = ans # = 等价于 <- + /last_fact = ans // = 等价于 <- } diff --git a/tutorial/06-algo/word_count.kv b/tutorial/06-algo/word_count.kv index 2df205e8..1a57a25e 100644 --- a/tutorial/06-algo/word_count.kv +++ b/tutorial/06-algo/word_count.kv @@ -1,39 +1,39 @@ -# word_count: 单词计数状态机(K&R C §1.5.4) -# 算法: for 遍历 + IN/OUT 状态机 -# 期望输出: -# word count = 3 +// word_count: 单词计数状态机(K&R C §1.5.4) +// 算法: for 遍历 + IN/OUT 状态机 +// 期望输出: +// word count = 3 rwfunc test() -> () { - chars·0 = "h" # = 等价于 <- + chars·0 = "h" // = 等价于 <- "e" -> chars·1 chars·2 <- "l" - chars·3 = "l" # = 等价于 <- + chars·3 = "l" // = 等价于 <- "o" -> chars·4 chars·5 <- " " - chars·6 = "w" # = 等价于 <- + chars·6 = "w" // = 等价于 <- "o" -> chars·7 chars·8 <- "r" - chars·9 = "l" # = 等价于 <- + chars·9 = "l" // = 等价于 <- "d" -> chars·10 chars·11 <- " " - chars·12 = "k" # = 等价于 <- + chars·12 = "k" // = 等价于 <- "v" -> chars·13 chars·14 <- "l" - chars·15 = "a" # = 等价于 <- + chars·15 = "a" // = 等价于 <- "n" -> chars·16 chars·17 <- "g" - nw = 0 # = 等价于 <- + nw = 0 // = 等价于 <- 0 -> state for (c in chars) { blank <- c == " " if (blank) { - state = 0 # = 等价于 <- + state = 0 // = 等价于 <- } else { state == 0 -> was_out if (was_out) { state <- 1 - nw = nw + 1 # = 等价于 <- + nw = nw + 1 // = 等价于 <- } } } diff --git a/tutorial/07-lib/anon/no_lib.kv b/tutorial/07-lib/anon/no_lib.kv index 30724ab3..ec0c9f17 100644 --- a/tutorial/07-lib/anon/no_lib.kv +++ b/tutorial/07-lib/anon/no_lib.kv @@ -1,6 +1,6 @@ -# 裸 def,匿名 lib -# 期望输出: -# 42 +// 裸 def,匿名 lib +// 期望输出: +// 42 rwfunc answer() -> () { println(42) } rwfunc test() -> () { diff --git a/tutorial/07-lib/anon/root.kv b/tutorial/07-lib/anon/root.kv index 7a27ec82..715b9c97 100644 --- a/tutorial/07-lib/anon/root.kv +++ b/tutorial/07-lib/anon/root.kv @@ -1,6 +1,6 @@ -# /lib 根函数调用 -# 期望输出: -# 42 +// /lib 根函数调用 +// 期望输出: +// 42 rwfunc answer() -> () { println(42) } rwfunc test() -> () { diff --git a/tutorial/07-lib/cross/inline.kv b/tutorial/07-lib/cross/inline.kv index 2a9dbc8f..070ca570 100644 --- a/tutorial/07-lib/cross/inline.kv +++ b/tutorial/07-lib/cross/inline.kv @@ -1,6 +1,6 @@ -# 单文件内跨 lib 全路径调用 -# 期望输出: -# 7 +// 单文件内跨 lib 全路径调用 +// 期望输出: +// 7 lib math { rwfunc sum(A:int64, B:int64) -> (C:int64) { A + B -> C } } diff --git a/tutorial/07-lib/cross/lib_b.kv b/tutorial/07-lib/cross/lib_b.kv index ca097ea4..262e62c3 100644 --- a/tutorial/07-lib/cross/lib_b.kv +++ b/tutorial/07-lib/cross/lib_b.kv @@ -1,4 +1,4 @@ -# 运行: kvlang loadandrun lib_a·kv lib_b·kv +// 运行: kvlang loadandrun lib_a·kv lib_b·kv lib calc { rwfunc init() -> () { /lib/math·sum(3, 4) -> s diff --git a/tutorial/07-lib/cross/multi_level.kv b/tutorial/07-lib/cross/multi_level.kv index 8d303dd1..30a02f07 100644 --- a/tutorial/07-lib/cross/multi_level.kv +++ b/tutorial/07-lib/cross/multi_level.kv @@ -1,12 +1,12 @@ -# 多级包名调用:全路径 /lib/aaa/bbb/math·sum() 与短形式 aaa/bbb/math·sum() 等价 -# 期望输出: -# 7 -# 7 -# 30 +// 多级包名调用:全路径 /lib/aaa/bbb/math·sum() 与短形式 aaa/bbb/math·sum() 等价 +// 期望输出: +// 7 +// 7 +// 30 lib aaa/bbb/math { rwfunc sum(A:int64, B:int64) -> (C:int64) { A + B -> C } rwfunc double(A:int64) -> (C:int64) { - sum(A, A) -> C # 同包裸名调用 + sum(A, A) -> C // 同包裸名调用 } } rwfunc test() -> () { diff --git a/tutorial/07-lib/cross/nested.kv b/tutorial/07-lib/cross/nested.kv index a0900232..ad80ecc8 100644 --- a/tutorial/07-lib/cross/nested.kv +++ b/tutorial/07-lib/cross/nested.kv @@ -1,7 +1,7 @@ -# 嵌套 lib + 扁平 lib 混合 -# 期望输出: -# nested -# 42 +// 嵌套 lib + 扁平 lib 混合 +// 期望输出: +// nested +// 42 lib a { lib b { rwfunc greet() -> () { println("nested") } diff --git a/tutorial/07-lib/inline_lib.kv b/tutorial/07-lib/inline_lib.kv index 33e8a20e..928df510 100644 --- a/tutorial/07-lib/inline_lib.kv +++ b/tutorial/07-lib/inline_lib.kv @@ -1,6 +1,6 @@ -# 期望输出: -# mylib·add(10,20) = 30 -# double(mylib·add(10,20)) = 60 +// 期望输出: +// mylib·add(10,20) = 30 +// double(mylib·add(10,20)) = 60 lib mylib { rwfunc add(A:int64, B:int64) -> (C:int64) { A + B -> C @@ -13,7 +13,7 @@ rwfunc double(x:int64) -> (y:int64) { } rwfunc test() -> () { - a = mylib·add(10, 20) # = 等价于 <- + a = mylib·add(10, 20) // = 等价于 <- println("mylib·add(10,20) =", a) double(a) -> b println("double(mylib·add(10,20)) =", b) diff --git a/tutorial/07-lib/multi/lib_b.kv b/tutorial/07-lib/multi/lib_b.kv index 3826f503..c70b5757 100644 --- a/tutorial/07-lib/multi/lib_b.kv +++ b/tutorial/07-lib/multi/lib_b.kv @@ -1,4 +1,4 @@ -# 运行: kvlang loadandrun lib_a·kv lib_b·kv +// 运行: kvlang loadandrun lib_a·kv lib_b·kv lib math { rwfunc twice(A:int64) -> (R:int64) { A × 2 -> R } rwfunc twice(A:int64) -> (R:int64) { A × 2 -> R_m } diff --git a/tutorial/07-lib/single/inline.kv b/tutorial/07-lib/single/inline.kv index f96f06e8..9f56f73f 100644 --- a/tutorial/07-lib/single/inline.kv +++ b/tutorial/07-lib/single/inline.kv @@ -1,6 +1,6 @@ -# 单 lib + 顶层 test 调用 -# 期望输出: -# 7 +// 单 lib + 顶层 test 调用 +// 期望输出: +// 7 lib math { rwfunc sum(A:int64, B:int64) -> (C:int64) { A + B -> C } } diff --git a/tutorial/07-lib/single/lib.kv b/tutorial/07-lib/single/lib.kv index 24c0bc5f..f2d3eac0 100644 --- a/tutorial/07-lib/single/lib.kv +++ b/tutorial/07-lib/single/lib.kv @@ -1,4 +1,4 @@ -# 单文件单 lib:math 库自含函数+init +// 单文件单 lib:math 库自含函数+init lib math { rwfunc sum(A:int64, B:int64) -> (C:int64) { A + B -> C } rwfunc init() -> () { diff --git a/tutorial/07-lib/walk_lib.kv b/tutorial/07-lib/walk_lib.kv index 32c0eccc..d1fb5228 100644 --- a/tutorial/07-lib/walk_lib.kv +++ b/tutorial/07-lib/walk_lib.kv @@ -1,12 +1,12 @@ -# 递归打印 /lib 代码树:kv·listlen/kv·listn 逐层列举 + 自递归 -# 目录名以 "/" 结尾则下钻;kv·listn 返回 utf8,显式 char/utf32 转码后才能喂给 string·find(utf32) -# 期望输出: -# /lib/ -# print -# println -# kv -# string -# math +// 递归打印 /lib 代码树:kv·listlen/kv·listn 逐层列举 + 自递归 +// 目录名以 "/" 结尾则下钻;kv·listn 返回 utf8,显式 char/utf32 转码后才能喂给 string·find(utf32) +// 期望输出: +// /lib/ +// print +// println +// kv +// string +// math rwfunc walk(path:[]char/utf32, indent:[]char/utf32) -> () { kv·listlen(path) -> n 0 -> i diff --git a/tutorial/08-leetcode/001_two-sum-hash.kv b/tutorial/08-leetcode/001_two-sum-hash.kv index afbf5f06..0e8ea4ff 100644 --- a/tutorial/08-leetcode/001_two-sum-hash.kv +++ b/tutorial/08-leetcode/001_two-sum-hash.kv @@ -1,24 +1,24 @@ -# 001: Two Sum — O(n) hash map (h·*key 动态解引用,has 检存在) -# 来源: LeetCode #1 -# 期望输出: -# [ 0 , 1 ] +// 001: Two Sum — O(n) hash map (h·*key 动态解引用,has 检存在) +// 来源: LeetCode #1 +// 期望输出: +// [ 0 , 1 ] rwfunc two_sum(nums:[]int64, target:int64) -> () { n <- ndarray·numel(nums) - i = 0 # = 等价于 <- + i = 0 // = 等价于 <- "/tmp" -> h while (i < n) { x <- nums[i] - need = target - x # = 等价于 <- + need = target - x // = 等价于 <- kv·get(h, need) != None -> exists if (exists) { kv·get(h, need) -> j - k = j - 1 # = 等价于 <- + k = j - 1 // = 等价于 <- println("[", k, ",", i, "]") n -> i } else { v <- i + 1 - _ = kv·set(h, x, v) # = 等价于 <- + _ = kv·set(h, x, v) // = 等价于 <- i + 1 -> i } } diff --git a/tutorial/08-leetcode/001_two_sum.kv b/tutorial/08-leetcode/001_two_sum.kv index 0ad03617..c9e27e0a 100644 --- a/tutorial/08-leetcode/001_two_sum.kv +++ b/tutorial/08-leetcode/001_two_sum.kv @@ -1,32 +1,32 @@ -# 001: Two Sum — 数组参数版 -# 来源: LeetCode #1 -# 期望输出: -# [ 0 , 1 ] -# [-1, -1] +// 001: Two Sum — 数组参数版 +// 来源: LeetCode #1 +// 期望输出: +// [ 0 , 1 ] +// [-1, -1] rwfunc two_sum(nums:[]int64, target:int64) -> () { n <- ndarray·numel(nums) - found = 0 # = 等价于 <- + found = 0 // = 等价于 <- 0 -> i while (i < n) { j <- 0 while (j < n) { - sk = i == j # = 等价于 <- + sk = i == j // = 等价于 <- if (sk) { j + 1 -> j } else { x <- nums[i] - y = nums[j] # = 等价于 <- + y = nums[j] // = 等价于 <- x + y -> s hit <- s == target if (hit) { println("[", i, ",", j, "]") - found = 1 # = 等价于 <- + found = 1 // = 等价于 <- n -> i j <- n } else { - j = j + 1 # = 等价于 <- + j = j + 1 // = 等价于 <- } } } diff --git a/tutorial/08-leetcode/002_add_two_numbers.kv b/tutorial/08-leetcode/002_add_two_numbers.kv index faef637f..22f1fdfb 100644 --- a/tutorial/08-leetcode/002_add_two_numbers.kv +++ b/tutorial/08-leetcode/002_add_two_numbers.kv @@ -1,9 +1,9 @@ -# 002: Add Two Numbers — 链表大数相加 -# 来源: LeetCode #2 -# 期望输出: -# 7 -# 0 -# 8 +// 002: Add Two Numbers — 链表大数相加 +// 来源: LeetCode #2 +// 期望输出: +// 7 +// 0 +// 8 rwfunc build_lists() -> () { /l1_0 = { val=2; next="/l1_1" } /l1_1 <- { val=4; next="/l1_2" } diff --git a/tutorial/08-leetcode/003_longest_substring.kv b/tutorial/08-leetcode/003_longest_substring.kv index 0b84c7e0..93a8ae53 100644 --- a/tutorial/08-leetcode/003_longest_substring.kv +++ b/tutorial/08-leetcode/003_longest_substring.kv @@ -1,14 +1,14 @@ -# 003: Longest Substring Without Repeating Characters — 滑动窗口 -# 来源: LeetCode #3 -# 期望输出: -# 3 -# 1 -# 5 +// 003: Longest Substring Without Repeating Characters — 滑动窗口 +// 来源: LeetCode #3 +// 期望输出: +// 3 +// 1 +// 5 rwfunc length_of_longest(s:[]char/utf32) -> (max_len:int64) { n <- string·len(s) - last:[]char/utf8·int64 = {} # = 等价于 <- - max_len = 0 # = 等价于 <- - left = 0 # = 等价于 <- + last:[]char/utf8·int64 = {} // = 等价于 <- + max_len = 0 // = 等价于 <- + left = 0 // = 等价于 <- right <- 0 while (right < n) { s[right] -> c @@ -18,7 +18,7 @@ rwfunc length_of_longest(s:[]char/utf32) -> (max_len:int64) { cand <- prev + 1 if (cand > left) { left <- cand } } - _ = kv·set(last, c, right) # = 等价于 <- + _ = kv·set(last, c, right) // = 等价于 <- cur <- right - left + 1 if (cur > max_len) { cur -> max_len } right + 1 -> right @@ -26,7 +26,7 @@ rwfunc length_of_longest(s:[]char/utf32) -> (max_len:int64) { } rwfunc test() -> () { - r1 = length_of_longest("abcabcbb") # = 等价于 <- + r1 = length_of_longest("abcabcbb") // = 等价于 <- println(r1) println(length_of_longest("bbbbb")) r3 <- length_of_longest("abcde") diff --git a/tutorial/08-leetcode/007_reverse_int.kv b/tutorial/08-leetcode/007_reverse_int.kv index c0e7c3ad..e6192ebe 100644 --- a/tutorial/08-leetcode/007_reverse_int.kv +++ b/tutorial/08-leetcode/007_reverse_int.kv @@ -1,22 +1,22 @@ -# 007: Reverse Integer -# 来源: LeetCode #7 -# 期望输出: -# 321 -# -321 +// 007: Reverse Integer +// 来源: LeetCode #7 +// 期望输出: +// 321 +// -321 rwfunc reverse(x:int64) -> (result:int64) { - neg = x < 0 # = 等价于 <- + neg = x < 0 // = 等价于 <- x -> n if (neg) { n <- -x } - rev = 0 # = 等价于 <- + rev = 0 // = 等价于 <- while (n > 0) { rev × 10 -> r rev × 10 -> r_m d <- n % 10 - rev = r + d # = 等价于 <- + rev = r + d // = 等价于 <- n ÷ 10 -> n n ÷ 10 -> n_m } @@ -24,7 +24,7 @@ rwfunc reverse(x:int64) -> (result:int64) { if (neg) { result <- -rev } else { - result = rev # = 等价于 <- + result = rev // = 等价于 <- } } diff --git a/tutorial/08-leetcode/008_string_to_int.kv b/tutorial/08-leetcode/008_string_to_int.kv index 0cb469b9..56a4278b 100644 --- a/tutorial/08-leetcode/008_string_to_int.kv +++ b/tutorial/08-leetcode/008_string_to_int.kv @@ -1,23 +1,23 @@ -# 008: String to Integer (atoi) — 字符串转整数 -# 来源: LeetCode #8 -# 简化: 不处理前导空格 -# 期望输出: -# 42 -# -42 -# 4193 +// 008: String to Integer (atoi) — 字符串转整数 +// 来源: LeetCode #8 +// 简化: 不处理前导空格 +// 期望输出: +// 42 +// -42 +// 4193 rwfunc my_atoi(s:[]char/utf32) -> (result:int64) { - result = 0 # = 等价于 <- - n = string·len(s) # = 等价于 <- + result = 0 // = 等价于 <- + n = string·len(s) // = 等价于 <- i <- 0 - sign = 1 # = 等价于 <- + sign = 1 // = 等价于 <- if (s[i] == "-") { -1 -> sign ; i + 1 -> i } if (s[i] == "+") { i + 1 -> i } while (i < n) { - c2 = s[i] # = 等价于 <- + c2 = s[i] // = 等价于 <- digit <- string·ord(c2) - 48 if (digit >= 0 && digit <= 9) { - result = result × 10 + digit # = 等价于 <- - result_m = result × 10 + digit # = 等价于 <- + result = result × 10 + digit // = 等价于 <- + result_m = result × 10 + digit // = 等价于 <- i + 1 -> i } else { n -> i } } diff --git a/tutorial/08-leetcode/009_palindrome.kv b/tutorial/08-leetcode/009_palindrome.kv index e7f3d9f6..ec8e9022 100644 --- a/tutorial/08-leetcode/009_palindrome.kv +++ b/tutorial/08-leetcode/009_palindrome.kv @@ -1,28 +1,28 @@ -# 009: Palindrome Number -# 来源: LeetCode #9 -# 期望输出: -# 1 -# 0 +// 009: Palindrome Number +// 来源: LeetCode #9 +// 期望输出: +// 1 +// 0 rwfunc is_pal(x:int64) -> (r:int64) { - neg = x < 0 # = 等价于 <- + neg = x < 0 // = 等价于 <- if (neg) { 0 -> r } else { orig <- x - rev = 0 # = 等价于 <- + rev = 0 // = 等价于 <- while (orig > 0) { rev × 10 -> r10 rev × 10 -> r10_m d <- orig % 10 - rev = r10 + d # = 等价于 <- + rev = r10 + d // = 等价于 <- orig ÷ 10 -> orig orig ÷ 10 -> orig_m } ok <- rev == x if (ok) { - r = 1 # = 等价于 <- + r = 1 // = 等价于 <- } else { 0 -> r } @@ -33,6 +33,6 @@ rwfunc test() -> () { r1 <- is_pal(121) println(r1) - r2 = is_pal(-121) # = 等价于 <- + r2 = is_pal(-121) // = 等价于 <- println(r2) } diff --git a/tutorial/08-leetcode/011_container_water.kv b/tutorial/08-leetcode/011_container_water.kv index 8245c342..38918891 100644 --- a/tutorial/08-leetcode/011_container_water.kv +++ b/tutorial/08-leetcode/011_container_water.kv @@ -1,26 +1,26 @@ -# 011: Container With Most Water — 数组参数版 -# 来源: LeetCode #11 -# 期望输出: -# 49 +// 011: Container With Most Water — 数组参数版 +// 来源: LeetCode #11 +// 期望输出: +// 49 rwfunc max_area(h:[]int64) -> (mx:int64) { ndarray·numel(h) -> n l <- 0 - r = n - 1 # = 等价于 <- + r = n - 1 // = 等价于 <- 0 -> mx while (l < r) { hl <- h[l] - hr = h[r] # = 等价于 <- + hr = h[r] // = 等价于 <- r - l -> w ls <- hl < hr if (ls) { - ar = hl × w # = 等价于 <- - ar_m = hl × w # = 等价于 <- + ar = hl × w // = 等价于 <- + ar_m = hl × w // = 等价于 <- l + 1 -> l } else { ar <- hr × w ar_m <- hr × w - r = r - 1 # = 等价于 <- + r = r - 1 // = 等价于 <- } ar > mx -> bg @@ -34,6 +34,6 @@ rwfunc max_area(h:[]int64) -> (mx:int64) { rwfunc test() -> () { a:[]int64 = [1, 8, 6, 2, 5, 4, 8, 3, 7] - r = max_area(a) # = 等价于 <- + r = max_area(a) // = 等价于 <- println(r) } diff --git a/tutorial/08-leetcode/012_int_to_roman.kv b/tutorial/08-leetcode/012_int_to_roman.kv index c2f2c22f..82f1fb6b 100644 --- a/tutorial/08-leetcode/012_int_to_roman.kv +++ b/tutorial/08-leetcode/012_int_to_roman.kv @@ -1,8 +1,8 @@ -# 012: Integer to Roman — 整数转罗马数字 -# 来源: LeetCode #12 -# 期望输出: -# LVIII -# MCMXCIV +// 012: Integer to Roman — 整数转罗马数字 +// 来源: LeetCode #12 +// 期望输出: +// LVIII +// MCMXCIV rwfunc int_to_roman(n:int64) -> () { result <- "" val <- n diff --git a/tutorial/08-leetcode/013_roman-to-integer.kv b/tutorial/08-leetcode/013_roman-to-integer.kv index 0636bbb8..af1770b2 100644 --- a/tutorial/08-leetcode/013_roman-to-integer.kv +++ b/tutorial/08-leetcode/013_roman-to-integer.kv @@ -1,25 +1,25 @@ -# 013 Roman to Integer -# 期望输出: 58, 1994 +// 013 Roman to Integer +// 期望输出: 58, 1994 rwfunc romanToInt(s:[]char/utf32) -> (val:int64) { 0 -> val i <- 0 - n = string·len(s) # = 等价于 <- + n = string·len(s) // = 等价于 <- "" -> prev while (i < n) { c <- s[i] - isI = c == "I" # = 等价于 <- + isI = c == "I" // = 等价于 <- c == "V" -> isV isX <- c == "X" - isL = c == "L" # = 等价于 <- + isL = c == "L" // = 等价于 <- c == "C" -> isC isD <- c == "D" - isM = c == "M" # = 等价于 <- - pI = prev == "I" # = 等价于 <- + isM = c == "M" // = 等价于 <- + pI = prev == "I" // = 等价于 <- prev == "X" -> pX pC <- prev == "C" if (isI) { - val = val + 1 # = 等价于 <- + val = val + 1 // = 等价于 <- } if (isV) { @@ -31,7 +31,7 @@ rwfunc romanToInt(s:[]char/utf32) -> (val:int64) { } if (isL) { - val = val + 50 # = 等价于 <- + val = val + 50 // = 等价于 <- } if (isC) { @@ -46,13 +46,13 @@ rwfunc romanToInt(s:[]char/utf32) -> (val:int64) { val + 1000 -> val } - subI = pI # = 等价于 <- + subI = pI // = 等价于 <- pX -> subX subC <- pC if (isV) { if (subI) { - val = val - 2 # = 等价于 <- + val = val - 2 // = 等价于 <- } } @@ -70,7 +70,7 @@ rwfunc romanToInt(s:[]char/utf32) -> (val:int64) { if (isC) { if (subX) { - val = val - 20 # = 等价于 <- + val = val - 20 // = 等价于 <- } } @@ -87,7 +87,7 @@ rwfunc romanToInt(s:[]char/utf32) -> (val:int64) { } prev <- c - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } } @@ -97,5 +97,5 @@ rwfunc test() -> () { println("LVIII =", a) b <- romanToInt("MCMXCIV") println("MCMXCIV =", b) - /roman_lviii = a # = 等价于 <- + /roman_lviii = a // = 等价于 <- } diff --git a/tutorial/08-leetcode/013_roman_v2.kv b/tutorial/08-leetcode/013_roman_v2.kv index 59806f35..e9e47a92 100644 --- a/tutorial/08-leetcode/013_roman_v2.kv +++ b/tutorial/08-leetcode/013_roman_v2.kv @@ -1,39 +1,39 @@ -# 013: Roman to Integer — 罗马数字转整数 -# 来源: LeetCode #13 -# 期望输出: -# 58 +// 013: Roman to Integer — 罗马数字转整数 +// 来源: LeetCode #13 +// 期望输出: +// 58 rwfunc roman_to_int(s:[]char/utf32) -> () { string·len(s) -> n result <- 0 - i = 0 # = 等价于 <- + i = 0 // = 等价于 <- while (i < n) { string·char(s, i) -> c is_I <- c == "I" - is_V = c == "V" # = 等价于 <- + is_V = c == "V" // = 等价于 <- c == "X" -> is_X is_L <- c == "L" - is_C = c == "C" # = 等价于 <- + is_C = c == "C" // = 等价于 <- c == "D" -> is_D is_M <- c == "M" if (is_I) { - ni = i + 1 # = 等价于 <- + ni = i + 1 // = 等价于 <- ni < n -> has_next if (has_next) { nc <- string·char(s, ni) - iv = nc == "V" # = 等价于 <- + iv = nc == "V" // = 等价于 <- nc == "X" -> ix if (iv) { val <- 4 - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } else { if (ix) { 9 -> val i <- i + 1 } else { - val = 1 # = 等价于 <- + val = 1 // = 等价于 <- } } } else { @@ -44,7 +44,7 @@ rwfunc roman_to_int(s:[]char/utf32) -> () { val <- 5 } else { if (is_X) { - val = 10 # = 等价于 <- + val = 10 // = 等价于 <- } else { if (is_L) { 50 -> val @@ -53,7 +53,7 @@ rwfunc roman_to_int(s:[]char/utf32) -> () { val <- 100 } else { if (is_D) { - val = 500 # = 等价于 <- + val = 500 // = 等价于 <- } else { 1000 -> val } @@ -64,7 +64,7 @@ rwfunc roman_to_int(s:[]char/utf32) -> () { } result <- result + val - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } println(result) } diff --git a/tutorial/08-leetcode/014_longest_common.kv b/tutorial/08-leetcode/014_longest_common.kv index 9fa7fe6f..50c45185 100644 --- a/tutorial/08-leetcode/014_longest_common.kv +++ b/tutorial/08-leetcode/014_longest_common.kv @@ -1,29 +1,29 @@ -# 014: Longest Common Prefix — 逐字符比较 -# 来源: LeetCode #14 -# 期望输出: -# fl +// 014: Longest Common Prefix — 逐字符比较 +// 来源: LeetCode #14 +// 期望输出: +// fl rwfunc lcp() -> () { "flower" -> a b <- "flow" - c = "flight" # = 等价于 <- + c = "flight" // = 等价于 <- string·len(a) -> na nb <- string·len(b) - nc = string·len(c) # = 等价于 <- + nc = string·len(c) // = 等价于 <- 0 -> i ok <- true while (ok) { - ca = i < na # = 等价于 <- + ca = i < na // = 等价于 <- i < nb -> cb cc <- i < nc - all_ok = ca && cb && cc # = 等价于 <- + all_ok = ca && cb && cc // = 等价于 <- if (all_ok) { string·char(a, i) -> va vb <- string·char(b, i) - vc = string·char(c, i) # = 等价于 <- + vc = string·char(c, i) // = 等价于 <- va == vb -> ab bc <- vb == vc - match = ab && bc # = 等价于 <- + match = ab && bc // = 等价于 <- if (match) { i + 1 -> i @@ -31,7 +31,7 @@ rwfunc lcp() -> () { ok <- false } } else { - ok = false # = 等价于 <- + ok = false // = 等价于 <- } } string·slice(a, 0, i) -> ans diff --git a/tutorial/08-leetcode/020_valid_parentheses.kv b/tutorial/08-leetcode/020_valid_parentheses.kv index 877dbf53..fb9b5378 100644 --- a/tutorial/08-leetcode/020_valid_parentheses.kv +++ b/tutorial/08-leetcode/020_valid_parentheses.kv @@ -1,66 +1,66 @@ -# 020: Valid Parentheses — 栈匹配括号 -# 来源: LeetCode #20 -# 期望输出: -# true -# true -# false +// 020: Valid Parentheses — 栈匹配括号 +// 来源: LeetCode #20 +// 期望输出: +// true +// true +// false rwfunc is_valid(s:[]char/utf32) -> (ok:int64) { ok <- 1 - si = -1 # = 等价于 <- - n = string·len(s) # = 等价于 <- + si = -1 // = 等价于 <- + n = string·len(s) // = 等价于 <- i <- 0 while (i < n) { - c = s[i] # = 等价于 <- + c = s[i] // = 等价于 <- if (c == "(") { si + 1 -> si _ <- kv·set("/tmp/vp", si, 1) } if (c == "[") { - si = si + 1 # = 等价于 <- + si = si + 1 // = 等价于 <- kv·set("/tmp/vp", si, 2) -> _ } if (c == "{") { si + 1 -> si - _ = kv·set("/tmp/vp", si, 3) # = 等价于 <- + _ = kv·set("/tmp/vp", si, 3) // = 等价于 <- } if (c == ")") { if (si < 0) { 0 -> ok ; n -> i } else { /tmp/vp[si] -> top si - 1 -> si - if (top != 1) { ok = 0 ; n -> i } # = 等价于 <- - if (top ≠ 1) { ok_m = 0 ; n -> i } # = 等价于 <- + if (top != 1) { ok = 0 ; n -> i } // = 等价于 <- + if (top ≠ 1) { ok_m = 0 ; n -> i } // = 等价于 <- } } if (c == "]") { - if (si < 0) { ok = 0 ; i <- n } # = 等价于 <- + if (si < 0) { ok = 0 ; i <- n } // = 等价于 <- else { /tmp/vp[si] -> top si - 1 -> si - if (top != 2) { 0 -> ok ; n -> i } # = 等价于 <- - if (top ≠ 2) { 0 -> ok_m ; n -> i } # = 等价于 <- + if (top != 2) { 0 -> ok ; n -> i } // = 等价于 <- + if (top ≠ 2) { 0 -> ok_m ; n -> i } // = 等价于 <- } } if (c == "}") { - if (si < 0) { 0 -> ok ; i <- n } # = 等价于 <- + if (si < 0) { 0 -> ok ; i <- n } // = 等价于 <- else { /tmp/vp[si] -> top - si = si - 1 # = 等价于 <- - if (top != 3) { ok <- 0 ; i = n } # = 等价于 <- - if (top ≠ 3) { ok_m <- 0 ; i = n } # = 等价于 <- + si = si - 1 // = 等价于 <- + if (top != 3) { ok <- 0 ; i = n } // = 等价于 <- + if (top ≠ 3) { ok_m <- 0 ; i = n } // = 等价于 <- } } - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } if (si >= 0) { 0 -> ok } if (si ≥ 0) { 0 -> ok_m } } rwfunc test() -> () { - r1 = is_valid("()") # = 等价于 <- + r1 = is_valid("()") // = 等价于 <- if (r1 == 1) { println("true") } else { println("false") } r2 <- is_valid("()[]{}") if (r2 == 1) { println("true") } else { println("false") } - r3 = is_valid("(]") # = 等价于 <- + r3 = is_valid("(]") // = 等价于 <- if (r3 == 1) { println("true") } else { println("false") } } diff --git a/tutorial/08-leetcode/021_merge_two_lists.kv b/tutorial/08-leetcode/021_merge_two_lists.kv index b9a9e8a7..b5c3c4a3 100644 --- a/tutorial/08-leetcode/021_merge_two_lists.kv +++ b/tutorial/08-leetcode/021_merge_two_lists.kv @@ -1,31 +1,31 @@ -# 021: Merge Two Sorted Lists -# 来源: LeetCode #21 -# 期望输出: -# 1 -# 1 -# 2 -# 3 -# 4 -# 4 +// 021: Merge Two Sorted Lists +// 来源: LeetCode #21 +// 期望输出: +// 1 +// 1 +// 2 +// 3 +// 4 +// 4 rwfunc build_lists() -> () { - /a0 = { val=1; next="/a1" } # = 等价于 <- + /a0 = { val=1; next="/a1" } // = 等价于 <- /a1 <- { val=2; next="/a2" } { val=4; next="" } -> /a2 - /b0 = { val=1; next="/b1" } # = 等价于 <- + /b0 = { val=1; next="/b1" } // = 等价于 <- /b1 <- { val=3; next="/b2" } { val=4; next="" } -> /b2 } rwfunc merge(a:[]char/utf32, b:[]char/utf32) -> () { pa <- a - pb = b # = 等价于 <- + pb = b // = 等价于 <- while (pa != "") { pa·val -> av pick_a <- pb == "" if (pick_a) { println(av) - pa = pa·next # = 等价于 <- + pa = pa·next // = 等价于 <- } else { pb·val -> bv take <- av <= bv @@ -33,7 +33,7 @@ rwfunc merge(a:[]char/utf32, b:[]char/utf32) -> () { if (take) { println(av) - pa = pa·next # = 等价于 <- + pa = pa·next // = 等价于 <- } else { println(bv) pb·next -> pb @@ -43,7 +43,7 @@ rwfunc merge(a:[]char/utf32, b:[]char/utf32) -> () { while (pb != "") { bv <- pb·val println(bv) - pb = pb·next # = 等价于 <- + pb = pb·next // = 等价于 <- } } diff --git a/tutorial/08-leetcode/022_generate_parens.kv b/tutorial/08-leetcode/022_generate_parens.kv index d713eb67..a24e9d65 100644 --- a/tutorial/08-leetcode/022_generate_parens.kv +++ b/tutorial/08-leetcode/022_generate_parens.kv @@ -1,8 +1,8 @@ -# 022: Generate Parentheses — 生成 n=2 的括号组合 -# 来源: LeetCode #22 -# 期望输出: -# (()) -# ()() +// 022: Generate Parentheses — 生成 n=2 的括号组合 +// 来源: LeetCode #22 +// 期望输出: +// (()) +// ()() rwfunc generate() -> () { total <- 16 idx <- 0 diff --git a/tutorial/08-leetcode/026_remove_dupes.kv b/tutorial/08-leetcode/026_remove_dupes.kv index bc8d33d5..7e480629 100644 --- a/tutorial/08-leetcode/026_remove_dupes.kv +++ b/tutorial/08-leetcode/026_remove_dupes.kv @@ -1,24 +1,24 @@ -# 026: Remove Duplicates from Sorted Array -# 来源: LeetCode #26 -# 期望输出: -# k = 5 -# k = 5 +// 026: Remove Duplicates from Sorted Array +// 来源: LeetCode #26 +// 期望输出: +// k = 5 +// k = 5 rwfunc remove_dupes() -> (k:int64) { a:[]int64 = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4] ndarray·numel(a) -> n k <- 1 - i = 1 # = 等价于 <- + i = 1 // = 等价于 <- while (i < n) { a[i] -> cur pi <- k - 1 - prev = a[pi] # = 等价于 <- + prev = a[pi] // = 等价于 <- cur == prev -> same if (same) { i <- i + 1 } else { a[k] <- cur - k = k + 1 # = 等价于 <- + k = k + 1 // = 等价于 <- i + 1 -> i } } diff --git a/tutorial/08-leetcode/027_remove_element.kv b/tutorial/08-leetcode/027_remove_element.kv index c3d4fa82..dfbf54ed 100644 --- a/tutorial/08-leetcode/027_remove_element.kv +++ b/tutorial/08-leetcode/027_remove_element.kv @@ -1,27 +1,27 @@ -# 027: Remove Element — 原地移除指定值 -# 算法: 读写指针,跳过等于 val 的元素 -# 来源: LeetCode #27 -# 期望输出: -# k = 2 -# k = 2 -# 2 -# 2 +// 027: Remove Element — 原地移除指定值 +// 算法: 读写指针,跳过等于 val 的元素 +// 来源: LeetCode #27 +// 期望输出: +// k = 2 +// k = 2 +// 2 +// 2 rwfunc remove_element() -> () { - a:[]int64 = [3, 2, 2, 3] # = 等价于 <- + a:[]int64 = [3, 2, 2, 3] // = 等价于 <- 3 -> val n <- ndarray·numel(a) - k = 0 # = 等价于 <- + k = 0 // = 等价于 <- 0 -> i while (i < n) { cur <- a[i] - skip = cur == val # = 等价于 <- + skip = cur == val // = 等价于 <- if (skip) { i + 1 -> i } else { a[k] <- cur k <- k + 1 - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } } println("k =", k) @@ -29,7 +29,7 @@ rwfunc remove_element() -> () { while (j < k) { v <- a[j] println(v) - j = j + 1 # = 等价于 <- + j = j + 1 // = 等价于 <- } } diff --git a/tutorial/08-leetcode/028_strstr.kv b/tutorial/08-leetcode/028_strstr.kv index 10c66834..f9bdb65a 100644 --- a/tutorial/08-leetcode/028_strstr.kv +++ b/tutorial/08-leetcode/028_strstr.kv @@ -1,33 +1,33 @@ -# 028: strStr — 暴力子串查找 -# 来源: LeetCode #28 -# 期望输出: -# 2 -# 2 +// 028: strStr — 暴力子串查找 +// 来源: LeetCode #28 +// 期望输出: +// 2 +// 2 rwfunc str_str(hay:[]char/utf32, needle:[]char/utf32) -> () { string·len(hay) -> nh nn <- string·len(needle) - i = 0 # = 等价于 <- + i = 0 // = 等价于 <- -1 -> ans limit <- nh - nn while (i <= limit) { - match = true # = 等价于 <- + match = true // = 等价于 <- 0 -> j while (j < nn) { hc <- string·char(hay, i + j) - nc = string·char(needle, j) # = 等价于 <- + nc = string·char(needle, j) // = 等价于 <- hc == nc -> eq if (eq) { j <- j + 1 } else { - match = false # = 等价于 <- + match = false // = 等价于 <- nn -> j } } if (match) { ans <- i - i = limit + 1 # = 等价于 <- + i = limit + 1 // = 等价于 <- } else { i + 1 -> i } diff --git a/tutorial/08-leetcode/029_divide_two_ints.kv b/tutorial/08-leetcode/029_divide_two_ints.kv index 2682cc77..39409c98 100644 --- a/tutorial/08-leetcode/029_divide_two_ints.kv +++ b/tutorial/08-leetcode/029_divide_two_ints.kv @@ -1,36 +1,36 @@ -# 029: Divide Two Integers — 不用 */ % 实现整数除法 -# 来源: LeetCode #29 -# 期望输出: -# 3 -# -2 +// 029: Divide Two Integers — 不用 */ % 实现整数除法 +// 来源: LeetCode #29 +// 期望输出: +// 3 +// -2 rwfunc divide(dividend:int64, divisor:int64) -> (result:int64) { dend <- dividend - dsor = divisor # = 等价于 <- - neg = 0 # = 等价于 <- + dsor = divisor // = 等价于 <- + neg = 0 // = 等价于 <- if (dend < 0) { neg <- 1 - neg dend <- 0 - dend } if (dsor < 0) { - neg = 1 - neg # = 等价于 <- + neg = 1 - neg // = 等价于 <- dsor <- 0 - dsor } - result = 0 # = 等价于 <- + result = 0 // = 等价于 <- while (dend >= dsor) { temp <- dsor - multiple = 1 # = 等价于 <- + multiple = 1 // = 等价于 <- while (dend >= temp + temp) { temp <- temp + temp multiple <- multiple + multiple } dend <- dend - temp - result = result + multiple # = 等价于 <- + result = result + multiple // = 等价于 <- } if (neg == 1) { result <- 0 - result } } rwfunc test() -> () { - r1 = divide(10, 3) # = 等价于 <- + r1 = divide(10, 3) // = 等价于 <- println(r1) r2 <- divide(7, -3) println(r2) diff --git a/tutorial/08-leetcode/033_search_rotated.kv b/tutorial/08-leetcode/033_search_rotated.kv index 244a48e0..36d4ea5e 100644 --- a/tutorial/08-leetcode/033_search_rotated.kv +++ b/tutorial/08-leetcode/033_search_rotated.kv @@ -1,35 +1,35 @@ -# 033: Search in Rotated Sorted Array -# 算法: 二分查找 + 半区判断 -# 来源: LeetCode #33 -# 期望输出: -# 4 +// 033: Search in Rotated Sorted Array +// 算法: 二分查找 + 半区判断 +// 来源: LeetCode #33 +// 期望输出: +// 4 rwfunc search() -> () { a:[]int64 <- [4, 5, 6, 7, 0, 1, 2] - n = ndarray·numel(a) # = 等价于 <- + n = ndarray·numel(a) // = 等价于 <- 0 -> target lo <- 0 - hi = n - 1 # = 等价于 <- + hi = n - 1 // = 等价于 <- -1 -> result while (lo <= hi) { s <- lo + hi - mid = s ÷ 2 # = 等价于 <- - mid_m = s ÷ 2 # = 等价于 <- + mid = s ÷ 2 // = 等价于 <- + mid_m = s ÷ 2 // = 等价于 <- a[mid] -> mv eq <- mv == target if (eq) { - result = mid # = 等价于 <- + result = mid // = 等价于 <- hi + 1 -> lo } else { lv <- a[lo] - rv = a[hi] # = 等价于 <- + rv = a[hi] // = 等价于 <- lv <= mv -> left_sorted lv ≤ mv -> left_sorted_m if (left_sorted) { t1 <- lv <= target t1_m <- lv ≤ target - t2 = target < mv # = 等价于 <- + t2 = target < mv // = 等价于 <- if (t1 && t2) { mid - 1 -> hi @@ -37,15 +37,15 @@ rwfunc search() -> () { lo <- mid + 1 } } else { - t3 = mv <= target # = 等价于 <- - t3_m = mv ≤ target # = 等价于 <- + t3 = mv <= target // = 等价于 <- + t3_m = mv ≤ target // = 等价于 <- target <= rv -> t4 target ≤ rv -> t4_m if (t3 && t4) { lo <- mid + 1 } else { - hi = mid - 1 # = 等价于 <- + hi = mid - 1 // = 等价于 <- } } } diff --git a/tutorial/08-leetcode/034_search_range.kv b/tutorial/08-leetcode/034_search_range.kv index 06e25f61..488f4484 100644 --- a/tutorial/08-leetcode/034_search_range.kv +++ b/tutorial/08-leetcode/034_search_range.kv @@ -1,43 +1,43 @@ -# 034: Find First and Last Position — 二分查找区间 -# 算法: 两次二分分别找左边界和右边界 -# 来源: LeetCode #34 -# 期望输出: -# [ 3 , 4 ] +// 034: Find First and Last Position — 二分查找区间 +// 算法: 两次二分分别找左边界和右边界 +// 来源: LeetCode #34 +// 期望输出: +// [ 3 , 4 ] rwfunc search_range() -> () { [5, 7, 7, 8, 8, 10] -> a:[]int64 n <- ndarray·numel(a) - target = 8 # = 等价于 <- - # find left + target = 8 // = 等价于 <- + // find left 0 -> lo hi <- n - 1 - left = -1 # = 等价于 <- + left = -1 // = 等价于 <- while (lo <= hi) { lo + hi -> s mid <- s ÷ 2 mid_m <- s ÷ 2 - mv = a[mid] # = 等价于 <- + mv = a[mid] // = 等价于 <- mv < target -> lt if (lt) { lo <- mid + 1 } else { - left = mid # = 等价于 <- + left = mid // = 等价于 <- mid - 1 -> hi } } - # find right + // find right lo2 <- 0 - hi2 = n - 1 # = 等价于 <- + hi2 = n - 1 // = 等价于 <- -1 -> right while (lo2 <= hi2) { s2 <- lo2 + hi2 - mid2 = s2 ÷ 2 # = 等价于 <- - mid2_m = s2 ÷ 2 # = 等价于 <- + mid2 = s2 ÷ 2 // = 等价于 <- + mid2_m = s2 ÷ 2 // = 等价于 <- a[mid2] -> mv2 gt <- mv2 > target if (gt) { - hi2 = mid2 - 1 # = 等价于 <- + hi2 = mid2 - 1 // = 等价于 <- } else { mid2 -> right lo2 <- mid2 + 1 diff --git a/tutorial/08-leetcode/035_search_insert.kv b/tutorial/08-leetcode/035_search_insert.kv index 33308177..6d0ada1e 100644 --- a/tutorial/08-leetcode/035_search_insert.kv +++ b/tutorial/08-leetcode/035_search_insert.kv @@ -1,27 +1,27 @@ -# 035: Search Insert Position — 二分查找插入位置 -# 算法: 二分查找 -# 来源: LeetCode #35 -# 期望输出: -# index = 2 +// 035: Search Insert Position — 二分查找插入位置 +// 算法: 二分查找 +// 来源: LeetCode #35 +// 期望输出: +// index = 2 rwfunc search_insert() -> () { - a:[]int64 = [1, 3, 5, 6] # = 等价于 <- + a:[]int64 = [1, 3, 5, 6] // = 等价于 <- 5 -> target n <- ndarray·numel(a) - lo = 0 # = 等价于 <- + lo = 0 // = 等价于 <- n - 1 -> hi pos <- 0 while (lo <= hi) { - s = lo + hi # = 等价于 <- + s = lo + hi // = 等价于 <- s ÷ 2 -> mid s ÷ 2 -> mid_m mv <- a[mid] - eq = mv == target # = 等价于 <- + eq = mv == target // = 等价于 <- if (eq) { mid -> pos lo <- hi + 1 } else { - lt = mv < target # = 等价于 <- + lt = mv < target // = 等价于 <- if (lt) { mid + 1 -> lo @@ -30,7 +30,7 @@ rwfunc search_insert() -> () { } } } - not_found = pos == 0 # = 等价于 <- + not_found = pos == 0 // = 等价于 <- if (not_found) { lo -> pos diff --git a/tutorial/08-leetcode/038_count_and_say.kv b/tutorial/08-leetcode/038_count_and_say.kv index ab2ec1da..0bb5572e 100644 --- a/tutorial/08-leetcode/038_count_and_say.kv +++ b/tutorial/08-leetcode/038_count_and_say.kv @@ -1,18 +1,18 @@ -# 038: Count and Say — 报数序列 -# 来源: LeetCode #38 -# 存储:(val, count) 交替排列在数组中 -# 期望输出: -# 1 -# 11 -# 21 -# 1211 -# 111221 +// 038: Count and Say — 报数序列 +// 来源: LeetCode #38 +// 存储:(val, count) 交替排列在数组中 +// 期望输出: +// 1 +// 11 +// 21 +// 1211 +// 111221 rwfunc next_seq(src_len:int64) -> (dst_len:int64) { - i = 0 # = 等价于 <- - di = 0 # = 等价于 <- + i = 0 // = 等价于 <- + di = 0 // = 等价于 <- while (i < src_len) { /tmp/s[i] -> cur - count = 1 # = 等价于 <- + count = 1 // = 等价于 <- j <- i + 1 while (j < src_len) { /tmp/s[j] -> v @@ -28,11 +28,11 @@ rwfunc next_seq(src_len:int64) -> (dst_len:int64) { } rwfunc print_seq_len(seq_len:int64) -> () { - i = 0 # = 等价于 <- + i = 0 // = 等价于 <- while (i < seq_len) { cnt <- /tmp/s[i] - val = /tmp/s[i+1] # = 等价于 <- - k = 0 # = 等价于 <- + val = /tmp/s[i+1] // = 等价于 <- + k = 0 // = 等价于 <- while (k < cnt) { print(val) k + 1 -> k @@ -43,19 +43,19 @@ rwfunc print_seq_len(seq_len:int64) -> () { } rwfunc copy_from_s2_to_s(s2_len:int64) -> () { - i = 0 # = 等价于 <- + i = 0 // = 等价于 <- while (i < s2_len) { /tmp/s2[i] -> v - _ = kv·set("/tmp/s", i, v) # = 等价于 <- + _ = kv·set("/tmp/s", i, v) // = 等价于 <- i + 1 -> i } } rwfunc count_and_say(N:int64) -> () { - _ = kv·set("/tmp/s", 0, 1) # count=1 of digit 1 + _ = kv·set("/tmp/s", 0, 1) // count=1 of digit 1 _ = kv·set("/tmp/s", 1, 1) - cur_len = 2 # = 等价于 <- - round = 1 # = 等价于 <- + cur_len = 2 // = 等价于 <- + round = 1 // = 等价于 <- while (round < N) { l <- next_seq(cur_len) copy_from_s2_to_s(l) diff --git a/tutorial/08-leetcode/048_rotate_image.kv b/tutorial/08-leetcode/048_rotate_image.kv index 30c3dee4..b577735c 100644 --- a/tutorial/08-leetcode/048_rotate_image.kv +++ b/tutorial/08-leetcode/048_rotate_image.kv @@ -1,26 +1,26 @@ -# 048: Rotate Image — 原地旋转矩阵 90° 顺时针 -# 来源: LeetCode #48 -# 期望输出: -# 7 -# 4 -# 1 -# 8 -# 5 -# 2 -# 9 -# 6 -# 3 +// 048: Rotate Image — 原地旋转矩阵 90° 顺时针 +// 来源: LeetCode #48 +// 期望输出: +// 7 +// 4 +// 1 +// 8 +// 5 +// 2 +// 9 +// 6 +// 3 rwfunc rotate(N:int64) -> () { mat:[]int64 = [1, 2, 3, 4, 5, 6, 7, 8, 9] - # transpose - i = 0 # = 等价于 <- + // transpose + i = 0 // = 等价于 <- while (i < N) { - j = i + 1 # = 等价于 <- + j = i + 1 // = 等价于 <- while (j < N) { ri <- i × N + j ri_m <- i × N + j - rj = j × N + i # = 等价于 <- - rj_m = j × N + i # = 等价于 <- + rj = j × N + i // = 等价于 <- + rj_m = j × N + i // = 等价于 <- mat[ri] -> t mat[rj] -> u mat[ri] <- u @@ -29,12 +29,12 @@ rwfunc rotate(N:int64) -> () { } i + 1 -> i } - # reverse each row - r = 0 # = 等价于 <- + // reverse each row + r = 0 // = 等价于 <- while (r < N) { l <- r × N l_m <- r × N - h = l + N - 1 # = 等价于 <- + h = l + N - 1 // = 等价于 <- while (l < h) { mat[l] -> v1 mat[h] -> v2 @@ -45,13 +45,13 @@ rwfunc rotate(N:int64) -> () { } r + 1 -> r } - # print - row = 0 # = 等价于 <- + // print + row = 0 // = 等价于 <- while (row < N) { - col = 0 # = 等价于 <- + col = 0 // = 等价于 <- while (col < N) { - idx = row × N + col # = 等价于 <- - idx_m = row × N + col # = 等价于 <- + idx = row × N + col // = 等价于 <- + idx_m = row × N + col // = 等价于 <- v <- mat[idx] println(v) col + 1 -> col diff --git a/tutorial/08-leetcode/050_pow.kv b/tutorial/08-leetcode/050_pow.kv index 05b2af70..f6fbfdb5 100644 --- a/tutorial/08-leetcode/050_pow.kv +++ b/tutorial/08-leetcode/050_pow.kv @@ -1,15 +1,15 @@ -# 050: Pow(x,n) — 快速幂 -# 来源: LeetCode #50 -# 期望输出: -# 1024.0 +// 050: Pow(x,n) — 快速幂 +// 来源: LeetCode #50 +// 期望输出: +// 1024.0 rwfunc my_pow(x:float64, n:int64) -> () { base <- x - exp = n # = 等价于 <- + exp = n // = 等价于 <- 1.0 -> result neg <- exp < 0 if (neg) { - exp = -exp # = 等价于 <- + exp = -exp // = 等价于 <- } while (exp > 0) { @@ -20,8 +20,8 @@ rwfunc my_pow(x:float64, n:int64) -> () { result_m <- result × base } - base = base × base # = 等价于 <- - base_m = base × base # = 等价于 <- + base = base × base // = 等价于 <- + base_m = base × base // = 等价于 <- exp ÷ 2 -> exp exp ÷ 2 -> exp_m } diff --git a/tutorial/08-leetcode/053_max_subarray.kv b/tutorial/08-leetcode/053_max_subarray.kv index 7dd763f6..58ca1f15 100644 --- a/tutorial/08-leetcode/053_max_subarray.kv +++ b/tutorial/08-leetcode/053_max_subarray.kv @@ -1,18 +1,18 @@ -# 053: Maximum Subarray — Kadane 算法 -# 算法: 动态规划 O(n),cur = max(x, cur+x) -# 来源: LeetCode #53 -# 期望输出: -# 6 +// 053: Maximum Subarray — Kadane 算法 +// 算法: 动态规划 O(n),cur = max(x, cur+x) +// 来源: LeetCode #53 +// 期望输出: +// 6 rwfunc max_subarray(nums:[]int64) -> () { a:[]int64 <- [-2, 1, -3, 4, -1, 2, 1, -5, 4] - n = ndarray·numel(a) # = 等价于 <- + n = ndarray·numel(a) // = 等价于 <- a[0] -> cur max <- a[0] - i = 1 # = 等价于 <- + i = 1 // = 等价于 <- while (i < n) { a[i] -> x curx <- cur + x - take_x = x > curx # = 等价于 <- + take_x = x > curx // = 等价于 <- if (take_x) { x -> cur @@ -20,7 +20,7 @@ rwfunc max_subarray(nums:[]int64) -> () { cur <- curx } - bigger = cur > max # = 等价于 <- + bigger = cur > max // = 等价于 <- if (bigger) { cur -> max diff --git a/tutorial/08-leetcode/055_jump_game.kv b/tutorial/08-leetcode/055_jump_game.kv index da8505d0..33d6806b 100644 --- a/tutorial/08-leetcode/055_jump_game.kv +++ b/tutorial/08-leetcode/055_jump_game.kv @@ -1,13 +1,13 @@ -# 055: Jump Game — 贪心最大可达位置 -# 来源: LeetCode #55 -# 期望输出: -# true -# false +// 055: Jump Game — 贪心最大可达位置 +// 来源: LeetCode #55 +// 期望输出: +// true +// false rwfunc can_jump(nums:[]int64) -> (ok:int64) { - ok = 1 # = 等价于 <- + ok = 1 // = 等价于 <- n <- ndarray·numel(nums) 0 -> reach - i = 0 # = 等价于 <- + i = 0 // = 等价于 <- while (i < n) { if (i > reach) { 0 -> ok @@ -26,7 +26,7 @@ rwfunc can_jump(nums:[]int64) -> (ok:int64) { rwfunc test() -> () { a1:[]int64 = [2, 3, 1, 1, 4] a2:[]int64 <- [3, 2, 1, 0, 4] - r1 = can_jump(a1) # = 等价于 <- + r1 = can_jump(a1) // = 等价于 <- if (r1 == 1) { println("true") } else { println("false") } r2 <- can_jump(a2) if (r2 == 1) { println("true") } else { println("false") } diff --git a/tutorial/08-leetcode/056_merge_intervals.kv b/tutorial/08-leetcode/056_merge_intervals.kv index ae046dbb..2cffb774 100644 --- a/tutorial/08-leetcode/056_merge_intervals.kv +++ b/tutorial/08-leetcode/056_merge_intervals.kv @@ -1,23 +1,23 @@ -# 056: Merge Intervals — 合并重叠区间 -# 来源: LeetCode #56 -# 用冒泡排序 + 贪心合并 -# 期望输出: -# [1,6] -# [8,10] -# [15,18] +// 056: Merge Intervals — 合并重叠区间 +// 来源: LeetCode #56 +// 用冒泡排序 + 贪心合并 +// 期望输出: +// [1,6] +// [8,10] +// [15,18] rwfunc bubble_sort(n:int64) -> () { - i = 0 # = 等价于 <- + i = 0 // = 等价于 <- while (i < n - 1) { - j = 0 # = 等价于 <- + j = 0 // = 等价于 <- while (j < n - 1 - i) { /tmp/mi[j][0] -> a /tmp/mi[j+1][0] -> b if (a > b) { - # swap start + // swap start /tmp/mi[j][1] -> a1 /tmp/mi[j+1][1] -> b1 - _ = kv·set("/tmp/mi", j, [b, b1]) # = 等价于 <- - _ = kv·set("/tmp/mi", j+1, [a, a1]) # = 等价于 <- + _ = kv·set("/tmp/mi", j, [b, b1]) // = 等价于 <- + _ = kv·set("/tmp/mi", j+1, [a, a1]) // = 等价于 <- } j + 1 -> j } @@ -27,10 +27,10 @@ rwfunc bubble_sort(n:int64) -> () { rwfunc merge(n:int64) -> (m:int64) { bubble_sort(n) - result:object = {} # = 等价于 <- - ki = 0 # = 等价于 <- + result:object = {} // = 等价于 <- + ki = 0 // = 等价于 <- /tmp/mi[0] -> cur - idx = 1 # = 等价于 <- + idx = 1 // = 等价于 <- while (idx < n) { /tmp/mi[idx] -> nxt cur[1] -> cur_end @@ -38,12 +38,12 @@ rwfunc merge(n:int64) -> (m:int64) { nxt[1] -> nxt_end if (cur_end >= nxt_start) { if (nxt_end > cur_end) { - _ = kv·set("/tmp/mr", ki, [cur[0], nxt_end]) # = 等价于 <- + _ = kv·set("/tmp/mr", ki, [cur[0], nxt_end]) // = 等价于 <- /tmp/mr[ki] -> cur } } else { _ = kv·set("/tmp/mr", ki, cur) - ki = ki + 1 # = 等价于 <- + ki = ki + 1 // = 等价于 <- nxt -> cur } idx + 1 -> idx @@ -53,13 +53,13 @@ rwfunc merge(n:int64) -> (m:int64) { } rwfunc test() -> () { - # init intervals in tmp storage + // init intervals in tmp storage _ = kv·set("/tmp/mi", 0, [1, 3]) _ = kv·set("/tmp/mi", 1, [2, 6]) _ = kv·set("/tmp/mi", 2, [8, 10]) _ = kv·set("/tmp/mi", 3, [15, 18]) cnt <- merge(4) - i = 0 # = 等价于 <- + i = 0 // = 等价于 <- while (i < cnt) { /tmp/mr[i] -> iv print("[", iv[0], ",", iv[1], "]"); println() diff --git a/tutorial/08-leetcode/058_length_last_word.kv b/tutorial/08-leetcode/058_length_last_word.kv index 1a61a314..6c447e2a 100644 --- a/tutorial/08-leetcode/058_length_last_word.kv +++ b/tutorial/08-leetcode/058_length_last_word.kv @@ -1,19 +1,19 @@ -# 058: Length of Last Word -# 来源: LeetCode #58 -# 期望输出: -# 5 +// 058: Length of Last Word +// 来源: LeetCode #58 +// 期望输出: +// 5 rwfunc last_word_len(s:[]char/utf32) -> () { - n = string·len(s) # = 等价于 <- + n = string·len(s) // = 等价于 <- n - 1 -> i count <- 0 while (i >= 0) { - c = string·char(s, i) # = 等价于 <- + c = string·char(s, i) // = 等价于 <- c == " " -> sp if (sp) { i <- -1 } else { - count = count + 1 # = 等价于 <- + count = count + 1 // = 等价于 <- } i - 1 -> i diff --git a/tutorial/08-leetcode/062_unique_paths.kv b/tutorial/08-leetcode/062_unique_paths.kv index 45ffe445..fe8352d5 100644 --- a/tutorial/08-leetcode/062_unique_paths.kv +++ b/tutorial/08-leetcode/062_unique_paths.kv @@ -1,21 +1,21 @@ -# 062: Unique Paths — DP 机器人路径数 -# 来源: LeetCode #62 -# 期望输出: -# 28 -# 3 +// 062: Unique Paths — DP 机器人路径数 +// 来源: LeetCode #62 +// 期望输出: +// 28 +// 3 rwfunc dp(m:int64, n:int64) -> (result:int64) { - i = 0 # = 等价于 <- + i = 0 // = 等价于 <- while (i < n) { - _ = kv·set("/tmp/up", i, 1) # = 等价于 <- + _ = kv·set("/tmp/up", i, 1) // = 等价于 <- i + 1 -> i } j <- 1 while (j < m) { - k = 1 # = 等价于 <- + k = 1 // = 等价于 <- while (k < n) { /tmp/up[k] -> v /tmp/up[k-1] -> prev - _ = kv·set("/tmp/up", k, prev + v) # = 等价于 <- + _ = kv·set("/tmp/up", k, prev + v) // = 等价于 <- k + 1 -> k } j + 1 -> j @@ -26,6 +26,6 @@ rwfunc dp(m:int64, n:int64) -> (result:int64) { rwfunc test() -> () { r1 <- dp(3, 7) println(r1) - r2 = dp(3, 2) # = 等价于 <- + r2 = dp(3, 2) // = 等价于 <- println(r2) } diff --git a/tutorial/08-leetcode/064_min_path_sum.kv b/tutorial/08-leetcode/064_min_path_sum.kv index 6b88bebd..357bef63 100644 --- a/tutorial/08-leetcode/064_min_path_sum.kv +++ b/tutorial/08-leetcode/064_min_path_sum.kv @@ -1,30 +1,30 @@ -# 064: Minimum Path Sum — 网格最小路径和 -# 来源: LeetCode #64 -# 期望输出: -# 7 +// 064: Minimum Path Sum — 网格最小路径和 +// 来源: LeetCode #64 +// 期望输出: +// 7 rwfunc min_path_sum() -> (result:int64) { - rows = 3 # = 等价于 <- + rows = 3 // = 等价于 <- cols <- 3 grid:[]int64 = [1, 3, 1, 1, 5, 1, 4, 2, 1] - # first row - j = 1 # = 等价于 <- + // first row + j = 1 // = 等价于 <- while (j < cols) { grid[j] <- grid[j] + grid[j-1] j + 1 -> j } - # first col and rest - r = 1 # = 等价于 <- + // first col and rest + r = 1 // = 等价于 <- while (r < rows) { - idx0 = r × cols # = 等价于 <- - idx0_m = r × cols # = 等价于 <- + idx0 = r × cols // = 等价于 <- + idx0_m = r × cols // = 等价于 <- grid[idx0] <- grid[idx0] + grid[idx0-cols] - c = 1 # = 等价于 <- + c = 1 // = 等价于 <- while (c < cols) { - idx = r × cols + c # = 等价于 <- - idx_m = r × cols + c # = 等价于 <- + idx = r × cols + c // = 等价于 <- + idx_m = r × cols + c // = 等价于 <- up <- grid[idx-cols] - left = grid[idx-1] # = 等价于 <- - min = up # = 等价于 <- + left = grid[idx-1] // = 等价于 <- + min = up // = 等价于 <- if (left < up) { left -> min } grid[idx] <- grid[idx] + min c + 1 -> c diff --git a/tutorial/08-leetcode/066_plus_one.kv b/tutorial/08-leetcode/066_plus_one.kv index e0009256..2995fb81 100644 --- a/tutorial/08-leetcode/066_plus_one.kv +++ b/tutorial/08-leetcode/066_plus_one.kv @@ -1,25 +1,25 @@ -# 066: Plus One — 数组表示的大整数加一 -# 算法: 从右向左进位 -# 来源: LeetCode #66 -# 期望输出: -# 1 -# 2 -# 4 -# 0 -# 0 -# 0 +// 066: Plus One — 数组表示的大整数加一 +// 算法: 从右向左进位 +// 来源: LeetCode #66 +// 期望输出: +// 1 +// 2 +// 4 +// 0 +// 0 +// 0 rwfunc plus_one() -> () { a:[]int64 <- [1, 2, 3] - n = ndarray·numel(a) # = 等价于 <- + n = ndarray·numel(a) // = 等价于 <- n - 1 -> i carry <- 1 while (i >= 0) { - d = a[i] # = 等价于 <- + d = a[i] // = 等价于 <- d + carry -> s overflow <- s == 10 if (overflow) { - carry = 0 # = 等价于 <- + carry = 0 // = 等价于 <- a[i] <- 0 } else { a[i] <- s @@ -27,11 +27,11 @@ rwfunc plus_one() -> () { i <- -1 } - i = i - 1 # = 等价于 <- + i = i - 1 // = 等价于 <- } carry == 1 -> need_extend len_val <- n - j = 0 # = 等价于 <- + j = 0 // = 等价于 <- while (j < n) { a[j] -> v println(v) @@ -40,14 +40,14 @@ rwfunc plus_one() -> () { } rwfunc plus_one_nines() -> () { - a:[]int64 = [9, 9, 9] # = 等价于 <- + a:[]int64 = [9, 9, 9] // = 等价于 <- ndarray·numel(a) -> n i <- n - 1 - carry = 1 # = 等价于 <- + carry = 1 // = 等价于 <- while (i >= 0) { a[i] -> d s <- d + carry - overflow = s == 10 # = 等价于 <- + overflow = s == 10 // = 等价于 <- if (overflow) { a[i] <- 0 @@ -55,14 +55,14 @@ rwfunc plus_one_nines() -> () { } else { a[i] <- s carry <- 0 - i = -1 # = 等价于 <- + i = -1 // = 等价于 <- } i - 1 -> i } j <- 0 while (j < n) { - v = a[j] # = 等价于 <- + v = a[j] // = 等价于 <- println(v) j + 1 -> j } diff --git a/tutorial/08-leetcode/067_add_binary.kv b/tutorial/08-leetcode/067_add_binary.kv index fac20a83..7669ffbd 100644 --- a/tutorial/08-leetcode/067_add_binary.kv +++ b/tutorial/08-leetcode/067_add_binary.kv @@ -1,27 +1,27 @@ -# 067: Add Binary — 二进制字符串加法 -# 来源: LeetCode #67 -# 期望输出: -# 100 -# 10101 +// 067: Add Binary — 二进制字符串加法 +// 来源: LeetCode #67 +// 期望输出: +// 100 +// 10101 rwfunc add_binary(a:[]char/utf32, b:[]char/utf32) -> () { - na = string·len(a) # = 等价于 <- + na = string·len(a) // = 等价于 <- nb <- string·len(b) - carry = 0 # = 等价于 <- - i = na - 1 # = 等价于 <- + carry = 0 // = 等价于 <- + i = na - 1 // = 等价于 <- j <- nb - 1 - result = "" # = 等价于 <- + result = "" // = 等价于 <- while (i >= 0 || j >= 0 || carry > 0) { sum <- carry if (i >= 0) { if (a[i] == "1") { sum + 1 -> sum } - i = i - 1 # = 等价于 <- + i = i - 1 // = 等价于 <- } if (j >= 0) { if (b[j] == "1") { 1 + sum -> sum } j - 1 -> j } if (sum % 2 == 1) { - result = "1" + result # = 等价于 <- + result = "1" + result // = 等价于 <- } else { "0" + result -> result } diff --git a/tutorial/08-leetcode/069_sqrt.kv b/tutorial/08-leetcode/069_sqrt.kv index bbfdf03f..57a2d342 100644 --- a/tutorial/08-leetcode/069_sqrt.kv +++ b/tutorial/08-leetcode/069_sqrt.kv @@ -1,22 +1,22 @@ -# 069: Sqrt(x) — 二分求平方根 -# 来源: LeetCode #69 -# 期望输出: -# 2 +// 069: Sqrt(x) — 二分求平方根 +// 来源: LeetCode #69 +// 期望输出: +// 2 rwfunc my_sqrt(x:int64) -> () { lo <- 0 - hi = x # = 等价于 <- + hi = x // = 等价于 <- 0 -> ans while (lo <= hi) { s <- lo + hi - mid = s ÷ 2 # = 等价于 <- - mid_m = s ÷ 2 # = 等价于 <- + mid = s ÷ 2 // = 等价于 <- + mid_m = s ÷ 2 // = 等价于 <- mid × mid -> sq mid × mid -> sq_m ok <- sq <= x ok_m <- sq ≤ x if (ok) { - ans = mid # = 等价于 <- + ans = mid // = 等价于 <- mid + 1 -> lo } else { hi <- mid - 1 diff --git a/tutorial/08-leetcode/070_climb_stairs.kv b/tutorial/08-leetcode/070_climb_stairs.kv index 256e157f..060ba359 100644 --- a/tutorial/08-leetcode/070_climb_stairs.kv +++ b/tutorial/08-leetcode/070_climb_stairs.kv @@ -1,16 +1,16 @@ -# 070: Climbing Stairs — 斐波那契爬楼梯 -# 来源: LeetCode #70 -# 期望输出: -# 8 +// 070: Climbing Stairs — 斐波那契爬楼梯 +// 来源: LeetCode #70 +// 期望输出: +// 8 rwfunc climb(n:int64) -> () { - a = 1 # = 等价于 <- + a = 1 // = 等价于 <- 1 -> b i <- 2 while (i <= n) { - c = a + b # = 等价于 <- + c = a + b // = 等价于 <- b -> a b <- c - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } println(c) } diff --git a/tutorial/08-leetcode/075_sort_colors.kv b/tutorial/08-leetcode/075_sort_colors.kv index 4699004d..8e79f98a 100644 --- a/tutorial/08-leetcode/075_sort_colors.kv +++ b/tutorial/08-leetcode/075_sort_colors.kv @@ -1,18 +1,18 @@ -# 075: Sort Colors — 荷兰国旗三指针 -# 来源: LeetCode #75 -# 期望输出: -# 0 -# 0 -# 1 -# 1 -# 2 -# 2 +// 075: Sort Colors — 荷兰国旗三指针 +// 来源: LeetCode #75 +// 期望输出: +// 0 +// 0 +// 1 +// 1 +// 2 +// 2 rwfunc sort_colors() -> () { nums:[]int64 = [2, 0, 2, 1, 1, 0] - n = ndarray·numel(nums) # = 等价于 <- - lo = 0 # = 等价于 <- + n = ndarray·numel(nums) // = 等价于 <- + lo = 0 // = 等价于 <- mid <- 0 - hi = n - 1 # = 等价于 <- + hi = n - 1 // = 等价于 <- while (mid <= hi) { nums[mid] -> v if (v == 0) { @@ -32,7 +32,7 @@ rwfunc sort_colors() -> () { hi - 1 -> hi } } - i = 0 # = 等价于 <- + i = 0 // = 等价于 <- while (i < n) { println(nums[i]) i + 1 -> i diff --git a/tutorial/08-leetcode/083_remove_dup_list.kv b/tutorial/08-leetcode/083_remove_dup_list.kv index 30b76d86..dad6262b 100644 --- a/tutorial/08-leetcode/083_remove_dup_list.kv +++ b/tutorial/08-leetcode/083_remove_dup_list.kv @@ -1,19 +1,19 @@ -# 083: Remove Duplicates from Sorted List — 链表去重(dict 字面量建表 + next 改写) -# 来源: LeetCode #83 -# 期望输出: -# 1 -# 2 -# 1 -# 2 -# 3 +// 083: Remove Duplicates from Sorted List — 链表去重(dict 字面量建表 + next 改写) +// 来源: LeetCode #83 +// 期望输出: +// 1 +// 2 +// 1 +// 2 +// 3 rwfunc build() -> () { - /e0 = { val=1; next="/e1" } # = 等价于 <- + /e0 = { val=1; next="/e1" } // = 等价于 <- /e1 <- { val=1; next="/e2" } { val=2; next="" } -> /e2 - /f0 = { val=1; next="/f1" } # = 等价于 <- + /f0 = { val=1; next="/f1" } // = 等价于 <- /f1 <- { val=1; next="/f2" } { val=2; next="/f3" } -> /f2 - /f3 = { val=3; next="/f4" } # = 等价于 <- + /f3 = { val=3; next="/f4" } // = 等价于 <- /f4 <- { val=3; next="" } } @@ -21,7 +21,7 @@ rwfunc dedup(head:[]char/utf32) -> () { head -> cur while (cur != "") { cur·next -> nxt - advance = true # = 等价于 <- + advance = true // = 等价于 <- if (nxt != "") { cur·val -> v diff --git a/tutorial/08-leetcode/088_merge_sorted.kv b/tutorial/08-leetcode/088_merge_sorted.kv index 1f854a55..9c78d86f 100644 --- a/tutorial/08-leetcode/088_merge_sorted.kv +++ b/tutorial/08-leetcode/088_merge_sorted.kv @@ -1,30 +1,30 @@ -# 088: Merge Sorted Array — 合并两个有序数组 -# 算法: 双指针从后向前合并 -# 来源: LeetCode #88 -# 期望输出: -# 1 -# 2 -# 2 -# 3 -# 5 -# 6 +// 088: Merge Sorted Array — 合并两个有序数组 +// 算法: 双指针从后向前合并 +// 来源: LeetCode #88 +// 期望输出: +// 1 +// 2 +// 2 +// 3 +// 5 +// 6 rwfunc merge() -> () { [1, 2, 3, 0, 0, 0] -> a:[]int64 m <- 3 - b:[]int64 = [2, 5, 6] # = 等价于 <- + b:[]int64 = [2, 5, 6] // = 等价于 <- 3 -> n i <- m - 1 - j = n - 1 # = 等价于 <- + j = n - 1 // = 等价于 <- m + n -> total k <- total - 1 while (j >= 0) { - i_ok = i >= 0 # = 等价于 <- - i_ok_m = i ≥ 0 # = 等价于 <- + i_ok = i >= 0 // = 等价于 <- + i_ok_m = i ≥ 0 // = 等价于 <- if (i_ok) { a[i] -> av bv <- b[j] - a_bigger = av > bv # = 等价于 <- + a_bigger = av > bv // = 等价于 <- if (a_bigger) { a[k] <- av @@ -34,14 +34,14 @@ rwfunc merge() -> () { j <- j - 1 } } else { - bv2 = b[j] # = 等价于 <- + bv2 = b[j] // = 等价于 <- a[k] <- bv2 j - 1 -> j } k <- k - 1 } - x = 0 # = 等价于 <- + x = 0 // = 等价于 <- while (x < 6) { a[x] -> v println(v) diff --git a/tutorial/08-leetcode/089_gray_code.kv b/tutorial/08-leetcode/089_gray_code.kv index 2de07fd8..9a4f023b 100644 --- a/tutorial/08-leetcode/089_gray_code.kv +++ b/tutorial/08-leetcode/089_gray_code.kv @@ -1,20 +1,20 @@ -# 089: Gray Code — 生成 n 位格雷码序列 -# 来源: LeetCode #89 -# 公式: G(i) = i ^ (i >> 1) -# 期望输出: -# 0 -# 1 -# 3 -# 2 +// 089: Gray Code — 生成 n 位格雷码序列 +// 来源: LeetCode #89 +// 公式: G(i) = i ^ (i >> 1) +// 期望输出: +// 0 +// 1 +// 3 +// 2 rwfunc gray_code(n:int64) -> () { - total = 1 # = 等价于 <- - k = 0 # = 等价于 <- + total = 1 // = 等价于 <- + k = 0 // = 等价于 <- while (k < n) { total <- total × 2 total_m <- total × 2 k + 1 -> k } - i = 0 # = 等价于 <- + i = 0 // = 等价于 <- while (i < total) { g <- i ^ (i ÷ 2) g_m <- i ^ (i ÷ 2) diff --git a/tutorial/08-leetcode/094_inorder_traversal.kv b/tutorial/08-leetcode/094_inorder_traversal.kv index 21e83cf9..6de0ec1c 100644 --- a/tutorial/08-leetcode/094_inorder_traversal.kv +++ b/tutorial/08-leetcode/094_inorder_traversal.kv @@ -1,9 +1,9 @@ -# 094: Binary Tree Inorder Traversal — 二叉树中序遍历 (迭代栈) -# 来源: LeetCode #94 -# 期望输出: -# 2 -# 1 -# 3 +// 094: Binary Tree Inorder Traversal — 二叉树中序遍历 (迭代栈) +// 来源: LeetCode #94 +// 期望输出: +// 2 +// 1 +// 3 rwfunc build_tree() -> () { /t0 = { val=1; left="/t1"; right="/t2" } /t1 <- { val=2; left=""; right="" } @@ -11,9 +11,9 @@ rwfunc build_tree() -> () { } rwfunc inorder(root:[]char/utf32) -> () { - # iterative stack simulation - si = 0 # = 等价于 <- - stack:[int64]·[]char/utf32 = {} # = 等价于 <- + // iterative stack simulation + si = 0 // = 等价于 <- + stack:[int64]·[]char/utf32 = {} // = 等价于 <- cur <- root while (cur != "" || si > 0) { while (cur != "") { diff --git a/tutorial/08-leetcode/100_same_tree.kv b/tutorial/08-leetcode/100_same_tree.kv index 6b17c14a..c7b44b5b 100644 --- a/tutorial/08-leetcode/100_same_tree.kv +++ b/tutorial/08-leetcode/100_same_tree.kv @@ -1,8 +1,8 @@ -# 100: Same Tree — 判断两棵二叉树是否相同 -# 来源: LeetCode #100 -# 期望输出: -# true -# false +// 100: Same Tree — 判断两棵二叉树是否相同 +// 来源: LeetCode #100 +// 期望输出: +// true +// false rwfunc build() -> () { /t0 <- { val=1; left="/t1"; right="/t2" } { val=2; left=""; right="" } -> /t1 diff --git a/tutorial/08-leetcode/104_max_tree_depth.kv b/tutorial/08-leetcode/104_max_tree_depth.kv index 619b587f..721dccb0 100644 --- a/tutorial/08-leetcode/104_max_tree_depth.kv +++ b/tutorial/08-leetcode/104_max_tree_depth.kv @@ -1,19 +1,19 @@ -# 104: Maximum Depth of Binary Tree — 二叉树最大深度 -# 来源: LeetCode #104 -# 期望输出: -# 3 +// 104: Maximum Depth of Binary Tree — 二叉树最大深度 +// 来源: LeetCode #104 +// 期望输出: +// 3 rwfunc build_tree() -> () { /t0 = { val=3; left="/t1"; right="/t2" } { val=9; left=""; right="" } -> /t1 /t2 <- { val=20; left="/t3"; right="/t4" } - /t3 = { val=15; left=""; right="" } # = 等价于 <- + /t3 = { val=15; left=""; right="" } // = 等价于 <- { val=7; left=""; right="" } -> /t4 } rwfunc max_depth(root:[]char/utf32) -> (depth:int64) { if (root == "") { 0 -> depth } else { - ld = max_depth(root·left) # = 等价于 <- + ld = max_depth(root·left) // = 等价于 <- rd <- max_depth(root·right) if (ld > rd) { ld + 1 -> depth } else { depth <- rd + 1 } diff --git a/tutorial/08-leetcode/118_pascal_triangle.kv b/tutorial/08-leetcode/118_pascal_triangle.kv index 5f22a214..62921b47 100644 --- a/tutorial/08-leetcode/118_pascal_triangle.kv +++ b/tutorial/08-leetcode/118_pascal_triangle.kv @@ -1,32 +1,32 @@ -# 118: Pascal's Triangle — 生成杨辉三角 -# 来源: LeetCode #118 -# 逐行计算并打印 -# 期望输出: -# 1 -# 1 -# 1 -# 1 -# 2 -# 1 -# 1 -# 3 -# 3 -# 1 -# 1 -# 4 -# 6 -# 4 -# 1 +// 118: Pascal's Triangle — 生成杨辉三角 +// 来源: LeetCode #118 +// 逐行计算并打印 +// 期望输出: +// 1 +// 1 +// 1 +// 1 +// 2 +// 1 +// 1 +// 3 +// 3 +// 1 +// 1 +// 4 +// 6 +// 4 +// 1 rwfunc generate(num_rows:int64) -> () { - # store prev row in dict + // store prev row in dict _ = kv·set("/tmp/pt", 0, 1) println(1) if (num_rows == 1) { } - r = 1 # = 等价于 <- + r = 1 // = 等价于 <- while (r < num_rows) { println(1) _ = kv·set("/tmp/cur", 0, 1) - i = 1 # = 等价于 <- + i = 1 // = 等价于 <- while (i < r) { /tmp/pt[i-1] -> a /tmp/pt[i] -> b @@ -37,8 +37,8 @@ rwfunc generate(num_rows:int64) -> () { } println(1) _ = kv·set("/tmp/cur", r, 1) - # copy cur to pt - k = 0 # = 等价于 <- + // copy cur to pt + k = 0 // = 等价于 <- while (k <= r) { /tmp/cur[k] -> val _ = kv·set("/tmp/pt", k, val) diff --git a/tutorial/08-leetcode/121_buy_sell_stock.kv b/tutorial/08-leetcode/121_buy_sell_stock.kv index d2ffe14d..fb4635b6 100644 --- a/tutorial/08-leetcode/121_buy_sell_stock.kv +++ b/tutorial/08-leetcode/121_buy_sell_stock.kv @@ -1,23 +1,23 @@ -# 121: Best Time to Buy and Sell Stock — 一次交易最大利润 -# 算法: 遍历记录最低买入价,计算最大利润 -# 来源: LeetCode #121 -# 期望输出: -# 5 +// 121: Best Time to Buy and Sell Stock — 一次交易最大利润 +// 算法: 遍历记录最低买入价,计算最大利润 +// 来源: LeetCode #121 +// 期望输出: +// 5 rwfunc max_profit() -> () { - a:[]int64 = [7, 1, 5, 3, 6, 4] # = 等价于 <- + a:[]int64 = [7, 1, 5, 3, 6, 4] // = 等价于 <- ndarray·numel(a) -> n min_price <- a[0] - max_profit = 0 # = 等价于 <- + max_profit = 0 // = 等价于 <- 1 -> i while (i < n) { price <- a[i] - new_min = price < min_price # = 等价于 <- + new_min = price < min_price // = 等价于 <- if (new_min) { price -> min_price } else { profit <- price - min_price - bigger = profit > max_profit # = 等价于 <- + bigger = profit > max_profit // = 等价于 <- if (bigger) { profit -> max_profit diff --git a/tutorial/08-leetcode/125_valid_palindrome.kv b/tutorial/08-leetcode/125_valid_palindrome.kv index 29ead612..40285bcd 100644 --- a/tutorial/08-leetcode/125_valid_palindrome.kv +++ b/tutorial/08-leetcode/125_valid_palindrome.kv @@ -1,23 +1,23 @@ -# 125: Valid Palindrome — 双指针判断回文(用数组模拟字符) -# 来源: LeetCode #125 -# 期望输出: -# 1 -# 0 -# 用整数数组模拟字符串,1='a', 2='b', etc. +// 125: Valid Palindrome — 双指针判断回文(用数组模拟字符) +// 来源: LeetCode #125 +// 期望输出: +// 1 +// 0 +// 用整数数组模拟字符串,1='a', 2='b', etc. rwfunc is_pal() -> () { - s:[]int64 = [1, 2, 1] # = 等价于 <- + s:[]int64 = [1, 2, 1] // = 等价于 <- ndarray·numel(s) -> n l <- 0 - r = n - 1 # = 等价于 <- + r = n - 1 // = 等价于 <- 1 -> ok while (l < r) { lc <- s[l] - rc = s[r] # = 等价于 <- + rc = s[r] // = 等价于 <- lc == rc -> match if (match) { l <- l + 1 - r = r - 1 # = 等价于 <- + r = r - 1 // = 等价于 <- } else { 0 -> ok l <- n @@ -27,19 +27,19 @@ rwfunc is_pal() -> () { } rwfunc not_pal() -> () { - s:[]int64 = [1, 2] # = 等价于 <- + s:[]int64 = [1, 2] // = 等价于 <- ndarray·numel(s) -> n l <- 0 - r = n - 1 # = 等价于 <- + r = n - 1 // = 等价于 <- 1 -> ok while (l < r) { lc <- s[l] - rc = s[r] # = 等价于 <- + rc = s[r] // = 等价于 <- lc == rc -> match if (match) { l <- l + 1 - r = r - 1 # = 等价于 <- + r = r - 1 // = 等价于 <- } else { 0 -> ok l <- n diff --git a/tutorial/08-leetcode/125_valid_palindrome_str.kv b/tutorial/08-leetcode/125_valid_palindrome_str.kv index 68335679..cfab721e 100644 --- a/tutorial/08-leetcode/125_valid_palindrome_str.kv +++ b/tutorial/08-leetcode/125_valid_palindrome_str.kv @@ -1,23 +1,23 @@ -# 125: Valid Palindrome — 用 char 双指针 -# 来源: LeetCode #125 -# 期望输出: -# 1 -# 0 +// 125: Valid Palindrome — 用 char 双指针 +// 来源: LeetCode #125 +// 期望输出: +// 1 +// 0 rwfunc is_pal(s:[]char/utf32) -> () { - n = string·len(s) # = 等价于 <- + n = string·len(s) // = 等价于 <- 0 -> l r <- n - 1 - ok = 1 # = 等价于 <- + ok = 1 // = 等价于 <- while (l < r) { string·char(s, l) -> lc rc <- string·char(s, r) - match = lc == rc # = 等价于 <- + match = lc == rc // = 等价于 <- if (match) { l + 1 -> l r <- r - 1 } else { - ok = 0 # = 等价于 <- + ok = 0 // = 等价于 <- n -> l } } diff --git a/tutorial/08-leetcode/136_single_number.kv b/tutorial/08-leetcode/136_single_number.kv index ff1981a0..379b3bad 100644 --- a/tutorial/08-leetcode/136_single_number.kv +++ b/tutorial/08-leetcode/136_single_number.kv @@ -1,15 +1,15 @@ -# 136: Single Number — 找出只出现一次的数 -# 算法: XOR 异或(所有成对出现的数互相抵消) -# 来源: LeetCode #136 -# 期望输出: -# 4 +// 136: Single Number — 找出只出现一次的数 +// 算法: XOR 异或(所有成对出现的数互相抵消) +// 来源: LeetCode #136 +// 期望输出: +// 4 rwfunc single_number() -> () { a:[]int64 <- [4, 1, 2, 1, 2] - n = ndarray·numel(a) # = 等价于 <- + n = ndarray·numel(a) // = 等价于 <- a[0] -> result i <- 1 while (i < n) { - x = a[i] # = 等价于 <- + x = a[i] // = 等价于 <- result ^ x -> result i <- i + 1 } diff --git a/tutorial/08-leetcode/141_linked_list_cycle.kv b/tutorial/08-leetcode/141_linked_list_cycle.kv index b698277b..ab3bd491 100644 --- a/tutorial/08-leetcode/141_linked_list_cycle.kv +++ b/tutorial/08-leetcode/141_linked_list_cycle.kv @@ -1,25 +1,25 @@ -# 141: Linked List Cycle — 快慢指针 -# 来源: LeetCode #141 -# 期望输出: -# 1 -# 0 +// 141: Linked List Cycle — 快慢指针 +// 来源: LeetCode #141 +// 期望输出: +// 1 +// 0 rwfunc has_cycle(head:[]char/utf32) -> (result:int64) { - result = 0 # = 等价于 <- + result = 0 // = 等价于 <- head -> slow fast <- head while (fast != "") { - slow = slow·next # = 等价于 <- + slow = slow·next // = 等价于 <- fast·next -> n1 at_end <- n1 == "" if (at_end) { - fast = "" # = 等价于 <- + fast = "" // = 等价于 <- } else { n1·next -> fast match <- slow == fast if (match) { - result = 1 # = 等价于 <- + result = 1 // = 等价于 <- "" -> fast } } @@ -28,19 +28,19 @@ rwfunc has_cycle(head:[]char/utf32) -> (result:int64) { rwfunc build_cycle() -> () { { val=3; next="/c1" } -> /c0 - /c1 = { val=2; next="/c2" } # = 等价于 <- + /c1 = { val=2; next="/c2" } // = 等价于 <- /c2 <- { val=0; next="/c0" } } rwfunc build_no_cycle() -> () { - /n0 = { val=1; next="/n1" } # = 等价于 <- + /n0 = { val=1; next="/n1" } // = 等价于 <- { val=2; next="" } -> /n1 } rwfunc test() -> () { build_cycle() - r1 = has_cycle("/c0") # = 等价于 <- + r1 = has_cycle("/c0") // = 等价于 <- println(r1) build_no_cycle() has_cycle("/n0") -> r2 diff --git a/tutorial/08-leetcode/153_find_min_rotated.kv b/tutorial/08-leetcode/153_find_min_rotated.kv index 6aec79db..9a8d869b 100644 --- a/tutorial/08-leetcode/153_find_min_rotated.kv +++ b/tutorial/08-leetcode/153_find_min_rotated.kv @@ -1,23 +1,23 @@ -# 153: Find Minimum in Rotated Sorted Array -# 来源: LeetCode #153 -# 期望输出: -# 0 +// 153: Find Minimum in Rotated Sorted Array +// 来源: LeetCode #153 +// 期望输出: +// 0 rwfunc find_min() -> () { a:[]int64 <- [4, 5, 6, 7, 0, 1, 2] - n = ndarray·numel(a) # = 等价于 <- + n = ndarray·numel(a) // = 等价于 <- 0 -> lo hi <- n - 1 while (lo < hi) { - s = lo + hi # = 等价于 <- + s = lo + hi // = 等价于 <- s ÷ 2 -> mid mv <- a[mid] - rv = a[hi] # = 等价于 <- + rv = a[hi] // = 等价于 <- mv < rv -> ok if (ok) { hi <- mid } else { - lo = mid + 1 # = 等价于 <- + lo = mid + 1 // = 等价于 <- } } a[lo] -> ans diff --git a/tutorial/08-leetcode/160_intersection_list.kv b/tutorial/08-leetcode/160_intersection_list.kv index 47c830a8..5e151246 100644 --- a/tutorial/08-leetcode/160_intersection_list.kv +++ b/tutorial/08-leetcode/160_intersection_list.kv @@ -1,26 +1,26 @@ -# 160: Intersection of Two Linked Lists — 找两个链表的交点 -# 来源: LeetCode #160 -# 双指针法: pA 走完走 B, pB 走完走 A, 相遇即交点 -# 期望输出: -# 8 +// 160: Intersection of Two Linked Lists — 找两个链表的交点 +// 来源: LeetCode #160 +// 双指针法: pA 走完走 B, pB 走完走 A, 相遇即交点 +// 期望输出: +// 8 rwfunc build_lists() -> () { - # common tail: 8→4→5 - /t8 = { val=8; next="/t4" } # = 等价于 <- + // common tail: 8→4→5 + /t8 = { val=8; next="/t4" } // = 等价于 <- /t4 <- { val=4; next="/t5" } { val=5; next="" } -> /t5 - # list A: 4→1→/t8 - /a0 = { val=4; next="/a1" } # = 等价于 <- + // list A: 4→1→/t8 + /a0 = { val=4; next="/a1" } // = 等价于 <- { val=1; next="/t8" } -> /a1 - # list B: 5→6→1→/t8 - /b0 = { val=5; next="/b1" } # = 等价于 <- + // list B: 5→6→1→/t8 + /b0 = { val=5; next="/b1" } // = 等价于 <- /b1 <- { val=6; next="/b2" } { val=1; next="/t8" } -> /b2 } rwfunc get_intersection(ha:[]char/utf32, hb:[]char/utf32) -> () { - pa = ha # = 等价于 <- + pa = ha // = 等价于 <- pb <- hb - switch_a = 0 # = 等价于 <- + switch_a = 0 // = 等价于 <- switch_b <- 0 while (pa != pb) { pa·next -> nxt diff --git a/tutorial/08-leetcode/162_find_peak.kv b/tutorial/08-leetcode/162_find_peak.kv index fbcb64b5..3ccc279a 100644 --- a/tutorial/08-leetcode/162_find_peak.kv +++ b/tutorial/08-leetcode/162_find_peak.kv @@ -1,24 +1,24 @@ -# 162: Find Peak Element — 二分找峰值 -# 来源: LeetCode #162 -# 期望输出: -# 2 +// 162: Find Peak Element — 二分找峰值 +// 来源: LeetCode #162 +// 期望输出: +// 2 rwfunc find_peak() -> () { a:[]int64 <- [1, 2, 3, 1] - n = ndarray·numel(a) # = 等价于 <- + n = ndarray·numel(a) // = 等价于 <- 0 -> lo hi <- n - 1 while (lo < hi) { - s = lo + hi # = 等价于 <- + s = lo + hi // = 等价于 <- s ÷ 2 -> mid s ÷ 2 -> mid_m mv <- a[mid] - nv = a[mid + 1] # = 等价于 <- + nv = a[mid + 1] // = 等价于 <- mv < nv -> up if (up) { lo <- mid + 1 } else { - hi = mid # = 等价于 <- + hi = mid // = 等价于 <- } } println(lo) diff --git a/tutorial/08-leetcode/167_two_sum_ii.kv b/tutorial/08-leetcode/167_two_sum_ii.kv index 8a1de49c..4e2b6006 100644 --- a/tutorial/08-leetcode/167_two_sum_ii.kv +++ b/tutorial/08-leetcode/167_two_sum_ii.kv @@ -1,31 +1,31 @@ -# 167: Two Sum II — 有序数组双指针 -# 来源: LeetCode #167 -# 期望输出: -# [ 1 , 2 ] +// 167: Two Sum II — 有序数组双指针 +// 来源: LeetCode #167 +// 期望输出: +// [ 1 , 2 ] rwfunc two_sum_ii() -> () { [2, 7, 11, 15] -> a:[]int64 target <- 9 - n = ndarray·numel(a) # = 等价于 <- + n = ndarray·numel(a) // = 等价于 <- 0 -> l r <- n - 1 while (l < r) { - lv = a[l] # = 等价于 <- + lv = a[l] // = 等价于 <- a[r] -> rv s <- lv + rv - hit = s == target # = 等价于 <- + hit = s == target // = 等价于 <- if (hit) { l + 1 -> i1 i2 <- r + 1 println("[", i1, ",", i2, "]") - l = n # = 等价于 <- + l = n // = 等价于 <- } else { s < target -> lt if (lt) { l <- l + 1 } else { - r = r - 1 # = 等价于 <- + r = r - 1 // = 等价于 <- } } } diff --git a/tutorial/08-leetcode/168_excel_title.kv b/tutorial/08-leetcode/168_excel_title.kv index e29730d4..8c868c3b 100644 --- a/tutorial/08-leetcode/168_excel_title.kv +++ b/tutorial/08-leetcode/168_excel_title.kv @@ -1,23 +1,23 @@ -# 168: Excel Sheet Column Title — 数字转26进制列名 -# 来源: LeetCode #168 -# 期望输出: -# 65 -# 66 +// 168: Excel Sheet Column Title — 数字转26进制列名 +// 来源: LeetCode #168 +// 期望输出: +// 65 +// 66 rwfunc convert(n:int64) -> () { - # Build reversed chars into array, then print in reverse + // Build reversed chars into array, then print in reverse [0, 0, 0, 0, 0] -> a:[]int64 idx <- 0 - num = n # = 等价于 <- + num = n // = 等价于 <- while (num > 0) { num - 1 -> n1 r <- n1 % 26 - ch = 65 + r # = 等价于 <- + ch = 65 + r // = 等价于 <- a[idx] <- ch idx + 1 -> idx num <- n1 ÷ 26 num_m <- n1 ÷ 26 } - k = idx - 1 # = 等价于 <- + k = idx - 1 // = 等价于 <- while (k >= 0) { a[k] -> v println(v) diff --git a/tutorial/08-leetcode/169_majority.kv b/tutorial/08-leetcode/169_majority.kv index 1d650e52..eec61be7 100644 --- a/tutorial/08-leetcode/169_majority.kv +++ b/tutorial/08-leetcode/169_majority.kv @@ -1,23 +1,23 @@ -# 169: Majority Element — Boyer-Moore 投票算法 -# 算法: 计数抵消,多数元素必然存活 -# 来源: LeetCode #169 -# 期望输出: -# 3 +// 169: Majority Element — Boyer-Moore 投票算法 +// 算法: 计数抵消,多数元素必然存活 +// 来源: LeetCode #169 +// 期望输出: +// 3 rwfunc majority() -> () { - a:[]int64 = [3, 2, 3] # = 等价于 <- + a:[]int64 = [3, 2, 3] // = 等价于 <- ndarray·numel(a) -> n candidate <- a[0] - count = 1 # = 等价于 <- + count = 1 // = 等价于 <- 1 -> i while (i < n) { x <- a[i] - reset = count == 0 # = 等价于 <- + reset = count == 0 // = 等价于 <- if (reset) { x -> candidate count <- 1 } else { - match = x == candidate # = 等价于 <- + match = x == candidate // = 等价于 <- if (match) { count + 1 -> count @@ -26,7 +26,7 @@ rwfunc majority() -> () { } } - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } println(candidate) } diff --git a/tutorial/08-leetcode/171_excel_column.kv b/tutorial/08-leetcode/171_excel_column.kv index e7d74e4a..2e7886e7 100644 --- a/tutorial/08-leetcode/171_excel_column.kv +++ b/tutorial/08-leetcode/171_excel_column.kv @@ -1,19 +1,19 @@ -# 171: Excel Sheet Column Number — 26进制转数字 -# 来源: LeetCode #171 -# 期望输出: -# 28 +// 171: Excel Sheet Column Number — 26进制转数字 +// 来源: LeetCode #171 +// 期望输出: +// 28 rwfunc title_to_num(s:[]char/utf32) -> () { string·len(s) -> n result <- 0 - i = 0 # = 等价于 <- + i = 0 // = 等价于 <- while (i < n) { result × 26 -> r26 result × 26 -> r26_m c <- string·char(s, i) - v = string·ord(c) - 65 # = 等价于 <- + v = string·ord(c) - 65 // = 等价于 <- v + 1 -> d result <- r26 + d - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } println(result) } diff --git a/tutorial/08-leetcode/172_fact_zeroes.kv b/tutorial/08-leetcode/172_fact_zeroes.kv index 2a3c929c..dc40b84e 100644 --- a/tutorial/08-leetcode/172_fact_zeroes.kv +++ b/tutorial/08-leetcode/172_fact_zeroes.kv @@ -1,14 +1,14 @@ -# 172: Factorial Trailing Zeroes — n! 尾部零的个数 -# 来源: LeetCode #172 -# 期望输出: -# 1 +// 172: Factorial Trailing Zeroes — n! 尾部零的个数 +// 来源: LeetCode #172 +// 期望输出: +// 1 rwfunc trailing(n:int64) -> () { n -> nv 0 -> count while (nv >= 5) { nv <- nv ÷ 5 nv_m <- nv ÷ 5 - count = count + nv # = 等价于 <- + count = count + nv // = 等价于 <- } println(count) } diff --git a/tutorial/08-leetcode/189_rotate_array.kv b/tutorial/08-leetcode/189_rotate_array.kv index 04ff7926..6b32a9ab 100644 --- a/tutorial/08-leetcode/189_rotate_array.kv +++ b/tutorial/08-leetcode/189_rotate_array.kv @@ -1,14 +1,14 @@ -# 189: Rotate Array — 三次反转旋转 -# 算法: reverse(0,n-1), reverse(0,k-1), reverse(k,n-1) -# 来源: LeetCode #189 -# 期望输出: -# 5 -# 6 -# 7 -# 1 -# 2 -# 3 -# 4 +// 189: Rotate Array — 三次反转旋转 +// 算法: reverse(0,n-1), reverse(0,k-1), reverse(k,n-1) +// 来源: LeetCode #189 +// 期望输出: +// 5 +// 6 +// 7 +// 1 +// 2 +// 3 +// 4 rwfunc swap(a_len:int64, lo:int64, hi:int64) -> () { a_len -> a_lenv lo -> lov @@ -18,50 +18,50 @@ rwfunc swap(a_len:int64, lo:int64, hi:int64) -> () { u <- a[hiv] a[lov] <- u a[hiv] <- t - lov = lov + 1 # = 等价于 <- + lov = lov + 1 // = 等价于 <- hiv - 1 -> hiv } } rwfunc rotate() -> () { a:[]int64 <- [1, 2, 3, 4, 5, 6, 7] - n = ndarray·numel(a) # = 等价于 <- + n = ndarray·numel(a) // = 等价于 <- 3 -> k k_eff <- k % n - # reverse all - lo = 0 # = 等价于 <- + // reverse all + lo = 0 // = 等价于 <- n - 1 -> hi while (lo < hi) { t <- a[lo] - u = a[hi] # = 等价于 <- + u = a[hi] // = 等价于 <- a[lo] <- u a[hi] <- t lo + 1 -> lo hi <- hi - 1 } - # reverse first k - lo2 = 0 # = 等价于 <- + // reverse first k + lo2 = 0 // = 等价于 <- k_eff - 1 -> hi2 while (lo2 < hi2) { t2 <- a[lo2] - u2 = a[hi2] # = 等价于 <- + u2 = a[hi2] // = 等价于 <- a[lo2] <- u2 a[hi2] <- t2 lo2 + 1 -> lo2 hi2 <- hi2 - 1 } - # reverse last n-k - lo3 = k_eff # = 等价于 <- + // reverse last n-k + lo3 = k_eff // = 等价于 <- n - 1 -> hi3 while (lo3 < hi3) { t3 <- a[lo3] - u3 = a[hi3] # = 等价于 <- + u3 = a[hi3] // = 等价于 <- a[lo3] <- u3 a[hi3] <- t3 lo3 + 1 -> lo3 hi3 <- hi3 - 1 } - j = 0 # = 等价于 <- + j = 0 // = 等价于 <- while (j < n) { a[j] -> v println(v) diff --git a/tutorial/08-leetcode/191_hamming_weight.kv b/tutorial/08-leetcode/191_hamming_weight.kv index c1c4773d..08f79647 100644 --- a/tutorial/08-leetcode/191_hamming_weight.kv +++ b/tutorial/08-leetcode/191_hamming_weight.kv @@ -1,10 +1,10 @@ -# 191: Number of 1 Bits — 汉明重量 -# 来源: LeetCode #191 -# 期望输出: -# 3 +// 191: Number of 1 Bits — 汉明重量 +// 来源: LeetCode #191 +// 期望输出: +// 3 rwfunc hamming(n:int64) -> () { n -> nv - count = 0 # = 等价于 <- + count = 0 // = 等价于 <- while (nv > 0) { nv % 2 -> bit @@ -12,7 +12,7 @@ rwfunc hamming(n:int64) -> () { count <- count + 1 } - nv = nv ÷ 2 # = 等价于 <- + nv = nv ÷ 2 // = 等价于 <- } println(count) } diff --git a/tutorial/08-leetcode/198_house_robber.kv b/tutorial/08-leetcode/198_house_robber.kv index c2d3ac71..50699f0e 100644 --- a/tutorial/08-leetcode/198_house_robber.kv +++ b/tutorial/08-leetcode/198_house_robber.kv @@ -1,40 +1,40 @@ -# 198: House Robber — DP 打家劫舍 -# 来源: LeetCode #198 -# 期望输出: -# 4 +// 198: House Robber — DP 打家劫舍 +// 来源: LeetCode #198 +// 期望输出: +// 4 rwfunc rob() -> () { [1, 2, 3, 1] -> a:[]int64 n <- ndarray·numel(a) - one = n == 1 # = 等价于 <- + one = n == 1 // = 等价于 <- n == 2 -> two if (one) { ans <- a[0] println(ans) } else { - p1 = a[0] # = 等价于 <- + p1 = a[0] // = 等价于 <- a[1] -> p2 bigger <- p1 > p2 if (bigger) { - p2 = p1 # = 等价于 <- + p2 = p1 // = 等价于 <- } 2 -> i while (i < n) { cur <- a[i] - take = p1 + cur # = 等价于 <- + take = p1 + cur // = 等价于 <- take > p2 -> better if (better) { tmp <- take } else { - tmp = p2 # = 等价于 <- + tmp = p2 // = 等价于 <- } p2 -> p1 p2 <- tmp - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } println(p2) } diff --git a/tutorial/08-leetcode/202_happy_number.kv b/tutorial/08-leetcode/202_happy_number.kv index 03ef7e8b..23e0be4e 100644 --- a/tutorial/08-leetcode/202_happy_number.kv +++ b/tutorial/08-leetcode/202_happy_number.kv @@ -1,28 +1,28 @@ -# 202: Happy Number — 快乐数检测(循环或到1) -# 来源: LeetCode #202 -# 期望输出: -# 1 +// 202: Happy Number — 快乐数检测(循环或到1) +// 来源: LeetCode #202 +// 期望输出: +// 1 rwfunc is_happy(n:int64) -> (result:int64) { n -> nv 0 -> slow fast <- nv - found = 0 # = 等价于 <- + found = 0 // = 等价于 <- while (found == 0) { nv -> x s <- 0 while (x > 0) { - d = x % 10 # = 等价于 <- + d = x % 10 // = 等价于 <- d × d -> d2 d × d -> d2_m s <- s + d2 - x = x ÷ 10 # = 等价于 <- - x_m = x ÷ 10 # = 等价于 <- + x = x ÷ 10 // = 等价于 <- + x_m = x ÷ 10 // = 等价于 <- } s -> nv done <- nv == 1 if (done) { - found = 1 # = 等价于 <- + found = 1 // = 等价于 <- 1 -> result } } diff --git a/tutorial/08-leetcode/203_remove_linked_elements.kv b/tutorial/08-leetcode/203_remove_linked_elements.kv index 2d021dde..ceaecd99 100644 --- a/tutorial/08-leetcode/203_remove_linked_elements.kv +++ b/tutorial/08-leetcode/203_remove_linked_elements.kv @@ -1,17 +1,17 @@ -# 203: Remove Linked List Elements -# 来源: LeetCode #203 -# 期望输出: -# 1 -# 2 -# 3 -# 4 -# 5 +// 203: Remove Linked List Elements +// 来源: LeetCode #203 +// 期望输出: +// 1 +// 2 +// 3 +// 4 +// 5 rwfunc build_list() -> () { /n0 <- { val=1; next="/n1" } - /n1 = { val=2; next="/n2" } # = 等价于 <- + /n1 = { val=2; next="/n2" } // = 等价于 <- { val=6; next="/n3" } -> /n2 /n3 <- { val=3; next="/n4" } - /n4 = { val=4; next="/n5" } # = 等价于 <- + /n4 = { val=4; next="/n5" } // = 等价于 <- { val=5; next="/n6" } -> /n5 /n6 <- { val=6; next="" } } @@ -19,7 +19,7 @@ rwfunc build_list() -> () { rwfunc remove(head:[]char/utf32, val:int64) -> () { p <- "/n0" while (p != "") { - v = p·val # = 等价于 <- + v = p·val // = 等价于 <- v == val -> skip if (skip) { diff --git a/tutorial/08-leetcode/204_count_primes.kv b/tutorial/08-leetcode/204_count_primes.kv index e5451919..ca995374 100644 --- a/tutorial/08-leetcode/204_count_primes.kv +++ b/tutorial/08-leetcode/204_count_primes.kv @@ -1,19 +1,19 @@ -# 204: Count Primes — 埃氏筛计数 n 以内质数 -# 来源: LeetCode #204 -# 期望输出: -# 4 +// 204: Count Primes — 埃氏筛计数 n 以内质数 +// 来源: LeetCode #204 +// 期望输出: +// 4 rwfunc count_primes(n:int64) -> () { - count = 0 # = 等价于 <- + count = 0 // = 等价于 <- 2 -> i while (i < n) { is_p <- true - d = 2 # = 等价于 <- + d = 2 // = 等价于 <- while (d < i) { i % d -> rem div <- rem == 0 if (div) { - is_p = false # = 等价于 <- + is_p = false // = 等价于 <- i -> d } else { d <- d + 1 @@ -21,7 +21,7 @@ rwfunc count_primes(n:int64) -> () { } if (is_p) { - count = count + 1 # = 等价于 <- + count = count + 1 // = 等价于 <- } i + 1 -> i diff --git a/tutorial/08-leetcode/206_reverse_linked_list.kv b/tutorial/08-leetcode/206_reverse_linked_list.kv index 922e1a94..f7c524cd 100644 --- a/tutorial/08-leetcode/206_reverse_linked_list.kv +++ b/tutorial/08-leetcode/206_reverse_linked_list.kv @@ -1,29 +1,29 @@ -# 206: Reverse Linked List -# 来源: LeetCode #206 -# 期望输出: -# 5 -# 4 -# 3 -# 2 -# 1 +// 206: Reverse Linked List +// 来源: LeetCode #206 +// 期望输出: +// 5 +// 4 +// 3 +// 2 +// 1 rwfunc build_list() -> () { - /n0 = { val=1; next="/n1" } # = 等价于 <- + /n0 = { val=1; next="/n1" } // = 等价于 <- { val=2; next="/n2" } -> /n1 /n2 <- { val=3; next="/n3" } - /n3 = { val=4; next="/n4" } # = 等价于 <- + /n3 = { val=4; next="/n4" } // = 等价于 <- { val=5; next="" } -> /n4 } rwfunc reverse(head:[]char/utf32) -> () { - prev = "" # = 等价于 <- + prev = "" // = 等价于 <- head -> cur while (cur != "") { nxt <- cur·next - cur·next = prev # = 等价于 <- + cur·next = prev // = 等价于 <- cur -> prev cur <- nxt } - p = prev # = 等价于 <- + p = prev // = 等价于 <- while (p != "") { p·val -> v println(v) diff --git a/tutorial/08-leetcode/217_contains_dup.kv b/tutorial/08-leetcode/217_contains_dup.kv index bb5e8228..f2377dca 100644 --- a/tutorial/08-leetcode/217_contains_dup.kv +++ b/tutorial/08-leetcode/217_contains_dup.kv @@ -1,30 +1,30 @@ -# 217: Contains Duplicate — 检测重复元素 -# 算法: O(n²) 双重遍历(无 hash map 时) -# 来源: LeetCode #217 -# 期望输出: -# true -# false +// 217: Contains Duplicate — 检测重复元素 +// 算法: O(n²) 双重遍历(无 hash map 时) +// 来源: LeetCode #217 +// 期望输出: +// true +// false rwfunc has_dup() -> () { - a:[]int64 = [1, 2, 3, 1] # = 等价于 <- + a:[]int64 = [1, 2, 3, 1] // = 等价于 <- ndarray·numel(a) -> n found <- false - i = 0 # = 等价于 <- + i = 0 // = 等价于 <- while (i < n) { i + 1 -> j while (j < n) { x <- a[i] - y = a[j] # = 等价于 <- + y = a[j] // = 等价于 <- x == y -> dup if (dup) { found <- true - i = n # = 等价于 <- + i = n // = 等价于 <- n -> j } else { j <- j + 1 } } - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } found -> f @@ -37,27 +37,27 @@ rwfunc has_dup() -> () { rwfunc no_dup() -> () { a:[]int64 <- [1, 2, 3, 4] - n = ndarray·numel(a) # = 等价于 <- + n = ndarray·numel(a) // = 等价于 <- false -> found i <- 0 while (i < n) { - j = i + 1 # = 等价于 <- + j = i + 1 // = 等价于 <- while (j < n) { a[i] -> x y <- a[j] - dup = x == y # = 等价于 <- + dup = x == y // = 等价于 <- if (dup) { true -> found i <- n - j = n # = 等价于 <- + j = n // = 等价于 <- } else { j + 1 -> j } } i <- i + 1 } - f = found # = 等价于 <- + f = found // = 等价于 <- if (f) { println("true") diff --git a/tutorial/08-leetcode/217_contains_dup_hash.kv b/tutorial/08-leetcode/217_contains_dup_hash.kv index b4ac233f..224500d5 100644 --- a/tutorial/08-leetcode/217_contains_dup_hash.kv +++ b/tutorial/08-leetcode/217_contains_dup_hash.kv @@ -1,13 +1,13 @@ -# 217: Contains Duplicate — O(n) hash set -# 来源: LeetCode #217 -# 期望输出: -# true -# false +// 217: Contains Duplicate — O(n) hash set +// 来源: LeetCode #217 +// 期望输出: +// true +// false rwfunc has_dup(a:[]int64) -> () { ndarray·numel(a) -> n - seen:[]char/utf8·int64 = {} # = 等价于 <- + seen:[]char/utf8·int64 = {} // = 等价于 <- found <- false - i = 0 # = 等价于 <- + i = 0 // = 等价于 <- while (i < n) { a[i] -> x kv·get(seen, x) != None -> exists @@ -16,7 +16,7 @@ rwfunc has_dup(a:[]int64) -> () { true -> found i <- n } else { - _ = kv·set(seen, x, 1) # = 等价于 <- + _ = kv·set(seen, x, 1) // = 等价于 <- i + 1 -> i } } @@ -30,11 +30,11 @@ rwfunc has_dup(a:[]int64) -> () { } rwfunc no_dup() -> () { - a:[]int64 = [1, 2, 3, 4] # = 等价于 <- + a:[]int64 = [1, 2, 3, 4] // = 等价于 <- ndarray·numel(a) -> n - seen:[]char/utf8·int64 = {} # = 等价于 <- + seen:[]char/utf8·int64 = {} // = 等价于 <- found <- false - i = 0 # = 等价于 <- + i = 0 // = 等价于 <- while (i < n) { a[i] -> x kv·get(seen, x) != None -> exists @@ -43,7 +43,7 @@ rwfunc no_dup() -> () { true -> found i <- n } else { - _ = kv·set(seen, x, 1) # = 等价于 <- + _ = kv·set(seen, x, 1) // = 等价于 <- i + 1 -> i } } diff --git a/tutorial/08-leetcode/219_contains_dup_ii.kv b/tutorial/08-leetcode/219_contains_dup_ii.kv index e1fc5615..fbd95edf 100644 --- a/tutorial/08-leetcode/219_contains_dup_ii.kv +++ b/tutorial/08-leetcode/219_contains_dup_ii.kv @@ -1,12 +1,12 @@ -# 219: Contains Duplicate II — hash 记录最近下标(has 检存在) -# 来源: LeetCode #219 -# 期望输出: -# true -# false +// 219: Contains Duplicate II — hash 记录最近下标(has 检存在) +// 来源: LeetCode #219 +// 期望输出: +// true +// false rwfunc near_dup(nums:[]int64, k:int64) -> () { n <- ndarray·numel(nums) - h:[]char/utf8·int64 = {} # = 等价于 <- - found = false # = 等价于 <- + h:[]char/utf8·int64 = {} // = 等价于 <- + found = false // = 等价于 <- 0 -> i while (i < n) { nums[i] -> x diff --git a/tutorial/08-leetcode/231_power_of_two.kv b/tutorial/08-leetcode/231_power_of_two.kv index 7aa14842..b5e68800 100644 --- a/tutorial/08-leetcode/231_power_of_two.kv +++ b/tutorial/08-leetcode/231_power_of_two.kv @@ -1,17 +1,17 @@ -# 231: Power of Two — 判断是否为2的幂 -# 来源: LeetCode #231 -# 期望输出: -# 1 -# 0 +// 231: Power of Two — 判断是否为2的幂 +// 来源: LeetCode #231 +// 期望输出: +// 1 +// 0 rwfunc is_power(n:int64) -> (r:int64) { - result = 0 # = 等价于 <- + result = 0 // = 等价于 <- n > 0 -> pos if (pos) { t <- 1 while (t < n) { - t = t × 2 # = 等价于 <- - t_m = t × 2 # = 等价于 <- + t = t × 2 // = 等价于 <- + t_m = t × 2 // = 等价于 <- } t == n -> eq @@ -20,7 +20,7 @@ rwfunc is_power(n:int64) -> (r:int64) { } } - r = result # = 等价于 <- + r = result // = 等价于 <- } rwfunc test() -> () { diff --git a/tutorial/08-leetcode/234_palindrome_list.kv b/tutorial/08-leetcode/234_palindrome_list.kv index 4944e84b..9fbad90f 100644 --- a/tutorial/08-leetcode/234_palindrome_list.kv +++ b/tutorial/08-leetcode/234_palindrome_list.kv @@ -1,10 +1,10 @@ -# 234: Palindrome Linked List — 链表复制到键族数组 + 双指针(dict 声明整型键) -# 来源: LeetCode #234 -# 期望输出: -# true -# false +// 234: Palindrome Linked List — 链表复制到键族数组 + 双指针(dict 声明整型键) +// 来源: LeetCode #234 +// 期望输出: +// true +// false rwfunc is_pal(head:[]char/utf32) -> () { - arr:[int64]·int64 = {} # = 等价于 <- + arr:[int64]·int64 = {} // = 等价于 <- 0 -> n head -> p while (p != "") { @@ -13,7 +13,7 @@ rwfunc is_pal(head:[]char/utf32) -> () { n <- n + 1 p·next -> p } - ok = true # = 等价于 <- + ok = true // = 等价于 <- 0 -> l r <- n - 1 while (l < r) { @@ -25,7 +25,7 @@ rwfunc is_pal(head:[]char/utf32) -> () { r -> l } l <- l + 1 - r = r - 1 # = 等价于 <- + r = r - 1 // = 等价于 <- } if (ok) { println("true") @@ -35,10 +35,10 @@ rwfunc is_pal(head:[]char/utf32) -> () { } rwfunc build() -> () { - /p0 = { val=1; next="/p1" } # = 等价于 <- + /p0 = { val=1; next="/p1" } // = 等价于 <- /p1 <- { val=2; next="/p2" } { val=2; next="/p3" } -> /p2 - /p3 = { val=1; next="" } # = 等价于 <- + /p3 = { val=1; next="" } // = 等价于 <- /q0 <- { val=1; next="/q1" } { val=2; next="" } -> /q1 } diff --git a/tutorial/08-leetcode/238_product_except_self.kv b/tutorial/08-leetcode/238_product_except_self.kv index 5671fd9b..9b220083 100644 --- a/tutorial/08-leetcode/238_product_except_self.kv +++ b/tutorial/08-leetcode/238_product_except_self.kv @@ -1,39 +1,39 @@ -# 238: Product of Array Except Self — 前后缀乘积 -# 算法: 两次遍历,前缀积×后缀积 -# 来源: LeetCode #238 -# 期望输出: -# 24 -# 12 -# 8 -# 6 +// 238: Product of Array Except Self — 前后缀乘积 +// 算法: 两次遍历,前缀积×后缀积 +// 来源: LeetCode #238 +// 期望输出: +// 24 +// 12 +// 8 +// 6 rwfunc product() -> () { - a:[]int64 = [1, 2, 3, 4] # = 等价于 <- + a:[]int64 = [1, 2, 3, 4] // = 等价于 <- ndarray·numel(a) -> n prefix <- 1 - suffix = 1 # = 等价于 <- - # build prefix products into result + suffix = 1 // = 等价于 <- + // build prefix products into result [1, 1, 1, 1] -> result:[]int64 i <- 0 while (i < n) { result[i] <- prefix - x = a[i] # = 等价于 <- + x = a[i] // = 等价于 <- prefix × x -> prefix prefix × x -> prefix_m i <- i + 1 } - # multiply by suffix products - j = n - 1 # = 等价于 <- + // multiply by suffix products + j = n - 1 // = 等价于 <- while (j >= 0) { result[j] -> rv newv <- suffix × rv newv_m <- suffix × rv result[j] <- newv - y = a[j] # = 等价于 <- + y = a[j] // = 等价于 <- suffix × y -> suffix suffix × y -> suffix_m j <- j - 1 } - k = 0 # = 等价于 <- + k = 0 // = 等价于 <- while (k < n) { result[k] -> v println(v) diff --git a/tutorial/08-leetcode/242_valid_anagram.kv b/tutorial/08-leetcode/242_valid_anagram.kv index b3c9a09d..ee5263c8 100644 --- a/tutorial/08-leetcode/242_valid_anagram.kv +++ b/tutorial/08-leetcode/242_valid_anagram.kv @@ -1,17 +1,17 @@ -# 242: Valid Anagram — dict 字符计数(动态键读写 h·*c,用 has 检存在) -# 来源: LeetCode #242 -# 期望输出: -# true -# false +// 242: Valid Anagram — dict 字符计数(动态键读写 h·*c,用 has 检存在) +// 来源: LeetCode #242 +// 期望输出: +// true +// false rwfunc is_anagram(s:[]char/utf32, t:[]char/utf32) -> () { - ns = string·len(s) # = 等价于 <- + ns = string·len(s) // = 等价于 <- nt <- string·len(t) - ok = true # = 等价于 <- + ok = true // = 等价于 <- if (ns != nt) { false -> ok } else { - h:[]char/utf8·int64 = {} # = 等价于 <- + h:[]char/utf8·int64 = {} // = 等价于 <- 0 -> i while (i < ns) { string·char(s, i) -> c diff --git a/tutorial/08-leetcode/258_add_digits.kv b/tutorial/08-leetcode/258_add_digits.kv index aa6b0daf..0b63a76a 100644 --- a/tutorial/08-leetcode/258_add_digits.kv +++ b/tutorial/08-leetcode/258_add_digits.kv @@ -1,15 +1,15 @@ -# 258: Add Digits — 数字根(反复各位相加直到一位数) -# 来源: LeetCode #258 -# 期望输出: -# 2 +// 258: Add Digits — 数字根(反复各位相加直到一位数) +// 来源: LeetCode #258 +// 期望输出: +// 2 rwfunc add_digits(n:int64) -> () { n -> nv while (nv >= 10) { - s = 0 # = 等价于 <- + s = 0 // = 等价于 <- nv -> x while (x > 0) { d <- x % 10 - s = s + d # = 等价于 <- + s = s + d // = 等价于 <- x ÷ 10 -> x x ÷ 10 -> x_m } diff --git a/tutorial/08-leetcode/263_ugly_number.kv b/tutorial/08-leetcode/263_ugly_number.kv index 65bb9217..81468d40 100644 --- a/tutorial/08-leetcode/263_ugly_number.kv +++ b/tutorial/08-leetcode/263_ugly_number.kv @@ -1,11 +1,11 @@ -# 263: Ugly Number -# 来源: LeetCode #263 -# 期望输出: -# 1 +// 263: Ugly Number +// 来源: LeetCode #263 +// 期望输出: +// 1 rwfunc is_ugly(n:int64) -> () { n -> nv - bad = nv <= 0 # = 等价于 <- - bad_m = nv ≤ 0 # = 等价于 <- + bad = nv <= 0 // = 等价于 <- + bad_m = nv ≤ 0 // = 等价于 <- if (bad) { println(0) @@ -14,19 +14,19 @@ rwfunc is_ugly(n:int64) -> () { while (r2 == 0) { nv <- nv ÷ 2 nv_m <- nv ÷ 2 - r2 = nv % 2 # = 等价于 <- + r2 = nv % 2 // = 等价于 <- } nv % 3 -> r3 while (r3 == 0) { nv <- nv ÷ 3 nv_m <- nv ÷ 3 - r3 = nv % 3 # = 等价于 <- + r3 = nv % 3 // = 等价于 <- } nv % 5 -> r5 while (r5 == 0) { nv <- nv ÷ 5 nv_m <- nv ÷ 5 - r5 = nv % 5 # = 等价于 <- + r5 = nv % 5 // = 等价于 <- } nv == 1 -> ok diff --git a/tutorial/08-leetcode/268_missing_number.kv b/tutorial/08-leetcode/268_missing_number.kv index 20693519..c7c19c90 100644 --- a/tutorial/08-leetcode/268_missing_number.kv +++ b/tutorial/08-leetcode/268_missing_number.kv @@ -1,24 +1,24 @@ -# 268: Missing Number — 找缺失数字(XOR 或求和) -# 算法: 求和公式 n*(n+1)/2 - sum -# 来源: LeetCode #268 -# 期望输出: -# 2 +// 268: Missing Number — 找缺失数字(XOR 或求和) +// 算法: 求和公式 n*(n+1)/2 - sum +// 来源: LeetCode #268 +// 期望输出: +// 2 rwfunc missing() -> () { a:[]int64 <- [3, 0, 1] - n = ndarray·numel(a) # = 等价于 <- + n = ndarray·numel(a) // = 等价于 <- 0 -> s i <- 0 while (i < n) { - x = a[i] # = 等价于 <- + x = a[i] // = 等价于 <- s + x -> s i <- i + 1 } - nn = n × n # = 等价于 <- - nn_m = n × n # = 等价于 <- + nn = n × n // = 等价于 <- + nn_m = n × n // = 等价于 <- nn + n -> total expected <- total ÷ 2 expected_m <- total ÷ 2 - result = expected - s # = 等价于 <- + result = expected - s // = 等价于 <- println(result) } diff --git a/tutorial/08-leetcode/278_first_bad.kv b/tutorial/08-leetcode/278_first_bad.kv index cdf74f13..879643a1 100644 --- a/tutorial/08-leetcode/278_first_bad.kv +++ b/tutorial/08-leetcode/278_first_bad.kv @@ -1,20 +1,20 @@ -# 278: First Bad Version — 二分查找第一个坏版本 -# 来源: LeetCode #278 -# 期望输出: -# 4 +// 278: First Bad Version — 二分查找第一个坏版本 +// 来源: LeetCode #278 +// 期望输出: +// 4 rwfunc first_bad(n:int64) -> () { - # isBadVersion(i) = i >= 4 + // isBadVersion(i) = i >= 4 1 -> lo hi <- n while (lo < hi) { - s = lo + hi # = 等价于 <- + s = lo + hi // = 等价于 <- s ÷ 2 -> mid s ÷ 2 -> mid_m bad <- mid >= 4 bad_m <- mid ≥ 4 if (bad) { - hi = mid # = 等价于 <- + hi = mid // = 等价于 <- } else { mid + 1 -> lo } diff --git a/tutorial/08-leetcode/283_move_zeroes.kv b/tutorial/08-leetcode/283_move_zeroes.kv index 7ae5baba..467fb30f 100644 --- a/tutorial/08-leetcode/283_move_zeroes.kv +++ b/tutorial/08-leetcode/283_move_zeroes.kv @@ -1,20 +1,20 @@ -# 283: Move Zeroes — 双指针原地移零(TLV 数组读写) -# 来源: LeetCode #283 -# 期望输出: -# 1 -# 3 -# 12 -# 0 -# 0 +// 283: Move Zeroes — 双指针原地移零(TLV 数组读写) +// 来源: LeetCode #283 +// 期望输出: +// 1 +// 3 +// 12 +// 0 +// 0 rwfunc move_zeroes() -> () { - a:[]int64 = [0, 1, 0, 3, 12] # = 等价于 <- + a:[]int64 = [0, 1, 0, 3, 12] // = 等价于 <- n <- ndarray·numel(a) 0 -> w 0 -> i while (i < n) { a[i] -> x - nz = x != 0 # = 等价于 <- - nz_m = x ≠ 0 # = 等价于 <- + nz = x != 0 // = 等价于 <- + nz_m = x ≠ 0 // = 等价于 <- if (nz) { a[w] <- x @@ -24,7 +24,7 @@ rwfunc move_zeroes() -> () { } while (w < n) { a[w] <- 0 - w = w + 1 # = 等价于 <- + w = w + 1 // = 等价于 <- } 0 -> i while (i < n) { diff --git a/tutorial/08-leetcode/292_nim_game.kv b/tutorial/08-leetcode/292_nim_game.kv index d6f319dc..0d682e20 100644 --- a/tutorial/08-leetcode/292_nim_game.kv +++ b/tutorial/08-leetcode/292_nim_game.kv @@ -1,9 +1,9 @@ -# 292: Nim Game — 巴什博弈,4的倍数必输 -# 来源: LeetCode #292 -# 期望输出: -# 0 +// 292: Nim Game — 巴什博弈,4的倍数必输 +// 来源: LeetCode #292 +// 期望输出: +// 0 rwfunc can_win(n:int64) -> () { - rem = n % 4 # = 等价于 <- + rem = n % 4 // = 等价于 <- rem == 0 -> lose if (lose) { diff --git a/tutorial/08-leetcode/303_range_sum.kv b/tutorial/08-leetcode/303_range_sum.kv index 0401a392..04dc4feb 100644 --- a/tutorial/08-leetcode/303_range_sum.kv +++ b/tutorial/08-leetcode/303_range_sum.kv @@ -1,28 +1,28 @@ -# 303: Range Sum Query — 前缀和 -# 来源: LeetCode #303 -# 期望输出: -# 1 -# -1 +// 303: Range Sum Query — 前缀和 +// 来源: LeetCode #303 +// 期望输出: +// 1 +// -1 rwfunc range_sum() -> () { a:[]int64 <- [-2, 0, 3, -5, 2, -1] - n = ndarray·numel(a) # = 等价于 <- - # build prefix sums + n = ndarray·numel(a) // = 等价于 <- + // build prefix sums [0, 0, 0, 0, 0, 0] -> p:[]int64 s <- a[0] p[0] <- s - i = 1 # = 等价于 <- + i = 1 // = 等价于 <- while (i < n) { a[i] -> v s <- s + v p[i] <- s - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } - # sumRange(0, 2) = p[2] + // sumRange(0, 2) = p[2] p[2] -> r1 println(r1) - # sumRange(2, 5) = p[5] - p[1] + // sumRange(2, 5) = p[5] - p[1] t2 <- p[5] - t1 = p[1] # = 等价于 <- + t1 = p[1] // = 等价于 <- t2 - t1 -> r2 println(r2) } diff --git a/tutorial/08-leetcode/326_power_of_three.kv b/tutorial/08-leetcode/326_power_of_three.kv index 40d93f03..dcf54078 100644 --- a/tutorial/08-leetcode/326_power_of_three.kv +++ b/tutorial/08-leetcode/326_power_of_three.kv @@ -1,13 +1,13 @@ -# 326: Power of Three — 判断3的幂 -# 来源: LeetCode #326 -# 期望输出: -# 1 -# 0 +// 326: Power of Three — 判断3的幂 +// 来源: LeetCode #326 +// 期望输出: +// 1 +// 0 rwfunc is_power3(n:int64) -> () { pos <- n > 0 if (pos) { - t = 1 # = 等价于 <- + t = 1 // = 等价于 <- while (t < n) { t × 3 -> t t × 3 -> t_m diff --git a/tutorial/08-leetcode/342_power_of_four.kv b/tutorial/08-leetcode/342_power_of_four.kv index 42d7d2a4..31a4b36b 100644 --- a/tutorial/08-leetcode/342_power_of_four.kv +++ b/tutorial/08-leetcode/342_power_of_four.kv @@ -1,9 +1,9 @@ -# 342: Power of Four — 判断4的幂 -# 来源: LeetCode #342 -# 期望输出: -# 1 +// 342: Power of Four — 判断4的幂 +// 来源: LeetCode #342 +// 期望输出: +// 1 rwfunc is_power4(n:int64) -> () { - pos = n > 0 # = 等价于 <- + pos = n > 0 // = 等价于 <- if (pos) { 1 -> t @@ -11,7 +11,7 @@ rwfunc is_power4(n:int64) -> () { t <- t × 4 t_m <- t × 4 } - eq = t == n # = 等价于 <- + eq = t == n // = 等价于 <- if (eq) { println(1) diff --git a/tutorial/08-leetcode/344_reverse_string.kv b/tutorial/08-leetcode/344_reverse_string.kv index 5d643969..23468145 100644 --- a/tutorial/08-leetcode/344_reverse_string.kv +++ b/tutorial/08-leetcode/344_reverse_string.kv @@ -1,26 +1,26 @@ -# 344: Reverse String (用数组模拟) — 双指针反转 -# 来源: LeetCode #344 -# 期望输出: -# o -# l -# l -# e -# h +// 344: Reverse String (用数组模拟) — 双指针反转 +// 来源: LeetCode #344 +// 期望输出: +// o +// l +// l +// e +// h rwfunc reverse_str() -> () { - # char 值数组: "hello" → ASCII [104, 101, 108, 108, 111] + // char 值数组: "hello" → ASCII [104, 101, 108, 108, 111] a:[]int64 = [104, 101, 108, 108, 111] n <- ndarray·numel(a) - l = 0 # = 等价于 <- + l = 0 // = 等价于 <- n - 1 -> r while (l < r) { tl <- a[l] - tr = a[r] # = 等价于 <- + tr = a[r] // = 等价于 <- a[l] <- tr a[r] <- tl l + 1 -> l r <- r - 1 } - i = 0 # = 等价于 <- + i = 0 // = 等价于 <- while (i < n) { a[i] -> c string·char("abcdefghijklmnopqrstuvwxyz", c - 97) -> s diff --git a/tutorial/08-leetcode/349_intersection.kv b/tutorial/08-leetcode/349_intersection.kv index 318246e8..3f0081ce 100644 --- a/tutorial/08-leetcode/349_intersection.kv +++ b/tutorial/08-leetcode/349_intersection.kv @@ -1,29 +1,29 @@ -# 349: Intersection of Two Arrays — O(n²) 暴力 -# 来源: LeetCode #349 -# 期望输出: -# 2 +// 349: Intersection of Two Arrays — O(n²) 暴力 +// 来源: LeetCode #349 +// 期望输出: +// 2 rwfunc intersection() -> () { - a:[]int64 = [1, 2, 2, 1] # = 等价于 <- + a:[]int64 = [1, 2, 2, 1] // = 等价于 <- ndarray·numel(a) -> na b:[]int64 <- [2, 2] - nb = ndarray·numel(b) # = 等价于 <- + nb = ndarray·numel(b) // = 等价于 <- [0, 0] -> r:[]int64 idx <- 0 - count = 0 # = 等价于 <- + count = 0 // = 等价于 <- 0 -> i while (i < na) { av <- a[i] - j = 0 # = 等价于 <- + j = 0 // = 等价于 <- false -> found while (j < nb) { bv <- b[j] - match = av == bv # = 等价于 <- + match = av == bv // = 等价于 <- if (match) { true -> found j <- nb } else { - j = j + 1 # = 等价于 <- + j = j + 1 // = 等价于 <- } } @@ -33,7 +33,7 @@ rwfunc intersection() -> () { count <- count + 1 } - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } r[0] -> v println(v) diff --git a/tutorial/08-leetcode/367_valid_square.kv b/tutorial/08-leetcode/367_valid_square.kv index e27cb4b8..0ec5a6a7 100644 --- a/tutorial/08-leetcode/367_valid_square.kv +++ b/tutorial/08-leetcode/367_valid_square.kv @@ -1,31 +1,31 @@ -# 367: Valid Perfect Square — 二分判断完全平方数 -# 来源: LeetCode #367 -# 期望输出: -# 1 -# 0 +// 367: Valid Perfect Square — 二分判断完全平方数 +// 来源: LeetCode #367 +// 期望输出: +// 1 +// 0 rwfunc is_square(n:int64) -> () { small <- n < 2 if (small) { println(1) } else { - lo = 1 # = 等价于 <- + lo = 1 // = 等价于 <- n ÷ 2 -> hi n ÷ 2 -> hi_m ans <- 0 while (lo <= hi) { - s = lo + hi # = 等价于 <- + s = lo + hi // = 等价于 <- s ÷ 2 -> mid s ÷ 2 -> mid_m sq <- mid × mid sq_m <- mid × mid - eq = sq == n # = 等价于 <- + eq = sq == n // = 等价于 <- if (eq) { 1 -> ans lo <- hi + 1 } else { - lt = sq < n # = 等价于 <- + lt = sq < n // = 等价于 <- if (lt) { mid + 1 -> lo diff --git a/tutorial/08-leetcode/371_sum_two.kv b/tutorial/08-leetcode/371_sum_two.kv index 0af9a421..a9044d33 100644 --- a/tutorial/08-leetcode/371_sum_two.kv +++ b/tutorial/08-leetcode/371_sum_two.kv @@ -1,15 +1,15 @@ -# 371: Sum of Two Integers — 位运算加法 -# 来源: LeetCode #371 -# 期望输出: -# 5 +// 371: Sum of Two Integers — 位运算加法 +// 来源: LeetCode #371 +// 期望输出: +// 5 rwfunc get_sum(a:int64, b:int64) -> () { a -> av b -> bv while (bv != 0) { - carry = av & bv # = 等价于 <- + carry = av & bv // = 等价于 <- carry << 1 -> c2 av <- av ^ bv - bv = c2 # = 等价于 <- + bv = c2 // = 等价于 <- } println(av) } diff --git a/tutorial/08-leetcode/374_guess_number.kv b/tutorial/08-leetcode/374_guess_number.kv index 1f5f9f17..ce1bd065 100644 --- a/tutorial/08-leetcode/374_guess_number.kv +++ b/tutorial/08-leetcode/374_guess_number.kv @@ -1,18 +1,18 @@ -# 374: Guess Number Higher or Lower — 二分猜数字 -# 来源: LeetCode #374 -# 期望输出: -# 6 +// 374: Guess Number Higher or Lower — 二分猜数字 +// 来源: LeetCode #374 +// 期望输出: +// 6 rwfunc guess_number(n:int64) -> () { 1 -> lo hi <- n while (lo <= hi) { - s = lo + hi # = 等价于 <- + s = lo + hi // = 等价于 <- s ÷ 2 -> mid s ÷ 2 -> mid_m low <- mid < 6 if (low) { - lo = mid + 1 # = 等价于 <- + lo = mid + 1 // = 等价于 <- } else { mid > 6 -> high @@ -20,7 +20,7 @@ rwfunc guess_number(n:int64) -> () { hi <- mid - 1 } else { println(mid) - lo = hi + 1 # = 等价于 <- + lo = hi + 1 // = 等价于 <- } } } diff --git a/tutorial/08-leetcode/412_fizz_buzz.kv b/tutorial/08-leetcode/412_fizz_buzz.kv index 5683aa9c..aac607a1 100644 --- a/tutorial/08-leetcode/412_fizz_buzz.kv +++ b/tutorial/08-leetcode/412_fizz_buzz.kv @@ -1,17 +1,17 @@ -# 412: Fizz Buzz — 经典面试题数组版 -# 来源: LeetCode #412 -# 期望输出: -# 1 -# 2 -# Fizz +// 412: Fizz Buzz — 经典面试题数组版 +// 来源: LeetCode #412 +// 期望输出: +// 1 +// 2 +// Fizz rwfunc fizzbuzz(n:int64) -> () { [1, 2, 3, 4, 5] -> a:[]int64 i <- 1 while (i <= n) { - m3 = i % 3 # = 等价于 <- + m3 = i % 3 // = 等价于 <- i % 5 -> m5 d3 <- m3 == 0 - d5 = m5 == 0 # = 等价于 <- + d5 = m5 == 0 // = 等价于 <- d3 && d5 -> fb if (fb) { diff --git a/tutorial/08-leetcode/414_third_max.kv b/tutorial/08-leetcode/414_third_max.kv index 263b8cc0..7fe73ef5 100644 --- a/tutorial/08-leetcode/414_third_max.kv +++ b/tutorial/08-leetcode/414_third_max.kv @@ -1,32 +1,32 @@ -# 414: Third Maximum Number — 找第三大的数 -# 来源: LeetCode #414 -# 期望输出: -# 1 +// 414: Third Maximum Number — 找第三大的数 +// 来源: LeetCode #414 +// 期望输出: +// 1 rwfunc third_max() -> () { - a:[]int64 = [2, 2, 3, 1] # = 等价于 <- + a:[]int64 = [2, 2, 3, 1] // = 等价于 <- ndarray·numel(a) -> n - # track top 3 + // track top 3 first <- 0 - second = 0 # = 等价于 <- + second = 0 // = 等价于 <- 0 -> third i <- 0 while (i < n) { - x = a[i] # = 等价于 <- + x = a[i] // = 等价于 <- x > first -> gt1 if (gt1) { third <- second - second = first # = 等价于 <- + second = first // = 等价于 <- x -> first } else { lt1 <- x < first - gt2 = x > second # = 等价于 <- + gt2 = x > second // = 等价于 <- if (lt1 && gt2) { second -> third second <- x } else { - lt2 = x < second # = 等价于 <- + lt2 = x < second // = 等价于 <- x > third -> gt3 if (lt2 && gt3) { @@ -35,7 +35,7 @@ rwfunc third_max() -> () { } } - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } third > 0 -> ok diff --git a/tutorial/08-leetcode/441_arrange_coins.kv b/tutorial/08-leetcode/441_arrange_coins.kv index f90f2db7..e84bb7e8 100644 --- a/tutorial/08-leetcode/441_arrange_coins.kv +++ b/tutorial/08-leetcode/441_arrange_coins.kv @@ -1,25 +1,25 @@ -# 441: Arranging Coins — 二分查找完整行数 -# 来源: LeetCode #441 -# 期望输出: -# 2 +// 441: Arranging Coins — 二分查找完整行数 +// 来源: LeetCode #441 +// 期望输出: +// 2 rwfunc arrange(n:int64) -> () { - lo = 1 # = 等价于 <- + lo = 1 // = 等价于 <- n -> hi ans <- 0 while (lo <= hi) { - s = lo + hi # = 等价于 <- + s = lo + hi // = 等价于 <- s ÷ 2 -> mid s ÷ 2 -> mid_m m2 <- mid × mid m2_m <- mid × mid - total = m2 + mid # = 等价于 <- + total = m2 + mid // = 等价于 <- total ÷ 2 -> t total ÷ 2 -> t_m ok <- t <= n ok_m <- t ≤ n if (ok) { - ans = mid # = 等价于 <- + ans = mid // = 等价于 <- mid + 1 -> lo } else { hi <- mid - 1 diff --git a/tutorial/08-leetcode/507_perfect_number.kv b/tutorial/08-leetcode/507_perfect_number.kv index 9c35d185..33dc51a3 100644 --- a/tutorial/08-leetcode/507_perfect_number.kv +++ b/tutorial/08-leetcode/507_perfect_number.kv @@ -1,26 +1,26 @@ -# 507: Perfect Number -# 来源: LeetCode #507 -# 期望输出: -# 1 +// 507: Perfect Number +// 来源: LeetCode #507 +// 期望输出: +// 1 rwfunc is_perfect(n:int64) -> () { - sum = 1 # = 等价于 <- + sum = 1 // = 等价于 <- 2 -> i sq <- i × i sq_m <- i × i while (sq <= n) { - rem = n % i # = 等价于 <- + rem = n % i // = 等价于 <- rem == 0 -> div if (div) { sum <- sum + i - j = n ÷ i # = 等价于 <- - j_m = n ÷ i # = 等价于 <- + j = n ÷ i // = 等价于 <- + j_m = n ÷ i // = 等价于 <- sum + j -> sum } i <- i + 1 - sq = i × i # = 等价于 <- - sq_m = i × i # = 等价于 <- + sq = i × i // = 等价于 <- + sq_m = i × i // = 等价于 <- } sum == n -> ok diff --git a/tutorial/08-leetcode/509_fib.kv b/tutorial/08-leetcode/509_fib.kv index 2c04cf29..b7c51328 100644 --- a/tutorial/08-leetcode/509_fib.kv +++ b/tutorial/08-leetcode/509_fib.kv @@ -1,7 +1,7 @@ -# 509: Fibonacci Number — 迭代斐波那契 -# 来源: LeetCode #509 -# 期望输出: -# 55 +// 509: Fibonacci Number — 迭代斐波那契 +// 来源: LeetCode #509 +// 期望输出: +// 55 rwfunc fib(n:int64) -> () { base <- n <= 1 base_m <- n ≤ 1 @@ -9,14 +9,14 @@ rwfunc fib(n:int64) -> () { if (base) { println(n) } else { - a = 0 # = 等价于 <- + a = 0 // = 等价于 <- 1 -> b i <- 2 while (i <= n) { - c = a + b # = 等价于 <- + c = a + b // = 等价于 <- b -> a b <- c - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } println(c) } diff --git a/tutorial/08-leetcode/728_self_dividing.kv b/tutorial/08-leetcode/728_self_dividing.kv index 8a87da68..cda6f850 100644 --- a/tutorial/08-leetcode/728_self_dividing.kv +++ b/tutorial/08-leetcode/728_self_dividing.kv @@ -1,42 +1,42 @@ -# 728: Self Dividing Numbers -# 来源: LeetCode #728 -# 期望输出: -# 1 -# 2 -# 3 -# 4 -# 5 -# 6 -# 7 -# 8 -# 9 -# 11 -# 12 -# 15 +// 728: Self Dividing Numbers +// 来源: LeetCode #728 +// 期望输出: +// 1 +// 2 +// 3 +// 4 +// 5 +// 6 +// 7 +// 8 +// 9 +// 11 +// 12 +// 15 rwfunc is_self(n:int64) -> (r:bool) { n -> num ok <- true while (num > 0) { - d = num % 10 # = 等价于 <- + d = num % 10 // = 等价于 <- d == 0 -> zero if (zero) { ok <- false - num = 0 # = 等价于 <- + num = 0 // = 等价于 <- } else { n % d -> rem div <- rem == 0 if (div) { - num = num ÷ 10 # = 等价于 <- - num_m = num ÷ 10 # = 等价于 <- + num = num ÷ 10 // = 等价于 <- + num_m = num ÷ 10 // = 等价于 <- } else { false -> ok num <- 0 } } } - r = ok # = 等价于 <- + r = ok // = 等价于 <- } rwfunc test() -> () { @@ -48,6 +48,6 @@ rwfunc test() -> () { println(i) } - i = i + 1 # = 等价于 <- + i = i + 1 // = 等价于 <- } } diff --git a/tutorial/09-debugger/breakpoint.kv b/tutorial/09-debugger/breakpoint.kv index 137589b6..9236dbaa 100644 --- a/tutorial/09-debugger/breakpoint.kv +++ b/tutorial/09-debugger/breakpoint.kv @@ -1,7 +1,7 @@ rwfunc loop(n: int64) -> () { 1 -> i while (i <= n) { - debugger() # 内联断点:执行至此暂停,等待 agent 命令 + debugger() // 内联断点:执行至此暂停,等待 agent 命令 println(i) i + 1 -> i } diff --git a/tutorial/09-debugger/chain_array.kv b/tutorial/09-debugger/chain_array.kv index 6aeaf00a..c03ecf89 100644 --- a/tutorial/09-debugger/chain_array.kv +++ b/tutorial/09-debugger/chain_array.kv @@ -1,23 +1,23 @@ -# 深层数组参数链路:main → f1 → f2 → f3 -# 在 f3 最深处 debugger() 暂停,可 dump kvspace 观察 ·rparam/·wparam 链 +// 深层数组参数链路:main → f1 → f2 → f3 +// 在 f3 最深处 debugger() 暂停,可 dump kvspace 观察 ·rparam/·wparam 链 rwfunc f3() -> (a:int64, s:int64) { println(a) - debugger() # 在此暂停 + debugger() // 在此暂停 at(a, 0) -> v0 at(a, 1) -> v1 - v0 + v1 -> s # 30 + 40 = 70 + v0 + v1 -> s // 30 + 40 = 70 } rwfunc f2() -> (a:int64, s:int64) { - a:[]int64 = [30, 40] # f2 创建数组放写参 - f3() -> (a, s) # 传给 f3 的写参,不拷贝,同路径直达 + a:[]int64 = [30, 40] // f2 创建数组放写参 + f3() -> (a, s) // 传给 f3 的写参,不拷贝,同路径直达 } rwfunc f1() -> (s:int64) { - f2() -> (_, s) # 接收 s,丢弃数组 + f2() -> (_, s) // 接收 s,丢弃数组 } rwfunc test() -> () { f1() -> r - println(r) # 70 + println(r) // 70 } diff --git a/tutorial/10-types/01-typed-map.kv b/tutorial/10-types/01-typed-map.kv index ef16893c..b1498986 100644 --- a/tutorial/10-types/01-typed-map.kv +++ b/tutorial/10-types/01-typed-map.kv @@ -1,9 +1,9 @@ -# 语义: stringkeymap 一等类型 —— kindexpr 用 `·` 声明 key·value 类型。 -# []char/utf8·int64 = Go 的 map[string]int64(key 侧恒 []char/ 字符串键)。 -# 建 map 用成员赋值 base·key = v;layout round-trip 类型进 defrwfunc 签名 head。 -# 期望输出: -# total = 30 -# max = 20 +// 语义: stringkeymap 一等类型 —— kindexpr 用 `·` 声明 key·value 类型。 +// []char/utf8·int64 = Go 的 map[string]int64(key 侧恒 []char/ 字符串键)。 +// 建 map 用成员赋值 base·key = v;layout round-trip 类型进 defrwfunc 签名 head。 +// 期望输出: +// total = 30 +// max = 20 rwfunc total(m:[]char/utf8·int64) -> (s:int64) { kv·get(m, "a") -> a kv·get(m, "b") -> b diff --git a/tutorial/10-types/02-string-map.kv b/tutorial/10-types/02-string-map.kv index af5f2a37..3e6e492a 100644 --- a/tutorial/10-types/02-string-map.kv +++ b/tutorial/10-types/02-string-map.kv @@ -1,9 +1,9 @@ -# 语义: []char/utf8·[]char/utf32 —— key 侧 []char/utf8 字符串键,value 侧完整 kindexpr。 -# = Go map[string]string。建 map 用成员赋值 d·key = v;字符串恒 []char/。 -# 期望输出: -# en = hello -# zh = 你好 -# missing: true +// 语义: []char/utf8·[]char/utf32 —— key 侧 []char/utf8 字符串键,value 侧完整 kindexpr。 +// = Go map[string]string。建 map 用成员赋值 d·key = v;字符串恒 []char/。 +// 期望输出: +// en = hello +// zh = 你好 +// missing: true rwfunc lookup(dict:[]char/utf8·[]char/utf32, k:[]char/utf32) -> (v:[]char/utf32) { kv·get(dict, k) -> v } diff --git a/tutorial/10-types/03-map-return.kv b/tutorial/10-types/03-map-return.kv index c15d32c2..36d52204 100644 --- a/tutorial/10-types/03-map-return.kv +++ b/tutorial/10-types/03-map-return.kv @@ -1,9 +1,9 @@ -# 语义: stringkeymap 作返回类型 —— rwfunc 返回槽 head 存 []char/utf8·int64。 -# = Go map[string]int64。用 dict 字面量 { … } 构造并返回;缺失键得 None。 -# 期望输出: -# n = 42 -# x = 7 -# miss = true +// 语义: stringkeymap 作返回类型 —— rwfunc 返回槽 head 存 []char/utf8·int64。 +// = Go map[string]int64。用 dict 字面量 { … } 构造并返回;缺失键得 None。 +// 期望输出: +// n = 42 +// x = 7 +// miss = true rwfunc build() -> (m:[]char/utf8·int64) { {n=42; x=7} -> m } diff --git a/tutorial/10-types/04-nested-type.kv b/tutorial/10-types/04-nested-type.kv index 61703266..d756c5a9 100644 --- a/tutorial/10-types/04-nested-type.kv +++ b/tutorial/10-types/04-nested-type.kv @@ -1,8 +1,8 @@ -# 语义: 嵌套 mapexpr —— []char/utf8·[]char/utf8·int64 右结合 = Go map[string]map[string]int。 -# value 侧递归为完整 kindexpr,故类型可无限嵌套;layout 校验并 round-trip 进签名 head。 -# (运行时值语义为内联标量/串,嵌套物化非本例范畴;本例证 layout 接受嵌套签名。) -# 期望输出: -# nested signature accepted +// 语义: 嵌套 mapexpr —— []char/utf8·[]char/utf8·int64 右结合 = Go map[string]map[string]int。 +// value 侧递归为完整 kindexpr,故类型可无限嵌套;layout 校验并 round-trip 进签名 head。 +// (运行时值语义为内联标量/串,嵌套物化非本例范畴;本例证 layout 接受嵌套签名。) +// 期望输出: +// nested signature accepted rwfunc grid(g:[]char/utf8·[]char/utf8·int64) -> (n:int64) { 0 -> n } diff --git a/tutorial/10-types/05-tuple-key.kv b/tutorial/10-types/05-tuple-key.kv index 395e6401..a39d4eb2 100644 --- a/tutorial/10-types/05-tuple-key.kv +++ b/tutorial/10-types/05-tuple-key.kv @@ -1,9 +1,9 @@ -# 语义: 元组键 —— key 侧 [T1,T2,…] 声明标量元组键(物理以字符串格式落 key)。 -# [int32,int32]·[]char/utf8 = 以「两个 int32 的字符串形式」为键、字符串为值的 map。 -# [float32,float32]·int64、[float32,int8,uint32]·int64 亦合法。 -# layout 校验元组元素为标量 kind 并 round-trip 进签名 head(本例证签名接受)。 -# 期望输出: -# tuple-key signatures accepted +// 语义: 元组键 —— key 侧 [T1,T2,…] 声明标量元组键(物理以字符串格式落 key)。 +// [int32,int32]·[]char/utf8 = 以「两个 int32 的字符串形式」为键、字符串为值的 map。 +// [float32,float32]·int64、[float32,int8,uint32]·int64 亦合法。 +// layout 校验元组元素为标量 kind 并 round-trip 进签名 head(本例证签名接受)。 +// 期望输出: +// tuple-key signatures accepted rwfunc grid_i(g:[int32,int32]·[]char/utf8) -> (n:int64) { 0 -> n } diff --git a/tutorial/11-string/01-basic.kv b/tutorial/11-string/01-basic.kv index 31b3c28f..3f47a437 100644 --- a/tutorial/11-string/01-basic.kv +++ b/tutorial/11-string/01-basic.kv @@ -1,9 +1,9 @@ -# 字符串基础:字面量、码点长度、+ 拼接 -# 默认编码 char/utf32(定宽码点,可索引,len 返回码点数) -# 期望输出: -# hello -# 5 -# kvlang +// 字符串基础:字面量、码点长度、+ 拼接 +// 默认编码 char/utf32(定宽码点,可索引,len 返回码点数) +// 期望输出: +// hello +// 5 +// kvlang rwfunc test() -> () { s = "hello" println(s) diff --git a/tutorial/11-string/02-char-ord.kv b/tutorial/11-string/02-char-ord.kv index 90f71f3d..021c477c 100644 --- a/tutorial/11-string/02-char-ord.kv +++ b/tutorial/11-string/02-char-ord.kv @@ -1,8 +1,8 @@ -# 码点操作:string·char(第 i 个码点)、string·ord(首码点值) -# 定宽 utf32 下 O(1) 索引;多字节字符(é)也按码点计 -# 期望输出: -# é -# 233 +// 码点操作:string·char(第 i 个码点)、string·ord(首码点值) +// 定宽 utf32 下 O(1) 索引;多字节字符(é)也按码点计 +// 期望输出: +// é +// 233 rwfunc test() -> () { s = "héllo" println(string·char(s, 1)) diff --git a/tutorial/11-string/03-slice-find.kv b/tutorial/11-string/03-slice-find.kv index 720dff6d..069b6373 100644 --- a/tutorial/11-string/03-slice-find.kv +++ b/tutorial/11-string/03-slice-find.kv @@ -1,8 +1,8 @@ -# 切片与查找:string·slice(码点区间 [lo,hi))、string·find(码点下标,未找到 -1) -# 期望输出: -# 6 -# hello -# -1 +// 切片与查找:string·slice(码点区间 [lo,hi))、string·find(码点下标,未找到 -1) +// 期望输出: +// 6 +// hello +// -1 rwfunc test() -> () { s = "hello world" println(string·find(s, "world")) diff --git a/tutorial/11-string/04-cmp-concat.kv b/tutorial/11-string/04-cmp-concat.kv index b651bcda..e57bffe9 100644 --- a/tutorial/11-string/04-cmp-concat.kv +++ b/tutorial/11-string/04-cmp-concat.kv @@ -1,8 +1,8 @@ -# 比较与拼接:string·cmp(-1/0/1,按码点序)、string·concat -# 期望输出: -# -1 -# 0 -# foobar +// 比较与拼接:string·cmp(-1/0/1,按码点序)、string·concat +// 期望输出: +// -1 +// 0 +// foobar rwfunc test() -> () { println(string·cmp("abc", "abd")) println(string·cmp("x", "x")) diff --git a/tutorial/11-string/05-encodings.kv b/tutorial/11-string/05-encodings.kv index ab7f9114..412aee7b 100644 --- a/tutorial/11-string/05-encodings.kv +++ b/tutorial/11-string/05-encodings.kv @@ -1,14 +1,14 @@ -# 字符串编码:char/utf32(默认定宽)、char/ascii(定宽)、char/utf8(变宽,仅存储/打印) -# 写槽类型标注反推字面量编码;utf8 禁索引(string·char/slice/s[i] 报错) -# 期望输出: -# abc -# y -# héllo +// 字符串编码:char/utf32(默认定宽)、char/ascii(定宽)、char/utf8(变宽,仅存储/打印) +// 写槽类型标注反推字面量编码;utf8 禁索引(string·char/slice/s[i] 报错) +// 期望输出: +// abc +// y +// héllo rwfunc test() -> () { - a = "abc" # 默认 char/utf32 + a = "abc" // 默认 char/utf32 println(a) - b:[]char/ascii = "xyz" # ASCII 定宽,可索引 + b:[]char/ascii = "xyz" // ASCII 定宽,可索引 println(string·char(b, 1)) - c:[]char/utf8 = "héllo" # UTF-8 变宽,打印 OK(索引会报错) + c:[]char/utf8 = "héllo" // UTF-8 变宽,打印 OK(索引会报错) println(c) } diff --git a/tutorial/11-string/06-convert.kv b/tutorial/11-string/06-convert.kv index 03d46790..90d5572b 100644 --- a/tutorial/11-string/06-convert.kv +++ b/tutorial/11-string/06-convert.kv @@ -1,15 +1,15 @@ -# 编码转换:char/utf32 / char/utf8 / char/ascii 就是转换函数(kind(x),同创建函数) -# 转换函数有写参(读参只读):t <- char/utf32(s) -# utf8 转 utf32 后可索引;char/ascii 拒非 ASCII 码点(U+00E9 报错) -# 期望输出: -# hello -# e -# world +// 编码转换:char/utf32 / char/utf8 / char/ascii 就是转换函数(kind(x),同创建函数) +// 转换函数有写参(读参只读):t <- char/utf32(s) +// utf8 转 utf32 后可索引;char/ascii 拒非 ASCII 码点(U+00E9 报错) +// 期望输出: +// hello +// e +// world rwfunc test() -> () { - s:[]char/utf8 = "hello" # 变宽,禁索引 - t <- char/utf32(s) # 转 utf32 定宽,可索引 + s:[]char/utf8 = "hello" // 变宽,禁索引 + t <- char/utf32(s) // 转 utf32 定宽,可索引 println(t) println(string·char(t, 1)) - u <- char/ascii("world") # 转 ascii(非 ASCII 会报错) + u <- char/ascii("world") // 转 ascii(非 ASCII 会报错) println(u) } diff --git a/tutorial/11-string/07-multiline.kv b/tutorial/11-string/07-multiline.kv index d30902eb..db22b007 100644 --- a/tutorial/11-string/07-multiline.kv +++ b/tutorial/11-string/07-multiline.kv @@ -1,16 +1,22 @@ -# 跨行字符串:"""..."""(对标 Python,跨行 + 转义)与 `...`(对标 Go,跨行 + 零转义) -# 期望输出: -# line1 -# line2 -# one -# two -# raw\nliteral +// 字符串三形式(对齐 Rust): +// "..." 转义串,\n \t 等转义生效,可跨行 +// r"..." 原始串,零转义 +// r#"..."# 原始串带井号栏,内容可含 " +// 期望输出: +// line1 +// line2 +// one +// two +// raw\nliteral +// he said "hi" rwfunc test() -> () { - s <- """line1 -line2""" + s <- "line1 +line2" println(s) - t <- """one\ntwo""" + t <- "one\ntwo" println(t) - r <- `raw\nliteral` + r <- r"raw\nliteral" println(r) + q <- r#"he said "hi""# + println(q) } diff --git a/tutorial/11-string/08-strconv.kv b/tutorial/11-string/08-strconv.kv index 79695c88..21056aab 100644 --- a/tutorial/11-string/08-strconv.kv +++ b/tutorial/11-string/08-strconv.kv @@ -1,11 +1,11 @@ -# strconv:整数 ↔ 字符串(对齐 Go strconv,base 2..36) -# formatint(有符号)/formatuint(无符号) -> []char/utf32;parseint -> int64、parseuint -> uint64 -# 期望输出: -# ff -# 11111111 -# -42 -# 255 -# 5 +// strconv:整数 ↔ 字符串(对齐 Go strconv,base 2..36) +// formatint(有符号)/formatuint(无符号) -> []char/utf32;parseint -> int64、parseuint -> uint64 +// 期望输出: +// ff +// 11111111 +// -42 +// 255 +// 5 rwfunc test() -> () { string·formatint(255, 16) -> hex println(hex) diff --git a/tutorial/12-struct/01-linked-list.kv b/tutorial/12-struct/01-linked-list.kv index a5c1660f..c1acb84c 100644 --- a/tutorial/12-struct/01-linked-list.kv +++ b/tutorial/12-struct/01-linked-list.kv @@ -1,11 +1,11 @@ -# 链表:非表意指针(隐式 ·hex 子 key)+ dict -# 待实现:需隐式 ·hex 子 key + ‥incr 计数(见 非表意指针key生成规则·md) -# wip: 需要 ·hex 隐式创建实现 -# 语义: l 是容器 dict;l·head = {} 隐式建节点 ·1;指针 p 走链,p·next = {} 隐式建下一节点 -# 期望输出: -# 10 -# 20 -# 30 +// 链表:非表意指针(隐式 ·hex 子 key)+ dict +// 待实现:需隐式 ·hex 子 key + ‥incr 计数(见 非表意指针key生成规则·md) +// wip: 需要 ·hex 隐式创建实现 +// 语义: l 是容器 dict;l·head = {} 隐式建节点 ·1;指针 p 走链,p·next = {} 隐式建下一节点 +// 期望输出: +// 10 +// 20 +// 30 l = {} l·head = {} @@ -20,7 +20,7 @@ p·next = {} p = p·next p·val = 30 -# 遍历链表 +// 遍历链表 p = l·head while (p != null) { p·val -> v diff --git a/tutorial/12-struct/02-tree.kv b/tutorial/12-struct/02-tree.kv index 8eb80449..4f6c6dc5 100644 --- a/tutorial/12-struct/02-tree.kv +++ b/tutorial/12-struct/02-tree.kv @@ -1,9 +1,9 @@ -# 二叉树:非表意指针 + dict -# 待实现:需隐式 ·hex 子 key -# wip: 需要 ·hex 隐式创建实现 -# 语义: t 是容器;t·root = {} 隐式建根节点 ·1,left/right 各隐式建子节点 -# 期望输出: -# root=5 left=3 right=8 +// 二叉树:非表意指针 + dict +// 待实现:需隐式 ·hex 子 key +// wip: 需要 ·hex 隐式创建实现 +// 语义: t 是容器;t·root = {} 隐式建根节点 ·1,left/right 各隐式建子节点 +// 期望输出: +// root=5 left=3 right=8 t = {} t·root = {} diff --git a/tutorial/12-struct/03-graph.kv b/tutorial/12-struct/03-graph.kv index 0fe2a4f1..158dbabe 100644 --- a/tutorial/12-struct/03-graph.kv +++ b/tutorial/12-struct/03-graph.kv @@ -1,9 +1,9 @@ -# 有向图(邻接表):非表意指针 + dict -# 待实现:需隐式 ·hex 子 key -# wip: 需要 ·hex 隐式创建实现 -# 语义: g 是容器;g·a/g·b/g·c 隐式建节点,邻居存为成员引用。边 a→b, a→c -# 期望输出: -# g·a -> 2 , 3 +// 有向图(邻接表):非表意指针 + dict +// 待实现:需隐式 ·hex 子 key +// wip: 需要 ·hex 隐式创建实现 +// 语义: g 是容器;g·a/g·b/g·c 隐式建节点,邻居存为成员引用。边 a→b, a→c +// 期望输出: +// g·a -> 2 , 3 g = {} g·a = {} diff --git a/tutorial/13-stdlib/duration/days.kv b/tutorial/13-stdlib/duration/days.kv index 094dbae6..b96ff77a 100644 --- a/tutorial/13-stdlib/duration/days.kv +++ b/tutorial/13-stdlib/duration/days.kv @@ -1,7 +1,7 @@ -# days / as_days:天为单位的 duration 构造与转换 -# 期望输出: -# 2 -# 3 +// days / as_days:天为单位的 duration 构造与转换 +// 期望输出: +// 2 +// 3 rwfunc test() -> () { time/duration·as_days(time/duration·hours(48)) -> d println(d) diff --git a/tutorial/13-stdlib/duration/equal.kv b/tutorial/13-stdlib/duration/equal.kv index 53cef7c4..7955cc11 100644 --- a/tutorial/13-stdlib/duration/equal.kv +++ b/tutorial/13-stdlib/duration/equal.kv @@ -1,7 +1,7 @@ -# equal:判断两 duration 是否相等 -# 期望输出: -# true -# false +// equal:判断两 duration 是否相等 +// 期望输出: +// true +// false rwfunc test() -> () { time/duration·hours(2) -> a time/duration·hours(2) -> b diff --git a/tutorial/13-stdlib/duration/is_zero.kv b/tutorial/13-stdlib/duration/is_zero.kv index 9c33c34d..45567a8d 100644 --- a/tutorial/13-stdlib/duration/is_zero.kv +++ b/tutorial/13-stdlib/duration/is_zero.kv @@ -1,7 +1,7 @@ -# is_zero:判断 duration 是否为零 -# 期望输出: -# true -# false +// is_zero:判断 duration 是否为零 +// 期望输出: +// true +// false rwfunc test() -> () { time/duration·nanos(0) -> z time/duration·is_zero(z) -> r diff --git a/tutorial/13-stdlib/duration/max_min.kv b/tutorial/13-stdlib/duration/max_min.kv index 9f8df467..e55c9ce0 100644 --- a/tutorial/13-stdlib/duration/max_min.kv +++ b/tutorial/13-stdlib/duration/max_min.kv @@ -1,7 +1,7 @@ -# max / min:取两 duration 的较大/较小值 -# 期望输出: -# max: 3 -# min: 1 +// max / min:取两 duration 的较大/较小值 +// 期望输出: +// max: 3 +// min: 1 rwfunc test() -> () { time/duration·hours(1) -> h1 time/duration·hours(3) -> h3 diff --git a/tutorial/13-stdlib/kv/get_or.kv b/tutorial/13-stdlib/kv/get_or.kv index b6478a8d..c27a0581 100644 --- a/tutorial/13-stdlib/kv/get_or.kv +++ b/tutorial/13-stdlib/kv/get_or.kv @@ -1,7 +1,7 @@ -# kv·get_or:读取 KV 值,不存在时返回默认值 -# 期望输出: -# get_or missing: default_val -# get_or existing: world +// kv·get_or:读取 KV 值,不存在时返回默认值 +// 期望输出: +// get_or missing: default_val +// get_or existing: world rwfunc test() -> () { v1 <- kv·get_or("/missing_key", "default_val") diff --git a/tutorial/13-stdlib/kv/has.kv b/tutorial/13-stdlib/kv/has.kv index 305de844..1b96e123 100644 --- a/tutorial/13-stdlib/kv/has.kv +++ b/tutorial/13-stdlib/kv/has.kv @@ -1,7 +1,7 @@ -# kv·has:检测 KV 路径是否存在 -# 期望输出: -# has missing: false -# has existing: true +// kv·has:检测 KV 路径是否存在 +// 期望输出: +// has missing: false +// has existing: true rwfunc test() -> () { h1 <- kv·has("/missing_key") diff --git a/tutorial/13-stdlib/kv/set_default.kv b/tutorial/13-stdlib/kv/set_default.kv index 0e8dcb06..d67301b4 100644 --- a/tutorial/13-stdlib/kv/set_default.kv +++ b/tutorial/13-stdlib/kv/set_default.kv @@ -1,7 +1,7 @@ -# kv·set_default:路径不存在时写入,已存在则保留原值 -# 期望输出: -# set_default new: first_val -# set_default existing: first_val +// kv·set_default:路径不存在时写入,已存在则保留原值 +// 期望输出: +// set_default new: first_val +// set_default existing: first_val rwfunc test() -> () { kv·set_default("/sd_key", "first_val") diff --git a/tutorial/13-stdlib/math/constants.kv b/tutorial/13-stdlib/math/constants.kv index e20a4f74..25e79339 100644 --- a/tutorial/13-stdlib/math/constants.kv +++ b/tutorial/13-stdlib/math/constants.kv @@ -1,8 +1,8 @@ -# math 常量:Pi / E / Tau(runtime 内嵌 stdlib,启动自动 layout+init)。读侧用绝对路径。 -# 期望输出: -# Pi= 3.141592653589793 -# E= 2.718281828459045 -# Tau= 6.283185307179586 +// math 常量:Pi / E / Tau(runtime 内嵌 stdlib,启动自动 layout+init)。读侧用绝对路径。 +// 期望输出: +// Pi= 3.141592653589793 +// E= 2.718281828459045 +// Tau= 6.283185307179586 rwfunc test() -> () { /lib/math·Pi -> pi println("Pi=", pi) diff --git a/tutorial/13-stdlib/string/01-predicate.kv b/tutorial/13-stdlib/string/01-predicate.kv index 81a1c6f8..610e2925 100644 --- a/tutorial/13-stdlib/string/01-predicate.kv +++ b/tutorial/13-stdlib/string/01-predicate.kv @@ -1,18 +1,18 @@ -# string 谓词:eq / ne / empty / contains / startswith / endswith -# 期望输出: -# true -# false -# true -# true -# false -# true -# false -# true -# false -# false -# true -# false -# false +// string 谓词:eq / ne / empty / contains / startswith / endswith +// 期望输出: +// true +// false +// true +// true +// false +// true +// false +// true +// false +// false +// true +// false +// false rwfunc test() -> () { println(string·eq("hello", "hello")) println(string·eq("hello", "world")) diff --git a/tutorial/13-stdlib/string/02-transform.kv b/tutorial/13-stdlib/string/02-transform.kv index dad243ab..1c38ab6c 100644 --- a/tutorial/13-stdlib/string/02-transform.kv +++ b/tutorial/13-stdlib/string/02-transform.kv @@ -1,9 +1,9 @@ -# string 变换:reverse / repeat / upper / lower -# 期望输出: -# olleh -# ababab -# HELLO WORLD -# hello world +// string 变换:reverse / repeat / upper / lower +// 期望输出: +// olleh +// ababab +// HELLO WORLD +// hello world rwfunc test() -> () { println(string·reverse("hello")) println(string·repeat("ab", 3)) diff --git a/tutorial/13-stdlib/time/elapsed_ns.kv b/tutorial/13-stdlib/time/elapsed_ns.kv index 70b4b3af..928c9fcf 100644 --- a/tutorial/13-stdlib/time/elapsed_ns.kv +++ b/tutorial/13-stdlib/time/elapsed_ns.kv @@ -1,6 +1,6 @@ -# time·elapsed_ns:从指定时刻到现在的纳秒数(确定 >= 0) -# 期望输出: -# elapsed >= 0: true +// time·elapsed_ns:从指定时刻到现在的纳秒数(确定 >= 0) +// 期望输出: +// elapsed >= 0: true rwfunc test() -> () { time·now() -> t0 time·elapsed_ns(t0) -> ns diff --git a/tutorial/13-stdlib/time/equal.kv b/tutorial/13-stdlib/time/equal.kv index 9c184e87..f4e24d77 100644 --- a/tutorial/13-stdlib/time/equal.kv +++ b/tutorial/13-stdlib/time/equal.kv @@ -1,7 +1,7 @@ -# time·equal:两时刻相等判断 -# 期望输出: -# same: true -# shifted: false +// time·equal:两时刻相等判断 +// 期望输出: +// same: true +// shifted: false rwfunc test() -> () { time·now() -> t0 time/duration·seconds(1) -> one_sec diff --git a/tutorial/13-stdlib/time/since.kv b/tutorial/13-stdlib/time/since.kv index 08764f0e..3902e368 100644 --- a/tutorial/13-stdlib/time/since.kv +++ b/tutorial/13-stdlib/time/since.kv @@ -1,6 +1,6 @@ -# time·since:从指定时刻到现在的时长(确定 >= 0) -# 期望输出: -# since >= 0: true +// time·since:从指定时刻到现在的时长(确定 >= 0) +// 期望输出: +// since >= 0: true rwfunc test() -> () { time·now() -> t0 time·since(t0) -> dur diff --git a/tutorial/13-stdlib/xv/first.kv b/tutorial/13-stdlib/xv/first.kv index a958cb1c..fc967530 100644 --- a/tutorial/13-stdlib/xv/first.kv +++ b/tutorial/13-stdlib/xv/first.kv @@ -1,6 +1,6 @@ -# xv·first:取数组首元素 -# 期望输出: -# first: 10 +// xv·first:取数组首元素 +// 期望输出: +// first: 10 rwfunc test() -> () { a:[]int64 = [10, 20, 30, 40] diff --git a/tutorial/13-stdlib/xv/swap.kv b/tutorial/13-stdlib/xv/swap.kv index 3310f4af..a55d064b 100644 --- a/tutorial/13-stdlib/xv/swap.kv +++ b/tutorial/13-stdlib/xv/swap.kv @@ -1,8 +1,8 @@ -# xv·swap:交换数组两下标元素,返回新数组,原数组不变 -# 期望输出: -# swap(0,2)[0]: 30 -# swap(0,2)[2]: 10 -# original[0]: 10 +// xv·swap:交换数组两下标元素,返回新数组,原数组不变 +// 期望输出: +// swap(0,2)[0]: 30 +// swap(0,2)[2]: 10 +// original[0]: 10 rwfunc test() -> () { a:[]int64 = [10, 20, 30, 40] diff --git a/tutorial/14-networld/01-exec.kv b/tutorial/14-networld/01-exec.kv index c6e105ea..63aef4dd 100644 --- a/tutorial/14-networld/01-exec.kv +++ b/tutorial/14-networld/01-exec.kv @@ -1,13 +1,13 @@ -# networld/proc·exec:同步执行外部命令到结束,返回 uint8 退出码 -# exec(args, envs) -> exitcode。args/envs 为 stringkeymap({..} 字面量),成员 []char/utf32 -# args 首成员=可执行文件;envs 空(map())=继承父环境,非空=完整替换 -# exitcode:正常=退出码;信号终止=128+signo;spawn 失败/无 argv=127(对齐 shell) -# 期望输出: -# hello from child -# ok= 0 -# seven= 7 -# missing= 127 -# FOO=bar123 +// networld/proc·exec:同步执行外部命令到结束,返回 uint8 退出码 +// exec(args, envs) -> exitcode。args/envs 为 stringkeymap({..} 字面量),成员 []char/utf32 +// args 首成员=可执行文件;envs 空(map())=继承父环境,非空=完整替换 +// exitcode:正常=退出码;信号终止=128+signo;spawn 失败/无 argv=127(对齐 shell) +// 期望输出: +// hello from child +// ok= 0 +// seven= 7 +// missing= 127 +// FOO=bar123 rwfunc test() -> () { noenv = map() echoargs = {"sh", "-c", "echo hello from child"} diff --git a/tutorial/14-networld/02-bash.kv b/tutorial/14-networld/02-bash.kv index deeadde0..0b0f2757 100644 --- a/tutorial/14-networld/02-bash.kv +++ b/tutorial/14-networld/02-bash.kv @@ -1,7 +1,7 @@ -# networld/proc·exec 启动 bash:算术求值,取退出码 -# 期望输出: -# bash 42 -# exit= 0 +// networld/proc·exec 启动 bash:算术求值,取退出码 +// 期望输出: +// bash 42 +// exit= 0 rwfunc test() -> () { noenv = map() args = {"bash", "-c", "echo bash $((6*7))"} diff --git a/tutorial/14-networld/03-python.kv b/tutorial/14-networld/03-python.kv index 9e6e6d22..d1007a23 100644 --- a/tutorial/14-networld/03-python.kv +++ b/tutorial/14-networld/03-python.kv @@ -1,7 +1,7 @@ -# networld/proc·exec 启动 python3:执行一行脚本,取退出码 -# 期望输出: -# python 1024 -# exit= 0 +// networld/proc·exec 启动 python3:执行一行脚本,取退出码 +// 期望输出: +// python 1024 +// exit= 0 rwfunc test() -> () { noenv = map() args = {"python3", "-c", "print('python', 2**10)"} diff --git a/tutorial/14-networld/04-kvlang.kv b/tutorial/14-networld/04-kvlang.kv index 2a35b718..dbd66318 100644 --- a/tutorial/14-networld/04-kvlang.kv +++ b/tutorial/14-networld/04-kvlang.kv @@ -1,8 +1,8 @@ -# networld/proc·exec 启动 kvlang 自身:子进程继承 KVSPACE,与父共享同一 redis -# 父作为子的父进程,同步等待并取回退出码 -# 期望输出: -# kvlang in kvlang -# exit= 0 +// networld/proc·exec 启动 kvlang 自身:子进程继承 KVSPACE,与父共享同一 redis +// 父作为子的父进程,同步等待并取回退出码 +// 期望输出: +// kvlang in kvlang +// exit= 0 rwfunc test() -> () { noenv = map() args = {"kvlang", "-c", "print(\"kvlang in kvlang\")"} diff --git a/tutorial/14-networld/05-capture.kv b/tutorial/14-networld/05-capture.kv index 3ac1167e..f5404f94 100644 --- a/tutorial/14-networld/05-capture.kv +++ b/tutorial/14-networld/05-capture.kv @@ -1,11 +1,11 @@ -# networld/proc·exec:捕获子进程 stdout/stderr -# exec(args, envs) -> code, out, err。绑定 out/err 写槽即捕获(未绑定则继承父终端) -# out/err 是 @[]uint8 扩展句柄:body 指向 /networld/{host}/proc/{pid}/{stdout,stderr} -# 读该句柄时按 body 前缀路由回 /lib/networld/proc 兑现物理字节 -# 期望输出: -# code= 0 -# out= hi -# err= oops +// networld/proc·exec:捕获子进程 stdout/stderr +// exec(args, envs) -> code, out, err。绑定 out/err 写槽即捕获(未绑定则继承父终端) +// out/err 是 @[]uint8 扩展句柄:body 指向 /networld/{host}/proc/{pid}/{stdout,stderr} +// 读该句柄时按 body 前缀路由回 /lib/networld/proc 兑现物理字节 +// 期望输出: +// code= 0 +// out= hi +// err= oops rwfunc test() -> () { noenv = map() a = {"sh", "-c", "echo hi; echo oops 1>&2"} diff --git a/tutorial/14-networld/06-fs.kv b/tutorial/14-networld/06-fs.kv index df87686c..f8654655 100644 --- a/tutorial/14-networld/06-fs.kv +++ b/tutorial/14-networld/06-fs.kv @@ -1,10 +1,10 @@ -# networld/fs·size + networld/fs·read + xv·reinterpret:文件 → 字符串 -# fs·size(p) -> n 取字节大小 -# fs·read(p, start, off) -> raw 从 start 起读 off 字节,返回 []uint8 -# xv·reinterpret(raw, "[]char/utf8") -> s body 字节原样,整个 kindexpr 换成传入的 -# 期望输出: -# size= 12 -# text= hello kvlang +// networld/fs·size + networld/fs·read + xv·reinterpret:文件 → 字符串 +// fs·size(p) -> n 取字节大小 +// fs·read(p, start, off) -> raw 从 start 起读 off 字节,返回 []uint8 +// xv·reinterpret(raw, "[]char/utf8") -> s body 字节原样,整个 kindexpr 换成传入的 +// 期望输出: +// size= 12 +// text= hello kvlang rwfunc test() -> () { p = "/tmp/kvlangfs_demo.txt" noenv = map() diff --git a/tutorial/14-networld/07-fs-write.kv b/tutorial/14-networld/07-fs-write.kv index 594895df..74f73886 100644 --- a/tutorial/14-networld/07-fs-write.kv +++ b/tutorial/14-networld/07-fs-write.kv @@ -1,12 +1,12 @@ -# networld/fs·write + append:字节写入/追加,配 xv·reinterpret 做字符串往返 -# fs·write(p, bytes) -> n 覆盖写(创建/截断),返回写入字节数 -# fs·append(p, bytes) -> n 追加到末尾,返回追加字节数 -# 字符串是 char/utf32(每字符 4 字节):reinterpret 成 []uint8 落盘,回读再 reinterpret 回 []char/utf32 -# 期望输出: -# write= 20 -# append= 24 -# size= 44 -# text= hello world +// networld/fs·write + append:字节写入/追加,配 xv·reinterpret 做字符串往返 +// fs·write(p, bytes) -> n 覆盖写(创建/截断),返回写入字节数 +// fs·append(p, bytes) -> n 追加到末尾,返回追加字节数 +// 字符串是 char/utf32(每字符 4 字节):reinterpret 成 []uint8 落盘,回读再 reinterpret 回 []char/utf32 +// 期望输出: +// write= 20 +// append= 24 +// size= 44 +// text= hello world rwfunc test() -> () { p = "/tmp/kvlang_fs_write.txt" networld/fs·write(p, xv·reinterpret("hello", "[]uint8")) -> wn diff --git a/tutorial/14-networld/08-fs-dir.kv b/tutorial/14-networld/08-fs-dir.kv index baf3b19a..a9824451 100644 --- a/tutorial/14-networld/08-fs-dir.kv +++ b/tutorial/14-networld/08-fs-dir.kv @@ -1,13 +1,13 @@ -# networld/fs·mkdir + list + del:目录创建、列举成员、删除 -# fs·mkdir(d) -> 0 创建目录(含缺失父级,幂等) -# fs·list(d) -> names 列目录成员(名字序,[]stringkeymap);散 key 两步遍历 kv·listn+kv·get 取名 -# fs·del(p) -> 0 删文件或空目录;非空目录失败返回 -1 -# 期望输出: -# count= 2 -# name= a.txt -# name= b.txt -# delfile= 0 -# deldir= 0 +// networld/fs·mkdir + list + del:目录创建、列举成员、删除 +// fs·mkdir(d) -> 0 创建目录(含缺失父级,幂等) +// fs·list(d) -> names 列目录成员(名字序,[]stringkeymap);散 key 两步遍历 kv·listn+kv·get 取名 +// fs·del(p) -> 0 删文件或空目录;非空目录失败返回 -1 +// 期望输出: +// count= 2 +// name= a.txt +// name= b.txt +// delfile= 0 +// deldir= 0 rwfunc test() -> () { d = "/tmp/kvlang_fs_dir" noenv = map() diff --git a/tutorial/14-networld/09-fs-exists.kv b/tutorial/14-networld/09-fs-exists.kv index e6b5fae7..1122db65 100644 --- a/tutorial/14-networld/09-fs-exists.kv +++ b/tutorial/14-networld/09-fs-exists.kv @@ -1,9 +1,9 @@ -# networld/fs·exists:存在性判定,写入/删除前后对比 -# fs·exists(p) -> bool -# 期望输出: -# before= false -# after_write= true -# after_del= false +// networld/fs·exists:存在性判定,写入/删除前后对比 +// fs·exists(p) -> bool +// 期望输出: +// before= false +// after_write= true +// after_del= false rwfunc test() -> () { p = "/tmp/kvlang_fs_exists.txt" noenv = map() diff --git a/tutorial/15-vthread/01-call.kv b/tutorial/15-vthread/01-call.kv index 8403a712..61f61f44 100644 --- a/tutorial/15-vthread/01-call.kv +++ b/tutorial/15-vthread/01-call.kv @@ -1,10 +1,10 @@ -# vthread·call(funckey):在当前 vthread(同 vid,进程↔vid 1:1)按运行时 funckey 动态调用 -# funckey 是去 /lib 前缀的 func key 串(裸名 pkg 空即裸名);被调跑完回到本指令后继续 -# 与 vthread·run 不同:不新开 vid、不 WATCH 挂起——被调里的 rwir 由当前驱动就地派发 -# 期望输出: -# before call -# hello from dynamic call -# after call +// vthread·call(funckey):在当前 vthread(同 vid,进程↔vid 1:1)按运行时 funckey 动态调用 +// funckey 是去 /lib 前缀的 func key 串(裸名 pkg 空即裸名);被调跑完回到本指令后继续 +// 与 vthread·run 不同:不新开 vid、不 WATCH 挂起——被调里的 rwir 由当前驱动就地派发 +// 期望输出: +// before call +// hello from dynamic call +// after call rwfunc greet() -> () { println("hello from dynamic call") } diff --git a/tutorial/15-vthread/02-crashrecover.kv b/tutorial/15-vthread/02-crashrecover.kv index 4b31d187..51dcb347 100644 --- a/tutorial/15-vthread/02-crashrecover.kv +++ b/tutorial/15-vthread/02-crashrecover.kv @@ -1,14 +1,14 @@ -# 崩溃恢复演示:每步把进度写进 kvspace(/crashtest/step),再 sleep 造一个可被外部打断的窗口。 -# 直接 `kvlang 02-crashrecover.kv` → 完整跑完 step 1..5(下方期望输出,也是 tutorial 回归路径)。 -# 崩溃恢复场景由同目录 crashrecover.sh 编排:跑到 step3 时外部 SIGKILL 掉 kvlang, -# 再另起进程 `kvlang run ` 从 kvspace 里持久化的 pc 续跑——只补打 step 4/5,不重演 1..3。 -# 期望输出: -# step 1 -# step 2 -# step 3 -# step 4 -# step 5 -# complete final= 5 +// 崩溃恢复演示:每步把进度写进 kvspace(/crashtest/step),再 sleep 造一个可被外部打断的窗口。 +// 直接 `kvlang 02-crashrecover.kv` → 完整跑完 step 1..5(下方期望输出,也是 tutorial 回归路径)。 +// 崩溃恢复场景由同目录 crashrecover.sh 编排:跑到 step3 时外部 SIGKILL 掉 kvlang, +// 再另起进程 `kvlang run ` 从 kvspace 里持久化的 pc 续跑——只补打 step 4/5,不重演 1..3。 +// 期望输出: +// step 1 +// step 2 +// step 3 +// step 4 +// step 5 +// complete final= 5 rwfunc test() -> () { 0 -> i while (i < 5) { diff --git a/tutorial/15-vthread/03-create-run.kv b/tutorial/15-vthread/03-create-run.kv index a41e6f09..b1e60cf4 100644 --- a/tutorial/15-vthread/03-create-run.kv +++ b/tutorial/15-vthread/03-create-run.kv @@ -1,11 +1,11 @@ -# vthread 创建/运行两步分离,对应 2 个 rwir(与 2 个 kvlang 子命令 create/run 同形): -# vthread·create(funckey) -> vid:只 bootstrap 首指令、置 init,返回 vid 句柄,不运行 -# vthread·run(vid):以 vid 为参数,从其持久化 pc 跑到结束(阻塞) -# vid 是两步之间的句柄;与 vthread·call 不同——create/run 新开独立 vid,call 是同 vid 内动态调用 -# 期望输出: -# created -# hello from vthread -# done +// vthread 创建/运行两步分离,对应 2 个 rwir(与 2 个 kvlang 子命令 create/run 同形): +// vthread·create(funckey) -> vid:只 bootstrap 首指令、置 init,返回 vid 句柄,不运行 +// vthread·run(vid):以 vid 为参数,从其持久化 pc 跑到结束(阻塞) +// vid 是两步之间的句柄;与 vthread·call 不同——create/run 新开独立 vid,call 是同 vid 内动态调用 +// 期望输出: +// created +// hello from vthread +// done rwfunc greet() -> () { println("hello from vthread") } diff --git a/tutorial/15-vthread/04-sleep.kv b/tutorial/15-vthread/04-sleep.kv index 05119747..f3805268 100644 --- a/tutorial/15-vthread/04-sleep.kv +++ b/tutorial/15-vthread/04-sleep.kv @@ -1,8 +1,8 @@ -# vthread·sleep(dur):让当前 vthread 阻塞一个 duration(纳秒精度),到点后续跑下一指令 -# dur 由 time/duration· 家族构造(nanos/millis/seconds/minutes/hours) -# 单进程模型下即阻塞驱动线程;与 vthread·setstatus("wait") 的挂起-恢复不同 -# 期望输出: -# slept >= 10ms: true +// vthread·sleep(dur):让当前 vthread 阻塞一个 duration(纳秒精度),到点后续跑下一指令 +// dur 由 time/duration· 家族构造(nanos/millis/seconds/minutes/hours) +// 单进程模型下即阻塞驱动线程;与 vthread·setstatus("wait") 的挂起-恢复不同 +// 期望输出: +// slept >= 10ms: true rwfunc test() -> () { time/duration·millis(10) -> d time·now() -> t0 diff --git a/tutorial/error_cases/array_param/mutate_correct.kv b/tutorial/error_cases/array_param/mutate_correct.kv index bb8a7575..e4ec5401 100644 --- a/tutorial/error_cases/array_param/mutate_correct.kv +++ b/tutorial/error_cases/array_param/mutate_correct.kv @@ -1,16 +1,16 @@ -# ✅ 正确:数组在写参位置,函数返回修改后的数组。 -# expected: -# has no type annotation +// ✅ 正确:数组在写参位置,函数返回修改后的数组。 +// expected: +// has no type annotation rwfunc mutate() -> (a) { arr:[]int64 = [10, 20] - 99 -> xv·set(arr, 0, 99) # set 返回修改后的数组 + 99 -> xv·set(arr, 0, 99) // set 返回修改后的数组 1 -> xv·set(arr, 1, 1) - arr -> a # 返回修改后的数组给调用方 + arr -> a // 返回修改后的数组给调用方 } rwfunc test() -> () { mutate() -> result xv·at(result, 0) -> v0 xv·at(result, 1) -> v1 - println(v0, v1) # 99 1 + println(v0, v1) // 99 1 } diff --git a/tutorial/error_cases/array_param/mutate_literal.kv b/tutorial/error_cases/array_param/mutate_literal.kv index 54f4db29..f55b35c9 100644 --- a/tutorial/error_cases/array_param/mutate_literal.kv +++ b/tutorial/error_cases/array_param/mutate_literal.kv @@ -1,10 +1,10 @@ -# ❌ 错误:数组字面量放读参位置,函数内写 a[k] <- v 被 fix-027 拒绝。 -# expected: -# read param "a" cannot be used as write slot -# kvlang 铁律:读参只读。要修改数组,必须放写参位置。 -# 正确: rwfunc mutate() -> (a) { array(10,20) -> a; 99 -> a[0]; ... } +// ❌ 错误:数组字面量放读参位置,函数内写 a[k] <- v 被 fix-027 拒绝。 +// expected: +// read param "a" cannot be used as write slot +// kvlang 铁律:读参只读。要修改数组,必须放写参位置。 +// 正确: rwfunc mutate() -> (a) { array(10,20) -> a; 99 -> a[0]; ... } rwfunc mutate(a) -> () { - 99 -> a[0] # ❌ a 是读参,a[0] 展开为 kv·set(a,0,99) -> a,写入读参槽被拒绝 + 99 -> a[0] // ❌ a 是读参,a[0] 展开为 kv·set(a,0,99) -> a,写入读参槽被拒绝 } rwfunc test() -> () { diff --git a/tutorial/error_cases/index_error/at_oob.kv b/tutorial/error_cases/index_error/at_oob.kv index 84216540..f9d6a66f 100644 --- a/tutorial/error_cases/index_error/at_oob.kv +++ b/tutorial/error_cases/index_error/at_oob.kv @@ -1,5 +1,5 @@ -# expected: -# error: KeyError: kv·at: key not found +// expected: +// error: KeyError: kv·at: key not found rwfunc test() -> () { kv·get([1, 2], 5) -> _ diff --git a/tutorial/error_cases/index_error/char_oob.kv b/tutorial/error_cases/index_error/char_oob.kv index 5ea3fea9..6b08b8c5 100644 --- a/tutorial/error_cases/index_error/char_oob.kv +++ b/tutorial/error_cases/index_error/char_oob.kv @@ -1,5 +1,5 @@ -# expected: -# IndexError: at: index +// expected: +// IndexError: at: index rwfunc test() -> () { string·char("hello", 10) diff --git a/tutorial/error_cases/index_error/slice_oob.kv b/tutorial/error_cases/index_error/slice_oob.kv index 96b04abd..160075c1 100644 --- a/tutorial/error_cases/index_error/slice_oob.kv +++ b/tutorial/error_cases/index_error/slice_oob.kv @@ -1,5 +1,5 @@ -# expected: -# IndexError +// expected: +// IndexError rwfunc test() -> () { string·slice("hello", 0, 10) diff --git a/tutorial/error_cases/index_error/typed_array_string_key.kv b/tutorial/error_cases/index_error/typed_array_string_key.kv index 8584389e..18ac76b9 100644 --- a/tutorial/error_cases/index_error/typed_array_string_key.kv +++ b/tutorial/error_cases/index_error/typed_array_string_key.kv @@ -1,5 +1,5 @@ -# expected: -# error: KeyError: kv·at: key not found +// expected: +// error: KeyError: kv·at: key not found rwfunc test() -> () { arr:[]int32 = [1, 2, 3] diff --git a/tutorial/error_cases/key_error/kv_at_missing.kv b/tutorial/error_cases/key_error/kv_at_missing.kv index deb05708..579e5dfc 100644 --- a/tutorial/error_cases/key_error/kv_at_missing.kv +++ b/tutorial/error_cases/key_error/kv_at_missing.kv @@ -1,5 +1,5 @@ -# expected: -# error: KeyError: kv·at: key not found +// expected: +// error: KeyError: kv·at: key not found rwfunc test() -> () { kv·get("/x", "y") -> _ diff --git a/tutorial/error_cases/name_error/nosuch_func.kv b/tutorial/error_cases/name_error/nosuch_func.kv index a571d28a..76c9ae89 100644 --- a/tutorial/error_cases/name_error/nosuch_func.kv +++ b/tutorial/error_cases/name_error/nosuch_func.kv @@ -1,5 +1,5 @@ -# expected: -# error: NameError: rwir/rwfunc not found +// expected: +// error: NameError: rwir/rwfunc not found rwfunc test() -> () { nosuch() diff --git a/tutorial/error_cases/none_type_error/none_arith.kv b/tutorial/error_cases/none_type_error/none_arith.kv index afc8da62..cadac1cc 100644 --- a/tutorial/error_cases/none_type_error/none_arith.kv +++ b/tutorial/error_cases/none_type_error/none_arith.kv @@ -1,5 +1,5 @@ -# expected -# TypeError: None in arithmetic +// expected +// TypeError: None in arithmetic rwfunc test() -> () { None + 1 -> x } diff --git a/tutorial/error_cases/none_type_error/none_bool.kv b/tutorial/error_cases/none_type_error/none_bool.kv index 86233b00..01efdbbe 100644 --- a/tutorial/error_cases/none_type_error/none_bool.kv +++ b/tutorial/error_cases/none_type_error/none_bool.kv @@ -1,5 +1,5 @@ -# expected -# TypeError: None in branch condition +// expected +// TypeError: None in branch condition rwfunc test() -> () { if (None) { } } diff --git a/tutorial/error_cases/none_type_error/none_cast.kv b/tutorial/error_cases/none_type_error/none_cast.kv index bd03c162..ecff43da 100644 --- a/tutorial/error_cases/none_type_error/none_cast.kv +++ b/tutorial/error_cases/none_type_error/none_cast.kv @@ -1,5 +1,5 @@ -# expected -# TypeError: cannot cast None +// expected +// TypeError: cannot cast None rwfunc test() -> () { int64(None) -> x } diff --git a/tutorial/error_cases/none_type_error/none_cmp.kv b/tutorial/error_cases/none_type_error/none_cmp.kv index 208fe0a9..14c93ea4 100644 --- a/tutorial/error_cases/none_type_error/none_cmp.kv +++ b/tutorial/error_cases/none_type_error/none_cmp.kv @@ -1,5 +1,5 @@ -# expected -# TypeError: None in comparison +// expected +// TypeError: None in comparison rwfunc test() -> () { None < 0 -> r } diff --git a/tutorial/error_cases/read_only/dup_param.kv b/tutorial/error_cases/read_only/dup_param.kv index b14ad91b..51e847c5 100644 --- a/tutorial/error_cases/read_only/dup_param.kv +++ b/tutorial/error_cases/read_only/dup_param.kv @@ -1,6 +1,6 @@ -# expected: -# param "A" appears in both read-params and write-params -# func f: read param "A" cannot be used as write slot +// expected: +// param "A" appears in both read-params and write-params +// func f: read param "A" cannot be used as write slot rwfunc f(A:int64) -> (A:int64) { A = 5 } diff --git a/tutorial/error_cases/read_only/write_param.kv b/tutorial/error_cases/read_only/write_param.kv index d8a6c2de..5b3a4d4b 100644 --- a/tutorial/error_cases/read_only/write_param.kv +++ b/tutorial/error_cases/read_only/write_param.kv @@ -1,5 +1,5 @@ -# expected: -# func f: read param "A" cannot be used as write slot +// expected: +// func f: read param "A" cannot be used as write slot rwfunc f(A:int64) -> () { A = 5 } diff --git a/tutorial/error_cases/recursion_error/stack_overflow.kv b/tutorial/error_cases/recursion_error/stack_overflow.kv index 2e345f64..11303aa3 100644 --- a/tutorial/error_cases/recursion_error/stack_overflow.kv +++ b/tutorial/error_cases/recursion_error/stack_overflow.kv @@ -1,5 +1,5 @@ -# expected: -# error: RecursionError: stack overflow +// expected: +// error: RecursionError: stack overflow rwfunc f() -> () { f() } diff --git a/tutorial/error_cases/runtime_error/bootstrap_missing.kv b/tutorial/error_cases/runtime_error/bootstrap_missing.kv index 877c0598..548f6f11 100644 --- a/tutorial/error_cases/runtime_error/bootstrap_missing.kv +++ b/tutorial/error_cases/runtime_error/bootstrap_missing.kv @@ -1,6 +1,6 @@ -# expected: -# error: NameError: rwir/rwfunc not found: absent -# NameError: rwir/rwfunc not found: absent +// expected: +// error: NameError: rwir/rwfunc not found: absent +// NameError: rwir/rwfunc not found: absent rwfunc test() -> () { absent() } diff --git a/tutorial/error_cases/syntax_error/break_outside_loop.kv b/tutorial/error_cases/syntax_error/break_outside_loop.kv index 2bc54344..ce321642 100644 --- a/tutorial/error_cases/syntax_error/break_outside_loop.kv +++ b/tutorial/error_cases/syntax_error/break_outside_loop.kv @@ -1,5 +1,5 @@ -# expected -# break outside loop +// expected +// break outside loop rwfunc f() -> () { break } diff --git a/tutorial/error_cases/syntax_error/return_with_value.kv b/tutorial/error_cases/syntax_error/return_with_value.kv index 094876e7..e05c55a2 100644 --- a/tutorial/error_cases/syntax_error/return_with_value.kv +++ b/tutorial/error_cases/syntax_error/return_with_value.kv @@ -1,5 +1,5 @@ -# expected -# return cannot take +// expected +// return cannot take rwfunc f() -> () { return 42 } diff --git a/tutorial/error_cases/syntax_error/sparse_literal_position.kv b/tutorial/error_cases/syntax_error/sparse_literal_position.kv index e9435bd0..2df4972e 100644 --- a/tutorial/error_cases/syntax_error/sparse_literal_position.kv +++ b/tutorial/error_cases/syntax_error/sparse_literal_position.kv @@ -1,6 +1,6 @@ -# expected -# scattered-key array literal {...} is only allowed as an assignment right-hand side -# 修复: 括号规约 — {..} 散 key 字面量只能作赋值右值 x = {..} 或 for-in 源 for(s in {..}) +// expected +// scattered-key array literal {...} is only allowed as an assignment right-hand side +// 修复: 括号规约 — {..} 散 key 字面量只能作赋值右值 x = {..} 或 for-in 源 for(s in {..}) rwfunc test() -> () { println({1, 2, 3}) } diff --git a/tutorial/error_cases/syntax_error/top_level_if.kv b/tutorial/error_cases/syntax_error/top_level_if.kv index 57c8e1a2..f0fac46d 100644 --- a/tutorial/error_cases/syntax_error/top_level_if.kv +++ b/tutorial/error_cases/syntax_error/top_level_if.kv @@ -1,5 +1,5 @@ -# expected -# top-level if +// expected +// top-level if rwfunc f() -> () { } rwfunc test() -> () { diff --git a/tutorial/error_cases/syntax_error/unclosed_block.kv b/tutorial/error_cases/syntax_error/unclosed_block.kv index 5a92cde6..6e10a6d0 100644 --- a/tutorial/error_cases/syntax_error/unclosed_block.kv +++ b/tutorial/error_cases/syntax_error/unclosed_block.kv @@ -1,4 +1,4 @@ -# expected -# expected +// expected +// expected rwfunc f() -> () { x = 1 diff --git a/tutorial/error_cases/type_error/arith_bool.kv b/tutorial/error_cases/type_error/arith_bool.kv index 64be427b..b95fe275 100644 --- a/tutorial/error_cases/type_error/arith_bool.kv +++ b/tutorial/error_cases/type_error/arith_bool.kv @@ -1,6 +1,6 @@ -# expected -# TypeError: expected numeric, got bool -# 修复: todo-033 — bool 不可参与算术运算(五语言中仅 Python/C 允许,kvlang 选严格阵营) +// expected +// TypeError: expected numeric, got bool +// 修复: todo-033 — bool 不可参与算术运算(五语言中仅 Python/C 允许,kvlang 选严格阵营) rwfunc test() -> () { true + false -> x } diff --git a/tutorial/error_cases/type_error/arith_string.kv b/tutorial/error_cases/type_error/arith_string.kv index e71bd2f1..132f9f40 100644 --- a/tutorial/error_cases/type_error/arith_string.kv +++ b/tutorial/error_cases/type_error/arith_string.kv @@ -1,6 +1,6 @@ -# expected -# TypeError: expected numeric, got char/utf32 -# 修复: todo-033 — asFloat/asInt 不再接受非数字类型;string+int 直接 TypeError +// expected +// TypeError: expected numeric, got char/utf32 +// 修复: todo-033 — asFloat/asInt 不再接受非数字类型;string+int 直接 TypeError rwfunc test() -> () { "hello" + int64(3) -> x } diff --git a/tutorial/error_cases/type_error/bitwise_bool.kv b/tutorial/error_cases/type_error/bitwise_bool.kv index aa4b6a25..0d374deb 100644 --- a/tutorial/error_cases/type_error/bitwise_bool.kv +++ b/tutorial/error_cases/type_error/bitwise_bool.kv @@ -1,6 +1,6 @@ -# expected -# TypeError: expected integer, got bool -# 修复: todo-033 — bool | int 曾是静默 coerce 为 1|3=3 +// expected +// TypeError: expected integer, got bool +// 修复: todo-033 — bool | int 曾是静默 coerce 为 1|3=3 rwfunc test() -> () { true | int64(3) -> x } diff --git a/tutorial/error_cases/type_error/bitwise_float.kv b/tutorial/error_cases/type_error/bitwise_float.kv index 486f0c25..e09ae2c9 100644 --- a/tutorial/error_cases/type_error/bitwise_float.kv +++ b/tutorial/error_cases/type_error/bitwise_float.kv @@ -1,6 +1,6 @@ -# expected -# TypeError: expected integer, got float64 -# 修复: todo-033 — 位运算仅接受整数(五语言一致:C 警告、C++/Rust/Go 编译错误、JS 先 ToInt32 但逻辑无意义) +// expected +// TypeError: expected integer, got float64 +// 修复: todo-033 — 位运算仅接受整数(五语言一致:C 警告、C++/Rust/Go 编译错误、JS 先 ToInt32 但逻辑无意义) rwfunc test() -> () { float64(1.0) & int64(3) -> x } diff --git a/tutorial/error_cases/type_error/char_bad_args.kv b/tutorial/error_cases/type_error/char_bad_args.kv index 7a793475..7d050ff1 100644 --- a/tutorial/error_cases/type_error/char_bad_args.kv +++ b/tutorial/error_cases/type_error/char_bad_args.kv @@ -1,5 +1,5 @@ -# expected: -# error: TypeError: string·char requires string and index +// expected: +// error: TypeError: string·char requires string and index rwfunc test() -> () { string·char(1) diff --git a/tutorial/error_cases/type_error/cmp_int_bool.kv b/tutorial/error_cases/type_error/cmp_int_bool.kv index 79368f6b..006b63eb 100644 --- a/tutorial/error_cases/type_error/cmp_int_bool.kv +++ b/tutorial/error_cases/type_error/cmp_int_bool.kv @@ -1,6 +1,6 @@ -# expected -# TypeError: cannot compare int64 with bool -# 修复: todo-033 — int>bool 曾通过 asInt 将 bool→0/1 静默比较 +// expected +// TypeError: cannot compare int64 with bool +// 修复: todo-033 — int>bool 曾通过 asInt 将 bool→0/1 静默比较 rwfunc test() -> () { int64(1) < true -> x } diff --git a/tutorial/error_cases/type_error/cmp_mixed.kv b/tutorial/error_cases/type_error/cmp_mixed.kv index 27ab255b..1f649b70 100644 --- a/tutorial/error_cases/type_error/cmp_mixed.kv +++ b/tutorial/error_cases/type_error/cmp_mixed.kv @@ -1,6 +1,6 @@ -# expected -# TypeError: cannot compare int64 with char/utf32 -# 修复: todo-033 — evalCmp 曾对所有类型对回退到字符串比较(dict==array 也"成功"),现跨类型直接 TypeError +// expected +// TypeError: cannot compare int64 with char/utf32 +// 修复: todo-033 — evalCmp 曾对所有类型对回退到字符串比较(dict==array 也"成功"),现跨类型直接 TypeError rwfunc test() -> () { int64(5) == "hello" -> x } diff --git a/tutorial/error_cases/type_error/compact_string_array.kv b/tutorial/error_cases/type_error/compact_string_array.kv index 7b460e48..1486962f 100644 --- a/tutorial/error_cases/type_error/compact_string_array.kv +++ b/tutorial/error_cases/type_error/compact_string_array.kv @@ -1,6 +1,6 @@ -# expected -# compact array [...] cannot hold variable-length string element -# 修复: 括号规约 — compact [..] 只容定长元素;变长字符串数组必须用散 key {..} +// expected +// compact array [...] cannot hold variable-length string element +// 修复: 括号规约 — compact [..] 只容定长元素;变长字符串数组必须用散 key {..} rwfunc test() -> () { x = ["af", "f23gw", "232f"] println(x) diff --git a/tutorial/error_cases/type_error/concat_non_string.kv b/tutorial/error_cases/type_error/concat_non_string.kv index 2500d22e..1662afd5 100644 --- a/tutorial/error_cases/type_error/concat_non_string.kv +++ b/tutorial/error_cases/type_error/concat_non_string.kv @@ -1,6 +1,6 @@ -# expected -# TypeError: string·concat requires strings, got int64 and bool -# 修复: todo-033 — concat 曾将 42→"42", true→"true" 静默拼接为 "42true" +// expected +// TypeError: string·concat requires strings, got int64 and bool +// 修复: todo-033 — concat 曾将 42→"42", true→"true" 静默拼接为 "42true" rwfunc test() -> () { string·concat(int64(42), true) -> x } diff --git a/tutorial/error_cases/type_error/minmax_mixed.kv b/tutorial/error_cases/type_error/minmax_mixed.kv index 870ee41c..f6599dd5 100644 --- a/tutorial/error_cases/type_error/minmax_mixed.kv +++ b/tutorial/error_cases/type_error/minmax_mixed.kv @@ -1,6 +1,6 @@ -# expected -# TypeError: max/min requires numeric, got int64 and char/utf32 -# 修复: min/max 现为 native 逐 kind op,混类型在运行时 TypeError +// expected +// TypeError: max/min requires numeric, got int64 and char/utf32 +// 修复: min/max 现为 native 逐 kind op,混类型在运行时 TypeError rwfunc test() -> () { min(int64(1), "a") -> x } diff --git a/tutorial/error_cases/type_error/mod_float.kv b/tutorial/error_cases/type_error/mod_float.kv index 8a20e221..a0014d8b 100644 --- a/tutorial/error_cases/type_error/mod_float.kv +++ b/tutorial/error_cases/type_error/mod_float.kv @@ -1,6 +1,6 @@ -# expected -# TypeError: expected integer, got float64 -# 修复: todo-033 — 模运算仅整数(五语言中仅 Python/JS 支持浮点取模,取 C/Go/Rust 阵营) +// expected +// TypeError: expected integer, got float64 +// 修复: todo-033 — 模运算仅整数(五语言中仅 Python/JS 支持浮点取模,取 C/Go/Rust 阵营) rwfunc test() -> () { float64(10.5) % int64(3) -> x } diff --git a/tutorial/error_cases/type_error/neg_unsigned.kv b/tutorial/error_cases/type_error/neg_unsigned.kv index 2c645b22..cd7ee587 100644 --- a/tutorial/error_cases/type_error/neg_unsigned.kv +++ b/tutorial/error_cases/type_error/neg_unsigned.kv @@ -1,6 +1,6 @@ -# expected -# TypeError: cannot negate unsigned uint8 -# 修复: fix-034 — neg 逐 kind switch,uint8/16/32/64 拒绝取负(五语言中 C 编译警告、Rust 编译错误、Go 编译错误、Python/JS 无符号类型) +// expected +// TypeError: cannot negate unsigned uint8 +// 修复: fix-034 — neg 逐 kind switch,uint8/16/32/64 拒绝取负(五语言中 C 编译警告、Rust 编译错误、Go 编译错误、Python/JS 无符号类型) rwfunc test() -> () { uint8(5) -> x -(x) -> y diff --git a/tutorial/error_cases/type_error/sqrt_string.kv b/tutorial/error_cases/type_error/sqrt_string.kv index b77d341f..ca9aee00 100644 --- a/tutorial/error_cases/type_error/sqrt_string.kv +++ b/tutorial/error_cases/type_error/sqrt_string.kv @@ -1,6 +1,6 @@ -# expected -# TypeError: expected numeric, got char/utf32 -# 修复: todo-033 — sqrt/exp/log/sign 曾通过 asFloat default 将 "hello"→0.0 静默计算 +// expected +// TypeError: expected numeric, got char/utf32 +// 修复: todo-033 — sqrt/exp/log/sign 曾通过 asFloat default 将 "hello"→0.0 静默计算 rwfunc test() -> () { sqrt("hello") -> x √("hello") -> x_m diff --git a/tutorial/error_cases/value_error/log_range.kv b/tutorial/error_cases/value_error/log_range.kv index 82d10c1a..48cce428 100644 --- a/tutorial/error_cases/value_error/log_range.kv +++ b/tutorial/error_cases/value_error/log_range.kv @@ -1,5 +1,5 @@ -# expected: -# error: ValueError: log of non-positive number +// expected: +// error: ValueError: log of non-positive number rwfunc test() -> () { log(-5) -> _ diff --git a/tutorial/error_cases/zero_division/div_zero.kv b/tutorial/error_cases/zero_division/div_zero.kv index f7ba4395..8815fd7a 100644 --- a/tutorial/error_cases/zero_division/div_zero.kv +++ b/tutorial/error_cases/zero_division/div_zero.kv @@ -1,5 +1,5 @@ -# expected: -# error: ZeroDivisionError: division by zero +// expected: +// error: ZeroDivisionError: division by zero rwfunc test() -> () { 1 ÷ 0 -> _ diff --git a/tutorial/error_cases/zero_division/float_underflow_div.kv b/tutorial/error_cases/zero_division/float_underflow_div.kv index eafec60b..26dbd326 100644 --- a/tutorial/error_cases/zero_division/float_underflow_div.kv +++ b/tutorial/error_cases/zero_division/float_underflow_div.kv @@ -1,5 +1,5 @@ -# expected -# ZeroDivisionError: division by zero +// expected +// ZeroDivisionError: division by zero rwfunc test() -> () { 1.0 ÷ 0.0 -> x 1.0 ÷ 0.0 -> x_m diff --git a/tutorial/error_cases/zero_division/mod_zero.kv b/tutorial/error_cases/zero_division/mod_zero.kv index 53908fa3..a55ed89a 100644 --- a/tutorial/error_cases/zero_division/mod_zero.kv +++ b/tutorial/error_cases/zero_division/mod_zero.kv @@ -1,6 +1,6 @@ -# expected -# ZeroDivisionError: modulo by zero -# 修复: fix-034 — 模零除同除零,C/Go/Rust/Python/JS 全部拒绝 +// expected +// ZeroDivisionError: modulo by zero +// 修复: fix-034 — 模零除同除零,C/Go/Rust/Python/JS 全部拒绝 rwfunc test() -> () { int64(7) % int64(0) -> x } diff --git a/tutorial/error_test.py b/tutorial/error_test.py index 02c39abb..c7b44762 100644 --- a/tutorial/error_test.py +++ b/tutorial/error_test.py @@ -27,12 +27,12 @@ def parse_expects(f: Path) -> list[str]: with open(f) as fh: for line in fh: line = line.rstrip("\n") - if line.startswith("# expected"): + if line.startswith("// expected"): in_block = True continue if in_block: - if line.startswith("# ") or line.startswith("# \t"): - p = line[2:].strip() + if line.startswith("// ") or line.startswith("// \t"): + p = line[3:].strip() if p: pats.append(p) else: diff --git a/tutorial/test.py b/tutorial/test.py index 3b23964a..a3464a78 100755 --- a/tutorial/test.py +++ b/tutorial/test.py @@ -34,33 +34,33 @@ def discover(root: Path) -> list[Path]: def parse_expects(f: Path) -> list[str]: - """从 .kv 文件头提取 # 期望输出 行,去掉注释前缀和尾部说明。""" + """从 .kv 文件头提取 // 期望输出 行,去掉注释前缀和尾部说明。""" pats = [] in_block = False with open(f) as fh: for line in fh: line = line.rstrip("\n") - if line.startswith("# 期望输出"): + if line.startswith("// 期望输出"): in_block = True continue if in_block: - if line.startswith("# ") or line.startswith("# \t"): - p = line[2:].strip() + if line.startswith("// ") or line.startswith("// \t"): + p = line[3:].strip() p = re.sub(r"\s*\(.*\)\s*$", "", p) if p: pats.append(p) - elif not line.startswith("#"): + elif not line.startswith("//"): break return pats def _needs_skip(f: Path) -> bool: - """文件头含 # extern 或 # wip 标记 = 不参与自动测试(外部 rwirext / 待实现特性)。""" + """文件头含 // extern 或 // wip 标记 = 不参与自动测试(外部 rwirext / 待实现特性)。""" with open(f) as fh: for line in fh: - if line.startswith("# extern") or line.startswith("# wip"): + if line.startswith("// extern") or line.startswith("// wip"): return True - if line and not line.startswith("#"): + if line and not line.startswith("//"): return False return False @@ -335,7 +335,7 @@ def tearDown(self): def write_fixture(self, python_output="answer 42", include_c=True): source = self.tutorial / "case.kv" - source.write_text("# 期望输出:\n# answer 42\n", encoding="utf-8") + source.write_text("// 期望输出:\n// answer 42\n", encoding="utf-8") source.with_suffix(".py").write_text( f"print({python_output!r})\n", encoding="utf-8", )