├── .github └── workflows │ ├── rust-wasm-deploy.yml │ └── rust-wasm.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── examples ├── 00-simple.rs ├── 01-read.rs ├── 02-operators.rs ├── 03-group.rs ├── 04-if.rs ├── 05-var.rs ├── 06-multiline.rs ├── 07-function.rs └── 08-recurse.rs ├── rustfmt.toml ├── screenshots ├── koch.png └── wasm-screenshot.png ├── scripts ├── fibonacci.txt ├── for.txt ├── function.txt ├── if.txt └── recurse.txt ├── src ├── lib.rs └── main.rs └── wasm ├── .appveyor.yml ├── .cargo-ok ├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE_APACHE ├── LICENSE_MIT ├── README.md ├── index.html ├── js ├── index.js └── main.js ├── package-lock.json ├── package.json ├── scripts ├── canvas.txt ├── koch.txt ├── mandel_canvas.txt └── mandel_canvas_recursive.txt ├── src ├── lib.rs ├── utils.rs └── wasm_imports.rs ├── tests └── web.rs ├── wasm_api.js └── webpack.config.js /.github/workflows/rust-wasm-deploy.yml: -------------------------------------------------------------------------------- 1 | name: Rust-wasm-deploy 2 | 3 | 4 | on: 5 | push: 6 | branches: [ master ] 7 | 8 | env: 9 | CARGO_TERM_COLOR: always 10 | 11 | jobs: 12 | build: 13 | 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: wasm-pack-action 19 | uses: jetli/wasm-pack-action@v0.3.0 20 | #with: 21 | # Optional version of wasm-pack to install (eg. "v0.9.1", "latest") 22 | #version: # optional, default is latest 23 | - name: Use Node.js 10.x 24 | uses: actions/setup-node@v1 25 | with: 26 | node-version: 10.x 27 | - name: Build 28 | run: 29 | cd wasm && 30 | mkdir dist && 31 | npm ci && npm run build && 32 | cp -r ../scripts ./dist/scripts 33 | - name: Deploy 34 | uses: peaceiris/actions-gh-pages@v3 35 | with: 36 | github_token: ${{ secrets.GITHUB_TOKEN }} 37 | publish_dir: ./wasm/dist 38 | force_orphan: true 39 | -------------------------------------------------------------------------------- /.github/workflows/rust-wasm.yml: -------------------------------------------------------------------------------- 1 | name: Rust-wasm 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: wasm-pack-action 20 | uses: jetli/wasm-pack-action@v0.3.0 21 | #with: 22 | # Optional version of wasm-pack to install (eg. "v0.9.1", "latest") 23 | #version: # optional, default is latest 24 | - name: Build 25 | run: cd wasm && wasm-pack build --target web 26 | - name: Run tests 27 | run: cargo test --verbose 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "bumpalo" 7 | version = "3.11.0" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "c1ad822118d20d2c234f427000d5acc36eabe1e29a348c89b63dd60b13f28e5d" 10 | 11 | [[package]] 12 | name = "cfg-if" 13 | version = "1.0.0" 14 | source = "registry+https://github.com/rust-lang/crates.io-index" 15 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 16 | 17 | [[package]] 18 | name = "console_error_panic_hook" 19 | version = "0.1.7" 20 | source = "registry+https://github.com/rust-lang/crates.io-index" 21 | checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" 22 | dependencies = [ 23 | "cfg-if", 24 | "wasm-bindgen", 25 | ] 26 | 27 | [[package]] 28 | name = "itoa" 29 | version = "1.0.3" 30 | source = "registry+https://github.com/rust-lang/crates.io-index" 31 | checksum = "6c8af84674fe1f223a982c933a0ee1086ac4d4052aa0fb8060c12c6ad838e754" 32 | 33 | [[package]] 34 | name = "js-sys" 35 | version = "0.3.60" 36 | source = "registry+https://github.com/rust-lang/crates.io-index" 37 | checksum = "49409df3e3bf0856b916e2ceaca09ee28e6871cf7d9ce97a692cacfdb2a25a47" 38 | dependencies = [ 39 | "wasm-bindgen", 40 | ] 41 | 42 | [[package]] 43 | name = "log" 44 | version = "0.4.17" 45 | source = "registry+https://github.com/rust-lang/crates.io-index" 46 | checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" 47 | dependencies = [ 48 | "cfg-if", 49 | ] 50 | 51 | [[package]] 52 | name = "once_cell" 53 | version = "1.14.0" 54 | source = "registry+https://github.com/rust-lang/crates.io-index" 55 | checksum = "2f7254b99e31cad77da24b08ebf628882739a608578bb1bcdfc1f9c21260d7c0" 56 | 57 | [[package]] 58 | name = "proc-macro2" 59 | version = "1.0.43" 60 | source = "registry+https://github.com/rust-lang/crates.io-index" 61 | checksum = "0a2ca2c61bc9f3d74d2886294ab7b9853abd9c1ad903a3ac7815c58989bb7bab" 62 | dependencies = [ 63 | "unicode-ident", 64 | ] 65 | 66 | [[package]] 67 | name = "quote" 68 | version = "1.0.21" 69 | source = "registry+https://github.com/rust-lang/crates.io-index" 70 | checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" 71 | dependencies = [ 72 | "proc-macro2", 73 | ] 74 | 75 | [[package]] 76 | name = "rustack" 77 | version = "0.1.0" 78 | 79 | [[package]] 80 | name = "ryu" 81 | version = "1.0.11" 82 | source = "registry+https://github.com/rust-lang/crates.io-index" 83 | checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09" 84 | 85 | [[package]] 86 | name = "scoped-tls" 87 | version = "1.0.0" 88 | source = "registry+https://github.com/rust-lang/crates.io-index" 89 | checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" 90 | 91 | [[package]] 92 | name = "serde" 93 | version = "1.0.145" 94 | source = "registry+https://github.com/rust-lang/crates.io-index" 95 | checksum = "728eb6351430bccb993660dfffc5a72f91ccc1295abaa8ce19b27ebe4f75568b" 96 | dependencies = [ 97 | "serde_derive", 98 | ] 99 | 100 | [[package]] 101 | name = "serde_derive" 102 | version = "1.0.145" 103 | source = "registry+https://github.com/rust-lang/crates.io-index" 104 | checksum = "81fa1584d3d1bcacd84c277a0dfe21f5b0f6accf4a23d04d4c6d61f1af522b4c" 105 | dependencies = [ 106 | "proc-macro2", 107 | "quote", 108 | "syn", 109 | ] 110 | 111 | [[package]] 112 | name = "serde_json" 113 | version = "1.0.85" 114 | source = "registry+https://github.com/rust-lang/crates.io-index" 115 | checksum = "e55a28e3aaef9d5ce0506d0a14dbba8054ddc7e499ef522dd8b26859ec9d4a44" 116 | dependencies = [ 117 | "itoa", 118 | "ryu", 119 | "serde", 120 | ] 121 | 122 | [[package]] 123 | name = "syn" 124 | version = "1.0.99" 125 | source = "registry+https://github.com/rust-lang/crates.io-index" 126 | checksum = "58dbef6ec655055e20b86b15a8cc6d439cca19b667537ac6a1369572d151ab13" 127 | dependencies = [ 128 | "proc-macro2", 129 | "quote", 130 | "unicode-ident", 131 | ] 132 | 133 | [[package]] 134 | name = "unicode-ident" 135 | version = "1.0.4" 136 | source = "registry+https://github.com/rust-lang/crates.io-index" 137 | checksum = "dcc811dc4066ac62f84f11307873c4850cb653bfa9b1719cee2bd2204a4bc5dd" 138 | 139 | [[package]] 140 | name = "wasm" 141 | version = "0.1.0" 142 | dependencies = [ 143 | "console_error_panic_hook", 144 | "js-sys", 145 | "rustack", 146 | "serde", 147 | "serde_json", 148 | "wasm-bindgen", 149 | "wasm-bindgen-test", 150 | ] 151 | 152 | [[package]] 153 | name = "wasm-bindgen" 154 | version = "0.2.83" 155 | source = "registry+https://github.com/rust-lang/crates.io-index" 156 | checksum = "eaf9f5aceeec8be17c128b2e93e031fb8a4d469bb9c4ae2d7dc1888b26887268" 157 | dependencies = [ 158 | "cfg-if", 159 | "wasm-bindgen-macro", 160 | ] 161 | 162 | [[package]] 163 | name = "wasm-bindgen-backend" 164 | version = "0.2.83" 165 | source = "registry+https://github.com/rust-lang/crates.io-index" 166 | checksum = "4c8ffb332579b0557b52d268b91feab8df3615f265d5270fec2a8c95b17c1142" 167 | dependencies = [ 168 | "bumpalo", 169 | "log", 170 | "once_cell", 171 | "proc-macro2", 172 | "quote", 173 | "syn", 174 | "wasm-bindgen-shared", 175 | ] 176 | 177 | [[package]] 178 | name = "wasm-bindgen-futures" 179 | version = "0.4.33" 180 | source = "registry+https://github.com/rust-lang/crates.io-index" 181 | checksum = "23639446165ca5a5de86ae1d8896b737ae80319560fbaa4c2887b7da6e7ebd7d" 182 | dependencies = [ 183 | "cfg-if", 184 | "js-sys", 185 | "wasm-bindgen", 186 | "web-sys", 187 | ] 188 | 189 | [[package]] 190 | name = "wasm-bindgen-macro" 191 | version = "0.2.83" 192 | source = "registry+https://github.com/rust-lang/crates.io-index" 193 | checksum = "052be0f94026e6cbc75cdefc9bae13fd6052cdcaf532fa6c45e7ae33a1e6c810" 194 | dependencies = [ 195 | "quote", 196 | "wasm-bindgen-macro-support", 197 | ] 198 | 199 | [[package]] 200 | name = "wasm-bindgen-macro-support" 201 | version = "0.2.83" 202 | source = "registry+https://github.com/rust-lang/crates.io-index" 203 | checksum = "07bc0c051dc5f23e307b13285f9d75df86bfdf816c5721e573dec1f9b8aa193c" 204 | dependencies = [ 205 | "proc-macro2", 206 | "quote", 207 | "syn", 208 | "wasm-bindgen-backend", 209 | "wasm-bindgen-shared", 210 | ] 211 | 212 | [[package]] 213 | name = "wasm-bindgen-shared" 214 | version = "0.2.83" 215 | source = "registry+https://github.com/rust-lang/crates.io-index" 216 | checksum = "1c38c045535d93ec4f0b4defec448e4291638ee608530863b1e2ba115d4fff7f" 217 | 218 | [[package]] 219 | name = "wasm-bindgen-test" 220 | version = "0.3.33" 221 | source = "registry+https://github.com/rust-lang/crates.io-index" 222 | checksum = "09d2fff962180c3fadf677438054b1db62bee4aa32af26a45388af07d1287e1d" 223 | dependencies = [ 224 | "console_error_panic_hook", 225 | "js-sys", 226 | "scoped-tls", 227 | "wasm-bindgen", 228 | "wasm-bindgen-futures", 229 | "wasm-bindgen-test-macro", 230 | ] 231 | 232 | [[package]] 233 | name = "wasm-bindgen-test-macro" 234 | version = "0.3.33" 235 | source = "registry+https://github.com/rust-lang/crates.io-index" 236 | checksum = "4683da3dfc016f704c9f82cf401520c4f1cb3ee440f7f52b3d6ac29506a49ca7" 237 | dependencies = [ 238 | "proc-macro2", 239 | "quote", 240 | ] 241 | 242 | [[package]] 243 | name = "web-sys" 244 | version = "0.3.60" 245 | source = "registry+https://github.com/rust-lang/crates.io-index" 246 | checksum = "bcda906d8be16e728fd5adc5b729afad4e444e106ab28cd1c7256e54fa61510f" 247 | dependencies = [ 248 | "js-sys", 249 | "wasm-bindgen", 250 | ] 251 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustack" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | 10 | [workspace] 11 | members = [ "wasm" ] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Masahiro Sakuta 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rustack 2 | 3 | A very simple stack based language interpreter in Rust 4 | 5 | Try it now on your browser! 6 | https://msakuta.github.io/rustack/ 7 | 8 | 9 | ## Overview 10 | 11 | This repo is the implementation of the example script used in my book: 12 | [Rustで作るプログラミング言語](https://www.amazon.co.jp/dp/4297141922) (Japanese). 13 | 14 | This is a sister project of [mascal](https://github.com/msakuta/mascal), 15 | a custom programming language compiler / interpreter. 16 | 17 | It has integrated step execution feature that visualize the interpreter state at each execution step. 18 | 19 | ![screenshot-step-execution](screenshots/wasm-screenshot.png) 20 | 21 | The WebAssembly deployment has API access to canvas rendering similar to PostScript graphics, so you can write 22 | a program that can render something like below. 23 | This example is a rendering of [Koch curve](https://en.wikipedia.org/wiki/Koch_snowflake) which uses recursive calls. You can find the source in [source](wasm/scripts/koch.txt). 24 | 25 | ![koch](screenshots/koch.png) 26 | 27 | This rustack is stack based virtual machine similar to JVM, 28 | but it is particularly following the design of PostScript runtime. 29 | It uses reverse-polish notation for all operations and functions. 30 | 31 | For example, the following program will print `90`. 32 | 33 | ``` 34 | 10 20 + 3 * puts 35 | ``` 36 | 37 | There are example source files in [examples](examples), which is step-by-step procedure 38 | to implement such a language. 39 | Each example source file in `examples` directory is prefixed with a number, which indicates 40 | the step of the particular source file in the progress. 41 | 42 | A notable difference from PostScript is that the dictionary stack and the execution stack is 43 | the same, i.e. when you call a function, it will implicitly introduce a local namespace. 44 | 45 | ## Wasm demo 46 | 47 | As always, I prepared a Wasm interpreter that you can play around with in your browser. 48 | -------------------------------------------------------------------------------- /examples/00-simple.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut stack = vec![]; 3 | 4 | stack.push(42); 5 | stack.push(36); 6 | 7 | add(&mut stack); 8 | 9 | stack.push(22); 10 | 11 | add(&mut stack); 12 | 13 | println!("stack: {stack:?}"); 14 | } 15 | 16 | fn add(stack: &mut Vec) { 17 | let lhs = stack.pop().unwrap(); 18 | let rhs = stack.pop().unwrap(); 19 | stack.push(lhs + rhs); 20 | } 21 | -------------------------------------------------------------------------------- /examples/01-read.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | for line in std::io::stdin().lines() { 3 | let mut stack = vec![]; 4 | if let Ok(line) = line { 5 | let words: Vec<_> = line.split(" ").collect(); 6 | 7 | for word in words { 8 | if let Ok(parsed) = word.parse::() { 9 | stack.push(parsed); 10 | } else { 11 | match word { 12 | "+" => add(&mut stack), 13 | _ => panic!("{word:?} could not be parsed"), 14 | } 15 | } 16 | } 17 | 18 | println!("stack: {stack:?}"); 19 | } 20 | } 21 | } 22 | 23 | fn add(stack: &mut Vec) { 24 | let lhs = stack.pop().unwrap(); 25 | let rhs = stack.pop().unwrap(); 26 | stack.push(lhs + rhs); 27 | } 28 | -------------------------------------------------------------------------------- /examples/02-operators.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | for line in std::io::stdin().lines() { 3 | let mut stack = vec![]; 4 | if let Ok(line) = line { 5 | let words: Vec<_> = line.split(" ").collect(); 6 | 7 | for word in words { 8 | if let Ok(parsed) = word.parse::() { 9 | stack.push(parsed); 10 | } else { 11 | match word { 12 | "+" => add(&mut stack), 13 | "-" => sub(&mut stack), 14 | "*" => mul(&mut stack), 15 | "/" => div(&mut stack), 16 | _ => panic!("{word:?} could not be parsed"), 17 | } 18 | } 19 | } 20 | 21 | println!("stack: {stack:?}"); 22 | } 23 | } 24 | } 25 | 26 | fn add(stack: &mut Vec) { 27 | let rhs = stack.pop().unwrap(); 28 | let lhs = stack.pop().unwrap(); 29 | stack.push(lhs + rhs); 30 | } 31 | 32 | fn sub(stack: &mut Vec) { 33 | let rhs = stack.pop().unwrap(); 34 | let lhs = stack.pop().unwrap(); 35 | stack.push(lhs - rhs); 36 | } 37 | 38 | fn mul(stack: &mut Vec) { 39 | let rhs = stack.pop().unwrap(); 40 | let lhs = stack.pop().unwrap(); 41 | stack.push(lhs * rhs); 42 | } 43 | 44 | fn div(stack: &mut Vec) { 45 | let rhs = stack.pop().unwrap(); 46 | let lhs = stack.pop().unwrap(); 47 | stack.push(lhs / rhs); 48 | } 49 | -------------------------------------------------------------------------------- /examples/03-group.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug, PartialEq, Eq)] 2 | enum Value<'src> { 3 | Num(i32), 4 | Op(&'src str), 5 | Block(Vec>), 6 | } 7 | 8 | impl<'src> Value<'src> { 9 | fn as_num(&self) -> i32 { 10 | match self { 11 | Self::Num(val) => *val, 12 | _ => panic!("Value is not a number"), 13 | } 14 | } 15 | } 16 | 17 | fn main() { 18 | for line in std::io::stdin().lines().flatten() { 19 | parse(&line); 20 | } 21 | } 22 | 23 | fn parse<'a>(line: &'a str) -> Vec { 24 | let mut stack = vec![]; 25 | let input: Vec<_> = line.split(" ").collect(); 26 | let mut words = &input[..]; 27 | 28 | while let Some((&word, mut rest)) = words.split_first() { 29 | if word.is_empty() { 30 | break; 31 | } 32 | if word == "{" { 33 | let value; 34 | (value, rest) = parse_block(rest); 35 | stack.push(value); 36 | } else if let Ok(parsed) = word.parse::() { 37 | stack.push(Value::Num(parsed)); 38 | } else { 39 | match word { 40 | "+" => add(&mut stack), 41 | "-" => sub(&mut stack), 42 | "*" => mul(&mut stack), 43 | "/" => div(&mut stack), 44 | _ => panic!("{word:?} could not be parsed"), 45 | } 46 | } 47 | words = rest; 48 | } 49 | 50 | println!("stack: {stack:?}"); 51 | 52 | stack 53 | } 54 | 55 | fn parse_block<'src, 'a>( 56 | input: &'a [&'src str], 57 | ) -> (Value<'src>, &'a [&'src str]) { 58 | let mut tokens = vec![]; 59 | let mut words = input; 60 | 61 | while let Some((&word, mut rest)) = words.split_first() { 62 | if word.is_empty() { 63 | break; 64 | } 65 | if word == "{" { 66 | let value; 67 | (value, rest) = parse_block(rest); 68 | tokens.push(value); 69 | } else if word == "}" { 70 | return (Value::Block(tokens), rest); 71 | } else if let Ok(value) = word.parse::() { 72 | tokens.push(Value::Num(value)); 73 | } else { 74 | tokens.push(Value::Op(word)); 75 | } 76 | words = rest; 77 | } 78 | 79 | (Value::Block(tokens), words) 80 | } 81 | 82 | fn add(stack: &mut Vec) { 83 | let rhs = stack.pop().unwrap().as_num(); 84 | let lhs = stack.pop().unwrap().as_num(); 85 | stack.push(Value::Num(lhs + rhs)); 86 | } 87 | 88 | fn sub(stack: &mut Vec) { 89 | let rhs = stack.pop().unwrap().as_num(); 90 | let lhs = stack.pop().unwrap().as_num(); 91 | stack.push(Value::Num(lhs - rhs)); 92 | } 93 | 94 | fn mul(stack: &mut Vec) { 95 | let rhs = stack.pop().unwrap().as_num(); 96 | let lhs = stack.pop().unwrap().as_num(); 97 | stack.push(Value::Num(lhs * rhs)); 98 | } 99 | 100 | fn div(stack: &mut Vec) { 101 | let rhs = stack.pop().unwrap().as_num(); 102 | let lhs = stack.pop().unwrap().as_num(); 103 | stack.push(Value::Num(lhs / rhs)); 104 | } 105 | 106 | #[cfg(test)] 107 | mod test { 108 | use super::{parse, Value::*}; 109 | #[test] 110 | fn test_group() { 111 | assert_eq!( 112 | parse("1 2 + { 3 4 }"), 113 | vec![Num(3), Block(vec![Num(3), Num(4)])] 114 | ); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /examples/04-if.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug, Clone, PartialEq, Eq)] 2 | enum Value<'src> { 3 | Num(i32), 4 | Op(&'src str), 5 | Block(Vec>), 6 | } 7 | 8 | impl<'src> Value<'src> { 9 | fn as_num(&self) -> i32 { 10 | match self { 11 | Self::Num(val) => *val, 12 | _ => panic!("Value is not a number"), 13 | } 14 | } 15 | 16 | fn to_block(self) -> Vec> { 17 | match self { 18 | Self::Block(val) => val, 19 | _ => panic!("Value is not a block"), 20 | } 21 | } 22 | } 23 | 24 | fn main() { 25 | for line in std::io::stdin().lines().flatten() { 26 | parse(&line); 27 | } 28 | } 29 | 30 | fn parse<'a>(line: &'a str) -> Vec { 31 | let mut stack = vec![]; 32 | let input: Vec<_> = line.split(" ").collect(); 33 | let mut words = &input[..]; 34 | 35 | while let Some((&word, mut rest)) = words.split_first() { 36 | if word.is_empty() { 37 | break; 38 | } 39 | if word == "{" { 40 | let value; 41 | (value, rest) = parse_block(rest); 42 | stack.push(value); 43 | } else { 44 | let code = if let Ok(num) = word.parse::() { 45 | Value::Num(num) 46 | } else { 47 | Value::Op(word) 48 | }; 49 | eval(code, &mut stack); 50 | } 51 | words = rest; 52 | } 53 | 54 | println!("stack: {stack:?}"); 55 | 56 | stack 57 | } 58 | 59 | fn eval<'src>(code: Value<'src>, stack: &mut Vec>) { 60 | match code { 61 | Value::Op(op) => match op { 62 | "+" => add(stack), 63 | "-" => sub(stack), 64 | "*" => mul(stack), 65 | "/" => div(stack), 66 | "if" => op_if(stack), 67 | _ => panic!("{op:?} could not be parsed"), 68 | }, 69 | _ => stack.push(code.clone()), 70 | } 71 | } 72 | 73 | fn parse_block<'src, 'a>( 74 | input: &'a [&'src str], 75 | ) -> (Value<'src>, &'a [&'src str]) { 76 | let mut tokens = vec![]; 77 | let mut words = input; 78 | 79 | while let Some((&word, mut rest)) = words.split_first() { 80 | if word.is_empty() { 81 | break; 82 | } 83 | if word == "{" { 84 | let value; 85 | (value, rest) = parse_block(rest); 86 | tokens.push(value); 87 | } else if word == "}" { 88 | return (Value::Block(tokens), rest); 89 | } else if let Ok(value) = word.parse::() { 90 | tokens.push(Value::Num(value)); 91 | } else { 92 | tokens.push(Value::Op(word)); 93 | } 94 | words = rest; 95 | } 96 | 97 | (Value::Block(tokens), words) 98 | } 99 | 100 | fn add(stack: &mut Vec) { 101 | let rhs = stack.pop().unwrap().as_num(); 102 | let lhs = stack.pop().unwrap().as_num(); 103 | stack.push(Value::Num(lhs + rhs)); 104 | } 105 | 106 | fn sub(stack: &mut Vec) { 107 | let rhs = stack.pop().unwrap().as_num(); 108 | let lhs = stack.pop().unwrap().as_num(); 109 | stack.push(Value::Num(lhs - rhs)); 110 | } 111 | 112 | fn mul(stack: &mut Vec) { 113 | let rhs = stack.pop().unwrap().as_num(); 114 | let lhs = stack.pop().unwrap().as_num(); 115 | stack.push(Value::Num(lhs * rhs)); 116 | } 117 | 118 | fn div(stack: &mut Vec) { 119 | let rhs = stack.pop().unwrap().as_num(); 120 | let lhs = stack.pop().unwrap().as_num(); 121 | stack.push(Value::Num(lhs / rhs)); 122 | } 123 | 124 | fn op_if(stack: &mut Vec) { 125 | let false_branch = stack.pop().unwrap().to_block(); 126 | let true_branch = stack.pop().unwrap().to_block(); 127 | let cond = stack.pop().unwrap().to_block(); 128 | 129 | for code in cond { 130 | eval(code, stack); 131 | } 132 | 133 | let cond_result = stack.pop().unwrap().as_num(); 134 | 135 | if cond_result != 0 { 136 | for code in true_branch { 137 | eval(code, stack); 138 | } 139 | } else { 140 | for code in false_branch { 141 | eval(code, stack); 142 | } 143 | } 144 | } 145 | 146 | #[cfg(test)] 147 | mod test { 148 | use super::{parse, Value::*}; 149 | 150 | #[test] 151 | fn test_group() { 152 | assert_eq!( 153 | parse("1 2 + { 3 4 }"), 154 | vec![Num(3), Block(vec![Num(3), Num(4)])] 155 | ); 156 | } 157 | 158 | #[test] 159 | fn test_if_false() { 160 | assert_eq!( 161 | parse("{ 1 -1 + } { 100 } { -100 } if"), 162 | vec![Num(-100)] 163 | ); 164 | } 165 | 166 | #[test] 167 | fn test_if_true() { 168 | assert_eq!( 169 | parse("{ 1 1 + } { 100 } { -100 } if"), 170 | vec![Num(100)] 171 | ); 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /examples/05-var.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | #[derive(Debug, Clone, PartialEq, Eq)] 4 | enum Value<'src> { 5 | Num(i32), 6 | Op(&'src str), 7 | Sym(&'src str), 8 | Block(Vec>), 9 | } 10 | 11 | impl<'src> Value<'src> { 12 | fn as_num(&self) -> i32 { 13 | match self { 14 | Self::Num(val) => *val, 15 | _ => panic!("Value is not a number"), 16 | } 17 | } 18 | 19 | fn to_block(self) -> Vec> { 20 | match self { 21 | Self::Block(val) => val, 22 | _ => panic!("Value is not a block"), 23 | } 24 | } 25 | 26 | fn as_sym(&self) -> &'src str { 27 | if let Self::Sym(sym) = self { 28 | *sym 29 | } else { 30 | panic!("Value is not a symbol"); 31 | } 32 | } 33 | } 34 | 35 | struct Vm<'src> { 36 | stack: Vec>, 37 | vars: HashMap<&'src str, Value<'src>>, 38 | } 39 | 40 | impl<'src> Vm<'src> { 41 | fn new() -> Self { 42 | Self { 43 | stack: vec![], 44 | vars: HashMap::new(), 45 | } 46 | } 47 | } 48 | 49 | fn main() { 50 | for line in std::io::stdin().lines().flatten() { 51 | parse(&line); 52 | } 53 | } 54 | 55 | fn parse<'a>(line: &'a str) -> Vec { 56 | let mut vm = Vm::new(); 57 | let input: Vec<_> = line.split(" ").collect(); 58 | let mut words = &input[..]; 59 | 60 | while let Some((&word, mut rest)) = words.split_first() { 61 | if word.is_empty() { 62 | break; 63 | } 64 | if word == "{" { 65 | let value; 66 | (value, rest) = parse_block(rest); 67 | vm.stack.push(value); 68 | } else { 69 | let code = if let Ok(num) = word.parse::() { 70 | Value::Num(num) 71 | } else if word.starts_with("/") { 72 | Value::Sym(&word[1..]) 73 | } else { 74 | Value::Op(word) 75 | }; 76 | eval(code, &mut vm); 77 | } 78 | words = rest; 79 | } 80 | 81 | println!("stack: {:?}", vm.stack); 82 | 83 | vm.stack 84 | } 85 | 86 | fn eval<'src>(code: Value<'src>, vm: &mut Vm<'src>) { 87 | match code { 88 | Value::Op(op) => match op { 89 | "+" => add(&mut vm.stack), 90 | "-" => sub(&mut vm.stack), 91 | "*" => mul(&mut vm.stack), 92 | "/" => div(&mut vm.stack), 93 | "<" => lt(&mut vm.stack), 94 | "if" => op_if(vm), 95 | "def" => op_def(vm), 96 | _ => { 97 | let val = vm.vars.get(op).expect(&format!( 98 | "{op:?} is not a defined operation" 99 | )); 100 | vm.stack.push(val.clone()); 101 | } 102 | }, 103 | _ => vm.stack.push(code.clone()), 104 | } 105 | } 106 | 107 | fn parse_block<'src, 'a>( 108 | input: &'a [&'src str], 109 | ) -> (Value<'src>, &'a [&'src str]) { 110 | let mut tokens = vec![]; 111 | let mut words = input; 112 | 113 | while let Some((&word, mut rest)) = words.split_first() { 114 | if word.is_empty() { 115 | break; 116 | } 117 | if word == "{" { 118 | let value; 119 | (value, rest) = parse_block(rest); 120 | tokens.push(value); 121 | } else if word == "}" { 122 | return (Value::Block(tokens), rest); 123 | } else if let Ok(value) = word.parse::() { 124 | tokens.push(Value::Num(value)); 125 | } else { 126 | tokens.push(Value::Op(word)); 127 | } 128 | words = rest; 129 | } 130 | 131 | (Value::Block(tokens), words) 132 | } 133 | 134 | macro_rules! impl_op { 135 | {$name:ident, $op:tt} => { 136 | fn $name(stack: &mut Vec) { 137 | let rhs = stack.pop().unwrap().as_num(); 138 | let lhs = stack.pop().unwrap().as_num(); 139 | stack.push(Value::Num((lhs $op rhs) as i32)); 140 | } 141 | } 142 | } 143 | 144 | impl_op!(add, +); 145 | impl_op!(sub, -); 146 | impl_op!(mul, *); 147 | impl_op!(div, /); 148 | impl_op!(lt, <); 149 | 150 | fn op_if(vm: &mut Vm) { 151 | let false_branch = vm.stack.pop().unwrap().to_block(); 152 | let true_branch = vm.stack.pop().unwrap().to_block(); 153 | let cond = vm.stack.pop().unwrap().to_block(); 154 | 155 | for code in cond { 156 | eval(code, vm); 157 | } 158 | 159 | let cond_result = vm.stack.pop().unwrap().as_num(); 160 | 161 | if cond_result != 0 { 162 | for code in true_branch { 163 | eval(code, vm); 164 | } 165 | } else { 166 | for code in false_branch { 167 | eval(code, vm); 168 | } 169 | } 170 | } 171 | 172 | fn op_def(vm: &mut Vm) { 173 | let value = vm.stack.pop().unwrap(); 174 | eval(value, vm); 175 | let value = vm.stack.pop().unwrap(); 176 | let sym = vm.stack.pop().unwrap().as_sym(); 177 | 178 | vm.vars.insert(sym, value); 179 | } 180 | 181 | #[cfg(test)] 182 | mod test { 183 | use super::{parse, Value::*}; 184 | 185 | #[test] 186 | fn test_group() { 187 | assert_eq!( 188 | parse("1 2 + { 3 4 }"), 189 | vec![Num(3), Block(vec![Num(3), Num(4)])] 190 | ); 191 | } 192 | 193 | #[test] 194 | fn test_if_false() { 195 | assert_eq!( 196 | parse("{ 1 -1 + } { 100 } { -100 } if"), 197 | vec![Num(-100)] 198 | ); 199 | } 200 | 201 | #[test] 202 | fn test_if_true() { 203 | assert_eq!( 204 | parse("{ 1 1 + } { 100 } { -100 } if"), 205 | vec![Num(100)] 206 | ); 207 | } 208 | 209 | #[test] 210 | fn test_var() { 211 | assert_eq!( 212 | parse("/x 10 def /y 20 def x y *"), 213 | vec![Num(200)] 214 | ); 215 | } 216 | 217 | #[test] 218 | fn test_var_if() { 219 | assert_eq!( 220 | parse("/x 10 def /y 20 def { x y < } { x } { y } if"), 221 | vec![Num(10)] 222 | ); 223 | } 224 | } 225 | -------------------------------------------------------------------------------- /examples/06-multiline.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | collections::HashMap, 3 | io::{BufRead, BufReader}, 4 | }; 5 | 6 | #[derive(Debug, Clone, PartialEq, Eq)] 7 | enum Value { 8 | Num(i32), 9 | Op(String), 10 | Sym(String), 11 | Block(Vec), 12 | } 13 | 14 | impl Value { 15 | fn as_num(&self) -> i32 { 16 | match self { 17 | Self::Num(val) => *val, 18 | _ => panic!("Value is not a number"), 19 | } 20 | } 21 | 22 | fn to_block(self) -> Vec { 23 | match self { 24 | Self::Block(val) => val, 25 | _ => panic!("Value is not a block"), 26 | } 27 | } 28 | 29 | fn as_sym(&self) -> &str { 30 | if let Self::Sym(sym) = self { 31 | sym 32 | } else { 33 | panic!("Value is not a symbol"); 34 | } 35 | } 36 | 37 | fn to_string(&self) -> String { 38 | match self { 39 | Self::Num(i) => i.to_string(), 40 | Self::Op(ref s) | Self::Sym(ref s) => s.clone(), 41 | Self::Block(_) => "".to_string(), 42 | } 43 | } 44 | } 45 | 46 | struct Vm { 47 | stack: Vec, 48 | vars: HashMap, 49 | blocks: Vec>, 50 | } 51 | 52 | impl Vm { 53 | fn new() -> Self { 54 | Self { 55 | stack: vec![], 56 | vars: HashMap::new(), 57 | blocks: vec![], 58 | } 59 | } 60 | } 61 | 62 | fn main() { 63 | if let Some(f) = std::env::args() 64 | .nth(1) 65 | .and_then(|f| std::fs::File::open(f).ok()) 66 | { 67 | parse_batch(BufReader::new(f)); 68 | } else { 69 | parse_interactive(); 70 | } 71 | } 72 | 73 | fn parse_batch(source: impl BufRead) -> Vec { 74 | let mut vm = Vm::new(); 75 | for line in source.lines().flatten() { 76 | for word in line.split(" ") { 77 | parse_word(word, &mut vm); 78 | } 79 | } 80 | vm.stack 81 | } 82 | 83 | fn parse_interactive() { 84 | let mut vm = Vm::new(); 85 | for line in std::io::stdin().lines().flatten() { 86 | for word in line.split(" ") { 87 | parse_word(word, &mut vm); 88 | } 89 | println!("stack: {:?}", vm.stack); 90 | } 91 | } 92 | 93 | fn parse_word(word: &str, vm: &mut Vm) { 94 | if word.is_empty() { 95 | return; 96 | } 97 | if word == "{" { 98 | vm.blocks.push(vec![]); 99 | } else if word == "}" { 100 | let top_block = 101 | vm.blocks.pop().expect("Block stack underrun!"); 102 | eval(Value::Block(top_block), vm); 103 | } else { 104 | let code = if let Ok(num) = word.parse::() { 105 | Value::Num(num) 106 | } else if word.starts_with("/") { 107 | Value::Sym(word[1..].to_string()) 108 | } else { 109 | Value::Op(word.to_string()) 110 | }; 111 | eval(code, vm); 112 | } 113 | } 114 | 115 | fn eval(code: Value, vm: &mut Vm) { 116 | if let Some(top_block) = vm.blocks.last_mut() { 117 | top_block.push(code); 118 | return; 119 | } 120 | match code { 121 | Value::Op(ref op) => match op as &str { 122 | "+" => add(&mut vm.stack), 123 | "-" => sub(&mut vm.stack), 124 | "*" => mul(&mut vm.stack), 125 | "/" => div(&mut vm.stack), 126 | "<" => lt(&mut vm.stack), 127 | "if" => op_if(vm), 128 | "def" => op_def(vm), 129 | "puts" => puts(vm), 130 | _ => { 131 | let val = vm.vars.get(op).expect(&format!( 132 | "{op:?} is not a defined operation" 133 | )); 134 | vm.stack.push(val.clone()); 135 | } 136 | }, 137 | _ => vm.stack.push(code.clone()), 138 | } 139 | } 140 | 141 | macro_rules! impl_op { 142 | {$name:ident, $op:tt} => { 143 | fn $name(stack: &mut Vec) { 144 | let rhs = stack.pop().unwrap().as_num(); 145 | let lhs = stack.pop().unwrap().as_num(); 146 | stack.push(Value::Num((lhs $op rhs) as i32)); 147 | } 148 | } 149 | } 150 | 151 | impl_op!(add, +); 152 | impl_op!(sub, -); 153 | impl_op!(mul, *); 154 | impl_op!(div, /); 155 | impl_op!(lt, <); 156 | 157 | fn op_if(vm: &mut Vm) { 158 | let false_branch = vm.stack.pop().unwrap().to_block(); 159 | let true_branch = vm.stack.pop().unwrap().to_block(); 160 | let cond = vm.stack.pop().unwrap().to_block(); 161 | 162 | for code in cond { 163 | eval(code, vm); 164 | } 165 | 166 | let cond_result = vm.stack.pop().unwrap().as_num(); 167 | 168 | if cond_result != 0 { 169 | for code in true_branch { 170 | eval(code, vm); 171 | } 172 | } else { 173 | for code in false_branch { 174 | eval(code, vm); 175 | } 176 | } 177 | } 178 | 179 | fn op_def(vm: &mut Vm) { 180 | let value = vm.stack.pop().unwrap(); 181 | eval(value, vm); 182 | let value = vm.stack.pop().unwrap(); 183 | let sym = vm.stack.pop().unwrap().as_sym().to_string(); 184 | 185 | vm.vars.insert(sym, value); 186 | } 187 | 188 | fn puts(vm: &mut Vm) { 189 | let value = vm.stack.pop().unwrap(); 190 | println!("{}", value.to_string()); 191 | } 192 | 193 | #[cfg(test)] 194 | mod test { 195 | use super::{Value::*, *}; 196 | use std::io::Cursor; 197 | 198 | fn parse(input: &str) -> Vec { 199 | parse_batch(Cursor::new(input)) 200 | } 201 | 202 | #[test] 203 | fn test_group() { 204 | assert_eq!( 205 | parse("1 2 + { 3 4 }"), 206 | vec![Num(3), Block(vec![Num(3), Num(4)])] 207 | ); 208 | } 209 | 210 | #[test] 211 | fn test_if_false() { 212 | assert_eq!( 213 | parse("{ 1 -1 + } { 100 } { -100 } if"), 214 | vec![Num(-100)] 215 | ); 216 | } 217 | 218 | #[test] 219 | fn test_if_true() { 220 | assert_eq!( 221 | parse("{ 1 1 + } { 100 } { -100 } if"), 222 | vec![Num(100)] 223 | ); 224 | } 225 | 226 | #[test] 227 | fn test_var() { 228 | assert_eq!( 229 | parse("/x 10 def /y 20 def x y *"), 230 | vec![Num(200)] 231 | ); 232 | } 233 | 234 | #[test] 235 | fn test_var_if() { 236 | assert_eq!( 237 | parse("/x 10 def /y 20 def { x y < } { x } { y } if"), 238 | vec![Num(10)] 239 | ); 240 | } 241 | 242 | #[test] 243 | fn test_multiline() { 244 | assert_eq!( 245 | parse( 246 | r#" 247 | /x 10 def 248 | /y 20 def 249 | 250 | { x y < } 251 | { x } 252 | { y } 253 | if 254 | "# 255 | ), 256 | vec![Num(10)] 257 | ); 258 | } 259 | } 260 | -------------------------------------------------------------------------------- /examples/07-function.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | collections::HashMap, 3 | io::{BufRead, BufReader}, 4 | }; 5 | 6 | #[derive(Debug, Clone, PartialEq, Eq)] 7 | enum Value { 8 | Num(i32), 9 | Op(String), 10 | Sym(String), 11 | Block(Vec), 12 | Native(NativeOp), 13 | } 14 | 15 | impl Value { 16 | fn as_num(&self) -> i32 { 17 | match self { 18 | Self::Num(val) => *val, 19 | _ => panic!("Value is not a number"), 20 | } 21 | } 22 | 23 | fn to_block(self) -> Vec { 24 | match self { 25 | Self::Block(val) => val, 26 | _ => panic!("Value is not a block"), 27 | } 28 | } 29 | 30 | fn as_sym(&self) -> &str { 31 | if let Self::Sym(sym) = self { 32 | sym 33 | } else { 34 | panic!("Value is not a symbol"); 35 | } 36 | } 37 | 38 | fn to_string(&self) -> String { 39 | match self { 40 | Self::Num(i) => i.to_string(), 41 | Self::Op(ref s) | Self::Sym(ref s) => s.clone(), 42 | Self::Block(_) => "".to_string(), 43 | Self::Native(_) => "".to_string(), 44 | } 45 | } 46 | } 47 | 48 | #[derive(Clone)] 49 | struct NativeOp(fn(&mut Vm)); 50 | 51 | impl PartialEq for NativeOp { 52 | fn eq(&self, other: &NativeOp) -> bool { 53 | self.0 as *const fn() == other.0 as *const fn() 54 | } 55 | } 56 | 57 | impl Eq for NativeOp {} 58 | 59 | impl std::fmt::Debug for NativeOp { 60 | fn fmt( 61 | &self, 62 | f: &mut std::fmt::Formatter<'_>, 63 | ) -> std::fmt::Result { 64 | write!(f, "") 65 | } 66 | } 67 | 68 | struct Vm { 69 | stack: Vec, 70 | vars: HashMap, 71 | blocks: Vec>, 72 | } 73 | 74 | impl Vm { 75 | fn new() -> Self { 76 | let functions: [(&str, fn(&mut Vm)); 12] = [ 77 | ("+", add), 78 | ("-", sub), 79 | ("*", mul), 80 | ("/", div), 81 | ("<", lt), 82 | ("if", op_if), 83 | ("def", op_def), 84 | ("puts", puts), 85 | ("pop", pop), 86 | ("dup", dup), 87 | ("exch", exch), 88 | ("index", index), 89 | ]; 90 | Self { 91 | stack: vec![], 92 | vars: functions 93 | .into_iter() 94 | .map(|(name, fun)| { 95 | (name.to_owned(), Value::Native(NativeOp(fun))) 96 | }) 97 | .collect(), 98 | blocks: vec![], 99 | } 100 | } 101 | } 102 | 103 | fn main() { 104 | if let Some(f) = std::env::args() 105 | .nth(1) 106 | .and_then(|f| std::fs::File::open(f).ok()) 107 | { 108 | parse_batch(BufReader::new(f)); 109 | } else { 110 | parse_interactive(); 111 | } 112 | } 113 | 114 | fn parse_batch(source: impl BufRead) -> Vec { 115 | let mut vm = Vm::new(); 116 | for line in source.lines().flatten() { 117 | for word in line.split(" ") { 118 | parse_word(word, &mut vm); 119 | } 120 | } 121 | vm.stack 122 | } 123 | 124 | fn parse_interactive() { 125 | let mut vm = Vm::new(); 126 | for line in std::io::stdin().lines().flatten() { 127 | for word in line.split(" ") { 128 | parse_word(word, &mut vm); 129 | } 130 | println!("stack: {:?}", vm.stack); 131 | } 132 | } 133 | 134 | fn parse_word(word: &str, vm: &mut Vm) { 135 | if word.is_empty() { 136 | return; 137 | } 138 | if word == "{" { 139 | vm.blocks.push(vec![]); 140 | } else if word == "}" { 141 | let top_block = 142 | vm.blocks.pop().expect("Block stack underflow!"); 143 | eval(Value::Block(top_block), vm); 144 | } else { 145 | let code = if let Ok(num) = word.parse::() { 146 | Value::Num(num) 147 | } else if word.starts_with("/") { 148 | Value::Sym(word[1..].to_string()) 149 | } else { 150 | Value::Op(word.to_string()) 151 | }; 152 | eval(code, vm); 153 | } 154 | } 155 | 156 | fn eval(code: Value, vm: &mut Vm) { 157 | if let Some(top_block) = vm.blocks.last_mut() { 158 | top_block.push(code); 159 | return; 160 | } 161 | if let Value::Op(ref op) = code { 162 | let val = vm 163 | .vars 164 | .get(op) 165 | .expect(&format!("{op:?} is not a defined operation")) 166 | .clone(); 167 | match val { 168 | Value::Block(block) => { 169 | for code in block { 170 | eval(code, vm); 171 | } 172 | } 173 | Value::Native(op) => op.0(vm), 174 | _ => vm.stack.push(val), 175 | } 176 | } else { 177 | vm.stack.push(code.clone()); 178 | } 179 | } 180 | 181 | macro_rules! impl_op { 182 | {$name:ident, $op:tt} => { 183 | fn $name(vm: &mut Vm) { 184 | let rhs = vm.stack.pop().unwrap().as_num(); 185 | let lhs = vm.stack.pop().unwrap().as_num(); 186 | vm.stack.push(Value::Num((lhs $op rhs) as i32)); 187 | } 188 | } 189 | } 190 | 191 | impl_op!(add, +); 192 | impl_op!(sub, -); 193 | impl_op!(mul, *); 194 | impl_op!(div, /); 195 | impl_op!(lt, <); 196 | 197 | fn op_if(vm: &mut Vm) { 198 | let false_branch = vm.stack.pop().unwrap().to_block(); 199 | let true_branch = vm.stack.pop().unwrap().to_block(); 200 | let cond = vm.stack.pop().unwrap().to_block(); 201 | 202 | for code in cond { 203 | eval(code, vm); 204 | } 205 | 206 | let cond_result = vm.stack.pop().unwrap().as_num(); 207 | 208 | if cond_result != 0 { 209 | for code in true_branch { 210 | eval(code, vm); 211 | } 212 | } else { 213 | for code in false_branch { 214 | eval(code, vm); 215 | } 216 | } 217 | } 218 | 219 | fn op_def(vm: &mut Vm) { 220 | let value = vm.stack.pop().unwrap(); 221 | eval(value, vm); 222 | let value = vm.stack.pop().unwrap(); 223 | let sym = vm.stack.pop().unwrap().as_sym().to_string(); 224 | 225 | vm.vars.insert(sym, value); 226 | } 227 | 228 | fn puts(vm: &mut Vm) { 229 | let value = vm.stack.pop().unwrap(); 230 | println!("{}", value.to_string()); 231 | } 232 | 233 | fn pop(vm: &mut Vm) { 234 | vm.stack.pop().unwrap(); 235 | } 236 | 237 | fn dup(vm: &mut Vm) { 238 | let value = vm.stack.last().unwrap(); 239 | vm.stack.push(value.clone()); 240 | } 241 | 242 | fn exch(vm: &mut Vm) { 243 | let last = vm.stack.pop().unwrap(); 244 | let second = vm.stack.pop().unwrap(); 245 | vm.stack.push(last); 246 | vm.stack.push(second); 247 | } 248 | 249 | fn index(vm: &mut Vm) { 250 | let index = vm.stack.pop().unwrap().as_num() as usize; 251 | let value = vm.stack[vm.stack.len() - index - 1].clone(); 252 | vm.stack.push(value); 253 | } 254 | 255 | #[cfg(test)] 256 | mod test { 257 | use super::{Value::*, *}; 258 | use std::io::Cursor; 259 | 260 | fn parse(input: &str) -> Vec { 261 | parse_batch(Cursor::new(input)) 262 | } 263 | 264 | #[test] 265 | fn test_group() { 266 | assert_eq!( 267 | parse("1 2 + { 3 4 }"), 268 | vec![Num(3), Block(vec![Num(3), Num(4)])] 269 | ); 270 | } 271 | 272 | #[test] 273 | fn test_if_false() { 274 | assert_eq!( 275 | parse("{ 1 -1 + } { 100 } { -100 } if"), 276 | vec![Num(-100)] 277 | ); 278 | } 279 | 280 | #[test] 281 | fn test_if_true() { 282 | assert_eq!( 283 | parse("{ 1 1 + } { 100 } { -100 } if"), 284 | vec![Num(100)] 285 | ); 286 | } 287 | 288 | #[test] 289 | fn test_var() { 290 | assert_eq!( 291 | parse("/x 10 def /y 20 def x y *"), 292 | vec![Num(200)] 293 | ); 294 | } 295 | 296 | #[test] 297 | fn test_var_if() { 298 | assert_eq!( 299 | parse("/x 10 def /y 20 def { x y < } { x } { y } if"), 300 | vec![Num(10)] 301 | ); 302 | } 303 | 304 | #[test] 305 | fn test_multiline() { 306 | assert_eq!( 307 | parse( 308 | r#" 309 | /x 10 def 310 | /y 20 def 311 | 312 | { x y < } 313 | { x } 314 | { y } 315 | if 316 | "# 317 | ), 318 | vec![Num(10)] 319 | ); 320 | } 321 | 322 | #[test] 323 | fn test_function() { 324 | assert_eq!( 325 | parse( 326 | r#" 327 | /double { 2 * } def 328 | 10 double"# 329 | ), 330 | vec![Num(20)] 331 | ); 332 | } 333 | } 334 | -------------------------------------------------------------------------------- /examples/08-recurse.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | collections::HashMap, 3 | io::{BufRead, BufReader}, 4 | }; 5 | 6 | #[derive(Debug, Clone, PartialEq, Eq)] 7 | enum Value { 8 | Num(i32), 9 | Op(String), 10 | Sym(String), 11 | Block(Vec), 12 | Native(NativeOp), 13 | } 14 | 15 | impl Value { 16 | fn as_num(&self) -> i32 { 17 | match self { 18 | Self::Num(val) => *val, 19 | _ => panic!("Value is not a number"), 20 | } 21 | } 22 | 23 | fn to_block(self) -> Vec { 24 | match self { 25 | Self::Block(val) => val, 26 | _ => panic!("Value is not a block"), 27 | } 28 | } 29 | 30 | fn as_sym(&self) -> &str { 31 | if let Self::Sym(sym) = self { 32 | sym 33 | } else { 34 | panic!("Value is not a symbol"); 35 | } 36 | } 37 | 38 | fn to_string(&self) -> String { 39 | match self { 40 | Self::Num(i) => i.to_string(), 41 | Self::Op(ref s) | Self::Sym(ref s) => s.clone(), 42 | Self::Block(_) => "".to_string(), 43 | Self::Native(_) => "".to_string(), 44 | } 45 | } 46 | } 47 | 48 | #[derive(Clone)] 49 | struct NativeOp(fn(&mut Vm)); 50 | 51 | impl PartialEq for NativeOp { 52 | fn eq(&self, other: &NativeOp) -> bool { 53 | self.0 as *const fn() == other.0 as *const fn() 54 | } 55 | } 56 | 57 | impl Eq for NativeOp {} 58 | 59 | impl std::fmt::Debug for NativeOp { 60 | fn fmt( 61 | &self, 62 | f: &mut std::fmt::Formatter<'_>, 63 | ) -> std::fmt::Result { 64 | write!(f, "") 65 | } 66 | } 67 | 68 | struct Vm { 69 | stack: Vec, 70 | vars: Vec>, 71 | blocks: Vec>, 72 | } 73 | 74 | impl Vm { 75 | fn new() -> Self { 76 | let functions: [(&str, fn(&mut Vm)); 12] = [ 77 | ("+", add), 78 | ("-", sub), 79 | ("*", mul), 80 | ("/", div), 81 | ("<", lt), 82 | ("if", op_if), 83 | ("def", op_def), 84 | ("puts", puts), 85 | ("pop", pop), 86 | ("dup", dup), 87 | ("exch", exch), 88 | ("index", index), 89 | ]; 90 | Self { 91 | stack: vec![], 92 | vars: vec![functions 93 | .into_iter() 94 | .map(|(name, fun)| { 95 | (name.to_owned(), Value::Native(NativeOp(fun))) 96 | }) 97 | .collect()], 98 | blocks: vec![], 99 | } 100 | } 101 | 102 | fn find_var(&self, name: &str) -> Option { 103 | self 104 | .vars 105 | .iter() 106 | .rev() 107 | .find_map(|vars| vars.get(name).map(|var| var.to_owned())) 108 | } 109 | } 110 | 111 | fn main() { 112 | if let Some(f) = std::env::args() 113 | .nth(1) 114 | .and_then(|f| std::fs::File::open(f).ok()) 115 | { 116 | parse_batch(BufReader::new(f)); 117 | } else { 118 | parse_interactive(); 119 | } 120 | } 121 | 122 | fn parse_batch(source: impl BufRead) -> Vec { 123 | let mut vm = Vm::new(); 124 | for line in source.lines().flatten() { 125 | for word in line.split(" ") { 126 | parse_word(word, &mut vm); 127 | } 128 | } 129 | vm.stack 130 | } 131 | 132 | fn parse_interactive() { 133 | let mut vm = Vm::new(); 134 | for line in std::io::stdin().lines().flatten() { 135 | for word in line.split(" ") { 136 | parse_word(word, &mut vm); 137 | } 138 | println!("stack: {:?}", vm.stack); 139 | } 140 | } 141 | 142 | fn parse_word(word: &str, vm: &mut Vm) { 143 | if word.is_empty() { 144 | return; 145 | } 146 | if word == "{" { 147 | vm.blocks.push(vec![]); 148 | } else if word == "}" { 149 | let top_block = 150 | vm.blocks.pop().expect("Block stack underflow!"); 151 | eval(Value::Block(top_block), vm); 152 | } else { 153 | let code = if let Ok(num) = word.parse::() { 154 | Value::Num(num) 155 | } else if word.starts_with("/") { 156 | Value::Sym(word[1..].to_string()) 157 | } else { 158 | Value::Op(word.to_string()) 159 | }; 160 | eval(code, vm); 161 | } 162 | } 163 | 164 | fn eval(code: Value, vm: &mut Vm) { 165 | if let Some(top_block) = vm.blocks.last_mut() { 166 | top_block.push(code); 167 | return; 168 | } 169 | if let Value::Op(ref op) = code { 170 | let val = vm 171 | .find_var(op) 172 | .expect(&format!("{op:?} is not a defined operation")); 173 | match val { 174 | Value::Block(block) => { 175 | vm.vars.push(HashMap::new()); 176 | for code in block { 177 | eval(code, vm); 178 | } 179 | vm.vars.pop(); 180 | } 181 | Value::Native(op) => op.0(vm), 182 | _ => vm.stack.push(val), 183 | } 184 | } else { 185 | vm.stack.push(code.clone()); 186 | } 187 | } 188 | 189 | macro_rules! impl_op { 190 | {$name:ident, $op:tt} => { 191 | fn $name(vm: &mut Vm) { 192 | let rhs = vm.stack.pop().unwrap().as_num(); 193 | let lhs = vm.stack.pop().unwrap().as_num(); 194 | vm.stack.push(Value::Num((lhs $op rhs) as i32)); 195 | } 196 | } 197 | } 198 | 199 | impl_op!(add, +); 200 | impl_op!(sub, -); 201 | impl_op!(mul, *); 202 | impl_op!(div, /); 203 | impl_op!(lt, <); 204 | 205 | fn op_if(vm: &mut Vm) { 206 | let false_branch = vm.stack.pop().unwrap().to_block(); 207 | let true_branch = vm.stack.pop().unwrap().to_block(); 208 | let cond = vm.stack.pop().unwrap().to_block(); 209 | 210 | for code in cond { 211 | eval(code, vm); 212 | } 213 | 214 | let cond_result = vm.stack.pop().unwrap().as_num(); 215 | 216 | if cond_result != 0 { 217 | for code in true_branch { 218 | eval(code, vm); 219 | } 220 | } else { 221 | for code in false_branch { 222 | eval(code, vm); 223 | } 224 | } 225 | } 226 | 227 | fn op_def(vm: &mut Vm) { 228 | let value = vm.stack.pop().unwrap(); 229 | eval(value, vm); 230 | let value = vm.stack.pop().unwrap(); 231 | let sym = vm.stack.pop().unwrap().as_sym().to_string(); 232 | 233 | vm.vars.last_mut().unwrap().insert(sym, value); 234 | } 235 | 236 | fn puts(vm: &mut Vm) { 237 | let value = vm.stack.pop().unwrap(); 238 | println!("{}", value.to_string()); 239 | } 240 | 241 | fn pop(vm: &mut Vm) { 242 | vm.stack.pop().unwrap(); 243 | } 244 | 245 | fn dup(vm: &mut Vm) { 246 | let value = vm.stack.last().unwrap(); 247 | vm.stack.push(value.clone()); 248 | } 249 | 250 | fn exch(vm: &mut Vm) { 251 | let last = vm.stack.pop().unwrap(); 252 | let second = vm.stack.pop().unwrap(); 253 | vm.stack.push(last); 254 | vm.stack.push(second); 255 | } 256 | 257 | fn index(vm: &mut Vm) { 258 | let index = vm.stack.pop().unwrap().as_num() as usize; 259 | let value = vm.stack[vm.stack.len() - index - 1].clone(); 260 | vm.stack.push(value); 261 | } 262 | 263 | #[cfg(test)] 264 | mod test { 265 | use super::{Value::*, *}; 266 | use std::io::Cursor; 267 | 268 | fn parse(input: &str) -> Vec { 269 | parse_batch(Cursor::new(input)) 270 | } 271 | 272 | #[test] 273 | fn test_group() { 274 | assert_eq!( 275 | parse("1 2 + { 3 4 }"), 276 | vec![Num(3), Block(vec![Num(3), Num(4)])] 277 | ); 278 | } 279 | 280 | #[test] 281 | fn test_if_false() { 282 | assert_eq!( 283 | parse("{ 1 -1 + } { 100 } { -100 } if"), 284 | vec![Num(-100)] 285 | ); 286 | } 287 | 288 | #[test] 289 | fn test_if_true() { 290 | assert_eq!( 291 | parse("{ 1 1 + } { 100 } { -100 } if"), 292 | vec![Num(100)] 293 | ); 294 | } 295 | 296 | #[test] 297 | fn test_var() { 298 | assert_eq!( 299 | parse("/x 10 def /y 20 def x y *"), 300 | vec![Num(200)] 301 | ); 302 | } 303 | 304 | #[test] 305 | fn test_var_if() { 306 | assert_eq!( 307 | parse("/x 10 def /y 20 def { x y < } { x } { y } if"), 308 | vec![Num(10)] 309 | ); 310 | } 311 | 312 | #[test] 313 | fn test_multiline() { 314 | assert_eq!( 315 | parse( 316 | r#" 317 | /x 10 def 318 | /y 20 def 319 | 320 | { x y < } 321 | { x } 322 | { y } 323 | if 324 | "# 325 | ), 326 | vec![Num(10)] 327 | ); 328 | } 329 | 330 | #[test] 331 | fn test_function() { 332 | assert_eq!( 333 | parse( 334 | r#" 335 | /double { 2 * } def 336 | 10 double"# 337 | ), 338 | vec![Num(20)] 339 | ); 340 | } 341 | } 342 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 64 2 | tab_spaces = 2 -------------------------------------------------------------------------------- /screenshots/koch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/msakuta/rustack/d30ad97af5af851b9627c34eaf7449fcf3524557/screenshots/koch.png -------------------------------------------------------------------------------- /screenshots/wasm-screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/msakuta/rustack/d30ad97af5af851b9627c34eaf7449fcf3524557/screenshots/wasm-screenshot.png -------------------------------------------------------------------------------- /scripts/fibonacci.txt: -------------------------------------------------------------------------------- 1 | /fib { 2 | /n exch def 3 | { n 1 < } 4 | { 0 } 5 | { 6 | { n 2 < } 7 | { 1 } 8 | { 9 | n 1 - 10 | fib 11 | 12 | n 2 - 13 | fib 14 | + 15 | } 16 | if 17 | } 18 | if 19 | } def 20 | 21 | 10 fib puts -------------------------------------------------------------------------------- /scripts/for.txt: -------------------------------------------------------------------------------- 1 | 2 | /for { 3 | /proc exch def 4 | /end exch def 5 | /start exch def 6 | 7 | { start end < } 8 | { start proc 9 | start 1 + end /proc load for } 10 | { } 11 | if 12 | } def 13 | 14 | 15 | 0 10 { puts } for 16 | 17 | -------------------------------------------------------------------------------- /scripts/function.txt: -------------------------------------------------------------------------------- 1 | 2 | /double { 2 * } def 3 | /square { dup * } def 4 | 5 | 10 double puts 6 | 10 square puts 7 | 8 | /vec2sqlen { square exch square exch + } def 9 | 10 | 1 2 vec2sqlen puts 11 | -------------------------------------------------------------------------------- /scripts/if.txt: -------------------------------------------------------------------------------- 1 | /x 10 def 2 | /y 20 def 3 | 4 | { 5 | x y < 6 | } 7 | { 8 | x 9 | } 10 | { 11 | y 12 | } if 13 | 14 | puts -------------------------------------------------------------------------------- /scripts/recurse.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | /factorial { 1 factorial_int } def 4 | 5 | /factorial_int { 6 | /acc exch def 7 | /n exch def 8 | { n 2 < } 9 | { acc } 10 | { 11 | n 1 - 12 | acc n * 13 | factorial_int 14 | } 15 | if 16 | } def 17 | 18 | 10 factorial puts 19 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::{collections::HashMap, io::BufRead, rc::Rc}; 2 | 3 | #[derive(Debug, Clone, PartialEq)] 4 | pub enum Value<'f> { 5 | Int(i32), 6 | Num(f32), 7 | Op(String), 8 | Sym(String), 9 | Block(BlockSpan<'f>), 10 | Native(NativeOp<'f>), 11 | } 12 | 13 | impl<'f> Value<'f> { 14 | pub fn as_int(&self) -> i32 { 15 | match self { 16 | Self::Int(val) => *val, 17 | Self::Num(val) => *val as i32, 18 | _ => panic!("Value is not a number"), 19 | } 20 | } 21 | 22 | pub fn as_num(&self) -> f32 { 23 | match self { 24 | Self::Int(val) => *val as f32, 25 | Self::Num(val) => *val, 26 | _ => panic!("Value is not a number"), 27 | } 28 | } 29 | 30 | pub fn as_bool(&self) -> bool { 31 | self.as_int() != 0 32 | } 33 | 34 | pub fn to_block(self) -> BlockSpan<'f> { 35 | match self { 36 | Self::Block(val) => val, 37 | _ => panic!("Value is not a block"), 38 | } 39 | } 40 | 41 | pub fn as_sym(&self) -> &str { 42 | if let Self::Sym(sym) = self { 43 | sym 44 | } else { 45 | panic!("Value is not a symbol"); 46 | } 47 | } 48 | } 49 | 50 | impl<'f> ToString for Value<'f> { 51 | fn to_string(&self) -> String { 52 | match self { 53 | Self::Int(i) => i.to_string(), 54 | Self::Num(i) => i.to_string(), 55 | Self::Op(ref s) | Self::Sym(ref s) => s.clone(), 56 | Self::Block(block) => { 57 | format!("", block.span.0, block.span.1) 58 | } 59 | Self::Native(_) => "".to_string(), 60 | } 61 | } 62 | } 63 | 64 | #[derive(Clone)] 65 | pub struct NativeOp<'f>(Rc>); 66 | 67 | impl<'f> PartialEq for NativeOp<'f> { 68 | fn eq(&self, other: &NativeOp<'f>) -> bool { 69 | Rc::as_ptr(&self.0) == Rc::as_ptr(&other.0) 70 | } 71 | } 72 | 73 | impl<'f> Eq for NativeOp<'f> {} 74 | 75 | impl<'f> std::fmt::Debug for NativeOp<'f> { 76 | fn fmt( 77 | &self, 78 | f: &mut std::fmt::Formatter<'_>, 79 | ) -> std::fmt::Result { 80 | write!(f, "") 81 | } 82 | } 83 | 84 | #[derive(Debug, Clone, PartialEq)] 85 | pub struct ValueSpan<'f> { 86 | value: Value<'f>, 87 | span: (usize, usize), 88 | } 89 | 90 | #[derive(Debug)] 91 | pub struct ExecFrame<'f> { 92 | pub name: String, 93 | block: BlockSpan<'f>, 94 | ip: usize, 95 | pub vars: HashMap>, 96 | } 97 | 98 | impl<'f> ExecFrame<'f> { 99 | fn new(name: String, block: BlockSpan<'f>) -> Self { 100 | Self { 101 | name, 102 | block, 103 | ip: 0, 104 | vars: HashMap::new(), 105 | } 106 | } 107 | } 108 | 109 | #[derive(Debug)] 110 | pub enum ExecState<'f> { 111 | Frame(ExecFrame<'f>), 112 | IfCond { 113 | frame: ExecFrame<'f>, 114 | true_branch: BlockSpan<'f>, 115 | false_branch: BlockSpan<'f>, 116 | }, 117 | IfTrue(ExecFrame<'f>), 118 | IfFalse(ExecFrame<'f>), 119 | For { 120 | frame: ExecFrame<'f>, 121 | i: i32, 122 | end: i32, 123 | }, 124 | } 125 | 126 | impl<'f> ExecState<'f> { 127 | pub fn as_frame(&self) -> &ExecFrame<'f> { 128 | match self { 129 | Self::Frame(frame) => frame, 130 | Self::IfCond { frame, .. } => frame, 131 | Self::IfTrue(frame) | Self::IfFalse(frame) => frame, 132 | Self::For { frame, .. } => frame, 133 | } 134 | } 135 | 136 | fn as_frame_mut(&mut self) -> &mut ExecFrame<'f> { 137 | match self { 138 | Self::Frame(frame) => frame, 139 | Self::IfCond { frame, .. } => frame, 140 | Self::IfTrue(frame) | Self::IfFalse(frame) => frame, 141 | Self::For { frame, .. } => frame, 142 | } 143 | } 144 | } 145 | 146 | #[derive(Debug, Clone, PartialEq)] 147 | pub struct BlockSpan<'f> { 148 | block: Vec>, 149 | span: (usize, usize), 150 | } 151 | 152 | impl<'f> BlockSpan<'f> { 153 | fn new(start: usize) -> Self { 154 | Self { 155 | block: vec![], 156 | span: (start, 0), 157 | } 158 | } 159 | } 160 | 161 | pub struct Vm<'f> { 162 | stack: Vec>, 163 | globals: HashMap>, 164 | exec_stack: Vec>, 165 | blocks: Vec>, 166 | } 167 | 168 | impl<'f> Vm<'f> { 169 | pub fn new() -> Self { 170 | let functions: &[(&str, fn(&mut Vm))] = &[ 171 | ("+", add), 172 | ("-", sub), 173 | ("*", mul), 174 | ("div", div), 175 | ("<", lt), 176 | ("or", op_or), 177 | ("and", op_and), 178 | ("if", op_if), 179 | ("for", op_for), 180 | ("def", op_def), 181 | ("puts", puts), 182 | ("pop", pop), 183 | ("dup", dup), 184 | ("exch", exch), 185 | ("index", index), 186 | ("load", load), 187 | ("sin", sin), 188 | ("cos", cos), 189 | ("pi", |vm| { 190 | vm.stack.push(Value::Num(std::f32::consts::PI)) 191 | }), 192 | ]; 193 | Self { 194 | stack: vec![], 195 | globals: functions 196 | .into_iter() 197 | .map(|(name, fun)| { 198 | ( 199 | name.to_string(), 200 | Value::Native(NativeOp(Rc::new(Box::new(fun)))), 201 | ) 202 | }) 203 | .collect(), 204 | exec_stack: vec![], 205 | blocks: vec![BlockSpan::new(0)], 206 | } 207 | } 208 | 209 | pub fn get_stack(&self) -> &[Value<'f>] { 210 | &self.stack 211 | } 212 | 213 | pub fn pop(&mut self) -> Option> { 214 | self.stack.pop() 215 | } 216 | 217 | pub fn get_exec_stack(&self) -> &[ExecState<'f>] { 218 | &self.exec_stack 219 | } 220 | 221 | pub fn add_fn( 222 | &mut self, 223 | name: String, 224 | f: Box, 225 | ) { 226 | self 227 | .globals 228 | .insert(name, Value::Native(NativeOp(Rc::new(f)))); 229 | } 230 | 231 | fn find_var(&self, name: &str) -> Option> { 232 | self 233 | .exec_stack 234 | .iter() 235 | .rev() 236 | .find_map(|state| { 237 | state.as_frame().vars.get(name).cloned() 238 | }) 239 | .or_else(|| self.globals.get(name).cloned()) 240 | } 241 | 242 | pub fn get_vars(&self) -> &HashMap { 243 | &self.exec_stack.last().unwrap().as_frame().vars 244 | } 245 | 246 | pub fn parse_batch(&mut self, source: impl BufRead) { 247 | let mut tokenbuf = vec![]; 248 | let mut byte_count = 0; 249 | for byte in source.bytes().map(|b| b.unwrap()) { 250 | match byte { 251 | b' ' | b'\t' | b'\r' | b'\n' => { 252 | parse_word( 253 | std::str::from_utf8(&tokenbuf).unwrap(), 254 | self, 255 | byte_count - tokenbuf.len(), 256 | ); 257 | tokenbuf.clear(); 258 | } 259 | _ => tokenbuf.push(byte), 260 | } 261 | byte_count += 1; 262 | } 263 | 264 | parse_word( 265 | std::str::from_utf8(&tokenbuf).unwrap(), 266 | self, 267 | byte_count - tokenbuf.len(), 268 | ); 269 | 270 | if let Some(top_block) = self.blocks.first() { 271 | self.exec_stack.push(ExecState::Frame(ExecFrame::new( 272 | "root".to_owned(), 273 | top_block.clone(), 274 | ))); 275 | } 276 | } 277 | 278 | pub fn eval_all(&mut self) -> Result<(), String> { 279 | while self.eval_step().map(|r| r.is_some())? {} 280 | Ok(()) 281 | } 282 | 283 | fn map_err(&self, e: String) -> String { 284 | format!("{e}:\n{}", self.stack_trace()) 285 | } 286 | 287 | pub fn eval_step( 288 | &mut self, 289 | ) -> Result, String> { 290 | let get_step = |frame: &mut ExecFrame<'f>| { 291 | if frame.ip < frame.block.block.len() { 292 | let value_span = frame.block.block[frame.ip].clone(); 293 | frame.ip += 1; 294 | Some(value_span) 295 | } else { 296 | None 297 | } 298 | }; 299 | 300 | if let Some(state) = self.exec_stack.last_mut() { 301 | Ok(match state { 302 | ExecState::Frame(frame) 303 | | ExecState::IfTrue(frame) 304 | | ExecState::IfFalse(frame) => { 305 | if let Some(value_span) = get_step(frame) { 306 | eval(&value_span.value, self) 307 | .map_err(|e| self.map_err(e))?; 308 | Some(value_span.span) 309 | } else { 310 | let frame = self.exec_stack.pop(); 311 | Some( 312 | frame 313 | .map(|frame| frame.as_frame().block.span) 314 | .unwrap_or((0, 0)), 315 | ) 316 | } 317 | } 318 | ExecState::IfCond { frame, .. } => { 319 | if let Some(value_span) = get_step(frame) { 320 | eval(&value_span.value, self) 321 | .map_err(|e| self.map_err(e))?; 322 | Some(value_span.span) 323 | } else { 324 | let cond = self.stack.pop().unwrap(); 325 | if cond.as_int() != 0 { 326 | let block = if let ExecState::IfCond { 327 | true_branch, 328 | .. 329 | } = self.exec_stack.pop().unwrap() 330 | { 331 | true_branch 332 | } else { 333 | panic!("Top should be IfCond!"); 334 | }; 335 | let ret = block 336 | .block 337 | .first() 338 | .map(|first| first.span) 339 | .unwrap_or((0, 0)); 340 | self.exec_stack.push(ExecState::IfTrue( 341 | ExecFrame::new("".to_owned(), block), 342 | )); 343 | Some(ret) 344 | } else { 345 | let block = if let ExecState::IfCond { 346 | false_branch, 347 | .. 348 | } = self.exec_stack.pop().unwrap() 349 | { 350 | false_branch 351 | } else { 352 | panic!("Top should be IfCond!"); 353 | }; 354 | let ret = block 355 | .block 356 | .first() 357 | .map(|first| first.span) 358 | .unwrap_or((0, 0)); 359 | self.exec_stack.push(ExecState::IfFalse( 360 | ExecFrame::new("".to_owned(), block), 361 | )); 362 | Some(ret) 363 | } 364 | } 365 | } 366 | ExecState::For { frame, i, end } => loop { 367 | if frame.ip == 0 { 368 | self.stack.push(Value::Int(*i)); 369 | } 370 | if let Some(value_span) = get_step(frame) { 371 | eval(&value_span.value, self) 372 | .map_err(|e| self.map_err(e))?; 373 | break Some(value_span.span); 374 | } else { 375 | *i += 1; 376 | if *i < *end { 377 | frame.ip = 0; 378 | continue; 379 | } 380 | } 381 | let frame = self.exec_stack.pop(); 382 | break Some( 383 | frame 384 | .map(|frame| frame.as_frame().block.span) 385 | .unwrap_or((0, 0)), 386 | ); 387 | }, 388 | }) 389 | } else { 390 | Ok(None) 391 | } 392 | } 393 | 394 | fn stack_trace(&self) -> String { 395 | self 396 | .exec_stack 397 | .iter() 398 | .rev() 399 | .enumerate() 400 | .map(|(i, state)| match state { 401 | ExecState::Frame(frame) 402 | | ExecState::IfTrue(frame) 403 | | ExecState::IfFalse(frame) 404 | | ExecState::IfCond { frame, .. } 405 | | ExecState::For { frame, .. } => { 406 | let local_vars = frame.vars.iter().map(|(k, v)| format!("{k}: {}", v.to_string())).fold("".to_string(), |acc, cur| { 407 | if acc.is_empty() { 408 | cur 409 | } else { 410 | acc + ", " + &cur 411 | } 412 | }); 413 | let stack_vars = frame 414 | .block 415 | .block 416 | .iter() 417 | .map(|value| value.value.to_string()) 418 | .fold("".to_string(), |acc, cur| { 419 | acc + " " + &cur 420 | }); 421 | format!(" frame[{i}]: locals: {{{local_vars}}}, stack: {stack_vars}") 422 | } 423 | }) 424 | .fold(" Stack trace:\n".to_string(), |acc, cur| { 425 | acc + &cur + "\n" 426 | }) 427 | } 428 | } 429 | 430 | pub fn parse_interactive() { 431 | let mut vm = Vm::new(); 432 | for line in std::io::stdin().lines().flatten() { 433 | for word in line.split(" ") { 434 | let offset = 435 | word.as_ptr() as usize - line.as_ptr() as usize; 436 | parse_word(word, &mut vm, offset); 437 | } 438 | println!("stack: {:?}", vm.stack); 439 | } 440 | } 441 | 442 | fn parse_word(word: &str, vm: &mut Vm, offset: usize) { 443 | if word.is_empty() { 444 | return; 445 | } 446 | if word == "{" { 447 | vm.blocks.push(BlockSpan::new(offset)); 448 | } else if word == "}" { 449 | let mut new_block = 450 | vm.blocks.pop().expect("Block stack underflow!"); 451 | if let Some(top_block) = vm.blocks.last_mut() { 452 | new_block.span.1 = offset + 1; 453 | top_block.block.push(ValueSpan { 454 | span: (new_block.span.0, offset + 1), 455 | value: Value::Block(new_block), 456 | }); 457 | } 458 | } else if let Some(top_block) = vm.blocks.last_mut() { 459 | let code = if let Ok(num) = word.parse::() { 460 | Value::Int(num) 461 | } else if let Ok(num) = word.parse::() { 462 | Value::Num(num) 463 | } else if word.starts_with("/") { 464 | Value::Sym(word[1..].to_string()) 465 | } else { 466 | Value::Op(word.to_string()) 467 | }; 468 | top_block.block.push(ValueSpan { 469 | value: code, 470 | span: (offset, offset + word.len()), 471 | }); 472 | // eval(code, vm); 473 | } 474 | } 475 | 476 | fn eval<'f>( 477 | code: &Value<'f>, 478 | vm: &mut Vm<'f>, 479 | ) -> Result<(), String> { 480 | if let Value::Op(ref op) = code { 481 | let val = vm.find_var(op).ok_or_else(|| { 482 | format!("{op:?} is not a defined operation") 483 | })?; 484 | match val { 485 | Value::Block(block) => { 486 | vm.exec_stack.push(ExecState::Frame(ExecFrame::new( 487 | op.clone(), 488 | block, 489 | ))); 490 | } 491 | Value::Native(op) => op.0(vm), 492 | _ => vm.stack.push(val), 493 | } 494 | } else { 495 | vm.stack.push(code.clone()); 496 | } 497 | Ok(()) 498 | } 499 | 500 | macro_rules! impl_op { 501 | {$name:ident, $op:tt} => { 502 | fn $name(vm: &mut Vm) { 503 | let rhs = vm.stack.pop().unwrap(); 504 | let lhs = vm.stack.pop().unwrap(); 505 | vm.stack.push(match (lhs, rhs) { 506 | (Value::Int(lhs), Value::Int(rhs)) => Value::Int((lhs $op rhs) as i32), 507 | (Value::Num(lhs), Value::Int(rhs)) => Value::Num(lhs as f32 $op rhs as f32), 508 | (Value::Int(lhs), Value::Num(rhs)) => Value::Num(lhs as f32 $op rhs as f32), 509 | (Value::Num(lhs), Value::Num(rhs)) => Value::Num(lhs $op rhs), 510 | _ => panic!("Binary arithmetic between incompatible types!"), 511 | }); 512 | } 513 | } 514 | } 515 | 516 | impl_op!(add, +); 517 | impl_op!(sub, -); 518 | impl_op!(mul, *); 519 | impl_op!(div, /); 520 | 521 | fn lt(vm: &mut Vm) { 522 | let rhs = vm.stack.pop().unwrap().as_num(); 523 | let lhs = vm.stack.pop().unwrap().as_num(); 524 | vm.stack.push(Value::Int((lhs < rhs) as i32)); 525 | } 526 | 527 | fn op_or(vm: &mut Vm){ 528 | let rhs = vm.stack.pop().unwrap().as_bool(); 529 | let lhs = vm.stack.pop().unwrap().as_bool(); 530 | vm.stack.push(Value::Int((lhs || rhs) as i32)); 531 | } 532 | 533 | fn op_and(vm: &mut Vm){ 534 | let rhs = vm.stack.pop().unwrap().as_bool(); 535 | let lhs = vm.stack.pop().unwrap().as_bool(); 536 | vm.stack.push(Value::Int((lhs && rhs) as i32)); 537 | } 538 | 539 | fn sin(vm: &mut Vm) { 540 | let o = vm.pop().unwrap().as_num(); 541 | vm.stack.push(Value::Num(o.sin())); 542 | } 543 | 544 | fn cos(vm: &mut Vm) { 545 | let o = vm.pop().unwrap().as_num(); 546 | vm.stack.push(Value::Num(o.cos())); 547 | } 548 | 549 | fn op_if(vm: &mut Vm) { 550 | let false_branch = vm.stack.pop().unwrap().to_block(); 551 | let true_branch = vm.stack.pop().unwrap().to_block(); 552 | let cond = vm.stack.pop().unwrap().to_block(); 553 | 554 | vm.exec_stack.push(ExecState::IfCond { 555 | frame: ExecFrame::new("".to_owned(), cond), 556 | true_branch, 557 | false_branch, 558 | }); 559 | } 560 | 561 | fn op_for(vm: &mut Vm) { 562 | let f = vm.stack.pop().unwrap().to_block(); 563 | let end = vm.stack.pop().unwrap().as_int(); 564 | let start = vm.stack.pop().unwrap().as_int(); 565 | 566 | vm.exec_stack.push(ExecState::For { 567 | frame: ExecFrame::new("".to_owned(), f), 568 | i: start, 569 | end, 570 | }); 571 | } 572 | 573 | fn op_def(vm: &mut Vm) { 574 | let value = vm.stack.pop().unwrap(); 575 | if let Err(e) = eval(&value, vm) { 576 | println!("eval returned error: {e:?}"); 577 | } 578 | let value = vm.stack.pop().unwrap(); 579 | let sym = vm.stack.pop().unwrap().as_sym().to_string(); 580 | 581 | vm.exec_stack 582 | .iter_mut() 583 | .rev() 584 | .find(|frame| matches!(frame, ExecState::Frame(_))) 585 | .unwrap() 586 | .as_frame_mut() 587 | .vars 588 | .insert(sym, value); 589 | } 590 | 591 | fn puts(vm: &mut Vm) { 592 | let value = vm.stack.pop().unwrap(); 593 | println!("{}", value.to_string()); 594 | } 595 | 596 | fn pop(vm: &mut Vm) { 597 | vm.stack.pop().unwrap(); 598 | } 599 | 600 | fn dup(vm: &mut Vm) { 601 | let value = vm.stack.last().unwrap(); 602 | vm.stack.push(value.clone()); 603 | } 604 | 605 | fn exch(vm: &mut Vm) { 606 | let last = vm.stack.pop().unwrap(); 607 | let second = vm.stack.pop().unwrap(); 608 | vm.stack.push(last); 609 | vm.stack.push(second); 610 | } 611 | 612 | fn index(vm: &mut Vm) { 613 | let index = vm.stack.pop().unwrap().as_num() as usize; 614 | let value = vm.stack[vm.stack.len() - index - 1].clone(); 615 | vm.stack.push(value); 616 | } 617 | 618 | fn load(vm: &mut Vm) { 619 | let key = vm.stack.pop().unwrap(); 620 | let value = vm.find_var(key.as_sym()).unwrap(); 621 | vm.stack.push(value); 622 | } 623 | 624 | #[cfg(test)] 625 | mod test { 626 | use super::{Value::*, *}; 627 | use std::io::Cursor; 628 | 629 | fn parse(input: &str) -> Vec { 630 | let mut vm = Vm::new(); 631 | vm.parse_batch(Cursor::new(input)); 632 | vm.eval_all(); 633 | vm.get_stack().to_vec() 634 | } 635 | 636 | fn span(value: Value, span: (usize, usize)) -> ValueSpan { 637 | ValueSpan { value, span } 638 | } 639 | 640 | #[test] 641 | fn test_group() { 642 | assert_eq!( 643 | parse("1 2 + { 3 4 }"), 644 | vec![ 645 | Int(3), 646 | Block(BlockSpan { 647 | block: vec![ 648 | span(Int(3), (8, 9)), 649 | span(Int(4), (10, 11)) 650 | ], 651 | span: (6, 13), 652 | }) 653 | ] 654 | ); 655 | } 656 | 657 | #[test] 658 | fn test_if_false() { 659 | assert_eq!( 660 | parse("{ 1 -1 + } { 100 } { -100 } if"), 661 | vec![Int(-100)] 662 | ); 663 | } 664 | 665 | #[test] 666 | fn test_if_true() { 667 | assert_eq!( 668 | parse("{ 1 1 + } { 100 } { -100 } if"), 669 | vec![Int(100)] 670 | ); 671 | } 672 | 673 | #[test] 674 | fn test_var() { 675 | assert_eq!( 676 | parse("/x 10 def /y 20 def x y *"), 677 | vec![Int(200)] 678 | ); 679 | } 680 | 681 | #[test] 682 | fn test_var_if() { 683 | assert_eq!( 684 | parse("/x 10 def /y 20 def { x y < } { x } { y } if"), 685 | vec![Int(10)] 686 | ); 687 | } 688 | 689 | #[test] 690 | fn test_multiline() { 691 | assert_eq!( 692 | parse( 693 | r#" 694 | /x 10 def 695 | /y 20 def 696 | 697 | { x y < } 698 | { x } 699 | { y } 700 | if 701 | "# 702 | ), 703 | vec![Int(10)] 704 | ); 705 | } 706 | 707 | #[test] 708 | fn test_function() { 709 | assert_eq!( 710 | parse( 711 | r#" 712 | /double { 2 * } def 713 | 10 double"# 714 | ), 715 | vec![Int(20)] 716 | ); 717 | } 718 | } 719 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error; 2 | 3 | use ::rustack::Vm; 4 | 5 | pub fn main() -> Result<(), Box> { 6 | let mut file_name = None; 7 | for arg in std::env::args().skip(1) { 8 | file_name = Some(arg); 9 | } 10 | let Some(file_name) = file_name else { 11 | eprintln!("usage: rustack [file_name.txt]"); 12 | return Ok(()); 13 | }; 14 | let src = std::fs::read_to_string(file_name)?; 15 | let mut vm = Vm::new(); 16 | vm.parse_batch(std::io::Cursor::new(src)); 17 | if let Err(e) = vm.eval_all() { 18 | eprintln!("ERROR: {e}"); 19 | return Ok(()); 20 | }; 21 | format!("stack: {:?}\n", vm.get_stack()); 22 | Ok(()) 23 | } 24 | -------------------------------------------------------------------------------- /wasm/.appveyor.yml: -------------------------------------------------------------------------------- 1 | install: 2 | - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe 3 | - if not defined RUSTFLAGS rustup-init.exe -y --default-host x86_64-pc-windows-msvc --default-toolchain nightly 4 | - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin 5 | - rustc -V 6 | - cargo -V 7 | 8 | build: false 9 | 10 | test_script: 11 | - cargo test --locked 12 | -------------------------------------------------------------------------------- /wasm/.cargo-ok: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/msakuta/rustack/d30ad97af5af851b9627c34eaf7449fcf3524557/wasm/.cargo-ok -------------------------------------------------------------------------------- /wasm/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | bin/ 5 | pkg/ 6 | wasm-pack.log 7 | node_modules/ 8 | dist/ 9 | -------------------------------------------------------------------------------- /wasm/.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | sudo: false 3 | 4 | cache: cargo 5 | 6 | matrix: 7 | include: 8 | 9 | # Builds with wasm-pack. 10 | - rust: beta 11 | env: RUST_BACKTRACE=1 12 | addons: 13 | firefox: latest 14 | chrome: stable 15 | before_script: 16 | - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) 17 | - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) 18 | - cargo install-update -a 19 | - curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh -s -- -f 20 | script: 21 | - cargo generate --git . --name testing 22 | # Having a broken Cargo.toml (in that it has curlies in fields) anywhere 23 | # in any of our parent dirs is problematic. 24 | - mv Cargo.toml Cargo.toml.tmpl 25 | - cd testing 26 | - wasm-pack build 27 | - wasm-pack test --chrome --firefox --headless 28 | 29 | # Builds on nightly. 30 | - rust: nightly 31 | env: RUST_BACKTRACE=1 32 | before_script: 33 | - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) 34 | - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) 35 | - cargo install-update -a 36 | - rustup target add wasm32-unknown-unknown 37 | script: 38 | - cargo generate --git . --name testing 39 | - mv Cargo.toml Cargo.toml.tmpl 40 | - cd testing 41 | - cargo check 42 | - cargo check --target wasm32-unknown-unknown 43 | - cargo check --no-default-features 44 | - cargo check --target wasm32-unknown-unknown --no-default-features 45 | - cargo check --no-default-features --features console_error_panic_hook 46 | - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook 47 | - cargo check --no-default-features --features "console_error_panic_hook wee_alloc" 48 | - cargo check --target wasm32-unknown-unknown --no-default-features --features "console_error_panic_hook wee_alloc" 49 | 50 | # Builds on beta. 51 | - rust: beta 52 | env: RUST_BACKTRACE=1 53 | before_script: 54 | - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) 55 | - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) 56 | - cargo install-update -a 57 | - rustup target add wasm32-unknown-unknown 58 | script: 59 | - cargo generate --git . --name testing 60 | - mv Cargo.toml Cargo.toml.tmpl 61 | - cd testing 62 | - cargo check 63 | - cargo check --target wasm32-unknown-unknown 64 | - cargo check --no-default-features 65 | - cargo check --target wasm32-unknown-unknown --no-default-features 66 | - cargo check --no-default-features --features console_error_panic_hook 67 | - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook 68 | # Note: no enabling the `wee_alloc` feature here because it requires 69 | # nightly for now. 70 | -------------------------------------------------------------------------------- /wasm/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "wasm" 3 | version = "0.1.0" 4 | authors = ["msakuta "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["cdylib", "rlib"] 9 | 10 | [features] 11 | default = ["console_error_panic_hook"] 12 | 13 | [dependencies] 14 | wasm-bindgen = "0.2.63" 15 | 16 | # The `console_error_panic_hook` crate provides better debugging of panics by 17 | # logging them with `console.error`. This is great for development, but requires 18 | # all the `std::fmt` and `std::panicking` infrastructure, so isn't great for 19 | # code size when deploying. 20 | console_error_panic_hook = { version = "0.1.6", optional = true } 21 | 22 | rustack = { path = ".." } 23 | 24 | js-sys = "0.3.60" 25 | serde = { version = "1.0", features = ["derive"] } 26 | serde_json = "1.0" 27 | 28 | [dev-dependencies] 29 | wasm-bindgen-test = "0.3.13" 30 | 31 | [profile.release] 32 | # Tell `rustc` to optimize for small code size. 33 | opt-level = "s" 34 | -------------------------------------------------------------------------------- /wasm/LICENSE_APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /wasm/LICENSE_MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 msakuta 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /wasm/README.md: -------------------------------------------------------------------------------- 1 | # Web page deployment with Wasm binary 2 | 3 | This is a WebAssembly build of Rustack. 4 | See the language itself's [README](../README.md) for more details. 5 | 6 | See the deployed web page here: https://msakuta.github.io/rustack/ 7 | 8 | 9 | ## How to build 10 | 11 | Run 12 | 13 | ``` 14 | $ mkdir dist && npm ci && npm run build 15 | ``` 16 | 17 | and now you have a web page in `dist/`. 18 | 19 | 20 | ## How to run development build 21 | 22 | Run 23 | 24 | ``` 25 | $ npm start 26 | ``` 27 | 28 | It will build the wasm binary and start web browser to open the page. 29 | 30 | ## Credit 31 | 32 | This app was made with template from wasm-pack [template][template-docs]. 33 | 34 | [template-docs]: https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/index.html 35 | 36 | 37 | ## License 38 | 39 | Licensed under either of 40 | 41 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 42 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 43 | 44 | at your option. 45 | 46 | ### Contribution 47 | 48 | Unless you explicitly state otherwise, any contribution intentionally 49 | submitted for inclusion in the work by you, as defined in the Apache-2.0 50 | license, shall be dual licensed as above, without any additional terms or 51 | conditions. -------------------------------------------------------------------------------- /wasm/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | rustack wasm 5 | 6 | 7 | 30 | 31 | 32 |

