Compare commits
24 Commits
f0a0593d4c
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
7a7229d70e
|
|||
|
e4004ccb6d
|
|||
|
843ae6cfb4
|
|||
|
c24d6a8bb3
|
|||
|
d7351e907b
|
|||
|
550223a1d7
|
|||
|
53dbee3514
|
|||
| e1517c338e | |||
| 45096f5254 | |||
| b57fea3104 | |||
| 4380fa85c4 | |||
| 99045aa76c | |||
| 7eb3acf26f | |||
| b424f60f9f | |||
| 42031edac1 | |||
| 04dcadfd61 | |||
| c3c39bda0c | |||
| 782092b91e | |||
| ae5febd5dd | |||
| 3cc7c7be75 | |||
| f49634ccc0 | |||
| 4a885c18b8 | |||
| 37e395c0e3 | |||
| 16a8480d29 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -7,3 +7,6 @@ flamegraph*.svg
|
||||
perf.data*
|
||||
profile.json.gz
|
||||
prof.json
|
||||
*.cpuprofile
|
||||
*.cpuprofile.gz
|
||||
*v8.log*
|
||||
|
||||
@@ -3,6 +3,15 @@ vim.lsp.config("biome", {
|
||||
on_dir(vim.fn.getcwd())
|
||||
end
|
||||
})
|
||||
vim.lsp.config("eslint", {
|
||||
settings = {
|
||||
eslint = {
|
||||
options = {
|
||||
configFile = "./nix-js/runtime-ts/eslint.config.mts"
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
vim.lsp.config("rust_analyzer", {
|
||||
settings = {
|
||||
["rust-analyzer"] = {
|
||||
|
||||
139
Cargo.lock
generated
139
Cargo.lock
generated
@@ -289,9 +289,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bumpalo"
|
||||
version = "3.19.1"
|
||||
version = "3.20.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510"
|
||||
checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"
|
||||
dependencies = [
|
||||
"allocator-api2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
@@ -429,9 +432,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.5.58"
|
||||
version = "4.5.59"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63be97961acde393029492ce0be7a1af7e323e6bae9511ebfac33751be5e6806"
|
||||
checksum = "c5caf74d17c3aec5495110c34cc3f78644bfa89af6c8993ed4de2790e49b6499"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
@@ -439,9 +442,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.5.58"
|
||||
version = "4.5.59"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f13174bda5dfd69d7e947827e5af4b0f2f94a4a3ee92912fba07a66150f21e2"
|
||||
checksum = "370daa45065b80218950227371916a1633217ae42b2715b2287b606dcd618e24"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
@@ -491,6 +494,15 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
|
||||
|
||||
[[package]]
|
||||
name = "colored"
|
||||
version = "3.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "combine"
|
||||
version = "4.6.7"
|
||||
@@ -959,6 +971,27 @@ version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c34f04666d835ff5d62e058c3995147c06f42fe86ff053337632bca83e42702d"
|
||||
|
||||
[[package]]
|
||||
name = "env_filter"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a1c3cc8e57274ec99de65301228b537f1e4eedc1b8e0f9411c6caac8ae7308f"
|
||||
dependencies = [
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "env_logger"
|
||||
version = "0.11.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2daee4ea451f429a58296525ddf28b45a3b64f1acf6587e2067437bb11e218d"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
"env_filter",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
@@ -1142,9 +1175,9 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
|
||||
|
||||
[[package]]
|
||||
name = "futures"
|
||||
version = "0.3.31"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876"
|
||||
checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"
|
||||
dependencies = [
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
@@ -1157,9 +1190,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "futures-channel"
|
||||
version = "0.3.31"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10"
|
||||
checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
@@ -1167,15 +1200,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "futures-core"
|
||||
version = "0.3.31"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
|
||||
checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
|
||||
|
||||
[[package]]
|
||||
name = "futures-executor"
|
||||
version = "0.3.31"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f"
|
||||
checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-task",
|
||||
@@ -1184,15 +1217,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "futures-io"
|
||||
version = "0.3.31"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6"
|
||||
checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
|
||||
|
||||
[[package]]
|
||||
name = "futures-macro"
|
||||
version = "0.3.31"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650"
|
||||
checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -1201,21 +1234,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "futures-sink"
|
||||
version = "0.3.31"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7"
|
||||
checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"
|
||||
|
||||
[[package]]
|
||||
name = "futures-task"
|
||||
version = "0.3.31"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"
|
||||
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
|
||||
|
||||
[[package]]
|
||||
name = "futures-util"
|
||||
version = "0.3.31"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"
|
||||
checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
|
||||
dependencies = [
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
@@ -1225,7 +1258,6 @@ dependencies = [
|
||||
"futures-task",
|
||||
"memchr",
|
||||
"pin-project-lite",
|
||||
"pin-utils",
|
||||
"slab",
|
||||
]
|
||||
|
||||
@@ -1279,6 +1311,12 @@ dependencies = [
|
||||
"wasip3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ghost-cell"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d8449d342b1c67f49169e92e71deb7b9b27f30062301a16dbc27a4cc8d2351b7"
|
||||
|
||||
[[package]]
|
||||
name = "gimli"
|
||||
version = "0.32.3"
|
||||
@@ -1987,7 +2025,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "nix-compat"
|
||||
version = "0.1.0"
|
||||
source = "git+https://git.snix.dev/snix/snix.git#9d414bec7c7fff1fca6ba6d14dda6c4295521260"
|
||||
source = "git+https://git.snix.dev/snix/snix.git#1b37f68842a7e5e226d9dc009e9a90d400c5fb14"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"bstr",
|
||||
@@ -2010,7 +2048,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "nix-compat-derive"
|
||||
version = "0.1.0"
|
||||
source = "git+https://git.snix.dev/snix/snix.git#9d414bec7c7fff1fca6ba6d14dda6c4295521260"
|
||||
source = "git+https://git.snix.dev/snix/snix.git#1b37f68842a7e5e226d9dc009e9a90d400c5fb14"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -2023,8 +2061,10 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
"bzip2",
|
||||
"clap",
|
||||
"colored",
|
||||
"criterion",
|
||||
"deno_core",
|
||||
"deno_error",
|
||||
@@ -2033,6 +2073,7 @@ dependencies = [
|
||||
"ere",
|
||||
"fastwebsockets",
|
||||
"flate2",
|
||||
"ghost-cell",
|
||||
"hashbrown 0.16.1",
|
||||
"hex",
|
||||
"http",
|
||||
@@ -2062,6 +2103,7 @@ dependencies = [
|
||||
"tap",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"test-log",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"toml",
|
||||
@@ -2076,6 +2118,7 @@ name = "nix-js-macros"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"convert_case 0.11.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
@@ -2678,9 +2721,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rnix"
|
||||
version = "0.13.0"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b8276b540c344ec04cd215fb3d35db378c2b1861cc44802c2c097f3490f6e52"
|
||||
checksum = "c163bd17372eecdf10d351c34584b7de7c1a33be4e92a32f3fb3f5a7fe3f579b"
|
||||
dependencies = [
|
||||
"rowan",
|
||||
]
|
||||
@@ -3261,9 +3304,9 @@ checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.115"
|
||||
version = "2.0.116"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e614ed320ac28113fa64972c4262d5dbc89deacdfd00c34a3e4cea073243c12"
|
||||
checksum = "3df424c70518695237746f84cede799c9c58fcb37450d7b23716568cc8bc69cb"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -3272,9 +3315,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "syn-match"
|
||||
version = "0.3.0"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "783c4140d7ed89f37116e865b49e5a9fdd28608b9071a9dd1e158b50fc0a31fc"
|
||||
checksum = "54b8f0a9004d6aafa6a588602a1119e6cdaacec9921aa1605383e6e7d6258fd6"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -3394,6 +3437,28 @@ dependencies = [
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "test-log"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37d53ac171c92a39e4769491c4b4dde7022c60042254b5fc044ae409d34a24d4"
|
||||
dependencies = [
|
||||
"env_logger",
|
||||
"test-log-macros",
|
||||
"tracing-subscriber",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "test-log-macros"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be35209fd0781c5401458ab66e4f98accf63553e8fae7425503e92fdd319783b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "text-size"
|
||||
version = "1.1.1"
|
||||
@@ -3583,9 +3648,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "toml_parser"
|
||||
version = "1.0.8+spec-1.1.0"
|
||||
version = "1.0.9+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0742ff5ff03ea7e67c8ae6c93cac239e0d9784833362da3f9a9c1da8dfefcbdc"
|
||||
checksum = "702d4415e08923e7e1ef96cd5727c0dfed80b4d2fa25db9647fe5eb6f7c5a4c4"
|
||||
dependencies = [
|
||||
"winnow",
|
||||
]
|
||||
@@ -3722,9 +3787,9 @@ checksum = "81b79ad29b5e19de4260020f8919b443b2ef0277d242ce532ec7b7a2cc8b6007"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.23"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "537dd038a89878be9b64dd4bd1b260315c1bb94f4d784956b81e27a088d9a09e"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-linebreak"
|
||||
|
||||
14
Justfile
14
Justfile
@@ -4,7 +4,7 @@
|
||||
|
||||
[no-exit-message]
|
||||
@eval expr:
|
||||
cargo run -- eval '{{expr}}'
|
||||
cargo run -- eval --expr '{{expr}}'
|
||||
|
||||
[no-exit-message]
|
||||
@replr:
|
||||
@@ -12,7 +12,7 @@
|
||||
|
||||
[no-exit-message]
|
||||
@evalr expr:
|
||||
cargo run --release -- eval '{{expr}}'
|
||||
cargo run --release -- eval --expr '{{expr}}'
|
||||
|
||||
[no-exit-message]
|
||||
@repli:
|
||||
@@ -20,4 +20,12 @@
|
||||
|
||||
[no-exit-message]
|
||||
@evali expr:
|
||||
cargo run --release --features inspector -- --inspect-brk 127.0.0.1:9229 eval '{{expr}}'
|
||||
cargo run --release --features inspector -- --inspect-brk 127.0.0.1:9229 eval --expr '{{expr}}'
|
||||
|
||||
[no-exit-message]
|
||||
@replp:
|
||||
cargo run --release --features prof -- repl
|
||||
|
||||
[no-exit-message]
|
||||
@evalp expr:
|
||||
cargo run --release --features prof -- eval --expr '{{expr}}'
|
||||
|
||||
@@ -8,5 +8,6 @@ proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
convert_case = "0.11"
|
||||
proc-macro2 = "1.0"
|
||||
quote = "1.0"
|
||||
syn = { version = "2.0", features = ["full"] }
|
||||
|
||||
@@ -4,22 +4,22 @@
|
||||
//! an Intermediate Representation (IR) that follows a specific pattern. It generates:
|
||||
//! 1. An enum representing the different kinds of IR nodes.
|
||||
//! 2. Structs for each of the variants that have fields.
|
||||
//! 3. `Ref` and `Mut` versions of the main enum for ergonomic pattern matching on references.
|
||||
//! 4. `From` implementations to easily convert from a struct variant (e.g., `BinOp`) to the main enum (`Ir::BinOp`).
|
||||
//! 5. A `To[IrName]` trait to provide a convenient `.to_ir()` method on the variant structs.
|
||||
//! 3. `From` implementations to easily convert from a struct variant (e.g., `BinOp`) to the main enum (`Ir::BinOp`).
|
||||
//! 4. A `To[IrName]` trait to provide a convenient `.to_ir()` method on the variant structs.
|
||||
|
||||
use convert_case::{Case, Casing};
|
||||
use proc_macro::TokenStream;
|
||||
use quote::{format_ident, quote};
|
||||
use syn::{
|
||||
FieldsNamed, Ident, Token, Type, parenthesized,
|
||||
Expr, ExprPath, FieldsNamed, GenericArgument, GenericParam, Generics, Ident, Path, PathSegment,
|
||||
Token, Type, TypePath, parenthesized,
|
||||
parse::{Parse, ParseStream, Result},
|
||||
punctuated::Punctuated,
|
||||
token,
|
||||
};
|
||||
|
||||
/// Represents one of the variants passed to the `ir!` macro.
|
||||
pub enum VariantInput {
|
||||
enum VariantInput {
|
||||
/// A unit-like variant, e.g., `Arg`.
|
||||
Unit(Ident),
|
||||
/// A tuple-like variant with one unnamed field, e.g., `ExprRef(ExprId)`.
|
||||
@@ -29,11 +29,12 @@ pub enum VariantInput {
|
||||
}
|
||||
|
||||
/// The top-level input for the `ir!` macro.
|
||||
pub struct MacroInput {
|
||||
struct MacroInput {
|
||||
/// The name of the main IR enum to be generated (e.g., `Ir`).
|
||||
pub base_name: Ident,
|
||||
base_name: Ident,
|
||||
generics: Generics,
|
||||
/// The list of variants for the enum.
|
||||
pub variants: Punctuated<VariantInput, Token![,]>,
|
||||
variants: Punctuated<VariantInput, Token![,]>,
|
||||
}
|
||||
|
||||
impl Parse for VariantInput {
|
||||
@@ -64,13 +65,14 @@ impl Parse for VariantInput {
|
||||
|
||||
impl Parse for MacroInput {
|
||||
fn parse(input: ParseStream) -> Result<Self> {
|
||||
// The macro input is expected to be: `IrName, Variant1, Variant2, ...`
|
||||
let base_name = input.parse()?;
|
||||
input.parse::<Token![,]>()?;
|
||||
let generics = Generics::parse(input)?;
|
||||
input.parse::<Token![;]>()?;
|
||||
let variants = Punctuated::parse_terminated(input)?;
|
||||
|
||||
Ok(MacroInput {
|
||||
base_name,
|
||||
generics,
|
||||
variants,
|
||||
})
|
||||
}
|
||||
@@ -81,17 +83,39 @@ pub fn ir_impl(input: TokenStream) -> TokenStream {
|
||||
let parsed_input = syn::parse_macro_input!(input as MacroInput);
|
||||
|
||||
let base_name = &parsed_input.base_name;
|
||||
let ref_name = format_ident!("{}Ref", base_name);
|
||||
let mut_name = format_ident!("{}Mut", base_name);
|
||||
let generic_params = &parsed_input.generics.params;
|
||||
let mk_ident_path = |ident| Path {
|
||||
leading_colon: None,
|
||||
segments: Punctuated::from_iter(std::iter::once(PathSegment {
|
||||
ident,
|
||||
arguments: Default::default(),
|
||||
})),
|
||||
};
|
||||
let generic_args = {
|
||||
generic_params
|
||||
.iter()
|
||||
.map(|arg| match arg {
|
||||
GenericParam::Lifetime(lifetime) => {
|
||||
GenericArgument::Lifetime(lifetime.lifetime.clone())
|
||||
}
|
||||
GenericParam::Const(cnst) => GenericArgument::Const(Expr::Path(ExprPath {
|
||||
path: mk_ident_path(cnst.ident.clone()),
|
||||
attrs: Vec::new(),
|
||||
qself: None,
|
||||
})),
|
||||
GenericParam::Type(ty) => GenericArgument::Type(Type::Path(TypePath {
|
||||
path: mk_ident_path(ty.ident.clone()),
|
||||
qself: None,
|
||||
})),
|
||||
})
|
||||
.collect::<Punctuated<_, Token![,]>>()
|
||||
};
|
||||
let where_clause = &parsed_input.generics.where_clause;
|
||||
let to_trait_name = format_ident!("To{}", base_name);
|
||||
let to_trait_fn_name = format_ident!("to_{}", base_name.to_string().to_case(Case::Snake));
|
||||
|
||||
let mut enum_variants = Vec::new();
|
||||
let mut struct_defs = Vec::new();
|
||||
let mut ref_variants = Vec::new();
|
||||
let mut mut_variants = Vec::new();
|
||||
let mut as_ref_arms = Vec::new();
|
||||
let mut as_mut_arms = Vec::new();
|
||||
let mut span_arms = Vec::new();
|
||||
let mut from_impls = Vec::new();
|
||||
let mut to_trait_impls = Vec::new();
|
||||
@@ -109,19 +133,15 @@ pub fn ir_impl(input: TokenStream) -> TokenStream {
|
||||
});
|
||||
|
||||
enum_variants.push(quote! { #name(#inner_type) });
|
||||
ref_variants.push(quote! { #name(&'a #inner_type) });
|
||||
mut_variants.push(quote! { #name(&'a mut #inner_type) });
|
||||
as_ref_arms.push(quote! { Self::#name(inner) => #ref_name::#name(inner) });
|
||||
as_mut_arms.push(quote! { Self::#name(inner) => #mut_name::#name(inner) });
|
||||
span_arms.push(quote! { Self::#name(inner) => inner.span });
|
||||
from_impls.push(quote! {
|
||||
impl From<#inner_type> for #base_name {
|
||||
impl <#generic_params> From<#inner_type> for #base_name <#generic_args> #where_clause {
|
||||
fn from(val: #inner_type) -> Self { #base_name::#name(val) }
|
||||
}
|
||||
});
|
||||
to_trait_impls.push(quote! {
|
||||
impl #to_trait_name for #name {
|
||||
fn #to_trait_fn_name(self) -> #base_name { #base_name::from(self) }
|
||||
impl <#generic_params> #to_trait_name <#generic_args> for #name #where_clause {
|
||||
fn #to_trait_fn_name(self) -> #base_name <#generic_args> { #base_name::from(self) }
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -138,25 +158,24 @@ pub fn ir_impl(input: TokenStream) -> TokenStream {
|
||||
|
||||
let inner_type = name.clone();
|
||||
enum_variants.push(quote! { #name(#inner_type) });
|
||||
ref_variants.push(quote! { #name(&'a #inner_type) });
|
||||
mut_variants.push(quote! { #name(&'a mut #inner_type) });
|
||||
as_ref_arms.push(quote! { Self::#name(inner) => #ref_name::#name(inner) });
|
||||
as_mut_arms.push(quote! { Self::#name(inner) => #mut_name::#name(inner) });
|
||||
span_arms.push(quote! { Self::#name(inner) => inner.span });
|
||||
from_impls.push(quote! {
|
||||
impl From<#inner_type> for #base_name {
|
||||
impl <#generic_params> From<#inner_type> for #base_name <#generic_args> #where_clause {
|
||||
fn from(val: #inner_type) -> Self { #base_name::#name(val) }
|
||||
}
|
||||
});
|
||||
to_trait_impls.push(quote! {
|
||||
impl #to_trait_name for #name {
|
||||
fn #to_trait_fn_name(self) -> #base_name { #base_name::from(self) }
|
||||
impl <#generic_params> #to_trait_name <#generic_args> for #name #where_clause {
|
||||
fn #to_trait_fn_name(self) -> #base_name <#generic_args> { #base_name::from(self) }
|
||||
}
|
||||
});
|
||||
}
|
||||
VariantInput::Struct(name, mut fields) => {
|
||||
let inner_type = name.clone();
|
||||
|
||||
fields.named.iter_mut().for_each(|field| {
|
||||
field.vis = syn::Visibility::Public(syn::token::Pub::default());
|
||||
});
|
||||
fields.named.push(syn::Field {
|
||||
attrs: vec![],
|
||||
vis: syn::Visibility::Public(syn::token::Pub::default()),
|
||||
@@ -168,22 +187,18 @@ pub fn ir_impl(input: TokenStream) -> TokenStream {
|
||||
|
||||
struct_defs.push(quote! {
|
||||
#[derive(Debug)]
|
||||
pub struct #name #fields
|
||||
pub struct #name <#generic_params> #where_clause #fields
|
||||
});
|
||||
enum_variants.push(quote! { #name(#inner_type) });
|
||||
ref_variants.push(quote! { #name(&'a #inner_type) });
|
||||
mut_variants.push(quote! { #name(&'a mut #inner_type) });
|
||||
as_ref_arms.push(quote! { Self::#name(inner) => #ref_name::#name(inner) });
|
||||
as_mut_arms.push(quote! { Self::#name(inner) => #mut_name::#name(inner) });
|
||||
enum_variants.push(quote! { #name(#inner_type <#generic_args>) });
|
||||
span_arms.push(quote! { Self::#name(inner) => inner.span });
|
||||
from_impls.push(quote! {
|
||||
impl From<#inner_type> for #base_name {
|
||||
fn from(val: #inner_type) -> Self { #base_name::#name(val) }
|
||||
impl <#generic_params> From<#inner_type <#generic_args>> for #base_name <#generic_args> #where_clause {
|
||||
fn from(val: #inner_type <#generic_args>) -> Self { #base_name::#name(val) }
|
||||
}
|
||||
});
|
||||
to_trait_impls.push(quote! {
|
||||
impl #to_trait_name for #name {
|
||||
fn #to_trait_fn_name(self) -> #base_name { #base_name::from(self) }
|
||||
impl <#generic_params> #to_trait_name <#generic_args> for #name <#generic_args> #where_clause {
|
||||
fn #to_trait_fn_name(self) -> #base_name <#generic_args> { #base_name::from(self) }
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -193,41 +208,15 @@ pub fn ir_impl(input: TokenStream) -> TokenStream {
|
||||
// Assemble the final generated code.
|
||||
let expanded = quote! {
|
||||
/// The main IR enum, generated by the `ir!` macro.
|
||||
#[derive(Debug, IsVariant, Unwrap, TryUnwrap)]
|
||||
pub enum #base_name {
|
||||
#[derive(Debug)]
|
||||
pub enum #base_name <#generic_params> #where_clause {
|
||||
#( #enum_variants ),*
|
||||
}
|
||||
|
||||
// The struct definitions for the enum variants.
|
||||
#( #struct_defs )*
|
||||
|
||||
/// An immutable reference version of the IR enum.
|
||||
#[derive(Debug, IsVariant, Unwrap, TryUnwrap)]
|
||||
pub enum #ref_name<'a> {
|
||||
#( #ref_variants ),*
|
||||
}
|
||||
|
||||
/// A mutable reference version of the IR enum.
|
||||
#[derive(Debug, IsVariant, Unwrap, TryUnwrap)]
|
||||
pub enum #mut_name<'a> {
|
||||
#( #mut_variants ),*
|
||||
}
|
||||
|
||||
impl #base_name {
|
||||
/// Converts a `&Ir` into a `IrRef`.
|
||||
pub fn as_ref(&self) -> #ref_name<'_> {
|
||||
match self {
|
||||
#( #as_ref_arms ),*
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a `&mut Ir` into a `IrMut`.
|
||||
pub fn as_mut(&mut self) -> #mut_name<'_> {
|
||||
match self {
|
||||
#( #as_mut_arms ),*
|
||||
}
|
||||
}
|
||||
|
||||
impl <#generic_params> #base_name <#generic_args> #where_clause {
|
||||
pub fn span(&self) -> rnix::TextRange {
|
||||
match self {
|
||||
#( #span_arms ),*
|
||||
@@ -239,9 +228,9 @@ pub fn ir_impl(input: TokenStream) -> TokenStream {
|
||||
#( #from_impls )*
|
||||
|
||||
/// A trait for converting a variant struct into the main IR enum.
|
||||
pub trait #to_trait_name {
|
||||
pub trait #to_trait_name <#generic_params> #where_clause {
|
||||
/// Performs the conversion.
|
||||
fn #to_trait_fn_name(self) -> #base_name;
|
||||
fn #to_trait_fn_name(self) -> #base_name <#generic_args>;
|
||||
}
|
||||
|
||||
// Implement the `ToIr` trait for each variant struct.
|
||||
|
||||
@@ -27,6 +27,7 @@ miette = { version = "7.4", features = ["fancy"] }
|
||||
|
||||
hashbrown = "0.16"
|
||||
string-interner = "0.19"
|
||||
bumpalo = { version = "3.20", features = ["allocator-api2", "boxed", "collections"] }
|
||||
|
||||
rust-embed="8.11"
|
||||
|
||||
@@ -58,7 +59,7 @@ dirs = "6.0"
|
||||
tempfile = "3.24"
|
||||
rusqlite = { version = "0.38", features = ["bundled"] }
|
||||
|
||||
rnix = "0.13"
|
||||
rnix = "0.14"
|
||||
rowan = "0.16"
|
||||
|
||||
nix-js-macros = { path = "../nix-js-macros" }
|
||||
@@ -73,12 +74,16 @@ hyper-util = { version = "0.1", features = ["tokio"], optional = true }
|
||||
http-body-util = { version = "0.1", optional = true }
|
||||
http = { version = "1", optional = true }
|
||||
uuid = { version = "1", features = ["v4"], optional = true }
|
||||
ghost-cell = "0.2.6"
|
||||
colored = "3.1.1"
|
||||
|
||||
[features]
|
||||
inspector = ["dep:fastwebsockets", "dep:hyper", "dep:hyper-util", "dep:http-body-util", "dep:http", "dep:uuid"]
|
||||
prof = []
|
||||
|
||||
[dev-dependencies]
|
||||
criterion = { version = "0.8", features = ["html_reports"] }
|
||||
test-log = { version = "0.2", features = ["trace"] }
|
||||
|
||||
[[bench]]
|
||||
name = "basic_ops"
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
mod utils;
|
||||
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use std::hint::black_box;
|
||||
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use utils::eval;
|
||||
|
||||
fn bench_arithmetic(c: &mut Criterion) {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
mod utils;
|
||||
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use std::hint::black_box;
|
||||
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use utils::eval;
|
||||
|
||||
fn bench_builtin_math(c: &mut Criterion) {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
mod utils;
|
||||
|
||||
use std::hint::black_box;
|
||||
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use nix_js::context::Context;
|
||||
use std::hint::black_box;
|
||||
use utils::compile;
|
||||
|
||||
fn bench_parse_and_downgrade(c: &mut Criterion) {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
mod utils;
|
||||
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use std::hint::black_box;
|
||||
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use utils::eval;
|
||||
|
||||
fn bench_non_recursive(c: &mut Criterion) {
|
||||
|
||||
20
nix-js/runtime-ts/eslint.config.mts
Normal file
20
nix-js/runtime-ts/eslint.config.mts
Normal file
@@ -0,0 +1,20 @@
|
||||
import js from "@eslint/js";
|
||||
import { defineConfig } from "eslint/config";
|
||||
import globals from "globals";
|
||||
import tseslint from "typescript-eslint";
|
||||
|
||||
export default defineConfig([
|
||||
js.configs.recommended,
|
||||
...tseslint.configs.recommended,
|
||||
{
|
||||
files: ["**/*.{js,mjs,cjs,ts,mts,cts}"],
|
||||
languageOptions: { globals: globals.es2022 },
|
||||
rules: {
|
||||
"no-unused-vars": "off",
|
||||
"@typescript-eslint/no-unused-vars": ["error", { varsIgnorePattern: "^_", argsIgnorePattern: "^_" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
ignores: ["dist/**/*"],
|
||||
},
|
||||
]);
|
||||
1459
nix-js/runtime-ts/package-lock.json
generated
1459
nix-js/runtime-ts/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -3,15 +3,20 @@
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"check": "tsc --noEmit && npx eslint && biome check",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"build": "node build.mjs",
|
||||
"dev": "npm run typecheck && npm run build"
|
||||
},
|
||||
"devDependencies": {
|
||||
"esbuild": "^0.24.2",
|
||||
"typescript": "^5.7.2"
|
||||
"eslint": "^9.39.2",
|
||||
"typescript": "^5.7.2",
|
||||
"typescript-eslint": "^8.55.0",
|
||||
"jiti": "^2.6.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"globals": "^17.3.0",
|
||||
"js-sdsl": "^4.4.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { mkPos } from "../helpers";
|
||||
import { mkPos, select } from "../helpers";
|
||||
import { createThunk } from "../thunk";
|
||||
import { forceAttrs, forceFunction, forceList, forceStringValue } from "../type-assert";
|
||||
import { ATTR_POSITIONS, type NixAttrs, type NixList, type NixValue } from "../types";
|
||||
|
||||
export const attrNames = (set: NixValue): string[] => Object.keys(forceAttrs(set)).sort();
|
||||
export const attrNames = (set: NixValue): string[] => Array.from(forceAttrs(set).keys()).sort();
|
||||
|
||||
export const attrValues = (set: NixValue): NixValue[] =>
|
||||
Object.entries(forceAttrs(set))
|
||||
Array.from(forceAttrs(set).entries())
|
||||
.sort(([a], [b]) => {
|
||||
if (a < b) {
|
||||
return -1;
|
||||
@@ -21,21 +21,24 @@ export const attrValues = (set: NixValue): NixValue[] =>
|
||||
export const getAttr =
|
||||
(s: NixValue) =>
|
||||
(set: NixValue): NixValue =>
|
||||
forceAttrs(set)[forceStringValue(s)];
|
||||
select(forceAttrs(set), [s]);
|
||||
|
||||
export const hasAttr =
|
||||
(s: NixValue) =>
|
||||
(set: NixValue): boolean =>
|
||||
Object.hasOwn(forceAttrs(set), forceStringValue(s));
|
||||
forceAttrs(set).has(forceStringValue(s));
|
||||
|
||||
export const mapAttrs =
|
||||
(f: NixValue) =>
|
||||
(attrs: NixValue): NixAttrs => {
|
||||
const forcedAttrs = forceAttrs(attrs);
|
||||
const forcedF = forceFunction(f);
|
||||
const newAttrs: NixAttrs = {};
|
||||
for (const key in forcedAttrs) {
|
||||
newAttrs[key] = createThunk(() => forceFunction(forcedF(key))(forcedAttrs[key]), "created by mapAttrs");
|
||||
const newAttrs: NixAttrs = new Map();
|
||||
for (const [key, val] of forcedAttrs) {
|
||||
newAttrs.set(
|
||||
key,
|
||||
createThunk(() => forceFunction(forcedF(key))(val), "created by mapAttrs"),
|
||||
);
|
||||
}
|
||||
return newAttrs;
|
||||
};
|
||||
@@ -43,25 +46,20 @@ export const mapAttrs =
|
||||
export const removeAttrs =
|
||||
(attrs: NixValue) =>
|
||||
(list: NixValue): NixAttrs => {
|
||||
const newAttrs: NixAttrs = {};
|
||||
const forcedAttrs = forceAttrs(attrs);
|
||||
const newAttrs: NixAttrs = new Map(forceAttrs(attrs));
|
||||
const forcedList = forceList(list);
|
||||
const keysToRemove = new Set(forcedList.map(forceStringValue));
|
||||
|
||||
for (const key in forcedAttrs) {
|
||||
if (!keysToRemove.has(key)) {
|
||||
newAttrs[key] = forcedAttrs[key];
|
||||
}
|
||||
for (const item of forcedList) {
|
||||
newAttrs.delete(forceStringValue(item));
|
||||
}
|
||||
return newAttrs;
|
||||
};
|
||||
|
||||
export const listToAttrs = (e: NixValue): NixAttrs => {
|
||||
const attrs: NixAttrs = {};
|
||||
const attrs: NixAttrs = new Map();
|
||||
const forcedE = [...forceList(e)].reverse();
|
||||
for (const obj of forcedE) {
|
||||
const item = forceAttrs(obj);
|
||||
attrs[forceStringValue(item.name)] = item.value;
|
||||
attrs.set(forceStringValue(select(item, ["name"])), select(item, ["value"]));
|
||||
}
|
||||
return attrs;
|
||||
};
|
||||
@@ -71,10 +69,18 @@ export const intersectAttrs =
|
||||
(e2: NixValue): NixAttrs => {
|
||||
const f1 = forceAttrs(e1);
|
||||
const f2 = forceAttrs(e2);
|
||||
const attrs: NixAttrs = {};
|
||||
for (const key of Object.keys(f2)) {
|
||||
if (Object.hasOwn(f1, key)) {
|
||||
attrs[key] = f2[key];
|
||||
const attrs: NixAttrs = new Map();
|
||||
if (f1.size < f2.size) {
|
||||
for (const [key] of f1) {
|
||||
if (f2.has(key)) {
|
||||
attrs.set(key, f2.get(key) as NixValue);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const [key] of f2) {
|
||||
if (f1.has(key)) {
|
||||
attrs.set(key, f2.get(key) as NixValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
return attrs;
|
||||
@@ -85,20 +91,20 @@ export const catAttrs =
|
||||
(list: NixValue): NixList => {
|
||||
const key = forceStringValue(attr);
|
||||
return forceList(list)
|
||||
.map((set) => forceAttrs(set)[key])
|
||||
.filter((val) => val !== undefined);
|
||||
.map((set) => forceAttrs(set).get(key))
|
||||
.filter((val) => val !== undefined) as NixList;
|
||||
};
|
||||
|
||||
export const groupBy =
|
||||
(f: NixValue) =>
|
||||
(list: NixValue): NixAttrs => {
|
||||
const attrs: NixAttrs = {};
|
||||
const attrs: NixAttrs = new Map();
|
||||
const forcedF = forceFunction(f);
|
||||
const forcedList = forceList(list);
|
||||
for (const elem of forcedList) {
|
||||
const key = forceStringValue(forcedF(elem));
|
||||
if (!attrs[key]) attrs[key] = [];
|
||||
(attrs[key] as NixList).push(elem);
|
||||
if (!attrs.has(key)) attrs.set(key, []);
|
||||
(attrs.get(key) as NixList).push(elem);
|
||||
}
|
||||
return attrs;
|
||||
};
|
||||
@@ -113,7 +119,7 @@ export const zipAttrsWith =
|
||||
for (const item of listForced) {
|
||||
const attrs = forceAttrs(item);
|
||||
|
||||
for (const [key, value] of Object.entries(attrs)) {
|
||||
for (const [key, value] of attrs) {
|
||||
if (!attrMap.has(key)) {
|
||||
attrMap.set(key, []);
|
||||
}
|
||||
@@ -121,10 +127,13 @@ export const zipAttrsWith =
|
||||
}
|
||||
}
|
||||
|
||||
const result: Record<string, NixValue> = {};
|
||||
const result: NixAttrs = new Map();
|
||||
|
||||
for (const [name, values] of attrMap.entries()) {
|
||||
result[name] = createThunk(() => forceFunction(forceFunction(f)(name))(values));
|
||||
result.set(
|
||||
name,
|
||||
createThunk(() => forceFunction(forceFunction(f)(name))(values)),
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
@@ -136,17 +145,15 @@ export const unsafeGetAttrPos =
|
||||
const name = forceStringValue(attrName);
|
||||
const attrs = forceAttrs(attrSet);
|
||||
|
||||
if (!(name in attrs)) {
|
||||
if (!attrs.has(name)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const positions = (attrs as NixAttrs & Record<symbol, unknown>)[ATTR_POSITIONS] as
|
||||
| Record<string, string>
|
||||
| undefined;
|
||||
if (!positions || !(name in positions)) {
|
||||
const positions = attrs[ATTR_POSITIONS];
|
||||
if (!positions || !positions.has(name)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const span = positions[name];
|
||||
const span = positions.get(name) as number;
|
||||
return mkPos(span);
|
||||
};
|
||||
|
||||
@@ -113,20 +113,20 @@ export const getContext = (value: NixValue): NixAttrs => {
|
||||
const context = getStringContext(s);
|
||||
|
||||
const infoMap = parseContextToInfoMap(context);
|
||||
const result: NixAttrs = {};
|
||||
const result: NixAttrs = new Map();
|
||||
|
||||
for (const [path, info] of infoMap) {
|
||||
const attrs: NixAttrs = {};
|
||||
const attrs: NixAttrs = new Map();
|
||||
if (info.path) {
|
||||
attrs.path = true;
|
||||
attrs.set("path", true);
|
||||
}
|
||||
if (info.allOutputs) {
|
||||
attrs.allOutputs = true;
|
||||
attrs.set("allOutputs", true);
|
||||
}
|
||||
if (info.outputs.length > 0) {
|
||||
attrs.outputs = info.outputs;
|
||||
attrs.set("outputs", info.outputs);
|
||||
}
|
||||
result[path] = attrs;
|
||||
result.set(path, attrs);
|
||||
}
|
||||
|
||||
return result;
|
||||
@@ -154,22 +154,22 @@ export const appendContext =
|
||||
const ctxAttrs = forceAttrs(ctxValue);
|
||||
const newContext: NixStringContext = new Set(existingContext);
|
||||
|
||||
for (const [path, infoVal] of Object.entries(ctxAttrs)) {
|
||||
for (const [path, infoVal] of ctxAttrs) {
|
||||
if (!path.startsWith("/nix/store/")) {
|
||||
throw new Error(`context key '${path}' is not a store path`);
|
||||
}
|
||||
|
||||
const info = forceAttrs(infoVal);
|
||||
const info = forceAttrs(infoVal as NixValue);
|
||||
|
||||
if ("path" in info) {
|
||||
const pathVal = force(info.path);
|
||||
if (info.has("path")) {
|
||||
const pathVal = force(info.get("path") as NixValue);
|
||||
if (pathVal === true) {
|
||||
newContext.add(path);
|
||||
}
|
||||
}
|
||||
|
||||
if ("allOutputs" in info) {
|
||||
const allOutputs = force(info.allOutputs);
|
||||
if (info.has("allOutputs")) {
|
||||
const allOutputs = force(info.get("allOutputs") as NixValue);
|
||||
if (allOutputs === true) {
|
||||
if (!path.endsWith(".drv")) {
|
||||
throw new Error(
|
||||
@@ -180,8 +180,8 @@ export const appendContext =
|
||||
}
|
||||
}
|
||||
|
||||
if ("outputs" in info) {
|
||||
const outputs = forceList(info.outputs);
|
||||
if (info.has("outputs")) {
|
||||
const outputs = forceList(info.get("outputs") as NixValue);
|
||||
if (outputs.length > 0 && !path.endsWith(".drv")) {
|
||||
throw new Error(
|
||||
`tried to add derivation output context of ${path}, which is not a derivation, to a string`,
|
||||
|
||||
@@ -2,11 +2,16 @@
|
||||
* Conversion and serialization builtin functions
|
||||
*/
|
||||
|
||||
import { addBuiltContext, mkStringWithContext, type NixStringContext } from "../string-context";
|
||||
import {
|
||||
addBuiltContext,
|
||||
mkStringWithContext,
|
||||
type NixStringContext,
|
||||
StringWithContext,
|
||||
} from "../string-context";
|
||||
import { force, isThunk } from "../thunk";
|
||||
import { forceFunction, forceStringNoCtx } from "../type-assert";
|
||||
import type { NixString, NixValue } from "../types";
|
||||
import { HAS_CONTEXT, IS_PATH, isNixPath, isStringWithContext } from "../types";
|
||||
import { isNixPath, isStringWithContext, NixPath } from "../types";
|
||||
import { isAttrs, isPath, typeOf } from "./type-check";
|
||||
|
||||
export const fromJSON = (e: NixValue): NixValue => {
|
||||
@@ -118,37 +123,31 @@ export const coerceToString = (
|
||||
}
|
||||
|
||||
if (typeof v === "object" && v !== null && !Array.isArray(v)) {
|
||||
// First, try the __toString method if present
|
||||
// This allows custom types to define their own string representation
|
||||
if ("__toString" in v) {
|
||||
// Force the method in case it's a thunk
|
||||
const toStringMethod = forceFunction(v.__toString);
|
||||
if (v instanceof Map) {
|
||||
if (v.has("__toString")) {
|
||||
const toStringMethod = forceFunction(v.get("__toString") as NixValue);
|
||||
const result = force(toStringMethod(v));
|
||||
// Recursively coerceToString
|
||||
return coerceToString(result, mode, copyToStore, outContext);
|
||||
}
|
||||
|
||||
// If no __toString, try outPath (used for derivations and store paths)
|
||||
// This allows derivation objects like { outPath = "/nix/store/..."; } to be coerced
|
||||
if ("outPath" in v) {
|
||||
// Recursively coerce the outPath value
|
||||
const outPath = coerceToString(v.outPath, mode, copyToStore, outContext);
|
||||
if ("type" in v && v.type === "derivation" && "drvPath" in v && outContext) {
|
||||
const drvPathValue = force(v.drvPath);
|
||||
if (v.has("outPath")) {
|
||||
const outPath = coerceToString(v.get("outPath") as NixValue, mode, copyToStore, outContext);
|
||||
if (v.has("type") && v.get("type") === "derivation" && v.has("drvPath") && outContext) {
|
||||
const drvPathValue = force(v.get("drvPath") as NixValue);
|
||||
const drvPathStr = isStringWithContext(drvPathValue)
|
||||
? drvPathValue.value
|
||||
: typeof drvPathValue === "string"
|
||||
? drvPathValue
|
||||
: null;
|
||||
if (drvPathStr) {
|
||||
const outputName = "outputName" in v ? String(force(v.outputName)) : "out";
|
||||
const outputName = v.has("outputName") ? String(force(v.get("outputName") as NixValue)) : "out";
|
||||
addBuiltContext(outContext, drvPathStr, outputName);
|
||||
}
|
||||
}
|
||||
return outPath;
|
||||
}
|
||||
}
|
||||
|
||||
// Attribute sets without __toString or outPath cannot be coerced
|
||||
throw new TypeError(`cannot coerce ${typeOf(v)} to a string`);
|
||||
}
|
||||
|
||||
@@ -259,8 +258,8 @@ export const coerceToPath = (value: NixValue, outContext: NixStringContext): str
|
||||
if (isPath(forced)) {
|
||||
return forced.value;
|
||||
}
|
||||
if (isAttrs(forced) && Object.hasOwn(forced, "__toString")) {
|
||||
const toStringFunc = forceFunction(forced.__toString);
|
||||
if (isAttrs(forced) && forced.has("__toString")) {
|
||||
const toStringFunc = forceFunction(forced.get("__toString") as NixValue);
|
||||
return coerceToPath(toStringFunc(forced), outContext);
|
||||
}
|
||||
|
||||
@@ -290,13 +289,14 @@ export const toStringFunc = (value: NixValue): NixString => {
|
||||
return coerceToStringWithContext(value, StringCoercionMode.ToString, false);
|
||||
};
|
||||
|
||||
export type JsonValue = number | boolean | string | null | { [key: string]: JsonValue } | Array<JsonValue>;
|
||||
export const nixValueToJson = (
|
||||
value: NixValue,
|
||||
strict: boolean,
|
||||
outContext: NixStringContext,
|
||||
copyToStore: boolean,
|
||||
seen: Set<NixValue> = new Set(),
|
||||
): unknown => {
|
||||
): JsonValue => {
|
||||
const v = strict ? force(value) : value;
|
||||
|
||||
if (isThunk(v) || typeof v === "function")
|
||||
@@ -312,13 +312,13 @@ export const nixValueToJson = (
|
||||
if (typeof v === "number") return v;
|
||||
if (typeof v === "boolean") return v;
|
||||
if (typeof v === "string") return v;
|
||||
if (typeof v === "object" && HAS_CONTEXT in v) {
|
||||
if (v instanceof StringWithContext) {
|
||||
for (const elem of v.context) {
|
||||
outContext.add(elem);
|
||||
}
|
||||
return v.value;
|
||||
}
|
||||
if (typeof v === "object" && IS_PATH in v) {
|
||||
if (v instanceof NixPath) {
|
||||
if (copyToStore) {
|
||||
const storePath = Deno.core.ops.op_copy_path_to_store(v.value);
|
||||
outContext.add(storePath);
|
||||
@@ -339,9 +339,9 @@ export const nixValueToJson = (
|
||||
return v.map((item) => nixValueToJson(item, strict, outContext, copyToStore, seen));
|
||||
}
|
||||
|
||||
// NixAttrs
|
||||
if ("__toString" in v && typeof force(v.__toString) === "function") {
|
||||
const toStringMethod = force(v.__toString) as (self: typeof v) => NixValue;
|
||||
if (v instanceof Map) {
|
||||
if (v.has("__toString") && typeof force(v.get("__toString") as NixValue) === "function") {
|
||||
const toStringMethod = force(v.get("__toString") as NixValue) as (self: typeof v) => NixValue;
|
||||
const result = force(toStringMethod(v));
|
||||
if (typeof result === "string") {
|
||||
return result;
|
||||
@@ -355,14 +355,17 @@ export const nixValueToJson = (
|
||||
return nixValueToJson(result, strict, outContext, copyToStore, seen);
|
||||
}
|
||||
|
||||
if ("outPath" in v) {
|
||||
return nixValueToJson(v.outPath, strict, outContext, copyToStore, seen);
|
||||
if (v.has("outPath")) {
|
||||
return nixValueToJson(v.get("outPath") as NixValue, strict, outContext, copyToStore, seen);
|
||||
}
|
||||
|
||||
const result: Record<string, unknown> = {};
|
||||
const keys = Object.keys(v).sort();
|
||||
const result: { [key: string]: JsonValue } = {};
|
||||
const keys = Array.from(v.keys()).sort();
|
||||
for (const key of keys) {
|
||||
result[key] = nixValueToJson(v[key], strict, outContext, copyToStore, seen);
|
||||
result[key] = nixValueToJson(v.get(key) as NixValue, strict, outContext, copyToStore, seen);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
throw new Error(`cannot convert ${typeof v} to JSON`);
|
||||
};
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
import { force } from "../thunk";
|
||||
import { forceAttrs, forceList, forceStringNoCtx, forceStringValue } from "../type-assert";
|
||||
import type { NixAttrs, NixValue } from "../types";
|
||||
import { coerceToString, nixValueToJson, StringCoercionMode } from "./conversion";
|
||||
import { coerceToString, type JsonValue, nixValueToJson, StringCoercionMode } from "./conversion";
|
||||
|
||||
export interface OutputInfo {
|
||||
path: string;
|
||||
@@ -116,10 +116,10 @@ export const generateAtermModulo = (drv: DerivationData, inputDrvHashes: Map<str
|
||||
return `Derive([${outputs}],[${inputDrvs}],[${inputSrcs}],${quoteString(drv.platform)},${escapeString(drv.builder)},[${args}],[${envs}])`;
|
||||
};
|
||||
const validateName = (attrs: NixAttrs): string => {
|
||||
if (!("name" in attrs)) {
|
||||
if (!attrs.has("name")) {
|
||||
throw new Error("derivation: missing required attribute 'name'");
|
||||
}
|
||||
const name = forceStringValue(attrs.name);
|
||||
const name = forceStringValue(attrs.get("name") as NixValue);
|
||||
if (!name) {
|
||||
throw new Error("derivation: 'name' cannot be empty");
|
||||
}
|
||||
@@ -130,17 +130,17 @@ const validateName = (attrs: NixAttrs): string => {
|
||||
};
|
||||
|
||||
const validateBuilder = (attrs: NixAttrs, outContext: NixStringContext): string => {
|
||||
if (!("builder" in attrs)) {
|
||||
if (!attrs.has("builder")) {
|
||||
throw new Error("derivation: missing required attribute 'builder'");
|
||||
}
|
||||
return coerceToString(attrs.builder, StringCoercionMode.ToString, true, outContext);
|
||||
return coerceToString(attrs.get("builder") as NixValue, StringCoercionMode.ToString, true, outContext);
|
||||
};
|
||||
|
||||
const validateSystem = (attrs: NixAttrs): string => {
|
||||
if (!("system" in attrs)) {
|
||||
if (!attrs.has("system")) {
|
||||
throw new Error("derivation: missing required attribute 'system'");
|
||||
}
|
||||
return forceStringValue(attrs.system);
|
||||
return forceStringValue(attrs.get("system") as NixValue);
|
||||
};
|
||||
|
||||
const validateOutputs = (outputs: string[]): void => {
|
||||
@@ -162,17 +162,25 @@ const validateOutputs = (outputs: string[]): void => {
|
||||
};
|
||||
|
||||
const extractOutputs = (attrs: NixAttrs, structuredAttrs: boolean): string[] => {
|
||||
if (!("outputs" in attrs)) {
|
||||
if (!attrs.has("outputs")) {
|
||||
return ["out"];
|
||||
}
|
||||
|
||||
let outputs: string[];
|
||||
if (structuredAttrs) {
|
||||
const outputsList = forceList(attrs.outputs);
|
||||
const outputsList = forceList(attrs.get("outputs") as NixValue);
|
||||
outputs = outputsList.map((o) => forceStringValue(o));
|
||||
} else {
|
||||
const outputsStr = coerceToString(attrs.outputs, StringCoercionMode.ToString, false, new Set());
|
||||
outputs = outputsStr.split(/\s+/).filter((s) => s.length > 0);
|
||||
const outputsStr = coerceToString(
|
||||
attrs.get("outputs") as NixValue,
|
||||
StringCoercionMode.ToString,
|
||||
false,
|
||||
new Set(),
|
||||
);
|
||||
outputs = outputsStr
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter((s) => s.length > 0);
|
||||
}
|
||||
|
||||
validateOutputs(outputs);
|
||||
@@ -180,10 +188,10 @@ const extractOutputs = (attrs: NixAttrs, structuredAttrs: boolean): string[] =>
|
||||
};
|
||||
|
||||
const extractArgs = (attrs: NixAttrs, outContext: NixStringContext): string[] => {
|
||||
if (!("args" in attrs)) {
|
||||
if (!attrs.has("args")) {
|
||||
return [];
|
||||
}
|
||||
const argsList = forceList(attrs.args);
|
||||
const argsList = forceList(attrs.get("args") as NixValue);
|
||||
return argsList.map((a) => coerceToString(a, StringCoercionMode.ToString, true, outContext));
|
||||
};
|
||||
|
||||
@@ -197,9 +205,9 @@ const structuredAttrsExcludedKeys = new Set([
|
||||
|
||||
const specialAttrs = new Set(["args", "__ignoreNulls", "__contentAddressed", "__impure"]);
|
||||
|
||||
const sortedJsonStringify = (obj: Record<string, unknown>): string => {
|
||||
const sortedJsonStringify = (obj: Record<string, JsonValue>): string => {
|
||||
const sortedKeys = Object.keys(obj).sort();
|
||||
const sortedObj: Record<string, unknown> = {};
|
||||
const sortedObj: Record<string, JsonValue> = {};
|
||||
for (const key of sortedKeys) {
|
||||
sortedObj[key] = obj[key];
|
||||
}
|
||||
@@ -216,8 +224,8 @@ const extractEnv = (
|
||||
const env = new Map<string, string>();
|
||||
|
||||
if (structuredAttrs) {
|
||||
const jsonAttrs: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(attrs)) {
|
||||
const jsonAttrs: Record<string, JsonValue> = {};
|
||||
for (const [key, value] of attrs) {
|
||||
if (!structuredAttrsExcludedKeys.has(key)) {
|
||||
const forcedValue = force(value);
|
||||
if (ignoreNulls && forcedValue === null) {
|
||||
@@ -271,13 +279,13 @@ const extractEnv = (
|
||||
}
|
||||
env.set("__json", sortedJsonStringify(jsonAttrs));
|
||||
} else {
|
||||
for (const [key, value] of Object.entries(attrs)) {
|
||||
for (const [key, value] of attrs) {
|
||||
if (!specialAttrs.has(key)) {
|
||||
const forcedValue = force(value);
|
||||
const forcedValue = force(value as NixValue);
|
||||
if (ignoreNulls && forcedValue === null) {
|
||||
continue;
|
||||
}
|
||||
env.set(key, coerceToString(value, StringCoercionMode.ToString, true, outContext));
|
||||
env.set(key, coerceToString(value as NixValue, StringCoercionMode.ToString, true, outContext));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -292,29 +300,29 @@ interface FixedOutputInfo {
|
||||
}
|
||||
|
||||
const extractFixedOutputInfo = (attrs: NixAttrs, ignoreNulls: boolean): FixedOutputInfo | null => {
|
||||
if (!("outputHash" in attrs)) {
|
||||
if (!attrs.has("outputHash")) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hashValue = force(attrs.outputHash);
|
||||
const hashValue = force(attrs.get("outputHash") as NixValue);
|
||||
if (ignoreNulls && hashValue === null) {
|
||||
return null;
|
||||
}
|
||||
const hashRaw = forceStringNoCtx(attrs.outputHash);
|
||||
const hashRaw = forceStringNoCtx(hashValue);
|
||||
|
||||
let hashAlgo = null;
|
||||
if ("outputHashAlgo" in attrs) {
|
||||
const algoValue = force(attrs.outputHashAlgo);
|
||||
if (attrs.has("outputHashAlgo")) {
|
||||
const algoValue = force(attrs.get("outputHashAlgo") as NixValue);
|
||||
if (!(ignoreNulls && algoValue === null)) {
|
||||
hashAlgo = forceStringNoCtx(attrs.outputHashAlgo);
|
||||
hashAlgo = forceStringNoCtx(algoValue);
|
||||
}
|
||||
}
|
||||
|
||||
let hashMode = "flat";
|
||||
if ("outputHashMode" in attrs) {
|
||||
const modeValue = force(attrs.outputHashMode);
|
||||
if (attrs.has("outputHashMode")) {
|
||||
const modeValue = force(attrs.get("outputHashMode") as NixValue);
|
||||
if (!(ignoreNulls && modeValue === null)) {
|
||||
hashMode = forceStringValue(attrs.outputHashMode);
|
||||
hashMode = forceStringValue(modeValue);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -341,18 +349,22 @@ export const derivationStrict = (args: NixValue): NixAttrs => {
|
||||
const builder = validateBuilder(attrs, collectedContext);
|
||||
const platform = validateSystem(attrs);
|
||||
|
||||
const structuredAttrs = "__structuredAttrs" in attrs ? force(attrs.__structuredAttrs) === true : false;
|
||||
const ignoreNulls = "__ignoreNulls" in attrs ? force(attrs.__ignoreNulls) === true : false;
|
||||
const structuredAttrs = attrs.has("__structuredAttrs")
|
||||
? force(attrs.get("__structuredAttrs") as NixValue) === true
|
||||
: false;
|
||||
const ignoreNulls = attrs.has("__ignoreNulls")
|
||||
? force(attrs.get("__ignoreNulls") as NixValue) === true
|
||||
: false;
|
||||
|
||||
const outputs = extractOutputs(attrs, structuredAttrs);
|
||||
const fixedOutputInfo = extractFixedOutputInfo(attrs, ignoreNulls);
|
||||
validateFixedOutputConstraints(fixedOutputInfo, outputs);
|
||||
|
||||
if ("__contentAddressed" in attrs && force(attrs.__contentAddressed) === true) {
|
||||
if (attrs.has("__contentAddressed") && force(attrs.get("__contentAddressed") as NixValue) === true) {
|
||||
throw new Error("ca derivations are not supported");
|
||||
}
|
||||
|
||||
if ("__impure" in attrs && force(attrs.__impure) === true) {
|
||||
if (attrs.has("__impure") && force(attrs.get("__impure") as NixValue) === true) {
|
||||
throw new Error("impure derivations are not supported");
|
||||
}
|
||||
|
||||
@@ -365,27 +377,27 @@ export const derivationStrict = (args: NixValue): NixAttrs => {
|
||||
const rustResult: {
|
||||
drvPath: string;
|
||||
outputs: [string, string][];
|
||||
} = Deno.core.ops.op_finalize_derivation({
|
||||
name: drvName,
|
||||
} = Deno.core.ops.op_finalize_derivation(
|
||||
drvName,
|
||||
builder,
|
||||
platform,
|
||||
outputs,
|
||||
args: drvArgs,
|
||||
env: envEntries,
|
||||
context: contextArray,
|
||||
fixedOutput: fixedOutputInfo,
|
||||
});
|
||||
drvArgs,
|
||||
envEntries,
|
||||
contextArray,
|
||||
fixedOutputInfo,
|
||||
);
|
||||
|
||||
const result: NixAttrs = {};
|
||||
const result: NixAttrs = new Map();
|
||||
|
||||
const drvPathContext = new Set<string>();
|
||||
addDrvDeepContext(drvPathContext, rustResult.drvPath);
|
||||
result.drvPath = mkStringWithContext(rustResult.drvPath, drvPathContext);
|
||||
result.set("drvPath", mkStringWithContext(rustResult.drvPath, drvPathContext));
|
||||
|
||||
for (const [outputName, outputPath] of rustResult.outputs) {
|
||||
const outputContext = new Set<string>();
|
||||
addBuiltContext(outputContext, rustResult.drvPath, outputName);
|
||||
result[outputName] = mkStringWithContext(outputPath, outputContext);
|
||||
result.set(outputName, mkStringWithContext(outputPath, outputContext));
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
@@ -27,7 +27,7 @@ export const deepSeq =
|
||||
recurse(val);
|
||||
}
|
||||
} else if (isAttrs(forced)) {
|
||||
for (const [_, val] of Object.entries(forced)) {
|
||||
for (const [_, val] of forced.entries()) {
|
||||
recurse(val);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { select } from "../helpers";
|
||||
import { forceAttrs, forceStringNoCtx, forceStringValue } from "../type-assert";
|
||||
import type { NixValue } from "../types";
|
||||
import { realisePath } from "./io";
|
||||
@@ -20,18 +21,14 @@ export const hashString =
|
||||
|
||||
export const convertHash = (args: NixValue): string => {
|
||||
const attrs = forceAttrs(args);
|
||||
const hash = forceStringNoCtx(attrs.hash);
|
||||
const hash = forceStringNoCtx(select(attrs, ["hash"]));
|
||||
|
||||
let hashAlgo: string | null = null;
|
||||
if ("hashAlgo" in attrs) {
|
||||
hashAlgo = forceStringNoCtx(attrs.hashAlgo);
|
||||
if (attrs.has("hashAlgo")) {
|
||||
hashAlgo = forceStringNoCtx(select(attrs, ["hashAlgo"]));
|
||||
}
|
||||
|
||||
const toHashFormat = forceStringNoCtx(attrs.toHashFormat);
|
||||
const toHashFormat = forceStringNoCtx(select(attrs, ["toHashFormat"]));
|
||||
|
||||
return Deno.core.ops.op_convert_hash({
|
||||
hash,
|
||||
hashAlgo,
|
||||
toHashFormat,
|
||||
});
|
||||
return Deno.core.ops.op_convert_hash(hash, hashAlgo, toHashFormat);
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createThunk, force } from "../thunk";
|
||||
import type { NixValue } from "../types";
|
||||
import type { NixAttrs, NixFunction, NixValue } from "../types";
|
||||
import * as arithmetic from "./arithmetic";
|
||||
import * as attrs from "./attrs";
|
||||
import * as conversion from "./conversion";
|
||||
@@ -24,31 +24,31 @@ export interface PrimopMetadata {
|
||||
}
|
||||
|
||||
export const mkPrimop = (
|
||||
func: (...args: NixValue[]) => NixValue,
|
||||
func: NixFunction,
|
||||
name: string,
|
||||
arity: number,
|
||||
applied: number = 0,
|
||||
): ((...args: NixValue[]) => NixValue) => {
|
||||
(func as unknown as Record<symbol, unknown>)[PRIMOP_METADATA] = {
|
||||
func[PRIMOP_METADATA] = {
|
||||
name,
|
||||
arity,
|
||||
applied,
|
||||
} satisfies PrimopMetadata;
|
||||
|
||||
if (applied < arity - 1) {
|
||||
const wrappedFunc = ((...args: NixValue[]) => {
|
||||
const result = func(...args);
|
||||
const wrappedFunc: NixFunction = ((arg: NixValue) => {
|
||||
const result = func(arg);
|
||||
if (typeof result === "function") {
|
||||
return mkPrimop(result, name, arity, applied + args.length);
|
||||
return mkPrimop(result, name, arity, applied + 1);
|
||||
}
|
||||
return result;
|
||||
}) as (...args: NixValue[]) => NixValue;
|
||||
});
|
||||
|
||||
(wrappedFunc as unknown as Record<symbol, unknown>)[PRIMOP_METADATA] = {
|
||||
wrappedFunc[PRIMOP_METADATA] = {
|
||||
name,
|
||||
arity,
|
||||
applied,
|
||||
} satisfies PrimopMetadata;
|
||||
};
|
||||
|
||||
return wrappedFunc;
|
||||
}
|
||||
@@ -57,8 +57,8 @@ export const mkPrimop = (
|
||||
};
|
||||
|
||||
export const isPrimop = (
|
||||
value: unknown,
|
||||
): value is ((...args: never[]) => unknown) & { [PRIMOP_METADATA]: PrimopMetadata } => {
|
||||
value: NixValue,
|
||||
): value is NixFunction & { [PRIMOP_METADATA]: PrimopMetadata } => {
|
||||
return (
|
||||
typeof value === "function" &&
|
||||
PRIMOP_METADATA in value &&
|
||||
@@ -67,14 +67,15 @@ export const isPrimop = (
|
||||
);
|
||||
};
|
||||
|
||||
export const getPrimopMetadata = (func: unknown): PrimopMetadata | undefined => {
|
||||
export const getPrimopMetadata = (func: NixValue): PrimopMetadata | undefined => {
|
||||
if (isPrimop(func)) {
|
||||
return func[PRIMOP_METADATA];
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
export const builtins: Record<string, NixValue> = {
|
||||
export const builtins: NixAttrs = new Map<string, NixValue>(
|
||||
Object.entries({
|
||||
add: mkPrimop(arithmetic.add, "add", 2),
|
||||
sub: mkPrimop(arithmetic.sub, "sub", 2),
|
||||
mul: mkPrimop(arithmetic.mul, "mul", 2),
|
||||
@@ -219,4 +220,5 @@ export const builtins: Record<string, NixValue> = {
|
||||
storeDir: createThunk(() => {
|
||||
throw new Error("stub storeDir evaluated");
|
||||
}),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { select } from "../helpers";
|
||||
import { getPathValue } from "../path";
|
||||
import type { NixStringContext, StringWithContext } from "../string-context";
|
||||
import { addOpaqueContext, decodeContextElem, mkStringWithContext } from "../string-context";
|
||||
@@ -10,11 +11,12 @@ import {
|
||||
forceStringNoCtx,
|
||||
forceStringValue,
|
||||
} from "../type-assert";
|
||||
import type { NixAttrs, NixPath, NixString, NixValue } from "../types";
|
||||
import { CatchableError, IS_PATH, isNixPath } from "../types";
|
||||
import type { NixAttrs, NixString, NixValue } from "../types";
|
||||
import { CatchableError, isNixPath, NixPath } from "../types";
|
||||
import { coerceToPath, coerceToString, StringCoercionMode } from "./conversion";
|
||||
import { baseNameOf } from "./path";
|
||||
import { isAttrs, isPath, isString } from "./type-check";
|
||||
import { execBytecode, execBytecodeScoped } from "../vm";
|
||||
|
||||
const importCache = new Map<string, NixValue>();
|
||||
|
||||
@@ -48,8 +50,8 @@ export const importFunc = (path: NixValue): NixValue => {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const code = Deno.core.ops.op_import(pathStr);
|
||||
const result = Function(`return (${code})`)();
|
||||
const [code, currentDir] = Deno.core.ops.op_import(pathStr);
|
||||
const result = execBytecode(code, currentDir);
|
||||
|
||||
importCache.set(pathStr, result);
|
||||
return result;
|
||||
@@ -59,14 +61,12 @@ export const scopedImport =
|
||||
(scope: NixValue) =>
|
||||
(path: NixValue): NixValue => {
|
||||
const scopeAttrs = forceAttrs(scope);
|
||||
const scopeKeys = Object.keys(scopeAttrs);
|
||||
const scopeKeys = Array.from(scopeAttrs.keys());
|
||||
|
||||
const pathStr = realisePath(path);
|
||||
|
||||
const code = Deno.core.ops.op_scoped_import(pathStr, scopeKeys);
|
||||
|
||||
const scopedFunc = Function(`return (${code})`)();
|
||||
return scopedFunc(scopeAttrs);
|
||||
const [code, currentDir] = Deno.core.ops.op_scoped_import(pathStr, scopeKeys);
|
||||
return execBytecodeScoped(code, currentDir, scopeAttrs);
|
||||
};
|
||||
|
||||
export const storePath = (pathArg: NixValue): StringWithContext => {
|
||||
@@ -84,24 +84,24 @@ export const fetchClosure = (_args: NixValue): never => {
|
||||
};
|
||||
|
||||
export interface FetchUrlResult {
|
||||
store_path: string;
|
||||
storePath: string;
|
||||
hash: string;
|
||||
}
|
||||
|
||||
export interface FetchTarballResult {
|
||||
store_path: string;
|
||||
nar_hash: string;
|
||||
storePath: string;
|
||||
narHash: string;
|
||||
}
|
||||
|
||||
export interface FetchGitResult {
|
||||
out_path: string;
|
||||
outPath: string;
|
||||
rev: string;
|
||||
short_rev: string;
|
||||
rev_count: number;
|
||||
last_modified: number;
|
||||
last_modified_date: string;
|
||||
shortRev: string;
|
||||
revCount: number;
|
||||
lastModified: number;
|
||||
lastModifiedDate: string;
|
||||
submodules: boolean;
|
||||
nar_hash: string | null;
|
||||
narHash: string | null;
|
||||
}
|
||||
|
||||
const normalizeUrlInput = (
|
||||
@@ -112,25 +112,23 @@ const normalizeUrlInput = (
|
||||
return { url: forced };
|
||||
}
|
||||
const attrs = forceAttrs(args);
|
||||
const url = forceStringValue(attrs.url);
|
||||
const hash =
|
||||
"sha256" in attrs
|
||||
? forceStringValue(attrs.sha256)
|
||||
: "hash" in attrs
|
||||
? forceStringValue(attrs.hash)
|
||||
const url = forceStringValue(select(attrs, ["url"]));
|
||||
const hash = attrs.has("sha256")
|
||||
? forceStringValue(attrs.get("sha256") as NixValue)
|
||||
: attrs.has("hash")
|
||||
? forceStringValue(attrs.get("hash") as NixValue)
|
||||
: undefined;
|
||||
const name = "name" in attrs ? forceStringValue(attrs.name) : undefined;
|
||||
const executable = "executable" in attrs ? forceBool(attrs.executable) : false;
|
||||
const name = attrs.has("name") ? forceStringValue(attrs.get("name") as NixValue) : undefined;
|
||||
const executable = attrs.has("executable") ? forceBool(attrs.get("executable") as NixValue) : false;
|
||||
return { url, hash, name, executable };
|
||||
};
|
||||
|
||||
const normalizeTarballInput = (args: NixValue): { url: string; sha256?: string; name?: string } => {
|
||||
const forced = force(args);
|
||||
if (isAttrs(forced)) {
|
||||
const url = resolvePseudoUrl(forceStringNoCtx(forced.url));
|
||||
const sha256 = "sha256" in forced ? forceStringNoCtx(forced.sha256) : undefined;
|
||||
const nameRaw = "name" in forced ? forceStringNoCtx(forced.name) : undefined;
|
||||
// FIXME: extract baseNameOfRaw
|
||||
const url = resolvePseudoUrl(forceStringNoCtx(select(forced, ["url"])));
|
||||
const sha256 = forced.has("sha256") ? forceStringNoCtx(forced.get("sha256") as NixValue) : undefined;
|
||||
const nameRaw = forced.has("name") ? forceStringNoCtx(forced.get("name") as NixValue) : undefined;
|
||||
const name = nameRaw === "" ? (baseNameOf(nameRaw) as string) : nameRaw;
|
||||
return { url, sha256, name };
|
||||
} else {
|
||||
@@ -155,16 +153,16 @@ export const fetchurl = (args: NixValue): NixString => {
|
||||
executable ?? false,
|
||||
);
|
||||
const context: NixStringContext = new Set();
|
||||
addOpaqueContext(context, result.store_path);
|
||||
return mkStringWithContext(result.store_path, context);
|
||||
addOpaqueContext(context, result.storePath);
|
||||
return mkStringWithContext(result.storePath, context);
|
||||
};
|
||||
|
||||
export const fetchTarball = (args: NixValue): NixString => {
|
||||
const { url, name, sha256 } = normalizeTarballInput(args);
|
||||
const result: FetchTarballResult = Deno.core.ops.op_fetch_tarball(url, name ?? null, sha256 ?? null);
|
||||
const context: NixStringContext = new Set();
|
||||
addOpaqueContext(context, result.store_path);
|
||||
return mkStringWithContext(result.store_path, context);
|
||||
addOpaqueContext(context, result.storePath);
|
||||
return mkStringWithContext(result.storePath, context);
|
||||
};
|
||||
|
||||
export const fetchGit = (args: NixValue): NixAttrs => {
|
||||
@@ -174,26 +172,26 @@ export const fetchGit = (args: NixValue): NixAttrs => {
|
||||
const url = coerceToString(forced, StringCoercionMode.Base, false, disposedContext);
|
||||
const result = Deno.core.ops.op_fetch_git(url, null, null, false, false, false, null);
|
||||
const outContext: NixStringContext = new Set();
|
||||
addOpaqueContext(outContext, result.out_path);
|
||||
return {
|
||||
outPath: mkStringWithContext(result.out_path, outContext),
|
||||
rev: result.rev,
|
||||
shortRev: result.short_rev,
|
||||
revCount: BigInt(result.rev_count),
|
||||
lastModified: BigInt(result.last_modified),
|
||||
lastModifiedDate: result.last_modified_date,
|
||||
submodules: result.submodules,
|
||||
narHash: result.nar_hash,
|
||||
};
|
||||
addOpaqueContext(outContext, result.outPath);
|
||||
return new Map<string, NixValue>([
|
||||
["outPath", mkStringWithContext(result.outPath, outContext)],
|
||||
["rev", result.rev],
|
||||
["shortRev", result.shortRev],
|
||||
["revCount", BigInt(result.revCount)],
|
||||
["lastModified", BigInt(result.lastModified)],
|
||||
["lastModifiedDate", result.lastModifiedDate],
|
||||
["submodules", result.submodules],
|
||||
["narHash", result.narHash],
|
||||
]);
|
||||
}
|
||||
const attrs = forceAttrs(args);
|
||||
const url = forceStringValue(attrs.url);
|
||||
const gitRef = "ref" in attrs ? forceStringValue(attrs.ref) : null;
|
||||
const rev = "rev" in attrs ? forceStringValue(attrs.rev) : null;
|
||||
const shallow = "shallow" in attrs ? forceBool(attrs.shallow) : false;
|
||||
const submodules = "submodules" in attrs ? forceBool(attrs.submodules) : false;
|
||||
const allRefs = "allRefs" in attrs ? forceBool(attrs.allRefs) : false;
|
||||
const name = "name" in attrs ? forceStringValue(attrs.name) : null;
|
||||
const url = forceStringValue(select(attrs, ["url"]));
|
||||
const gitRef = attrs.has("ref") ? forceStringValue(attrs.get("ref") as NixValue) : null;
|
||||
const rev = attrs.has("rev") ? forceStringValue(attrs.get("rev") as NixValue) : null;
|
||||
const shallow = attrs.has("shallow") ? forceBool(attrs.get("shallow") as NixValue) : false;
|
||||
const submodules = attrs.has("submodules") ? forceBool(attrs.get("submodules") as NixValue) : false;
|
||||
const allRefs = attrs.has("allRefs") ? forceBool(attrs.get("allRefs") as NixValue) : false;
|
||||
const name = attrs.has("name") ? forceStringValue(attrs.get("name") as NixValue) : null;
|
||||
|
||||
const result: FetchGitResult = Deno.core.ops.op_fetch_git(
|
||||
url,
|
||||
@@ -206,17 +204,17 @@ export const fetchGit = (args: NixValue): NixAttrs => {
|
||||
);
|
||||
|
||||
const outContext: NixStringContext = new Set();
|
||||
addOpaqueContext(outContext, result.out_path);
|
||||
return {
|
||||
outPath: mkStringWithContext(result.out_path, outContext),
|
||||
rev: result.rev,
|
||||
shortRev: result.short_rev,
|
||||
revCount: BigInt(result.rev_count),
|
||||
lastModified: BigInt(result.last_modified),
|
||||
lastModifiedDate: result.last_modified_date,
|
||||
submodules: result.submodules,
|
||||
narHash: result.nar_hash,
|
||||
};
|
||||
addOpaqueContext(outContext, result.outPath);
|
||||
return new Map<string, NixValue>([
|
||||
["outPath", mkStringWithContext(result.outPath, outContext)],
|
||||
["rev", result.rev],
|
||||
["shortRev", result.shortRev],
|
||||
["revCount", BigInt(result.revCount)],
|
||||
["lastModified", BigInt(result.lastModified)],
|
||||
["lastModifiedDate", result.lastModifiedDate],
|
||||
["submodules", result.submodules],
|
||||
["narHash", result.narHash],
|
||||
]);
|
||||
};
|
||||
|
||||
export const fetchMercurial = (_args: NixValue): NixAttrs => {
|
||||
@@ -225,7 +223,7 @@ export const fetchMercurial = (_args: NixValue): NixAttrs => {
|
||||
|
||||
export const fetchTree = (args: NixValue): NixAttrs => {
|
||||
const attrs = forceAttrs(args);
|
||||
const type = "type" in attrs ? forceStringValue(attrs.type) : "auto";
|
||||
const type = attrs.has("type") ? forceStringValue(attrs.get("type") as NixValue) : "auto";
|
||||
|
||||
switch (type) {
|
||||
case "git":
|
||||
@@ -234,12 +232,12 @@ export const fetchTree = (args: NixValue): NixAttrs => {
|
||||
case "mercurial":
|
||||
return fetchMercurial(args);
|
||||
case "tarball":
|
||||
return { outPath: fetchTarball(args) };
|
||||
return new Map<string, NixValue>([["outPath", fetchTarball(args)]]);
|
||||
case "file":
|
||||
return { outPath: fetchurl(args) };
|
||||
return new Map<string, NixValue>([["outPath", fetchurl(args)]]);
|
||||
case "path": {
|
||||
const path = forceStringValue(attrs.path);
|
||||
return { outPath: path };
|
||||
const path = forceStringValue(select(attrs, ["path"]));
|
||||
return new Map<string, NixValue>([["outPath", path]]);
|
||||
}
|
||||
case "github":
|
||||
case "gitlab":
|
||||
@@ -251,11 +249,14 @@ export const fetchTree = (args: NixValue): NixAttrs => {
|
||||
};
|
||||
|
||||
const fetchGitForge = (forge: string, attrs: NixAttrs): NixAttrs => {
|
||||
const owner = forceStringValue(attrs.owner);
|
||||
const repo = forceStringValue(attrs.repo);
|
||||
const rev =
|
||||
"rev" in attrs ? forceStringValue(attrs.rev) : "ref" in attrs ? forceStringValue(attrs.ref) : "HEAD";
|
||||
const host = "host" in attrs ? forceStringValue(attrs.host) : undefined;
|
||||
const owner = forceStringValue(select(forge, ["owner"]));
|
||||
const repo = forceStringValue(select(forge, ["repo"]));
|
||||
const rev = attrs.has("rev")
|
||||
? forceStringValue(attrs.get("rev") as NixValue)
|
||||
: attrs.has("ref")
|
||||
? forceStringValue(attrs.get("ref") as NixValue)
|
||||
: "HEAD";
|
||||
const host = attrs.has("host") ? forceStringValue(attrs.get("host") as NixValue) : undefined;
|
||||
|
||||
let tarballUrl: string;
|
||||
switch (forge) {
|
||||
@@ -278,17 +279,17 @@ const fetchGitForge = (forge: string, attrs: NixAttrs): NixAttrs => {
|
||||
throw new Error(`Unknown forge type: ${forge}`);
|
||||
}
|
||||
|
||||
const outPath = fetchTarball({ url: tarballUrl, ...attrs });
|
||||
const outPath = fetchTarball(new Map<string, NixValue>([["url", tarballUrl], ...attrs]));
|
||||
|
||||
return {
|
||||
outPath,
|
||||
rev,
|
||||
shortRev: rev.substring(0, 7),
|
||||
};
|
||||
return new Map<string, NixValue>([
|
||||
["outPath", outPath],
|
||||
["rev", rev],
|
||||
["shortRev", rev.substring(0, 7)],
|
||||
]);
|
||||
};
|
||||
|
||||
const autoDetectAndFetch = (attrs: NixAttrs): NixAttrs => {
|
||||
const url = forceStringValue(attrs.url);
|
||||
const url = forceStringValue(select(attrs, ["url"]));
|
||||
if (url.endsWith(".git") || url.includes("github.com") || url.includes("gitlab.com")) {
|
||||
return fetchGit(attrs);
|
||||
}
|
||||
@@ -298,19 +299,14 @@ const autoDetectAndFetch = (attrs: NixAttrs): NixAttrs => {
|
||||
url.endsWith(".tar.bz2") ||
|
||||
url.endsWith(".tgz")
|
||||
) {
|
||||
return { outPath: fetchTarball(attrs) };
|
||||
return new Map<string, NixValue>([["outPath", fetchTarball(attrs)]]);
|
||||
}
|
||||
return { outPath: fetchurl(attrs) };
|
||||
return new Map<string, NixValue>([["outPath", fetchurl(attrs)]]);
|
||||
};
|
||||
|
||||
export const readDir = (path: NixValue): NixAttrs => {
|
||||
const pathStr = realisePath(path);
|
||||
const entries: Record<string, string> = Deno.core.ops.op_read_dir(pathStr);
|
||||
const result: NixAttrs = {};
|
||||
for (const [name, type] of Object.entries(entries)) {
|
||||
result[name] = type;
|
||||
}
|
||||
return result;
|
||||
return Deno.core.ops.op_read_dir(pathStr);
|
||||
};
|
||||
|
||||
export const readFile = (path: NixValue): string => {
|
||||
@@ -348,11 +344,11 @@ export const pathExists = (path: NixValue): boolean => {
|
||||
export const path = (args: NixValue): NixString => {
|
||||
const attrs = forceAttrs(args);
|
||||
|
||||
if (!("path" in attrs)) {
|
||||
if (!attrs.has("path")) {
|
||||
throw new TypeError("builtins.path: 'path' attribute is required");
|
||||
}
|
||||
|
||||
const pathValue = force(attrs.path);
|
||||
const pathValue = force(attrs.get("path") as NixValue);
|
||||
let pathStr: string;
|
||||
|
||||
if (isNixPath(pathValue)) {
|
||||
@@ -361,14 +357,14 @@ export const path = (args: NixValue): NixString => {
|
||||
pathStr = forceStringValue(pathValue);
|
||||
}
|
||||
|
||||
const name = "name" in attrs ? forceStringValue(attrs.name) : null;
|
||||
const recursive = "recursive" in attrs ? forceBool(attrs.recursive) : true;
|
||||
const sha256 = "sha256" in attrs ? forceStringValue(attrs.sha256) : null;
|
||||
const name = attrs.has("name") ? forceStringValue(attrs.get("name") as NixValue) : null;
|
||||
const recursive = attrs.has("recursive") ? forceBool(attrs.get("recursive") as NixValue) : true;
|
||||
const sha256 = attrs.has("sha256") ? forceStringValue(attrs.get("sha256") as NixValue) : null;
|
||||
|
||||
let storePath: string;
|
||||
|
||||
if ("filter" in attrs) {
|
||||
const filterFn = forceFunction(attrs.filter);
|
||||
if (attrs.has("filter")) {
|
||||
const filterFn = forceFunction(attrs.get("filter") as NixValue);
|
||||
|
||||
const entries: [string, string][] = Deno.core.ops.op_walk_dir(pathStr);
|
||||
|
||||
@@ -445,9 +441,9 @@ export const findFile =
|
||||
for (const item of forcedSearchPath) {
|
||||
const attrs = forceAttrs(item);
|
||||
|
||||
const prefix = "prefix" in attrs ? forceStringNoCtx(attrs.prefix) : "";
|
||||
const prefix = attrs.has("prefix") ? forceStringNoCtx(attrs.get("prefix") as NixValue) : "";
|
||||
|
||||
if (!("path" in attrs)) {
|
||||
if (!attrs.has("path")) {
|
||||
throw new Error("findFile: search path element is missing 'path' attribute");
|
||||
}
|
||||
|
||||
@@ -457,7 +453,12 @@ export const findFile =
|
||||
}
|
||||
|
||||
const context: NixStringContext = new Set();
|
||||
const pathVal = coerceToString(attrs.path, StringCoercionMode.Interpolation, false, context);
|
||||
const pathVal = coerceToString(
|
||||
attrs.get("path") as NixValue,
|
||||
StringCoercionMode.Interpolation,
|
||||
false,
|
||||
context,
|
||||
);
|
||||
|
||||
if (context.size > 0) {
|
||||
throw new Error("findFile: path with string context is not yet supported");
|
||||
@@ -468,13 +469,13 @@ export const findFile =
|
||||
suffix.length > 0 ? Deno.core.ops.op_resolve_path(suffix, resolvedPath) : resolvedPath;
|
||||
|
||||
if (Deno.core.ops.op_path_exists(candidatePath)) {
|
||||
return { [IS_PATH]: true, value: candidatePath };
|
||||
return new NixPath(candidatePath);
|
||||
}
|
||||
}
|
||||
|
||||
if (lookupPathStr.startsWith("nix/")) {
|
||||
// FIXME: special path type
|
||||
return { [IS_PATH]: true, value: `<${lookupPathStr}>` };
|
||||
return new NixPath(`<${lookupPathStr}>`);
|
||||
}
|
||||
|
||||
throw new CatchableError(`file '${lookupPathStr}' was not found in the Nix search path`);
|
||||
|
||||
@@ -95,18 +95,19 @@ export const partition =
|
||||
(list: NixValue): NixAttrs => {
|
||||
const forcedList = forceList(list);
|
||||
const forcedPred = forceFunction(pred);
|
||||
const attrs = {
|
||||
right: [] as NixList,
|
||||
wrong: [] as NixList,
|
||||
};
|
||||
const right: NixList = [];
|
||||
const wrong: NixList = [];
|
||||
for (const elem of forcedList) {
|
||||
if (force(forcedPred(elem))) {
|
||||
attrs.right.push(elem);
|
||||
right.push(elem);
|
||||
} else {
|
||||
attrs.wrong.push(elem);
|
||||
wrong.push(elem);
|
||||
}
|
||||
}
|
||||
return attrs;
|
||||
return new Map<string, NixValue>([
|
||||
["right", right],
|
||||
["wrong", wrong],
|
||||
]);
|
||||
};
|
||||
|
||||
export const genList =
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { OrderedSet } from "js-sdsl";
|
||||
import { select } from "../helpers";
|
||||
import { compareValues } from "../operators";
|
||||
import {
|
||||
getStringContext,
|
||||
@@ -15,7 +16,7 @@ import {
|
||||
forceStringNoCtx,
|
||||
forceStringValue,
|
||||
} from "../type-assert";
|
||||
import type { NixAttrs, NixBool, NixStrictValue, NixValue } from "../types";
|
||||
import type { NixAttrs, NixStrictValue, NixValue } from "../types";
|
||||
import { ATTR_POSITIONS, CatchableError } from "../types";
|
||||
import * as context from "./context";
|
||||
import { isBool, isFloat, isInt, isList, isString, typeOf } from "./type-check";
|
||||
@@ -137,24 +138,20 @@ function componentsLt(c1: string, c2: string): boolean {
|
||||
export const functionArgs = (f: NixValue): NixAttrs => {
|
||||
const func = forceFunction(f);
|
||||
if (func.args) {
|
||||
const ret: NixAttrs = {};
|
||||
const ret: NixAttrs = new Map();
|
||||
for (const key of func.args.required) {
|
||||
ret[key] = false;
|
||||
ret.set(key, false);
|
||||
}
|
||||
for (const key of func.args.optional) {
|
||||
ret[key] = true;
|
||||
ret.set(key, true);
|
||||
}
|
||||
const positions = func.args.positions;
|
||||
if (positions && Object.keys(positions).length > 0) {
|
||||
Object.defineProperty(ret, ATTR_POSITIONS, {
|
||||
value: positions,
|
||||
enumerable: false,
|
||||
writable: false,
|
||||
});
|
||||
if (positions) {
|
||||
ret[ATTR_POSITIONS] = positions;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
return {};
|
||||
return new Map();
|
||||
};
|
||||
|
||||
const checkComparable = (value: NixStrictValue): void => {
|
||||
@@ -166,7 +163,8 @@ const checkComparable = (value: NixStrictValue): void => {
|
||||
|
||||
export const genericClosure = (args: NixValue): NixValue => {
|
||||
const forcedArgs = forceAttrs(args);
|
||||
const { startSet, operator } = forcedArgs;
|
||||
const startSet = select(forcedArgs, ["startSet"]);
|
||||
const operator = select(forcedArgs, ["operator"]);
|
||||
|
||||
const initialList = forceList(startSet);
|
||||
const opFunction = forceFunction(operator);
|
||||
@@ -177,7 +175,7 @@ export const genericClosure = (args: NixValue): NixValue => {
|
||||
|
||||
for (const item of initialList) {
|
||||
const itemAttrs = forceAttrs(item);
|
||||
const key = force(itemAttrs.key);
|
||||
const key = force(select(itemAttrs, ["key"]));
|
||||
checkComparable(key);
|
||||
if (resultSet.find(key).equals(resultSet.end())) {
|
||||
resultSet.insert(key);
|
||||
@@ -193,7 +191,7 @@ export const genericClosure = (args: NixValue): NixValue => {
|
||||
|
||||
for (const newItem of newItems) {
|
||||
const newItemAttrs = forceAttrs(newItem);
|
||||
const key = force(newItemAttrs.key);
|
||||
const key = force(select(newItemAttrs, ["key"]));
|
||||
checkComparable(key);
|
||||
if (resultSet.find(key).equals(resultSet.end())) {
|
||||
resultSet.insert(key);
|
||||
@@ -223,10 +221,10 @@ export const parseDrvName = (s: NixValue): NixAttrs => {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return {
|
||||
name,
|
||||
version,
|
||||
};
|
||||
return new Map<string, NixValue>([
|
||||
["name", name],
|
||||
["version", version],
|
||||
]);
|
||||
};
|
||||
|
||||
export const placeholder = (output: NixValue): NixValue => {
|
||||
@@ -320,23 +318,25 @@ export const splitVersion = (s: NixValue): NixValue => {
|
||||
return components;
|
||||
};
|
||||
|
||||
export const traceVerbose = (_e1: NixValue, e2: NixValue): NixStrictValue => {
|
||||
export const traceVerbose =
|
||||
(_e1: NixValue) =>
|
||||
(e2: NixValue): NixStrictValue => {
|
||||
// TODO: implement traceVerbose
|
||||
return force(e2)
|
||||
};
|
||||
|
||||
export const tryEval = (e: NixValue): { success: NixBool; value: NixStrictValue } => {
|
||||
try {
|
||||
return {
|
||||
success: true,
|
||||
value: force(e),
|
||||
return force(e2);
|
||||
};
|
||||
|
||||
export const tryEval = (e: NixValue): NixAttrs => {
|
||||
try {
|
||||
return new Map<string, NixValue>([
|
||||
["success", true],
|
||||
["value", force(e)],
|
||||
]);
|
||||
} catch (err) {
|
||||
if (err instanceof CatchableError) {
|
||||
return {
|
||||
success: false,
|
||||
value: false,
|
||||
};
|
||||
return new Map<string, NixValue>([
|
||||
["success", false],
|
||||
["value", false],
|
||||
]);
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
HAS_CONTEXT,
|
||||
isNixPath,
|
||||
isStringWithContext,
|
||||
type NixAttrs,
|
||||
@@ -19,10 +18,7 @@ export const isNixString = (v: NixStrictValue): v is NixString => {
|
||||
};
|
||||
|
||||
export const isAttrs = (e: NixStrictValue): e is NixAttrs => {
|
||||
const val = e;
|
||||
return (
|
||||
typeof val === "object" && !Array.isArray(val) && val !== null && !(HAS_CONTEXT in val) && !isPath(val)
|
||||
);
|
||||
return e instanceof Map;
|
||||
};
|
||||
|
||||
export const isBool = (e: NixStrictValue): e is NixBool => typeof e === "boolean";
|
||||
@@ -60,7 +56,7 @@ export const typeOf = (e: NixStrictValue): NixType => {
|
||||
if (isNixString(e)) return "string";
|
||||
if (isNixPath(e)) return "path";
|
||||
if (Array.isArray(e)) return "list";
|
||||
if (typeof e === "object") return "set";
|
||||
if (e instanceof Map) return "set";
|
||||
if (typeof e === "function") return "lambda";
|
||||
|
||||
throw new TypeError(`Unknown Nix type: ${typeof e}`);
|
||||
|
||||
@@ -3,12 +3,12 @@ import { isAttrs, typeOf } from "./builtins/type-check";
|
||||
import { mkPath } from "./path";
|
||||
import { isStringWithContext, mkStringWithContext, type NixStringContext } from "./string-context";
|
||||
import { force } from "./thunk";
|
||||
import { forceAttrs, forceBool, forceFunction, forceStringValue } from "./type-assert";
|
||||
import { forceAttrs, forceBool, forceFunction, forceStringNoCtx, forceStringValue } from "./type-assert";
|
||||
import type { NixAttrs, NixBool, NixPath, NixString, NixValue } from "./types";
|
||||
import { CatchableError, isNixPath } from "./types";
|
||||
|
||||
interface StackFrame {
|
||||
span: string;
|
||||
span: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ function enrichError(error: unknown): Error {
|
||||
return err;
|
||||
}
|
||||
|
||||
const pushContext = (message: string, span: string): void => {
|
||||
const pushContext = (message: string, span: number): void => {
|
||||
if (callStack.length >= MAX_STACK_DEPTH) {
|
||||
callStack.shift();
|
||||
}
|
||||
@@ -43,7 +43,7 @@ const popContext = (): void => {
|
||||
callStack.pop();
|
||||
};
|
||||
|
||||
export const withContext = <T>(message: string, span: string, fn: () => T): T => {
|
||||
export const withContext = <T>(message: string, span: number, fn: () => T): T => {
|
||||
pushContext(message, span);
|
||||
try {
|
||||
return fn();
|
||||
@@ -142,19 +142,22 @@ export const resolvePath = (currentDir: string, path: NixValue): NixPath => {
|
||||
return mkPath(resolved);
|
||||
};
|
||||
|
||||
export const select = (obj: NixValue, attrpath: NixValue[], span?: string): NixValue => {
|
||||
if (span) {
|
||||
const pathStrings = attrpath.map((a) => forceStringValue(a));
|
||||
const path = pathStrings.join(".");
|
||||
const message = path ? `while selecting attribute [${path}]` : "while selecting attribute";
|
||||
|
||||
export const select = (obj: NixValue, attrpath: NixValue[], span?: number): NixValue => {
|
||||
if (span !== undefined) {
|
||||
if (callStack.length >= MAX_STACK_DEPTH) {
|
||||
callStack.shift();
|
||||
}
|
||||
callStack.push({ span, message });
|
||||
const frame: StackFrame = { span, message: "while selecting attribute" };
|
||||
callStack.push(frame);
|
||||
try {
|
||||
return selectImpl(obj, attrpath);
|
||||
} catch (error) {
|
||||
try {
|
||||
const path = attrpath.map((a) => forceStringValue(a)).join(".");
|
||||
if (path) frame.message = `while selecting attribute [${path}]`;
|
||||
} catch {
|
||||
throw enrichError(error);
|
||||
}
|
||||
throw enrichError(error);
|
||||
} finally {
|
||||
callStack.pop();
|
||||
@@ -167,40 +170,43 @@ export const select = (obj: NixValue, attrpath: NixValue[], span?: string): NixV
|
||||
function selectImpl(obj: NixValue, attrpath: NixValue[]): NixValue {
|
||||
let attrs = forceAttrs(obj);
|
||||
|
||||
for (const attr of attrpath.slice(0, -1)) {
|
||||
const key = forceStringValue(attr);
|
||||
if (!(key in attrs)) {
|
||||
for (let i = 0; i < attrpath.length - 1; i++) {
|
||||
const key = forceStringValue(attrpath[i]);
|
||||
if (!attrs.has(key)) {
|
||||
throw new Error(`Attribute '${key}' not found`);
|
||||
}
|
||||
const cur = forceAttrs(attrs[forceStringValue(attr)]);
|
||||
const cur = forceAttrs(attrs.get(key) as NixValue);
|
||||
attrs = cur;
|
||||
}
|
||||
|
||||
const last = forceStringValue(attrpath[attrpath.length - 1]);
|
||||
if (!(last in attrs)) {
|
||||
if (!attrs.has(last)) {
|
||||
throw new Error(`Attribute '${last}' not found`);
|
||||
}
|
||||
return attrs[last];
|
||||
return attrs.get(last) as NixValue;
|
||||
}
|
||||
|
||||
export const selectWithDefault = (
|
||||
obj: NixValue,
|
||||
attrpath: NixValue[],
|
||||
defaultVal: NixValue,
|
||||
span?: string,
|
||||
span?: number,
|
||||
): NixValue => {
|
||||
if (span) {
|
||||
const pathStrings = attrpath.map((a) => forceStringValue(a));
|
||||
const path = pathStrings.join(".");
|
||||
const message = path ? `while selecting attribute [${path}]` : "while selecting attribute";
|
||||
|
||||
if (span !== undefined) {
|
||||
if (callStack.length >= MAX_STACK_DEPTH) {
|
||||
callStack.shift();
|
||||
}
|
||||
callStack.push({ span, message });
|
||||
const frame: StackFrame = { span, message: "while selecting attribute" };
|
||||
callStack.push(frame);
|
||||
try {
|
||||
return selectWithDefaultImpl(obj, attrpath, defaultVal);
|
||||
} catch (error) {
|
||||
try {
|
||||
const path = attrpath.map((a) => forceStringValue(a)).join(".");
|
||||
if (path) frame.message = `while selecting attribute [${path}]`;
|
||||
} catch {
|
||||
throw enrichError(error);
|
||||
}
|
||||
throw enrichError(error);
|
||||
} finally {
|
||||
callStack.pop();
|
||||
@@ -216,12 +222,12 @@ function selectWithDefaultImpl(obj: NixValue, attrpath: NixValue[], defaultVal:
|
||||
return defaultVal;
|
||||
}
|
||||
|
||||
for (const attr of attrpath.slice(0, -1)) {
|
||||
const key = forceStringValue(attr);
|
||||
if (!(key in attrs)) {
|
||||
for (let i = 0; i < attrpath.length - 1; i++) {
|
||||
const key = forceStringValue(attrpath[i]);
|
||||
if (!attrs.has(key)) {
|
||||
return defaultVal;
|
||||
}
|
||||
const cur = force(attrs[key]);
|
||||
const cur = force(attrs.get(key) as NixValue);
|
||||
if (!isAttrs(cur)) {
|
||||
return defaultVal;
|
||||
}
|
||||
@@ -229,8 +235,8 @@ function selectWithDefaultImpl(obj: NixValue, attrpath: NixValue[], defaultVal:
|
||||
}
|
||||
|
||||
const last = forceStringValue(attrpath[attrpath.length - 1]);
|
||||
if (last in attrs) {
|
||||
return attrs[last];
|
||||
if (attrs.has(last)) {
|
||||
return attrs.get(last) as NixValue;
|
||||
}
|
||||
return defaultVal;
|
||||
}
|
||||
@@ -242,19 +248,23 @@ export const hasAttr = (obj: NixValue, attrpath: NixValue[]): NixBool => {
|
||||
}
|
||||
let attrs = forced;
|
||||
|
||||
for (const attr of attrpath.slice(0, -1)) {
|
||||
const cur = force(attrs[forceStringValue(attr)]);
|
||||
for (let i = 0; i < attrpath.length - 1; i++) {
|
||||
const key = forceStringNoCtx(attrpath[i]);
|
||||
if (!attrs.has(key)) {
|
||||
return false;
|
||||
}
|
||||
const cur = force(attrs.get(key) as NixValue);
|
||||
if (!isAttrs(cur)) {
|
||||
return false;
|
||||
}
|
||||
attrs = cur;
|
||||
}
|
||||
|
||||
return forceStringValue(attrpath[attrpath.length - 1]) in attrs;
|
||||
return attrs.has(forceStringValue(attrpath[attrpath.length - 1]));
|
||||
};
|
||||
|
||||
export const call = (func: NixValue, arg: NixValue, span?: string): NixValue => {
|
||||
if (span) {
|
||||
export const call = (func: NixValue, arg: NixValue, span?: number): NixValue => {
|
||||
if (span !== undefined) {
|
||||
if (callStack.length >= MAX_STACK_DEPTH) {
|
||||
callStack.shift();
|
||||
}
|
||||
@@ -272,24 +282,19 @@ export const call = (func: NixValue, arg: NixValue, span?: string): NixValue =>
|
||||
};
|
||||
|
||||
function callImpl(func: NixValue, arg: NixValue): NixValue {
|
||||
const forcedFunc = force(func);
|
||||
if (typeof forcedFunc === "function") {
|
||||
forcedFunc.args?.check(arg);
|
||||
return forcedFunc(arg);
|
||||
const forced = force(func);
|
||||
if (typeof forced === "function") {
|
||||
forced.args?.check(arg);
|
||||
return forced(arg);
|
||||
}
|
||||
if (
|
||||
typeof forcedFunc === "object" &&
|
||||
!Array.isArray(forcedFunc) &&
|
||||
forcedFunc !== null &&
|
||||
"__functor" in forcedFunc
|
||||
) {
|
||||
const functor = forceFunction(forcedFunc.__functor);
|
||||
return call(functor(forcedFunc), arg);
|
||||
if (forced instanceof Map && forced.has("__functor")) {
|
||||
const functor = forceFunction(forced.get("__functor") as NixValue);
|
||||
return call(callImpl(functor, forced), arg);
|
||||
}
|
||||
throw new Error(`attempt to call something which is not a function but ${typeOf(forcedFunc)}`);
|
||||
throw new Error(`attempt to call something which is not a function but ${typeOf(forced)}`);
|
||||
}
|
||||
|
||||
export const assert = (assertion: NixValue, expr: NixValue, assertionRaw: string, span: string): NixValue => {
|
||||
export const assert = (assertion: NixValue, expr: NixValue, assertionRaw: string, span: number): NixValue => {
|
||||
if (forceBool(assertion)) {
|
||||
return expr;
|
||||
}
|
||||
@@ -299,14 +304,7 @@ export const assert = (assertion: NixValue, expr: NixValue, assertionRaw: string
|
||||
throw "unreachable";
|
||||
};
|
||||
|
||||
export const ifFunc = (cond: NixValue, consq: NixValue, alter: NixValue) => {
|
||||
if (forceBool(cond)) {
|
||||
return consq;
|
||||
}
|
||||
return alter;
|
||||
};
|
||||
|
||||
export const mkPos = (span: string): NixAttrs => {
|
||||
export const mkPos = (span: number): NixAttrs => {
|
||||
return Deno.core.ops.op_decode_span(span);
|
||||
};
|
||||
|
||||
@@ -315,12 +313,12 @@ interface WithScope {
|
||||
last: WithScope | null;
|
||||
}
|
||||
|
||||
export const lookupWith = (name: string, withScope: WithScope | null): NixValue => {
|
||||
let current = withScope;
|
||||
export const lookupWith = (name: string, withScope: WithScope): NixValue => {
|
||||
let current: WithScope | null = withScope;
|
||||
while (current !== null) {
|
||||
const attrs = forceAttrs(current.env);
|
||||
if (name in attrs) {
|
||||
return attrs[name];
|
||||
if (attrs.has(name)) {
|
||||
return attrs.get(name) as NixValue;
|
||||
}
|
||||
current = current.last;
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
*/
|
||||
|
||||
import { builtins, PRIMOP_METADATA } from "./builtins";
|
||||
import { coerceToString, StringCoercionMode } from "./builtins/conversion";
|
||||
import {
|
||||
assert,
|
||||
call,
|
||||
@@ -16,40 +15,32 @@ import {
|
||||
resolvePath,
|
||||
select,
|
||||
selectWithDefault,
|
||||
withContext,
|
||||
} from "./helpers";
|
||||
import { op } from "./operators";
|
||||
import { HAS_CONTEXT } from "./string-context";
|
||||
import {
|
||||
createThunk,
|
||||
DEBUG_THUNKS,
|
||||
force,
|
||||
forceDeep,
|
||||
forceShallow,
|
||||
IS_CYCLE,
|
||||
IS_THUNK,
|
||||
isThunk,
|
||||
} from "./thunk";
|
||||
import { createThunk, DEBUG_THUNKS, force, forceDeep, forceShallow, IS_CYCLE, IS_THUNK } from "./thunk";
|
||||
import { forceBool } from "./type-assert";
|
||||
import { ATTR_POSITIONS, IS_PATH, mkAttrs, mkAttrsWithPos, mkFunction, type NixValue } from "./types";
|
||||
import { IS_PATH, mkAttrs, mkFunction, type NixValue } from "./types";
|
||||
import { execBytecode, execBytecodeScoped, vmStrings, vmConstants } from "./vm";
|
||||
|
||||
export type NixRuntime = typeof Nix;
|
||||
|
||||
const replBindings: Record<string, NixValue> = {};
|
||||
const replBindings: Map<string, NixValue> = new Map();
|
||||
|
||||
export const Nix = {
|
||||
createThunk,
|
||||
force,
|
||||
forceShallow,
|
||||
forceDeep,
|
||||
forceBool,
|
||||
isThunk,
|
||||
IS_THUNK,
|
||||
IS_CYCLE,
|
||||
HAS_CONTEXT,
|
||||
IS_PATH,
|
||||
PRIMOP_METADATA,
|
||||
DEBUG_THUNKS,
|
||||
|
||||
createThunk,
|
||||
force,
|
||||
forceBool,
|
||||
forceShallow,
|
||||
forceDeep,
|
||||
|
||||
assert,
|
||||
call,
|
||||
hasAttr,
|
||||
@@ -57,26 +48,51 @@ export const Nix = {
|
||||
selectWithDefault,
|
||||
lookupWith,
|
||||
resolvePath,
|
||||
coerceToString,
|
||||
concatStringsWithContext,
|
||||
StringCoercionMode,
|
||||
mkAttrs,
|
||||
mkAttrsWithPos,
|
||||
mkFunction,
|
||||
mkPos,
|
||||
ATTR_POSITIONS,
|
||||
|
||||
withContext,
|
||||
|
||||
op,
|
||||
builtins,
|
||||
PRIMOP_METADATA,
|
||||
|
||||
strings: vmStrings,
|
||||
constants: vmConstants,
|
||||
execBytecode,
|
||||
execBytecodeScoped,
|
||||
|
||||
replBindings,
|
||||
setReplBinding: (name: string, value: NixValue) => {
|
||||
replBindings[name] = value;
|
||||
replBindings.set(name, value);
|
||||
},
|
||||
getReplBinding: (name: string) => replBindings[name],
|
||||
getReplBinding: (name: string) => replBindings.get(name),
|
||||
};
|
||||
|
||||
globalThis.Nix = Nix;
|
||||
globalThis.$t = createThunk;
|
||||
globalThis.$f = force;
|
||||
globalThis.$fb = forceBool;
|
||||
globalThis.$a = assert;
|
||||
globalThis.$c = call;
|
||||
globalThis.$h = hasAttr;
|
||||
globalThis.$s = select;
|
||||
globalThis.$sd = selectWithDefault;
|
||||
globalThis.$l = lookupWith;
|
||||
globalThis.$r = resolvePath;
|
||||
globalThis.$cs = concatStringsWithContext;
|
||||
globalThis.$ma = mkAttrs;
|
||||
globalThis.$mf = mkFunction;
|
||||
globalThis.$mp = mkPos;
|
||||
globalThis.$gb = Nix.getReplBinding;
|
||||
|
||||
globalThis.$oa = op.add;
|
||||
globalThis.$os = op.sub;
|
||||
globalThis.$om = op.mul;
|
||||
globalThis.$od = op.div;
|
||||
globalThis.$oe = op.eq;
|
||||
globalThis.$ol = op.lt;
|
||||
globalThis.$og = op.gt;
|
||||
globalThis.$oc = op.concat;
|
||||
globalThis.$ou = op.update;
|
||||
globalThis.$b = builtins;
|
||||
globalThis.$e = new Map();
|
||||
|
||||
@@ -16,8 +16,8 @@ import { isNixPath } from "./types";
|
||||
const canCoerceToString = (v: NixValue): boolean => {
|
||||
const forced = force(v);
|
||||
if (isNixString(forced)) return true;
|
||||
if (typeof forced === "object" && forced !== null && !Array.isArray(forced)) {
|
||||
if ("outPath" in forced || "__toString" in forced) return true;
|
||||
if (forced instanceof Map) {
|
||||
if (forced.has("outPath") || forced.has("__toString")) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
@@ -219,27 +219,24 @@ export const op = {
|
||||
const attrsA = av as NixAttrs;
|
||||
const attrsB = bv as NixAttrs;
|
||||
|
||||
// Derivation comparison: compare outPaths only
|
||||
// Safe to force 'type' because it's always a string literal, never a computed value
|
||||
if ("type" in attrsA && "type" in attrsB) {
|
||||
const typeValA = force(attrsA.type);
|
||||
const typeValB = force(attrsB.type);
|
||||
if (attrsA.has("type") && attrsB.has("type")) {
|
||||
const typeValA = force(attrsA.get("type") as NixValue);
|
||||
const typeValB = force(attrsB.get("type") as NixValue);
|
||||
if (typeValA === "derivation" && typeValB === "derivation") {
|
||||
if ("outPath" in attrsA && "outPath" in attrsB) {
|
||||
return op.eq(attrsA.outPath, attrsB.outPath);
|
||||
if (attrsA.has("outPath") && attrsB.has("outPath")) {
|
||||
return op.eq(attrsA.get("outPath") as NixValue, attrsB.get("outPath") as NixValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise, compare attributes one by one
|
||||
const keysA = Object.keys(attrsA).sort();
|
||||
const keysB = Object.keys(attrsB).sort();
|
||||
const keysA = Array.from(attrsA.keys()).sort();
|
||||
const keysB = Array.from(attrsB.keys()).sort();
|
||||
|
||||
if (keysA.length !== keysB.length) return false;
|
||||
|
||||
for (let i = 0; i < keysA.length; i++) {
|
||||
if (keysA[i] !== keysB[i]) return false;
|
||||
if (!op.eq(attrsA[keysA[i]], attrsB[keysB[i]])) return false;
|
||||
if (!op.eq(attrsA.get(keysA[i]) as NixValue, attrsB.get(keysB[i]) as NixValue)) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -270,5 +267,19 @@ export const op = {
|
||||
return forceList(a).concat(forceList(b));
|
||||
},
|
||||
|
||||
update: (a: NixValue, b: NixValue): NixAttrs => ({ ...forceAttrs(a), ...forceAttrs(b) }),
|
||||
update: (a: NixValue, b: NixValue): NixAttrs => {
|
||||
const mapA = forceAttrs(a);
|
||||
const mapB = forceAttrs(b);
|
||||
if (mapA.size === 0) {
|
||||
return mapB;
|
||||
}
|
||||
if (mapB.size === 0) {
|
||||
return mapA;
|
||||
}
|
||||
const result: NixAttrs = new Map(mapA);
|
||||
for (const [k, v] of mapB) {
|
||||
result.set(k, v);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { IS_PATH, type NixPath } from "./types";
|
||||
import { NixPath } from "./types";
|
||||
|
||||
const canonicalizePath = (path: string): string => {
|
||||
const parts: string[] = [];
|
||||
@@ -14,12 +14,11 @@ const canonicalizePath = (path: string): string => {
|
||||
const component = path.slice(i, j);
|
||||
i = j;
|
||||
|
||||
if (component === ".") {
|
||||
} else if (component === "..") {
|
||||
if (component === "..") {
|
||||
if (parts.length > 0) {
|
||||
parts.pop();
|
||||
}
|
||||
} else {
|
||||
} else if (component !== ".") {
|
||||
parts.push(component);
|
||||
}
|
||||
}
|
||||
@@ -31,7 +30,7 @@ const canonicalizePath = (path: string): string => {
|
||||
};
|
||||
|
||||
export const mkPath = (value: string): NixPath => {
|
||||
return { [IS_PATH]: true, value: canonicalizePath(value) };
|
||||
return new NixPath(canonicalizePath(value));
|
||||
};
|
||||
|
||||
export const getPathValue = (p: NixPath): string => {
|
||||
|
||||
@@ -39,16 +39,10 @@ export const printValue = (value: NixValue, seen: WeakSet<object> = new WeakSet(
|
||||
return "<LAMBDA>";
|
||||
}
|
||||
|
||||
if (typeof value === "object") {
|
||||
if (IS_CYCLE in value && (value as Record<symbol, unknown>)[IS_CYCLE] === true) {
|
||||
if (IS_CYCLE in value) {
|
||||
return "«repeated»";
|
||||
}
|
||||
|
||||
if (seen.has(value)) {
|
||||
return "«repeated»";
|
||||
}
|
||||
seen.add(value);
|
||||
|
||||
if (isNixPath(value)) {
|
||||
return value.value;
|
||||
}
|
||||
@@ -58,17 +52,27 @@ export const printValue = (value: NixValue, seen: WeakSet<object> = new WeakSet(
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
if (value.length > 0) {
|
||||
if (seen.has(value)) {
|
||||
return "«repeated»";
|
||||
}
|
||||
seen.add(value);
|
||||
}
|
||||
const items = value.map((v) => printValue(v, seen)).join(" ");
|
||||
return `[ ${items} ]`;
|
||||
}
|
||||
|
||||
const entries = Object.entries(value)
|
||||
if (seen.has(value)) {
|
||||
return "«repeated»";
|
||||
}
|
||||
if (value.size > 0) {
|
||||
seen.add(value);
|
||||
}
|
||||
|
||||
const entries = [...value.entries()]
|
||||
.map(([k, v]) => `${printSymbol(k)} = ${printValue(v, seen)};`)
|
||||
.join(" ");
|
||||
return `{${entries ? ` ${entries} ` : " "}}`;
|
||||
}
|
||||
|
||||
return "<unknown>";
|
||||
};
|
||||
|
||||
const printString = (s: string): string => {
|
||||
|
||||
@@ -22,18 +22,22 @@ export type StringContextElem = StringContextOpaque | StringContextDrvDeep | Str
|
||||
|
||||
export type NixStringContext = Set<string>;
|
||||
|
||||
export interface StringWithContext {
|
||||
readonly [HAS_CONTEXT]: true;
|
||||
export class StringWithContext {
|
||||
readonly [HAS_CONTEXT] = true as const;
|
||||
value: string;
|
||||
context: NixStringContext;
|
||||
constructor(value: string, context: NixStringContext) {
|
||||
this.value = value;
|
||||
this.context = context;
|
||||
}
|
||||
}
|
||||
|
||||
export const isStringWithContext = (v: NixStrictValue): v is StringWithContext => {
|
||||
return typeof v === "object" && v !== null && HAS_CONTEXT in v;
|
||||
return v instanceof StringWithContext;
|
||||
};
|
||||
|
||||
export const mkStringWithContext = (value: string, context: NixStringContext): StringWithContext => {
|
||||
return { [HAS_CONTEXT]: true, value, context };
|
||||
return new StringWithContext(value, context);
|
||||
};
|
||||
|
||||
export const mkPlainString = (value: string): string => value;
|
||||
@@ -45,11 +49,12 @@ export const getStringValue = (s: string | StringWithContext): string => {
|
||||
return s;
|
||||
};
|
||||
|
||||
const emptyContext: NixStringContext = new Set();
|
||||
export const getStringContext = (s: string | StringWithContext): NixStringContext => {
|
||||
if (isStringWithContext(s)) {
|
||||
return s.context;
|
||||
}
|
||||
return new Set();
|
||||
return emptyContext;
|
||||
};
|
||||
|
||||
export const mergeContexts = (...contexts: NixStringContext[]): NixStringContext => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { isAttrs, isList } from "./builtins/type-check";
|
||||
import { HAS_CONTEXT } from "./string-context";
|
||||
import type { NixStrictValue, NixThunkInterface, NixValue } from "./types";
|
||||
import { IS_PATH } from "./types";
|
||||
import { StringWithContext } from "./string-context";
|
||||
import type { NixAttrs, NixStrictValue, NixValue } from "./types";
|
||||
import { NixPath } from "./types";
|
||||
|
||||
export const IS_THUNK = Symbol("is_thunk");
|
||||
|
||||
@@ -21,8 +21,7 @@ export const DEBUG_THUNKS = { enabled: true };
|
||||
* - Evaluating (blackhole): func is undefined, result is undefined
|
||||
* - Evaluated: func is undefined, result is defined
|
||||
*/
|
||||
export class NixThunk implements NixThunkInterface {
|
||||
[key: symbol]: unknown;
|
||||
export class NixThunk {
|
||||
readonly [IS_THUNK] = true as const;
|
||||
func: (() => NixValue) | undefined;
|
||||
result: NixStrictValue | undefined;
|
||||
@@ -42,8 +41,8 @@ export class NixThunk implements NixThunkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
export const isThunk = (value: NixValue): value is NixThunkInterface => {
|
||||
return value !== null && typeof value === "object" && IS_THUNK in value && value[IS_THUNK] === true;
|
||||
export const isThunk = (value: NixValue): value is NixThunk => {
|
||||
return value instanceof NixThunk;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -112,12 +111,12 @@ export const force = (value: NixValue): NixStrictValue => {
|
||||
}
|
||||
};
|
||||
|
||||
export const createThunk = (func: () => NixValue, label?: string): NixThunkInterface => {
|
||||
export const createThunk = (func: () => NixValue, label?: string): NixThunk => {
|
||||
return new NixThunk(func, label);
|
||||
};
|
||||
|
||||
export const IS_CYCLE = Symbol("is_cycle");
|
||||
export const CYCLE_MARKER = { [IS_CYCLE]: true };
|
||||
export const CYCLE_MARKER = { [IS_CYCLE]: true as const };
|
||||
|
||||
/**
|
||||
* Deeply force a value, handling cycles by returning a special marker.
|
||||
@@ -133,16 +132,13 @@ export const forceDeep = (value: NixValue, seen: WeakSet<object> = new WeakSet()
|
||||
}
|
||||
|
||||
if (seen.has(forced)) {
|
||||
if (Array.isArray(forced)) {
|
||||
return [CYCLE_MARKER];
|
||||
}
|
||||
return CYCLE_MARKER;
|
||||
}
|
||||
if (isAttrs(forced) || isList(forced)) {
|
||||
if ((isAttrs(forced) && forced.size > 0) || (isList(forced) && forced.length > 0)) {
|
||||
seen.add(forced);
|
||||
}
|
||||
|
||||
if (HAS_CONTEXT in forced || IS_PATH in forced) {
|
||||
if (forced instanceof StringWithContext || forced instanceof NixPath) {
|
||||
return forced;
|
||||
}
|
||||
|
||||
@@ -150,10 +146,10 @@ export const forceDeep = (value: NixValue, seen: WeakSet<object> = new WeakSet()
|
||||
return forced.map((item) => forceDeep(item, seen));
|
||||
}
|
||||
|
||||
if (typeof forced === "object") {
|
||||
const result: Record<string, NixValue> = {};
|
||||
for (const [key, val] of Object.entries(forced)) {
|
||||
result[key] = forceDeep(val, seen);
|
||||
if (forced instanceof Map) {
|
||||
const result: NixAttrs = new Map();
|
||||
for (const [key, val] of forced) {
|
||||
result.set(key, forceDeep(val, seen));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -180,10 +176,10 @@ export const forceShallow = (value: NixValue): NixStrictValue => {
|
||||
}
|
||||
|
||||
if (isAttrs(forced)) {
|
||||
const result: Record<string, NixValue> = {};
|
||||
for (const [key, val] of Object.entries(forced)) {
|
||||
const forcedVal = force(val);
|
||||
result[key] = forcedVal === forced ? CYCLE_MARKER : forcedVal;
|
||||
const result: NixAttrs = new Map();
|
||||
for (const [key, val] of forced) {
|
||||
const forcedVal = force(val as NixValue);
|
||||
result.set(key, forcedVal === forced ? CYCLE_MARKER : forcedVal);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -26,9 +26,9 @@ export const forceFunction = (value: NixValue): NixFunction => {
|
||||
if (isFunction(forced)) {
|
||||
return forced;
|
||||
}
|
||||
if (typeof forced === "object" && !Array.isArray(forced) && forced !== null && "__functor" in forced) {
|
||||
if (forced instanceof Map && forced.has("__functor")) {
|
||||
const functorSet = forced as NixAttrs;
|
||||
const functor = forceFunction(functorSet.__functor);
|
||||
const functor = forceFunction(functorSet.get("__functor") as NixValue);
|
||||
return (arg: NixValue) => forceFunction(functor(functorSet))(arg);
|
||||
}
|
||||
throw new TypeError(`Expected function, got ${typeOf(forced)}`);
|
||||
|
||||
@@ -1,18 +1,22 @@
|
||||
import { PRIMOP_METADATA, type PrimopMetadata } from "./builtins";
|
||||
import { HAS_CONTEXT, isStringWithContext, type StringWithContext } from "./string-context";
|
||||
import { force, IS_THUNK } from "./thunk";
|
||||
import { type CYCLE_MARKER, force, type NixThunk } from "./thunk";
|
||||
import { forceAttrs, forceStringNoCtx } from "./type-assert";
|
||||
export { HAS_CONTEXT, isStringWithContext };
|
||||
export type { StringWithContext };
|
||||
|
||||
export const IS_PATH = Symbol("IS_PATH");
|
||||
|
||||
export interface NixPath {
|
||||
readonly [IS_PATH]: true;
|
||||
export class NixPath {
|
||||
readonly [IS_PATH] = true as const;
|
||||
value: string;
|
||||
constructor(value: string) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
export const isNixPath = (v: NixStrictValue): v is NixPath => {
|
||||
return typeof v === "object" && v !== null && IS_PATH in v;
|
||||
return v instanceof NixPath;
|
||||
};
|
||||
|
||||
export type NixInt = bigint;
|
||||
@@ -22,17 +26,20 @@ export type NixBool = boolean;
|
||||
export type NixString = string | StringWithContext;
|
||||
export type NixNull = null;
|
||||
|
||||
export const ATTR_POSITIONS = Symbol("attrPositions");
|
||||
export type NixList = NixValue[];
|
||||
// FIXME: reject contextful string
|
||||
export type NixAttrs = { [key: string]: NixValue };
|
||||
export type NixFunction = ((arg: NixValue) => NixValue) & { args?: NixArgs };
|
||||
export type NixAttrs = Map<string, NixValue> & { [ATTR_POSITIONS]?: Map<string, number> };
|
||||
export type NixFunction = ((arg: NixValue) => NixValue) & {
|
||||
args?: NixArgs;
|
||||
[PRIMOP_METADATA]?: PrimopMetadata;
|
||||
};
|
||||
export class NixArgs {
|
||||
required: string[];
|
||||
optional: string[];
|
||||
allowed: Set<string>;
|
||||
ellipsis: boolean;
|
||||
positions: Record<string, string>;
|
||||
constructor(required: string[], optional: string[], positions: Record<string, string>, ellipsis: boolean) {
|
||||
positions: Map<string, number>;
|
||||
constructor(required: string[], optional: string[], positions: Map<string, number>, ellipsis: boolean) {
|
||||
this.required = required;
|
||||
this.optional = optional;
|
||||
this.positions = positions;
|
||||
@@ -43,13 +50,13 @@ export class NixArgs {
|
||||
const attrs = forceAttrs(arg);
|
||||
|
||||
for (const key of this.required) {
|
||||
if (!Object.hasOwn(attrs, key)) {
|
||||
if (!attrs.has(key)) {
|
||||
throw new Error(`Function called without required argument '${key}'`);
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.ellipsis) {
|
||||
for (const key in attrs) {
|
||||
for (const key of attrs.keys()) {
|
||||
if (!this.allowed.has(key)) {
|
||||
throw new Error(`Function called with unexpected argument '${key}'`);
|
||||
}
|
||||
@@ -61,7 +68,7 @@ export const mkFunction = (
|
||||
f: (arg: NixValue) => NixValue,
|
||||
required: string[],
|
||||
optional: string[],
|
||||
positions: Record<string, string>,
|
||||
positions: Map<string, number>,
|
||||
ellipsis: boolean,
|
||||
): NixFunction => {
|
||||
const func: NixFunction = f;
|
||||
@@ -69,25 +76,10 @@ export const mkFunction = (
|
||||
return func;
|
||||
};
|
||||
|
||||
export const mkAttrs = (attrs: NixAttrs, keys: NixValue[], values: NixValue[]): NixAttrs => {
|
||||
const len = keys.length;
|
||||
for (let i = 0; i < len; i++) {
|
||||
const key = force(keys[i]);
|
||||
if (key === null) {
|
||||
continue;
|
||||
}
|
||||
const str = forceStringNoCtx(key);
|
||||
attrs[str] = values[i];
|
||||
}
|
||||
return attrs;
|
||||
};
|
||||
|
||||
export const ATTR_POSITIONS = Symbol("attrPositions");
|
||||
|
||||
export const mkAttrsWithPos = (
|
||||
export const mkAttrs = (
|
||||
attrs: NixAttrs,
|
||||
positions: Record<string, string>,
|
||||
dyns?: { dynKeys: NixValue[]; dynVals: NixValue[]; dynSpans: string[] },
|
||||
positions: Map<string, number>,
|
||||
dyns?: { dynKeys: NixValue[]; dynVals: NixValue[]; dynSpans: number[] },
|
||||
): NixAttrs => {
|
||||
if (dyns) {
|
||||
const len = dyns.dynKeys.length;
|
||||
@@ -97,30 +89,27 @@ export const mkAttrsWithPos = (
|
||||
continue;
|
||||
}
|
||||
const str = forceStringNoCtx(key);
|
||||
attrs[str] = dyns.dynVals[i];
|
||||
positions[str] = dyns.dynSpans[i];
|
||||
attrs.set(str, dyns.dynVals[i]);
|
||||
positions.set(str, dyns.dynSpans[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(positions).length > 0) {
|
||||
Object.defineProperty(attrs, ATTR_POSITIONS, {
|
||||
value: positions,
|
||||
enumerable: false,
|
||||
writable: false,
|
||||
});
|
||||
if (positions.size > 0) {
|
||||
attrs[ATTR_POSITIONS] = positions;
|
||||
}
|
||||
|
||||
return attrs;
|
||||
};
|
||||
|
||||
export interface NixThunkInterface {
|
||||
readonly [IS_THUNK]: true;
|
||||
func: (() => NixValue) | undefined;
|
||||
result: NixStrictValue | undefined;
|
||||
}
|
||||
|
||||
export type NixPrimitive = NixNull | NixBool | NixInt | NixFloat | NixString;
|
||||
export type NixValue = NixPrimitive | NixPath | NixList | NixAttrs | NixFunction | NixThunkInterface;
|
||||
export type NixStrictValue = Exclude<NixValue, NixThunkInterface>;
|
||||
export type NixValue =
|
||||
| NixPrimitive
|
||||
| NixPath
|
||||
| NixList
|
||||
| NixAttrs
|
||||
| NixFunction
|
||||
| NixThunk
|
||||
| typeof CYCLE_MARKER;
|
||||
export type NixStrictValue = Exclude<NixValue, NixThunk>;
|
||||
|
||||
export class CatchableError extends Error {}
|
||||
|
||||
85
nix-js/runtime-ts/src/types/global.d.ts
vendored
85
nix-js/runtime-ts/src/types/global.d.ts
vendored
@@ -1,30 +1,69 @@
|
||||
import type { NixRuntime } from "..";
|
||||
import type { builtins } from "../builtins";
|
||||
import type { FetchGitResult, FetchTarballResult, FetchUrlResult } from "../builtins/io";
|
||||
import type {
|
||||
assert,
|
||||
call,
|
||||
concatStringsWithContext,
|
||||
hasAttr,
|
||||
lookupWith,
|
||||
mkPos,
|
||||
resolvePath,
|
||||
select,
|
||||
selectWithDefault,
|
||||
} from "../helpers";
|
||||
import type { op } from "../operators";
|
||||
import type { createThunk, force } from "../thunk";
|
||||
import type { forceBool } from "../type-assert";
|
||||
import type { mkAttrs, mkFunction, NixAttrs, NixStrictValue } from "../types";
|
||||
|
||||
declare global {
|
||||
var Nix: NixRuntime;
|
||||
var $t: typeof createThunk;
|
||||
var $f: typeof force;
|
||||
var $fb: typeof forceBool;
|
||||
var $a: typeof assert;
|
||||
var $c: typeof call;
|
||||
var $h: typeof hasAttr;
|
||||
var $s: typeof select;
|
||||
var $sd: typeof selectWithDefault;
|
||||
var $l: typeof lookupWith;
|
||||
var $r: typeof resolvePath;
|
||||
var $cs: typeof concatStringsWithContext;
|
||||
var $ma: typeof mkAttrs;
|
||||
var $mf: typeof mkFunction;
|
||||
var $mp: typeof mkPos;
|
||||
var $oa: typeof op.add;
|
||||
var $os: typeof op.sub;
|
||||
var $om: typeof op.mul;
|
||||
var $od: typeof op.div;
|
||||
var $oe: typeof op.eq;
|
||||
var $ol: typeof op.lt;
|
||||
var $og: typeof op.gt;
|
||||
var $oc: typeof op.concat;
|
||||
var $ou: typeof op.update;
|
||||
var $b: typeof builtins;
|
||||
var $e: NixAttrs;
|
||||
var $gb: typeof Nix.getReplBinding;
|
||||
|
||||
namespace Deno {
|
||||
namespace core {
|
||||
namespace ops {
|
||||
function op_import(path: string): string;
|
||||
function op_scoped_import(path: string, scopeKeys: string[]): string;
|
||||
function op_import(path: string): [Uint8Array, string];
|
||||
function op_scoped_import(path: string, scopeKeys: string[]): [Uint8Array, string];
|
||||
|
||||
function op_resolve_path(currentDir: string, path: string): string;
|
||||
|
||||
function op_read_file(path: string): string;
|
||||
function op_read_file_type(path: string): string;
|
||||
function op_read_dir(path: string): Record<string, string>;
|
||||
function op_read_dir(path: string): Map<string, string>;
|
||||
function op_path_exists(path: string): boolean;
|
||||
function op_walk_dir(path: string): [string, string][];
|
||||
|
||||
function op_make_placeholder(output: string): string;
|
||||
function op_store_path(path: string): string;
|
||||
|
||||
function op_convert_hash(input: {
|
||||
hash: string;
|
||||
hashAlgo: string | null;
|
||||
toHashFormat: string;
|
||||
}): string;
|
||||
function op_convert_hash(hash: string, hashAlgo: string | null, toHashFormat: string): string;
|
||||
function op_hash_string(algo: string, data: string): string;
|
||||
function op_hash_file(algo: string, path: string): string;
|
||||
function op_parse_hash(hashStr: string, algo: string | null): { hex: string; algo: string };
|
||||
@@ -43,11 +82,7 @@ declare global {
|
||||
includePaths: string[],
|
||||
): string;
|
||||
|
||||
function op_decode_span(span: string): {
|
||||
file: string | null;
|
||||
line: number | null;
|
||||
column: number | null;
|
||||
};
|
||||
function op_decode_span(span: number): NixAttrs;
|
||||
|
||||
function op_to_file(name: string, contents: string, references: string[]): string;
|
||||
|
||||
@@ -58,20 +93,20 @@ declare global {
|
||||
function op_match(regex: string, text: string): (string | null)[] | null;
|
||||
function op_split(regex: string, text: string): (string | (string | null)[])[];
|
||||
|
||||
function op_from_json(json: string): unknown;
|
||||
function op_from_toml(toml: string): unknown;
|
||||
function op_from_json(json: string): NixStrictValue;
|
||||
function op_from_toml(toml: string): NixStrictValue;
|
||||
function op_to_xml(e: NixValue): [string, string[]];
|
||||
|
||||
function op_finalize_derivation(input: {
|
||||
name: string;
|
||||
builder: string;
|
||||
platform: string;
|
||||
outputs: string[];
|
||||
args: string[];
|
||||
env: [string, string][];
|
||||
context: string[];
|
||||
fixedOutput: { hashAlgo: string; hash: string; hashMode: string } | null;
|
||||
}): { drvPath: string; outputs: [string, string][] };
|
||||
function op_finalize_derivation(
|
||||
name: string,
|
||||
builder: string,
|
||||
platform: string,
|
||||
outputs: string[],
|
||||
args: string[],
|
||||
env: [string, string][],
|
||||
context: string[],
|
||||
fixedOutput: { hashAlgo: string; hash: string; hashMode: string } | null,
|
||||
): { drvPath: string; outputs: [string, string][] };
|
||||
|
||||
function op_fetch_url(
|
||||
url: string,
|
||||
|
||||
617
nix-js/runtime-ts/src/vm.ts
Normal file
617
nix-js/runtime-ts/src/vm.ts
Normal file
@@ -0,0 +1,617 @@
|
||||
import {
|
||||
assert,
|
||||
call,
|
||||
concatStringsWithContext,
|
||||
hasAttr,
|
||||
lookupWith,
|
||||
mkPos,
|
||||
resolvePath,
|
||||
select,
|
||||
selectWithDefault,
|
||||
} from "./helpers";
|
||||
import { op } from "./operators";
|
||||
import { NixThunk } from "./thunk";
|
||||
import { forceBool } from "./type-assert";
|
||||
import { mkAttrs, NixArgs, type NixAttrs, type NixFunction, type NixValue } from "./types";
|
||||
import { builtins } from "./builtins";
|
||||
|
||||
enum Op {
|
||||
PushConst = 0x01,
|
||||
PushString = 0x02,
|
||||
PushNull = 0x03,
|
||||
PushTrue = 0x04,
|
||||
PushFalse = 0x05,
|
||||
|
||||
LoadLocal = 0x06,
|
||||
LoadOuter = 0x07,
|
||||
StoreLocal = 0x08,
|
||||
AllocLocals = 0x09,
|
||||
|
||||
MakeThunk = 0x0A,
|
||||
MakeClosure = 0x0B,
|
||||
MakePatternClosure = 0x0C,
|
||||
|
||||
Call = 0x0D,
|
||||
CallNoSpan = 0x0E,
|
||||
|
||||
MakeAttrs = 0x0F,
|
||||
MakeAttrsDyn = 0x10,
|
||||
MakeEmptyAttrs = 0x11,
|
||||
Select = 0x12,
|
||||
SelectDefault = 0x13,
|
||||
HasAttr = 0x14,
|
||||
|
||||
MakeList = 0x15,
|
||||
|
||||
OpAdd = 0x16,
|
||||
OpSub = 0x17,
|
||||
OpMul = 0x18,
|
||||
OpDiv = 0x19,
|
||||
OpEq = 0x20,
|
||||
OpNeq = 0x21,
|
||||
OpLt = 0x22,
|
||||
OpGt = 0x23,
|
||||
OpLeq = 0x24,
|
||||
OpGeq = 0x25,
|
||||
OpConcat = 0x26,
|
||||
OpUpdate = 0x27,
|
||||
|
||||
OpNeg = 0x28,
|
||||
OpNot = 0x29,
|
||||
|
||||
ForceBool = 0x30,
|
||||
JumpIfFalse = 0x31,
|
||||
JumpIfTrue = 0x32,
|
||||
Jump = 0x33,
|
||||
|
||||
ConcatStrings = 0x34,
|
||||
ResolvePath = 0x35,
|
||||
|
||||
Assert = 0x36,
|
||||
|
||||
PushWith = 0x37,
|
||||
PopWith = 0x38,
|
||||
WithLookup = 0x39,
|
||||
|
||||
LoadBuiltins = 0x40,
|
||||
LoadBuiltin = 0x41,
|
||||
|
||||
MkPos = 0x43,
|
||||
|
||||
LoadReplBinding = 0x44,
|
||||
LoadScopedBinding = 0x45,
|
||||
|
||||
Return = 0x46,
|
||||
}
|
||||
|
||||
interface ScopeChain {
|
||||
locals: NixValue[];
|
||||
parent: ScopeChain | null;
|
||||
}
|
||||
|
||||
interface WithScope {
|
||||
env: NixValue;
|
||||
last: WithScope | null;
|
||||
}
|
||||
|
||||
const strings: string[] = [];
|
||||
const constants: NixValue[] = [];
|
||||
|
||||
const $e: NixAttrs = new Map();
|
||||
|
||||
function readU16(code: Uint8Array, offset: number): number {
|
||||
return code[offset] | (code[offset + 1] << 8);
|
||||
}
|
||||
|
||||
function readU32(code: Uint8Array, offset: number): number {
|
||||
return (
|
||||
code[offset] |
|
||||
(code[offset + 1] << 8) |
|
||||
(code[offset + 2] << 16) |
|
||||
(code[offset + 3] << 24)
|
||||
) >>> 0;
|
||||
}
|
||||
|
||||
function readI32(code: Uint8Array, offset: number): number {
|
||||
return code[offset] | (code[offset + 1] << 8) | (code[offset + 2] << 16) | (code[offset + 3] << 24);
|
||||
}
|
||||
|
||||
export function execBytecode(code: Uint8Array, currentDir: string): NixValue {
|
||||
const chain: ScopeChain = { locals: [], parent: null };
|
||||
return execFrame(code, 0, chain, currentDir, null, null);
|
||||
}
|
||||
|
||||
export function execBytecodeScoped(
|
||||
code: Uint8Array,
|
||||
currentDir: string,
|
||||
scopeMap: NixAttrs,
|
||||
): NixValue {
|
||||
const chain: ScopeChain = { locals: [], parent: null };
|
||||
return execFrame(code, 0, chain, currentDir, null, scopeMap);
|
||||
}
|
||||
|
||||
function execFrame(
|
||||
code: Uint8Array,
|
||||
startPc: number,
|
||||
chain: ScopeChain,
|
||||
currentDir: string,
|
||||
withScope: WithScope | null,
|
||||
scopeMap: NixAttrs | null,
|
||||
): NixValue {
|
||||
const locals = chain.locals;
|
||||
const stack: NixValue[] = [];
|
||||
let pc = startPc;
|
||||
|
||||
for (;;) {
|
||||
const opcode = code[pc++];
|
||||
switch (opcode) {
|
||||
case Op.PushConst: {
|
||||
const idx = readU32(code, pc);
|
||||
pc += 4;
|
||||
stack.push(constants[idx]);
|
||||
break;
|
||||
}
|
||||
case Op.PushString: {
|
||||
const idx = readU32(code, pc);
|
||||
pc += 4;
|
||||
stack.push(strings[idx]);
|
||||
break;
|
||||
}
|
||||
case Op.PushNull:
|
||||
stack.push(null);
|
||||
break;
|
||||
case Op.PushTrue:
|
||||
stack.push(true);
|
||||
break;
|
||||
case Op.PushFalse:
|
||||
stack.push(false);
|
||||
break;
|
||||
|
||||
case Op.LoadLocal: {
|
||||
const idx = readU32(code, pc);
|
||||
pc += 4;
|
||||
stack.push(locals[idx]);
|
||||
break;
|
||||
}
|
||||
case Op.LoadOuter: {
|
||||
const layer = code[pc++];
|
||||
const idx = readU32(code, pc);
|
||||
pc += 4;
|
||||
let c: ScopeChain = chain;
|
||||
for (let i = 0; i < layer; i++) c = c.parent!;
|
||||
stack.push(c.locals[idx]);
|
||||
break;
|
||||
}
|
||||
case Op.StoreLocal: {
|
||||
const idx = readU32(code, pc);
|
||||
pc += 4;
|
||||
locals[idx] = stack.pop()!;
|
||||
break;
|
||||
}
|
||||
case Op.AllocLocals: {
|
||||
const n = readU32(code, pc);
|
||||
pc += 4;
|
||||
for (let i = 0; i < n; i++) locals.push(null);
|
||||
break;
|
||||
}
|
||||
|
||||
case Op.MakeThunk: {
|
||||
const bodyPc = readU32(code, pc);
|
||||
pc += 4;
|
||||
const labelIdx = readU32(code, pc);
|
||||
pc += 4;
|
||||
const label = strings[labelIdx];
|
||||
const scopeChain = chain;
|
||||
const scopeCode = code;
|
||||
const scopeDir = currentDir;
|
||||
const scopeWith = withScope;
|
||||
stack.push(
|
||||
new NixThunk(
|
||||
() => execFrame(scopeCode, bodyPc, scopeChain, scopeDir, scopeWith, null),
|
||||
label,
|
||||
),
|
||||
);
|
||||
break;
|
||||
}
|
||||
case Op.MakeClosure: {
|
||||
const bodyPc = readU32(code, pc);
|
||||
pc += 4;
|
||||
const nSlots = readU32(code, pc);
|
||||
pc += 4;
|
||||
const closureChain = chain;
|
||||
const closureCode = code;
|
||||
const closureDir = currentDir;
|
||||
const closureWith = withScope;
|
||||
const func: NixFunction = (arg: NixValue) => {
|
||||
const innerLocals = new Array<NixValue>(1 + nSlots).fill(null);
|
||||
innerLocals[0] = arg;
|
||||
const innerChain: ScopeChain = { locals: innerLocals, parent: closureChain };
|
||||
return execFrame(closureCode, bodyPc, innerChain, closureDir, closureWith, null);
|
||||
};
|
||||
stack.push(func);
|
||||
break;
|
||||
}
|
||||
case Op.MakePatternClosure: {
|
||||
const bodyPc = readU32(code, pc);
|
||||
pc += 4;
|
||||
const nSlots = readU32(code, pc);
|
||||
pc += 4;
|
||||
const nRequired = readU16(code, pc);
|
||||
pc += 2;
|
||||
const nOptional = readU16(code, pc);
|
||||
pc += 2;
|
||||
const hasEllipsis = code[pc++] !== 0;
|
||||
|
||||
const required: string[] = [];
|
||||
for (let i = 0; i < nRequired; i++) {
|
||||
required.push(strings[readU32(code, pc)]);
|
||||
pc += 4;
|
||||
}
|
||||
const optional: string[] = [];
|
||||
for (let i = 0; i < nOptional; i++) {
|
||||
optional.push(strings[readU32(code, pc)]);
|
||||
pc += 4;
|
||||
}
|
||||
const positions = new Map<string, number>();
|
||||
const nTotal = nRequired + nOptional;
|
||||
for (let i = 0; i < nTotal; i++) {
|
||||
const nameIdx = readU32(code, pc);
|
||||
pc += 4;
|
||||
const spanId = readU32(code, pc);
|
||||
pc += 4;
|
||||
positions.set(strings[nameIdx], spanId);
|
||||
}
|
||||
|
||||
const closureChain = chain;
|
||||
const closureCode = code;
|
||||
const closureDir = currentDir;
|
||||
const closureWith = withScope;
|
||||
const func: NixFunction = (arg: NixValue) => {
|
||||
const innerLocals = new Array<NixValue>(1 + nSlots).fill(null);
|
||||
innerLocals[0] = arg;
|
||||
const innerChain: ScopeChain = { locals: innerLocals, parent: closureChain };
|
||||
return execFrame(closureCode, bodyPc, innerChain, closureDir, closureWith, null);
|
||||
};
|
||||
func.args = new NixArgs(required, optional, positions, hasEllipsis);
|
||||
stack.push(func);
|
||||
break;
|
||||
}
|
||||
|
||||
case Op.Call: {
|
||||
const spanId = readU32(code, pc);
|
||||
pc += 4;
|
||||
const arg = stack.pop()!;
|
||||
const func = stack.pop()!;
|
||||
stack.push(call(func, arg, spanId));
|
||||
break;
|
||||
}
|
||||
case Op.CallNoSpan: {
|
||||
const arg = stack.pop()!;
|
||||
const func = stack.pop()!;
|
||||
stack.push(call(func, arg));
|
||||
break;
|
||||
}
|
||||
|
||||
case Op.MakeAttrs: {
|
||||
const n = readU32(code, pc);
|
||||
pc += 4;
|
||||
const spanValues: number[] = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
spanValues.push(stack.pop() as number);
|
||||
}
|
||||
spanValues.reverse();
|
||||
const map: NixAttrs = new Map();
|
||||
const posMap = new Map<string, number>();
|
||||
const pairs: [string, NixValue][] = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const val = stack.pop()!;
|
||||
const key = stack.pop() as string;
|
||||
pairs.push([key, val]);
|
||||
}
|
||||
pairs.reverse();
|
||||
for (let i = 0; i < n; i++) {
|
||||
map.set(pairs[i][0], pairs[i][1]);
|
||||
posMap.set(pairs[i][0], spanValues[i]);
|
||||
}
|
||||
stack.push(mkAttrs(map, posMap));
|
||||
break;
|
||||
}
|
||||
case Op.MakeAttrsDyn: {
|
||||
const nStatic = readU32(code, pc);
|
||||
pc += 4;
|
||||
const nDyn = readU32(code, pc);
|
||||
pc += 4;
|
||||
|
||||
const dynTriples: [NixValue, NixValue, number][] = [];
|
||||
for (let i = 0; i < nDyn; i++) {
|
||||
const dynSpan = stack.pop() as number;
|
||||
const dynVal = stack.pop()!;
|
||||
const dynKey = stack.pop()!;
|
||||
dynTriples.push([dynKey, dynVal, dynSpan]);
|
||||
}
|
||||
dynTriples.reverse();
|
||||
|
||||
const spanValues: number[] = [];
|
||||
for (let i = 0; i < nStatic; i++) {
|
||||
spanValues.push(stack.pop() as number);
|
||||
}
|
||||
spanValues.reverse();
|
||||
|
||||
const map: NixAttrs = new Map();
|
||||
const posMap = new Map<string, number>();
|
||||
const pairs: [string, NixValue][] = [];
|
||||
for (let i = 0; i < nStatic; i++) {
|
||||
const val = stack.pop()!;
|
||||
const key = stack.pop() as string;
|
||||
pairs.push([key, val]);
|
||||
}
|
||||
pairs.reverse();
|
||||
for (let i = 0; i < nStatic; i++) {
|
||||
map.set(pairs[i][0], pairs[i][1]);
|
||||
posMap.set(pairs[i][0], spanValues[i]);
|
||||
}
|
||||
|
||||
const dynKeys: NixValue[] = [];
|
||||
const dynVals: NixValue[] = [];
|
||||
const dynSpans: number[] = [];
|
||||
for (const [k, v, s] of dynTriples) {
|
||||
dynKeys.push(k);
|
||||
dynVals.push(v);
|
||||
dynSpans.push(s);
|
||||
}
|
||||
|
||||
stack.push(mkAttrs(map, posMap, { dynKeys, dynVals, dynSpans }));
|
||||
break;
|
||||
}
|
||||
case Op.MakeEmptyAttrs:
|
||||
stack.push($e);
|
||||
break;
|
||||
|
||||
case Op.Select: {
|
||||
const nKeys = readU16(code, pc);
|
||||
pc += 2;
|
||||
const spanId = readU32(code, pc);
|
||||
pc += 4;
|
||||
const keys: NixValue[] = [];
|
||||
for (let i = 0; i < nKeys; i++) keys.push(stack.pop()!);
|
||||
keys.reverse();
|
||||
const obj = stack.pop()!;
|
||||
stack.push(select(obj, keys, spanId));
|
||||
break;
|
||||
}
|
||||
case Op.SelectDefault: {
|
||||
const nKeys = readU16(code, pc);
|
||||
pc += 2;
|
||||
const spanId = readU32(code, pc);
|
||||
pc += 4;
|
||||
const defaultVal = stack.pop()!;
|
||||
const keys: NixValue[] = [];
|
||||
for (let i = 0; i < nKeys; i++) keys.push(stack.pop()!);
|
||||
keys.reverse();
|
||||
const obj = stack.pop()!;
|
||||
stack.push(selectWithDefault(obj, keys, defaultVal, spanId));
|
||||
break;
|
||||
}
|
||||
case Op.HasAttr: {
|
||||
const nKeys = readU16(code, pc);
|
||||
pc += 2;
|
||||
const keys: NixValue[] = [];
|
||||
for (let i = 0; i < nKeys; i++) keys.push(stack.pop()!);
|
||||
keys.reverse();
|
||||
const obj = stack.pop()!;
|
||||
stack.push(hasAttr(obj, keys));
|
||||
break;
|
||||
}
|
||||
|
||||
case Op.MakeList: {
|
||||
const count = readU32(code, pc);
|
||||
pc += 4;
|
||||
const items: NixValue[] = new Array(count);
|
||||
for (let i = count - 1; i >= 0; i--) {
|
||||
items[i] = stack.pop()!;
|
||||
}
|
||||
stack.push(items);
|
||||
break;
|
||||
}
|
||||
|
||||
case Op.OpAdd: {
|
||||
const b = stack.pop()!;
|
||||
const a = stack.pop()!;
|
||||
stack.push(op.add(a, b));
|
||||
break;
|
||||
}
|
||||
case Op.OpSub: {
|
||||
const b = stack.pop()!;
|
||||
const a = stack.pop()!;
|
||||
stack.push(op.sub(a, b));
|
||||
break;
|
||||
}
|
||||
case Op.OpMul: {
|
||||
const b = stack.pop()!;
|
||||
const a = stack.pop()!;
|
||||
stack.push(op.mul(a, b));
|
||||
break;
|
||||
}
|
||||
case Op.OpDiv: {
|
||||
const b = stack.pop()!;
|
||||
const a = stack.pop()!;
|
||||
stack.push(op.div(a, b));
|
||||
break;
|
||||
}
|
||||
case Op.OpEq: {
|
||||
const b = stack.pop()!;
|
||||
const a = stack.pop()!;
|
||||
stack.push(op.eq(a, b));
|
||||
break;
|
||||
}
|
||||
case Op.OpNeq: {
|
||||
const b = stack.pop()!;
|
||||
const a = stack.pop()!;
|
||||
stack.push(!op.eq(a, b));
|
||||
break;
|
||||
}
|
||||
case Op.OpLt: {
|
||||
const b = stack.pop()!;
|
||||
const a = stack.pop()!;
|
||||
stack.push(op.lt(a, b));
|
||||
break;
|
||||
}
|
||||
case Op.OpGt: {
|
||||
const b = stack.pop()!;
|
||||
const a = stack.pop()!;
|
||||
stack.push(op.gt(a, b));
|
||||
break;
|
||||
}
|
||||
case Op.OpLeq: {
|
||||
const b = stack.pop()!;
|
||||
const a = stack.pop()!;
|
||||
stack.push(!op.gt(a, b));
|
||||
break;
|
||||
}
|
||||
case Op.OpGeq: {
|
||||
const b = stack.pop()!;
|
||||
const a = stack.pop()!;
|
||||
stack.push(!op.lt(a, b));
|
||||
break;
|
||||
}
|
||||
case Op.OpConcat: {
|
||||
const b = stack.pop()!;
|
||||
const a = stack.pop()!;
|
||||
stack.push(op.concat(a, b));
|
||||
break;
|
||||
}
|
||||
case Op.OpUpdate: {
|
||||
const b = stack.pop()!;
|
||||
const a = stack.pop()!;
|
||||
stack.push(op.update(a, b));
|
||||
break;
|
||||
}
|
||||
|
||||
case Op.OpNeg: {
|
||||
const a = stack.pop()!;
|
||||
stack.push(op.sub(0n, a));
|
||||
break;
|
||||
}
|
||||
case Op.OpNot: {
|
||||
const a = stack.pop()!;
|
||||
stack.push(!forceBool(a));
|
||||
break;
|
||||
}
|
||||
|
||||
case Op.ForceBool: {
|
||||
const val = stack.pop()!;
|
||||
stack.push(forceBool(val));
|
||||
break;
|
||||
}
|
||||
case Op.JumpIfFalse: {
|
||||
const offset = readI32(code, pc);
|
||||
pc += 4;
|
||||
const val = stack.pop()!;
|
||||
if (val === false) {
|
||||
pc += offset;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Op.JumpIfTrue: {
|
||||
const offset = readI32(code, pc);
|
||||
pc += 4;
|
||||
const val = stack.pop()!;
|
||||
if (val === true) {
|
||||
pc += offset;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Op.Jump: {
|
||||
const offset = readI32(code, pc);
|
||||
pc += 4;
|
||||
pc += offset;
|
||||
break;
|
||||
}
|
||||
|
||||
case Op.ConcatStrings: {
|
||||
const nParts = readU16(code, pc);
|
||||
pc += 2;
|
||||
const forceString = code[pc++] !== 0;
|
||||
const parts: NixValue[] = new Array(nParts);
|
||||
for (let i = nParts - 1; i >= 0; i--) {
|
||||
parts[i] = stack.pop()!;
|
||||
}
|
||||
stack.push(concatStringsWithContext(parts, forceString));
|
||||
break;
|
||||
}
|
||||
case Op.ResolvePath: {
|
||||
const pathExpr = stack.pop()!;
|
||||
stack.push(resolvePath(currentDir, pathExpr));
|
||||
break;
|
||||
}
|
||||
|
||||
case Op.Assert: {
|
||||
const rawIdx = readU32(code, pc);
|
||||
pc += 4;
|
||||
const spanId = readU32(code, pc);
|
||||
pc += 4;
|
||||
const expr = stack.pop()!;
|
||||
const assertion = stack.pop()!;
|
||||
stack.push(assert(assertion, expr, strings[rawIdx], spanId));
|
||||
break;
|
||||
}
|
||||
|
||||
case Op.PushWith: {
|
||||
const namespace = stack.pop()!;
|
||||
withScope = { env: namespace, last: withScope };
|
||||
break;
|
||||
}
|
||||
case Op.PopWith:
|
||||
withScope = withScope!.last;
|
||||
break;
|
||||
case Op.WithLookup: {
|
||||
const nameIdx = readU32(code, pc);
|
||||
pc += 4;
|
||||
stack.push(lookupWith(strings[nameIdx], withScope!));
|
||||
break;
|
||||
}
|
||||
|
||||
case Op.LoadBuiltins:
|
||||
stack.push(builtins);
|
||||
break;
|
||||
case Op.LoadBuiltin: {
|
||||
const idx = readU32(code, pc);
|
||||
pc += 4;
|
||||
stack.push(builtins.get(strings[idx])!);
|
||||
break;
|
||||
}
|
||||
|
||||
case Op.MkPos: {
|
||||
const spanId = readU32(code, pc);
|
||||
pc += 4;
|
||||
stack.push(mkPos(spanId));
|
||||
break;
|
||||
}
|
||||
|
||||
case Op.LoadReplBinding: {
|
||||
const idx = readU32(code, pc);
|
||||
pc += 4;
|
||||
stack.push(Nix.getReplBinding(strings[idx]));
|
||||
break;
|
||||
}
|
||||
case Op.LoadScopedBinding: {
|
||||
const idx = readU32(code, pc);
|
||||
pc += 4;
|
||||
stack.push(scopeMap!.get(strings[idx])!);
|
||||
break;
|
||||
}
|
||||
|
||||
case Op.Return:
|
||||
return stack.pop()!;
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown bytecode opcode: ${opcode ? `0x${opcode.toString(16)}` : "undefined"} at pc=${pc - 1}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
declare const Nix: {
|
||||
getReplBinding: (name: string) => NixValue;
|
||||
};
|
||||
|
||||
export { strings as vmStrings, constants as vmConstants };
|
||||
906
nix-js/src/bytecode.rs
Normal file
906
nix-js/src/bytecode.rs
Normal file
@@ -0,0 +1,906 @@
|
||||
use std::ops::Deref;
|
||||
use std::path::Path;
|
||||
|
||||
use hashbrown::HashMap;
|
||||
use num_enum::TryFromPrimitive;
|
||||
use rnix::TextRange;
|
||||
|
||||
use crate::ir::{ArgId, Attr, BinOpKind, Ir, Param, RawIrRef, SymId, ThunkId, UnOpKind};
|
||||
|
||||
#[derive(Clone, Hash, Eq, PartialEq)]
|
||||
pub(crate) enum Constant {
|
||||
Int(i64),
|
||||
Float(u64),
|
||||
}
|
||||
|
||||
pub struct Bytecode {
|
||||
pub code: Box<[u8]>,
|
||||
pub current_dir: String,
|
||||
}
|
||||
|
||||
pub(crate) trait BytecodeContext {
|
||||
fn intern_string(&mut self, s: &str) -> u32;
|
||||
fn intern_constant(&mut self, c: Constant) -> u32;
|
||||
fn register_span(&self, range: TextRange) -> u32;
|
||||
fn get_sym(&self, id: SymId) -> &str;
|
||||
fn get_current_dir(&self) -> &Path;
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Clone, Copy, TryFromPrimitive)]
|
||||
#[allow(clippy::enum_variant_names)]
|
||||
pub enum Op {
|
||||
PushConst = 0x01,
|
||||
PushString = 0x02,
|
||||
PushNull = 0x03,
|
||||
PushTrue = 0x04,
|
||||
PushFalse = 0x05,
|
||||
|
||||
LoadLocal = 0x06,
|
||||
LoadOuter = 0x07,
|
||||
StoreLocal = 0x08,
|
||||
AllocLocals = 0x09,
|
||||
|
||||
MakeThunk = 0x0A,
|
||||
MakeClosure = 0x0B,
|
||||
MakePatternClosure = 0x0C,
|
||||
|
||||
Call = 0x0D,
|
||||
CallNoSpan = 0x0E,
|
||||
|
||||
MakeAttrs = 0x0F,
|
||||
MakeAttrsDyn = 0x10,
|
||||
MakeEmptyAttrs = 0x11,
|
||||
Select = 0x12,
|
||||
SelectDefault = 0x13,
|
||||
HasAttr = 0x14,
|
||||
|
||||
MakeList = 0x15,
|
||||
|
||||
OpAdd = 0x16,
|
||||
OpSub = 0x17,
|
||||
OpMul = 0x18,
|
||||
OpDiv = 0x19,
|
||||
OpEq = 0x20,
|
||||
OpNeq = 0x21,
|
||||
OpLt = 0x22,
|
||||
OpGt = 0x23,
|
||||
OpLeq = 0x24,
|
||||
OpGeq = 0x25,
|
||||
OpConcat = 0x26,
|
||||
OpUpdate = 0x27,
|
||||
|
||||
OpNeg = 0x28,
|
||||
OpNot = 0x29,
|
||||
|
||||
ForceBool = 0x30,
|
||||
JumpIfFalse = 0x31,
|
||||
JumpIfTrue = 0x32,
|
||||
Jump = 0x33,
|
||||
|
||||
ConcatStrings = 0x34,
|
||||
ResolvePath = 0x35,
|
||||
|
||||
Assert = 0x36,
|
||||
|
||||
PushWith = 0x37,
|
||||
PopWith = 0x38,
|
||||
WithLookup = 0x39,
|
||||
|
||||
LoadBuiltins = 0x40,
|
||||
LoadBuiltin = 0x41,
|
||||
|
||||
MkPos = 0x43,
|
||||
|
||||
LoadReplBinding = 0x44,
|
||||
LoadScopedBinding = 0x45,
|
||||
|
||||
Return = 0x46,
|
||||
}
|
||||
|
||||
struct ScopeInfo {
|
||||
depth: u16,
|
||||
arg_id: Option<ArgId>,
|
||||
thunk_map: HashMap<ThunkId, u32>,
|
||||
}
|
||||
|
||||
struct BytecodeEmitter<'a, Ctx: BytecodeContext> {
|
||||
ctx: &'a mut Ctx,
|
||||
code: Vec<u8>,
|
||||
scope_stack: Vec<ScopeInfo>,
|
||||
}
|
||||
|
||||
pub(crate) fn compile_bytecode(ir: RawIrRef<'_>, ctx: &mut impl BytecodeContext) -> Bytecode {
|
||||
let current_dir = ctx.get_current_dir().to_string_lossy().to_string();
|
||||
let mut emitter = BytecodeEmitter::new(ctx);
|
||||
emitter.emit_toplevel(ir);
|
||||
Bytecode {
|
||||
code: emitter.code.into_boxed_slice(),
|
||||
current_dir,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn compile_bytecode_scoped(
|
||||
ir: RawIrRef<'_>,
|
||||
ctx: &mut impl BytecodeContext,
|
||||
) -> Bytecode {
|
||||
let current_dir = ctx.get_current_dir().to_string_lossy().to_string();
|
||||
let mut emitter = BytecodeEmitter::new(ctx);
|
||||
emitter.emit_toplevel_scoped(ir);
|
||||
Bytecode {
|
||||
code: emitter.code.into_boxed_slice(),
|
||||
current_dir,
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Ctx: BytecodeContext> BytecodeEmitter<'a, Ctx> {
|
||||
fn new(ctx: &'a mut Ctx) -> Self {
|
||||
Self {
|
||||
ctx,
|
||||
code: Vec::with_capacity(4096),
|
||||
scope_stack: Vec::with_capacity(32),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn emit_op(&mut self, op: Op) {
|
||||
self.code.push(op as u8);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn emit_u8(&mut self, val: u8) {
|
||||
self.code.push(val);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn emit_u16(&mut self, val: u16) {
|
||||
self.code.extend_from_slice(&val.to_le_bytes());
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn emit_u32(&mut self, val: u32) {
|
||||
self.code.extend_from_slice(&val.to_le_bytes());
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn emit_i32_placeholder(&mut self) -> usize {
|
||||
let offset = self.code.len();
|
||||
self.code.extend_from_slice(&[0u8; 4]);
|
||||
offset
|
||||
}
|
||||
#[inline]
|
||||
fn patch_i32(&mut self, offset: usize, val: i32) {
|
||||
self.code[offset..offset + 4].copy_from_slice(&val.to_le_bytes());
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn emit_jump_placeholder(&mut self) -> usize {
|
||||
self.emit_op(Op::Jump);
|
||||
self.emit_i32_placeholder()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn patch_jump_target(&mut self, placeholder_offset: usize) {
|
||||
let current_pos = self.code.len();
|
||||
let relative_offset = (current_pos as i32) - (placeholder_offset as i32) - 4;
|
||||
self.patch_i32(placeholder_offset, relative_offset);
|
||||
}
|
||||
|
||||
fn current_depth(&self) -> u16 {
|
||||
self.scope_stack.last().map_or(0, |s| s.depth)
|
||||
}
|
||||
|
||||
fn resolve_thunk(&self, id: ThunkId) -> (u16, u32) {
|
||||
for scope in self.scope_stack.iter().rev() {
|
||||
if let Some(&local_idx) = scope.thunk_map.get(&id) {
|
||||
let layer = self.current_depth() - scope.depth;
|
||||
return (layer, local_idx);
|
||||
}
|
||||
}
|
||||
panic!("ThunkId {:?} not found in any scope", id);
|
||||
}
|
||||
|
||||
fn resolve_arg(&self, id: ArgId) -> (u16, u32) {
|
||||
for scope in self.scope_stack.iter().rev() {
|
||||
if scope.arg_id == Some(id) {
|
||||
let layer = self.current_depth() - scope.depth;
|
||||
return (layer, 0);
|
||||
}
|
||||
}
|
||||
panic!("ArgId {:?} not found in any scope", id);
|
||||
}
|
||||
|
||||
fn emit_load(&mut self, layer: u16, local: u32) {
|
||||
if layer == 0 {
|
||||
self.emit_op(Op::LoadLocal);
|
||||
self.emit_u32(local);
|
||||
} else {
|
||||
self.emit_op(Op::LoadOuter);
|
||||
self.emit_u8(layer as u8);
|
||||
self.emit_u32(local);
|
||||
}
|
||||
}
|
||||
|
||||
fn count_with_thunks(&self, ir: RawIrRef<'_>) -> usize {
|
||||
match ir.deref() {
|
||||
Ir::With { thunks, body, .. } => thunks.len() + self.count_with_thunks(*body),
|
||||
Ir::TopLevel { thunks, body } => thunks.len() + self.count_with_thunks(*body),
|
||||
Ir::If { cond, consq, alter } => {
|
||||
self.count_with_thunks(*cond)
|
||||
+ self.count_with_thunks(*consq)
|
||||
+ self.count_with_thunks(*alter)
|
||||
}
|
||||
Ir::BinOp { lhs, rhs, .. } => {
|
||||
self.count_with_thunks(*lhs) + self.count_with_thunks(*rhs)
|
||||
}
|
||||
Ir::UnOp { rhs, .. } => self.count_with_thunks(*rhs),
|
||||
Ir::Call { func, arg, .. } => {
|
||||
self.count_with_thunks(*func) + self.count_with_thunks(*arg)
|
||||
}
|
||||
Ir::Assert {
|
||||
assertion, expr, ..
|
||||
} => self.count_with_thunks(*assertion) + self.count_with_thunks(*expr),
|
||||
Ir::Select { expr, default, .. } => {
|
||||
self.count_with_thunks(*expr) + default.map_or(0, |d| self.count_with_thunks(d))
|
||||
}
|
||||
Ir::HasAttr { lhs, .. } => self.count_with_thunks(*lhs),
|
||||
Ir::ConcatStrings { parts, .. } => {
|
||||
parts.iter().map(|p| self.count_with_thunks(*p)).sum()
|
||||
}
|
||||
Ir::Path(p) => self.count_with_thunks(*p),
|
||||
Ir::List { items } => items.iter().map(|item| self.count_with_thunks(*item)).sum(),
|
||||
Ir::AttrSet { stcs, dyns } => {
|
||||
stcs.iter()
|
||||
.map(|(_, &(val, _))| self.count_with_thunks(val))
|
||||
.sum::<usize>()
|
||||
+ dyns
|
||||
.iter()
|
||||
.map(|&(k, v, _)| self.count_with_thunks(k) + self.count_with_thunks(v))
|
||||
.sum::<usize>()
|
||||
}
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_all_thunks<'ir>(
|
||||
&self,
|
||||
own_thunks: &[(ThunkId, RawIrRef<'ir>)],
|
||||
body: RawIrRef<'ir>,
|
||||
) -> Vec<(ThunkId, RawIrRef<'ir>)> {
|
||||
let mut all = Vec::from(own_thunks);
|
||||
self.collect_with_thunks_recursive(body, &mut all);
|
||||
let mut i = 0;
|
||||
while i < all.len() {
|
||||
let thunk_body = all[i].1;
|
||||
self.collect_with_thunks_recursive(thunk_body, &mut all);
|
||||
i += 1;
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn collect_with_thunks_recursive<'ir>(
|
||||
&self,
|
||||
ir: RawIrRef<'ir>,
|
||||
out: &mut Vec<(ThunkId, RawIrRef<'ir>)>,
|
||||
) {
|
||||
match ir.deref() {
|
||||
Ir::With { thunks, body, .. } => {
|
||||
for &(id, inner) in thunks.iter() {
|
||||
out.push((id, inner));
|
||||
}
|
||||
self.collect_with_thunks_recursive(*body, out);
|
||||
}
|
||||
Ir::TopLevel { thunks, body } => {
|
||||
for &(id, inner) in thunks.iter() {
|
||||
out.push((id, inner));
|
||||
}
|
||||
self.collect_with_thunks_recursive(*body, out);
|
||||
}
|
||||
Ir::If { cond, consq, alter } => {
|
||||
self.collect_with_thunks_recursive(*cond, out);
|
||||
self.collect_with_thunks_recursive(*consq, out);
|
||||
self.collect_with_thunks_recursive(*alter, out);
|
||||
}
|
||||
Ir::BinOp { lhs, rhs, .. } => {
|
||||
self.collect_with_thunks_recursive(*lhs, out);
|
||||
self.collect_with_thunks_recursive(*rhs, out);
|
||||
}
|
||||
Ir::UnOp { rhs, .. } => self.collect_with_thunks_recursive(*rhs, out),
|
||||
Ir::Call { func, arg, .. } => {
|
||||
self.collect_with_thunks_recursive(*func, out);
|
||||
self.collect_with_thunks_recursive(*arg, out);
|
||||
}
|
||||
Ir::Assert {
|
||||
assertion, expr, ..
|
||||
} => {
|
||||
self.collect_with_thunks_recursive(*assertion, out);
|
||||
self.collect_with_thunks_recursive(*expr, out);
|
||||
}
|
||||
Ir::Select { expr, default, .. } => {
|
||||
self.collect_with_thunks_recursive(*expr, out);
|
||||
if let Some(d) = default {
|
||||
self.collect_with_thunks_recursive(*d, out);
|
||||
}
|
||||
}
|
||||
Ir::HasAttr { lhs, .. } => self.collect_with_thunks_recursive(*lhs, out),
|
||||
Ir::ConcatStrings { parts, .. } => {
|
||||
for p in parts.iter() {
|
||||
self.collect_with_thunks_recursive(*p, out);
|
||||
}
|
||||
}
|
||||
Ir::Path(p) => self.collect_with_thunks_recursive(*p, out),
|
||||
Ir::List { items } => {
|
||||
for item in items.iter() {
|
||||
self.collect_with_thunks_recursive(*item, out);
|
||||
}
|
||||
}
|
||||
Ir::AttrSet { stcs, dyns } => {
|
||||
for (_, &(val, _)) in stcs.iter() {
|
||||
self.collect_with_thunks_recursive(val, out);
|
||||
}
|
||||
for &(key, val, _) in dyns.iter() {
|
||||
self.collect_with_thunks_recursive(key, out);
|
||||
self.collect_with_thunks_recursive(val, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn push_scope(&mut self, has_arg: bool, arg_id: Option<ArgId>, thunk_ids: &[ThunkId]) {
|
||||
let depth = self.scope_stack.len() as u16;
|
||||
let thunk_base = if has_arg { 1u32 } else { 0u32 };
|
||||
let thunk_map = thunk_ids
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &id)| (id, thunk_base + i as u32))
|
||||
.collect();
|
||||
self.scope_stack.push(ScopeInfo {
|
||||
depth,
|
||||
arg_id,
|
||||
thunk_map,
|
||||
});
|
||||
}
|
||||
|
||||
fn pop_scope(&mut self) {
|
||||
self.scope_stack.pop();
|
||||
}
|
||||
|
||||
fn emit_toplevel(&mut self, ir: RawIrRef<'_>) {
|
||||
match ir.deref() {
|
||||
Ir::TopLevel { body, thunks } => {
|
||||
let with_thunk_count = self.count_with_thunks(*body);
|
||||
let total_slots = thunks.len() + with_thunk_count;
|
||||
|
||||
let all_thunks = self.collect_all_thunks(thunks, *body);
|
||||
let thunk_ids: Vec<ThunkId> = all_thunks.iter().map(|&(id, _)| id).collect();
|
||||
|
||||
self.push_scope(false, None, &thunk_ids);
|
||||
|
||||
if total_slots > 0 {
|
||||
self.emit_op(Op::AllocLocals);
|
||||
self.emit_u32(total_slots as u32);
|
||||
}
|
||||
|
||||
self.emit_scope_thunks(thunks);
|
||||
self.emit_expr(*body);
|
||||
self.emit_op(Op::Return);
|
||||
|
||||
self.pop_scope();
|
||||
}
|
||||
_ => {
|
||||
self.push_scope(false, None, &[]);
|
||||
self.emit_expr(ir);
|
||||
self.emit_op(Op::Return);
|
||||
self.pop_scope();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_toplevel_scoped(&mut self, ir: RawIrRef<'_>) {
|
||||
match ir.deref() {
|
||||
Ir::TopLevel { body, thunks } => {
|
||||
let with_thunk_count = self.count_with_thunks(*body);
|
||||
let total_slots = thunks.len() + with_thunk_count;
|
||||
|
||||
let all_thunks = self.collect_all_thunks(thunks, *body);
|
||||
let thunk_ids: Vec<ThunkId> = all_thunks.iter().map(|&(id, _)| id).collect();
|
||||
|
||||
self.push_scope(false, None, &thunk_ids);
|
||||
|
||||
if total_slots > 0 {
|
||||
self.emit_op(Op::AllocLocals);
|
||||
self.emit_u32(total_slots as u32);
|
||||
}
|
||||
|
||||
self.emit_scope_thunks(thunks);
|
||||
self.emit_expr(*body);
|
||||
self.emit_op(Op::Return);
|
||||
|
||||
self.pop_scope();
|
||||
}
|
||||
_ => {
|
||||
self.push_scope(false, None, &[]);
|
||||
self.emit_expr(ir);
|
||||
self.emit_op(Op::Return);
|
||||
self.pop_scope();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_scope_thunks(&mut self, thunks: &[(ThunkId, RawIrRef<'_>)]) {
|
||||
for &(id, inner) in thunks {
|
||||
let label = format!("e{}", id.0);
|
||||
let label_idx = self.ctx.intern_string(&label);
|
||||
|
||||
let skip_patch = self.emit_jump_placeholder();
|
||||
let entry_point = self.code.len() as u32;
|
||||
self.emit_expr(inner);
|
||||
self.emit_op(Op::Return);
|
||||
self.patch_jump_target(skip_patch);
|
||||
self.emit_op(Op::MakeThunk);
|
||||
self.emit_u32(entry_point);
|
||||
self.emit_u32(label_idx);
|
||||
let (_, local_idx) = self.resolve_thunk(id);
|
||||
self.emit_op(Op::StoreLocal);
|
||||
self.emit_u32(local_idx);
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_expr(&mut self, ir: RawIrRef<'_>) {
|
||||
match ir.deref() {
|
||||
&Ir::Int(x) => {
|
||||
let idx = self.ctx.intern_constant(Constant::Int(x));
|
||||
self.emit_op(Op::PushConst);
|
||||
self.emit_u32(idx);
|
||||
}
|
||||
&Ir::Float(x) => {
|
||||
let idx = self.ctx.intern_constant(Constant::Float(x.to_bits()));
|
||||
self.emit_op(Op::PushConst);
|
||||
self.emit_u32(idx);
|
||||
}
|
||||
&Ir::Bool(true) => self.emit_op(Op::PushTrue),
|
||||
&Ir::Bool(false) => self.emit_op(Op::PushFalse),
|
||||
Ir::Null => self.emit_op(Op::PushNull),
|
||||
Ir::Str(s) => {
|
||||
let idx = self.ctx.intern_string(s.deref());
|
||||
self.emit_op(Op::PushString);
|
||||
self.emit_u32(idx);
|
||||
}
|
||||
&Ir::Path(p) => {
|
||||
self.emit_expr(p);
|
||||
self.emit_op(Op::ResolvePath);
|
||||
}
|
||||
&Ir::If { cond, consq, alter } => {
|
||||
self.emit_expr(cond);
|
||||
self.emit_op(Op::ForceBool);
|
||||
|
||||
self.emit_op(Op::JumpIfFalse);
|
||||
let else_placeholder = self.emit_i32_placeholder();
|
||||
let after_jif = self.code.len();
|
||||
|
||||
self.emit_expr(consq);
|
||||
|
||||
self.emit_op(Op::Jump);
|
||||
let end_placeholder = self.emit_i32_placeholder();
|
||||
let after_jump = self.code.len();
|
||||
|
||||
let else_offset = (after_jump as i32) - (after_jif as i32);
|
||||
self.patch_i32(else_placeholder, else_offset);
|
||||
|
||||
self.emit_expr(alter);
|
||||
|
||||
let end_offset = (self.code.len() as i32) - (after_jump as i32);
|
||||
self.patch_i32(end_placeholder, end_offset);
|
||||
}
|
||||
&Ir::BinOp { lhs, rhs, kind } => {
|
||||
self.emit_binop(lhs, rhs, kind);
|
||||
}
|
||||
&Ir::UnOp { rhs, kind } => match kind {
|
||||
UnOpKind::Neg => {
|
||||
self.emit_expr(rhs);
|
||||
self.emit_op(Op::OpNeg);
|
||||
}
|
||||
UnOpKind::Not => {
|
||||
self.emit_expr(rhs);
|
||||
self.emit_op(Op::OpNot);
|
||||
}
|
||||
},
|
||||
&Ir::Func {
|
||||
body,
|
||||
ref param,
|
||||
arg,
|
||||
ref thunks,
|
||||
} => {
|
||||
self.emit_func(arg, thunks, param, body);
|
||||
}
|
||||
Ir::AttrSet { stcs, dyns } => {
|
||||
self.emit_attrset(stcs, dyns);
|
||||
}
|
||||
Ir::List { items } => {
|
||||
for &item in items.iter() {
|
||||
self.emit_expr(item);
|
||||
}
|
||||
self.emit_op(Op::MakeList);
|
||||
self.emit_u32(items.len() as u32);
|
||||
}
|
||||
&Ir::Call { func, arg, span } => {
|
||||
self.emit_expr(func);
|
||||
self.emit_expr(arg);
|
||||
let span_id = self.ctx.register_span(span);
|
||||
self.emit_op(Op::Call);
|
||||
self.emit_u32(span_id);
|
||||
}
|
||||
&Ir::Arg(id) => {
|
||||
let (layer, local) = self.resolve_arg(id);
|
||||
self.emit_load(layer, local);
|
||||
}
|
||||
&Ir::TopLevel { body, ref thunks } => {
|
||||
self.emit_toplevel_inner(body, thunks);
|
||||
}
|
||||
&Ir::Select {
|
||||
expr,
|
||||
ref attrpath,
|
||||
default,
|
||||
span,
|
||||
} => {
|
||||
self.emit_select(expr, attrpath, default, span);
|
||||
}
|
||||
&Ir::Thunk(id) => {
|
||||
let (layer, local) = self.resolve_thunk(id);
|
||||
self.emit_load(layer, local);
|
||||
}
|
||||
Ir::Builtins => {
|
||||
self.emit_op(Op::LoadBuiltins);
|
||||
}
|
||||
&Ir::Builtin(name) => {
|
||||
let sym = self.ctx.get_sym(name).to_string();
|
||||
let idx = self.ctx.intern_string(&sym);
|
||||
self.emit_op(Op::LoadBuiltin);
|
||||
self.emit_u32(idx);
|
||||
}
|
||||
&Ir::ConcatStrings {
|
||||
ref parts,
|
||||
force_string,
|
||||
} => {
|
||||
for &part in parts.iter() {
|
||||
self.emit_expr(part);
|
||||
}
|
||||
self.emit_op(Op::ConcatStrings);
|
||||
self.emit_u16(parts.len() as u16);
|
||||
self.emit_u8(if force_string { 1 } else { 0 });
|
||||
}
|
||||
&Ir::HasAttr { lhs, ref rhs } => {
|
||||
self.emit_has_attr(lhs, rhs);
|
||||
}
|
||||
Ir::Assert {
|
||||
assertion,
|
||||
expr,
|
||||
assertion_raw,
|
||||
span,
|
||||
} => {
|
||||
let raw_idx = self.ctx.intern_string(assertion_raw);
|
||||
let span_id = self.ctx.register_span(*span);
|
||||
self.emit_expr(*assertion);
|
||||
self.emit_expr(*expr);
|
||||
self.emit_op(Op::Assert);
|
||||
self.emit_u32(raw_idx);
|
||||
self.emit_u32(span_id);
|
||||
}
|
||||
&Ir::CurPos(span) => {
|
||||
let span_id = self.ctx.register_span(span);
|
||||
self.emit_op(Op::MkPos);
|
||||
self.emit_u32(span_id);
|
||||
}
|
||||
&Ir::ReplBinding(name) => {
|
||||
let sym = self.ctx.get_sym(name).to_string();
|
||||
let idx = self.ctx.intern_string(&sym);
|
||||
self.emit_op(Op::LoadReplBinding);
|
||||
self.emit_u32(idx);
|
||||
}
|
||||
&Ir::ScopedImportBinding(name) => {
|
||||
let sym = self.ctx.get_sym(name).to_string();
|
||||
let idx = self.ctx.intern_string(&sym);
|
||||
self.emit_op(Op::LoadScopedBinding);
|
||||
self.emit_u32(idx);
|
||||
}
|
||||
&Ir::With {
|
||||
namespace,
|
||||
body,
|
||||
ref thunks,
|
||||
} => {
|
||||
self.emit_with(namespace, body, thunks);
|
||||
}
|
||||
&Ir::WithLookup(name) => {
|
||||
let sym = self.ctx.get_sym(name).to_string();
|
||||
let idx = self.ctx.intern_string(&sym);
|
||||
self.emit_op(Op::WithLookup);
|
||||
self.emit_u32(idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_binop(&mut self, lhs: RawIrRef<'_>, rhs: RawIrRef<'_>, kind: BinOpKind) {
|
||||
use BinOpKind::*;
|
||||
match kind {
|
||||
And => {
|
||||
self.emit_expr(lhs);
|
||||
self.emit_op(Op::ForceBool);
|
||||
self.emit_op(Op::JumpIfFalse);
|
||||
let skip_placeholder = self.emit_i32_placeholder();
|
||||
let after_jif = self.code.len();
|
||||
|
||||
self.emit_expr(rhs);
|
||||
self.emit_op(Op::ForceBool);
|
||||
self.emit_op(Op::Jump);
|
||||
let end_placeholder = self.emit_i32_placeholder();
|
||||
let after_jump = self.code.len();
|
||||
|
||||
let false_offset = (after_jump as i32) - (after_jif as i32);
|
||||
self.patch_i32(skip_placeholder, false_offset);
|
||||
|
||||
self.emit_op(Op::PushFalse);
|
||||
|
||||
let end_offset = (self.code.len() as i32) - (after_jump as i32);
|
||||
self.patch_i32(end_placeholder, end_offset);
|
||||
}
|
||||
Or => {
|
||||
self.emit_expr(lhs);
|
||||
self.emit_op(Op::ForceBool);
|
||||
self.emit_op(Op::JumpIfTrue);
|
||||
let skip_placeholder = self.emit_i32_placeholder();
|
||||
let after_jit = self.code.len();
|
||||
|
||||
self.emit_expr(rhs);
|
||||
self.emit_op(Op::ForceBool);
|
||||
self.emit_op(Op::Jump);
|
||||
let end_placeholder = self.emit_i32_placeholder();
|
||||
let after_jump = self.code.len();
|
||||
|
||||
let true_offset = (after_jump as i32) - (after_jit as i32);
|
||||
self.patch_i32(skip_placeholder, true_offset);
|
||||
|
||||
self.emit_op(Op::PushTrue);
|
||||
|
||||
let end_offset = (self.code.len() as i32) - (after_jump as i32);
|
||||
self.patch_i32(end_placeholder, end_offset);
|
||||
}
|
||||
Impl => {
|
||||
self.emit_expr(lhs);
|
||||
self.emit_op(Op::ForceBool);
|
||||
self.emit_op(Op::JumpIfFalse);
|
||||
let skip_placeholder = self.emit_i32_placeholder();
|
||||
let after_jif = self.code.len();
|
||||
|
||||
self.emit_expr(rhs);
|
||||
self.emit_op(Op::ForceBool);
|
||||
self.emit_op(Op::Jump);
|
||||
let end_placeholder = self.emit_i32_placeholder();
|
||||
let after_jump = self.code.len();
|
||||
|
||||
let true_offset = (after_jump as i32) - (after_jif as i32);
|
||||
self.patch_i32(skip_placeholder, true_offset);
|
||||
|
||||
self.emit_op(Op::PushTrue);
|
||||
|
||||
let end_offset = (self.code.len() as i32) - (after_jump as i32);
|
||||
self.patch_i32(end_placeholder, end_offset);
|
||||
}
|
||||
PipeL => {
|
||||
self.emit_expr(rhs);
|
||||
self.emit_expr(lhs);
|
||||
self.emit_op(Op::CallNoSpan);
|
||||
}
|
||||
PipeR => {
|
||||
self.emit_expr(lhs);
|
||||
self.emit_expr(rhs);
|
||||
self.emit_op(Op::CallNoSpan);
|
||||
}
|
||||
_ => {
|
||||
self.emit_expr(lhs);
|
||||
self.emit_expr(rhs);
|
||||
self.emit_op(match kind {
|
||||
Add => Op::OpAdd,
|
||||
Sub => Op::OpSub,
|
||||
Mul => Op::OpMul,
|
||||
Div => Op::OpDiv,
|
||||
Eq => Op::OpEq,
|
||||
Neq => Op::OpNeq,
|
||||
Lt => Op::OpLt,
|
||||
Gt => Op::OpGt,
|
||||
Leq => Op::OpLeq,
|
||||
Geq => Op::OpGeq,
|
||||
Con => Op::OpConcat,
|
||||
Upd => Op::OpUpdate,
|
||||
_ => unreachable!(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_func(
|
||||
&mut self,
|
||||
arg: ArgId,
|
||||
thunks: &[(ThunkId, RawIrRef<'_>)],
|
||||
param: &Option<Param<'_>>,
|
||||
body: RawIrRef<'_>,
|
||||
) {
|
||||
let with_thunk_count = self.count_with_thunks(body);
|
||||
let total_slots = thunks.len() + with_thunk_count;
|
||||
|
||||
let all_thunks = self.collect_all_thunks(thunks, body);
|
||||
let thunk_ids: Vec<ThunkId> = all_thunks.iter().map(|&(id, _)| id).collect();
|
||||
|
||||
let skip_patch = self.emit_jump_placeholder();
|
||||
let entry_point = self.code.len() as u32;
|
||||
self.push_scope(true, Some(arg), &thunk_ids);
|
||||
self.emit_scope_thunks(thunks);
|
||||
self.emit_expr(body);
|
||||
self.emit_op(Op::Return);
|
||||
self.pop_scope();
|
||||
self.patch_jump_target(skip_patch);
|
||||
|
||||
if let Some(Param {
|
||||
required,
|
||||
optional,
|
||||
ellipsis,
|
||||
}) = param
|
||||
{
|
||||
self.emit_op(Op::MakePatternClosure);
|
||||
self.emit_u32(entry_point);
|
||||
self.emit_u32(total_slots as u32);
|
||||
self.emit_u16(required.len() as u16);
|
||||
self.emit_u16(optional.len() as u16);
|
||||
self.emit_u8(if *ellipsis { 1 } else { 0 });
|
||||
|
||||
for &(sym, _) in required.iter() {
|
||||
let name = self.ctx.get_sym(sym).to_string();
|
||||
let idx = self.ctx.intern_string(&name);
|
||||
self.emit_u32(idx);
|
||||
}
|
||||
for &(sym, _) in optional.iter() {
|
||||
let name = self.ctx.get_sym(sym).to_string();
|
||||
let idx = self.ctx.intern_string(&name);
|
||||
self.emit_u32(idx);
|
||||
}
|
||||
for &(sym, span) in required.iter().chain(optional.iter()) {
|
||||
let name = self.ctx.get_sym(sym).to_string();
|
||||
let name_idx = self.ctx.intern_string(&name);
|
||||
let span_id = self.ctx.register_span(span);
|
||||
self.emit_u32(name_idx);
|
||||
self.emit_u32(span_id);
|
||||
}
|
||||
} else {
|
||||
self.emit_op(Op::MakeClosure);
|
||||
self.emit_u32(entry_point);
|
||||
self.emit_u32(total_slots as u32);
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_attrset(
|
||||
&mut self,
|
||||
stcs: &crate::ir::HashMap<'_, SymId, (RawIrRef<'_>, TextRange)>,
|
||||
dyns: &[(RawIrRef<'_>, RawIrRef<'_>, TextRange)],
|
||||
) {
|
||||
if stcs.is_empty() && dyns.is_empty() {
|
||||
self.emit_op(Op::MakeEmptyAttrs);
|
||||
return;
|
||||
}
|
||||
|
||||
if !dyns.is_empty() {
|
||||
for (&sym, &(val, _)) in stcs.iter() {
|
||||
let key = self.ctx.get_sym(sym).to_string();
|
||||
let idx = self.ctx.intern_string(&key);
|
||||
self.emit_op(Op::PushString);
|
||||
self.emit_u32(idx);
|
||||
self.emit_expr(val);
|
||||
}
|
||||
for (_, &(_, span)) in stcs.iter() {
|
||||
let span_id = self.ctx.register_span(span);
|
||||
let idx = self.ctx.intern_constant(Constant::Int(span_id as i64));
|
||||
self.emit_op(Op::PushConst);
|
||||
self.emit_u32(idx);
|
||||
}
|
||||
for &(key, val, span) in dyns.iter() {
|
||||
self.emit_expr(key);
|
||||
self.emit_expr(val);
|
||||
let span_id = self.ctx.register_span(span);
|
||||
let idx = self.ctx.intern_constant(Constant::Int(span_id as i64));
|
||||
self.emit_op(Op::PushConst);
|
||||
self.emit_u32(idx);
|
||||
}
|
||||
self.emit_op(Op::MakeAttrsDyn);
|
||||
self.emit_u32(stcs.len() as u32);
|
||||
self.emit_u32(dyns.len() as u32);
|
||||
} else {
|
||||
for (&sym, &(val, _)) in stcs.iter() {
|
||||
let key = self.ctx.get_sym(sym).to_string();
|
||||
let idx = self.ctx.intern_string(&key);
|
||||
self.emit_op(Op::PushString);
|
||||
self.emit_u32(idx);
|
||||
self.emit_expr(val);
|
||||
}
|
||||
for (_, &(_, span)) in stcs.iter() {
|
||||
let span_id = self.ctx.register_span(span);
|
||||
let idx = self.ctx.intern_constant(Constant::Int(span_id as i64));
|
||||
self.emit_op(Op::PushConst);
|
||||
self.emit_u32(idx);
|
||||
}
|
||||
self.emit_op(Op::MakeAttrs);
|
||||
self.emit_u32(stcs.len() as u32);
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_select(
|
||||
&mut self,
|
||||
expr: RawIrRef<'_>,
|
||||
attrpath: &[Attr<RawIrRef<'_>>],
|
||||
default: Option<RawIrRef<'_>>,
|
||||
span: TextRange,
|
||||
) {
|
||||
self.emit_expr(expr);
|
||||
for attr in attrpath.iter() {
|
||||
match attr {
|
||||
Attr::Str(sym, _) => {
|
||||
let key = self.ctx.get_sym(*sym).to_string();
|
||||
let idx = self.ctx.intern_string(&key);
|
||||
self.emit_op(Op::PushString);
|
||||
self.emit_u32(idx);
|
||||
}
|
||||
Attr::Dynamic(expr, _) => {
|
||||
self.emit_expr(*expr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(default) = default {
|
||||
self.emit_expr(default);
|
||||
let span_id = self.ctx.register_span(span);
|
||||
self.emit_op(Op::SelectDefault);
|
||||
self.emit_u16(attrpath.len() as u16);
|
||||
self.emit_u32(span_id);
|
||||
} else {
|
||||
let span_id = self.ctx.register_span(span);
|
||||
self.emit_op(Op::Select);
|
||||
self.emit_u16(attrpath.len() as u16);
|
||||
self.emit_u32(span_id);
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_has_attr(&mut self, lhs: RawIrRef<'_>, rhs: &[Attr<RawIrRef<'_>>]) {
|
||||
self.emit_expr(lhs);
|
||||
for attr in rhs.iter() {
|
||||
match attr {
|
||||
Attr::Str(sym, _) => {
|
||||
let key = self.ctx.get_sym(*sym).to_string();
|
||||
let idx = self.ctx.intern_string(&key);
|
||||
self.emit_op(Op::PushString);
|
||||
self.emit_u32(idx);
|
||||
}
|
||||
Attr::Dynamic(expr, _) => {
|
||||
self.emit_expr(*expr);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.emit_op(Op::HasAttr);
|
||||
self.emit_u16(rhs.len() as u16);
|
||||
}
|
||||
|
||||
fn emit_with(
|
||||
&mut self,
|
||||
namespace: RawIrRef<'_>,
|
||||
body: RawIrRef<'_>,
|
||||
thunks: &[(ThunkId, RawIrRef<'_>)],
|
||||
) {
|
||||
self.emit_expr(namespace);
|
||||
self.emit_op(Op::PushWith);
|
||||
self.emit_scope_thunks(thunks);
|
||||
self.emit_expr(body);
|
||||
self.emit_op(Op::PopWith);
|
||||
}
|
||||
|
||||
fn emit_toplevel_inner(&mut self, body: RawIrRef<'_>, thunks: &[(ThunkId, RawIrRef<'_>)]) {
|
||||
self.emit_scope_thunks(thunks);
|
||||
self.emit_expr(body);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
use std::fmt::{self, Write as _};
|
||||
use std::ops::Deref;
|
||||
use std::path::Path;
|
||||
|
||||
use rnix::TextRange;
|
||||
|
||||
use crate::ir::*;
|
||||
use crate::value::Symbol;
|
||||
|
||||
@@ -26,46 +29,23 @@ macro_rules! code {
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) fn compile(expr: &Ir, ctx: &impl CodegenContext) -> String {
|
||||
pub(crate) fn compile<const SCOPED: bool>(expr: RawIrRef<'_>, ctx: &impl CodegenContext) -> String {
|
||||
let mut buf = CodeBuffer::with_capacity(8192);
|
||||
|
||||
code!(&mut buf, ctx; "(()=>{");
|
||||
|
||||
if std::env::var("NIX_JS_DEBUG_THUNKS").is_ok() {
|
||||
code!(&mut buf, ctx; "Nix.DEBUG_THUNKS.enabled=true;");
|
||||
}
|
||||
|
||||
code!(&mut buf, ctx;
|
||||
"const __currentDir="
|
||||
code!(
|
||||
&mut buf, ctx;
|
||||
"((" { if SCOPED { "_s" } else { "" } } ")=>{"
|
||||
"const _d="
|
||||
quoted(&ctx.get_current_dir().display().to_string())
|
||||
";const __with=null;return "
|
||||
expr
|
||||
"})()");
|
||||
|
||||
buf.into_string()
|
||||
}
|
||||
|
||||
pub(crate) fn compile_scoped(expr: &Ir, ctx: &impl CodegenContext) -> String {
|
||||
let mut buf = CodeBuffer::with_capacity(8192);
|
||||
|
||||
code!(&mut buf, ctx; "((__scope)=>{");
|
||||
|
||||
if std::env::var("NIX_JS_DEBUG_THUNKS").is_ok() {
|
||||
code!(&mut buf, ctx; "Nix.DEBUG_THUNKS.enabled=true;");
|
||||
}
|
||||
|
||||
code!(&mut buf, ctx;
|
||||
"const __currentDir="
|
||||
quoted(&ctx.get_current_dir().display().to_string())
|
||||
";return "
|
||||
expr
|
||||
"})"
|
||||
",_w=null;"
|
||||
"return " expr
|
||||
"})" { if SCOPED { "" } else { "()" } }
|
||||
);
|
||||
|
||||
buf.into_string()
|
||||
}
|
||||
|
||||
pub(crate) struct CodeBuffer {
|
||||
struct CodeBuffer {
|
||||
buf: String,
|
||||
}
|
||||
|
||||
@@ -191,29 +171,16 @@ where
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for rnix::TextRange {
|
||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
code!(
|
||||
buf,
|
||||
"\"{}:{}:{}\"",
|
||||
ctx.get_current_source_id(),
|
||||
usize::from(self.start()),
|
||||
usize::from(self.end())
|
||||
);
|
||||
code!(buf, "{}", ctx.register_span(*self));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) trait CodegenContext {
|
||||
fn get_ir(&self, id: ExprId) -> &Ir;
|
||||
fn get_sym(&self, id: SymId) -> Symbol<'_>;
|
||||
fn get_current_dir(&self) -> &Path;
|
||||
fn get_store_dir(&self) -> &str;
|
||||
fn get_current_source_id(&self) -> usize;
|
||||
fn get_current_source(&self) -> crate::error::Source;
|
||||
}
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for ExprId {
|
||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
ctx.get_ir(*self).compile(ctx, buf);
|
||||
}
|
||||
fn register_span(&self, range: rnix::TextRange) -> usize;
|
||||
}
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for Symbol<'_> {
|
||||
@@ -222,70 +189,90 @@ impl<Ctx: CodegenContext> Compile<Ctx> for Symbol<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for Ir {
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for RawIrRef<'_> {
|
||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
match self {
|
||||
match self.deref() {
|
||||
Ir::Int(int) => {
|
||||
code!(buf, "{}n", int.inner);
|
||||
code!(buf, "{}n", int);
|
||||
}
|
||||
Ir::Float(float) => {
|
||||
code!(buf, "{}", float.inner);
|
||||
code!(buf, "{}", float);
|
||||
}
|
||||
Ir::Bool(bool) => {
|
||||
code!(buf, "{}", bool.inner);
|
||||
code!(buf, "{}", bool);
|
||||
}
|
||||
Ir::Null(_) => {
|
||||
Ir::Null => {
|
||||
code!(buf, ctx; "null");
|
||||
}
|
||||
Ir::Str(s) => {
|
||||
code!(buf, ctx; quoted(&s.val));
|
||||
code!(buf, ctx; quoted(s));
|
||||
}
|
||||
Ir::Path(p) => {
|
||||
code!(buf, ctx; "Nix.resolvePath(__currentDir," ctx.get_ir(p.expr) ")");
|
||||
// Nix.resolvePath
|
||||
code!(buf, ctx; "$r(_d," p ")");
|
||||
}
|
||||
Ir::If(x) => x.compile(ctx, buf),
|
||||
Ir::BinOp(x) => x.compile(ctx, buf),
|
||||
Ir::UnOp(x) => x.compile(ctx, buf),
|
||||
Ir::Func(x) => x.compile(ctx, buf),
|
||||
Ir::AttrSet(x) => x.compile(ctx, buf),
|
||||
Ir::List(x) => x.compile(ctx, buf),
|
||||
Ir::Call(x) => x.compile(ctx, buf),
|
||||
Ir::Arg(x) => {
|
||||
code!(buf, "arg{}", x.inner.0);
|
||||
Ir::If { cond, consq, alter } => {
|
||||
code!(buf, ctx; "$fb(" cond ")?(" consq "):(" alter ")");
|
||||
}
|
||||
Ir::TopLevel(x) => x.compile(ctx, buf),
|
||||
Ir::Select(x) => x.compile(ctx, buf),
|
||||
&Ir::Thunk(Thunk { inner: expr_id, .. }) => {
|
||||
code!(buf, "expr{}", expr_id.0);
|
||||
}
|
||||
Ir::Builtins(_) => {
|
||||
code!(buf, ctx; "Nix.builtins");
|
||||
}
|
||||
&Ir::Builtin(Builtin { inner: name, .. }) => {
|
||||
&Ir::BinOp { lhs, rhs, kind } => compile_binop(lhs, rhs, kind, ctx, buf),
|
||||
&Ir::UnOp { rhs, kind } => compile_unop(rhs, kind, ctx, buf),
|
||||
&Ir::Func {
|
||||
body,
|
||||
ref param,
|
||||
arg,
|
||||
ref thunks,
|
||||
} => compile_func(arg, thunks, param, body, ctx, buf),
|
||||
Ir::AttrSet { stcs, dyns } => compile_attrset(stcs, dyns, ctx, buf),
|
||||
Ir::List { items } => compile_list(items, ctx, buf),
|
||||
Ir::Call { func, arg, span } => {
|
||||
code!(buf, ctx;
|
||||
"Nix.builtins["
|
||||
ctx.get_sym(name)
|
||||
"]"
|
||||
"$c("
|
||||
func
|
||||
","
|
||||
arg
|
||||
","
|
||||
span
|
||||
")"
|
||||
);
|
||||
}
|
||||
Ir::ConcatStrings(x) => x.compile(ctx, buf),
|
||||
Ir::HasAttr(x) => x.compile(ctx, buf),
|
||||
&Ir::Assert(Assert {
|
||||
Ir::Arg(x) => {
|
||||
code!(buf, "a{}", x.0);
|
||||
}
|
||||
&Ir::TopLevel { body, ref thunks } => compile_toplevel(body, thunks, ctx, buf),
|
||||
&Ir::Select {
|
||||
expr,
|
||||
ref attrpath,
|
||||
default,
|
||||
span,
|
||||
} => compile_select(expr, attrpath, default, span, ctx, buf),
|
||||
Ir::Thunk(ThunkId(id)) => {
|
||||
code!(buf, "e{}", id);
|
||||
}
|
||||
Ir::Builtins => {
|
||||
// Nix.builtins
|
||||
code!(buf, ctx; "$b");
|
||||
}
|
||||
&Ir::Builtin(name) => {
|
||||
// Nix.builtins
|
||||
code!(buf, ctx; "$b.get(" ctx.get_sym(name) ")");
|
||||
}
|
||||
&Ir::ConcatStrings {
|
||||
ref parts,
|
||||
force_string,
|
||||
} => compile_concat_strings(parts, force_string, ctx, buf),
|
||||
&Ir::HasAttr { lhs, ref rhs } => compile_has_attr(lhs, rhs, ctx, buf),
|
||||
Ir::Assert {
|
||||
assertion,
|
||||
expr,
|
||||
ref assertion_raw,
|
||||
assertion_raw,
|
||||
span: assert_span,
|
||||
}) => {
|
||||
let assertion_ir = ctx.get_ir(assertion);
|
||||
let assertion_span = assertion_ir.span();
|
||||
|
||||
} => {
|
||||
// Nix.assert
|
||||
code!(buf, ctx;
|
||||
"Nix.assert(Nix.withContext(\"while evaluating the condition of the assert statement\","
|
||||
assertion_span
|
||||
",()=>("
|
||||
assertion_ir
|
||||
")),"
|
||||
ctx.get_ir(expr)
|
||||
"$a("
|
||||
assertion
|
||||
","
|
||||
expr
|
||||
","
|
||||
quoted(assertion_raw)
|
||||
","
|
||||
@@ -293,162 +280,127 @@ impl<Ctx: CodegenContext> Compile<Ctx> for Ir {
|
||||
")"
|
||||
);
|
||||
}
|
||||
Ir::CurPos(cur_pos) => {
|
||||
code!(buf, ctx;
|
||||
"Nix.mkPos("
|
||||
cur_pos.span
|
||||
")"
|
||||
);
|
||||
Ir::CurPos(span) => {
|
||||
// Nix.mkPos
|
||||
code!(buf, ctx; "$mp(" span ")");
|
||||
}
|
||||
&Ir::ReplBinding(ReplBinding { inner: name, .. }) => {
|
||||
code!(buf, ctx;
|
||||
"Nix.getReplBinding("
|
||||
ctx.get_sym(name)
|
||||
")"
|
||||
);
|
||||
&Ir::ReplBinding(name) => {
|
||||
// Nix.getReplBinding
|
||||
code!(buf, ctx; "$gb(" ctx.get_sym(name) ")");
|
||||
}
|
||||
&Ir::ScopedImportBinding(ScopedImportBinding { inner: name, .. }) => {
|
||||
code!(buf, ctx;
|
||||
"__scope["
|
||||
ctx.get_sym(name)
|
||||
"]"
|
||||
);
|
||||
&Ir::ScopedImportBinding(name) => {
|
||||
code!(buf, ctx; "_s.get(" ctx.get_sym(name) ")");
|
||||
}
|
||||
Ir::WithExpr(x) => x.compile(ctx, buf),
|
||||
&Ir::WithLookup(WithLookup { inner: name, .. }) => {
|
||||
code!(buf, ctx;
|
||||
"Nix.lookupWith("
|
||||
ctx.get_sym(name)
|
||||
",__with)"
|
||||
);
|
||||
&Ir::With {
|
||||
namespace,
|
||||
body,
|
||||
ref thunks,
|
||||
} => compile_with(namespace, body, thunks, ctx, buf),
|
||||
&Ir::WithLookup(name) => {
|
||||
// Nix.lookupWith
|
||||
code!(buf, ctx; "$l(" ctx.get_sym(name) ",_w)");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for If {
|
||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
let &If {
|
||||
cond,
|
||||
consq,
|
||||
alter,
|
||||
span: _,
|
||||
} = self;
|
||||
let cond_ir = ctx.get_ir(cond);
|
||||
let cond_span = cond_ir.span();
|
||||
|
||||
code!(buf, ctx;
|
||||
"(Nix.withContext(\"while evaluating a branch condition\"," cond_span ",()=>Nix.forceBool(" cond_ir ")))"
|
||||
"?(" consq "):(" alter ")"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for BinOp {
|
||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
fn compile_binop<'ir>(
|
||||
lhs: RawIrRef<'ir>,
|
||||
rhs: RawIrRef<'ir>,
|
||||
kind: BinOpKind,
|
||||
ctx: &impl CodegenContext,
|
||||
buf: &mut CodeBuffer,
|
||||
) {
|
||||
use BinOpKind::*;
|
||||
|
||||
let lhs = ctx.get_ir(self.lhs);
|
||||
let rhs = ctx.get_ir(self.rhs);
|
||||
|
||||
match self.kind {
|
||||
match kind {
|
||||
Add | Sub | Mul | Div | Eq | Neq | Lt | Gt | Leq | Geq | Con | Upd => {
|
||||
let op_name = match self.kind {
|
||||
Add => "+",
|
||||
Sub => "-",
|
||||
Mul => "*",
|
||||
Div => "/",
|
||||
Eq => "==",
|
||||
Neq => "!=",
|
||||
Lt => "<",
|
||||
Gt => ">",
|
||||
Leq => "<=",
|
||||
Geq => ">=",
|
||||
Con => "++",
|
||||
Upd => "//",
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let op_func = match self.kind {
|
||||
Add => "Nix.op.add",
|
||||
Sub => "Nix.op.sub",
|
||||
Mul => "Nix.op.mul",
|
||||
Div => "Nix.op.div",
|
||||
Eq => "Nix.op.eq",
|
||||
Neq => "Nix.op.neq",
|
||||
Lt => "Nix.op.lt",
|
||||
Gt => "Nix.op.gt",
|
||||
Leq => "Nix.op.lte",
|
||||
Geq => "Nix.op.gte",
|
||||
Con => "Nix.op.concat",
|
||||
Upd => "Nix.op.update",
|
||||
let op_func = match kind {
|
||||
Add => "$oa",
|
||||
Sub => "$os",
|
||||
Mul => "$om",
|
||||
Div => "$od",
|
||||
Eq => "$oe",
|
||||
Neq => "!$oe",
|
||||
Lt => "$ol",
|
||||
Gt => "$og",
|
||||
Leq => "!$og",
|
||||
Geq => "!$ol",
|
||||
Con => "$oc",
|
||||
Upd => "$ou",
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
code!(
|
||||
buf, ctx;
|
||||
"Nix.withContext(\"while evaluating the " op_name " operator\"," self.span ",()=>(" op_func "(" lhs "," rhs ")))"
|
||||
op_func "(" lhs "," rhs ")"
|
||||
);
|
||||
}
|
||||
And => {
|
||||
code!(
|
||||
buf, ctx;
|
||||
"Nix.withContext(\"while evaluating the && operator\"," self.span ",()=>(Nix.forceBool(" lhs ")&&Nix.forceBool(" rhs ")))"
|
||||
"$fb(" lhs ")" "&&" "$fb(" rhs ")"
|
||||
);
|
||||
}
|
||||
Or => {
|
||||
code!(
|
||||
buf, ctx;
|
||||
"Nix.withContext(\"while evaluating the || operator\"," self.span ",()=>(Nix.forceBool(" lhs ")||Nix.forceBool(" rhs ")))"
|
||||
"$fb(" lhs ")" "||" "$fb(" rhs ")"
|
||||
);
|
||||
}
|
||||
Impl => {
|
||||
code!(
|
||||
buf, ctx;
|
||||
"Nix.withContext(\"while evaluating the -> operator\"," self.span ",()=>(!Nix.forceBool(" lhs ")||Nix.forceBool(" rhs ")))"
|
||||
"!$fb(" lhs ")" "||" "$fb(" rhs ")"
|
||||
);
|
||||
}
|
||||
PipeL => {
|
||||
code!(buf, ctx; "Nix.call(" rhs "," lhs ")");
|
||||
code!(buf, ctx; "$c(" rhs "," lhs ")");
|
||||
}
|
||||
PipeR => {
|
||||
code!(buf, ctx; "Nix.call(" lhs "," rhs ")");
|
||||
}
|
||||
code!(buf, ctx; "$c(" lhs "," rhs ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for UnOp {
|
||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
fn compile_unop(
|
||||
rhs: RawIrRef<'_>,
|
||||
kind: UnOpKind,
|
||||
ctx: &impl CodegenContext,
|
||||
buf: &mut CodeBuffer,
|
||||
) {
|
||||
use UnOpKind::*;
|
||||
let rhs = ctx.get_ir(self.rhs);
|
||||
match self.kind {
|
||||
match kind {
|
||||
Neg => {
|
||||
code!(buf, ctx; "Nix.op.sub(0n," rhs ")");
|
||||
// 0 - rhs
|
||||
code!(buf, ctx; "$os(0n," rhs ")");
|
||||
}
|
||||
Not => {
|
||||
code!(buf, ctx; "Nix.op.bnot(" ctx.get_ir(self.rhs) ")");
|
||||
}
|
||||
code!(buf, ctx; "!$fb(" rhs ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for Func {
|
||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
let id = ctx.get_ir(self.arg).as_ref().unwrap_arg().inner.0;
|
||||
|
||||
let has_thunks = !self.thunks.is_empty();
|
||||
fn compile_func<'ir, Ctx: CodegenContext>(
|
||||
ArgId(id): ArgId,
|
||||
thunks: &[(ThunkId, RawIrRef<'ir>)],
|
||||
param: &Option<Param<'ir>>,
|
||||
body: RawIrRef<'ir>,
|
||||
ctx: &Ctx,
|
||||
buf: &mut CodeBuffer,
|
||||
) {
|
||||
let has_thunks = !thunks.is_empty();
|
||||
|
||||
if let Some(Param {
|
||||
required,
|
||||
optional,
|
||||
ellipsis,
|
||||
}) = &self.param
|
||||
}) = ¶m
|
||||
{
|
||||
code!(buf, "Nix.mkFunction(arg{}=>", id);
|
||||
code!(buf, "$mf(a{}=>", id);
|
||||
if has_thunks {
|
||||
code!(buf, ctx; "{" self.thunks "return " self.body "}");
|
||||
code!(buf, ctx; "{" thunks "return " body "}");
|
||||
} else {
|
||||
code!(buf, ctx; "(" self.body ")");
|
||||
code!(buf, ctx; "(" body ")");
|
||||
}
|
||||
code!(buf, ctx;
|
||||
",["
|
||||
@@ -459,229 +411,208 @@ impl<Ctx: CodegenContext> Compile<Ctx> for Func {
|
||||
joined(optional.iter(), ",", |ctx: &Ctx, buf, &(sym, _)| {
|
||||
code!(buf, ctx; ctx.get_sym(sym));
|
||||
})
|
||||
"],{"
|
||||
"],new Map(["
|
||||
joined(required.iter().chain(optional.iter()), ",", |ctx: &Ctx, buf, &(sym, span)| {
|
||||
code!(buf, ctx; ctx.get_sym(sym) ":" span);
|
||||
code!(buf, ctx; "[" ctx.get_sym(sym) "," span "]");
|
||||
})
|
||||
"},"
|
||||
"]),"
|
||||
ellipsis
|
||||
")"
|
||||
);
|
||||
} else {
|
||||
code!(buf, "arg{}=>", id);
|
||||
code!(buf, "a{}=>", id);
|
||||
if has_thunks {
|
||||
code!(buf, ctx; "{" self.thunks "return " self.body "}");
|
||||
code!(buf, ctx; "{" thunks "return " body "}");
|
||||
} else {
|
||||
code!(buf, ctx; "(" self.body ")");
|
||||
}
|
||||
code!(buf, ctx; "(" body ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for Call {
|
||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
code!(buf, ctx;
|
||||
"Nix.call("
|
||||
ctx.get_ir(self.func)
|
||||
","
|
||||
ctx.get_ir(self.arg)
|
||||
","
|
||||
self.span
|
||||
")"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for [(ExprId, ExprId)] {
|
||||
impl<'ir, Ctx: CodegenContext> Compile<Ctx> for [(ThunkId, RawIrRef<'ir>)] {
|
||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
if self.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
for &(slot, inner) in self {
|
||||
let inner_ir = ctx.get_ir(inner);
|
||||
let inner_span = inner_ir.span();
|
||||
|
||||
code!(
|
||||
buf, ctx;
|
||||
"let expr" slot.0 "=Nix.createThunk(()=>(" inner_ir "),"
|
||||
"\"expr" slot.0 " "
|
||||
ctx.get_current_source().get_name() ":"
|
||||
usize::from(inner_span.start()) ":"
|
||||
usize::from(inner_span.end())
|
||||
"\");"
|
||||
"const "
|
||||
joined(self.iter(), ",", |ctx: &Ctx, buf, &(slot, inner)| {
|
||||
code!(buf, ctx; "e" slot.0 "=$t(()=>(" inner ")," "'e" slot.0 "')");
|
||||
})
|
||||
";"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for TopLevel {
|
||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
if self.thunks.is_empty() {
|
||||
ctx.get_ir(self.body).compile(ctx, buf);
|
||||
fn compile_toplevel<'ir, Ctx: CodegenContext>(
|
||||
body: RawIrRef<'ir>,
|
||||
thunks: &[(ThunkId, RawIrRef<'ir>)],
|
||||
ctx: &Ctx,
|
||||
buf: &mut CodeBuffer,
|
||||
) {
|
||||
if thunks.is_empty() {
|
||||
body.compile(ctx, buf);
|
||||
} else {
|
||||
let body = ctx.get_ir(self.body);
|
||||
code!(buf, ctx; "(()=>{" self.thunks "return " body "})()");
|
||||
}
|
||||
code!(buf, ctx; "(()=>{" thunks "return " body "})()");
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for WithExpr {
|
||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
let namespace = ctx.get_ir(self.namespace);
|
||||
let body = ctx.get_ir(self.body);
|
||||
let has_thunks = !self.thunks.is_empty();
|
||||
fn compile_with<'ir>(
|
||||
namespace: RawIrRef<'ir>,
|
||||
body: RawIrRef<'ir>,
|
||||
thunks: &[(ThunkId, RawIrRef<'ir>)],
|
||||
ctx: &impl CodegenContext,
|
||||
buf: &mut CodeBuffer,
|
||||
) {
|
||||
let has_thunks = !thunks.is_empty();
|
||||
if has_thunks {
|
||||
code!(buf, ctx; "((__with)=>{" self.thunks "return " body "})({env:" namespace ",last:__with})");
|
||||
code!(buf, ctx; "((_w)=>{" thunks "return " body "})({env:" namespace ",last:_w})");
|
||||
} else {
|
||||
code!(buf, ctx; "((__with)=>(" body "))({env:" namespace ",last:__with})");
|
||||
}
|
||||
code!(buf, ctx; "((_w)=>(" body "))({env:" namespace ",last:_w})");
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for Select {
|
||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
if let Some(default) = self.default {
|
||||
fn compile_select<'ir, Ctx: CodegenContext>(
|
||||
expr: RawIrRef<'ir>,
|
||||
attrpath: &[Attr<RawIrRef<'ir>>],
|
||||
default: Option<RawIrRef<'ir>>,
|
||||
span: TextRange,
|
||||
ctx: &Ctx,
|
||||
buf: &mut CodeBuffer,
|
||||
) {
|
||||
if let Some(default) = default {
|
||||
code!(buf, ctx;
|
||||
"Nix.selectWithDefault("
|
||||
ctx.get_ir(self.expr)
|
||||
"$sd("
|
||||
expr
|
||||
",["
|
||||
joined(self.attrpath.iter(), ",", |ctx: &Ctx, buf, attr| {
|
||||
joined(attrpath.iter(), ",", |ctx: &Ctx, buf, attr| {
|
||||
match attr {
|
||||
Attr::Str(sym, _) => code!(buf, ctx; ctx.get_sym(*sym)),
|
||||
Attr::Dynamic(expr_id, _) => code!(buf, ctx; ctx.get_ir(*expr_id)),
|
||||
Attr::Dynamic(expr_id, _) => code!(buf, ctx; *expr_id),
|
||||
}
|
||||
})
|
||||
"],"
|
||||
ctx.get_ir(default)
|
||||
default
|
||||
","
|
||||
self.span
|
||||
span
|
||||
")"
|
||||
);
|
||||
} else {
|
||||
code!(buf, ctx;
|
||||
"Nix.select("
|
||||
ctx.get_ir(self.expr)
|
||||
"$s("
|
||||
expr
|
||||
",["
|
||||
joined(self.attrpath.iter(), ",", |ctx: &Ctx, buf, attr| {
|
||||
joined(attrpath.iter(), ",", |ctx: &Ctx, buf, attr| {
|
||||
match attr {
|
||||
Attr::Str(sym, _) => code!(buf, ctx; ctx.get_sym(*sym)),
|
||||
Attr::Dynamic(expr_id, _) => code!(buf, ctx; ctx.get_ir(*expr_id)),
|
||||
Attr::Dynamic(expr, _) => code!(buf, ctx; expr),
|
||||
}
|
||||
})
|
||||
"],"
|
||||
self.span
|
||||
span
|
||||
")"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for AttrSet {
|
||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
if !self.dyns.is_empty() {
|
||||
fn compile_attrset<'ir, Ctx: CodegenContext>(
|
||||
stcs: &HashMap<'ir, SymId, (RawIrRef<'ir>, TextRange)>,
|
||||
dyns: &[(RawIrRef<'ir>, RawIrRef<'ir>, TextRange)],
|
||||
ctx: &Ctx,
|
||||
buf: &mut CodeBuffer,
|
||||
) {
|
||||
if !dyns.is_empty() {
|
||||
code!(buf, ctx;
|
||||
"Nix.mkAttrsWithPos({"
|
||||
joined(self.stcs.iter(), ",", |ctx: &Ctx, buf, (&sym, &(expr, _))| {
|
||||
"$ma(new Map(["
|
||||
joined(stcs.iter(), ",", |ctx: &Ctx, buf, (&sym, &(val, _))| {
|
||||
let key = ctx.get_sym(sym);
|
||||
let val = ctx.get_ir(expr);
|
||||
|
||||
code!(
|
||||
buf, ctx;
|
||||
key ":Nix.withContext(\"while evaluating the attribute '" escaped(&key) "'\"," val.span() ",()=>(" val "))"
|
||||
"[" key "," val "]"
|
||||
);
|
||||
})
|
||||
"},{"
|
||||
joined(self.stcs.iter(), ",", |ctx: &Ctx, buf, (&sym, &(_, span))| {
|
||||
code!(buf, ctx; ctx.get_sym(sym) ":" span);
|
||||
"]),new Map(["
|
||||
joined(stcs.iter(), ",", |ctx: &Ctx, buf, (&sym, &(_, span))| {
|
||||
code!(buf, ctx; "[" ctx.get_sym(sym) "," span "]");
|
||||
})
|
||||
"},{dynKeys:["
|
||||
joined(self.dyns.iter(), ",", |ctx: &Ctx, buf, (key, _, _)| {
|
||||
code!(buf, ctx; ctx.get_ir(*key));
|
||||
"]),{dynKeys:["
|
||||
joined(dyns.iter(), ",", |ctx: &Ctx, buf, (key, _, _)| {
|
||||
code!(buf, ctx; key);
|
||||
})
|
||||
"],dynVals:["
|
||||
joined(self.dyns.iter(), ",", |ctx: &Ctx, buf, (_, val, _)| {
|
||||
let val = ctx.get_ir(*val);
|
||||
code!(
|
||||
buf, ctx;
|
||||
"Nix.withContext(\"while evaluating a dynamic attribute\"," val.span() ",()=>(" val "))"
|
||||
);
|
||||
joined(dyns.iter(), ",", |ctx: &Ctx, buf, (_, val, _)| {
|
||||
code!(buf, ctx; val);
|
||||
})
|
||||
"],dynSpans:["
|
||||
joined(self.dyns.iter(), ",", |ctx: &Ctx, buf, (_, _, attr_span)| {
|
||||
joined(dyns.iter(), ",", |ctx: &Ctx, buf, (_, _, attr_span)| {
|
||||
code!(buf, ctx; attr_span);
|
||||
})
|
||||
"]})"
|
||||
);
|
||||
} else if !self.stcs.is_empty() {
|
||||
} else if !stcs.is_empty() {
|
||||
code!(buf, ctx;
|
||||
"Nix.mkAttrsWithPos({"
|
||||
joined(self.stcs.iter(), ",", |ctx: &Ctx, buf, (&sym, &(expr, _))| {
|
||||
"$ma(new Map(["
|
||||
joined(stcs.iter(), ",", |ctx: &Ctx, buf, (&sym, &(val, _))| {
|
||||
let key = ctx.get_sym(sym);
|
||||
let val = ctx.get_ir(expr);
|
||||
|
||||
code!(
|
||||
buf, ctx;
|
||||
key ":Nix.withContext(\"while evaluating the attribute '" escaped(&key) "'\"," val.span() ",()=>(" val "))"
|
||||
"[" key "," val "]"
|
||||
);
|
||||
})
|
||||
"},{"
|
||||
joined(self.stcs.iter(), ",", |ctx: &Ctx, buf, (&sym, &(_, span))| {
|
||||
code!(buf, ctx; ctx.get_sym(sym) ":" span);
|
||||
"]),new Map(["
|
||||
joined(stcs.iter(), ",", |ctx: &Ctx, buf, (&sym, &(_, span))| {
|
||||
code!(buf, ctx; "[" ctx.get_sym(sym) "," span "]");
|
||||
})
|
||||
"})"
|
||||
"]))"
|
||||
);
|
||||
} else {
|
||||
code!(buf, ctx; "{}");
|
||||
}
|
||||
code!(buf, ctx; "$e");
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for List {
|
||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
fn compile_list<Ctx: CodegenContext>(items: &[RawIrRef<'_>], ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
code!(buf, ctx;
|
||||
"["
|
||||
joined(self.items.iter().enumerate(), ",", |ctx: &Ctx, buf, (idx, item)| {
|
||||
let item = ctx.get_ir(*item);
|
||||
code!(
|
||||
buf, ctx;
|
||||
"Nix.withContext(\"while evaluating list element " idx "\"," item.span() ",()=>(" item "))"
|
||||
);
|
||||
joined(items.iter(), ",", |ctx: &Ctx, buf, item| {
|
||||
code!(buf, ctx; item);
|
||||
})
|
||||
"]"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for ConcatStrings {
|
||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
fn compile_concat_strings<Ctx: CodegenContext>(
|
||||
parts: &[RawIrRef<'_>],
|
||||
force_string: bool,
|
||||
ctx: &Ctx,
|
||||
buf: &mut CodeBuffer,
|
||||
) {
|
||||
code!(buf, ctx;
|
||||
"Nix.concatStringsWithContext(["
|
||||
joined(self.parts.iter(), ",", |ctx: &Ctx, buf, part| {
|
||||
let part = ctx.get_ir(*part);
|
||||
code!(
|
||||
buf, ctx;
|
||||
"Nix.withContext(\"while evaluating a path segment\"," part.span() ",()=>(" part "))"
|
||||
);
|
||||
"$cs(["
|
||||
joined(parts.iter(), ",", |ctx: &Ctx, buf, part| {
|
||||
code!(buf, ctx; part);
|
||||
})
|
||||
"]," self.force_string ")"
|
||||
"]," force_string ")"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl<Ctx: CodegenContext> Compile<Ctx> for HasAttr {
|
||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||
fn compile_has_attr<'ir, Ctx: CodegenContext>(
|
||||
lhs: RawIrRef<'ir>,
|
||||
rhs: &[Attr<RawIrRef<'ir>>],
|
||||
ctx: &Ctx,
|
||||
buf: &mut CodeBuffer,
|
||||
) {
|
||||
code!(buf, ctx;
|
||||
"Nix.hasAttr("
|
||||
ctx.get_ir(self.lhs)
|
||||
"$h("
|
||||
lhs
|
||||
",["
|
||||
joined(self.rhs.iter(), ",", |ctx: &Ctx, buf, attr| {
|
||||
joined(rhs.iter(), ",", |ctx: &Ctx, buf, attr| {
|
||||
match attr {
|
||||
Attr::Str(sym, _) => code!(buf, ctx; ctx.get_sym(*sym)),
|
||||
Attr::Dynamic(expr_id, _) => code!(buf, ctx; ctx.get_ir(*expr_id)),
|
||||
Attr::Dynamic(expr, _) => code!(buf, ctx; expr),
|
||||
}
|
||||
})
|
||||
"])"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,22 @@
|
||||
use std::cell::UnsafeCell;
|
||||
use std::hash::BuildHasher;
|
||||
use std::path::Path;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
use hashbrown::{HashMap, HashSet};
|
||||
use bumpalo::Bump;
|
||||
use ghost_cell::{GhostCell, GhostToken};
|
||||
use hashbrown::{DefaultHashBuilder, HashMap, HashSet, HashTable};
|
||||
use rnix::TextRange;
|
||||
use string_interner::DefaultStringInterner;
|
||||
|
||||
use crate::codegen::{CodegenContext, compile, compile_scoped};
|
||||
use crate::bytecode::{self, Bytecode, BytecodeContext, Constant};
|
||||
use crate::codegen::{CodegenContext, compile};
|
||||
use crate::disassembler::{Disassembler, DisassemblerContext};
|
||||
use crate::downgrade::*;
|
||||
use crate::error::{Error, Result, Source};
|
||||
use crate::ir::{
|
||||
Arg, ArgId, Bool, Builtin, ExprId, Ir, Null, ReplBinding, ScopedImportBinding, SymId, Thunk,
|
||||
ToIr as _, WithLookup,
|
||||
};
|
||||
use crate::runtime::{Runtime, RuntimeContext};
|
||||
use crate::ir::{ArgId, Ir, IrKey, IrRef, RawIrRef, SymId, ThunkId, ir_content_eq};
|
||||
#[cfg(feature = "inspector")]
|
||||
use crate::runtime::inspector::InspectorServer;
|
||||
use crate::runtime::{ForceMode, Runtime, RuntimeContext};
|
||||
use crate::store::{DaemonStore, Store, StoreConfig};
|
||||
use crate::value::{Symbol, Value};
|
||||
|
||||
@@ -48,19 +52,19 @@ pub struct Context {
|
||||
ctx: Ctx,
|
||||
runtime: Runtime<Ctx>,
|
||||
#[cfg(feature = "inspector")]
|
||||
_inspector_server: Option<crate::runtime::inspector::InspectorServer>,
|
||||
_inspector_server: Option<InspectorServer>,
|
||||
}
|
||||
|
||||
macro_rules! eval {
|
||||
($name:ident, $wrapper:literal) => {
|
||||
macro_rules! eval_bc {
|
||||
($name:ident, $mode:expr) => {
|
||||
pub fn $name(&mut self, source: Source) -> Result<Value> {
|
||||
tracing::info!("Starting evaluation");
|
||||
|
||||
tracing::debug!("Compiling code");
|
||||
let code = self.compile(source)?;
|
||||
tracing::debug!("Compiling bytecode");
|
||||
let bytecode = self.ctx.compile_bytecode(source)?;
|
||||
|
||||
tracing::debug!("Executing JavaScript");
|
||||
self.runtime.eval(format!($wrapper, code), &mut self.ctx)
|
||||
tracing::debug!("Executing bytecode");
|
||||
self.runtime.eval_bytecode(bytecode, &mut self.ctx, $mode)
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -121,19 +125,23 @@ impl Context {
|
||||
let code = self.ctx.compile(source, None)?;
|
||||
self.runtime.eval(
|
||||
format!(
|
||||
"Nix.builtins.derivation = {};Nix.builtins.storeDir=\"{}\"",
|
||||
"Nix.builtins.set('derivation',({}));Nix.builtins.set('storeDir','{}');{}0n",
|
||||
code,
|
||||
self.get_store_dir()
|
||||
self.get_store_dir(),
|
||||
if std::env::var("NIX_JS_DEBUG_THUNKS").is_ok() {
|
||||
"Nix.DEBUG_THUNKS.enabled=true;"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
),
|
||||
&mut self.ctx,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
eval!(eval, "Nix.force({})");
|
||||
eval!(eval_shallow, "Nix.forceShallow({})");
|
||||
eval!(eval_deep, "Nix.forceDeep({})");
|
||||
|
||||
eval_bc!(eval, ForceMode::Force);
|
||||
eval_bc!(eval_shallow, ForceMode::ForceShallow);
|
||||
eval_bc!(eval_deep, ForceMode::ForceDeep);
|
||||
pub fn eval_repl<'a>(&'a mut self, source: Source, scope: &'a HashSet<SymId>) -> Result<Value> {
|
||||
tracing::info!("Starting evaluation");
|
||||
|
||||
@@ -149,6 +157,18 @@ impl Context {
|
||||
self.ctx.compile(source, None)
|
||||
}
|
||||
|
||||
pub fn compile_bytecode(&mut self, source: Source) -> Result<Bytecode> {
|
||||
self.ctx.compile_bytecode(source)
|
||||
}
|
||||
|
||||
pub fn disassemble(&self, bytecode: &Bytecode) -> String {
|
||||
Disassembler::new(bytecode, &self.ctx).disassemble()
|
||||
}
|
||||
|
||||
pub fn disassemble_colored(&self, bytecode: &Bytecode) -> String {
|
||||
Disassembler::new(bytecode, &self.ctx).disassemble_colored()
|
||||
}
|
||||
|
||||
pub fn get_store_dir(&self) -> &str {
|
||||
self.ctx.get_store_dir()
|
||||
}
|
||||
@@ -174,32 +194,44 @@ impl Context {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Ctx {
|
||||
irs: Vec<Ir>,
|
||||
struct Ctx {
|
||||
symbols: DefaultStringInterner,
|
||||
global: NonNull<HashMap<SymId, ExprId>>,
|
||||
global: HashMap<SymId, Ir<'static, RawIrRef<'static>>>,
|
||||
sources: Vec<Source>,
|
||||
store: DaemonStore,
|
||||
spans: UnsafeCell<Vec<(usize, TextRange)>>,
|
||||
thunk_count: usize,
|
||||
global_strings: Vec<String>,
|
||||
global_string_map: HashMap<String, u32>,
|
||||
global_constants: Vec<Constant>,
|
||||
global_constant_map: HashMap<Constant, u32>,
|
||||
synced_strings: usize,
|
||||
synced_constants: usize,
|
||||
}
|
||||
|
||||
/// Owns the bump allocator and a read-only reference into it.
|
||||
///
|
||||
/// # Safety
|
||||
/// The `ir` field points into `_bump`'s storage. We use `'static` as a sentinel
|
||||
/// lifetime because the struct owns the backing memory. The `as_ref` method
|
||||
/// re-binds the lifetime to `&self`, preventing use-after-free.
|
||||
struct OwnedIr {
|
||||
_bump: Bump,
|
||||
ir: RawIrRef<'static>,
|
||||
}
|
||||
|
||||
impl OwnedIr {
|
||||
fn as_ref(&self) -> RawIrRef<'_> {
|
||||
self.ir
|
||||
}
|
||||
}
|
||||
|
||||
impl Ctx {
|
||||
fn new() -> Result<Self> {
|
||||
use crate::ir::{Builtins, ToIr as _};
|
||||
|
||||
let mut symbols = DefaultStringInterner::new();
|
||||
let mut irs = Vec::new();
|
||||
let mut global = HashMap::new();
|
||||
|
||||
irs.push(
|
||||
Builtins {
|
||||
span: rnix::TextRange::default(),
|
||||
}
|
||||
.to_ir(),
|
||||
);
|
||||
let builtins_expr = ExprId(0);
|
||||
|
||||
let builtins_sym = symbols.get_or_intern("builtins");
|
||||
global.insert(builtins_sym, builtins_expr);
|
||||
global.insert(builtins_sym, Ir::Builtins);
|
||||
|
||||
let free_globals = [
|
||||
"abort",
|
||||
@@ -223,48 +255,19 @@ impl Ctx {
|
||||
"toString",
|
||||
];
|
||||
let consts = [
|
||||
(
|
||||
"true",
|
||||
Bool {
|
||||
inner: true,
|
||||
span: rnix::TextRange::default(),
|
||||
}
|
||||
.to_ir(),
|
||||
),
|
||||
(
|
||||
"false",
|
||||
Bool {
|
||||
inner: false,
|
||||
span: rnix::TextRange::default(),
|
||||
}
|
||||
.to_ir(),
|
||||
),
|
||||
(
|
||||
"null",
|
||||
Null {
|
||||
span: rnix::TextRange::default(),
|
||||
}
|
||||
.to_ir(),
|
||||
),
|
||||
("true", Ir::Bool(true)),
|
||||
("false", Ir::Bool(false)),
|
||||
("null", Ir::Null),
|
||||
];
|
||||
|
||||
for name in free_globals {
|
||||
let name_sym = symbols.get_or_intern(name);
|
||||
let id = ExprId(irs.len());
|
||||
irs.push(
|
||||
Builtin {
|
||||
inner: name_sym,
|
||||
span: rnix::TextRange::default(),
|
||||
}
|
||||
.to_ir(),
|
||||
);
|
||||
global.insert(name_sym, id);
|
||||
let name = symbols.get_or_intern(name);
|
||||
let value = Ir::Builtin(name);
|
||||
global.insert(name, value);
|
||||
}
|
||||
for (name, value) in consts {
|
||||
let name_sym = symbols.get_or_intern(name);
|
||||
let id = ExprId(irs.len());
|
||||
irs.push(value);
|
||||
global.insert(name_sym, id);
|
||||
let name = symbols.get_or_intern(name);
|
||||
global.insert(name, value);
|
||||
}
|
||||
|
||||
let config = StoreConfig::from_env();
|
||||
@@ -272,19 +275,39 @@ impl Ctx {
|
||||
|
||||
Ok(Self {
|
||||
symbols,
|
||||
irs,
|
||||
global: unsafe { NonNull::new_unchecked(Box::leak(Box::new(global))) },
|
||||
global,
|
||||
sources: Vec::new(),
|
||||
store,
|
||||
spans: UnsafeCell::new(Vec::new()),
|
||||
thunk_count: 0,
|
||||
global_strings: Vec::new(),
|
||||
global_string_map: HashMap::new(),
|
||||
global_constants: Vec::new(),
|
||||
global_constant_map: HashMap::new(),
|
||||
synced_strings: 0,
|
||||
synced_constants: 0,
|
||||
})
|
||||
}
|
||||
|
||||
fn downgrade_ctx<'a>(&'a mut self, extra_scope: Option<Scope<'a>>) -> DowngradeCtx<'a> {
|
||||
let global_ref = unsafe { self.global.as_ref() };
|
||||
DowngradeCtx::new(self, global_ref, extra_scope)
|
||||
fn downgrade_ctx<'ctx, 'id, 'ir>(
|
||||
&'ctx mut self,
|
||||
bump: &'ir Bump,
|
||||
token: GhostToken<'id>,
|
||||
extra_scope: Option<Scope<'ctx>>,
|
||||
) -> DowngradeCtx<'ctx, 'id, 'ir> {
|
||||
let source = self.get_current_source();
|
||||
DowngradeCtx::new(
|
||||
bump,
|
||||
token,
|
||||
&mut self.symbols,
|
||||
&self.global,
|
||||
extra_scope,
|
||||
&mut self.thunk_count,
|
||||
source,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn get_current_dir(&self) -> &Path {
|
||||
fn get_current_dir(&self) -> &Path {
|
||||
self.sources
|
||||
.last()
|
||||
.as_ref()
|
||||
@@ -292,18 +315,18 @@ impl Ctx {
|
||||
.get_dir()
|
||||
}
|
||||
|
||||
pub(crate) fn get_current_source(&self) -> Source {
|
||||
fn get_current_source(&self) -> Source {
|
||||
self.sources
|
||||
.last()
|
||||
.expect("current_source is not set")
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn get_source(&self, id: usize) -> Source {
|
||||
self.sources.get(id).expect("source not found").clone()
|
||||
}
|
||||
|
||||
fn downgrade<'a>(&mut self, source: Source, extra_scope: Option<Scope<'a>>) -> Result<ExprId> {
|
||||
fn downgrade<'ctx>(
|
||||
&'ctx mut self,
|
||||
source: Source,
|
||||
extra_scope: Option<Scope<'ctx>>,
|
||||
) -> Result<OwnedIr> {
|
||||
tracing::debug!("Parsing Nix expression");
|
||||
|
||||
self.sources.push(source.clone());
|
||||
@@ -316,18 +339,29 @@ impl Ctx {
|
||||
.tree()
|
||||
.expr()
|
||||
.ok_or_else(|| Error::parse_error("unexpected EOF".into()))?;
|
||||
self.downgrade_ctx(extra_scope).downgrade(expr)
|
||||
let bump = Bump::new();
|
||||
GhostToken::new(|token| {
|
||||
let ir = self
|
||||
.downgrade_ctx(&bump, token, extra_scope)
|
||||
.downgrade_toplevel(expr)?;
|
||||
let ir = unsafe { std::mem::transmute::<RawIrRef<'_>, RawIrRef<'static>>(ir) };
|
||||
Ok(OwnedIr { _bump: bump, ir })
|
||||
})
|
||||
}
|
||||
|
||||
fn compile<'a>(&'a mut self, source: Source, extra_scope: Option<Scope<'a>>) -> Result<String> {
|
||||
fn compile<'ctx>(
|
||||
&'ctx mut self,
|
||||
source: Source,
|
||||
extra_scope: Option<Scope<'ctx>>,
|
||||
) -> Result<String> {
|
||||
let root = self.downgrade(source, extra_scope)?;
|
||||
tracing::debug!("Generating JavaScript code");
|
||||
let code = compile(self.get_ir(root), self);
|
||||
let code = compile::<false>(root.as_ref(), self);
|
||||
tracing::debug!("Generated code: {}", &code);
|
||||
Ok(code)
|
||||
}
|
||||
|
||||
pub(crate) fn compile_scoped(&mut self, source: Source, scope: Vec<String>) -> Result<String> {
|
||||
fn compile_scoped(&mut self, source: Source, scope: Vec<String>) -> Result<String> {
|
||||
let scope = Scope::ScopedImport(
|
||||
scope
|
||||
.into_iter()
|
||||
@@ -336,16 +370,33 @@ impl Ctx {
|
||||
);
|
||||
let root = self.downgrade(source, Some(scope))?;
|
||||
tracing::debug!("Generating JavaScript code for scoped import");
|
||||
let code = compile_scoped(self.get_ir(root), self);
|
||||
let code = compile::<true>(root.as_ref(), self);
|
||||
tracing::debug!("Generated scoped code: {}", &code);
|
||||
Ok(code)
|
||||
}
|
||||
|
||||
fn compile_bytecode(&mut self, source: Source) -> Result<Bytecode> {
|
||||
let root = self.downgrade(source, None)?;
|
||||
tracing::debug!("Generating bytecode");
|
||||
let bytecode = bytecode::compile_bytecode(root.as_ref(), self);
|
||||
tracing::debug!("Compiled bytecode: {:#04X?}", bytecode.code);
|
||||
Ok(bytecode)
|
||||
}
|
||||
|
||||
fn compile_bytecode_scoped(&mut self, source: Source, scope: Vec<String>) -> Result<Bytecode> {
|
||||
let scope = Scope::ScopedImport(
|
||||
scope
|
||||
.into_iter()
|
||||
.map(|k| self.symbols.get_or_intern(k))
|
||||
.collect(),
|
||||
);
|
||||
let root = self.downgrade(source, Some(scope))?;
|
||||
tracing::debug!("Generating bytecode for scoped import");
|
||||
Ok(bytecode::compile_bytecode_scoped(root.as_ref(), self))
|
||||
}
|
||||
}
|
||||
|
||||
impl CodegenContext for Ctx {
|
||||
fn get_ir(&self, id: ExprId) -> &Ir {
|
||||
self.irs.get(id.0).expect("ExprId out of bounds")
|
||||
}
|
||||
fn get_sym(&self, id: SymId) -> Symbol<'_> {
|
||||
self.symbols
|
||||
.resolve(id)
|
||||
@@ -361,12 +412,49 @@ impl CodegenContext for Ctx {
|
||||
.checked_sub(1)
|
||||
.expect("current_source not set")
|
||||
}
|
||||
fn get_current_source(&self) -> crate::error::Source {
|
||||
self.sources.last().expect("current_source not set").clone()
|
||||
}
|
||||
fn get_store_dir(&self) -> &str {
|
||||
self.store.get_store_dir()
|
||||
}
|
||||
fn register_span(&self, range: rnix::TextRange) -> usize {
|
||||
let spans = unsafe { &mut *self.spans.get() };
|
||||
let id = spans.len();
|
||||
spans.push((self.get_current_source_id(), range));
|
||||
id
|
||||
}
|
||||
}
|
||||
|
||||
impl BytecodeContext for Ctx {
|
||||
fn intern_string(&mut self, s: &str) -> u32 {
|
||||
if let Some(&idx) = self.global_string_map.get(s) {
|
||||
return idx;
|
||||
}
|
||||
let idx = self.global_strings.len() as u32;
|
||||
self.global_strings.push(s.to_string());
|
||||
self.global_string_map.insert(s.to_string(), idx);
|
||||
idx
|
||||
}
|
||||
|
||||
fn intern_constant(&mut self, c: Constant) -> u32 {
|
||||
if let Some(&idx) = self.global_constant_map.get(&c) {
|
||||
return idx;
|
||||
}
|
||||
let idx = self.global_constants.len() as u32;
|
||||
self.global_constants.push(c.clone());
|
||||
self.global_constant_map.insert(c, idx);
|
||||
idx
|
||||
}
|
||||
|
||||
fn register_span(&self, range: TextRange) -> u32 {
|
||||
CodegenContext::register_span(self, range) as u32
|
||||
}
|
||||
|
||||
fn get_sym(&self, id: SymId) -> &str {
|
||||
self.symbols.resolve(id).expect("SymId out of bounds")
|
||||
}
|
||||
|
||||
fn get_current_dir(&self) -> &Path {
|
||||
Ctx::get_current_dir(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl RuntimeContext for Ctx {
|
||||
@@ -382,156 +470,239 @@ impl RuntimeContext for Ctx {
|
||||
fn compile_scoped(&mut self, source: Source, scope: Vec<String>) -> Result<String> {
|
||||
self.compile_scoped(source, scope)
|
||||
}
|
||||
fn compile_bytecode(&mut self, source: Source) -> Result<Bytecode> {
|
||||
self.compile_bytecode(source)
|
||||
}
|
||||
fn compile_bytecode_scoped(&mut self, source: Source, scope: Vec<String>) -> Result<Bytecode> {
|
||||
self.compile_bytecode_scoped(source, scope)
|
||||
}
|
||||
fn get_source(&self, id: usize) -> Source {
|
||||
self.get_source(id)
|
||||
self.sources.get(id).expect("source not found").clone()
|
||||
}
|
||||
fn get_store(&self) -> &DaemonStore {
|
||||
&self.store
|
||||
}
|
||||
fn get_span(&self, id: usize) -> (usize, TextRange) {
|
||||
let spans = unsafe { &*self.spans.get() };
|
||||
spans[id]
|
||||
}
|
||||
fn get_unsynced(&mut self) -> (&[String], &[Constant], usize, usize) {
|
||||
let strings_base = self.synced_strings;
|
||||
let constants_base = self.synced_constants;
|
||||
let new_strings = &self.global_strings[strings_base..];
|
||||
let new_constants = &self.global_constants[constants_base..];
|
||||
self.synced_strings = self.global_strings.len();
|
||||
self.synced_constants = self.global_constants.len();
|
||||
(new_strings, new_constants, strings_base, constants_base)
|
||||
}
|
||||
}
|
||||
|
||||
impl DisassemblerContext for Ctx {
|
||||
fn lookup_string(&self, id: u32) -> &str {
|
||||
self.global_strings
|
||||
.get(id as usize)
|
||||
.expect("string not found")
|
||||
}
|
||||
fn lookup_constant(&self, id: u32) -> &Constant {
|
||||
self.global_constants
|
||||
.get(id as usize)
|
||||
.expect("constant not found")
|
||||
}
|
||||
}
|
||||
|
||||
enum Scope<'ctx> {
|
||||
Global(&'ctx HashMap<SymId, ExprId>),
|
||||
Global(&'ctx HashMap<SymId, Ir<'static, RawIrRef<'static>>>),
|
||||
Repl(&'ctx HashSet<SymId>),
|
||||
ScopedImport(HashSet<SymId>),
|
||||
Let(HashMap<SymId, ExprId>),
|
||||
Param(SymId, ExprId),
|
||||
Let(HashMap<SymId, ThunkId>),
|
||||
Param(SymId, ArgId),
|
||||
}
|
||||
|
||||
struct ScopeGuard<'a, 'ctx> {
|
||||
ctx: &'a mut DowngradeCtx<'ctx>,
|
||||
struct ScopeGuard<'a, 'ctx, 'id, 'ir> {
|
||||
ctx: &'a mut DowngradeCtx<'ctx, 'id, 'ir>,
|
||||
}
|
||||
|
||||
impl<'a, 'ctx> Drop for ScopeGuard<'a, 'ctx> {
|
||||
impl Drop for ScopeGuard<'_, '_, '_, '_> {
|
||||
fn drop(&mut self) {
|
||||
self.ctx.scopes.pop();
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'ctx> ScopeGuard<'a, 'ctx> {
|
||||
fn as_ctx(&mut self) -> &mut DowngradeCtx<'ctx> {
|
||||
impl<'id, 'ir, 'ctx> ScopeGuard<'_, 'ctx, 'id, 'ir> {
|
||||
fn as_ctx(&mut self) -> &mut DowngradeCtx<'ctx, 'id, 'ir> {
|
||||
self.ctx
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DowngradeCtx<'ctx> {
|
||||
ctx: &'ctx mut Ctx,
|
||||
irs: Vec<Ir>,
|
||||
struct ThunkScope<'id, 'ir> {
|
||||
bindings: bumpalo::collections::Vec<'ir, (ThunkId, IrRef<'id, 'ir>)>,
|
||||
cache: HashTable<(IrRef<'id, 'ir>, ThunkId)>,
|
||||
hasher: DefaultHashBuilder,
|
||||
}
|
||||
|
||||
impl<'id, 'ir> ThunkScope<'id, 'ir> {
|
||||
fn new_in(bump: &'ir Bump) -> Self {
|
||||
Self {
|
||||
bindings: bumpalo::collections::Vec::new_in(bump),
|
||||
cache: HashTable::new(),
|
||||
hasher: DefaultHashBuilder::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn lookup_cache(&self, key: IrRef<'id, 'ir>, token: &GhostToken<'id>) -> Option<ThunkId> {
|
||||
let hash = self.hasher.hash_one(IrKey(key, token));
|
||||
self.cache
|
||||
.find(hash, |&(ir, _)| ir_content_eq(key, ir, token))
|
||||
.map(|&(_, id)| id)
|
||||
}
|
||||
|
||||
fn add_binding(&mut self, id: ThunkId, ir: IrRef<'id, 'ir>, token: &GhostToken<'id>) {
|
||||
self.bindings.push((id, ir));
|
||||
let hash = self.hasher.hash_one(IrKey(ir, token));
|
||||
self.cache.insert_unique(hash, (ir, id), |&(ir, _)| {
|
||||
self.hasher.hash_one(IrKey(ir, token))
|
||||
});
|
||||
}
|
||||
|
||||
fn extend_bindings(&mut self, iter: impl IntoIterator<Item = (ThunkId, IrRef<'id, 'ir>)>) {
|
||||
self.bindings.extend(iter);
|
||||
}
|
||||
}
|
||||
|
||||
struct DowngradeCtx<'ctx, 'id, 'ir> {
|
||||
bump: &'ir Bump,
|
||||
token: GhostToken<'id>,
|
||||
symbols: &'ctx mut DefaultStringInterner,
|
||||
source: Source,
|
||||
scopes: Vec<Scope<'ctx>>,
|
||||
with_scope_count: usize,
|
||||
arg_id: usize,
|
||||
thunk_scopes: Vec<Vec<(ExprId, ExprId)>>,
|
||||
arg_count: usize,
|
||||
thunk_count: &'ctx mut usize,
|
||||
thunk_scopes: Vec<ThunkScope<'id, 'ir>>,
|
||||
}
|
||||
|
||||
impl<'ctx> DowngradeCtx<'ctx> {
|
||||
fn new(
|
||||
ctx: &'ctx mut Ctx,
|
||||
global: &'ctx HashMap<SymId, ExprId>,
|
||||
extra_scope: Option<Scope<'ctx>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
scopes: std::iter::once(Scope::Global(global))
|
||||
.chain(extra_scope)
|
||||
.collect(),
|
||||
irs: vec![],
|
||||
arg_id: 0,
|
||||
with_scope_count: 0,
|
||||
thunk_scopes: vec![Vec::new()],
|
||||
ctx,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DowngradeContext for DowngradeCtx<'_> {
|
||||
fn new_expr(&mut self, expr: Ir) -> ExprId {
|
||||
self.irs.push(expr);
|
||||
ExprId(self.ctx.irs.len() + self.irs.len() - 1)
|
||||
}
|
||||
|
||||
fn new_arg(&mut self, span: TextRange) -> ExprId {
|
||||
self.irs.push(
|
||||
Arg {
|
||||
inner: ArgId(self.arg_id),
|
||||
span,
|
||||
}
|
||||
.to_ir(),
|
||||
);
|
||||
self.arg_id += 1;
|
||||
ExprId(self.ctx.irs.len() + self.irs.len() - 1)
|
||||
}
|
||||
|
||||
fn get_ir(&self, id: ExprId) -> &Ir {
|
||||
if id.0 < self.ctx.irs.len() {
|
||||
self.ctx.irs.get(id.0).expect("unreachable")
|
||||
} else {
|
||||
self.irs
|
||||
.get(id.0 - self.ctx.irs.len())
|
||||
.expect("ExprId out of bounds")
|
||||
}
|
||||
}
|
||||
|
||||
fn maybe_thunk(&mut self, id: ExprId) -> ExprId {
|
||||
let ir = self.get_ir(id);
|
||||
match ir {
|
||||
fn should_thunk<'id>(ir: IrRef<'id, '_>, token: &GhostToken<'id>) -> bool {
|
||||
!matches!(
|
||||
ir.borrow(token),
|
||||
Ir::Builtin(_)
|
||||
| Ir::Builtins(_)
|
||||
| Ir::Builtins
|
||||
| Ir::Int(_)
|
||||
| Ir::Float(_)
|
||||
| Ir::Bool(_)
|
||||
| Ir::Null(_)
|
||||
| Ir::Null
|
||||
| Ir::Str(_)
|
||||
| Ir::Thunk(_) => id,
|
||||
_ => {
|
||||
let span = ir.span();
|
||||
let slot = self.reserve_slots(1).next().expect("reserve_slots failed");
|
||||
self.replace_ir(slot, Thunk { inner: slot, span }.to_ir());
|
||||
self.register_thunk(slot, id);
|
||||
slot
|
||||
| Ir::Thunk(_)
|
||||
)
|
||||
}
|
||||
|
||||
impl<'ctx, 'id, 'ir> DowngradeCtx<'ctx, 'id, 'ir> {
|
||||
fn new(
|
||||
bump: &'ir Bump,
|
||||
token: GhostToken<'id>,
|
||||
symbols: &'ctx mut DefaultStringInterner,
|
||||
global: &'ctx HashMap<SymId, Ir<'static, RawIrRef<'static>>>,
|
||||
extra_scope: Option<Scope<'ctx>>,
|
||||
thunk_count: &'ctx mut usize,
|
||||
source: Source,
|
||||
) -> Self {
|
||||
Self {
|
||||
bump,
|
||||
token,
|
||||
symbols,
|
||||
source,
|
||||
scopes: std::iter::once(Scope::Global(global))
|
||||
.chain(extra_scope)
|
||||
.collect(),
|
||||
thunk_count,
|
||||
arg_count: 0,
|
||||
with_scope_count: 0,
|
||||
thunk_scopes: vec![ThunkScope::new_in(bump)],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx: 'ir, 'id, 'ir> DowngradeContext<'id, 'ir> for DowngradeCtx<'ctx, 'id, 'ir> {
|
||||
fn new_expr(&self, expr: Ir<'ir, IrRef<'id, 'ir>>) -> IrRef<'id, 'ir> {
|
||||
IrRef::new(self.bump.alloc(GhostCell::new(expr)))
|
||||
}
|
||||
|
||||
fn new_arg(&mut self) -> ArgId {
|
||||
self.arg_count += 1;
|
||||
ArgId(self.arg_count - 1)
|
||||
}
|
||||
|
||||
fn maybe_thunk(&mut self, ir: IrRef<'id, 'ir>) -> IrRef<'id, 'ir> {
|
||||
if !should_thunk(ir, &self.token) {
|
||||
return ir;
|
||||
}
|
||||
|
||||
let cached = self
|
||||
.thunk_scopes
|
||||
.last()
|
||||
.expect("no active cache scope")
|
||||
.lookup_cache(ir, &self.token);
|
||||
|
||||
if let Some(id) = cached {
|
||||
return IrRef::alloc(self.bump, Ir::Thunk(id));
|
||||
}
|
||||
|
||||
let id = ThunkId(*self.thunk_count);
|
||||
*self.thunk_count = self.thunk_count.checked_add(1).expect("thunk id overflow");
|
||||
self.thunk_scopes
|
||||
.last_mut()
|
||||
.expect("no active cache scope")
|
||||
.add_binding(id, ir, &self.token);
|
||||
IrRef::alloc(self.bump, Ir::Thunk(id))
|
||||
}
|
||||
|
||||
fn new_sym(&mut self, sym: String) -> SymId {
|
||||
self.ctx.symbols.get_or_intern(sym)
|
||||
self.symbols.get_or_intern(sym)
|
||||
}
|
||||
|
||||
fn get_sym(&self, id: SymId) -> Symbol<'_> {
|
||||
self.ctx.get_sym(id)
|
||||
self.symbols.resolve(id).expect("no symbol found").into()
|
||||
}
|
||||
|
||||
fn lookup(&mut self, sym: SymId, span: TextRange) -> Result<ExprId> {
|
||||
fn lookup(&self, sym: SymId, span: TextRange) -> Result<IrRef<'id, 'ir>> {
|
||||
for scope in self.scopes.iter().rev() {
|
||||
match scope {
|
||||
&Scope::Global(global_scope) => {
|
||||
if let Some(&expr) = global_scope.get(&sym) {
|
||||
return Ok(expr);
|
||||
if let Some(expr) = global_scope.get(&sym) {
|
||||
let ir = match expr {
|
||||
Ir::Builtins => Ir::Builtins,
|
||||
Ir::Builtin(s) => Ir::Builtin(*s),
|
||||
Ir::Bool(b) => Ir::Bool(*b),
|
||||
Ir::Null => Ir::Null,
|
||||
_ => unreachable!("globals should only contain leaf IR nodes"),
|
||||
};
|
||||
return Ok(self.new_expr(ir));
|
||||
}
|
||||
}
|
||||
&Scope::Repl(repl_bindings) => {
|
||||
if repl_bindings.contains(&sym) {
|
||||
return Ok(self.new_expr(ReplBinding { inner: sym, span }.to_ir()));
|
||||
return Ok(self.new_expr(Ir::ReplBinding(sym)));
|
||||
}
|
||||
}
|
||||
Scope::ScopedImport(scoped_bindings) => {
|
||||
if scoped_bindings.contains(&sym) {
|
||||
return Ok(self.new_expr(ScopedImportBinding { inner: sym, span }.to_ir()));
|
||||
return Ok(self.new_expr(Ir::ScopedImportBinding(sym)));
|
||||
}
|
||||
}
|
||||
Scope::Let(let_scope) => {
|
||||
if let Some(&expr) = let_scope.get(&sym) {
|
||||
return Ok(self.new_expr(Thunk { inner: expr, span }.to_ir()));
|
||||
return Ok(self.new_expr(Ir::Thunk(expr)));
|
||||
}
|
||||
}
|
||||
&Scope::Param(param_sym, expr) => {
|
||||
&Scope::Param(param_sym, id) => {
|
||||
if param_sym == sym {
|
||||
return Ok(expr);
|
||||
return Ok(self.new_expr(Ir::Arg(id)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if self.with_scope_count > 0 {
|
||||
Ok(self.new_expr(WithLookup { inner: sym, span }.to_ir()))
|
||||
Ok(self.new_expr(Ir::WithLookup(sym)))
|
||||
} else {
|
||||
Err(Error::downgrade_error(
|
||||
format!("'{}' not found", self.get_sym(sym)),
|
||||
@@ -541,49 +712,37 @@ impl DowngradeContext for DowngradeCtx<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
fn replace_ir(&mut self, id: ExprId, expr: Ir) {
|
||||
let local_id = id.0 - self.ctx.irs.len();
|
||||
*self.irs.get_mut(local_id).expect("ExprId out of bounds") = expr;
|
||||
}
|
||||
|
||||
fn get_current_source(&self) -> Source {
|
||||
self.ctx.get_current_source()
|
||||
self.source.clone()
|
||||
}
|
||||
|
||||
#[allow(refining_impl_trait)]
|
||||
fn reserve_slots(&mut self, slots: usize) -> impl Iterator<Item = ExprId> + Clone + use<> {
|
||||
let start = self.ctx.irs.len() + self.irs.len();
|
||||
let range = (start..start + slots).map(ExprId);
|
||||
let span = rnix::TextRange::default();
|
||||
// Fill reserved slots with placeholder value
|
||||
self.irs.extend(
|
||||
range
|
||||
.clone()
|
||||
.map(|slot| Thunk { inner: slot, span }.to_ir()),
|
||||
);
|
||||
range
|
||||
}
|
||||
|
||||
fn downgrade(mut self, root: rnix::ast::Expr) -> Result<ExprId> {
|
||||
use crate::ir::TopLevel;
|
||||
let body = root.downgrade(&mut self)?;
|
||||
let thunks = self.thunk_scopes.pop().expect("no thunk scope left???");
|
||||
let span = self.get_ir(body).span();
|
||||
let top_level = self.new_expr(TopLevel { body, thunks, span }.to_ir());
|
||||
self.ctx.irs.extend(self.irs);
|
||||
Ok(top_level)
|
||||
}
|
||||
|
||||
fn with_let_scope<F, R>(&mut self, bindings: HashMap<SymId, ExprId>, f: F) -> R
|
||||
fn with_let_scope<F, R>(&mut self, keys: &[SymId], f: F) -> Result<R>
|
||||
where
|
||||
F: FnOnce(&mut Self) -> R,
|
||||
F: FnOnce(&mut Self) -> Result<(bumpalo::collections::Vec<'ir, IrRef<'id, 'ir>>, R)>,
|
||||
{
|
||||
self.scopes.push(Scope::Let(bindings));
|
||||
let base = *self.thunk_count;
|
||||
*self.thunk_count = self
|
||||
.thunk_count
|
||||
.checked_add(keys.len())
|
||||
.expect("thunk id overflow");
|
||||
let iter = keys.iter().enumerate().map(|(offset, &key)| {
|
||||
(
|
||||
key,
|
||||
ThunkId(unsafe { base.checked_add(offset).unwrap_unchecked() }),
|
||||
)
|
||||
});
|
||||
self.scopes.push(Scope::Let(iter.collect()));
|
||||
let (vals, ret) = {
|
||||
let mut guard = ScopeGuard { ctx: self };
|
||||
f(guard.as_ctx())
|
||||
f(guard.as_ctx())?
|
||||
};
|
||||
assert_eq!(keys.len(), vals.len());
|
||||
let scope = self.thunk_scopes.last_mut().expect("no active thunk scope");
|
||||
scope.extend_bindings((base..base + keys.len()).map(ThunkId).zip(vals));
|
||||
Ok(ret)
|
||||
}
|
||||
|
||||
fn with_param_scope<F, R>(&mut self, param: SymId, arg: ExprId, f: F) -> R
|
||||
fn with_param_scope<F, R>(&mut self, param: SymId, arg: ArgId, f: F) -> R
|
||||
where
|
||||
F: FnOnce(&mut Self) -> R,
|
||||
{
|
||||
@@ -602,22 +761,41 @@ impl DowngradeContext for DowngradeCtx<'_> {
|
||||
ret
|
||||
}
|
||||
|
||||
fn with_thunk_scope<F, R>(&mut self, f: F) -> (R, Vec<(ExprId, ExprId)>)
|
||||
fn with_thunk_scope<F, R>(
|
||||
&mut self,
|
||||
f: F,
|
||||
) -> (
|
||||
R,
|
||||
bumpalo::collections::Vec<'ir, (ThunkId, IrRef<'id, 'ir>)>,
|
||||
)
|
||||
where
|
||||
F: FnOnce(&mut Self) -> R,
|
||||
{
|
||||
self.thunk_scopes.push(Vec::new());
|
||||
self.thunk_scopes.push(ThunkScope::new_in(self.bump));
|
||||
let ret = f(self);
|
||||
(
|
||||
ret,
|
||||
self.thunk_scopes.pop().expect("no thunk scope left???"),
|
||||
self.thunk_scopes
|
||||
.pop()
|
||||
.expect("no thunk scope left???")
|
||||
.bindings,
|
||||
)
|
||||
}
|
||||
|
||||
fn register_thunk(&mut self, slot: ExprId, inner: ExprId) {
|
||||
self.thunk_scopes
|
||||
.last_mut()
|
||||
.expect("register_thunk without active scope")
|
||||
.push((slot, inner));
|
||||
fn bump(&self) -> &'ir bumpalo::Bump {
|
||||
self.bump
|
||||
}
|
||||
}
|
||||
|
||||
impl<'id, 'ir, 'ctx: 'ir> DowngradeCtx<'ctx, 'id, 'ir> {
|
||||
fn downgrade_toplevel(mut self, root: rnix::ast::Expr) -> Result<RawIrRef<'ir>> {
|
||||
let body = root.downgrade(&mut self)?;
|
||||
let thunks = self
|
||||
.thunk_scopes
|
||||
.pop()
|
||||
.expect("no thunk scope left???")
|
||||
.bindings;
|
||||
let ir = IrRef::alloc(self.bump, Ir::TopLevel { body, thunks });
|
||||
Ok(ir.freeze(self.token))
|
||||
}
|
||||
}
|
||||
|
||||
354
nix-js/src/disassembler.rs
Normal file
354
nix-js/src/disassembler.rs
Normal file
@@ -0,0 +1,354 @@
|
||||
use std::fmt::Write;
|
||||
|
||||
use colored::Colorize;
|
||||
use num_enum::TryFromPrimitive;
|
||||
|
||||
use crate::bytecode::{Bytecode, Constant, Op};
|
||||
|
||||
pub(crate) trait DisassemblerContext {
|
||||
fn lookup_string(&self, id: u32) -> &str;
|
||||
fn lookup_constant(&self, id: u32) -> &Constant;
|
||||
}
|
||||
|
||||
pub(crate) struct Disassembler<'a, Ctx> {
|
||||
code: &'a [u8],
|
||||
ctx: &'a Ctx,
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl<'a, Ctx: DisassemblerContext> Disassembler<'a, Ctx> {
|
||||
pub fn new(bytecode: &'a Bytecode, ctx: &'a Ctx) -> Self {
|
||||
Self {
|
||||
code: &bytecode.code,
|
||||
ctx,
|
||||
pos: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn read_u8(&mut self) -> u8 {
|
||||
let b = self.code[self.pos];
|
||||
self.pos += 1;
|
||||
b
|
||||
}
|
||||
|
||||
fn read_u16(&mut self) -> u16 {
|
||||
let bytes = self.code[self.pos..self.pos + 2]
|
||||
.try_into()
|
||||
.expect("no enough bytes");
|
||||
self.pos += 2;
|
||||
u16::from_le_bytes(bytes)
|
||||
}
|
||||
|
||||
fn read_u32(&mut self) -> u32 {
|
||||
let bytes = self.code[self.pos..self.pos + 4]
|
||||
.try_into()
|
||||
.expect("no enough bytes");
|
||||
self.pos += 4;
|
||||
u32::from_le_bytes(bytes)
|
||||
}
|
||||
|
||||
fn read_i32(&mut self) -> i32 {
|
||||
let bytes = self.code[self.pos..self.pos + 4]
|
||||
.try_into()
|
||||
.expect("no enough bytes");
|
||||
self.pos += 4;
|
||||
i32::from_le_bytes(bytes)
|
||||
}
|
||||
|
||||
pub fn disassemble(&mut self) -> String {
|
||||
self.disassemble_impl(false)
|
||||
}
|
||||
|
||||
pub fn disassemble_colored(&mut self) -> String {
|
||||
self.disassemble_impl(true)
|
||||
}
|
||||
|
||||
fn disassemble_impl(&mut self, color: bool) -> String {
|
||||
let mut out = String::new();
|
||||
if color {
|
||||
let _ = writeln!(out, "{}", "=== Bytecode Disassembly ===".bold().white());
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{} {}",
|
||||
"Length:".white(),
|
||||
format!("{} bytes", self.code.len()).cyan()
|
||||
);
|
||||
} else {
|
||||
let _ = writeln!(out, "=== Bytecode Disassembly ===");
|
||||
let _ = writeln!(out, "Length: {} bytes", self.code.len());
|
||||
}
|
||||
|
||||
while self.pos < self.code.len() {
|
||||
let start_pos = self.pos;
|
||||
let op_byte = self.read_u8();
|
||||
let (mnemonic, args) = self.decode_instruction(op_byte, start_pos);
|
||||
|
||||
let bytes_slice = &self.code[start_pos + 1..self.pos];
|
||||
|
||||
for (i, chunk) in bytes_slice.chunks(4).enumerate() {
|
||||
let bytes_str = {
|
||||
let mut temp = String::new();
|
||||
if i == 0 {
|
||||
let _ = write!(&mut temp, "{:02x}", self.code[start_pos]);
|
||||
} else {
|
||||
let _ = write!(&mut temp, " ");
|
||||
}
|
||||
for b in chunk.iter() {
|
||||
let _ = write!(&mut temp, " {:02x}", b);
|
||||
}
|
||||
temp
|
||||
};
|
||||
|
||||
if i == 0 {
|
||||
if color {
|
||||
let sep = if args.is_empty() { "" } else { " " };
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{} {:<14} | {}{}{}",
|
||||
format!("{:04x}", start_pos).dimmed(),
|
||||
bytes_str.green(),
|
||||
mnemonic.yellow().bold(),
|
||||
sep,
|
||||
args.cyan()
|
||||
);
|
||||
} else {
|
||||
let op_str = if args.is_empty() {
|
||||
mnemonic.to_string()
|
||||
} else {
|
||||
format!("{} {}", mnemonic, args)
|
||||
};
|
||||
let _ = writeln!(out, "{:04x} {:<14} | {}", start_pos, bytes_str, op_str);
|
||||
}
|
||||
} else {
|
||||
let extra_width = start_pos.ilog2() >> 4;
|
||||
if color {
|
||||
let _ = write!(out, " ");
|
||||
for _ in 0..extra_width {
|
||||
let _ = write!(out, " ");
|
||||
}
|
||||
let _ = writeln!(out, " {:<14} |", bytes_str.green());
|
||||
} else {
|
||||
let _ = write!(out, " ");
|
||||
for _ in 0..extra_width {
|
||||
let _ = write!(out, " ");
|
||||
}
|
||||
let _ = writeln!(out, " {:<14} |", bytes_str);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn decode_instruction(&mut self, op_byte: u8, current_pc: usize) -> (&'static str, String) {
|
||||
let op = Op::try_from_primitive(op_byte).expect("invalid op code");
|
||||
|
||||
match op {
|
||||
Op::PushConst => {
|
||||
let idx = self.read_u32();
|
||||
let val = self.ctx.lookup_constant(idx);
|
||||
let val_str = match val {
|
||||
Constant::Int(i) => format!("Int({})", i),
|
||||
Constant::Float(f) => format!("Float(bits: {})", f),
|
||||
};
|
||||
("PushConst", format!("@{} ({})", idx, val_str))
|
||||
}
|
||||
Op::PushString => {
|
||||
let idx = self.read_u32();
|
||||
let s = self.ctx.lookup_string(idx);
|
||||
let len = s.len();
|
||||
let mut s_fmt = format!("{:?}", s);
|
||||
if s_fmt.len() > 60 {
|
||||
s_fmt.truncate(57);
|
||||
#[allow(clippy::unwrap_used)]
|
||||
write!(s_fmt, "...\" (total {len} bytes)").unwrap();
|
||||
}
|
||||
("PushString", format!("@{} {}", idx, s_fmt))
|
||||
}
|
||||
Op::PushNull => ("PushNull", String::new()),
|
||||
Op::PushTrue => ("PushTrue", String::new()),
|
||||
Op::PushFalse => ("PushFalse", String::new()),
|
||||
|
||||
Op::LoadLocal => {
|
||||
let idx = self.read_u32();
|
||||
("LoadLocal", format!("[{}]", idx))
|
||||
}
|
||||
Op::LoadOuter => {
|
||||
let depth = self.read_u8();
|
||||
let idx = self.read_u32();
|
||||
("LoadOuter", format!("depth={} [{}]", depth, idx))
|
||||
}
|
||||
Op::StoreLocal => {
|
||||
let idx = self.read_u32();
|
||||
("StoreLocal", format!("[{}]", idx))
|
||||
}
|
||||
Op::AllocLocals => {
|
||||
let count = self.read_u32();
|
||||
("AllocLocals", format!("count={}", count))
|
||||
}
|
||||
|
||||
Op::MakeThunk => {
|
||||
let offset = self.read_u32();
|
||||
let label_idx = self.read_u32();
|
||||
let label = self.ctx.lookup_string(label_idx);
|
||||
("MakeThunk", format!("-> {:04x} label={}", offset, label))
|
||||
}
|
||||
Op::MakeClosure => {
|
||||
let offset = self.read_u32();
|
||||
let slots = self.read_u32();
|
||||
("MakeClosure", format!("-> {:04x} slots={}", offset, slots))
|
||||
}
|
||||
Op::MakePatternClosure => {
|
||||
let offset = self.read_u32();
|
||||
let slots = self.read_u32();
|
||||
let req_count = self.read_u16();
|
||||
let opt_count = self.read_u16();
|
||||
let ellipsis = self.read_u8() != 0;
|
||||
|
||||
let mut arg_str = format!(
|
||||
"-> {:04x} slots={} req={} opt={} ...={})",
|
||||
offset, slots, req_count, opt_count, ellipsis
|
||||
);
|
||||
|
||||
arg_str.push_str(" Args=[");
|
||||
for _ in 0..req_count {
|
||||
let idx = self.read_u32();
|
||||
arg_str.push_str(&format!("Req({}) ", self.ctx.lookup_string(idx)));
|
||||
}
|
||||
for _ in 0..opt_count {
|
||||
let idx = self.read_u32();
|
||||
arg_str.push_str(&format!("Opt({}) ", self.ctx.lookup_string(idx)));
|
||||
}
|
||||
|
||||
let total_args = req_count + opt_count;
|
||||
for _ in 0..total_args {
|
||||
let _name_idx = self.read_u32();
|
||||
let _span_id = self.read_u32();
|
||||
}
|
||||
arg_str.push(']');
|
||||
|
||||
("MakePatternClosure", arg_str)
|
||||
}
|
||||
|
||||
Op::Call => {
|
||||
let span_id = self.read_u32();
|
||||
("Call", format!("span={}", span_id))
|
||||
}
|
||||
Op::CallNoSpan => ("CallNoSpan", String::new()),
|
||||
|
||||
Op::MakeAttrs => {
|
||||
let count = self.read_u32();
|
||||
("MakeAttrs", format!("size={}", count))
|
||||
}
|
||||
Op::MakeAttrsDyn => {
|
||||
let static_count = self.read_u32();
|
||||
let dyn_count = self.read_u32();
|
||||
(
|
||||
"MakeAttrsDyn",
|
||||
format!("static={} dyn={}", static_count, dyn_count),
|
||||
)
|
||||
}
|
||||
Op::MakeEmptyAttrs => ("MakeEmptyAttrs", String::new()),
|
||||
|
||||
Op::Select => {
|
||||
let path_len = self.read_u16();
|
||||
let span_id = self.read_u32();
|
||||
("Select", format!("path_len={} span={}", path_len, span_id))
|
||||
}
|
||||
Op::SelectDefault => {
|
||||
let path_len = self.read_u16();
|
||||
let span_id = self.read_u32();
|
||||
(
|
||||
"SelectDefault",
|
||||
format!("path_len={} span={}", path_len, span_id),
|
||||
)
|
||||
}
|
||||
Op::HasAttr => {
|
||||
let path_len = self.read_u16();
|
||||
("HasAttr", format!("path_len={}", path_len))
|
||||
}
|
||||
|
||||
Op::MakeList => {
|
||||
let count = self.read_u32();
|
||||
("MakeList", format!("size={}", count))
|
||||
}
|
||||
|
||||
Op::OpAdd => ("OpAdd", String::new()),
|
||||
Op::OpSub => ("OpSub", String::new()),
|
||||
Op::OpMul => ("OpMul", String::new()),
|
||||
Op::OpDiv => ("OpDiv", String::new()),
|
||||
Op::OpEq => ("OpEq", String::new()),
|
||||
Op::OpNeq => ("OpNeq", String::new()),
|
||||
Op::OpLt => ("OpLt", String::new()),
|
||||
Op::OpGt => ("OpGt", String::new()),
|
||||
Op::OpLeq => ("OpLeq", String::new()),
|
||||
Op::OpGeq => ("OpGeq", String::new()),
|
||||
Op::OpConcat => ("OpConcat", String::new()),
|
||||
Op::OpUpdate => ("OpUpdate", String::new()),
|
||||
Op::OpNeg => ("OpNeg", String::new()),
|
||||
Op::OpNot => ("OpNot", String::new()),
|
||||
|
||||
Op::ForceBool => ("ForceBool", String::new()),
|
||||
|
||||
Op::JumpIfFalse => {
|
||||
let offset = self.read_i32();
|
||||
let target = (current_pc as isize + 1 + 4 + offset as isize) as usize;
|
||||
(
|
||||
"JumpIfFalse",
|
||||
format!("-> {:04x} offset={}", target, offset),
|
||||
)
|
||||
}
|
||||
Op::JumpIfTrue => {
|
||||
let offset = self.read_i32();
|
||||
let target = (current_pc as isize + 1 + 4 + offset as isize) as usize;
|
||||
("JumpIfTrue", format!("-> {:04x} offset={}", target, offset))
|
||||
}
|
||||
Op::Jump => {
|
||||
let offset = self.read_i32();
|
||||
let target = (current_pc as isize + 1 + 4 + offset as isize) as usize;
|
||||
("Jump", format!("-> {:04x} offset={}", target, offset))
|
||||
}
|
||||
|
||||
Op::ConcatStrings => {
|
||||
let count = self.read_u16();
|
||||
let force = self.read_u8();
|
||||
("ConcatStrings", format!("count={} force={}", count, force))
|
||||
}
|
||||
Op::ResolvePath => ("ResolvePath", String::new()),
|
||||
Op::Assert => {
|
||||
let raw_idx = self.read_u32();
|
||||
let span_id = self.read_u32();
|
||||
("Assert", format!("text_id={} span={}", raw_idx, span_id))
|
||||
}
|
||||
Op::PushWith => ("PushWith", String::new()),
|
||||
Op::PopWith => ("PopWith", String::new()),
|
||||
Op::WithLookup => {
|
||||
let idx = self.read_u32();
|
||||
let name = self.ctx.lookup_string(idx);
|
||||
("WithLookup", format!("{:?}", name))
|
||||
}
|
||||
|
||||
Op::LoadBuiltins => ("LoadBuiltins", String::new()),
|
||||
Op::LoadBuiltin => {
|
||||
let idx = self.read_u32();
|
||||
let name = self.ctx.lookup_string(idx);
|
||||
("LoadBuiltin", format!("{:?}", name))
|
||||
}
|
||||
Op::MkPos => {
|
||||
let span_id = self.read_u32();
|
||||
("MkPos", format!("id={}", span_id))
|
||||
}
|
||||
Op::LoadReplBinding => {
|
||||
let idx = self.read_u32();
|
||||
let name = self.ctx.lookup_string(idx);
|
||||
("LoadReplBinding", format!("{:?}", name))
|
||||
}
|
||||
Op::LoadScopedBinding => {
|
||||
let idx = self.read_u32();
|
||||
let name = self.ctx.lookup_string(idx);
|
||||
("LoadScopedBinding", format!("{:?}", name))
|
||||
}
|
||||
Op::Return => ("Return", String::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -292,43 +292,32 @@ fn parse_frames(stack: &str, ctx: &impl RuntimeContext) -> Vec<NixStackFrame> {
|
||||
let mut frames = Vec::new();
|
||||
|
||||
for line in stack.lines() {
|
||||
// Format: NIX_STACK_FRAME:source_id:start:end[:extra_data]
|
||||
// Format: NIX_STACK_FRAME:span_id:message
|
||||
let Some(rest) = line.strip_prefix("NIX_STACK_FRAME:") else {
|
||||
continue;
|
||||
};
|
||||
let parts: Vec<&str> = rest.splitn(4, ':').collect();
|
||||
let parts: Vec<&str> = rest.splitn(2, ':').collect();
|
||||
|
||||
if parts.len() < 3 {
|
||||
if parts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let src = match parts[0].parse() {
|
||||
Ok(id) => ctx.get_source(id),
|
||||
Err(_) => continue,
|
||||
};
|
||||
let start: u32 = match parts[1].parse() {
|
||||
Ok(v) => v,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let end: u32 = match parts[2].parse() {
|
||||
Ok(v) => v,
|
||||
let span_id: usize = match parts[0].parse() {
|
||||
Ok(id) => id,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let (source_id, span) = ctx.get_span(span_id);
|
||||
let src = ctx.get_source(source_id);
|
||||
|
||||
let span = rnix::TextRange::new(rnix::TextSize::from(start), rnix::TextSize::from(end));
|
||||
|
||||
let message = {
|
||||
if parts.len() == 4 {
|
||||
parts[3].to_string()
|
||||
let message = if parts.len() == 2 {
|
||||
parts[1].to_string()
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
};
|
||||
|
||||
frames.push(NixStackFrame { span, message, src });
|
||||
}
|
||||
|
||||
// Deduplicate consecutive identical frames
|
||||
frames.dedup_by(|a, b| a.span == b.span && a.message == b.message);
|
||||
|
||||
frames
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use deno_core::OpState;
|
||||
use deno_core::ToV8;
|
||||
use deno_core::op2;
|
||||
use nix_compat::nixhash::HashAlgo;
|
||||
use nix_compat::nixhash::NixHash;
|
||||
use serde::Serialize;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use crate::runtime::OpStateExt;
|
||||
@@ -22,19 +22,19 @@ pub use metadata_cache::MetadataCache;
|
||||
use crate::nar;
|
||||
use crate::runtime::NixRuntimeError;
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[derive(ToV8)]
|
||||
pub struct FetchUrlResult {
|
||||
pub store_path: String,
|
||||
pub hash: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[derive(ToV8)]
|
||||
pub struct FetchTarballResult {
|
||||
pub store_path: String,
|
||||
pub nar_hash: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[derive(ToV8)]
|
||||
pub struct FetchGitResult {
|
||||
pub out_path: String,
|
||||
pub rev: String,
|
||||
@@ -47,7 +47,6 @@ pub struct FetchGitResult {
|
||||
}
|
||||
|
||||
#[op2]
|
||||
#[serde]
|
||||
pub fn op_fetch_url<Ctx: RuntimeContext>(
|
||||
state: &mut OpState,
|
||||
#[string] url: String,
|
||||
@@ -152,7 +151,6 @@ pub fn op_fetch_url<Ctx: RuntimeContext>(
|
||||
}
|
||||
|
||||
#[op2]
|
||||
#[serde]
|
||||
pub fn op_fetch_tarball<Ctx: RuntimeContext>(
|
||||
state: &mut OpState,
|
||||
#[string] url: String,
|
||||
@@ -266,7 +264,6 @@ pub fn op_fetch_tarball<Ctx: RuntimeContext>(
|
||||
}
|
||||
|
||||
#[op2]
|
||||
#[serde]
|
||||
pub fn op_fetch_git<Ctx: RuntimeContext>(
|
||||
state: &mut OpState,
|
||||
#[string] url: String,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use reqwest::blocking::Client;
|
||||
use std::time::Duration;
|
||||
|
||||
use reqwest::blocking::Client;
|
||||
|
||||
pub struct Downloader {
|
||||
client: Client,
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum CacheError {
|
||||
|
||||
605
nix-js/src/ir.rs
605
nix-js/src/ir.rs
@@ -1,46 +1,158 @@
|
||||
use derive_more::{IsVariant, TryUnwrap, Unwrap};
|
||||
use hashbrown::HashMap;
|
||||
use std::{
|
||||
hash::{Hash, Hasher},
|
||||
ops::Deref,
|
||||
};
|
||||
|
||||
use bumpalo::{Bump, boxed::Box, collections::Vec};
|
||||
use ghost_cell::{GhostCell, GhostToken};
|
||||
use rnix::{TextRange, ast};
|
||||
use string_interner::symbol::SymbolU32;
|
||||
|
||||
use nix_js_macros::ir;
|
||||
pub type HashMap<'ir, K, V> = hashbrown::HashMap<K, V, hashbrown::DefaultHashBuilder, &'ir Bump>;
|
||||
|
||||
ir! {
|
||||
Ir,
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct IrRef<'id, 'ir>(&'ir GhostCell<'id, Ir<'ir, Self>>);
|
||||
|
||||
impl<'id, 'ir> IrRef<'id, 'ir> {
|
||||
pub fn new(ir: &'ir GhostCell<'id, Ir<'ir, Self>>) -> Self {
|
||||
Self(ir)
|
||||
}
|
||||
|
||||
pub fn alloc(bump: &'ir Bump, ir: Ir<'ir, Self>) -> Self {
|
||||
Self(bump.alloc(GhostCell::new(ir)))
|
||||
}
|
||||
|
||||
/// Freeze a mutable IR reference into a read-only one, consuming the
|
||||
/// `GhostToken` to prevent any further mutation.
|
||||
///
|
||||
/// # Safety
|
||||
/// The transmute is sound because:
|
||||
/// - `GhostCell<'id, T>` is `#[repr(transparent)]` over `T`
|
||||
/// - `IrRef<'id, 'ir>` is `#[repr(transparent)]` over
|
||||
/// `&'ir GhostCell<'id, Ir<'ir, Self>>`
|
||||
/// - `RawIrRef<'ir>` is `#[repr(transparent)]` over `&'ir Ir<'ir, Self>`
|
||||
/// - `Ir<'ir, Ref>` is `#[repr(C)]` and both ref types are pointer-sized
|
||||
///
|
||||
/// Consuming the `GhostToken` guarantees no `borrow_mut` calls can occur
|
||||
/// afterwards, so the shared `&Ir` references from `RawIrRef::Deref` can
|
||||
/// never alias with mutable references.
|
||||
pub fn freeze(self, _token: GhostToken<'id>) -> RawIrRef<'ir> {
|
||||
unsafe { std::mem::transmute(self) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'id, 'ir> Deref for IrRef<'id, 'ir> {
|
||||
type Target = GhostCell<'id, Ir<'ir, IrRef<'id, 'ir>>>;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RawIrRef<'ir>(&'ir Ir<'ir, Self>);
|
||||
|
||||
impl<'ir> Deref for RawIrRef<'ir> {
|
||||
type Target = Ir<'ir, RawIrRef<'ir>>;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub enum Ir<'ir, Ref> {
|
||||
Int(i64),
|
||||
Float(f64),
|
||||
Bool(bool),
|
||||
Null,
|
||||
Str { pub val: String },
|
||||
AttrSet { pub stcs: HashMap<SymId, (ExprId, rnix::TextRange)>, pub dyns: Vec<(ExprId, ExprId, rnix::TextRange)> },
|
||||
List { pub items: Vec<ExprId> },
|
||||
Str(Box<'ir, String>),
|
||||
AttrSet {
|
||||
stcs: HashMap<'ir, SymId, (Ref, TextRange)>,
|
||||
dyns: Vec<'ir, (Ref, Ref, TextRange)>,
|
||||
},
|
||||
List {
|
||||
items: Vec<'ir, Ref>,
|
||||
},
|
||||
Path(Ref),
|
||||
ConcatStrings {
|
||||
parts: Vec<'ir, Ref>,
|
||||
force_string: bool,
|
||||
},
|
||||
|
||||
HasAttr { pub lhs: ExprId, pub rhs: Vec<Attr> },
|
||||
BinOp { pub lhs: ExprId, pub rhs: ExprId, pub kind: BinOpKind },
|
||||
UnOp { pub rhs: ExprId, pub kind: UnOpKind },
|
||||
Select { pub expr: ExprId, pub attrpath: Vec<Attr>, pub default: Option<ExprId> },
|
||||
If { pub cond: ExprId, pub consq: ExprId, pub alter: ExprId },
|
||||
Call { pub func: ExprId, pub arg: ExprId },
|
||||
Assert { pub assertion: ExprId, pub expr: ExprId, pub assertion_raw: String },
|
||||
ConcatStrings { pub parts: Vec<ExprId>, pub force_string: bool },
|
||||
Path { pub expr: ExprId },
|
||||
Func { pub body: ExprId, pub param: Option<Param>, pub arg: ExprId, pub thunks: Vec<(ExprId, ExprId)> },
|
||||
TopLevel { pub body: ExprId, pub thunks: Vec<(ExprId, ExprId)> },
|
||||
// OPs
|
||||
UnOp {
|
||||
rhs: Ref,
|
||||
kind: UnOpKind,
|
||||
},
|
||||
BinOp {
|
||||
lhs: Ref,
|
||||
rhs: Ref,
|
||||
kind: BinOpKind,
|
||||
},
|
||||
HasAttr {
|
||||
lhs: Ref,
|
||||
rhs: Vec<'ir, Attr<Ref>>,
|
||||
},
|
||||
Select {
|
||||
expr: Ref,
|
||||
attrpath: Vec<'ir, Attr<Ref>>,
|
||||
default: Option<Ref>,
|
||||
span: TextRange,
|
||||
},
|
||||
|
||||
// Conditionals
|
||||
If {
|
||||
cond: Ref,
|
||||
consq: Ref,
|
||||
alter: Ref,
|
||||
},
|
||||
Assert {
|
||||
assertion: Ref,
|
||||
expr: Ref,
|
||||
assertion_raw: String,
|
||||
span: TextRange,
|
||||
},
|
||||
|
||||
With {
|
||||
namespace: Ref,
|
||||
body: Ref,
|
||||
thunks: Vec<'ir, (ThunkId, Ref)>,
|
||||
},
|
||||
WithLookup(SymId),
|
||||
|
||||
// Function related
|
||||
Func {
|
||||
body: Ref,
|
||||
param: Option<Param<'ir>>,
|
||||
arg: ArgId,
|
||||
thunks: Vec<'ir, (ThunkId, Ref)>,
|
||||
},
|
||||
Arg(ArgId),
|
||||
Thunk(ExprId),
|
||||
Call {
|
||||
func: Ref,
|
||||
arg: Ref,
|
||||
span: TextRange,
|
||||
},
|
||||
|
||||
// Builtins
|
||||
Builtins,
|
||||
Builtin(SymId),
|
||||
CurPos,
|
||||
|
||||
// Misc
|
||||
TopLevel {
|
||||
body: Ref,
|
||||
thunks: Vec<'ir, (ThunkId, Ref)>,
|
||||
},
|
||||
Thunk(ThunkId),
|
||||
CurPos(TextRange),
|
||||
ReplBinding(SymId),
|
||||
ScopedImportBinding(SymId),
|
||||
WithExpr { pub namespace: ExprId, pub body: ExprId, pub thunks: Vec<(ExprId, ExprId)> },
|
||||
WithLookup(SymId),
|
||||
}
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct ExprId(pub usize);
|
||||
pub struct ThunkId(pub usize);
|
||||
|
||||
pub type SymId = SymbolU32;
|
||||
|
||||
@@ -50,18 +162,18 @@ pub struct ArgId(pub usize);
|
||||
|
||||
/// Represents a key in an attribute path.
|
||||
#[allow(unused)]
|
||||
#[derive(Debug, TryUnwrap)]
|
||||
pub enum Attr {
|
||||
#[derive(Debug)]
|
||||
pub enum Attr<Ref> {
|
||||
/// A dynamic attribute key, which is an expression that must evaluate to a string.
|
||||
/// Example: `attrs.${key}`
|
||||
Dynamic(ExprId, TextRange),
|
||||
Dynamic(Ref, TextRange),
|
||||
/// A static attribute key.
|
||||
/// Example: `attrs.key`
|
||||
Str(SymId, TextRange),
|
||||
}
|
||||
|
||||
/// The kinds of binary operations supported in Nix.
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
|
||||
pub enum BinOpKind {
|
||||
// Arithmetic
|
||||
Add,
|
||||
@@ -118,7 +230,7 @@ impl From<ast::BinOpKind> for BinOpKind {
|
||||
}
|
||||
|
||||
/// The kinds of unary operations.
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
|
||||
pub enum UnOpKind {
|
||||
Neg, // Negation (`-`)
|
||||
Not, // Logical not (`!`)
|
||||
@@ -135,8 +247,437 @@ impl From<ast::UnaryOpKind> for UnOpKind {
|
||||
|
||||
/// Describes the parameters of a function.
|
||||
#[derive(Debug)]
|
||||
pub struct Param {
|
||||
pub required: Vec<(SymId, TextRange)>,
|
||||
pub optional: Vec<(SymId, TextRange)>,
|
||||
pub struct Param<'ir> {
|
||||
pub required: Vec<'ir, (SymId, TextRange)>,
|
||||
pub optional: Vec<'ir, (SymId, TextRange)>,
|
||||
pub ellipsis: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct IrKey<'id, 'ir, 'a>(pub IrRef<'id, 'ir>, pub &'a GhostToken<'id>);
|
||||
|
||||
impl std::hash::Hash for IrKey<'_, '_, '_> {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
ir_content_hash(self.0, self.1, state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for IrKey<'_, '_, '_> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
ir_content_eq(self.0, other.0, self.1)
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for IrKey<'_, '_, '_> {}
|
||||
|
||||
fn attr_content_hash<'id>(
|
||||
attr: &Attr<IrRef<'id, '_>>,
|
||||
token: &GhostToken<'id>,
|
||||
state: &mut impl Hasher,
|
||||
) {
|
||||
core::mem::discriminant(attr).hash(state);
|
||||
match attr {
|
||||
Attr::Dynamic(expr, _) => ir_content_hash(*expr, token, state),
|
||||
Attr::Str(sym, _) => sym.hash(state),
|
||||
}
|
||||
}
|
||||
|
||||
fn attr_content_eq<'id, 'ir>(
|
||||
a: &Attr<IrRef<'id, 'ir>>,
|
||||
b: &Attr<IrRef<'id, 'ir>>,
|
||||
token: &GhostToken<'id>,
|
||||
) -> bool {
|
||||
match (a, b) {
|
||||
(Attr::Dynamic(ae, _), Attr::Dynamic(be, _)) => ir_content_eq(*ae, *be, token),
|
||||
(Attr::Str(a, _), Attr::Str(b, _)) => a == b,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn param_content_hash(param: &Param<'_>, state: &mut impl Hasher) {
|
||||
param.required.len().hash(state);
|
||||
for (sym, _) in param.required.iter() {
|
||||
sym.hash(state);
|
||||
}
|
||||
param.optional.len().hash(state);
|
||||
for (sym, _) in param.optional.iter() {
|
||||
sym.hash(state);
|
||||
}
|
||||
param.ellipsis.hash(state);
|
||||
}
|
||||
|
||||
fn param_content_eq(a: &Param<'_>, b: &Param<'_>) -> bool {
|
||||
a.ellipsis == b.ellipsis
|
||||
&& a.required.len() == b.required.len()
|
||||
&& a.optional.len() == b.optional.len()
|
||||
&& a.required
|
||||
.iter()
|
||||
.zip(b.required.iter())
|
||||
.all(|((a, _), (b, _))| a == b)
|
||||
&& a.optional
|
||||
.iter()
|
||||
.zip(b.optional.iter())
|
||||
.all(|((a, _), (b, _))| a == b)
|
||||
}
|
||||
|
||||
fn thunks_content_hash<'id>(
|
||||
thunks: &[(ThunkId, IrRef<'id, '_>)],
|
||||
token: &GhostToken<'id>,
|
||||
state: &mut impl Hasher,
|
||||
) {
|
||||
thunks.len().hash(state);
|
||||
for &(id, ir) in thunks {
|
||||
id.hash(state);
|
||||
ir_content_hash(ir, token, state);
|
||||
}
|
||||
}
|
||||
|
||||
fn thunks_content_eq<'id, 'ir>(
|
||||
a: &[(ThunkId, IrRef<'id, 'ir>)],
|
||||
b: &[(ThunkId, IrRef<'id, 'ir>)],
|
||||
token: &GhostToken<'id>,
|
||||
) -> bool {
|
||||
a.len() == b.len()
|
||||
&& a.iter()
|
||||
.zip(b.iter())
|
||||
.all(|(&(ai, ae), &(bi, be))| ai == bi && ir_content_eq(ae, be, token))
|
||||
}
|
||||
|
||||
fn ir_content_hash<'id>(ir: IrRef<'id, '_>, token: &GhostToken<'id>, state: &mut impl Hasher) {
|
||||
let ir = ir.borrow(token);
|
||||
core::mem::discriminant(ir).hash(state);
|
||||
match ir {
|
||||
Ir::Int(x) => x.hash(state),
|
||||
Ir::Float(x) => x.to_bits().hash(state),
|
||||
Ir::Bool(x) => x.hash(state),
|
||||
Ir::Null => {}
|
||||
Ir::Str(x) => x.hash(state),
|
||||
Ir::AttrSet { stcs, dyns } => {
|
||||
stcs.len().hash(state);
|
||||
let mut combined: u64 = 0;
|
||||
for (&key, &(val, _)) in stcs.iter() {
|
||||
let mut h = std::hash::DefaultHasher::new();
|
||||
key.hash(&mut h);
|
||||
ir_content_hash(val, token, &mut h);
|
||||
combined = combined.wrapping_add(h.finish());
|
||||
}
|
||||
combined.hash(state);
|
||||
dyns.len().hash(state);
|
||||
for &(k, v, _) in dyns.iter() {
|
||||
ir_content_hash(k, token, state);
|
||||
ir_content_hash(v, token, state);
|
||||
}
|
||||
}
|
||||
Ir::List { items } => {
|
||||
items.len().hash(state);
|
||||
for &item in items.iter() {
|
||||
ir_content_hash(item, token, state);
|
||||
}
|
||||
}
|
||||
Ir::HasAttr { lhs, rhs } => {
|
||||
ir_content_hash(*lhs, token, state);
|
||||
rhs.len().hash(state);
|
||||
for attr in rhs.iter() {
|
||||
attr_content_hash(attr, token, state);
|
||||
}
|
||||
}
|
||||
&Ir::BinOp { lhs, rhs, kind } => {
|
||||
ir_content_hash(lhs, token, state);
|
||||
ir_content_hash(rhs, token, state);
|
||||
kind.hash(state);
|
||||
}
|
||||
&Ir::UnOp { rhs, kind } => {
|
||||
ir_content_hash(rhs, token, state);
|
||||
kind.hash(state);
|
||||
}
|
||||
Ir::Select {
|
||||
expr,
|
||||
attrpath,
|
||||
default,
|
||||
..
|
||||
} => {
|
||||
ir_content_hash(*expr, token, state);
|
||||
attrpath.len().hash(state);
|
||||
for attr in attrpath.iter() {
|
||||
attr_content_hash(attr, token, state);
|
||||
}
|
||||
default.is_some().hash(state);
|
||||
if let Some(d) = default {
|
||||
ir_content_hash(*d, token, state);
|
||||
}
|
||||
}
|
||||
&Ir::If { cond, consq, alter } => {
|
||||
ir_content_hash(cond, token, state);
|
||||
ir_content_hash(consq, token, state);
|
||||
ir_content_hash(alter, token, state);
|
||||
}
|
||||
&Ir::Call { func, arg, .. } => {
|
||||
ir_content_hash(func, token, state);
|
||||
ir_content_hash(arg, token, state);
|
||||
}
|
||||
Ir::Assert {
|
||||
assertion,
|
||||
expr,
|
||||
assertion_raw,
|
||||
..
|
||||
} => {
|
||||
ir_content_hash(*assertion, token, state);
|
||||
ir_content_hash(*expr, token, state);
|
||||
assertion_raw.hash(state);
|
||||
}
|
||||
Ir::ConcatStrings {
|
||||
force_string,
|
||||
parts,
|
||||
} => {
|
||||
force_string.hash(state);
|
||||
parts.len().hash(state);
|
||||
for &part in parts.iter() {
|
||||
ir_content_hash(part, token, state);
|
||||
}
|
||||
}
|
||||
&Ir::Path(expr) => ir_content_hash(expr, token, state),
|
||||
Ir::Func {
|
||||
body,
|
||||
arg,
|
||||
param,
|
||||
thunks,
|
||||
} => {
|
||||
ir_content_hash(*body, token, state);
|
||||
arg.hash(state);
|
||||
param.is_some().hash(state);
|
||||
if let Some(p) = param {
|
||||
param_content_hash(p, state);
|
||||
}
|
||||
thunks_content_hash(thunks, token, state);
|
||||
}
|
||||
Ir::TopLevel { body, thunks } => {
|
||||
ir_content_hash(*body, token, state);
|
||||
thunks_content_hash(thunks, token, state);
|
||||
}
|
||||
Ir::Arg(x) => x.hash(state),
|
||||
Ir::Thunk(x) => x.hash(state),
|
||||
Ir::Builtins => {}
|
||||
Ir::Builtin(x) => x.hash(state),
|
||||
Ir::CurPos(x) => x.hash(state),
|
||||
Ir::ReplBinding(x) => x.hash(state),
|
||||
Ir::ScopedImportBinding(x) => x.hash(state),
|
||||
&Ir::With {
|
||||
namespace,
|
||||
body,
|
||||
ref thunks,
|
||||
} => {
|
||||
ir_content_hash(namespace, token, state);
|
||||
ir_content_hash(body, token, state);
|
||||
thunks_content_hash(thunks, token, state);
|
||||
}
|
||||
Ir::WithLookup(x) => x.hash(state),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn ir_content_eq<'id, 'ir>(
|
||||
a: IrRef<'id, 'ir>,
|
||||
b: IrRef<'id, 'ir>,
|
||||
token: &GhostToken<'id>,
|
||||
) -> bool {
|
||||
std::ptr::eq(a.0, b.0)
|
||||
|| match (a.borrow(token), b.borrow(token)) {
|
||||
(Ir::Int(a), Ir::Int(b)) => a == b,
|
||||
(Ir::Float(a), Ir::Float(b)) => a.to_bits() == b.to_bits(),
|
||||
(Ir::Bool(a), Ir::Bool(b)) => a == b,
|
||||
(Ir::Null, Ir::Null) => true,
|
||||
(Ir::Str(a), Ir::Str(b)) => **a == **b,
|
||||
(
|
||||
Ir::AttrSet {
|
||||
stcs: a_stcs,
|
||||
dyns: a_dyns,
|
||||
},
|
||||
Ir::AttrSet {
|
||||
stcs: b_stcs,
|
||||
dyns: b_dyns,
|
||||
},
|
||||
) => {
|
||||
a_stcs.len() == b_stcs.len()
|
||||
&& a_dyns.len() == b_dyns.len()
|
||||
&& a_stcs.iter().all(|(&k, &(av, _))| {
|
||||
b_stcs
|
||||
.get(&k)
|
||||
.is_some_and(|&(bv, _)| ir_content_eq(av, bv, token))
|
||||
})
|
||||
&& a_dyns
|
||||
.iter()
|
||||
.zip(b_dyns.iter())
|
||||
.all(|(&(ak, av, _), &(bk, bv, _))| {
|
||||
ir_content_eq(ak, bk, token) && ir_content_eq(av, bv, token)
|
||||
})
|
||||
}
|
||||
(Ir::List { items: a }, Ir::List { items: b }) => {
|
||||
a.len() == b.len()
|
||||
&& a.iter()
|
||||
.zip(b.iter())
|
||||
.all(|(&a, &b)| ir_content_eq(a, b, token))
|
||||
}
|
||||
(Ir::HasAttr { lhs: al, rhs: ar }, Ir::HasAttr { lhs: bl, rhs: br }) => {
|
||||
ir_content_eq(*al, *bl, token)
|
||||
&& ar.len() == br.len()
|
||||
&& ar
|
||||
.iter()
|
||||
.zip(br.iter())
|
||||
.all(|(a, b)| attr_content_eq(a, b, token))
|
||||
}
|
||||
(
|
||||
&Ir::BinOp {
|
||||
lhs: al,
|
||||
rhs: ar,
|
||||
kind: ak,
|
||||
},
|
||||
&Ir::BinOp {
|
||||
lhs: bl,
|
||||
rhs: br,
|
||||
kind: bk,
|
||||
},
|
||||
) => ak == bk && ir_content_eq(al, bl, token) && ir_content_eq(ar, br, token),
|
||||
(&Ir::UnOp { rhs: ar, kind: ak }, &Ir::UnOp { rhs: br, kind: bk }) => {
|
||||
ak == bk && ir_content_eq(ar, br, token)
|
||||
}
|
||||
(
|
||||
Ir::Select {
|
||||
expr: ae,
|
||||
attrpath: aa,
|
||||
default: ad,
|
||||
..
|
||||
},
|
||||
Ir::Select {
|
||||
expr: be,
|
||||
attrpath: ba,
|
||||
default: bd,
|
||||
..
|
||||
},
|
||||
) => {
|
||||
ir_content_eq(*ae, *be, token)
|
||||
&& aa.len() == ba.len()
|
||||
&& aa
|
||||
.iter()
|
||||
.zip(ba.iter())
|
||||
.all(|(a, b)| attr_content_eq(a, b, token))
|
||||
&& match (ad, bd) {
|
||||
(Some(a), Some(b)) => ir_content_eq(*a, *b, token),
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
(
|
||||
&Ir::If {
|
||||
cond: ac,
|
||||
consq: acs,
|
||||
alter: aa,
|
||||
},
|
||||
&Ir::If {
|
||||
cond: bc,
|
||||
consq: bcs,
|
||||
alter: ba,
|
||||
},
|
||||
) => {
|
||||
ir_content_eq(ac, bc, token)
|
||||
&& ir_content_eq(acs, bcs, token)
|
||||
&& ir_content_eq(aa, ba, token)
|
||||
}
|
||||
(
|
||||
&Ir::Call {
|
||||
func: af, arg: aa, ..
|
||||
},
|
||||
&Ir::Call {
|
||||
func: bf, arg: ba, ..
|
||||
},
|
||||
) => ir_content_eq(af, bf, token) && ir_content_eq(aa, ba, token),
|
||||
(
|
||||
Ir::Assert {
|
||||
assertion: aa,
|
||||
expr: ae,
|
||||
assertion_raw: ar,
|
||||
..
|
||||
},
|
||||
Ir::Assert {
|
||||
assertion: ba,
|
||||
expr: be,
|
||||
assertion_raw: br,
|
||||
..
|
||||
},
|
||||
) => ar == br && ir_content_eq(*aa, *ba, token) && ir_content_eq(*ae, *be, token),
|
||||
(
|
||||
Ir::ConcatStrings {
|
||||
force_string: af,
|
||||
parts: ap,
|
||||
},
|
||||
Ir::ConcatStrings {
|
||||
force_string: bf,
|
||||
parts: bp,
|
||||
},
|
||||
) => {
|
||||
af == bf
|
||||
&& ap.len() == bp.len()
|
||||
&& ap
|
||||
.iter()
|
||||
.zip(bp.iter())
|
||||
.all(|(&a, &b)| ir_content_eq(a, b, token))
|
||||
}
|
||||
(&Ir::Path(a), &Ir::Path(b)) => ir_content_eq(a, b, token),
|
||||
(
|
||||
Ir::Func {
|
||||
body: ab,
|
||||
arg: aa,
|
||||
param: ap,
|
||||
thunks: at,
|
||||
},
|
||||
Ir::Func {
|
||||
body: bb,
|
||||
arg: ba,
|
||||
param: bp,
|
||||
thunks: bt,
|
||||
},
|
||||
) => {
|
||||
ir_content_eq(*ab, *bb, token)
|
||||
&& aa == ba
|
||||
&& match (ap, bp) {
|
||||
(Some(a), Some(b)) => param_content_eq(a, b),
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
}
|
||||
&& thunks_content_eq(at, bt, token)
|
||||
}
|
||||
(
|
||||
Ir::TopLevel {
|
||||
body: ab,
|
||||
thunks: at,
|
||||
},
|
||||
Ir::TopLevel {
|
||||
body: bb,
|
||||
thunks: bt,
|
||||
},
|
||||
) => ir_content_eq(*ab, *bb, token) && thunks_content_eq(at, bt, token),
|
||||
(Ir::Arg(a), Ir::Arg(b)) => a == b,
|
||||
(Ir::Thunk(a), Ir::Thunk(b)) => a == b,
|
||||
(Ir::Builtins, Ir::Builtins) => true,
|
||||
(Ir::Builtin(a), Ir::Builtin(b)) => a == b,
|
||||
(Ir::CurPos(a), Ir::CurPos(b)) => a == b,
|
||||
(Ir::ReplBinding(a), Ir::ReplBinding(b)) => a == b,
|
||||
(Ir::ScopedImportBinding(a), Ir::ScopedImportBinding(b)) => a == b,
|
||||
(
|
||||
Ir::With {
|
||||
namespace: a_ns,
|
||||
body: a_body,
|
||||
thunks: a_thunks,
|
||||
},
|
||||
Ir::With {
|
||||
namespace: b_ns,
|
||||
body: b_body,
|
||||
thunks: b_thunks,
|
||||
},
|
||||
) => {
|
||||
ir_content_eq(*a_ns, *b_ns, token)
|
||||
&& ir_content_eq(*a_body, *b_body, token)
|
||||
&& thunks_content_eq(a_thunks, b_thunks, token)
|
||||
}
|
||||
(Ir::WithLookup(a), Ir::WithLookup(b)) => a == b,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,8 +5,10 @@ pub mod error;
|
||||
pub mod logging;
|
||||
pub mod value;
|
||||
|
||||
mod bytecode;
|
||||
mod codegen;
|
||||
mod derivation;
|
||||
mod disassembler;
|
||||
mod downgrade;
|
||||
mod fetcher;
|
||||
mod ir;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::env;
|
||||
use std::io::IsTerminal;
|
||||
|
||||
use tracing_subscriber::{EnvFilter, Layer, fmt, layer::SubscriberExt, util::SubscriberInitExt};
|
||||
|
||||
pub fn init_logging() {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use std::path::PathBuf;
|
||||
use std::process::exit;
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::{Parser, Subcommand};
|
||||
use clap::{Args, Parser, Subcommand};
|
||||
use hashbrown::HashSet;
|
||||
use nix_js::context::Context;
|
||||
use nix_js::error::Source;
|
||||
@@ -25,10 +26,28 @@ struct Cli {
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
Eval { expr: String },
|
||||
Compile {
|
||||
#[clap(flatten)]
|
||||
source: ExprSource,
|
||||
#[arg(long)]
|
||||
silent: bool,
|
||||
},
|
||||
Eval {
|
||||
#[clap(flatten)]
|
||||
source: ExprSource,
|
||||
},
|
||||
Repl,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
#[group(required = true, multiple = false)]
|
||||
struct ExprSource {
|
||||
#[clap(short, long)]
|
||||
expr: Option<String>,
|
||||
#[clap(short, long)]
|
||||
file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
fn create_context(#[cfg(feature = "inspector")] cli: &Cli) -> Result<Context> {
|
||||
#[cfg(feature = "inspector")]
|
||||
{
|
||||
@@ -50,11 +69,41 @@ fn create_context(#[cfg(feature = "inspector")] cli: &Cli) -> Result<Context> {
|
||||
Ok(Context::new()?)
|
||||
}
|
||||
|
||||
fn run_eval(context: &mut Context, expr: String) -> Result<()> {
|
||||
let src = Source::new_eval(expr)?;
|
||||
match context.eval(src) {
|
||||
fn run_compile(context: &mut Context, src: ExprSource, silent: bool) -> Result<()> {
|
||||
let src = if let Some(expr) = src.expr {
|
||||
Source::new_eval(expr)?
|
||||
} else if let Some(file) = src.file {
|
||||
Source::new_file(file)?
|
||||
} else {
|
||||
unreachable!()
|
||||
};
|
||||
match context.compile_bytecode(src) {
|
||||
Ok(compiled) => {
|
||||
if !silent {
|
||||
println!("{}", context.disassemble_colored(&compiled));
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("{:?}", miette::Report::new(*err));
|
||||
exit(1);
|
||||
}
|
||||
};
|
||||
#[cfg(feature = "inspector")]
|
||||
context.wait_for_inspector_disconnect();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_eval(context: &mut Context, src: ExprSource) -> Result<()> {
|
||||
let src = if let Some(expr) = src.expr {
|
||||
Source::new_eval(expr)?
|
||||
} else if let Some(file) = src.file {
|
||||
Source::new_file(file)?
|
||||
} else {
|
||||
unreachable!()
|
||||
};
|
||||
match context.eval_deep(src) {
|
||||
Ok(value) => {
|
||||
println!("{value}");
|
||||
println!("{}", value.display_compat());
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("{:?}", miette::Report::new(*err));
|
||||
@@ -131,7 +180,8 @@ fn main() -> Result<()> {
|
||||
)?;
|
||||
|
||||
match cli.command {
|
||||
Command::Eval { expr } => run_eval(&mut context, expr),
|
||||
Command::Compile { source, silent } => run_compile(&mut context, source, silent),
|
||||
Command::Eval { source } => run_eval(&mut context, source),
|
||||
Command::Repl => run_repl(&mut context),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
use nix_nar::Encoder;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
|
||||
use nix_nar::Encoder;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
pub fn compute_nar_hash(path: &Path) -> Result<[u8; 32]> {
|
||||
@@ -27,11 +28,13 @@ pub fn pack_nar(path: &Path) -> Result<Vec<u8>> {
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
use super::*;
|
||||
|
||||
#[test_log::test]
|
||||
fn test_simple_file() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let file_path = temp.path().join("test.txt");
|
||||
@@ -46,7 +49,7 @@ mod tests {
|
||||
assert_eq!(hash.len(), 64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn test_directory() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
fs::write(temp.path().join("a.txt"), "aaa").unwrap();
|
||||
|
||||
@@ -6,6 +6,7 @@ use std::path::Path;
|
||||
use deno_core::PollEventLoopOptions;
|
||||
use deno_core::{Extension, ExtensionFileSource, JsRuntime, OpState, RuntimeOptions, v8};
|
||||
|
||||
use crate::bytecode::{Bytecode, Constant};
|
||||
use crate::error::{Error, Result, Source};
|
||||
use crate::store::DaemonStore;
|
||||
use crate::value::{AttrSet, List, Symbol, Value};
|
||||
@@ -24,8 +25,12 @@ pub(crate) trait RuntimeContext: 'static {
|
||||
fn add_source(&mut self, path: Source);
|
||||
fn compile(&mut self, source: Source) -> Result<String>;
|
||||
fn compile_scoped(&mut self, source: Source, scope: Vec<String>) -> Result<String>;
|
||||
fn compile_bytecode(&mut self, source: Source) -> Result<Bytecode>;
|
||||
fn compile_bytecode_scoped(&mut self, source: Source, scope: Vec<String>) -> Result<Bytecode>;
|
||||
fn get_source(&self, id: usize) -> Source;
|
||||
fn get_store(&self) -> &DaemonStore;
|
||||
fn get_span(&self, id: usize) -> (usize, rnix::TextRange);
|
||||
fn get_unsynced(&mut self) -> (&[String], &[Constant], usize, usize);
|
||||
}
|
||||
|
||||
pub(crate) trait OpStateExt<Ctx: RuntimeContext> {
|
||||
@@ -90,7 +95,7 @@ fn runtime_extension<Ctx: RuntimeContext>() -> Extension {
|
||||
mod private {
|
||||
use deno_error::js_error_wrapper;
|
||||
#[derive(Debug)]
|
||||
pub struct SimpleErrorWrapper(pub(crate) String);
|
||||
pub struct SimpleErrorWrapper(String);
|
||||
impl std::fmt::Display for SimpleErrorWrapper {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
std::fmt::Display::fmt(&self.0, f)
|
||||
@@ -115,14 +120,12 @@ pub(crate) use private::NixRuntimeError;
|
||||
|
||||
pub(crate) struct Runtime<Ctx: RuntimeContext> {
|
||||
js_runtime: JsRuntime,
|
||||
#[cfg(feature = "inspector")]
|
||||
rt: tokio::runtime::Runtime,
|
||||
#[cfg(feature = "inspector")]
|
||||
wait_for_inspector: bool,
|
||||
is_thunk_symbol: v8::Global<v8::Symbol>,
|
||||
primop_metadata_symbol: v8::Global<v8::Symbol>,
|
||||
has_context_symbol: v8::Global<v8::Symbol>,
|
||||
is_path_symbol: v8::Global<v8::Symbol>,
|
||||
is_cycle_symbol: v8::Global<v8::Symbol>,
|
||||
symbols: GlobalSymbols,
|
||||
cached_fns: CachedFunctions,
|
||||
_marker: PhantomData<Ctx>,
|
||||
}
|
||||
|
||||
@@ -142,7 +145,12 @@ impl<Ctx: RuntimeContext> Runtime<Ctx> {
|
||||
static INIT: Once = Once::new();
|
||||
INIT.call_once(|| {
|
||||
assert_eq!(
|
||||
deno_core::v8_set_flags(vec!["".into(), format!("--stack-size={}", 8 * 1024)]),
|
||||
deno_core::v8_set_flags(vec![
|
||||
"".into(),
|
||||
format!("--stack-size={}", 8 * 1024),
|
||||
#[cfg(feature = "prof")]
|
||||
("--prof".into())
|
||||
]),
|
||||
[""]
|
||||
);
|
||||
JsRuntime::init_platform(Some(v8::new_default_platform(0, false).make_shared()));
|
||||
@@ -159,30 +167,24 @@ impl<Ctx: RuntimeContext> Runtime<Ctx> {
|
||||
js_runtime.op_state().borrow_mut().put(RegexCache::new());
|
||||
js_runtime.op_state().borrow_mut().put(DrvHashCache::new());
|
||||
|
||||
let (
|
||||
is_thunk_symbol,
|
||||
primop_metadata_symbol,
|
||||
has_context_symbol,
|
||||
is_path_symbol,
|
||||
is_cycle_symbol,
|
||||
) = {
|
||||
let (symbols, cached_fns) = {
|
||||
deno_core::scope!(scope, &mut js_runtime);
|
||||
Self::get_symbols(scope)?
|
||||
let symbols = Self::get_symbols(scope)?;
|
||||
let cached_fns = Self::get_cached_functions(scope)?;
|
||||
(symbols, cached_fns)
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
js_runtime,
|
||||
#[cfg(feature = "inspector")]
|
||||
rt: tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("failed to build tokio runtime"),
|
||||
#[cfg(feature = "inspector")]
|
||||
wait_for_inspector: inspector_options.wait,
|
||||
is_thunk_symbol,
|
||||
primop_metadata_symbol,
|
||||
has_context_symbol,
|
||||
is_path_symbol,
|
||||
is_cycle_symbol,
|
||||
symbols,
|
||||
cached_fns,
|
||||
_marker: PhantomData,
|
||||
})
|
||||
}
|
||||
@@ -224,54 +226,97 @@ impl<Ctx: RuntimeContext> Runtime<Ctx> {
|
||||
|
||||
crate::error::parse_js_error(error, ctx)
|
||||
})?;
|
||||
let global_value = self
|
||||
.rt
|
||||
.block_on(self.js_runtime.resolve(global_value))
|
||||
.map_err(|error| {
|
||||
let op_state = self.js_runtime.op_state();
|
||||
let op_state_borrow = op_state.borrow();
|
||||
let ctx: &Ctx = op_state_borrow.get_ctx();
|
||||
|
||||
crate::error::parse_js_error(error, ctx)
|
||||
})?;
|
||||
#[cfg(feature = "inspector")]
|
||||
{
|
||||
let _ = self
|
||||
.rt
|
||||
.block_on(self.js_runtime.run_event_loop(Default::default()));
|
||||
}
|
||||
|
||||
// Retrieve scope from JsRuntime
|
||||
deno_core::scope!(scope, self.js_runtime);
|
||||
let local_value = v8::Local::new(scope, &global_value);
|
||||
let is_thunk_symbol = v8::Local::new(scope, &self.is_thunk_symbol);
|
||||
let primop_metadata_symbol = v8::Local::new(scope, &self.primop_metadata_symbol);
|
||||
let has_context_symbol = v8::Local::new(scope, &self.has_context_symbol);
|
||||
let is_path_symbol = v8::Local::new(scope, &self.is_path_symbol);
|
||||
let is_cycle_symbol = v8::Local::new(scope, &self.is_cycle_symbol);
|
||||
let symbols = &self.symbols.local(scope);
|
||||
|
||||
Ok(to_value(
|
||||
local_value,
|
||||
scope,
|
||||
is_thunk_symbol,
|
||||
primop_metadata_symbol,
|
||||
has_context_symbol,
|
||||
is_path_symbol,
|
||||
is_cycle_symbol,
|
||||
))
|
||||
Ok(to_value(local_value, scope, symbols))
|
||||
}
|
||||
|
||||
/// get (IS_THUNK, PRIMOP_METADATA, HAS_CONTEXT, IS_PATH, IS_CYCLE)
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn get_symbols(
|
||||
scope: &ScopeRef,
|
||||
) -> Result<(
|
||||
v8::Global<v8::Symbol>,
|
||||
v8::Global<v8::Symbol>,
|
||||
v8::Global<v8::Symbol>,
|
||||
v8::Global<v8::Symbol>,
|
||||
v8::Global<v8::Symbol>,
|
||||
)> {
|
||||
pub(crate) fn eval_bytecode(
|
||||
&mut self,
|
||||
result: Bytecode,
|
||||
ctx: &mut Ctx,
|
||||
force_mode: ForceMode,
|
||||
) -> Result<Value> {
|
||||
let ctx: &'static mut Ctx = unsafe { &mut *(ctx as *mut Ctx) };
|
||||
{
|
||||
deno_core::scope!(scope, self.js_runtime);
|
||||
sync_global_tables(scope, &self.cached_fns, ctx);
|
||||
}
|
||||
let op_state = self.js_runtime.op_state();
|
||||
op_state.borrow_mut().put(ctx);
|
||||
|
||||
#[cfg(feature = "inspector")]
|
||||
if self.wait_for_inspector {
|
||||
self.js_runtime
|
||||
.inspector()
|
||||
.wait_for_session_and_break_on_next_statement();
|
||||
} else {
|
||||
self.js_runtime.inspector().wait_for_session();
|
||||
}
|
||||
|
||||
deno_core::scope!(scope, self.js_runtime);
|
||||
|
||||
let store = v8::ArrayBuffer::new_backing_store_from_boxed_slice(result.code);
|
||||
let ab = v8::ArrayBuffer::with_backing_store(scope, &store.make_shared());
|
||||
let u8a = v8::Uint8Array::new(scope, ab, 0, ab.byte_length())
|
||||
.ok_or_else(|| Error::internal("failed to create Uint8Array".into()))?;
|
||||
|
||||
let dir = v8::String::new(scope, &result.current_dir)
|
||||
.ok_or_else(|| Error::internal("failed to create dir string".into()))?;
|
||||
|
||||
let undef = v8::undefined(scope);
|
||||
let tc = std::pin::pin!(v8::TryCatch::new(scope));
|
||||
let scope = &mut tc.init();
|
||||
|
||||
let exec_bytecode = v8::Local::new(scope, &self.cached_fns.exec_bytecode);
|
||||
let raw_result = exec_bytecode
|
||||
.call(scope, undef.into(), &[u8a.into(), dir.into()])
|
||||
.ok_or_else(|| {
|
||||
scope
|
||||
.exception()
|
||||
.map(|e| {
|
||||
let op_state_borrow = op_state.borrow();
|
||||
let ctx: &Ctx = op_state_borrow.get_ctx();
|
||||
Box::new(crate::error::parse_js_error(
|
||||
deno_core::error::JsError::from_v8_exception(scope, e),
|
||||
ctx,
|
||||
))
|
||||
})
|
||||
.unwrap_or_else(|| Error::internal("bytecode execution failed".into()))
|
||||
})?;
|
||||
|
||||
let force_fn = match force_mode {
|
||||
ForceMode::Force => &self.cached_fns.force_fn,
|
||||
ForceMode::ForceShallow => &self.cached_fns.force_shallow_fn,
|
||||
ForceMode::ForceDeep => &self.cached_fns.force_deep_fn,
|
||||
};
|
||||
let force_fn = v8::Local::new(scope, force_fn);
|
||||
|
||||
let forced = force_fn
|
||||
.call(scope, undef.into(), &[raw_result])
|
||||
.ok_or_else(|| {
|
||||
scope
|
||||
.exception()
|
||||
.map(|e| {
|
||||
let op_state_borrow = op_state.borrow();
|
||||
let ctx: &Ctx = op_state_borrow.get_ctx();
|
||||
Box::new(crate::error::parse_js_error(
|
||||
deno_core::error::JsError::from_v8_exception(scope, e),
|
||||
ctx,
|
||||
))
|
||||
})
|
||||
.unwrap_or_else(|| Error::internal("force failed".into()))
|
||||
})?;
|
||||
|
||||
let symbols = &self.symbols.local(scope);
|
||||
Ok(to_value(forced, scope, symbols))
|
||||
}
|
||||
|
||||
fn get_symbols(scope: &ScopeRef) -> Result<GlobalSymbols> {
|
||||
let global = scope.get_current_context().global(scope);
|
||||
let nix_key = v8::String::new(scope, "Nix")
|
||||
.ok_or_else(|| Error::internal("failed to create V8 String".into()))?;
|
||||
@@ -303,18 +348,148 @@ impl<Ctx: RuntimeContext> Runtime<Ctx> {
|
||||
let is_path = get_symbol("IS_PATH")?;
|
||||
let is_cycle = get_symbol("IS_CYCLE")?;
|
||||
|
||||
Ok((is_thunk, primop_metadata, has_context, is_path, is_cycle))
|
||||
Ok(GlobalSymbols {
|
||||
is_thunk,
|
||||
primop_metadata,
|
||||
has_context,
|
||||
is_path,
|
||||
is_cycle,
|
||||
})
|
||||
}
|
||||
|
||||
fn get_cached_functions(scope: &ScopeRef) -> Result<CachedFunctions> {
|
||||
let global = scope.get_current_context().global(scope);
|
||||
let nix_key = v8::String::new(scope, "Nix")
|
||||
.ok_or_else(|| Error::internal("failed to create V8 String".into()))?;
|
||||
let nix_obj = global
|
||||
.get(scope, nix_key.into())
|
||||
.ok_or_else(|| Error::internal("failed to get global Nix object".into()))?
|
||||
.to_object(scope)
|
||||
.ok_or_else(|| {
|
||||
Error::internal("failed to convert global Nix Value to object".into())
|
||||
})?;
|
||||
|
||||
let get_fn = |name: &str| -> Result<v8::Global<v8::Function>> {
|
||||
let key = v8::String::new(scope, name)
|
||||
.ok_or_else(|| Error::internal("failed to create V8 String".into()))?;
|
||||
let val = nix_obj
|
||||
.get(scope, key.into())
|
||||
.ok_or_else(|| Error::internal(format!("failed to get Nix.{name}")))?;
|
||||
let func = val
|
||||
.try_cast::<v8::Function>()
|
||||
.map_err(|err| Error::internal(format!("Nix.{name} is not a function ({err})")))?;
|
||||
Ok(v8::Global::new(scope, func))
|
||||
};
|
||||
|
||||
let exec_bytecode = get_fn("execBytecode")?;
|
||||
let force_fn = get_fn("force")?;
|
||||
let force_shallow_fn = get_fn("forceShallow")?;
|
||||
let force_deep_fn = get_fn("forceDeep")?;
|
||||
|
||||
let strings_key = v8::String::new(scope, "strings")
|
||||
.ok_or_else(|| Error::internal("failed to create V8 String".into()))?;
|
||||
let strings_array = nix_obj
|
||||
.get(scope, strings_key.into())
|
||||
.ok_or_else(|| Error::internal("failed to get Nix.strings".into()))?
|
||||
.try_cast::<v8::Array>()
|
||||
.map_err(|err| Error::internal(format!("Nix.strings is not an array ({err})")))?;
|
||||
|
||||
let constants_key = v8::String::new(scope, "constants")
|
||||
.ok_or_else(|| Error::internal("failed to create V8 String".into()))?;
|
||||
let constants_array = nix_obj
|
||||
.get(scope, constants_key.into())
|
||||
.ok_or_else(|| Error::internal("failed to get Nix.constants".into()))?
|
||||
.try_cast::<v8::Array>()
|
||||
.map_err(|err| Error::internal(format!("Nix.constants is not an array ({err})")))?;
|
||||
|
||||
Ok(CachedFunctions {
|
||||
exec_bytecode,
|
||||
force_fn,
|
||||
force_shallow_fn,
|
||||
force_deep_fn,
|
||||
strings_array: v8::Global::new(scope, strings_array),
|
||||
constants_array: v8::Global::new(scope, constants_array),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct GlobalSymbols {
|
||||
is_thunk: v8::Global<v8::Symbol>,
|
||||
primop_metadata: v8::Global<v8::Symbol>,
|
||||
has_context: v8::Global<v8::Symbol>,
|
||||
is_path: v8::Global<v8::Symbol>,
|
||||
is_cycle: v8::Global<v8::Symbol>,
|
||||
}
|
||||
|
||||
impl GlobalSymbols {
|
||||
fn local<'a>(&self, scope: &ScopeRef<'a, '_>) -> LocalSymbols<'a> {
|
||||
LocalSymbols {
|
||||
is_thunk: v8::Local::new(scope, &self.is_thunk),
|
||||
primop_metadata: v8::Local::new(scope, &self.primop_metadata),
|
||||
has_context: v8::Local::new(scope, &self.has_context),
|
||||
is_path: v8::Local::new(scope, &self.is_path),
|
||||
is_cycle: v8::Local::new(scope, &self.is_cycle),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct LocalSymbols<'a> {
|
||||
is_thunk: v8::Local<'a, v8::Symbol>,
|
||||
primop_metadata: v8::Local<'a, v8::Symbol>,
|
||||
has_context: v8::Local<'a, v8::Symbol>,
|
||||
is_path: v8::Local<'a, v8::Symbol>,
|
||||
is_cycle: v8::Local<'a, v8::Symbol>,
|
||||
}
|
||||
|
||||
struct CachedFunctions {
|
||||
exec_bytecode: v8::Global<v8::Function>,
|
||||
force_fn: v8::Global<v8::Function>,
|
||||
force_shallow_fn: v8::Global<v8::Function>,
|
||||
force_deep_fn: v8::Global<v8::Function>,
|
||||
strings_array: v8::Global<v8::Array>,
|
||||
constants_array: v8::Global<v8::Array>,
|
||||
}
|
||||
|
||||
pub(crate) enum ForceMode {
|
||||
Force,
|
||||
ForceShallow,
|
||||
ForceDeep,
|
||||
}
|
||||
|
||||
fn sync_global_tables<Ctx: RuntimeContext>(
|
||||
scope: &ScopeRef,
|
||||
cached: &CachedFunctions,
|
||||
ctx: &mut Ctx,
|
||||
) {
|
||||
let (new_strings, new_constants, strings_base, constants_base) = ctx.get_unsynced();
|
||||
|
||||
if !new_strings.is_empty() {
|
||||
let s_array = v8::Local::new(scope, &cached.strings_array);
|
||||
for (i, s) in new_strings.iter().enumerate() {
|
||||
let idx = (strings_base + i) as u32;
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let val = v8::String::new(scope, s).unwrap();
|
||||
s_array.set_index(scope, idx, val.into());
|
||||
}
|
||||
}
|
||||
|
||||
if !new_constants.is_empty() {
|
||||
let k_array = v8::Local::new(scope, &cached.constants_array);
|
||||
for (i, c) in new_constants.iter().enumerate() {
|
||||
let idx = (constants_base + i) as u32;
|
||||
let val: v8::Local<v8::Value> = match c {
|
||||
Constant::Int(n) => v8::BigInt::new_from_i64(scope, *n).into(),
|
||||
Constant::Float(bits) => v8::Number::new(scope, f64::from_bits(*bits)).into(),
|
||||
};
|
||||
k_array.set_index(scope, idx, val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn to_value<'a>(
|
||||
val: LocalValue<'a>,
|
||||
scope: &ScopeRef<'a, '_>,
|
||||
is_thunk_symbol: LocalSymbol<'a>,
|
||||
primop_metadata_symbol: LocalSymbol<'a>,
|
||||
has_context_symbol: LocalSymbol<'a>,
|
||||
is_path_symbol: LocalSymbol<'a>,
|
||||
is_cycle_symbol: LocalSymbol<'a>,
|
||||
symbols: &LocalSymbols<'a>,
|
||||
) -> Value {
|
||||
match () {
|
||||
_ if val.is_big_int() => {
|
||||
@@ -344,40 +519,51 @@ fn to_value<'a>(
|
||||
let list = (0..len)
|
||||
.map(|i| {
|
||||
let val = val.get_index(scope, i).expect("infallible index operation");
|
||||
to_value(
|
||||
val,
|
||||
scope,
|
||||
is_thunk_symbol,
|
||||
primop_metadata_symbol,
|
||||
has_context_symbol,
|
||||
is_path_symbol,
|
||||
is_cycle_symbol,
|
||||
)
|
||||
to_value(val, scope, symbols)
|
||||
})
|
||||
.collect();
|
||||
Value::List(List::new(list))
|
||||
}
|
||||
_ if val.is_function() => {
|
||||
if let Some(primop) = to_primop(val, scope, primop_metadata_symbol) {
|
||||
if let Some(primop) = to_primop(val, scope, symbols.primop_metadata) {
|
||||
primop
|
||||
} else {
|
||||
Value::Func
|
||||
}
|
||||
}
|
||||
_ if val.is_map() => {
|
||||
let val = val.try_cast::<v8::Map>().expect("infallible conversion");
|
||||
let size = val.size() as u32;
|
||||
let array = val.as_array(scope);
|
||||
let attrs = (0..size)
|
||||
.map(|i| {
|
||||
let key = array
|
||||
.get_index(scope, i * 2)
|
||||
.expect("infallible index operation");
|
||||
let key = key.to_rust_string_lossy(scope);
|
||||
let val = array
|
||||
.get_index(scope, i * 2 + 1)
|
||||
.expect("infallible index operation");
|
||||
let val = to_value(val, scope, symbols);
|
||||
(Symbol::new(Cow::Owned(key)), val)
|
||||
})
|
||||
.collect();
|
||||
Value::AttrSet(AttrSet::new(attrs))
|
||||
}
|
||||
_ if val.is_object() => {
|
||||
if is_thunk(val, scope, is_thunk_symbol) {
|
||||
if is_thunk(val, scope, symbols.is_thunk) {
|
||||
return Value::Thunk;
|
||||
}
|
||||
|
||||
if is_cycle(val, scope, is_cycle_symbol) {
|
||||
if is_cycle(val, scope, symbols.is_cycle) {
|
||||
return Value::Repeated;
|
||||
}
|
||||
|
||||
if let Some(path_val) = extract_path(val, scope, is_path_symbol) {
|
||||
if let Some(path_val) = extract_path(val, scope, symbols.is_path) {
|
||||
return Value::Path(path_val);
|
||||
}
|
||||
|
||||
if let Some(string_val) = extract_string_with_context(val, scope, has_context_symbol) {
|
||||
if let Some(string_val) = extract_string_with_context(val, scope, symbols.has_context) {
|
||||
return Value::String(string_val);
|
||||
}
|
||||
|
||||
@@ -393,18 +579,7 @@ fn to_value<'a>(
|
||||
.expect("infallible index operation");
|
||||
let val = val.get(scope, key).expect("infallible operation");
|
||||
let key = key.to_rust_string_lossy(scope);
|
||||
(
|
||||
Symbol::from(key),
|
||||
to_value(
|
||||
val,
|
||||
scope,
|
||||
is_thunk_symbol,
|
||||
primop_metadata_symbol,
|
||||
has_context_symbol,
|
||||
is_path_symbol,
|
||||
is_cycle_symbol,
|
||||
),
|
||||
)
|
||||
(Symbol::from(key), to_value(val, scope, symbols))
|
||||
})
|
||||
.collect();
|
||||
Value::AttrSet(AttrSet::new(attrs))
|
||||
|
||||
@@ -2,6 +2,14 @@
|
||||
|
||||
// Alias for the future `!` type.
|
||||
use core::convert::Infallible as Never;
|
||||
use std::cell::RefCell;
|
||||
use std::net::SocketAddr;
|
||||
use std::pin::pin;
|
||||
use std::process;
|
||||
use std::rc::Rc;
|
||||
use std::task::Poll;
|
||||
use std::thread;
|
||||
|
||||
use deno_core::InspectorMsg;
|
||||
use deno_core::InspectorSessionChannels;
|
||||
use deno_core::InspectorSessionKind;
|
||||
@@ -21,16 +29,9 @@ use deno_core::url::Url;
|
||||
use fastwebsockets::Frame;
|
||||
use fastwebsockets::OpCode;
|
||||
use fastwebsockets::WebSocket;
|
||||
use hashbrown::HashMap;
|
||||
use hyper::body::Bytes;
|
||||
use hyper_util::rt::TokioIo;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::pin::pin;
|
||||
use std::process;
|
||||
use std::rc::Rc;
|
||||
use std::task::Poll;
|
||||
use std::thread;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::broadcast;
|
||||
use uuid::Uuid;
|
||||
@@ -269,7 +270,8 @@ async fn server(
|
||||
let mut accept = pin!(listener.accept());
|
||||
|
||||
let stream = tokio::select! {
|
||||
accept_result = &mut accept => {
|
||||
accept_result =
|
||||
&mut accept => {
|
||||
match accept_result {
|
||||
Ok((s, _)) => s,
|
||||
Err(err) => {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -87,11 +87,12 @@ impl Store for DaemonStore {
|
||||
recursive: bool,
|
||||
references: Vec<String>,
|
||||
) -> Result<String> {
|
||||
use std::fs;
|
||||
|
||||
use nix_compat::nix_daemon::types::AddToStoreNarRequest;
|
||||
use nix_compat::nixhash::{CAHash, NixHash};
|
||||
use nix_compat::store_path::{StorePath, build_ca_path};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::fs;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
let temp_file = NamedTempFile::new()
|
||||
@@ -237,11 +238,12 @@ impl Store for DaemonStore {
|
||||
content: &str,
|
||||
references: Vec<String>,
|
||||
) -> Result<String> {
|
||||
use std::fs;
|
||||
|
||||
use nix_compat::nix_daemon::types::AddToStoreNarRequest;
|
||||
use nix_compat::nixhash::CAHash;
|
||||
use nix_compat::store_path::{StorePath, build_text_path};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::fs;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
let temp_file = NamedTempFile::new()
|
||||
@@ -540,6 +542,7 @@ impl NixDaemonClient {
|
||||
}
|
||||
|
||||
/// Query information about a store path
|
||||
#[allow(dead_code)]
|
||||
pub async fn query_path_info(&mut self, path: &str) -> IoResult<Option<UnkeyedValidPathInfo>> {
|
||||
let store_path = StorePath::<String>::from_absolute_path(path.as_bytes())
|
||||
.map_err(|e| IoError::new(IoErrorKind::InvalidInput, e.to_string()))?;
|
||||
@@ -613,6 +616,7 @@ impl NixDaemonClient {
|
||||
}
|
||||
|
||||
/// Query which paths are valid
|
||||
#[allow(dead_code)]
|
||||
pub async fn query_valid_paths(&mut self, paths: Vec<String>) -> IoResult<Vec<String>> {
|
||||
let store_paths: IoResult<Vec<StorePath<String>>> = paths
|
||||
.iter()
|
||||
@@ -717,6 +721,7 @@ impl NixDaemonConnection {
|
||||
}
|
||||
|
||||
/// Query information about a store path
|
||||
#[allow(dead_code)]
|
||||
pub async fn query_path_info(&self, path: &str) -> IoResult<Option<UnkeyedValidPathInfo>> {
|
||||
let mut client = self.client.lock().await;
|
||||
client.query_path_info(path).await
|
||||
@@ -729,6 +734,7 @@ impl NixDaemonConnection {
|
||||
}
|
||||
|
||||
/// Query which paths are valid
|
||||
#[allow(dead_code)]
|
||||
pub async fn query_valid_paths(&self, paths: Vec<String>) -> IoResult<Vec<String>> {
|
||||
let mut client = self.client.lock().await;
|
||||
client.query_valid_paths(paths).await
|
||||
|
||||
@@ -81,7 +81,7 @@ pub fn validate_store_path(store_dir: &str, path: &str) -> Result<()> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn test_valid_store_paths() {
|
||||
let store_dir = "/nix/store";
|
||||
let valid_paths = vec![
|
||||
@@ -100,7 +100,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn test_invalid_store_paths() {
|
||||
let store_dir = "/nix/store";
|
||||
let invalid_paths = vec![
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use core::fmt::{Debug, Display, Formatter, Result as FmtResult};
|
||||
use core::hash::Hash;
|
||||
use core::ops::Deref;
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::BTreeMap;
|
||||
use std::ops::DerefMut;
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
[ { } { a = 1; } { a = 1; } { a = "a"; } { m = 1; } { m = "m"; } { n = 1; } { n = "n"; } { n = 1; p = 2; } { n = "n"; p = "p"; } { n = 1; p = 2; } { n = "n"; p = "p"; } { a = "a"; b = "b"; c = "c"; d = "d"; e = "e"; f = "f"; g = "g"; h = "h"; i = "i"; j = "j"; k = "k"; l = "l"; m = "m"; n = "n"; o = "o"; p = "p"; q = "q"; r = "r"; s = "s"; t = "t"; u = "u"; v = "v"; w = "w"; x = "x"; y = "y"; z = "z"; } true ]
|
||||
@@ -1 +0,0 @@
|
||||
[ null <PRIMOP> <PRIMOP-APP> <LAMBDA> [ [ «repeated» ] ] ]
|
||||
@@ -1,36 +1,33 @@
|
||||
mod utils;
|
||||
|
||||
use nix_js::value::Value;
|
||||
use utils::eval;
|
||||
|
||||
use crate::utils::eval_result;
|
||||
use crate::utils::{eval, eval_result};
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn arithmetic() {
|
||||
assert_eq!(eval("1 + 1"), Value::Int(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn simple_function_application() {
|
||||
assert_eq!(eval("(x: x) 1"), Value::Int(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn curried_function() {
|
||||
assert_eq!(eval("(x: y: x - y) 2 1"), Value::Int(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn rec_attrset() {
|
||||
assert_eq!(eval("rec { b = a; a = 1; }.b"), Value::Int(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn let_binding() {
|
||||
assert_eq!(eval("let b = a; a = 1; in b"), Value::Int(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn fibonacci() {
|
||||
assert_eq!(
|
||||
eval(
|
||||
@@ -40,7 +37,7 @@ fn fibonacci() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn fixed_point_combinator() {
|
||||
assert_eq!(
|
||||
eval("((f: let x = f x; in x)(self: { x = 1; y = self.x + 1; })).y"),
|
||||
@@ -48,17 +45,17 @@ fn fixed_point_combinator() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn conditional_true() {
|
||||
assert_eq!(eval("if true then 1 else 0"), Value::Int(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn conditional_false() {
|
||||
assert_eq!(eval("if false then 1 else 0"), Value::Int(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn nested_let() {
|
||||
assert_eq!(
|
||||
eval("let x = 1; in let y = x + 1; z = y + 1; in z"),
|
||||
@@ -66,7 +63,7 @@ fn nested_let() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn rec_inherit_fails() {
|
||||
assert!(eval_result("{ inherit x; }").is_err());
|
||||
}
|
||||
@@ -1,33 +1,32 @@
|
||||
mod utils;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use nix_js::value::{AttrSet, List, Value};
|
||||
use utils::eval;
|
||||
|
||||
#[test]
|
||||
use crate::utils::eval;
|
||||
|
||||
#[test_log::test]
|
||||
fn builtins_accessible() {
|
||||
let result = eval("builtins");
|
||||
assert!(matches!(result, Value::AttrSet(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_self_reference() {
|
||||
let result = eval("builtins.builtins");
|
||||
assert!(matches!(result, Value::AttrSet(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_add() {
|
||||
assert_eq!(eval("builtins.add 1 2"), Value::Int(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_length() {
|
||||
assert_eq!(eval("builtins.length [1 2 3]"), Value::Int(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_map() {
|
||||
assert_eq!(
|
||||
eval("builtins.map (x: x * 2) [1 2 3]"),
|
||||
@@ -35,7 +34,7 @@ fn builtins_map() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_filter() {
|
||||
assert_eq!(
|
||||
eval("builtins.filter (x: x > 1) [1 2 3]"),
|
||||
@@ -43,7 +42,7 @@ fn builtins_filter() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_attrnames() {
|
||||
let result = eval("builtins.attrNames { a = 1; b = 2; }");
|
||||
assert!(matches!(result, Value::List(_)));
|
||||
@@ -52,12 +51,12 @@ fn builtins_attrnames() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_head() {
|
||||
assert_eq!(eval("builtins.head [1 2 3]"), Value::Int(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_tail() {
|
||||
assert_eq!(
|
||||
eval("builtins.tail [1 2 3]"),
|
||||
@@ -65,17 +64,17 @@ fn builtins_tail() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_in_let() {
|
||||
assert_eq!(eval("let b = builtins; in b.add 5 3"), Value::Int(8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_in_with() {
|
||||
assert_eq!(eval("with builtins; add 10 20"), Value::Int(30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_nested_calls() {
|
||||
assert_eq!(
|
||||
eval("builtins.add (builtins.mul 2 3) (builtins.sub 10 5)"),
|
||||
@@ -83,32 +82,32 @@ fn builtins_nested_calls() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_is_list() {
|
||||
assert_eq!(eval("builtins.isList [1 2 3]"), Value::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_is_attrs() {
|
||||
assert_eq!(eval("builtins.isAttrs { a = 1; }"), Value::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_is_function() {
|
||||
assert_eq!(eval("builtins.isFunction (x: x)"), Value::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_is_null() {
|
||||
assert_eq!(eval("builtins.isNull null"), Value::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_is_bool() {
|
||||
assert_eq!(eval("builtins.isBool true"), Value::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_shadowing() {
|
||||
assert_eq!(
|
||||
eval("let builtins = { add = x: y: x - y; }; in builtins.add 5 3"),
|
||||
@@ -116,13 +115,13 @@ fn builtins_shadowing() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_lazy_evaluation() {
|
||||
let result = eval("builtins.builtins.builtins.add 1 1");
|
||||
assert_eq!(result, Value::Int(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_foldl() {
|
||||
assert_eq!(
|
||||
eval("builtins.foldl' (acc: x: acc + x) 0 [1 2 3 4 5]"),
|
||||
@@ -130,13 +129,13 @@ fn builtins_foldl() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_elem() {
|
||||
assert_eq!(eval("builtins.elem 2 [1 2 3]"), Value::Bool(true));
|
||||
assert_eq!(eval("builtins.elem 5 [1 2 3]"), Value::Bool(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_concat_lists() {
|
||||
assert_eq!(
|
||||
eval("builtins.concatLists [[1 2] [3 4] [5]]"),
|
||||
@@ -150,7 +149,7 @@ fn builtins_concat_lists() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_compare_versions_basic() {
|
||||
assert_eq!(
|
||||
eval("builtins.compareVersions \"1.0\" \"2.3\""),
|
||||
@@ -174,7 +173,7 @@ fn builtins_compare_versions_basic() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_compare_versions_components() {
|
||||
assert_eq!(
|
||||
eval("builtins.compareVersions \"2.3.1\" \"2.3\""),
|
||||
@@ -186,7 +185,7 @@ fn builtins_compare_versions_components() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_compare_versions_numeric_vs_alpha() {
|
||||
// Numeric component comes before alpha component
|
||||
assert_eq!(
|
||||
@@ -199,7 +198,7 @@ fn builtins_compare_versions_numeric_vs_alpha() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_compare_versions_pre() {
|
||||
// "pre" is special: comes before everything except another "pre"
|
||||
assert_eq!(
|
||||
@@ -220,7 +219,7 @@ fn builtins_compare_versions_pre() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_compare_versions_alpha() {
|
||||
// Alphabetic comparison
|
||||
assert_eq!(
|
||||
@@ -233,7 +232,7 @@ fn builtins_compare_versions_alpha() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_compare_versions_symmetry() {
|
||||
// Test symmetry: compareVersions(a, b) == -compareVersions(b, a)
|
||||
assert_eq!(
|
||||
@@ -246,7 +245,7 @@ fn builtins_compare_versions_symmetry() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_compare_versions_complex() {
|
||||
// Complex version strings with multiple components
|
||||
assert_eq!(
|
||||
@@ -263,7 +262,7 @@ fn builtins_compare_versions_complex() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_generic_closure() {
|
||||
assert_eq!(
|
||||
eval(
|
||||
@@ -279,7 +278,7 @@ fn builtins_generic_closure() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_function_args() {
|
||||
assert_eq!(
|
||||
eval("builtins.functionArgs (x: 1)"),
|
||||
@@ -316,7 +315,7 @@ fn builtins_function_args() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn builtins_parse_drv_name() {
|
||||
let result = eval(r#"builtins.parseDrvName "nix-js-0.1.0pre""#).unwrap_attr_set();
|
||||
assert_eq!(result.get("name"), Some(&Value::String("nix-js".into())));
|
||||
@@ -1,9 +1,8 @@
|
||||
mod utils;
|
||||
|
||||
use nix_js::value::Value;
|
||||
use utils::eval_result;
|
||||
|
||||
#[test]
|
||||
use crate::utils::eval_result;
|
||||
|
||||
#[test_log::test]
|
||||
fn to_file_simple() {
|
||||
let result =
|
||||
eval_result(r#"builtins.toFile "hello.txt" "Hello, World!""#).expect("Failed to evaluate");
|
||||
@@ -20,7 +19,7 @@ fn to_file_simple() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn to_file_with_references() {
|
||||
let result = eval_result(
|
||||
r#"
|
||||
@@ -43,7 +42,7 @@ fn to_file_with_references() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn to_file_invalid_name_with_slash() {
|
||||
let result = eval_result(r#"builtins.toFile "foo/bar.txt" "content""#);
|
||||
|
||||
@@ -56,7 +55,7 @@ fn to_file_invalid_name_with_slash() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn to_file_invalid_name_dot() {
|
||||
let result = eval_result(r#"builtins.toFile "." "content""#);
|
||||
|
||||
@@ -64,7 +63,7 @@ fn to_file_invalid_name_dot() {
|
||||
assert!(result.unwrap_err().to_string().contains("invalid name"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn to_file_invalid_name_dotdot() {
|
||||
let result = eval_result(r#"builtins.toFile ".." "content""#);
|
||||
|
||||
@@ -72,7 +71,7 @@ fn to_file_invalid_name_dotdot() {
|
||||
assert!(result.unwrap_err().to_string().contains("invalid name"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn store_path_validation_not_in_store() {
|
||||
let result = eval_result(r#"builtins.storePath "/tmp/foo""#);
|
||||
|
||||
@@ -85,7 +84,7 @@ fn store_path_validation_not_in_store() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn store_path_validation_malformed_hash() {
|
||||
let dummy_file_result = eval_result(r#"builtins.toFile "dummy.txt" "content""#)
|
||||
.expect("Failed to create dummy file");
|
||||
@@ -113,7 +112,7 @@ fn store_path_validation_malformed_hash() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn store_path_validation_missing_name() {
|
||||
let dummy_file_result = eval_result(r#"builtins.toFile "dummy.txt" "content""#)
|
||||
.expect("Failed to create dummy file");
|
||||
@@ -141,7 +140,7 @@ fn store_path_validation_missing_name() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn to_file_curried_application() {
|
||||
let result = eval_result(
|
||||
r#"
|
||||
@@ -163,7 +162,7 @@ fn to_file_curried_application() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn to_file_number_conversion() {
|
||||
let result = eval_result(r#"builtins.toFile "number.txt" (builtins.toString 42)"#)
|
||||
.expect("Failed to evaluate");
|
||||
@@ -177,7 +176,7 @@ fn to_file_number_conversion() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn to_file_list_conversion() {
|
||||
let result = eval_result(
|
||||
r#"builtins.toFile "list.txt" (builtins.concatStringsSep "\n" ["line1" "line2" "line3"])"#,
|
||||
@@ -1,9 +1,8 @@
|
||||
mod utils;
|
||||
|
||||
use nix_js::value::Value;
|
||||
use utils::{eval_deep, eval_deep_result};
|
||||
|
||||
#[test]
|
||||
use crate::utils::{eval_deep, eval_deep_result};
|
||||
|
||||
#[test_log::test]
|
||||
fn add_operator_preserves_derivation_context() {
|
||||
let result = eval_deep(
|
||||
r#"
|
||||
@@ -39,7 +38,7 @@ fn add_operator_preserves_derivation_context() {
|
||||
assert_eq!(result, nix_result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn derivation_minimal() {
|
||||
let result = eval_deep(
|
||||
r#"derivation { name = "hello"; builder = "/bin/sh"; system = "x86_64-linux"; }"#,
|
||||
@@ -77,7 +76,7 @@ fn derivation_minimal() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn derivation_with_args() {
|
||||
let result = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -99,7 +98,7 @@ fn derivation_with_args() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn derivation_to_string() {
|
||||
let result = eval_deep(
|
||||
r#"toString (derivation { name = "foo"; builder = "/bin/sh"; system = "x86_64-linux"; })"#,
|
||||
@@ -111,7 +110,7 @@ fn derivation_to_string() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn derivation_missing_name() {
|
||||
let result =
|
||||
eval_deep_result(r#"derivation { builder = "/bin/sh"; system = "x86_64-linux"; }"#);
|
||||
@@ -121,7 +120,7 @@ fn derivation_missing_name() {
|
||||
assert!(err_msg.contains("missing required attribute 'name'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn derivation_invalid_name_with_drv_suffix() {
|
||||
let result = eval_deep_result(
|
||||
r#"derivation { name = "foo.drv"; builder = "/bin/sh"; system = "x86_64-linux"; }"#,
|
||||
@@ -132,7 +131,7 @@ fn derivation_invalid_name_with_drv_suffix() {
|
||||
assert!(err_msg.contains("cannot end with .drv"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn derivation_missing_builder() {
|
||||
let result = eval_deep_result(r#"derivation { name = "test"; system = "x86_64-linux"; }"#);
|
||||
|
||||
@@ -141,7 +140,7 @@ fn derivation_missing_builder() {
|
||||
assert!(err_msg.contains("missing required attribute 'builder'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn derivation_missing_system() {
|
||||
let result = eval_deep_result(r#"derivation { name = "test"; builder = "/bin/sh"; }"#);
|
||||
|
||||
@@ -150,7 +149,7 @@ fn derivation_missing_system() {
|
||||
assert!(err_msg.contains("missing required attribute 'system'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn derivation_with_env_vars() {
|
||||
let result = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -171,7 +170,7 @@ fn derivation_with_env_vars() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn derivation_strict() {
|
||||
let result = eval_deep(
|
||||
r#"builtins.derivationStrict { name = "test"; builder = "/bin/sh"; system = "x86_64-linux"; }"#,
|
||||
@@ -188,7 +187,7 @@ fn derivation_strict() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn derivation_deterministic_paths() {
|
||||
let expr = r#"derivation { name = "hello"; builder = "/bin/sh"; system = "x86_64-linux"; }"#;
|
||||
|
||||
@@ -204,7 +203,7 @@ fn derivation_deterministic_paths() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn derivation_escaping_in_aterm() {
|
||||
let result = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -224,7 +223,7 @@ fn derivation_escaping_in_aterm() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn multi_output_two_outputs() {
|
||||
let drv = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -267,7 +266,7 @@ fn multi_output_two_outputs() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn multi_output_three_outputs() {
|
||||
let result = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -315,7 +314,7 @@ fn multi_output_three_outputs() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn multi_output_backward_compat() {
|
||||
let result = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -341,7 +340,7 @@ fn multi_output_backward_compat() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn multi_output_deterministic() {
|
||||
let result1 = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -364,7 +363,7 @@ fn multi_output_deterministic() {
|
||||
assert_eq!(result1, result2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn fixed_output_sha256_flat() {
|
||||
let result = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -401,7 +400,7 @@ fn fixed_output_sha256_flat() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn fixed_output_missing_hashalgo() {
|
||||
assert!(
|
||||
eval_deep_result(
|
||||
@@ -416,7 +415,7 @@ fn fixed_output_missing_hashalgo() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn fixed_output_recursive_mode() {
|
||||
let result = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -446,7 +445,7 @@ fn fixed_output_recursive_mode() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn fixed_output_rejects_multi_output() {
|
||||
let result = eval_deep_result(
|
||||
r#"derivation {
|
||||
@@ -464,7 +463,7 @@ fn fixed_output_rejects_multi_output() {
|
||||
assert!(err_msg.contains("fixed-output") && err_msg.contains("one"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn fixed_output_invalid_hash_mode() {
|
||||
let result = eval_deep_result(
|
||||
r#"derivation {
|
||||
@@ -481,7 +480,7 @@ fn fixed_output_invalid_hash_mode() {
|
||||
assert!(err_msg.contains("outputHashMode") && err_msg.contains("invalid"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn structured_attrs_basic() {
|
||||
let result = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -506,7 +505,7 @@ fn structured_attrs_basic() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn structured_attrs_nested() {
|
||||
let result = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -527,7 +526,7 @@ fn structured_attrs_nested() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn structured_attrs_rejects_functions() {
|
||||
let result = eval_deep_result(
|
||||
r#"derivation {
|
||||
@@ -544,7 +543,7 @@ fn structured_attrs_rejects_functions() {
|
||||
assert!(err_msg.contains("cannot convert lambda to JSON"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn structured_attrs_false() {
|
||||
let result = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -567,7 +566,7 @@ fn structured_attrs_false() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn ignore_nulls_true() {
|
||||
let result = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -589,7 +588,7 @@ fn ignore_nulls_true() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn ignore_nulls_false() {
|
||||
let result = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -612,7 +611,7 @@ fn ignore_nulls_false() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn ignore_nulls_with_structured_attrs() {
|
||||
let result = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -636,7 +635,7 @@ fn ignore_nulls_with_structured_attrs() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn all_features_combined() {
|
||||
let result = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -663,7 +662,7 @@ fn all_features_combined() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn fixed_output_with_structured_attrs() {
|
||||
let result = eval_deep(
|
||||
r#"derivation {
|
||||
@@ -1,8 +1,6 @@
|
||||
mod utils;
|
||||
use crate::utils::eval;
|
||||
|
||||
use utils::eval;
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn test_find_file_corepkg_fetchurl() {
|
||||
let result = eval(
|
||||
r#"
|
||||
@@ -17,13 +15,13 @@ fn test_find_file_corepkg_fetchurl() {
|
||||
assert!(result.to_string().contains("fetchurl.nix"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn test_lookup_path_syntax() {
|
||||
let result = eval(r#"<nix/fetchurl.nix>"#);
|
||||
assert!(result.to_string().contains("fetchurl.nix"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn test_import_corepkg() {
|
||||
let result = eval(
|
||||
r#"
|
||||
@@ -1,24 +1,23 @@
|
||||
mod utils;
|
||||
|
||||
use nix_js::value::{List, Value};
|
||||
use utils::eval;
|
||||
|
||||
#[test]
|
||||
use crate::utils::{eval, eval_result};
|
||||
|
||||
#[test_log::test]
|
||||
fn true_literal() {
|
||||
assert_eq!(eval("true"), Value::Bool(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn false_literal() {
|
||||
assert_eq!(eval("false"), Value::Bool(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn null_literal() {
|
||||
assert_eq!(eval("null"), Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn map_function() {
|
||||
assert_eq!(
|
||||
eval("map (x: x * 2) [1 2 3]"),
|
||||
@@ -26,23 +25,23 @@ fn map_function() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn is_null_function() {
|
||||
assert_eq!(eval("isNull null"), Value::Bool(true));
|
||||
assert_eq!(eval("isNull 5"), Value::Bool(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn shadow_true() {
|
||||
assert_eq!(eval("let true = false; in true"), Value::Bool(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn shadow_map() {
|
||||
assert_eq!(eval("let map = x: y: x; in map 1 2"), Value::Int(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn mixed_usage() {
|
||||
assert_eq!(
|
||||
eval("if true then map (x: x + 1) [1 2] else []"),
|
||||
@@ -50,7 +49,7 @@ fn mixed_usage() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn in_let_bindings() {
|
||||
assert_eq!(
|
||||
eval("let x = true; y = false; in x && y"),
|
||||
@@ -58,18 +57,18 @@ fn in_let_bindings() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn shadow_in_function() {
|
||||
assert_eq!(eval("(true: true) false"), Value::Bool(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn throw_function() {
|
||||
let result = utils::eval_result("throw \"error message\"");
|
||||
let result = eval_result("throw \"error message\"");
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn to_string_function() {
|
||||
assert_eq!(eval("toString 42"), Value::String("42".to_string()));
|
||||
}
|
||||
@@ -1,20 +1,19 @@
|
||||
mod utils;
|
||||
|
||||
use nix_js::value::Value;
|
||||
use utils::{eval, eval_result};
|
||||
|
||||
#[test]
|
||||
use crate::utils::{eval, eval_result};
|
||||
|
||||
#[test_log::test]
|
||||
fn required_parameters() {
|
||||
assert_eq!(eval("({ a, b }: a + b) { a = 1; b = 2; }"), Value::Int(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn missing_required_parameter() {
|
||||
let result = eval_result("({ a, b }: a + b) { a = 1; }");
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn all_required_parameters_present() {
|
||||
assert_eq!(
|
||||
eval("({ x, y, z }: x + y + z) { x = 1; y = 2; z = 3; }"),
|
||||
@@ -22,13 +21,13 @@ fn all_required_parameters_present() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn reject_unexpected_arguments() {
|
||||
let result = eval_result("({ a, b }: a + b) { a = 1; b = 2; c = 3; }");
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn ellipsis_accepts_extra_arguments() {
|
||||
assert_eq!(
|
||||
eval("({ a, b, ... }: a + b) { a = 1; b = 2; c = 3; }"),
|
||||
@@ -36,12 +35,12 @@ fn ellipsis_accepts_extra_arguments() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn default_parameters() {
|
||||
assert_eq!(eval("({ a, b ? 5 }: a + b) { a = 1; }"), Value::Int(6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn override_default_parameter() {
|
||||
assert_eq!(
|
||||
eval("({ a, b ? 5 }: a + b) { a = 1; b = 10; }"),
|
||||
@@ -49,7 +48,7 @@ fn override_default_parameter() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn at_pattern_alias() {
|
||||
assert_eq!(
|
||||
eval("(args@{ a, b }: args.a + args.b) { a = 1; b = 2; }"),
|
||||
@@ -57,17 +56,17 @@ fn at_pattern_alias() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn simple_parameter_no_validation() {
|
||||
assert_eq!(eval("(x: x.a + x.b) { a = 1; b = 2; }"), Value::Int(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn simple_parameter_accepts_any_argument() {
|
||||
assert_eq!(eval("(x: x) 42"), Value::Int(42));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn nested_function_parameters() {
|
||||
assert_eq!(
|
||||
eval("({ a }: { b }: a + b) { a = 5; } { b = 3; }"),
|
||||
@@ -75,12 +74,12 @@ fn nested_function_parameters() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn pattern_param_simple_reference_in_default() {
|
||||
assert_eq!(eval("({ a, b ? a }: b) { a = 10; }"), Value::Int(10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn pattern_param_multiple_references_in_default() {
|
||||
assert_eq!(
|
||||
eval("({ a, b ? a + 5, c ? 1 }: b + c) { a = 10; }"),
|
||||
@@ -88,7 +87,7 @@ fn pattern_param_multiple_references_in_default() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn pattern_param_mutual_reference() {
|
||||
assert_eq!(
|
||||
eval("({ a, b ? c + 1, c ? 5 }: b) { a = 1; }"),
|
||||
@@ -96,7 +95,7 @@ fn pattern_param_mutual_reference() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn pattern_param_override_mutual_reference() {
|
||||
assert_eq!(
|
||||
eval("({ a, b ? c + 1, c ? 5 }: b) { a = 1; c = 10; }"),
|
||||
@@ -104,7 +103,7 @@ fn pattern_param_override_mutual_reference() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn pattern_param_reference_list() {
|
||||
assert_eq!(
|
||||
eval("({ a, b ? [ a 2 ] }: builtins.elemAt b 0) { a = 42; }"),
|
||||
@@ -112,7 +111,7 @@ fn pattern_param_reference_list() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn pattern_param_alias_in_default() {
|
||||
assert_eq!(
|
||||
eval("(args@{ a, b ? args.a + 10 }: b) { a = 5; }"),
|
||||
@@ -1,12 +1,10 @@
|
||||
mod utils;
|
||||
|
||||
use nix_js::context::Context;
|
||||
use nix_js::error::Source;
|
||||
use nix_js::value::Value;
|
||||
|
||||
use crate::utils::{eval, eval_result};
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn import_absolute_path() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let lib_path = temp_dir.path().join("nix_test_lib.nix");
|
||||
@@ -17,7 +15,7 @@ fn import_absolute_path() {
|
||||
assert_eq!(eval(&expr), Value::Int(8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn import_nested() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -35,7 +33,7 @@ fn import_nested() {
|
||||
assert_eq!(eval(&expr), Value::Int(30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn import_relative_path() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let subdir = temp_dir.path().join("subdir");
|
||||
@@ -66,7 +64,7 @@ fn import_relative_path() {
|
||||
assert_eq!(eval(&expr), Value::Int(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn import_returns_function() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let func_path = temp_dir.path().join("nix_test_func.nix");
|
||||
@@ -76,7 +74,7 @@ fn import_returns_function() {
|
||||
assert_eq!(eval(&expr), Value::Int(10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn import_with_complex_dependency_graph() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -97,7 +95,7 @@ fn import_with_complex_dependency_graph() {
|
||||
|
||||
// Tests for builtins.path
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn path_with_file() {
|
||||
let mut ctx = Context::new().unwrap();
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
@@ -116,7 +114,7 @@ fn path_with_file() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn path_with_custom_name() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let test_file = temp_dir.path().join("original.txt");
|
||||
@@ -136,7 +134,7 @@ fn path_with_custom_name() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn path_with_directory_recursive() {
|
||||
let mut ctx = Context::new().unwrap();
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
@@ -159,7 +157,7 @@ fn path_with_directory_recursive() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn path_flat_with_file() {
|
||||
let mut ctx = Context::new().unwrap();
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
@@ -179,7 +177,7 @@ fn path_flat_with_file() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn path_flat_with_directory_fails() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let test_dir = temp_dir.path().join("mydir");
|
||||
@@ -196,7 +194,7 @@ fn path_flat_with_directory_fails() {
|
||||
assert!(err_msg.contains("recursive") || err_msg.contains("regular file"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn path_nonexistent_fails() {
|
||||
let expr = r#"builtins.path { path = "/nonexistent/path/that/should/not/exist"; }"#;
|
||||
let result = eval_result(expr);
|
||||
@@ -206,7 +204,7 @@ fn path_nonexistent_fails() {
|
||||
assert!(err_msg.contains("does not exist"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn path_missing_path_param() {
|
||||
let expr = r#"builtins.path { name = "test"; }"#;
|
||||
let result = eval_result(expr);
|
||||
@@ -216,7 +214,7 @@ fn path_missing_path_param() {
|
||||
assert!(err_msg.contains("path") && err_msg.contains("required"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn path_with_sha256() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let test_file = temp_dir.path().join("hash_test.txt");
|
||||
@@ -243,7 +241,7 @@ fn path_with_sha256() {
|
||||
assert_eq!(store_path1, store_path2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn path_deterministic() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let test_file = temp_dir.path().join("deterministic.txt");
|
||||
@@ -261,7 +259,7 @@ fn path_deterministic() {
|
||||
assert_eq!(result1, result2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn read_file_type_regular_file() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let test_file = temp_dir.path().join("test.txt");
|
||||
@@ -271,7 +269,7 @@ fn read_file_type_regular_file() {
|
||||
assert_eq!(eval(&expr), Value::String("regular".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn read_file_type_directory() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let test_dir = temp_dir.path().join("testdir");
|
||||
@@ -281,7 +279,7 @@ fn read_file_type_directory() {
|
||||
assert_eq!(eval(&expr), Value::String("directory".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn read_file_type_symlink() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let target = temp_dir.path().join("target.txt");
|
||||
@@ -299,7 +297,7 @@ fn read_file_type_symlink() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn read_dir_basic() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let test_dir = temp_dir.path().join("readdir_test");
|
||||
@@ -331,7 +329,7 @@ fn read_dir_basic() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn read_dir_empty() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let test_dir = temp_dir.path().join("empty_dir");
|
||||
@@ -347,7 +345,7 @@ fn read_dir_empty() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn read_dir_nonexistent_fails() {
|
||||
let expr = r#"builtins.readDir "/nonexistent/directory""#;
|
||||
let result = eval_result(expr);
|
||||
@@ -355,7 +353,7 @@ fn read_dir_nonexistent_fails() {
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn read_dir_on_file_fails() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let test_file = temp_dir.path().join("test.txt");
|
||||
@@ -1,7 +1,5 @@
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
mod utils;
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use nix_js::context::Context;
|
||||
@@ -9,7 +7,7 @@ use nix_js::error::Source;
|
||||
use nix_js::value::Value;
|
||||
|
||||
fn get_lang_dir() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/lang")
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/tests/lang")
|
||||
}
|
||||
|
||||
fn eval_file(name: &str) -> Result<(Value, Source), String> {
|
||||
@@ -44,7 +42,7 @@ fn format_value(value: &Value) -> String {
|
||||
macro_rules! eval_okay_test {
|
||||
($(#[$attr:meta])* $name:ident$(, $pre:expr)?) => {
|
||||
$(#[$attr])*
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn $name() {
|
||||
$(($pre)();)?
|
||||
let test_name = concat!("eval-okay-", stringify!($name))
|
||||
@@ -76,7 +74,7 @@ macro_rules! eval_okay_test {
|
||||
|
||||
macro_rules! eval_fail_test {
|
||||
($name:ident) => {
|
||||
#[test]
|
||||
#[test_log::test]
|
||||
fn $name() {
|
||||
let test_name = concat!("eval-fail-", stringify!($name))
|
||||
.replace("_", "-")
|
||||
@@ -194,15 +192,11 @@ eval_okay_test!(
|
||||
eval_okay_test!(partition);
|
||||
eval_okay_test!(path);
|
||||
eval_okay_test!(pathexists);
|
||||
eval_okay_test!(
|
||||
#[ignore = "rnix 0.13 regression: /${foo}-/*...*/ fails to parse"]
|
||||
path_string_interpolation,
|
||||
|| {
|
||||
eval_okay_test!(path_string_interpolation, || {
|
||||
unsafe {
|
||||
std::env::set_var("HOME", "/fake-home");
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
eval_okay_test!(patterns);
|
||||
eval_okay_test!(print);
|
||||
eval_okay_test!(readDir);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user