Compare commits

...

57 Commits

Author SHA1 Message Date
92bcb6f358 All tests passing when run with --release. Not sure if this is really correct, or if the algorithm is being too wasteful and re-executing versions of functions taht should have been inlined or something (this may esp be true without the parameter/wrap_level stuff, and also I'm a little sus of the env chains - oh hay, it might even just be becasue only legal env chains are allowed which prevents pe-ing) 2023-03-20 01:06:24 -04:00
48de9517c9 An unvaled Pair should have a True override for its IDs 2023-03-19 11:15:22 -04:00
9162b456d2 Oh some were just changes in formatting. First real issue looks like it's VMAP 2023-03-19 02:03:41 -04:00
1df3acccd7 Some tests passing again, namely all of basic and fact 2023-03-19 01:52:18 -04:00
7b334e96df Finally finished sketching out the new version, lets get on the compile errors 2023-03-19 00:59:46 -04:00
04bf1c6249 Website reformat - content still TBD 2023-03-18 14:57:31 -04:00
d4920ec4b6 Notes for hopefully the full simple kraken PE, with initial implementation of new NeededIds (split between head and tails (heads are ids for which progress will be made, tails might not progress but are contained), body_under and if_under). 2023-03-15 01:16:37 -04:00
865fc1b4b6 Update flake, split ast out into ast & pe_ast, and main into main & test 2023-03-14 20:14:17 -04:00
46e6e27f88 pre change 2023-03-14 20:05:39 -04:00
d836a66e66 more numbers of evals/calls 2023-03-01 00:33:43 -05:00
3df2d02286 Merge branch 'master' into partially_broken 2023-02-28 01:15:48 -05:00
3d6082503c track evals, dyn 0 calls, dyn 1 calls 2023-02-28 01:15:36 -05:00
af2fb537c7 saving remaining before 2023-02-28 01:14:03 -05:00
4752dde4af Added recursive If tracking, but that still doesn't seem to have solved the problem. Have to dig deeper into the actual failed tests now... 2023-02-24 01:19:55 -05:00
abddf1db06 transition to fake-ids instead of rec-hashes. Still have infinate recursion, need to check on it 2023-02-23 13:14:10 -05:00
6357297cd1 been going down withat's probs the wrong path for solving infinate recursion for bvau, did a lot on suspended IF but that doesn't seem to be the issue... Not sure if this was done in vain 2023-02-23 02:48:40 -05:00
bb6b15c156 some bugfixes, and moving towards a reconstruct-on-error. More bugs remain though, ?uncovered? by this, including another infinate loop. Fixed a tricky one where a function would recursively call it self for real while evaluating itself fake, and create an environment that had a loop indirected through subbing itself in for SuspendedEnv (since the real and the fake had the same ID). 2023-02-23 01:38:46 -05:00
e327ed7314 Found the bug. All tests pass PE, except for those that overflow the stack. Those are disabled, and the remaning must be run with --release. Can maybe improve PE tail call to prevent that 2023-02-22 20:16:08 -05:00
bde04e94df Still buggy, but implemented a more tail-recursive PE with non-recursive drop_redundent_veval, special forms SuspendedEval and SuspendedIf, simplification of how primitives work, and more 2023-02-22 01:22:57 -05:00
45a869b09b Remove year and weird (c) from copyright line, concensus is it's not needed these days 2023-02-21 10:53:07 -05:00
21fb47470a Too much debugging to find out PE assert was broken and debugging printlns were overflowing the stack. Some of the other tests also overflow the stack if not built in release mode, and I disabled the stack-testing tests for PE 2023-02-21 10:32:26 -05:00
67feab10bc Add rec-hash-stopping for SuspendedPair calls 2023-02-21 01:48:04 -05:00
76b68e28d8 Implement cached hashes 2023-02-20 22:20:00 -05:00
7f10d111ac Fix attempted in SuspendedPair, a lot more tests also work PE-wise now. Many are overflowing the stack, might be recursion causing or just really bad lack of tail calls, or a bug... 2023-02-20 00:22:29 -05:00
5107c1d7e4 Add in evaling of DeriComb, first let test in fib passes now (but not fib itself) 2023-02-19 23:16:10 -05:00
4d251964a2 Sketch combiner_return_ok and fix DeriComb ids 2023-02-19 20:33:09 -05:00
5df87a53cf Proper progress decisionmaking via NeededIDs and DCtx taking into account ids and hashes (not that we're storing hashes yet) 2023-02-19 19:28:48 -05:00
71326738fa First basic use of suspended lookup progress using the environment, basic tests passing again for pe 2023-02-19 18:52:39 -05:00
91e0641045 Split Ctx into BCtx (bi-directional ctx, must be returned) and DCtx (downwards-ctx, only passed down). Env goes in DCtx, so you don't have to play a replace-back game with ctx when returning from function calls. 2023-02-19 12:37:12 -05:00
283c0232b0 Some steps forward, some back - add sanity testing that eval(e,x) == parial_eval(ctx, x.unval()), start fixing the bugs it reveals, split SuspendedLookup into SuspendedEnvLookup and SuspendedParamLookup 2023-02-19 01:18:59 -05:00
fdaca7f807 Implement basic derived calls, and fix eval not unvaling bug 2023-02-19 00:46:54 -05:00
c5f7a52a38 Implment basic function calling pe 2023-02-18 22:46:23 -05:00
b893787a1b move towards just MarkedForm (with no Value(Form)), with Attempted and MarkedIDs, and sketch out the MarkedForm::PrimComb versions of all the primitives with translation from PrimComb 2023-02-18 19:32:59 -05:00
8b59d5a16a reorginze, start sketching partial eval 2023-02-16 18:21:13 -05:00
520e473415 Add RBTREE and test, along with <, >, <=, >= 2023-02-14 13:18:19 -05:00
f568ee3d50 Add len, finish match 2023-02-14 12:47:48 -05:00
66fc1db606 Implemented Display for Form, then first sketch of MarkedForm, NeededIds, and unval, and Display for MarkedForm 2023-02-14 00:50:05 -05:00
ad3c251ba9 implement non-varidic and/or and start porting match. Need to make and/or varidac and continue match work 2023-02-13 01:08:34 -05:00
3df7d6e0ec Finish converting into individual tests (mostly) - might need to split out and uncomment some should-fail tests 2023-02-13 00:42:54 -05:00
e9b8f636cf Start splitting out the tests into multiples, with the library code at top level in once_cell's Lazy 2023-02-12 16:16:59 -05:00
5838cf0bdd Added 'assert', and changed match_params to assert that when the param tree is nil so are the passed params, which should handle exact length for functions etc.
Added unwrap, lapply, array, the Y combinator, and rlambda. Y and rlambda were almost verbatim copies from old Kraken, with a change for how variadic functions are declared ( '( & args )' vs 'args' ) and a name change.
2023-02-12 13:30:45 -05:00
5512ab8804 Fix warnings, add destructuring let1 2023-02-12 12:19:56 -05:00
30964bf4ec Better BVAU, which does full trees-of-symbols destructuring with varidic support! 2023-02-12 11:56:32 -05:00
c028e975d4 Add wrap, vfoldl, zipd, concat, bvau, and lambda! Need to add varidac handling to bvau, but getting tired 2023-02-11 00:34:24 -05:00
1b813e39fb Fix vapply bug, write vmap, add debug 2023-02-10 23:05:08 -05:00
606972a38b Implement vapply, got around the ever-growing environment 2023-02-10 22:34:04 -05:00
3c2dfbf8a7 Add tail call recursion - works, but if a datastructure is too deep (say, because env keeps growing on the heap) Rc::drop will end up overflowing the stack when trying to deallocate 2023-02-10 19:38:44 -05:00
ba67b8c67b Add "!" syntatic form - a bit like the single quote, but !(a b c) d => !(a b c d). Useful for like !(let a 1) (+ a 3) or w/e. Break out some of the infinate nesting" 2023-02-10 01:01:04 -05:00
3b5cc2c506 Implement a new style of let1 based on direct env manipulation 2023-02-09 01:20:19 -05:00
02e359f42d Finish out the basic primitives along with testing infra for both parsing and evalaution, with some slick Into<> impls to make Rust values Kraken values, which is esp useful for testing 2023-02-08 23:37:23 -05:00
d861d91397 Fix ', add if and = along with bools 2023-02-08 01:54:53 -05:00
c801f604c2 Add derived combiners and fix some bugs with eval, vau, quote, cons, car, cdr 2023-02-07 13:00:15 -05:00
60dad101f8 Speed sketch beginnings of a Rust implementation of new stripped-down Scheme-like Kraken 2023-02-07 02:07:53 -05:00
3807381ceb Sketch out call-info, realized it and function-analysis needs pectx and also err threaded through it, since it can fail (which must be recoverable) and needs env and pectx for partial_eval inside 2023-02-02 01:18:17 -05:00
bea48eb18b Reviewing and making notes about analysises, looking to see if they can be implemented with a generic traversal or something 2023-02-01 01:01:37 -05:00
a038a8cebf Ensure proper env care during memo short circuiting 2023-01-31 22:54:53 -05:00
967ec0feb4 After too much procrastination trying a bunch of parentheses editing plugins (parinfer the most interesting), did a bit of actual work and refactoring where the compiled function is checked for and inserted using both the pre and post partial-eval hash, and the analysis functions are pulled out together into a single meta analysis 2023-01-31 00:59:16 -05:00
21 changed files with 4956 additions and 131 deletions

View File

@@ -1,4 +1,4 @@
Copyright (c) 2020-2022 Nathan Braswell
Copyright Nathan Braswell
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

View File

@@ -13,7 +13,7 @@ with partial evaluation during compilation to make it efficient.
koka_bench: Licensed under Apache-2.0, as they are derived from the benchmarks of the Koka project, see the readme and license in koka_bench for more, or https://github.com/koka-lang/koka for the source project.
Kraken (everything else besides the benchmarks in koka_bench) Licensed under
Kraken (everything else besides the benchmarks in koka_bench, and Recursive/CodeJar/Highlight.js in website/) Licensed under
SPDX-License-Identifier: BSD-2-Clause-Patent
Note: This license is designed to provide: a) a simple permissive license; b) that is compatible with the GNU General Public License (GPL), version 2; and c) which also has an express patent grant included.

88
basic_dyns Normal file
View File

@@ -0,0 +1,88 @@
RB-TREE
evals all_evals evaled_wrap_1 evaled_wrap_0 compiled_dyn_1 compiled_dyn_0
non-PE10 114_170 5_032_297 1_291_489 398_104 1 0
PE10 0 0 0 0 10 0
nonPE9 97087 4278001 1097965 338383 1 0
PE9 0 0 0 0 9 0
nonPE8 80160 3532131 906548 279379 1 0
PE8 0 0 0 0 8 0
nonPE7 67050 2952848 757932 233513 1 0
PE7 0 0 0 0 7 0
nonPE6 50361 2219792 569723 175593 1 0
PE6 0 0 0 0 6 0
nonPE5 37299 1643049 421745 129938 1 0
PE5 0 0 0 0 5 0
nonPE4 24393 1074730 275873 85000 1 0
PE4 0 0 0 0 4 0
nonPE3 15304 672998 172802 53200 1 0
PE3 0 0 0 0 3 0
nonPE2 6453 284080 72939 22484 1 0
PE2 0 0 0 0 2 0
nonPE1 1385 59899 15413 4750 1 0
PE1 0 0 0 0 1 0
Fib
evals all_evals evaled_wrap_1 evaled_wrap_0 compiled_dyn_1 compiled_dyn_0
non-PE35 29860726 1320920726 337695363 119442881 1 0
non-PE30 2692560 119107888 30450112 10770217 1 0
non-PE25 242808 10740492 2745825 971209 1 0
non-PE20 21914 969010 247731 87633 1 0
non-PE15 1996 87916 22478 7961 1 0
non-PE10 200 8468 2167 777 1 0
PE10 0 0 0 0 0 0
PE15 0 0 0 0 0 0
PE20 0 0 0 0 0 0
PE25 0 0 0 0 0 0
PE30 0 0 0 0 0 0
PE35 0 0 0 0 0 0
cfold
evals all_evals evaled_wrap_1 evaled_wrap_0 compiled_dyn_1 compiled_dyn_0
non-PE5 239660 10897376 2784275 879066 1 0
PE5 0 0 0 0 0 0
deriv
evals all_evals evaled_wrap_1 evaled_wrap_0 compiled_dyn_1 compiled_dyn_0
non-PE2 257693 11708558 2990090 946500 1 0
PE2 0 0 0 0 2 0
nqueens
evals all_evals evaled_wrap_1 evaled_wrap_0 compiled_dyn_1 compiled_dyn_0
non-PE7 271720 13530241 3429161 1108393 1 0
PE7 0 0 0 0 0 0
scheme --script ../../partial_eval.scm rbtree-opt.kp no_partial_eval && mv csc_out.wasm rbtree-opt.wasm && time wasmtime ./rbtree-opt.wasm 10
scheme --script ../../partial_eval.scm rbtree-opt.kp && mv csc_out.wasm rbtree-opt.wasm && time wasmtime ./rbtree-opt.wasm 10

24
flake.lock generated
View File