rustack Wasm

33 |
34 |
35 |
36 |
37 | Samples: 38 |
39 |
40 | 41 |
42 | 45 | 46 |
47 | 48 | 49 | 50 | 51 | 52 |
53 | 54 |
55 |
56 | 57 |
58 |
59 | 60 |
61 |
Execution state:
62 |
63 | 64 |
65 |
66 |
67 | 68 |

Canvas:

69 |
70 | 71 | 72 |
73 |

Data types

74 | rustack has following value types. 75 | It is dynamically typed language, so each stack element can have any type at any time. 76 |
    77 |
  • Int (i32)
  • 78 |
  • Num (f32)
  • 79 |
  • Symbol
  • 80 |
  • Block
  • 81 |
  • Native
  • 82 |
83 | 84 |

Built-in functions

85 | As an experimental language, it has only few Built-in functions. 86 | 87 |
    88 |
  • "puts" - Pop a value from the stack and print it to the console.
  • 89 |
  • "+" - addition
  • 90 |
  • "-" - subtraction
  • 91 |
  • "*" - multiplication
  • 92 |
  • "/" - division
  • 93 |
  • "<" - less-than (yields 1 if true, otherwise 0)
  • 94 |
  • "and" - logical AND (yields 1 if both of 2 operands are nonzero, otherwise 0)
  • 95 |
  • "or" - logical OR (yields 1 if both of 2 operands are nonzero, otherwise 0)
  • 96 |
  • "if" - conditional branching, taking 3 argument blocks
  • 97 |
  • "for" - Pop (start, end, block), loop from start through end, calling block with the iteration number pushed to the operand stack
  • 98 |
  • "def" - pop a symbol (name) and a value and define a variable (a scalar) or a function (a block)
  • 99 |
  • "pop" - pop the topmost value from the stack
  • 100 |
  • "dup" - duplicate the topmost value of the stack and push it
  • 101 |
  • "exch" - exchange the topmost 2 values
  • 102 |
  • "index" - pop a value from the stack, and extract a value at stack index specified by the popped value
  • 103 |
  • "load" - pop a value from the stack, get a value from dictionary stack with the popped value as the key and push it without executing it
  • 104 |
