Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b5e9d15391 | ||
|
|
dcd0cdb8f7 | ||
|
|
a53ebb65ee | ||
|
|
a5d30c00b3 | ||
|
|
fd36b92224 | ||
|
|
30cd39fd8f | ||
|
|
31a4b69bbd |
No files matched your search
@@ -28,7 +28,7 @@ jobs:
|
||||
- name: Build & export site
|
||||
run: |
|
||||
cargo build --release
|
||||
find public -name '*.mq.md' ! -name 'utils.mq.md' -print0 \
|
||||
find public -name '*.mq.md' ! -name 'utils.mq.md' ! -name '¹¤¾ß.mq.md' -print0 \
|
||||
| xargs -0 -n1 ./target/release/marqdo run
|
||||
./target/release/marqdo view output public -o public
|
||||
|
||||
|
||||
Generated
+324
@@ -11,6 +11,15 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "android_system_properties"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstream"
|
||||
version = "0.6.21"
|
||||
@@ -94,6 +103,12 @@ version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
|
||||
|
||||
[[package]]
|
||||
name = "bstr"
|
||||
version = "1.13.0"
|
||||
@@ -105,6 +120,39 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.20.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
|
||||
[[package]]
|
||||
name = "chrono"
|
||||
version = "0.4.45"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
|
||||
dependencies = [
|
||||
"iana-time-zone",
|
||||
"num-traits",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chunked_transfer"
|
||||
version = "1.5.0"
|
||||
@@ -157,6 +205,12 @@ version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
||||
|
||||
[[package]]
|
||||
name = "difflib"
|
||||
version = "0.4.0"
|
||||
@@ -169,6 +223,12 @@ version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "780955b8b195a21ab8e4ac6b60dd1dbdcec1dc6c51c0617964b08c81785e12c9"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
|
||||
|
||||
[[package]]
|
||||
name = "float-cmp"
|
||||
version = "0.9.0"
|
||||
@@ -178,6 +238,39 @@ dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-core"
|
||||
version = "0.3.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7"
|
||||
|
||||
[[package]]
|
||||
name = "futures-task"
|
||||
version = "0.3.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109"
|
||||
|
||||
[[package]]
|
||||
name = "futures-util"
|
||||
version = "0.3.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-task",
|
||||
"pin-project-lite",
|
||||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getopts"
|
||||
version = "0.2.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"
|
||||
dependencies = [
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.4.1"
|
||||
@@ -190,12 +283,53 @@ version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone"
|
||||
version = "0.1.65"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
|
||||
dependencies = [
|
||||
"android_system_properties",
|
||||
"core-foundation-sys",
|
||||
"iana-time-zone-haiku",
|
||||
"js-sys",
|
||||
"log",
|
||||
"wasm-bindgen",
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone-haiku"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.103"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"futures-util",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.189"
|
||||
@@ -214,8 +348,11 @@ version = "0.0.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"assert_cmd",
|
||||
"chrono",
|
||||
"clap",
|
||||
"predicates",
|
||||
"pulldown-cmark",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
"tiny_http",
|
||||
]
|
||||
@@ -241,12 +378,24 @@ dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "predicates"
|
||||
version = "3.1.0"
|
||||
@@ -286,6 +435,25 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pulldown-cmark"
|
||||
version = "0.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f86ba2052aebccc42cbbb3ed234b8b13ce76f75c3551a303cb2bcffcff12bb14"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"getopts",
|
||||
"memchr",
|
||||
"pulldown-cmark-escape",
|
||||
"unicase",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pulldown-cmark-escape"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
@@ -324,6 +492,21 @@ version = "0.8.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
@@ -344,6 +527,31 @@ dependencies = [
|
||||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.151"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.10.0"
|
||||
@@ -410,12 +618,24 @@ dependencies = [
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicase"
|
||||
version = "2.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-width"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
|
||||
|
||||
[[package]]
|
||||
name = "utf8parse"
|
||||
version = "0.2.2"
|
||||
@@ -431,12 +651,110 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.126"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"once_cell",
|
||||
"rustversion",
|
||||
"wasm-bindgen-macro",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro"
|
||||
version = "0.2.126"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"wasm-bindgen-macro-support",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro-support"
|
||||
version = "0.2.126"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"wasm-bindgen-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-shared"
|
||||
version = "0.2.126"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.60.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.59.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
@@ -445,3 +763,9 @@ checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
+4
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "marqdo"
|
||||
version = "0.0.3"
|
||||
version = "0.0.4"
|
||||
edition = "2021"
|
||||
license = "Apache-2.0"
|
||||
description = "Marqdo — Markdown markers as an interpreted programming language"
|
||||
@@ -13,7 +13,10 @@ path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
|
||||
clap = { version = "=4.4.18", features = ["derive"] }
|
||||
pulldown-cmark = "0.12"
|
||||
serde_json = "1"
|
||||
thiserror = "1"
|
||||
tiny_http = "0.12"
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
Marqdo:Markdown **标记即语法**。源文件 `.mq.md` 既是文稿也是程序。
|
||||
|
||||
欢迎访问[marqdo官方网站](https://www.marqdo.com/)阅读marqdo更多特性
|
||||
|
||||
语法宪法:[doc/design/markdown-mapping.md](doc/design/markdown-mapping.md) · 调用实参:[call-arguments.md](doc/design/call-arguments.md) · 测试布局:[examples-and-tests.md](doc/design/examples-and-tests.md) · 用户站:[user-site.md](doc/design/user-site.md) · 浏览:[view.md](doc/design/view.md) · 金样例:[tests/](tests/) · 用户文档:[public/](public/)
|
||||
|
||||
---
|
||||
|
||||
+8
-1
@@ -22,7 +22,13 @@
|
||||
| [design/tech-stack.md](design/tech-stack.md) | 实现栈对比 |
|
||||
| [adr/0001-implementation-language.md](adr/0001-implementation-language.md) | **Accepted:Rust 参考解释器;不用 Flex/Bison** |
|
||||
| [design/dependencies.md](design/dependencies.md) | 依赖详单(无 Flex/Bison) |
|
||||
| [design/keywords.md](design/keywords.md) | **英文最小关键字 / 内置 `print` `input`** |
|
||||
| [design/keywords.md](design/keywords.md) | **英文最小关键字 / 内置函数** |
|
||||
| [design/keywords-i18n.md](design/keywords-i18n.md) | **内核中英双名(无需导入;少而精)** |
|
||||
| [design/stdlib.md](design/stdlib.md) | **P2 标准库:内置 + `lib/` + 错误约定** |
|
||||
| [design/stdlib-i18n.md](design/stdlib-i18n.md) | **标准库中英命名:靠库文件名区分,无 lang 开关** |
|
||||
| [design/stdlib-modules.md](design/stdlib-modules.md) | **本波 L1:文件/系统/时间/JSON/网络(JSON 中英同库)** |
|
||||
| [design/stdlib-math.md](design/stdlib-math.md) | **方案:数学库(数值/随机/作图/轻量求解)** |
|
||||
| [design/stdlib-foreign.md](design/stdlib-foreign.md) | **暂缓:外联胶水(\`\`\`lang 具名块)** |
|
||||
| [design/call-arguments.md](design/call-arguments.md) | **调用:具名 + 位置实参** |
|
||||
| [design/examples-and-tests.md](design/examples-and-tests.md) | **tests/ 金样例目录布局** |
|
||||
| [design/view.md](design/view.md) | **`marqdo view` / `view output` 黑白极简 + 静态文档** |
|
||||
@@ -32,6 +38,7 @@
|
||||
| [design/pipeline-debug.md](design/pipeline-debug.md) | **流水线 `--dump-*` 可视调试** |
|
||||
| [dev-setup.md](dev-setup.md) | 开发环境配置(Rust M0) |
|
||||
| [roadmap/interpreter.md](roadmap/interpreter.md) | 正经解释器路线图 |
|
||||
| [roadmap/next-phase.md](roadmap/next-phase.md) | **下一阶段:input / 诊断 / 标准库 / view 调试** |
|
||||
| [research/okf-and-marqdo.md](research/okf-and-marqdo.md) | OKF 调研 |
|
||||
|
||||
金样例与集成测试:[`tests/`](../tests/)。面向访客的可执行文档:[`public/`](../public/)。Spike 存档:[`spike/`](../spike/)。
|
||||
|
||||
@@ -32,7 +32,10 @@ positional ::= value_token
|
||||
|
||||
- `value`(具名右侧):可含空格与 `` `var` `` 插值,直到下一个 `ident=` 边界。
|
||||
- `value_token`(位置):空白分隔的一个词法单元——数字、`` `名` ``、标识/文本词;**不含空格**。多词字符串请用具名,例如 `> print text=Hello World!`。
|
||||
- 内置 `print` 形参名为 `text`:`> print Hi` 与 `> print text=Hi` 等价。
|
||||
- 内置 `print` / `打印` 形参:`text` ≡ `内容`。
|
||||
- `input` / `输入`:`prompt` ≡ `提示`。
|
||||
- `len` / `长度`、`str` / `文本`、`int` / `整数`:`value` ≡ `值`。
|
||||
- 完整中英双名见 [keywords-i18n.md](keywords-i18n.md)。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
# 内置关键字 / 函数:中英双名(草案)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **已定(已实现)** |
|
||||
| 日期 | 2026-08-05 |
|
||||
| 原则 | **无需导入**;中英为**同一语义的别名**,不是语言模式开关 |
|
||||
| 相关 | [keywords.md](keywords.md) · [stdlib-i18n.md](stdlib-i18n.md) · [call-arguments.md](call-arguments.md) |
|
||||
|
||||
---
|
||||
|
||||
## 1. 动机
|
||||
|
||||
Marqdo 要中英文都能自然书写。标准库已约定「**库文件名区分语言**」(见 [stdlib-i18n.md](stdlib-i18n.md));对**不必导入**的一层——字面量关键字与极少内置函数——也要对等提供中文名。
|
||||
|
||||
正因为每增加一个内置名,就要同时维护中英(及日后更多语言)别名,所以:
|
||||
|
||||
> **关键字 / 内置必须少而精**——体积在「名字 × 语言」上放大,而不是在功能清单上堆满。
|
||||
|
||||
更多能力进可导入的 `lib/`,用中英**不同库文件、不同函数名**扩展,不膨胀解释器内核。
|
||||
|
||||
---
|
||||
|
||||
## 2. 分层(与标准库对齐)
|
||||
|
||||
| 层 | 是否导入 | 中英怎么区分 |
|
||||
|----|----------|--------------|
|
||||
| **L0 内核** | 否 | **同一文件内双名**:`print` ≡ `打印`;`True` ≡ `真` |
|
||||
| **L1 标准库** | 是(`> lib/…`) | **不同文件**:`text.mq.md` vs `文本.mq.md`(见 i18n 草案) |
|
||||
|
||||
L0 **不做** `lang:`、不做「当前语言模式」;写英文名就用英文,写中文名就用中文,可在同一程序里混用。
|
||||
|
||||
---
|
||||
|
||||
## 3. 范围:哪些要双名
|
||||
|
||||
### 3.1 字面量 / 逻辑关键字(词法保留)
|
||||
|
||||
控制流仍靠 Markdown(`#` `+` `-` `*` `**`),**不**为 `if`/`while`/`def` 做中英关键字。
|
||||
|
||||
| 英文 | 中文(提案) | 备注 |
|
||||
|------|--------------|------|
|
||||
| `True` | `真` | 布尔真 |
|
||||
| `False` | `假` | 布尔假 |
|
||||
| `None` | `空` | 空值 |
|
||||
| `and` | `且` | 逻辑与 |
|
||||
| `or` | `或` | 逻辑或 |
|
||||
| `not` | `非` | 逻辑非 |
|
||||
|
||||
中英文名均**不可作变量名**(同一保留集)。
|
||||
|
||||
### 3.2 内置函数(可调用、无需导入)
|
||||
|
||||
**仅**下列核心五项做中英双名(与「少而精」一致):
|
||||
|
||||
| 英文 | 中文(提案) | 作用 |
|
||||
|------|--------------|------|
|
||||
| `print` | `打印` | 写 stdout |
|
||||
| `input` | `输入` | 读一行 |
|
||||
| `len` | `长度` | 文本/表长度 |
|
||||
| `str` | `文本` | 转为显示文本 |
|
||||
| `int` | `整数` | 转为整数 |
|
||||
|
||||
形参名也提供中英别名(便于纯中文调用):
|
||||
|
||||
| 英文形参 | 中文形参 | 用于 |
|
||||
|----------|----------|------|
|
||||
| `text` | `内容` | `print` / `打印` |
|
||||
| `prompt` | `提示` | `input` / `输入` |
|
||||
| `value` | `值` | `len`/`str`/`int` 及对应中文名 |
|
||||
|
||||
示例(等价):
|
||||
|
||||
```markdown
|
||||
> print text=Hello
|
||||
> 打印 内容=你好
|
||||
|
||||
*`n` = > len `s`*
|
||||
*`n` = > 长度 值=`s`*
|
||||
```
|
||||
|
||||
### 3.3 明确不进 L0 双名表
|
||||
|
||||
下列若已在解释器中实现,视为**宿主原语 / 过渡 API**,**不**再批中文内核别名;应迁入或仅通过标准库暴露(中英分文件):
|
||||
|
||||
| 英文名 | 去向 |
|
||||
|--------|------|
|
||||
| `type` | L1 或维持实现细节,不进「关键字最少集」宣传 |
|
||||
| `trim` `split` `join` | L1:`lib/text.mq.md` / `lib/文本.mq.md` |
|
||||
| `at` | L1:`lib/table.mq.md` / `lib/表.mq.md` |
|
||||
|
||||
这样 L0 公开面 ≈ **6 个关键字词 ×2 + 5 个函数 ×2**,而不是「每个工具函数都 ×2」。
|
||||
|
||||
---
|
||||
|
||||
## 4. 语义规则
|
||||
|
||||
1. **别名等价**:中英文名绑定同一实现;诊断文案可用英文稳定串(金样例已有),用户文档中英均可举例。
|
||||
2. **可混用**:同一文件可同时出现 `print` 与 `打印`、`True` 与 `真`。
|
||||
3. **遮蔽**:用户 `# 打印` 与 `# print` 均会遮蔽对应内置名(实现阶段应警告)。
|
||||
4. **大小写**:英文关键字保持 Python 风格(`True`/`False`/`None`);中文无名感大小写问题。
|
||||
5. **扩语言**:日后日文等 → 再为 L0 增加第三个别名列;仍无「名字表」而非语言开关。标准库继续用**文件名**区分(见 i18n 草案)。
|
||||
|
||||
---
|
||||
|
||||
## 5. 与旧决议的关系
|
||||
|
||||
- 旧文「中文 `print` 废弃、统一为 `print`」:**废止**;改为正式双名 `print` / `打印`。
|
||||
- [keywords.md](keywords.md) 原则条「英文标识」改为「**内核双名;标准库分文件**」——实现阶段改正文。
|
||||
- 不引入中文控制流关键字(`如果`/`循环` 等);分支循环仍用 `+` / `-`。
|
||||
|
||||
---
|
||||
|
||||
## 6. 文档与金样例义务(实现时)
|
||||
|
||||
| 项 | 要求 |
|
||||
|----|------|
|
||||
| `keywords.md` | L0 表改为中英并列;砍掉对 `trim`/`split`/… 的「内核关键字」宣传 |
|
||||
| `public/` | 英 / 中文件同目录并列(拉丁名 vs 中文名) |
|
||||
| `tests/` | 中文关键字 / `打印`·`长度` 等金样例;与英文样例对等 |
|
||||
| 诊断 | 位置格式不变;message 可暂维持英文,或中英均可接受(另开小节) |
|
||||
|
||||
---
|
||||
|
||||
## 7. 实现备忘(暂不开发)
|
||||
|
||||
1. 词法 / 解析:字面量与 `and`/`or`/`not` 识别中文别名。
|
||||
2. 调用解析:内置表按别名归一到同一 `BuiltinId`。
|
||||
3. 形参绑定:`text`≡`内容`,`prompt`≡`提示`,`value`≡`值`。
|
||||
4. **不要**加 `lang:` 或全局「中文模式」。
|
||||
5. 与 [stdlib-i18n.md](stdlib-i18n.md) 一并落地时:先收束 L0 公开面,再铺 `lib/text` ↔ `lib/文本`。
|
||||
|
||||
---
|
||||
|
||||
## 8. 一句话
|
||||
|
||||
**内核:中英别名、无需导入、必须少;标准库:中英分文件、靠导入路径选择——这样 Marqdo 才能中英文通用而不把解释器撑爆。**
|
||||
+46
-35
@@ -2,51 +2,63 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | 已定(前期够用) |
|
||||
| 日期 | 2026-08-04 |
|
||||
| 原则 | **英文**;参考 [Python](https://realpython.com/python-keywords/) 但远更少;控制流仍靠 Markdown 标记,不引入 `if`/`while`/`def` |
|
||||
| 相关 | [markdown-mapping.md](markdown-mapping.md) |
|
||||
| 状态 | 已定(中英双名) |
|
||||
| 日期 | 2026-08-05 |
|
||||
| 原则 | **少而精**;控制流靠 Markdown;内核中英**别名等价**(见 [keywords-i18n.md](keywords-i18n.md)) |
|
||||
| 相关 | [markdown-mapping.md](markdown-mapping.md) · [keywords-i18n.md](keywords-i18n.md) · [stdlib-i18n.md](stdlib-i18n.md) |
|
||||
|
||||
---
|
||||
|
||||
## 1. 设计原则
|
||||
|
||||
1. **标记承担架构**:函数=`#`,分支=`+`,循环=`-`,返回=`**…**`,语句=`*…*`。因此 **不**把 `def`/`if`/`else`/`while`/`for`/`return` 做成关键字。
|
||||
2. **英文标识**:内置与字面量用英文,便于工具高亮与国际协作。
|
||||
3. **学 Python 的边界**:Python 3 里 [`print` / `input` 是内置函数,不是关键字](https://realpython.com/python-keywords/);布尔与空值是字面量关键字。Marqdo 同样区分 **关键字** vs **内置函数名**。
|
||||
4. **宁少勿多**:前期只列执行金样例所需;要加再进 ADR。
|
||||
2. **内核双名**:字面量 / 逻辑词 / 五个核心内置函数均有中英别名,**无需导入**,可混用。
|
||||
3. **学 Python 的边界**:区分 **关键字** vs **内置函数名**。
|
||||
4. **宁少勿多**:扩展能力进可导入标准库(中英分文件,见 [stdlib-i18n.md](stdlib-i18n.md))。
|
||||
|
||||
---
|
||||
|
||||
## 2. 关键字(词法保留,不可作变量名)
|
||||
|
||||
| 关键字 | 含义 | 备注 |
|
||||
|--------|------|------|
|
||||
| `True` | 布尔真 | 对齐 Python 大小写 |
|
||||
| `False` | 布尔假 | |
|
||||
| `None` | 空值 | |
|
||||
| `and` | 逻辑与 | 表达式内 |
|
||||
| `or` | 逻辑或 | |
|
||||
| `not` | 逻辑非 | |
|
||||
| 英文 | 中文 | 含义 |
|
||||
|------|------|------|
|
||||
| `True` | `真` | 布尔真 |
|
||||
| `False` | `假` | 布尔假 |
|
||||
| `None` | `空` | 空值 |
|
||||
| `and` | `且` | 逻辑与 |
|
||||
| `or` | `或` | 逻辑或 |
|
||||
| `not` | `非` | 逻辑非 |
|
||||
|
||||
**本期不引入:** `if` `else` `elif` `while` `for` `def` `class` `return` `import` `pass` `break` `continue` `in` `is` `lambda` …
|
||||
(`else` 分支臂仍用臂头单独的 `*` 标记,不是单词 `else`。)
|
||||
**不引入:** `if` `else` `while` `for` `def` `return` …(分支臂 `*` 不是单词 `else`。)
|
||||
|
||||
---
|
||||
|
||||
## 3. 内置函数(可调用名,建议勿遮蔽)
|
||||
## 3. 内置函数(可调用,无需导入)
|
||||
|
||||
| 名称 | 作用 | 调用示例 |
|
||||
|------|------|----------|
|
||||
| `print` | 写到 stdout(副作用) | `> print text=Hello` 或 `> print Hello`(位置实参,见 [call-arguments.md](call-arguments.md)) |
|
||||
| `input` | 从 stdin 读一行(返回文本) | `*`name` = > input prompt=Name: *` |
|
||||
| 英文 | 中文 | 作用 |
|
||||
|------|------|------|
|
||||
| `print` | `打印` | 写 stdout |
|
||||
| `input` | `输入` | 读一行;capture / view 用 frontmatter `stdin:` / `输入:`、表单或 `--stdin-file` 预置 |
|
||||
| `len` | `长度` | 文本/表长度 |
|
||||
| `str` | `文本` | 转为显示文本 |
|
||||
| `int` | `整数` | 转为整数 |
|
||||
|
||||
参数约定(v0):
|
||||
形参别名:
|
||||
|
||||
- `print`:具名实参 `text`(必填);日后可扩展 `end` 等。
|
||||
- `input`:可选 `prompt`;返回用户输入字符串(不含换行)。
|
||||
| 英文 | 中文 | 用于 |
|
||||
|------|------|------|
|
||||
| `text` | `内容` | `print` / `打印` |
|
||||
| `prompt` | `提示` | `input` / `输入` |
|
||||
| `value` | `值` | `len`/`str`/`int` 及其中文名 |
|
||||
|
||||
旧文档中的中文 `print` **废弃**,统一为 `print`。
|
||||
```markdown
|
||||
> print text=Hello
|
||||
> 打印 内容=你好
|
||||
|
||||
*`n` = > 长度 值=`s`*
|
||||
```
|
||||
|
||||
宿主原语 `type` / `trim` / `split` / `join` / `at` **无**内核中文别名;文本/表扩展走标准库文件(见 [stdlib-i18n.md](stdlib-i18n.md))。转换错误见 [stdlib.md](stdlib.md)。
|
||||
|
||||
---
|
||||
|
||||
@@ -55,30 +67,29 @@
|
||||
```markdown
|
||||
# main
|
||||
|
||||
> print text=Hello World!
|
||||
> 打印 内容=Hello World!
|
||||
|
||||
*`n` = 1*
|
||||
|
||||
+ `n` > 0
|
||||
> print text=positive
|
||||
+ *
|
||||
> print text=other
|
||||
> 打印 内容=other
|
||||
```
|
||||
|
||||
- `>` 是**调用标记**(架构)。
|
||||
- `print` 是**被调名字**(内置库)。
|
||||
- 用户自定义 `# print` 会遮蔽内置(实现应警告)。
|
||||
- `>` 是调用标记;`print` / `打印` 是同一内置的别名。
|
||||
- 用户 `# print` 或 `# 打印` 会遮蔽对应名字。
|
||||
|
||||
---
|
||||
|
||||
## 5. 标识符规则(摘要)
|
||||
|
||||
- 变量:行内 `` `name` ``;`name` 不可为上表关键字。
|
||||
- 函数名:`#` 标题文本;建议 ASCII/英文,中文标题仍允许但内置名保持英文。
|
||||
- 比较:`==` `>` `<` `>=` `<=`;逻辑:`and` `or` `not`。
|
||||
- 变量:`` `name` ``;不可为上表任一中英文关键字。
|
||||
- 函数名:`#` 标题;中英文均可。
|
||||
- 比较:`==` `>` `<` `>=` `<=`;逻辑:`and`/`且`、`or`/`或`、`not`/`非`。
|
||||
|
||||
---
|
||||
|
||||
## 6. 后续可增(未批准)
|
||||
|
||||
`len`、`str`、`int`、`float`、`range`;以及 `break`/`continue`(若循环需要)。增加前开短 ADR。
|
||||
`float`、`range`;以及 `break`/`continue`。增加前开短 ADR,并同步考虑是否值得占用双名配额。
|
||||
@@ -51,6 +51,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置
|
||||
| `****` / `**` + 空白 + `**` | **空返回**(`None`),并结束本函数体 |
|
||||
| 无标记行 / 成段续行 | 注释(空行分段,见 §2) |
|
||||
| GFM 表格 | 集合 |
|
||||
| 空 RHS 赋值 + 后随 `$$…$$`(或同行 `$$…$$`) | **公式赋值** → 运行时 `formula`(见 [stdlib-math.md](stdlib-math.md));叙述面无名 `$$` 仅展示 |
|
||||
| ` ```lang ` | 外联异种代码 |
|
||||
| 函数体内 `---` / `***` | **结束本函数体**(无返回值函数的收束;见 §11) |
|
||||
|
||||
|
||||
@@ -27,15 +27,17 @@ marqdo dump FILE --stage lines|tokens|ast|sema|all
|
||||
| `--dump-tokens` | 词法 | Token 流:`type lexeme line:col` |
|
||||
| `--dump-ast` | 语法 | S 表达式或缩进树(模块/函数/语句) |
|
||||
| `--dump-sema` | 语义 | 作用域、导入图、提升后的符号表 |
|
||||
| `--trace-eval` | 求值 | 进入/离开函数、绑定、分支臂选择、`print` 调用 |
|
||||
| `--dump-bytecode` | 字节码 | 反汇编 `Program`(见 [bytecode.md](bytecode.md)) |
|
||||
| `--trace-eval` | 求值 | **JSON 行**(stderr):语句级事件,含 `path` / `span`(`line:col`) |
|
||||
| `--dump-bytecode` | 字节码 | 反汇编 `Program`(指令旁带 `@line:col`;见 [bytecode.md](bytecode.md)) |
|
||||
| `--backend tree\|bytecode` | 执行后端 | 默认 `tree`;`bytecode` 走栈式 VM |
|
||||
| `--dump-all` | 以上全部 | 按管道顺序打印,段之间用横幅分隔 |
|
||||
|
||||
格式约定:
|
||||
|
||||
- 人类可读优先;段首统一:`=== marqdo: <stage> ===`
|
||||
- 可选 `--dump-format=text|json`(json 后置,text 先做)
|
||||
- dump 人类可读优先;段首统一:`=== marqdo: <stage> ===`
|
||||
- `--trace-eval`:每条事件一行 JSON,例如
|
||||
`{"event":"stmt","path":"…","span":"5:1","kind":"call","callee":"print"}`
|
||||
树遍历:`enter_fn` / `stmt` / `leave_fn`;字节码:`op`(`print`/`input`/`call`/`return`)。
|
||||
- 有 dump 时:若求值未实现,仍打印已实现阶段再以非 0 退出(便于 M1 只测 lines)
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# 外联 / 胶水标准库
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **已定(v1)** |
|
||||
| 日期 | 2026-08-05 |
|
||||
| 相关 | [stdlib-modules.md](stdlib-modules.md) · [stdlib-math.md](stdlib-math.md)(公式同构绑定) |
|
||||
|
||||
---
|
||||
|
||||
## 1. 原则
|
||||
|
||||
**导入即用**:`lib/foreign` / `lib/外联`。解释器来自用户本机(PATH / `set_cmd` / `MARQDO_FOREIGN_*`)。live view 可点 Run;静态导出展示源码,Run 禁用。
|
||||
|
||||
---
|
||||
|
||||
## 2. 绑定语法(与公式同构)
|
||||
|
||||
```markdown
|
||||
`hi` =
|
||||
```python
|
||||
print("hello")
|
||||
```
|
||||
|
||||
*`out` = > run code=`hi` *
|
||||
```
|
||||
|
||||
得到运行时类型 **`code`**(`lang` + `source`)。未绑定的 \`\`\` 围栏仍是叙述注释。
|
||||
|
||||
曾用的 \`\`\`python name=hi **已移除**。
|
||||
|
||||
---
|
||||
|
||||
## 3. API
|
||||
|
||||
| 英文 | 中文 | 形参 | 结果 |
|
||||
|------|------|------|------|
|
||||
| `set_cmd` | `设置命令` | `lang`, `cmd` | None |
|
||||
| `run` | `运行` | `code`(code 值) | 文本 stdout |
|
||||
| `run_lang` | `按语言运行` | `lang`, `source` | 文本 |
|
||||
| `langs` | `语言表` | | 列表 |
|
||||
|
||||
live view:Structure 中 code 卡片带命令框 + Run → `POST /api/foreign-run`。
|
||||
|
||||
---
|
||||
|
||||
## 4. 一句话
|
||||
|
||||
**`name` = + \`\`\`lang 围栏 → code 值;显式 run;本机解释器可配置。**
|
||||
@@ -0,0 +1,146 @@
|
||||
# 标准库多语言命名(草案)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **草案(先文档、后实现)** |
|
||||
| 日期 | 2026-08-04 |
|
||||
| 原则 | **不指定语言**;靠**库文件名**区分中英(及日后其它语言) |
|
||||
| 相关 | [stdlib.md](stdlib.md) · [stdlib-modules.md](stdlib-modules.md) · [keywords.md](keywords.md) · [keywords-i18n.md](keywords-i18n.md) · [user-site.md](user-site.md) |
|
||||
|
||||
---
|
||||
|
||||
## 1. 要解决什么
|
||||
|
||||
- 内置(解释器里的名字)必须**少而精**;更多能力放进可 `>` 导入的标准库。
|
||||
- 标准库需要**中英两套 API**(函数名不同),并方便以后再加日文、西班牙文等。
|
||||
- **不要**用 frontmatter `lang:`、环境变量默认语言、或「同一导入路径再解析语言」——那是负累,也不符合「文档即代码」的直观性。
|
||||
|
||||
---
|
||||
|
||||
## 2. 方案(采用)
|
||||
|
||||
**导入哪个库文件,就用哪套函数名。**
|
||||
文件名本身表达语言;解释器只做路径解析,不做语言推断。
|
||||
|
||||
### 2.1 推荐:库名用目标语言书写
|
||||
|
||||
| 导入 | 库内函数名(示例) |
|
||||
|------|-------------------|
|
||||
| `> lib/text.mq.md` | `trim` · `split` · `join` |
|
||||
| `> lib/文本.mq.md` | `去空白` · `拆分` · `拼接` |
|
||||
| `> lib/table.mq.md` | `rows` · `row_at` |
|
||||
| `> lib/表.mq.md` | `行数` · `取行` |
|
||||
|
||||
示例:
|
||||
|
||||
```markdown
|
||||
---
|
||||
> lib/text.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
*`xs` = > split value=a,b,c sep=,*
|
||||
```
|
||||
|
||||
```markdown
|
||||
---
|
||||
> lib/文本.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
*`xs` = > 拆分 s=a,b,c sep=,*
|
||||
```
|
||||
|
||||
读者看到导入路径就能知道后面该用英文还是中文函数名——**无需再声明语言**。
|
||||
|
||||
### 2.2 可选:同概念用后缀区分(同目录、同「概念」)
|
||||
|
||||
若希望「同一概念」在文件名上仍共享拉丁词根,可用:
|
||||
|
||||
| 导入 | 含义 |
|
||||
|------|------|
|
||||
| `> lib/text-en.mq.md` | 英文 API |
|
||||
| `> lib/text-zh.mq.md` | 中文 API |
|
||||
|
||||
这与 §2.1 **等价可选**,不是第二套解析器:仍然是「写哪个路径就加载哪个文件」。
|
||||
**优先推荐 §2.1**(`text` / `文本`),后缀形式留给需要 ASCII-only 路径的环境。
|
||||
|
||||
### 2.3 明确不做
|
||||
|
||||
| 不做 | 原因 |
|
||||
|------|------|
|
||||
| `lang: zh` / `MARQDO_LANG` | 隐式状态,难读、难测 |
|
||||
| `> std/text` 再按语言展开 | 多一次魔法 |
|
||||
| 同一文件内中英函数双份导出 | 遮蔽与文档混乱 |
|
||||
| 强制用户只许用中文或只许用英文 | Marqdo 本就多语言友好 |
|
||||
|
||||
---
|
||||
|
||||
## 2.4 特例:JSON
|
||||
|
||||
`JSON` 为专有缩写,**不强求**中文库名或中文 API 翻译。官方只提供:
|
||||
|
||||
```text
|
||||
lib/json.mq.md # 中英文档均 `> lib/json.mq.md`;函数 parse / stringify / get / keys
|
||||
```
|
||||
|
||||
不设 `lib/数据.mq.md` 等平行文件。其余模块仍遵守 §2.1。详见 [stdlib-modules.md](stdlib-modules.md) §3.4。
|
||||
|
||||
---
|
||||
|
||||
## 3. 与「少而精内置」的边界
|
||||
|
||||
| 层 | 内容 | 如何获得 |
|
||||
|----|------|----------|
|
||||
| **内置(L0)** | 极少:`print` `input` `len` `str` `int`(及语言字面量关键字) | 直接调用,无需导入 |
|
||||
| **标准库(L1)** | 文本/表等扩展 API;**通常**中英各一套文件、各一套函数名(**JSON 例外**:仅 `lib/json.mq.md`) | frontmatter `> lib/…` |
|
||||
| **宿主原语(实现细节)** | 若 `trim`/`split` 等暂由解释器实现 | 仅供标准库包装调用;**文档与用户站引导走 L1**,不鼓励当「关键字」堆砌 |
|
||||
|
||||
日后若某能力足够「核心」,可再升格为 L0;升格前先留在 L1。
|
||||
|
||||
---
|
||||
|
||||
## 4. 目录与扩展约定
|
||||
|
||||
```text
|
||||
lib/
|
||||
text.mq.md / 文本.mq.md
|
||||
table.mq.md / 表.mq.md
|
||||
# 本波:fs/文件 · sys/系统 · time/时间 · json(中英同文件)· net/网络
|
||||
# 暂缓:math/数学 · foreign/外联
|
||||
# 其它语言:texte.mq.md / テキスト.mq.md …
|
||||
```
|
||||
|
||||
扩展新语言时:
|
||||
|
||||
1. **新加一个库文件**(文件名用该语言或 `概念-xx`)。
|
||||
2. 库内函数名用该语言习惯。
|
||||
3. 文档表增加一行映射;**无需改解释器语言开关**。
|
||||
|
||||
导入解析仍沿用现有规则:相对路径 → 官方 `lib/` 根(`MARQDO_LIB` / 工作区 `lib/` 等),**不增加语言分支**。
|
||||
|
||||
---
|
||||
|
||||
## 5. 文档与示例义务
|
||||
|
||||
- 用户站:英/中库各一页(或同页两小节),导入路径与调用名并排;**JSON** 可共用一页、同一导入。
|
||||
- 金样例:分文件模块中英导入至少各一条;JSON 测 `lib/json.mq.md` 即可。
|
||||
- [keywords.md](keywords.md) 只列 L0;L1 指向本文 + [stdlib.md](stdlib.md) + [stdlib-modules.md](stdlib-modules.md)。
|
||||
|
||||
---
|
||||
|
||||
## 6. 实现备忘(暂不开发)
|
||||
|
||||
实现阶段仅需:
|
||||
|
||||
1. 落地 `lib/text.mq.md` 与 `lib/文本.mq.md`(及 table / 表)两套文件与函数名。
|
||||
2. 更新导入示例与金样例;删除「仅中文库名」的单轨示例。
|
||||
3. **不要**实现 `lang:`、默认语言、或 `std/text` 自动选语言。
|
||||
|
||||
若历史上加过 `Module.lang` / `lang:` 解析,应撤回,与本草案对齐。
|
||||
|
||||
---
|
||||
|
||||
## 7. 一句话
|
||||
|
||||
**标准库用文件名区分语言(导入即选择);JSON 为缩写特例,中英共用 `lib/json.mq.md`——无语言开关。**
|
||||
@@ -0,0 +1,231 @@
|
||||
# 数学标准库(方案)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **已实现(M1–M4)** |
|
||||
| 日期 | 2026-08-05 |
|
||||
| 相关 | [stdlib-modules.md](stdlib-modules.md) · [stdlib-i18n.md](stdlib-i18n.md) · [markdown-mapping.md](markdown-mapping.md) · [view.md](view.md) |
|
||||
| 导入 | `lib/math.mq.md`(英)· `lib/数学.mq.md`(中) |
|
||||
| 范围 | **高中数学**(初等函数、导数、圆锥曲线、简单方程);非大学 CAS |
|
||||
|
||||
---
|
||||
|
||||
## 1. 目标
|
||||
|
||||
1. **公式类型**:解析 `$$…$$`(及行内 `$…$` 的可选支持),得到可绑定、可传递的 **`formula` 值**——语义上像「公式常量 / 公式变量」。
|
||||
2. **数学库对 `formula`(及文本表达式)做操作**:求值、化简、求导、求解、作图等。
|
||||
3. **数值 + 随机**:日常算术与可复现随机。
|
||||
4. **作图**:view / 静态页内嵌 SVG;CLI 写本地文件(可指定 `path`)。
|
||||
|
||||
**难度自觉:** 只覆盖高中知识面,自研小型表达式 AST + 规则即可,**不**追求 Mathematica / SymPy 完备性。
|
||||
|
||||
---
|
||||
|
||||
## 2. 核心模型:`formula` 类型
|
||||
|
||||
### 2.1 运行时
|
||||
|
||||
| 类型 | `type` 标签 | 说明 |
|
||||
|------|-------------|------|
|
||||
| `Value::Num(f64)` | `num` | 浮点 |
|
||||
| `Value::Formula(…)` | `formula` | 已解析的表达式树(或等价内部表示) |
|
||||
|
||||
`print` / `str` 对 `formula`:输出规范 ASCII(如 `2*x + 1`)或保留源 LaTeX 的一种(实现时写死并文档化;建议 **ASCII 规范式** 便于测试)。
|
||||
|
||||
### 2.2 文档中的 `$$` = 公式赋值(与表格同构)
|
||||
|
||||
在可执行面用 **空 RHS 赋值** 后跟展示数学块,把公式绑到变量(与 `` `xs` = `` 后跟表格一致):
|
||||
|
||||
````markdown
|
||||
# main
|
||||
|
||||
`f` =
|
||||
$$
|
||||
sin(x) + x
|
||||
$$
|
||||
|
||||
*`df` = > diff formula=`f` var=x *
|
||||
|
||||
> plot formula=`f` var=x min=-3 max=3 path=f.svg
|
||||
````
|
||||
|
||||
也支持:
|
||||
|
||||
- 单行围栏:下一行 `$$x^2 - 2$$`
|
||||
- 同行 compact:`*`f` = $$x^2 - 2$$ *`
|
||||
|
||||
**废除:** `$$:name` / `$$ name=…` 模块级具名块(不再产生绑定)。
|
||||
|
||||
**无名 `$$…$$`:** 仅在成段注释(叙述面)里作展示,**不**进入运行时。可执行区若出现未挂在赋值上的裸 `$$` 围栏 → 报错,提示使用 `` `name` = `` + 围栏。
|
||||
|
||||
**行内 `$…$`:** v1 不做绑定;需要时用 `> formula text=…` 显式构造。
|
||||
|
||||
### 2.3 从文本构造
|
||||
|
||||
| 英文 | 中文 | 说明 |
|
||||
|------|------|------|
|
||||
| `formula` | `公式` | `text=` 解析为 `formula`(ASCII 或简单 LaTeX 子集) |
|
||||
|
||||
数学库函数形参统一接受:**`formula` 值**,或能解析的 **文本**(内部先 `formula` 化)。
|
||||
|
||||
### 2.4 与叙述面的关系
|
||||
|
||||
- `` `f` = `` + `$$…$$`:代码面赋值,得到 `formula` 值。
|
||||
- 成段注释里的 `$$`:仍是注释,不解析为公式。
|
||||
- view:公式赋值在 Structure 中显示为绑定,不是 comment。
|
||||
|
||||
(见 [markdown-mapping.md](markdown-mapping.md):空 RHS + `$$` → 公式赋值。)
|
||||
|
||||
---
|
||||
|
||||
## 3. 知识范围(高中)
|
||||
|
||||
### 3.1 表达式与符号(S)
|
||||
|
||||
| 纳入 | 例子 |
|
||||
|------|------|
|
||||
| 多项式 | `x^2 - 3*x + 2` |
|
||||
| 初等函数 | `sin` `cos` `tan` `ln` `exp` `sqrt` `abs` |
|
||||
| 四则、幂 | `+ - * / ^` |
|
||||
| 化简 / 展开 | 合并同类项、基本三角恒等(小集合) |
|
||||
| 求导 | 单变元,初等函数求导法则 |
|
||||
| 代入求值 | `subs` → `num` 或公式 |
|
||||
| 求解 | 一元一次 / 二次闭式;其它用数值求根并标明 |
|
||||
|
||||
**不做(本波):** 多元方程组、极限 ε-δ、级数、积分保证、矩阵、复数完备、任意证明。
|
||||
|
||||
### 3.2 作图(P)
|
||||
|
||||
| 纳入 | 说明 |
|
||||
|------|------|
|
||||
| 显函数 `y=f(x)` | 采样折线 SVG |
|
||||
| 导数曲线 | 对 `formula` 先 `diff` 再画,或 `plot` 选项 `derivative=true` |
|
||||
| 圆锥曲线 | 标准形:圆、椭圆、双曲线、抛物线(参数方程或隐式采样) |
|
||||
| 点列 | `plot_points` |
|
||||
|
||||
**不做:** 三维、隐函数通用求解器、交互缩放(静态 SVG 足够)。
|
||||
|
||||
### 3.3 数值与随机(N)
|
||||
|
||||
常数、四则、三角、对数、取整、`num` 转换、`random` / `random_int` / `seed`(同前稿)。
|
||||
|
||||
---
|
||||
|
||||
## 4. API 草图(对 `formula` 操作)
|
||||
|
||||
### 4.1 构造与数值
|
||||
|
||||
| 英文 | 中文 | 要点 |
|
||||
|------|------|------|
|
||||
| `formula` | `公式` | 文本 → formula |
|
||||
| `pi` `e` | `圆周率` `自然底数` | → num |
|
||||
| `add`… / `sin`… | `加`… / `正弦`… | 对 num;若传入 formula 则返回 formula(符号)或报错——**v1 建议:算术函数只接 num;符号用 simplify/diff/subs** |
|
||||
| `eval` | `求值` | `formula` + 变量赋值 → num |
|
||||
| `random` / `random_int` / `seed` | `随机` / `随机整数` / `设种子` | 见前 |
|
||||
|
||||
### 4.2 符号
|
||||
|
||||
| 英文 | 中文 | 形参 | 结果 |
|
||||
|------|------|------|------|
|
||||
| `simplify` | `化简` | `formula` | formula |
|
||||
| `expand` | `展开` | `formula` | formula |
|
||||
| `diff` | `求导` | `formula`, `var` | formula |
|
||||
| `subs` | `代入` | `formula`, `var`, `value` | formula 或 num |
|
||||
| `solve` | `求解` | `formula`, `var`,可选区间 | list(num 或公式根) |
|
||||
|
||||
### 4.3 作图
|
||||
|
||||
| 英文 | 中文 | 形参 |
|
||||
|------|------|------|
|
||||
| `plot` | `绘图` | **`formula`**(或 `expr` 文本), `var`, `min`, `max`;可选 `steps`, `path`, `derivative`, **`grid`**(默认开;`False`/`假` 关) |
|
||||
| `plot_conic` | `绘圆锥` | `kind`(circle/ellipse/hyperbola/parabola)+ 系数;可选 `path`, `grid` |
|
||||
| `plot_points` | `绘点列` | `xs`, `ys`;可选 `path`, `grid` |
|
||||
|
||||
返回 **SVG 文本**;坐标轴带箭头与刻度,默认网格;写文件与 view 嵌入规则同前(§5)。
|
||||
|
||||
`diff` / `simplify` / `expand` / 未完全数值化的 `subs` 返回 **`formula`**,可继续链式调用。
|
||||
|
||||
示例:
|
||||
|
||||
```markdown
|
||||
# main
|
||||
|
||||
`f` =
|
||||
$$
|
||||
x^2 - 2
|
||||
$$
|
||||
|
||||
*`roots` = > solve formula=`f` var=x *
|
||||
|
||||
> print text=`roots`
|
||||
|
||||
*`svg` = > plot formula=`f` var=x min=-3 max=3 path=parabola.svg *
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 作图:CLI / view / 静态(不变精神)
|
||||
|
||||
| 场景 | 行为 |
|
||||
|------|------|
|
||||
| 带 `path=` | 写 SVG 到该路径(沙箱内) |
|
||||
| CLI 无 path | 自动 `{stem}-plot-{n}.svg` + 一行 `plot: …` |
|
||||
| view / 导出无 path | 不强制写盘;加入 **plots 产物列表**,Execution 内嵌 |
|
||||
| view / 导出有 path | 写盘 + 内嵌 |
|
||||
|
||||
不把整段 SVG 默认灌进 CLI stdout。
|
||||
|
||||
---
|
||||
|
||||
## 6. 分期
|
||||
|
||||
| 期 | 交付 |
|
||||
|----|------|
|
||||
| **M1** | `Num` + 数值/随机;`Formula` AST + `` `name` = `` + `$$…$$` 赋值绑定 |
|
||||
| **M2** | `simplify` / `diff` / `subs` / `eval` / 二次 `solve`(高中子集) |
|
||||
| **M3** | `plot` / `plot_points` / `plot_conic` + view 内嵌 + path 写盘 |
|
||||
| **M4** | 用户文档 `public/stdlib/math*` · 金样例 · mapping 文档补丁 |
|
||||
|
||||
M1–M3 可在同一发版列车上连续落地;验收以「公式赋值 → 求导 → 作图」一条龙为准。
|
||||
|
||||
---
|
||||
|
||||
## 7. 实现要点
|
||||
|
||||
```text
|
||||
src/formula/ # 词法/AST/化简/求导/求值(高中规则表)
|
||||
src/host/math.rs # 数值、随机、对 formula 的 host 入口
|
||||
src/host/plot.rs # SVG
|
||||
lex/parse:空 RHS 赋值 + $$ 围栏 → Expr::Formula
|
||||
Value::Num / Value::Formula
|
||||
Interpreter.plots: Vec<String>
|
||||
lib/math.mq.md · lib/数学.mq.md
|
||||
```
|
||||
|
||||
依赖:纯 Rust;不绑 SymPy。公式复杂度、采样点、SVG 大小设硬上限。
|
||||
|
||||
---
|
||||
|
||||
## 8. 刻意不做
|
||||
|
||||
- `$$:name` 模块级具名绑定(已废除)。
|
||||
- 无名 `$$` 自动进运行时。
|
||||
- 大学级数 / 完备积分 / 定理证明。
|
||||
- 通用隐函数作图引擎。
|
||||
- 3D、交互式图表库。
|
||||
|
||||
---
|
||||
|
||||
## 9. 验收
|
||||
|
||||
1. `` `f` = `` + `$$…$$` + `diff` / `solve` / `plot` 金样例(中英库)。
|
||||
2. 固定 `seed` 的随机金样例。
|
||||
3. `plot` + `path` 在 CLI 落盘;view HTML 含 `<svg`。
|
||||
4. `type` 对公式为 `formula`,对浮点为 `num`。
|
||||
5. view Structure 将公式赋值显示为绑定,而非 comment。
|
||||
|
||||
---
|
||||
|
||||
## 10. 一句话
|
||||
|
||||
**`` `f` = `` + `$$…$$` 产出 `formula` 值;数学库对它做高中范围的符号运算、求解与作图——数值与随机并行,图在 view 内嵌、在 CLI 写文件。**
|
||||
@@ -0,0 +1,228 @@
|
||||
# 标准库下一波(L1 扩展模块)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **五库 + 数学已落地**;下一波:**外联**([stdlib-foreign.md](stdlib-foreign.md)) |
|
||||
| 日期 | 2026-08-05 |
|
||||
| 本波范围 | 文件 / 系统 / 时间 / JSON / 网络 / 数学(已完成) |
|
||||
| 下一波 | **外联**(本机解释器 / 具名围栏) |
|
||||
| 暂缓 | — |
|
||||
| 原则 | 全部经 frontmatter **导入**;除 JSON 外中英分文件;内核保持少而精 |
|
||||
| 相关 | [stdlib.md](stdlib.md) · [stdlib-i18n.md](stdlib-i18n.md) · [keywords-i18n.md](keywords-i18n.md) · [view.md](view.md) |
|
||||
|
||||
---
|
||||
|
||||
## 1. 目标
|
||||
|
||||
在现有 `lib/text`·`lib/文本`、`lib/table`·`lib/表` 之上,把 Marqdo 推进到可写日常脚本。标准库**必须导入**才可用。
|
||||
|
||||
| 模块族 | 英文库 | 中文库 | 本波 |
|
||||
|--------|--------|--------|------|
|
||||
| 文本(已有) | `lib/text.mq.md` | `lib/文本.mq.md` | 已有 |
|
||||
| 表(已有) | `lib/table.mq.md` | `lib/表.mq.md` | 已有 |
|
||||
| **文件** | `lib/fs.mq.md` | `lib/文件.mq.md` | **做** |
|
||||
| **系统** | `lib/sys.mq.md` | `lib/系统.mq.md` | **做** |
|
||||
| **时间** | `lib/time.mq.md` | `lib/时间.mq.md` | **做** |
|
||||
| **JSON** | `lib/json.mq.md` | **同文件(特例,§3.4)** | **做** |
|
||||
| **网络(简)** | `lib/net.mq.md` | `lib/网络.mq.md` | **做** |
|
||||
| 数学 | `lib/math.mq.md` | `lib/数学.mq.md` | **下一波** |
|
||||
| 外联 | `lib/foreign.mq.md` | `lib/外联.mq.md` | **做** |
|
||||
|
||||
---
|
||||
|
||||
## 2. 分层与实现分工
|
||||
|
||||
```text
|
||||
用户 .mq.md
|
||||
│ > lib/fs.mq.md
|
||||
▼
|
||||
L1 官方库(.mq.md)
|
||||
│
|
||||
▼
|
||||
L0.5 宿主原语(Rust,英文蛇形)
|
||||
│
|
||||
▼
|
||||
OS / HTTP / 时钟 / …
|
||||
```
|
||||
|
||||
| 层 | 谁实现 | 用户是否直接调用 |
|
||||
|----|--------|------------------|
|
||||
| **L0** | 解释器内置 | 是(`print`/`len`/…) |
|
||||
| **L0.5 宿主原语** | Rust(`src/builtin` 或 `src/host/`) | **原则上否**;供 L1 包装;金样例可直测 |
|
||||
| **L1 官方库** | `lib/*.mq.md` | **是**(文档与用户站只教这一层) |
|
||||
|
||||
规则:
|
||||
|
||||
1. **导入即选择语言**(JSON 除外):`lib/fs.mq.md` → 英文 API;`lib/文件.mq.md` → 中文 API(见 [stdlib-i18n.md](stdlib-i18n.md))。
|
||||
2. **不设 `lang:`**。
|
||||
3. 宿主原语保持英文;中英差异只存在于 L1 包装层(JSON 无第二套包装)。
|
||||
4. 失败一律 `path:line:col: message`([stdlib.md](stdlib.md) §4)。
|
||||
|
||||
---
|
||||
|
||||
## 3. 核心模块 API 草图(L1)
|
||||
|
||||
### 3.1 文件 — `fs` / `文件`
|
||||
|
||||
| 英文 | 中文 | 形参(英 / 中) | 结果 |
|
||||
|------|------|-----------------|------|
|
||||
| `read_text` | `读文本` | `path` / `路径` | 文本 |
|
||||
| `write_text` | `写文本` | `path`, `text` / `路径`, `内容` | `None` |
|
||||
| `append_text` | `追加文本` | 同上 | `None` |
|
||||
| `exists` | `存在` | `path` / `路径` | 布尔 |
|
||||
| `list_dir` | `列目录` | `path` / `路径` | 文本列表 |
|
||||
| `make_dir` | `建目录` | `path` / `路径` | `None` |
|
||||
| `remove` | `删除` | `path` / `路径` | `None` |
|
||||
|
||||
约定:路径相对工作目录或绝对路径;二进制 I/O 本波不做;写/删默认需 `--allow-fs-write`(§6)。
|
||||
|
||||
### 3.2 系统 — `sys` / `系统`
|
||||
|
||||
| 英文 | 中文 | 形参 | 结果 |
|
||||
|------|------|------|------|
|
||||
| `env_get` | `取环境` | `name` / `名` | 文本或 `None` |
|
||||
| `env_set` | `设环境` | `name`, `value` / `名`, `值` | `None` |
|
||||
| `args` | `参数表` | (无) | 文本列表 |
|
||||
| `cwd` | `工作目录` | (无) | 文本 |
|
||||
| `exit` | `退出` | `code` / `码` | 不返回 |
|
||||
| `exec` | `执行` | `cmd`, 可选 `args` | 退出码(实现时写死语义) |
|
||||
|
||||
`exec` 默认关(`--allow-exec`);view / 静态站永不开放。
|
||||
|
||||
### 3.3 时间 — `time` / `时间`
|
||||
|
||||
| 英文 | 中文 | 形参 | 结果 |
|
||||
|------|------|------|------|
|
||||
| `now_unix` | `此刻秒` | (无) | 整数(Unix 秒) |
|
||||
| `now_ms` | `此刻毫秒` | (无) | 整数 |
|
||||
| `format` | `格式化` | `unix`, `pattern` / `秒`, `格式` | 文本 |
|
||||
| `sleep_ms` | `睡眠毫秒` | `ms` / `毫秒` | `None` |
|
||||
| `parse` | `解析时间` | `text`, `pattern` / `内容`, `格式` | 整数秒或诊断失败 |
|
||||
|
||||
view 中 `sleep_ms` 设上限(如 5s)。
|
||||
|
||||
### 3.4 JSON — `json`(**中英同库特例**)
|
||||
|
||||
JSON 是专有缩写,**很难也不必要**做合规中文库名/API 翻译。本波定稿:
|
||||
|
||||
| 项 | 约定 |
|
||||
|----|------|
|
||||
| 唯一路径 | **`lib/json.mq.md`**(中英文档均导入此路径) |
|
||||
| 函数名 | 国际通行英文:`parse` / `stringify` / `get` / `keys` |
|
||||
| 形参 | 英文:`text` / `value` / `key` / `indent` |
|
||||
| 不设 | `lib/数据.mq.md`、音译名、中文函数双份 |
|
||||
|
||||
这是对 [stdlib-i18n.md](stdlib-i18n.md)「一概念两文件」的**显式例外**;其它模块仍中英分文件。
|
||||
|
||||
| 函数 | 形参 | 结果 |
|
||||
|------|------|------|
|
||||
| `parse` | `text` | 值(见下) |
|
||||
| `stringify` | `value`, 可选 `indent` | JSON 文本 |
|
||||
| `get` | `value`, `key` | 值或 `None` |
|
||||
| `keys` | `value` | 文本列表 |
|
||||
|
||||
**类型映射(草案)**:
|
||||
|
||||
| JSON | Marqdo Value |
|
||||
|------|----------------|
|
||||
| `null` | `None` |
|
||||
| bool | bool |
|
||||
| number(整数可表) | int |
|
||||
| number(其余) | 文本(本波不引入 float)或诊断拒绝 |
|
||||
| string | text |
|
||||
| array | list |
|
||||
| object | 倾向新宿主类型 **`map`**(`type` → `map`);否则体验差 |
|
||||
|
||||
`map` 为 L0.5 类型扩展,可与 json 同期或紧随;不阻塞 `fs`/`time` 先行。
|
||||
|
||||
### 3.5 网络(简)— `net` / `网络`
|
||||
|
||||
| 英文 | 中文 | 形参 | 结果 |
|
||||
|------|------|------|------|
|
||||
| `http_get` | `获取` | `url` / `地址` | 响应文本(或 map:status/body) |
|
||||
| `http_post` | `提交` | `url`, `body`, 可选 `content_type` | 同上 |
|
||||
| `url_encode` | `编码地址` | `text` / `内容` | 文本 |
|
||||
|
||||
仅 **HTTP 明文**(HTTPS 本波未做,会诊断提示);短超时、响应体上限;默认需 `--allow-net`;view / 静态站默认关。
|
||||
|
||||
**路径字面量:** 具名实参里 `path=a/b` 会被解析成除法。请用无斜杠文件名,或先赋给变量再传入。
|
||||
|
||||
---
|
||||
|
||||
## 4. 中英路径总表(本波)
|
||||
|
||||
```text
|
||||
lib/
|
||||
text.mq.md / 文本.mq.md # 已有
|
||||
table.mq.md / 表.mq.md # 已有
|
||||
fs.mq.md / 文件.mq.md # 本波
|
||||
sys.mq.md / 系统.mq.md
|
||||
time.mq.md / 时间.mq.md
|
||||
json.mq.md # 本波;中英共用,无第二文件
|
||||
net.mq.md / 网络.mq.md
|
||||
# 暂缓:math / 数学 · foreign / 外联
|
||||
```
|
||||
|
||||
别名:`std/…` ≡ `lib/…`。
|
||||
|
||||
---
|
||||
|
||||
## 5. 落地分期(本波 = M1–M5)
|
||||
|
||||
| 期 | 内容 | 完成定义 |
|
||||
|----|------|----------|
|
||||
| **M1** | 宿主能力框架:权限旗标、`host` 分发、错误文案 | `--allow-*` 可测 |
|
||||
| **M2** | `fs` + `time`(只读 fs + 时钟) | 中英库 + 金样例 |
|
||||
| **M3** | `sys`(env/cwd/args;`exec` 默认关) | 同上 |
|
||||
| **M4** | `json`(+ 可选 `map`) | 往返金样例;唯 `lib/json.mq.md` |
|
||||
| **M5** | `net`(默认关) | 本地 mock 或录制夹具 |
|
||||
|
||||
**不做 M6/M7**(数学 / 外联):详稿仅存档,待五库稳定后再议。
|
||||
|
||||
文档站:`fs`/`sys`/`time`/`net` 英中各一页;`json` 可一页双语叙述、同一导入路径。
|
||||
|
||||
---
|
||||
|
||||
## 6. 安全与 view / 静态导出
|
||||
|
||||
### 6.1 行为一致
|
||||
|
||||
`marqdo run`、live `view`、`view output` 对标准库 **默认同一套能力**(读/写盘、HTTP、exec 均可用)。导入库即表示要用;不再要求 `--allow-*`。
|
||||
|
||||
差异仅在 **软退出**:
|
||||
|
||||
| | CLI `run` | view / capture / 静态导出 |
|
||||
|--|-----------|---------------------------|
|
||||
| `exit` | 结束进程 | 报诊断,不杀 view/构建进程 |
|
||||
| `sleep_ms` | 默认可睡(有上限) | live 有上限;导出通常为 0 |
|
||||
|
||||
沙箱:相对路径落在源文件目录(或 view 根)下,防止 `..` 逃逸。
|
||||
|
||||
### 6.2 静态部署
|
||||
|
||||
访客浏览器 **不再执行** Marqdo;HTML 里是构建时冻结的输出。源码中的路径/URL 访客改不了、也触发不了新的 host 调用。审 PR 时审查写死的目标即可。
|
||||
|
||||
勿在静态页嵌入「用户可改 URL 再请求」的浏览器脚本。
|
||||
|
||||
---
|
||||
|
||||
## 7. 与现有库的关系
|
||||
|
||||
- `text` / `table` 继续纯包装、无 IO。
|
||||
- JSON `stringify` ≠ `str`(显示)。
|
||||
|
||||
---
|
||||
|
||||
## 8. 刻意不做(本波)
|
||||
|
||||
- 数学库、外联/胶水库(及其依赖、权限旗标实现)。
|
||||
- 数据库、异步事件循环、WebSocket、原始 TCP。
|
||||
- float/复数进 L0。
|
||||
- `lang:` 或按 locale 自动选库。
|
||||
- 为 JSON 强造中文库名或中文 API 双份。
|
||||
|
||||
---
|
||||
|
||||
## 9. 一句话
|
||||
|
||||
**本波只落地文件 / 系统 / 时间 / JSON / 网络;JSON 中英共用 `lib/json.mq.md`;数学与外联暂缓。**
|
||||
@@ -0,0 +1,96 @@
|
||||
# 标准库(P2)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **S0–S3 落地** |
|
||||
| 日期 | 2026-08-04 |
|
||||
| 相关 | [keywords.md](keywords.md) · [call-arguments.md](call-arguments.md) · [stdlib-i18n.md](stdlib-i18n.md) · [stdlib-modules.md](stdlib-modules.md) · [roadmap/next-phase.md](../roadmap/next-phase.md) |
|
||||
|
||||
> **多语言库命名**:见 [stdlib-i18n.md](stdlib-i18n.md)(不设 `lang:`;中英分文件)。
|
||||
> **下一波模块(本波:文件 / 系统 / 时间 / JSON / 网络;数学·外联暂缓)**:见 [stdlib-modules.md](stdlib-modules.md)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 分层
|
||||
|
||||
| 层 | 内容 |
|
||||
|----|------|
|
||||
| **L0 内置** | 解释器内:`print` `input` `len` `str` `int` `type` `trim` `split` `join` `at` |
|
||||
| **L1 官方库** | 仓库根目录 [`lib/`](../../lib/)(`.mq.md`);可用 `lib/…` 或别名 `std/…` 导入 |
|
||||
| **L2** | catalog / 用户站收录(随发版) |
|
||||
|
||||
---
|
||||
|
||||
## 2. 内置一览(S0 + S1)
|
||||
|
||||
| 名 | 形参 | 结果 |
|
||||
|----|------|------|
|
||||
| `len` | `value` | 文本标量数或列表长度 |
|
||||
| `str` | `value` | 显示文本 |
|
||||
| `int` | `value` | 整数(失败 → 诊断) |
|
||||
| `type` | `value` | `none`/`bool`/`int`/`text`/`list` |
|
||||
| `trim` | `value` | 去首尾空白 |
|
||||
| `split` | `value`, `sep` | 文本列表 |
|
||||
| `join` | `value`, `sep` | 拼接文本 |
|
||||
| `at` | `value`, `index` | 列表下标(越界 → `None`) |
|
||||
|
||||
表(单列表格)在运行时是 `list`:行数用 `len`,取行用 `at`。
|
||||
|
||||
---
|
||||
|
||||
## 3. 官方库导入(S2)
|
||||
|
||||
Frontmatter:
|
||||
|
||||
```markdown
|
||||
---
|
||||
> lib/text.mq.md
|
||||
> lib/table.mq.md
|
||||
---
|
||||
```
|
||||
|
||||
`std/text.mq.md` 等价于 `lib/text.mq.md`。解析顺序:
|
||||
|
||||
1. 相对当前文件
|
||||
2. `MARQDO_LIB`(可指向 `lib` 目录或仓库根)
|
||||
3. 当前工作目录的 `lib/`
|
||||
4. 可执行文件附近的 `lib/`(含 `cargo run` 的相对路径)
|
||||
|
||||
当前模块:
|
||||
|
||||
| 路径 | 导出函数 |
|
||||
|------|----------|
|
||||
| `lib/fs.mq.md` / `lib/文件.mq.md` | `read_text`… / `读文本`… |
|
||||
| `lib/time.mq.md` / `lib/时间.mq.md` | `now_unix`… / `此刻秒`… |
|
||||
| `lib/sys.mq.md` / `lib/系统.mq.md` | `env_get`… / `取环境`… |
|
||||
| `lib/json.mq.md` | `parse` `stringify` `get` `keys`(中英同文件) |
|
||||
| `lib/net.mq.md` / `lib/网络.mq.md` | `http_get`… / `获取`… |
|
||||
| `lib/text.mq.md` | `str_trim` `str_split` `str_join` |
|
||||
| `lib/文本.mq.md` | `去空白` `拆分` `拼接` |
|
||||
| `lib/table.mq.md` | `rows` `row_at` |
|
||||
| `lib/表.mq.md` | `行数` `取行` |
|
||||
|
||||
规划中的 L1 扩展见 [stdlib-modules.md](stdlib-modules.md)。
|
||||
|
||||
---
|
||||
|
||||
## 4. 转换错误约定(S3)
|
||||
|
||||
用户可见失败统一为:
|
||||
|
||||
```text
|
||||
path:line:col: message
|
||||
```
|
||||
|
||||
内置转换相关文案(稳定子集,金样例断言):
|
||||
|
||||
| 情况 | message |
|
||||
|------|---------|
|
||||
| 非法整数文本 | `cannot convert to int: "…"` |
|
||||
| `int` 类型不对 | `int needs int, bool, or text` |
|
||||
| `len` 类型不对 | `len needs text or list` |
|
||||
| `trim` 非文本 | `trim needs text` |
|
||||
| `split`/`join` 参数类型 | `split needs text value` 等 |
|
||||
| 空分隔符 | `split sep must not be empty` |
|
||||
|
||||
不引入独立异常类型对象;一律走 `Diagnostic`。
|
||||
@@ -13,7 +13,7 @@
|
||||
| 路径 | 是否入库 | 职责 |
|
||||
|------|----------|------|
|
||||
| `doc/` | 是 | 开发者设计 / ADR / 路线图(单数 `doc`,勿再造 `docs/`) |
|
||||
| `public/**/*.mq.md` | 是 | 用户可读、可执行、可下载的介绍(结构 / 关键字 / 特性迭代) |
|
||||
| `public/**/*.mq.md` | 是 | 用户可读、可执行、可下载的介绍(结构 / 关键字 / 特性迭代);**双语**:拉丁文件名 = 英文,中文文件名 = 中文编程,同目录并列 |
|
||||
| `public/index.html`、`public/pages/` | **否**(ignore) | `marqdo view output` 生成的 HTML |
|
||||
| `tests/{structure,keywords,errors}/` | 是 | 金样例与失败夹具(含 errors) |
|
||||
| 远程分支 `gh-pages` | 发布产物 | 发布整个 `public/`(源文件 + 生成 HTML) |
|
||||
|
||||
@@ -75,6 +75,7 @@ OUT_DIR/
|
||||
|
||||
- 页内链接一律**相对路径**,可用任意静态服务器或 `file://`(同目录结构下)打开。
|
||||
- 用户文档推荐流程:`marqdo view output public -o public`,将生成物发布到 `gh-pages`(见 [user-site.md](user-site.md))。
|
||||
- **执行权限**:与 `marqdo run` 一致(导入即用);view/导出仅对 `exit`/`sleep` 做软化,避免拖垮进程。详见 [stdlib-modules.md](stdlib-modules.md) §6。
|
||||
- 金样例浏览仍可用:`marqdo view output tests -o /tmp/mq-tests`(含 errors,勿当对外用户站)。
|
||||
- 渲染逻辑与实时 `view` **共用**同一套 HTML 构件(结构 / 执行 / 源码),禁止两套皮肤分叉。
|
||||
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
# 下一阶段:从玩具到可用语言
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **进行中**(P2 完成;下一:P3-D2 调试会话) |
|
||||
| 日期 | 2026-08-04 |
|
||||
| 目标 | 交互 I/O、可信诊断、可生长标准库;view 渐进成为调试宿主 |
|
||||
| 相关 | [interpreter.md](interpreter.md) · [keywords.md](../design/keywords.md) · [pipeline-debug.md](../design/pipeline-debug.md) · [view.md](../design/view.md) |
|
||||
|
||||
---
|
||||
|
||||
## 0. 现状快照(决策依据)
|
||||
|
||||
| 能力 | 现状 | 结论 |
|
||||
|------|------|------|
|
||||
| **`print`** | 树遍历 + 字节码均可用 | 够用 |
|
||||
| **`input`** | CLI 双后端 + `--stdin-file`;frontmatter `stdin:`/`输入:`;live view 表单覆盖;无预置时 capture 提示补线 | **P1a + P1b 完成** |
|
||||
| **诊断** | 语句级 `path:line:col: message`;字节码指令带 `spans`;errors 金样例双后端断言位置 | **P0 完成** |
|
||||
| **view** | 结构 + 一次执行 + 源码;注释已 Markdown 渲染;无暂停/断点 | **文档浏览器,不是调试器** |
|
||||
| **标准库** | S0–S3 完成;本波扩展 = 文件/系统/时间/JSON/网络([stdlib-modules.md](../design/stdlib-modules.md));数学/外联暂缓 | **P2 完成;五库扩展设计中** |
|
||||
| **模块** | `> file.mq.md` 顶层函数合并,无命名空间 | 短期可继续用 |
|
||||
|
||||
用户点名的三件事都对,但**不能并行硬开**:断点调试依赖「可信位置 + 可暂停执行」;标准库依赖稳定运行时与 I/O;`input` 在 CLI 与 view 是两条路径。
|
||||
|
||||
---
|
||||
|
||||
## 1. 轻重缓急(总序)
|
||||
|
||||
```text
|
||||
P0 诊断加固(短、撬动后续一切)
|
||||
P1 输入补完(先 CLI,再 view)
|
||||
P2 最小标准库(内置 + 可选 .mq.md 库)
|
||||
P3 view 调试(断点 / 单步)—— 在 P0 之后分期,勿一上来做 DAP
|
||||
```
|
||||
|
||||
| 优先级 | 主题 | 为何此刻 | 不做的代价 |
|
||||
|--------|------|----------|------------|
|
||||
| **P0** | 诊断完备度 | 便宜;给金样例、字节码、调试打地基 | 断点停错行;双后端错误体验分裂 |
|
||||
| **P1** | `input` | 「真语言」最低交互面;已有半截实现 | 只能写纯计算/打印 demo |
|
||||
| **P2** | 标准库 | 无库则用户无法写稍大程序 | 人人自造轮子、示例膨胀 |
|
||||
| **P3** | 前端调试 | 差异化(文档即调试);成本最高 | view 仍停留在「跑完看 stdout」 |
|
||||
|
||||
**原则:** 先让 **CLI 树遍历**成为完备参考实现;字节码跟进同语义;view 只接「已有事件/钩子」,不单独发明第二套语义。
|
||||
|
||||
---
|
||||
|
||||
## 2. P0 — 诊断与错误模型(约 3–7 天)
|
||||
|
||||
### 目标
|
||||
|
||||
所有用户可见失败统一为:
|
||||
|
||||
```text
|
||||
path:line:col: message
|
||||
```
|
||||
|
||||
树遍历与字节码**同文案、同位置粒度(至少语句级)**;金样例断言位置而不只子串。
|
||||
|
||||
### 工作项
|
||||
|
||||
1. **统一出口**
|
||||
- 解析侧尽量只产 `Diagnostic`(减少裸 `bail!("7:1: …")`)。
|
||||
- 字节码编译/VM:错误携带 `Span`(或指令 → 源行映射)。
|
||||
2. **位置粒度**
|
||||
- 短期:保持「语句起点」亦可;中期:为 `Expr`/`CallExpr` 补 `span`,让「未定义名」落在标识符上。
|
||||
3. **金样例**
|
||||
- `tests/errors/*`:断言完整 `path:line:col` 前缀(或相对路径规范化后的形式)。
|
||||
- 补:类型错误、除零、循环条件、capture 下 `input` 等。
|
||||
4. **文档**
|
||||
- 更新 [pipeline-debug.md](../design/pipeline-debug.md):错误码/严重级别可列为 P0.5(可选 `E0001` 一类,不阻塞)。
|
||||
|
||||
### 完成定义
|
||||
|
||||
- `cargo test`:errors 金样例含位置。
|
||||
- 同一 `.mq.md` 在 `--backend tree|bytecode` 下诊断一致(允许实现细节差异写进豁免表)。
|
||||
- view 执行失败区仍可读,路径无 `\\?\`。
|
||||
|
||||
### 刻意不做
|
||||
|
||||
- IDE DAP、完整堆栈 UI、sourcemap 可视化编辑器。
|
||||
|
||||
---
|
||||
|
||||
## 3. P1 — 输入(约 1–2 周)
|
||||
|
||||
分两轨:**CLI 必须先绿**;**view 交互后做**。
|
||||
|
||||
### P1a — CLI 完备(高优先级)
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| 树遍历 | 已实现 stdin;补 `tests/keywords/input.mq.md`(用管道喂入) |
|
||||
| 字节码 | 增加 `Op::Input`(或等价 host call);与树同语义;capture 下同样拒绝或改走注入 API |
|
||||
| 文档/用户站 | `public/keywords/input.mq.md`;说明「view 默认无交互 stdin」 |
|
||||
|
||||
完成定义:`echo Alice | marqdo run …` 与字节码后端输出一致;金样例稳定。
|
||||
|
||||
### P1b — view / 静态站中的输入(中优先级,接在 P1a 后)
|
||||
|
||||
当前 `run_file_capture` **不能**接真实 stdin——这是设计,不是偶然 bug。
|
||||
|
||||
推荐路径(由易到难):
|
||||
|
||||
1. **脚本化注入(无 UI)**
|
||||
- `marqdo run --stdin-file answers.txt` 或 frontmatter/`---` 旁测数据。
|
||||
- view:执行前提供「预置输入行」文本框,一次性灌入队列。
|
||||
2. **实时交互(live view)**
|
||||
- 执行到 `input` → 暂停 → HTTP/WS 返回 prompt → 用户提交一行 → 继续。
|
||||
- 依赖 P3 的「可暂停执行」钩子;可与断点共用会话模型。
|
||||
3. **静态 `view output`**
|
||||
- 无服务器则只支持预置输入或跳过并标明 `input skipped`。
|
||||
|
||||
完成定义:live `marqdo view` 下至少一个带 `input` 的示例可点按跑通;静态导出行为有文档。
|
||||
|
||||
---
|
||||
|
||||
## 4. P2 — 标准库(约 2–3 周,可与 P1b/P3 前半重叠)
|
||||
|
||||
### 分层
|
||||
|
||||
```text
|
||||
L0 内置函数(解释器内) len / str / int / float? / type?
|
||||
L1 标准库模块(.mq.md) 文本、表/集合小工具;官方路径如 lib/ 或 std/
|
||||
L2 生态约定 catalog 收录;用户站专章
|
||||
```
|
||||
|
||||
### 建议落地顺序
|
||||
|
||||
| 迭代 | 内容 | 依据 |
|
||||
|------|------|------|
|
||||
| **S0** | `len`(文本/表)、`str`、`int` | keywords.md 已列候选;字节码已有闲置 `Op::Len` 可接线 |
|
||||
| **S1** | 表工具:取列、行数;字符串 trim/split(先内置或纯 mq 实现二选一) | 文档型语言高频 |
|
||||
| **S2** | 官方 `lib/` 或 `std/` + 导入约定(仍可用 frontmatter;或日后 `> std/text.mq.md`) | 可生长而不破现有导入 |
|
||||
| **S3** | 错误类型约定(如非法 `int` 文本 → 诊断) | 依赖 P0 |
|
||||
|
||||
### 完成定义(S0)
|
||||
|
||||
- 金样例 + 双后端;`public/` 有对应介绍页。
|
||||
- 不引入 `if`/`while` 英文关键字(控制流仍归 Markdown 标记)。
|
||||
|
||||
### 刻意不做(本阶段)
|
||||
|
||||
- 完整面向对象、包管理器、异步 I/O、HTTP 客户端(可列远期)。
|
||||
|
||||
---
|
||||
|
||||
## 5. P3 — 前端成为调试机构(约 3–6 周,分里程碑)
|
||||
|
||||
**不要从 DAP/VS Code 插件开干。** view 已有 Structure / Source / Execution,是天然宿主。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
P0loc[P0 可信位置] --> Pause[语句边界暂停钩子]
|
||||
Pause --> Sess[调试会话 API]
|
||||
Sess --> UI[view 断点与单步 UI]
|
||||
UI --> DAP[可选 DAP 适配]
|
||||
```
|
||||
|
||||
| 里程碑 | 交付 | 依赖 |
|
||||
|--------|------|------|
|
||||
| **D0** | 语句级源映射(树优先;字节码指令→行) | P0 |
|
||||
| **D1** | 运行时钩子:进入语句前可 pause;`--trace-eval` 结构化事件(JSON 行) | D0 |
|
||||
| **D2** | 进程内调试会话:设/清断点、continue、step over(先树遍历) | D1 |
|
||||
| **D3** | **view debug 模式**:源码行点击断点;高亮当前行;侧栏 locals/栈;与文档模式切换 | D2 + 少量 JS 或服务端推进 |
|
||||
| **D4** | 与 P1b 合流:`input` 暂停复用同一会话 | P1b |
|
||||
| **D5**(可选) | DAP 薄适配,供外部 IDE | D2 稳定后 |
|
||||
|
||||
### 完成定义(D3 即「可用调试」)
|
||||
|
||||
- 用户能在 `marqdo view` 对某 `.mq.md` 设断点、单步、看变量。
|
||||
- 文档站默认模式不变(一次执行);debug 为显式开关。
|
||||
- 断点命中行与 P0 诊断行一致(允许文档说明「语句起点」语义)。
|
||||
|
||||
### 风险与边界
|
||||
|
||||
- 静态 `gh-pages` **无法**真断点(无常驻 VM);调试仅 **live view**(或未来 WASM 解释器)。
|
||||
- 字节码调试可晚于树遍历一个迭代。
|
||||
|
||||
---
|
||||
|
||||
## 6. 推荐排期(可执行流程)
|
||||
|
||||
按「每段都可合并、可演示」切周,避免大爆炸:
|
||||
|
||||
| 周序 | 主题 | 可合并交付 |
|
||||
|------|------|------------|
|
||||
| **W1** | P0 诊断统一 + errors 金样例加固 | 双后端错误位置一致 |
|
||||
| **W2** | P1a `input` 字节码 + 管道金样例 + 用户文档 | CLI 交互闭环 |
|
||||
| **W3** | P2-S0 `len`/`str`/`int` + 样例 | 「有点像语言」的第一批库 |
|
||||
| **W4** | P1b 预置输入(view 文本框 / `--stdin-file`) | view 可跑含 input 的 demo |
|
||||
| **W5–W6** | P3-D0–D2 暂停与会话 | 无 UI 也能用 API/CLI 单步 |
|
||||
| **W7–W8** | P3-D3 view 断点 UI + D4 与 input 暂停 | **调试机构**第一版 |
|
||||
| **并行/随后** | P2-S1/S2 扩库;P3-D5 DAP | 按反馈加 |
|
||||
|
||||
若人力紧:**砍掉顺序为 D5 → S2 花活 → 字节码调试**;**不可砍:P0、P1a、P2-S0、D3 之前的 D0–D2。**
|
||||
|
||||
---
|
||||
|
||||
## 7. 验收总表(「真正可用」最低线)
|
||||
|
||||
1. **I/O**:CLI 上 `print`/`input` 双后端一致;view 至少支持预置或交互输入之一。
|
||||
2. **错误**:失败必有稳定位置;常见错误有金样例;用户站不靠「瞎猜 stderr」。
|
||||
3. **库**:至少 `len`/`str`/`int` 可用并有文档。
|
||||
4. **调试**:live view 可断点 + 单步 + 看当前绑定(树遍历即可宣称 v1)。
|
||||
5. **不破坏**:现有 `tests/` 金样例与 `public/` 用户站回归绿。
|
||||
|
||||
---
|
||||
|
||||
## 8. 文档与工程动作(开工时)
|
||||
|
||||
1. 本文件定为「下一阶段宪法」;开工后把各 P 拆到 `doc/design/` 子设计(`input-interactive.md`、`stdlib.md`、`view-debug.md`)。
|
||||
2. 每个里程碑:金样例 → 实现 → `public/` 更新 →(若行为用户可见)再发版 / 刷 `gh-pages`。
|
||||
3. 版本建议:P1a+P0 可打 `v0.0.4`;P2-S0 打 `v0.0.5`;P3-D3 打 `v0.1.0`(「可用调试」语义升级)。
|
||||
|
||||
---
|
||||
|
||||
## 9. 一句话路线
|
||||
|
||||
**先把错误说准、把输入在 CLI 做完,再长出最小标准库;最后把现有 view 升级成可暂停的调试宿主——而不是先做 IDE 插件或大而全标准库。**
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
title: lib/foreign
|
||||
description: Run bound code fences and inline sources via local interpreters
|
||||
---
|
||||
|
||||
# set_cmd
|
||||
- lang
|
||||
- cmd
|
||||
|
||||
**> host_foreign_set_cmd lang=`lang` cmd=`cmd`**
|
||||
|
||||
# run
|
||||
- code
|
||||
|
||||
**> host_foreign_run code=`code`**
|
||||
|
||||
# run_lang
|
||||
- lang
|
||||
- source
|
||||
|
||||
**> host_foreign_run_lang lang=`lang` source=`source`**
|
||||
|
||||
# langs
|
||||
|
||||
**> host_foreign_langs**
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
title: lib/fs
|
||||
description: English filesystem wrappers
|
||||
---
|
||||
|
||||
# read_text
|
||||
- path
|
||||
|
||||
**> host_read_text path=`path`**
|
||||
|
||||
# write_text
|
||||
- path
|
||||
- text
|
||||
|
||||
**> host_write_text path=`path` text=`text`**
|
||||
|
||||
# append_text
|
||||
- path
|
||||
- text
|
||||
|
||||
**> host_append_text path=`path` text=`text`**
|
||||
|
||||
# exists
|
||||
- path
|
||||
|
||||
**> host_exists path=`path`**
|
||||
|
||||
# list_dir
|
||||
- path
|
||||
|
||||
**> host_list_dir path=`path`**
|
||||
|
||||
# make_dir
|
||||
- path
|
||||
|
||||
**> host_make_dir path=`path`**
|
||||
|
||||
# remove
|
||||
- path
|
||||
|
||||
**> host_remove path=`path`**
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
title: lib/json
|
||||
description: JSON parse/stringify (shared EN/ZH import)
|
||||
---
|
||||
|
||||
# parse
|
||||
- text
|
||||
|
||||
**> host_json_parse text=`text`**
|
||||
|
||||
# stringify
|
||||
- value
|
||||
|
||||
**> host_json_stringify value=`value`**
|
||||
|
||||
# get
|
||||
- value
|
||||
- key
|
||||
|
||||
**> host_json_get value=`value` key=`key`**
|
||||
|
||||
# keys
|
||||
- value
|
||||
|
||||
**> host_json_keys value=`value`**
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
---
|
||||
title: lib/math
|
||||
description: High-school math — num, random, formula, plot
|
||||
---
|
||||
|
||||
# pi
|
||||
|
||||
**> host_pi**
|
||||
|
||||
# e
|
||||
|
||||
**> host_e**
|
||||
|
||||
# num
|
||||
- value
|
||||
|
||||
**> host_num value=`value`**
|
||||
|
||||
# add
|
||||
- a
|
||||
- b
|
||||
|
||||
**> host_math_add a=`a` b=`b`**
|
||||
|
||||
# sub
|
||||
- a
|
||||
- b
|
||||
|
||||
**> host_math_sub a=`a` b=`b`**
|
||||
|
||||
# mul
|
||||
- a
|
||||
- b
|
||||
|
||||
**> host_math_mul a=`a` b=`b`**
|
||||
|
||||
# div
|
||||
- a
|
||||
- b
|
||||
|
||||
**> host_math_div a=`a` b=`b`**
|
||||
|
||||
# pow
|
||||
- a
|
||||
- b
|
||||
|
||||
**> host_math_pow a=`a` b=`b`**
|
||||
|
||||
# neg
|
||||
- value
|
||||
|
||||
**> host_math_neg value=`value`**
|
||||
|
||||
# sin
|
||||
- value
|
||||
|
||||
**> host_math_sin value=`value`**
|
||||
|
||||
# cos
|
||||
- value
|
||||
|
||||
**> host_math_cos value=`value`**
|
||||
|
||||
# tan
|
||||
- value
|
||||
|
||||
**> host_math_tan value=`value`**
|
||||
|
||||
# asin
|
||||
- value
|
||||
|
||||
**> host_math_asin value=`value`**
|
||||
|
||||
# acos
|
||||
- value
|
||||
|
||||
**> host_math_acos value=`value`**
|
||||
|
||||
# atan
|
||||
- value
|
||||
|
||||
**> host_math_atan value=`value`**
|
||||
|
||||
# sqrt
|
||||
- value
|
||||
|
||||
**> host_math_sqrt value=`value`**
|
||||
|
||||
# abs
|
||||
- value
|
||||
|
||||
**> host_math_abs value=`value`**
|
||||
|
||||
# ln
|
||||
- value
|
||||
|
||||
**> host_math_ln value=`value`**
|
||||
|
||||
# exp
|
||||
- value
|
||||
|
||||
**> host_math_exp value=`value`**
|
||||
|
||||
# floor
|
||||
- value
|
||||
|
||||
**> host_math_floor value=`value`**
|
||||
|
||||
# ceil
|
||||
- value
|
||||
|
||||
**> host_math_ceil value=`value`**
|
||||
|
||||
# min
|
||||
- a
|
||||
- b
|
||||
|
||||
**> host_math_min a=`a` b=`b`**
|
||||
|
||||
# max
|
||||
- a
|
||||
- b
|
||||
|
||||
**> host_math_max a=`a` b=`b`**
|
||||
|
||||
# random
|
||||
|
||||
**> host_random**
|
||||
|
||||
# random_int
|
||||
- min
|
||||
- max
|
||||
|
||||
**> host_random_int min=`min` max=`max`**
|
||||
|
||||
# seed
|
||||
- value
|
||||
|
||||
**> host_seed value=`value`**
|
||||
|
||||
# formula
|
||||
- text
|
||||
|
||||
**> host_formula value=`text`**
|
||||
|
||||
# simplify
|
||||
- formula
|
||||
|
||||
**> host_simplify value=`formula`**
|
||||
|
||||
# expand
|
||||
- formula
|
||||
|
||||
**> host_expand value=`formula`**
|
||||
|
||||
# diff
|
||||
- formula
|
||||
- var
|
||||
|
||||
**> host_diff formula=`formula` var=`var`**
|
||||
|
||||
# subs
|
||||
- formula
|
||||
- var
|
||||
- value
|
||||
|
||||
**> host_subs formula=`formula` var=`var` value=`value`**
|
||||
|
||||
# eval
|
||||
- formula
|
||||
- var
|
||||
- value
|
||||
|
||||
**> host_eval formula=`formula` var=`var` value=`value`**
|
||||
|
||||
# solve
|
||||
- formula
|
||||
- var
|
||||
|
||||
**> host_solve formula=`formula` var=`var`**
|
||||
|
||||
# plot
|
||||
- formula
|
||||
- var
|
||||
- min
|
||||
- max
|
||||
|
||||
**> host_plot formula=`formula` var=`var` min=`min` max=`max`**
|
||||
|
||||
# plot_points
|
||||
- xs
|
||||
- ys
|
||||
|
||||
**> host_plot_points xs=`xs` ys=`ys`**
|
||||
|
||||
# plot_conic
|
||||
- kind
|
||||
- a
|
||||
|
||||
**> host_plot_conic kind=`kind` a=`a`**
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
title: lib/net
|
||||
description: English minimal HTTP wrappers
|
||||
---
|
||||
|
||||
# http_get
|
||||
- url
|
||||
|
||||
**> host_http_get url=`url`**
|
||||
|
||||
# http_post
|
||||
- url
|
||||
- body
|
||||
|
||||
**> host_http_post url=`url` body=`body`**
|
||||
|
||||
# url_encode
|
||||
- text
|
||||
|
||||
**> host_url_encode text=`text`**
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
title: lib/sys
|
||||
description: English system wrappers
|
||||
---
|
||||
|
||||
# env_get
|
||||
- name
|
||||
|
||||
**> host_env_get name=`name`**
|
||||
|
||||
# env_set
|
||||
- name
|
||||
- value
|
||||
|
||||
**> host_env_set name=`name` value=`value`**
|
||||
|
||||
# args
|
||||
|
||||
**> host_args**
|
||||
|
||||
# cwd
|
||||
|
||||
**> host_cwd**
|
||||
|
||||
# exit
|
||||
- code
|
||||
|
||||
**> host_exit code=`code`**
|
||||
|
||||
# exec
|
||||
- cmd
|
||||
|
||||
**> host_exec cmd=`cmd`**
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
title: lib/table
|
||||
description: English table helpers over len / at
|
||||
---
|
||||
|
||||
# rows
|
||||
- xs
|
||||
|
||||
**> len `xs`**
|
||||
|
||||
# row_at
|
||||
- xs
|
||||
- i
|
||||
|
||||
**> at value=`xs` index=`i`**
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
title: lib/text
|
||||
description: English text helpers over trim / split / join
|
||||
---
|
||||
|
||||
# str_trim
|
||||
- s
|
||||
|
||||
**> trim `s`**
|
||||
|
||||
# str_split
|
||||
- s
|
||||
- sep
|
||||
|
||||
**> split value=`s` sep=`sep`**
|
||||
|
||||
# str_join
|
||||
- xs
|
||||
- sep
|
||||
|
||||
**> join value=`xs` sep=`sep`**
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
title: lib/time
|
||||
description: English time wrappers
|
||||
---
|
||||
|
||||
# now_unix
|
||||
|
||||
**> host_now_unix**
|
||||
|
||||
# now_ms
|
||||
|
||||
**> host_now_ms**
|
||||
|
||||
# format
|
||||
- unix
|
||||
- pattern
|
||||
|
||||
**> host_format_time unix=`unix` pattern=`pattern`**
|
||||
|
||||
# sleep_ms
|
||||
- ms
|
||||
|
||||
**> host_sleep_ms ms=`ms`**
|
||||
|
||||
# parse
|
||||
- text
|
||||
- pattern
|
||||
|
||||
**> host_parse_time text=`text` pattern=`pattern`**
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
title: lib/外联
|
||||
description: 通过本机解释器运行绑定的代码围栏与内联源码
|
||||
---
|
||||
|
||||
# 设置命令
|
||||
- 语言
|
||||
- 命令
|
||||
|
||||
**> host_foreign_set_cmd lang=`语言` cmd=`命令`**
|
||||
|
||||
# 运行
|
||||
- 代码
|
||||
|
||||
**> host_foreign_run code=`代码`**
|
||||
|
||||
# 按语言运行
|
||||
- 语言
|
||||
- 源码
|
||||
|
||||
**> host_foreign_run_lang lang=`语言` source=`源码`**
|
||||
|
||||
# 语言表
|
||||
|
||||
**> host_foreign_langs**
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
---
|
||||
title: lib/数学
|
||||
description: 高中数学 — 数值、随机、公式、作图
|
||||
---
|
||||
|
||||
# 圆周率
|
||||
|
||||
**> host_pi**
|
||||
|
||||
# 自然底数
|
||||
|
||||
**> host_e**
|
||||
|
||||
# 数
|
||||
- value
|
||||
|
||||
**> host_num value=`value`**
|
||||
|
||||
# 加
|
||||
- a
|
||||
- b
|
||||
|
||||
**> host_math_add a=`a` b=`b`**
|
||||
|
||||
# 减
|
||||
- a
|
||||
- b
|
||||
|
||||
**> host_math_sub a=`a` b=`b`**
|
||||
|
||||
# 乘
|
||||
- a
|
||||
- b
|
||||
|
||||
**> host_math_mul a=`a` b=`b`**
|
||||
|
||||
# 除
|
||||
- a
|
||||
- b
|
||||
|
||||
**> host_math_div a=`a` b=`b`**
|
||||
|
||||
# 幂
|
||||
- a
|
||||
- b
|
||||
|
||||
**> host_math_pow a=`a` b=`b`**
|
||||
|
||||
# 负
|
||||
- value
|
||||
|
||||
**> host_math_neg value=`value`**
|
||||
|
||||
# 正弦
|
||||
- value
|
||||
|
||||
**> host_math_sin value=`value`**
|
||||
|
||||
# 余弦
|
||||
- value
|
||||
|
||||
**> host_math_cos value=`value`**
|
||||
|
||||
# 正切
|
||||
- value
|
||||
|
||||
**> host_math_tan value=`value`**
|
||||
|
||||
# 反正弦
|
||||
- value
|
||||
|
||||
**> host_math_asin value=`value`**
|
||||
|
||||
# 反余弦
|
||||
- value
|
||||
|
||||
**> host_math_acos value=`value`**
|
||||
|
||||
# 反正切
|
||||
- value
|
||||
|
||||
**> host_math_atan value=`value`**
|
||||
|
||||
# 平方根
|
||||
- value
|
||||
|
||||
**> host_math_sqrt value=`value`**
|
||||
|
||||
# 绝对值
|
||||
- value
|
||||
|
||||
**> host_math_abs value=`value`**
|
||||
|
||||
# 对数
|
||||
- value
|
||||
|
||||
**> host_math_ln value=`value`**
|
||||
|
||||
# 指数
|
||||
- value
|
||||
|
||||
**> host_math_exp value=`value`**
|
||||
|
||||
# 向下取整
|
||||
- value
|
||||
|
||||
**> host_math_floor value=`value`**
|
||||
|
||||
# 向上取整
|
||||
- value
|
||||
|
||||
**> host_math_ceil value=`value`**
|
||||
|
||||
# 最小
|
||||
- a
|
||||
- b
|
||||
|
||||
**> host_math_min a=`a` b=`b`**
|
||||
|
||||
# 最大
|
||||
- a
|
||||
- b
|
||||
|
||||
**> host_math_max a=`a` b=`b`**
|
||||
|
||||
# 随机
|
||||
|
||||
**> host_random**
|
||||
|
||||
# 随机整数
|
||||
- min
|
||||
- max
|
||||
|
||||
**> host_random_int min=`min` max=`max`**
|
||||
|
||||
# 设种子
|
||||
- value
|
||||
|
||||
**> host_seed value=`value`**
|
||||
|
||||
# 公式
|
||||
- text
|
||||
|
||||
**> host_formula value=`text`**
|
||||
|
||||
# 化简
|
||||
- formula
|
||||
|
||||
**> host_simplify value=`formula`**
|
||||
|
||||
# 展开
|
||||
- formula
|
||||
|
||||
**> host_expand value=`formula`**
|
||||
|
||||
# 求导
|
||||
- formula
|
||||
- var
|
||||
|
||||
**> host_diff formula=`formula` var=`var`**
|
||||
|
||||
# 代入
|
||||
- formula
|
||||
- var
|
||||
- value
|
||||
|
||||
**> host_subs formula=`formula` var=`var` value=`value`**
|
||||
|
||||
# 求值
|
||||
- formula
|
||||
- var
|
||||
- value
|
||||
|
||||
**> host_eval formula=`formula` var=`var` value=`value`**
|
||||
|
||||
# 求解
|
||||
- formula
|
||||
- var
|
||||
|
||||
**> host_solve formula=`formula` var=`var`**
|
||||
|
||||
# 绘图
|
||||
- formula
|
||||
- var
|
||||
- min
|
||||
- max
|
||||
|
||||
**> host_plot formula=`formula` var=`var` min=`min` max=`max`**
|
||||
|
||||
# 绘点列
|
||||
- xs
|
||||
- ys
|
||||
|
||||
**> host_plot_points xs=`xs` ys=`ys`**
|
||||
|
||||
# 绘圆锥
|
||||
- kind
|
||||
- a
|
||||
|
||||
**> host_plot_conic kind=`kind` a=`a`**
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
title: lib/文件
|
||||
description: 中文文件系统包装
|
||||
---
|
||||
|
||||
# 读文本
|
||||
- 路径
|
||||
|
||||
**> host_read_text path=`路径`**
|
||||
|
||||
# 写文本
|
||||
- 路径
|
||||
- 内容
|
||||
|
||||
**> host_write_text path=`路径` text=`内容`**
|
||||
|
||||
# 追加文本
|
||||
- 路径
|
||||
- 内容
|
||||
|
||||
**> host_append_text path=`路径` text=`内容`**
|
||||
|
||||
# 存在
|
||||
- 路径
|
||||
|
||||
**> host_exists path=`路径`**
|
||||
|
||||
# 列目录
|
||||
- 路径
|
||||
|
||||
**> host_list_dir path=`路径`**
|
||||
|
||||
# 建目录
|
||||
- 路径
|
||||
|
||||
**> host_make_dir path=`路径`**
|
||||
|
||||
# 删除
|
||||
- 路径
|
||||
|
||||
**> host_remove path=`路径`**
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
title: lib/文本
|
||||
description: 中文文本库:去空白 / 拆分 / 拼接
|
||||
---
|
||||
|
||||
# 去空白
|
||||
- s
|
||||
|
||||
**> trim `s`**
|
||||
|
||||
# 拆分
|
||||
- s
|
||||
- sep
|
||||
|
||||
**> split value=`s` sep=`sep`**
|
||||
|
||||
# 拼接
|
||||
- xs
|
||||
- sep
|
||||
|
||||
**> join value=`xs` sep=`sep`**
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
title: lib/时间
|
||||
description: 中文时间包装
|
||||
---
|
||||
|
||||
# 此刻秒
|
||||
|
||||
**> host_now_unix**
|
||||
|
||||
# 此刻毫秒
|
||||
|
||||
**> host_now_ms**
|
||||
|
||||
# 格式化
|
||||
- 秒
|
||||
- 格式
|
||||
|
||||
**> host_format_time unix=`秒` pattern=`格式`**
|
||||
|
||||
# 睡眠毫秒
|
||||
- 毫秒
|
||||
|
||||
**> host_sleep_ms ms=`毫秒`**
|
||||
|
||||
# 解析时间
|
||||
- 内容
|
||||
- 格式
|
||||
|
||||
**> host_parse_time text=`内容` pattern=`格式`**
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
title: lib/系统
|
||||
description: 中文系统包装
|
||||
---
|
||||
|
||||
# 取环境
|
||||
- 名
|
||||
|
||||
**> host_env_get name=`名`**
|
||||
|
||||
# 设环境
|
||||
- 名
|
||||
- 值
|
||||
|
||||
**> host_env_set name=`名` value=`值`**
|
||||
|
||||
# 参数表
|
||||
|
||||
**> host_args**
|
||||
|
||||
# 工作目录
|
||||
|
||||
**> host_cwd**
|
||||
|
||||
# 退出
|
||||
- 码
|
||||
|
||||
**> host_exit code=`码`**
|
||||
|
||||
# 执行
|
||||
- 命令
|
||||
|
||||
**> host_exec cmd=`命令`**
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
title: lib/网络
|
||||
description: 中文简易网络包装
|
||||
---
|
||||
|
||||
# 获取
|
||||
- 地址
|
||||
|
||||
**> host_http_get url=`地址`**
|
||||
|
||||
# 提交
|
||||
- 地址
|
||||
- 内容
|
||||
|
||||
**> host_http_post url=`地址` body=`内容`**
|
||||
|
||||
# 编码地址
|
||||
- 内容
|
||||
|
||||
**> host_url_encode text=`内容`**
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
---
|
||||
title: lib/表
|
||||
description: 中文表库:行数 / 取行
|
||||
---
|
||||
|
||||
# 行数
|
||||
- xs
|
||||
|
||||
**> len `xs`**
|
||||
|
||||
# 取行
|
||||
- xs
|
||||
- i
|
||||
|
||||
**> at value=`xs` index=`i`**
|
||||
+39
-15
@@ -1,31 +1,55 @@
|
||||
---
|
||||
title: 欢迎使用 Marqdo
|
||||
description: 用户文档首页 — 代码即文档
|
||||
title: Welcome to Marqdo
|
||||
description: User docs home — code is documentation (English)
|
||||
> lib/math.mq.md
|
||||
> lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
阅读到这里的朋友你好!我是marqdo的开发者,很高兴你看到这个网站,marqdo是一个代码即文档的编程语言,作者想要做这个项目来源于一个小小的想法,AI输出的首选语言是markdown,为什么不能基于markdown创建一个新式的编程语言,不再区分文档和代码,代码写出来就是一份文档,文档也是代码(这个项目的野心实际更大些,项目立项之处就调研了谷歌OKF规范,计划自动生成YAML使得代码和文档能够自动的变成知识库,与此同时还有更多可能,例如规范化生成的PPT)。
|
||||
Hi — thanks for reading this far. I am Marqdo’s developer. Marqdo is a language where **code is documentation, and documentation is code**: Markdown markers are the program structure, so what you read is what runs.
|
||||
|
||||
所以marqdo产生了,为了确保我们的新语言能够百分百被markdown渲染,这门语言甚至采用了`.mq.md`的双层嵌套后缀,所以不需要有压力使用这门语言,就算出现了巨大的问题,就当让ai写文档好了,如果成功了,试想这样一种场景,你不再需要让ai生成代码的文档,ai写的代码能够便捷的被你读懂,至少能省点token,毕竟烧了太多,钱包容易饿瘦。
|
||||
AI already prefers Markdown-shaped output. The idea was: why keep docs and code as two separate worlds? So Marqdo was born as a “docs are code” language. To keep every source renderable as Markdown, files use the `.mq.md` suffix. From early on we aimed for richer tooling — auto-generated YAML for OKF-style knowledge bases, even auto-generated slides — those are later goals. Happily, it already works well as a blogging tool: yes, this site is generated by Marqdo. And when AI writes Marqdo, you tend to burn fewer tokens — wallets everywhere thank you.
|
||||
|
||||
这门语言还是起步阶段,目前计划是制作一个解释型的语言,现在的marqdo支持一些特定的语法结构和关键字,并且允许自由的输出调试信息,以及直接通过前端预览各个代码块,生成静态文件,是的,没错,这个网站就是marqdo制作的,至少我相信marqdo会成为一个博客工具。
|
||||
The language is still young: structure markers, bilingual core names (`print` / `打印`, …), importable stdlibs (see [`stdlib/`](stdlib/) on this site), local `view`, and static export. Contribute on [GitHub](https://github.com/cflmy/marqdo).
|
||||
|
||||
除了部分内置的关键字,marqdo并不限制必须使用英文编程,当然这并不意味着我要开发一个中文编程系统,事实上,这是由于文档即代码、代码即文档的结构决定的,如果只支持英文,那还有什么作用?还要掌握一门语言,这并不是让人愉悦的阅读体验,所以marqdo会长期支持多语言编程的可能。
|
||||
中文文档请看同目录的 [`00-欢迎.mq.md`](00-欢迎.mq.md)(叙述与内置均用中文)。
|
||||
|
||||
欢迎各位加入开源库,共同建设和完成这个项目[marqdo的github仓库链接](https://github.com/cflmy/marqdo)
|
||||
A small function to say hello:
|
||||
|
||||
最后,引用所有程序员的开始欢迎各位:
|
||||
> greet who=marqdo
|
||||
|
||||
> 问候 marqdo
|
||||
Named args can include spaces:
|
||||
|
||||
如果你是一个敏锐的程序员应该会察觉到一个小问题,这个问题的解决方案是像下面这样的,我其实并不知道这样解决是否正确,但是我暂且放在这里,欢迎你,敏锐的程序元朋友。
|
||||
> greet who=marqdo user
|
||||
|
||||
> 问候 谁=marqdo user
|
||||
## greet
|
||||
- who
|
||||
|
||||
## 问候
|
||||
- 谁
|
||||
|
||||
> print text=欢迎,`谁`!
|
||||
> print text=Welcome, `who`!
|
||||
|
||||
---
|
||||
|
||||
Beyond the basics above, Marqdo also ships standard libraries: table, time, text, files, system, math, foreign, and more.
|
||||
|
||||
Math and foreign deserve a special mention. With the math library you can bind a formula like this:
|
||||
|
||||
`f` =
|
||||
$$
|
||||
x^2 - 2
|
||||
$$
|
||||
|
||||
Then plot it:
|
||||
|
||||
*`_svg` = > plot formula=`f` var=x min=-3 max=3 *
|
||||
|
||||
The foreign library lets you call external code, for example:
|
||||
|
||||
`hi` =
|
||||
```python
|
||||
print("hello-from-python")
|
||||
```
|
||||
|
||||
Under Markdown this stays easy to read — which is the point: Marqdo’s design is code as documentation, documentation as code.
|
||||
|
||||
Welcome again — enjoy exploring Marqdo.
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
title: 欢迎使用 Marqdo
|
||||
description: 用户文档首页 — 代码即文档(中文版)
|
||||
> lib/数学.mq.md
|
||||
> lib/外联.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
阅读到这里的朋友你好!我是 Marqdo 的开发者。Marqdo 是一门**代码即文档,文档即代码**的语言:Markdown 标记就是程序结构,你读到的就是能跑的程序。
|
||||
|
||||
AI 偏爱 Markdown结构的输出。作者的念头是:何必再把文档和代码拆成两套?我们来实现一个文档即代码的语言,所以marqdo应运而生,为了确保代码一定可以被渲染,marqdo的文件后缀定义为了`.mq.md`。在开发之处我们就尝试希望更丰富的支持,自动生成一个yaml文件使得 OKF 式知识库便捷的自动配置,乃至自动生成ppt,自然这都是以后的目标了。不过相当不错的是,至少这会成为一个不错的博客工具——对,这个站点就是 Marqdo 生成的,而且AI输出的时候会节约不少token,你知道的,token烧的太多,钱包会可怜的饿瘦的。
|
||||
|
||||
语言仍在起步:结构标记、中英内核双名(`打印` / `print` …)、可导入的标准库(见本站 [`stdlib/`](stdlib/))、本地 `view` 与静态导出。欢迎到 [GitHub](https://github.com/cflmy/marqdo) 一起做。
|
||||
|
||||
English docs: [`00-welcome.mq.md`](00-welcome.mq.md) (English prose and English builtins).
|
||||
|
||||
用一个小函数打个招呼:
|
||||
|
||||
> 问候 谁=marqdo
|
||||
|
||||
具名实参可以带空格:
|
||||
|
||||
> 问候 谁=marqdo user
|
||||
|
||||
## 问候
|
||||
- 谁
|
||||
|
||||
> 打印 内容=欢迎,`谁`!
|
||||
|
||||
---
|
||||
|
||||
除了上面的一些基本内容之外,我还开发了这个语言的一些标准库,包括表、时间、文本、文件、系统、数学和外联等标准库。
|
||||
|
||||
其中数学库和外联库是我要着重提到的,例如数学库,你可以通过下面的方式调用:
|
||||
|
||||
`f` =
|
||||
$$
|
||||
x^2 - 2
|
||||
$$
|
||||
|
||||
之后让我们画个图像吧!
|
||||
|
||||
*`_svg` = > 绘图 formula=`f` var=x min=-3 max=3 *
|
||||
|
||||
外联库则允许你调用外部代码,例如:
|
||||
|
||||
`hi` =
|
||||
```python
|
||||
print("hello-from-python")
|
||||
```
|
||||
|
||||
这些代码在markdown下面都非常的易读,就像我说的,marqdo的设计思想就是代码即文档,
|
||||
文档即代码。
|
||||
|
||||
最后,再次欢迎你,尽情体验marqdo吧!
|
||||
+10
-10
@@ -1,26 +1,26 @@
|
||||
# 用户文档(可执行 · 可下载)
|
||||
# 用户文档(可执行 · 可下载 · 中英双语)
|
||||
|
||||
本目录即面向访客的 Marqdo 介绍:每个 `.mq.md` 既是文稿也能 `marqdo run`,并随仓库 / 静态站一起下载。
|
||||
|
||||
**双语约定:** 拉丁文件名 → 英文叙述与英文内置;中文文件名 → 中文叙述与中文编程。成对放在同一目录。标准库:拉丁路径用英文 API,中文路径用中文 API;JSON 仅 `lib/json.mq.md`。
|
||||
|
||||
| 路径 | 内容 |
|
||||
|------|------|
|
||||
| [`00-welcome.mq.md`](00-welcome.mq.md) | 首页 |
|
||||
| [`00-welcome.mq.md`](00-welcome.mq.md) / [`00-欢迎.mq.md`](00-欢迎.mq.md) | 首页(英 / 中) |
|
||||
| [`structure/`](structure/) | 基本结构 |
|
||||
| [`keywords/`](keywords/) | 关键字与内置 `print` |
|
||||
| [`features/`](features/) | 特性迭代说明 |
|
||||
| [`keywords/`](keywords/) | 关键字与 L0 内置 |
|
||||
| [`stdlib/`](stdlib/) | **标准库**(导入方式 + text/表/文件/时间/系统/json/网络/数学/外联) |
|
||||
| [`features/`](features/) | 特性迭代 |
|
||||
|
||||
**不放** `errors/`:失败样例只在 `tests/errors/`,避免用户站出现红色执行失败。
|
||||
**不放** `errors/`:失败样例只在 `tests/errors/`。
|
||||
|
||||
开发文档(语言设计等)在 [`doc/`](../doc/),与本目录分离。
|
||||
开发文档在 [`doc/`](../doc/)。
|
||||
|
||||
## 浏览与生成 HTML
|
||||
|
||||
```bash
|
||||
cargo run -- view public
|
||||
cargo run -- view output public -o public
|
||||
# 或
|
||||
./scripts/build-public.sh
|
||||
powershell -File ./scripts/build-public.ps1
|
||||
```
|
||||
|
||||
生成的 `index.html` 与 `pages/` 默认被 ignore;CI 构建后推到 `gh-pages`。详见 [user-site.md](../doc/design/user-site.md)。
|
||||
详见 [user-site.md](../doc/design/user-site.md)。
|
||||
@@ -1,14 +1,14 @@
|
||||
---
|
||||
title: Phase I — 树遍历解释器
|
||||
description: 词法 · 语法 · 语义 · 树遍历已贯通
|
||||
title: Phase I — tree-walk interpreter
|
||||
description: Lex · parse · check · tree-walk end to end
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
里程碑:Phase I(树遍历)。
|
||||
Milestone: Phase I (tree-walk).
|
||||
|
||||
流水线:加载 → 行分类 → 递归下降语法 → 语义检查 → 树遍历执行。实现不用 Flex/Bison。
|
||||
Pipeline: load → line classify → recursive-descent parse → semantic check → tree-walk eval. No Flex/Bison.
|
||||
|
||||
本页本身即可运行,证明「文档即程序」在解释器里已落地:
|
||||
This page runs as a program — documentation is executable:
|
||||
|
||||
> print text=Phase I:tree-walk interpreter is live.
|
||||
> print text=Phase I: tree-walk interpreter is live.
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
title: 第一阶段 — 树遍历解释器
|
||||
description: 词法 · 语法 · 语义 · 树遍历已贯通
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
里程碑:第一阶段(树遍历)。
|
||||
|
||||
流水线:加载 → 行分类 → 递归下降语法 → 语义检查 → 树遍历执行。实现不用 Flex/Bison。
|
||||
|
||||
本页本身即可运行,证明「文档即程序」已落地:
|
||||
|
||||
> 打印 内容=第一阶段:树遍历解释器已就绪。
|
||||
@@ -1,18 +1,18 @@
|
||||
---
|
||||
title: 字节码后端
|
||||
description: --backend bytecode 与树遍历共用语义
|
||||
title: Bytecode backend
|
||||
description: `--backend bytecode` shares semantics with tree-walk
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
里程碑:字节码原型。
|
||||
Milestone: bytecode prototype.
|
||||
|
||||
同一套 .mq.md 可用树遍历或字节码 VM 执行。命令示例:
|
||||
The same `.mq.md` runs on tree-walk or the bytecode VM:
|
||||
|
||||
marqdo run FILE --backend tree
|
||||
|
||||
marqdo run FILE --backend bytecode
|
||||
|
||||
下面这段在两种后端下输出一致:
|
||||
Output matches on both backends:
|
||||
|
||||
> print text=Bytecode backend:same program, alternate engine.
|
||||
> print text=Bytecode backend: same program, alternate engine.
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
title: 字节码后端
|
||||
description: `--backend bytecode` 与树遍历共用语义
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
里程碑:字节码原型。
|
||||
|
||||
同一套 `.mq.md` 可用树遍历或字节码 VM:
|
||||
|
||||
marqdo run FILE --backend tree
|
||||
|
||||
marqdo run FILE --backend bytecode
|
||||
|
||||
两种后端输出一致:
|
||||
|
||||
> 打印 内容=字节码后端:同一程序,另一引擎。
|
||||
@@ -1,16 +1,16 @@
|
||||
---
|
||||
title: view 与用户文档站
|
||||
description: 本地浏览与静态导出由解释器生成
|
||||
title: view and the user docs site
|
||||
description: Local browse and static export from the interpreter
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
里程碑:marqdo view 与 view output。
|
||||
Milestone: `marqdo view` and `view output`.
|
||||
|
||||
本地浏览:marqdo view public
|
||||
Local: `marqdo view public`
|
||||
|
||||
静态导出:marqdo view output public -o public
|
||||
Static export: `marqdo view output public -o public`
|
||||
|
||||
用户可执行文档就在 public/;生成的 HTML(index.html / pages/)供静态托管,CI 发布到 gh-pages。
|
||||
Executable user docs live under `public/`. Generated HTML (`index.html` / `pages/`) is for hosting; CI publishes to `gh-pages`.
|
||||
|
||||
> print text=Docs site:generated by the Marqdo interpreter, not hand-written HTML.
|
||||
> print text=Docs site: generated by the Marqdo interpreter, not hand-written HTML.
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
title: view 与用户文档站
|
||||
description: 本地浏览与静态导出由解释器生成
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
里程碑:`marqdo view` 与 `view output`。
|
||||
|
||||
本地浏览:`marqdo view public`
|
||||
|
||||
静态导出:`marqdo view output public -o public`
|
||||
|
||||
用户可执行文档在 `public/`;生成的 HTML(`index.html` / `pages/`)供静态托管,CI 发布到 `gh-pages`。
|
||||
|
||||
> 打印 内容=文档站:由 Marqdo 解释器生成,不是手写 HTML。
|
||||
@@ -1,11 +1,11 @@
|
||||
---
|
||||
title: 布尔与逻辑
|
||||
description: True / False / None 与 and / or / not
|
||||
title: Booleans and logic
|
||||
description: True / False / None and and / or / not
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
关键字:`True`、`False`、`None`,以及 `and` / `or` / `not`。
|
||||
Keywords: `True`, `False`, `None`, and `and` / `or` / `not`.
|
||||
|
||||
*`a` = True*
|
||||
*`b` = False*
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
title: Built-in input
|
||||
description: Read one line from stdin; optional prompt. Demo via frontmatter stdin.
|
||||
stdin: Ada
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
The input builtin reads one line. For demos and marqdo view / static export, put sample lines in frontmatter (stdin:). CLI can also use a pipe or --stdin-file. Live view can override with the Preset input box.
|
||||
|
||||
*`name` = > input prompt=Name: *
|
||||
|
||||
> print text=Hello `name`!
|
||||
@@ -1,14 +1,14 @@
|
||||
---
|
||||
title: 内置 print
|
||||
description: 具名与位置两种写法
|
||||
title: Built-in print
|
||||
description: Named and positional forms
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
内置 print 接受具名或位置实参:
|
||||
The `print` builtin accepts named or positional arguments:
|
||||
|
||||
> print text=named form
|
||||
|
||||
> print positional
|
||||
|
||||
这里的设计思路是具名实参允许空格的传入,位置实参则不允许。
|
||||
Named args may contain spaces; positional args may not.
|
||||
@@ -0,0 +1,34 @@
|
||||
---
|
||||
title: Built-ins len / str / int / type / trim / split / join / at
|
||||
description: Host builtins for strings and tables
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
Length and type:
|
||||
|
||||
*`s` = hello*
|
||||
|
||||
*`n` = > len `s`*
|
||||
|
||||
> print text=`n`
|
||||
|
||||
*`ty` = > type `s`*
|
||||
|
||||
> print text=`ty`
|
||||
|
||||
Trim, split, join, and index:
|
||||
|
||||
*`t` = > trim value= hi *
|
||||
|
||||
*`parts` = > split value=a,b sep=,*
|
||||
|
||||
*`mid` = > at value=`parts` index=0*
|
||||
|
||||
*`j` = > join value=`parts` sep=-*
|
||||
|
||||
> print text=`t`
|
||||
|
||||
> print text=`mid`
|
||||
|
||||
> print text=`j`
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
title: 中英内核双名
|
||||
description: 无需导入:打印、长度、文本、整数 与 print / len / …
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
内核中英别名等价,可混用:
|
||||
|
||||
*`s` = 你好*
|
||||
|
||||
*`n` = > 长度 值=`s`*
|
||||
|
||||
> 打印 内容=`n`
|
||||
|
||||
> print text=also-english
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
title: 布尔与逻辑
|
||||
description: 真 / 假 / 空 与 且 / 或 / 非
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
关键字:`真`、`假`、`空`,以及 `且` / `或` / `非`。
|
||||
|
||||
*`a` = 真*
|
||||
*`b` = 假*
|
||||
|
||||
+ `a` 且 非 `b`
|
||||
> 打印 内容=通过
|
||||
+ *
|
||||
> 打印 内容=失败
|
||||
|
||||
*`probe` = 1*
|
||||
|
||||
+ 空
|
||||
> 打印 内容=空为真
|
||||
+ *
|
||||
> 打印 内容=空为假
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
title: 内置 打印
|
||||
description: 具名与位置两种写法
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
内置 `打印` 接受具名或位置实参:
|
||||
|
||||
> 打印 内容=具名写法
|
||||
|
||||
> 打印 位置写法
|
||||
|
||||
具名实参可以带空格;位置实参不可以。
|
||||
@@ -0,0 +1,34 @@
|
||||
---
|
||||
title: 内置 长度 / 文本 / 整数 与 trim 等
|
||||
description: 主机内置;中文别名覆盖常用几个
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
长度与英文 `type`(类型无中文内核别名,见标准库文档):
|
||||
|
||||
*`s` = 你好*
|
||||
|
||||
*`n` = > 长度 值=`s`*
|
||||
|
||||
> 打印 内容=`n`
|
||||
|
||||
*`ty` = > type `s`*
|
||||
|
||||
> 打印 内容=`ty`
|
||||
|
||||
去空白、拆分、拼接、按下标(主机名仍为英文):
|
||||
|
||||
*`t` = > trim value= 嗨 *
|
||||
|
||||
*`parts` = > split value=甲,乙 sep=,*
|
||||
|
||||
*`mid` = > at value=`parts` index=0*
|
||||
|
||||
*`j` = > join value=`parts` sep=-*
|
||||
|
||||
> 打印 内容=`t`
|
||||
|
||||
> 打印 内容=`mid`
|
||||
|
||||
> 打印 内容=`j`
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
title: 内置 输入
|
||||
description: 从 stdin 读一行;可选提示。演示数据写在 frontmatter 输入。
|
||||
输入: 小明
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
内置「输入」读一行。演示与 marqdo view / 静态导出可在 frontmatter 写「输入:」(或 stdin:)。CLI 也可用管道或 --stdin-file。Live view 可用 Preset input 覆盖。
|
||||
|
||||
*`名字` = > 输入 提示=名字: *
|
||||
|
||||
> 打印 内容=你好 `名字`!
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
title: Standard library — overview
|
||||
description: How to import official lib modules
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
Official libraries live under lib/ (alias std/). Import them in YAML frontmatter with a greater-than line, for example lib/text.mq.md or lib/fs.mq.md.
|
||||
|
||||
English-named files export English APIs; Chinese-named files export Chinese APIs. JSON is special: only lib/json.mq.md (shared by both languages).
|
||||
|
||||
No extra allow flags: importing a module means you intend to use it. Under marqdo view or static export, exit soft-fails and long sleeps are clamped so the console stays up.
|
||||
|
||||
Modules: text (text / 文本), table (table / 表), files (fs / 文件), time (time / 时间), system (sys / 系统), json (json only), net (net / 网络), math (math / 数学), foreign (foreign / 外联).
|
||||
|
||||
Sibling pages in this folder document each module. Chinese overview: 00-索引.mq.md.
|
||||
|
||||
> print text=stdlib overview ok
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
title: 标准库 — 总览
|
||||
description: 如何导入官方 lib 模块
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
官方库在仓库 lib/(别名 std/)。在 YAML frontmatter 用大于号行导入,例如 lib/文本.mq.md 或 lib/文件.mq.md。
|
||||
|
||||
拉丁文件名导出英文 API;中文文件名导出中文 API。JSON 特例:只有 lib/json.mq.md(中英共用)。
|
||||
|
||||
导入即表示要用对应能力,无需再加允许旗标。marqdo view 或静态导出里,退出会软失败、长睡眠会被钳制,以免拖垮控制台。
|
||||
|
||||
模块:文本(text / 文本)、表(table / 表)、文件(fs / 文件)、时间(time / 时间)、系统(sys / 系统)、json(仅 json)、网络(net / 网络)、数学(math / 数学)、外联(foreign / 外联)。
|
||||
|
||||
各模块说明见本目录其它页。English: 00-overview.mq.md.
|
||||
|
||||
> 打印 内容=标准库总览就绪
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
title: lib/foreign — external languages
|
||||
description: Run local interpreters from Marqdo (English)
|
||||
> lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
Import lib/foreign.mq.md. Bind a code fence like a formula: empty-RHS assign then a ```lang block. The value type is code. Call run code=`name` to execute via your local interpreter. run_lang runs an inline source string.
|
||||
|
||||
`hi` =
|
||||
```python
|
||||
print("hello-from-python")
|
||||
```
|
||||
|
||||
Default command is python (Windows) or python3 (Unix). Override with set_cmd, env MARQDO_FOREIGN_PYTHON, or the command box in live view. Failures ask you to check that configuration.
|
||||
|
||||
*`out` = > run code=`hi` *
|
||||
|
||||
> print text=`out`
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
title: lib/fs — files
|
||||
description: Read and write text under the sandbox
|
||||
> lib/fs.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
Import lib/fs.mq.md. Functions: read_text, write_text, append_text, exists, list_dir, make_dir, remove (path / text params).
|
||||
|
||||
Bare path words must not contain a slash character (parsed as division). Prefer a same-folder name or a variable.
|
||||
|
||||
*`ok` = > exists path=demo.txt *
|
||||
|
||||
+ `ok`
|
||||
> print text=demo-present
|
||||
+ *
|
||||
> print text=demo-missing
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
title: lib/json — JSON
|
||||
description: Shared EN/ZH path; parse and stringify
|
||||
> lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
Import lib/json.mq.md from both English and Chinese docs (no translated twin). Functions: parse(text), stringify(value), get(value, key), keys(value). Objects become the map runtime type.
|
||||
|
||||
*`obj` = > parse text={} *
|
||||
|
||||
*`ty` = > type `obj` *
|
||||
|
||||
> print text=`ty`
|
||||
|
||||
*`out` = > stringify value=`obj` *
|
||||
|
||||
> print text=`out`
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
title: lib/math — numbers, formulas, plots
|
||||
description: High-school math stdlib (English)
|
||||
> lib/math.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
Import lib/math.mq.md. Runtime types: num (float) and formula (symbolic tree). Bind a formula with an empty-RHS assign followed by a `$$…$$` fence (same shape as table assigns). In view, Structure renders that fence with KaTeX.
|
||||
|
||||
`f` =
|
||||
$$
|
||||
x^2 - 2
|
||||
$$
|
||||
|
||||
Numeric helpers: pi, e, num, add/sub/mul/div/pow, sin/cos/tan, sqrt/abs/ln/exp, floor/ceil, min/max. Random: seed, random, random_int (reproducible after seed).
|
||||
|
||||
Symbolic: formula(text), simplify, expand, diff, subs, eval, solve.
|
||||
|
||||
Plotting (already in the library): plot / plot_points / plot_conic return SVG text. Axes include arrows and tick labels; **grid is on by default** (pass grid=False / grid=假 to hide). Optional path= writes a file under the sandbox. With no path, CLI auto-writes stem-plot-n.svg and prints plot: …; view embeds the SVG under Execution.
|
||||
|
||||
diff / simplify / expand / partial subs return formula values so you can chain (e.g. differentiate twice, then plot or eval).
|
||||
|
||||
*`ty` = > type `f` *
|
||||
|
||||
> print text=`ty`
|
||||
|
||||
*`df` = > diff formula=`f` var=x *
|
||||
|
||||
> print text=`df`
|
||||
|
||||
*`roots` = > solve formula=`f` var=x *
|
||||
|
||||
> print text=`roots`
|
||||
|
||||
*`_svg` = > plot formula=`f` var=x min=-3 max=3 *
|
||||
|
||||
> print text=plot-ok
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
title: lib/net — HTTP
|
||||
description: Minimal HTTP client and URL encode
|
||||
> lib/net.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
Import lib/net.mq.md. Functions: http_get(url) returns map status/body, http_post(url, body), url_encode(text). v1 speaks cleartext http only.
|
||||
|
||||
*`e` = > url_encode text=hello world *
|
||||
|
||||
> print text=`e`
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
title: lib/sys — process
|
||||
description: Env, cwd, args, exit, exec
|
||||
> lib/sys.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
Import lib/sys.mq.md. Functions: env_get, env_set, args, cwd, exit(code), exec(cmd). Under view, exit soft-fails instead of killing the process.
|
||||
|
||||
*`d` = > cwd *
|
||||
|
||||
*`n` = > len `d` *
|
||||
|
||||
+ `n` > 0
|
||||
> print text=cwd-ok
|
||||
+ *
|
||||
> print text=cwd-empty
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
title: lib/table — lists
|
||||
description: Row count and index helpers
|
||||
> lib/table.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
Import lib/table.mq.md. Functions: rows(xs), row_at(xs, i). Single-column Markdown tables are lists at runtime.
|
||||
|
||||
`xs` =
|
||||
|
||||
| v |
|
||||
|---|
|
||||
| a |
|
||||
| b |
|
||||
|
||||
*`n` = > rows xs=`xs`*
|
||||
|
||||
> print text=`n`
|
||||
|
||||
*`r` = > row_at xs=`xs` i=0*
|
||||
|
||||
> print text=`r`
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
title: lib/text — strings
|
||||
description: Trim, split, join wrappers
|
||||
> lib/text.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
Import lib/text.mq.md. Functions: str_trim(s), str_split(s, sep), str_join(xs, sep).
|
||||
|
||||
*`t` = > str_trim s= marqdo *
|
||||
|
||||
> print text=`t`
|
||||
|
||||
*`parts` = > str_split s=a,b,c sep=,*
|
||||
|
||||
*`j` = > str_join xs=`parts` sep=-*
|
||||
|
||||
> print text=`j`
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
title: lib/time — clock
|
||||
description: Unix time, format, parse, sleep
|
||||
> lib/time.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
Import lib/time.mq.md. Functions: now_unix, now_ms, format(unix, pattern), parse(text, pattern), sleep_ms(ms). Patterns use strftime.
|
||||
|
||||
*`s` = > format unix=0 pattern=%Y-%m-%d *
|
||||
|
||||
> print text=`s`
|
||||
|
||||
*`u` = > parse text=1970-01-01 00:00:00 pattern=%Y-%m-%d %H:%M:%S *
|
||||
|
||||
> print text=`u`
|
||||
|
||||
> sleep_ms ms=0
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
title: lib/外联 — 外部语言
|
||||
description: 从 Marqdo 调用本机解释器(中文)
|
||||
> lib/外联.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
导入 lib/外联.mq.md。代码围栏与公式同构:空 RHS 赋值后跟 lang 代码块,得到 code 类型。用 运行 代码=`名` 调用本机解释器。
|
||||
|
||||
`hi` =
|
||||
```python
|
||||
print("hello-from-python")
|
||||
```
|
||||
|
||||
默认命令可用 设置命令 或 MARQDO_FOREIGN_PYTHON 覆盖;live view 里可改命令框再点 Run。
|
||||
|
||||
*`out` = > 运行 代码=`hi` *
|
||||
|
||||
> print text=`out`
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
title: lib/数学 — 数值、公式、作图
|
||||
description: 高中数学标准库(中文)
|
||||
> lib/数学.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
导入 lib/数学.mq.md。运行时类型:num(浮点)与 formula(符号树)。用空 RHS 赋值后跟 `$$…$$` 围栏绑定公式(与表格赋值同构)。view 的 Structure 会用 KaTeX 渲染该公式。
|
||||
|
||||
`f` =
|
||||
$$
|
||||
x^2 - 2
|
||||
$$
|
||||
|
||||
数值:圆周率、自然底数、数、加/减/乘/除/幂、正弦/余弦/正切、平方根/绝对值/对数/指数、向下取整/向上取整、最小/最大。随机:设种子、随机、随机整数。
|
||||
|
||||
符号:公式、化简、展开、求导、代入、求值、求解。
|
||||
|
||||
作图(库已提供):绘图 / 绘点列 / 绘圆锥,返回 SVG 文本。坐标轴带箭头与刻度;**默认显示网格**(`grid=假` 可关闭)。可选 path= 写盘。无 path 时 CLI 自动写 stem-plot-n.svg 并打印 plot: …;view 在 Execution 内嵌 SVG。
|
||||
|
||||
求导 / 化简 / 展开 / 未完全数值化的代入仍返回 formula,可继续链式调用(例如求二阶导后再绘图或求值)。
|
||||
|
||||
*`ty` = > type `f` *
|
||||
|
||||
> print text=`ty`
|
||||
|
||||
*`df` = > 求导 formula=`f` var=x *
|
||||
|
||||
> print text=`df`
|
||||
|
||||
*`roots` = > 求解 formula=`f` var=x *
|
||||
|
||||
> print text=`roots`
|
||||
|
||||
*`_svg` = > 绘图 formula=`f` var=x min=-3 max=3 *
|
||||
|
||||
> print text=plot-ok
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
title: lib/文件 — 文件系统
|
||||
description: 沙箱内读写文本
|
||||
> lib/文件.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
导入 lib/文件.mq.md。函数:读文本、写文本、追加文本、存在、列目录、建目录、删除。
|
||||
|
||||
裸路径字面量不要写斜杠(会被当成除法)。可用同目录文件名或变量。
|
||||
|
||||
*`ok` = > 存在 路径=demo.txt *
|
||||
|
||||
+ `ok`
|
||||
> 打印 内容=有演示文件
|
||||
+ *
|
||||
> 打印 内容=无演示文件
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
title: lib/文本 — 字符串
|
||||
description: 去空白、拆分、拼接
|
||||
> lib/文本.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
导入 lib/文本.mq.md。函数:去空白(s)、拆分(s, sep)、拼接(xs, sep)。
|
||||
|
||||
*`t` = > 去空白 s= marqdo *
|
||||
|
||||
> 打印 内容=`t`
|
||||
|
||||
*`parts` = > 拆分 s=甲,乙,丙 sep=,*
|
||||
|
||||
*`j` = > 拼接 xs=`parts` sep=-*
|
||||
|
||||
> 打印 内容=`j`
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
title: lib/时间 — 时钟
|
||||
description: Unix 时间、格式化、解析、睡眠
|
||||
> lib/时间.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
导入 lib/时间.mq.md。函数:此刻秒、此刻毫秒、格式化(秒, 格式)、解析时间(内容, 格式)、睡眠毫秒(毫秒)。格式为 strftime。
|
||||
|
||||
*`s` = > 格式化 秒=0 格式=%Y-%m-%d *
|
||||
|
||||
> 打印 内容=`s`
|
||||
|
||||
*`u` = > 解析时间 内容=1970-01-01 00:00:00 格式=%Y-%m-%d %H:%M:%S *
|
||||
|
||||
> 打印 内容=`u`
|
||||
|
||||
> 睡眠毫秒 毫秒=0
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
title: lib/系统 — 进程
|
||||
description: 环境变量、工作目录、参数、退出、执行
|
||||
> lib/系统.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
导入 lib/系统.mq.md。函数:取环境、设环境、参数表、工作目录、退出(码)、执行(命令)。view 下退出会软失败,不结束进程。
|
||||
|
||||
*`d` = > 工作目录 *
|
||||
|
||||
*`n` = > 长度 值=`d` *
|
||||
|
||||
+ `n` > 0
|
||||
> 打印 内容=工作目录就绪
|
||||
+ *
|
||||
> 打印 内容=工作目录空
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
title: lib/网络 — HTTP
|
||||
description: 简易 HTTP 与地址编码
|
||||
> lib/网络.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
导入 lib/网络.mq.md。函数:获取(地址) 返回 map status/body、提交(地址, 内容)、编码地址(内容)。本波仅明文 http。
|
||||
|
||||
*`e` = > 编码地址 内容=你好 *
|
||||
|
||||
> 打印 内容=`e`
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
title: lib/表 — 列表
|
||||
description: 行数与取行
|
||||
> lib/表.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
导入 lib/表.mq.md。函数:行数(xs)、取行(xs, i)。单列表在运行时是列表。
|
||||
|
||||
`xs` =
|
||||
|
||||
| v |
|
||||
|---|
|
||||
| 甲 |
|
||||
| 乙 |
|
||||
|
||||
*`n` = > 行数 xs=`xs`*
|
||||
|
||||
> 打印 内容=`n`
|
||||
|
||||
*`r` = > 取行 xs=`xs` i=0*
|
||||
|
||||
> 打印 内容=`r`
|
||||
@@ -1,12 +1,12 @@
|
||||
---
|
||||
title: Hello World
|
||||
description: 最简单的可执行文档
|
||||
description: Smallest runnable doc
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
普通段落是注释。print 是内置函数,不是语法架构。
|
||||
Ordinary paragraphs are comments. `print` is a built-in, not a syntax marker.
|
||||
|
||||
注释里的粗体与斜体标记若出现在行首会被当成代码,所以叙述行请用普通文字开头。
|
||||
Lines that start with Markdown emphasis markers can be treated as code — keep narrative as plain prose.
|
||||
|
||||
> print text=Hello World!
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
title: 你好世界
|
||||
description: 最小可运行文档
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
普通段落是注释。`打印` 是内置函数,不是语法标记。
|
||||
|
||||
以 Markdown 强调标记开头的行可当作代码——叙述请用普通段落。
|
||||
|
||||
> 打印 内容=你好世界!
|
||||
@@ -1,17 +1,17 @@
|
||||
---
|
||||
title: 函数与具名调用
|
||||
description: `#` 定义函数,`>` 调用;`-` 下列纯名为形参
|
||||
title: Functions and named calls
|
||||
description: `#` defines functions; `>` calls; `-` lists parameter names
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
用 `#` / `##` 定义函数。形参写在函数头下方的 `-` 纯名行。
|
||||
Use `#` / `##` for functions. Parameters are bare `- name` lines under the heading.
|
||||
|
||||
调用用 `>`:具名实参写作 `形参=值`。
|
||||
Call with `>` and named args `param=value`:
|
||||
|
||||
> 问候 谁=World
|
||||
> greet who=World
|
||||
|
||||
## 问候
|
||||
- 谁
|
||||
## greet
|
||||
- who
|
||||
|
||||
> print text=Hello `谁`!
|
||||
> print text=Hello `who`!
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
title: 函数与具名调用
|
||||
description: `#` 定义函数;`>` 调用;`-` 列出参数名
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
用 `#` / `##` 定义函数。参数是标题下的裸 `- 名` 行。
|
||||
|
||||
用 `>` 与具名实参 `参数=值` 调用:
|
||||
|
||||
> 问候 谁=世界
|
||||
|
||||
## 问候
|
||||
- 谁
|
||||
|
||||
> 打印 内容=你好 `谁`!
|
||||
@@ -1,19 +1,19 @@
|
||||
---
|
||||
title: 位置实参
|
||||
description: 按形参顺序传参;也可继续用具名
|
||||
title: Positional arguments
|
||||
description: Bind by parameter order; named form still works
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
位置实参:按形参声明顺序绑定,不必写 `谁=`。
|
||||
Positional args bind in declaration order (no `who=` needed):
|
||||
|
||||
> 问候 Marqdo
|
||||
> greet Marqdo
|
||||
|
||||
具名形式仍然可用:
|
||||
Named form still works:
|
||||
|
||||
> 问候 谁=World
|
||||
> greet who=World
|
||||
|
||||
## 问候
|
||||
- 谁
|
||||
## greet
|
||||
- who
|
||||
|
||||
> print text=Hello `谁`!
|
||||
> print text=Hello `who`!
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
title: 位置实参
|
||||
description: 按参数声明顺序绑定;具名写法仍然可用
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
位置实参按声明顺序绑定(不必写 `谁=`):
|
||||
|
||||
> 问候 Marqdo
|
||||
|
||||
具名写法仍然可用:
|
||||
|
||||
> 问候 谁=世界
|
||||
|
||||
## 问候
|
||||
- 谁
|
||||
|
||||
> 打印 内容=你好 `谁`!
|
||||
@@ -1,17 +1,17 @@
|
||||
---
|
||||
title: 分支
|
||||
description: `+` 臂;整行 `*` 为 else
|
||||
title: Branch
|
||||
description: `+` arms; a lone `*` arm is else
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
斜体行是程序语句。分支用 `+`;臂头单独一行 `*` 表示 else。
|
||||
Italic lines are statements. Branches use `+`; a head that is only `*` is the else arm.
|
||||
|
||||
*`x` = 0*
|
||||
|
||||
+ `x` > 0
|
||||
> print text=正数
|
||||
> print text=positive
|
||||
+ `x` < 0
|
||||
> print text=负数
|
||||
> print text=negative
|
||||
+ *
|
||||
> print text=零
|
||||
> print text=zero
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
title: 分支
|
||||
description: `+` 各臂;单独的 `*` 臂为否则
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
斜体行是语句。分支用 `+`;表头仅为 `*` 的是否则臂。
|
||||
|
||||
*`x` = 0*
|
||||
|
||||
+ `x` > 0
|
||||
> 打印 内容=正数
|
||||
+ `x` < 0
|
||||
> 打印 内容=负数
|
||||
+ *
|
||||
> 打印 内容=零
|
||||
@@ -1,13 +1,13 @@
|
||||
---
|
||||
title: 循环
|
||||
description: 条件循环与表格遍历
|
||||
title: Loops
|
||||
description: Condition loops and table walks
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
函数体内的 `-` 是循环(不是形参)。
|
||||
Inside a function body, `-` starts a loop (not a parameter).
|
||||
|
||||
倒数:
|
||||
Countdown:
|
||||
|
||||
*`n` = 3*
|
||||
|
||||
@@ -15,14 +15,14 @@ description: 条件循环与表格遍历
|
||||
> print text=`n`
|
||||
*`n` = `n` - 1*
|
||||
|
||||
遍历篮子(表格是集合):
|
||||
Walk a table (tables are collections):
|
||||
|
||||
`篮子` =
|
||||
`basket` =
|
||||
|
||||
| 果 |
|
||||
|----|
|
||||
| 苹果 |
|
||||
| 梨 |
|
||||
| fruit |
|
||||
|-------|
|
||||
| apple |
|
||||
| pear |
|
||||
|
||||
- [果](篮子)
|
||||
> print text=今天吃`果`
|
||||
- [fruit](basket)
|
||||
> print text=today `fruit`
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
title: 循环
|
||||
description: 条件循环与表遍历
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
在函数体里,`-` 表示循环(不是参数)。
|
||||
|
||||
倒数:
|
||||
|
||||
*`n` = 3*
|
||||
|
||||
- `n` > 0
|
||||
> 打印 内容=`n`
|
||||
*`n` = `n` - 1*
|
||||
|
||||
遍历表(表即集合):
|
||||
|
||||
`篮子` =
|
||||
|
||||
| 水果 |
|
||||
|------|
|
||||
| 苹果 |
|
||||
| 梨 |
|
||||
|
||||
- [水果](篮子)
|
||||
> 打印 内容=今天 `水果`
|
||||
@@ -1,19 +1,19 @@
|
||||
---
|
||||
title: 集合(表格)
|
||||
description: GFM 表格即集合
|
||||
title: Collections (tables)
|
||||
description: GFM tables are collections
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
Markdown 表格在 Marqdo 里就是集合,可用循环逐行取出。
|
||||
A Markdown table is a collection; loop to read each row.
|
||||
|
||||
`篮子` =
|
||||
`basket` =
|
||||
|
||||
| 果 |
|
||||
|----|
|
||||
| 苹果 |
|
||||
| 梨 |
|
||||
| 桃 |
|
||||
| fruit |
|
||||
|-------|
|
||||
| apple |
|
||||
| pear |
|
||||
| peach |
|
||||
|
||||
- [果](篮子)
|
||||
> print text=`果`
|
||||
- [fruit](basket)
|
||||
> print text=`fruit`
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
title: 集合(表)
|
||||
description: GFM 表格即集合
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
Markdown 表是集合;用循环读每一行。
|
||||
|
||||
`篮子` =
|
||||
|
||||
| 水果 |
|
||||
|------|
|
||||
| 苹果 |
|
||||
| 梨 |
|
||||
| 桃 |
|
||||
|
||||
- [水果](篮子)
|
||||
> 打印 内容=`水果`
|
||||
@@ -1,17 +1,17 @@
|
||||
---
|
||||
title: 跨文件导入
|
||||
description: frontmatter 中 `> 文件.mq.md` 导入模块
|
||||
title: Cross-file import
|
||||
description: Frontmatter `> file.mq.md` merges modules
|
||||
> utils.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
文件头 YAML 里写 `> utils.mq.md` 即可导入同目录模块。
|
||||
In the YAML header, `> utils.mq.md` imports a sibling module.
|
||||
|
||||
导入后:用返回值绑定,再输出;并直接调用问候。
|
||||
Bind a return value, print it, then call greet:
|
||||
|
||||
*`y` = > 加一 n=41*
|
||||
*`y` = > add_one n=41*
|
||||
|
||||
> print text=`y`
|
||||
|
||||
> 问候 谁=Marqdo
|
||||
> greet who=Marqdo
|
||||
@@ -1,14 +1,14 @@
|
||||
---
|
||||
title: 工具模块
|
||||
description: 被 main 导入;粗体是返回值
|
||||
title: Utility module
|
||||
description: Imported by main; bold is a return value
|
||||
---
|
||||
|
||||
# 加一
|
||||
# add_one
|
||||
- n
|
||||
|
||||
**`n` + 1**
|
||||
|
||||
# 问候
|
||||
- 谁
|
||||
# greet
|
||||
- who
|
||||
|
||||
> print text=你好,`谁`!
|
||||
> print text=Hello, `who`!
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
title: 跨文件导入
|
||||
description: frontmatter 中 `> 文件.mq.md` 合并模块
|
||||
> 工具.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
在 YAML 头里写 `> 工具.mq.md` 可导入同级模块。
|
||||
|
||||
绑定返回值、打印,再调用问候:
|
||||
|
||||
*`y` = > 加一 n=41*
|
||||
|
||||
> 打印 内容=`y`
|
||||
|
||||
> 问候 谁=Marqdo
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
title: 工具模块
|
||||
description: 被 main 导入;粗体为返回值
|
||||
---
|
||||
|
||||
# 加一
|
||||
- n
|
||||
|
||||
**`n` + 1**
|
||||
|
||||
# 问候
|
||||
- 谁
|
||||
|
||||
> 打印 内容=你好,`谁`!
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
//! Canonical names and Chinese aliases for L0 keywords / builtins / params.
|
||||
//!
|
||||
//! See `doc/design/keywords-i18n.md`. No language mode — aliases are equivalent.
|
||||
|
||||
/// Map a literal / logic keyword to its English canonical form, if reserved.
|
||||
pub fn canonical_keyword(name: &str) -> Option<&'static str> {
|
||||
match name {
|
||||
"True" | "真" => Some("True"),
|
||||
"False" | "假" => Some("False"),
|
||||
"None" | "空" => Some("None"),
|
||||
"and" | "且" => Some("and"),
|
||||
"or" | "或" => Some("or"),
|
||||
"not" | "非" => Some("not"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_reserved_keyword(name: &str) -> bool {
|
||||
canonical_keyword(name).is_some()
|
||||
}
|
||||
|
||||
/// Map a builtin callee (EN or ZH alias) to its English canonical name.
|
||||
/// Host primitives without ZH L0 aliases only match English.
|
||||
pub fn canonical_builtin(name: &str) -> Option<&'static str> {
|
||||
if let Some(h) = crate::host::HostFn::from_name(name) {
|
||||
return Some(h.name());
|
||||
}
|
||||
match name {
|
||||
"print" | "打印" => Some("print"),
|
||||
"input" | "输入" => Some("input"),
|
||||
"len" | "长度" => Some("len"),
|
||||
"str" | "文本" => Some("str"),
|
||||
"int" | "整数" => Some("int"),
|
||||
"type" => Some("type"),
|
||||
"trim" => Some("trim"),
|
||||
"split" => Some("split"),
|
||||
"join" => Some("join"),
|
||||
"at" => Some("at"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalize a named-argument key for a builtin to the English param name.
|
||||
pub fn canonical_param(builtin: &str, param: &str) -> String {
|
||||
let b = canonical_builtin(builtin).unwrap_or(builtin);
|
||||
match (b, param) {
|
||||
("print", "text" | "内容") => "text".into(),
|
||||
("input", "prompt" | "提示") => "prompt".into(),
|
||||
("len" | "str" | "int" | "type" | "trim", "value" | "值") => "value".into(),
|
||||
("split" | "join", "value" | "值") => "value".into(),
|
||||
("split" | "join", "sep" | "分隔") => "sep".into(),
|
||||
("at", "value" | "值") => "value".into(),
|
||||
("at", "index" | "下标") => "index".into(),
|
||||
(
|
||||
"host_plot" | "host_plot_points" | "host_plot_conic",
|
||||
"grid" | "网格",
|
||||
) => "grid".into(),
|
||||
("host_plot" | "host_plot_points" | "host_plot_conic", "path" | "路径") => {
|
||||
"path".into()
|
||||
}
|
||||
("host_plot", "steps" | "步数") => "steps".into(),
|
||||
("host_plot", "derivative" | "导数") => "derivative".into(),
|
||||
("host_foreign_run", "code" | "代码") => "code".into(),
|
||||
("host_foreign_run" | "host_foreign_run_lang", "stdin" | "标准输入") => "stdin".into(),
|
||||
("host_foreign_set_cmd" | "host_foreign_run_lang", "lang" | "语言") => "lang".into(),
|
||||
("host_foreign_set_cmd", "cmd" | "命令") => "cmd".into(),
|
||||
("host_foreign_run_lang", "source" | "源码") => "source".into(),
|
||||
_ => param.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rewrite callee + named args to English canonical forms when this is a builtin.
|
||||
/// Returns the callee to dispatch on (canonical builtin or original user/fn name).
|
||||
pub fn normalize_call_callee_and_args(callee: &str, args: &mut [crate::ast::Arg]) -> String {
|
||||
match canonical_builtin(callee) {
|
||||
Some(canon) => {
|
||||
for a in args.iter_mut() {
|
||||
if let crate::ast::Arg::Named { name, .. } = a {
|
||||
*name = canonical_param(canon, name);
|
||||
}
|
||||
}
|
||||
canon.to_string()
|
||||
}
|
||||
None => callee.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn keyword_aliases() {
|
||||
assert_eq!(canonical_keyword("真"), Some("True"));
|
||||
assert_eq!(canonical_keyword("且"), Some("and"));
|
||||
assert!(is_reserved_keyword("空"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_aliases() {
|
||||
assert_eq!(canonical_builtin("打印"), Some("print"));
|
||||
assert_eq!(canonical_builtin("长度"), Some("len"));
|
||||
assert_eq!(canonical_param("打印", "内容"), "text");
|
||||
assert_eq!(canonical_param("print", "内容"), "text");
|
||||
}
|
||||
}
|
||||
+17
-2
@@ -1,6 +1,8 @@
|
||||
//! Marqdo AST (Phase I).
|
||||
|
||||
use crate::diagnostics::Span;
|
||||
use crate::formula::Expr as FormulaExpr;
|
||||
use crate::value::CodeBlock;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Module {
|
||||
@@ -24,6 +26,8 @@ pub enum Stmt {
|
||||
name: String,
|
||||
value: Expr,
|
||||
span: Span,
|
||||
/// Inclusive last source line (covers following `$$` fence or table rows).
|
||||
end_line: u32,
|
||||
},
|
||||
Return {
|
||||
value: Expr,
|
||||
@@ -86,6 +90,10 @@ pub enum Expr {
|
||||
},
|
||||
Call(CallExpr),
|
||||
List(Vec<Expr>),
|
||||
/// Parsed `$$…$$` formula tree (from assignment RHS).
|
||||
Formula(FormulaExpr),
|
||||
/// Bound ```lang … ``` fence (`code` value).
|
||||
Code(CodeBlock),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -156,8 +164,15 @@ fn dump_fun(out: &mut String, fun: &Function, depth: usize) {
|
||||
fn dump_stmt(out: &mut String, stmt: &Stmt, depth: usize) {
|
||||
let pad = " ".repeat(depth);
|
||||
match stmt {
|
||||
Stmt::Assign { name, value, span } => {
|
||||
out.push_str(&format!("{pad}(assign {name:?} {value:?} @{span})\n"));
|
||||
Stmt::Assign {
|
||||
name,
|
||||
value,
|
||||
span,
|
||||
end_line,
|
||||
} => {
|
||||
out.push_str(&format!(
|
||||
"{pad}(assign {name:?} {value:?} @{span}..{end_line})\n"
|
||||
));
|
||||
}
|
||||
Stmt::Return { value, span } => {
|
||||
out.push_str(&format!("{pad}(return {value:?} @{span})\n"));
|
||||
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
//! Built-in helpers shared by tree-walk and bytecode.
|
||||
|
||||
use crate::value::Value;
|
||||
|
||||
/// `len`: text → Unicode scalar count; list → element count.
|
||||
pub fn builtin_len(v: &Value) -> Result<i64, String> {
|
||||
match v {
|
||||
Value::Text(s) => Ok(s.chars().count() as i64),
|
||||
Value::List(xs) => Ok(xs.len() as i64),
|
||||
_ => Err("len needs text or list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `str`: display conversion (same surface as `print`).
|
||||
pub fn builtin_str(v: &Value) -> Value {
|
||||
Value::Text(v.as_display())
|
||||
}
|
||||
|
||||
/// `int`: Int passthrough; Bool → 0/1; Text → parse trimmed decimal.
|
||||
pub fn builtin_int(v: &Value) -> Result<i64, String> {
|
||||
match v {
|
||||
Value::Int(n) => Ok(*n),
|
||||
Value::Num(n) => Ok(*n as i64),
|
||||
Value::Bool(true) => Ok(1),
|
||||
Value::Bool(false) => Ok(0),
|
||||
Value::Text(s) => {
|
||||
let t = s.trim();
|
||||
t.parse::<i64>()
|
||||
.map_err(|_| format!("cannot convert to int: {s:?}"))
|
||||
}
|
||||
_ => Err("int needs int, num, bool, or text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `type`: type tag as text (`none` / `bool` / `int` / `num` / `text` / `list` / `map` / `formula`).
|
||||
pub fn builtin_type(v: &Value) -> Value {
|
||||
Value::Text(
|
||||
match v {
|
||||
Value::None => "none",
|
||||
Value::Bool(_) => "bool",
|
||||
Value::Int(_) => "int",
|
||||
Value::Num(_) => "num",
|
||||
Value::Text(_) => "text",
|
||||
Value::List(_) => "list",
|
||||
Value::Map(_) => "map",
|
||||
Value::Formula(_) => "formula",
|
||||
Value::Code(_) => "code",
|
||||
}
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
|
||||
/// `trim`: strip leading/trailing Unicode whitespace from text.
|
||||
pub fn builtin_trim(v: &Value) -> Result<Value, String> {
|
||||
match v {
|
||||
Value::Text(s) => Ok(Value::Text(s.trim().to_string())),
|
||||
_ => Err("trim needs text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `split`: split text by separator → list of text parts.
|
||||
pub fn builtin_split(value: &Value, sep: &Value) -> Result<Value, String> {
|
||||
let text = match value {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("split needs text value".into()),
|
||||
};
|
||||
let sep = match sep {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("split needs text sep".into()),
|
||||
};
|
||||
if sep.is_empty() {
|
||||
return Err("split sep must not be empty".into());
|
||||
}
|
||||
let parts: Vec<Value> = text
|
||||
.split(sep)
|
||||
.map(|p| Value::Text(p.to_string()))
|
||||
.collect();
|
||||
Ok(Value::List(parts))
|
||||
}
|
||||
|
||||
/// `join`: join list elements with separator → text.
|
||||
pub fn builtin_join(value: &Value, sep: &Value) -> Result<Value, String> {
|
||||
let items = match value {
|
||||
Value::List(xs) => xs,
|
||||
_ => return Err("join needs list value".into()),
|
||||
};
|
||||
let sep = match sep {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("join needs text sep".into()),
|
||||
};
|
||||
let mut out = String::new();
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push_str(sep);
|
||||
}
|
||||
out.push_str(&item.as_display());
|
||||
}
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
/// `at`: list element at index (0-based); out of range → None.
|
||||
pub fn builtin_at(value: &Value, index: &Value) -> Result<Value, String> {
|
||||
let xs = match value {
|
||||
Value::List(xs) => xs,
|
||||
_ => return Err("at needs list value".into()),
|
||||
};
|
||||
let i = match index {
|
||||
Value::Int(n) => *n,
|
||||
_ => return Err("at needs int index".into()),
|
||||
};
|
||||
if i < 0 || (i as usize) >= xs.len() {
|
||||
return Ok(Value::None);
|
||||
}
|
||||
Ok(xs[i as usize].clone())
|
||||
}
|
||||
+217
-19
@@ -2,11 +2,13 @@
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::ast::{
|
||||
Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Stmt, UnaryOp,
|
||||
};
|
||||
use crate::bytecode::{FnChunk, Op, Program};
|
||||
use crate::diagnostics::{bail_at, Span};
|
||||
use crate::value::Value;
|
||||
|
||||
struct FlatFun {
|
||||
@@ -15,9 +17,10 @@ struct FlatFun {
|
||||
params: Vec<String>,
|
||||
body: Vec<Stmt>,
|
||||
children: Vec<usize>,
|
||||
span: Span,
|
||||
}
|
||||
|
||||
pub fn compile_module(module: &Module) -> Result<Program> {
|
||||
pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
|
||||
let mut flat = Vec::new();
|
||||
for fun in &module.functions {
|
||||
collect_fun(fun, None, &mut flat);
|
||||
@@ -35,9 +38,10 @@ pub fn compile_module(module: &Module) -> Result<Program> {
|
||||
})
|
||||
.ok_or_else(|| anyhow::anyhow!("bytecode: no entry function"))?;
|
||||
|
||||
let path_buf = path.map(|p| p.to_path_buf());
|
||||
let mut functions = Vec::new();
|
||||
for i in 0..flat.len() {
|
||||
functions.push(compile_function(i, &flat)?);
|
||||
functions.push(compile_function(i, &flat, path_buf.as_deref())?);
|
||||
}
|
||||
|
||||
Ok(Program { functions, entry })
|
||||
@@ -51,6 +55,7 @@ fn collect_fun(fun: &Function, parent: Option<usize>, flat: &mut Vec<FlatFun>) -
|
||||
params: fun.params.clone(),
|
||||
body: fun.body.clone(),
|
||||
children: Vec::new(),
|
||||
span: fun.span,
|
||||
});
|
||||
let mut child_ids = Vec::new();
|
||||
for child in &fun.children {
|
||||
@@ -61,33 +66,39 @@ fn collect_fun(fun: &Function, parent: Option<usize>, flat: &mut Vec<FlatFun>) -
|
||||
}
|
||||
|
||||
struct FnCompiler<'a> {
|
||||
path: Option<&'a Path>,
|
||||
flat: &'a [FlatFun],
|
||||
fn_id: usize,
|
||||
chunk: FnChunk,
|
||||
locals: HashMap<String, u8>,
|
||||
stmt_span: Span,
|
||||
}
|
||||
|
||||
fn compile_function(fn_id: usize, flat: &[FlatFun]) -> Result<FnChunk> {
|
||||
fn compile_function(fn_id: usize, flat: &[FlatFun], path: Option<&Path>) -> Result<FnChunk> {
|
||||
let fun = &flat[fn_id];
|
||||
let mut locals = HashMap::new();
|
||||
for (i, p) in fun.params.iter().enumerate() {
|
||||
locals.insert(p.clone(), i as u8);
|
||||
}
|
||||
let mut c = FnCompiler {
|
||||
path,
|
||||
flat,
|
||||
fn_id,
|
||||
chunk: FnChunk {
|
||||
name: fun.name.clone(),
|
||||
params: fun.params.clone(),
|
||||
code: Vec::new(),
|
||||
spans: Vec::new(),
|
||||
constants: Vec::new(),
|
||||
locals: fun.params.clone(),
|
||||
},
|
||||
locals,
|
||||
stmt_span: fun.span,
|
||||
};
|
||||
for stmt in &fun.body {
|
||||
c.compile_stmt(stmt)?;
|
||||
}
|
||||
c.stmt_span = fun.span;
|
||||
c.emit(Op::None_);
|
||||
c.emit(Op::Return);
|
||||
let mut names = vec![String::new(); c.locals.len()];
|
||||
@@ -95,12 +106,52 @@ fn compile_function(fn_id: usize, flat: &[FlatFun]) -> Result<FnChunk> {
|
||||
names[*slot as usize] = name.clone();
|
||||
}
|
||||
c.chunk.locals = names;
|
||||
debug_assert_eq!(c.chunk.code.len(), c.chunk.spans.len());
|
||||
Ok(c.chunk)
|
||||
}
|
||||
|
||||
impl<'a> FnCompiler<'a> {
|
||||
fn err(&self, message: impl Into<String>) -> anyhow::Error {
|
||||
bail_at(self.path, self.stmt_span, message)
|
||||
}
|
||||
|
||||
fn emit(&mut self, op: Op) {
|
||||
self.chunk.code.push(op);
|
||||
self.chunk.spans.push(self.stmt_span);
|
||||
}
|
||||
|
||||
fn named_or_first<'b>(&self, call: &'b CallExpr, name: &str) -> Option<&'b Expr> {
|
||||
call.args
|
||||
.iter()
|
||||
.find_map(|a| match a {
|
||||
Arg::Named { name: n, value } if n == name => Some(value),
|
||||
_ => None,
|
||||
})
|
||||
.or_else(|| {
|
||||
call.args.iter().find_map(|a| match a {
|
||||
Arg::Positional(e) => Some(e),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn named_or_pos<'b>(&self, call: &'b CallExpr, name: &str, pos: usize) -> Option<&'b Expr> {
|
||||
if let Some(e) = call.args.iter().find_map(|a| match a {
|
||||
Arg::Named { name: n, value } if n == name => Some(value),
|
||||
_ => None,
|
||||
}) {
|
||||
return Some(e);
|
||||
}
|
||||
let mut i = 0usize;
|
||||
for a in &call.args {
|
||||
if let Arg::Positional(e) = a {
|
||||
if i == pos {
|
||||
return Some(e);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn here(&self) -> u16 {
|
||||
@@ -150,23 +201,29 @@ impl<'a> FnCompiler<'a> {
|
||||
return Ok(i);
|
||||
}
|
||||
}
|
||||
bail!("bytecode: unknown function `{name}`")
|
||||
Err(self.err(format!("unknown function `{name}`")))
|
||||
}
|
||||
|
||||
fn compile_stmt(&mut self, stmt: &Stmt) -> Result<()> {
|
||||
match stmt {
|
||||
Stmt::Assign { name, value, .. } => {
|
||||
Stmt::Assign { name, value, span, .. } => {
|
||||
self.stmt_span = *span;
|
||||
self.compile_expr(value)?;
|
||||
let slot = self.local_slot(name);
|
||||
self.emit(Op::SetLocal(slot));
|
||||
self.emit(Op::Pop);
|
||||
}
|
||||
Stmt::Return { value, .. } => {
|
||||
Stmt::Return { value, span } => {
|
||||
self.stmt_span = *span;
|
||||
self.compile_expr(value)?;
|
||||
self.emit(Op::Return);
|
||||
}
|
||||
Stmt::Call { call, .. } => self.compile_call(call, true)?,
|
||||
Stmt::Branch { arms, .. } => {
|
||||
Stmt::Call { call, span } => {
|
||||
self.stmt_span = *span;
|
||||
self.compile_call(call, true)?;
|
||||
}
|
||||
Stmt::Branch { arms, span } => {
|
||||
self.stmt_span = *span;
|
||||
let mut end_jumps = Vec::new();
|
||||
for (i, arm) in arms.iter().enumerate() {
|
||||
let is_last = i + 1 == arms.len();
|
||||
@@ -180,6 +237,7 @@ impl<'a> FnCompiler<'a> {
|
||||
for st in &arm.body {
|
||||
self.compile_stmt(st)?;
|
||||
}
|
||||
self.stmt_span = *span;
|
||||
if !is_last {
|
||||
let j = self.here();
|
||||
self.emit(Op::Jump(0));
|
||||
@@ -195,8 +253,11 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
}
|
||||
Stmt::While {
|
||||
condition, body, ..
|
||||
condition,
|
||||
body,
|
||||
span,
|
||||
} => {
|
||||
self.stmt_span = *span;
|
||||
let loop_start = self.here();
|
||||
self.compile_expr(condition)?;
|
||||
let exit_j = self.here();
|
||||
@@ -204,6 +265,7 @@ impl<'a> FnCompiler<'a> {
|
||||
for st in body {
|
||||
self.compile_stmt(st)?;
|
||||
}
|
||||
self.stmt_span = *span;
|
||||
self.emit(Op::Jump(loop_start));
|
||||
self.patch(exit_j, Op::JumpIfFalse(self.here()));
|
||||
}
|
||||
@@ -211,8 +273,9 @@ impl<'a> FnCompiler<'a> {
|
||||
item,
|
||||
collection,
|
||||
body,
|
||||
..
|
||||
span,
|
||||
} => {
|
||||
self.stmt_span = *span;
|
||||
self.compile_expr(&Expr::Var(collection.clone()))?;
|
||||
let coll_slot = self.local_slot(&format!("__coll_{collection}"));
|
||||
self.emit(Op::SetLocal(coll_slot));
|
||||
@@ -242,6 +305,7 @@ impl<'a> FnCompiler<'a> {
|
||||
self.compile_stmt(st)?;
|
||||
}
|
||||
|
||||
self.stmt_span = *span;
|
||||
self.emit(Op::GetLocal(i_slot));
|
||||
let one = self.add_const(Value::Int(1));
|
||||
self.emit(Op::Constant(one));
|
||||
@@ -256,6 +320,10 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
|
||||
fn compile_call(&mut self, call: &CallExpr, as_stmt: bool) -> Result<()> {
|
||||
let mut call = call.clone();
|
||||
call.callee =
|
||||
crate::aliases::normalize_call_callee_and_args(&call.callee, &mut call.args);
|
||||
|
||||
match call.callee.as_str() {
|
||||
"print" => {
|
||||
let text_expr = call
|
||||
@@ -271,7 +339,7 @@ impl<'a> FnCompiler<'a> {
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
.ok_or_else(|| anyhow::anyhow!("bytecode: print needs text"))?;
|
||||
.ok_or_else(|| self.err("print requires text (named or positional)"))?;
|
||||
self.compile_expr(text_expr)?;
|
||||
self.emit(Op::Print);
|
||||
if !as_stmt {
|
||||
@@ -279,7 +347,125 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
"input" => bail!("bytecode: input not supported"),
|
||||
"input" => {
|
||||
let prompt_expr = call
|
||||
.args
|
||||
.iter()
|
||||
.find_map(|a| match a {
|
||||
Arg::Named { name, value } if name == "prompt" => Some(value),
|
||||
_ => None,
|
||||
})
|
||||
.or_else(|| {
|
||||
call.args.iter().find_map(|a| match a {
|
||||
Arg::Positional(e) => Some(e),
|
||||
_ => None,
|
||||
})
|
||||
});
|
||||
if let Some(e) = prompt_expr {
|
||||
self.compile_expr(e)?;
|
||||
} else {
|
||||
let i = self.add_const(Value::Text(String::new()));
|
||||
self.emit(Op::Constant(i));
|
||||
}
|
||||
self.emit(Op::Input);
|
||||
if as_stmt {
|
||||
self.emit(Op::Pop);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
"len" | "str" | "int" | "type" | "trim" => {
|
||||
let name = call.callee.as_str();
|
||||
let value_expr = self
|
||||
.named_or_first(&call, "value")
|
||||
.ok_or_else(|| self.err(format!("{name} requires value")))?;
|
||||
self.compile_expr(value_expr)?;
|
||||
self.emit(match name {
|
||||
"len" => Op::Len,
|
||||
"str" => Op::Str,
|
||||
"int" => Op::Int,
|
||||
"type" => Op::TypeOf,
|
||||
"trim" => Op::Trim,
|
||||
_ => unreachable!(),
|
||||
});
|
||||
if as_stmt {
|
||||
self.emit(Op::Pop);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
"split" | "join" => {
|
||||
let name = call.callee.as_str();
|
||||
let value_expr = self
|
||||
.named_or_pos(&call, "value", 0)
|
||||
.ok_or_else(|| self.err(format!("{name} requires value")))?;
|
||||
let sep_expr = self
|
||||
.named_or_pos(&call, "sep", 1)
|
||||
.ok_or_else(|| self.err(format!("{name} requires sep")))?;
|
||||
self.compile_expr(value_expr)?;
|
||||
self.compile_expr(sep_expr)?;
|
||||
self.emit(match name {
|
||||
"split" => Op::Split,
|
||||
"join" => Op::Join,
|
||||
_ => unreachable!(),
|
||||
});
|
||||
if as_stmt {
|
||||
self.emit(Op::Pop);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
"at" => {
|
||||
let value_expr = self
|
||||
.named_or_pos(&call, "value", 0)
|
||||
.ok_or_else(|| self.err("at requires value"))?;
|
||||
let index_expr = self
|
||||
.named_or_pos(&call, "index", 1)
|
||||
.ok_or_else(|| self.err("at requires index"))?;
|
||||
self.compile_expr(value_expr)?;
|
||||
self.compile_expr(index_expr)?;
|
||||
self.emit(Op::GetIndex);
|
||||
if as_stmt {
|
||||
self.emit(Op::Pop);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
other if crate::host::HostFn::from_name(other).is_some() => {
|
||||
let hf = crate::host::HostFn::from_name(other).unwrap();
|
||||
let params = hf.all_params();
|
||||
let mut named: HashMap<String, &Expr> = HashMap::new();
|
||||
let mut positionals = Vec::new();
|
||||
for a in &call.args {
|
||||
match a {
|
||||
Arg::Positional(e) => positionals.push(e),
|
||||
Arg::Named { name, value } => {
|
||||
named.insert(name.clone(), value);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut pos_i = 0usize;
|
||||
let required_n = hf.required_params().len();
|
||||
for (i, p) in params.iter().enumerate() {
|
||||
if let Some(e) = named.get(*p) {
|
||||
self.compile_expr(e)?;
|
||||
} else if pos_i < positionals.len() {
|
||||
self.compile_expr(positionals[pos_i])?;
|
||||
pos_i += 1;
|
||||
} else if i < required_n {
|
||||
return Err(self.err(format!("{} requires `{p}`", hf.name())));
|
||||
} else {
|
||||
self.emit(Op::None_);
|
||||
}
|
||||
}
|
||||
if pos_i < positionals.len() {
|
||||
return Err(self.err(format!(
|
||||
"too many positional arguments ({} extra)",
|
||||
positionals.len() - pos_i
|
||||
)));
|
||||
}
|
||||
self.emit(Op::HostCall(hf.as_u16(), params.len() as u8));
|
||||
if as_stmt {
|
||||
self.emit(Op::Pop);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -303,11 +489,14 @@ impl<'a> FnCompiler<'a> {
|
||||
self.compile_expr(positionals[pos_i])?;
|
||||
pos_i += 1;
|
||||
} else {
|
||||
bail!("bytecode: missing argument for parameter `{p}`");
|
||||
return Err(self.err(format!("missing argument for parameter `{p}`")));
|
||||
}
|
||||
}
|
||||
if pos_i < positionals.len() {
|
||||
bail!("bytecode: too many positional arguments");
|
||||
return Err(self.err(format!(
|
||||
"too many positional arguments ({} extra)",
|
||||
positionals.len() - pos_i
|
||||
)));
|
||||
}
|
||||
self.emit(Op::Call(fid as u16, params.len() as u8));
|
||||
if as_stmt {
|
||||
@@ -336,7 +525,7 @@ impl<'a> FnCompiler<'a> {
|
||||
.locals
|
||||
.get(name)
|
||||
.copied()
|
||||
.ok_or_else(|| anyhow::anyhow!("bytecode: undefined variable `{name}`"))?;
|
||||
.ok_or_else(|| self.err(format!("undefined variable `{name}`")))?;
|
||||
self.emit(Op::GetLocal(slot));
|
||||
}
|
||||
Expr::Interp(parts) => {
|
||||
@@ -352,9 +541,11 @@ impl<'a> FnCompiler<'a> {
|
||||
self.emit(Op::Constant(i));
|
||||
}
|
||||
InterpPart::Var(n) => {
|
||||
let slot = self.locals.get(n).copied().ok_or_else(|| {
|
||||
anyhow::anyhow!("bytecode: undefined variable `{n}`")
|
||||
})?;
|
||||
let slot = self
|
||||
.locals
|
||||
.get(n)
|
||||
.copied()
|
||||
.ok_or_else(|| self.err(format!("undefined variable `{n}`")))?;
|
||||
self.emit(Op::GetLocal(slot));
|
||||
}
|
||||
}
|
||||
@@ -375,7 +566,6 @@ impl<'a> FnCompiler<'a> {
|
||||
left,
|
||||
right,
|
||||
} => {
|
||||
// JumpIfFalse always pops the tested value.
|
||||
self.compile_expr(left)?;
|
||||
let j_false = self.here();
|
||||
self.emit(Op::JumpIfFalse(0));
|
||||
@@ -447,6 +637,14 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
self.emit(Op::BuildList(items.len() as u16));
|
||||
}
|
||||
Expr::Formula(e) => {
|
||||
let i = self.add_const(Value::Formula(e.clone()));
|
||||
self.emit(Op::Constant(i));
|
||||
}
|
||||
Expr::Code(c) => {
|
||||
let i = self.add_const(Value::Code(c.clone()));
|
||||
self.emit(Op::Constant(i));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+22
-1
@@ -6,6 +6,7 @@ mod vm;
|
||||
pub use compile::compile_module;
|
||||
pub use vm::Vm;
|
||||
|
||||
use crate::diagnostics::Span;
|
||||
use crate::value::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -33,11 +34,28 @@ pub enum Op {
|
||||
Jump(u16),
|
||||
JumpIfFalse(u16),
|
||||
Print,
|
||||
/// Pop prompt text, print it (no newline), read one stdin line → push Text.
|
||||
Input,
|
||||
BuildList(u16),
|
||||
/// Pop value → push `len` (text/list).
|
||||
Len,
|
||||
/// Pop value → push display text.
|
||||
Str,
|
||||
/// Pop value → push int (or fail).
|
||||
Int,
|
||||
/// Pop value → push type name text.
|
||||
TypeOf,
|
||||
/// Pop text → push trimmed text.
|
||||
Trim,
|
||||
/// Pop sep, then value → push list of text parts.
|
||||
Split,
|
||||
/// Pop sep, then list → push joined text.
|
||||
Join,
|
||||
GetIndex,
|
||||
/// Call function by index; argc values are on the stack (param order).
|
||||
Call(u16, u8),
|
||||
/// Host primitive: pop `argc` args (param order), push result.
|
||||
HostCall(u16, u8),
|
||||
Return,
|
||||
}
|
||||
|
||||
@@ -46,6 +64,8 @@ pub struct FnChunk {
|
||||
pub name: String,
|
||||
pub params: Vec<String>,
|
||||
pub code: Vec<Op>,
|
||||
/// Parallel to `code`: source location for diagnostics / debug.
|
||||
pub spans: Vec<Span>,
|
||||
pub constants: Vec<Value>,
|
||||
/// Local slot names (params first).
|
||||
pub locals: Vec<String>,
|
||||
@@ -71,7 +91,8 @@ impl Program {
|
||||
out.push_str(&format!(" const[{i}] = {c:?}\n"));
|
||||
}
|
||||
for (ip, op) in fun.code.iter().enumerate() {
|
||||
out.push_str(&format!(" {ip:04} {op:?}\n"));
|
||||
let sp = fun.spans.get(ip).copied().unwrap_or(Span::new(1, 1));
|
||||
out.push_str(&format!(" {ip:04} {op:?} @{sp}\n"));
|
||||
}
|
||||
}
|
||||
out.push_str("=== marqdo: end bytecode ===\n");
|
||||
|
||||
+219
-56
@@ -1,13 +1,28 @@
|
||||
//! Stack VM for Marqdo bytecode.
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
use anyhow::Result;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::builtin::{
|
||||
builtin_at, builtin_int, builtin_join, builtin_len, builtin_split, builtin_str, builtin_trim,
|
||||
builtin_type,
|
||||
};
|
||||
use crate::host::{call_host, HostContext, HostFn};
|
||||
use crate::bytecode::{Op, Program};
|
||||
use crate::debug::emit_trace;
|
||||
use crate::diagnostics::{bail_at, Span};
|
||||
use crate::input_feed::InputFeed;
|
||||
use crate::value::Value;
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub struct Vm {
|
||||
path: Option<PathBuf>,
|
||||
capture: bool,
|
||||
pub captured_stdout: String,
|
||||
input: InputFeed,
|
||||
trace: bool,
|
||||
host: HostContext,
|
||||
}
|
||||
|
||||
struct Frame {
|
||||
@@ -17,20 +32,47 @@ struct Frame {
|
||||
}
|
||||
|
||||
impl Vm {
|
||||
pub fn new() -> Self {
|
||||
pub fn new(path: Option<&Path>) -> Self {
|
||||
Self {
|
||||
path: path.map(|p| p.to_path_buf()),
|
||||
capture: false,
|
||||
captured_stdout: String::new(),
|
||||
input: InputFeed::new(false, Vec::new()),
|
||||
trace: false,
|
||||
host: HostContext::for_run(path, Default::default(), Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_capture() -> Self {
|
||||
pub fn with_capture(path: Option<&Path>) -> Self {
|
||||
Self {
|
||||
path: path.map(|p| p.to_path_buf()),
|
||||
capture: true,
|
||||
captured_stdout: String::new(),
|
||||
input: InputFeed::new(true, Vec::new()),
|
||||
trace: false,
|
||||
host: HostContext::for_capture(path, Default::default()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_stdin(mut self, lines: Vec<String>) -> Self {
|
||||
self.input = InputFeed::new(self.capture, lines);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_trace(mut self, trace: bool) -> Self {
|
||||
self.trace = trace;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_host(mut self, host: HostContext) -> Self {
|
||||
self.host = host;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn take_plots(&mut self) -> Vec<crate::host::PlotArtifact> {
|
||||
std::mem::take(&mut self.host.plots)
|
||||
}
|
||||
|
||||
fn emit_line(&mut self, text: &str) {
|
||||
if self.capture {
|
||||
self.captured_stdout.push_str(text);
|
||||
@@ -40,12 +82,33 @@ impl Vm {
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_prompt(&mut self, prompt: &str) {
|
||||
if prompt.is_empty() {
|
||||
return;
|
||||
}
|
||||
if self.capture {
|
||||
self.captured_stdout.push_str(prompt);
|
||||
} else {
|
||||
print!("{prompt}");
|
||||
let _ = std::io::stdout().flush();
|
||||
}
|
||||
}
|
||||
|
||||
fn err_at(&self, span: Span, message: impl Into<String>) -> anyhow::Error {
|
||||
bail_at(self.path.as_deref(), span, message)
|
||||
}
|
||||
|
||||
pub fn run(&mut self, program: &Program) -> Result<Value> {
|
||||
let mut stack: Vec<Value> = Vec::new();
|
||||
let entry = program.entry;
|
||||
let arity = program.functions[entry].params.len();
|
||||
if arity != 0 {
|
||||
bail!("bytecode: entry function needs arguments");
|
||||
let span = program.functions[entry]
|
||||
.spans
|
||||
.first()
|
||||
.copied()
|
||||
.unwrap_or(Span::new(1, 1));
|
||||
return Err(self.err_at(span, "bytecode: entry function needs arguments"));
|
||||
}
|
||||
let mut frames = vec![Frame {
|
||||
fn_idx: entry,
|
||||
@@ -57,11 +120,40 @@ impl Vm {
|
||||
let frame = frames.last_mut().unwrap();
|
||||
let fun = &program.functions[frame.fn_idx];
|
||||
if frame.ip >= fun.code.len() {
|
||||
bail!("bytecode: ip out of range in {}", fun.name);
|
||||
let span = fun.spans.last().copied().unwrap_or(Span::new(1, 1));
|
||||
return Err(self.err_at(span, format!("bytecode: ip out of range in {}", fun.name)));
|
||||
}
|
||||
let op = fun.code[frame.ip];
|
||||
let ip = frame.ip;
|
||||
let op = fun.code[ip];
|
||||
let span = fun.spans.get(ip).copied().unwrap_or(Span::new(1, 1));
|
||||
frame.ip += 1;
|
||||
|
||||
if self.trace {
|
||||
match op {
|
||||
Op::Print | Op::Input | Op::Call(_, _) | Op::Return => {
|
||||
let kind = match op {
|
||||
Op::Print => "print",
|
||||
Op::Input => "input",
|
||||
Op::Call(_, _) => "call",
|
||||
Op::Return => "return",
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let ip_s = ip.to_string();
|
||||
emit_trace(
|
||||
self.path.as_deref(),
|
||||
Some(span),
|
||||
"op",
|
||||
&[
|
||||
("kind", kind),
|
||||
("fn", fun.name.as_str()),
|
||||
("ip", ip_s.as_str()),
|
||||
],
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
match op {
|
||||
Op::Constant(i) => stack.push(fun.constants[i as usize].clone()),
|
||||
Op::True => stack.push(Value::Bool(true)),
|
||||
@@ -84,95 +176,160 @@ impl Vm {
|
||||
fr.slots[slot] = v;
|
||||
}
|
||||
Op::Add => {
|
||||
let b = pop(&mut stack)?;
|
||||
let a = pop(&mut stack)?;
|
||||
stack.push(add(a, b)?);
|
||||
let b = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
let a = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(add(a, b).map_err(|m| self.err_at(span, m))?);
|
||||
}
|
||||
Op::Sub => bin_int(&mut stack, |a, b| a - b)?,
|
||||
Op::Mul => bin_int(&mut stack, |a, b| a * b)?,
|
||||
Op::Sub => bin_int(&mut stack, |a, b| a - b).map_err(|m| self.err_at(span, m))?,
|
||||
Op::Mul => bin_int(&mut stack, |a, b| a * b).map_err(|m| self.err_at(span, m))?,
|
||||
Op::Div => {
|
||||
let b = pop(&mut stack)?;
|
||||
let a = pop(&mut stack)?;
|
||||
let b = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
let a = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
match (a, b) {
|
||||
(Value::Int(_), Value::Int(0)) => bail!("division by zero"),
|
||||
(Value::Int(_), Value::Int(0)) => {
|
||||
return Err(self.err_at(span, "division by zero"));
|
||||
}
|
||||
(Value::Int(x), Value::Int(y)) => stack.push(Value::Int(x / y)),
|
||||
_ => bail!("`/` needs ints"),
|
||||
_ => return Err(self.err_at(span, "`/` needs ints")),
|
||||
}
|
||||
}
|
||||
Op::Negate => match pop(&mut stack)? {
|
||||
Op::Negate => match pop(&mut stack).map_err(|m| self.err_at(span, m))? {
|
||||
Value::Int(n) => stack.push(Value::Int(-n)),
|
||||
_ => bail!("unary `-` needs int"),
|
||||
_ => return Err(self.err_at(span, "unary `-` needs int")),
|
||||
},
|
||||
Op::Not => {
|
||||
let v = pop(&mut stack)?;
|
||||
let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(Value::Bool(!v.truthy()));
|
||||
}
|
||||
Op::Equal => {
|
||||
let b = pop(&mut stack)?;
|
||||
let a = pop(&mut stack)?;
|
||||
let b = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
let a = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(Value::Bool(a == b));
|
||||
}
|
||||
Op::NotEqual => {
|
||||
let b = pop(&mut stack)?;
|
||||
let a = pop(&mut stack)?;
|
||||
let b = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
let a = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(Value::Bool(a != b));
|
||||
}
|
||||
Op::Greater => cmp(&mut stack, |o| o.is_gt())?,
|
||||
Op::GreaterEqual => cmp(&mut stack, |o| o.is_ge())?,
|
||||
Op::Less => cmp(&mut stack, |o| o.is_lt())?,
|
||||
Op::Lessequal => cmp(&mut stack, |o| o.is_le())?,
|
||||
Op::Greater => cmp(&mut stack, |o| o.is_gt()).map_err(|m| self.err_at(span, m))?,
|
||||
Op::GreaterEqual => {
|
||||
cmp(&mut stack, |o| o.is_ge()).map_err(|m| self.err_at(span, m))?
|
||||
}
|
||||
Op::Less => cmp(&mut stack, |o| o.is_lt()).map_err(|m| self.err_at(span, m))?,
|
||||
Op::Lessequal => cmp(&mut stack, |o| o.is_le()).map_err(|m| self.err_at(span, m))?,
|
||||
Op::Jump(t) => {
|
||||
frames.last_mut().unwrap().ip = t as usize;
|
||||
}
|
||||
Op::JumpIfFalse(t) => {
|
||||
let v = pop(&mut stack)?;
|
||||
let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
if !v.truthy() {
|
||||
frames.last_mut().unwrap().ip = t as usize;
|
||||
}
|
||||
}
|
||||
Op::Print => {
|
||||
let v = pop(&mut stack)?;
|
||||
let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
self.emit_line(&v.as_display());
|
||||
}
|
||||
Op::Input => {
|
||||
let prompt = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
let text = prompt.as_display();
|
||||
self.emit_prompt(&text);
|
||||
let line = self.input.read_line().map_err(|e| {
|
||||
let msg = e.to_string();
|
||||
if msg.contains("input needs a line") {
|
||||
self.err_at(span, msg)
|
||||
} else {
|
||||
e
|
||||
}
|
||||
})?;
|
||||
stack.push(Value::Text(line));
|
||||
}
|
||||
Op::BuildList(n) => {
|
||||
let n = n as usize;
|
||||
let mut items = Vec::with_capacity(n);
|
||||
for _ in 0..n {
|
||||
items.push(pop(&mut stack)?);
|
||||
items.push(pop(&mut stack).map_err(|m| self.err_at(span, m))?);
|
||||
}
|
||||
items.reverse();
|
||||
stack.push(Value::List(items));
|
||||
}
|
||||
Op::Len => match pop(&mut stack)? {
|
||||
Value::List(xs) => stack.push(Value::Int(xs.len() as i64)),
|
||||
_ => bail!("len needs list"),
|
||||
},
|
||||
Op::Len => {
|
||||
let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
let n = builtin_len(&v).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(Value::Int(n));
|
||||
}
|
||||
Op::Str => {
|
||||
let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(builtin_str(&v));
|
||||
}
|
||||
Op::Int => {
|
||||
let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
let n = builtin_int(&v).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(Value::Int(n));
|
||||
}
|
||||
Op::TypeOf => {
|
||||
let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(builtin_type(&v));
|
||||
}
|
||||
Op::Trim => {
|
||||
let v = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(builtin_trim(&v).map_err(|m| self.err_at(span, m))?);
|
||||
}
|
||||
Op::Split => {
|
||||
let sep = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
let value = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(builtin_split(&value, &sep).map_err(|m| self.err_at(span, m))?);
|
||||
}
|
||||
Op::Join => {
|
||||
let sep = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
let value = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(builtin_join(&value, &sep).map_err(|m| self.err_at(span, m))?);
|
||||
}
|
||||
Op::GetIndex => {
|
||||
let idx = pop(&mut stack)?;
|
||||
let list = pop(&mut stack)?;
|
||||
match (list, idx) {
|
||||
(Value::List(xs), Value::Int(i)) if i >= 0 && (i as usize) < xs.len() => {
|
||||
stack.push(xs[i as usize].clone());
|
||||
}
|
||||
(Value::List(_), Value::Int(_)) => stack.push(Value::None),
|
||||
_ => bail!("GetIndex needs list and int"),
|
||||
let idx = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
let list = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(builtin_at(&list, &idx).map_err(|m| self.err_at(span, m))?);
|
||||
}
|
||||
Op::HostCall(id, argc) => {
|
||||
let hf = HostFn::from_u16(id)
|
||||
.ok_or_else(|| self.err_at(span, format!("unknown host id {id}")))?;
|
||||
let argc = argc as usize;
|
||||
let params = hf.all_params();
|
||||
if params.len() != argc {
|
||||
return Err(self.err_at(span, "host call argc mismatch"));
|
||||
}
|
||||
let mut vals = Vec::with_capacity(argc);
|
||||
for _ in 0..argc {
|
||||
vals.push(pop(&mut stack).map_err(|m| self.err_at(span, m))?);
|
||||
}
|
||||
vals.reverse();
|
||||
let mut bound = HashMap::new();
|
||||
for (p, v) in params.iter().zip(vals.into_iter()) {
|
||||
bound.insert((*p).to_string(), v);
|
||||
}
|
||||
for req in hf.required_params() {
|
||||
if !bound.contains_key(*req) {
|
||||
return Err(self.err_at(
|
||||
span,
|
||||
format!("{} requires `{req}`", hf.name()),
|
||||
));
|
||||
}
|
||||
}
|
||||
let result =
|
||||
call_host(&mut self.host, hf, &bound).map_err(|m| self.err_at(span, m))?;
|
||||
stack.push(result);
|
||||
}
|
||||
Op::Call(fid, argc) => {
|
||||
let fid = fid as usize;
|
||||
let argc = argc as usize;
|
||||
let callee = &program.functions[fid];
|
||||
if callee.params.len() != argc {
|
||||
bail!("bytecode: call argc mismatch");
|
||||
return Err(self.err_at(span, "call argument count mismatch"));
|
||||
}
|
||||
let mut slots = vec![Value::None; callee.locals.len().max(argc).max(1)];
|
||||
for i in (0..argc).rev() {
|
||||
slots[i] = pop(&mut stack)?;
|
||||
slots[i] = pop(&mut stack).map_err(|m| self.err_at(span, m))?;
|
||||
}
|
||||
// args were pushed in param order; we popped reverse so slots[0] is last param — fix:
|
||||
// stack had p0, p1, p2 (top). pop → p2, p1, p0. So assign slots[argc-1-i] or pop into reverse.
|
||||
// Actually we did: for i in (0..argc).rev() { slots[i] = pop() }
|
||||
// first pop → slots[argc-1] = top = last param. Good if push order was p0..plast.
|
||||
frames.push(Frame {
|
||||
fn_idx: fid,
|
||||
ip: 0,
|
||||
@@ -192,26 +349,25 @@ impl Vm {
|
||||
}
|
||||
}
|
||||
|
||||
fn pop(stack: &mut Vec<Value>) -> Result<Value> {
|
||||
fn pop(stack: &mut Vec<Value>) -> Result<Value, String> {
|
||||
stack
|
||||
.pop()
|
||||
.ok_or_else(|| anyhow::anyhow!("bytecode: stack underflow"))
|
||||
.ok_or_else(|| "bytecode: stack underflow".to_string())
|
||||
}
|
||||
|
||||
fn add(a: Value, b: Value) -> Result<Value> {
|
||||
fn add(a: Value, b: Value) -> Result<Value, String> {
|
||||
match (a, b) {
|
||||
(Value::Int(x), Value::Int(y)) => Ok(Value::Int(x + y)),
|
||||
(Value::Text(x), Value::Text(y)) => Ok(Value::Text(format!("{x}{y}"))),
|
||||
(Value::Text(x), y) => Ok(Value::Text(format!("{x}{}", y.as_display()))),
|
||||
(x, Value::Text(y)) => Ok(Value::Text(format!("{}{y}", x.as_display()))),
|
||||
// Int + display for interp GetLocal Int + Lit text
|
||||
(Value::Int(x), y) => Ok(Value::Text(format!("{}{}", x, y.as_display()))),
|
||||
(x, Value::Int(y)) => Ok(Value::Text(format!("{}{y}", x.as_display()))),
|
||||
_ => bail!("`+` needs ints or text"),
|
||||
_ => Err("`+` needs ints or text".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn bin_int(stack: &mut Vec<Value>, f: impl Fn(i64, i64) -> i64) -> Result<()> {
|
||||
fn bin_int(stack: &mut Vec<Value>, f: impl Fn(i64, i64) -> i64) -> Result<(), String> {
|
||||
let b = pop(stack)?;
|
||||
let a = pop(stack)?;
|
||||
match (a, b) {
|
||||
@@ -219,17 +375,24 @@ fn bin_int(stack: &mut Vec<Value>, f: impl Fn(i64, i64) -> i64) -> Result<()> {
|
||||
stack.push(Value::Int(f(x, y)));
|
||||
Ok(())
|
||||
}
|
||||
_ => bail!("binary op needs ints"),
|
||||
_ => Err("binary op needs ints".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn cmp(stack: &mut Vec<Value>, pred: impl Fn(std::cmp::Ordering) -> bool) -> Result<()> {
|
||||
fn cmp(stack: &mut Vec<Value>, pred: impl Fn(std::cmp::Ordering) -> bool) -> Result<(), String> {
|
||||
let b = pop(stack)?;
|
||||
let a = pop(stack)?;
|
||||
let ord = match (&a, &b) {
|
||||
(Value::Int(x), Value::Int(y)) => x.cmp(y),
|
||||
(Value::Num(x), Value::Num(y)) => x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal),
|
||||
(Value::Int(x), Value::Num(y)) => {
|
||||
(*x as f64).partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal)
|
||||
}
|
||||
(Value::Num(x), Value::Int(y)) => {
|
||||
x.partial_cmp(&(*y as f64)).unwrap_or(std::cmp::Ordering::Equal)
|
||||
}
|
||||
(Value::Text(x), Value::Text(y)) => x.cmp(y),
|
||||
_ => bail!("comparison needs two ints or two texts"),
|
||||
_ => return Err("comparison needs two ints/nums or two texts".into()),
|
||||
};
|
||||
stack.push(Value::Bool(pred(ord)));
|
||||
Ok(())
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
//! Captured program run (for tests and `view`).
|
||||
|
||||
use crate::value::Value;
|
||||
use crate::host::PlotArtifact;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunCapture {
|
||||
pub stdout: String,
|
||||
pub value: Value,
|
||||
pub plots: Vec<PlotArtifact>,
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
//! Pipeline dump helpers (see doc/design/pipeline-debug.md).
|
||||
|
||||
mod trace;
|
||||
|
||||
pub use crate::lex::format_lines_dump;
|
||||
pub use trace::emit_trace;
|
||||
@@ -0,0 +1,49 @@
|
||||
//! Structured eval trace (P3-D1): JSON lines on stderr.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::diagnostics::{display_path, Span};
|
||||
|
||||
/// Emit one JSON object line to stderr when tracing.
|
||||
pub fn emit_trace(path: Option<&Path>, span: Option<Span>, event: &str, fields: &[(&str, &str)]) {
|
||||
let mut out = String::from("{");
|
||||
out.push_str(&format!("\"event\":{}", json_str(event)));
|
||||
if let Some(p) = path {
|
||||
out.push_str(&format!(",\"path\":{}", json_str(&display_path(p))));
|
||||
}
|
||||
if let Some(sp) = span {
|
||||
out.push_str(&format!(",\"span\":{}", json_str(&sp.to_string())));
|
||||
}
|
||||
for (k, v) in fields {
|
||||
out.push_str(&format!(",\"{}\":{}", k, json_str(v)));
|
||||
}
|
||||
out.push('}');
|
||||
eprintln!("{out}");
|
||||
}
|
||||
|
||||
fn json_str(s: &str) -> String {
|
||||
let mut out = String::from("\"");
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn json_str_escapes() {
|
||||
assert_eq!(json_str("a\"b"), r#""a\"b""#);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//! Foreign / code-block helpers (外联).
|
||||
|
||||
/// Default interpreter argv for a language tag (before env / set_cmd).
|
||||
pub fn default_argv(lang: &str) -> Option<Vec<String>> {
|
||||
match lang.to_ascii_lowercase().as_str() {
|
||||
"python" | "python3" | "py" => Some(default_python_argv()),
|
||||
"javascript" | "js" | "node" => Some(vec!["node".into()]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default_python_argv() -> Vec<String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
vec!["python".into()]
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
vec!["python3".into()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Placeholder shown in the view command box.
|
||||
pub fn default_cmd_display(lang: &str) -> String {
|
||||
default_argv(lang)
|
||||
.map(|a| a.join(" "))
|
||||
.unwrap_or_else(|| lang.to_string())
|
||||
}
|
||||
|
||||
/// Parse ```lang … opener → language id (first token).
|
||||
pub fn fence_lang(opener_trimmed: &str) -> Option<String> {
|
||||
let rest = opener_trimmed.strip_prefix("```")?;
|
||||
if rest.is_empty() || rest.chars().all(|c| c == '`') {
|
||||
return None;
|
||||
}
|
||||
let lang = rest.split_whitespace().next()?.to_string();
|
||||
if lang.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(lang)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_fence_opener(trimmed: &str) -> bool {
|
||||
fence_lang(trimmed).is_some()
|
||||
}
|
||||
|
||||
pub fn is_fence_closer(trimmed: &str) -> bool {
|
||||
trimmed.starts_with("```")
|
||||
&& trimmed
|
||||
.chars()
|
||||
.skip_while(|c| *c == '`')
|
||||
.all(|c| c.is_whitespace())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn fence_lang_python() {
|
||||
assert_eq!(fence_lang("```python").as_deref(), Some("python"));
|
||||
assert_eq!(fence_lang("```python name=x").as_deref(), Some("python"));
|
||||
assert!(fence_lang("```").is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,961 @@
|
||||
//! High-school formula AST: parse, simplify, diff, eval, solve, plot helpers.
|
||||
|
||||
mod plot;
|
||||
|
||||
pub use plot::{plot_conic_svg, plot_function_svg, plot_points_svg, PlotStyle};
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
|
||||
/// Expression tree for `Value::Formula`.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Expr {
|
||||
Num(f64),
|
||||
Var(String),
|
||||
UnaryNeg(Box<Expr>),
|
||||
Bin {
|
||||
op: BinOp,
|
||||
left: Box<Expr>,
|
||||
right: Box<Expr>,
|
||||
},
|
||||
Call {
|
||||
name: String,
|
||||
args: Vec<Expr>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BinOp {
|
||||
Add,
|
||||
Sub,
|
||||
Mul,
|
||||
Div,
|
||||
Pow,
|
||||
}
|
||||
|
||||
impl Expr {
|
||||
pub fn num(n: f64) -> Self {
|
||||
Expr::Num(n)
|
||||
}
|
||||
|
||||
pub fn var(name: impl Into<String>) -> Self {
|
||||
Expr::Var(name.into())
|
||||
}
|
||||
|
||||
pub fn as_display(&self) -> String {
|
||||
self.fmt_prec(0)
|
||||
}
|
||||
|
||||
fn fmt_prec(&self, parent_prec: u8) -> String {
|
||||
match self {
|
||||
Expr::Num(n) => format_num(*n),
|
||||
Expr::Var(v) => v.clone(),
|
||||
Expr::UnaryNeg(e) => {
|
||||
let inner = e.fmt_prec(3);
|
||||
let s = format!("-{inner}");
|
||||
if parent_prec > 2 {
|
||||
format!("({s})")
|
||||
} else {
|
||||
s
|
||||
}
|
||||
}
|
||||
Expr::Bin { op, left, right } => {
|
||||
let prec = op.prec();
|
||||
let ls = left.fmt_prec(prec);
|
||||
let rs = right.fmt_prec(if matches!(op, BinOp::Sub | BinOp::Div) {
|
||||
prec + 1
|
||||
} else if matches!(op, BinOp::Pow) {
|
||||
prec
|
||||
} else {
|
||||
prec
|
||||
});
|
||||
let s = format!("{ls}{}{rs}", op.sym());
|
||||
if prec < parent_prec {
|
||||
format!("({s})")
|
||||
} else {
|
||||
s
|
||||
}
|
||||
}
|
||||
Expr::Call { name, args } => {
|
||||
let joined: Vec<String> = args.iter().map(|a| a.as_display()).collect();
|
||||
format!("{name}({})", joined.join(", "))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Expr {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.as_display())
|
||||
}
|
||||
}
|
||||
|
||||
impl BinOp {
|
||||
fn prec(self) -> u8 {
|
||||
match self {
|
||||
BinOp::Add | BinOp::Sub => 1,
|
||||
BinOp::Mul | BinOp::Div => 2,
|
||||
BinOp::Pow => 3,
|
||||
}
|
||||
}
|
||||
|
||||
fn sym(self) -> &'static str {
|
||||
match self {
|
||||
BinOp::Add => " + ",
|
||||
BinOp::Sub => " - ",
|
||||
BinOp::Mul => "*",
|
||||
BinOp::Div => "/",
|
||||
BinOp::Pow => "^",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn format_num(n: f64) -> String {
|
||||
if n.is_nan() {
|
||||
return "nan".into();
|
||||
}
|
||||
if n.is_infinite() {
|
||||
return if n.is_sign_positive() {
|
||||
"inf".into()
|
||||
} else {
|
||||
"-inf".into()
|
||||
};
|
||||
}
|
||||
if n.fract() == 0.0 && n.abs() < 1e15 {
|
||||
return format!("{}", n as i64);
|
||||
}
|
||||
let s = format!("{n:.10}");
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
if s.is_empty() || s == "-" {
|
||||
"0".into()
|
||||
} else {
|
||||
s.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse ASCII formula text (`sin(x) + x^2`, optional simple `y = …` left strip).
|
||||
pub fn parse(input: &str) -> Result<Expr, String> {
|
||||
let t = input.trim();
|
||||
if t.is_empty() {
|
||||
return Err("empty formula".into());
|
||||
}
|
||||
let body = if let Some((lhs, rhs)) = t.split_once('=') {
|
||||
let lhs = lhs.trim();
|
||||
if lhs.chars().all(|c| c.is_ascii_alphabetic() || c == '_') && !rhs.trim().is_empty() {
|
||||
rhs.trim()
|
||||
} else {
|
||||
t
|
||||
}
|
||||
} else {
|
||||
t
|
||||
};
|
||||
let mut p = Parser {
|
||||
src: body.chars().collect(),
|
||||
i: 0,
|
||||
};
|
||||
let e = p.parse_expr()?;
|
||||
p.skip_ws();
|
||||
if p.i < p.src.len() {
|
||||
return Err(format!(
|
||||
"unexpected trailing input near `{}`",
|
||||
p.src[p.i..].iter().collect::<String>()
|
||||
));
|
||||
}
|
||||
Ok(e)
|
||||
}
|
||||
|
||||
struct Parser {
|
||||
src: Vec<char>,
|
||||
i: usize,
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
fn skip_ws(&mut self) {
|
||||
while self.i < self.src.len() && self.src[self.i].is_whitespace() {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn peek(&mut self) -> Option<char> {
|
||||
self.skip_ws();
|
||||
self.src.get(self.i).copied()
|
||||
}
|
||||
|
||||
fn bump(&mut self) -> Option<char> {
|
||||
self.skip_ws();
|
||||
let c = self.src.get(self.i).copied()?;
|
||||
self.i += 1;
|
||||
Some(c)
|
||||
}
|
||||
|
||||
fn parse_expr(&mut self) -> Result<Expr, String> {
|
||||
self.parse_add()
|
||||
}
|
||||
|
||||
fn parse_add(&mut self) -> Result<Expr, String> {
|
||||
let mut left = self.parse_mul()?;
|
||||
loop {
|
||||
match self.peek() {
|
||||
Some('+') => {
|
||||
self.bump();
|
||||
let right = self.parse_mul()?;
|
||||
left = Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
};
|
||||
}
|
||||
Some('-') => {
|
||||
self.bump();
|
||||
let right = self.parse_mul()?;
|
||||
left = Expr::Bin {
|
||||
op: BinOp::Sub,
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
};
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
Ok(left)
|
||||
}
|
||||
|
||||
fn parse_mul(&mut self) -> Result<Expr, String> {
|
||||
let mut left = self.parse_pow()?;
|
||||
loop {
|
||||
match self.peek() {
|
||||
Some('*') => {
|
||||
self.bump();
|
||||
let right = self.parse_pow()?;
|
||||
left = Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
};
|
||||
}
|
||||
Some('/') => {
|
||||
self.bump();
|
||||
let right = self.parse_pow()?;
|
||||
left = Expr::Bin {
|
||||
op: BinOp::Div,
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
};
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
Ok(left)
|
||||
}
|
||||
|
||||
fn parse_pow(&mut self) -> Result<Expr, String> {
|
||||
let left = self.parse_unary()?;
|
||||
if self.peek() == Some('^') {
|
||||
self.bump();
|
||||
let right = self.parse_pow()?; // right-assoc
|
||||
Ok(Expr::Bin {
|
||||
op: BinOp::Pow,
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
})
|
||||
} else {
|
||||
Ok(left)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_unary(&mut self) -> Result<Expr, String> {
|
||||
match self.peek() {
|
||||
Some('+') => {
|
||||
self.bump();
|
||||
self.parse_unary()
|
||||
}
|
||||
Some('-') => {
|
||||
self.bump();
|
||||
Ok(Expr::UnaryNeg(Box::new(self.parse_unary()?)))
|
||||
}
|
||||
_ => self.parse_primary(),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_primary(&mut self) -> Result<Expr, String> {
|
||||
match self.peek() {
|
||||
Some('(') => {
|
||||
self.bump();
|
||||
let e = self.parse_expr()?;
|
||||
if self.bump() != Some(')') {
|
||||
return Err("expected `)`".into());
|
||||
}
|
||||
Ok(e)
|
||||
}
|
||||
Some(c) if c.is_ascii_digit() || c == '.' => self.parse_number(),
|
||||
Some(c) if c.is_ascii_alphabetic() || c == '_' => {
|
||||
let name = self.parse_ident()?;
|
||||
if self.peek() == Some('(') {
|
||||
self.bump();
|
||||
let mut args = Vec::new();
|
||||
if self.peek() != Some(')') {
|
||||
loop {
|
||||
args.push(self.parse_expr()?);
|
||||
match self.peek() {
|
||||
Some(',') => {
|
||||
self.bump();
|
||||
}
|
||||
Some(')') => break,
|
||||
_ => return Err("expected `,` or `)` in call".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.bump() != Some(')') {
|
||||
return Err("expected `)` after call args".into());
|
||||
}
|
||||
Ok(Expr::Call { name, args })
|
||||
} else {
|
||||
Ok(Expr::Var(name))
|
||||
}
|
||||
}
|
||||
Some(c) => Err(format!("unexpected `{c}` in formula")),
|
||||
None => Err("unexpected end of formula".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_number(&mut self) -> Result<Expr, String> {
|
||||
self.skip_ws();
|
||||
let start = self.i;
|
||||
while self.i < self.src.len()
|
||||
&& (self.src[self.i].is_ascii_digit() || self.src[self.i] == '.')
|
||||
{
|
||||
self.i += 1;
|
||||
}
|
||||
let s: String = self.src[start..self.i].iter().collect();
|
||||
let n: f64 = s
|
||||
.parse()
|
||||
.map_err(|_| format!("invalid number `{s}`"))?;
|
||||
Ok(Expr::Num(n))
|
||||
}
|
||||
|
||||
fn parse_ident(&mut self) -> Result<String, String> {
|
||||
self.skip_ws();
|
||||
let start = self.i;
|
||||
while self.i < self.src.len() {
|
||||
let c = self.src[self.i];
|
||||
if c.is_ascii_alphanumeric() || c == '_' {
|
||||
self.i += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if start == self.i {
|
||||
return Err("expected identifier".into());
|
||||
}
|
||||
Ok(self.src[start..self.i].iter().collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// Constant-fold + light algebraic cleanup.
|
||||
pub fn simplify(e: &Expr) -> Expr {
|
||||
match e {
|
||||
Expr::Num(n) => Expr::Num(*n),
|
||||
Expr::Var(v) => Expr::Var(v.clone()),
|
||||
Expr::UnaryNeg(inner) => {
|
||||
let i = simplify(inner);
|
||||
match i {
|
||||
Expr::Num(n) => Expr::Num(-n),
|
||||
Expr::UnaryNeg(x) => *x,
|
||||
other => Expr::UnaryNeg(Box::new(other)),
|
||||
}
|
||||
}
|
||||
Expr::Bin { op, left, right } => {
|
||||
let l = simplify(left);
|
||||
let r = simplify(right);
|
||||
fold_bin(*op, l, r)
|
||||
}
|
||||
Expr::Call { name, args } => {
|
||||
let args: Vec<Expr> = args.iter().map(simplify).collect();
|
||||
if args.len() == 1 {
|
||||
if let Expr::Num(n) = &args[0] {
|
||||
if let Some(v) = eval_call_f64(name, &[*n]) {
|
||||
return Expr::Num(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
Expr::Call {
|
||||
name: name.clone(),
|
||||
args,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fold_bin(op: BinOp, l: Expr, r: Expr) -> Expr {
|
||||
match (op, &l, &r) {
|
||||
(BinOp::Add, Expr::Num(a), Expr::Num(b)) => Expr::Num(a + b),
|
||||
(BinOp::Sub, Expr::Num(a), Expr::Num(b)) => Expr::Num(a - b),
|
||||
(BinOp::Mul, Expr::Num(a), Expr::Num(b)) => Expr::Num(a * b),
|
||||
(BinOp::Div, Expr::Num(a), Expr::Num(b)) if *b != 0.0 => Expr::Num(a / b),
|
||||
(BinOp::Pow, Expr::Num(a), Expr::Num(b)) => Expr::Num(a.powf(*b)),
|
||||
(BinOp::Add, _, Expr::Num(0.0)) => l,
|
||||
(BinOp::Add, Expr::Num(0.0), _) => r,
|
||||
(BinOp::Sub, _, Expr::Num(0.0)) => l,
|
||||
(BinOp::Mul, _, Expr::Num(1.0)) => l,
|
||||
(BinOp::Mul, Expr::Num(1.0), _) => r,
|
||||
(BinOp::Mul, _, Expr::Num(0.0)) | (BinOp::Mul, Expr::Num(0.0), _) => Expr::Num(0.0),
|
||||
(BinOp::Pow, _, Expr::Num(1.0)) => l,
|
||||
(BinOp::Pow, _, Expr::Num(0.0)) => Expr::Num(1.0),
|
||||
(BinOp::Div, _, Expr::Num(1.0)) => l,
|
||||
_ => Expr::Bin {
|
||||
op,
|
||||
left: Box::new(l),
|
||||
right: Box::new(r),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Lightweight expand: distribute multiplication over addition one level.
|
||||
pub fn expand(e: &Expr) -> Expr {
|
||||
let e = simplify(e);
|
||||
match e {
|
||||
Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left,
|
||||
right,
|
||||
} => {
|
||||
let l = expand(&left);
|
||||
let r = expand(&right);
|
||||
match (l, r) {
|
||||
(
|
||||
Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left: a,
|
||||
right: b,
|
||||
},
|
||||
r,
|
||||
) => simplify(&Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: a,
|
||||
right: Box::new(r.clone()),
|
||||
}),
|
||||
right: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: b,
|
||||
right: Box::new(r),
|
||||
}),
|
||||
}),
|
||||
(
|
||||
l,
|
||||
Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left: a,
|
||||
right: b,
|
||||
},
|
||||
) => simplify(&Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(l.clone()),
|
||||
right: a,
|
||||
}),
|
||||
right: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(l),
|
||||
right: b,
|
||||
}),
|
||||
}),
|
||||
(l, r) => simplify(&Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(l),
|
||||
right: Box::new(r),
|
||||
}),
|
||||
}
|
||||
}
|
||||
Expr::Bin { op, left, right } => simplify(&Expr::Bin {
|
||||
op,
|
||||
left: Box::new(expand(&left)),
|
||||
right: Box::new(expand(&right)),
|
||||
}),
|
||||
Expr::UnaryNeg(x) => simplify(&Expr::UnaryNeg(Box::new(expand(&x)))),
|
||||
Expr::Call { name, args } => Expr::Call {
|
||||
name,
|
||||
args: args.iter().map(expand).collect(),
|
||||
},
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn diff(e: &Expr, var: &str) -> Expr {
|
||||
simplify(&diff_raw(e, var))
|
||||
}
|
||||
|
||||
fn diff_raw(e: &Expr, var: &str) -> Expr {
|
||||
match e {
|
||||
Expr::Num(_) => Expr::Num(0.0),
|
||||
Expr::Var(v) => {
|
||||
if v == var {
|
||||
Expr::Num(1.0)
|
||||
} else {
|
||||
Expr::Num(0.0)
|
||||
}
|
||||
}
|
||||
Expr::UnaryNeg(x) => Expr::UnaryNeg(Box::new(diff_raw(x, var))),
|
||||
Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left,
|
||||
right,
|
||||
} => Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left: Box::new(diff_raw(left, var)),
|
||||
right: Box::new(diff_raw(right, var)),
|
||||
},
|
||||
Expr::Bin {
|
||||
op: BinOp::Sub,
|
||||
left,
|
||||
right,
|
||||
} => Expr::Bin {
|
||||
op: BinOp::Sub,
|
||||
left: Box::new(diff_raw(left, var)),
|
||||
right: Box::new(diff_raw(right, var)),
|
||||
},
|
||||
Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left,
|
||||
right,
|
||||
} => {
|
||||
// product rule
|
||||
Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(diff_raw(left, var)),
|
||||
right: right.clone(),
|
||||
}),
|
||||
right: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: left.clone(),
|
||||
right: Box::new(diff_raw(right, var)),
|
||||
}),
|
||||
}
|
||||
}
|
||||
Expr::Bin {
|
||||
op: BinOp::Div,
|
||||
left,
|
||||
right,
|
||||
} => {
|
||||
// (u'v - uv') / v^2
|
||||
let num = Expr::Bin {
|
||||
op: BinOp::Sub,
|
||||
left: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(diff_raw(left, var)),
|
||||
right: right.clone(),
|
||||
}),
|
||||
right: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: left.clone(),
|
||||
right: Box::new(diff_raw(right, var)),
|
||||
}),
|
||||
};
|
||||
Expr::Bin {
|
||||
op: BinOp::Div,
|
||||
left: Box::new(num),
|
||||
right: Box::new(Expr::Bin {
|
||||
op: BinOp::Pow,
|
||||
left: right.clone(),
|
||||
right: Box::new(Expr::Num(2.0)),
|
||||
}),
|
||||
}
|
||||
}
|
||||
Expr::Bin {
|
||||
op: BinOp::Pow,
|
||||
left,
|
||||
right,
|
||||
} => {
|
||||
// d/dx [u^n] when n constant: n*u^(n-1)*u'
|
||||
if let Expr::Num(n) = right.as_ref() {
|
||||
Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(Expr::Num(*n)),
|
||||
right: Box::new(Expr::Bin {
|
||||
op: BinOp::Pow,
|
||||
left: left.clone(),
|
||||
right: Box::new(Expr::Num(n - 1.0)),
|
||||
}),
|
||||
}),
|
||||
right: Box::new(diff_raw(left, var)),
|
||||
}
|
||||
} else {
|
||||
// a^u → a^u * ln(a) * u' when a constant
|
||||
if let Expr::Num(a) = left.as_ref() {
|
||||
Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(e.clone()),
|
||||
right: Box::new(Expr::Call {
|
||||
name: "ln".into(),
|
||||
args: vec![Expr::Num(*a)],
|
||||
}),
|
||||
}),
|
||||
right: Box::new(diff_raw(right, var)),
|
||||
}
|
||||
} else {
|
||||
// fallback: treat as exp(v*ln(u))
|
||||
Expr::Num(0.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
Expr::Call { name, args } => {
|
||||
if args.len() != 1 {
|
||||
return Expr::Num(0.0);
|
||||
}
|
||||
let u = &args[0];
|
||||
let du = diff_raw(u, var);
|
||||
let chain = |outer: Expr| {
|
||||
Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(outer),
|
||||
right: Box::new(du.clone()),
|
||||
}
|
||||
};
|
||||
match name.as_str() {
|
||||
"sin" => chain(Expr::Call {
|
||||
name: "cos".into(),
|
||||
args: vec![u.clone()],
|
||||
}),
|
||||
"cos" => chain(Expr::UnaryNeg(Box::new(Expr::Call {
|
||||
name: "sin".into(),
|
||||
args: vec![u.clone()],
|
||||
}))),
|
||||
"tan" => chain(Expr::Bin {
|
||||
op: BinOp::Pow,
|
||||
left: Box::new(Expr::Call {
|
||||
name: "cos".into(),
|
||||
args: vec![u.clone()],
|
||||
}),
|
||||
right: Box::new(Expr::Num(-2.0)),
|
||||
}),
|
||||
"sqrt" => chain(Expr::Bin {
|
||||
op: BinOp::Div,
|
||||
left: Box::new(Expr::Num(1.0)),
|
||||
right: Box::new(Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left: Box::new(Expr::Num(2.0)),
|
||||
right: Box::new(Expr::Call {
|
||||
name: "sqrt".into(),
|
||||
args: vec![u.clone()],
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
"ln" | "log" => chain(Expr::Bin {
|
||||
op: BinOp::Div,
|
||||
left: Box::new(Expr::Num(1.0)),
|
||||
right: Box::new(u.clone()),
|
||||
}),
|
||||
"exp" => chain(Expr::Call {
|
||||
name: "exp".into(),
|
||||
args: vec![u.clone()],
|
||||
}),
|
||||
"abs" => {
|
||||
// sign(u)*u' — use u/abs(u) when u≠0
|
||||
chain(Expr::Bin {
|
||||
op: BinOp::Div,
|
||||
left: Box::new(u.clone()),
|
||||
right: Box::new(Expr::Call {
|
||||
name: "abs".into(),
|
||||
args: vec![u.clone()],
|
||||
}),
|
||||
})
|
||||
}
|
||||
_ => Expr::Num(0.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn subs(e: &Expr, var: &str, value: &Expr) -> Expr {
|
||||
simplify(&subs_raw(e, var, value))
|
||||
}
|
||||
|
||||
fn subs_raw(e: &Expr, var: &str, value: &Expr) -> Expr {
|
||||
match e {
|
||||
Expr::Num(n) => Expr::Num(*n),
|
||||
Expr::Var(v) => {
|
||||
if v == var {
|
||||
value.clone()
|
||||
} else {
|
||||
Expr::Var(v.clone())
|
||||
}
|
||||
}
|
||||
Expr::UnaryNeg(x) => Expr::UnaryNeg(Box::new(subs_raw(x, var, value))),
|
||||
Expr::Bin { op, left, right } => Expr::Bin {
|
||||
op: *op,
|
||||
left: Box::new(subs_raw(left, var, value)),
|
||||
right: Box::new(subs_raw(right, var, value)),
|
||||
},
|
||||
Expr::Call { name, args } => Expr::Call {
|
||||
name: name.clone(),
|
||||
args: args.iter().map(|a| subs_raw(a, var, value)).collect(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn eval_f64(e: &Expr, env: &HashMap<String, f64>) -> Result<f64, String> {
|
||||
match e {
|
||||
Expr::Num(n) => Ok(*n),
|
||||
Expr::Var(v) => env
|
||||
.get(v)
|
||||
.copied()
|
||||
.ok_or_else(|| format!("unbound variable `{v}`")),
|
||||
Expr::UnaryNeg(x) => Ok(-eval_f64(x, env)?),
|
||||
Expr::Bin { op, left, right } => {
|
||||
let a = eval_f64(left, env)?;
|
||||
let b = eval_f64(right, env)?;
|
||||
Ok(match op {
|
||||
BinOp::Add => a + b,
|
||||
BinOp::Sub => a - b,
|
||||
BinOp::Mul => a * b,
|
||||
BinOp::Div => {
|
||||
if b == 0.0 {
|
||||
return Err("division by zero".into());
|
||||
}
|
||||
a / b
|
||||
}
|
||||
BinOp::Pow => a.powf(b),
|
||||
})
|
||||
}
|
||||
Expr::Call { name, args } => {
|
||||
let mut xs = Vec::with_capacity(args.len());
|
||||
for a in args {
|
||||
xs.push(eval_f64(a, env)?);
|
||||
}
|
||||
eval_call_f64(name, &xs).ok_or_else(|| format!("unknown or arity-mismatch function `{name}`"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn eval_call_f64(name: &str, args: &[f64]) -> Option<f64> {
|
||||
match (name, args) {
|
||||
("sin", [x]) => Some(x.sin()),
|
||||
("cos", [x]) => Some(x.cos()),
|
||||
("tan", [x]) => Some(x.tan()),
|
||||
("asin", [x]) => Some(x.asin()),
|
||||
("acos", [x]) => Some(x.acos()),
|
||||
("atan", [x]) => Some(x.atan()),
|
||||
("sqrt", [x]) => Some(x.sqrt()),
|
||||
("abs", [x]) => Some(x.abs()),
|
||||
("ln" | "log", [x]) => Some(x.ln()),
|
||||
("exp", [x]) => Some(x.exp()),
|
||||
("floor", [x]) => Some(x.floor()),
|
||||
("ceil", [x]) => Some(x.ceil()),
|
||||
("pow", [a, b]) => Some(a.powf(*b)),
|
||||
("min", [a, b]) => Some(a.min(*b)),
|
||||
("max", [a, b]) => Some(a.max(*b)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Solve `e = 0` for `var`. Quadratic/linear closed form; else numeric scan.
|
||||
pub fn solve(e: &Expr, var: &str, xmin: f64, xmax: f64) -> Result<Vec<f64>, String> {
|
||||
let e = expand(&simplify(e));
|
||||
if let Some(roots) = try_polynomial_solve(&e, var) {
|
||||
return Ok(roots);
|
||||
}
|
||||
numeric_roots(&e, var, xmin, xmax)
|
||||
}
|
||||
|
||||
fn try_polynomial_solve(e: &Expr, var: &str) -> Option<Vec<f64>> {
|
||||
let (a, b, c) = poly_coeffs_quadratic(e, var)?;
|
||||
if a.abs() < 1e-12 {
|
||||
if b.abs() < 1e-12 {
|
||||
return if c.abs() < 1e-12 {
|
||||
None // identity
|
||||
} else {
|
||||
Some(vec![])
|
||||
};
|
||||
}
|
||||
return Some(vec![-c / b]);
|
||||
}
|
||||
let disc = b * b - 4.0 * a * c;
|
||||
if disc < -1e-12 {
|
||||
return Some(vec![]);
|
||||
}
|
||||
if disc.abs() <= 1e-12 {
|
||||
return Some(vec![-b / (2.0 * a)]);
|
||||
}
|
||||
let s = disc.sqrt();
|
||||
let mut roots = vec![(-b - s) / (2.0 * a), (-b + s) / (2.0 * a)];
|
||||
roots.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal));
|
||||
Some(roots)
|
||||
}
|
||||
|
||||
/// Collect ax^2+bx+c if expression is a polynomial of degree ≤ 2 in `var`.
|
||||
fn poly_coeffs_quadratic(e: &Expr, var: &str) -> Option<(f64, f64, f64)> {
|
||||
let mut a = 0.0;
|
||||
let mut b = 0.0;
|
||||
let mut c = 0.0;
|
||||
if !accum_poly(e, var, 1.0, &mut a, &mut b, &mut c) {
|
||||
return None;
|
||||
}
|
||||
Some((a, b, c))
|
||||
}
|
||||
|
||||
fn accum_poly(e: &Expr, var: &str, scale: f64, a: &mut f64, b: &mut f64, c: &mut f64) -> bool {
|
||||
match e {
|
||||
Expr::Num(n) => {
|
||||
*c += scale * n;
|
||||
true
|
||||
}
|
||||
Expr::Var(v) if v == var => {
|
||||
*b += scale;
|
||||
true
|
||||
}
|
||||
Expr::Var(_) => false,
|
||||
Expr::UnaryNeg(x) => accum_poly(x, var, -scale, a, b, c),
|
||||
Expr::Bin {
|
||||
op: BinOp::Add,
|
||||
left,
|
||||
right,
|
||||
} => accum_poly(left, var, scale, a, b, c) && accum_poly(right, var, scale, a, b, c),
|
||||
Expr::Bin {
|
||||
op: BinOp::Sub,
|
||||
left,
|
||||
right,
|
||||
} => accum_poly(left, var, scale, a, b, c) && accum_poly(right, var, -scale, a, b, c),
|
||||
Expr::Bin {
|
||||
op: BinOp::Mul,
|
||||
left,
|
||||
right,
|
||||
} => match (left.as_ref(), right.as_ref()) {
|
||||
(Expr::Num(n), r) => accum_poly(r, var, scale * n, a, b, c),
|
||||
(l, Expr::Num(n)) => accum_poly(l, var, scale * n, a, b, c),
|
||||
(Expr::Var(v), Expr::Var(w)) if v == var && w == var => {
|
||||
*a += scale;
|
||||
true
|
||||
}
|
||||
(
|
||||
Expr::Bin {
|
||||
op: BinOp::Pow,
|
||||
left: base,
|
||||
right: exp,
|
||||
},
|
||||
other,
|
||||
)
|
||||
| (
|
||||
other,
|
||||
Expr::Bin {
|
||||
op: BinOp::Pow,
|
||||
left: base,
|
||||
right: exp,
|
||||
},
|
||||
) => {
|
||||
if let (Expr::Var(v), Expr::Num(2.0)) = (base.as_ref(), exp.as_ref()) {
|
||||
if v == var {
|
||||
if let Expr::Num(n) = other {
|
||||
*a += scale * n;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
Expr::Bin {
|
||||
op: BinOp::Pow,
|
||||
left,
|
||||
right,
|
||||
} => match (left.as_ref(), right.as_ref()) {
|
||||
(Expr::Var(v), Expr::Num(2.0)) if v == var => {
|
||||
*a += scale;
|
||||
true
|
||||
}
|
||||
(Expr::Var(v), Expr::Num(1.0)) if v == var => {
|
||||
*b += scale;
|
||||
true
|
||||
}
|
||||
(Expr::Var(v), Expr::Num(0.0)) if v == var => {
|
||||
*c += scale;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn numeric_roots(e: &Expr, var: &str, xmin: f64, xmax: f64) -> Result<Vec<f64>, String> {
|
||||
const STEPS: usize = 200;
|
||||
let mut roots = Vec::new();
|
||||
let mut env = HashMap::new();
|
||||
let dx = (xmax - xmin) / STEPS as f64;
|
||||
let mut x0 = xmin;
|
||||
env.insert(var.to_string(), x0);
|
||||
let mut y0 = eval_f64(e, &env)?;
|
||||
for i in 1..=STEPS {
|
||||
let x1 = xmin + dx * i as f64;
|
||||
env.insert(var.to_string(), x1);
|
||||
let y1 = eval_f64(e, &env)?;
|
||||
if y0 == 0.0 {
|
||||
push_unique(&mut roots, x0);
|
||||
} else if y0.signum() != y1.signum() && y1 != 0.0 {
|
||||
// bisection
|
||||
let mut lo = x0;
|
||||
let mut hi = x1;
|
||||
let mut flo = y0;
|
||||
for _ in 0..40 {
|
||||
let mid = 0.5 * (lo + hi);
|
||||
env.insert(var.to_string(), mid);
|
||||
let fm = eval_f64(e, &env)?;
|
||||
if fm == 0.0 || (hi - lo).abs() < 1e-10 {
|
||||
push_unique(&mut roots, mid);
|
||||
break;
|
||||
}
|
||||
if flo.signum() == fm.signum() {
|
||||
lo = mid;
|
||||
flo = fm;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
}
|
||||
if i == STEPS && y1 == 0.0 {
|
||||
push_unique(&mut roots, x1);
|
||||
}
|
||||
x0 = x1;
|
||||
y0 = y1;
|
||||
}
|
||||
Ok(roots)
|
||||
}
|
||||
|
||||
fn push_unique(xs: &mut Vec<f64>, x: f64) {
|
||||
if xs.iter().any(|y| (y - x).abs() < 1e-6) {
|
||||
return;
|
||||
}
|
||||
xs.push(x);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_and_diff_quadratic() {
|
||||
let e = parse("x^2 - 2").unwrap();
|
||||
let d = diff(&e, "x");
|
||||
assert_eq!(d.as_display(), "2*x");
|
||||
let roots = solve(&e, "x", -10.0, 10.0).unwrap();
|
||||
assert_eq!(roots.len(), 2);
|
||||
assert!((roots[0] + 2f64.sqrt()).abs() < 1e-6);
|
||||
assert!((roots[1] - 2f64.sqrt()).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_sin() {
|
||||
let e = parse("sin(x)").unwrap();
|
||||
let mut env = HashMap::new();
|
||||
env.insert("x".into(), 0.0);
|
||||
assert!((eval_f64(&e, &env).unwrap()).abs() < 1e-12);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
//! SVG plot helpers for high-school graphs.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::{eval_f64, Expr};
|
||||
|
||||
const MAX_STEPS: usize = 2000;
|
||||
const DEFAULT_STEPS: usize = 200;
|
||||
const SVG_W: f64 = 520.0;
|
||||
const SVG_H: f64 = 360.0;
|
||||
const PAD: f64 = 36.0;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct PlotStyle {
|
||||
pub grid: bool,
|
||||
}
|
||||
|
||||
impl Default for PlotStyle {
|
||||
fn default() -> Self {
|
||||
Self { grid: true }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn plot_function_svg(
|
||||
expr: &Expr,
|
||||
var: &str,
|
||||
xmin: f64,
|
||||
xmax: f64,
|
||||
steps: usize,
|
||||
style: PlotStyle,
|
||||
) -> Result<String, String> {
|
||||
if !(xmin.is_finite() && xmax.is_finite()) || xmax <= xmin {
|
||||
return Err("plot needs finite min < max".into());
|
||||
}
|
||||
let steps = steps.clamp(2, MAX_STEPS);
|
||||
let mut env = HashMap::new();
|
||||
let mut pts: Vec<(f64, f64)> = Vec::with_capacity(steps + 1);
|
||||
let mut ymin = f64::INFINITY;
|
||||
let mut ymax = f64::NEG_INFINITY;
|
||||
for i in 0..=steps {
|
||||
let x = xmin + (xmax - xmin) * (i as f64) / (steps as f64);
|
||||
env.insert(var.to_string(), x);
|
||||
match eval_f64(expr, &env) {
|
||||
Ok(y) if y.is_finite() => {
|
||||
ymin = ymin.min(y);
|
||||
ymax = ymax.max(y);
|
||||
pts.push((x, y));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if pts.is_empty() {
|
||||
return Err("plot produced no finite points".into());
|
||||
}
|
||||
if (ymax - ymin).abs() < 1e-12 {
|
||||
ymin -= 1.0;
|
||||
ymax += 1.0;
|
||||
}
|
||||
let pad_y = 0.05 * (ymax - ymin);
|
||||
ymin -= pad_y;
|
||||
ymax += pad_y;
|
||||
|
||||
let mut path = String::new();
|
||||
for (i, (x, y)) in pts.iter().enumerate() {
|
||||
let (sx, sy) = map_xy(*x, *y, xmin, xmax, ymin, ymax);
|
||||
if i == 0 {
|
||||
path.push_str(&format!("M {sx:.2} {sy:.2}"));
|
||||
} else {
|
||||
path.push_str(&format!(" L {sx:.2} {sy:.2}"));
|
||||
}
|
||||
}
|
||||
|
||||
let frame = draw_frame(xmin, xmax, ymin, ymax, style);
|
||||
Ok(svg_wrap(
|
||||
&format!(r#"{frame}<path d="{path}" class="curve"/>"#),
|
||||
"function plot",
|
||||
))
|
||||
}
|
||||
|
||||
pub fn plot_points_svg(xs: &[f64], ys: &[f64], style: PlotStyle) -> Result<String, String> {
|
||||
if xs.len() != ys.len() {
|
||||
return Err("plot_points: xs and ys length mismatch".into());
|
||||
}
|
||||
if xs.is_empty() {
|
||||
return Err("plot_points: empty series".into());
|
||||
}
|
||||
let xmin = xs.iter().cloned().fold(f64::INFINITY, f64::min);
|
||||
let xmax = xs.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
|
||||
let ymin = ys.iter().cloned().fold(f64::INFINITY, f64::min);
|
||||
let ymax = ys.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
|
||||
let (xmin, xmax) = pad_range(xmin, xmax);
|
||||
let (ymin, ymax) = pad_range(ymin, ymax);
|
||||
let mut dots = String::new();
|
||||
for (x, y) in xs.iter().zip(ys.iter()) {
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
continue;
|
||||
}
|
||||
let (sx, sy) = map_xy(*x, *y, xmin, xmax, ymin, ymax);
|
||||
dots.push_str(&format!(
|
||||
r#"<circle cx="{sx:.2}" cy="{sy:.2}" r="3" class="pt"/>"#
|
||||
));
|
||||
}
|
||||
let frame = draw_frame(xmin, xmax, ymin, ymax, style);
|
||||
Ok(svg_wrap(&format!("{frame}{dots}"), "points plot"))
|
||||
}
|
||||
|
||||
/// Standard conics via parametric sampling.
|
||||
/// kind: circle | ellipse | hyperbola | parabola
|
||||
pub fn plot_conic_svg(
|
||||
kind: &str,
|
||||
a: f64,
|
||||
b: f64,
|
||||
h: f64,
|
||||
k: f64,
|
||||
style: PlotStyle,
|
||||
) -> Result<String, String> {
|
||||
let steps = DEFAULT_STEPS;
|
||||
let mut pts: Vec<(f64, f64)> = Vec::new();
|
||||
match kind {
|
||||
"circle" => {
|
||||
let r = if a > 0.0 { a } else { b };
|
||||
if r <= 0.0 {
|
||||
return Err("circle needs positive radius (a)".into());
|
||||
}
|
||||
for i in 0..=steps {
|
||||
let t = std::f64::consts::TAU * (i as f64) / (steps as f64);
|
||||
pts.push((h + r * t.cos(), k + r * t.sin()));
|
||||
}
|
||||
}
|
||||
"ellipse" => {
|
||||
if a <= 0.0 || b <= 0.0 {
|
||||
return Err("ellipse needs a>0, b>0".into());
|
||||
}
|
||||
for i in 0..=steps {
|
||||
let t = std::f64::consts::TAU * (i as f64) / (steps as f64);
|
||||
pts.push((h + a * t.cos(), k + b * t.sin()));
|
||||
}
|
||||
}
|
||||
"hyperbola" => {
|
||||
if a <= 0.0 || b <= 0.0 {
|
||||
return Err("hyperbola needs a>0, b>0".into());
|
||||
}
|
||||
for branch in [-1.0_f64, 1.0] {
|
||||
for i in 0..=steps {
|
||||
let t = -2.0 + 4.0 * (i as f64) / (steps as f64);
|
||||
pts.push((h + branch * a * t.cosh(), k + b * t.sinh()));
|
||||
}
|
||||
}
|
||||
let mid = pts.len() / 2;
|
||||
let (left, right) = pts.split_at(mid);
|
||||
let xmin = pts.iter().map(|p| p.0).fold(f64::INFINITY, f64::min);
|
||||
let xmax = pts.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max);
|
||||
let ymin = pts.iter().map(|p| p.1).fold(f64::INFINITY, f64::min);
|
||||
let ymax = pts.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max);
|
||||
let (xmin, xmax) = pad_range(xmin, xmax);
|
||||
let (ymin, ymax) = pad_range(ymin, ymax);
|
||||
let p1 = polyline_path(left, xmin, xmax, ymin, ymax);
|
||||
let p2 = polyline_path(right, xmin, xmax, ymin, ymax);
|
||||
let frame = draw_frame(xmin, xmax, ymin, ymax, style);
|
||||
return Ok(svg_wrap(
|
||||
&format!(
|
||||
r#"{frame}<path d="{p1}" class="curve"/><path d="{p2}" class="curve"/>"#
|
||||
),
|
||||
"hyperbola",
|
||||
));
|
||||
}
|
||||
"parabola" => {
|
||||
let scale = if a.abs() > 1e-12 { a } else { 1.0 };
|
||||
for i in 0..=steps {
|
||||
let t = -3.0 + 6.0 * (i as f64) / (steps as f64);
|
||||
let x = h + t;
|
||||
let y = k + (t * t) / (4.0 * scale.abs()) * scale.signum();
|
||||
pts.push((x, y));
|
||||
}
|
||||
}
|
||||
other => return Err(format!("unknown conic kind `{other}`")),
|
||||
}
|
||||
|
||||
let xmin = pts.iter().map(|p| p.0).fold(f64::INFINITY, f64::min);
|
||||
let xmax = pts.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max);
|
||||
let ymin = pts.iter().map(|p| p.1).fold(f64::INFINITY, f64::min);
|
||||
let ymax = pts.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max);
|
||||
let (xmin, xmax) = pad_range(xmin, xmax);
|
||||
let (ymin, ymax) = pad_range(ymin, ymax);
|
||||
let path = polyline_path(&pts, xmin, xmax, ymin, ymax);
|
||||
let frame = draw_frame(xmin, xmax, ymin, ymax, style);
|
||||
Ok(svg_wrap(
|
||||
&format!(r#"{frame}<path d="{path}" class="curve"/>"#),
|
||||
kind,
|
||||
))
|
||||
}
|
||||
|
||||
fn pad_range(lo: f64, hi: f64) -> (f64, f64) {
|
||||
if (hi - lo).abs() < 1e-12 {
|
||||
(lo - 1.0, hi + 1.0)
|
||||
} else {
|
||||
let pad = 0.05 * (hi - lo);
|
||||
(lo - pad, hi + pad)
|
||||
}
|
||||
}
|
||||
|
||||
fn polyline_path(pts: &[(f64, f64)], xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> String {
|
||||
let mut path = String::new();
|
||||
for (i, (x, y)) in pts.iter().enumerate() {
|
||||
let (sx, sy) = map_xy(*x, *y, xmin, xmax, ymin, ymax);
|
||||
if i == 0 {
|
||||
path.push_str(&format!("M {sx:.2} {sy:.2}"));
|
||||
} else {
|
||||
path.push_str(&format!(" L {sx:.2} {sy:.2}"));
|
||||
}
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
fn map_xy(x: f64, y: f64, xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> (f64, f64) {
|
||||
let w = SVG_W - 2.0 * PAD;
|
||||
let h = SVG_H - 2.0 * PAD;
|
||||
let sx = PAD + (x - xmin) / (xmax - xmin) * w;
|
||||
let sy = PAD + (ymax - y) / (ymax - ymin) * h;
|
||||
(sx, sy)
|
||||
}
|
||||
|
||||
fn nice_step(span: f64, target: usize) -> f64 {
|
||||
let target = target.max(2) as f64;
|
||||
let raw = (span / target).abs().max(1e-12);
|
||||
let exp = raw.log10().floor();
|
||||
let mag = 10f64.powf(exp);
|
||||
let norm = raw / mag;
|
||||
let nice = if norm <= 1.5 {
|
||||
1.0
|
||||
} else if norm <= 3.0 {
|
||||
2.0
|
||||
} else if norm <= 7.0 {
|
||||
5.0
|
||||
} else {
|
||||
10.0
|
||||
};
|
||||
nice * mag
|
||||
}
|
||||
|
||||
fn tick_values(lo: f64, hi: f64, step: f64) -> Vec<f64> {
|
||||
if step <= 0.0 || !step.is_finite() {
|
||||
return Vec::new();
|
||||
}
|
||||
let start = (lo / step).ceil() * step;
|
||||
let mut out = Vec::new();
|
||||
let mut v = start;
|
||||
let mut guard = 0;
|
||||
while v <= hi + step * 1e-9 && guard < 200 {
|
||||
if v >= lo - step * 1e-9 && v <= hi + step * 1e-9 {
|
||||
if v.abs() < step * 1e-9 {
|
||||
out.push(0.0);
|
||||
} else {
|
||||
out.push(v);
|
||||
}
|
||||
}
|
||||
v += step;
|
||||
guard += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn draw_frame(xmin: f64, xmax: f64, ymin: f64, ymax: f64, style: PlotStyle) -> String {
|
||||
let left = PAD;
|
||||
let right = SVG_W - PAD;
|
||||
let top = PAD;
|
||||
let bottom = SVG_H - PAD;
|
||||
|
||||
let (ox, _) = map_xy(0.0, 0.0, xmin, xmax, ymin, ymax);
|
||||
let (_, oy) = map_xy(0.0, 0.0, xmin, xmax, ymin, ymax);
|
||||
let axis_x_y = if ymin <= 0.0 && ymax >= 0.0 {
|
||||
oy.clamp(top, bottom)
|
||||
} else if ymax < 0.0 {
|
||||
top
|
||||
} else {
|
||||
bottom
|
||||
};
|
||||
let axis_y_x = if xmin <= 0.0 && xmax >= 0.0 {
|
||||
ox.clamp(left, right)
|
||||
} else if xmax < 0.0 {
|
||||
right
|
||||
} else {
|
||||
left
|
||||
};
|
||||
|
||||
let mut s = String::new();
|
||||
let x_step = nice_step(xmax - xmin, 8);
|
||||
let y_step = nice_step(ymax - ymin, 6);
|
||||
|
||||
if style.grid {
|
||||
for x in tick_values(xmin, xmax, x_step) {
|
||||
let (sx, _) = map_xy(x, 0.0, xmin, xmax, ymin, ymax);
|
||||
if sx < left - 0.5 || sx > right + 0.5 {
|
||||
continue;
|
||||
}
|
||||
s.push_str(&format!(
|
||||
r#"<line x1="{sx:.2}" y1="{top}" x2="{sx:.2}" y2="{bottom}" class="grid"/>"#
|
||||
));
|
||||
}
|
||||
for y in tick_values(ymin, ymax, y_step) {
|
||||
let (_, sy) = map_xy(0.0, y, xmin, xmax, ymin, ymax);
|
||||
if sy < top - 0.5 || sy > bottom + 0.5 {
|
||||
continue;
|
||||
}
|
||||
s.push_str(&format!(
|
||||
r#"<line x1="{left}" y1="{sy:.2}" x2="{right}" y2="{sy:.2}" class="grid"/>"#
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Axes with arrowheads (positive direction).
|
||||
s.push_str(&format!(
|
||||
r#"<line x1="{left}" y1="{axis_x_y:.2}" x2="{right}" y2="{axis_x_y:.2}" class="axis" marker-end="url(#arrow)"/>"#
|
||||
));
|
||||
s.push_str(&format!(
|
||||
r#"<line x1="{axis_y_x:.2}" y1="{bottom}" x2="{axis_y_x:.2}" y2="{top}" class="axis" marker-end="url(#arrow)"/>"#
|
||||
));
|
||||
|
||||
// Axis end labels
|
||||
s.push_str(&format!(
|
||||
r#"<text x="{x:.2}" y="{y:.2}" class="axis-label">x</text>"#,
|
||||
x = right + 4.0,
|
||||
y = axis_x_y + 4.0,
|
||||
));
|
||||
s.push_str(&format!(
|
||||
r#"<text x="{x:.2}" y="{y:.2}" class="axis-label">y</text>"#,
|
||||
x = axis_y_x + 6.0,
|
||||
y = top + 4.0,
|
||||
));
|
||||
|
||||
// Tick labels along axes (skip 0 clutter when both axes cross).
|
||||
for x in tick_values(xmin, xmax, x_step) {
|
||||
if x.abs() < x_step * 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let (sx, _) = map_xy(x, 0.0, xmin, xmax, ymin, ymax);
|
||||
if sx < left || sx > right {
|
||||
continue;
|
||||
}
|
||||
s.push_str(&format!(
|
||||
r#"<line x1="{sx:.2}" y1="{y1:.2}" x2="{sx:.2}" y2="{y2:.2}" class="tick"/>"#,
|
||||
y1 = axis_x_y - 4.0,
|
||||
y2 = axis_x_y + 4.0,
|
||||
));
|
||||
s.push_str(&format!(
|
||||
r#"<text x="{sx:.2}" y="{ty:.2}" text-anchor="middle" class="tick-label">{label}</text>"#,
|
||||
ty = (axis_x_y + 14.0).min(bottom + 14.0),
|
||||
label = super::format_num(x),
|
||||
));
|
||||
}
|
||||
for y in tick_values(ymin, ymax, y_step) {
|
||||
if y.abs() < y_step * 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let (_, sy) = map_xy(0.0, y, xmin, xmax, ymin, ymax);
|
||||
if sy < top || sy > bottom {
|
||||
continue;
|
||||
}
|
||||
s.push_str(&format!(
|
||||
r#"<line x1="{x1:.2}" y1="{sy:.2}" x2="{x2:.2}" y2="{sy:.2}" class="tick"/>"#,
|
||||
x1 = axis_y_x - 4.0,
|
||||
x2 = axis_y_x + 4.0,
|
||||
));
|
||||
s.push_str(&format!(
|
||||
r#"<text x="{tx:.2}" y="{sy:.2}" text-anchor="end" dominant-baseline="middle" class="tick-label">{label}</text>"#,
|
||||
tx = (axis_y_x - 8.0).max(4.0),
|
||||
label = super::format_num(y),
|
||||
));
|
||||
}
|
||||
|
||||
// Origin mark when visible
|
||||
if xmin <= 0.0 && xmax >= 0.0 && ymin <= 0.0 && ymax >= 0.0 {
|
||||
s.push_str(&format!(
|
||||
r#"<text x="{x:.2}" y="{y:.2}" class="tick-label">0</text>"#,
|
||||
x = axis_y_x - 8.0,
|
||||
y = axis_x_y + 14.0,
|
||||
));
|
||||
}
|
||||
|
||||
s
|
||||
}
|
||||
|
||||
fn svg_wrap(body: &str, title: &str) -> String {
|
||||
// r## so fill="#…" does not terminate the raw string at "#
|
||||
format!(
|
||||
r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" width="{w}" height="{h}" role="img" aria-label="{title}">
|
||||
<defs>
|
||||
<marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill="#4b5563"/>
|
||||
</marker>
|
||||
</defs>
|
||||
<style>
|
||||
.grid {{ stroke: #e5e7eb; stroke-width: 1; }}
|
||||
.axis {{ stroke: #4b5563; stroke-width: 1.5; }}
|
||||
.tick {{ stroke: #4b5563; stroke-width: 1; }}
|
||||
.curve {{ fill: none; stroke: #1f6feb; stroke-width: 2; }}
|
||||
.pt {{ fill: #1f6feb; }}
|
||||
.axis-label {{ font: 12px ui-sans-serif, system-ui, sans-serif; fill: #374151; font-weight: 600; }}
|
||||
.tick-label {{ font: 10px ui-sans-serif, system-ui, sans-serif; fill: #6b7280; }}
|
||||
</style>
|
||||
{body}
|
||||
</svg>"##,
|
||||
w = SVG_W,
|
||||
h = SVG_H,
|
||||
title = title,
|
||||
body = body,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::formula::parse;
|
||||
|
||||
#[test]
|
||||
fn plot_has_arrows_and_grid_by_default() {
|
||||
let e = parse("x^2").unwrap();
|
||||
let svg = plot_function_svg(&e, "x", -2.0, 2.0, 40, PlotStyle::default()).unwrap();
|
||||
assert!(svg.contains("marker-end=\"url(#arrow)\""));
|
||||
assert!(svg.contains("class=\"grid\""));
|
||||
assert!(svg.contains(">x</text>"));
|
||||
assert!(svg.contains(">y</text>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plot_can_disable_grid() {
|
||||
let e = parse("x").unwrap();
|
||||
let svg = plot_function_svg(&e, "x", -1.0, 1.0, 20, PlotStyle { grid: false }).unwrap();
|
||||
assert!(!svg.contains("class=\"grid\""));
|
||||
assert!(svg.contains("marker-end=\"url(#arrow)\""));
|
||||
}
|
||||
}
|
||||
Loaded 100 of 151 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user