@@ -2,11 +2,11 @@
"nodes": {
"flake-utils": {
"locked": {
"lastModified": 1667395993,
"narHash": "sha256-nuEHfE/LcWyuSWnS8t12N1wc105Qtau+/OdUAjtQ0rA=",
"lastModified": 1676283394,
"narHash": "sha256-XX2f9c3iySLCw54rJ/CZs+ZK6IQy7GXNY4nSOyu2QG4=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "5aed5285a952e0b949eb3ba02c12fa4fcfef535f",
"rev": "3db36a8b464d0c4532ba1c7dda728f4576d6d073",
"type": "github"
},
"original": {
@@ -36,11 +36,11 @@
"nixpkgs": "nixpkgs"
},
"locked": {
"lastModified": 1673836088,
"narHash": "sha256-cAlfrHbX9sLcRdydMP8vhyxZChlVHqkEkumgc2LK4FY=",
"lastModified": 1678760344,
"narHash": "sha256-N8u9/O0NWt3PUQc9xmCeod1SFilOFicALjtYtslib2g=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "8f201a1adfddf715b708befd18164c8cbe65a268",
"rev": "d907affef544f64bd6886fe6bcc5fa2495a82373",
"type": "github"
},
"original": {
@@ -67,11 +67,11 @@
},
"nixpkgs_stable_new": {
"locked": {
"lastModified": 1673800717,
"narHash": "sha256-SFHraUqLSu5cC6IxTprex/nTsI81ZQAtDvlBvGDWfnA=",
"lastModified": 1678703398,
"narHash": "sha256-Y1mW3dBsoWLHpYm+UIHb5VZ7rx024NNHaF16oZBx++o=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "2f9fd351ec37f5d479556cd48be4ca340da59b8f",
"rev": "67f26c1cfc5d5783628231e776a81c1ade623e0b",
"type": "github"
},
"original": {
@@ -97,11 +97,11 @@
},
"nixpkgs_unstable": {
"locked": {
"lastModified": 1673914939,
"narHash": "sha256-CfsyGi3y/ok7se6wd/OD+F8muVRZ1zYdE/0wsV2C/u8=",
"lastModified": 1678838343,
"narHash": "sha256-aA48yVAUyppdlVHhMStlWjB8u9uzA5iel3C47xlbkrw=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "341aa70d1e5098d6c01791e1175baa84793b3aae",
"rev": "b16f2a75619fe8e6adf4583f5fc6448bc967d482",
"type": "github"
},
"original": {

1
kr/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
target

559
kr/Cargo.lock generated Normal file
View File

@@ -0,0 +1,559 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "aho-corasick"
version = "0.7.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc936419f96fa211c1b9166887b38e5e40b19958e5b895be7c1f93adec7071ac"
dependencies = [
"memchr",
]
[[package]]
name = "anyhow"
version = "1.0.70"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7de8ce5e0f9f8d88245311066a578d72b7af3e7088f32783804676302df237e4"
[[package]]
name = "ascii-canvas"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8824ecca2e851cec16968d54a01dd372ef8f95b244fb84b84e70128be347c3c6"
dependencies = [
"term",
]
[[package]]
name = "atty"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
dependencies = [
"hermit-abi",
"libc",
"winapi",
]
[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "bit-set"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1"
dependencies = [
"bit-vec",
]
[[package]]
name = "bit-vec"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "crunchy"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7"
[[package]]
name = "diff"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8"
[[package]]
name = "dirs-next"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1"
dependencies = [
"cfg-if",
"dirs-sys-next",
]
[[package]]
name = "dirs-sys-next"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d"
dependencies = [
"libc",
"redox_users",
"winapi",
]
[[package]]
name = "either"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91"
[[package]]
name = "ena"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7402b94a93c24e742487327a7cd839dc9d36fec9de9fb25b09f2dae459f36c3"
dependencies = [
"log",
]
[[package]]
name = "fixedbitset"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
[[package]]
name = "getrandom"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "hashbrown"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
[[package]]
name = "hermit-abi"
version = "0.1.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
dependencies = [
"libc",
]
[[package]]
name = "indexmap"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885e79c1fc4b10f0e172c475f458b7f7b93061064d98c3293e98c5ba0c8b399"
dependencies = [
"autocfg",
"hashbrown",
]
[[package]]
name = "itertools"
version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
dependencies = [
"either",
]
[[package]]
name = "kr"
version = "0.1.0"
dependencies = [
"anyhow",
"lalrpop",
"lalrpop-util",
"once_cell",
"regex",
]
[[package]]
name = "lalrpop"
version = "0.19.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b30455341b0e18f276fa64540aff54deafb54c589de6aca68659c63dd2d5d823"
dependencies = [
"ascii-canvas",
"atty",
"bit-set",
"diff",
"ena",
"itertools",
"lalrpop-util",
"petgraph",
"pico-args",
"regex",
"regex-syntax",
"string_cache",
"term",
"tiny-keccak",
"unicode-xid",
]
[[package]]
name = "lalrpop-util"
version = "0.19.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bcf796c978e9b4d983414f4caedc9273aa33ee214c5b887bd55fde84c85d2dc4"
dependencies = [
"regex",
]
[[package]]
name = "libc"
version = "0.2.139"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79"
[[package]]
name = "lock_api"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df"
dependencies = [
"autocfg",
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e"
dependencies = [
"cfg-if",
]
[[package]]
name = "memchr"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
[[package]]
name = "new_debug_unreachable"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4a24736216ec316047a1fc4252e27dabb04218aa4a3f37c6e7ddbf1f9782b54"
[[package]]
name = "once_cell"
version = "1.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f61fba1741ea2b3d6a1e3178721804bb716a68a6aeba1149b5d52e3d464ea66"
[[package]]
name = "parking_lot"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-sys",
]
[[package]]
name = "petgraph"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4dd7d28ee937e54fe3080c91faa1c3a46c06de6252988a7f4592ba2310ef22a4"
dependencies = [
"fixedbitset",
"indexmap",
]
[[package]]
name = "phf_shared"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096"
dependencies = [
"siphasher",
]
[[package]]
name = "pico-args"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db8bcd96cb740d03149cbad5518db9fd87126a10ab519c011893b1754134c468"
[[package]]
name = "precomputed-hash"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
[[package]]
name = "proc-macro2"
version = "1.0.51"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d727cae5b39d21da60fa540906919ad737832fe0b1c165da3a34d6548c849d6"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b"
dependencies = [
"proc-macro2",
]
[[package]]
name = "redox_syscall"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a"
dependencies = [
"bitflags",
]
[[package]]
name = "redox_users"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b"
dependencies = [
"getrandom",
"redox_syscall",
"thiserror",
]
[[package]]
name = "regex"
version = "1.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48aaa5748ba571fb95cd2c85c09f629215d3a6ece942baa100950af03a34f733"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.6.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848"
[[package]]
name = "rustversion"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5583e89e108996506031660fe09baa5011b9dd0341b89029313006d1fb508d70"
[[package]]
name = "scopeguard"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]]
name = "siphasher"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7bd3e3206899af3f8b12af284fafc038cc1dc2b41d1b89dd17297221c5d225de"
[[package]]
name = "smallvec"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0"
[[package]]
name = "string_cache"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "213494b7a2b503146286049378ce02b482200519accc31872ee8be91fa820a08"
dependencies = [
"new_debug_unreachable",
"once_cell",
"parking_lot",
"phf_shared",
"precomputed-hash",
]
[[package]]
name = "syn"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f4064b5b16e03ae50984a5a8ed5d4f8803e6bc1fd170a3cda91a1be4b18e3f5"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "term"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c59df8ac95d96ff9bede18eb7300b0fda5e5d8d90960e76f8e14ae765eedbf1f"
dependencies = [
"dirs-next",
"rustversion",
"winapi",
]
[[package]]
name = "thiserror"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a9cd18aa97d5c45c6603caea1da6628790b37f7a34b6ca89522331c5180fed0"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fb327af4685e4d03fa8cbcf1716380da910eeb2bb8be417e7f9fd3fb164f36f"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tiny-keccak"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"
dependencies = [
"crunchy",
]
[[package]]
name = "unicode-ident"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc"
[[package]]
name = "unicode-xid"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-sys"
version = "0.45.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e2522491fbfcd58cc84d47aeb2958948c4b8982e9a2d8a2a35bbaed431390e7"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c9864e83243fdec7fc9c5444389dcbbfd258f745e7853198f365e3c4968a608"
[[package]]
name = "windows_aarch64_msvc"
version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c8b1b673ffc16c47a9ff48570a9d85e25d265735c503681332589af6253c6c7"
[[package]]
name = "windows_i686_gnu"
version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de3887528ad530ba7bdbb1faa8275ec7a1155a45ffa57c37993960277145d640"
[[package]]
name = "windows_i686_msvc"
version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf4d1122317eddd6ff351aa852118a2418ad4214e6613a50e0191f7004372605"
[[package]]
name = "windows_x86_64_gnu"
version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1040f221285e17ebccbc2591ffdc2d44ee1f9186324dd3e84e99ac68d699c45"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "628bfdf232daa22b0d64fdb62b09fcc36bb01f05a3939e20ab73aaf9470d0463"
[[package]]
name = "windows_x86_64_msvc"
version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd"

16
kr/Cargo.toml Normal file
View File

@@ -0,0 +1,16 @@
[package]
name = "kr"
version = "0.1.0"
edition = "2021"
build = "build.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
lalrpop-util = {version="0.19.7", features=["lexer"]}
regex = "1"
once_cell = "1.17.0"
anyhow = "1"
[build-dependencies]
lalrpop = "0.19.7"

5
kr/build.rs Normal file
View File

@@ -0,0 +1,5 @@
extern crate lalrpop;
fn main() {
lalrpop::process_root().unwrap();
}

338
kr/src/ast.rs Normal file
View File

@@ -0,0 +1,338 @@
use std::fmt;
use std::rc::Rc;
use std::convert::From;
// TODO:
// -extend vau & env logic and SuspendedPair PE with sequence_params & wrap_level
// -add current-hashes to if
// -expand combiner_Return_ok with (func ...params) | func doesn't take de and func+params are return ok
// -add recursive drop redundent veval
// -mark rec-hash on DeriComb
// -add compiler
//
// -use current fake comb ids instead of hashes
// -do they have to be added to not-under thing like hashes
// -make cons work only for SuspendedParam/Env
impl From<i32> for Form { fn from(item: i32) -> Self { Form::Int(item) } }
impl From<bool> for Form { fn from(item: bool) -> Self { Form::Bool(item) } }
// todo, strings not symbols?
impl From<String> for Form { fn from(item: String) -> Self { Form::Symbol(item) } }
impl From<&str> for Form { fn from(item: &str) -> Self { Form::Symbol(item.to_owned()) } }
impl<A: Into<Form>, B: Into<Form>> From<(A, B)> for Form {
fn from(item: (A, B)) -> Self {
Form::Pair(Rc::new(item.0.into()), Rc::new(item.1.into()))
}
}
pub enum PossibleTailCall {
Result(Rc<Form>),
TailCall(Rc<Form>, Rc<Form>),
}
#[derive(Debug, Eq, PartialEq)]
pub enum Form {
Nil,
Int(i32),
Bool(bool),
Symbol(String),
Pair(Rc<Form>,Rc<Form>),
PrimComb(String, fn(Rc<Form>, Rc<Form>) -> PossibleTailCall),
DeriComb { se: Rc<Form>, de: Option<String>, params: String, body: Rc<Form> },
}
impl Form {
pub fn truthy(&self) -> bool {
match self {
Form::Bool(b) => *b,
Form::Nil => false,
_ => true,
}
}
pub fn int(&self) -> Option<i32> {
match self {
Form::Int(i) => Some(*i),
_ => None,
}
}
pub fn sym(&self) -> Option<&str> {
match self {
Form::Symbol(s) => Some(s),
_ => None,
}
}
pub fn car(&self) -> Option<Rc<Form>> {
match self {
Form::Pair(car, _cdr) => Some(Rc::clone(car)),
_ => None,
}
}
pub fn cdr(&self) -> Option<Rc<Form>> {
match self {
Form::Pair(_car, cdr) => Some(Rc::clone(cdr)),
_ => None,
}
}
pub fn append(&self, x: Rc<Form>) -> Option<Form> {
match self {
Form::Pair(car, cdr) => cdr.append(x).map(|x| Form::Pair(Rc::clone(car), Rc::new(x))),
Form::Nil => Some(Form::Pair(x, Rc::new(Form::Nil))),
_ => None,
}
}
}
impl fmt::Display for Form {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Form::Nil => write!(f, "nil"),
Form::Int(i) => write!(f, "{}", i),
Form::Bool(b) => write!(f, "{}", b),
Form::Symbol(s) => write!(f, "{}", s),
Form::Pair(car, cdr) => {
write!(f, "({}", car)?;
let mut traverse: Rc<Form> = Rc::clone(cdr);
loop {
match &*traverse {
Form::Pair(ref carp, ref cdrp) => {
write!(f, " {}", carp)?;
traverse = Rc::clone(cdrp);
},
Form::Nil => {
write!(f, ")")?;
return Ok(());
},
x => {
write!(f, ". {})", x)?;
return Ok(());
},
}
}
},
Form::PrimComb(name, _f) => write!(f, "<{}>", name),
Form::DeriComb { se, de, params, body } => {
write!(f, "<{} {} {}>", de.as_ref().unwrap_or(&"".to_string()), params, body)
},
}
}
}
pub fn eval(e: Rc<Form>, f: Rc<Form>) -> Rc<Form> {
let mut e = e;
let mut x = Option::Some(f);
loop {
let cur = x.take().unwrap();
//println!("Evaluating {:?} in {:?}", cur, e);
match *cur {
Form::Symbol(ref s) => {
let mut t = e;
//println!("Looking up {} in {:?}", s, t);
//println!("Looking up {}", s);
while s != t.car().unwrap().car().unwrap().sym().unwrap() {
t = t.cdr().unwrap();
}
return t.car().unwrap().cdr().unwrap();
},
Form::Pair(ref c, ref p) => {
let comb = eval(Rc::clone(&e), Rc::clone(c));
match *comb {
Form::PrimComb(ref _n, ref f) => match f(e, Rc::clone(p)) {
PossibleTailCall::Result(r) => return r,
PossibleTailCall::TailCall(ne, nx) => {
e = ne;
x = Some(nx);
},
},
Form::DeriComb{ref se, ref de, ref params, ref body } => {
let mut new_e = Rc::clone(se);
if let Some(de) = de {
new_e = assoc(de, Rc::clone(&e), new_e);
}
new_e = assoc(params, Rc::clone(p), new_e);
// always a tail call
e = new_e;
x = Some(Rc::clone(body));
},
_ => panic!("Tried to call not a Prim/DeriComb {:?}", comb),
}
},
_ => return cur,
}
}
}
fn assoc(k: &str, v: Rc<Form>, l: Rc<Form>) -> Rc<Form> {
Rc::new(Form::Pair(
Rc::new(Form::Pair(
Rc::new(Form::Symbol(k.to_owned())),
v)),
l))
}
fn assoc_vec(kvs: Vec<(&str, Rc<Form>)>) -> Rc<Form> {
let mut to_ret = Rc::new(Form::Nil);
for (k, v) in kvs {
to_ret = assoc(k, v, to_ret);
}
to_ret
}
pub fn root_env() -> Rc<Form> {
assoc_vec(vec![
("eval", Rc::new(Form::PrimComb("eval".to_owned(), |e, p| {
let b = eval(Rc::clone(&e), p.car().unwrap());
let e = eval(e, p.cdr().unwrap().car().unwrap());
PossibleTailCall::TailCall(e, b)
}))),
// (vau de params body)
("vau", Rc::new(Form::PrimComb("vau".to_owned(), |e, p| {
let de = p.car().unwrap().sym().map(|s| s.to_owned());
let params = p.cdr().unwrap().car().unwrap().sym().unwrap().to_owned();
let body = p.cdr().unwrap().cdr().unwrap().car().unwrap();
PossibleTailCall::Result(Rc::new(Form::DeriComb { se: e, de, params, body }))
}))),
("=", Rc::new(Form::PrimComb("=".to_owned(), |e, p| {
let a = eval(Rc::clone(&e), p.car().unwrap());
let b = eval(e, p.cdr().unwrap().car().unwrap());
PossibleTailCall::Result(Rc::new(Form::Bool(a == b)))
}))),
("<", Rc::new(Form::PrimComb("<".to_owned(), |e, p| {
let a = eval(Rc::clone(&e), p.car().unwrap());
let b = eval(e, p.cdr().unwrap().car().unwrap());
PossibleTailCall::Result(Rc::new(Form::Bool(a.int().unwrap() < b.int().unwrap())))
}))),
(">", Rc::new(Form::PrimComb(">".to_owned(), |e, p| {
let a = eval(Rc::clone(&e), p.car().unwrap());
let b = eval(e, p.cdr().unwrap().car().unwrap());
PossibleTailCall::Result(Rc::new(Form::Bool(a.int().unwrap() > b.int().unwrap())))
}))),
("<=", Rc::new(Form::PrimComb("<=".to_owned(), |e, p| {
let a = eval(Rc::clone(&e), p.car().unwrap());
let b = eval(e, p.cdr().unwrap().car().unwrap());
PossibleTailCall::Result(Rc::new(Form::Bool(a.int().unwrap() <= b.int().unwrap())))
}))),
(">=", Rc::new(Form::PrimComb(">=".to_owned(), |e, p| {
let a = eval(Rc::clone(&e), p.car().unwrap());
let b = eval(e, p.cdr().unwrap().car().unwrap());
PossibleTailCall::Result(Rc::new(Form::Bool(a.int().unwrap() >= b.int().unwrap())))
}))),
("if", Rc::new(Form::PrimComb("if".to_owned(), |e, p| {
if eval(Rc::clone(&e), p.car().unwrap()).truthy() {
PossibleTailCall::TailCall(e, p.cdr().unwrap().car().unwrap())
} else {
PossibleTailCall::TailCall(e, p.cdr().unwrap().cdr().unwrap().car().unwrap())
}
}))),
("cons", Rc::new(Form::PrimComb("cons".to_owned(), |e, p| {
let h = eval(Rc::clone(&e), p.car().unwrap());
let t = eval(e, p.cdr().unwrap().car().unwrap());
PossibleTailCall::Result(Rc::new(Form::Pair(h, t)))
}))),
("car", Rc::new(Form::PrimComb("car".to_owned(), |e, p| {
PossibleTailCall::Result(eval(Rc::clone(&e), p.car().unwrap()).car().unwrap())
}))),
("cdr", Rc::new(Form::PrimComb("cdr".to_owned(), |e, p| {
PossibleTailCall::Result(eval(Rc::clone(&e), p.car().unwrap()).cdr().unwrap())
}))),
("quote", Rc::new(Form::PrimComb("quote".to_owned(), |_e, p| {
PossibleTailCall::Result(p.car().unwrap())
}))),
("debug", Rc::new(Form::PrimComb("debug".to_owned(), |e, p| {
//println!("Debug: {:?}", eval(Rc::clone(&e), p.car().unwrap()));
println!("Debug: {}", eval(Rc::clone(&e), p.car().unwrap()));
PossibleTailCall::TailCall(e, p.cdr().unwrap().car().unwrap())
}))),
("assert", Rc::new(Form::PrimComb("assert".to_owned(), |e, p| {
let thing = eval(Rc::clone(&e), p.car().unwrap());
if !thing.truthy() {
println!("Assert failed: {:?}", thing);
}
assert!(thing.truthy());
PossibleTailCall::TailCall(e, p.cdr().unwrap().car().unwrap())
}))),
("+", Rc::new(Form::PrimComb("+".to_owned(), |e, p| {
let a = eval(Rc::clone(&e), p.car().unwrap()).int().unwrap();
let b = eval(e, p.cdr().unwrap().car().unwrap()).int().unwrap();
PossibleTailCall::Result(Rc::new(Form::Int(a + b)))
}))),
("-", Rc::new(Form::PrimComb("-".to_owned(), |e, p| {
let a = eval(Rc::clone(&e), p.car().unwrap()).int().unwrap();
let b = eval(e, p.cdr().unwrap().car().unwrap()).int().unwrap();
PossibleTailCall::Result(Rc::new(Form::Int(a - b)))
}))),
("*", Rc::new(Form::PrimComb("*".to_owned(), |e, p| {
let a = eval(Rc::clone(&e), p.car().unwrap()).int().unwrap();
let b = eval(e, p.cdr().unwrap().car().unwrap()).int().unwrap();
PossibleTailCall::Result(Rc::new(Form::Int(a * b)))
}))),
("/", Rc::new(Form::PrimComb("/".to_owned(), |e, p| {
let a = eval(Rc::clone(&e), p.car().unwrap()).int().unwrap();
let b = eval(e, p.cdr().unwrap().car().unwrap()).int().unwrap();
PossibleTailCall::Result(Rc::new(Form::Int(a / b)))
}))),
("%", Rc::new(Form::PrimComb("%".to_owned(), |e, p| {
let a = eval(Rc::clone(&e), p.car().unwrap()).int().unwrap();
let b = eval(e, p.cdr().unwrap().car().unwrap()).int().unwrap();
PossibleTailCall::Result(Rc::new(Form::Int(a % b)))
}))),
("&", Rc::new(Form::PrimComb("&".to_owned(), |e, p| {
let a = eval(Rc::clone(&e), p.car().unwrap()).int().unwrap();
let b = eval(e, p.cdr().unwrap().car().unwrap()).int().unwrap();
PossibleTailCall::Result(Rc::new(Form::Int(a & b)))
}))),
("|", Rc::new(Form::PrimComb("|".to_owned(), |e, p| {
let a = eval(Rc::clone(&e), p.car().unwrap()).int().unwrap();
let b = eval(e, p.cdr().unwrap().car().unwrap()).int().unwrap();
PossibleTailCall::Result(Rc::new(Form::Int(a | b)))
}))),
("^", Rc::new(Form::PrimComb("^".to_owned(), |e, p| {
let a = eval(Rc::clone(&e), p.car().unwrap()).int().unwrap();
let b = eval(e, p.cdr().unwrap().car().unwrap()).int().unwrap();
PossibleTailCall::Result(Rc::new(Form::Int(a ^ b)))
}))),
("comb?", Rc::new(Form::PrimComb("comb?".to_owned(), |e, p| {
PossibleTailCall::Result(Rc::new(Form::Bool(match &*eval(e, p.car().unwrap()) {
Form::PrimComb(_n, _f) => true,
Form::DeriComb { .. } => true,
_ => false,
})))
}))),
("pair?", Rc::new(Form::PrimComb("pair?".to_owned(), |e, p| {
PossibleTailCall::Result(Rc::new(Form::Bool(match &*eval(e, p.car().unwrap()) {
Form::Pair(_a,_b) => true,
_ => false,
})))
}))),
("symbol?", Rc::new(Form::PrimComb("symbol?".to_owned(), |e, p| {
PossibleTailCall::Result(Rc::new(Form::Bool(match &*eval(e, p.car().unwrap()) {
Form::Symbol(_) => true,
_ => false,
})))
}))),
("int?", Rc::new(Form::PrimComb("int?".to_owned(), |e, p| {
PossibleTailCall::Result(Rc::new(Form::Bool(match &*eval(e, p.car().unwrap()) {
Form::Int(_) => true,
_ => false,
})))
}))),
// maybe bool? but also could be derived. Nil def
("bool?", Rc::new(Form::PrimComb("bool?".to_owned(), |e, p| {
PossibleTailCall::Result(Rc::new(Form::Bool(match &*eval(e, p.car().unwrap()) {
Form::Bool(_) => true,
_ => false,
})))
}))),
("nil?", Rc::new(Form::PrimComb("nil?".to_owned(), |e, p| {
PossibleTailCall::Result(Rc::new(Form::Bool(match &*eval(e, p.car().unwrap()) {
Form::Nil => true,
_ => false,
})))
}))),
// consts
("true", Rc::new(Form::Bool(true))),
("false", Rc::new(Form::Bool(false))),
("nil", Rc::new(Form::Nil)),
])
}

31
kr/src/grammar.lalrpop Normal file
View File

@@ -0,0 +1,31 @@
use std::str::FromStr;
use std::rc::Rc;
use crate::ast::Form;
grammar;
pub Term: Form = {
NUM => Form::Int(i32::from_str(<>).unwrap()),
SYM => Form::Symbol(<>.to_owned()),
"(" <ListInside?> ")" => <>.unwrap_or(Form::Nil),
"'" <Term> => Form::Pair(Rc::new(Form::Symbol("quote".to_owned())), Rc::new(Form::Pair(Rc::new(<>), Rc::new(Form::Nil)))),
"!" <h: Term> <t: Term> => {
h.append(Rc::new(t)).unwrap()
},
};
ListInside: Form = {
<Term> => Form::Pair(Rc::new(<>), Rc::new(Form::Nil)),
<h: Term> <t: ListInside> => Form::Pair(Rc::new(h), Rc::new(t)),
<a: Term> "." <d: Term> => Form::Pair(Rc::new(a), Rc::new(d)),
}
match {
"(",
")",
".",
"'",
"!",
r"[0-9]+" => NUM,
r"[a-zA-Z+*/_=?%&|^<>-][\w+*/=_?%&|^<>-]*" => SYM,
r"(;[^\n]*\n)|\s+" => { }
}

26
kr/src/main.rs Normal file
View File

@@ -0,0 +1,26 @@
#[macro_use] extern crate lalrpop_util;
lalrpop_mod!(pub grammar);
use std::rc::Rc;
mod ast;
use crate::ast::{eval,root_env};
mod pe_ast;
use crate::pe_ast::{mark,partial_eval,new_base_ctxs};
mod test;
fn main() {
let input = "(= 17 ((vau d p (+ (eval (car p) d) 13)) (+ 1 3)))";
let parsed_input = Rc::new(grammar::TermParser::new().parse(input).unwrap());
println!("Parsed input is {} - {:?}", parsed_input, parsed_input);
let (bctx, dctx) = new_base_ctxs();
let (bctx, marked) = mark(Rc::clone(&parsed_input),bctx);
let unvaled = marked.unval().unwrap();
println!("Parsed unvaled that is {}", unvaled);
let (bctx, ped) = partial_eval(bctx, dctx, unvaled).unwrap();
let result = eval(root_env(), parsed_input);
println!("Result is {} - {:?}", result, result);
}

1042
kr/src/pe_ast.rs Normal file

File diff suppressed because it is too large Load Diff

617
kr/src/test.rs Normal file
View File

@@ -0,0 +1,617 @@
use std::rc::Rc;
use crate::grammar;
use crate::ast::{eval,root_env,Form,PossibleTailCall};
use crate::pe_ast::{mark,partial_eval,new_base_ctxs,MarkedForm};
#[test]
fn parse_test() {
let g = grammar::TermParser::new();
for test in [
"22", "(22)", "(((22)))",
"(22 )", "()", "( )", "( 44)", "(44 )",
"(22 44 (1) 33 (4 5 (6) 6))", "hello",
"-", "+", "(+ 1 ;hi
3)", "'13", "hello-world", "_",
] {
assert!(g.parse(test).is_ok());
}
assert!(g.parse("((22)").is_err());
}
fn eval_test<T: Into<Form>>(also_pe: bool, gram: &grammar::TermParser, e: &Rc<Form>, code: &str, expected: T) {
println!("Doing test {}", code);
let parsed = Rc::new(gram.parse(code).unwrap());
let basic_result = eval(Rc::clone(e), Rc::clone(&parsed));
assert_eq!(*basic_result, expected.into());
if also_pe {
let (bctx, dctx) = new_base_ctxs();
let (bctx, marked) = mark(parsed,bctx);
let unvaled = marked.unval().unwrap();
let (bctx, ped) = partial_eval(bctx, dctx, unvaled).unwrap();
let (bctx, marked_basic_result) = mark(basic_result,bctx);
println!("Final PE {}", ped);
println!("wanted {}", marked_basic_result);
assert_eq!(*ped, *marked_basic_result);
}
}
fn partial_eval_test(gram: &grammar::TermParser, code: &str, expected: &str) {
println!("Doing PE test {}", code);
let parsed = Rc::new(gram.parse(code).unwrap());
let (bctx, dctx) = new_base_ctxs();
let (bctx, marked) = mark(parsed,bctx);
let unvaled = marked.unval().unwrap();
let (bctx, ped) = partial_eval(bctx, dctx, unvaled).unwrap();
println!("Final PE {}", ped);
println!("wanted {}", expected);
assert_eq!(format!("{}", ped), expected);
}
#[test]
fn basic_pe_test() {
let g = grammar::TermParser::new();
partial_eval_test(&g, "(+ 2 (car (cons 4 '(1 2))))", "6");
partial_eval_test(&g, "(vau 0 p (+ 1 2))", "NeededIds { heads: {}, tails: {}, body_stopped: {}, if_stopped: {} }#[None/None/EnvID(1)/0/[]/Some(\"p\")/3]");
}
#[test]
fn basic_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
eval_test(true, &g, &e, "(+ 2 (car (cons 4 '(1 2))))", 6);
eval_test(true, &g, &e, "(= 17 ((vau d p (+ (eval (car p) d) 13)) (+ 1 3)))", true);
eval_test(true, &g, &e, "(if (= 2 2) (+ 1 2) (+ 3 4))", 3);
eval_test(true, &g, &e, "(quote a)", "a");
eval_test(true, &g, &e, "'a", "a");
eval_test(true, &g, &e, "'(1 . a)", (1, "a"));
eval_test(true, &g, &e, "'(1 a)", (1, ("a", Form::Nil)));
eval_test(true, &g, &e, "true", true);
eval_test(true, &g, &e, "false", false);
eval_test(true, &g, &e, "nil", Form::Nil);
eval_test(true, &g, &e, "(+ 1 2)", 3);
eval_test(true, &g, &e, "(- 1 2)", -1);
eval_test(true, &g, &e, "(* 1 2)", 2);
eval_test(true, &g, &e, "(/ 4 2)", 2);
eval_test(true, &g, &e, "(% 3 2)", 1);
eval_test(true, &g, &e, "(& 3 2)", 2);
eval_test(true, &g, &e, "(| 2 1)", 3);
eval_test(true, &g, &e, "(^ 2 1)", 3);
eval_test(true, &g, &e, "(^ 3 1)", 2);
eval_test(true, &g, &e, "(< 3 1)", false);
eval_test(true, &g, &e, "(<= 3 1)", false);
eval_test(true, &g, &e, "(> 3 1)", true);
eval_test(true, &g, &e, "(>= 3 1)", true);
eval_test(true, &g, &e, "(comb? +)", true);
eval_test(true, &g, &e, "(comb? (vau d p 1))", true);
eval_test(true, &g, &e, "(comb? 1)", false);
eval_test(true, &g, &e, "(pair? '(a))", true);
//eval_test(true, &g, &e, "(pair? '())", true);
eval_test(true, &g, &e, "(nil? nil)", true);
eval_test(true, &g, &e, "(nil? 1)", false);
eval_test(true, &g, &e, "(pair? 1)", false);
eval_test(true, &g, &e, "(symbol? 'a)", true);
eval_test(true, &g, &e, "(symbol? 1)", false);
eval_test(true, &g, &e, "(int? 1)", true);
eval_test(true, &g, &e, "(int? true)", false);
eval_test(true, &g, &e, "(bool? true)", true);
eval_test(true, &g, &e, "(bool? 1)", false);
eval_test(true, &g, &e, "!(bool?) 1", false);
eval_test(true, &g, &e, "!(bool?) true", true);
eval_test(true, &g, &e, "((vau root_env _ (eval 'a (cons (cons 'a 2) root_env))))", 2);
eval_test(true, &g, &e, "'name-dash", "name-dash");
}
use once_cell::sync::Lazy;
static LET: Lazy<String> = Lazy::new(|| {
"!((vau root_env p (eval (car p)
(cons (cons 'let1
(vau de p (eval (car (cdr (cdr p))) (cons (cons (car p) (eval (car (cdr p)) de)) de)))
) root_env))))".to_owned()
});
#[test]
fn let_pe_test() {
let g = grammar::TermParser::new();
partial_eval_test(&g, &format!("{} (let1 a 2 (+ a (car (cons 4 '(1 2)))))", *LET), "6");
partial_eval_test(&g, &format!("{} (let1 a 2 (vau 0 p (+ 1 a)))", *LET),"NeededIds { heads: {}, tails: {}, body_stopped: {}, if_stopped: {} }#[None/None/EnvID(3)/0/[]/Some(\"p\")/3]");
partial_eval_test(&g, &format!("{}
!(let1 a 2)
(vau 0 p (+ 1 a))
", *LET), "NeededIds { heads: {}, tails: {}, body_stopped: {}, if_stopped: {} }#[None/None/EnvID(3)/0/[]/Some(\"p\")/3]");
partial_eval_test(&g, &format!("{}
!(let1 a 2)
!(let1 b 5)
(vau 0 p (+ b a))
", *LET), "NeededIds { heads: {}, tails: {}, body_stopped: {}, if_stopped: {} }#[None/None/EnvID(3)/0/[]/Some(\"p\")/7]");
/*
partial_eval_test(&g, &format!("{}
(vau 0 p
!(let1 a 2)
!(let1 b 5)
(+ b a)
)
", *LET), "None({})#[None/None/EnvID(0)/0/[]/Some(\"p\")/7]");
partial_eval_test(&g, &format!("{}
(vau d p
!(let1 a 2)
(+ (eval (car p) d) a)
)
", *LET), "None({})#[None/None/EnvID(2)/0/[]/Some(\"p\")/7]");
*/
}
#[test]
fn fib_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
eval_test(true, &g, &e, &format!("{} (let1 x 10 (+ x 7))", *LET), 17);
let def_fib = "
!(let1 fib (vau de p
!(let1 self (eval (car p) de))
!(let1 n (eval (car (cdr p)) de))
!(if (= 0 n) 0)
!(if (= 1 n) 1)
(+ (self self (- n 1)) (self self (- n 2)))
))";
eval_test(false, &g, &e, &format!("{} {} (fib fib 6)", *LET, def_fib), 8);
}
#[test]
fn fact_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
let def_fact = "
!(let1 fact (vau de p
!(let1 self (eval (car p) de))
!(let1 n (eval (car (cdr p)) de))
!(if (= 0 n) 1)
(* n (self self (- n 1)))
))";
eval_test(true, &g, &e, &format!("{} {} (fact fact 6)", *LET, def_fact), 720);
}
static VAPPLY: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 vapply (vau de p
!(let1 f (eval (car p) de))
!(let1 ip (eval (car (cdr p)) de))
!(let1 nde (eval (car (cdr (cdr p))) de))
(eval (cons f ip) nde)
))", *LET)
});
#[test]
fn vapply_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
// need the vapply to keep env in check because otherwise the env keeps growing
// and the Rc::drop will overflow the stack lol
let def_badid = format!("
{}
!(let1 badid (vau de p
!(let1 inner (vau ide ip
!(let1 self (car ip))
!(let1 n (car (cdr ip)))
!(let1 acc (car (cdr (cdr ip))))
!(if (= 0 n) acc)
(vapply self (cons self (cons (- n 1) (cons (+ acc 1) nil))) de)
))
(vapply inner (cons inner (cons (eval (car p) de) (cons 0 nil))) de)
))", *VAPPLY);
// Won't work unless tail calls work
// so no PE?
eval_test(false, &g, &e, &format!("{} (badid 1000)", def_badid), 1000);
}
static VMAP: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 vmap (vau de p
!(let1 vmap_inner (vau ide ip
!(let1 self (car ip))
!(let1 f (car (cdr ip)))
!(let1 l (car (cdr (cdr ip))))
!(if (= nil l) l)
(cons (vapply f (cons (car l) nil) de) (vapply self (cons self (cons f (cons (cdr l) nil))) de))
))
(vapply vmap_inner (cons vmap_inner (cons (eval (car p) de) (cons (eval (car (cdr p)) de) nil))) de)
))", *VAPPLY)
});
#[test]
fn vmap_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
// Maybe define in terms of a right fold?
//eval_test(true, &g, &e, &format!("{} (vmap (vau de p (+ 1 (car p))) '(1 2 3))", *VMAP), (2, (3, (4, Form::Nil))));
eval_test(true, &g, &e, &format!("{} (vmap (vau de p (+ 1 (car p))) '(1))", *VMAP), (2, Form::Nil));
}
static WRAP: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 wrap (vau de p
!(let1 f (eval (car p) de))
(vau ide p (vapply f (vmap (vau _ xp (eval (car xp) ide)) p) ide))
))", *VMAP)
});
#[test]
fn wrap_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
// Make sure (wrap (vau ...)) and internal style are optimized the same
eval_test(true, &g, &e, &format!("{} ((wrap (vau _ p (+ (car p) 1))) (+ 1 2))", *WRAP), 4);
}
static UNWRAP: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 unwrap (vau de p
!(let1 f (eval (car p) de))
(vau ide p (vapply f (vmap (vau _ xp (cons quote (cons (car xp) nil))) p) ide))
))", *WRAP)
});
#[test]
fn unwrap_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
// Can't represent prims in tests :( - they do work though, uncommenting and checking the
// failed assert verifies
//eval_test(true, &g, &e, &format!("{} ((unwrap (vau de p (car p))) (+ 1 2))", def_unwrap), ("quote", (("+", (1, (2, Form::Nil))), Form::Nil)));
//eval_test(true, &g, &e, &format!("{} ((unwrap (vau de p (eval (car p) de))) (+ 1 2))", def_unwrap), (("+", (1, (2, Form::Nil))), Form::Nil));
eval_test(true, &g, &e, &format!("{} ((unwrap (vau de p (eval (eval (car p) de) de))) (+ 1 2))", *UNWRAP), 3);
eval_test(true, &g, &e, &format!("{} ((unwrap (vau de p (+ (eval (eval (car p) de) de) 1))) (+ 1 2))", *UNWRAP), 4);
}
static LAPPLY: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 lapply (vau de p
!(let1 f (eval (car p) de))
!(let1 ip (eval (car (cdr p)) de))
!(let1 nde (eval (car (cdr (cdr p))) de))
(eval (cons (unwrap f) ip) nde)
))", *UNWRAP)
});
#[test]
fn lapply_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
// Should this allow envs at all? It technically can, but I feel like it kinda goes against the
// sensible deriviation
let def_lbadid = format!("
{}
!(let1 lbadid (vau de p
!(let1 inner (wrap (vau ide ip
!(let1 self (car ip))
!(let1 n (car (cdr ip)))
!(let1 acc (car (cdr (cdr ip))))
!(if (= 0 n) acc)
(lapply self (cons self (cons (- n 1) (cons (+ acc 1) nil))) de)
)))
(lapply inner (cons inner (cons (eval (car p) de) (cons 0 nil))) de)
))", *LAPPLY);
// Won't work unless tail calls work
// takes a while though
eval_test(false, &g, &e, &format!("{} (lbadid 1000)", def_lbadid), 1000);
}
static VFOLDL: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 vfoldl (vau de p
!(let1 vfoldl_inner (vau ide ip
!(let1 self (car ip))
!(let1 f (car (cdr ip)))
!(let1 a (car (cdr (cdr ip))))
!(let1 l (car (cdr (cdr (cdr ip)))))
!(if (= nil l) a)
(vapply self (cons self (cons f (cons (vapply f (cons a (cons (car l) nil)) de) (cons (cdr l) nil)))) de)
))
(vapply vfoldl_inner (cons vfoldl_inner (cons (eval (car p) de) (cons (eval (car (cdr p)) de) (cons (eval (car (cdr (cdr p))) de) nil)))) de)
))", *LAPPLY)
});
#[test]
fn vfoldl_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
eval_test(true, &g, &e, &format!("{} (vfoldl (vau de p (+ (car p) (car (cdr p)))) 0 '(1 2 3))", *VFOLDL), 6);
}
static ZIPD: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 zipd (vau de p
!(let1 zipd_inner (vau ide ip
!(let1 self (car ip))
!(let1 a (car (cdr ip)))
!(let1 b (car (cdr (cdr ip))))
!(if (= nil a) a)
!(if (= nil b) b)
(cons (cons (car a) (car b)) (vapply self (cons self (cons (cdr a) (cons (cdr b) nil))) de))
))
(vapply zipd_inner (cons zipd_inner (cons (eval (car p) de) (cons (eval (car (cdr p)) de) nil))) de)
))", *VFOLDL)
});
#[test]
fn zipd_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
eval_test(true, &g, &e, &format!("{} (zipd '(1 2 3) '(4 5 6))", *ZIPD), ((1,4), ((2,5), ((3,6), Form::Nil))));
}
static CONCAT: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 concat (vau de p
!(let1 concat_inner (vau ide ip
!(let1 self (car ip))
!(let1 a (car (cdr ip)))
!(let1 b (car (cdr (cdr ip))))
!(if (= nil a) b)
(cons (car a) (vapply self (cons self (cons (cdr a) (cons b nil))) de))
))
(vapply concat_inner (cons concat_inner (cons (eval (car p) de) (cons (eval (car (cdr p)) de) nil))) de)
))", *ZIPD)
});
#[test]
fn concat_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
eval_test(true, &g, &e, &format!("{} (concat '(1 2 3) '(4 5 6))", *CONCAT), (1, (2, (3, (4, (5, (6, Form::Nil)))))));
}
static BVAU: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 match_params (wrap (vau 0 p
!(let1 self (car p))
!(let1 p_ls (car (cdr p)))
!(let1 dp (car (cdr (cdr p))))
!(let1 e (car (cdr (cdr (cdr p)))))
!(if (= nil p_ls) (assert (= nil dp) e))
!(if (symbol? p_ls) (cons (cons p_ls dp) e))
(self self (cdr p_ls) (cdr dp) (self self (car p_ls) (car dp) e))
)))
!(let1 bvau (vau se p
(if (= nil (cdr (cdr p)))
; No de case
!(let1 p_ls (car p))
!(let1 b_v (car (cdr p)))
(vau 0 dp
(eval b_v (match_params match_params p_ls dp se))
)
; de case
!(let1 de_s (car p))
!(let1 p_ls (car (cdr p)))
!(let1 b_v (car (cdr (cdr p))))
(vau dde dp
(eval b_v (match_params match_params p_ls dp (cons (cons de_s dde) se)))
)
)
))", *CONCAT)
});
#[test]
fn bvau_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
eval_test(true, &g, &e, &format!("{} ((bvau _ (a b c) (+ a (- b c))) 10 2 3)", *BVAU), 9);
//eval_test(true, &g, &e, &format!("{} ((bvau (a b c) (+ a (- b c))) 10 2 3)", *BVAU), 9);
//eval_test(true, &g, &e, &format!("{} ((bvau (a b . c) c) 10 2 3)", *BVAU), (3, Form::Nil));
//eval_test(true, &g, &e, &format!("{} ((bvau (a b . c) c) 10 2)", *BVAU), Form::Nil);
//eval_test(true, &g, &e, &format!("{} ((bvau (a b . c) c) 10 2 3 4 5)", *BVAU), (3, (4, (5, Form::Nil))));
//eval_test(true, &g, &e, &format!("{} ((bvau c c) 3 4 5)", *BVAU), (3, (4, (5, Form::Nil))));
//eval_test(true, &g, &e, &format!("{} ((bvau c c))", *BVAU), Form::Nil);
//eval_test(true, &g, &e, &format!("{} ((bvau ((a b) . c) c) (10 2) 3 4 5)", *BVAU), (3, (4, (5, Form::Nil))));
//eval_test(true, &g, &e, &format!("{} ((bvau ((a b) . c) a) (10 2) 3 4 5)", *BVAU), 10);
//eval_test(true, &g, &e, &format!("{} ((bvau ((a b) . c) b) (10 2) 3 4 5)", *BVAU), 2);
//eval_test(true, &g, &e, &format!("{} ((wrap (bvau _ (a b c) (+ a (- b c)))) (+ 10 1) (+ 2 2) (+ 5 3))", *BVAU), 7);
//eval_test(true, &g, &e, &format!("{} ((wrap (bvau (a b c) (+ a (- b c)))) (+ 10 1) (+ 2 2) (+ 5 3))", *BVAU), 7);
}
static LAMBDA: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 lambda (vau de p
(wrap (vapply bvau p de))
))", *BVAU)
});
#[test]
fn lambda_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
eval_test(true, &g, &e, &format!("{} ((lambda (a b c) (+ a (- b c))) (+ 10 1) (+ 2 2) (+ 5 3))", *LAMBDA), 7);
eval_test(true, &g, &e, &format!("{} ((lambda (a b . c) c) 10 2 3)", *LAMBDA), (3, Form::Nil));
eval_test(true, &g, &e, &format!("{} ((lambda (a b . c) c) 10 2)", *LAMBDA), Form::Nil);
eval_test(true, &g, &e, &format!("{} ((lambda (a b . c) c) 10 2 3 4 5)", *LAMBDA), (3, (4, (5, Form::Nil))));
eval_test(true, &g, &e, &format!("{} ((lambda c c) 3 4 5)", *LAMBDA), (3, (4, (5, Form::Nil))));
eval_test(true, &g, &e, &format!("{} ((lambda c c))", *LAMBDA), Form::Nil);
eval_test(true, &g, &e, &format!("{} ((lambda ((a b) . c) c) '(10 2) 3 4 5)", *LAMBDA), (3, (4, (5, Form::Nil))));
eval_test(true, &g, &e, &format!("{} ((lambda ((a b) . c) a) '(10 2) 3 4 5)", *LAMBDA), 10);
eval_test(true, &g, &e, &format!("{} ((lambda ((a b) . c) b) '(10 2) 3 4 5)", *LAMBDA), 2);
eval_test(true, &g, &e, &format!("{} ((lambda ((a b . c) d) b) '(10 2 3 4) 3)", *LAMBDA), 2);
eval_test(true, &g, &e, &format!("{} ((lambda ((a b . c) d) c) '(10 2 3 4) 3)", *LAMBDA), (3, (4, Form::Nil)));
// should fail
//eval_test(true, &g, &e, &format!("{} ((lambda (a b c) c) 10 2 3 4)", *LAMBDA), 3);
}
static LET2: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 let1 (bvau dp (s v b)
(eval b (match_params match_params s (eval v dp) dp))
))
", *LAMBDA)
});
#[test]
fn let2_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
eval_test(true, &g, &e, &format!("{} (let1 x (+ 10 1) (+ x 1))", *LET2), 12);
eval_test(true, &g, &e, &format!("{} (let1 x '(10 1) x)", *LET2), (10, (1, Form::Nil)));
eval_test(true, &g, &e, &format!("{} (let1 (a b) '(10 1) a)", *LET2), 10);
eval_test(true, &g, &e, &format!("{} (let1 (a b) '(10 1) b)", *LET2), 1);
eval_test(true, &g, &e, &format!("{} (let1 (a b . c) '(10 1) c)", *LET2), Form::Nil);
eval_test(true, &g, &e, &format!("{} (let1 (a b . c) '(10 1 2 3) c)", *LET2), (2, (3, Form::Nil)));
eval_test(true, &g, &e, &format!("{} (let1 ((a . b) . c) '((10 1) 2 3) a)", *LET2), 10);
eval_test(true, &g, &e, &format!("{} (let1 ((a . b) . c) '((10 1) 2 3) b)", *LET2), (1, Form::Nil));
// should fail
//eval_test(true, &g, &e, &format!("{} (let1 (a b c) '(10 2 3 4) a)", *LET2), 10);
}
static LIST: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 list (lambda args args))
", *LET2)
});
#[test]
fn list_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
eval_test(true, &g, &e, &format!("{} (list 1 2 (+ 3 4))", *LIST), (1, (2, (7, Form::Nil))));
}
static Y: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 Y (lambda (f3)
((lambda (x1) (x1 x1))
(lambda (x2) (f3 (wrap (vau app_env y (lapply (x2 x2) y app_env)))))))
)
", *LIST)
});
#[test]
fn y_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
eval_test(true, &g, &e, &format!("{} ((Y (lambda (recurse) (lambda (n) (if (= 0 n) 1 (* n (recurse (- n 1))))))) 5)", *Y), 120);
}
static RLAMBDA: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 rlambda (bvau se (n p b)
(eval (list Y (list lambda (list n) (list lambda p b))) se)
))
", *Y)
});
#[test]
fn rlambda_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
eval_test(true, &g, &e, &format!("{} ((rlambda recurse (n) (if (= 0 n) 1 (* n (recurse (- n 1))))) 5)", *RLAMBDA), 120);
}
static AND_OR: Lazy<String> = Lazy::new(|| {
// need to extend for varidac
format!("
{}
!(let1 and (bvau se (a b)
!(let1 ae (eval a se))
(if ae (eval b se) ae)
))
!(let1 or (bvau se (a b)
!(let1 ae (eval a se))
(if ae ae (eval b se))
))
", *RLAMBDA)
});
#[test]
fn and_or_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
eval_test(true, &g, &e, &format!("{} (and true true)", *AND_OR), true);
eval_test(true, &g, &e, &format!("{} (and false true)", *AND_OR), false);
eval_test(true, &g, &e, &format!("{} (and true false)", *AND_OR), false);
eval_test(true, &g, &e, &format!("{} (and false false)", *AND_OR), false);
eval_test(true, &g, &e, &format!("{} (or true true)", *AND_OR), true);
eval_test(true, &g, &e, &format!("{} (or false true)", *AND_OR), true);
eval_test(true, &g, &e, &format!("{} (or true false)", *AND_OR), true);
eval_test(true, &g, &e, &format!("{} (or false false)", *AND_OR), false);
}
static LEN: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 len (lambda (l)
!(let1 len_helper (rlambda len_helper (l a)
(if (pair? l) (len_helper (cdr l) (+ 1 a))
a)
))
(len_helper l 0)
))
", *AND_OR)
});
#[test]
fn len_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
eval_test(true, &g, &e, &format!("{} (len '())", *LEN), 0);
eval_test(true, &g, &e, &format!("{} (len '(1))", *LEN), 1);
eval_test(true, &g, &e, &format!("{} (len '(1 2))", *LEN), 2);
eval_test(true, &g, &e, &format!("{} (len '(1 2 3))", *LEN), 3);
}
static MATCH: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 match (bvau de (x . cases)
!(let1 evaluate_case (rlambda evaluate_case (access c)
!(if (symbol? c) (list true (lambda (b) (list let1 c access b))))
!(if (and (pair? c) (= 'unquote (car c))) (list (list = access (car (cdr c))) (lambda (b) b)))
!(if (and (pair? c) (= 'quote (car c))) (list (list = access c) (lambda (b) b)))
!(if (pair? c)
!(let1 tests (list and (list pair? access) (list = (len c) (list len access))))
!(let1 (tests body_func) ((rlambda recurse (c tests access body_func) (if (pair? c)
!(let1 (inner_test inner_body_func) (evaluate_case (list car access) (car c)))
(recurse (cdr c)
(list and tests inner_test)
(list cdr access)
(lambda (b) (body_func (inner_body_func b))))
; else
(list tests body_func)
))
c tests access (lambda (b) b)))
(list tests body_func))
(list (list = access c) (lambda (b) b))
))
!(let1 helper (rlambda helper (x_sym cases) (if (= nil cases) (list assert false)
(let1 (test body_func) (evaluate_case x_sym (car cases))
(concat (list if test (body_func (car (cdr cases)))) (list (helper x_sym (cdr (cdr cases)))))))))
(eval (list let1 '___MATCH_SYM x (helper '___MATCH_SYM cases)) de)
;!(let1 expanded (list let1 '___MATCH_SYM x (helper '___MATCH_SYM cases)))
;(debug expanded (eval expanded de))
))
", *LEN)
});
#[test]
fn match_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
eval_test(true, &g, &e, &format!("{} (match (+ 1 2) 1 2 2 3 3 4 _ 0)", *MATCH), 4);
eval_test(true, &g, &e, &format!("{} (match '(1 2) 1 2 2 3 3 4 _ 0)", *MATCH), 0);
eval_test(true, &g, &e, &format!("{} (match '(1 2) 1 2 2 3 (a b) (+ a (+ 2 b)) _ 0)", *MATCH), 5);
eval_test(true, &g, &e, &format!("{} (match '(1 2) 1 2 2 3 '(1 2) 7 _ 0)", *MATCH), 7);
eval_test(true, &g, &e, &format!("{} (let1 a 70 (match (+ 60 10) (unquote a) 100 2 3 _ 0))", *MATCH), 100);
}
static RBTREE: Lazy<String> = Lazy::new(|| {
format!("
{}
!(let1 empty (list 'B nil nil nil))
!(let1 E empty)
!(let1 EE (list 'BB nil nil nil))
!(let1 generic-foldl (rlambda generic-foldl (f z t) (match t
(unquote E) z
(c a x b) !(let1 new_left_result (generic-foldl f z a))
!(let1 folded (f new_left_result x))
(generic-foldl f folded b))))
!(let1 blacken (lambda (t) (match t
('R a x b) (list 'B a x b)
t t)))
!(let1 balance (lambda (t) (match t
; figures 1 and 2
('B ('R ('R a x b) y c) z d) (list 'R (list 'B a x b) y (list 'B c z d))
('B ('R a x ('R b y c)) z d) (list 'R (list 'B a x b) y (list 'B c z d))
('B a x ('R ('R b y c) z d)) (list 'R (list 'B a x b) y (list 'B c z d))
('B a x ('R b y ('R c z d))) (list 'R (list 'B a x b) y (list 'B c z d))
; figure 8, double black cases
('BB ('R a x ('R b y c)) z d) (list 'B (list 'B a x b) y (list 'B c z d))
('BB a x ('R ('R b y c) z d)) (list 'B (list 'B a x b) y (list 'B c z d))
; already balenced
t t)))
!(let1 map-insert !(let1 ins (rlambda ins (t k v) (match t
(unquote E) (list 'R t (list k v) t)
(c a x b) !(if (< k (car x)) (balance (list c (ins a k v) x b)))
!(if (= k (car x)) (list c a (list k v) b))
(balance (list c a x (ins b k v))))))
(lambda (t k v) (blacken (ins t k v))))
!(let1 map-empty empty)
!(let1 make-test-tree (rlambda make-test-tree (n t) (if (<= n 0) t
(make-test-tree (- n 1) (map-insert t n (= 0 (% n 10)))))))
!(let1 reduce-test-tree (lambda (tree) (generic-foldl (lambda (a x) (if (car (cdr x)) (+ a 1) a)) 0 tree)))
", *MATCH)
});
#[test]
fn rbtree_eval_test() { let g = grammar::TermParser::new(); let e = root_env();
eval_test(false, &g, &e, &format!("{} (reduce-test-tree (make-test-tree 10 map-empty))", *RBTREE), 1);
//eval_test(false, &g, &e, &format!("{} (reduce-test-tree (make-test-tree 20 map-empty))", *RBTREE), 2);
}

View File

@@ -275,7 +275,7 @@
(.marked_env (lambda (x) (slice x 2 -1)))
(.marked_env_has_vals (lambda (x) (idx x 2)))
(.marked_env_needed_for_progress (lambda (x) (idx x 3)))
(.marked_env_idx (lambda (x) (idx x 4)))
(.marked_env_id (lambda (x) (idx x 4)))
(.marked_env_upper (lambda (x) (idx (idx x 5) -1)))
(.env_marked (lambda (x) (idx x 5)))
(marked_env_real? (lambda (x) (= nil (idx (.marked_env_needed_for_progress x) 0))))
@@ -431,6 +431,7 @@
(marked_val (lambda (x) (array 'val (hash_val x) x)))
(marked_comb (lambda (wrap_level env_id de? se variadic params body) (array 'comb (hash_comb wrap_level env_id de? se variadic params body) wrap_level env_id de? se variadic params body)))
(comb_w_body (dlambda ((_comb _hash wrap_level env_id de? se variadic params _body) new_body) (marked_comb wrap_level env_id de? se variadic params new_body)))
(marked_prim_comb (lambda (handler_fun real_or_name wrap_level val_head_ok) (array 'prim_comb (hash_prim_comb handler_fun real_or_name wrap_level val_head_ok) handler_fun real_or_name wrap_level val_head_ok)))
(with_wrap_level (lambda (x new_wrap) (cond ((prim_comb? x) (dlet (((handler_fun real_or_name wrap_level val_head_ok) (.prim_comb x)))
@@ -494,7 +495,7 @@
(array (true_str "<n " (needed_for_progress x) " (comb " wrap_level " " env_id " " se_s " " de? " " params " " body_s ")>") done_envs)))
((prim_comb? x) (array (true_str "<wl=" (.prim_comb_wrap_level x) " " (.prim_comb_sym x) ">") done_envs))
((marked_env? x) (dlet ((e (.env_marked x))
(index (.marked_env_idx x))
(index (.marked_env_id x))
(u (idx e -1))
(already (in_array index done_envs))
(opening (true_str "{" (mif (marked_env_real? x) "real" "fake") (mif (.marked_env_has_vals x) " real vals" " fake vals") " ENV idx: " (true_str index) ", "))
@@ -596,7 +597,7 @@
;(memo (put memo hash total))
) (array memo total)))
((marked_env? x) (if (and (not (marked_env_real? x)) (= s_env_id (.marked_env_idx x))) (array memo true)
((marked_env? x) (if (and (not (marked_env_real? x)) (= s_env_id (.marked_env_id x))) (array memo true)
(dlet (
(values (slice (.env_marked x) 0 -2))
(upper (idx (.env_marked x) -1))
@@ -674,19 +675,18 @@
))
(drop_redundent_veval (rec-lambda drop_redundent_veval (partial_eval_helper x de env_stack pectx indent) (dlet (
(env_id (.marked_env_idx de))
(env_id (.marked_env_id de))
(r (if
(and (marked_array? x)
(not (.marked_array_is_val x)))
(and (marked_array? x) (not (.marked_array_is_val x)))
(if (and (prim_comb? (idx (.marked_array_values x) 0))
(= 'veval (.prim_comb_sym (idx (.marked_array_values x) 0)))
(= 3 (len (.marked_array_values x)))
(not (marked_env_real? (idx (.marked_array_values x) 2)))
(= env_id (.marked_env_idx (idx (.marked_array_values x) 2)))) (drop_redundent_veval partial_eval_helper (idx (.marked_array_values x) 1) de env_stack pectx (+ 1 indent))
(= env_id (.marked_env_id (idx (.marked_array_values x) 2)))) (drop_redundent_veval partial_eval_helper (idx (.marked_array_values x) 1) de env_stack pectx (+ 1 indent))
; wait, can it do this? will this mess with eval?
; basically making sure that this comb's params are still good to eval
(if (and (or (prim_comb? (idx (.marked_array_values x) 0)) (comb? (idx (.marked_array_values x) 0)))
; basically making sure that this comb's params are still good to eval
(if (and (or (prim_comb? (idx (.marked_array_values x) 0)) (comb? (idx (.marked_array_values x) 0)))
(!= -1 (.any_comb_wrap_level (idx (.marked_array_values x) 0))))
(dlet (((pectx err ress changed) (foldl (dlambda ((c er ds changed) p) (dlet (
(pre_hash (.hash p))
@@ -721,10 +721,10 @@
)
(if (or force hashes_now (= for_progress true) (intset_intersection_nonempty for_progress (idx env_stack 0)))
(cond ((val? x) (array pectx nil x))
((marked_env? x) (dlet ((dbi (.marked_env_idx x)))
((marked_env? x) (dlet ((dbi (.marked_env_id x)))
; compiler calls with empty env stack
(mif dbi (dlet ( (new_env ((rec-lambda rec (i len_env_stack) (cond ((= i len_env_stack) nil)
((= dbi (.marked_env_idx (idx (idx env_stack 1) i))) (idx (idx env_stack 1) i))
((= dbi (.marked_env_id (idx (idx env_stack 1) i))) (idx (idx env_stack 1) i))
(true (rec (+ i 1) len_env_stack))))
0 (len (idx env_stack 1))))
(_ (println (str_strip "replacing " x) (str_strip " with (if nonnil) " new_env)))
@@ -767,7 +767,7 @@
; (array pectx err comb)))
(_ (println (indent_str indent) "Going to do an array call!"))
(indent (+ 1 indent))
(_ (print_strip (indent_str indent) "total (in env " (.marked_env_idx env) ") is (proceeding err " err ") " x))
(_ (print_strip (indent_str indent) "total (in env " (.marked_env_id env) ") is (proceeding err " err ") " x))
(map_rp_eval (lambda (pectx ps) (foldl (dlambda ((c er ds) p) (dlet ((_ (print_strip (indent_str indent) "rp_evaling " p)) ((c e d) (partial_eval_helper p false env env_stack c (+ 1 indent) false)) (_ (print_strip (indent_str indent) "result of rp_eval was err " e " and value " d))) (array c (mif er er e) (concat ds (array d)))))
(array pectx nil (array))
ps)))
@@ -836,10 +836,10 @@
(pectx (array env_counter memo))
) (array pectx func_err func_result false))))
(_ (print_strip (indent_str indent) "evaled result of function call (in env " (.marked_env_idx env) ", with inner " env_id ") and err " func_err " is " func_result))
(_ (print_strip (indent_str indent) "evaled result of function call (in env " (.marked_env_id env) ", with inner " env_id ") and err " func_err " is " func_result))
(must_stop_maybe_id (and (= nil func_err)
(or rec_stop (if (not (combiner_return_ok func_result env_id))
(if (!= nil de?) (.marked_env_idx env) true)
(if (!= nil de?) (.marked_env_id env) true)
false))))
) (if (!= nil func_err) (array pectx func_err nil)
(if must_stop_maybe_id
@@ -879,7 +879,7 @@
((!= nil err) (begin (print (indent_str indent) "got err " err) (array pectx err nil)))
; If our env was implicit, then our unval'd code can be inlined directly in our caller
(implicit_env (drop_redundent_veval partial_eval_helper ebody de env_stack pectx indent))
((combiner_return_ok ebody (.marked_env_idx eval_env)) (drop_redundent_veval partial_eval_helper ebody de env_stack pectx indent))
((combiner_return_ok ebody (.marked_env_id eval_env)) (drop_redundent_veval partial_eval_helper ebody de env_stack pectx indent))
(true (drop_redundent_veval partial_eval_helper (marked_array false true nil (array (marked_prim_comb recurse 'veval -1 true) ebody eval_env) nil) de env_stack pectx indent))
))))
@@ -975,7 +975,7 @@
(this (marked_array false true nil (concat (array (marked_prim_comb (recurse false) 'cond 0 true)
pred)
sliced_params) nil))
(hash (combine_hash (combine_hash 101 (.hash this)) (+ 103 (.marked_env_idx de))))
(hash (combine_hash (combine_hash 101 (.hash this)) (+ 103 (.marked_env_id de))))
((env_counter memo) pectx)
(already_in (!= false (get-value-or-false memo hash)))
(_ (if already_in (print_strip "ALREADY IN " this)
@@ -1862,6 +1862,13 @@
(global '$num_sbrks '(mut i32) (i32.const 0))
(global '$num_frees '(mut i32) (i32.const 0))
(global '$num_evals '(mut i32) (i32.const 0))
(global '$num_all_evals '(mut i32) (i32.const 0))
(global '$num_interp_dzero '(mut i32) (i32.const 0))
(global '$num_interp_done '(mut i32) (i32.const 0))
(global '$num_compiled_dzero '(mut i32) (i32.const 0))
(global '$num_compiled_done '(mut i32) (i32.const 0))
(global '$num_array_innerdrops '(mut i32) (i32.const 0))
(global '$num_env_innerdrops '(mut i32) (i32.const 0))
(global '$num_array_subdrops '(mut i32) (i32.const 0))
@@ -4025,6 +4032,7 @@
((k_eval_helper func_idx funcs) (array func_idx (+ 1 func_idx) (concat funcs (func '$eval_helper '(param $it i64) '(param $env i64) '(result i64) '(local $len i32) '(local $ptr i32) '(local $current_env i64) '(local $res i64) '(local $env_ptr i32) '(local $tmp_ptr i32) '(local $i i32) '(local $comb i64) '(local $params i64) '(local $wrap i32) '(local $tmp i64) '(local $rc_bytes i64) '(local $rc_ptr i32) '(local $rc_tmp i32)
(global.set '$num_all_evals (i32.add (i32.const 1) (global.get '$num_all_evals)))
; The cool thing about Vau calculus / Kernel / Kraken
; is that everything is a value that evaluates to itself except symbols
; and arrays.
@@ -4108,6 +4116,17 @@
)
(local.set '$wrap (i32.wrap_i64 (extract_wrap_code (local.get '$comb))))
(local.set '$params (call '$slice_impl (generate_dup (local.get '$it)) (i32.const 1) (local.get '$len)))
; Pure benchmarking
(_if '$is_wrap_one
(i32.eq (i32.const 1) (local.get '$wrap))
(then (global.set '$num_interp_done (i32.add (i32.const 1) (global.get '$num_interp_done))))
(else
(_if '$is_wrap_zero
(i32.eqz (local.get '$wrap))
(then (global.set '$num_interp_dzero (i32.add (i32.const 1) (global.get '$num_interp_dzero))))
(else (unreachable)))))
; we'll reuse len and ptr now for params
(local.set '$len (extract_size_code (local.get '$params)))
(local.set '$ptr (extract_ptr_code (local.get '$params)))
@@ -4165,6 +4184,7 @@
((k_eval func_idx funcs) (array func_idx (+ 1 func_idx) (concat funcs (func '$eval '(param $p i64) '(param $d i64) '(param $s i64) '(result i64) '(local $len i32) '(local $ptr i32) '(local $rc_bytes i64) '(local $rc_ptr i32) '(local $rc_tmp i32)
(ensure_not_op_n_params_set_ptr_len i32.lt_u 1)
(global.set '$num_evals (i32.add (i32.const 1) (global.get '$num_evals)))
(_if '$using_d_env '(result i64)
(i32.eq (i32.const 1) (local.get '$len))
(then
@@ -4597,21 +4617,6 @@
(if r (array r nil nil (array datasi funcs memo env pectx inline_locals)) #f))))
; TODO:
;
; Split compile-inner into compile-value and compile-code.
; Compile-value can only call into compile-code to compile a function.
; Compile-code can call into compile-value, but doesn't have to pass any of the data for the analysis passes.
; (BUT does pass memo back and forth as to not re-compile over and over, ofc)
; Compile-value is then what is called on the parsed program for NO PE
; OR
; called on ['run <wrap=0 nil.. () parsed_expr>]
; which when encountering a function will call compile-code to do partial evaluation & all the dataflow
; no PE can have compile function compile the body as (eval <body-compiled-as-value>)
;
; Feels like compling the function actually belongs in compile-value, in a weird way.
; Since it has to figure out what is code and what is value, is there actually any benefit in splitting them up?
; This is the second run at this, and is a little interesting
; It can return a value OR code OR an error string. An error string should be propegated,
; unless it was expected as a possiblity, which can happen when compling a call that may or
@@ -4623,8 +4628,10 @@
(let_like_inline_closure (lambda (func_value containing_env_idx) (and (comb? func_value)
(not (.comb_varadic func_value))
(= containing_env_idx (.marked_env_idx (.comb_env func_value)))
(= containing_env_idx (.marked_env_id (.comb_env func_value)))
(= nil (.comb_des func_value)))))
(is_prim_function_call (lambda (c s) (and (marked_array? c) (not (.marked_array_is_val c)) (<= 2 (len (.marked_array_values c)))
(prim_comb? (idx (.marked_array_values c) 0)) (= s (.prim_comb_sym (idx (.marked_array_values c) 0))))))
; Ok, we're pulling out the call stuff out of compile
; Wrapped vs unwrapped
@@ -4633,49 +4640,81 @@
; tail call elimination
; dynamic call unval-partial-eval branch
;
; ALSO: This means that it needs to be pulled out of even the compile-function bit, since it has to go through multiple function compilations
; in order to notice Y-Comb tying and Eta-reduce the lazyness
; which also means it needs to be able to memoize
;
; Rembember to account for (dont_compile dont_lazy_env dont_y_comb dont_prim_inline dont_closure_inline)
(call-info (rec-lambda call-info (c env_id) (cond
((val? c) nil)
((and (marked_symbol? c) (.marked_symbol_is_val c)) nil)
((marked_symbol? c) nil)
((marked_env? c) nil) ; So it actually needs to recurse into env
((comb? c) (dlet (
((wrap_level env_id de? se variadic params body) (.comb c))
(_ (mif (> wrap_level 1) (error "wrap level TOO DARN HIGH")))
) nil)
((prim_comb? c) nil)
((and (marked_array? c) (.marked_array_is_val c)) nil) ; and array values
; (<this_data>... <sub_data>)
((and (marked_array? c) ;(>= 2 (len (.marked_array_values c)))
(let_like_inline_closure (idx (.marked_array_values c) 0) env_id)) nil)
; REMEMBER - new env_id inside
; but same tce-data
; and same y-comb memo
(true nil)
; obv need to handle possible dynamic calls with an additional unval side, but also be careful of infinite recursion (as we had happen on compile before)
; due to the interaction of partial eval and unval (previously in compile) here
; call-info will be a fairly simple pre-order traversal (looking at caller before params)
; infer-type has to walk though cond in pairs, special handle the (and ) case, and adjust parameters for veval
; perceus is weird, as it has to look at the head to determine how to order/combine the children, as well as an extra sub-data for the call itself (though I guess this is just part of the node data)
; check for Y-comb tie looked like
(and (not dont_y_comb) (!= nil (.marked_array_this_rec_stop c)) (get_passthrough (idx (.marked_array_this_rec_stop c) 0) ctx))
; Starting with only dynamic call unval
; TODO: tce-data
(call-info (rec-lambda call-info (c env pectx) (cond
((val? c) (array nil nil pectx))
((and (marked_symbol? c) (.marked_symbol_is_val c)) (array nil nil pectx))
((marked_symbol? c) (array nil nil pectx))
((marked_env? c) (array nil nil pectx))
((prim_comb? c) (array nil nil pectx))
((and (marked_array? c) (.marked_array_is_val c)) (array nil nil pectx))
((comb? c) (array nil nil pectx))
((ok x) (try_unval x (lambda (_) nil)))
(err (if (not ok) "couldn't unval in compile" err))
((and (marked_array? c) (let_like_inline_closure (idx (.marked_array_values c) 0) (.marked_env_id env))) (dlet (
(func_param_values (.marked_array_values c))
(func (idx func_param_values 0))
; TODO: pull errors out of here
;(param_data (map (lambda (x) (call-info x env)) (slice func_param_values 1 -1)))
; TODO: pull errors out of here
; mk tmp env
;(body_data (call-info (.comb_body func tmp_env)))
) (array nil nil pectx))) ;(array nil (cons body_data param_data))))
((pectx e pex) (cond ((!= nil err) (array pectx err nil))
(true (partial_eval_helper x false env (array nil nil) pectx 1 false))))
((is_prim_function_call c 'veval) (dlet (
(func_param_values (.marked_array_values c))
(num_params (- (len func_param_values) 1))
(params (slice func_param_values 1 -1))
; These can't be fatal either
;(_ (if (!= 2 num_params) (error "call to veval has != 2 params!")))
;(_ (if (not (marked_env? (idx params 1))) (error "call to veval has not marked_env second param")))
((tce_idx tce_full_params) (mif tce_data tce_data (array nil nil)))
(tce_able (and unwrapped (= tce_idx (extract_func_idx func_val))))
; TODO: pull errors out of here
;(sub_data (array nil (call-info (idx params 0) (idx params 1)) nil))
) (array nil nil pectx))) ;(array nil sub_data)))
; NOTICE TRANSPARENT VEVAL
; also vcond, of course
))))
(true (dlet (
; obv need to handle possible dynamic calls with an additional unval side, but also be careful of infinite recursion (as we had happen on compile before)
; due to the interaction of partial eval and unval (previously in compile) here
; might need to check for (is_prim_function_call c 'vcond) for recursion?
; the basic check is is this dynamic or not, and if so (and thus we don't know the wrap level)
; we need to
; if not dynamic, just recurse as normal
; assert wrap-level == 0 or == -1
(func_param_values (.marked_array_values c))
(func (idx func_param_values 0))
; ; TODO: pull errors out of here
; (sub_data (map (lambda (x) (call-info x env)) func_param_values))
; ; TODO: pull errors out of here
; (our_data (cond ((and (comb? func) ( = (.comb_wrap_level func) 0)) nil)
; ((and (comb? func) (!= (.comb_wrap_level func) 1)) (error "bad wrap level call-info")) ; this is a tad tricky - I wanted to just have error here, but
; ; *concievably this is the result of wrongly evaluted code based on this
; ; very method of prediction. Instead, we need to error here,
; ; and have that count as erroing out of the compile.
; ; How best should we do that, I wonder?
; ((prim_comb? func) nil)
; (true (dlet (
; ((ok x) (try_unval x (lambda (_) nil)))
; (err (if (not ok) "couldn't unval in compile" err))
; ((pectx e pex) (mif err (array pectx err nil))
; ; x only_head env env_stack pectx indent force
; (partial_eval_helper x false env (array nil nil) pectx 1 false))))
; ) nil)
; ))
;) (array our_data sub_data))
) (array nil nil pectx))) ;(array nil sub_data)))
)))
; type is a bit generic, both the runtime types + length of arrays
;
@@ -4702,8 +4741,6 @@
(get-list-or (lambda (d k o) (dlet ((x (get-list d k)))
(mif x (idx x 1)
o))))
(is_prim_function_call (lambda (c s) (and (marked_array? c) (not (.marked_array_is_val c)) (<= 2 (len (.marked_array_values c)))
(prim_comb? (idx (.marked_array_values c) 0)) (= s (.prim_comb_sym (idx (.marked_array_values c) 0))))))
(is_markable (lambda (x) (or (and (marked_symbol? x) (not (.marked_symbol_is_val x)))
(and (marked_array? x) (not (.marked_array_is_val x)))
)))
@@ -4856,11 +4893,10 @@
(_ (if (!= 2 num_params) (error "call to veval has != 2 params!")))
(_ (if (not (marked_env? (idx params 1))) (error "call to veval has not marked_env second param")))
(new_env_id (.marked_env_idx (idx params 1)))
((btyp bimpl b_assertion b_subdata) (infer_types (idx params 0) new_env_id empty_dict-list empty_dict-list))
(new_env_id (.marked_env_id (idx params 1)))
(sub_data (array (infer_types func env_id implies guarentees)
(array btyp bimpl b_assertion b_subdata)
(infer_types (idx params 0) new_env_id empty_dict-list empty_dict-list)
(infer_types (idx params 1) env_id implies guarentees)))
) (array btyp false empty_dict-list sub_data)))
@@ -4870,6 +4906,7 @@
;(_ (true_print " doing infer-types for random call "))
(sub_results (map (lambda (x) (infer_types x env_id implies guarentees)) (.marked_array_values c)))
;(_ (true_print " done infer-types for random call "))
; I belive this .hash doesn't do anything
) (array (get-list-or guarentees (.hash c) false) false empty_dict-list sub_results)))
; fallthrough
@@ -4964,7 +5001,7 @@
(_ (if (!= 2 num_params) (error "call to veval has != 2 params!")))
(_ (if (not (marked_env? (idx params 1))) (error "call to veval has not marked_env second param")))
(new_env_id (.marked_env_idx (idx params 1)))
(new_env_id (.marked_env_id (idx params 1)))
(body_data (pseudo_perceus (idx params 0) new_env_id knot_memo empty_use_map))
((used_map_pre_env env_sub_data) (pseudo_perceus (idx params 1) env_id knot_memo used_map_after))
@@ -5005,6 +5042,7 @@
; YES remember to check for Y-combiner recursion knot tying - (and (!= nil (.marked_array_this_rec_stop c)) (get_passthrough (idx (.marked_array_this_rec_stop c) 0) ctx))
; YES remember to check for let-like inlining (and (marked_array? c) (let_like_inline_closure (idx (.marked_array_values c) 0) env_id))
; YES remember to properly handle crazy stuff like inlining inside of veval (does that mean we have to re-pick up inside veval after all?)
; TODO: properly handle param usage based on wrap level if unknown (based on call-info)
; remember to think (/modify appropriately) about TCE - I think it's fine to have it act like a normal call?
((and (marked_array? c) (not (.marked_array_is_val c))) (dlet (
; check func first for val or not & if val if it uses de (comb that uses de, prim_comb that takes it)
@@ -5065,7 +5103,7 @@
((and (marked_array? c) (.marked_array_is_val c)) (array b borrow_nil))
; no matter if env is real or not, it's borrowed,
; as it will be cached for the length of the function
((marked_env? c) (array b borrow_nil))
((marked_env? c) (array b borrow_nil)) ; I feel like all of these value ones but esp this one should be true instead of b? must-be-borrowed
((and (marked_symbol? c) (not (.marked_symbol_is_val c))) (array (and b (not (cached_pseudo_perceus_sym_borrowed used_map_sub_data))) borrow_nil))
; comb value just does its env
((comb? c) (borrow? (.comb_env c) b env_id used_map_sub_data))
@@ -5097,7 +5135,7 @@
(_ (if (!= 2 num_params) (error "call to veval has != 2 params!")))
(_ (if (not (marked_env? (idx params 1))) (error "call to veval has not marked_env second param")))
(new_env_id (.marked_env_idx (idx params 1)))
(new_env_id (.marked_env_id (idx params 1)))
((body_borrowed body_sub_data) (borrow? (idx params 0) b new_env_id (pseudo_perceus_just_sub_idx used_map_sub_data 1)))
((env_borrowed env_sub_data) (borrow? (idx params 1) true env_id (pseudo_perceus_just_sub_idx used_map_sub_data 2)))
) (array body_borrowed (array borrow_nil (array body_borrowed body_sub_data) (array env_borrowed env_sub_data)))))
@@ -5117,6 +5155,7 @@
) (array borrowed sub_data)))
; call taxonomy a bit simpler this time - if it's not already special cased, it's either an inline or it's owned
; This also has to be adjusted based on possibly dynamic calls with unknown wrap level
((and (marked_array? c) (not (.marked_array_is_val c))) (dlet (
(func_param_values (.marked_array_values c))
(num_params (- (len func_param_values) 1))
@@ -5143,6 +5182,25 @@
;(_ (true_print "done borrow!"))
) r)))
(function-analysis (lambda (c memo pectx) (dlet (
((wrap_level env_id de? se variadic params body) (.comb c))
(full_params (concat params (mif de? (array de?) (array))))
(inner_env (make_tmp_inner_env params de? se env_id))
((call_info call_err pectx) (call-info body inner_env pectx))
(analysis_err call_err)
(inner_type_data (infer_types body env_id empty_dict-list empty_dict-list))
((used_map_before used_map_sub_data) (pseudo_perceus body env_id memo (push_used_map empty_use_map full_params)))
((borrowed borrow_sub_data) (borrow? body false env_id used_map_sub_data))
(_ (mif borrowed (error "body hast to be borrowed? " borrowed " " (true_str_strip body))))
(inner_analysis_data (array inner_type_data used_map_sub_data call_info))
) (array inner_analysis_data analysis_err pectx))))
(cached_analysis_idx (lambda (c env_id cache i) (dlet (
;(_ (true_print "doing infer-types-idx for " (true_str_strip c)))
;(_ (true_print "doing infer-types-idx i " i))
@@ -5153,9 +5211,10 @@
;( t (cached_infer_types_idx c env_id (idx cache 0) i))
;( p (mif cache (pseudo_perceus_just_sub_idx (idx cache 1) i) nil))
( p nil )
( c nil )
;(_ (true_print "done infer-types-idx"))
) (array t p))))
) (array t p c))))
(compile-inner (rec-lambda compile-inner (ctx c need_value inside_veval outer_s_env_access_code s_env_access_code inline_level tce_data analysis_data) (cond
@@ -5229,7 +5288,7 @@
(func_value (idx func_param_values 0))
(_ (true_print "about to get cached_infer_types_idx for call before checking for 'idx"))
;(_ (true_print " cache is " type_data))
(parameter_subs (map (lambda (i) (cached_analysis_idx c (.marked_env_idx env) analysis_data i)) (range 1 (len func_param_values))))
(parameter_subs (map (lambda (i) (cached_analysis_idx c (.marked_env_id env) analysis_data i)) (range 1 (len func_param_values))))
(parameter_types (map just_type parameter_subs))
; used_data HERE
@@ -5462,7 +5521,7 @@
; User inline
((and (not dont_closure_inline) (let_like_inline_closure func_value (.marked_env_idx env))) (dlet (
((and (not dont_closure_inline) (let_like_inline_closure func_value (.marked_env_id env))) (dlet (
; To inline, we add all of the parameters + inline_level + 1 to the current functions additional symbols
; as well as a new se + inline_level + 1 symbol
; fill them with the result of evaling the parameters now
@@ -5631,11 +5690,17 @@
(local.tee '$tmp)
(_if '$is_wrap_0
(is_wrap_code 0 (local.get '$tmp))
(then wrap_0_param_code)
(then
(global.set '$num_compiled_dzero (i32.add (i32.const 1) (global.get '$num_compiled_dzero)))
wrap_0_param_code
)
(else
(_if '$is_wrap_1
(is_wrap_code 1 (local.get '$tmp))
(then wrap_1_param_code)
(then
(global.set '$num_compiled_done (i32.add (i32.const 1) (global.get '$num_compiled_done)))
wrap_1_param_code
)
(else wrap_x_param_code)
)
)
@@ -5670,7 +5735,7 @@
(generate_env_access (dlambda ((datasi funcs memo env pectx inline_locals) env_id reason) ((rec-lambda recurse (code this_env)
(cond
((= env_id (.marked_env_idx this_env)) (array nil (generate_dup code) nil (array datasi funcs memo env pectx inline_locals)))
((= env_id (.marked_env_id this_env)) (array nil (generate_dup code) nil (array datasi funcs memo env pectx inline_locals)))
((= nil (.marked_env_upper this_env)) (array nil nil (str "bad env, upper is nil and we haven't found " env_id ", (this is *possiblely* because we're not recreating val/notval chains?) maxing out at " (str_strip this_env) ", having started at " (str_strip env) ", we're generating because " reason) (array datasi funcs memo env pectx)))
(true (recurse (i64.load 16 (extract_ptr_code code)) (.marked_env_upper this_env)))
)
@@ -5678,7 +5743,7 @@
) (if (not (marked_env_real? c)) (begin (print_strip "env wasn't real: " (marked_env_real? c) ", so generating access (env was) " c)
(if need_value (array nil nil (str "marked env not real, though we need_value: " (str_strip c)) ctx)
(generate_env_access ctx (.marked_env_idx c) "it wasn't real: " (str_strip c))))
(generate_env_access ctx (.marked_env_id c) "it wasn't real: " (str_strip c))))
(dlet (
;(_ (true_print "gonna compile kvs vvs"))
@@ -5695,11 +5760,11 @@
((uv ucode err ctx) (mif (idx e -1) (compile-inner ctx (idx e -1) need_value inside_veval outer_s_env_access_code s_env_access_code inline_level nil analysis_nil)
(array nil_val nil nil ctx)))
) (mif (or (= false kvs) (= nil uv) (!= nil err))
(begin (print_strip "kvs " kvs " vvs " vvs " uv " uv " or err " err " based off of " c)
(begin (true_print "kvs " kvs " vvs " vvs " uv " uv " or err " err " based off of " (true_str_strip c))
(error "I DON'T LIKE IT - IMPOSSIBLE?")
(if need_value
(array nil nil (str "had to generate env access (course " need_value ") for " (str_strip c) "vvs is " vvs " err was " err) ctx)
(generate_env_access ctx (.marked_env_idx c) (str " vvs " vvs " uv " uv " or err " err " based off of " (str_strip c)))))
(generate_env_access ctx (.marked_env_id c) (str " vvs " vvs " uv " uv " or err " err " based off of " (str_strip c)))))
(dlet (
((datasi funcs memo env pectx inline_locals) ctx)
;(_ (true_print "about to kvs_array"))
@@ -5773,15 +5838,17 @@
((wrap_level env_id de? se variadic params body) (.comb c))
(_ (mif (> wrap_level 1) (error "wrap level TOO DARN HIGH")))
; note that this is just the func, not the env
(maybe_func (get_passthrough (.hash c) ctx))
; note that this is just the hash of the func, not the env
(old_hash (.hash c))
(maybe_func (get_passthrough old_hash ctx))
((datasi funcs memo env pectx inline_locals) ctx)
((pectx err evaled_body) (mif (or maybe_func dont_partial_eval)
(array pectx "don't pe" body)
(dlet ((inner_env (make_tmp_inner_env params de? env env_id)))
(partial_eval_helper body false inner_env (array nil (array inner_env)) pectx 1 false))))
(body (mif err body evaled_body))
(c (comb_w_body c body))
(new_hash (.hash c))
(ctx (array datasi funcs memo env pectx inline_locals))
; Let's look and see if we can eta-reduce!
@@ -5791,6 +5858,11 @@
; and so we can only tell here weather or not it will be safe to remove the level of lazyness (because we get a func value back instead of code)
; and perform the eta reduction.
((env_val env_code env_err ctx) (if (and need_value (not (marked_env_real? se)))
(array nil nil "Env wasn't real when compiling comb, but need value" ctx)
(compile-inner ctx se need_value inside_veval outer_s_env_access_code s_env_access_code inline_level nil analysis_nil)))
(_ (if (not (or (= nil env_val) (int? env_val))) (error "BADBADBADenv_val")))
) (mif (and
(not dont_y_comb)
variadic
@@ -5806,22 +5878,18 @@
(marked_symbol? (idx (.marked_array_values body) 3))
(not (.marked_symbol_is_val (idx (.marked_array_values body) 3)))
(= de? (.marked_symbol_value (idx (.marked_array_values body) 3)))
env_val
)
(array (set_wrap_val wrap_level (get-value-or-false memo (.hash (idx (.marked_array_values body) 1)))) nil err ctx)
(array (combine_env_comb_val env_val (set_wrap_val wrap_level (get-value-or-false memo (.hash (idx (.marked_array_values body) 1))))) nil err ctx)
(dlet (
(full_params (concat params (mif de? (array de?) (array))))
(normal_params_length (if variadic (- (len params) 1) (len params)))
((env_val env_code env_err ctx) (if (and need_value (not (marked_env_real? se)))
(array nil nil "Env wasn't real when compiling comb, but need value" ctx)
(compile-inner ctx se need_value inside_veval outer_s_env_access_code s_env_access_code inline_level nil analysis_nil)))
(_ (if (not (or (= nil env_val) (int? env_val))) (error "BADBADBADenv_val")))
(maybe_func (get_passthrough (.hash c) ctx))
(maybe_func (or (get_passthrough old_hash ctx) (get_passthrough new_hash ctx)))
((func_value _ func_err ctx) (mif maybe_func maybe_func
(dlet (
(full_params (concat params (mif de? (array de?) (array))))
(normal_params_length (if variadic (- (len params) 1) (len params)))
((datasi funcs memo env pectx outer_inline_locals) ctx)
(old_funcs funcs)
(funcs (concat funcs (array nil)))
@@ -5832,12 +5900,17 @@
(func_value (calculate_func_val wrap_level))
; if variadic, we just use the wrapper func and don't expect callers to know that we're varidic
(func_value (mif variadic (mod_fval_to_wrap func_value) func_value))
(memo (put memo (.hash c) func_value))
; Put our eventual func_value in the memo before we actually compile for recursion etc
(memo (put (put memo new_hash func_value) old_hash func_value))
((inner_analysis_data analysis_err pectx) (function-analysis c memo pectx))
(ctx (array datasi funcs memo env pectx outer_inline_locals))
; EARLY QUIT IF Analysis Error
) (mif analysis_err (array nil nil analysis_err ctx) (dlet (
(new_inline_locals (array))
(ctx (array datasi funcs memo env pectx new_inline_locals))
(new_tce_data (array our_func_idx full_params))
(inner_env (make_tmp_inner_env params de? se env_id))
@@ -5863,19 +5936,7 @@
(new_get_s_env_code (if dont_lazy_env basic_get_s_env_code lazy_get_s_env_code))
((datasi funcs memo env pectx inline_locals) ctx)
(inner_ctx (array datasi funcs memo inner_env pectx inline_locals))
;-------------
;(_ (true_print "Doing call-info" full_params))
;(call_info (call-info c env_id))
;-------------
(_ (true_print "Doing infer_types for body part for " full_params))
(inner_type_data (infer_types body (.marked_env_idx inner_env) empty_dict-list empty_dict-list))
(_ (true_print "done infer_types, Doing pseudo perceus " full_params))
((used_map_before used_map_sub_data) (pseudo_perceus body (.marked_env_idx inner_env) memo (push_used_map empty_use_map full_params)))
(_ (true_print "done pseudo_perceus, Doing borrow? " full_params))
((borrowed borrow_sub_data) (borrow? body false (.marked_env_idx inner_env) used_map_sub_data))
(_ (mif borrowed (error "body hast to be borrowed? " borrowed " " (true_str_strip body))))
(_ (true_print "done pseudo_perceus, Doing compile_body func def compile-inner " full_params))
(inner_analysis_data (array inner_type_data used_map_sub_data))
((inner_value inner_code err ctx) (compile-inner inner_ctx body false false (local.get '$outer_s_env) new_get_s_env_code 0 new_tce_data inner_analysis_data))
(_ (true_print "Done compile_body func def compile-inner " full_params))
; Don't overwrite env with what was our inner env! Env is returned as part of context to our caller!
@@ -5935,13 +5996,15 @@
(funcs (concat old_funcs wrapper_func our_func (drop funcs (+ 2 (len old_funcs)))))
) (array func_value nil err (array datasi funcs memo env pectx outer_inline_locals)))
))
))))
(_ (print_strip "returning " func_value " for " c))
(_ (if (not (int? func_value)) (error "BADBADBADfunc")))
(full_result (mif env_val
(array (combine_env_comb_val env_val func_value) nil (mif func_err (str func_err ", from compiling comb body") (mif env_err (str env_err ", from compiling comb env") nil)) ctx)
(array nil (combine_env_code_comb_val_code env_code (mod_fval_to_wrap func_value)) (mif func_err (str func_err ", from compiling comb body (env as code)") (mif env_err (str env_err ", from compiling comb env (as code)") nil)) ctx)))
;(_ (mif env_val (true_print "total function " (idx full_result 0) " based on " env_val " and " func_value)))
(_ (if (and (not func_err) (not (int? func_value))) (error "BADBADBADfunc")))
(full_result (cond
((!= nil func_err) (array nil nil (str func_err ", from compiling comb body") ctx))
((!= nil env_err) (array nil nil (str env_err ", from compiling env") ctx))
((!= nil env_val) (array (combine_env_comb_val env_val func_value) nil nil ctx))
(true (array nil (combine_env_code_comb_val_code env_code (mod_fval_to_wrap func_value)) nil ctx))))
) full_result
))))
@@ -6333,6 +6396,34 @@
(mk_int_code_i32s (global.get '$num_mallocs))
(mk_int_code_i32s (global.get '$num_sbrks))
(mk_int_code_i32s (global.get '$num_compiled_dzero))
(mk_int_code_i32s (global.get '$num_compiled_done))
(mk_int_code_i32s (global.get '$num_interp_dzero))
(mk_int_code_i32s (global.get '$num_interp_done))
(mk_int_code_i32s (global.get '$num_all_evals))
(mk_int_code_i32s (global.get '$num_evals))
(call '$print (i64.const newline_msg_val))
(call '$print (i64.const newline_msg_val))
(call '$print (i64.const newline_msg_val))
(call '$print (i64.const newline_msg_val))
(call '$print )
(call '$print (i64.const newline_msg_val))
(call '$print )
(call '$print (i64.const newline_msg_val))
(call '$print )
(call '$print (i64.const newline_msg_val))
(call '$print )
(call '$print (i64.const newline_msg_val))
(call '$print )
(call '$print (i64.const newline_msg_val))
(call '$print )
(call '$print (i64.const newline_msg_val))
(call '$print (i64.const newline_msg_val))
(call '$print (i64.const newline_msg_val))
(call '$print (i64.const newline_msg_val))
(call '$print (i64.const newline_msg_val))
(call '$print )
(call '$print (i64.const newline_msg_val))

163
website/LICENSE Normal file
View File

@@ -0,0 +1,163 @@
###########################
For Recursive (the font):
###########################
Copyright 2020 The Recursive Project Authors (https://github.com/arrowtype/recursive)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
###########################
For CodeJar:
###########################
MIT License
Copyright (c) 2020 Anton Medvedev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
###########################
For highlight.js:
###########################
BSD 3-Clause License
Copyright (c) 2006, Ivan Sagalaev.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

BIN
website/Recursive.woff2 Normal file

Binary file not shown.

466
website/codejar.js Normal file
View File

@@ -0,0 +1,466 @@
const globalWindow = window;
export function CodeJar(editor, highlight, opt = {}) {
const options = Object.assign({ tab: '\t', indentOn: /[({\[]$/, moveToNewLine: /^[)}\]]/, spellcheck: false, catchTab: true, preserveIdent: true, addClosing: true, history: true, window: globalWindow }, opt);
const window = options.window;
const document = window.document;
let listeners = [];
let history = [];
let at = -1;
let focus = false;
let callback;
let prev; // code content prior keydown event
editor.setAttribute('contenteditable', 'plaintext-only');
editor.setAttribute('spellcheck', options.spellcheck ? 'true' : 'false');
editor.style.outline = 'none';
editor.style.overflowWrap = 'break-word';
editor.style.overflowY = 'auto';
editor.style.whiteSpace = 'pre-wrap';
let isLegacy = false; // true if plaintext-only is not supported
highlight(editor);
if (editor.contentEditable !== 'plaintext-only')
isLegacy = true;
if (isLegacy)
editor.setAttribute('contenteditable', 'true');
const debounceHighlight = debounce(() => {
const pos = save();
highlight(editor, pos);
restore(pos);
}, 30);
let recording = false;
const shouldRecord = (event) => {
return !isUndo(event) && !isRedo(event)
&& event.key !== 'Meta'
&& event.key !== 'Control'
&& event.key !== 'Alt'
&& !event.key.startsWith('Arrow');
};
const debounceRecordHistory = debounce((event) => {
if (shouldRecord(event)) {
recordHistory();
recording = false;
}
}, 300);
const on = (type, fn) => {
listeners.push([type, fn]);
editor.addEventListener(type, fn);
};
on('keydown', event => {
if (event.defaultPrevented)
return;
prev = toString();
if (options.preserveIdent)
handleNewLine(event);
else
legacyNewLineFix(event);
if (options.catchTab)
handleTabCharacters(event);
if (options.addClosing)
handleSelfClosingCharacters(event);
if (options.history) {
handleUndoRedo(event);
if (shouldRecord(event) && !recording) {
recordHistory();
recording = true;
}
}
if (isLegacy && !isCopy(event))
restore(save());
});
on('keyup', event => {
if (event.defaultPrevented)
return;
if (event.isComposing)
return;
if (prev !== toString())
debounceHighlight();
debounceRecordHistory(event);
if (callback)
callback(toString());
});
on('focus', _event => {
focus = true;
});
on('blur', _event => {
focus = false;
});
on('paste', event => {
recordHistory();
handlePaste(event);
recordHistory();
if (callback)
callback(toString());
});
function save() {
const s = getSelection();
const pos = { start: 0, end: 0, dir: undefined };
let { anchorNode, anchorOffset, focusNode, focusOffset } = s;
if (!anchorNode || !focusNode)
throw 'error1';
// If the anchor and focus are the editor element, return either a full
// highlight or a start/end cursor position depending on the selection
if (anchorNode === editor && focusNode === editor) {
pos.start = (anchorOffset > 0 && editor.textContent) ? editor.textContent.length : 0;
pos.end = (focusOffset > 0 && editor.textContent) ? editor.textContent.length : 0;
pos.dir = (focusOffset >= anchorOffset) ? '->' : '<-';
return pos;
}
// Selection anchor and focus are expected to be text nodes,
// so normalize them.
if (anchorNode.nodeType === Node.ELEMENT_NODE) {
const node = document.createTextNode('');
anchorNode.insertBefore(node, anchorNode.childNodes[anchorOffset]);
anchorNode = node;
anchorOffset = 0;
}
if (focusNode.nodeType === Node.ELEMENT_NODE) {
const node = document.createTextNode('');
focusNode.insertBefore(node, focusNode.childNodes[focusOffset]);
focusNode = node;
focusOffset = 0;
}
visit(editor, el => {
if (el === anchorNode && el === focusNode) {
pos.start += anchorOffset;
pos.end += focusOffset;
pos.dir = anchorOffset <= focusOffset ? '->' : '<-';
return 'stop';
}
if (el === anchorNode) {
pos.start += anchorOffset;
if (!pos.dir) {
pos.dir = '->';
}
else {
return 'stop';
}
}
else if (el === focusNode) {
pos.end += focusOffset;
if (!pos.dir) {
pos.dir = '<-';
}
else {
return 'stop';
}
}
if (el.nodeType === Node.TEXT_NODE) {
if (pos.dir != '->')
pos.start += el.nodeValue.length;
if (pos.dir != '<-')
pos.end += el.nodeValue.length;
}
});
// collapse empty text nodes
editor.normalize();
return pos;
}
function restore(pos) {
const s = getSelection();
let startNode, startOffset = 0;
let endNode, endOffset = 0;
if (!pos.dir)
pos.dir = '->';
if (pos.start < 0)
pos.start = 0;
if (pos.end < 0)
pos.end = 0;
// Flip start and end if the direction reversed
if (pos.dir == '<-') {
const { start, end } = pos;
pos.start = end;
pos.end = start;
}
let current = 0;
visit(editor, el => {
if (el.nodeType !== Node.TEXT_NODE)
return;
const len = (el.nodeValue || '').length;
if (current + len > pos.start) {
if (!startNode) {
startNode = el;
startOffset = pos.start - current;
}
if (current + len > pos.end) {
endNode = el;
endOffset = pos.end - current;
return 'stop';
}
}
current += len;
});
if (!startNode)
startNode = editor, startOffset = editor.childNodes.length;
if (!endNode)
endNode = editor, endOffset = editor.childNodes.length;
// Flip back the selection
if (pos.dir == '<-') {
[startNode, startOffset, endNode, endOffset] = [endNode, endOffset, startNode, startOffset];
}
s.setBaseAndExtent(startNode, startOffset, endNode, endOffset);
}
function beforeCursor() {
const s = getSelection();
const r0 = s.getRangeAt(0);
const r = document.createRange();
r.selectNodeContents(editor);
r.setEnd(r0.startContainer, r0.startOffset);
return r.toString();
}
function afterCursor() {
const s = getSelection();
const r0 = s.getRangeAt(0);
const r = document.createRange();
r.selectNodeContents(editor);
r.setStart(r0.endContainer, r0.endOffset);
return r.toString();
}
function handleNewLine(event) {
if (event.key === 'Enter') {
const before = beforeCursor();
const after = afterCursor();
let [padding] = findPadding(before);
let newLinePadding = padding;
// If last symbol is "{" ident new line
if (options.indentOn.test(before)) {
newLinePadding += options.tab;
}
// Preserve padding
if (newLinePadding.length > 0) {
preventDefault(event);
event.stopPropagation();
insert('\n' + newLinePadding);
}
else {
legacyNewLineFix(event);
}
// Place adjacent "}" on next line
if (newLinePadding !== padding && options.moveToNewLine.test(after)) {
const pos = save();
insert('\n' + padding);
restore(pos);
}
}
}
function legacyNewLineFix(event) {
// Firefox does not support plaintext-only mode
// and puts <div><br></div> on Enter. Let's help.
if (isLegacy && event.key === 'Enter') {
preventDefault(event);
event.stopPropagation();
if (afterCursor() == '') {
insert('\n ');
const pos = save();
pos.start = --pos.end;
restore(pos);
}
else {
insert('\n');
}
}
}
function handleSelfClosingCharacters(event) {
const open = `([{'"`;
const close = `)]}'"`;
const codeAfter = afterCursor();
const codeBefore = beforeCursor();
const escapeCharacter = codeBefore.substr(codeBefore.length - 1) === '\\';
const charAfter = codeAfter.substr(0, 1);
if (close.includes(event.key) && !escapeCharacter && charAfter === event.key) {
// We already have closing char next to cursor.
// Move one char to right.
const pos = save();
preventDefault(event);
pos.start = ++pos.end;
restore(pos);
}
else if (open.includes(event.key)
&& !escapeCharacter
&& (`"'`.includes(event.key) || ['', ' ', '\n'].includes(charAfter))) {
preventDefault(event);
const pos = save();
const wrapText = pos.start == pos.end ? '' : getSelection().toString();
const text = event.key + wrapText + close[open.indexOf(event.key)];
insert(text);
pos.start++;
pos.end++;
restore(pos);
}
}
function handleTabCharacters(event) {
if (event.key === 'Tab') {
preventDefault(event);
if (event.shiftKey) {
const before = beforeCursor();
let [padding, start,] = findPadding(before);
if (padding.length > 0) {
const pos = save();
// Remove full length tab or just remaining padding
const len = Math.min(options.tab.length, padding.length);
restore({ start, end: start + len });
document.execCommand('delete');
pos.start -= len;
pos.end -= len;
restore(pos);
}
}
else {
insert(options.tab);
}
}
}
function handleUndoRedo(event) {
if (isUndo(event)) {
preventDefault(event);
at--;
const record = history[at];
if (record) {
editor.innerHTML = record.html;
restore(record.pos);
}
if (at < 0)
at = 0;
}
if (isRedo(event)) {
preventDefault(event);
at++;
const record = history[at];
if (record) {
editor.innerHTML = record.html;
restore(record.pos);
}
if (at >= history.length)
at--;
}
}
function recordHistory() {
if (!focus)
return;
const html = editor.innerHTML;
const pos = save();
const lastRecord = history[at];
if (lastRecord) {
if (lastRecord.html === html
&& lastRecord.pos.start === pos.start
&& lastRecord.pos.end === pos.end)
return;
}
at++;
history[at] = { html, pos };
history.splice(at + 1);
const maxHistory = 300;
if (at > maxHistory) {
at = maxHistory;
history.splice(0, 1);
}
}
function handlePaste(event) {
preventDefault(event);
const text = (event.originalEvent || event)
.clipboardData
.getData('text/plain')
.replace(/\r/g, '');
const pos = save();
insert(text);
highlight(editor);
restore({
start: Math.min(pos.start, pos.end) + text.length,
end: Math.min(pos.start, pos.end) + text.length,
dir: '<-',
});
}
function visit(editor, visitor) {
const queue = [];
if (editor.firstChild)
queue.push(editor.firstChild);
let el = queue.pop();
while (el) {
if (visitor(el) === 'stop')
break;
if (el.nextSibling)
queue.push(el.nextSibling);
if (el.firstChild)
queue.push(el.firstChild);
el = queue.pop();
}
}
function isCtrl(event) {
return event.metaKey || event.ctrlKey;
}
function isUndo(event) {
return isCtrl(event) && !event.shiftKey && getKeyCode(event) === 'Z';
}
function isRedo(event) {
return isCtrl(event) && event.shiftKey && getKeyCode(event) === 'Z';
}
function isCopy(event) {
return isCtrl(event) && getKeyCode(event) === 'C';
}
function getKeyCode(event) {
let key = event.key || event.keyCode || event.which;
if (!key)
return undefined;
return (typeof key === 'string' ? key : String.fromCharCode(key)).toUpperCase();
}
function insert(text) {
text = text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
document.execCommand('insertHTML', false, text);
}
function debounce(cb, wait) {
let timeout = 0;
return (...args) => {
clearTimeout(timeout);
timeout = window.setTimeout(() => cb(...args), wait);
};
}
function findPadding(text) {
// Find beginning of previous line.
let i = text.length - 1;
while (i >= 0 && text[i] !== '\n')
i--;
i++;
// Find padding of the line.
let j = i;
while (j < text.length && /[ \t]/.test(text[j]))
j++;
return [text.substring(i, j) || '', i, j];
}
function toString() {
return editor.textContent || '';
}
function preventDefault(event) {
event.preventDefault();
}
function getSelection() {
var _a;
if (((_a = editor.parentNode) === null || _a === void 0 ? void 0 : _a.nodeType) == Node.DOCUMENT_FRAGMENT_NODE) {
return editor.parentNode.getSelection();
}
return window.getSelection();
}
return {
updateOptions(newOptions) {
Object.assign(options, newOptions);
},
updateCode(code) {
editor.textContent = code;
highlight(editor);
},
onUpdate(cb) {
callback = cb;
},
toString,
save,
restore,
recordHistory,
destroy() {
for (let [type, fn] of listeners) {
editor.removeEventListener(type, fn);
}
},
};
}

9
website/default.min.css vendored Normal file
View File

@@ -0,0 +1,9 @@
/*!
Theme: Default
Description: Original highlight.js style
Author: (c) Ivan Sagalaev <maniac@softwaremaniacs.org>
Maintainer: @highlightjs/core-team
Website: https://highlightjs.org/
License: see project LICENSE
Touched: 2021
*/pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}.hljs{background:#f3f3f3;color:#444}.hljs-comment{color:#697070}.hljs-punctuation,.hljs-tag{color:#444a}.hljs-tag .hljs-attr,.hljs-tag .hljs-name{color:#444}.hljs-attribute,.hljs-doctag,.hljs-keyword,.hljs-meta .hljs-keyword,.hljs-name,.hljs-selector-tag{font-weight:700}.hljs-deletion,.hljs-number,.hljs-quote,.hljs-selector-class,.hljs-selector-id,.hljs-string,.hljs-template-tag,.hljs-type{color:#800}.hljs-section,.hljs-title{color:#800;font-weight:700}.hljs-link,.hljs-operator,.hljs-regexp,.hljs-selector-attr,.hljs-selector-pseudo,.hljs-symbol,.hljs-template-variable,.hljs-variable{color:#ab5656}.hljs-literal{color:#695}.hljs-addition,.hljs-built_in,.hljs-bullet,.hljs-code{color:#397300}.hljs-meta{color:#1f7199}.hljs-meta .hljs-string{color:#38a}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}

BIN
website/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

1202
website/highlight.min.js vendored Normal file

File diff suppressed because one or more lines are too long

171
website/index.html Normal file
View File

@@ -0,0 +1,171 @@
<!doctype html>
<html lang="en-us">
<meta charset="UTF-8">
<head>
<style>
@font-face {
font-family: 'Recursive';
font-style: oblique 0deg 15deg;
font-weight: 300 1000;
font-display: swap;
src: url(./Recursive.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
:root {
--rec-wght: 400;
--rec-slnt: 0;
--rec-mono: 0;
--rec-casl: 0;
--rec-csrv: 0;
}
* {
font-variation-settings: "wght" var(--rec-wght),
"slnt" var(--rec-slnt),
"MONO" var(--rec-mono),
"CASL" var(--rec-casl),
"CRSV" var(--rec-csrv);
}
body {
max-width: 45em;
margin: 1em auto;
padding: 0 .62em;
font: 1.2em/1.62 'Recursive', sans-serif;
}
h1, h2, h3, h4 {
line-height:1.2;
--rec-wght: 700;
--rec-casl: 1;
--rec-crsv: 1;
}
h1 {
line-height:0.7;
font-size: 4em;
--rec-wght: 900;
--rec-slnt: -15;
text-decoration: underline;
text-decoration-thickness: 0.4rem;
//border-bottom: 0.08em solid;
//border-left: 0.1em solid;
//display: inline-block;
}
h2 { font-size: 3em; }
h3 { font-size: 1.5em; }
h4 { font-size: 1.2em; }
i { --rec-slnt: -14; }
b { --rec-wght: 600; }
.run_container { position: relative; }
.editor {
font-family: 'Recursive', monospace;
font-size: 1rem;
--rec-mono: 1;
border-radius: 6px;
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2);
height: 7em;
letter-spacing: normal;
tab-size: 4;
}
.output {
margin-block-start: 1rem;
font-family: 'Recursive', monospace;
font-size: 1rem;
--rec-mono: 1;
tab-size: 4;
height: 5em;
width: 100%;
}
.run_button {
font-family: 'Recursive', sans-serif;
font-size: 1em;
--rec-wght: 900;
--rec-slnt: -15;
--rec-casl: 1;
--rec-crsv: 1;
position: absolute;
top: 0;
right: 0;
}
</style>
</head>
<body>
<header><h1>Kraken</h1></header>
<i>FOSS Fexprs: <a title="Kraken on GitHub" href="https://github.com/limvot/kraken">https://github.com/limvot/kraken</a></i>
<br>
<h3>Demo:</h3>
<div class="run_container">
<div class="editor" id="hello_editor">; Of course
(println "Hello World")
; Just print 3
(println "Math works:" (+ 1 2))
</div>
<textarea class="output" id="hello_output">Output will appear here</textarea>
<button class="run_button" onclick="executeKraken(hello_editor_jar.toString(), 'hello_output')"><b>Run</b></button> <br>
</div>
<a name="concept"/>
<h3>Concept:</h3>
<ul>
<li> Minimal, close to the metal Kernel/Scheme (operate on words, bytes, arrays) as AST / core language, with Kernel/Vau calculus inspiration oblivating the need for non-reader macros (<a title="Kernel/Vau calculus thesis" href="https://web.wpi.edu/Pubs/ETD/Available/etd-090110-124904/unrestricted/jshutt.pdf">Kernel/Vau calculus thesis</a>)
<li> Full Context-free (and eventually, context sensitive) reader macros using FUN-GLL (<a title="fun-gll paper" href="https://www.sciencedirect.com/science/article/pii/S2590118420300058">FUN-GLL paper</a>) to extend language's syntax dynamically
<li> Implement Type Systems as Macros (but using Vaus instead of macros) (<a title="type systems as macros paper 1" href="http://www.ccs.neu.edu/home/stchang/pubs/ckg-popl2017.pdf">paper, up to System Fω</a>) (<a title="type systems as macros paper 2" href="https://www.ccs.neu.edu/home/stchang/pubs/cbtb-popl2020.pdf">second paper, up to dependent types</a>)
<li> Use above "type systems as vaus" to create richer language and embed entire other programming languages (syntax, semantics, and type system) for flawless interop/FFI (C, Go, Lua, JS, etc)
<li> File is interpreted, and then if "main" exists it is compiled, spidering backwards to referenced functions and data (Allows interpreted code to do metaprogramming, dependency resolution, generate code, etc, which is then compiled)
<li> Regionalized Value State Dependence Graph as backend-IR, enabling simpler implementations of powerful optimizations (<a title="RSVDG paper" href="https://arxiv.org/pdf/1912.05036.pdf">RSVDG paper</a>) so that embedded languages have good performance when compiled with little code
</ul>
<a name="about"/>
<h3> About:</h3>
<p> Currently, I am bootstrapping this new core Lisp out of my prior compiler for my programming language, Kraken. I have implemented the first version of the FUN-GLL algorithm and have working vaus and context-free reader macros.
<p> The general flow is that the input files will be executed with the core Lisp interpreter, and if there is a "main" symbol defined the compiler emits C code for that function & all other functions & data that it references. In this way the language supports very powerful meta-programming at compile time, including adding syntax to the language, arbitrary computation, and importing other files, and then compiles into a static executable.
<p> Below are a few examples of using the vau / live grammar modification / context-free reader macros to implement basic methods as well as embed the BF language into the core Lisp. The core Lisp implementation has been compiled to WebAssembly and should be able to run in your browser. Feel free to make edits and play around below.
<br>
Note that the current implementation is inefficient, and sometimes has problems running in phone web browsers.
<a name="hello_example"/>
<a name="vau_core"/>
<h4>Vau/Kernel as simple core:</h4>
By constructing our core language on a very simple Vau/Kernel base, we can keep the base truely tiny, and build up normal Lisp functions and programming language features in the language itself. This should help implement other programming languages concisely, and will hopefully make optimization easier and more broadly applicable.
<br>
Below is the current prelude that adds quoting, quasiquoting, syntax for arrays and quoting/quasiquoting, do, if, let, and even lambda itself!
<a name="next_steps"/>
<h3>Next Steps</h3>
<ul>
<li> Implement persistent functional data structures
<ul>
<li> Hash Array-Mapped Trie (HAMT) / Relaxed Radix Balance Tree (RRB-Tree)
<li> Hash Map based on the above
<li> Hash Set based on the above
</ul>
<li> Prototype Type Systems as Macros, may require macro system rewrite/upgrade
<li> Sketch out Kraken language on top of core Lisp, includes basic Hindley-Milner type system implemented with Macros and above data structures
<li> Re-self-host using functional approach in above Kraken language
<li> Use Type System Macros to implement automatic transient creation on HAMT/RBB-Tree as an optimization
<li> Implement RVSDG IR and develop best bang-for-buck optimizations using it
</ul>
<link rel="stylesheet" href="./default.min.css">
<script src="./highlight.min.js"></script>
<script type="module">
import {CodeJar} from './codejar.js'
document.querySelectorAll('.editor').forEach((editor_div) => {
window[editor_div.id + "_jar"] = CodeJar(editor_div, hljs.highlightElement)
});
</script>
<script>
var output_name = ""
var Module = {
noInitialRun: true,
onRuntimeInitialized: () => {
},
print: txt => {
document.getElementById(output_name).value += txt + "\n";
},
printErr: txt => {
document.getElementById(output_name).value += "STDERR:[" + txt + "]\n";
}
};
function executeKraken(code, new_output_name) {
output_name = new_output_name
document.getElementById(new_output_name).value = "running...\n";
Module.callMain(["-C", code]);
}
</script>
<script type="text/javascript" src="k_prime.js"></script>
</body>
</html>