105 | 106 |

Canvas rendering functions

107 | 119 | 120 |

Time measurement resolution

121 | Due to security reasons, your browser may have reduced time resolution for measurement. 122 | It is typically 0.1ms or 1ms, but can be larger. 123 | Please be aware that the lower digits may be always 0 because of this rounding. 124 | See this page for details. 125 |
126 | 127 |
128 |

Source on GitHub.

129 | 130 | 131 | 132 | -------------------------------------------------------------------------------- /wasm/js/index.js: -------------------------------------------------------------------------------- 1 | // Wait for the html to fully load before loading main.js, since it assumes static html elements exist. 2 | window.onload = () => { 3 | import("./main.js").catch(console.error); 4 | } 5 | -------------------------------------------------------------------------------- /wasm/js/main.js: -------------------------------------------------------------------------------- 1 | import { init, entry, start_step } from "../pkg/index.js"; 2 | 3 | init(); 4 | 5 | function runCommon(process, clearOutput=true, measureTime=true) { 6 | // Clear output 7 | const output = document.getElementById("output"); 8 | if (clearOutput) { 9 | output.value = ""; 10 | const canvas = document.getElementById("canvas"); 11 | const canvasRect = canvas.getBoundingClientRect(); 12 | const ctx = canvas.getContext("2d"); 13 | ctx.clearRect(0, 0, canvasRect.width, canvasRect.height); 14 | ctx.reset(); 15 | document.getElementById("timeMessage").innerHTML = ""; 16 | } 17 | 18 | const source = document.getElementById("input").value; 19 | try{ 20 | const start = performance.now(); 21 | const res = process(source); 22 | const end = performance.now(); 23 | if (measureTime) { 24 | document.getElementById("timeMessage").innerHTML = `Execution time: ${(end - start).toFixed(1)} ms (See notes)`; 25 | } 26 | } 27 | catch(e){ 28 | output.value = e; 29 | } 30 | } 31 | 32 | let vm = null; 33 | let sourceText = ""; 34 | 35 | document.getElementById("run").addEventListener("click", () => runCommon(entry)); 36 | document.getElementById("startStep").addEventListener("click", () => runCommon((source) => { 37 | vm = start_step(source); 38 | sourceText = source; 39 | document.getElementById("fixedInput").innerHTML = source; 40 | updateButtonStates(); 41 | return runStep(); 42 | }, true, false)); 43 | document.getElementById("startAutoStep").addEventListener("click", () => runCommon((source) => { 44 | vm = start_step(source); 45 | sourceText = source; 46 | document.getElementById("fixedInput").innerHTML = source; 47 | updateButtonStates(); 48 | runAutoStep(); 49 | }, true, false)); 50 | document.getElementById("step").addEventListener("click", () => runCommon(runStep, false)); 51 | document.getElementById("haltStep").addEventListener("click", () => runCommon((source) => { 52 | vm = null; 53 | updateButtonStates(); 54 | return "Step execution halted"; 55 | }, true, false)); 56 | document.getElementById("clearCanvas").addEventListener("click", () => { 57 | const canvas = document.getElementById("canvas"); 58 | const ctx = canvas.getContext("2d"); 59 | ctx.reset(); 60 | ctx.fillStyle = "rgb(255, 255, 255)"; 61 | ctx.clearRect(0, 0, canvas.width, canvas.height); 62 | }); 63 | 64 | function runStep() { 65 | if (vm) { 66 | try { 67 | const ret = vm.step(); 68 | const first = sourceText.substring(0, ret[0]); 69 | const middle = sourceText.substring(ret[0], ret[1]); 70 | const last = sourceText.substring(ret[1]); 71 | document.getElementById("fixedInput").innerHTML = first + `${middle}` + last; 72 | const stack = vm.get_stack(); 73 | renderStack(stack, vm.get_exec_stack()); 74 | return ""; 75 | } 76 | catch(e) { 77 | vm = null; 78 | updateButtonStates(); 79 | throw e; 80 | } 81 | } 82 | throw "Start step execution first"; 83 | } 84 | 85 | function runAutoStep() { 86 | if (vm) { 87 | runStep(); 88 | requestAnimationFrame(runAutoStep, 50); 89 | } 90 | } 91 | 92 | const stackTop = 50; 93 | const stackLeft = 20; 94 | const frameTop = stackTop + 50; 95 | const frameLeft = 20; 96 | const frameMargin = 10; 97 | const frameNameHeight = 25; 98 | const varLeft = stackLeft + frameMargin; 99 | const varWidth = 100; 100 | const varHeight = 30; 101 | 102 | function estimateHeight(stack, execStack) { 103 | let offset = frameTop; 104 | for(let n = execStack.length - 1; 0 <= n; n--) { 105 | offset += execStack[n].vars.length * varHeight + frameMargin * 3 + frameNameHeight; 106 | } 107 | return offset; 108 | } 109 | 110 | function renderStack(stack, execStackJson) { 111 | const execStack = JSON.parse(execStackJson); 112 | 113 | const canvas = document.getElementById("stack"); 114 | canvas.height = estimateHeight(stack, execStack); 115 | const ctx = canvas.getContext("2d"); 116 | ctx.fillStyle = "rgb(255, 255, 255)"; 117 | ctx.fillRect(0, 0, canvas.width, canvas.height); 118 | 119 | ctx.fillStyle = "black"; 120 | ctx.fillText(`Operand stack[${stack.length}]: `, stackLeft, stackTop - 5); 121 | 122 | for(let i in stack) { 123 | const val = stack[i]; 124 | renderRect(ctx, stackLeft + i * 100, stackTop, val); 125 | } 126 | 127 | ctx.fillStyle = "black"; 128 | ctx.fillText(`Execution stack[${execStack.length}]:`, frameLeft, frameTop - 5); 129 | 130 | let offset = frameTop; 131 | for(let n = execStack.length - 1; 0 <= n; n--) { 132 | const { name, vars } = execStack[n]; 133 | const varTop = offset + frameMargin + frameNameHeight; 134 | 135 | ctx.beginPath(); 136 | ctx.rect(frameLeft, offset, varWidth * 2 + frameMargin * 2, varHeight * vars.length + frameMargin * 2 + frameNameHeight); 137 | ctx.fillStyle = "rgb(191, 191, 191)"; 138 | ctx.fill(); 139 | ctx.strokeStyle = "black"; 140 | ctx.stroke(); 141 | 142 | ctx.fillStyle = "black"; 143 | ctx.fillText(`function: ${name}`, varLeft, varTop - 20); 144 | 145 | ctx.fillText(`variables:`, varLeft, varTop - 5); 146 | 147 | for(let i = 0; i < vars.length; i++) { 148 | const [key, value] = vars[i]; 149 | renderRect(ctx, varLeft, varTop + varHeight * i, key); 150 | renderRect(ctx, varLeft + varWidth, varTop + varHeight * i, value, "rgb(127, 255, 255)"); 151 | } 152 | offset += vars.length * varHeight + frameMargin * 3 + frameNameHeight; 153 | } 154 | } 155 | 156 | function renderRect(ctx, x, y, txt, color="rgb(127, 255, 127)") { 157 | ctx.beginPath(); 158 | ctx.rect(x, y, 100, varHeight); 159 | ctx.fillStyle = color; 160 | ctx.fill(); 161 | ctx.strokeStyle = "black"; 162 | ctx.stroke(); 163 | 164 | ctx.fillStyle = "black"; 165 | ctx.fillText(txt, x + 5, y + varHeight - 5); 166 | } 167 | 168 | function updateButtonStates() { 169 | if(vm){ 170 | document.getElementById("code").style.display = "none"; 171 | document.getElementById("fixedCode").style.display = "block"; 172 | document.getElementById("run").setAttribute("disabled", ""); 173 | document.getElementById("startStep").setAttribute("disabled", ""); 174 | document.getElementById("step").removeAttribute("disabled"); 175 | document.getElementById("haltStep").removeAttribute("disabled"); 176 | } 177 | else{ 178 | document.getElementById("code").style.display = "block"; 179 | document.getElementById("fixedCode").style.display = "none"; 180 | document.getElementById("run").removeAttribute("disabled"); 181 | document.getElementById("startStep").removeAttribute("disabled"); 182 | document.getElementById("step").setAttribute("disabled", ""); 183 | document.getElementById("haltStep").setAttribute("disabled", ""); 184 | } 185 | } 186 | 187 | document.getElementById("input").value = ` 188 | 10 20 + puts 189 | `; 190 | 191 | const samples = document.getElementById("samples"); 192 | 193 | ["function.txt", "fibonacci.txt", "if.txt", "for.txt", "recurse.txt", "canvas.txt", "koch.txt", "mandel_canvas.txt", "mandel_canvas_recursive.txt"] 194 | .forEach(fileName => { 195 | const link = document.createElement("a"); 196 | link.href = "#"; 197 | link.addEventListener("click", () => { 198 | fetch("scripts/" + fileName) 199 | .then(file => file.text()) 200 | .then(text => { 201 | document.getElementById("input").value = text 202 | vm = null; 203 | updateButtonStates(); 204 | }); 205 | }); 206 | link.innerHTML = fileName; 207 | samples.appendChild(link); 208 | samples.append(" "); 209 | }) 210 | 211 | // function updateStackSvg() { 212 | // const stack = document.getElementById("stack"); 213 | // while(stack.firstChild) 214 | // stack.removeChild(stack.firstChild); 215 | 216 | // for() 217 | // stack.appendChild(""); 218 | // } -------------------------------------------------------------------------------- /wasm/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "You ", 3 | "name": "rust-webpack-template", 4 | "version": "0.1.0", 5 | "scripts": { 6 | "build": "rimraf dist pkg && webpack", 7 | "start": "rimraf dist pkg && webpack-dev-server --open -d", 8 | "test": "cargo test && wasm-pack test --headless" 9 | }, 10 | "devDependencies": { 11 | "@wasm-tool/wasm-pack-plugin": "^1.1.0", 12 | "copy-webpack-plugin": "^6.0.0", 13 | "html-loader": "^1.3.2", 14 | "html-webpack-plugin": "^4.5.0", 15 | "rimraf": "^3.0.0", 16 | "url-loader": "^4.1.1", 17 | "webpack": "^4.42.0", 18 | "webpack-cli": "^3.3.3", 19 | "webpack-dev-server": "^3.7.1" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /wasm/scripts/canvas.txt: -------------------------------------------------------------------------------- 1 | 2 | /for { 3 | /proc exch def 4 | /end exch def 5 | /start exch def 6 | 7 | { start end < } 8 | { start proc 9 | start 1 + end /proc load for } 10 | { } 11 | if 12 | } def 13 | 14 | 15 | 0 10 { 16 | dup 17 | 25 * 127 0 set_fill_style 18 | 30 * 10 + 19 | 10 20 | 20 21 | 30 22 | rectangle 23 | } for 24 | -------------------------------------------------------------------------------- /wasm/scripts/koch.txt: -------------------------------------------------------------------------------- 1 | /koch { 2 | /level exch def 3 | /scale exch def 4 | 5 | { level 5 < } 6 | { 7 | save 8 | 9 | scale 3. div level 1 + koch 10 | 11 | scale 100 * 12 | 0 13 | translate 14 | pi -3. div rotate 15 | 16 | scale 3. div 17 | level 1 + 18 | koch 19 | 20 | scale 100 * 21 | 0 22 | translate 23 | pi 2. * 3. div rotate 24 | 25 | scale 3. div 26 | level 1 + koch 27 | 28 | scale 100 * 29 | 0 30 | translate 31 | pi -3. div rotate 32 | scale 3. div 33 | level 1 + koch 34 | 35 | restore 36 | } 37 | { 38 | begin_path 39 | 0 0 move_to 40 | scale 300 * 0 line_to 41 | stroke 42 | } 43 | if 44 | 45 | } def 46 | 47 | 10 300 translate 48 | 1. 1 koch 49 | -------------------------------------------------------------------------------- /wasm/scripts/mandel_canvas.txt: -------------------------------------------------------------------------------- 1 | 2 | /printdensity { 3 | /y exch def 4 | /x exch def 5 | /d exch def 6 | 7 | 0 d 0 set_fill_style 8 | x 4 * y 4 * 4 4 rectangle 9 | } def 10 | 11 | /mandelconverger { 12 | /cimag exch def 13 | /creal exch def 14 | /iters exch def 15 | /imag exch def 16 | /real exch def 17 | 18 | 0 255 { 19 | { 4 real real * imag imag * + < } 20 | { } 21 | { 22 | /iters exch def 23 | /real_next real real * imag imag * - creal + def 24 | /imag 2 real * imag * cimag + def 25 | /real real_next def 26 | } if 27 | } for 28 | iters 29 | } def 30 | 31 | /mandelconverge { 32 | /imag exch def 33 | /real exch def 34 | 35 | real imag 0 real imag mandelconverger 36 | } def 37 | 38 | /mandel { 39 | /ysteps exch def 40 | /xsteps exch def 41 | /ystep exch def 42 | /xstep exch def 43 | /ymin exch def 44 | /xmin exch def 45 | 46 | 0 ysteps { 47 | /iy exch def 48 | /y iy ystep * ymin + def 49 | 0 xsteps { 50 | /ix exch def 51 | /x ix xstep * xmin + def 52 | x y mandelconverge 53 | ix iy printdensity 54 | } for 55 | } for 56 | } def 57 | 58 | -2.0 -2.0 0.05 0.05 80 80 mandel 59 | -------------------------------------------------------------------------------- /wasm/scripts/mandel_canvas_recursive.txt: -------------------------------------------------------------------------------- 1 | 2 | /printdensity { 3 | /y exch def 4 | /x exch def 5 | /d exch def 6 | 7 | 0 d 0 set_fill_style 8 | x 4 * y 4 * 4 4 rectangle 9 | } def 10 | 11 | /mandelconverger { 12 | /cimag exch def 13 | /creal exch def 14 | /imag exch def 15 | /real exch def 16 | 17 | /loop { 18 | /iters exch def 19 | /imag exch def 20 | /real exch def 21 | 22 | { 23 | 4 real real * imag imag * + < 24 | 255 iters < or 25 | } 26 | { iters } 27 | { 28 | /real_next real real * imag imag * - creal + def 29 | /imag 2 real * imag * cimag + def 30 | /real real_next def 31 | real imag iters 1 + loop 32 | } if 33 | } def 34 | 35 | real imag 0 loop 36 | } def 37 | 38 | /mandelconverge { 39 | /imag exch def 40 | /real exch def 41 | 42 | real imag real imag mandelconverger 43 | } def 44 | 45 | /mandel { 46 | /ysteps exch def 47 | /xsteps exch def 48 | /ystep exch def 49 | /xstep exch def 50 | /ymin exch def 51 | /xmin exch def 52 | 53 | 0 ysteps { 54 | /iy exch def 55 | /y iy ystep * ymin + def 56 | 0 xsteps { 57 | /ix exch def 58 | /x ix xstep * xmin + def 59 | x y mandelconverge 60 | ix iy printdensity 61 | } for 62 | } for 63 | } def 64 | 65 | -2.0 -2.0 0.05 0.05 80 80 mandel 66 | -------------------------------------------------------------------------------- /wasm/src/lib.rs: -------------------------------------------------------------------------------- 1 | mod utils; 2 | mod wasm_imports; 3 | 4 | use crate::wasm_imports::register_wasm_fn; 5 | use rustack::Vm; 6 | use serde::Serialize; 7 | use wasm_bindgen::prelude::*; 8 | 9 | #[wasm_bindgen] 10 | extern "C" { 11 | #[wasm_bindgen(js_namespace = console)] 12 | pub(crate) fn log(s: &str); 13 | } 14 | 15 | #[wasm_bindgen] 16 | pub fn init() { 17 | utils::set_panic_hook(); 18 | } 19 | 20 | #[wasm_bindgen] 21 | pub fn entry(src: &str) -> Result { 22 | let stack = { 23 | let mut vm = Vm::new(); 24 | register_wasm_fn(&mut vm); 25 | vm.parse_batch(std::io::Cursor::new(src)); 26 | vm.eval_all()?; 27 | format!("stack: {:?}\n", vm.get_stack()) 28 | }; 29 | Ok(stack) 30 | } 31 | 32 | #[wasm_bindgen] 33 | pub struct VmHandle { 34 | vm: Vm<'static>, 35 | tokens: Vec, 36 | } 37 | 38 | #[wasm_bindgen] 39 | pub fn start_step(src: String) -> VmHandle { 40 | let tokens = src 41 | .split([' ', '\t', '\r', '\n']) 42 | .filter_map(|tok| { 43 | if tok.is_empty() { 44 | None 45 | } else { 46 | Some(tok.to_owned()) 47 | } 48 | }) 49 | .collect(); 50 | let mut vm = Vm::new(); 51 | register_wasm_fn(&mut vm); 52 | vm.parse_batch(std::io::Cursor::new(src)); 53 | VmHandle { vm, tokens } 54 | } 55 | 56 | #[wasm_bindgen] 57 | impl VmHandle { 58 | pub fn step(&mut self) -> Result, JsValue> { 59 | log(&format!("tokens: {:?}", self.tokens)); 60 | if let Some(span) = self.vm.eval_step()? { 61 | Ok(vec![span.0, span.1]) 62 | } else { 63 | return Err(JsValue::from_str("Input tokens exhausted")); 64 | } 65 | } 66 | 67 | pub fn get_stack(&self) -> Result, JsValue> { 68 | Ok( 69 | self 70 | .vm 71 | .get_stack() 72 | .iter() 73 | .map(|val| JsValue::from_str(&val.to_string())) 74 | .collect(), 75 | ) 76 | } 77 | 78 | /// Return execution stack in JSON string 79 | pub fn get_exec_stack(&self) -> Result { 80 | #[derive(Serialize)] 81 | struct ExecFrame { 82 | name: String, 83 | /// We could return HashMap, but it would be mapped to a JS object, 84 | /// which in turn changes order every time you run. 85 | vars: Vec<[String; 2]>, 86 | } 87 | 88 | let ret: Vec = self 89 | .vm 90 | .get_exec_stack() 91 | .iter() 92 | .map(|ex| { 93 | let frame = ex.as_frame(); 94 | ExecFrame { 95 | name: frame.name.clone(), 96 | vars: frame 97 | .vars 98 | .iter() 99 | .map(|(key, val)| [key.clone(), val.to_string()]) 100 | .collect(), 101 | } 102 | }) 103 | .collect(); 104 | let js = serde_json::to_string(&ret) 105 | .map_err(|e| JsValue::from_str(&e.to_string()))?; 106 | Ok(js) 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /wasm/src/utils.rs: -------------------------------------------------------------------------------- 1 | pub fn set_panic_hook() { 2 | // When the `console_error_panic_hook` feature is enabled, we can call the 3 | // `set_panic_hook` function at least once during initialization, and then 4 | // we will get better error messages if our code ever panics. 5 | // 6 | // For more details see 7 | // https://github.com/rustwasm/console_error_panic_hook#readme 8 | #[cfg(feature = "console_error_panic_hook")] 9 | console_error_panic_hook::set_once(); 10 | } 11 | -------------------------------------------------------------------------------- /wasm/src/wasm_imports.rs: -------------------------------------------------------------------------------- 1 | use rustack::Vm; 2 | use wasm_bindgen::prelude::*; 3 | 4 | pub(super) fn register_wasm_fn(vm: &mut Vm) { 5 | vm.add_fn("puts".to_string(), Box::new(puts)); 6 | vm.add_fn("rectangle".to_string(), Box::new(rectangle)); 7 | vm.add_fn( 8 | "set_fill_style".to_string(), 9 | Box::new(set_fill_style), 10 | ); 11 | vm.add_fn( 12 | "set_stroke_style".to_string(), 13 | Box::new(set_stroke_style), 14 | ); 15 | vm.add_fn("begin_path".to_string(), Box::new(begin_path)); 16 | vm.add_fn("move_to".to_string(), Box::new(move_to)); 17 | vm.add_fn("line_to".to_string(), Box::new(line_to)); 18 | vm.add_fn("stroke".to_string(), Box::new(stroke)); 19 | vm.add_fn("rotate".to_string(), Box::new(rotate)); 20 | vm.add_fn("translate".to_string(), Box::new(translate)); 21 | vm.add_fn("save".to_string(), Box::new(save)); 22 | vm.add_fn("restore".to_string(), Box::new(restore)); 23 | } 24 | 25 | #[wasm_bindgen(module = "/wasm_api.js")] 26 | extern "C" { 27 | pub(crate) fn wasm_print(s: &str); 28 | pub(crate) fn wasm_rectangle( 29 | x0: f32, 30 | y0: f32, 31 | x1: f32, 32 | y1: f32, 33 | ); 34 | pub(crate) fn wasm_set_fill_style(s: &str); 35 | pub(crate) fn wasm_set_stroke_style(s: &str); 36 | pub(crate) fn wasm_begin_path(); 37 | pub(crate) fn wasm_move_to(x0: f32, y0: f32); 38 | pub(crate) fn wasm_line_to(x0: f32, y0: f32); 39 | pub(crate) fn wasm_stroke(); 40 | pub(crate) fn wasm_rotate(angle: f32); 41 | pub(crate) fn wasm_translate(x: f32, y: f32); 42 | pub(crate) fn wasm_save(); 43 | pub(crate) fn wasm_restore(); 44 | } 45 | 46 | fn puts(vm: &mut Vm) { 47 | wasm_print(&format!( 48 | "puts: {}\n", 49 | vm.pop().unwrap().to_string() 50 | )); 51 | } 52 | 53 | fn rectangle(vm: &mut Vm) { 54 | let y1 = vm.pop().unwrap().as_num(); 55 | let x1 = vm.pop().unwrap().as_num(); 56 | let y0 = vm.pop().unwrap().as_num(); 57 | let x0 = vm.pop().unwrap().as_num(); 58 | wasm_rectangle(x0, y0, x1, y1); 59 | } 60 | 61 | fn set_fill_style(vm: &mut Vm) { 62 | let b = vm.pop().unwrap().as_num(); 63 | let g = vm.pop().unwrap().as_num(); 64 | let r = vm.pop().unwrap().as_num(); 65 | wasm_set_fill_style(&format!("rgb({r},{g},{b})")); 66 | } 67 | 68 | fn set_stroke_style(vm: &mut Vm) { 69 | let b = vm.pop().unwrap().as_num(); 70 | let g = vm.pop().unwrap().as_num(); 71 | let r = vm.pop().unwrap().as_num(); 72 | wasm_set_stroke_style(&format!("rgb({r},{g},{b})")); 73 | } 74 | 75 | fn begin_path(_vm: &mut Vm) { 76 | wasm_begin_path(); 77 | } 78 | 79 | fn move_to(vm: &mut Vm) { 80 | let y0 = vm.pop().unwrap().as_num(); 81 | let x0 = vm.pop().unwrap().as_num(); 82 | wasm_move_to(x0, y0); 83 | } 84 | 85 | fn line_to(vm: &mut Vm) { 86 | let y0 = vm.pop().unwrap().as_num(); 87 | let x0 = vm.pop().unwrap().as_num(); 88 | wasm_line_to(x0, y0); 89 | } 90 | 91 | fn stroke(_vm: &mut Vm) { 92 | wasm_stroke(); 93 | } 94 | 95 | fn rotate(vm: &mut Vm) { 96 | let angle = vm.pop().unwrap().as_num(); 97 | wasm_rotate(angle); 98 | } 99 | 100 | fn translate(vm: &mut Vm) { 101 | let y = vm.pop().unwrap().as_num(); 102 | let x = vm.pop().unwrap().as_num(); 103 | wasm_translate(x, y); 104 | } 105 | 106 | fn save(_vm: &mut Vm) { 107 | wasm_save(); 108 | } 109 | 110 | fn restore(_vm: &mut Vm) { 111 | wasm_restore(); 112 | } 113 | -------------------------------------------------------------------------------- /wasm/tests/web.rs: -------------------------------------------------------------------------------- 1 | //! Test suite for the Web and headless browsers. 2 | 3 | #![cfg(target_arch = "wasm32")] 4 | 5 | extern crate wasm_bindgen_test; 6 | use wasm_bindgen_test::*; 7 | 8 | wasm_bindgen_test_configure!(run_in_browser); 9 | 10 | #[wasm_bindgen_test] 11 | fn pass() { 12 | assert_eq!(1 + 1, 2); 13 | } 14 | -------------------------------------------------------------------------------- /wasm/wasm_api.js: -------------------------------------------------------------------------------- 1 | export function wasm_print(str){ 2 | document.getElementById("output").value += str; 3 | } 4 | 5 | export function wasm_set_fill_style(str){ 6 | const canvas = document.getElementById("canvas"); 7 | const ctx = canvas.getContext('2d'); 8 | ctx.fillStyle = str; 9 | } 10 | 11 | export function wasm_rectangle(x0, y0, x1, y1){ 12 | const canvas = document.getElementById("canvas"); 13 | const ctx = canvas.getContext('2d'); 14 | ctx.fillRect(x0, y0, x1, y1); 15 | } 16 | 17 | export function wasm_set_stroke_style(str){ 18 | const canvas = document.getElementById("canvas"); 19 | const ctx = canvas.getContext('2d'); 20 | ctx.strokeStyle = str; 21 | } 22 | 23 | export function wasm_begin_path(){ 24 | const canvas = document.getElementById("canvas"); 25 | const ctx = canvas.getContext('2d'); 26 | ctx.beginPath(); 27 | } 28 | 29 | export function wasm_move_to(x0, y0){ 30 | const canvas = document.getElementById("canvas"); 31 | const ctx = canvas.getContext('2d'); 32 | ctx.moveTo(x0, y0); 33 | } 34 | 35 | export function wasm_line_to(x0, y0){ 36 | const canvas = document.getElementById("canvas"); 37 | const ctx = canvas.getContext('2d'); 38 | ctx.lineTo(x0, y0); 39 | } 40 | 41 | export function wasm_stroke(){ 42 | const canvas = document.getElementById("canvas"); 43 | const ctx = canvas.getContext('2d'); 44 | ctx.stroke(); 45 | } 46 | 47 | export function wasm_rotate(angle){ 48 | const canvas = document.getElementById("canvas"); 49 | const ctx = canvas.getContext('2d'); 50 | ctx.rotate(angle); 51 | } 52 | 53 | export function wasm_translate(x, y){ 54 | const canvas = document.getElementById("canvas"); 55 | const ctx = canvas.getContext('2d'); 56 | ctx.translate(x, y); 57 | } 58 | 59 | export function wasm_save(){ 60 | const canvas = document.getElementById("canvas"); 61 | const ctx = canvas.getContext('2d'); 62 | ctx.save(); 63 | } 64 | 65 | export function wasm_restore(){ 66 | const canvas = document.getElementById("canvas"); 67 | const ctx = canvas.getContext('2d'); 68 | ctx.restore(); 69 | } 70 | -------------------------------------------------------------------------------- /wasm/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const CopyPlugin = require("copy-webpack-plugin"); 3 | const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin"); 4 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 5 | 6 | const dist = path.resolve(__dirname, "dist"); 7 | 8 | module.exports = { 9 | mode: "production", 10 | entry: { 11 | index: "./js/index.js" 12 | }, 13 | output: { 14 | path: dist, 15 | filename: "[name].js" 16 | }, 17 | devServer: { 18 | contentBase: dist, 19 | }, 20 | plugins: [ 21 | new CopyPlugin({ 22 | patterns: [ 23 | { from: "../scripts", to: "scripts" }, 24 | { from: "scripts", to: "scripts" }, 25 | ] 26 | }), 27 | 28 | new WasmPackPlugin({ 29 | crateDirectory: __dirname, 30 | }), 31 | 32 | new HtmlWebpackPlugin({ 33 | template: "./index.html" 34 | }), 35 | ], 36 | module: { 37 | rules: [ 38 | { 39 | test: /\.html$/i, 40 | loader: 'html-loader', 41 | }, 42 | { 43 | test: /\.(png|jpe?g|gif)$/i, 44 | use: [ 45 | { 46 | loader: 'url-loader', 47 | options: { 48 | limit: 8192, 49 | }, 50 | }, 51 | ], 52 | }, 53 | ] 54 | } 55 | }; 56 | --------------------------------------------------------------------------------