From ef57a42eb6954558edc76bd0362e78e7c2b25541 Mon Sep 17 00:00:00 2001 From: Jeff Date: Tue, 22 Aug 2023 11:40:50 -0400 Subject: [PATCH] Migrate repository --- .gitignore | 1 + Cargo.lock | 3906 ++++++++++++++++++++++++++++++ Cargo.toml | 40 + README.md | 286 +++ examples/cpu_monitor.whale | 9 + examples/fetch.whale | 4 + examples/hello_world.whale | 1 + examples/map.whale | 7 + examples/random_user_data.whale | 14 + examples/table.whale | 29 + examples/toolbox.whale | 21 + examples/wait.whale | 3 + src/error.rs | 615 +++++ src/interface.rs | 58 + src/lib.rs | 23 + src/macros/collections.rs | 561 +++++ src/macros/command.rs | 119 + src/macros/data_formats.rs | 151 ++ src/macros/disks.rs | 123 + src/macros/filesystem.rs | 454 ++++ src/macros/general.rs | 126 + src/macros/gui.rs | 375 +++ src/macros/logic.rs | 81 + src/macros/mod.rs | 368 +++ src/macros/network.rs | 23 + src/macros/package_management.rs | 170 ++ src/macros/random.rs | 149 ++ src/macros/system.rs | 24 + src/macros/test.rs | 42 + src/macros/time.rs | 43 + src/main.rs | 273 +++ src/operator.rs | 547 +++++ src/token.rs | 562 +++++ src/tree/iter.rs | 94 + src/tree/mod.rs | 905 +++++++ src/value/function.rs | 28 + src/value/iter.rs | 21 + src/value/mod.rs | 731 ++++++ src/value/table.rs | 353 +++ src/value/time.rs | 88 + src/value/value_type.rs | 86 + src/value/variable_map.rs | 211 ++ 42 files changed, 11725 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 README.md create mode 100644 examples/cpu_monitor.whale create mode 100644 examples/fetch.whale create mode 100644 examples/hello_world.whale create mode 100644 examples/map.whale create mode 100644 examples/random_user_data.whale create mode 100644 examples/table.whale create mode 100644 examples/toolbox.whale create mode 100644 examples/wait.whale create mode 100644 src/error.rs create mode 100644 src/interface.rs create mode 100644 src/lib.rs create mode 100644 src/macros/collections.rs create mode 100644 src/macros/command.rs create mode 100644 src/macros/data_formats.rs create mode 100644 src/macros/disks.rs create mode 100644 src/macros/filesystem.rs create mode 100644 src/macros/general.rs create mode 100644 src/macros/gui.rs create mode 100644 src/macros/logic.rs create mode 100644 src/macros/mod.rs create mode 100644 src/macros/network.rs create mode 100644 src/macros/package_management.rs create mode 100644 src/macros/random.rs create mode 100644 src/macros/system.rs create mode 100644 src/macros/test.rs create mode 100644 src/macros/time.rs create mode 100644 src/main.rs create mode 100644 src/operator.rs create mode 100644 src/token.rs create mode 100644 src/tree/iter.rs create mode 100644 src/tree/mod.rs create mode 100644 src/value/function.rs create mode 100644 src/value/iter.rs create mode 100644 src/value/mod.rs create mode 100644 src/value/table.rs create mode 100644 src/value/time.rs create mode 100644 src/value/value_type.rs create mode 100644 src/value/variable_map.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..bf57fb5 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,3906 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "ab_glyph" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5110f1c78cf582855d895ecd0746b653db010cec6d9f5575293f27934d980a39" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c71b1793ee61086797f5c80b6efa2b8ffa6d5dd703f118545808a7f2e27f7046" + +[[package]] +name = "accesskit" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02c98a5d094590335462354da402d754fe2cb78f0e6ce5024611c28ed539c1de" + +[[package]] +name = "accesskit_consumer" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca541e0fdb600916d196a940228df99b86d804fd2e6ef13894d7814f2799db43" +dependencies = [ + "accesskit", +] + +[[package]] +name = "accesskit_macos" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4baea9413f0daf1cd4aab199bc09f8139cd726ce7673d523c27d186b8b878325" +dependencies = [ + "accesskit", + "accesskit_consumer", + "objc2", + "once_cell", +] + +[[package]] +name = "accesskit_unix" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4d1517421278cc8e67422d0786a18cf4291093ebe49eadf1cf989ff80e57f90" +dependencies = [ + "accesskit", + "accesskit_consumer", + "async-channel", + "atspi", + "futures-lite", + "serde", + "zbus", +] + +[[package]] +name = "accesskit_windows" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11c7f177739f23bd19bb856e4a64fdd96eb8638ec0a6a6dde9a7019a9e91c53" +dependencies = [ + "accesskit", + "accesskit_consumer", + "arrayvec 0.7.4", + "once_cell", + "paste", + "windows 0.44.0", +] + +[[package]] +name = "accesskit_winit" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14f1bd64cd0b480cafb7bdd91eb489a1ff50f0f5702437b9efa32a25b8bb82a1" +dependencies = [ + "accesskit", + "accesskit_macos", + "accesskit_unix", + "accesskit_windows", + "winit", +] + +[[package]] +name = "addr2line" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4fa78e18c64fce05e902adecd7a5eed15a5e0a3439f7b0e169f0252214865e3" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "ahash" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c99f64d1e06488f620f932677e24bc6e2897582980441ae90a671415bd7ec2f" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", +] + +[[package]] +name = "aho-corasick" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43f6cb1bf222025340178f382c426f13757b2960e89779dfcb319c32542a5a41" +dependencies = [ + "memchr", +] + +[[package]] +name = "android-activity" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40bc1575e653f158cbdc6ebcd917b9564e66321c5325c232c3591269c257be69" +dependencies = [ + "android-properties", + "bitflags 1.3.2", + "cc", + "jni-sys", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum 0.6.1", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ca84f3628370c59db74ee214b3263d58f9aadd9b4fe7e711fd87dc452b7f163" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is-terminal", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a30da5c5f2d5e72842e00bcb57657162cdabef0931f40e2deb9b4140440cecd" + +[[package]] +name = "anstyle-parse" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "938874ff5980b03a87c5524b3ae5b59cf99b1d6bc836848df7bc5ada9643c333" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b" +dependencies = [ + "windows-sys 0.48.0", +] + +[[package]] +name = "anstyle-wincon" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180abfa45703aebe0093f79badacc01b8fd4ea2e35118747e5811127f926e188" +dependencies = [ + "anstyle", + "windows-sys 0.48.0", +] + +[[package]] +name = "arboard" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6041616acea41d67c4a984709ddab1587fd0b10efe5cc563fee954d2f011854" +dependencies = [ + "clipboard-win", + "log", + "objc", + "objc-foundation", + "objc_id", + "once_cell", + "parking_lot", + "thiserror", + "winapi", + "x11rb", +] + +[[package]] +name = "arrayref" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b4930d2cb77ce62f89ee5d5289b4ac049559b1c45539271f5ed4fdc7db34545" + +[[package]] +name = "arrayvec" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" + +[[package]] +name = "arrayvec" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" + +[[package]] +name = "async-broadcast" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c48ccdbf6ca6b121e0f586cbc0e73ae440e56c67c30fa0873b4e110d9c26d2b" +dependencies = [ + "event-listener", + "futures-core", +] + +[[package]] +name = "async-channel" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35" +dependencies = [ + "concurrent-queue", + "event-listener", + "futures-core", +] + +[[package]] +name = "async-executor" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fa3dc5f2a8564f07759c008b9109dc0d39de92a88d5588b8a5036d286383afb" +dependencies = [ + "async-lock", + "async-task", + "concurrent-queue", + "fastrand 1.9.0", + "futures-lite", + "slab", +] + +[[package]] +name = "async-fs" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "279cf904654eeebfa37ac9bb1598880884924aab82e290aa65c9e77a0e142e06" +dependencies = [ + "async-lock", + "autocfg", + "blocking", + "futures-lite", +] + +[[package]] +name = "async-io" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fc5b45d93ef0529756f812ca52e44c221b35341892d3dcc34132ac02f3dd2af" +dependencies = [ + "async-lock", + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-lite", + "log", + "parking", + "polling", + "rustix 0.37.23", + "slab", + "socket2", + "waker-fn", +] + +[[package]] +name = "async-lock" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa24f727524730b077666307f2734b4a1a1c57acb79193127dcc8914d5242dd7" +dependencies = [ + "event-listener", +] + +[[package]] +name = "async-process" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9d28b1d97e08915212e2e45310d47854eafa69600756fc735fb788f75199c9" +dependencies = [ + "async-io", + "async-lock", + "autocfg", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix 0.37.23", + "signal-hook", + "windows-sys 0.48.0", +] + +[[package]] +name = "async-recursion" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e97ce7de6cf12de5d7226c73f5ba9811622f4db3a5b91b55c53e987e5f91cba" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.27", +] + +[[package]] +name = "async-task" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc7ab41815b3c653ccd2978ec3255c81349336702dfdf62ee6f7069b12a3aae" + +[[package]] +name = "async-trait" +version = "0.1.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b2d0f03b3640e3a630367e40c468cb7f309529c708ed1d88597047b0e7c6ef7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.27", +] + +[[package]] +name = "atomic-waker" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1181e1e0d1fce796a03db1ae795d67167da795f9cf4a39c37589e85ef57f26d3" + +[[package]] +name = "atomic_refcell" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79d6dc922a2792b006573f60b2648076355daeae5ce9cb59507e5908c9625d31" + +[[package]] +name = "atspi" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "674e7a3376837b2e7d12d34d58ac47073c491dc3bf6f71a7adaf687d4d817faa" +dependencies = [ + "async-recursion", + "async-trait", + "atspi-macros", + "enumflags2", + "futures-lite", + "serde", + "tracing", + "zbus", + "zbus_names", +] + +[[package]] +name = "atspi-macros" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb4870a32c0eaa17e35bca0e6b16020635157121fb7d45593d242c295bc768" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "backtrace" +version = "0.3.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4319208da049c43661739c5fade2ba182f09d1dc2299b32298d3a31692b17e12" +dependencies = [ + "addr2line", + "cc", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", +] + +[[package]] +name = "base64" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "630be753d4e58660abd17930c71b647fe46c27ea6b63cc59e1e3851406972e42" + +[[package]] +name = "block" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-sys" +version = "0.1.0-beta.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa55741ee90902547802152aaf3f8e5248aab7e21468089560d4c8840561146" +dependencies = [ + "objc-sys", +] + +[[package]] +name = "block2" +version = "0.2.0-alpha.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dd9e63c1744f755c2f60332b88de39d341e5e86239014ad839bd71c106dec42" +dependencies = [ + "block-sys", + "objc2-encode", +] + +[[package]] +name = "blocking" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77231a1c8f801696fc0123ec6150ce92cffb8e164a02afb9c8ddee0e9b65ad65" +dependencies = [ + "async-channel", + "async-lock", + "async-task", + "atomic-waker", + "fastrand 1.9.0", + "futures-lite", + "log", +] + +[[package]] +name = "bumpalo" +version = "3.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1" + +[[package]] +name = "bytemuck" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17febce684fd15d89027105661fec94afb475cb995fbc59d2865198446ba2eea" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdde5c9cd29ebd706ce1b35600920a33550e402fc998a2e53ad3b42c3c47a192" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.27", +] + +[[package]] +name = "byteorder" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" + +[[package]] +name = "bytes" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be" + +[[package]] +name = "calloop" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52e0d00eb1ea24371a97d2da6201c6747a633dc6dc1988ef503403b4c59504a8" +dependencies = [ + "bitflags 1.3.2", + "log", + "nix 0.25.1", + "slotmap", + "thiserror", + "vec_map", +] + +[[package]] +name = "cc" +version = "1.0.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" +dependencies = [ + "jobserver", +] + +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "cfg_aliases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" + +[[package]] +name = "cgl" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff" +dependencies = [ + "libc", +] + +[[package]] +name = "chrono" +version = "0.4.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec837a71355b28f6556dbd569b37b3f363091c0bd4b2e735674521b4c5fd9bc5" +dependencies = [ + "android-tzdata", + "iana-time-zone", + "js-sys", + "num-traits", + "time", + "wasm-bindgen", + "winapi", +] + +[[package]] +name = "clap" +version = "4.3.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd304a20bff958a57f04c4e96a2e7594cc4490a0e809cbd48bb6437edaa452d" +dependencies = [ + "clap_builder", + "clap_derive", + "once_cell", +] + +[[package]] +name = "clap_builder" +version = "4.3.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c6a3f08f1fe5662a35cfe393aec09c4df95f60ee93b7556505260f75eee9e1" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54a9bb5758fc5dfe728d1019941681eccaf0cf8a4189b692a0ee2f2ecf90a050" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.27", +] + +[[package]] +name = "clap_lex" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2da6da31387c7e4ef160ffab6d5e7f00c42626fe39aea70a7b0f1773f7dd6c1b" + +[[package]] +name = "clipboard-win" +version = "4.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7191c27c2357d9b7ef96baac1773290d4ca63b24205b82a3fd8a0637afcf0362" +dependencies = [ + "error-code", + "str-buf", + "winapi", +] + +[[package]] +name = "cocoa" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f425db7937052c684daec3bd6375c8abe2d146dca4b8b143d6db777c39138f3a" +dependencies = [ + "bitflags 1.3.2", + "block", + "cocoa-foundation", + "core-foundation", + "core-graphics", + "foreign-types", + "libc", + "objc", +] + +[[package]] +name = "cocoa-foundation" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "931d3837c286f56e3c58423ce4eba12d08db2374461a785c86f672b08b5650d6" +dependencies = [ + "bitflags 1.3.2", + "block", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", + "objc", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "colorchoice" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" + +[[package]] +name = "combine" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35ed6e9d84f0b51a7f52daf1c7d71dd136fd7a3f41a8462b8cdb8c78d920fad4" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "comfy-table" +version = "7.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ab77dbd8adecaf3f0db40581631b995f312a8a5ae3aa9993188bb8f23d83a5b" +dependencies = [ + "crossterm", + "strum 0.24.1", + "strum_macros 0.24.3", + "unicode-width", +] + +[[package]] +name = "concurrent-queue" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62ec6771ecfa0762d24683ee5a32ad78487a3d3afdc0fb8cae19d2c5deb50b7c" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "core-foundation" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" + +[[package]] +name = "core-graphics" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2581bbab3b8ffc6fcbd550bf46c355135d16e9ff2a6ea032ad6b9bf1d7efe4fb" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bb142d41022986c1d8ff29103a1411c8a3dfad3552f87a4f8dc50d61d4f4e33" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a33c2bf77f2df06183c3aa30d1e96c0695a313d4f9c453cc3762a6db39f99200" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6fd6f855243022dcecf8702fef0c297d4338e226845fe067f6341ad9fa0cef" +dependencies = [ + "cfg-if", + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae211234986c545741a7dc064309f67ee1e5ad243d0e48335adc0484d960bcc7" +dependencies = [ + "autocfg", + "cfg-if", + "crossbeam-utils", + "memoffset 0.9.0", + "scopeguard", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossterm" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a84cda67535339806297f1b331d6dd6320470d2a0fe65381e79ee9e156dd3d13" +dependencies = [ + "bitflags 1.3.2", + "crossterm_winapi", + "libc", + "mio", + "parking_lot", + "serde", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "csv" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626ae34994d3d8d668f4269922248239db4ae42d538b14c398b74a52208e8086" +dependencies = [ + "csv-core", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "csv-core" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90" +dependencies = [ + "memchr", +] + +[[package]] +name = "derivative" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dlib" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412" +dependencies = [ + "libloading 0.8.0", +] + +[[package]] +name = "downcast-rs" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ea835d29036a4087793836fa931b08837ad5e957da9e23886b29586fb9b6650" + +[[package]] +name = "ecolor" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e479a7fa3f23d4e794f8b2f8b3568dd4e47886ad1b12c9c095e141cb591eb63" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "eframe" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf4596583a2c680c55b6feaa748f74890c4f9cb9c7cb69d6117110444cb65b2f" +dependencies = [ + "bytemuck", + "cocoa", + "egui", + "egui-winit", + "egui_glow", + "glow", + "glutin", + "glutin-winit", + "image", + "js-sys", + "log", + "objc", + "percent-encoding", + "raw-window-handle", + "thiserror", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "winapi", + "winit", +] + +[[package]] +name = "egui" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3aef8ec3ae1b772f340170c65bf27d5b8c28f543a0116c844d2ac08d01123e7" +dependencies = [ + "accesskit", + "ahash", + "epaint", + "log", + "nohash-hasher", +] + +[[package]] +name = "egui-winit" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a49155fd4a0a4fb21224407a91de0030847972ef90fc64edb63621caea61cb2" +dependencies = [ + "accesskit_winit", + "arboard", + "egui", + "instant", + "log", + "raw-window-handle", + "smithay-clipboard", + "webbrowser", + "winit", +] + +[[package]] +name = "egui_extras" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9278f4337b526f0d57e5375e5a7340a311fa6ee8f9fcc75721ac50af13face02" +dependencies = [ + "egui", + "serde", +] + +[[package]] +name = "egui_glow" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f8c2752cdf1b0ef5fcda59a898cacabad974d4f5880e92a420b2c917022da64" +dependencies = [ + "bytemuck", + "egui", + "glow", + "log", + "memoffset 0.6.5", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "either" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91" + +[[package]] +name = "emath" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3857d743a6e0741cdd60b622a74c7a36ea75f5f8f11b793b41d905d2c9721a4b" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "encoding_rs" +version = "0.8.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071a31f4ee85403370b58aca746f01041ede6f0da2730960ad001edc2b71b394" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "enumflags2" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c041f5090df68b32bcd905365fd51769c8b9d553fe87fde0b683534f10c01bd2" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e9a1f9f7d83e59740248a6e14ecf93929ade55027844dfcea78beafccc15745" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.27", +] + +[[package]] +name = "epaint" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09333964d4d57f40a85338ba3ca5ed4716070ab184dcfed966b35491c5c64f3b" +dependencies = [ + "ab_glyph", + "ahash", + "atomic_refcell", + "bytemuck", + "ecolor", + "emath", + "log", + "nohash-hasher", + "parking_lot", +] + +[[package]] +name = "equivalent" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88bffebc5d80432c9b140ee17875ff173a8ab62faad5b257da912bd2f6c1c0a1" + +[[package]] +name = "errno" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a" +dependencies = [ + "errno-dragonfly", + "libc", + "windows-sys 0.48.0", +] + +[[package]] +name = "errno-dragonfly" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "error-code" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64f18991e7bf11e7ffee451b5318b5c1a73c52d0d0ada6e5a3017c8c1ced6a21" +dependencies = [ + "libc", + "str-buf", +] + +[[package]] +name = "event-listener" +version = "2.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" + +[[package]] +name = "fastrand" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" +dependencies = [ + "instant", +] + +[[package]] +name = "fastrand" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6999dc1837253364c2ebb0704ba97994bd874e8f195d665c50b7548f6ea92764" + +[[package]] +name = "fd-lock" +version = "3.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef033ed5e9bad94e55838ca0ca906db0e043f517adda0c8b79c7a8c66c93c1b5" +dependencies = [ + "cfg-if", + "rustix 0.38.3", + "windows-sys 0.48.0", +] + +[[package]] +name = "fdeflate" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d329bdeac514ee06249dabc27877490f17f5d371ec693360768b838e19f3ae10" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "flate2" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b9429470923de8e8cbd4d2dc513535400b4b3fef0319fb5c4e1f520a7bef743" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" + +[[package]] +name = "futures-io" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" + +[[package]] +name = "futures-lite" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce" +dependencies = [ + "fastrand 1.9.0", + "futures-core", + "futures-io", + "memchr", + "parking", + "pin-project-lite", + "waker-fn", +] + +[[package]] +name = "futures-sink" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e" + +[[package]] +name = "futures-task" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" + +[[package]] +name = "futures-util" +version = "0.3.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "gethostname" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1ebd34e35c46e00bb73e81363248d627782724609fe1b6396f553f68fe3862e" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "getrandom" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.11.0+wasi-snapshot-preview1", +] + +[[package]] +name = "gimli" +version = "0.27.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c80984affa11d98d1b88b66ac8853f143217b399d3c74116778ff8fdb4ed2e" + +[[package]] +name = "git2" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b989d6a7ca95a362cf2cfc5ad688b3a467be1f87e480b8dad07fee8c79b0044" +dependencies = [ + "bitflags 1.3.2", + "libc", + "libgit2-sys", + "log", + "openssl-probe", + "openssl-sys", + "url", +] + +[[package]] +name = "gl_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +dependencies = [ + "khronos_api", + "log", + "xml-rs", +] + +[[package]] +name = "glow" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "807edf58b70c0b5b2181dd39fe1839dbdb3ba02645630dc5f753e23da307f762" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "glutin" +version = "0.30.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b0385782048be65f0a9dd046c469d6a758a53fe1aa63a8111dea394d2ffa2f" +dependencies = [ + "bitflags 1.3.2", + "cfg_aliases", + "cgl", + "core-foundation", + "dispatch", + "glutin_egl_sys", + "glutin_glx_sys", + "glutin_wgl_sys", + "libloading 0.7.4", + "objc2", + "once_cell", + "raw-window-handle", + "wayland-sys 0.30.1", + "windows-sys 0.45.0", + "x11-dl", +] + +[[package]] +name = "glutin-winit" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "629a873fc04062830bfe8f97c03773bcd7b371e23bcc465d0a61448cd1588fa4" +dependencies = [ + "cfg_aliases", + "glutin", + "raw-window-handle", + "winit", +] + +[[package]] +name = "glutin_egl_sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b3bcbddc51573b977fc6dca5d93867e4f29682cdbaf5d13e48f4fa4346d4d87" +dependencies = [ + "gl_generator", + "windows-sys 0.45.0", +] + +[[package]] +name = "glutin_glx_sys" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b53cb5fe568964aa066a3ba91eac5ecbac869fb0842cd0dc9e412434f1a1494" +dependencies = [ + "gl_generator", + "x11-dl", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef89398e90033fc6bc65e9bd42fd29bbbfd483bda5b56dc5562f455550618165" +dependencies = [ + "gl_generator", +] + +[[package]] +name = "h2" +version = "0.3.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97ec8491ebaf99c8eaa73058b045fe58073cd6be7f596ac993ced0b0a0c01049" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http", + "indexmap 1.9.3", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "hermit-abi" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" +dependencies = [ + "libc", +] + +[[package]] +name = "hermit-abi" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "home" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5444c27eef6923071f7ebcc33e3444508466a76f7a2b93da00ed6e19f30c1ddb" +dependencies = [ + "windows-sys 0.48.0", +] + +[[package]] +name = "http" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd6effc99afb63425aff9b05836f029929e345a6148a14b7ecd5ab67af944482" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http-body" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" +dependencies = [ + "bytes", + "http", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" + +[[package]] +name = "httpdate" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" + +[[package]] +name = "hyper" +version = "0.14.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffb1cfd654a8219eaef89881fdb3bb3b1cdc5fa75ded05d6933b2b382e395468" +dependencies = [ + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", + "want", +] + +[[package]] +name = "hyper-tls" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" +dependencies = [ + "bytes", + "hyper", + "native-tls", + "tokio", + "tokio-native-tls", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fad5b825842d2b38bd206f3e81d6957625fd7f0a361e345c30e01a0ae2dd613" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "wasm-bindgen", + "windows 0.48.0", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "idna" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c" +dependencies = [ + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "image" +version = "0.24.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527909aa81e20ac3a44803521443a765550f09b5130c2c2fa1ea59c2f8f50a3a" +dependencies = [ + "bytemuck", + "byteorder", + "color_quant", + "num-rational", + "num-traits", + "png", +] + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", +] + +[[package]] +name = "indexmap" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" +dependencies = [ + "equivalent", + "hashbrown 0.14.0", +] + +[[package]] +name = "instant" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "io-lifetimes" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" +dependencies = [ + "hermit-abi 0.3.2", + "libc", + "windows-sys 0.48.0", +] + +[[package]] +name = "ipnet" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6" + +[[package]] +name = "is-terminal" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b" +dependencies = [ + "hermit-abi 0.3.2", + "rustix 0.38.3", + "windows-sys 0.48.0", +] + +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys", + "log", + "thiserror", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni-sys" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" + +[[package]] +name = "jobserver" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "936cfd212a0155903bcbc060e316fb6cc7cbf2e1907329391ebadc1fe0ce77c2" +dependencies = [ + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "json" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078e285eafdfb6c4b434e0d31e8cfcb5115b651496faca5749b88fafd4f23bfd" + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "libc" +version = "0.2.146" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f92be4933c13fd498862a9e02a3055f8a8d9c039ce33db97306fd5a6caa7f29b" + +[[package]] +name = "libgit2-sys" +version = "0.15.2+1.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a80df2e11fb4a61f4ba2ab42dbe7f74468da143f1a75c74e11dee7c813f694fa" +dependencies = [ + "cc", + "libc", + "libssh2-sys", + "libz-sys", + "openssl-sys", + "pkg-config", +] + +[[package]] +name = "libloading" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +dependencies = [ + "cfg-if", + "winapi", +] + +[[package]] +name = "libloading" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d580318f95776505201b28cf98eb1fa5e4be3b689633ba6a3e6cd880ff22d8cb" +dependencies = [ + "cfg-if", + "windows-sys 0.48.0", +] + +[[package]] +name = "libssh2-sys" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dc8a030b787e2119a731f1951d6a773e2280c660f8ec4b0f5e1505a386e71ee" +dependencies = [ + "cc", + "libc", + "libz-sys", + "openssl-sys", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "libz-sys" +version = "1.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d97137b25e321a73eef1418d1d5d2eda4d77e12813f8e6dead84bc52c5870a7b" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" + +[[package]] +name = "linux-raw-sys" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09fc20d2ca12cb9f044c93e3bd6d32d523e6e2ec3db4f7b2939cd99026ecd3f0" + +[[package]] +name = "lock_api" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1cc9717a20b1bb222f333e6a92fd32f7d8a18ddc5a3191a11af45dcbf4dcd16" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4" + +[[package]] +name = "malloc_buf" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" +dependencies = [ + "libc", +] + +[[package]] +name = "memchr" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" + +[[package]] +name = "memmap2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83faa42c0a078c393f6b29d5db232d8be22776a891f8f56e5284faee4a20b327" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" +dependencies = [ + "autocfg", +] + +[[package]] +name = "memoffset" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5de893c32cde5f383baa4c04c5d6dbdd735cfd4a794b0debdb2bb1b421da5ff4" +dependencies = [ + "autocfg", +] + +[[package]] +name = "memoffset" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" +dependencies = [ + "adler", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "927a765cd3fc26206e66b296465fa9d3e5ab003e651c1b3c060e7956d96b19d2" +dependencies = [ + "libc", + "log", + "wasi 0.11.0+wasi-snapshot-preview1", + "windows-sys 0.48.0", +] + +[[package]] +name = "native-tls" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e" +dependencies = [ + "lazy_static", + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "ndk" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451422b7e4718271c8b5b3aadf5adedba43dc76312454b387e98fae0fc951aa0" +dependencies = [ + "bitflags 1.3.2", + "jni-sys", + "ndk-sys", + "num_enum 0.5.11", + "raw-window-handle", + "thiserror", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.4.1+23.1.7779620" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cf2aae958bd232cac5069850591667ad422d263686d75b52a065f9badeee5a3" +dependencies = [ + "jni-sys", +] + +[[package]] +name = "nix" +version = "0.24.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa52e972a9a719cecb6864fb88568781eb706bac2cd1d4f04a648542dbf78069" +dependencies = [ + "bitflags 1.3.2", + "cfg-if", + "libc", + "memoffset 0.6.5", +] + +[[package]] +name = "nix" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f346ff70e7dbfd675fe90590b92d59ef2de15a8779ae305ebcbfd3f0caf59be4" +dependencies = [ + "autocfg", + "bitflags 1.3.2", + "cfg-if", + "libc", + "memoffset 0.6.5", +] + +[[package]] +name = "nix" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfdda3d196821d6af13126e40375cdf7da646a96114af134d5f417a9a1dc8e1a" +dependencies = [ + "bitflags 1.3.2", + "cfg-if", + "libc", + "memoffset 0.7.1", + "static_assertions", +] + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "ntapi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8a3895c6391c39d7fe7ebc444a87eb2991b2a0bc718fdabd071eec617fc68e4" +dependencies = [ + "winapi", +] + +[[package]] +name = "nu-ansi-term" +version = "0.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c073d3c1930d0751774acf49e66653acecb416c3a54c6ec095a9b11caddb5a68" +dependencies = [ + "windows-sys 0.48.0", +] + +[[package]] +name = "num-integer" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" +dependencies = [ + "autocfg", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0638a1c9d0a3c0914158145bc76cff373a75a627e6ecbfb71cbe6f453a5a19b0" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" +dependencies = [ + "hermit-abi 0.2.6", + "libc", +] + +[[package]] +name = "num_enum" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f646caf906c20226733ed5b1374287eb97e3c2a5c227ce668c1f2ce20ae57c9" +dependencies = [ + "num_enum_derive 0.5.11", +] + +[[package]] +name = "num_enum" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a015b430d3c108a207fd776d2e2196aaf8b1cf8cf93253e3a097ff3085076a1" +dependencies = [ + "num_enum_derive 0.6.1", +] + +[[package]] +name = "num_enum_derive" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcbff9bc912032c62bf65ef1d5aea88983b420f4f839db1e9b0c281a25c9c799" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "num_enum_derive" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96667db765a921f7b295ffee8b60472b686a51d4f21c2ee4ffdb94c7013b65a6" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.27", +] + +[[package]] +name = "objc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" +dependencies = [ + "malloc_buf", +] + +[[package]] +name = "objc-foundation" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1add1b659e36c9607c7aab864a76c7a4c2760cd0cd2e120f3fb8b952c7e22bf9" +dependencies = [ + "block", + "objc", + "objc_id", +] + +[[package]] +name = "objc-sys" +version = "0.2.0-beta.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b9834c1e95694a05a828b59f55fa2afec6288359cda67146126b3f90a55d7" + +[[package]] +name = "objc2" +version = "0.3.0-beta.3.patch-leaks.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e01640f9f2cb1220bbe80325e179e532cb3379ebcd1bf2279d703c19fe3a468" +dependencies = [ + "block2", + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2-encode" +version = "2.0.0-pre.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abfcac41015b00a120608fdaa6938c44cb983fee294351cc4bac7638b4e50512" +dependencies = [ + "objc-sys", +] + +[[package]] +name = "objc_id" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92d4ddb4bd7b50d730c215ff871754d0da6b2178849f8a2a2ab69712d0c073b" +dependencies = [ + "objc", +] + +[[package]] +name = "object" +version = "0.31.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bda667d9f2b5051b8833f59f3bf748b28ef54f850f4fcb389a252aa383866d1" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" + +[[package]] +name = "openssl" +version = "0.10.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "729b745ad4a5575dd06a3e1af1414bd330ee561c01b3899eb584baeaa8def17e" +dependencies = [ + "bitflags 1.3.2", + "cfg-if", + "foreign-types", + "libc", + "once_cell", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.27", +] + +[[package]] +name = "openssl-probe" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" + +[[package]] +name = "openssl-sys" +version = "0.9.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "866b5f16f90776b9bb8dc1e1802ac6f0513de3a7a7465867bfbc563dc737faac" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "orbclient" +version = "0.3.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "221d488cd70617f1bd599ed8ceb659df2147d9393717954d82a0f5e8032a6ab1" +dependencies = [ + "redox_syscall", +] + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "owned_ttf_parser" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "706de7e2214113d63a8238d1910463cfce781129a6f263d13fdb09ff64355ba4" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "parking" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14f2252c834a40ed9bb5422029649578e63aa341ac401f74e719dd1afda8394e" + +[[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.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93f00c865fe7cabf650081affecd3871070f26767e7b2070a3ffae14c654b447" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-targets 0.48.0", +] + +[[package]] +name = "paste" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c" + +[[package]] +name = "percent-encoding" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" + +[[package]] +name = "pin-project-lite" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkg-config" +version = "0.3.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" + +[[package]] +name = "png" +version = "0.17.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59871cc5b6cce7eaccca5a802b4173377a1c2ba90654246789a8fa2334426d11" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + +[[package]] +name = "polling" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b2d323e8ca7996b3e23126511a523f7e62924d93ecd5ae73b333815b0eb3dce" +dependencies = [ + "autocfg", + "bitflags 1.3.2", + "cfg-if", + "concurrent-queue", + "libc", + "log", + "pin-project-lite", + "windows-sys 0.48.0", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" + +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "raw-window-handle" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ff9a1f06a88b01621b7ae906ef0211290d1c8a168a15542486a8f61c0833b9" + +[[package]] +name = "rayon" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d2df5196e37bcc87abebc0053e20787d73847bb33134a69841207dd0a47f03b" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b8f95bd6966f5c87776639160a66bd8ab9895d9d4ab01ddba9fc60661aebe8d" +dependencies = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-utils", + "num_cpus", +] + +[[package]] +name = "redox_syscall" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "reedline" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2fde955d11817fdcb79d703932fb6b473192cb36b6a92ba21f7f4ac0513374e" +dependencies = [ + "chrono", + "crossterm", + "fd-lock", + "itertools", + "nu-ansi-term", + "serde", + "strip-ansi-escapes", + "strum 0.25.0", + "strum_macros 0.25.1", + "thiserror", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "regex" +version = "1.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0ab3ca65655bb1e41f2a8c8cd662eb4fb035e67c3f78da1d61dffe89d07300f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436b050e76ed2903236f032a59761c1eb99e1b0aead2c257922771dab1fc8c78" + +[[package]] +name = "reqwest" +version = "0.11.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cde824a14b7c14f85caff81225f411faacc04a2013f41670f41443742b1c1c55" +dependencies = [ + "base64", + "bytes", + "encoding_rs", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "hyper", + "hyper-tls", + "ipnet", + "js-sys", + "log", + "mime", + "native-tls", + "once_cell", + "percent-encoding", + "pin-project-lite", + "serde", + "serde_json", + "serde_urlencoded", + "tokio", + "tokio-native-tls", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "winreg", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" + +[[package]] +name = "rustix" +version = "0.37.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d69718bf81c6127a49dc64e44a742e8bb9213c0ff8869a22c308f84c1d4ab06" +dependencies = [ + "bitflags 1.3.2", + "errno", + "io-lifetimes", + "libc", + "linux-raw-sys 0.3.8", + "windows-sys 0.48.0", +] + +[[package]] +name = "rustix" +version = "0.38.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac5ffa1efe7548069688cd7028f32591853cd7b5b756d41bcffd2353e4fc75b4" +dependencies = [ + "bitflags 2.3.3", + "errno", + "libc", + "linux-raw-sys 0.4.3", + "windows-sys 0.48.0", +] + +[[package]] +name = "rustversion" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" + +[[package]] +name = "ryu" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c3733bf4cf7ea0880754e19cb5a462007c4a8c1914bff372ccc95b464f1df88" +dependencies = [ + "windows-sys 0.48.0", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "sctk-adwaita" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cda4e97be1fd174ccc2aae81c8b694e803fa99b34e8fd0f057a9d70698e3ed09" +dependencies = [ + "ab_glyph", + "log", + "memmap2", + "smithay-client-toolkit", + "tiny-skia", +] + +[[package]] +name = "security-framework" +version = "2.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05b64fb303737d99b81884b2c63433e9ae28abebe5eb5045dcdd175dc2ecf4de" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e932934257d3b408ed8f30db49d85ea163bfe74961f017f405b025af298f0c7a" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "serde" +version = "1.0.176" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76dc28c9523c5d70816e393136b86d48909cfb27cecaa902d338c19ed47164dc" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.176" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4e7b8c5dc823e3b90651ff1d3808419cd14e5ad76de04feaf37da114e7a306f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.27", +] + +[[package]] +name = "serde_json" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "076066c5f1078eac5b722a31827a8832fe108bed65dfa75e233c89f8206e976c" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_repr" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f0a21fba416426ac927b1691996e82079f8b6156e920c85345f135b2e9ba2de" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.27", +] + +[[package]] +name = "serde_spanned" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96426c9936fd7a0124915f9185ea1d20aa9445cc9821142f0a73bc9207a2e186" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "signal-hook" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" +dependencies = [ + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "238abfbb77c1915110ad968465608b68e869e0772622c9656714e73e5a1a522f" + +[[package]] +name = "slab" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6528351c9bc8ab22353f9d776db39a20288e8d6c37ef8cfe3317cf875eecfc2d" +dependencies = [ + "autocfg", +] + +[[package]] +name = "slotmap" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1e08e261d0e8f5c43123b7adf3e4ca1690d655377ac93a03b2c9d3e98de1342" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" + +[[package]] +name = "smithay-client-toolkit" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f307c47d32d2715eb2e0ece5589057820e0e5e70d07c247d1063e844e107f454" +dependencies = [ + "bitflags 1.3.2", + "calloop", + "dlib", + "lazy_static", + "log", + "memmap2", + "nix 0.24.3", + "pkg-config", + "wayland-client", + "wayland-cursor", + "wayland-protocols", +] + +[[package]] +name = "smithay-clipboard" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a345c870a1fae0b1b779085e81b51e614767c239e93503588e54c5b17f4b0e8" +dependencies = [ + "smithay-client-toolkit", + "wayland-client", +] + +[[package]] +name = "socket2" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64a4a911eed85daf18834cfaa86a79b7d266ff93ff5ba14005426219480ed662" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "str-buf" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e08d8363704e6c71fc928674353e6b7c23dcea9d82d7012c8faf2a3a025f8d0" + +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" + +[[package]] +name = "strip-ansi-escapes" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "011cbb39cf7c1f62871aea3cc46e5817b0937b49e9447370c93cacbe93a766d8" +dependencies = [ + "vte", +] + +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + +[[package]] +name = "strum" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f" + +[[package]] +name = "strum" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" + +[[package]] +name = "strum_macros" +version = "0.24.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e385be0d24f186b4ce2f9982191e7101bb737312ad61c1f2f984f34bcf85d59" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 1.0.109", +] + +[[package]] +name = "strum_macros" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6069ca09d878a33f883cc06aaa9718ede171841d3832450354410b718b097232" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.27", +] + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b60f673f44a8255b9c8c657daf66a596d435f2da81a555b06dc644d080ba45e0" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sys-info" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b3a0d0aba8bf96a0e1ddfdc352fc53b3df7f39318c71854910c3c4b024ae52c" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "sysinfo" +version = "0.29.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "165d6d8539689e3d3bc8b98ac59541e1f21c7de7c85d60dc80e43ae0ed2113db" +dependencies = [ + "cfg-if", + "core-foundation-sys", + "libc", + "ntapi", + "once_cell", + "rayon", + "winapi", +] + +[[package]] +name = "tempfile" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5486094ee78b2e5038a6382ed7645bc084dc2ec433426ca4c3cb61e2007b8998" +dependencies = [ + "cfg-if", + "fastrand 2.0.0", + "redox_syscall", + "rustix 0.38.3", + "windows-sys 0.48.0", +] + +[[package]] +name = "thiserror" +version = "1.0.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.27", +] + +[[package]] +name = "time" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a" +dependencies = [ + "libc", + "wasi 0.10.0+wasi-snapshot-preview1", + "winapi", +] + +[[package]] +name = "tiny-skia" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df8493a203431061e901613751931f047d1971337153f96d0e5e363d6dbf6a67" +dependencies = [ + "arrayref", + "arrayvec 0.7.4", + "bytemuck", + "cfg-if", + "png", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adbfb5d3f3dd57a0e11d12f4f13d4ebbbc1b5c15b7ab0a156d030b21da5f677c" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tinyvec" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "532826ff75199d5833b9d2c5fe410f29235e25704ee5f0ef599fb51c21f4a4da" +dependencies = [ + "autocfg", + "backtrace", + "bytes", + "libc", + "mio", + "num_cpus", + "pin-project-lite", + "socket2", + "windows-sys 0.48.0", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "806fe8c2c87eccc8b3267cbae29ed3ab2d0bd37fca70ab622e46aaa9375ddb7d" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", + "tracing", +] + +[[package]] +name = "toml" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c17e963a819c331dcacd7ab957d80bc2b9a9c1e71c804826d2f283dd65306542" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.19.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8123f27e969974a3dfba720fdb560be359f57b44302d280ba72e76a74480e8a" +dependencies = [ + "indexmap 2.0.0", + "serde", + "serde_spanned", + "toml_datetime", + "winnow", +] + +[[package]] +name = "tower-service" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" + +[[package]] +name = "tracing" +version = "0.1.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" +dependencies = [ + "cfg-if", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f4f31f56159e98206da9efd823404b79b6ef3143b4a7ab76e67b1751b25a4ab" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.27", +] + +[[package]] +name = "tracing-core" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "trash" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3663fb8f476d674b9c61d1d2796acec725bef6bec4b41402a904252a25971e" +dependencies = [ + "chrono", + "libc", + "log", + "objc", + "once_cell", + "scopeguard", + "url", + "windows 0.44.0", +] + +[[package]] +name = "try-lock" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed" + +[[package]] +name = "ttf-parser" +version = "0.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a464a4b34948a5f67fddd2b823c62d9d92e44be75058b99939eae6c5b6960b33" + +[[package]] +name = "typenum" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" + +[[package]] +name = "uds_windows" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce65604324d3cce9b966701489fbd0cf318cb1f7bd9dd07ac9a4ee6fb791930d" +dependencies = [ + "tempfile", + "winapi", +] + +[[package]] +name = "unicode-bidi" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" + +[[package]] +name = "unicode-ident" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0" + +[[package]] +name = "unicode-normalization" +version = "0.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-segmentation" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" + +[[package]] +name = "unicode-width" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" + +[[package]] +name = "url" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50bff7831e19200a85b17131d085c25d7811bc4e186efdaf54bbd132994a88cb" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", +] + +[[package]] +name = "utf8parse" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "vec_map" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "vte" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cbce692ab4ca2f1f3047fcf732430249c0e971bfdd2b234cf2c47ad93af5983" +dependencies = [ + "arrayvec 0.5.2", + "utf8parse", + "vte_generate_state_changes", +] + +[[package]] +name = "vte_generate_state_changes" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d257817081c7dffcdbab24b9e62d2def62e2ff7d00b1c20062551e6cccc145ff" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "waker-fn" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca" + +[[package]] +name = "walkdir" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36df944cda56c7d8d8b7496af378e6b16de9284591917d307c9b4d313c44e698" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.10.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.27", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.27", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" + +[[package]] +name = "wayland-client" +version = "0.29.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f3b068c05a039c9f755f881dc50f01732214f5685e379829759088967c46715" +dependencies = [ + "bitflags 1.3.2", + "downcast-rs", + "libc", + "nix 0.24.3", + "scoped-tls", + "wayland-commons", + "wayland-scanner", + "wayland-sys 0.29.5", +] + +[[package]] +name = "wayland-commons" +version = "0.29.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8691f134d584a33a6606d9d717b95c4fa20065605f798a3f350d78dced02a902" +dependencies = [ + "nix 0.24.3", + "once_cell", + "smallvec", + "wayland-sys 0.29.5", +] + +[[package]] +name = "wayland-cursor" +version = "0.29.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6865c6b66f13d6257bef1cd40cbfe8ef2f150fb8ebbdb1e8e873455931377661" +dependencies = [ + "nix 0.24.3", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.29.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b950621f9354b322ee817a23474e479b34be96c2e909c14f7bc0100e9a970bc6" +dependencies = [ + "bitflags 1.3.2", + "wayland-client", + "wayland-commons", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.29.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f4303d8fa22ab852f789e75a967f0a2cdc430a607751c0499bada3e451cbd53" +dependencies = [ + "proc-macro2", + "quote", + "xml-rs", +] + +[[package]] +name = "wayland-sys" +version = "0.29.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be12ce1a3c39ec7dba25594b97b42cb3195d54953ddb9d3d95a7c3902bc6e9d4" +dependencies = [ + "dlib", + "lazy_static", + "pkg-config", +] + +[[package]] +name = "wayland-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96b2a02ac608e07132978689a6f9bf4214949c85998c247abadd4f4129b1aa06" +dependencies = [ + "dlib", + "lazy_static", + "log", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webbrowser" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd222aa310eb7532e3fd427a5d7db7e44bc0b0cf1c1e21139c345325511a85b6" +dependencies = [ + "core-foundation", + "home", + "jni", + "log", + "ndk-context", + "objc", + "raw-window-handle", + "url", + "web-sys", +] + +[[package]] +name = "whale" +version = "0.3.0" +dependencies = [ + "chrono", + "clap", + "comfy-table", + "csv", + "eframe", + "egui_extras", + "git2", + "json", + "lazy_static", + "nu-ansi-term", + "rand", + "rayon", + "reedline", + "reqwest", + "serde", + "serde_json", + "sys-info", + "sysinfo", + "toml", + "toml_edit", + "trash", +] + +[[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-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-wsapoll" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c17110f57155602a80dca10be03852116403c9ff3cd25b079d666f2aa3df6e" +dependencies = [ + "winapi", +] + +[[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" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e745dab35a0c4c77aa3ce42d595e13d2003d6902d6b08c9ef5fc326d08da12b" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-targets 0.42.2", +] + +[[package]] +name = "windows" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" +dependencies = [ + "windows-targets 0.48.0", +] + +[[package]] +name = "windows-implement" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce87ca8e3417b02dc2a8a22769306658670ec92d78f1bd420d6310a67c245c6" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "windows-interface" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "853f69a591ecd4f810d29f17e902d40e349fb05b0b11fff63b08b826bfe39c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.0", +] + +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-targets" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5" +dependencies = [ + "windows_aarch64_gnullvm 0.48.0", + "windows_aarch64_msvc 0.48.0", + "windows_i686_gnu 0.48.0", + "windows_i686_msvc 0.48.0", + "windows_x86_64_gnu 0.48.0", + "windows_x86_64_gnullvm 0.48.0", + "windows_x86_64_msvc 0.48.0", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" + +[[package]] +name = "winit" +version = "0.28.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "866db3f712fffba75d31bf0cdecf357c8aeafd158c5b7ab51dba2a2b2d47f196" +dependencies = [ + "android-activity", + "bitflags 1.3.2", + "cfg_aliases", + "core-foundation", + "core-graphics", + "dispatch", + "instant", + "libc", + "log", + "mio", + "ndk", + "objc2", + "once_cell", + "orbclient", + "percent-encoding", + "raw-window-handle", + "redox_syscall", + "sctk-adwaita", + "smithay-client-toolkit", + "wasm-bindgen", + "wayland-client", + "wayland-commons", + "wayland-protocols", + "wayland-scanner", + "web-sys", + "windows-sys 0.45.0", + "x11-dl", +] + +[[package]] +name = "winnow" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25b5872fa2e10bd067ae946f927e726d7d603eaeb6e02fa6a350e0722d2b8c11" +dependencies = [ + "memchr", +] + +[[package]] +name = "winreg" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +dependencies = [ + "winapi", +] + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "592b4883219f345e712b3209c62654ebda0bb50887f330cbd018d0f654bfd507" +dependencies = [ + "gethostname", + "nix 0.24.3", + "winapi", + "winapi-wsapoll", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56b245751c0ac9db0e006dc812031482784e434630205a93c73cfefcaabeac67" +dependencies = [ + "nix 0.24.3", +] + +[[package]] +name = "xcursor" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "463705a63313cd4301184381c5e8042f0a7e9b4bb63653f216311d4ae74690b7" +dependencies = [ + "nom", +] + +[[package]] +name = "xdg-home" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2769203cd13a0c6015d515be729c526d041e9cf2c0cc478d57faee85f40c6dcd" +dependencies = [ + "nix 0.26.2", + "winapi", +] + +[[package]] +name = "xml-rs" +version = "0.8.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52839dc911083a8ef63efa4d039d1f58b5e409f923e44c80828f206f66e5541c" + +[[package]] +name = "zbus" +version = "3.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31de390a2d872e4cd04edd71b425e29853f786dc99317ed72d73d6fcf5ebb948" +dependencies = [ + "async-broadcast", + "async-executor", + "async-fs", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "byteorder", + "derivative", + "enumflags2", + "event-listener", + "futures-core", + "futures-sink", + "futures-util", + "hex", + "nix 0.26.2", + "once_cell", + "ordered-stream", + "rand", + "serde", + "serde_repr", + "sha1", + "static_assertions", + "tracing", + "uds_windows", + "winapi", + "xdg-home", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "3.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d1794a946878c0e807f55a397187c11fc7a038ba5d868e7db4f3bd7760bc9d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "regex", + "syn 1.0.109", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb80bb776dbda6e23d705cf0123c3b95df99c4ebeaec6c2599d4a5419902b4a9" +dependencies = [ + "serde", + "static_assertions", + "zvariant", +] + +[[package]] +name = "zvariant" +version = "3.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44b291bee0d960c53170780af148dca5fa260a63cdd24f1962fa82e03e53338c" +dependencies = [ + "byteorder", + "enumflags2", + "libc", + "serde", + "static_assertions", + "zvariant_derive", +] + +[[package]] +name = "zvariant_derive" +version = "3.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "934d7a7dfc310d6ee06c87ffe88ef4eca7d3e37bb251dece2ef93da8f17d8ecd" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 1.0.109", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7234f0d811589db492d16893e3f21e8e2fd282e6d01b0cddee310322062cc200" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..807e1f7 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "whale" +version = "0.3.0" +description = "Data-oriented programming language and interactive shell." +authors = ["jeff "] +repository = "https://git.jeffa.io/jeff/whale.git" +homepage = "https://git.jeffa.io/jeff/whale" +readme = "README.md" +license = "MIT" +edition = "2018" + +[[bin]] +name = "whale" + +[lib] +name = "whale_lib" +path = "src/lib.rs" + +[dependencies] +rand = "0.8.5" +chrono = "0.4.26" +eframe = "0.22.0" +trash = "3.0.3" +lazy_static = "1.4.0" +rayon = "1.7.0" +serde = { version = "1.0.171", features = ["derive"] } +sys-info = "0.9.1" +sysinfo = "0.29.6" +toml = "0.7.6" +toml_edit = "0.19.14" +comfy-table = "7.0.1" +reedline = "0.22.0" +clap = { version = "4.3.19", features = ["derive"] } +nu-ansi-term = "0.49" +git2 = "0.17.2" +csv = "1.2.2" +json = "0.12.4" +reqwest = { version = "0.11.18", features = ["blocking", "json"] } +serde_json = "1.0.104" +egui_extras = "0.22.0" diff --git a/README.md b/README.md new file mode 100644 index 0000000..693e44b --- /dev/null +++ b/README.md @@ -0,0 +1,286 @@ +# Dust + +Dust is a data-oriented programming language and interactive shell. The command-line interface can also be run as a singular command or it can run a file. Dust is minimal, easy to read and easy to learn by example. Your code will always do exactly what it looks like it's going to do. + +A basic dust program: + +```dust +output "Hello world!" +``` + +Dust can do two things at the same time: + +```dust +async ( + 'output "will this one finish first?"', + 'output "or will this one?"' +) +``` + +Display CSV data as a line plot in a GUI window: + +```dust +read("examples/assets/faithful.csv") + -> from_csv(input) + -> get_rows(input) + -> transform(input, 'input:get(1)') + -> plot(input) +``` + +## Features + +### Data Visualization + +Aside from downloading and processing data, dust is able to display it. Unfortunately the command line is a text interface that struggles to render data in the form of charts and graphs. That's why dust is able to instantly spin up GUI windows with beautifully rendered data. Plots, graphs and charts are available from directly within dust. No external tools are needed. + +[bar_graph_demo.webm](https://github.com/solaeus/whale/assets/112188538/deba6e3c-35d4-47e9-9db9-2045ff2e7c9c) + +### Powerful Tooling + +Built-in tools called **macros** reduce complex tasks to plain, simple code. + +```whale +download "https://api.sampleapis.com/futurama/cast" +``` + +### Pipelines + +Like a pipe in bash, zsh or fish, the yield operator `->` evaluates the expression on the left and passes it as input to the expression on the right. That input is always assigned to the **`input` variable** for that context. These expressions may simply contain a value or they can call a macro or function that returns a value. + +```whale +download "https://api.sampleapis.com/futurama/cast" -> output(input) +``` + +### Format conversion + +Effortlessly convert between whale and formats like JSON, CSV and TOML. + +```whale +download "https://api.sampleapis.com/futurama/cast" + -> from_json(input) + -> to_csv(input) +``` + +### Structured data + +Unlike a traditional command line shell, whale can represent data with more than just strings. Lists, maps and tables are everywhere in whale. When you pull in external data, it is easy to deserialize it into whale. + +```whale +download "https://api.sampleapis.com/futurama/cast" + -> input:from_json() + -> input:get(0) + -> input.name +``` + +### Disk Management + +Whale scripts are clear and easy-to-maintain. You can manage disks with sets of key-value pairs instead of remembering positional arguments. + +``` +new_disk.name = "My Files" +new_disk.filesystem = "btrfs"; +new_disk.path = "/dev/sdb"; +new_disk.label = "gpt"; +new_disk.range = (0, 8000); + +new_disk:partition(); +``` + +### First-Class Functions + +Assign custom functions to variables. Functions can return any value or none at all. Use functions to build structured data or automate tasks. + +```whale +User = ' + this.name = input.0; + this.age = input.1; + this +'; + +user_0 = User("bob", "44"); +user_1 = User("mary", "77"); +``` + +This "fetch" function will download JSON data and parse it. + +``` +fetch = ' + raw_data = download(input); + from_json(raw_data) +'; +``` + +## Usage + +Dust is an experimental project under active development. At this stage, features come and go and the API is always changing. It should not be considered for serious use yet. + +## Installation + +You must have the default rust toolchain installed and up-to-date. Clone the repository and run `cargo run` to start the interactive shell. To see other command line options, use `cargo run -- --help`. + +## The Whale Programming Language + +Dust is a hard fork of [evalexpr]; a simple expression language. Dust's core language features maintain this simplicity. But it can manage large, complex sets of data and perform complicated tasks through macros. It should not take long for a new user to learn the language, especially with the assistance of the shell. + +### Variables and Data Types + +Variables have two parts: a key and a value. The key is always a text string. The value can be any of the following data types: + +- string +- integer +- floating point value +- boolean +- list +- map +- table +- function +- time +- empty + +Here are some examples of variables in dust. + +```whale +x = 1; +y = "hello, it is " + now().time; +z = "42.42"; + +list = (3, 2, x); +big_list = (x, y, z, list) +map.x = "foobar"; +function = 'output "I'm a function"'; +``` + +### Macros + +**Macros** are dust's built-in tools. Some of them can reconfigure your whole system while others are do very little. They may accept different inputs, or none at all. Macros in the `random` group can be run without input, but the `random_integer` macro can optionally take two numbers as in inclusive range. + +```whale +die_roll = random_integer(1, 6); +d20_roll = random_integer(1, 20); +coin_flip = random_boolean(); +``` + +Other macros can be found by pressing TAB in the interactive shell. + +```whale +message = "I hate dust."; +replace(message, "hate", "love"); +``` + +### Lists + +Lists are sequential collections. They can be built by grouping values with parentheses and separating them with commas. Values can be indexed by their position to access their contents. Lists are used to represent rows in tables and most macros take a list as an argument. + +```whale +list = (true, 42, "Ok"); + +assert_eq(get(list, 0), true); +``` + +### Maps + +Maps are flexible collections with arbitrary key-value pairs, similar to JSON objects. Under the hood, all of dust's runtime variables are stored in a map, so, as with variables, the key is always a string. + +```whale +reminder.message = "Buy milk"; +reminder.tags = ("groceries", "home"); + +json = to_json(reminder); +append_to_file(json, "info.txt"); +``` + +### Tables + +Tables are strict collections, each row must have a value for each column. Empty cells must be explicitly set to an empty value. Querying a table is similar to SQL. + +```whale +animals.all = create_table ( + ("name", "species", "age"), + ("rover", "cat", 14), + ("spot", "snake", 9), + ("bob", "giraffe", 2), +); +``` + +The macros `create_table` and `insert` make sure that all of the memory used to hold the rows is allocated at once, so it is good practice to group your rows together instead of using a call for each row. + +```whale +animals.all:insert( + ("eliza", "ostrich", 4), + ("pat", "white rhino", 7), + ("jim", "walrus", 9) +); + +assert_eq(animals:length(), 6); + +animals.by_name = animals:sort_by("name"); +``` + +### The Yield Operator + +Like a pipe in bash, zsh or fish, the yield operator evaluates the expression on the left and passes it as input to the expression on the right. That input is always assigned to the **`input` variable** for that context. These expressions may simply contain a value or they can call a macro or function that returns a value. + +```whale +"Hello dust!" -> output(input) +``` + +This can be useful when working on the command line but to make a script easier to read or to avoid fetching the same resource multiple times, we can also declare variables. You should use `->` and variables together to write short, elegant scripts. + +```whale +json = download("https://api.sampleapis.com/futurama/characters"); +from_json(json) + -> select(input, "name"); + -> get(input, 4) +``` + +### Functions + +Functions are first-class values in dust, so they are assigned to variables like any other value. The function body is wrapped in single parentheses. To call a function, it's just like calling a macro: simply pass it an argument or use an empty set of parentheses to pass an empty value. + +In the function bod, the **`input` variable** represents whatever value is passed to the function when called. + +```whale +say_hi = 'output "hi"'; +add_one = 'input + 1'; + +assert_eq(add_one(3), 4); +say_hi(); +``` + +This function simply passes the input to the shell's standard output. + +```whale +print = 'output(input)'; +``` + +Because functions are stored in variables, we can use collections like maps to +organize them. + +```whale +math.add = 'input.0 + input.1'; +math.subtract = 'input.0 - input.1'; + +assert_eq(math.add(2, 2), 4); +assert_eq(math.subtract(100, 1), 99); +``` + +### Time + +Whale can record, parse and convert time values. Whale can parse TOML datetime +values or can create time values using macros. + +```whale +dob = from_toml("1979-05-27T07:32:00-08:00") + +output "Date of birth = " + local(dob); +``` + +```whale +time = now(); + +output "Universal time is " + time:utc(); +output "Local time is " + time:local(); +``` + +[dnf]: https://dnf.readthedocs.io/en/latest/index.html +[evalexpr]: https://github.com/ISibboI/evalexpr diff --git a/examples/cpu_monitor.whale b/examples/cpu_monitor.whale new file mode 100644 index 0000000..475ec22 --- /dev/null +++ b/examples/cpu_monitor.whale @@ -0,0 +1,9 @@ +loop(' + speed = cpu_speed(); + message = "Current CPU clock: " + string(speed); + + output(message); + wait 300; +'); + + diff --git a/examples/fetch.whale b/examples/fetch.whale new file mode 100644 index 0000000..ad19c67 --- /dev/null +++ b/examples/fetch.whale @@ -0,0 +1,4 @@ +raw_data = download "https://api.sampleapis.com/futurama/cast"; +data = raw_data:from_json(); +first = data:get 0; +first.name diff --git a/examples/hello_world.whale b/examples/hello_world.whale new file mode 100644 index 0000000..83743f0 --- /dev/null +++ b/examples/hello_world.whale @@ -0,0 +1 @@ +output "Hello world!" diff --git a/examples/map.whale b/examples/map.whale new file mode 100644 index 0000000..c2c89a1 --- /dev/null +++ b/examples/map.whale @@ -0,0 +1,7 @@ +x = 1; +y = 2; +z = 3; +a = "foo"; +b = "bar"; +c = "foobar"; +d = ("abc", "123", "xyz"); diff --git a/examples/random_user_data.whale b/examples/random_user_data.whale new file mode 100644 index 0000000..b028177 --- /dev/null +++ b/examples/random_user_data.whale @@ -0,0 +1,14 @@ +create_user = ' + names = ("bob", "bill", "mary", "susan"); + (random_integer(), names:random(), random_integer(0, 100)) +'; + +create_table( + ("id", "name", "age"), + ( + repeat ( + create_user, + 10 + ) + ) +) \ No newline at end of file diff --git a/examples/table.whale b/examples/table.whale new file mode 100644 index 0000000..25c3b5c --- /dev/null +++ b/examples/table.whale @@ -0,0 +1,29 @@ +table = create_table ( + ("text", "number", "bool"), + ( + ("a", 1, true), + ("b", 2, true), + ("a", 3, true) + ) +); + +test_table = create_table ( + ("text", "bool"), + ( + ("a", true), + ("b", true), + ("a", true) + ) +); + +assert_equal(table:select("text", "bool"), test_table); + +test_table = create_table ( + ("text", "number", "bool"), + ( + ("a", 1, true), + ("a", 3, true) + ) +); + +assert_equal(table:where('text == "a"'), test_table); diff --git a/examples/toolbox.whale b/examples/toolbox.whale new file mode 100644 index 0000000..660fe86 --- /dev/null +++ b/examples/toolbox.whale @@ -0,0 +1,21 @@ +enable_copr_repositories = ("varlad/helix"); +enable_rpm_repositories ( + "https://mirrors.rpmfusion.org/free/fedora/rpmfusion-free-release-38.noarch.rpm", + "https://mirrors.rpmfusion.org/free/fedora/rpmfusion-nonfree-release-38.noarch.rpm" +); +install_package ( + "bat", + "egl-wayland", + "fd-find", + "fish", + "fzf", + "lsd", + "kitty", + "helix", + "libwayland-cursor", + "libwayland-egl", + "wl-clipboard" +); + +sh "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh"; +sh "cargo install starship zoxide"; \ No newline at end of file diff --git a/examples/wait.whale b/examples/wait.whale new file mode 100644 index 0000000..2aaec87 --- /dev/null +++ b/examples/wait.whale @@ -0,0 +1,3 @@ +output "foo..."; +wait 1; +output "bar!"; \ No newline at end of file diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..af7e115 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,615 @@ +//! Error and Result types. +//! +//! To deal with errors from dependencies, either create a new error variant +//! or use the MacroFailure variant if the error can only occur inside a macro. +use crate::{ + operator::Operator, token::PartialToken, value::value_type::ValueType, value::Value, MacroInfo, + Node, +}; + +use std::{fmt, io, time::SystemTimeError}; + +pub type Result = std::result::Result; + +#[derive(Debug, Clone, PartialEq)] +#[non_exhaustive] +pub enum Error { + /// A row was inserted to a table with the wrong amount of values. + WrongColumnAmount { + expected: usize, + actual: usize, + }, + + /// An operator was called with the wrong amount of arguments. + ExpectedOperatorArgumentAmount { + expected: usize, + actual: usize, + }, + + /// A function was called with the wrong amount of arguments. + ExpectedFunctionArgumentAmount { + identifier: String, + expected: usize, + actual: usize, + }, + + /// A function was called with the wrong amount of arguments. + ExpectedAtLeastFunctionArgumentAmount { + identifier: String, + minimum: usize, + actual: usize, + }, + + ExpectedString { + actual: Value, + }, + + ExpectedInt { + actual: Value, + }, + + ExpectedFloat { + actual: Value, + }, + + /// An integer, floating point or value was expected. + ExpectedNumber { + actual: Value, + }, + + /// An integer, floating point or string value was expected. + ExpectedNumberOrString { + actual: Value, + }, + + ExpectedBoolean { + actual: Value, + }, + + ExpectedList { + actual: Value, + }, + + ExpectedFixedLenList { + expected_len: usize, + actual: Value, + }, + + ExpectedEmpty { + actual: Value, + }, + + ExpectedMap { + actual: Value, + }, + + ExpectedTable { + actual: Value, + }, + + ExpectedFunction { + actual: Value, + }, + + /// A string, list, map or table value was expected. + ExpectedCollection { + actual: Value, + }, + + /// Tried to append a child to a leaf node. + /// Leaf nodes cannot have children. + AppendedToLeafNode(Node), + + /// Tried to append a child to a node such that the precedence of the child + /// is not higher. This error should never occur. If it does, please file a + /// bug report. + PrecedenceViolation, + + /// A `VariableIdentifier` operation did not find its value in the context. + VariableIdentifierNotFound(String), + + /// A `FunctionIdentifier` operation did not find its value in the context. + FunctionIdentifierNotFound(String), + + /// A value has the wrong type. + /// Only use this if there is no other error that describes the expected and + /// provided types in more detail. + TypeError { + /// The expected types. + expected: &'static [ValueType], + /// The actual value. + actual: Value, + }, + + /// A macro or function was called with the wrong type of input. + MacroArgumentType { + /// The macro that was called. + macro_info: MacroInfo<'static>, + /// The actual value. + actual: Value, + }, + + /// An operator is used with a wrong combination of types. + WrongTypeCombination { + /// The operator that whose evaluation caused the error. + operator: Operator, + /// The types that were used in the operator causing it to fail. + actual: Vec, + }, + + /// An opening brace without a matching closing brace was found. + UnmatchedLBrace, + + /// A closing brace without a matching opening brace was found. + UnmatchedRBrace, + + /// Left of an opening brace or right of a closing brace is a token that does not expect the brace next to it. + /// For example, writing `4(5)` would yield this error, as the `4` does not have any operands. + MissingOperatorOutsideOfBrace, + + /// A `PartialToken` is unmatched, such that it cannot be combined into a full `Token`. + /// This happens if for example a single `=` is found, surrounded by whitespace. + /// It is not a token, but it is part of the string representation of some tokens. + UnmatchedPartialToken { + /// The unmatched partial token. + first: PartialToken, + /// The token that follows the unmatched partial token and that cannot be matched to the partial token, or `None`, if `first` is the last partial token in the stream. + second: Option, + }, + + /// An addition operation performed by Rust failed. + AdditionError { + /// The first argument of the addition. + augend: Value, + /// The second argument of the addition. + addend: Value, + }, + + /// A subtraction operation performed by Rust failed. + SubtractionError { + /// The first argument of the subtraction. + minuend: Value, + /// The second argument of the subtraction. + subtrahend: Value, + }, + + /// A negation operation performed by Rust failed. + NegationError { + /// The argument of the negation. + argument: Value, + }, + + /// A multiplication operation performed by Rust failed. + MultiplicationError { + /// The first argument of the multiplication. + multiplicand: Value, + /// The second argument of the multiplication. + multiplier: Value, + }, + + /// A division operation performed by Rust failed. + DivisionError { + /// The first argument of the division. + dividend: Value, + /// The second argument of the division. + divisor: Value, + }, + + /// A modulation operation performed by Rust failed. + ModulationError { + /// The first argument of the modulation. + dividend: Value, + /// The second argument of the modulation. + divisor: Value, + }, + + /// A regular expression could not be parsed + InvalidRegex { + /// The invalid regular expression + regex: String, + /// Failure message from the regex engine + message: String, + }, + + /// A modification was attempted on a `Context` that does not allow modifications. + ContextNotMutable, + + /// An escape sequence within a string literal is illegal. + IllegalEscapeSequence(String), + + /// This context does not allow enabling builtin functions. + BuiltinFunctionsCannotBeEnabled, + + /// This context does not allow disabling builtin functions. + BuiltinFunctionsCannotBeDisabled, + + /// The function failed due to an external error. + MacroFailure(String), + + /// A custom error explained by its message. + CustomMessage(String), +} + +impl From for Error { + fn from(value: csv::Error) -> Self { + Error::MacroFailure(value.to_string()) + } +} + +impl From for Error { + fn from(value: json::Error) -> Self { + Error::MacroFailure(value.to_string()) + } +} + +impl From for Error { + fn from(value: std::io::Error) -> Self { + Error::MacroFailure(value.to_string()) + } +} + +impl From for Error { + fn from(value: git2::Error) -> Self { + Error::MacroFailure(value.to_string()) + } +} + +impl From for Error { + fn from(value: reqwest::Error) -> Self { + Error::MacroFailure(value.to_string()) + } +} + +impl From for Error { + fn from(value: serde_json::Error) -> Self { + Error::MacroFailure(value.to_string()) + } +} + +impl From for Error { + fn from(value: sys_info::Error) -> Self { + Error::MacroFailure(value.to_string()) + } +} + +impl From for Error { + fn from(value: SystemTimeError) -> Self { + Error::MacroFailure(value.to_string()) + } +} + +impl From for Error { + fn from(value: trash::Error) -> Self { + Error::MacroFailure(value.to_string()) + } +} + +impl Error { + pub(crate) fn expect_operator_argument_amount(actual: usize, expected: usize) -> Result<()> { + if actual == expected { + Ok(()) + } else { + Err(Error::ExpectedOperatorArgumentAmount { expected, actual }) + } + } + + pub(crate) fn expect_function_argument_amount( + identifier: &str, + actual: usize, + expected: usize, + ) -> Result<()> { + if actual == expected { + Ok(()) + } else { + Err(Error::ExpectedFunctionArgumentAmount { + identifier: identifier.to_string(), + expected, + actual, + }) + } + } + + pub(crate) fn expected_minimum_function_argument_amount( + identifier: &str, + actual: usize, + minimum: usize, + ) -> Result<()> { + if actual >= minimum { + Ok(()) + } else { + Err(Error::ExpectedAtLeastFunctionArgumentAmount { + identifier: identifier.to_string(), + minimum, + actual, + }) + } + } + + pub fn type_error(actual: Value, expected: &'static [ValueType]) -> Self { + Error::TypeError { actual, expected } + } + + pub fn wrong_type_combination(operator: Operator, actual: Vec) -> Self { + Error::WrongTypeCombination { operator, actual } + } + + pub fn expected_string(actual: Value) -> Self { + Error::ExpectedString { actual } + } + + pub fn expected_int(actual: Value) -> Self { + Error::ExpectedInt { actual } + } + + pub fn expected_float(actual: Value) -> Self { + Error::ExpectedFloat { actual } + } + + pub fn expected_number(actual: Value) -> Self { + Error::ExpectedNumber { actual } + } + + pub fn expected_number_or_string(actual: Value) -> Self { + Error::ExpectedNumberOrString { actual } + } + + pub fn expected_boolean(actual: Value) -> Self { + Error::ExpectedBoolean { actual } + } + + pub fn expected_list(actual: Value) -> Self { + Error::ExpectedList { actual } + } + + pub fn expected_fixed_len_list(expected_len: usize, actual: Value) -> Self { + Error::ExpectedFixedLenList { + expected_len, + actual, + } + } + + pub fn expected_empty(actual: Value) -> Self { + Error::ExpectedEmpty { actual } + } + + pub fn expected_map(actual: Value) -> Self { + Error::ExpectedMap { actual } + } + + pub fn expected_table(actual: Value) -> Self { + Error::ExpectedTable { actual } + } + + pub fn expected_function(actual: Value) -> Self { + Error::ExpectedFunction { actual } + } + + pub fn expected_collection(actual: Value) -> Self { + Error::ExpectedCollection { actual } + } + + pub(crate) fn unmatched_partial_token( + first: PartialToken, + second: Option, + ) -> Self { + Error::UnmatchedPartialToken { first, second } + } + + pub(crate) fn addition_error(augend: Value, addend: Value) -> Self { + Error::AdditionError { augend, addend } + } + + pub(crate) fn subtraction_error(minuend: Value, subtrahend: Value) -> Self { + Error::SubtractionError { + minuend, + subtrahend, + } + } + + pub(crate) fn negation_error(argument: Value) -> Self { + Error::NegationError { argument } + } + + pub(crate) fn multiplication_error(multiplicand: Value, multiplier: Value) -> Self { + Error::MultiplicationError { + multiplicand, + multiplier, + } + } + + pub(crate) fn division_error(dividend: Value, divisor: Value) -> Self { + Error::DivisionError { dividend, divisor } + } + + pub(crate) fn modulation_error(dividend: Value, divisor: Value) -> Self { + Error::ModulationError { dividend, divisor } + } + + /// Constructs `EvalexprError::InvalidRegex(regex)` + pub fn invalid_regex(regex: String, message: String) -> Self { + Error::InvalidRegex { regex, message } + } +} + +/// Returns `Ok(())` if the given value is a string or a numeric. +pub fn expect_number_or_string(actual: &Value) -> Result<()> { + match actual { + Value::String(_) | Value::Float(_) | Value::Integer(_) => Ok(()), + _ => Err(Error::expected_number_or_string(actual.clone())), + } +} + +/// Returns `Ok(())` if the given value is a String, List, Map or Table. +pub fn _expect_collection(actual: &Value) -> Result<()> { + match actual { + Value::String(_) | Value::List(_) | Value::Map(_) | Value::Table(_) => Ok(()), + _ => Err(Error::expected_collection(actual.clone())), + } +} + +impl std::error::Error for Error {} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use Error::*; + + match self { + ExpectedOperatorArgumentAmount { expected, actual } => write!( + f, + "An operator expected {} arguments, but got {}.", + expected, actual + ), + ExpectedFunctionArgumentAmount { + expected, + actual, + identifier, + } => write!( + f, + "{identifier} expected {expected} arguments, but got {actual}.", + ), + ExpectedAtLeastFunctionArgumentAmount { + minimum, + actual, + identifier, + } => write!( + f, + "{identifier} expected a minimum of {minimum} arguments, but got {actual}.", + ), + ExpectedString { actual } => { + write!(f, "Expected a Value::String, but got {:?}.", actual) + } + ExpectedInt { actual } => write!(f, "Expected a Value::Int, but got {:?}.", actual), + ExpectedFloat { actual } => write!(f, "Expected a Value::Float, but got {:?}.", actual), + ExpectedNumber { actual } => write!( + f, + "Expected a Value::Float or Value::Int, but got {:?}.", + actual + ), + ExpectedNumberOrString { actual } => write!( + f, + "Expected a Value::Number or a Value::String, but got {:?}.", + actual + ), + ExpectedBoolean { actual } => { + write!(f, "Expected a Value::Boolean, but got {:?}.", actual) + } + ExpectedList { actual } => write!(f, "Expected a Value::Tuple, but got {:?}.", actual), + ExpectedFixedLenList { + expected_len, + actual, + } => write!( + f, + "Expected a Value::Tuple of len {}, but got {:?}.", + expected_len, actual + ), + ExpectedEmpty { actual } => write!(f, "Expected a Value::Empty, but got {:?}.", actual), + ExpectedMap { actual } => write!(f, "Expected a Value::Map, but got {:?}.", actual), + ExpectedTable { actual } => write!(f, "Expected a Value::Table, but got {:?}.", actual), + ExpectedFunction { actual } => { + write!(f, "Expected Value::Function, but got {:?}.", actual) + } + ExpectedCollection { actual } => { + write!( + f, + "Expected a string, list, map or table, but got {:?}.", + actual + ) + } + AppendedToLeafNode(node) => write!(f, "Syntax error at \"{node}\"."), + PrecedenceViolation => write!( + f, + "Tried to append a node to another node with higher precedence." + ), + VariableIdentifierNotFound(identifier) => write!( + f, + "Variable identifier is not bound to anything by context: {:?}.", + identifier + ), + FunctionIdentifierNotFound(identifier) => write!( + f, + "Function identifier is not bound to anything by context: {:?}.", + identifier + ), + TypeError { expected, actual } => { + write!( + f, + "Type Error. The value {actual} is not one of the following: {expected:?}.", + ) + } + WrongTypeCombination { operator, actual } => write!( + f, + "The operator {:?} was called with a wrong combination of types: {:?}", + operator, actual + ), + UnmatchedLBrace => write!(f, "Found an unmatched opening parenthesis '('."), + UnmatchedRBrace => write!(f, "Found an unmatched closing parenthesis ')'."), + MissingOperatorOutsideOfBrace { .. } => write!( + f, + "Found an opening parenthesis that is preceded by something that does not take \ + any arguments on the right, or found a closing parenthesis that is succeeded by \ + something that does not take any arguments on the left." + ), + UnmatchedPartialToken { first, second } => { + if let Some(second) = second { + write!( + f, + "Found a partial token '{}' that should not be followed by '{}'.", + first, second + ) + } else { + write!( + f, + "Found a partial token '{}' that should be followed by another partial \ + token.", + first + ) + } + } + AdditionError { augend, addend } => write!(f, "Error adding {} + {}", augend, addend), + SubtractionError { + minuend, + subtrahend, + } => write!(f, "Error subtracting {} - {}", minuend, subtrahend), + NegationError { argument } => write!(f, "Error negating -{}", argument), + MultiplicationError { + multiplicand, + multiplier, + } => write!(f, "Error multiplying {} * {}", multiplicand, multiplier), + DivisionError { dividend, divisor } => { + write!(f, "Error dividing {} / {}", dividend, divisor) + } + ModulationError { dividend, divisor } => { + write!(f, "Error modulating {} % {}", dividend, divisor) + } + InvalidRegex { regex, message } => write!( + f, + "Regular expression {:?} is invalid: {:?}", + regex, message + ), + ContextNotMutable => write!(f, "Cannot manipulate context"), + BuiltinFunctionsCannotBeEnabled => { + write!(f, "This context does not allow enabling builtin functions") + } + BuiltinFunctionsCannotBeDisabled => { + write!(f, "This context does not allow disabling builtin functions") + } + IllegalEscapeSequence(string) => write!(f, "Illegal escape sequence: {}", string), + MacroFailure(message) => write!(f, "Function failure: {}", message), + CustomMessage(message) => write!(f, "Error: {}", message), + WrongColumnAmount { expected, actual } => write!( + f, + "Wrong number of columns for this table. Expected {expected}, found {actual}." + ), + MacroArgumentType { + macro_info, + actual, + } => write!( + f, + "Wrong argument of type {:?} was passed to {}. Expected one of the following types: {:?}.", + actual.value_type(), + macro_info.identifier, + macro_info.inputs + ), + } + } +} diff --git a/src/interface.rs b/src/interface.rs new file mode 100644 index 0000000..122c397 --- /dev/null +++ b/src/interface.rs @@ -0,0 +1,58 @@ +use crate::{token, tree, Result, Value, VariableMap}; + +/// Evaluate the given expression string. +/// +/// # Examples +/// +/// ```rust +/// # use whale_lib::*; +/// assert_eq!(eval("1 + 2 + 3"), Ok(Value::from(6))); +/// ``` +/// +/// *See the [crate doc](index.html) for more examples and explanations of the expression format.* +pub fn eval(string: &str) -> Result { + let mut context = VariableMap::new(); + let eval = eval_with_context(string, &mut context); + + match eval { + Ok(output) => { + if output.is_empty() { + Ok(Value::Map(context)) + } else { + Ok(output) + } + } + Err(error) => Err(error), + } +} + +/// Evaluate the given expression string with the given context. +/// +/// # Examples +/// +/// ```rust +/// # use whale_lib::*; +/// let mut context = VariableMap::new(); +/// context.set_value("one".into(), 1.into()).unwrap(); // Do proper error handling here +/// context.set_value("two".into(), 2.into()).unwrap(); // Do proper error handling here +/// context.set_value("three".into(), 3.into()).unwrap(); // Do proper error handling here +/// assert_eq!(eval_with_context("one + two + three", &context), Ok(Value::from(6))); +/// ``` +/// +/// *See the [crate doc](index.html) for more examples and explanations of the expression format.* +pub fn eval_with_context(string: &str, context: &mut VariableMap) -> Result { + let split = string.split_once("::"); + + if let Some((left, right)) = split { + let left_result = tree::tokens_to_operator_tree(token::tokenize(left)?)? + .eval_with_context_mut(context)?; + + context.set_value("input", left_result)?; + + let right_result = eval_with_context(right, context)?; + + Ok(right_result) + } else { + tree::tokens_to_operator_tree(token::tokenize(string)?)?.eval_with_context_mut(context) + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..ccb5bd3 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,23 @@ +#![doc = include_str!("../README.md")] +#![forbid(unsafe_code)] + +pub use crate::{ + error::*, + interface::*, + macros::*, + operator::Operator, + token::PartialToken, + tree::Node, + value::{ + function::Function, table::Table, time::Time, value_type::ValueType, + variable_map::VariableMap, Value, + }, +}; + +mod error; +mod interface; +mod macros; +mod operator; +mod token; +mod tree; +mod value; diff --git a/src/macros/collections.rs b/src/macros/collections.rs new file mode 100644 index 0000000..9c36888 --- /dev/null +++ b/src/macros/collections.rs @@ -0,0 +1,561 @@ +//! Macros for collection values: strings, lists, maps and tables. + +use crate::{Error, Macro, MacroInfo, Result, Table, Value, VariableMap}; + +pub struct Transform; + +impl Macro for Transform { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "transform", + description: "Change each value with a function.", + group: "collections", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_list()?; + let value = &argument[0]; + let function = argument[1].as_function()?; + + match value { + Value::String(_string) => todo!(), + Value::Float(_) => todo!(), + Value::Integer(_) => todo!(), + Value::Boolean(_) => todo!(), + Value::List(list) => { + let mut mapped_list = Vec::with_capacity(list.len()); + + for value in list { + let mut context = VariableMap::new(); + + context.set_value("input", value.clone())?; + + let mapped_value = function.run_with_context(&mut context)?; + + mapped_list.push(mapped_value); + } + + Ok(Value::List(mapped_list)) + } + Value::Empty => todo!(), + Value::Map(_map) => todo!(), + Value::Table(_) => todo!(), + Value::Function(_) => todo!(), + Value::Time(_) => todo!(), + } + } +} + +pub struct String; + +impl Macro for String { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "string", + description: "Stringify a value.", + group: "collections", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let string = match argument.clone() { + Value::String(string) => string, + Value::List(_list) => todo!(), + Value::Map(_map) => todo!(), + Value::Table(_table) => todo!(), + Value::Function(function) => function.to_string(), + Value::Float(float) => float.to_string(), + Value::Integer(integer) => integer.to_string(), + Value::Boolean(boolean) => boolean.to_string(), + Value::Time(_) => todo!(), + Value::Empty => todo!(), + }; + + Ok(Value::String(string)) + } +} + +pub struct Count; + +impl Macro for Count { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "count", + description: "Return the number of items in a value.", + group: "collections", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let len = match argument { + Value::String(string) => string.len(), + Value::List(list) => list.len(), + Value::Map(map) => map.len(), + Value::Table(table) => table.len(), + Value::Function(_) + | Value::Float(_) + | Value::Integer(_) + | Value::Boolean(_) + | Value::Time(_) => 1, + Value::Empty => 0, + }; + + Ok(Value::Integer(len as i64)) + } +} + +pub struct CreateTable; + +impl Macro for CreateTable { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "create_table", + description: "Define a new table with a list of column names and list of rows.", + group: "collections", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_list()?; + + let column_name_inputs = argument[0].as_list()?; + let mut column_names = Vec::with_capacity(column_name_inputs.len()); + + for name in column_name_inputs { + column_names.push(name.as_string()?.clone()); + } + + let column_count = column_names.len(); + let rows = argument[1].as_list()?; + let mut table = Table::new(column_names); + + for row in rows { + let row = row.as_fixed_len_list(column_count)?; + + table.insert(row.clone()).unwrap(); + } + + Ok(Value::Table(table)) + } +} + +pub struct Rows; + +impl Macro for Rows { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "rows", + description: "Extract a table's rows as a list.", + group: "collections", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let table = argument.as_table()?; + + let rows = table + .rows() + .iter() + .map(|row| Value::List(row.clone())) + .collect(); + + Ok(Value::List(rows)) + } +} + +pub struct Get; + +impl Macro for Get { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "get", + description: "Retrieve a value from a collection.", + group: "collections", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_list()?; + + let collection = &argument[0]; + let index = argument[1].as_int()?; + + if let Ok(list) = collection.as_list() { + if let Some(value) = list.get(index as usize) { + return Ok(value.clone()); + } else { + return Ok(Value::Empty); + } + } + + todo!() + } +} + +pub struct Insert; + +impl Macro for Insert { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "insert", + description: "Add new rows to a table.", + group: "collections", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_list()?; + let new_rows = &argument[1..]; + let mut table = argument[0].as_table()?.clone(); + + table.reserve(new_rows.len()); + + for row in new_rows { + let row = row.as_list()?.clone(); + + table.insert(row)?; + } + + Ok(Value::Table(table)) + } +} + +pub struct Select; + +impl Macro for Select { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "select", + description: "Extract one or more values based on their key.", + group: "collections", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let arguments = argument.as_fixed_len_list(2)?; + let collection = &arguments[0]; + + if let Value::List(list) = collection { + let mut selected = Vec::new(); + + let index = arguments[1].as_int()?; + let value = list.get(index as usize); + + if let Some(value) = value { + selected.push(value.clone()); + return Ok(Value::List(selected)); + } else { + return Ok(Value::List(selected)); + } + } + + let mut column_names = Vec::new(); + + if let Value::List(columns) = &arguments[1] { + for column in columns { + let name = column.as_string()?; + + column_names.push(name.clone()); + } + } else if let Value::String(column) = &arguments[1] { + column_names.push(column.clone()); + } else { + todo!() + }; + + if let Value::Map(map) = collection { + let mut selected = VariableMap::new(); + + for (key, value) in map.inner() { + if column_names.contains(key) { + selected.set_value(key, value.clone())?; + } + } + + return Ok(Value::Map(selected)); + } + + if let Value::Table(table) = collection { + let selected = table.select(&column_names); + + return Ok(Value::Table(selected)); + } + + todo!() + } +} + +pub struct ForEach; + +impl Macro for ForEach { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "for_each", + description: "Run an operation on every item in a collection.", + group: "collections", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_list()?; + + Error::expected_minimum_function_argument_amount( + self.info().identifier, + 2, + argument.len(), + )?; + + let table = argument[0].as_table()?; + let columns = argument[1].as_list()?; + let mut column_names = Vec::new(); + + for column in columns { + let name = column.as_string()?; + + column_names.push(name.clone()); + } + + let selected = table.select(&column_names); + + Ok(Value::Table(selected)) + } +} + +pub struct Where; + +impl Macro for Where { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "where", + description: "Keep rows matching a predicate.", + group: "collections", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument_list = argument.as_list()?; + Error::expect_function_argument_amount(self.info().identifier, argument_list.len(), 2)?; + + let collection = &argument_list[0]; + let function = argument_list[1].as_function()?; + + if let Ok(list) = collection.as_list() { + let mut context = VariableMap::new(); + let mut new_list = Vec::new(); + + for value in list { + context.set_value("input", value.clone())?; + let keep_row = function.run_with_context(&mut context)?.as_boolean()?; + + if keep_row { + new_list.push(value.clone()); + } + } + + return Ok(Value::List(new_list)); + } + + if let Ok(map) = collection.as_map() { + let mut context = VariableMap::new(); + let mut new_map = VariableMap::new(); + + for (key, value) in map.inner() { + if let Ok(map) = value.as_map() { + for (key, value) in map.inner() { + context.set_value(key, value.clone())?; + } + } else { + context.set_value("input", value.clone())?; + } + + let keep_row = function.run_with_context(&mut context)?.as_boolean()?; + + if keep_row { + new_map.set_value(key, value.clone())?; + } + } + + return Ok(Value::Map(new_map)); + } + + if let Ok(table) = collection.as_table() { + let mut context = VariableMap::new(); + let mut new_table = Table::new(table.column_names().clone()); + + for row in table.rows() { + for (column_index, cell) in row.iter().enumerate() { + let column_name = table.column_names().get(column_index).unwrap(); + + context.set_value(column_name, cell.clone())?; + } + let keep_row = function.run_with_context(&mut context)?.as_boolean()?; + + if keep_row { + new_table.insert(row.clone())?; + } + } + + return Ok(Value::Table(new_table)); + } + + todo!() + } +} + +#[cfg(test)] +mod tests { + use crate::Function; + + use super::*; + + #[test] + fn where_from_non_collections() { + Where + .run(&Value::List(vec![ + Value::Integer(1), + Value::Function(Function::new("input == 1")), + ])) + .unwrap_err(); + Where + .run(&Value::List(vec![ + Value::Float(1.0), + Value::Function(Function::new("input == 1.0")), + ])) + .unwrap_err(); + Where + .run(&Value::List(vec![ + Value::Boolean(true), + Value::Function(Function::new("input == true")), + ])) + .unwrap_err(); + } + + #[test] + fn where_from_list() { + let arguments = Value::List(vec![ + Value::List(vec![Value::Integer(1), Value::Integer(2)]), + Value::Function(Function::new("input == 1")), + ]); + let select = Where.run(&arguments).unwrap(); + + assert_eq!(Value::List(vec![Value::Integer(1)]), select); + } + + #[test] + fn where_from_map() { + let mut map = VariableMap::new(); + + map.set_value("foo", Value::Integer(1)).unwrap(); + map.set_value("bar", Value::Integer(2)).unwrap(); + + let arguments = Value::List(vec![ + Value::Map(map), + Value::Function(Function::new("input == 1")), + ]); + let select = Where.run(&arguments).unwrap(); + + let mut map = VariableMap::new(); + + map.set_value("foo", Value::Integer(1)).unwrap(); + + assert_eq!(Value::Map(map), select); + } + + #[test] + fn where_from_table() { + let mut table = Table::new(vec!["foo".to_string(), "bar".to_string()]); + + table + .insert(vec![Value::Integer(1), Value::Integer(2)]) + .unwrap(); + table + .insert(vec![Value::Integer(3), Value::Integer(4)]) + .unwrap(); + + let arguments = Value::List(vec![ + Value::Table(table), + Value::Function(Function::new("foo == 1")), + ]); + let select = Where.run(&arguments).unwrap(); + let mut table = Table::new(vec!["foo".to_string(), "bar".to_string()]); + + table + .insert(vec![Value::Integer(1), Value::Integer(2)]) + .unwrap(); + + assert_eq!(Value::Table(table), select); + } + + #[test] + fn select_from_non_collections() { + Select + .run(&Value::List(vec![Value::Integer(1), Value::Integer(1)])) + .unwrap_err(); + Select + .run(&Value::List(vec![Value::Float(1.0), Value::Float(1.0)])) + .unwrap_err(); + Select + .run(&Value::List(vec![ + Value::Boolean(true), + Value::Boolean(true), + ])) + .unwrap_err(); + } + + #[test] + fn select_from_list() { + let arguments = Value::List(vec![ + Value::List(vec![Value::Integer(1), Value::Integer(2)]), + Value::Integer(0), + ]); + let select = Select.run(&arguments).unwrap(); + + assert_eq!(Value::List(vec![Value::Integer(1)]), select); + } + + #[test] + fn select_from_map() { + let mut map = VariableMap::new(); + + map.set_value("foo", Value::Integer(1)).unwrap(); + map.set_value("bar", Value::Integer(2)).unwrap(); + + let arguments = Value::List(vec![Value::Map(map), Value::String("foo".to_string())]); + let select = Select.run(&arguments).unwrap(); + + let mut map = VariableMap::new(); + + map.set_value("foo", Value::Integer(1)).unwrap(); + + assert_eq!(Value::Map(map), select); + } + + #[test] + fn select_from_table() { + let mut table = Table::new(vec!["foo".to_string(), "bar".to_string()]); + + table + .insert(vec![Value::Integer(1), Value::Integer(2)]) + .unwrap(); + + let arguments = Value::List(vec![Value::Table(table), Value::String("foo".to_string())]); + let select = Select.run(&arguments).unwrap(); + + let mut table = Table::new(vec!["foo".to_string()]); + + table.insert(vec![Value::Integer(1)]).unwrap(); + + assert_eq!(Value::Table(table), select); + } +} diff --git a/src/macros/command.rs b/src/macros/command.rs new file mode 100644 index 0000000..b18f9d3 --- /dev/null +++ b/src/macros/command.rs @@ -0,0 +1,119 @@ +use std::process::Command; + +use crate::{Macro, MacroInfo, Result, Value}; + +pub struct Sh; + +impl Macro for Sh { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "sh", + description: "Pass input to the Bourne Shell.", + group: "command", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_string()?; + + Command::new("sh").arg("-c").arg(argument).spawn()?.wait()?; + + Ok(Value::Empty) + } +} + +pub struct Bash; + +impl Macro for Bash { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "bash", + description: "Pass input to the Bourne Again Shell.", + group: "command", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_string()?; + + Command::new("bash") + .arg("-c") + .arg(argument) + .spawn()? + .wait()?; + + Ok(Value::Empty) + } +} +pub struct Fish; + +impl Macro for Fish { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "fish", + description: "Pass input to the fish shell.", + group: "command", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_string()?; + + Command::new("fish") + .arg("-c") + .arg(argument) + .spawn()? + .wait()?; + + Ok(Value::Empty) + } +} + +pub struct Zsh; + +impl Macro for Zsh { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "zsh", + description: "Pass input to the Z shell.", + group: "command", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_string()?; + + Command::new("zsh") + .arg("-c") + .arg(argument) + .spawn()? + .wait()?; + + Ok(Value::Empty) + } +} + +pub struct Raw; + +impl Macro for Raw { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "raw", + description: "Run input as a command without a shell", + group: "command", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_string()?; + + Command::new(argument).spawn()?.wait()?; + + Ok(Value::Empty) + } +} diff --git a/src/macros/data_formats.rs b/src/macros/data_formats.rs new file mode 100644 index 0000000..afd921b --- /dev/null +++ b/src/macros/data_formats.rs @@ -0,0 +1,151 @@ +//! Convert values to and from data formats like JSON and TOML. + +use crate::{Macro, MacroInfo, Result, Table, Value}; + +pub struct FromJson; + +impl Macro for FromJson { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "from_json", + description: "Get a whale value from a JSON string.", + group: "data", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_string()?; + let value = serde_json::from_str(argument)?; + + Ok(value) + } +} + +pub struct ToJson; + +impl Macro for ToJson { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "to_json", + description: "Create a JSON string from a whale value.", + group: "data", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let json = serde_json::to_string(argument)?; + + Ok(Value::String(json)) + } +} + +pub struct FromCsv; + +impl Macro for FromCsv { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "from_csv", + description: "Create a whale value from a CSV string.", + group: "data", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let csv = argument.as_string()?; + let mut reader = csv::Reader::from_reader(csv.as_bytes()); + + let headers = reader + .headers()? + .iter() + .map(|header| header.trim().trim_matches('"').to_string()) + .collect(); + + let mut table = Table::new(headers); + + for result in reader.records() { + let row = result? + .iter() + .map(|column| { + let column = column.trim().trim_matches('"').trim_matches('\''); + + if let Ok(integer) = column.parse::() { + Value::Integer(integer) + } else if let Ok(float) = column.parse::() { + Value::Float(float) + } else { + Value::String(column.to_string()) + } + }) + .collect(); + + table.insert(row)?; + } + + Ok(Value::Table(table)) + } +} + +pub struct ToCsv; + +impl Macro for ToCsv { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "to_csv", + description: "Convert a value to a string of comma-separated values.", + group: "data", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let mut buffer = Vec::new(); + let mut writer = csv::Writer::from_writer(&mut buffer); + + match argument { + Value::String(string) => { + writer.write_record([string])?; + } + Value::Float(float) => { + writer.write_record(&[float.to_string()])?; + } + Value::Integer(integer) => { + writer.write_record(&[integer.to_string()])?; + } + Value::Boolean(boolean) => { + writer.write_record(&[boolean.to_string()])?; + } + Value::List(list) => { + let string_list = list.iter().map(|value| value.to_string()); + + writer.write_record(string_list)?; + } + Value::Empty => {} + Value::Map(map) => { + writer.write_record(map.inner().keys())?; + writer.write_record(map.inner().values().map(|value| value.to_string()))?; + } + Value::Table(table) => { + writer.write_record(table.column_names())?; + + for row in table.rows() { + let row_string = row.iter().map(|value| value.to_string()); + + writer.write_record(row_string)?; + } + } + Value::Function(_) => todo!(), + Value::Time(time) => { + writer.write_record(&[time.to_string()])?; + } + } + + writer.flush()?; + + Ok(Value::String( + String::from_utf8_lossy(writer.get_ref()).to_string(), + )) + } +} diff --git a/src/macros/disks.rs b/src/macros/disks.rs new file mode 100644 index 0000000..377f6e2 --- /dev/null +++ b/src/macros/disks.rs @@ -0,0 +1,123 @@ +use std::process::Command; + +use sysinfo::{DiskExt, System, SystemExt}; + +use crate::{Macro, MacroInfo, Result, Table, Value}; + +pub struct ListDisks; + +impl Macro for ListDisks { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "list_disks", + description: "List all block devices.", + group: "disks", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + argument.as_empty()?; + + let mut sys = System::new_all(); + sys.refresh_all(); + + let mut disk_table = Table::new(vec![ + "name".to_string(), + "kind".to_string(), + "file system".to_string(), + "mount point".to_string(), + "total space".to_string(), + "available space".to_string(), + "is removable".to_string(), + ]); + + for disk in sys.disks() { + let name = disk.name().to_string_lossy().to_string(); + let kind = disk.kind(); + let file_system = String::from_utf8_lossy(disk.file_system()).to_string(); + let mount_point = disk.mount_point().to_str().unwrap().to_string(); + let total_space = disk.total_space() as i64; + let available_space = disk.available_space() as i64; + let is_removable = disk.is_removable(); + + let row = vec![ + Value::String(name), + Value::String(format!("{kind:?}")), + Value::String(file_system), + Value::String(mount_point), + Value::Integer(total_space), + Value::Integer(available_space), + Value::Boolean(is_removable), + ]; + + disk_table.insert(row)?; + } + + Ok(Value::Table(disk_table)) + } +} + +pub struct Partition; + +impl Macro for Partition { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "partition", + description: "Partition a disk, clearing its content.", + group: "disks", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_map()?; + let path = argument + .get_value("path")? + .unwrap_or(Value::Empty) + .as_string()? + .clone(); + let label = argument + .get_value("label")? + .unwrap_or(Value::Empty) + .as_string()? + .clone(); + let name = argument + .get_value("name")? + .unwrap_or(Value::Empty) + .as_string()? + .clone(); + let filesystem = argument + .get_value("filesystem")? + .unwrap_or(Value::Empty) + .as_string()? + .clone(); + let range = argument + .get_value("range")? + .unwrap_or(Value::Empty) + .as_list()? + .clone(); + + if range.len() != 2 { + return Err(crate::Error::ExpectedFixedLenList { + expected_len: 2, + actual: Value::List(range), + }); + } + + let range_start = range[0].as_string()?; + let range_end = range[1].as_string()?; + + let script = format!( + "sudo parted {path} mklabel {label} mkpart {name} {filesystem} {range_start} {range_end}" + ); + + Command::new("fish") + .arg("-c") + .arg(&script) + .spawn()? + .wait()?; + + Ok(Value::Empty) + } +} diff --git a/src/macros/filesystem.rs b/src/macros/filesystem.rs new file mode 100644 index 0000000..d31284e --- /dev/null +++ b/src/macros/filesystem.rs @@ -0,0 +1,454 @@ +//! Tools for files and directories. + +use std::{ + fs::{self, OpenOptions}, + io::{Read, Write as IoWrite}, + path::PathBuf, +}; + +use crate::{Error, Macro, MacroInfo, Result, Table, Time, Value, ValueType}; + +pub struct Append; + +impl Macro for Append { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "append", + description: "Append data to a file.", + group: "filesystem", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let arguments = argument.as_fixed_len_list(2)?; + let path = arguments[0].as_string()?; + let content = arguments[1].as_string()?; + let mut file = OpenOptions::new().append(true).open(path)?; + + file.write_all(content.as_bytes())?; + + Ok(Value::Empty) + } +} + +pub struct CreateDir; + +impl Macro for CreateDir { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "create_dir", + description: "Create one or more directories.", + group: "filesystem", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let path = argument.as_string()?; + fs::create_dir_all(path)?; + + Ok(Value::Empty) + } +} + +pub struct FileMetadata; + +impl Macro for FileMetadata { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "file_metadata", + description: "Get metadata for files.", + group: "filesystem", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let path_string = argument.as_string()?; + let metadata = PathBuf::from(path_string).metadata()?; + let created = metadata.accessed()?.elapsed()?.as_secs() / 60; + let accessed = metadata.accessed()?.elapsed()?.as_secs() / 60; + let modified = metadata.modified()?.elapsed()?.as_secs() / 60; + let read_only = metadata.permissions().readonly(); + let size = metadata.len(); + + let mut file_table = Table::new(vec![ + "path".to_string(), + "size".to_string(), + "created".to_string(), + "accessed".to_string(), + "modified".to_string(), + "read only".to_string(), + ]); + + file_table.insert(vec![ + Value::String(path_string.clone()), + Value::Integer(size as i64), + Value::Integer(created as i64), + Value::Integer(accessed as i64), + Value::Integer(modified as i64), + Value::Boolean(read_only), + ])?; + + Ok(Value::Table(file_table)) + } +} + +pub struct ReadDir; + +impl Macro for ReadDir { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "read_dir", + description: "Read the content of a directory.", + group: "filesystem", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let path = if let Ok(path) = argument.as_string() { + path + } else if argument.is_empty() { + "." + } else { + return Err(Error::TypeError { + expected: &[ValueType::Empty, ValueType::String], + actual: argument.clone(), + }); + }; + let dir = fs::read_dir(path)?; + let mut file_table = Table::new(vec![ + "path".to_string(), + "size".to_string(), + "created".to_string(), + "accessed".to_string(), + "modified".to_string(), + "read only".to_string(), + ]); + + for entry in dir { + let entry = entry?; + let file_type = entry.file_type()?; + let file_name = if file_type.is_dir() { + let name = entry.file_name().into_string().unwrap_or_default(); + + format!("{name}/") + } else { + entry.file_name().into_string().unwrap_or_default() + }; + let metadata = entry.path().metadata()?; + + let created_timestamp = metadata.accessed()?; + let created = Time::from(created_timestamp); + + let accessed_timestamp = metadata.accessed()?; + let accessed = Time::from(accessed_timestamp); + + let modified_timestamp = metadata.modified()?; + let modified = Time::from(modified_timestamp); + + let read_only = metadata.permissions().readonly(); + let size = metadata.len(); + + file_table.insert(vec![ + Value::String(file_name), + Value::Integer(size as i64), + Value::Time(created), + Value::Time(accessed), + Value::Time(modified), + Value::Boolean(read_only), + ])?; + } + + Ok(Value::Table(file_table)) + } +} + +pub struct ReadFile; + +impl Macro for ReadFile { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "read_file", + description: "Read file contents.", + group: "filesystem", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let path = argument.as_string()?; + let mut contents = String::new(); + + OpenOptions::new() + .read(true) + .create(false) + .open(path)? + .read_to_string(&mut contents)?; + + Ok(Value::String(contents)) + } +} + +pub struct RemoveDir; + +impl Macro for RemoveDir { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "remove_dir", + description: "Remove directories.", + group: "filesystem", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let path = argument.as_string()?; + fs::remove_file(path)?; + + Ok(Value::Empty) + } +} + +pub struct MoveDir; + +impl Macro for MoveDir { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "move_dir", + description: "Move a directory to a new path.", + group: "filesystem", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_list()?; + + Error::expect_function_argument_amount(self.info().identifier, argument.len(), 2)?; + + let current_path = argument[0].as_string()?; + let target_path = argument[1].as_string()?; + let file_list = ReadDir.run(&Value::String(current_path.clone()))?; + + for path in file_list.as_list()? { + let path = PathBuf::from(path.as_string()?); + let new_path = PathBuf::from(&target_path).join(&path); + + if path.is_file() { + fs::copy(&path, target_path)?; + } + + if path.is_symlink() && path.symlink_metadata()?.is_file() { + fs::copy(&path, new_path)?; + } + } + + Ok(Value::Empty) + } +} + +pub struct Trash; + +impl Macro for Trash { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "trash", + description: "Move a file or directory to the trash.", + group: "filesystem", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let path = argument.as_string()?; + + trash::delete(path)?; + + Ok(Value::Empty) + } +} + +pub struct Write; + +impl Macro for Write { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "write", + description: "Write data to a file.", + group: "filesystem", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let strings = argument.as_list()?; + + Error::expect_function_argument_amount(self.info().identifier, strings.len(), 2)?; + + let path = strings.first().unwrap().as_string()?; + let mut file = OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .open(path)?; + + for content in &strings[1..] { + let content = content.to_string(); + + file.write_all(content.as_bytes())?; + } + + Ok(Value::Empty) + } +} + +pub struct RemoveFile; + +impl Macro for RemoveFile { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "write", + description: "Write data to a file.", + group: "filesystem", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let strings = argument.as_list()?; + + Error::expect_function_argument_amount(self.info().identifier, strings.len(), 2)?; + + let _path = strings.first().unwrap().as_string()?; + + todo!(); + } +} + +pub struct Watch; + +impl Macro for Watch { + fn info(&self) -> crate::MacroInfo<'static> { + crate::MacroInfo { + identifier: "watch", + description: "Wait until a file changes.", + group: "filesystem", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_string()?; + let path = PathBuf::from(argument); + let modified_old = path.metadata()?.modified()?; + let wait_time = loop { + let modified_new = path.metadata()?.modified()?; + + if modified_old != modified_new { + break modified_new + .duration_since(modified_old) + .unwrap_or_default() + .as_millis() as i64; + } + }; + + Ok(Value::Integer(wait_time)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn create_dir() { + let path = PathBuf::from("./target/create_dir/"); + let path_value = Value::String(path.to_string_lossy().to_string()); + let _ = std::fs::remove_file(&path); + + CreateDir.run(&path_value).unwrap(); + + assert!(path.is_dir()); + } + + #[test] + fn create_dir_nested() { + let path = PathBuf::from("./target/create_dir/nested"); + let path_value = Value::String(path.to_string_lossy().to_string()); + let _ = std::fs::remove_file(&path); + + CreateDir.run(&path_value).unwrap(); + + assert!(path.is_dir()); + } + + #[test] + fn write() { + let path = PathBuf::from("./target/write.txt"); + let path_value = Value::String(path.to_string_lossy().to_string()); + let message = "hiya".to_string(); + let message_value = Value::String(message.clone()); + let _ = std::fs::remove_file(&path); + + Write + .run(&Value::List(vec![path_value, message_value])) + .unwrap(); + + assert!(path.is_file()); + } + + #[test] + fn append() { + let path = PathBuf::from("./target/append.txt"); + let path_value = Value::String(path.to_string_lossy().to_string()); + let message = "hiya".to_string(); + let message_value = Value::String(message.clone()); + let _ = std::fs::remove_file(&path); + + Write + .run(&Value::List(vec![ + path_value.clone(), + message_value.clone(), + ])) + .unwrap(); + Append + .run(&Value::List(vec![path_value, message_value])) + .unwrap(); + + let read = fs::read_to_string(&path).unwrap(); + + assert_eq!("hiyahiya", read); + } + + #[test] + fn read_file() { + let path = PathBuf::from("./target/read_file.txt"); + let path_value = Value::String(path.to_string_lossy().to_string()); + let message = "hiya".to_string(); + let message_value = Value::String(message.clone()); + let _ = std::fs::remove_file(&path); + + Write + .run(&Value::List(vec![path_value.clone(), message_value])) + .unwrap(); + + let test = ReadFile.run(&path_value).unwrap(); + let read = fs::read_to_string(&path).unwrap(); + + assert_eq!(test, Value::String(read)); + } + + #[test] + fn remove_file() { + let path = PathBuf::from("./target/remove_file.txt"); + let path_value = Value::String(path.to_string_lossy().to_string()); + let _ = std::fs::File::create(&path); + + RemoveFile.run(&path_value).unwrap(); + + assert!(!path.exists()); + } +} diff --git a/src/macros/general.rs b/src/macros/general.rs new file mode 100644 index 0000000..ed026e8 --- /dev/null +++ b/src/macros/general.rs @@ -0,0 +1,126 @@ +use std::{fs, thread::sleep, time::Duration}; + +use rayon::prelude::{IntoParallelRefIterator, ParallelIterator}; + +use crate::{Function, Macro, MacroInfo, Result, Value}; + +pub struct Output; + +impl Macro for Output { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "output", + description: "Print a value.", + group: "general", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + println!("{argument}"); + + Ok(Value::Empty) + } +} +pub struct Repeat; + +impl Macro for Repeat { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "repeat", + description: "Run a function the given number of times.", + group: "general", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_list()?; + let function = argument[0].as_function()?; + let count = argument[1].as_int()?; + let mut result_list = Vec::with_capacity(count as usize); + + for _ in 0..count { + let result = function.run()?; + + result_list.push(result); + } + + Ok(Value::List(result_list)) + } +} + +pub struct Run; + +impl Macro for Run { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "run", + description: "Run a whale file.", + group: "general", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let path = argument.as_string()?; + let file_contents = fs::read_to_string(path)?; + + Function::new(&file_contents).run() + } +} + +pub struct Async; + +impl Macro for Async { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "async", + description: "Run functions in parallel.", + group: "general", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument_list = argument.as_list()?; + let results = argument_list + .par_iter() + .map(|value| { + let function = if let Ok(function) = value.as_function() { + function + } else { + return value.clone(); + }; + + match function.run() { + Ok(value) => value, + Err(error) => Value::String(error.to_string()), + } + }) + .collect(); + + Ok(Value::List(results)) + } +} + +pub struct Wait; + +impl Macro for Wait { + fn info(&self) -> crate::MacroInfo<'static> { + MacroInfo { + identifier: "wait", + description: "Wait for the given number of milliseconds.", + group: "general", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_int()?; + + sleep(Duration::from_millis(argument as u64)); + + Ok(Value::Empty) + } +} diff --git a/src/macros/gui.rs b/src/macros/gui.rs new file mode 100644 index 0000000..612a611 --- /dev/null +++ b/src/macros/gui.rs @@ -0,0 +1,375 @@ +use eframe::{ + egui::{ + plot::{Bar, BarChart, Line, Plot as EguiPlot, PlotPoints}, + CentralPanel, Context, Direction, Layout, RichText, ScrollArea, Ui, + }, + emath::Align, + epaint::{Color32, Stroke}, + run_native, NativeOptions, +}; +use egui_extras::{Column, StripBuilder, TableBuilder}; + +use crate::{eval_with_context, Error, Macro, MacroInfo, Result, Table, Value, VariableMap}; + +pub struct CreateLine; + +impl Macro for CreateLine { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "create_line", + description: "Create a map value to be shown as a line in a plot.", + group: "gui", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_list()?; + let index = argument[0].as_int()?.clone(); + let height = argument[1].as_float()?.clone(); + let name = argument[2].clone(); + let mut line = VariableMap::new(); + + line.set_value("index", Value::Float(index as f64))?; + line.set_value("height", Value::Float(height))?; + line.set_value("name", name)?; + + Ok(Value::Map(line)) + } +} + +pub struct BarGraph; + +impl Macro for BarGraph { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "bar_graph", + description: "Render a list of values as a bar graph.", + group: "gui", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_list()?; + let mut bars = Vec::new(); + + for (index, value) in argument.into_iter().enumerate() { + let list = value.as_list()?; + let mut name = None; + let mut height = None; + + for value in list { + match value { + Value::Float(float) => { + if height.is_none() { + height = Some(float); + } + } + Value::Integer(integer) => {} + Value::String(string) => name = Some(string), + Value::Boolean(_) + | Value::List(_) + | Value::Map(_) + | Value::Table(_) + | Value::Time(_) + | Value::Function(_) + | Value::Empty => continue, + } + } + + let height = + match height { + Some(height) => *height, + None => return Err(Error::CustomMessage( + "Could not create bar graph. No float value was found to use as a height." + .to_string(), + )), + }; + + let bar = Bar::new(index as f64, height).name(name.unwrap_or(&"".to_string())); + + bars.push(bar); + } + + run_native( + "bar_graph", + NativeOptions::default(), + Box::new(|_cc| Box::new(BarGraphGui::new(bars))), + ) + .unwrap(); + + Ok(Value::Empty) + } +} + +struct BarGraphGui { + bars: Vec, +} + +impl BarGraphGui { + fn new(data: Vec) -> Self { + Self { bars: data } + } +} + +impl eframe::App for BarGraphGui { + fn update(&mut self, ctx: &Context, _frame: &mut eframe::Frame) { + CentralPanel::default().show(ctx, |ui| { + EguiPlot::new("bar_graph").show(ui, |plot_ui| { + plot_ui.bar_chart(BarChart::new(self.bars.clone()).color(Color32::RED)); + }); + }); + } +} + +pub struct Plot; + +impl Macro for Plot { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "plot", + description: "Render a list of numbers as a scatter plot graph.", + group: "gui", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_list()?; + let mut floats = Vec::new(); + + for value in argument { + if let Ok(float) = value.as_float() { + floats.push(float); + } else if let Ok(integer) = value.as_int() { + floats.push(integer as f64); + } else { + return Err(Error::expected_number(value.clone())); + } + } + + run_native( + "plot", + NativeOptions { + resizable: true, + centered: true, + ..Default::default() + }, + Box::new(|_cc| Box::new(PlotGui::new(floats))), + ) + .unwrap(); + + Ok(Value::Empty) + } +} + +struct PlotGui { + data: Vec, +} + +impl PlotGui { + fn new(data: Vec) -> Self { + Self { data } + } +} + +impl eframe::App for PlotGui { + fn update(&mut self, ctx: &Context, _frame: &mut eframe::Frame) { + CentralPanel::default().show(ctx, |ui| { + EguiPlot::new("plot").show(ui, |plot_ui| { + let points = self + .data + .iter() + .enumerate() + .map(|(index, value)| [index as f64, *value]) + .collect::(); + let line = Line::new(points); + plot_ui.line(line); + }) + }); + } +} + +pub struct Gui; + +impl Macro for Gui { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "gui", + description: "Display a value in a GUI window.", + group: "gui", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.clone(); + + run_native( + &argument.value_type().to_string(), + NativeOptions::default(), + Box::new(|_cc| Box::new(GuiApp::new(Ok(argument)))), + ) + .unwrap(); + + Ok(Value::Empty) + } +} + +pub struct GuiApp { + text_edit_buffer: String, + whale_context: VariableMap, + eval_result: Result, +} + +impl GuiApp { + pub fn new(result: Result) -> Self { + GuiApp { + text_edit_buffer: String::new(), + whale_context: VariableMap::new(), + eval_result: result, + } + } + + fn table_ui(&mut self, table: &Table, ui: &mut Ui) { + TableBuilder::new(ui) + .resizable(true) + .striped(true) + .columns(Column::remainder(), table.column_names().len()) + .header(30.0, |mut row| { + for name in table.column_names() { + row.col(|ui| { + ui.label(name); + }); + } + }) + .body(|body| { + body.rows(20.0, table.rows().len(), |index, mut row| { + let row_data = table.rows().get(index).unwrap(); + + for cell_data in row_data { + row.col(|ui| { + ui.label(cell_data.to_string()); + }); + } + }); + }); + } +} + +impl eframe::App for GuiApp { + fn update(&mut self, ctx: &Context, _frame: &mut eframe::Frame) { + CentralPanel::default().show(ctx, |ui| { + ui.with_layout( + Layout { + main_dir: Direction::TopDown, + main_wrap: false, + main_align: Align::Center, + main_justify: false, + cross_align: Align::Center, + cross_justify: true, + }, + |ui| { + ui.text_edit_multiline(&mut self.text_edit_buffer); + ui.horizontal(|ui| { + let clear = ui.button("clear"); + let submit = ui.button("submit"); + + if clear.clicked() { + self.text_edit_buffer.clear(); + } + + if submit.clicked() { + self.eval_result = + eval_with_context(&self.text_edit_buffer, &mut self.whale_context); + } + }); + }, + ); + ui.separator(); + + StripBuilder::new(ui) + .sizes(egui_extras::Size::remainder(), 1) + .vertical(|mut strip| { + strip.cell(|ui| { + let rectangle = ui.available_rect_before_wrap(); + let corner = 5.0; + let border = Stroke::new(1.0, Color32::DARK_GREEN); + let item_size = 20.0; + + ui.painter().rect_stroke(rectangle, corner, border); + + match &self.eval_result { + Ok(value) => match value { + Value::String(string) => { + ui.label(RichText::new(string).size(item_size)); + } + Value::Float(float) => { + ui.label(RichText::new(float.to_string()).size(item_size)); + } + Value::Integer(integer) => { + ui.label(RichText::new(integer.to_string()).size(item_size)); + } + Value::Boolean(boolean) => { + ui.label(RichText::new(boolean.to_string()).size(item_size)); + } + Value::List(list) => { + for value in list { + ui.label(RichText::new(value.to_string()).size(item_size)); + } + } + Value::Map(_) => todo!(), + Value::Table(table) => { + ScrollArea::both().show(ui, |ui| { + TableBuilder::new(ui) + .resizable(true) + .striped(true) + .vscroll(true) + .columns( + Column::remainder(), + table.column_names().len(), + ) + .header(20.0, |mut row| { + for name in table.column_names() { + row.col(|ui| { + ui.label(name); + }); + } + }) + .body(|body| { + body.rows( + 20.0, + table.rows().len(), + |index, mut row| { + let row_data = + table.rows().get(index).unwrap(); + + for value in row_data { + row.col(|ui| { + ui.label(value.to_string()); + }); + } + }, + ); + }); + }); + } + Value::Function(_) => todo!(), + Value::Empty => {} + Value::Time(_) => todo!(), + }, + Err(error) => { + let rectangle = ui.available_rect_before_wrap(); + let corner = 5.0; + let border = Stroke::new(1.0, Color32::DARK_RED); + + ui.painter().rect_stroke(rectangle, corner, border); + ui.label(error.to_string()); + } + } + }); + }); + }); + } +} diff --git a/src/macros/logic.rs b/src/macros/logic.rs new file mode 100644 index 0000000..696bc88 --- /dev/null +++ b/src/macros/logic.rs @@ -0,0 +1,81 @@ +use crate::{Error, Macro, MacroInfo, Result, Value, ValueType}; + +pub struct If; + +impl Macro for If { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "if", + description: "Evaluates the first argument. If true, it does the second argument. If false, it does the third argument", + group: "general", + inputs: vec![ + ValueType::List(vec![ + ValueType::Boolean, + ValueType::Any, + ValueType::Any + ]), + ValueType::List(vec![ + ValueType::Function, + ValueType::Any, + ValueType::Any + ])], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_fixed_len_list(3)?; + let (condition, if_true, if_false) = (&argument[0], &argument[1], &argument[2]); + + let condition_is_true = if let Ok(boolean) = condition.as_boolean() { + boolean + } else if let Ok(function) = condition.as_function() { + function.run()?.as_boolean()? + } else { + return Err(Error::TypeError { + expected: &[ValueType::Boolean, ValueType::Function], + actual: condition.clone(), + }); + }; + + let should_yield = if condition_is_true { if_true } else { if_false }; + + if let Ok(function) = should_yield.as_function() { + function.run() + } else { + Ok(should_yield.clone()) + } + } +} + +pub struct Loop; + +impl Macro for Loop { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "loop", + description: "Repeats a function until the program ends.", + group: "general", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let function = argument.as_function()?; + + function.run()?; + + Loop.run(argument) + } +} + +pub struct While; + +impl Macro for While { + fn info(&self) -> MacroInfo<'static> { + todo!() + } + + fn run(&self, _argument: &Value) -> Result { + todo!() + } +} diff --git a/src/macros/mod.rs b/src/macros/mod.rs new file mode 100644 index 0000000..c7910d2 --- /dev/null +++ b/src/macros/mod.rs @@ -0,0 +1,368 @@ +//! This module contains whale's built-in macro system. Every macro is listed +//! alphabetically. Use [call_macro] to check an identifier against every macro. +//! +//! ## Writing macros +//! +//! - snake case identifier, this is enforced by a test +//! - the type name should be the identifier in upper camel case +//! - always verify user input, this creates helpful errors +//! - the description should be brief, it will display in the shell +//! - maintain alphabetical order +//! +//! ## Usage +//! +//! Macros can be used in Rust by passing a Value to the run method. +//! +//! ``` +//! let value = Value::List(vec![1, 2,3]); +//! let count = Count.run(value).as_string().unwrap(); +//! +//! assert_eq!(count, 3); +//! ``` + +use crate::{Result, Value, ValueType}; + +pub mod collections; +pub mod command; +pub mod data_formats; +pub mod disks; +pub mod filesystem; +pub mod general; +pub mod gui; +pub mod logic; +pub mod network; +pub mod package_management; +pub mod random; +pub mod system; +pub mod test; +pub mod time; + +/// Master list of all macros. +/// +/// This list is used to match identifiers with macros and to provide info to +/// the shell. +pub const MACRO_LIST: [&'static dyn Macro; 56] = [ + &collections::Count, + &collections::CreateTable, + &collections::Get, + &collections::Insert, + &collections::Rows, + &collections::Select, + &collections::String, + &collections::Transform, + &collections::Where, + &command::Bash, + &command::Fish, + &command::Raw, + &command::Sh, + &command::Zsh, + &data_formats::FromCsv, + &data_formats::ToCsv, + &data_formats::FromJson, + &data_formats::ToJson, + &disks::ListDisks, + &disks::Partition, + &filesystem::Append, + &filesystem::CreateDir, + &filesystem::FileMetadata, + &filesystem::MoveDir, + &filesystem::ReadDir, + &filesystem::ReadFile, + &filesystem::RemoveDir, + &filesystem::Trash, + &filesystem::Watch, + &filesystem::Write, + &general::Async, + &general::Output, + &general::Repeat, + &general::Run, + &general::Wait, + &gui::BarGraph, + &gui::Plot, + &gui::Gui, + &logic::If, + &logic::Loop, + &network::Download, + &package_management::CoprRepositories, + &package_management::EnableRpmRepositories, + &package_management::InstallPackage, + &package_management::UninstallPackage, + &package_management::UpgradePackages, + &random::Random, + &random::RandomBoolean, + &random::RandomFloat, + &random::RandomInteger, + &random::RandomString, + &system::CpuSpeed, + &test::Assert, + &test::AssertEqual, + &time::Local, + &time::Now, +]; + +/// A whale macro function. +pub trait Macro: Sync + Send { + fn info(&self) -> MacroInfo<'static>; + fn run(&self, argument: &Value) -> Result; +} + +/// Information needed for each macro. +#[derive(Clone, Debug, PartialEq)] +pub struct MacroInfo<'a> { + /// Text pattern that triggers this macro. + pub identifier: &'a str, + + /// User-facing information about how the macro works. + pub description: &'a str, + + /// Category used to sort macros in the shell. + pub group: &'a str, + + pub inputs: Vec, +} + +// pub struct SystemInfo; + +// impl Macro for SystemInfo { +// fn info(&self) -> MacroInfo<'static> { +// MacroInfo { +// identifier: "system_info", +// description: "Get information on the system.", +// } +// } + +// fn run(&self, argument: &Value) -> crate::Result { +// argument.as_empty()?; + +// let mut map = VariableMap::new(); + +// map.set_value("hostname", Value::String(hostname()?))?; + +// Ok(Value::Map(map)) +// } +// } + +// pub struct Sort; + +// impl Macro for Sort { +// fn info(&self) -> MacroInfo<'static> { +// MacroInfo { +// identifier: "sort", +// description: "Apply default ordering.", +// } +// } + +// fn run(&self, argument: &Value) -> Result { +// if let Ok(mut list) = argument.as_list().cloned() { +// list.sort(); + +// Ok(Value::List(list)) +// } else if let Ok(map) = argument.as_map().cloned() { +// Ok(Value::Map(map)) +// } else if let Ok(mut table) = argument.as_table().cloned() { +// table.sort(); + +// Ok(Value::Table(table)) +// } else { +// Err(crate::Error::ExpectedList { +// actual: argument.clone(), +// }) +// } +// } +// } + +// pub struct Map; + +// impl Macro for Map { +// fn info(&self) -> MacroInfo<'static> { +// MacroInfo { +// identifier: "map", +// description: "Create a map from a value.", +// } +// } + +// fn run(&self, argument: &Value) -> Result { +// match argument { +// Value::String(_) => todo!(), +// Value::Float(_) => todo!(), +// Value::Integer(_) => todo!(), +// Value::Boolean(_) => todo!(), +// Value::List(_) => todo!(), +// Value::Map(_) => todo!(), +// Value::Table(table) => Ok(Value::Map(VariableMap::from(table))), +// Value::Function(_) => todo!(), +// Value::Empty => todo!(), +// } +// } +// } + +// pub struct Status; + +// impl Macro for Status { +// fn info(&self) -> MacroInfo<'static> { +// MacroInfo { +// identifier: "git_status", +// description: "Get the repository status for the current directory.", +// } +// } + +// fn run(&self, argument: &Value) -> Result { +// argument.as_empty()?; + +// let repo = Repository::open(".")?; +// let mut table = Table::new(vec![ +// "path".to_string(), +// "status".to_string(), +// "staged".to_string(), +// ]); + +// for entry in repo.statuses(None)?.into_iter() { +// let (status, staged) = { +// if entry.status().is_wt_new() { +// ("created".to_string(), false) +// } else if entry.status().is_wt_deleted() { +// ("deleted".to_string(), false) +// } else if entry.status().is_wt_modified() { +// ("modified".to_string(), false) +// } else if entry.status().is_index_new() { +// ("created".to_string(), true) +// } else if entry.status().is_index_deleted() { +// ("deleted".to_string(), true) +// } else if entry.status().is_index_modified() { +// ("modified".to_string(), true) +// } else if entry.status().is_ignored() { +// continue; +// } else { +// ("".to_string(), false) +// } +// }; +// let path = entry.path().unwrap().to_string(); + +// table.insert(vec![ +// Value::String(path), +// Value::String(status), +// Value::Boolean(staged), +// ])?; +// } + +// Ok(Value::Table(table)) +// } +// } + +// pub struct DocumentConvert; + +// impl Macro for DocumentConvert { +// fn info(&self) -> MacroInfo<'static> { +// MacroInfo { +// identifier: "convert_document", +// description: "Convert a file's contents to a format and set the extension.", +// } +// } + +// fn run(&self, argument: &Value) -> Result { +// let argument = argument.as_list()?; + +// if argument.len() != 3 { +// return Err(Error::WrongFunctionArgumentAmount { +// expected: 3, +// actual: argument.len(), +// }); +// } + +// let (path, from, to) = ( +// argument[0].as_string()?, +// argument[1].as_string()?, +// argument[2].as_string()?, +// ); +// let mut file_name = PathBuf::from(&path); +// file_name.set_extension(to); +// let new_file_name = file_name.to_str().unwrap(); +// let script = format!("pandoc --from {from} --to {to} --output {new_file_name} {path}"); + +// Command::new("fish").arg("-c").arg(script).spawn()?.wait()?; + +// Ok(Value::Empty) +// } +// } + +// pub struct Trash; + +// impl Macro for Trash { +// fn info(&self) -> MacroInfo<'static> { +// MacroInfo { +// identifier: "trash_dir", +// description: "Move a directory to the trash.", +// } +// } + +// fn run(&self, argument: &Value) -> Result { +// let path = argument.as_string()?; + +// trash::delete(path)?; + +// Ok(Value::Empty) +// } +// } + +// pub struct Get; + +// impl Macro for Get { +// fn info(&self) -> MacroInfo<'static> { +// MacroInfo { +// identifier: "get", +// description: "Extract a value from a collection.", +// } +// } + +// fn run(&self, argument: &Value) -> Result { +// let argument_list = argument.as_list()?; +// let collection = &argument_list[0]; +// let index = &argument_list[1]; + +// if let Ok(list) = collection.as_list() { +// let index = index.as_int()?; +// let value = list.get(index as usize).unwrap_or(&Value::Empty); + +// return Ok(value.clone()); +// } + +// if let Ok(table) = collection.as_table() { +// let index = index.as_int()?; +// let get_row = table.get(index as usize); + +// if let Some(row) = get_row { +// return Ok(Value::List(row.clone())); +// } +// } + +// Err(Error::TypeError { +// expected: &[ +// ValueType::List, +// ValueType::Map, +// ValueType::Table, +// ValueType::String, +// ], +// actual: collection.clone(), +// }) +// } +// } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn macro_formatting() { + for function in MACRO_LIST { + let identifier = function.info().identifier; + + assert_eq!(identifier.to_lowercase(), identifier); + assert!(identifier.is_ascii()); + assert!(!identifier.is_empty()); + assert!(!identifier.contains(' ')); + assert!(!identifier.contains(':')); + assert!(!identifier.contains('.')); + assert!(!identifier.contains('-')); + } + } +} diff --git a/src/macros/network.rs b/src/macros/network.rs new file mode 100644 index 0000000..a0f6fcb --- /dev/null +++ b/src/macros/network.rs @@ -0,0 +1,23 @@ +//! Macros for network access. + +use crate::{Macro, MacroInfo, Result, Value}; + +pub struct Download; + +impl Macro for Download { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "download", + description: "Fetch a network resource.", + group: "network", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let argument = argument.as_string()?; + let output = reqwest::blocking::get(argument)?.text()?; + + Ok(Value::String(output)) + } +} diff --git a/src/macros/package_management.rs b/src/macros/package_management.rs new file mode 100644 index 0000000..77176a6 --- /dev/null +++ b/src/macros/package_management.rs @@ -0,0 +1,170 @@ +use std::process::Command; + +use crate::{Error, Macro, MacroInfo, Result, Value}; + +pub struct CoprRepositories; + +impl Macro for CoprRepositories { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "enable_copr_repository", + description: "Enable one or more COPR repositories.", + group: "package management", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let repo_list_string = if let Ok(repo) = argument.as_string().cloned() { + repo + } else if let Ok(repos) = argument.as_list() { + repos.iter().map(|value| value.to_string() + " ").collect() + } else { + return Err(crate::Error::ExpectedString { + actual: argument.clone(), + }); + }; + + Command::new("fish") + .arg("-c") + .arg(format!("sudo dnf -y copr enable {repo_list_string}")) + .spawn()? + .wait()?; + + Ok(Value::Empty) + } +} + +pub struct InstallPackage; + +impl Macro for InstallPackage { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "install_package", + description: "Install one or more packages.", + group: "package management", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let package_list_string = if let Ok(package) = argument.as_string().cloned() { + package + } else if let Ok(packages) = argument.as_list() { + packages + .iter() + .map(|value| value.to_string() + " ") + .collect() + } else { + return Err(Error::ExpectedString { + actual: argument.clone(), + }); + }; + + Command::new("fish") + .arg("-c") + .arg(format!("sudo dnf -y install {package_list_string}")) + .spawn()? + .wait()?; + + Ok(Value::Empty) + } +} + +pub struct EnableRpmRepositories; + +impl Macro for EnableRpmRepositories { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "enable_rpm_repositories", + description: "Enable one or more RPM repositories.", + group: "package management", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + if let Ok(repo) = argument.as_string() { + Command::new("fish") + .arg("-c") + .arg(format!("sudo dnf -y config-manager --add-repo {repo}")) + .spawn()? + .wait()?; + } else if let Ok(repos) = argument.as_list() { + for repo in repos { + Command::new("fish") + .arg("-c") + .arg(format!("sudo dnf -y config-manager --add-repo {repo}")) + .spawn()? + .wait()?; + } + } else { + return Err(crate::Error::ExpectedString { + actual: argument.clone(), + }); + }; + + Ok(Value::Empty) + } +} + +pub struct UninstallPackage; + +impl Macro for UninstallPackage { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "uninstall_package", + description: "Uninstall one or more packages.", + group: "package management", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let package_list_string = if let Ok(package) = argument.as_string().cloned() { + package + } else if let Ok(packages) = argument.as_list() { + packages + .iter() + .map(|value| value.to_string() + " ") + .collect() + } else { + return Err(Error::ExpectedString { + actual: argument.clone(), + }); + }; + + Command::new("fish") + .arg("-c") + .arg(format!("sudo dnf -y remove {package_list_string}")) + .spawn()? + .wait()?; + + Ok(Value::Empty) + } +} + +pub struct UpgradePackages; + +impl Macro for UpgradePackages { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "upgrade_packages", + description: "Upgrade all installed packages.", + group: "package management", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + argument.as_empty()?; + + Command::new("fish") + .arg("-c") + .arg("sudo dnf -y upgrade") + .spawn()? + .wait()?; + + Ok(Value::Empty) + } +} diff --git a/src/macros/random.rs b/src/macros/random.rs new file mode 100644 index 0000000..9cf9ec8 --- /dev/null +++ b/src/macros/random.rs @@ -0,0 +1,149 @@ +use std::convert::TryInto; + +use rand::{random, thread_rng, Rng}; + +use crate::{Error, Macro, MacroInfo, Result, Value}; + +pub struct RandomBoolean; + +impl Macro for RandomBoolean { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "random_boolean", + description: "Create a random boolean.", + group: "random", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + argument.as_empty()?; + + let boolean = rand::thread_rng().gen(); + + Ok(Value::Boolean(boolean)) + } +} + +pub struct RandomInteger; + +impl Macro for RandomInteger { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "random_integer", + description: "Create a random integer.", + group: "random", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + match argument { + Value::Integer(max) => { + let integer = rand::thread_rng().gen_range(0..*max); + + Ok(Value::Integer(integer)) + } + Value::List(min_max) => { + Error::expect_function_argument_amount(self.info().identifier, min_max.len(), 2)?; + + let min = min_max.get(0).unwrap().as_int()?; + let max = min_max.get(1).unwrap().as_int()? + 1; + let integer = rand::thread_rng().gen_range(min..max); + + Ok(Value::Integer(integer)) + } + Value::Empty => Ok(crate::Value::Integer(random())), + _ => todo!(), + } + } +} + +pub struct RandomString; + +impl Macro for RandomString { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "random_string", + description: "Generate a random string.", + group: "random", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + match argument { + Value::Integer(length) => { + let length: usize = length.unsigned_abs().try_into().unwrap_or(0); + let mut random = String::with_capacity(length); + + for _ in 0..length { + let random_char = thread_rng().gen_range('A'..='z').to_string(); + + random.push_str(&random_char); + } + + Ok(Value::String(random)) + } + Value::Empty => { + let mut random = String::with_capacity(10); + + for _ in 0..10 { + let random_char = thread_rng().gen_range('A'..='z').to_string(); + + random.push_str(&random_char); + } + + Ok(Value::String(random)) + } + _ => Err(Error::ExpectedEmpty { + actual: argument.clone(), + }), + } + } +} + +pub struct RandomFloat; + +impl Macro for RandomFloat { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "random_float", + description: "Generate a random floating point value between 0 and 1.", + group: "random", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + argument.as_empty()?; + + Ok(Value::Float(random())) + } +} + +pub struct Random; + +impl Macro for Random { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "random", + description: "Select a random item from a collection.", + group: "random", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + if let Ok(list) = argument.as_list() { + let random_index = thread_rng().gen_range(0..list.len()); + let random_item = list.get(random_index).unwrap(); + + Ok(random_item.clone()) + } else { + Err(Error::ExpectedCollection { + actual: argument.clone(), + }) + } + } +} diff --git a/src/macros/system.rs b/src/macros/system.rs new file mode 100644 index 0000000..5a5f121 --- /dev/null +++ b/src/macros/system.rs @@ -0,0 +1,24 @@ +use sys_info::cpu_speed; + +use crate::{Macro, MacroInfo, Result, Value}; + +pub struct CpuSpeed; + +impl Macro for CpuSpeed { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "cpu_speed", + description: "Return the current processor speed in megahertz.", + group: "system", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + argument.as_empty()?; + + let speed = cpu_speed().unwrap_or_default() as i64; + + Ok(Value::Integer(speed)) + } +} diff --git a/src/macros/test.rs b/src/macros/test.rs new file mode 100644 index 0000000..1efe29a --- /dev/null +++ b/src/macros/test.rs @@ -0,0 +1,42 @@ +use crate::{Macro, MacroInfo, Result, Value}; + +pub struct Assert; + +impl Macro for Assert { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "assert", + description: "Panic if a boolean is false.", + group: "test", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let boolean = argument.as_boolean()?; + + assert!(boolean); + + Ok(Value::Empty) + } +} + +pub struct AssertEqual; + +impl Macro for AssertEqual { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "assert_equal", + description: "Panic if two values do not match.", + group: "test", + inputs: vec![], + } + } + + fn run(&self, argument: &Value) -> Result { + let arguments = argument.as_fixed_len_list(2)?; + assert_eq!(arguments[0], arguments[1]); + + Ok(Value::Empty) + } +} diff --git a/src/macros/time.rs b/src/macros/time.rs new file mode 100644 index 0000000..8bc12f0 --- /dev/null +++ b/src/macros/time.rs @@ -0,0 +1,43 @@ +use std::time::Instant; + +use crate::{Macro, MacroInfo, Result, Time, Value}; + +pub struct Now; + +impl Macro for Now { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "now", + description: "Return the current time.", + group: "time", + inputs: vec![], + } + } + + fn run(&self, argument: &crate::Value) -> Result { + argument.as_empty()?; + + let time = Time::monotonic(Instant::now()); + + Ok(Value::Time(time)) + } +} + +pub struct Local; + +impl Macro for Local { + fn info(&self) -> MacroInfo<'static> { + MacroInfo { + identifier: "local", + description: "Show a time value adjusted for the current time zone.", + group: "time", + inputs: vec![], + } + } + + fn run(&self, argument: &crate::Value) -> Result { + let argument = argument.as_time()?; + + Ok(Value::String(argument.as_local())) + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..051c8df --- /dev/null +++ b/src/main.rs @@ -0,0 +1,273 @@ +//! Command line interface for the whale programming language. +use clap::Parser; +use eframe::{run_native, NativeOptions}; +use nu_ansi_term::{Color, Style}; +use reedline::{ + default_emacs_keybindings, ColumnarMenu, Completer, DefaultHinter, DefaultPrompt, + DefaultPromptSegment, EditCommand, Emacs, FileBackedHistory, KeyCode, KeyModifiers, Reedline, + ReedlineEvent, ReedlineMenu, Signal, Span, Suggestion, +}; + +use std::{ + fs::{self, read_to_string}, + path::PathBuf, +}; + +use whale_lib::{ + eval, eval_with_context, gui::GuiApp, Macro, MacroInfo, Result, Value, VariableMap, MACRO_LIST, +}; + +/// Command-line arguments to be parsed. +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +struct Args { + /// Whale source code to evaluate. + #[arg(short, long)] + command: Option, + + /// Location of the file to run. + #[arg(short, long)] + path: Option, + + #[arg(short, long)] + gui: bool, +} + +fn main() { + let args = Args::parse(); + + if !args.gui && args.path.is_none() && args.command.is_none() { + return run_cli_shell(); + } + + let eval_result = if let Some(path) = args.path { + let file_contents = read_to_string(path).unwrap(); + + eval(&file_contents) + } else if let Some(command) = args.command { + eval(&command) + } else { + Ok(Value::Empty) + }; + + if args.gui { + return run_gui_shell(eval_result); + } + + match eval_result { + Ok(value) => println!("{value}"), + Err(error) => eprintln!("{error}"), + } +} + +fn run_gui_shell(result: Result) { + run_native( + &Value::Empty.to_string(), + NativeOptions::default(), + Box::new(|_cc| Box::new(GuiApp::new(result))), + ) + .unwrap(); +} + +fn run_cli_shell() { + let mut context = VariableMap::new(); + let mut line_editor = setup_reedline(); + let prompt = DefaultPrompt { + left_prompt: DefaultPromptSegment::WorkingDirectory, + right_prompt: DefaultPromptSegment::CurrentDateTime, + }; + + loop { + let sig = line_editor.read_line(&prompt); + + match sig { + Ok(Signal::Success(buffer)) => { + let eval_result = eval_with_context(&buffer, &mut context); + + match eval_result { + Ok(value) => println!("{value}"), + Err(error) => eprintln!("{error}"), + } + } + Ok(Signal::CtrlD) | Ok(Signal::CtrlC) => { + println!("\nExit"); + break; + } + signal => { + println!("Unhandled signal: {:?}", signal); + } + } + } +} + +struct WhaleCompeleter { + macro_list: Vec, + files: Vec, +} + +impl WhaleCompeleter { + pub fn new() -> Self { + WhaleCompeleter { + macro_list: Vec::new(), + files: Vec::new(), + } + } + + pub fn set_macro_list(&mut self, macro_list: Vec<&'static dyn Macro>) -> &mut Self { + self.macro_list = macro_list + .iter() + .map(|r#macro| { + let MacroInfo { + identifier, + description, + group, + inputs, + } = r#macro.info(); + + let description = format!("{description} | {group}"); + let inputs = inputs + .iter() + .map(|value_type| value_type.to_string()) + .collect(); + + Suggestion { + value: identifier.to_string(), + description: Some(description), + extra: Some(inputs), + ..Default::default() + } + }) + .collect(); + + self.macro_list + .sort_by_key(|suggestion| suggestion.extra.clone()); + + self + } + + pub fn get_suggestions(&mut self, start: usize, end: usize) -> Vec { + let macro_suggestions = self + .macro_list + .iter() + .cloned() + .map(|suggestion| Suggestion { + span: Span { start, end }, + ..suggestion + }); + let file_suggestions = self.files.iter().cloned().map(|suggestion| Suggestion { + span: Span { start, end }, + ..suggestion + }); + + file_suggestions.chain(macro_suggestions).collect() + } + + pub fn update_files(&mut self, mut path: &str) { + if path.starts_with('\"') { + path = &path[1..]; + } + + let path = PathBuf::from(path); + + if !path.is_dir() { + return; + } + + self.files = fs::read_dir(path) + .unwrap() + .map(|entry| { + let path = entry.unwrap().path(); + let path = path.to_string_lossy(); + + Suggestion { + value: format!("\"{path}\""), + description: None, + ..Default::default() + } + }) + .collect(); + } +} + +impl Completer for WhaleCompeleter { + fn complete(&mut self, line: &str, pos: usize) -> Vec { + let split = line.split(' '); + let current_word = split.last().unwrap_or(""); + let start = pos.saturating_sub(current_word.len()); + let end = line.len(); + + self.update_files(current_word); + self.get_suggestions(start, end) + } +} + +fn setup_reedline() -> Reedline { + let mut completer = Box::new(WhaleCompeleter::new()); + + completer.set_macro_list(MACRO_LIST.to_vec()); + + let completion_menu = Box::new( + ColumnarMenu::default() + .with_name("completion_menu") + .with_columns(1) + .with_text_style(Style { + foreground: Some(Color::White), + is_dimmed: false, + ..Default::default() + }) + .with_description_text_style(Style { + is_dimmed: true, + ..Default::default() + }) + .with_selected_text_style(Style { + is_bold: true, + background: Some(Color::Black), + foreground: Some(Color::White), + ..Default::default() + }), + ); + + let mut keybindings = default_emacs_keybindings(); + keybindings.add_binding( + KeyModifiers::NONE, + KeyCode::Tab, + ReedlineEvent::UntilFound(vec![ + ReedlineEvent::Menu("completion_menu".to_string()), + ReedlineEvent::MenuNext, + ]), + ); + keybindings.add_binding( + KeyModifiers::SHIFT, + KeyCode::Tab, + ReedlineEvent::UntilFound(vec![ + ReedlineEvent::Menu("completion_menu".to_string()), + ReedlineEvent::MenuPrevious, + ]), + ); + keybindings.add_binding( + KeyModifiers::ALT, + KeyCode::Enter, + ReedlineEvent::Edit(vec![EditCommand::InsertNewline]), + ); + + let edit_mode = Box::new(Emacs::new(keybindings)); + let history = Box::new( + FileBackedHistory::with_file(100, "target/history.txt".into()) + .expect("Error configuring shell history file."), + ); + let mut hinter = DefaultHinter::default(); + + hinter = hinter.with_style(Style { + foreground: Some(Color::Yellow), + ..Default::default() + }); + + Reedline::create() + .with_completer(completer) + .with_menu(ReedlineMenu::EngineCompleter(completion_menu)) + .with_edit_mode(edit_mode) + .with_history(history) + .with_hinter(Box::new(hinter)) + .with_partial_completions(true) + .with_quick_completions(true) +} diff --git a/src/operator.rs b/src/operator.rs new file mode 100644 index 0000000..1809794 --- /dev/null +++ b/src/operator.rs @@ -0,0 +1,547 @@ +use std::fmt::{self, Display, Formatter}; + +use crate::{error::*, value::Value, Result, VariableMap}; + +/// An enum that represents operators in the operator tree. +#[derive(Debug, PartialEq, Clone)] +pub enum Operator { + /// A root node in the operator tree. + /// The whole expression is stored under a root node, as well as each subexpression surrounded by parentheses. + RootNode, + + /// A binary addition operator. + Add, + /// A binary subtraction operator. + Sub, + /// A unary negation operator. + Neg, + /// A binary multiplication operator. + Mul, + /// A binary division operator. + Div, + /// A binary modulo operator. + Mod, + /// A binary exponentiation operator. + Exp, + + /// A binary equality comparator. + Eq, + /// A binary inequality comparator. + Neq, + /// A binary greater-than comparator. + Gt, + /// A binary lower-than comparator. + Lt, + /// A binary greater-than-or-equal comparator. + Geq, + /// A binary lower-than-or-equal comparator. + Leq, + /// A binary logical and operator. + And, + /// A binary logical or operator. + Or, + /// A binary logical not operator. + Not, + + /// A binary assignment operator. + Assign, + /// A binary add-assign operator. + AddAssign, + /// A binary subtract-assign operator. + SubAssign, + /// A binary multiply-assign operator. + MulAssign, + /// A binary divide-assign operator. + DivAssign, + /// A binary modulo-assign operator. + ModAssign, + /// A binary exponentiate-assign operator. + ExpAssign, + /// A binary and-assign operator. + AndAssign, + /// A binary or-assign operator. + OrAssign, + + /// An n-ary tuple constructor. + Tuple, + /// An n-ary subexpression chain. + Chain, + + /// A constant value. + Const { + /** The value of the constant. */ + value: Value, + }, + /// A write to a variable identifier. + VariableIdentifierWrite { + /// The identifier of the variable. + identifier: String, + }, + /// A read from a variable identifier. + VariableIdentifierRead { + /// The identifier of the variable. + identifier: String, + }, + /// A function identifier. + FunctionIdentifier { + /// The identifier of the function. + identifier: String, + }, +} + +impl Operator { + pub(crate) fn value(value: Value) -> Self { + Operator::Const { value } + } + + pub(crate) fn variable_identifier_write(identifier: String) -> Self { + Operator::VariableIdentifierWrite { identifier } + } + + pub(crate) fn variable_identifier_read(identifier: String) -> Self { + Operator::VariableIdentifierRead { identifier } + } + + pub(crate) fn function_identifier(identifier: String) -> Self { + Operator::FunctionIdentifier { identifier } + } + + /// Returns the precedence of the operator. + /// A high precedence means that the operator has priority to be deeper in the tree. + pub(crate) const fn precedence(&self) -> i32 { + use crate::operator::Operator::*; + match self { + RootNode => 200, + + Add | Sub => 95, + Neg => 110, + Mul | Div | Mod => 100, + Exp => 120, + + Eq | Neq | Gt | Lt | Geq | Leq => 80, + And => 75, + Or => 70, + Not => 110, + + Assign | AddAssign | SubAssign | MulAssign | DivAssign | ModAssign | ExpAssign + | AndAssign | OrAssign => 50, + + Tuple => 40, + Chain => 0, + + Const { .. } => 200, + VariableIdentifierWrite { .. } | VariableIdentifierRead { .. } => 200, + FunctionIdentifier { .. } => 190, + } + } + + /// Returns true if chains of operators with the same precedence as this one should be evaluated left-to-right, + /// and false if they should be evaluated right-to-left. + /// Left-to-right chaining has priority if operators with different order but same precedence are chained. + pub(crate) const fn is_left_to_right(&self) -> bool { + use crate::operator::Operator::*; + !matches!(self, Assign | FunctionIdentifier { .. }) + } + + /// Returns true if chains of this operator should be flattened into one operator with many arguments. + pub(crate) const fn is_sequence(&self) -> bool { + use crate::operator::Operator::*; + matches!(self, Tuple | Chain) + } + + /// True if this operator is a leaf, meaning it accepts no arguments. + // Make this a const fn as soon as whatever is missing gets stable (issue #57563) + pub(crate) fn is_leaf(&self) -> bool { + self.max_argument_amount() == Some(0) + } + + /// Returns the maximum amount of arguments required by this operator. + pub(crate) const fn max_argument_amount(&self) -> Option { + use crate::operator::Operator::*; + match self { + Add | Sub | Mul | Div | Mod | Exp | Eq | Neq | Gt | Lt | Geq | Leq | And | Or + | Assign | AddAssign | SubAssign | MulAssign | DivAssign | ModAssign | ExpAssign + | AndAssign | OrAssign => Some(2), + Tuple | Chain => None, + Not | Neg | RootNode => Some(1), + Const { .. } => Some(0), + VariableIdentifierWrite { .. } | VariableIdentifierRead { .. } => Some(0), + FunctionIdentifier { .. } => Some(1), + } + } + + /// Returns true if this operator is unary, i.e. it requires exactly one argument. + pub(crate) fn is_unary(&self) -> bool { + self.max_argument_amount() == Some(1) && *self != Operator::RootNode + } + + /// Evaluates the operator with the given arguments and context. + pub(crate) fn eval(&self, arguments: &[Value], context: &VariableMap) -> Result { + use crate::operator::Operator::*; + + match self { + RootNode => { + if let Some(first) = arguments.first() { + Ok(first.clone()) + } else { + Ok(Value::Empty) + } + } + Add => { + Error::expect_operator_argument_amount(arguments.len(), 2)?; + expect_number_or_string(&arguments[0])?; + expect_number_or_string(&arguments[1])?; + + if let (Ok(a), Ok(b)) = (arguments[0].as_string(), arguments[1].as_string()) { + let mut result = String::with_capacity(a.len() + b.len()); + result.push_str(a); + result.push_str(b); + Ok(Value::String(result)) + } else if let (Ok(a), Ok(b)) = (arguments[0].as_int(), arguments[1].as_int()) { + let result = a.checked_add(b); + if let Some(result) = result { + Ok(Value::Integer(result)) + } else { + Err(Error::addition_error( + arguments[0].clone(), + arguments[1].clone(), + )) + } + } else if let (Ok(a), Ok(b)) = (arguments[0].as_number(), arguments[1].as_number()) + { + Ok(Value::Float(a + b)) + } else { + Err(Error::wrong_type_combination( + self.clone(), + vec![ + arguments.get(0).unwrap().into(), + arguments.get(1).unwrap().into(), + ], + )) + } + } + Sub => { + Error::expect_operator_argument_amount(arguments.len(), 2)?; + arguments[0].as_number()?; + arguments[1].as_number()?; + + if let (Ok(a), Ok(b)) = (arguments[0].as_int(), arguments[1].as_int()) { + let result = a.checked_sub(b); + if let Some(result) = result { + Ok(Value::Integer(result)) + } else { + Err(Error::subtraction_error( + arguments[0].clone(), + arguments[1].clone(), + )) + } + } else { + Ok(Value::Float( + arguments[0].as_number()? - arguments[1].as_number()?, + )) + } + } + Neg => { + Error::expect_operator_argument_amount(arguments.len(), 1)?; + arguments[0].as_number()?; + + if let Ok(a) = arguments[0].as_int() { + let result = a.checked_neg(); + if let Some(result) = result { + Ok(Value::Integer(result)) + } else { + Err(Error::negation_error(arguments[0].clone())) + } + } else { + Ok(Value::Float(-arguments[0].as_number()?)) + } + } + Mul => { + Error::expect_operator_argument_amount(arguments.len(), 2)?; + arguments[0].as_number()?; + arguments[1].as_number()?; + + if let (Ok(a), Ok(b)) = (arguments[0].as_int(), arguments[1].as_int()) { + let result = a.checked_mul(b); + if let Some(result) = result { + Ok(Value::Integer(result)) + } else { + Err(Error::multiplication_error( + arguments[0].clone(), + arguments[1].clone(), + )) + } + } else { + Ok(Value::Float( + arguments[0].as_number()? * arguments[1].as_number()?, + )) + } + } + Div => { + Error::expect_operator_argument_amount(arguments.len(), 2)?; + arguments[0].as_number()?; + arguments[1].as_number()?; + + if let (Ok(a), Ok(b)) = (arguments[0].as_int(), arguments[1].as_int()) { + let result = a.checked_div(b); + if let Some(result) = result { + Ok(Value::Integer(result)) + } else { + Err(Error::division_error( + arguments[0].clone(), + arguments[1].clone(), + )) + } + } else { + Ok(Value::Float( + arguments[0].as_number()? / arguments[1].as_number()?, + )) + } + } + Mod => { + Error::expect_operator_argument_amount(arguments.len(), 2)?; + arguments[0].as_number()?; + arguments[1].as_number()?; + + if let (Ok(a), Ok(b)) = (arguments[0].as_int(), arguments[1].as_int()) { + let result = a.checked_rem(b); + if let Some(result) = result { + Ok(Value::Integer(result)) + } else { + Err(Error::modulation_error( + arguments[0].clone(), + arguments[1].clone(), + )) + } + } else { + Ok(Value::Float( + arguments[0].as_number()? % arguments[1].as_number()?, + )) + } + } + Exp => { + Error::expect_operator_argument_amount(arguments.len(), 2)?; + arguments[0].as_number()?; + arguments[1].as_number()?; + + Ok(Value::Float( + arguments[0].as_number()?.powf(arguments[1].as_number()?), + )) + } + Eq => { + Error::expect_operator_argument_amount(arguments.len(), 2)?; + + Ok(Value::Boolean(arguments[0] == arguments[1])) + } + Neq => { + Error::expect_operator_argument_amount(arguments.len(), 2)?; + + Ok(Value::Boolean(arguments[0] != arguments[1])) + } + Gt => { + Error::expect_operator_argument_amount(arguments.len(), 2)?; + expect_number_or_string(&arguments[0])?; + expect_number_or_string(&arguments[1])?; + + if let (Ok(a), Ok(b)) = (arguments[0].as_string(), arguments[1].as_string()) { + Ok(Value::Boolean(a > b)) + } else if let (Ok(a), Ok(b)) = (arguments[0].as_int(), arguments[1].as_int()) { + Ok(Value::Boolean(a > b)) + } else { + Ok(Value::Boolean( + arguments[0].as_number()? > arguments[1].as_number()?, + )) + } + } + Lt => { + Error::expect_operator_argument_amount(arguments.len(), 2)?; + expect_number_or_string(&arguments[0])?; + expect_number_or_string(&arguments[1])?; + + if let (Ok(a), Ok(b)) = (arguments[0].as_string(), arguments[1].as_string()) { + Ok(Value::Boolean(a < b)) + } else if let (Ok(a), Ok(b)) = (arguments[0].as_int(), arguments[1].as_int()) { + Ok(Value::Boolean(a < b)) + } else { + Ok(Value::Boolean( + arguments[0].as_number()? < arguments[1].as_number()?, + )) + } + } + Geq => { + Error::expect_operator_argument_amount(arguments.len(), 2)?; + expect_number_or_string(&arguments[0])?; + expect_number_or_string(&arguments[1])?; + + if let (Ok(a), Ok(b)) = (arguments[0].as_string(), arguments[1].as_string()) { + Ok(Value::Boolean(a >= b)) + } else if let (Ok(a), Ok(b)) = (arguments[0].as_int(), arguments[1].as_int()) { + Ok(Value::Boolean(a >= b)) + } else { + Ok(Value::Boolean( + arguments[0].as_number()? >= arguments[1].as_number()?, + )) + } + } + Leq => { + Error::expect_operator_argument_amount(arguments.len(), 2)?; + expect_number_or_string(&arguments[0])?; + expect_number_or_string(&arguments[1])?; + + if let (Ok(a), Ok(b)) = (arguments[0].as_string(), arguments[1].as_string()) { + Ok(Value::Boolean(a <= b)) + } else if let (Ok(a), Ok(b)) = (arguments[0].as_int(), arguments[1].as_int()) { + Ok(Value::Boolean(a <= b)) + } else { + Ok(Value::Boolean( + arguments[0].as_number()? <= arguments[1].as_number()?, + )) + } + } + And => { + Error::expect_operator_argument_amount(arguments.len(), 2)?; + let a = arguments[0].as_boolean()?; + let b = arguments[1].as_boolean()?; + + Ok(Value::Boolean(a && b)) + } + Or => { + Error::expect_operator_argument_amount(arguments.len(), 2)?; + let a = arguments[0].as_boolean()?; + let b = arguments[1].as_boolean()?; + + Ok(Value::Boolean(a || b)) + } + Not => { + Error::expect_operator_argument_amount(arguments.len(), 1)?; + let a = arguments[0].as_boolean()?; + + Ok(Value::Boolean(!a)) + } + Assign | AddAssign | SubAssign | MulAssign | DivAssign | ModAssign | ExpAssign + | AndAssign | OrAssign => Err(Error::ContextNotMutable), + Tuple => Ok(Value::List(arguments.into())), + Chain => { + if arguments.is_empty() { + return Err(Error::expect_operator_argument_amount(0, 1).unwrap_err()); + } + + Ok(arguments.last().cloned().unwrap_or(Value::Empty)) + } + Const { value } => { + Error::expect_operator_argument_amount(arguments.len(), 0)?; + + Ok(value.clone()) + } + VariableIdentifierWrite { identifier } => { + Error::expect_operator_argument_amount(arguments.len(), 0)?; + + Ok(identifier.clone().into()) + } + VariableIdentifierRead { identifier } => { + Error::expect_operator_argument_amount(arguments.len(), 0)?; + + if let Some(value) = context.get_value(identifier)? { + Ok(value) + } else { + Err(Error::VariableIdentifierNotFound(identifier.clone())) + } + } + FunctionIdentifier { identifier } => { + Error::expect_operator_argument_amount(arguments.len(), 1)?; + let arguments = &arguments[0]; + + context.call_function(identifier, arguments) + } + } + } + + /// Evaluates the operator with the given arguments and mutable context. + pub(crate) fn eval_mut(&self, arguments: &[Value], context: &mut VariableMap) -> Result { + use crate::operator::Operator::*; + match self { + Assign => { + Error::expect_operator_argument_amount(arguments.len(), 2)?; + let target = arguments[0].as_string()?; + context.set_value(target, arguments[1].clone())?; + + Ok(Value::Empty) + } + AddAssign | SubAssign | MulAssign | DivAssign | ModAssign | ExpAssign | AndAssign + | OrAssign => { + Error::expect_operator_argument_amount(arguments.len(), 2)?; + + let target = arguments[0].as_string()?; + let left_value = Operator::VariableIdentifierRead { + identifier: target.clone(), + } + .eval(&Vec::new(), context)?; + let arguments = vec![left_value, arguments[1].clone()]; + + let result = match self { + AddAssign => Operator::Add.eval(&arguments, context), + SubAssign => Operator::Sub.eval(&arguments, context), + MulAssign => Operator::Mul.eval(&arguments, context), + DivAssign => Operator::Div.eval(&arguments, context), + ModAssign => Operator::Mod.eval(&arguments, context), + ExpAssign => Operator::Exp.eval(&arguments, context), + AndAssign => Operator::And.eval(&arguments, context), + OrAssign => Operator::Or.eval(&arguments, context), + _ => unreachable!( + "Forgot to add a match arm for an assign operation: {}", + self + ), + }?; + context.set_value(target, result)?; + + Ok(Value::Empty) + } + _ => self.eval(arguments, context), + } + } +} + +impl Display for Operator { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + use crate::operator::Operator::*; + match self { + RootNode => Ok(()), + Add => write!(f, "+"), + Sub => write!(f, "-"), + Neg => write!(f, "-"), + Mul => write!(f, "*"), + Div => write!(f, "/"), + Mod => write!(f, "%"), + Exp => write!(f, "^"), + + Eq => write!(f, "=="), + Neq => write!(f, "!="), + Gt => write!(f, ">"), + Lt => write!(f, "<"), + Geq => write!(f, ">="), + Leq => write!(f, "<="), + And => write!(f, "&&"), + Or => write!(f, "||"), + Not => write!(f, "!"), + + Assign => write!(f, " = "), + AddAssign => write!(f, " += "), + SubAssign => write!(f, " -= "), + MulAssign => write!(f, " *= "), + DivAssign => write!(f, " /= "), + ModAssign => write!(f, " %= "), + ExpAssign => write!(f, " ^= "), + AndAssign => write!(f, " &&= "), + OrAssign => write!(f, " ||= "), + + Tuple => write!(f, ", "), + Chain => write!(f, "; "), + + Const { value } => write!(f, "{}", value), + VariableIdentifierWrite { identifier } | VariableIdentifierRead { identifier } => { + write!(f, "{}", identifier) + } + FunctionIdentifier { identifier } => write!(f, "{}", identifier), + } + } +} diff --git a/src/token.rs b/src/token.rs new file mode 100644 index 0000000..f974c59 --- /dev/null +++ b/src/token.rs @@ -0,0 +1,562 @@ +use std::fmt::{self, Display, Formatter}; + +use crate::error::{Error, Result}; + +#[derive(Clone, PartialEq, Debug)] +pub enum Token { + // Arithmetic + Plus, + Minus, + Star, + Slash, + Percent, + Hat, + + // Logic + Eq, + Neq, + Gt, + Lt, + Geq, + Leq, + And, + Or, + Not, + + // Precedence + LBrace, + RBrace, + + // Assignment + Assign, + PlusAssign, + MinusAssign, + StarAssign, + SlashAssign, + PercentAssign, + HatAssign, + AndAssign, + OrAssign, + + // Special + Comma, + Semicolon, + Yield(String, String), + + // Values, Variables and Functions + Identifier(String), + Float(f64), + Int(i64), + Boolean(bool), + String(String), + Function(String), +} + +/// A partial token is an input character whose meaning depends on the characters around it. +#[derive(Clone, Debug, PartialEq)] +pub enum PartialToken { + /// A partial token that unambiguously maps to a single token. + Token(Token), + /// A partial token that is a literal. + Literal(String), + /// A plus character '+'. + Plus, + /// A minus character '-'. + Minus, + /// A star character '*'. + Star, + /// A slash character '/'. + Slash, + /// A percent character '%'. + Percent, + /// A hat character '^'. + Hat, + /// A whitespace character, e.g. ' '. + Whitespace, + /// An equal-to character '='. + Eq, + /// An exclamation mark character '!'. + ExclamationMark, + /// A greater-than character '>'. + Gt, + /// A lower-than character '<'. + Lt, + /// An ampersand character '&'. + Ampersand, + /// A vertical bar character '|'. + VerticalBar, +} + +// Make this a const fn as soon as is_whitespace and to_string get stable (issue #57563) +fn char_to_partial_token(c: char) -> PartialToken { + match c { + '+' => PartialToken::Plus, + '-' => PartialToken::Minus, + '*' => PartialToken::Star, + '/' => PartialToken::Slash, + '%' => PartialToken::Percent, + '^' => PartialToken::Hat, + + '(' => PartialToken::Token(Token::LBrace), + ')' => PartialToken::Token(Token::RBrace), + + ',' => PartialToken::Token(Token::Comma), + ';' => PartialToken::Token(Token::Semicolon), + + '=' => PartialToken::Eq, + '!' => PartialToken::ExclamationMark, + '>' => PartialToken::Gt, + '<' => PartialToken::Lt, + '&' => PartialToken::Ampersand, + '|' => PartialToken::VerticalBar, + + c => { + if c.is_whitespace() { + PartialToken::Whitespace + } else { + PartialToken::Literal(c.to_string()) + } + } + } +} + +impl Token { + #[cfg(not(tarpaulin_include))] + pub(crate) const fn is_leftsided_value(&self) -> bool { + match self { + Token::Plus => false, + Token::Minus => false, + Token::Star => false, + Token::Slash => false, + Token::Percent => false, + Token::Hat => false, + + Token::Eq => false, + Token::Neq => false, + Token::Gt => false, + Token::Lt => false, + Token::Geq => false, + Token::Leq => false, + Token::And => false, + Token::Or => false, + Token::Not => false, + + Token::LBrace => true, + Token::RBrace => false, + + Token::Comma => false, + Token::Semicolon => false, + Token::Yield(_, _) => false, + + Token::Assign => false, + Token::PlusAssign => false, + Token::MinusAssign => false, + Token::StarAssign => false, + Token::SlashAssign => false, + Token::PercentAssign => false, + Token::HatAssign => false, + Token::AndAssign => false, + Token::OrAssign => false, + + Token::Identifier(_) => true, + Token::Float(_) => true, + Token::Int(_) => true, + Token::Boolean(_) => true, + Token::String(_) => true, + Token::Function(_) => true, + } + } + + #[cfg(not(tarpaulin_include))] + pub(crate) const fn is_rightsided_value(&self) -> bool { + match self { + Token::Plus => false, + Token::Minus => false, + Token::Star => false, + Token::Slash => false, + Token::Percent => false, + Token::Hat => false, + + Token::Eq => false, + Token::Neq => false, + Token::Gt => false, + Token::Lt => false, + Token::Geq => false, + Token::Leq => false, + Token::And => false, + Token::Or => false, + Token::Not => false, + + Token::LBrace => false, + Token::RBrace => true, + + Token::Comma => false, + Token::Semicolon => false, + Token::Yield(_, _) => false, + + Token::Assign => false, + Token::PlusAssign => false, + Token::MinusAssign => false, + Token::StarAssign => false, + Token::SlashAssign => false, + Token::PercentAssign => false, + Token::HatAssign => false, + Token::AndAssign => false, + Token::OrAssign => false, + + Token::Identifier(_) => true, + Token::Float(_) => true, + Token::Int(_) => true, + Token::Boolean(_) => true, + Token::String(_) => true, + Token::Function(_) => true, + } + } + + #[cfg(not(tarpaulin_include))] + pub(crate) fn is_assignment(&self) -> bool { + use Token::*; + matches!( + self, + Assign + | PlusAssign + | MinusAssign + | StarAssign + | SlashAssign + | PercentAssign + | HatAssign + | AndAssign + | OrAssign + ) + } +} + +/// Parses an escape sequence within a string literal. +fn parse_escape_sequence>(iter: &mut Iter) -> Result { + match iter.next() { + Some('"') => Ok('"'), + Some('\\') => Ok('\\'), + Some(c) => Err(Error::IllegalEscapeSequence(format!("\\{}", c))), + None => Err(Error::IllegalEscapeSequence("\\".to_string())), + } +} + +/// Parses a string value from the given character iterator. +/// +/// The first character from the iterator is interpreted as first character of the string. +/// The string is terminated by a double quote `"`. +/// Occurrences of `"` within the string can be escaped with `\`. +/// The backslash needs to be escaped with another backslash `\`. +fn parse_string_literal>(mut iter: &mut Iter) -> Result { + let mut result = String::new(); + + while let Some(c) = iter.next() { + match c { + '"' => break, + '\\' => result.push(parse_escape_sequence(&mut iter)?), + c => result.push(c), + } + } + + Ok(PartialToken::Token(Token::String(result))) +} + +fn parse_function>(mut iter: &mut Iter) -> Result { + let mut result = String::new(); + + while let Some(c) = iter.next() { + match c { + '\'' => break, + '\\' => result.push(parse_escape_sequence(&mut iter)?), + c => result.push(c), + } + } + + Ok(PartialToken::Token(Token::Function(result))) +} + +/// Converts a string to a vector of partial tokens. +fn str_to_partial_tokens(string: &str) -> Result> { + let mut result = Vec::new(); + let mut iter = string.chars().peekable(); + + while let Some(c) = iter.next() { + if c == '"' { + result.push(parse_string_literal(&mut iter)?); + } else if c == '\'' { + result.push(parse_function(&mut iter)?) + } else { + let partial_token = char_to_partial_token(c); + + let if_let_successful = + if let (Some(PartialToken::Literal(last)), PartialToken::Literal(literal)) = + (result.last_mut(), &partial_token) + { + last.push_str(literal); + true + } else { + false + }; + + if !if_let_successful { + result.push(partial_token); + } + } + } + Ok(result) +} + +/// Resolves all partial tokens by converting them to complex tokens. +fn partial_tokens_to_tokens(mut tokens: &[PartialToken]) -> Result> { + let mut result = Vec::new(); + while !tokens.is_empty() { + let first = tokens[0].clone(); + let second = tokens.get(1).cloned(); + let third = tokens.get(2).cloned(); + let mut cutoff = 2; + + result.extend( + match first { + PartialToken::Token(token) => { + cutoff = 1; + Some(token) + } + PartialToken::Plus => match second { + Some(PartialToken::Eq) => Some(Token::PlusAssign), + _ => { + cutoff = 1; + Some(Token::Plus) + } + }, + PartialToken::Minus => match second { + Some(PartialToken::Eq) => Some(Token::MinusAssign), + _ => { + cutoff = 1; + Some(Token::Minus) + } + }, + PartialToken::Star => match second { + Some(PartialToken::Eq) => Some(Token::StarAssign), + _ => { + cutoff = 1; + Some(Token::Star) + } + }, + PartialToken::Slash => match second { + Some(PartialToken::Eq) => Some(Token::SlashAssign), + _ => { + cutoff = 1; + Some(Token::Slash) + } + }, + PartialToken::Percent => match second { + Some(PartialToken::Eq) => Some(Token::PercentAssign), + _ => { + cutoff = 1; + Some(Token::Percent) + } + }, + PartialToken::Hat => match second { + Some(PartialToken::Eq) => Some(Token::HatAssign), + _ => { + cutoff = 1; + Some(Token::Hat) + } + }, + PartialToken::Literal(literal) => { + cutoff = 1; + if let Ok(number) = parse_dec_or_hex(&literal) { + Some(Token::Int(number)) + } else if let Ok(number) = literal.parse::() { + Some(Token::Float(number)) + } else if let Ok(boolean) = literal.parse::() { + Some(Token::Boolean(boolean)) + } else { + // If there are two tokens following this one, check if the next one is + // a plus or a minus. If so, then attempt to parse all three tokens as a + // scientific notation number of the form `e{+,-}`, + // for example [Literal("10e"), Minus, Literal("3")] => "1e-3".parse(). + match (second, third) { + (Some(second), Some(third)) + if second == PartialToken::Minus + || second == PartialToken::Plus => + { + if let Ok(number) = + format!("{}{}{}", literal, second, third).parse::() + { + cutoff = 3; + Some(Token::Float(number)) + } else { + Some(Token::Identifier(literal.to_string())) + } + } + _ => Some(Token::Identifier(literal.to_string())), + } + } + } + PartialToken::Whitespace => { + cutoff = 1; + None + } + PartialToken::Eq => match second { + Some(PartialToken::Eq) => Some(Token::Eq), + _ => { + cutoff = 1; + Some(Token::Assign) + } + }, + PartialToken::ExclamationMark => match second { + Some(PartialToken::Eq) => Some(Token::Neq), + _ => { + cutoff = 1; + Some(Token::Not) + } + }, + PartialToken::Gt => match second { + Some(PartialToken::Eq) => Some(Token::Geq), + _ => { + cutoff = 1; + Some(Token::Gt) + } + }, + PartialToken::Lt => match second { + Some(PartialToken::Eq) => Some(Token::Leq), + _ => { + cutoff = 1; + Some(Token::Lt) + } + }, + PartialToken::Ampersand => match second { + Some(PartialToken::Ampersand) => match third { + Some(PartialToken::Eq) => { + cutoff = 3; + Some(Token::AndAssign) + } + _ => Some(Token::And), + }, + _ => return Err(Error::unmatched_partial_token(first, second)), + }, + PartialToken::VerticalBar => match second { + Some(PartialToken::VerticalBar) => match third { + Some(PartialToken::Eq) => { + cutoff = 3; + Some(Token::OrAssign) + } + _ => Some(Token::Or), + }, + _ => return Err(Error::unmatched_partial_token(first, second)), + }, + } + .into_iter(), + ); + + tokens = &tokens[cutoff..]; + } + Ok(result) +} + +impl Display for Token { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + use self::Token::*; + match self { + Plus => write!(f, "+"), + Minus => write!(f, "-"), + Star => write!(f, "*"), + Slash => write!(f, "/"), + Percent => write!(f, "%"), + Hat => write!(f, "^"), + + // Logic + Eq => write!(f, "=="), + Neq => write!(f, "!="), + Gt => write!(f, ">"), + Lt => write!(f, "<"), + Geq => write!(f, ">="), + Leq => write!(f, "<="), + And => write!(f, "&&"), + Or => write!(f, "||"), + Not => write!(f, "!"), + + // Precedence + LBrace => write!(f, "("), + RBrace => write!(f, ")"), + + // Assignment + Assign => write!(f, "="), + PlusAssign => write!(f, "+="), + MinusAssign => write!(f, "-="), + StarAssign => write!(f, "*="), + SlashAssign => write!(f, "/="), + PercentAssign => write!(f, "%="), + HatAssign => write!(f, "^="), + AndAssign => write!(f, "&&="), + OrAssign => write!(f, "||="), + + // Special + Comma => write!(f, ","), + Semicolon => write!(f, ";"), + + // Values => write!(f, ""), Variables and Functions + Identifier(identifier) => identifier.fmt(f), + Float(float) => float.fmt(f), + Int(int) => int.fmt(f), + Boolean(boolean) => boolean.fmt(f), + String(string) => fmt::Debug::fmt(string, f), + Function(string) => write!(f, "'{string}'"), + Yield(_, _) => todo!(), + } + } +} + +impl Display for PartialToken { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + use self::PartialToken::*; + match self { + Token(token) => token.fmt(f), + Literal(literal) => literal.fmt(f), + Whitespace => write!(f, " "), + Plus => write!(f, "+"), + Minus => write!(f, "-"), + Star => write!(f, "*"), + Slash => write!(f, "/"), + Percent => write!(f, "%"), + Hat => write!(f, "^"), + Eq => write!(f, "="), + ExclamationMark => write!(f, "!"), + Gt => write!(f, ">"), + Lt => write!(f, "<"), + Ampersand => write!(f, "&"), + VerticalBar => write!(f, "|"), + } + } +} + +pub(crate) fn tokenize(string: &str) -> Result> { + partial_tokens_to_tokens(&str_to_partial_tokens(string)?) +} + +fn parse_dec_or_hex(literal: &str) -> std::result::Result { + if let Some(literal) = literal.strip_prefix("0x") { + literal.parse() + } else { + literal.parse() + } +} + +#[cfg(test)] +mod tests { + use crate::token::{tokenize, Token}; + + #[test] + fn assignment_lhs_is_identifier() { + let tokens = tokenize("a = 1").unwrap(); + assert_eq!( + tokens.as_slice(), + [ + Token::Identifier("a".to_string()), + Token::Assign, + Token::Int(1) + ] + ); + } +} diff --git a/src/tree/iter.rs b/src/tree/iter.rs new file mode 100644 index 0000000..0524361 --- /dev/null +++ b/src/tree/iter.rs @@ -0,0 +1,94 @@ +use crate::{operator::Operator, Node}; +use std::slice::{Iter, IterMut}; + +/// An iterator that traverses an operator tree in pre-order. +pub struct NodeIter<'a> { + stack: Vec>, +} + +impl<'a> NodeIter<'a> { + fn new(node: &'a Node) -> Self { + NodeIter { + stack: vec![node.children.iter()], + } + } +} + +impl<'a> Iterator for NodeIter<'a> { + type Item = &'a Node; + + fn next(&mut self) -> Option { + loop { + let mut result = None; + + if let Some(last) = self.stack.last_mut() { + if let Some(next) = last.next() { + result = Some(next); + } else { + // Can not fail because we just borrowed last. + // We just checked that the iterator is empty, so we can safely discard it. + let _ = self.stack.pop().unwrap(); + } + } else { + return None; + } + + if let Some(result) = result { + self.stack.push(result.children.iter()); + return Some(result); + } + } + } +} + +/// An iterator that mutably traverses an operator tree in pre-order. +pub struct OperatorIterMut<'a> { + stack: Vec>, +} + +impl<'a> OperatorIterMut<'a> { + fn new(node: &'a mut Node) -> Self { + OperatorIterMut { + stack: vec![node.children.iter_mut()], + } + } +} + +impl<'a> Iterator for OperatorIterMut<'a> { + type Item = &'a mut Operator; + + fn next(&mut self) -> Option { + loop { + let mut result = None; + + if let Some(last) = self.stack.last_mut() { + if let Some(next) = last.next() { + result = Some(next); + } else { + // Can not fail because we just borrowed last. + // We just checked that the iterator is empty, so we can safely discard it. + let _ = self.stack.pop().unwrap(); + } + } else { + return None; + } + + if let Some(result) = result { + self.stack.push(result.children.iter_mut()); + return Some(&mut result.operator); + } + } + } +} + +impl Node { + /// Returns an iterator over all nodes in this tree. + pub fn iter(&self) -> impl Iterator { + NodeIter::new(self) + } + + /// Returns a mutable iterator over all operators in this tree. + pub fn iter_operators_mut(&mut self) -> impl Iterator { + OperatorIterMut::new(self) + } +} diff --git a/src/tree/mod.rs b/src/tree/mod.rs new file mode 100644 index 0000000..c8d2248 --- /dev/null +++ b/src/tree/mod.rs @@ -0,0 +1,905 @@ +use crate::Function; +use crate::{token::Token, VariableMap}; + +use crate::{ + error::{Error, Result}, + operator::*, + value::Value, +}; +use std::{ + fmt::{self, Display, Formatter}, + mem, +}; + +// Exclude display module from coverage, as it prints not well-defined prefix notation. +#[cfg(not(tarpaulin_include))] +mod iter; + +/// A node in the operator tree. +/// The operator tree is created by the crate-level `build_operator_tree` method. +/// It can be evaluated for a given context with the `Node::eval` method. +/// +/// The advantage of constructing the operator tree separately from the actual evaluation is that it can be evaluated arbitrarily often with different contexts. +/// +/// # Examples +/// +/// ```rust +/// use evalexpr::*; +/// +/// let mut context = HashMapContext::new(); +/// context.set_value("alpha".into(), 2.into()).unwrap(); // Do proper error handling here +/// let node = build_operator_tree("1 + alpha").unwrap(); // Do proper error handling here +/// assert_eq!(node.eval_with_context(&context), Ok(Value::from(3))); +/// ``` +/// +#[derive(Debug, PartialEq, Clone)] +pub struct Node { + operator: Operator, + children: Vec, +} + +impl Node { + fn new(operator: Operator) -> Self { + Self { + children: Vec::new(), + operator, + } + } + + fn root_node() -> Self { + Self::new(Operator::RootNode) + } + + /// Returns an iterator over all identifiers in this expression. + /// Each occurrence of an identifier is returned separately. + /// + /// # Examples + /// + /// ```rust + /// use evalexpr::*; + /// + /// let tree = build_operator_tree("a + b + c * f()").unwrap(); // Do proper error handling here + /// let mut iter = tree.iter_identifiers(); + /// assert_eq!(iter.next(), Some("a")); + /// assert_eq!(iter.next(), Some("b")); + /// assert_eq!(iter.next(), Some("c")); + /// assert_eq!(iter.next(), Some("f")); + /// assert_eq!(iter.next(), None); + /// ``` + pub fn iter_identifiers(&self) -> impl Iterator { + self.iter().filter_map(|node| match node.operator() { + Operator::VariableIdentifierWrite { identifier } + | Operator::VariableIdentifierRead { identifier } + | Operator::FunctionIdentifier { identifier } => Some(identifier.as_str()), + _ => None, + }) + } + + /// Returns an iterator over all identifiers in this expression, allowing mutation. + /// Each occurrence of an identifier is returned separately. + /// + /// # Examples + /// + /// ```rust + /// use evalexpr::*; + /// + /// let mut tree = build_operator_tree("a + b + c * f()").unwrap(); // Do proper error handling here + /// + /// for identifier in tree.iter_identifiers_mut() { + /// *identifier = String::from("x"); + /// } + /// + /// let mut iter = tree.iter_identifiers(); + /// + /// assert_eq!(iter.next(), Some("x")); + /// assert_eq!(iter.next(), Some("x")); + /// assert_eq!(iter.next(), Some("x")); + /// assert_eq!(iter.next(), Some("x")); + /// assert_eq!(iter.next(), None); + /// ``` + pub fn iter_identifiers_mut(&mut self) -> impl Iterator { + self.iter_operators_mut() + .filter_map(|operator| match operator { + Operator::VariableIdentifierWrite { identifier } + | Operator::VariableIdentifierRead { identifier } + | Operator::FunctionIdentifier { identifier } => Some(identifier), + _ => None, + }) + } + + /// Returns an iterator over all variable identifiers in this expression. + /// Each occurrence of a variable identifier is returned separately. + /// + /// # Examples + /// + /// ```rust + /// use evalexpr::*; + /// + /// let tree = build_operator_tree("a + f(b + c)").unwrap(); // Do proper error handling here + /// let mut iter = tree.iter_variable_identifiers(); + /// assert_eq!(iter.next(), Some("a")); + /// assert_eq!(iter.next(), Some("b")); + /// assert_eq!(iter.next(), Some("c")); + /// assert_eq!(iter.next(), None); + /// ``` + pub fn iter_variable_identifiers(&self) -> impl Iterator { + self.iter().filter_map(|node| match node.operator() { + Operator::VariableIdentifierWrite { identifier } + | Operator::VariableIdentifierRead { identifier } => Some(identifier.as_str()), + _ => None, + }) + } + + /// Returns an iterator over all variable identifiers in this expression, allowing mutation. + /// Each occurrence of a variable identifier is returned separately. + /// + /// # Examples + /// + /// ```rust + /// use evalexpr::*; + /// + /// let mut tree = build_operator_tree("a + b + c * f()").unwrap(); // Do proper error handling here + /// + /// for identifier in tree.iter_variable_identifiers_mut() { + /// *identifier = String::from("x"); + /// } + /// + /// let mut iter = tree.iter_identifiers(); + /// + /// assert_eq!(iter.next(), Some("x")); + /// assert_eq!(iter.next(), Some("x")); + /// assert_eq!(iter.next(), Some("x")); + /// assert_eq!(iter.next(), Some("f")); + /// assert_eq!(iter.next(), None); + /// ``` + pub fn iter_variable_identifiers_mut(&mut self) -> impl Iterator { + self.iter_operators_mut() + .filter_map(|operator| match operator { + Operator::VariableIdentifierWrite { identifier } + | Operator::VariableIdentifierRead { identifier } => Some(identifier), + _ => None, + }) + } + + /// Returns an iterator over all read variable identifiers in this expression. + /// Each occurrence of a variable identifier is returned separately. + /// + /// # Examples + /// + /// ```rust + /// use evalexpr::*; + /// + /// let tree = build_operator_tree("d = a + f(b + c)").unwrap(); // Do proper error handling here + /// let mut iter = tree.iter_read_variable_identifiers(); + /// assert_eq!(iter.next(), Some("a")); + /// assert_eq!(iter.next(), Some("b")); + /// assert_eq!(iter.next(), Some("c")); + /// assert_eq!(iter.next(), None); + /// ``` + pub fn iter_read_variable_identifiers(&self) -> impl Iterator { + self.iter().filter_map(|node| match node.operator() { + Operator::VariableIdentifierRead { identifier } => Some(identifier.as_str()), + _ => None, + }) + } + + /// Returns an iterator over all read variable identifiers in this expression, allowing mutation. + /// Each occurrence of a variable identifier is returned separately. + /// + /// # Examples + /// + /// ```rust + /// use evalexpr::*; + /// + /// let mut tree = build_operator_tree("d = a + f(b + c)").unwrap(); // Do proper error handling here + /// + /// for identifier in tree.iter_read_variable_identifiers_mut() { + /// *identifier = String::from("x"); + /// } + /// + /// let mut iter = tree.iter_identifiers(); + /// + /// assert_eq!(iter.next(), Some("d")); + /// assert_eq!(iter.next(), Some("x")); + /// assert_eq!(iter.next(), Some("f")); + /// assert_eq!(iter.next(), Some("x")); + /// assert_eq!(iter.next(), Some("x")); + /// assert_eq!(iter.next(), None); + /// ``` + pub fn iter_read_variable_identifiers_mut(&mut self) -> impl Iterator { + self.iter_operators_mut() + .filter_map(|operator| match operator { + Operator::VariableIdentifierRead { identifier } => Some(identifier), + _ => None, + }) + } + + /// Returns an iterator over all write variable identifiers in this expression. + /// Each occurrence of a variable identifier is returned separately. + /// + /// # Examples + /// + /// ```rust + /// use evalexpr::*; + /// + /// let tree = build_operator_tree("d = a + f(b + c)").unwrap(); // Do proper error handling here + /// let mut iter = tree.iter_write_variable_identifiers(); + /// assert_eq!(iter.next(), Some("d")); + /// assert_eq!(iter.next(), None); + /// ``` + pub fn iter_write_variable_identifiers(&self) -> impl Iterator { + self.iter().filter_map(|node| match node.operator() { + Operator::VariableIdentifierWrite { identifier } => Some(identifier.as_str()), + _ => None, + }) + } + + /// Returns an iterator over all write variable identifiers in this expression, allowing mutation. + /// Each occurrence of a variable identifier is returned separately. + /// + /// # Examples + /// + /// ```rust + /// use evalexpr::*; + /// + /// let mut tree = build_operator_tree("d = a + f(b + c)").unwrap(); // Do proper error handling here + /// + /// for identifier in tree.iter_write_variable_identifiers_mut() { + /// *identifier = String::from("x"); + /// } + /// + /// let mut iter = tree.iter_identifiers(); + /// + /// assert_eq!(iter.next(), Some("x")); + /// assert_eq!(iter.next(), Some("a")); + /// assert_eq!(iter.next(), Some("f")); + /// assert_eq!(iter.next(), Some("b")); + /// assert_eq!(iter.next(), Some("c")); + /// assert_eq!(iter.next(), None); + /// ``` + pub fn iter_write_variable_identifiers_mut(&mut self) -> impl Iterator { + self.iter_operators_mut() + .filter_map(|operator| match operator { + Operator::VariableIdentifierWrite { identifier } => Some(identifier), + _ => None, + }) + } + + /// Returns an iterator over all function identifiers in this expression. + /// Each occurrence of a function identifier is returned separately. + /// + /// # Examples + /// + /// ```rust + /// use evalexpr::*; + /// + /// let tree = build_operator_tree("a + f(b + c)").unwrap(); // Do proper error handling here + /// let mut iter = tree.iter_function_identifiers(); + /// assert_eq!(iter.next(), Some("f")); + /// assert_eq!(iter.next(), None); + /// ``` + pub fn iter_function_identifiers(&self) -> impl Iterator { + self.iter().filter_map(|node| match node.operator() { + Operator::FunctionIdentifier { identifier } => Some(identifier.as_str()), + _ => None, + }) + } + + /// Returns an iterator over all function identifiers in this expression, allowing mutation. + /// Each occurrence of a variable identifier is returned separately. + /// + /// # Examples + /// + /// ```rust + /// use evalexpr::*; + /// + /// let mut tree = build_operator_tree("d = a + f(b + c)").unwrap(); // Do proper error handling here + /// + /// for identifier in tree.iter_function_identifiers_mut() { + /// *identifier = String::from("x"); + /// } + /// + /// let mut iter = tree.iter_identifiers(); + /// + /// assert_eq!(iter.next(), Some("d")); + /// assert_eq!(iter.next(), Some("a")); + /// assert_eq!(iter.next(), Some("x")); + /// assert_eq!(iter.next(), Some("b")); + /// assert_eq!(iter.next(), Some("c")); + /// assert_eq!(iter.next(), None); + /// ``` + pub fn iter_function_identifiers_mut(&mut self) -> impl Iterator { + self.iter_operators_mut() + .filter_map(|operator| match operator { + Operator::FunctionIdentifier { identifier } => Some(identifier), + _ => None, + }) + } + + /// Evaluates the operator tree rooted at this node with the given context. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_with_context(&self, context: &VariableMap) -> Result { + let mut arguments = Vec::new(); + for child in self.children() { + arguments.push(child.eval_with_context(context)?); + } + self.operator().eval(&arguments, context) + } + + /// Evaluates the operator tree rooted at this node with the given mutable context. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_with_context_mut(&self, context: &mut VariableMap) -> Result { + let mut arguments = Vec::new(); + for child in self.children() { + arguments.push(child.eval_with_context_mut(context)?); + } + self.operator().eval_mut(&arguments, context) + } + + /// Evaluates the operator tree rooted at this node. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval(&self) -> Result { + self.eval_with_context_mut(&mut VariableMap::new()) + } + + /// Evaluates the operator tree rooted at this node into a string with an the given context. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_string_with_context(&self, context: &VariableMap) -> Result { + match self.eval_with_context(context) { + Ok(Value::String(string)) => Ok(string), + Ok(value) => Err(Error::expected_string(value)), + Err(error) => Err(error), + } + } + + /// Evaluates the operator tree rooted at this node into a float with an the given context. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_float_with_context(&self, context: &VariableMap) -> Result { + match self.eval_with_context(context) { + Ok(Value::Float(float)) => Ok(float), + Ok(value) => Err(Error::expected_float(value)), + Err(error) => Err(error), + } + } + + /// Evaluates the operator tree rooted at this node into an integer with an the given context. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_int_with_context(&self, context: &VariableMap) -> Result { + match self.eval_with_context(context) { + Ok(Value::Integer(int)) => Ok(int), + Ok(value) => Err(Error::expected_int(value)), + Err(error) => Err(error), + } + } + + /// Evaluates the operator tree rooted at this node into a float with an the given context. + /// If the result of the expression is an integer, it is silently converted into a float. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_number_with_context(&self, context: &VariableMap) -> Result { + match self.eval_with_context(context) { + Ok(Value::Integer(int)) => Ok(int as f64), + Ok(Value::Float(float)) => Ok(float), + Ok(value) => Err(Error::expected_number(value)), + Err(error) => Err(error), + } + } + + /// Evaluates the operator tree rooted at this node into a boolean with an the given context. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_boolean_with_context(&self, context: &VariableMap) -> Result { + match self.eval_with_context(context) { + Ok(Value::Boolean(boolean)) => Ok(boolean), + Ok(value) => Err(Error::expected_boolean(value)), + Err(error) => Err(error), + } + } + + /// Evaluates the operator tree rooted at this node into a tuple with an the given context. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_tuple_with_context(&self, context: &VariableMap) -> Result> { + match self.eval_with_context(context) { + Ok(Value::List(tuple)) => Ok(tuple), + Ok(value) => Err(Error::expected_list(value)), + Err(error) => Err(error), + } + } + + /// Evaluates the operator tree rooted at this node into an empty value with an the given context. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_empty_with_context(&self, context: &VariableMap) -> Result<()> { + match self.eval_with_context(context) { + Ok(Value::Empty) => Ok(()), + Ok(value) => Err(Error::expected_empty(value)), + Err(error) => Err(error), + } + } + + /// Evaluates the operator tree rooted at this node into a string with an the given mutable context. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_string_with_context_mut(&self, context: &mut VariableMap) -> Result { + match self.eval_with_context_mut(context) { + Ok(Value::String(string)) => Ok(string), + Ok(value) => Err(Error::expected_string(value)), + Err(error) => Err(error), + } + } + + /// Evaluates the operator tree rooted at this node into a float with an the given mutable context. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_float_with_context_mut(&self, context: &mut VariableMap) -> Result { + match self.eval_with_context_mut(context) { + Ok(Value::Float(float)) => Ok(float), + Ok(value) => Err(Error::expected_float(value)), + Err(error) => Err(error), + } + } + + /// Evaluates the operator tree rooted at this node into an integer with an the given mutable context. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_int_with_context_mut(&self, context: &mut VariableMap) -> Result { + match self.eval_with_context_mut(context) { + Ok(Value::Integer(int)) => Ok(int), + Ok(value) => Err(Error::expected_int(value)), + Err(error) => Err(error), + } + } + + /// Evaluates the operator tree rooted at this node into a float with an the given mutable context. + /// If the result of the expression is an integer, it is silently converted into a float. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_number_with_context_mut(&self, context: &mut VariableMap) -> Result { + match self.eval_with_context_mut(context) { + Ok(Value::Integer(int)) => Ok(int as f64), + Ok(Value::Float(float)) => Ok(float), + Ok(value) => Err(Error::expected_number(value)), + Err(error) => Err(error), + } + } + + /// Evaluates the operator tree rooted at this node into a boolean with an the given mutable context. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_boolean_with_context_mut(&self, context: &mut VariableMap) -> Result { + match self.eval_with_context_mut(context) { + Ok(Value::Boolean(boolean)) => Ok(boolean), + Ok(value) => Err(Error::expected_boolean(value)), + Err(error) => Err(error), + } + } + + /// Evaluates the operator tree rooted at this node into a tuple with an the given mutable context. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_tuple_with_context_mut(&self, context: &mut VariableMap) -> Result> { + match self.eval_with_context_mut(context) { + Ok(Value::List(tuple)) => Ok(tuple), + Ok(value) => Err(Error::expected_list(value)), + Err(error) => Err(error), + } + } + + /// Evaluates the operator tree rooted at this node into an empty value with an the given mutable context. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_empty_with_context_mut(&self, context: &mut VariableMap) -> Result<()> { + match self.eval_with_context_mut(context) { + Ok(Value::Empty) => Ok(()), + Ok(value) => Err(Error::expected_empty(value)), + Err(error) => Err(error), + } + } + + /// Evaluates the operator tree rooted at this node into a string. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_string(&self) -> Result { + self.eval_string_with_context_mut(&mut VariableMap::new()) + } + + /// Evaluates the operator tree rooted at this node into a float. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_float(&self) -> Result { + self.eval_float_with_context_mut(&mut VariableMap::new()) + } + + /// Evaluates the operator tree rooted at this node into an integer. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_int(&self) -> Result { + self.eval_int_with_context_mut(&mut VariableMap::new()) + } + + /// Evaluates the operator tree rooted at this node into a float. + /// If the result of the expression is an integer, it is silently converted into a float. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_number(&self) -> Result { + self.eval_number_with_context_mut(&mut VariableMap::new()) + } + + /// Evaluates the operator tree rooted at this node into a boolean. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_boolean(&self) -> Result { + self.eval_boolean_with_context_mut(&mut VariableMap::new()) + } + + /// Evaluates the operator tree rooted at this node into a tuple. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_tuple(&self) -> Result> { + self.eval_tuple_with_context_mut(&mut VariableMap::new()) + } + + /// Evaluates the operator tree rooted at this node into an empty value. + /// + /// Fails, if one of the operators in the expression tree fails. + pub fn eval_empty(&self) -> Result<()> { + self.eval_empty_with_context_mut(&mut VariableMap::new()) + } + + /// Returns the children of this node as a slice. + pub fn children(&self) -> &[Node] { + &self.children + } + + /// Returns the operator associated with this node. + pub fn operator(&self) -> &Operator { + &self.operator + } + + /// Returns a mutable reference to the vector containing the children of this node. + /// + /// WARNING: Writing to this might have unexpected results, as some operators require certain amounts and types of arguments. + pub fn children_mut(&mut self) -> &mut Vec { + &mut self.children + } + + /// Returns a mutable reference to the operator associated with this node. + /// + /// WARNING: Writing to this might have unexpected results, as some operators require different amounts and types of arguments. + pub fn operator_mut(&mut self) -> &mut Operator { + &mut self.operator + } + + fn has_enough_children(&self) -> bool { + Some(self.children().len()) == self.operator().max_argument_amount() + } + + fn has_too_many_children(&self) -> bool { + if let Some(max_argument_amount) = self.operator().max_argument_amount() { + self.children().len() > max_argument_amount + } else { + false + } + } + + fn insert_back_prioritized(&mut self, node: Node, is_root_node: bool) -> Result<()> { + // println!( + // "Inserting {:?} into {:?}, is_root_node = {is_root_node}", + // node.operator(), + // self.operator() + // ); + // println!("Self is {:?}", self); + if self.operator().precedence() < node.operator().precedence() || node.operator().is_unary() || is_root_node + // Right-to-left chaining + || (self.operator().precedence() == node.operator().precedence() && !self.operator().is_left_to_right() && !node.operator().is_left_to_right()) + { + if self.operator().is_leaf() { + Err(Error::AppendedToLeafNode(node)) + } else if self.has_enough_children() { + // Unwrap cannot fail because is_leaf being false and has_enough_children being true implies that the operator wants and has at least one child + let last_child_operator = self.children.last().unwrap().operator(); + + if last_child_operator.precedence() + < node.operator().precedence() || node.operator().is_unary() + // Right-to-left chaining + || (last_child_operator.precedence() + == node.operator().precedence() && !last_child_operator.is_left_to_right() && !node.operator().is_left_to_right()) + { + // println!( + // "Recursing into {:?}", + // self.children.last().unwrap().operator() + // ); + // Unwrap cannot fail because is_leaf being false and has_enough_children being true implies that the operator wants and has at least one child + self.children + .last_mut() + .unwrap() + .insert_back_prioritized(node, false) + } else { + // println!("Rotating"); + if node.operator().is_leaf() { + return Err(Error::AppendedToLeafNode(node)); + } + + // Unwrap cannot fail because is_leaf being false and has_enough_children being true implies that the operator wants and has at least one child + let last_child = self.children.pop().unwrap(); + // Root nodes have at most one child + // TODO I am not sure if this is the correct error + if self.operator() == &Operator::RootNode && !self.children().is_empty() { + return Err(Error::MissingOperatorOutsideOfBrace); + } + // Do not insert root nodes into root nodes. + // TODO I am not sure if this is the correct error + if self.operator() == &Operator::RootNode + && node.operator() == &Operator::RootNode + { + return Err(Error::MissingOperatorOutsideOfBrace); + } + self.children.push(node); + let node = self.children.last_mut().unwrap(); + + // Root nodes have at most one child + // TODO I am not sure if this is the correct error + if node.operator() == &Operator::RootNode && !node.children().is_empty() { + return Err(Error::MissingOperatorOutsideOfBrace); + } + // Do not insert root nodes into root nodes. + // TODO I am not sure if this is the correct error + if node.operator() == &Operator::RootNode + && last_child.operator() == &Operator::RootNode + { + return Err(Error::MissingOperatorOutsideOfBrace); + } + node.children.push(last_child); + Ok(()) + } + } else { + // println!("Inserting as specified"); + self.children.push(node); + Ok(()) + } + } else { + Err(Error::PrecedenceViolation) + } + } +} + +impl Display for Node { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + self.operator.fmt(f)?; + for child in self.children() { + write!(f, " {}", child)?; + } + Ok(()) + } +} + +fn collapse_root_stack_to( + root_stack: &mut Vec, + mut root: Node, + collapse_goal: &Node, +) -> Result { + loop { + if let Some(mut potential_higher_root) = root_stack.pop() { + // TODO I'm not sure about this >, as I have no example for different sequence operators with the same precedence + if potential_higher_root.operator().precedence() > collapse_goal.operator().precedence() + { + potential_higher_root.children.push(root); + root = potential_higher_root; + } else { + root_stack.push(potential_higher_root); + break; + } + } else { + // This is the only way the topmost root node could have been removed + return Err(Error::UnmatchedRBrace); + } + } + + Ok(root) +} + +fn collapse_all_sequences(root_stack: &mut Vec) -> Result<()> { + // println!("Collapsing all sequences"); + // println!("Initial root stack is: {:?}", root_stack); + let mut root = if let Some(root) = root_stack.pop() { + root + } else { + return Err(Error::UnmatchedRBrace); + }; + + loop { + // println!("Root is: {:?}", root); + if root.operator() == &Operator::RootNode { + // This should fire if parsing something like `4(5)` + if root.has_too_many_children() { + return Err(Error::MissingOperatorOutsideOfBrace); + } + + root_stack.push(root); + break; + } + + if let Some(mut potential_higher_root) = root_stack.pop() { + if root.operator().is_sequence() { + potential_higher_root.children.push(root); + root = potential_higher_root; + } else { + // This should fire if parsing something like `4(5)` + if root.has_too_many_children() { + return Err(Error::MissingOperatorOutsideOfBrace); + } + + root_stack.push(potential_higher_root); + root_stack.push(root); + break; + } + } else { + // This is the only way the topmost root node could have been removed + return Err(Error::UnmatchedRBrace); + } + } + + // println!("Root stack after collapsing all sequences is: {:?}", root_stack); + Ok(()) +} + +pub(crate) fn tokens_to_operator_tree(tokens: Vec) -> Result { + let mut root_stack = vec![Node::root_node()]; + let mut last_token_is_rightsided_value = false; + let mut token_iter = tokens.iter().peekable(); + + while let Some(token) = token_iter.next().cloned() { + let next = token_iter.peek().cloned(); + + let node = match token.clone() { + Token::Plus => Some(Node::new(Operator::Add)), + Token::Minus => { + if last_token_is_rightsided_value { + Some(Node::new(Operator::Sub)) + } else { + Some(Node::new(Operator::Neg)) + } + } + Token::Star => Some(Node::new(Operator::Mul)), + Token::Slash => Some(Node::new(Operator::Div)), + Token::Percent => Some(Node::new(Operator::Mod)), + Token::Hat => Some(Node::new(Operator::Exp)), + + Token::Eq => Some(Node::new(Operator::Eq)), + Token::Neq => Some(Node::new(Operator::Neq)), + Token::Gt => Some(Node::new(Operator::Gt)), + Token::Lt => Some(Node::new(Operator::Lt)), + Token::Geq => Some(Node::new(Operator::Geq)), + Token::Leq => Some(Node::new(Operator::Leq)), + Token::And => Some(Node::new(Operator::And)), + Token::Or => Some(Node::new(Operator::Or)), + Token::Not => Some(Node::new(Operator::Not)), + + Token::LBrace => { + root_stack.push(Node::root_node()); + None + } + Token::RBrace => { + if root_stack.len() <= 1 { + return Err(Error::UnmatchedRBrace); + } else { + collapse_all_sequences(&mut root_stack)?; + root_stack.pop() + } + } + + Token::Assign => Some(Node::new(Operator::Assign)), + Token::PlusAssign => Some(Node::new(Operator::AddAssign)), + Token::MinusAssign => Some(Node::new(Operator::SubAssign)), + Token::StarAssign => Some(Node::new(Operator::MulAssign)), + Token::SlashAssign => Some(Node::new(Operator::DivAssign)), + Token::PercentAssign => Some(Node::new(Operator::ModAssign)), + Token::HatAssign => Some(Node::new(Operator::ExpAssign)), + Token::AndAssign => Some(Node::new(Operator::AndAssign)), + Token::OrAssign => Some(Node::new(Operator::OrAssign)), + + Token::Comma => Some(Node::new(Operator::Tuple)), + Token::Semicolon => Some(Node::new(Operator::Chain)), + Token::Identifier(identifier) => { + let mut result = Some(Node::new(Operator::variable_identifier_read( + identifier.clone(), + ))); + if let Some(next) = next { + if next.is_assignment() { + result = Some(Node::new(Operator::variable_identifier_write( + identifier.clone(), + ))); + } else if next.is_leftsided_value() { + result = Some(Node::new(Operator::function_identifier(identifier))); + } + } + result + } + Token::Float(float) => Some(Node::new(Operator::value(Value::Float(float)))), + Token::Int(int) => Some(Node::new(Operator::value(Value::Integer(int)))), + Token::Boolean(boolean) => Some(Node::new(Operator::value(Value::Boolean(boolean)))), + Token::String(string) => Some(Node::new(Operator::value(Value::String(string)))), + Token::Function(string) => Some(Node::new(Operator::value(Value::Function( + Function::new(&string), + )))), + Token::Yield(_, _) => todo!(), + }; + + if let Some(mut node) = node { + // Need to pop and then repush here, because Rust 1.33.0 cannot release the mutable borrow of root_stack before the end of this complete if-statement + if let Some(mut root) = root_stack.pop() { + if node.operator().is_sequence() { + // println!("Found a sequence operator"); + // println!("Stack before sequence operation: {:?}, {:?}", root_stack, root); + // If root.operator() and node.operator() are of the same variant, ... + if mem::discriminant(root.operator()) == mem::discriminant(node.operator()) { + // ... we create a new root node for the next expression in the sequence + root.children.push(Node::root_node()); + root_stack.push(root); + } else if root.operator() == &Operator::RootNode { + // If the current root is an actual root node, we start a new sequence + node.children.push(root); + node.children.push(Node::root_node()); + root_stack.push(Node::root_node()); + root_stack.push(node); + } else { + // Otherwise, we combine the sequences based on their precedences + // TODO I'm not sure about this <, as I have no example for different sequence operators with the same precedence + if root.operator().precedence() < node.operator().precedence() { + // If the new sequence has a higher precedence, it is part of the last element of the current root sequence + if let Some(last_root_child) = root.children.pop() { + node.children.push(last_root_child); + node.children.push(Node::root_node()); + root_stack.push(root); + root_stack.push(node); + } else { + // Once a sequence has been pushed on top of the stack, it also gets a child + unreachable!() + } + } else { + // If the new sequence doesn't have a higher precedence, then all sequences with a higher precedence are collapsed below this one + root = collapse_root_stack_to(&mut root_stack, root, &node)?; + node.children.push(root); + root_stack.push(node); + } + } + // println!("Stack after sequence operation: {:?}", root_stack); + } else if root.operator().is_sequence() { + if let Some(mut last_root_child) = root.children.pop() { + last_root_child.insert_back_prioritized(node, true)?; + root.children.push(last_root_child); + root_stack.push(root); + } else { + // Once a sequence has been pushed on top of the stack, it also gets a child + unreachable!() + } + } else { + root.insert_back_prioritized(node, true)?; + root_stack.push(root); + } + } else { + return Err(Error::UnmatchedRBrace); + } + } + + last_token_is_rightsided_value = token.is_rightsided_value(); + } + + // In the end, all sequences are implicitly terminated + collapse_all_sequences(&mut root_stack)?; + + if root_stack.len() > 1 { + Err(Error::UnmatchedLBrace) + } else if let Some(root) = root_stack.pop() { + Ok(root) + } else { + Err(Error::UnmatchedRBrace) + } +} diff --git a/src/value/function.rs b/src/value/function.rs new file mode 100644 index 0000000..50a0f36 --- /dev/null +++ b/src/value/function.rs @@ -0,0 +1,28 @@ +use std::fmt::{self, Display, Formatter}; + +use serde::{Deserialize, Serialize}; + +use crate::{eval, eval_with_context, Result, Value, VariableMap}; + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct Function(String); + +impl Function { + pub fn new(body: &str) -> Self { + Function(body.to_string()) + } + + pub fn run(&self) -> Result { + eval(&self.0) + } + + pub fn run_with_context(&self, context: &mut VariableMap) -> Result { + eval_with_context(&self.0, context) + } +} + +impl Display for Function { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0) + } +} diff --git a/src/value/iter.rs b/src/value/iter.rs new file mode 100644 index 0000000..1bc9e3f --- /dev/null +++ b/src/value/iter.rs @@ -0,0 +1,21 @@ +use crate::Value; + +pub struct Iter(Value); + +impl IntoIterator for Value { + type Item = Value; + + type IntoIter = Iter; + + fn into_iter(self) -> Self::IntoIter { + Iter(self) + } +} + +impl Iterator for Iter { + type Item = Value; + + fn next(&mut self) -> Option { + todo!() + } +} diff --git a/src/value/mod.rs b/src/value/mod.rs new file mode 100644 index 0000000..1e5692a --- /dev/null +++ b/src/value/mod.rs @@ -0,0 +1,731 @@ +use crate::{ + error::{Error, Result}, + Function, Table, Time, ValueType, VariableMap, +}; + +use json::JsonValue; +use serde::{ + de::{MapAccess, SeqAccess, Visitor}, + ser::SerializeTuple, + Deserialize, Serialize, Serializer, +}; + +use std::{ + cmp::Ordering, + convert::TryFrom, + fmt::{self, Display, Formatter}, + marker::PhantomData, +}; + +pub mod function; +pub mod iter; +pub mod table; +pub mod time; +pub mod value_type; +pub mod variable_map; + +/// Whale value representation. +/// +/// Every whale variable has a key and a Value. Variables are represented by +/// storing them in a VariableMap. This means the map of variables is itself a +/// value that can be treated as any other. +#[derive(Clone, Debug, PartialEq, Default)] +pub enum Value { + String(String), + Float(f64), + Integer(i64), + Boolean(bool), + List(Vec), + Map(VariableMap), + Table(Table), + Time(Time), + Function(Function), + #[default] + Empty, +} + +impl Value { + pub fn value_type(&self) -> ValueType { + ValueType::from(self) + } + + pub fn is_table(&self) -> bool { + matches!(self, Value::Table(_)) + } + + pub fn is_string(&self) -> bool { + matches!(self, Value::String(_)) + } + + pub fn is_integer(&self) -> bool { + matches!(self, Value::Integer(_)) + } + + pub fn is_float(&self) -> bool { + matches!(self, Value::Float(_)) + } + + pub fn is_number(&self) -> bool { + matches!(self, Value::Integer(_) | Value::Float(_)) + } + + pub fn is_boolean(&self) -> bool { + matches!(self, Value::Boolean(_)) + } + + pub fn is_list(&self) -> bool { + matches!(self, Value::List(_)) + } + + pub fn is_empty(&self) -> bool { + matches!(self, Value::Empty) + } + + pub fn is_map(&self) -> bool { + matches!(self, Value::Map(_)) + } + + pub fn is_function(&self) -> bool { + matches!(self, Value::Map(_)) + } + + /// Borrows the value stored in `self` as `String`, or returns `Err` if `self` is not a `Value::String`. + pub fn as_string(&self) -> Result<&String> { + match self { + Value::String(string) => Ok(string), + value => Err(Error::expected_string(value.clone())), + } + } + + /// Copies the value stored in `self` as `i64`, or returns `Err` if `self` is not a `Value::Int`. + pub fn as_int(&self) -> Result { + match self { + Value::Integer(i) => Ok(*i), + value => Err(Error::expected_int(value.clone())), + } + } + + /// Copies the value stored in `self` as `f64`, or returns `Err` if `self` is not a `Value::Float`. + pub fn as_float(&self) -> Result { + match self { + Value::Float(f) => Ok(*f), + value => Err(Error::expected_float(value.clone())), + } + } + + /// Copies the value stored in `self` as `f64`, or returns `Err` if `self` is not a `Value::Float` or `Value::Int`. + /// Note that this method silently converts `i64` to `f64`, if `self` is a `Value::Int`. + pub fn as_number(&self) -> Result { + match self { + Value::Float(f) => Ok(*f), + Value::Integer(i) => Ok(*i as f64), + value => Err(Error::expected_number(value.clone())), + } + } + + /// Copies the value stored in `self` as `bool`, or returns `Err` if `self` is not a `Value::Boolean`. + pub fn as_boolean(&self) -> Result { + match self { + Value::Boolean(boolean) => Ok(*boolean), + value => Err(Error::expected_boolean(value.clone())), + } + } + + /// Borrows the value stored in `self` as `Vec`, or returns `Err` if `self` is not a `Value::List`. + pub fn as_list(&self) -> Result<&Vec> { + match self { + Value::List(list) => Ok(list), + value => Err(Error::expected_list(value.clone())), + } + } + + /// Borrows the value stored in `self` as `Vec`, or returns `Err` if `self` is not a `Value::List`. + pub fn into_inner_list(self) -> Result> { + match self { + Value::List(list) => Ok(list), + value => Err(Error::expected_list(value.clone())), + } + } + + /// Borrows the value stored in `self` as `Vec` or returns `Err` if `self` is not a `Value::Map` of the required length. + pub fn as_fixed_len_list(&self, len: usize) -> Result<&Vec> { + match self { + Value::List(tuple) => { + if tuple.len() == len { + Ok(tuple) + } else { + Err(Error::expected_fixed_len_list(len, self.clone())) + } + } + value => Err(Error::expected_list(value.clone())), + } + } + + /// Borrows the value stored in `self` as `Vec`, or returns `Err` if `self` is not a `Value::Map`. + pub fn as_map(&self) -> Result<&VariableMap> { + match self { + Value::Map(map) => Ok(map), + value => Err(Error::expected_map(value.clone())), + } + } + + /// Borrows the value stored in `self` as `Vec`, or returns `Err` if `self` is not a `Value::Table`. + pub fn as_table(&self) -> Result<&Table> { + match self { + Value::Table(table) => Ok(table), + value => Err(Error::expected_table(value.clone())), + } + } + + /// Borrows the value stored in `self` as `Function`, or returns `Err` if + /// `self` is not a `Value::Function`. + pub fn as_function(&self) -> Result<&Function> { + match self { + Value::Function(function) => Ok(function), + value => Err(Error::expected_function(value.clone())), + } + } + + /// Borrows the value stored in `self` as `Time`, or returns `Err` if + /// `self` is not a `Value::Time`. + pub fn as_time(&self) -> Result<&Time> { + match self { + Value::Time(time) => Ok(time), + value => Err(Error::expected_function(value.clone())), + } + } + + /// Returns `()`, or returns`Err` if `self` is not a `Value::Tuple`. + pub fn as_empty(&self) -> Result<()> { + match self { + Value::Empty => Ok(()), + value => Err(Error::expected_empty(value.clone())), + } + } + + /// Returns an owned table, either by cloning or converting the inner value.. + pub fn to_table(&self) -> Result { + match self { + Value::Table(table) => Ok(table.clone()), + Value::List(list) => Ok(Table::from(list)), + Value::Map(map) => Ok(Table::from(map)), + value => Err(Error::expected_table(value.clone())), + } + } +} + +impl Eq for Value {} + +impl PartialOrd for Value { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Value { + fn cmp(&self, other: &Self) -> Ordering { + match (self, other) { + (Value::String(left), Value::String(right)) => left.cmp(right), + (Value::String(_), _) => Ordering::Greater, + (Value::Integer(left), Value::Integer(right)) => left.cmp(right), + (Value::Integer(_), _) => Ordering::Greater, + (Value::Boolean(left), Value::Boolean(right)) => left.cmp(right), + (Value::Boolean(_), _) => Ordering::Greater, + (Value::Float(left), Value::Float(right)) => left.total_cmp(right), + (Value::Float(_), _) => Ordering::Greater, + (Value::List(left), Value::List(right)) => left.cmp(right), + (Value::List(_), _) => Ordering::Greater, + (Value::Map(left), Value::Map(right)) => left.cmp(right), + (Value::Map(_), _) => Ordering::Greater, + (Value::Table(left), Value::Table(right)) => left.cmp(right), + (Value::Table(_), _) => Ordering::Greater, + (Value::Function(left), Value::Function(right)) => left.cmp(right), + (Value::Function(_), _) => Ordering::Greater, + (Value::Time(left), Value::Time(right)) => left.cmp(right), + (Value::Time(_), _) => Ordering::Greater, + (Value::Empty, Value::Empty) => Ordering::Equal, + (Value::Empty, _) => Ordering::Less, + } + } +} + +impl Serialize for Value { + fn serialize(&self, serializer: S) -> std::result::Result + where + S: Serializer, + { + match self { + Value::String(inner) => serializer.serialize_str(inner), + Value::Float(inner) => serializer.serialize_f64(*inner), + Value::Integer(inner) => serializer.serialize_i64(*inner), + Value::Boolean(inner) => serializer.serialize_bool(*inner), + Value::List(inner) => { + let mut tuple = serializer.serialize_tuple(inner.len())?; + + for value in inner { + tuple.serialize_element(value)?; + } + + tuple.end() + } + Value::Empty => todo!(), + Value::Map(inner) => inner.serialize(serializer), + Value::Table(inner) => inner.serialize(serializer), + Value::Function(inner) => inner.serialize(serializer), + Value::Time(inner) => inner.serialize(serializer), + } + } +} + +impl Display for Value { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match self { + Value::String(string) => write!(f, "{string}"), + Value::Float(float) => write!(f, "{}", float), + Value::Integer(int) => write!(f, "{}", int), + Value::Boolean(boolean) => write!(f, "{}", boolean), + Value::Empty => write!(f, "()"), + Value::List(list) => Table::from(list).fmt(f), + Value::Map(map) => write!(f, "{map}"), + Value::Table(table) => write!(f, "{table}"), + Value::Function(function) => write!(f, "{function}"), + Value::Time(time) => write!(f, "{time}"), + } + } +} + +impl From for Value { + fn from(string: String) -> Self { + Value::String(string) + } +} + +impl From<&str> for Value { + fn from(string: &str) -> Self { + Value::String(string.to_string()) + } +} + +impl From for Value { + fn from(float: f64) -> Self { + Value::Float(float) + } +} + +impl From for Value { + fn from(int: i64) -> Self { + Value::Integer(int) + } +} + +impl From for Value { + fn from(boolean: bool) -> Self { + Value::Boolean(boolean) + } +} + +impl From> for Value { + fn from(tuple: Vec) -> Self { + Value::List(tuple) + } +} + +impl From for Result { + fn from(value: Value) -> Self { + Ok(value) + } +} + +impl From<()> for Value { + fn from(_: ()) -> Self { + Value::Empty + } +} + +impl TryFrom for Value { + type Error = Error; + + fn try_from(json_value: JsonValue) -> Result { + use JsonValue::*; + + match json_value { + Null => Ok(Value::Empty), + Short(short) => Ok(Value::String(short.to_string())), + String(string) => Ok(Value::String(string)), + Number(number) => Ok(Value::Float(f64::from(number))), + Boolean(boolean) => Ok(Value::Boolean(boolean)), + Object(object) => { + let mut map = VariableMap::new(); + + for (key, node_value) in object.iter() { + let value = Value::try_from(node_value)?; + + map.set_value(key, value)?; + } + + Ok(Value::Map(map)) + } + Array(array) => { + let mut list = Vec::new(); + + for json_value in array { + let value = Value::try_from(json_value)?; + + list.push(value); + } + + Ok(Value::List(list)) + } + } + } +} + +impl TryFrom<&JsonValue> for Value { + type Error = Error; + + fn try_from(json_value: &JsonValue) -> Result { + use JsonValue::*; + + match json_value { + Null => Ok(Value::Empty), + Short(short) => Ok(Value::String(short.to_string())), + String(string) => Ok(Value::String(string.clone())), + Number(number) => Ok(Value::Float(f64::from(*number))), + Boolean(boolean) => Ok(Value::Boolean(*boolean)), + Object(object) => { + let mut map = VariableMap::new(); + + for (key, node_value) in object.iter() { + let value = Value::try_from(node_value)?; + + map.set_value(key, value)?; + } + + Ok(Value::Map(map)) + } + Array(array) => { + let mut list = Vec::new(); + + for json_value in array { + let value = Value::try_from(json_value)?; + + list.push(value); + } + + Ok(Value::List(list)) + } + } + } +} + +impl TryFrom for String { + type Error = Error; + + fn try_from(value: Value) -> std::result::Result { + if let Value::String(value) = value { + Ok(value) + } else { + Err(Error::ExpectedString { actual: value }) + } + } +} + +impl TryFrom for f64 { + type Error = Error; + + fn try_from(value: Value) -> std::result::Result { + if let Value::Float(value) = value { + Ok(value) + } else { + Err(Error::ExpectedFloat { actual: value }) + } + } +} + +impl TryFrom for i64 { + type Error = Error; + + fn try_from(value: Value) -> std::result::Result { + if let Value::Integer(value) = value { + Ok(value) + } else { + Err(Error::ExpectedInt { actual: value }) + } + } +} + +impl TryFrom for bool { + type Error = Error; + + fn try_from(value: Value) -> std::result::Result { + if let Value::Boolean(value) = value { + Ok(value) + } else { + Err(Error::ExpectedBoolean { actual: value }) + } + } +} + +struct ValueVisitor { + marker: PhantomData Value>, +} + +impl ValueVisitor { + fn new() -> Self { + ValueVisitor { + marker: PhantomData, + } + } +} + +impl<'de> Visitor<'de> for ValueVisitor { + type Value = Value; + + fn expecting(&self, formatter: &mut Formatter) -> fmt::Result { + formatter.write_str("Any valid whale data.") + } + + fn visit_bool(self, v: bool) -> std::result::Result + where + E: serde::de::Error, + { + Ok(Value::Boolean(v)) + } + + fn visit_i8(self, v: i8) -> std::result::Result + where + E: serde::de::Error, + { + self.visit_i64(v as i64) + } + + fn visit_i16(self, v: i16) -> std::result::Result + where + E: serde::de::Error, + { + self.visit_i64(v as i64) + } + + fn visit_i32(self, v: i32) -> std::result::Result + where + E: serde::de::Error, + { + self.visit_i64(v as i64) + } + + fn visit_i64(self, v: i64) -> std::result::Result + where + E: serde::de::Error, + { + Ok(Value::Integer(v as i64)) + } + + fn visit_i128(self, v: i128) -> std::result::Result + where + E: serde::de::Error, + { + if v > i64::MAX as i128 { + Ok(Value::Integer(i64::MAX)) + } else { + Ok(Value::Integer(v as i64)) + } + } + + fn visit_u8(self, v: u8) -> std::result::Result + where + E: serde::de::Error, + { + self.visit_u64(v as u64) + } + + fn visit_u16(self, v: u16) -> std::result::Result + where + E: serde::de::Error, + { + self.visit_u64(v as u64) + } + + fn visit_u32(self, v: u32) -> std::result::Result + where + E: serde::de::Error, + { + self.visit_u64(v as u64) + } + + fn visit_u64(self, v: u64) -> std::result::Result + where + E: serde::de::Error, + { + self.visit_i64(v as i64) + } + + fn visit_u128(self, v: u128) -> std::result::Result + where + E: serde::de::Error, + { + self.visit_i128(v as i128) + } + + fn visit_f32(self, v: f32) -> std::result::Result + where + E: serde::de::Error, + { + self.visit_f64(v as f64) + } + + fn visit_f64(self, v: f64) -> std::result::Result + where + E: serde::de::Error, + { + Ok(Value::Float(v)) + } + + fn visit_char(self, v: char) -> std::result::Result + where + E: serde::de::Error, + { + self.visit_str(&v.to_string()) + } + + fn visit_str(self, v: &str) -> std::result::Result + where + E: serde::de::Error, + { + Ok(Value::String(v.to_string())) + } + + fn visit_borrowed_str(self, v: &'de str) -> std::result::Result + where + E: serde::de::Error, + { + self.visit_str(v) + } + + fn visit_string(self, v: String) -> std::result::Result + where + E: serde::de::Error, + { + Ok(Value::String(v)) + } + + fn visit_bytes(self, v: &[u8]) -> std::result::Result + where + E: serde::de::Error, + { + let _ = v; + Err(serde::de::Error::invalid_type( + serde::de::Unexpected::Bytes(v), + &self, + )) + } + + fn visit_borrowed_bytes(self, v: &'de [u8]) -> std::result::Result + where + E: serde::de::Error, + { + self.visit_bytes(v) + } + + fn visit_byte_buf(self, v: Vec) -> std::result::Result + where + E: serde::de::Error, + { + self.visit_bytes(&v) + } + + fn visit_none(self) -> std::result::Result + where + E: serde::de::Error, + { + Err(serde::de::Error::invalid_type( + serde::de::Unexpected::Option, + &self, + )) + } + + fn visit_some(self, deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + let _ = deserializer; + Err(serde::de::Error::invalid_type( + serde::de::Unexpected::Option, + &self, + )) + } + + fn visit_unit(self) -> std::result::Result + where + E: serde::de::Error, + { + Err(serde::de::Error::invalid_type( + serde::de::Unexpected::Unit, + &self, + )) + } + + fn visit_newtype_struct(self, deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + let _ = deserializer; + Err(serde::de::Error::invalid_type( + serde::de::Unexpected::NewtypeStruct, + &self, + )) + } + + fn visit_seq(self, mut access: A) -> std::result::Result + where + A: SeqAccess<'de>, + { + let mut list = Vec::new(); + + while let Some(value) = access.next_element()? { + list.push(value); + } + + Ok(Value::List(list)) + } + + fn visit_map(self, mut access: M) -> std::result::Result + where + M: MapAccess<'de>, + { + let mut map = VariableMap::new(); + + while let Some((key, value)) = access.next_entry()? { + map.set_value(key, value) + .expect("Failed to deserialize Value. This is a no-op."); + } + + Ok(Value::Map(map)) + } + + fn visit_enum(self, data: A) -> std::result::Result + where + A: serde::de::EnumAccess<'de>, + { + let _ = data; + Err(serde::de::Error::invalid_type( + serde::de::Unexpected::Enum, + &self, + )) + } + + fn __private_visit_untagged_option(self, _: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + Err(()) + } +} + +impl<'de> Deserialize<'de> for Value { + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + deserializer.deserialize_any(ValueVisitor::new()) + } +} diff --git a/src/value/table.rs b/src/value/table.rs new file mode 100644 index 0000000..65bf261 --- /dev/null +++ b/src/value/table.rs @@ -0,0 +1,353 @@ +use crate::{Error, Result, Value, VariableMap}; +use comfy_table::{Cell, Color, ContentArrangement, Table as ComfyTable}; +use serde::{Deserialize, Serialize}; +use std::{ + cmp::Ordering, + fmt::{self, Display, Formatter}, +}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Table { + header: Vec, + rows: Vec>, + primary_key_index: usize, +} + +impl Table { + pub fn new(column_names: Vec) -> Self { + Table { + header: column_names, + rows: Vec::new(), + primary_key_index: 0, + } + } + + pub fn reserve(&mut self, additional: usize) { + self.rows.reserve(additional); + } + + pub fn column_names(&self) -> &Vec { + &self.header + } + + pub fn rows(&self) -> &Vec> { + &self.rows + } + + pub fn len(&self) -> usize { + self.rows.len() + } + + pub fn is_empty(&self) -> bool { + self.rows.is_empty() + } + + pub fn sort(&mut self) { + self.rows.sort(); + } + + pub fn insert(&mut self, row: Vec) -> Result<()> { + if row.len() != self.header.len() { + return Err(Error::WrongColumnAmount { + expected: self.header.len(), + actual: row.len(), + }); + } + + self.rows.push(row); + + Ok(()) + } + + pub fn remove(&mut self, index: usize) -> Result<()> { + self.rows.remove(index); + + Ok(()) + } + + pub fn get_row(&self, index: usize) -> Option<&Vec> { + self.rows.get(index) + } + + pub fn get(&self, value: &Value) -> Option<&Vec> { + let primary_key = self.column_names().get(self.primary_key_index)?; + + self.get_where(primary_key, value) + } + + pub fn select(&self, column_names: &[String]) -> Table { + let mut new_table = Table::new(column_names.to_vec()); + + for row in &self.rows { + let mut new_row = Vec::new(); + + for (i, value) in row.iter().enumerate() { + let column_name = self.header.get(i).unwrap(); + let new_table_column_index = + new_table + .header + .iter() + .enumerate() + .find_map(|(index, new_column_name)| { + if new_column_name == column_name { + Some(index) + } else { + None + } + }); + + if let Some(index) = new_table_column_index { + while new_row.len() < index + 1 { + new_row.push(Value::Empty); + } + new_row[index] = value.clone(); + } + } + + new_table.insert(new_row).unwrap(); + } + + new_table + } + + pub fn get_where(&self, column_name: &str, expected: &Value) -> Option<&Vec> { + let column_index = self.get_column_index(column_name)?; + + for row in &self.rows { + if let Some(actual) = row.get(column_index) { + if actual == expected { + return Some(row); + } + } + } + + None + } + + pub fn filter(&self, column_name: &str, expected: &Value) -> Option
{ + let mut filtered = Table::new(self.header.clone()); + let column_index = self.get_column_index(column_name)?; + + for row in &self.rows { + let actual = row.get(column_index).unwrap(); + + if actual == expected { + let _ = filtered.insert(row.clone()); + } + } + + Some(filtered) + } + + pub fn get_column_index(&self, column_name: &str) -> Option { + let column_names = &self.header; + for (i, column) in column_names.iter().enumerate() { + if column == column_name { + return Some(i); + } + } + None + } +} + +impl Display for Table { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + let mut table = ComfyTable::new(); + + table + .load_preset("││──├─┼┤│ ┬┴╭╮╰╯") + .set_content_arrangement(ContentArrangement::Dynamic) + .set_header(&self.header); + + for row in &self.rows { + let row = row.iter().map(|value| { + let text = match value { + Value::List(list) => format!("{list:?}"), + Value::Map(map) => format!("Map ({} items)", map.len()), + Value::Table(table) => format!("Table ({} items)", table.len()), + Value::Function(_) => "Function".to_string(), + Value::Empty => "Empty".to_string(), + value => value.to_string(), + }; + + let mut cell = Cell::new(text).bg(Color::Rgb { + r: 40, + g: 40, + b: 40, + }); + + if value.is_string() { + cell = cell.fg(Color::Green); + } + if value.is_integer() { + cell = cell.fg(Color::Blue); + } + if value.is_boolean() { + cell = cell.fg(Color::Red); + } + if value.is_function() { + cell = cell.fg(Color::Cyan); + } + + cell + }); + + table.add_row(row); + } + + if self.header.is_empty() { + table.set_header(["empty"]); + } + + write!(f, "{table}") + } +} + +impl From<&Value> for Table { + fn from(value: &Value) -> Self { + match value { + Value::String(string) => { + let mut table = Table::new(vec!["string".to_string()]); + + table + .insert(vec![Value::String(string.to_string())]) + .unwrap(); + + table + } + Value::Float(float) => { + let mut table = Table::new(vec!["float".to_string()]); + + table.insert(vec![Value::Float(*float)]).unwrap(); + + table + } + Value::Integer(integer) => { + let mut table = Table::new(vec!["integer".to_string()]); + + table.insert(vec![Value::Integer(*integer)]).unwrap(); + + table + } + Value::Boolean(boolean) => { + let mut table = Table::new(vec!["boolean".to_string()]); + + table.insert(vec![Value::Boolean(*boolean)]).unwrap(); + + table + } + Value::List(list) => Self::from(list), + Value::Empty => Table::new(Vec::with_capacity(0)), + Value::Map(map) => Self::from(map), + Value::Table(table) => table.clone(), + Value::Function(function) => { + let mut table = Table::new(vec!["function".to_string()]); + + table + .insert(vec![Value::Function(function.clone())]) + .unwrap(); + + table + } + Value::Time(_) => todo!(), + } + } +} + +impl From<&Vec> for Table { + fn from(list: &Vec) -> Self { + let mut table = Table::new(vec!["index".to_string(), "item".to_string()]); + + for (i, value) in list.iter().enumerate() { + table + .insert(vec![Value::Integer(i as i64), value.clone()]) + .unwrap(); + } + + table + } +} + +impl From<&mut Vec> for Table { + fn from(list: &mut Vec) -> Self { + let mut table = Table::new(vec!["index".to_string(), "item".to_string()]); + + for (i, value) in list.iter().enumerate() { + if let Ok(list) = value.as_list() { + table.insert(list.clone()).unwrap(); + } else { + table + .insert(vec![Value::Integer(i as i64), value.clone()]) + .unwrap(); + } + } + + table + } +} + +impl From for Table { + fn from(map: VariableMap) -> Self { + let keys = map.inner().keys().cloned().collect(); + let values = map.inner().values().cloned().collect(); + let mut table = Table::new(keys); + + table + .insert(values) + .expect("Failed to create Table from Map. This is a no-op."); + + table + } +} + +impl From<&VariableMap> for Table { + fn from(map: &VariableMap) -> Self { + let keys = map.inner().keys().cloned().collect(); + let values = map.inner().values().cloned().collect(); + let mut table = Table::new(keys); + + table + .insert(values) + .expect("Failed to create Table from Map. This is a no-op."); + + table + } +} + +impl From<&mut VariableMap> for Table { + fn from(map: &mut VariableMap) -> Self { + let keys = map.inner().keys().cloned().collect(); + let values = map.inner().values().cloned().collect(); + let mut table = Table::new(keys); + + table + .insert(values) + .expect("Failed to create Table from Map. This is a no-op."); + + table + } +} + +impl Eq for Table {} + +impl PartialEq for Table { + fn eq(&self, other: &Self) -> bool { + if self.header != other.header { + return false; + } + + self.rows == other.rows + } +} + +impl PartialOrd for Table { + fn partial_cmp(&self, other: &Self) -> Option { + self.header.partial_cmp(&other.header) + } +} + +impl Ord for Table { + fn cmp(&self, other: &Self) -> Ordering { + self.header.cmp(&other.header) + } +} diff --git a/src/value/time.rs b/src/value/time.rs new file mode 100644 index 0000000..b6ff386 --- /dev/null +++ b/src/value/time.rs @@ -0,0 +1,88 @@ +use std::{ + fmt::{self, Display, Formatter}, + time::{Instant, SystemTime, UNIX_EPOCH}, +}; + +use chrono::{DateTime, FixedOffset, Local as LocalTime, NaiveDateTime}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Time { + Utc(NaiveDateTime), + Local(DateTime), + Monotonic(Instant), +} + +impl Time { + pub fn utc(instant: Instant) -> Self { + let utc = + NaiveDateTime::from_timestamp_micros(instant.elapsed().as_micros() as i64).unwrap(); + + Time::Utc(utc) + } + + pub fn from_timestamp(microseconds: i64) -> Self { + let utc = NaiveDateTime::from_timestamp_micros(microseconds).unwrap(); + + Time::Utc(utc) + } + + pub fn local(instant: Instant) -> Self { + let local = DateTime::from_local( + NaiveDateTime::from_timestamp_micros(instant.elapsed().as_micros() as i64).unwrap(), + FixedOffset::west_opt(0).unwrap(), + ); + + Time::Local(local) + } + + pub fn monotonic(instant: Instant) -> Self { + Time::Monotonic(instant) + } + + pub fn as_local(&self) -> String { + let date_time = match *self { + Time::Utc(utc) => DateTime::from_utc(utc, FixedOffset::west_opt(0).unwrap()), + Time::Local(local) => local, + Time::Monotonic(instant) => DateTime::from_utc( + NaiveDateTime::from_timestamp_micros(instant.elapsed().as_micros() as i64).unwrap(), + FixedOffset::west_opt(0).unwrap(), + ), + }; + + date_time.to_string() + } +} + +impl Display for Time { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.as_local()) + } +} + +impl Serialize for Time { + fn serialize(&self, _serializer: S) -> Result + where + S: serde::Serializer, + { + todo!() + } +} + +impl<'de> Deserialize<'de> for Time { + fn deserialize(_deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + todo!() + } +} + +impl From for Time { + fn from(value: SystemTime) -> Self { + let timestamp = value.duration_since(UNIX_EPOCH).unwrap().as_micros(); + let naive = NaiveDateTime::from_timestamp_micros(timestamp as i64).unwrap(); + + Time::Utc(naive) + } +} diff --git a/src/value/value_type.rs b/src/value/value_type.rs new file mode 100644 index 0000000..8223b84 --- /dev/null +++ b/src/value/value_type.rs @@ -0,0 +1,86 @@ +use std::fmt::Display; + +use crate::Value; + +/// The type of a `Value`. +#[derive(Clone, Debug)] +pub enum ValueType { + Any, + String, + Float, + Int, + Boolean, + List(Vec), + Empty, + Map, + Table, + Function, + Time, +} + +impl Eq for ValueType {} + +impl PartialEq for ValueType { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (ValueType::Any, _) => true, + (_, ValueType::Any) => true, + (ValueType::String, ValueType::String) => true, + (ValueType::Float, ValueType::Float) => true, + (ValueType::Int, ValueType::Int) => true, + (ValueType::Boolean, ValueType::Boolean) => true, + (ValueType::List(left), ValueType::List(right)) => left == right, + (ValueType::Empty, ValueType::Empty) => true, + (ValueType::Map, ValueType::Map) => true, + (ValueType::Table, ValueType::Table) => true, + (ValueType::Function, ValueType::Function) => true, + (ValueType::Time, ValueType::Time) => true, + _ => false, + } + } +} + +impl Display for ValueType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let text = match &self { + ValueType::Any => "any", + ValueType::String => "string", + ValueType::Float => "float", + ValueType::Int => "integer", + ValueType::Boolean => "boolean", + ValueType::List(_) => "list", + ValueType::Empty => "empty", + ValueType::Map => "map", + ValueType::Table => "table", + ValueType::Function => "function", + ValueType::Time => "time", + }; + + write!(f, "{text}") + } +} + +impl From<&Value> for ValueType { + fn from(value: &Value) -> Self { + match value { + Value::String(_) => ValueType::String, + Value::Float(_) => ValueType::Float, + Value::Integer(_) => ValueType::Int, + Value::Boolean(_) => ValueType::Boolean, + Value::List(list) => { + ValueType::List(list.iter().map(|value| value.value_type()).collect()) + } + Value::Empty => ValueType::Empty, + Value::Map(_) => ValueType::Map, + Value::Table { .. } => ValueType::Table, + Value::Function(_) => ValueType::Function, + Value::Time(_) => ValueType::Time, + } + } +} + +impl From<&mut Value> for ValueType { + fn from(value: &mut Value) -> Self { + From::<&Value>::from(value) + } +} diff --git a/src/value/variable_map.rs b/src/value/variable_map.rs new file mode 100644 index 0000000..841d475 --- /dev/null +++ b/src/value/variable_map.rs @@ -0,0 +1,211 @@ +use serde::{Deserialize, Serialize}; +use std::{ + collections::BTreeMap, + fmt::{self, Display, Formatter}, +}; + +use crate::{value::Value, Error, Result, Table, MACRO_LIST}; + +/// A context that stores its mappings in hash maps. +#[derive(Clone, Debug, PartialEq, PartialOrd, Ord, Eq, Serialize, Deserialize)] +pub struct VariableMap { + variables: BTreeMap, +} + +impl VariableMap { + /// Creates a new instace. + pub fn new() -> Self { + VariableMap { + variables: BTreeMap::new(), + } + } + + pub fn call_function(&self, identifier: &str, argument: &Value) -> Result { + for macro_item in MACRO_LIST { + let valid_input_types = macro_item.info().inputs; + + if identifier == macro_item.info().identifier { + let input_type = argument.value_type(); + + if valid_input_types.contains(&input_type) { + return macro_item.run(argument); + } else { + return Err(Error::MacroArgumentType { + macro_info: macro_item.info(), + actual: argument.clone(), + }); + } + } + } + + for (key, value) in &self.variables { + if identifier == key { + if let Ok(function) = value.as_function() { + let mut context = VariableMap::new(); + + context.set_value("input", argument.clone())?; + + return function.run_with_context(&mut context); + } + } + } + + let mut split = identifier.split(':').rev(); + + if let (Some(function_identifier), Some(variable_identifier)) = (split.next(), split.next()) + { + if function_identifier.contains(':') { + return self.call_function(function_identifier, argument); + } + + if variable_identifier.contains('.') { + let value = self.get_value(variable_identifier)?.unwrap_or(Value::Empty); + + return self.call_function(function_identifier, &value); + } + + if let Some(value) = self.get_value(variable_identifier)? { + if argument.is_empty() { + return self.call_function(function_identifier, &value); + } + + let value_type = value.value_type(); + + let list = Value::List(vec![value, argument.clone()]); + + return self.call_function(function_identifier, &list); + } + } + + Err(Error::FunctionIdentifierNotFound(identifier.to_string())) + } + + pub fn get_value(&self, identifier: &str) -> Result> { + let split = identifier.split_once('.'); + + if let Some((identifier, next_identifier)) = split { + if let Some(value) = self.variables.get(identifier) { + if let Value::Map(map) = value { + map.get_value(next_identifier) + } else { + Err(Error::ExpectedMap { + actual: value.clone(), + }) + } + } else { + Ok(None) + } + } else { + let value = self.variables.get(identifier); + + if let Some(value) = value { + Ok(Some(value.clone())) + } else { + Ok(None) + } + } + } + + pub fn set_value(&mut self, identifier: &str, value: Value) -> Result<()> { + let split = identifier.split_once('.'); + + if let Some((map_name, next_identifier)) = split { + let get_value = self.variables.get_mut(map_name); + + if let Some(map_value) = get_value { + if let Value::Map(map) = map_value { + map.set_value(next_identifier, value) + } else { + Err(Error::ExpectedMap { + actual: map_value.clone(), + }) + } + } else { + let mut new_map = VariableMap::new(); + + new_map.set_value(next_identifier, value)?; + + self.variables + .insert(map_name.to_string(), Value::Map(new_map)); + + Ok(()) + } + } else { + self.variables.insert(identifier.to_string(), value); + + Ok(()) + } + } + + /// Returns a reference to the inner BTreeMap. + pub fn inner(&self) -> &BTreeMap { + &self.variables + } + + /// Returns the number of stored variables. + pub fn len(&self) -> usize { + self.variables.len() + } + + /// Returns true if the length is zero. + pub fn is_empty(&self) -> bool { + self.variables.is_empty() + } +} + +impl Default for VariableMap { + fn default() -> Self { + Self::new() + } +} + +impl Display for VariableMap { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + Table::from(self).fmt(f) + } +} + +impl From<&Table> for VariableMap { + fn from(value: &Table) -> Self { + let mut map = VariableMap::new(); + + for (row_index, row) in value.rows().iter().enumerate() { + map.set_value(&row_index.to_string(), Value::List(row.clone())) + .unwrap(); + } + + map + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn get_and_set_simple_value() { + let mut map = VariableMap::new(); + + map.set_value("x", Value::Integer(1)).unwrap(); + + assert_eq!(Value::Integer(1), map.get_value("x").unwrap().unwrap()); + } + + #[test] + fn get_and_set_nested_maps() { + let mut map = VariableMap::new(); + + map.set_value("x", Value::Map(VariableMap::new())).unwrap(); + map.set_value("x.x", Value::Map(VariableMap::new())) + .unwrap(); + map.set_value("x.x.x", Value::Map(VariableMap::new())) + .unwrap(); + map.set_value("x.x.x.x", Value::Map(VariableMap::new())) + .unwrap(); + + assert_eq!( + Value::Map(VariableMap::new()), + map.get_value("x.x.x.x").unwrap().unwrap() + ); + } +}