Compare commits
53 Commits
b7f4ece472
...
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 | |||
| f0a0593d4c | |||
| ce64a82da3 | |||
| 5c48e5cfdd | |||
| 7836f8c869 | |||
| e357678d70 | |||
| 2f2c690023 | |||
| cf4dd6c379 | |||
| 31c7a62311 | |||
| ad5d047c01 | |||
| 795742e3d8 | |||
| 60cd61d771 | |||
| d95a6e509c | |||
| 48a43bed55 | |||
| 6d8f1e79e6 | |||
| df4edaf5bb | |||
| 3aee3c67b9 | |||
|
a8f1c81b60
|
|||
|
249eaf3c11
|
|||
|
a79e20c417
|
|||
|
bd9eb638af
|
|||
|
d09b84676c
|
|||
|
1346ae5405
|
|||
|
6b46e466c2
|
|||
|
f154010120
|
|||
|
f5364ded1e
|
|||
|
26e7b74585
|
|||
|
e8a28a6d2f
|
|||
|
216930027d
|
|||
|
4d6fd6d614
|
5
.gitignore
vendored
5
.gitignore
vendored
@@ -5,3 +5,8 @@ target/
|
|||||||
# Profiling
|
# Profiling
|
||||||
flamegraph*.svg
|
flamegraph*.svg
|
||||||
perf.data*
|
perf.data*
|
||||||
|
profile.json.gz
|
||||||
|
prof.json
|
||||||
|
*.cpuprofile
|
||||||
|
*.cpuprofile.gz
|
||||||
|
*v8.log*
|
||||||
|
|||||||
11
.lazy.lua
11
.lazy.lua
@@ -3,12 +3,21 @@ vim.lsp.config("biome", {
|
|||||||
on_dir(vim.fn.getcwd())
|
on_dir(vim.fn.getcwd())
|
||||||
end
|
end
|
||||||
})
|
})
|
||||||
|
vim.lsp.config("eslint", {
|
||||||
|
settings = {
|
||||||
|
eslint = {
|
||||||
|
options = {
|
||||||
|
configFile = "./nix-js/runtime-ts/eslint.config.mts"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
vim.lsp.config("rust_analyzer", {
|
vim.lsp.config("rust_analyzer", {
|
||||||
settings = {
|
settings = {
|
||||||
["rust-analyzer"] = {
|
["rust-analyzer"] = {
|
||||||
cargo = {
|
cargo = {
|
||||||
features = {
|
features = {
|
||||||
"daemon"
|
"inspector"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
1515
Cargo.lock
generated
1515
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
24
Justfile
24
Justfile
@@ -1,15 +1,31 @@
|
|||||||
[no-exit-message]
|
[no-exit-message]
|
||||||
@repl:
|
@repl:
|
||||||
RUST_LOG=none,nix_js=debug cargo run --bin repl
|
cargo run -- repl
|
||||||
|
|
||||||
[no-exit-message]
|
[no-exit-message]
|
||||||
@eval expr:
|
@eval expr:
|
||||||
RUST_LOG=none,nix_js=debug cargo run --bin eval -- '{{expr}}'
|
cargo run -- eval --expr '{{expr}}'
|
||||||
|
|
||||||
[no-exit-message]
|
[no-exit-message]
|
||||||
@replr:
|
@replr:
|
||||||
RUST_LOG=info cargo run --bin repl --release
|
cargo run --release -- repl
|
||||||
|
|
||||||
[no-exit-message]
|
[no-exit-message]
|
||||||
@evalr expr:
|
@evalr expr:
|
||||||
RUST_LOG=silent cargo run --bin eval --release -- '{{expr}}'
|
cargo run --release -- eval --expr '{{expr}}'
|
||||||
|
|
||||||
|
[no-exit-message]
|
||||||
|
@repli:
|
||||||
|
cargo run --release --features inspector -- --inspect-brk 127.0.0.1:9229 repl
|
||||||
|
|
||||||
|
[no-exit-message]
|
||||||
|
@evali 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}}'
|
||||||
|
|||||||
31
biome.json
31
biome.json
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://biomejs.dev/schemas/2.3.9/schema.json",
|
"$schema": "https://biomejs.dev/schemas/2.3.14/schema.json",
|
||||||
"vcs": {
|
"vcs": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
"clientKind": "git",
|
"clientKind": "git",
|
||||||
@@ -20,10 +20,37 @@
|
|||||||
"linter": {
|
"linter": {
|
||||||
"rules": {
|
"rules": {
|
||||||
"style": {
|
"style": {
|
||||||
"useNamingConvention": "warn"
|
"useNamingConvention": {
|
||||||
|
"level": "warn",
|
||||||
|
"options": {
|
||||||
|
"strictCase": false,
|
||||||
|
"conventions": [
|
||||||
|
{
|
||||||
|
"selector": { "kind": "objectLiteralProperty" },
|
||||||
|
"formats": ["camelCase", "PascalCase", "CONSTANT_CASE"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"selector": { "kind": "typeProperty" },
|
||||||
|
"formats": ["camelCase", "snake_case"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"overrides": [
|
||||||
|
{
|
||||||
|
"includes": ["**/global.d.ts"],
|
||||||
|
"linter": {
|
||||||
|
"rules": {
|
||||||
|
"style": {
|
||||||
|
"useNamingConvention": "off"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
"javascript": {
|
"javascript": {
|
||||||
"formatter": {
|
"formatter": {
|
||||||
"arrowParentheses": "always",
|
"arrowParentheses": "always",
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ let
|
|||||||
flake = (
|
flake = (
|
||||||
import flake-compat {
|
import flake-compat {
|
||||||
src = ./.;
|
src = ./.;
|
||||||
|
copySourceTreeToStore = false;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
in
|
in
|
||||||
|
|||||||
18
flake.lock
generated
18
flake.lock
generated
@@ -8,11 +8,11 @@
|
|||||||
"rust-analyzer-src": "rust-analyzer-src"
|
"rust-analyzer-src": "rust-analyzer-src"
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1768892055,
|
"lastModified": 1770966612,
|
||||||
"narHash": "sha256-zatCoDgFd0C8YEOztMeBcom6cka0GqJGfc0aAXvpktc=",
|
"narHash": "sha256-S6k14z/JsDwX6zZyLucDBTOe/9RsvxH9GTUxHn2o4vc=",
|
||||||
"owner": "nix-community",
|
"owner": "nix-community",
|
||||||
"repo": "fenix",
|
"repo": "fenix",
|
||||||
"rev": "81d6a7547e090f7e760b95b9cc534461f6045e43",
|
"rev": "e90d48dcfaebac7ea7a5687888a2d0733be26343",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -37,11 +37,11 @@
|
|||||||
},
|
},
|
||||||
"nixpkgs": {
|
"nixpkgs": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1768886240,
|
"lastModified": 1770841267,
|
||||||
"narHash": "sha256-C2TjvwYZ2VDxYWeqvvJ5XPPp6U7H66zeJlRaErJKoEM=",
|
"narHash": "sha256-9xejG0KoqsoKEGp2kVbXRlEYtFFcDTHjidiuX8hGO44=",
|
||||||
"owner": "nixos",
|
"owner": "nixos",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"rev": "80e4adbcf8992d3fd27ad4964fbb84907f9478b0",
|
"rev": "ec7c70d12ce2fc37cb92aff673dcdca89d187bae",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -61,11 +61,11 @@
|
|||||||
"rust-analyzer-src": {
|
"rust-analyzer-src": {
|
||||||
"flake": false,
|
"flake": false,
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1768816483,
|
"lastModified": 1770934477,
|
||||||
"narHash": "sha256-bXeWgVkvxN76QEw12OaWFbRhO1yt+5QETz/BxBX4dk0=",
|
"narHash": "sha256-GX0cINHhhzUbQHyDYN2Mc+ovb6Sx/4yrF95VVou9aW4=",
|
||||||
"owner": "rust-lang",
|
"owner": "rust-lang",
|
||||||
"repo": "rust-analyzer",
|
"repo": "rust-analyzer",
|
||||||
"rev": "1b8952b49fa10cae9020f0e46d0b8938563a6b64",
|
"rev": "931cd553be123b11db1435ac7ea5657e62e5e601",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
|||||||
@@ -27,11 +27,14 @@
|
|||||||
"rust-analyzer"
|
"rust-analyzer"
|
||||||
])
|
])
|
||||||
cargo-outdated
|
cargo-outdated
|
||||||
|
cargo-machete
|
||||||
lldb
|
lldb
|
||||||
valgrind
|
valgrind
|
||||||
hyperfine
|
hyperfine
|
||||||
just
|
just
|
||||||
samply
|
samply
|
||||||
|
jq
|
||||||
|
tokei
|
||||||
|
|
||||||
nodejs
|
nodejs
|
||||||
nodePackages.npm
|
nodePackages.npm
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ edition = "2024"
|
|||||||
proc-macro = true
|
proc-macro = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
convert_case = "0.8"
|
convert_case = "0.11"
|
||||||
quote = "1.0"
|
|
||||||
proc-macro2 = "1.0"
|
proc-macro2 = "1.0"
|
||||||
|
quote = "1.0"
|
||||||
syn = { version = "2.0", features = ["full"] }
|
syn = { version = "2.0", features = ["full"] }
|
||||||
|
|||||||
@@ -4,22 +4,22 @@
|
|||||||
//! an Intermediate Representation (IR) that follows a specific pattern. It generates:
|
//! an Intermediate Representation (IR) that follows a specific pattern. It generates:
|
||||||
//! 1. An enum representing the different kinds of IR nodes.
|
//! 1. An enum representing the different kinds of IR nodes.
|
||||||
//! 2. Structs for each of the variants that have fields.
|
//! 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.
|
//! 3. `From` implementations to easily convert from a struct variant (e.g., `BinOp`) to the main enum (`Ir::BinOp`).
|
||||||
//! 4. `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.
|
||||||
//! 5. A `To[IrName]` trait to provide a convenient `.to_ir()` method on the variant structs.
|
|
||||||
|
|
||||||
use convert_case::{Case, Casing};
|
use convert_case::{Case, Casing};
|
||||||
use proc_macro::TokenStream;
|
use proc_macro::TokenStream;
|
||||||
use quote::{format_ident, quote};
|
use quote::{format_ident, quote};
|
||||||
use syn::{
|
use syn::{
|
||||||
FieldsNamed, Ident, Token, Type, parenthesized,
|
Expr, ExprPath, FieldsNamed, GenericArgument, GenericParam, Generics, Ident, Path, PathSegment,
|
||||||
|
Token, Type, TypePath, parenthesized,
|
||||||
parse::{Parse, ParseStream, Result},
|
parse::{Parse, ParseStream, Result},
|
||||||
punctuated::Punctuated,
|
punctuated::Punctuated,
|
||||||
token,
|
token,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Represents one of the variants passed to the `ir!` macro.
|
/// Represents one of the variants passed to the `ir!` macro.
|
||||||
pub enum VariantInput {
|
enum VariantInput {
|
||||||
/// A unit-like variant, e.g., `Arg`.
|
/// A unit-like variant, e.g., `Arg`.
|
||||||
Unit(Ident),
|
Unit(Ident),
|
||||||
/// A tuple-like variant with one unnamed field, e.g., `ExprRef(ExprId)`.
|
/// 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.
|
/// 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`).
|
/// 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.
|
/// The list of variants for the enum.
|
||||||
pub variants: Punctuated<VariantInput, Token![,]>,
|
variants: Punctuated<VariantInput, Token![,]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Parse for VariantInput {
|
impl Parse for VariantInput {
|
||||||
@@ -64,13 +65,14 @@ impl Parse for VariantInput {
|
|||||||
|
|
||||||
impl Parse for MacroInput {
|
impl Parse for MacroInput {
|
||||||
fn parse(input: ParseStream) -> Result<Self> {
|
fn parse(input: ParseStream) -> Result<Self> {
|
||||||
// The macro input is expected to be: `IrName, Variant1, Variant2, ...`
|
|
||||||
let base_name = input.parse()?;
|
let base_name = input.parse()?;
|
||||||
input.parse::<Token![,]>()?;
|
let generics = Generics::parse(input)?;
|
||||||
|
input.parse::<Token![;]>()?;
|
||||||
let variants = Punctuated::parse_terminated(input)?;
|
let variants = Punctuated::parse_terminated(input)?;
|
||||||
|
|
||||||
Ok(MacroInput {
|
Ok(MacroInput {
|
||||||
base_name,
|
base_name,
|
||||||
|
generics,
|
||||||
variants,
|
variants,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -81,17 +83,39 @@ pub fn ir_impl(input: TokenStream) -> TokenStream {
|
|||||||
let parsed_input = syn::parse_macro_input!(input as MacroInput);
|
let parsed_input = syn::parse_macro_input!(input as MacroInput);
|
||||||
|
|
||||||
let base_name = &parsed_input.base_name;
|
let base_name = &parsed_input.base_name;
|
||||||
let ref_name = format_ident!("{}Ref", base_name);
|
let generic_params = &parsed_input.generics.params;
|
||||||
let mut_name = format_ident!("{}Mut", base_name);
|
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_name = format_ident!("To{}", base_name);
|
||||||
let to_trait_fn_name = format_ident!("to_{}", base_name.to_string().to_case(Case::Snake));
|
let to_trait_fn_name = format_ident!("to_{}", base_name.to_string().to_case(Case::Snake));
|
||||||
|
|
||||||
let mut enum_variants = Vec::new();
|
let mut enum_variants = Vec::new();
|
||||||
let mut struct_defs = 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 span_arms = Vec::new();
|
||||||
let mut from_impls = Vec::new();
|
let mut from_impls = Vec::new();
|
||||||
let mut to_trait_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) });
|
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 });
|
span_arms.push(quote! { Self::#name(inner) => inner.span });
|
||||||
from_impls.push(quote! {
|
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) }
|
fn from(val: #inner_type) -> Self { #base_name::#name(val) }
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
to_trait_impls.push(quote! {
|
to_trait_impls.push(quote! {
|
||||||
impl #to_trait_name for #name {
|
impl <#generic_params> #to_trait_name <#generic_args> for #name #where_clause {
|
||||||
fn #to_trait_fn_name(self) -> #base_name { #base_name::from(self) }
|
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();
|
let inner_type = name.clone();
|
||||||
enum_variants.push(quote! { #name(#inner_type) });
|
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 });
|
span_arms.push(quote! { Self::#name(inner) => inner.span });
|
||||||
from_impls.push(quote! {
|
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) }
|
fn from(val: #inner_type) -> Self { #base_name::#name(val) }
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
to_trait_impls.push(quote! {
|
to_trait_impls.push(quote! {
|
||||||
impl #to_trait_name for #name {
|
impl <#generic_params> #to_trait_name <#generic_args> for #name #where_clause {
|
||||||
fn #to_trait_fn_name(self) -> #base_name { #base_name::from(self) }
|
fn #to_trait_fn_name(self) -> #base_name <#generic_args> { #base_name::from(self) }
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
VariantInput::Struct(name, mut fields) => {
|
VariantInput::Struct(name, mut fields) => {
|
||||||
let inner_type = name.clone();
|
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 {
|
fields.named.push(syn::Field {
|
||||||
attrs: vec![],
|
attrs: vec![],
|
||||||
vis: syn::Visibility::Public(syn::token::Pub::default()),
|
vis: syn::Visibility::Public(syn::token::Pub::default()),
|
||||||
@@ -168,22 +187,18 @@ pub fn ir_impl(input: TokenStream) -> TokenStream {
|
|||||||
|
|
||||||
struct_defs.push(quote! {
|
struct_defs.push(quote! {
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct #name #fields
|
pub struct #name <#generic_params> #where_clause #fields
|
||||||
});
|
});
|
||||||
enum_variants.push(quote! { #name(#inner_type) });
|
enum_variants.push(quote! { #name(#inner_type <#generic_args>) });
|
||||||
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 });
|
span_arms.push(quote! { Self::#name(inner) => inner.span });
|
||||||
from_impls.push(quote! {
|
from_impls.push(quote! {
|
||||||
impl From<#inner_type> for #base_name {
|
impl <#generic_params> From<#inner_type <#generic_args>> for #base_name <#generic_args> #where_clause {
|
||||||
fn from(val: #inner_type) -> Self { #base_name::#name(val) }
|
fn from(val: #inner_type <#generic_args>) -> Self { #base_name::#name(val) }
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
to_trait_impls.push(quote! {
|
to_trait_impls.push(quote! {
|
||||||
impl #to_trait_name for #name {
|
impl <#generic_params> #to_trait_name <#generic_args> for #name <#generic_args> #where_clause {
|
||||||
fn #to_trait_fn_name(self) -> #base_name { #base_name::from(self) }
|
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.
|
// Assemble the final generated code.
|
||||||
let expanded = quote! {
|
let expanded = quote! {
|
||||||
/// The main IR enum, generated by the `ir!` macro.
|
/// The main IR enum, generated by the `ir!` macro.
|
||||||
#[derive(Debug, IsVariant, Unwrap, TryUnwrap)]
|
#[derive(Debug)]
|
||||||
pub enum #base_name {
|
pub enum #base_name <#generic_params> #where_clause {
|
||||||
#( #enum_variants ),*
|
#( #enum_variants ),*
|
||||||
}
|
}
|
||||||
|
|
||||||
// The struct definitions for the enum variants.
|
// The struct definitions for the enum variants.
|
||||||
#( #struct_defs )*
|
#( #struct_defs )*
|
||||||
|
|
||||||
/// An immutable reference version of the IR enum.
|
impl <#generic_params> #base_name <#generic_args> #where_clause {
|
||||||
#[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 ),*
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn span(&self) -> rnix::TextRange {
|
pub fn span(&self) -> rnix::TextRange {
|
||||||
match self {
|
match self {
|
||||||
#( #span_arms ),*
|
#( #span_arms ),*
|
||||||
@@ -239,9 +228,9 @@ pub fn ir_impl(input: TokenStream) -> TokenStream {
|
|||||||
#( #from_impls )*
|
#( #from_impls )*
|
||||||
|
|
||||||
/// A trait for converting a variant struct into the main IR enum.
|
/// 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.
|
/// 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.
|
// Implement the `ToIr` trait for each variant struct.
|
||||||
|
|||||||
@@ -4,19 +4,18 @@ version = "0.1.0"
|
|||||||
edition = "2024"
|
edition = "2024"
|
||||||
build = "build.rs"
|
build = "build.rs"
|
||||||
|
|
||||||
[features]
|
|
||||||
default = ["daemon"]
|
|
||||||
daemon = ["dep:tokio", "dep:nix-compat"]
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
mimalloc = "0.1"
|
mimalloc = "0.1"
|
||||||
|
|
||||||
tokio = { version = "1.41", features = ["rt-multi-thread", "sync", "net", "io-util"], optional = true }
|
tokio = { version = "1.41", features = ["rt-multi-thread", "sync", "net", "io-util"] }
|
||||||
nix-compat = { git = "https://git.snix.dev/snix/snix.git", version = "0.1.0", features = ["wire", "async"], optional = true }
|
nix-compat = { git = "https://git.snix.dev/snix/snix.git", version = "0.1.0", features = ["wire", "async"] }
|
||||||
|
|
||||||
# REPL
|
# REPL
|
||||||
anyhow = "1.0"
|
anyhow = "1.0"
|
||||||
rustyline = "14.0"
|
rustyline = "17.0"
|
||||||
|
|
||||||
|
# CLI
|
||||||
|
clap = { version = "4", features = ["derive"] }
|
||||||
|
|
||||||
# Logging
|
# Logging
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
@@ -27,8 +26,8 @@ thiserror = "2"
|
|||||||
miette = { version = "7.4", features = ["fancy"] }
|
miette = { version = "7.4", features = ["fancy"] }
|
||||||
|
|
||||||
hashbrown = "0.16"
|
hashbrown = "0.16"
|
||||||
petgraph = "0.8"
|
|
||||||
string-interner = "0.19"
|
string-interner = "0.19"
|
||||||
|
bumpalo = { version = "3.20", features = ["allocator-api2", "boxed", "collections"] }
|
||||||
|
|
||||||
rust-embed="8.11"
|
rust-embed="8.11"
|
||||||
|
|
||||||
@@ -36,35 +35,55 @@ itertools = "0.14"
|
|||||||
|
|
||||||
regex = "1.11"
|
regex = "1.11"
|
||||||
|
|
||||||
deno_core = "0.376"
|
deno_core = "0.385"
|
||||||
deno_error = "0.7"
|
deno_error = "0.7"
|
||||||
|
|
||||||
nix-nar = "0.3"
|
nix-nar = "0.3"
|
||||||
sha2 = "0.10"
|
sha2 = "0.10"
|
||||||
|
sha1 = "0.10"
|
||||||
|
md5 = "0.8"
|
||||||
hex = "0.4"
|
hex = "0.4"
|
||||||
|
|
||||||
base64 = "0.22"
|
base64 = "0.22"
|
||||||
|
|
||||||
# Fetcher dependencies
|
reqwest = { version = "0.13", features = ["blocking", "rustls"], default-features = false }
|
||||||
reqwest = { version = "0.12", features = ["blocking", "rustls-tls"], default-features = false }
|
|
||||||
tar = "0.4"
|
tar = "0.4"
|
||||||
flate2 = "1.0"
|
flate2 = "1.0"
|
||||||
xz2 = "0.1"
|
xz2 = "0.1"
|
||||||
bzip2 = "0.5"
|
bzip2 = "0.6"
|
||||||
zip = "2.2"
|
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
dirs = "5.0"
|
# spec 1.0.0
|
||||||
|
toml = "0.9.9"
|
||||||
|
dirs = "6.0"
|
||||||
tempfile = "3.24"
|
tempfile = "3.24"
|
||||||
rusqlite = { version = "0.33", features = ["bundled"] }
|
rusqlite = { version = "0.38", features = ["bundled"] }
|
||||||
|
|
||||||
rnix = "0.12"
|
rnix = "0.14"
|
||||||
rowan = "0.15"
|
rowan = "0.16"
|
||||||
|
|
||||||
nix-js-macros = { path = "../nix-js-macros" }
|
nix-js-macros = { path = "../nix-js-macros" }
|
||||||
|
ere = "0.2.4"
|
||||||
|
num_enum = "0.7.5"
|
||||||
|
tap = "1.0.1"
|
||||||
|
|
||||||
|
# Inspector (optional)
|
||||||
|
fastwebsockets = { version = "0.10", features = ["upgrade"], optional = true }
|
||||||
|
hyper = { version = "1", features = ["http1", "server"], optional = true }
|
||||||
|
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]
|
[dev-dependencies]
|
||||||
criterion = { version = "0.5", features = ["html_reports"] }
|
criterion = { version = "0.8", features = ["html_reports"] }
|
||||||
|
test-log = { version = "0.2", features = ["trace"] }
|
||||||
|
|
||||||
[[bench]]
|
[[bench]]
|
||||||
name = "basic_ops"
|
name = "basic_ops"
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
mod utils;
|
mod utils;
|
||||||
|
|
||||||
use criterion::{Criterion, black_box, criterion_group, criterion_main};
|
use std::hint::black_box;
|
||||||
|
|
||||||
|
use criterion::{Criterion, criterion_group, criterion_main};
|
||||||
use utils::eval;
|
use utils::eval;
|
||||||
|
|
||||||
fn bench_arithmetic(c: &mut Criterion) {
|
fn bench_arithmetic(c: &mut Criterion) {
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
mod utils;
|
mod utils;
|
||||||
|
|
||||||
use criterion::{Criterion, black_box, criterion_group, criterion_main};
|
use std::hint::black_box;
|
||||||
|
|
||||||
|
use criterion::{Criterion, criterion_group, criterion_main};
|
||||||
use utils::eval;
|
use utils::eval;
|
||||||
|
|
||||||
fn bench_builtin_math(c: &mut Criterion) {
|
fn bench_builtin_math(c: &mut Criterion) {
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
mod utils;
|
mod utils;
|
||||||
|
|
||||||
use criterion::{Criterion, black_box, criterion_group, criterion_main};
|
use std::hint::black_box;
|
||||||
|
|
||||||
|
use criterion::{Criterion, criterion_group, criterion_main};
|
||||||
use nix_js::context::Context;
|
use nix_js::context::Context;
|
||||||
use utils::compile;
|
use utils::compile;
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
mod utils;
|
mod utils;
|
||||||
|
|
||||||
use criterion::{Criterion, black_box, criterion_group, criterion_main};
|
use std::hint::black_box;
|
||||||
|
|
||||||
|
use criterion::{Criterion, criterion_group, criterion_main};
|
||||||
use utils::eval;
|
use utils::eval;
|
||||||
|
|
||||||
fn bench_non_recursive(c: &mut Criterion) {
|
fn bench_non_recursive(c: &mut Criterion) {
|
||||||
|
|||||||
@@ -7,19 +7,19 @@ use nix_js::value::Value;
|
|||||||
pub fn eval(expr: &str) -> Value {
|
pub fn eval(expr: &str) -> Value {
|
||||||
Context::new()
|
Context::new()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.eval_code(Source::new_eval(expr.into()).unwrap())
|
.eval(Source::new_eval(expr.into()).unwrap())
|
||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn eval_result(expr: &str) -> Result<Value> {
|
pub fn eval_result(expr: &str) -> Result<Value> {
|
||||||
Context::new()
|
Context::new()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.eval_code(Source::new_eval(expr.into()).unwrap())
|
.eval(Source::new_eval(expr.into()).unwrap())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn compile(expr: &str) -> String {
|
pub fn compile(expr: &str) -> String {
|
||||||
Context::new()
|
Context::new()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.compile_code(Source::new_eval(expr.into()).unwrap())
|
.compile(Source::new_eval(expr.into()).unwrap())
|
||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|||||||
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",
|
"version": "0.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
"check": "tsc --noEmit && npx eslint && biome check",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"build": "node build.mjs",
|
"build": "node build.mjs",
|
||||||
"dev": "npm run typecheck && npm run build"
|
"dev": "npm run typecheck && npm run build"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"esbuild": "^0.24.2",
|
"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": {
|
"dependencies": {
|
||||||
|
"globals": "^17.3.0",
|
||||||
"js-sdsl": "^4.4.2"
|
"js-sdsl": "^4.4.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,30 +1,26 @@
|
|||||||
/**
|
|
||||||
* Arithmetic builtin functions
|
|
||||||
*/
|
|
||||||
|
|
||||||
import type { NixBool, NixInt, NixNumber, NixValue } from "../types";
|
|
||||||
import { forceNumeric, coerceNumeric, forceInt } from "../type-assert";
|
|
||||||
import { op } from "../operators";
|
import { op } from "../operators";
|
||||||
|
import { coerceNumeric, forceInt, forceNumeric } from "../type-assert";
|
||||||
|
import type { NixBool, NixInt, NixNumber, NixValue } from "../types";
|
||||||
|
|
||||||
export const add =
|
export const add =
|
||||||
(a: NixValue) =>
|
(a: NixValue) =>
|
||||||
(b: NixValue): bigint | number => {
|
(b: NixValue): bigint | number => {
|
||||||
const [av, bv] = coerceNumeric(forceNumeric(a), forceNumeric(b));
|
const [av, bv] = coerceNumeric(forceNumeric(a), forceNumeric(b));
|
||||||
return (av as any) + (bv as any);
|
return (av as never) + (bv as never);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const sub =
|
export const sub =
|
||||||
(a: NixValue) =>
|
(a: NixValue) =>
|
||||||
(b: NixValue): bigint | number => {
|
(b: NixValue): bigint | number => {
|
||||||
const [av, bv] = coerceNumeric(forceNumeric(a), forceNumeric(b));
|
const [av, bv] = coerceNumeric(forceNumeric(a), forceNumeric(b));
|
||||||
return (av as any) - (bv as any);
|
return (av as never) - (bv as never);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const mul =
|
export const mul =
|
||||||
(a: NixValue) =>
|
(a: NixValue) =>
|
||||||
(b: NixValue): bigint | number => {
|
(b: NixValue): bigint | number => {
|
||||||
const [av, bv] = coerceNumeric(forceNumeric(a), forceNumeric(b));
|
const [av, bv] = coerceNumeric(forceNumeric(a), forceNumeric(b));
|
||||||
return (av as any) * (bv as any);
|
return (av as never) * (bv as never);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const div =
|
export const div =
|
||||||
@@ -36,10 +32,9 @@ export const div =
|
|||||||
throw new RangeError("Division by zero");
|
throw new RangeError("Division by zero");
|
||||||
}
|
}
|
||||||
|
|
||||||
return (av as any) / (bv as any);
|
return (av as never) / (bv as never);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Bitwise operations - only for integers
|
|
||||||
export const bitAnd =
|
export const bitAnd =
|
||||||
(a: NixValue) =>
|
(a: NixValue) =>
|
||||||
(b: NixValue): NixInt => {
|
(b: NixValue): NixInt => {
|
||||||
|
|||||||
@@ -1,15 +1,12 @@
|
|||||||
/**
|
import { mkPos, select } from "../helpers";
|
||||||
* Attribute set operation builtin functions
|
|
||||||
*/
|
|
||||||
|
|
||||||
import type { NixValue, NixAttrs, NixList } from "../types";
|
|
||||||
import { forceAttrs, forceStringValue, forceFunction, forceList } from "../type-assert";
|
|
||||||
import { createThunk } from "../thunk";
|
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[] =>
|
export const attrValues = (set: NixValue): NixValue[] =>
|
||||||
Object.entries(forceAttrs(set))
|
Array.from(forceAttrs(set).entries())
|
||||||
.sort(([a], [b]) => {
|
.sort(([a], [b]) => {
|
||||||
if (a < b) {
|
if (a < b) {
|
||||||
return -1;
|
return -1;
|
||||||
@@ -24,21 +21,24 @@ export const attrValues = (set: NixValue): NixValue[] =>
|
|||||||
export const getAttr =
|
export const getAttr =
|
||||||
(s: NixValue) =>
|
(s: NixValue) =>
|
||||||
(set: NixValue): NixValue =>
|
(set: NixValue): NixValue =>
|
||||||
forceAttrs(set)[forceStringValue(s)];
|
select(forceAttrs(set), [s]);
|
||||||
|
|
||||||
export const hasAttr =
|
export const hasAttr =
|
||||||
(s: NixValue) =>
|
(s: NixValue) =>
|
||||||
(set: NixValue): boolean =>
|
(set: NixValue): boolean =>
|
||||||
Object.hasOwn(forceAttrs(set), forceStringValue(s));
|
forceAttrs(set).has(forceStringValue(s));
|
||||||
|
|
||||||
export const mapAttrs =
|
export const mapAttrs =
|
||||||
(f: NixValue) =>
|
(f: NixValue) =>
|
||||||
(attrs: NixValue): NixAttrs => {
|
(attrs: NixValue): NixAttrs => {
|
||||||
const forcedAttrs = forceAttrs(attrs);
|
const forcedAttrs = forceAttrs(attrs);
|
||||||
const forcedF = forceFunction(f);
|
const forcedF = forceFunction(f);
|
||||||
const newAttrs: NixAttrs = {};
|
const newAttrs: NixAttrs = new Map();
|
||||||
for (const key in forcedAttrs) {
|
for (const [key, val] of forcedAttrs) {
|
||||||
newAttrs[key] = createThunk(() => forceFunction(forcedF(key))(forcedAttrs[key]), "created by mapAttrs");
|
newAttrs.set(
|
||||||
|
key,
|
||||||
|
createThunk(() => forceFunction(forcedF(key))(val), "created by mapAttrs"),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return newAttrs;
|
return newAttrs;
|
||||||
};
|
};
|
||||||
@@ -46,25 +46,20 @@ export const mapAttrs =
|
|||||||
export const removeAttrs =
|
export const removeAttrs =
|
||||||
(attrs: NixValue) =>
|
(attrs: NixValue) =>
|
||||||
(list: NixValue): NixAttrs => {
|
(list: NixValue): NixAttrs => {
|
||||||
const new_attrs: NixAttrs = {};
|
const newAttrs: NixAttrs = new Map(forceAttrs(attrs));
|
||||||
const forced_attrs = forceAttrs(attrs);
|
const forcedList = forceList(list);
|
||||||
const forced_list = forceList(list);
|
for (const item of forcedList) {
|
||||||
const keys_to_remove = new Set(forced_list.map(forceStringValue));
|
newAttrs.delete(forceStringValue(item));
|
||||||
|
|
||||||
for (const key in forced_attrs) {
|
|
||||||
if (!keys_to_remove.has(key)) {
|
|
||||||
new_attrs[key] = forced_attrs[key];
|
|
||||||
}
|
}
|
||||||
}
|
return newAttrs;
|
||||||
return new_attrs;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const listToAttrs = (e: NixValue): NixAttrs => {
|
export const listToAttrs = (e: NixValue): NixAttrs => {
|
||||||
const attrs: NixAttrs = {};
|
const attrs: NixAttrs = new Map();
|
||||||
const forced_e = [...forceList(e)].reverse();
|
const forcedE = [...forceList(e)].reverse();
|
||||||
for (const obj of forced_e) {
|
for (const obj of forcedE) {
|
||||||
const item = forceAttrs(obj);
|
const item = forceAttrs(obj);
|
||||||
attrs[forceStringValue(item.name)] = item.value;
|
attrs.set(forceStringValue(select(item, ["name"])), select(item, ["value"]));
|
||||||
}
|
}
|
||||||
return attrs;
|
return attrs;
|
||||||
};
|
};
|
||||||
@@ -74,10 +69,18 @@ export const intersectAttrs =
|
|||||||
(e2: NixValue): NixAttrs => {
|
(e2: NixValue): NixAttrs => {
|
||||||
const f1 = forceAttrs(e1);
|
const f1 = forceAttrs(e1);
|
||||||
const f2 = forceAttrs(e2);
|
const f2 = forceAttrs(e2);
|
||||||
const attrs: NixAttrs = {};
|
const attrs: NixAttrs = new Map();
|
||||||
for (const key of Object.keys(f2)) {
|
if (f1.size < f2.size) {
|
||||||
if (Object.hasOwn(f1, key)) {
|
for (const [key] of f1) {
|
||||||
attrs[key] = f2[key];
|
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;
|
return attrs;
|
||||||
@@ -88,20 +91,20 @@ export const catAttrs =
|
|||||||
(list: NixValue): NixList => {
|
(list: NixValue): NixList => {
|
||||||
const key = forceStringValue(attr);
|
const key = forceStringValue(attr);
|
||||||
return forceList(list)
|
return forceList(list)
|
||||||
.map((set) => forceAttrs(set)[key])
|
.map((set) => forceAttrs(set).get(key))
|
||||||
.filter((val) => val !== undefined);
|
.filter((val) => val !== undefined) as NixList;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const groupBy =
|
export const groupBy =
|
||||||
(f: NixValue) =>
|
(f: NixValue) =>
|
||||||
(list: NixValue): NixAttrs => {
|
(list: NixValue): NixAttrs => {
|
||||||
const attrs: NixAttrs = {};
|
const attrs: NixAttrs = new Map();
|
||||||
const forced_f = forceFunction(f);
|
const forcedF = forceFunction(f);
|
||||||
const forced_list = forceList(list);
|
const forcedList = forceList(list);
|
||||||
for (const elem of forced_list) {
|
for (const elem of forcedList) {
|
||||||
const key = forceStringValue(forced_f(elem));
|
const key = forceStringValue(forcedF(elem));
|
||||||
if (!attrs[key]) attrs[key] = [];
|
if (!attrs.has(key)) attrs.set(key, []);
|
||||||
(attrs[key] as NixList).push(elem);
|
(attrs.get(key) as NixList).push(elem);
|
||||||
}
|
}
|
||||||
return attrs;
|
return attrs;
|
||||||
};
|
};
|
||||||
@@ -111,29 +114,26 @@ export const zipAttrsWith =
|
|||||||
(list: NixValue): NixValue => {
|
(list: NixValue): NixValue => {
|
||||||
const listForced = forceList(list);
|
const listForced = forceList(list);
|
||||||
|
|
||||||
// Map to collect all values for each attribute name
|
|
||||||
const attrMap = new Map<string, NixValue[]>();
|
const attrMap = new Map<string, NixValue[]>();
|
||||||
|
|
||||||
// Iterate through each attribute set in the list
|
|
||||||
for (const item of listForced) {
|
for (const item of listForced) {
|
||||||
const attrs = forceAttrs(item);
|
const attrs = forceAttrs(item);
|
||||||
|
|
||||||
// Collect all attribute names and their values
|
for (const [key, value] of attrs) {
|
||||||
for (const [key, value] of Object.entries(attrs)) {
|
|
||||||
if (!attrMap.has(key)) {
|
if (!attrMap.has(key)) {
|
||||||
attrMap.set(key, []);
|
attrMap.set(key, []);
|
||||||
}
|
}
|
||||||
attrMap.get(key)!.push(value);
|
(attrMap.get(key) as NixValue[]).push(value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build the result attribute set
|
const result: NixAttrs = new Map();
|
||||||
const result: Record<string, NixValue> = {};
|
|
||||||
|
|
||||||
for (const [name, values] of attrMap.entries()) {
|
for (const [name, values] of attrMap.entries()) {
|
||||||
// Apply f to name and values list
|
result.set(
|
||||||
// f is curried: f name values
|
name,
|
||||||
result[name] = createThunk(() => forceFunction(forceFunction(f)(name))(values));
|
createThunk(() => forceFunction(forceFunction(f)(name))(values)),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@@ -145,15 +145,15 @@ export const unsafeGetAttrPos =
|
|||||||
const name = forceStringValue(attrName);
|
const name = forceStringValue(attrName);
|
||||||
const attrs = forceAttrs(attrSet);
|
const attrs = forceAttrs(attrSet);
|
||||||
|
|
||||||
if (!(name in attrs)) {
|
if (!attrs.has(name)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const positions = (attrs as any)[Nix.ATTR_POSITIONS];
|
const positions = attrs[ATTR_POSITIONS];
|
||||||
if (!positions || !(name in positions)) {
|
if (!positions || !positions.has(name)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const span = positions[name];
|
const span = positions.get(name) as number;
|
||||||
return Nix.mkPos(span);
|
return mkPos(span);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
import type { NixValue, NixAttrs, NixString } from "../types";
|
|
||||||
import { isStringWithContext } from "../types";
|
|
||||||
import { forceString, forceAttrs, forceList, forceStringValue } from "../type-assert";
|
|
||||||
import { force } from "../thunk";
|
|
||||||
import {
|
import {
|
||||||
type NixStringContext,
|
|
||||||
getStringValue,
|
|
||||||
getStringContext,
|
|
||||||
mkStringWithContext,
|
|
||||||
decodeContextElem,
|
decodeContextElem,
|
||||||
|
getStringContext,
|
||||||
|
getStringValue,
|
||||||
|
mkStringWithContext,
|
||||||
|
type NixStringContext,
|
||||||
parseContextToInfoMap,
|
parseContextToInfoMap,
|
||||||
} from "../string-context";
|
} from "../string-context";
|
||||||
|
import { force } from "../thunk";
|
||||||
|
import { forceAttrs, forceList, forceString, forceStringValue } from "../type-assert";
|
||||||
|
import type { NixAttrs, NixString, NixValue } from "../types";
|
||||||
|
import { isStringWithContext } from "../types";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* builtins.hasContext - Check if string has context
|
* builtins.hasContext - Check if string has context
|
||||||
@@ -113,20 +113,20 @@ export const getContext = (value: NixValue): NixAttrs => {
|
|||||||
const context = getStringContext(s);
|
const context = getStringContext(s);
|
||||||
|
|
||||||
const infoMap = parseContextToInfoMap(context);
|
const infoMap = parseContextToInfoMap(context);
|
||||||
const result: NixAttrs = {};
|
const result: NixAttrs = new Map();
|
||||||
|
|
||||||
for (const [path, info] of infoMap) {
|
for (const [path, info] of infoMap) {
|
||||||
const attrs: NixAttrs = {};
|
const attrs: NixAttrs = new Map();
|
||||||
if (info.path) {
|
if (info.path) {
|
||||||
attrs["path"] = true;
|
attrs.set("path", true);
|
||||||
}
|
}
|
||||||
if (info.allOutputs) {
|
if (info.allOutputs) {
|
||||||
attrs["allOutputs"] = true;
|
attrs.set("allOutputs", true);
|
||||||
}
|
}
|
||||||
if (info.outputs.length > 0) {
|
if (info.outputs.length > 0) {
|
||||||
attrs["outputs"] = info.outputs;
|
attrs.set("outputs", info.outputs);
|
||||||
}
|
}
|
||||||
result[path] = attrs;
|
result.set(path, attrs);
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@@ -154,22 +154,22 @@ export const appendContext =
|
|||||||
const ctxAttrs = forceAttrs(ctxValue);
|
const ctxAttrs = forceAttrs(ctxValue);
|
||||||
const newContext: NixStringContext = new Set(existingContext);
|
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/")) {
|
if (!path.startsWith("/nix/store/")) {
|
||||||
throw new Error(`context key '${path}' is not a store path`);
|
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) {
|
if (info.has("path")) {
|
||||||
const pathVal = force(info["path"]);
|
const pathVal = force(info.get("path") as NixValue);
|
||||||
if (pathVal === true) {
|
if (pathVal === true) {
|
||||||
newContext.add(path);
|
newContext.add(path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ("allOutputs" in info) {
|
if (info.has("allOutputs")) {
|
||||||
const allOutputs = force(info["allOutputs"]);
|
const allOutputs = force(info.get("allOutputs") as NixValue);
|
||||||
if (allOutputs === true) {
|
if (allOutputs === true) {
|
||||||
if (!path.endsWith(".drv")) {
|
if (!path.endsWith(".drv")) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
@@ -180,8 +180,8 @@ export const appendContext =
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ("outputs" in info) {
|
if (info.has("outputs")) {
|
||||||
const outputs = forceList(info["outputs"]);
|
const outputs = forceList(info.get("outputs") as NixValue);
|
||||||
if (outputs.length > 0 && !path.endsWith(".drv")) {
|
if (outputs.length > 0 && !path.endsWith(".drv")) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`tried to add derivation output context of ${path}, which is not a derivation, to a string`,
|
`tried to add derivation output context of ${path}, which is not a derivation, to a string`,
|
||||||
|
|||||||
@@ -2,72 +2,47 @@
|
|||||||
* Conversion and serialization builtin functions
|
* Conversion and serialization builtin functions
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import type { NixValue, NixString, NixPath } from "../types";
|
import {
|
||||||
import { isStringWithContext, isNixPath } from "../types";
|
addBuiltContext,
|
||||||
import { force } from "../thunk";
|
mkStringWithContext,
|
||||||
import { type NixStringContext, mkStringWithContext, addBuiltContext } from "../string-context";
|
type NixStringContext,
|
||||||
import { forceFunction } from "../type-assert";
|
StringWithContext,
|
||||||
import { nixValueToJson } from "../conversion";
|
} from "../string-context";
|
||||||
|
import { force, isThunk } from "../thunk";
|
||||||
|
import { forceFunction, forceStringNoCtx } from "../type-assert";
|
||||||
|
import type { NixString, NixValue } from "../types";
|
||||||
|
import { isNixPath, isStringWithContext, NixPath } from "../types";
|
||||||
import { isAttrs, isPath, typeOf } from "./type-check";
|
import { isAttrs, isPath, typeOf } from "./type-check";
|
||||||
|
|
||||||
const convertJsonToNix = (json: unknown): NixValue => {
|
|
||||||
if (json === null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (typeof json === "boolean") {
|
|
||||||
return json;
|
|
||||||
}
|
|
||||||
if (typeof json === "number") {
|
|
||||||
if (Number.isInteger(json)) {
|
|
||||||
return BigInt(json);
|
|
||||||
}
|
|
||||||
return json;
|
|
||||||
}
|
|
||||||
if (typeof json === "string") {
|
|
||||||
return json;
|
|
||||||
}
|
|
||||||
if (Array.isArray(json)) {
|
|
||||||
return json.map(convertJsonToNix);
|
|
||||||
}
|
|
||||||
if (typeof json === "object") {
|
|
||||||
const result: Record<string, NixValue> = {};
|
|
||||||
for (const [key, value] of Object.entries(json)) {
|
|
||||||
result[key] = convertJsonToNix(value);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
throw new TypeError(`unsupported JSON value type: ${typeof json}`);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const fromJSON = (e: NixValue): NixValue => {
|
export const fromJSON = (e: NixValue): NixValue => {
|
||||||
const str = force(e);
|
const str = force(e);
|
||||||
if (typeof str !== "string" && !isStringWithContext(str)) {
|
if (typeof str !== "string" && !isStringWithContext(str)) {
|
||||||
throw new TypeError(`builtins.fromJSON: expected a string, got ${typeOf(str)}`);
|
throw new TypeError(`builtins.fromJSON: expected a string, got ${typeOf(str)}`);
|
||||||
}
|
}
|
||||||
const jsonStr = isStringWithContext(str) ? str.value : str;
|
const jsonStr = isStringWithContext(str) ? str.value : str;
|
||||||
try {
|
return Deno.core.ops.op_from_json(jsonStr) as NixValue;
|
||||||
const parsed = JSON.parse(jsonStr);
|
|
||||||
return convertJsonToNix(parsed);
|
|
||||||
} catch (err) {
|
|
||||||
throw new SyntaxError(`builtins.fromJSON: ${err instanceof Error ? err.message : String(err)}`);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const fromTOML = (e: NixValue): never => {
|
export const fromTOML = (e: NixValue): NixValue => {
|
||||||
throw new Error("Not implemented: fromTOML");
|
const toml = forceStringNoCtx(e);
|
||||||
|
return Deno.core.ops.op_from_toml(toml) as NixValue;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const toJSON = (e: NixValue): NixString => {
|
export const toJSON = (e: NixValue): NixString => {
|
||||||
const context: Set<string> = new Set();
|
const context: Set<string> = new Set();
|
||||||
const string = JSON.stringify(nixValueToJson(e, new Set(), context));
|
const string = JSON.stringify(nixValueToJson(e, true, context, true));
|
||||||
if (context.size === 0) {
|
if (context.size === 0) {
|
||||||
return string;
|
return string;
|
||||||
}
|
}
|
||||||
return mkStringWithContext(string, context);
|
return mkStringWithContext(string, context);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const toXML = (e: NixValue): never => {
|
export const toXML = (e: NixValue): NixString => {
|
||||||
throw new Error("Not implemented: toXML");
|
const [xml, context] = Deno.core.ops.op_to_xml(force(e));
|
||||||
|
if (context.length === 0) {
|
||||||
|
return xml;
|
||||||
|
}
|
||||||
|
return mkStringWithContext(xml, new Set(context));
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -120,7 +95,7 @@ export const coerceToString = (
|
|||||||
value: NixValue,
|
value: NixValue,
|
||||||
mode: StringCoercionMode,
|
mode: StringCoercionMode,
|
||||||
copyToStore: boolean = false,
|
copyToStore: boolean = false,
|
||||||
outContext?: NixStringContext,
|
outContext: NixStringContext,
|
||||||
): string => {
|
): string => {
|
||||||
const v = force(value);
|
const v = force(value);
|
||||||
|
|
||||||
@@ -130,11 +105,9 @@ export const coerceToString = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isStringWithContext(v)) {
|
if (isStringWithContext(v)) {
|
||||||
if (outContext) {
|
|
||||||
for (const elem of v.context) {
|
for (const elem of v.context) {
|
||||||
outContext.add(elem);
|
outContext.add(elem);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return v.value;
|
return v.value;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,41 +116,38 @@ export const coerceToString = (
|
|||||||
if (copyToStore) {
|
if (copyToStore) {
|
||||||
const pathStr = v.value;
|
const pathStr = v.value;
|
||||||
const storePath = Deno.core.ops.op_copy_path_to_store(pathStr);
|
const storePath = Deno.core.ops.op_copy_path_to_store(pathStr);
|
||||||
if (outContext) {
|
|
||||||
outContext.add(storePath);
|
outContext.add(storePath);
|
||||||
}
|
|
||||||
return storePath;
|
return storePath;
|
||||||
}
|
}
|
||||||
return v.value;
|
return v.value;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof v === "object" && v !== null && !Array.isArray(v)) {
|
if (typeof v === "object" && v !== null && !Array.isArray(v)) {
|
||||||
// First, try the __toString method if present
|
if (v instanceof Map) {
|
||||||
// This allows custom types to define their own string representation
|
if (v.has("__toString")) {
|
||||||
if ("__toString" in v) {
|
const toStringMethod = forceFunction(v.get("__toString") as NixValue);
|
||||||
// Force the method in case it's a thunk
|
|
||||||
const toStringMethod = forceFunction(v.__toString);
|
|
||||||
const result = force(toStringMethod(v));
|
const result = force(toStringMethod(v));
|
||||||
// Recursively coerceToString
|
|
||||||
return coerceToString(result, mode, copyToStore, outContext);
|
return coerceToString(result, mode, copyToStore, outContext);
|
||||||
}
|
}
|
||||||
|
|
||||||
// If no __toString, try outPath (used for derivations and store paths)
|
if (v.has("outPath")) {
|
||||||
// This allows derivation objects like { outPath = "/nix/store/..."; } to be coerced
|
const outPath = coerceToString(v.get("outPath") as NixValue, mode, copyToStore, outContext);
|
||||||
if ("outPath" in v) {
|
if (v.has("type") && v.get("type") === "derivation" && v.has("drvPath") && outContext) {
|
||||||
// Recursively coerce the outPath value
|
const drvPathValue = force(v.get("drvPath") as NixValue);
|
||||||
const outPath = coerceToString(v.outPath, mode, copyToStore, outContext);
|
const drvPathStr = isStringWithContext(drvPathValue)
|
||||||
if ("type" in v && v.type === "derivation" && "drvPath" in v) {
|
? drvPathValue.value
|
||||||
const drvPath = force(v.drvPath);
|
: typeof drvPathValue === "string"
|
||||||
if (typeof drvPath === "string" && outContext) {
|
? drvPathValue
|
||||||
const outputName = "outputName" in v ? String(force(v.outputName)) : "out";
|
: null;
|
||||||
addBuiltContext(outContext, drvPath, outputName);
|
if (drvPathStr) {
|
||||||
|
const outputName = v.has("outputName") ? String(force(v.get("outputName") as NixValue)) : "out";
|
||||||
|
addBuiltContext(outContext, drvPathStr, outputName);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return outPath;
|
return outPath;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Attribute sets without __toString or outPath cannot be coerced
|
|
||||||
throw new TypeError(`cannot coerce ${typeOf(v)} to a string`);
|
throw new TypeError(`cannot coerce ${typeOf(v)} to a string`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -282,14 +252,14 @@ export const coerceToStringWithContext = (
|
|||||||
* - Returns the path string (not a NixPath object)
|
* - Returns the path string (not a NixPath object)
|
||||||
* - Preserves string context if present
|
* - Preserves string context if present
|
||||||
*/
|
*/
|
||||||
export const coerceToPath = (value: NixValue, outContext?: NixStringContext): string => {
|
export const coerceToPath = (value: NixValue, outContext: NixStringContext): string => {
|
||||||
const forced = force(value);
|
const forced = force(value);
|
||||||
|
|
||||||
if (isPath(forced)) {
|
if (isPath(forced)) {
|
||||||
return forced.value;
|
return forced.value;
|
||||||
}
|
}
|
||||||
if (isAttrs(forced) && Object.hasOwn(forced, "__toString")) {
|
if (isAttrs(forced) && forced.has("__toString")) {
|
||||||
const toStringFunc = forceFunction(forced.__toString);
|
const toStringFunc = forceFunction(forced.get("__toString") as NixValue);
|
||||||
return coerceToPath(toStringFunc(forced), outContext);
|
return coerceToPath(toStringFunc(forced), outContext);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -318,3 +288,84 @@ export const coerceToPath = (value: NixValue, outContext?: NixStringContext): st
|
|||||||
export const toStringFunc = (value: NixValue): NixString => {
|
export const toStringFunc = (value: NixValue): NixString => {
|
||||||
return coerceToStringWithContext(value, StringCoercionMode.ToString, false);
|
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(),
|
||||||
|
): JsonValue => {
|
||||||
|
const v = strict ? force(value) : value;
|
||||||
|
|
||||||
|
if (isThunk(v) || typeof v === "function")
|
||||||
|
throw new Error(`cannot convert ${isThunk(v) ? "thunk" : "lambda"} to JSON`);
|
||||||
|
if (v === null) return null;
|
||||||
|
if (typeof v === "bigint") {
|
||||||
|
const num = Number(v);
|
||||||
|
if (v > Number.MAX_SAFE_INTEGER || v < Number.MIN_SAFE_INTEGER) {
|
||||||
|
console.warn(`integer ${v} exceeds safe range, precision may be lost`);
|
||||||
|
}
|
||||||
|
return num;
|
||||||
|
}
|
||||||
|
if (typeof v === "number") return v;
|
||||||
|
if (typeof v === "boolean") return v;
|
||||||
|
if (typeof v === "string") return v;
|
||||||
|
if (v instanceof StringWithContext) {
|
||||||
|
for (const elem of v.context) {
|
||||||
|
outContext.add(elem);
|
||||||
|
}
|
||||||
|
return v.value;
|
||||||
|
}
|
||||||
|
if (v instanceof NixPath) {
|
||||||
|
if (copyToStore) {
|
||||||
|
const storePath = Deno.core.ops.op_copy_path_to_store(v.value);
|
||||||
|
outContext.add(storePath);
|
||||||
|
return storePath;
|
||||||
|
} else {
|
||||||
|
return v.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// FIXME: is this check necessary?
|
||||||
|
// if (seen.has(v)) {
|
||||||
|
// throw new Error("cycle detected in toJSON");
|
||||||
|
// } else {
|
||||||
|
// seen.add(v)
|
||||||
|
// }
|
||||||
|
|
||||||
|
if (Array.isArray(v)) {
|
||||||
|
return v.map((item) => nixValueToJson(item, strict, outContext, copyToStore, seen));
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
if (isStringWithContext(result)) {
|
||||||
|
for (const elem of result.context) {
|
||||||
|
outContext.add(elem);
|
||||||
|
}
|
||||||
|
return result.value;
|
||||||
|
}
|
||||||
|
return nixValueToJson(result, strict, outContext, copyToStore, seen);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (v.has("outPath")) {
|
||||||
|
return nixValueToJson(v.get("outPath") as NixValue, strict, outContext, copyToStore, seen);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result: { [key: string]: JsonValue } = {};
|
||||||
|
const keys = Array.from(v.keys()).sort();
|
||||||
|
for (const key of keys) {
|
||||||
|
result[key] = nixValueToJson(v.get(key) as NixValue, strict, outContext, copyToStore, seen);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`cannot convert ${typeof v} to JSON`);
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,38 +1,125 @@
|
|||||||
import type { NixValue, NixAttrs } from "../types";
|
|
||||||
import { forceStringValue, forceList } from "../type-assert";
|
|
||||||
import { force, createThunk } from "../thunk";
|
|
||||||
import { type DerivationData, type OutputInfo, generateAterm } from "../derivation-helpers";
|
|
||||||
import { coerceToString, StringCoercionMode } from "./conversion";
|
|
||||||
import {
|
import {
|
||||||
type NixStringContext,
|
|
||||||
extractInputDrvsAndSrcs,
|
|
||||||
isStringWithContext,
|
|
||||||
mkStringWithContext,
|
|
||||||
addDrvDeepContext,
|
|
||||||
addBuiltContext,
|
addBuiltContext,
|
||||||
|
addDrvDeepContext,
|
||||||
|
mkStringWithContext,
|
||||||
|
type NixStringContext,
|
||||||
} from "../string-context";
|
} from "../string-context";
|
||||||
import { nixValueToJson } from "../conversion";
|
import { force } from "../thunk";
|
||||||
import { isNixPath } from "../types";
|
import { forceAttrs, forceList, forceStringNoCtx, forceStringValue } from "../type-assert";
|
||||||
|
import type { NixAttrs, NixValue } from "../types";
|
||||||
|
import { coerceToString, type JsonValue, nixValueToJson, StringCoercionMode } from "./conversion";
|
||||||
|
|
||||||
const forceAttrs = (value: NixValue): NixAttrs => {
|
export interface OutputInfo {
|
||||||
const forced = force(value);
|
path: string;
|
||||||
if (
|
hashAlgo: string;
|
||||||
typeof forced !== "object" ||
|
hash: string;
|
||||||
forced === null ||
|
}
|
||||||
Array.isArray(forced) ||
|
|
||||||
isStringWithContext(forced) ||
|
export interface DerivationData {
|
||||||
isNixPath(forced)
|
name: string;
|
||||||
) {
|
outputs: Map<string, OutputInfo>;
|
||||||
throw new TypeError(`Expected attribute set for derivation, got ${typeof forced}`);
|
inputDrvs: Map<string, Set<string>>;
|
||||||
|
inputSrcs: Set<string>;
|
||||||
|
platform: string;
|
||||||
|
builder: string;
|
||||||
|
args: string[];
|
||||||
|
env: Map<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const escapeString = (s: string): string => {
|
||||||
|
let result = "";
|
||||||
|
for (const char of s) {
|
||||||
|
switch (char) {
|
||||||
|
case '"':
|
||||||
|
result += '\\"';
|
||||||
|
break;
|
||||||
|
case "\\":
|
||||||
|
result += "\\\\";
|
||||||
|
break;
|
||||||
|
case "\n":
|
||||||
|
result += "\\n";
|
||||||
|
break;
|
||||||
|
case "\r":
|
||||||
|
result += "\\r";
|
||||||
|
break;
|
||||||
|
case "\t":
|
||||||
|
result += "\\t";
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
result += char;
|
||||||
}
|
}
|
||||||
return forced;
|
}
|
||||||
|
return `"${result}"`;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const quoteString = (s: string): string => `"${s}"`;
|
||||||
|
|
||||||
|
const cmpByKey = <T>(a: [string, T], b: [string, T]): number => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
|
||||||
|
|
||||||
|
export const generateAterm = (drv: DerivationData): string => {
|
||||||
|
const outputEntries: string[] = [];
|
||||||
|
const sortedOutputs = Array.from(drv.outputs.entries()).sort(cmpByKey);
|
||||||
|
for (const [name, info] of sortedOutputs) {
|
||||||
|
outputEntries.push(
|
||||||
|
`(${quoteString(name)},${quoteString(info.path)},${quoteString(info.hashAlgo)},${quoteString(info.hash)})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const outputs = outputEntries.join(",");
|
||||||
|
|
||||||
|
const inputDrvEntries: string[] = [];
|
||||||
|
const sortedInputDrvs = Array.from(drv.inputDrvs.entries()).sort(cmpByKey);
|
||||||
|
for (const [drvPath, outputs] of sortedInputDrvs) {
|
||||||
|
const sortedOuts = Array.from(outputs).sort();
|
||||||
|
const outList = `[${sortedOuts.map(quoteString).join(",")}]`;
|
||||||
|
inputDrvEntries.push(`(${quoteString(drvPath)},${outList})`);
|
||||||
|
}
|
||||||
|
const inputDrvs = inputDrvEntries.join(",");
|
||||||
|
|
||||||
|
const sortedInputSrcs = Array.from(drv.inputSrcs).sort();
|
||||||
|
const inputSrcs = sortedInputSrcs.map(quoteString).join(",");
|
||||||
|
|
||||||
|
const args = drv.args.map(escapeString).join(",");
|
||||||
|
const envs = Array.from(drv.env.entries())
|
||||||
|
.sort(cmpByKey)
|
||||||
|
.map(([k, v]) => `(${escapeString(k)},${escapeString(v)})`);
|
||||||
|
|
||||||
|
return `Derive([${outputs}],[${inputDrvs}],[${inputSrcs}],${quoteString(drv.platform)},${escapeString(drv.builder)},[${args}],[${envs}])`;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const generateAtermModulo = (drv: DerivationData, inputDrvHashes: Map<string, string>): string => {
|
||||||
|
const outputEntries: string[] = [];
|
||||||
|
const sortedOutputs = Array.from(drv.outputs.entries()).sort(cmpByKey);
|
||||||
|
for (const [name, info] of sortedOutputs) {
|
||||||
|
outputEntries.push(
|
||||||
|
`(${quoteString(name)},${quoteString(info.path)},${quoteString(info.hashAlgo)},${quoteString(info.hash)})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const outputs = outputEntries.join(",");
|
||||||
|
|
||||||
|
const inputDrvEntries: string[] = [];
|
||||||
|
const sortedInputDrvHashes = Array.from(inputDrvHashes.entries()).sort(cmpByKey);
|
||||||
|
for (const [drvHash, outputs] of sortedInputDrvHashes) {
|
||||||
|
const sortedOuts = outputs.split(",").sort();
|
||||||
|
const outList = `[${sortedOuts.map(quoteString).join(",")}]`;
|
||||||
|
inputDrvEntries.push(`(${quoteString(drvHash)},${outList})`);
|
||||||
|
}
|
||||||
|
const inputDrvs = inputDrvEntries.join(",");
|
||||||
|
|
||||||
|
const sortedInputSrcs = Array.from(drv.inputSrcs).sort();
|
||||||
|
const inputSrcs = sortedInputSrcs.map(quoteString).join(",");
|
||||||
|
|
||||||
|
const args = drv.args.map(escapeString).join(",");
|
||||||
|
const envs = Array.from(drv.env.entries())
|
||||||
|
.sort(cmpByKey)
|
||||||
|
.map(([k, v]) => `(${escapeString(k)},${escapeString(v)})`);
|
||||||
|
|
||||||
|
return `Derive([${outputs}],[${inputDrvs}],[${inputSrcs}],${quoteString(drv.platform)},${escapeString(drv.builder)},[${args}],[${envs}])`;
|
||||||
|
};
|
||||||
const validateName = (attrs: NixAttrs): string => {
|
const validateName = (attrs: NixAttrs): string => {
|
||||||
if (!("name" in attrs)) {
|
if (!attrs.has("name")) {
|
||||||
throw new Error("derivation: missing required attribute 'name'");
|
throw new Error("derivation: missing required attribute 'name'");
|
||||||
}
|
}
|
||||||
const name = forceStringValue(attrs.name);
|
const name = forceStringValue(attrs.get("name") as NixValue);
|
||||||
if (!name) {
|
if (!name) {
|
||||||
throw new Error("derivation: 'name' cannot be empty");
|
throw new Error("derivation: 'name' cannot be empty");
|
||||||
}
|
}
|
||||||
@@ -43,26 +130,20 @@ const validateName = (attrs: NixAttrs): string => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const validateBuilder = (attrs: NixAttrs, outContext: NixStringContext): string => {
|
const validateBuilder = (attrs: NixAttrs, outContext: NixStringContext): string => {
|
||||||
if (!("builder" in attrs)) {
|
if (!attrs.has("builder")) {
|
||||||
throw new Error("derivation: missing required attribute '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 => {
|
const validateSystem = (attrs: NixAttrs): string => {
|
||||||
if (!("system" in attrs)) {
|
if (!attrs.has("system")) {
|
||||||
throw new Error("derivation: missing required attribute 'system'");
|
throw new Error("derivation: missing required attribute 'system'");
|
||||||
}
|
}
|
||||||
return forceStringValue(attrs.system);
|
return forceStringValue(attrs.get("system") as NixValue);
|
||||||
};
|
};
|
||||||
|
|
||||||
const extractOutputs = (attrs: NixAttrs): string[] => {
|
const validateOutputs = (outputs: string[]): void => {
|
||||||
if (!("outputs" in attrs)) {
|
|
||||||
return ["out"];
|
|
||||||
}
|
|
||||||
const outputsList = forceList(attrs.outputs);
|
|
||||||
const outputs = outputsList.map((o) => forceStringValue(o));
|
|
||||||
|
|
||||||
if (outputs.length === 0) {
|
if (outputs.length === 0) {
|
||||||
throw new Error("derivation: outputs list cannot be empty");
|
throw new Error("derivation: outputs list cannot be empty");
|
||||||
}
|
}
|
||||||
@@ -78,15 +159,39 @@ const extractOutputs = (attrs: NixAttrs): string[] => {
|
|||||||
}
|
}
|
||||||
seen.add(output);
|
seen.add(output);
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const extractOutputs = (attrs: NixAttrs, structuredAttrs: boolean): string[] => {
|
||||||
|
if (!attrs.has("outputs")) {
|
||||||
|
return ["out"];
|
||||||
|
}
|
||||||
|
|
||||||
|
let outputs: string[];
|
||||||
|
if (structuredAttrs) {
|
||||||
|
const outputsList = forceList(attrs.get("outputs") as NixValue);
|
||||||
|
outputs = outputsList.map((o) => forceStringValue(o));
|
||||||
|
} else {
|
||||||
|
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);
|
||||||
return outputs;
|
return outputs;
|
||||||
};
|
};
|
||||||
|
|
||||||
const extractArgs = (attrs: NixAttrs, outContext: NixStringContext): string[] => {
|
const extractArgs = (attrs: NixAttrs, outContext: NixStringContext): string[] => {
|
||||||
if (!("args" in attrs)) {
|
if (!attrs.has("args")) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
const argsList = forceList(attrs.args);
|
const argsList = forceList(attrs.get("args") as NixValue);
|
||||||
return argsList.map((a) => coerceToString(a, StringCoercionMode.ToString, true, outContext));
|
return argsList.map((a) => coerceToString(a, StringCoercionMode.ToString, true, outContext));
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -94,25 +199,15 @@ const structuredAttrsExcludedKeys = new Set([
|
|||||||
"__structuredAttrs",
|
"__structuredAttrs",
|
||||||
"__ignoreNulls",
|
"__ignoreNulls",
|
||||||
"__contentAddressed",
|
"__contentAddressed",
|
||||||
"impure",
|
"__impure",
|
||||||
"args",
|
"args",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const specialAttrs = new Set([
|
const specialAttrs = new Set(["args", "__ignoreNulls", "__contentAddressed", "__impure"]);
|
||||||
"name",
|
|
||||||
"builder",
|
|
||||||
"system",
|
|
||||||
"args",
|
|
||||||
"outputs",
|
|
||||||
"__structuredAttrs",
|
|
||||||
"__ignoreNulls",
|
|
||||||
"__contentAddressed",
|
|
||||||
"impure",
|
|
||||||
]);
|
|
||||||
|
|
||||||
const sortedJsonStringify = (obj: Record<string, any>): string => {
|
const sortedJsonStringify = (obj: Record<string, JsonValue>): string => {
|
||||||
const sortedKeys = Object.keys(obj).sort();
|
const sortedKeys = Object.keys(obj).sort();
|
||||||
const sortedObj: Record<string, any> = {};
|
const sortedObj: Record<string, JsonValue> = {};
|
||||||
for (const key of sortedKeys) {
|
for (const key of sortedKeys) {
|
||||||
sortedObj[key] = obj[key];
|
sortedObj[key] = obj[key];
|
||||||
}
|
}
|
||||||
@@ -129,68 +224,68 @@ const extractEnv = (
|
|||||||
const env = new Map<string, string>();
|
const env = new Map<string, string>();
|
||||||
|
|
||||||
if (structuredAttrs) {
|
if (structuredAttrs) {
|
||||||
const jsonAttrs: Record<string, any> = {};
|
const jsonAttrs: Record<string, JsonValue> = {};
|
||||||
for (const [key, value] of Object.entries(attrs)) {
|
for (const [key, value] of attrs) {
|
||||||
if (!structuredAttrsExcludedKeys.has(key)) {
|
if (!structuredAttrsExcludedKeys.has(key)) {
|
||||||
const forcedValue = force(value);
|
const forcedValue = force(value);
|
||||||
if (ignoreNulls && forcedValue === null) {
|
if (ignoreNulls && forcedValue === null) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
jsonAttrs[key] = nixValueToJson(value, new Set(), outContext);
|
jsonAttrs[key] = nixValueToJson(value, true, outContext, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (key === "allowedReferences") {
|
if (key === "allowedReferences") {
|
||||||
console.warn(
|
console.warn(
|
||||||
`In a derivation named '${drvName}', 'structuredAttrs' disables the effect of ` +
|
`In a derivation named '${drvName}', 'structuredAttrs' disables the effect of ` +
|
||||||
`the derivation attribute 'allowedReferences'; use ` +
|
`the derivation attribute 'allowedReferences'; use ` +
|
||||||
`'outputChecks.<output>.allowedReferences' instead`
|
`'outputChecks.<output>.allowedReferences' instead`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (key === "allowedRequisites") {
|
if (key === "allowedRequisites") {
|
||||||
console.warn(
|
console.warn(
|
||||||
`In a derivation named '${drvName}', 'structuredAttrs' disables the effect of ` +
|
`In a derivation named '${drvName}', 'structuredAttrs' disables the effect of ` +
|
||||||
`the derivation attribute 'allowedRequisites'; use ` +
|
`the derivation attribute 'allowedRequisites'; use ` +
|
||||||
`'outputChecks.<output>.allowedRequisites' instead`
|
`'outputChecks.<output>.allowedRequisites' instead`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (key === "disallowedReferences") {
|
if (key === "disallowedReferences") {
|
||||||
console.warn(
|
console.warn(
|
||||||
`In a derivation named '${drvName}', 'structuredAttrs' disables the effect of ` +
|
`In a derivation named '${drvName}', 'structuredAttrs' disables the effect of ` +
|
||||||
`the derivation attribute 'disallowedReferences'; use ` +
|
`the derivation attribute 'disallowedReferences'; use ` +
|
||||||
`'outputChecks.<output>.disallowedReferences' instead`
|
`'outputChecks.<output>.disallowedReferences' instead`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (key === "disallowedRequisites") {
|
if (key === "disallowedRequisites") {
|
||||||
console.warn(
|
console.warn(
|
||||||
`In a derivation named '${drvName}', 'structuredAttrs' disables the effect of ` +
|
`In a derivation named '${drvName}', 'structuredAttrs' disables the effect of ` +
|
||||||
`the derivation attribute 'disallowedRequisites'; use ` +
|
`the derivation attribute 'disallowedRequisites'; use ` +
|
||||||
`'outputChecks.<output>.disallowedRequisites' instead`
|
`'outputChecks.<output>.disallowedRequisites' instead`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (key === "maxSize") {
|
if (key === "maxSize") {
|
||||||
console.warn(
|
console.warn(
|
||||||
`In a derivation named '${drvName}', 'structuredAttrs' disables the effect of ` +
|
`In a derivation named '${drvName}', 'structuredAttrs' disables the effect of ` +
|
||||||
`the derivation attribute 'maxSize'; use ` +
|
`the derivation attribute 'maxSize'; use ` +
|
||||||
`'outputChecks.<output>.maxSize' instead`
|
`'outputChecks.<output>.maxSize' instead`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (key === "maxClosureSize") {
|
if (key === "maxClosureSize") {
|
||||||
console.warn(
|
console.warn(
|
||||||
`In a derivation named '${drvName}', 'structuredAttrs' disables the effect of ` +
|
`In a derivation named '${drvName}', 'structuredAttrs' disables the effect of ` +
|
||||||
`the derivation attribute 'maxClosureSize'; use ` +
|
`the derivation attribute 'maxClosureSize'; use ` +
|
||||||
`'outputChecks.<output>.maxClosureSize' instead`
|
`'outputChecks.<output>.maxClosureSize' instead`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
env.set("__json", sortedJsonStringify(jsonAttrs));
|
env.set("__json", sortedJsonStringify(jsonAttrs));
|
||||||
} else {
|
} else {
|
||||||
for (const [key, value] of Object.entries(attrs)) {
|
for (const [key, value] of attrs) {
|
||||||
if (!specialAttrs.has(key)) {
|
if (!specialAttrs.has(key)) {
|
||||||
const forcedValue = force(value);
|
const forcedValue = force(value as NixValue);
|
||||||
if (ignoreNulls && forcedValue === null) {
|
if (ignoreNulls && forcedValue === null) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
env.set(key, coerceToString(value, StringCoercionMode.ToString, true, outContext));
|
env.set(key, coerceToString(value as NixValue, StringCoercionMode.ToString, true, outContext));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -205,29 +300,29 @@ interface FixedOutputInfo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const extractFixedOutputInfo = (attrs: NixAttrs, ignoreNulls: boolean): FixedOutputInfo | null => {
|
const extractFixedOutputInfo = (attrs: NixAttrs, ignoreNulls: boolean): FixedOutputInfo | null => {
|
||||||
if (!("outputHash" in attrs)) {
|
if (!attrs.has("outputHash")) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const hashValue = force(attrs.outputHash);
|
const hashValue = force(attrs.get("outputHash") as NixValue);
|
||||||
if (ignoreNulls && hashValue === null) {
|
if (ignoreNulls && hashValue === null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const hash = forceStringValue(attrs.outputHash);
|
const hashRaw = forceStringNoCtx(hashValue);
|
||||||
|
|
||||||
let hashAlgo = "sha256";
|
let hashAlgo = null;
|
||||||
if ("outputHashAlgo" in attrs) {
|
if (attrs.has("outputHashAlgo")) {
|
||||||
const algoValue = force(attrs.outputHashAlgo);
|
const algoValue = force(attrs.get("outputHashAlgo") as NixValue);
|
||||||
if (!(ignoreNulls && algoValue === null)) {
|
if (!(ignoreNulls && algoValue === null)) {
|
||||||
hashAlgo = forceStringValue(attrs.outputHashAlgo);
|
hashAlgo = forceStringNoCtx(algoValue);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let hashMode = "flat";
|
let hashMode = "flat";
|
||||||
if ("outputHashMode" in attrs) {
|
if (attrs.has("outputHashMode")) {
|
||||||
const modeValue = force(attrs.outputHashMode);
|
const modeValue = force(attrs.get("outputHashMode") as NixValue);
|
||||||
if (!(ignoreNulls && modeValue === null)) {
|
if (!(ignoreNulls && modeValue === null)) {
|
||||||
hashMode = forceStringValue(attrs.outputHashMode);
|
hashMode = forceStringValue(modeValue);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -235,7 +330,9 @@ const extractFixedOutputInfo = (attrs: NixAttrs, ignoreNulls: boolean): FixedOut
|
|||||||
throw new Error(`derivation: invalid outputHashMode '${hashMode}' (must be 'flat' or 'recursive')`);
|
throw new Error(`derivation: invalid outputHashMode '${hashMode}' (must be 'flat' or 'recursive')`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return { hash, hashAlgo, hashMode };
|
const parsed = Deno.core.ops.op_parse_hash(hashRaw, hashAlgo);
|
||||||
|
|
||||||
|
return { hash: parsed.hex, hashAlgo: parsed.algo, hashMode };
|
||||||
};
|
};
|
||||||
|
|
||||||
const validateFixedOutputConstraints = (fixedOutput: FixedOutputInfo | null, outputs: string[]) => {
|
const validateFixedOutputConstraints = (fixedOutput: FixedOutputInfo | null, outputs: string[]) => {
|
||||||
@@ -252,200 +349,60 @@ export const derivationStrict = (args: NixValue): NixAttrs => {
|
|||||||
const builder = validateBuilder(attrs, collectedContext);
|
const builder = validateBuilder(attrs, collectedContext);
|
||||||
const platform = validateSystem(attrs);
|
const platform = validateSystem(attrs);
|
||||||
|
|
||||||
const structuredAttrs = "__structuredAttrs" in attrs ? force(attrs.__structuredAttrs) === true : false;
|
const structuredAttrs = attrs.has("__structuredAttrs")
|
||||||
const ignoreNulls = "__ignoreNulls" in attrs ? force(attrs.__ignoreNulls) === true : false;
|
? 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);
|
const outputs = extractOutputs(attrs, structuredAttrs);
|
||||||
const fixedOutputInfo = extractFixedOutputInfo(attrs, ignoreNulls);
|
const fixedOutputInfo = extractFixedOutputInfo(attrs, ignoreNulls);
|
||||||
validateFixedOutputConstraints(fixedOutputInfo, outputs);
|
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");
|
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");
|
throw new Error("impure derivations are not supported");
|
||||||
}
|
}
|
||||||
|
|
||||||
const drvArgs = extractArgs(attrs, collectedContext);
|
const drvArgs = extractArgs(attrs, collectedContext);
|
||||||
const env = extractEnv(attrs, structuredAttrs, ignoreNulls, collectedContext, drvName);
|
const env = extractEnv(attrs, structuredAttrs, ignoreNulls, collectedContext, drvName);
|
||||||
|
|
||||||
if (!structuredAttrs) {
|
const envEntries: [string, string][] = Array.from(env.entries());
|
||||||
env.set("name", drvName);
|
const contextArray: string[] = Array.from(collectedContext);
|
||||||
env.set("builder", builder);
|
|
||||||
env.set("system", platform);
|
|
||||||
if (outputs.length > 1 || outputs[0] !== "out") {
|
|
||||||
env.set("outputs", outputs.join(" "));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const { inputDrvs, inputSrcs } = extractInputDrvsAndSrcs(collectedContext);
|
const rustResult: {
|
||||||
|
drvPath: string;
|
||||||
const collectDrvReferences = (): string[] => {
|
outputs: [string, string][];
|
||||||
const refs = new Set<string>();
|
} = Deno.core.ops.op_finalize_derivation(
|
||||||
for (const src of inputSrcs) {
|
drvName,
|
||||||
refs.add(src);
|
builder,
|
||||||
}
|
platform,
|
||||||
for (const drvPath of inputDrvs.keys()) {
|
outputs,
|
||||||
refs.add(drvPath);
|
drvArgs,
|
||||||
}
|
envEntries,
|
||||||
return Array.from(refs).sort();
|
contextArray,
|
||||||
};
|
fixedOutputInfo,
|
||||||
|
|
||||||
let outputInfos: Map<string, OutputInfo>;
|
|
||||||
let drvPath: string;
|
|
||||||
|
|
||||||
if (fixedOutputInfo) {
|
|
||||||
const pathName = Deno.core.ops.op_output_path_name(drvName, "out");
|
|
||||||
const outPath = Deno.core.ops.op_make_fixed_output_path(
|
|
||||||
fixedOutputInfo.hashAlgo,
|
|
||||||
fixedOutputInfo.hash,
|
|
||||||
fixedOutputInfo.hashMode,
|
|
||||||
pathName,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const hashAlgoPrefix = fixedOutputInfo.hashMode === "recursive" ? "r:" : "";
|
const result: NixAttrs = new Map();
|
||||||
outputInfos = new Map([
|
|
||||||
[
|
|
||||||
"out",
|
|
||||||
{
|
|
||||||
path: outPath,
|
|
||||||
hashAlgo: hashAlgoPrefix + fixedOutputInfo.hashAlgo,
|
|
||||||
hash: fixedOutputInfo.hash,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
]);
|
|
||||||
env.set("out", outPath);
|
|
||||||
|
|
||||||
const finalDrv: DerivationData = {
|
|
||||||
name: drvName,
|
|
||||||
outputs: outputInfos,
|
|
||||||
inputDrvs,
|
|
||||||
inputSrcs,
|
|
||||||
platform,
|
|
||||||
builder,
|
|
||||||
args: drvArgs,
|
|
||||||
env,
|
|
||||||
};
|
|
||||||
const finalAterm = generateAterm(finalDrv);
|
|
||||||
const finalDrvHash = Deno.core.ops.op_sha256_hex(finalAterm);
|
|
||||||
drvPath = Deno.core.ops.op_make_text_store_path(finalDrvHash, `${drvName}.drv`, collectDrvReferences());
|
|
||||||
} else {
|
|
||||||
const maskedOutputs = new Map<string, OutputInfo>(
|
|
||||||
outputs.map((o) => [
|
|
||||||
o,
|
|
||||||
{
|
|
||||||
path: "",
|
|
||||||
hashAlgo: "",
|
|
||||||
hash: "",
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
const maskedEnv = new Map(env);
|
|
||||||
for (const output of outputs) {
|
|
||||||
maskedEnv.set(output, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
const maskedDrv: DerivationData = {
|
|
||||||
name: drvName,
|
|
||||||
outputs: maskedOutputs,
|
|
||||||
inputDrvs,
|
|
||||||
inputSrcs,
|
|
||||||
platform,
|
|
||||||
builder,
|
|
||||||
args: drvArgs,
|
|
||||||
env: maskedEnv,
|
|
||||||
};
|
|
||||||
|
|
||||||
const maskedAterm = generateAterm(maskedDrv);
|
|
||||||
const drvModuloHash = Deno.core.ops.op_sha256_hex(maskedAterm);
|
|
||||||
|
|
||||||
outputInfos = new Map<string, OutputInfo>();
|
|
||||||
for (const outputName of outputs) {
|
|
||||||
const pathName = Deno.core.ops.op_output_path_name(drvName, outputName);
|
|
||||||
const outPath = Deno.core.ops.op_make_store_path(`output:${outputName}`, drvModuloHash, pathName);
|
|
||||||
outputInfos.set(outputName, {
|
|
||||||
path: outPath,
|
|
||||||
hashAlgo: "",
|
|
||||||
hash: "",
|
|
||||||
});
|
|
||||||
env.set(outputName, outPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
const finalDrv: DerivationData = {
|
|
||||||
...maskedDrv,
|
|
||||||
outputs: outputInfos,
|
|
||||||
env,
|
|
||||||
};
|
|
||||||
const finalAterm = generateAterm(finalDrv);
|
|
||||||
const finalDrvHash = Deno.core.ops.op_sha256_hex(finalAterm);
|
|
||||||
|
|
||||||
drvPath = Deno.core.ops.op_make_text_store_path(finalDrvHash, `${drvName}.drv`, collectDrvReferences());
|
|
||||||
}
|
|
||||||
|
|
||||||
const result: NixAttrs = {};
|
|
||||||
|
|
||||||
const drvPathContext = new Set<string>();
|
const drvPathContext = new Set<string>();
|
||||||
addDrvDeepContext(drvPathContext, drvPath);
|
addDrvDeepContext(drvPathContext, rustResult.drvPath);
|
||||||
result.drvPath = mkStringWithContext(drvPath, drvPathContext);
|
result.set("drvPath", mkStringWithContext(rustResult.drvPath, drvPathContext));
|
||||||
|
|
||||||
for (const [outputName, outputInfo] of outputInfos.entries()) {
|
for (const [outputName, outputPath] of rustResult.outputs) {
|
||||||
const outputContext = new Set<string>();
|
const outputContext = new Set<string>();
|
||||||
addBuiltContext(outputContext, drvPath, outputName);
|
addBuiltContext(outputContext, rustResult.drvPath, outputName);
|
||||||
result[outputName] = mkStringWithContext(outputInfo.path, outputContext);
|
result.set(outputName, mkStringWithContext(outputPath, outputContext));
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const derivation = (args: NixValue): NixAttrs => {
|
export const derivationStub = (_: NixValue): NixAttrs => {
|
||||||
const attrs = forceAttrs(args);
|
throw new Error("unreachable: stub derivation implementation called");
|
||||||
|
|
||||||
const outputs: string[] = extractOutputs(attrs);
|
|
||||||
|
|
||||||
const strictThunk = createThunk(() => derivationStrict(args), "derivationStrict");
|
|
||||||
|
|
||||||
const commonAttrs: NixAttrs = { ...attrs };
|
|
||||||
|
|
||||||
const outputToAttrListElement = (outputName: string): { name: string; value: NixAttrs } => {
|
|
||||||
const value: NixAttrs = {
|
|
||||||
...commonAttrs,
|
|
||||||
outPath: createThunk(() => (force(strictThunk) as NixAttrs)[outputName], `outPath_${outputName}`),
|
|
||||||
drvPath: createThunk(() => (force(strictThunk) as NixAttrs).drvPath, "drvPath"),
|
|
||||||
type: "derivation",
|
|
||||||
outputName,
|
|
||||||
};
|
|
||||||
return { name: outputName, value };
|
|
||||||
};
|
|
||||||
|
|
||||||
const outputsList = outputs.map(outputToAttrListElement);
|
|
||||||
|
|
||||||
for (const { name: outputName } of outputsList) {
|
|
||||||
commonAttrs[outputName] = createThunk(
|
|
||||||
() => outputsList.find((o) => o.name === outputName)!.value,
|
|
||||||
`output_${outputName}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
commonAttrs.all = createThunk(
|
|
||||||
() => outputsList.map((o) => o.value),
|
|
||||||
"all_outputs",
|
|
||||||
);
|
|
||||||
commonAttrs.drvAttrs = attrs;
|
|
||||||
|
|
||||||
for (const { value: outputObj } of outputsList) {
|
|
||||||
for (const { name: outputName } of outputsList) {
|
|
||||||
outputObj[outputName] = createThunk(
|
|
||||||
() => outputsList.find((o) => o.name === outputName)!.value,
|
|
||||||
`output_${outputName}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
outputObj.all = createThunk(
|
|
||||||
() => outputsList.map((o) => o.value),
|
|
||||||
"all_outputs",
|
|
||||||
);
|
|
||||||
outputObj.drvAttrs = attrs;
|
|
||||||
}
|
|
||||||
|
|
||||||
return outputsList[0].value;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
17
nix-js/runtime-ts/src/builtins/flake.ts
Normal file
17
nix-js/runtime-ts/src/builtins/flake.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import type { NixValue } from "../types";
|
||||||
|
|
||||||
|
export const getFlake = (_attrs: NixValue): never => {
|
||||||
|
throw new Error("Not implemented: getFlake");
|
||||||
|
};
|
||||||
|
|
||||||
|
export const parseFlakeName = (_s: NixValue): never => {
|
||||||
|
throw new Error("Not implemented: parseFlakeName");
|
||||||
|
};
|
||||||
|
|
||||||
|
export const parseFlakeRef = (_s: NixValue): never => {
|
||||||
|
throw new Error("Not implemented: parseFlakeRef");
|
||||||
|
};
|
||||||
|
|
||||||
|
export const flakeRefToString = (_attrs: NixValue): never => {
|
||||||
|
throw new Error("Not implemented: flakeRefToString");
|
||||||
|
};
|
||||||
@@ -1,11 +1,8 @@
|
|||||||
/**
|
|
||||||
* Functional programming builtin functions
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { CatchableError, HAS_CONTEXT, type NixValue } from "../types";
|
|
||||||
import { force } from "../thunk";
|
|
||||||
import { coerceToString, StringCoercionMode } from "./conversion";
|
|
||||||
import { printValue } from "../print";
|
import { printValue } from "../print";
|
||||||
|
import { force } from "../thunk";
|
||||||
|
import { CatchableError, type NixValue } from "../types";
|
||||||
|
import { coerceToString, StringCoercionMode } from "./conversion";
|
||||||
|
import { isAttrs } from "./type-check";
|
||||||
|
|
||||||
export const seq =
|
export const seq =
|
||||||
(e1: NixValue) =>
|
(e1: NixValue) =>
|
||||||
@@ -17,16 +14,25 @@ export const seq =
|
|||||||
export const deepSeq =
|
export const deepSeq =
|
||||||
(e1: NixValue) =>
|
(e1: NixValue) =>
|
||||||
(e2: NixValue): NixValue => {
|
(e2: NixValue): NixValue => {
|
||||||
const forced = force(e1);
|
const seen: Set<NixValue> = new Set();
|
||||||
|
const recurse = (e: NixValue) => {
|
||||||
|
if (!seen.has(e)) {
|
||||||
|
seen.add(e);
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const forced = force(e);
|
||||||
if (Array.isArray(forced)) {
|
if (Array.isArray(forced)) {
|
||||||
for (const val of forced) {
|
for (const val of forced) {
|
||||||
deepSeq(val);
|
recurse(val);
|
||||||
}
|
}
|
||||||
} else if (typeof forced === "object" && forced !== null && !(HAS_CONTEXT in forced)) {
|
} else if (isAttrs(forced)) {
|
||||||
for (const [_, val] of Object.entries(forced)) {
|
for (const [_, val] of forced.entries()) {
|
||||||
deepSeq(val);
|
recurse(val);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
recurse(e1);
|
||||||
return e2;
|
return e2;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -35,7 +41,7 @@ export const abort = (s: NixValue): never => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const throwFunc = (s: NixValue): never => {
|
export const throwFunc = (s: NixValue): never => {
|
||||||
throw new CatchableError(coerceToString(s, StringCoercionMode.Base));
|
throw new CatchableError(coerceToString(s, StringCoercionMode.Base, false, new Set()));
|
||||||
};
|
};
|
||||||
|
|
||||||
export const trace =
|
export const trace =
|
||||||
|
|||||||
34
nix-js/runtime-ts/src/builtins/hash.ts
Normal file
34
nix-js/runtime-ts/src/builtins/hash.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { select } from "../helpers";
|
||||||
|
import { forceAttrs, forceStringNoCtx, forceStringValue } from "../type-assert";
|
||||||
|
import type { NixValue } from "../types";
|
||||||
|
import { realisePath } from "./io";
|
||||||
|
|
||||||
|
export const hashFile =
|
||||||
|
(type: NixValue) =>
|
||||||
|
(p: NixValue): string => {
|
||||||
|
const algo = forceStringNoCtx(type);
|
||||||
|
const pathStr = realisePath(p);
|
||||||
|
return Deno.core.ops.op_hash_file(algo, pathStr);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const hashString =
|
||||||
|
(type: NixValue) =>
|
||||||
|
(s: NixValue): string => {
|
||||||
|
const algo = forceStringNoCtx(type);
|
||||||
|
const data = forceStringValue(s);
|
||||||
|
return Deno.core.ops.op_hash_string(algo, data);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const convertHash = (args: NixValue): string => {
|
||||||
|
const attrs = forceAttrs(args);
|
||||||
|
const hash = forceStringNoCtx(select(attrs, ["hash"]));
|
||||||
|
|
||||||
|
let hashAlgo: string | null = null;
|
||||||
|
if (attrs.has("hashAlgo")) {
|
||||||
|
hashAlgo = forceStringNoCtx(select(attrs, ["hashAlgo"]));
|
||||||
|
}
|
||||||
|
|
||||||
|
const toHashFormat = forceStringNoCtx(select(attrs, ["toHashFormat"]));
|
||||||
|
|
||||||
|
return Deno.core.ops.op_convert_hash(hash, hashAlgo, toHashFormat);
|
||||||
|
};
|
||||||
@@ -1,85 +1,54 @@
|
|||||||
/**
|
import { createThunk, force } from "../thunk";
|
||||||
* Main builtins export
|
import type { NixAttrs, NixFunction, NixValue } from "../types";
|
||||||
* Combines all builtin function categories into the global `builtins` object
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Import all builtin categories
|
|
||||||
import * as arithmetic from "./arithmetic";
|
import * as arithmetic from "./arithmetic";
|
||||||
import * as math from "./math";
|
|
||||||
import * as typeCheck from "./type-check";
|
|
||||||
import * as list from "./list";
|
|
||||||
import * as attrs from "./attrs";
|
import * as attrs from "./attrs";
|
||||||
import * as string from "./string";
|
|
||||||
import * as pathOps from "./path";
|
|
||||||
import * as functional from "./functional";
|
|
||||||
import * as io from "./io";
|
|
||||||
import * as conversion from "./conversion";
|
import * as conversion from "./conversion";
|
||||||
import * as misc from "./misc";
|
|
||||||
import * as derivation from "./derivation";
|
import * as derivation from "./derivation";
|
||||||
|
import * as flake from "./flake";
|
||||||
|
import * as functional from "./functional";
|
||||||
|
import * as hash from "./hash";
|
||||||
|
import * as io from "./io";
|
||||||
|
import * as list from "./list";
|
||||||
|
import * as math from "./math";
|
||||||
|
import * as misc from "./misc";
|
||||||
|
import * as pathOps from "./path";
|
||||||
|
import * as string from "./string";
|
||||||
|
import * as typeCheck from "./type-check";
|
||||||
|
|
||||||
import type { NixValue } from "../types";
|
|
||||||
import { createThunk, force, isThunk } from "../thunk";
|
|
||||||
import { getTos } from "../helpers";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Symbol used to mark functions as primops (primitive operations)
|
|
||||||
* This is similar to IS_THUNK but for builtin functions
|
|
||||||
*/
|
|
||||||
export const PRIMOP_METADATA = Symbol("primop_metadata");
|
export const PRIMOP_METADATA = Symbol("primop_metadata");
|
||||||
|
|
||||||
/**
|
|
||||||
* Metadata interface for primop functions
|
|
||||||
*/
|
|
||||||
export interface PrimopMetadata {
|
export interface PrimopMetadata {
|
||||||
/** The name of the primop (e.g., "add", "map") */
|
|
||||||
name: string;
|
name: string;
|
||||||
/** Total arity of the function (number of arguments it expects) */
|
|
||||||
arity: number;
|
arity: number;
|
||||||
/** Number of arguments already applied (for partial applications) */
|
|
||||||
applied: number;
|
applied: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Mark a function as a primop with metadata
|
|
||||||
* For curried functions, this recursively marks each layer
|
|
||||||
*
|
|
||||||
* @param func - The function to mark
|
|
||||||
* @param name - Name of the primop
|
|
||||||
* @param arity - Total number of arguments expected
|
|
||||||
* @param applied - Number of arguments already applied (default: 0)
|
|
||||||
* @returns The marked function
|
|
||||||
*/
|
|
||||||
export const mkPrimop = (
|
export const mkPrimop = (
|
||||||
func: (...args: NixValue[]) => NixValue,
|
func: NixFunction,
|
||||||
name: string,
|
name: string,
|
||||||
arity: number,
|
arity: number,
|
||||||
applied: number = 0,
|
applied: number = 0,
|
||||||
): Function => {
|
): ((...args: NixValue[]) => NixValue) => {
|
||||||
// Mark this function as a primop
|
func[PRIMOP_METADATA] = {
|
||||||
(func as any)[PRIMOP_METADATA] = {
|
|
||||||
name,
|
name,
|
||||||
arity,
|
arity,
|
||||||
applied,
|
applied,
|
||||||
} satisfies PrimopMetadata;
|
} satisfies PrimopMetadata;
|
||||||
|
|
||||||
// If this is a curried function and not fully applied,
|
|
||||||
// wrap it to mark the next layer too
|
|
||||||
if (applied < arity - 1) {
|
if (applied < arity - 1) {
|
||||||
const wrappedFunc = ((...args: NixValue[]) => {
|
const wrappedFunc: NixFunction = ((arg: NixValue) => {
|
||||||
const result = func(...args);
|
const result = func(arg);
|
||||||
// If result is a function, mark it as the next layer
|
|
||||||
if (typeof result === "function") {
|
if (typeof result === "function") {
|
||||||
return mkPrimop(result, name, arity, applied + args.length);
|
return mkPrimop(result, name, arity, applied + 1);
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}) as any;
|
});
|
||||||
|
|
||||||
// Copy the primop metadata to the wrapper
|
|
||||||
wrappedFunc[PRIMOP_METADATA] = {
|
wrappedFunc[PRIMOP_METADATA] = {
|
||||||
name,
|
name,
|
||||||
arity,
|
arity,
|
||||||
applied,
|
applied,
|
||||||
} satisfies PrimopMetadata;
|
};
|
||||||
|
|
||||||
return wrappedFunc;
|
return wrappedFunc;
|
||||||
}
|
}
|
||||||
@@ -87,12 +56,9 @@ export const mkPrimop = (
|
|||||||
return func;
|
return func;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
export const isPrimop = (
|
||||||
* Type guard to check if a value is a primop
|
value: NixValue,
|
||||||
* @param value - Value to check
|
): value is NixFunction & { [PRIMOP_METADATA]: PrimopMetadata } => {
|
||||||
* @returns true if value is marked as a primop
|
|
||||||
*/
|
|
||||||
export const is_primop = (value: unknown): value is Function & { [PRIMOP_METADATA]: PrimopMetadata } => {
|
|
||||||
return (
|
return (
|
||||||
typeof value === "function" &&
|
typeof value === "function" &&
|
||||||
PRIMOP_METADATA in value &&
|
PRIMOP_METADATA in value &&
|
||||||
@@ -101,29 +67,15 @@ export const is_primop = (value: unknown): value is Function & { [PRIMOP_METADAT
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
export const getPrimopMetadata = (func: NixValue): PrimopMetadata | undefined => {
|
||||||
* Get primop metadata from a function
|
if (isPrimop(func)) {
|
||||||
* @param func - Function to get metadata from
|
|
||||||
* @returns Metadata if function is a primop, undefined otherwise
|
|
||||||
*/
|
|
||||||
export const get_primop_metadata = (func: unknown): PrimopMetadata | undefined => {
|
|
||||||
if (is_primop(func)) {
|
|
||||||
return func[PRIMOP_METADATA];
|
return func[PRIMOP_METADATA];
|
||||||
}
|
}
|
||||||
return undefined;
|
return undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
export const builtins: NixAttrs = new Map<string, NixValue>(
|
||||||
* The global builtins object
|
Object.entries({
|
||||||
* Contains 80+ Nix builtin functions plus metadata
|
|
||||||
*
|
|
||||||
* All functions are curried for Nix semantics:
|
|
||||||
* - Single argument functions: (a) => result
|
|
||||||
* - Multi-argument functions: (a) => (b) => result
|
|
||||||
*
|
|
||||||
* All primop functions are marked with PRIMOP_METADATA symbol for runtime introspection
|
|
||||||
*/
|
|
||||||
export const builtins: any = {
|
|
||||||
add: mkPrimop(arithmetic.add, "add", 2),
|
add: mkPrimop(arithmetic.add, "add", 2),
|
||||||
sub: mkPrimop(arithmetic.sub, "sub", 2),
|
sub: mkPrimop(arithmetic.sub, "sub", 2),
|
||||||
mul: mkPrimop(arithmetic.mul, "mul", 2),
|
mul: mkPrimop(arithmetic.mul, "mul", 2),
|
||||||
@@ -193,7 +145,7 @@ export const builtins: any = {
|
|||||||
warn: mkPrimop(functional.warn, "warn", 2),
|
warn: mkPrimop(functional.warn, "warn", 2),
|
||||||
break: mkPrimop(functional.breakFunc, "break", 1),
|
break: mkPrimop(functional.breakFunc, "break", 1),
|
||||||
|
|
||||||
derivation: mkPrimop(derivation.derivation, "derivation", 1),
|
derivation: mkPrimop(derivation.derivationStub, "derivation", 1),
|
||||||
derivationStrict: mkPrimop(derivation.derivationStrict, "derivationStrict", 1),
|
derivationStrict: mkPrimop(derivation.derivationStrict, "derivationStrict", 1),
|
||||||
|
|
||||||
import: mkPrimop(io.importFunc, "import", 1),
|
import: mkPrimop(io.importFunc, "import", 1),
|
||||||
@@ -221,13 +173,19 @@ export const builtins: any = {
|
|||||||
toXML: mkPrimop(conversion.toXML, "toXML", 1),
|
toXML: mkPrimop(conversion.toXML, "toXML", 1),
|
||||||
toString: mkPrimop(conversion.toStringFunc, "toString", 1),
|
toString: mkPrimop(conversion.toStringFunc, "toString", 1),
|
||||||
|
|
||||||
|
hashFile: mkPrimop(hash.hashFile, "hashFile", 2),
|
||||||
|
hashString: mkPrimop(hash.hashString, "hashString", 2),
|
||||||
|
convertHash: mkPrimop(hash.convertHash, "convertHash", 2),
|
||||||
|
|
||||||
|
flakeRefToString: mkPrimop(flake.flakeRefToString, "flakeRefToString", 1),
|
||||||
|
getFlake: mkPrimop(flake.getFlake, "getFlake", 1),
|
||||||
|
parseFlakeName: mkPrimop(flake.parseFlakeName, "parseFlakeName", 1),
|
||||||
|
parseFlakeRef: mkPrimop(flake.parseFlakeRef, "parseFlakeRef", 1),
|
||||||
|
|
||||||
addErrorContext: mkPrimop(misc.addErrorContext, "addErrorContext", 1),
|
addErrorContext: mkPrimop(misc.addErrorContext, "addErrorContext", 1),
|
||||||
appendContext: mkPrimop(misc.appendContext, "appendContext", 1),
|
appendContext: mkPrimop(misc.appendContext, "appendContext", 1),
|
||||||
getContext: mkPrimop(misc.getContext, "getContext", 1),
|
getContext: mkPrimop(misc.getContext, "getContext", 1),
|
||||||
hasContext: mkPrimop(misc.hasContext, "hasContext", 1),
|
hasContext: mkPrimop(misc.hasContext, "hasContext", 1),
|
||||||
hashFile: mkPrimop(misc.hashFile, "hashFile", 2),
|
|
||||||
hashString: mkPrimop(misc.hashString, "hashString", 2),
|
|
||||||
convertHash: mkPrimop(misc.convertHash, "convertHash", 2),
|
|
||||||
unsafeDiscardOutputDependency: mkPrimop(
|
unsafeDiscardOutputDependency: mkPrimop(
|
||||||
misc.unsafeDiscardOutputDependency,
|
misc.unsafeDiscardOutputDependency,
|
||||||
"unsafeDiscardOutputDependency",
|
"unsafeDiscardOutputDependency",
|
||||||
@@ -236,14 +194,10 @@ export const builtins: any = {
|
|||||||
unsafeDiscardStringContext: mkPrimop(misc.unsafeDiscardStringContext, "unsafeDiscardStringContext", 1),
|
unsafeDiscardStringContext: mkPrimop(misc.unsafeDiscardStringContext, "unsafeDiscardStringContext", 1),
|
||||||
addDrvOutputDependencies: mkPrimop(misc.addDrvOutputDependencies, "addDrvOutputDependencies", 2),
|
addDrvOutputDependencies: mkPrimop(misc.addDrvOutputDependencies, "addDrvOutputDependencies", 2),
|
||||||
compareVersions: mkPrimop(misc.compareVersions, "compareVersions", 2),
|
compareVersions: mkPrimop(misc.compareVersions, "compareVersions", 2),
|
||||||
flakeRefToString: mkPrimop(misc.flakeRefToString, "flakeRefToString", 1),
|
|
||||||
functionArgs: mkPrimop(misc.functionArgs, "functionArgs", 1),
|
functionArgs: mkPrimop(misc.functionArgs, "functionArgs", 1),
|
||||||
genericClosure: mkPrimop(misc.genericClosure, "genericClosure", 1),
|
genericClosure: mkPrimop(misc.genericClosure, "genericClosure", 1),
|
||||||
getFlake: mkPrimop(misc.getFlake, "getFlake", 1),
|
|
||||||
outputOf: mkPrimop(misc.outputOf, "outputOf", 2),
|
outputOf: mkPrimop(misc.outputOf, "outputOf", 2),
|
||||||
parseDrvName: mkPrimop(misc.parseDrvName, "parseDrvName", 1),
|
parseDrvName: mkPrimop(misc.parseDrvName, "parseDrvName", 1),
|
||||||
parseFlakeName: mkPrimop(misc.parseFlakeName, "parseFlakeName", 1),
|
|
||||||
parseFlakeRef: mkPrimop(misc.parseFlakeRef, "parseFlakeRef", 1),
|
|
||||||
placeholder: mkPrimop(misc.placeholder, "placeholder", 1),
|
placeholder: mkPrimop(misc.placeholder, "placeholder", 1),
|
||||||
replaceStrings: mkPrimop(misc.replaceStrings, "replaceStrings", 3),
|
replaceStrings: mkPrimop(misc.replaceStrings, "replaceStrings", 3),
|
||||||
splitVersion: mkPrimop(misc.splitVersion, "splitVersion", 1),
|
splitVersion: mkPrimop(misc.splitVersion, "splitVersion", 1),
|
||||||
@@ -263,10 +217,8 @@ export const builtins: any = {
|
|||||||
langVersion: 6,
|
langVersion: 6,
|
||||||
nixPath: [],
|
nixPath: [],
|
||||||
nixVersion: "2.31.2",
|
nixVersion: "2.31.2",
|
||||||
storeDir: "INVALID_PATH",
|
storeDir: createThunk(() => {
|
||||||
|
throw new Error("stub storeDir evaluated");
|
||||||
__traceCaller: (e: NixValue) => {
|
}),
|
||||||
console.log(`traceCaller: ${getTos()}`)
|
}),
|
||||||
return e
|
);
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,44 +1,57 @@
|
|||||||
/**
|
import { select } from "../helpers";
|
||||||
* I/O and filesystem builtin functions
|
|
||||||
* Implemented via Rust ops exposed through deno_core
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { forceAttrs, forceBool, forceFunction, forceList, forceStringNoCtx, forceStringValue } from "../type-assert";
|
|
||||||
import type { NixValue, NixAttrs, NixPath } from "../types";
|
|
||||||
import { isNixPath, IS_PATH, CatchableError } from "../types";
|
|
||||||
import { force } from "../thunk";
|
|
||||||
import { coerceToPath, coerceToString, StringCoercionMode } from "./conversion";
|
|
||||||
import { getPathValue } from "../path";
|
import { getPathValue } from "../path";
|
||||||
import type { NixStringContext, StringWithContext } from "../string-context";
|
import type { NixStringContext, StringWithContext } from "../string-context";
|
||||||
import { mkStringWithContext } from "../string-context";
|
import { addOpaqueContext, decodeContextElem, mkStringWithContext } from "../string-context";
|
||||||
import { isPath } from "./type-check";
|
import { force } from "../thunk";
|
||||||
|
import {
|
||||||
|
forceAttrs,
|
||||||
|
forceBool,
|
||||||
|
forceFunction,
|
||||||
|
forceList,
|
||||||
|
forceStringNoCtx,
|
||||||
|
forceStringValue,
|
||||||
|
} from "../type-assert";
|
||||||
|
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>();
|
const importCache = new Map<string, NixValue>();
|
||||||
|
|
||||||
export const importFunc = (path: NixValue): NixValue => {
|
const realiseContext = (context: NixStringContext): void => {
|
||||||
const context: NixStringContext = new Set();
|
for (const encoded of context) {
|
||||||
const pathStr = coerceToPath(path, context);
|
const elem = decodeContextElem(encoded);
|
||||||
|
if (elem.type === "built") {
|
||||||
// FIXME: Context collected but not yet propagated to build system
|
throw new Error(
|
||||||
// This means derivation dependencies from imported paths are not
|
`cannot build derivation '${elem.drvPath}' during evaluation because import-from-derivation is not supported`,
|
||||||
// currently tracked. This will cause issues when:
|
|
||||||
// 1. Importing from derivation outputs: import "${drv}/file.nix"
|
|
||||||
// 2. Building packages that depend on imported configurations
|
|
||||||
if (context.size > 0) {
|
|
||||||
console.warn(
|
|
||||||
`[WARN] import: Path has string context which is not yet fully tracked.
|
|
||||||
Dependency tracking for imported derivations may be incomplete.`,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const realisePath = (value: NixValue): string => {
|
||||||
|
const context: NixStringContext = new Set();
|
||||||
|
const pathStr = coerceToPath(value, context);
|
||||||
|
|
||||||
|
if (context.size > 0) {
|
||||||
|
realiseContext(context);
|
||||||
|
}
|
||||||
|
|
||||||
|
return pathStr;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const importFunc = (path: NixValue): NixValue => {
|
||||||
|
const pathStr = realisePath(path);
|
||||||
|
|
||||||
const cached = importCache.get(pathStr);
|
const cached = importCache.get(pathStr);
|
||||||
if (cached !== undefined) {
|
if (cached !== undefined) {
|
||||||
return cached;
|
return cached;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call Rust op - returns JS code string
|
const [code, currentDir] = Deno.core.ops.op_import(pathStr);
|
||||||
const code = Deno.core.ops.op_import(pathStr);
|
const result = execBytecode(code, currentDir);
|
||||||
const result = Function(`return (${code})`)();
|
|
||||||
|
|
||||||
importCache.set(pathStr, result);
|
importCache.set(pathStr, result);
|
||||||
return result;
|
return result;
|
||||||
@@ -46,8 +59,14 @@ Dependency tracking for imported derivations may be incomplete.`,
|
|||||||
|
|
||||||
export const scopedImport =
|
export const scopedImport =
|
||||||
(scope: NixValue) =>
|
(scope: NixValue) =>
|
||||||
(path: NixValue): never => {
|
(path: NixValue): NixValue => {
|
||||||
throw new Error("Not implemented: scopedImport");
|
const scopeAttrs = forceAttrs(scope);
|
||||||
|
const scopeKeys = Array.from(scopeAttrs.keys());
|
||||||
|
|
||||||
|
const pathStr = realisePath(path);
|
||||||
|
|
||||||
|
const [code, currentDir] = Deno.core.ops.op_scoped_import(pathStr, scopeKeys);
|
||||||
|
return execBytecodeScoped(code, currentDir, scopeAttrs);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const storePath = (pathArg: NixValue): StringWithContext => {
|
export const storePath = (pathArg: NixValue): StringWithContext => {
|
||||||
@@ -60,38 +79,29 @@ export const storePath = (pathArg: NixValue): StringWithContext => {
|
|||||||
return mkStringWithContext(validatedPath, context);
|
return mkStringWithContext(validatedPath, context);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const fetchClosure = (args: NixValue): never => {
|
export const fetchClosure = (_args: NixValue): never => {
|
||||||
throw new Error("Not implemented: fetchClosure");
|
throw new Error("Not implemented: fetchClosure");
|
||||||
};
|
};
|
||||||
|
|
||||||
interface FetchUrlResult {
|
export interface FetchUrlResult {
|
||||||
store_path: string;
|
storePath: string;
|
||||||
hash: string;
|
hash: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface FetchTarballResult {
|
export interface FetchTarballResult {
|
||||||
store_path: string;
|
storePath: string;
|
||||||
hash: string;
|
narHash: string;
|
||||||
nar_hash: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface FetchGitResult {
|
export interface FetchGitResult {
|
||||||
out_path: string;
|
outPath: string;
|
||||||
rev: string;
|
rev: string;
|
||||||
short_rev: string;
|
shortRev: string;
|
||||||
rev_count: number;
|
revCount: number;
|
||||||
last_modified: number;
|
lastModified: number;
|
||||||
last_modified_date: string;
|
lastModifiedDate: string;
|
||||||
submodules: boolean;
|
submodules: boolean;
|
||||||
nar_hash: string | null;
|
narHash: string | null;
|
||||||
}
|
|
||||||
|
|
||||||
interface FetchHgResult {
|
|
||||||
out_path: string;
|
|
||||||
branch: string;
|
|
||||||
rev: string;
|
|
||||||
short_rev: string;
|
|
||||||
rev_count: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const normalizeUrlInput = (
|
const normalizeUrlInput = (
|
||||||
@@ -102,39 +112,39 @@ const normalizeUrlInput = (
|
|||||||
return { url: forced };
|
return { url: forced };
|
||||||
}
|
}
|
||||||
const attrs = forceAttrs(args);
|
const attrs = forceAttrs(args);
|
||||||
const url = forceStringValue(attrs.url);
|
const url = forceStringValue(select(attrs, ["url"]));
|
||||||
const hash =
|
const hash = attrs.has("sha256")
|
||||||
"sha256" in attrs
|
? forceStringValue(attrs.get("sha256") as NixValue)
|
||||||
? forceStringValue(attrs.sha256)
|
: attrs.has("hash")
|
||||||
: "hash" in attrs
|
? forceStringValue(attrs.get("hash") as NixValue)
|
||||||
? forceStringValue(attrs.hash)
|
|
||||||
: undefined;
|
: undefined;
|
||||||
const name = "name" in attrs ? forceStringValue(attrs.name) : undefined;
|
const name = attrs.has("name") ? forceStringValue(attrs.get("name") as NixValue) : undefined;
|
||||||
const executable = "executable" in attrs ? forceBool(attrs.executable) : false;
|
const executable = attrs.has("executable") ? forceBool(attrs.get("executable") as NixValue) : false;
|
||||||
return { url, hash, name, executable };
|
return { url, hash, name, executable };
|
||||||
};
|
};
|
||||||
|
|
||||||
const normalizeTarballInput = (
|
const normalizeTarballInput = (args: NixValue): { url: string; sha256?: string; name?: string } => {
|
||||||
args: NixValue,
|
|
||||||
): { url: string; hash?: string; narHash?: string; name?: string } => {
|
|
||||||
const forced = force(args);
|
const forced = force(args);
|
||||||
if (typeof forced === "string") {
|
if (isAttrs(forced)) {
|
||||||
return { url: forced };
|
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 {
|
||||||
|
return { url: forceStringNoCtx(forced) };
|
||||||
}
|
}
|
||||||
const attrs = forceAttrs(args);
|
|
||||||
const url = forceStringValue(attrs.url);
|
|
||||||
const hash = "hash" in attrs ? forceStringValue(attrs.hash) : undefined;
|
|
||||||
const narHash =
|
|
||||||
"narHash" in attrs
|
|
||||||
? forceStringValue(attrs.narHash)
|
|
||||||
: "sha256" in attrs
|
|
||||||
? forceStringValue(attrs.sha256)
|
|
||||||
: undefined;
|
|
||||||
const name = "name" in attrs ? forceStringValue(attrs.name) : undefined;
|
|
||||||
return { url, hash, narHash, name };
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const fetchurl = (args: NixValue): string => {
|
const resolvePseudoUrl = (url: string) => {
|
||||||
|
if (url.startsWith("channel:")) {
|
||||||
|
return `https://channels.nixos.org/${url.substring(8)}/nixexprs.tar.xz`;
|
||||||
|
} else {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const fetchurl = (args: NixValue): NixString => {
|
||||||
const { url, hash, name, executable } = normalizeUrlInput(args);
|
const { url, hash, name, executable } = normalizeUrlInput(args);
|
||||||
const result: FetchUrlResult = Deno.core.ops.op_fetch_url(
|
const result: FetchUrlResult = Deno.core.ops.op_fetch_url(
|
||||||
url,
|
url,
|
||||||
@@ -142,44 +152,46 @@ export const fetchurl = (args: NixValue): string => {
|
|||||||
name ?? null,
|
name ?? null,
|
||||||
executable ?? false,
|
executable ?? false,
|
||||||
);
|
);
|
||||||
return result.store_path;
|
const context: NixStringContext = new Set();
|
||||||
|
addOpaqueContext(context, result.storePath);
|
||||||
|
return mkStringWithContext(result.storePath, context);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const fetchTarball = (args: NixValue): string => {
|
export const fetchTarball = (args: NixValue): NixString => {
|
||||||
const { url, hash, narHash, name } = normalizeTarballInput(args);
|
const { url, name, sha256 } = normalizeTarballInput(args);
|
||||||
const result: FetchTarballResult = Deno.core.ops.op_fetch_tarball(
|
const result: FetchTarballResult = Deno.core.ops.op_fetch_tarball(url, name ?? null, sha256 ?? null);
|
||||||
url,
|
const context: NixStringContext = new Set();
|
||||||
hash ?? null,
|
addOpaqueContext(context, result.storePath);
|
||||||
narHash ?? null,
|
return mkStringWithContext(result.storePath, context);
|
||||||
name ?? null,
|
|
||||||
);
|
|
||||||
return result.store_path;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const fetchGit = (args: NixValue): NixAttrs => {
|
export const fetchGit = (args: NixValue): NixAttrs => {
|
||||||
const forced = force(args);
|
const forced = force(args);
|
||||||
if (typeof forced === "string" || isPath(forced)) {
|
const disposedContext: NixStringContext = new Set();
|
||||||
const path = coerceToPath(forced);
|
if (isString(forced) || isPath(forced)) {
|
||||||
const result: FetchGitResult = Deno.core.ops.op_fetch_git(path, null, null, false, false, false, null);
|
const url = coerceToString(forced, StringCoercionMode.Base, false, disposedContext);
|
||||||
return {
|
const result = Deno.core.ops.op_fetch_git(url, null, null, false, false, false, null);
|
||||||
outPath: result.out_path,
|
const outContext: NixStringContext = new Set();
|
||||||
rev: result.rev,
|
addOpaqueContext(outContext, result.outPath);
|
||||||
shortRev: result.short_rev,
|
return new Map<string, NixValue>([
|
||||||
revCount: BigInt(result.rev_count),
|
["outPath", mkStringWithContext(result.outPath, outContext)],
|
||||||
lastModified: BigInt(result.last_modified),
|
["rev", result.rev],
|
||||||
lastModifiedDate: result.last_modified_date,
|
["shortRev", result.shortRev],
|
||||||
submodules: result.submodules,
|
["revCount", BigInt(result.revCount)],
|
||||||
narHash: result.nar_hash,
|
["lastModified", BigInt(result.lastModified)],
|
||||||
};
|
["lastModifiedDate", result.lastModifiedDate],
|
||||||
|
["submodules", result.submodules],
|
||||||
|
["narHash", result.narHash],
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
const attrs = forceAttrs(args);
|
const attrs = forceAttrs(args);
|
||||||
const url = forceStringValue(attrs.url);
|
const url = forceStringValue(select(attrs, ["url"]));
|
||||||
const gitRef = "ref" in attrs ? forceStringValue(attrs.ref) : null;
|
const gitRef = attrs.has("ref") ? forceStringValue(attrs.get("ref") as NixValue) : null;
|
||||||
const rev = "rev" in attrs ? forceStringValue(attrs.rev) : null;
|
const rev = attrs.has("rev") ? forceStringValue(attrs.get("rev") as NixValue) : null;
|
||||||
const shallow = "shallow" in attrs ? forceBool(attrs.shallow) : false;
|
const shallow = attrs.has("shallow") ? forceBool(attrs.get("shallow") as NixValue) : false;
|
||||||
const submodules = "submodules" in attrs ? forceBool(attrs.submodules) : false;
|
const submodules = attrs.has("submodules") ? forceBool(attrs.get("submodules") as NixValue) : false;
|
||||||
const allRefs = "allRefs" in attrs ? forceBool(attrs.allRefs) : false;
|
const allRefs = attrs.has("allRefs") ? forceBool(attrs.get("allRefs") as NixValue) : false;
|
||||||
const name = "name" in attrs ? forceStringValue(attrs.name) : null;
|
const name = attrs.has("name") ? forceStringValue(attrs.get("name") as NixValue) : null;
|
||||||
|
|
||||||
const result: FetchGitResult = Deno.core.ops.op_fetch_git(
|
const result: FetchGitResult = Deno.core.ops.op_fetch_git(
|
||||||
url,
|
url,
|
||||||
@@ -191,38 +203,27 @@ export const fetchGit = (args: NixValue): NixAttrs => {
|
|||||||
name,
|
name,
|
||||||
);
|
);
|
||||||
|
|
||||||
return {
|
const outContext: NixStringContext = new Set();
|
||||||
outPath: result.out_path,
|
addOpaqueContext(outContext, result.outPath);
|
||||||
rev: result.rev,
|
return new Map<string, NixValue>([
|
||||||
shortRev: result.short_rev,
|
["outPath", mkStringWithContext(result.outPath, outContext)],
|
||||||
revCount: BigInt(result.rev_count),
|
["rev", result.rev],
|
||||||
lastModified: BigInt(result.last_modified),
|
["shortRev", result.shortRev],
|
||||||
lastModifiedDate: result.last_modified_date,
|
["revCount", BigInt(result.revCount)],
|
||||||
submodules: result.submodules,
|
["lastModified", BigInt(result.lastModified)],
|
||||||
narHash: result.nar_hash,
|
["lastModifiedDate", result.lastModifiedDate],
|
||||||
};
|
["submodules", result.submodules],
|
||||||
|
["narHash", result.narHash],
|
||||||
|
]);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const fetchMercurial = (args: NixValue): NixAttrs => {
|
export const fetchMercurial = (_args: NixValue): NixAttrs => {
|
||||||
const attrs = forceAttrs(args);
|
throw new Error("Not implemented: fetchMercurial");
|
||||||
const url = forceStringValue(attrs.url);
|
|
||||||
const rev = "rev" in attrs ? forceStringValue(attrs.rev) : null;
|
|
||||||
const name = "name" in attrs ? forceStringValue(attrs.name) : null;
|
|
||||||
|
|
||||||
const result: FetchHgResult = Deno.core.ops.op_fetch_hg(url, rev, name);
|
|
||||||
|
|
||||||
return {
|
|
||||||
outPath: result.out_path,
|
|
||||||
branch: result.branch,
|
|
||||||
rev: result.rev,
|
|
||||||
shortRev: result.short_rev,
|
|
||||||
revCount: BigInt(result.rev_count),
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const fetchTree = (args: NixValue): NixAttrs => {
|
export const fetchTree = (args: NixValue): NixAttrs => {
|
||||||
const attrs = forceAttrs(args);
|
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) {
|
switch (type) {
|
||||||
case "git":
|
case "git":
|
||||||
@@ -231,29 +232,31 @@ export const fetchTree = (args: NixValue): NixAttrs => {
|
|||||||
case "mercurial":
|
case "mercurial":
|
||||||
return fetchMercurial(args);
|
return fetchMercurial(args);
|
||||||
case "tarball":
|
case "tarball":
|
||||||
return { outPath: fetchTarball(args) };
|
return new Map<string, NixValue>([["outPath", fetchTarball(args)]]);
|
||||||
case "file":
|
case "file":
|
||||||
return { outPath: fetchurl(args) };
|
return new Map<string, NixValue>([["outPath", fetchurl(args)]]);
|
||||||
case "path": {
|
case "path": {
|
||||||
const path = forceStringValue(attrs.path);
|
const path = forceStringValue(select(attrs, ["path"]));
|
||||||
return { outPath: path };
|
return new Map<string, NixValue>([["outPath", path]]);
|
||||||
}
|
}
|
||||||
case "github":
|
case "github":
|
||||||
case "gitlab":
|
case "gitlab":
|
||||||
case "sourcehut":
|
case "sourcehut":
|
||||||
return fetchGitForge(type, attrs);
|
return fetchGitForge(type, attrs);
|
||||||
case "auto":
|
|
||||||
default:
|
default:
|
||||||
return autoDetectAndFetch(attrs);
|
return autoDetectAndFetch(attrs);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const fetchGitForge = (forge: string, attrs: NixAttrs): NixAttrs => {
|
const fetchGitForge = (forge: string, attrs: NixAttrs): NixAttrs => {
|
||||||
const owner = forceStringValue(attrs.owner);
|
const owner = forceStringValue(select(forge, ["owner"]));
|
||||||
const repo = forceStringValue(attrs.repo);
|
const repo = forceStringValue(select(forge, ["repo"]));
|
||||||
const rev =
|
const rev = attrs.has("rev")
|
||||||
"rev" in attrs ? forceStringValue(attrs.rev) : "ref" in attrs ? forceStringValue(attrs.ref) : "HEAD";
|
? forceStringValue(attrs.get("rev") as NixValue)
|
||||||
const host = "host" in attrs ? forceStringValue(attrs.host) : undefined;
|
: 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;
|
let tarballUrl: string;
|
||||||
switch (forge) {
|
switch (forge) {
|
||||||
@@ -276,17 +279,17 @@ const fetchGitForge = (forge: string, attrs: NixAttrs): NixAttrs => {
|
|||||||
throw new Error(`Unknown forge type: ${forge}`);
|
throw new Error(`Unknown forge type: ${forge}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const outPath = fetchTarball({ url: tarballUrl, ...attrs });
|
const outPath = fetchTarball(new Map<string, NixValue>([["url", tarballUrl], ...attrs]));
|
||||||
|
|
||||||
return {
|
return new Map<string, NixValue>([
|
||||||
outPath,
|
["outPath", outPath],
|
||||||
rev,
|
["rev", rev],
|
||||||
shortRev: rev.substring(0, 7),
|
["shortRev", rev.substring(0, 7)],
|
||||||
};
|
]);
|
||||||
};
|
};
|
||||||
|
|
||||||
const autoDetectAndFetch = (attrs: NixAttrs): NixAttrs => {
|
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")) {
|
if (url.endsWith(".git") || url.includes("github.com") || url.includes("gitlab.com")) {
|
||||||
return fetchGit(attrs);
|
return fetchGit(attrs);
|
||||||
}
|
}
|
||||||
@@ -296,34 +299,33 @@ const autoDetectAndFetch = (attrs: NixAttrs): NixAttrs => {
|
|||||||
url.endsWith(".tar.bz2") ||
|
url.endsWith(".tar.bz2") ||
|
||||||
url.endsWith(".tgz")
|
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 => {
|
export const readDir = (path: NixValue): NixAttrs => {
|
||||||
const pathStr = coerceToPath(path);
|
const pathStr = realisePath(path);
|
||||||
const entries: Record<string, string> = Deno.core.ops.op_read_dir(pathStr);
|
return Deno.core.ops.op_read_dir(pathStr);
|
||||||
const result: NixAttrs = {};
|
|
||||||
for (const [name, type] of Object.entries(entries)) {
|
|
||||||
result[name] = type;
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const readFile = (path: NixValue): string => {
|
export const readFile = (path: NixValue): string => {
|
||||||
const pathStr = coerceToPath(path);
|
const pathStr = realisePath(path);
|
||||||
return Deno.core.ops.op_read_file(pathStr);
|
return Deno.core.ops.op_read_file(pathStr);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const readFileType = (path: NixValue): string => {
|
export const readFileType = (path: NixValue): string => {
|
||||||
const pathStr = coerceToPath(path);
|
const pathStr = realisePath(path);
|
||||||
return Deno.core.ops.op_read_file_type(pathStr);
|
return Deno.core.ops.op_read_file_type(pathStr);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const pathExists = (path: NixValue): boolean => {
|
export const pathExists = (path: NixValue): boolean => {
|
||||||
const pathStr = coerceToPath(path);
|
try {
|
||||||
|
const pathStr = realisePath(path);
|
||||||
return Deno.core.ops.op_path_exists(pathStr);
|
return Deno.core.ops.op_path_exists(pathStr);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -339,42 +341,36 @@ export const pathExists = (path: NixValue): boolean => {
|
|||||||
*
|
*
|
||||||
* Returns: Store path string
|
* Returns: Store path string
|
||||||
*/
|
*/
|
||||||
export const path = (args: NixValue): string => {
|
export const path = (args: NixValue): NixString => {
|
||||||
const attrs = forceAttrs(args);
|
const attrs = forceAttrs(args);
|
||||||
|
|
||||||
// Required: path parameter
|
if (!attrs.has("path")) {
|
||||||
if (!("path" in attrs)) {
|
|
||||||
throw new TypeError("builtins.path: 'path' attribute is required");
|
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;
|
let pathStr: string;
|
||||||
|
|
||||||
// Accept both Path values and strings
|
|
||||||
if (isNixPath(pathValue)) {
|
if (isNixPath(pathValue)) {
|
||||||
pathStr = getPathValue(pathValue);
|
pathStr = getPathValue(pathValue);
|
||||||
} else {
|
} else {
|
||||||
pathStr = forceStringValue(pathValue);
|
pathStr = forceStringValue(pathValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Optional: name parameter (defaults to basename in Rust)
|
const name = attrs.has("name") ? forceStringValue(attrs.get("name") as NixValue) : null;
|
||||||
const name = "name" in attrs ? forceStringValue(attrs.name) : 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;
|
||||||
|
|
||||||
// Optional: recursive parameter (default: true)
|
let storePath: string;
|
||||||
const recursive = "recursive" in attrs ? forceBool(attrs.recursive) : true;
|
|
||||||
|
|
||||||
// Optional: sha256 parameter
|
if (attrs.has("filter")) {
|
||||||
const sha256 = "sha256" in attrs ? forceStringValue(attrs.sha256) : null;
|
const filterFn = forceFunction(attrs.get("filter") as NixValue);
|
||||||
|
|
||||||
// Handle filter parameter
|
|
||||||
if ("filter" in attrs) {
|
|
||||||
const filterFn = forceFunction(attrs.filter);
|
|
||||||
|
|
||||||
const entries: [string, string][] = Deno.core.ops.op_walk_dir(pathStr);
|
const entries: [string, string][] = Deno.core.ops.op_walk_dir(pathStr);
|
||||||
|
|
||||||
const includePaths: string[] = [];
|
const includePaths: string[] = [];
|
||||||
for (const [relPath, fileType] of entries) {
|
for (const [relPath, fileType] of entries) {
|
||||||
const fullPath = pathStr + "/" + relPath;
|
const fullPath = `${pathStr}/${relPath}`;
|
||||||
const innerFn = forceFunction(filterFn(fullPath));
|
const innerFn = forceFunction(filterFn(fullPath));
|
||||||
const shouldInclude = force(innerFn(fileType));
|
const shouldInclude = force(innerFn(fileType));
|
||||||
if (shouldInclude === true) {
|
if (shouldInclude === true) {
|
||||||
@@ -382,20 +378,14 @@ export const path = (args: NixValue): string => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const storePath: string = Deno.core.ops.op_add_filtered_path(
|
storePath = Deno.core.ops.op_add_filtered_path(pathStr, name, recursive, sha256, includePaths);
|
||||||
pathStr,
|
} else {
|
||||||
name,
|
storePath = Deno.core.ops.op_add_path(pathStr, name, recursive, sha256);
|
||||||
recursive,
|
|
||||||
sha256,
|
|
||||||
includePaths,
|
|
||||||
);
|
|
||||||
return storePath;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call Rust op to add path to store
|
const context: NixStringContext = new Set();
|
||||||
const storePath: string = Deno.core.ops.op_add_path(pathStr, name, recursive, sha256);
|
addOpaqueContext(context, storePath);
|
||||||
|
return mkStringWithContext(storePath, context);
|
||||||
return storePath;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const toFile =
|
export const toFile =
|
||||||
@@ -420,13 +410,11 @@ export const toFile =
|
|||||||
return mkStringWithContext(storePath, new Set([storePath]));
|
return mkStringWithContext(storePath, new Set([storePath]));
|
||||||
};
|
};
|
||||||
|
|
||||||
export const toPath = (name: NixValue, s: NixValue): never => {
|
export const filterSource =
|
||||||
throw new Error("Not implemented: toPath");
|
(_filter: NixValue) =>
|
||||||
};
|
(_path: NixValue): never => {
|
||||||
|
|
||||||
export const filterSource = (args: NixValue): never => {
|
|
||||||
throw new Error("Not implemented: filterSource");
|
throw new Error("Not implemented: filterSource");
|
||||||
};
|
};
|
||||||
|
|
||||||
const suffixIfPotentialMatch = (prefix: string, path: string): string | null => {
|
const suffixIfPotentialMatch = (prefix: string, path: string): string | null => {
|
||||||
const n = prefix.length;
|
const n = prefix.length;
|
||||||
@@ -453,9 +441,9 @@ export const findFile =
|
|||||||
for (const item of forcedSearchPath) {
|
for (const item of forcedSearchPath) {
|
||||||
const attrs = forceAttrs(item);
|
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");
|
throw new Error("findFile: search path element is missing 'path' attribute");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -465,25 +453,29 @@ export const findFile =
|
|||||||
}
|
}
|
||||||
|
|
||||||
const context: NixStringContext = new Set();
|
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) {
|
if (context.size > 0) {
|
||||||
throw new Error("findFile: path with string context is not yet supported");
|
throw new Error("findFile: path with string context is not yet supported");
|
||||||
}
|
}
|
||||||
|
|
||||||
const resolvedPath = Deno.core.ops.op_resolve_path(pathVal, "");
|
const resolvedPath = Deno.core.ops.op_resolve_path(pathVal, "");
|
||||||
const candidatePath = suffix.length > 0
|
const candidatePath =
|
||||||
? Deno.core.ops.op_resolve_path(suffix, resolvedPath)
|
suffix.length > 0 ? Deno.core.ops.op_resolve_path(suffix, resolvedPath) : resolvedPath;
|
||||||
: resolvedPath;
|
|
||||||
|
|
||||||
if (Deno.core.ops.op_path_exists(candidatePath)) {
|
if (Deno.core.ops.op_path_exists(candidatePath)) {
|
||||||
return { [IS_PATH]: true, value: candidatePath };
|
return new NixPath(candidatePath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (lookupPathStr.startsWith("nix/")) {
|
if (lookupPathStr.startsWith("nix/")) {
|
||||||
// FIXME: special path type
|
// 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`);
|
throw new CatchableError(`file '${lookupPathStr}' was not found in the Nix search path`);
|
||||||
|
|||||||
@@ -1,12 +1,7 @@
|
|||||||
/**
|
|
||||||
* List operation builtin functions
|
|
||||||
* All functions are properly curried
|
|
||||||
*/
|
|
||||||
|
|
||||||
import type { NixValue, NixList, NixAttrs } from "../types";
|
|
||||||
import { force } from "../thunk";
|
|
||||||
import { forceList, forceFunction, forceInt, forceBool } from "../type-assert";
|
|
||||||
import { op } from "../operators";
|
import { op } from "../operators";
|
||||||
|
import { force } from "../thunk";
|
||||||
|
import { forceBool, forceFunction, forceInt, forceList } from "../type-assert";
|
||||||
|
import type { NixAttrs, NixList, NixValue } from "../types";
|
||||||
|
|
||||||
export const map =
|
export const map =
|
||||||
(f: NixValue) =>
|
(f: NixValue) =>
|
||||||
@@ -74,23 +69,23 @@ export const concatMap =
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const foldlPrime =
|
export const foldlPrime =
|
||||||
(op_fn: NixValue) =>
|
(opFn: NixValue) =>
|
||||||
(nul: NixValue) =>
|
(nul: NixValue) =>
|
||||||
(list: NixValue): NixValue => {
|
(list: NixValue): NixValue => {
|
||||||
const forced_op = forceFunction(op_fn);
|
const forcedOp = forceFunction(opFn);
|
||||||
return forceList(list).reduce((acc: NixValue, cur: NixValue) => {
|
return forceList(list).reduce((acc: NixValue, cur: NixValue) => {
|
||||||
return forceFunction(forced_op(acc))(cur);
|
return forceFunction(forcedOp(acc))(cur);
|
||||||
}, nul);
|
}, nul);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const sort =
|
export const sort =
|
||||||
(cmp: NixValue) =>
|
(cmp: NixValue) =>
|
||||||
(list: NixValue): NixList => {
|
(list: NixValue): NixList => {
|
||||||
const forced_list = [...forceList(list)];
|
const forcedList = [...forceList(list)];
|
||||||
const forced_cmp = forceFunction(cmp);
|
const forcedCmp = forceFunction(cmp);
|
||||||
return forced_list.sort((a, b) => {
|
return forcedList.sort((a, b) => {
|
||||||
if (force(forceFunction(forced_cmp(a))(b))) return -1;
|
if (force(forceFunction(forcedCmp(a))(b))) return -1;
|
||||||
if (force(forceFunction(forced_cmp(b))(a))) return 1;
|
if (force(forceFunction(forcedCmp(b))(a))) return 1;
|
||||||
return 0;
|
return 0;
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -98,20 +93,21 @@ export const sort =
|
|||||||
export const partition =
|
export const partition =
|
||||||
(pred: NixValue) =>
|
(pred: NixValue) =>
|
||||||
(list: NixValue): NixAttrs => {
|
(list: NixValue): NixAttrs => {
|
||||||
const forced_list = forceList(list);
|
const forcedList = forceList(list);
|
||||||
const forced_pred = forceFunction(pred);
|
const forcedPred = forceFunction(pred);
|
||||||
const attrs = {
|
const right: NixList = [];
|
||||||
right: [] as NixList,
|
const wrong: NixList = [];
|
||||||
wrong: [] as NixList,
|
for (const elem of forcedList) {
|
||||||
};
|
if (force(forcedPred(elem))) {
|
||||||
for (const elem of forced_list) {
|
right.push(elem);
|
||||||
if (force(forced_pred(elem))) {
|
|
||||||
attrs.right.push(elem);
|
|
||||||
} else {
|
} else {
|
||||||
attrs.wrong.push(elem);
|
wrong.push(elem);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return attrs;
|
return new Map<string, NixValue>([
|
||||||
|
["right", right],
|
||||||
|
["wrong", wrong],
|
||||||
|
]);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const genList =
|
export const genList =
|
||||||
|
|||||||
@@ -1,9 +1,5 @@
|
|||||||
/**
|
|
||||||
* Math builtin functions
|
|
||||||
*/
|
|
||||||
|
|
||||||
import type { NixValue } from "../types";
|
|
||||||
import { forceNumeric } from "../type-assert";
|
import { forceNumeric } from "../type-assert";
|
||||||
|
import type { NixValue } from "../types";
|
||||||
|
|
||||||
export const ceil = (x: NixValue): bigint => {
|
export const ceil = (x: NixValue): bigint => {
|
||||||
const val = forceNumeric(x);
|
const val = forceNumeric(x);
|
||||||
|
|||||||
@@ -1,24 +1,28 @@
|
|||||||
/**
|
|
||||||
* Miscellaneous builtin functions
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { force } from "../thunk";
|
|
||||||
import { CatchableError, ATTR_POSITIONS } from "../types";
|
|
||||||
import type { NixAttrs, NixBool, NixStrictValue, NixValue } from "../types";
|
|
||||||
import { forceList, forceAttrs, forceFunction, forceStringValue, forceString, forceStringNoCtx } from "../type-assert";
|
|
||||||
import * as context from "./context";
|
|
||||||
import { compareValues } from "../operators";
|
|
||||||
import { isBool, isFloat, isInt, isList, isString, typeOf } from "./type-check";
|
|
||||||
import { OrderedSet } from "js-sdsl";
|
import { OrderedSet } from "js-sdsl";
|
||||||
|
import { select } from "../helpers";
|
||||||
|
import { compareValues } from "../operators";
|
||||||
import {
|
import {
|
||||||
type NixStringContext,
|
|
||||||
getStringValue,
|
|
||||||
getStringContext,
|
getStringContext,
|
||||||
|
getStringValue,
|
||||||
mkStringWithContext,
|
mkStringWithContext,
|
||||||
|
type NixStringContext,
|
||||||
} from "../string-context";
|
} from "../string-context";
|
||||||
|
import { force } from "../thunk";
|
||||||
|
import {
|
||||||
|
forceAttrs,
|
||||||
|
forceFunction,
|
||||||
|
forceList,
|
||||||
|
forceString,
|
||||||
|
forceStringNoCtx,
|
||||||
|
forceStringValue,
|
||||||
|
} from "../type-assert";
|
||||||
|
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";
|
||||||
|
|
||||||
export const addErrorContext =
|
export const addErrorContext =
|
||||||
(e1: NixValue) =>
|
(_e1: NixValue) =>
|
||||||
(e2: NixValue): NixValue => {
|
(e2: NixValue): NixValue => {
|
||||||
// FIXME:
|
// FIXME:
|
||||||
// console.log("[WARNING]: addErrorContext not implemented");
|
// console.log("[WARNING]: addErrorContext not implemented");
|
||||||
@@ -31,22 +35,6 @@ export const getContext = context.getContext;
|
|||||||
|
|
||||||
export const hasContext = context.hasContext;
|
export const hasContext = context.hasContext;
|
||||||
|
|
||||||
export const hashFile =
|
|
||||||
(type: NixValue) =>
|
|
||||||
(p: NixValue): never => {
|
|
||||||
throw new Error("Not implemented: hashFile");
|
|
||||||
};
|
|
||||||
|
|
||||||
export const hashString =
|
|
||||||
(type: NixValue) =>
|
|
||||||
(p: NixValue): never => {
|
|
||||||
throw new Error("Not implemented: hashString");
|
|
||||||
};
|
|
||||||
|
|
||||||
export const convertHash = (args: NixValue): never => {
|
|
||||||
throw new Error("Not implemented: convertHash");
|
|
||||||
};
|
|
||||||
|
|
||||||
export const unsafeDiscardOutputDependency = context.unsafeDiscardOutputDependency;
|
export const unsafeDiscardOutputDependency = context.unsafeDiscardOutputDependency;
|
||||||
|
|
||||||
export const unsafeDiscardStringContext = context.unsafeDiscardStringContext;
|
export const unsafeDiscardStringContext = context.unsafeDiscardStringContext;
|
||||||
@@ -69,9 +57,9 @@ export const compareVersions =
|
|||||||
i1 = c1.nextIndex;
|
i1 = c1.nextIndex;
|
||||||
i2 = c2.nextIndex;
|
i2 = c2.nextIndex;
|
||||||
|
|
||||||
if (componentsLT(c1.component, c2.component)) {
|
if (componentsLt(c1.component, c2.component)) {
|
||||||
return -1n;
|
return -1n;
|
||||||
} else if (componentsLT(c2.component, c1.component)) {
|
} else if (componentsLt(c2.component, c1.component)) {
|
||||||
return 1n;
|
return 1n;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -113,7 +101,7 @@ function nextComponent(s: string, startIdx: number): ComponentResult {
|
|||||||
return { component: s.substring(start, p), nextIndex: p };
|
return { component: s.substring(start, p), nextIndex: p };
|
||||||
}
|
}
|
||||||
|
|
||||||
function componentsLT(c1: string, c2: string): boolean {
|
function componentsLt(c1: string, c2: string): boolean {
|
||||||
const n1 = c1.match(/^[0-9]+$/) ? BigInt(c1) : null;
|
const n1 = c1.match(/^[0-9]+$/) ? BigInt(c1) : null;
|
||||||
const n2 = c2.match(/^[0-9]+$/) ? BigInt(c2) : null;
|
const n2 = c2.match(/^[0-9]+$/) ? BigInt(c2) : null;
|
||||||
|
|
||||||
@@ -147,35 +135,23 @@ function componentsLT(c1: string, c2: string): boolean {
|
|||||||
return c1 < c2;
|
return c1 < c2;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const dirOf = (s: NixValue): never => {
|
|
||||||
throw new Error("Not implemented: dirOf");
|
|
||||||
};
|
|
||||||
|
|
||||||
export const flakeRefToString = (attrs: NixValue): never => {
|
|
||||||
throw new Error("Not implemented: flakeRefToString");
|
|
||||||
};
|
|
||||||
|
|
||||||
export const functionArgs = (f: NixValue): NixAttrs => {
|
export const functionArgs = (f: NixValue): NixAttrs => {
|
||||||
const func = forceFunction(f);
|
const func = forceFunction(f);
|
||||||
if (func.args) {
|
if (func.args) {
|
||||||
const ret: NixAttrs = {};
|
const ret: NixAttrs = new Map();
|
||||||
for (const key of func.args!.required) {
|
for (const key of func.args.required) {
|
||||||
ret[key] = false;
|
ret.set(key, false);
|
||||||
}
|
}
|
||||||
for (const key of func.args!.optional) {
|
for (const key of func.args.optional) {
|
||||||
ret[key] = true;
|
ret.set(key, true);
|
||||||
}
|
}
|
||||||
const positions = func.args!.positions;
|
const positions = func.args.positions;
|
||||||
if (positions && Object.keys(positions).length > 0) {
|
if (positions) {
|
||||||
Object.defineProperty(ret, ATTR_POSITIONS, {
|
ret[ATTR_POSITIONS] = positions;
|
||||||
value: positions,
|
|
||||||
enumerable: false,
|
|
||||||
writable: false,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
return {};
|
return new Map();
|
||||||
};
|
};
|
||||||
|
|
||||||
const checkComparable = (value: NixStrictValue): void => {
|
const checkComparable = (value: NixStrictValue): void => {
|
||||||
@@ -187,7 +163,8 @@ const checkComparable = (value: NixStrictValue): void => {
|
|||||||
|
|
||||||
export const genericClosure = (args: NixValue): NixValue => {
|
export const genericClosure = (args: NixValue): NixValue => {
|
||||||
const forcedArgs = forceAttrs(args);
|
const forcedArgs = forceAttrs(args);
|
||||||
const { startSet, operator } = forcedArgs;
|
const startSet = select(forcedArgs, ["startSet"]);
|
||||||
|
const operator = select(forcedArgs, ["operator"]);
|
||||||
|
|
||||||
const initialList = forceList(startSet);
|
const initialList = forceList(startSet);
|
||||||
const opFunction = forceFunction(operator);
|
const opFunction = forceFunction(operator);
|
||||||
@@ -198,7 +175,7 @@ export const genericClosure = (args: NixValue): NixValue => {
|
|||||||
|
|
||||||
for (const item of initialList) {
|
for (const item of initialList) {
|
||||||
const itemAttrs = forceAttrs(item);
|
const itemAttrs = forceAttrs(item);
|
||||||
const key = force(itemAttrs.key);
|
const key = force(select(itemAttrs, ["key"]));
|
||||||
checkComparable(key);
|
checkComparable(key);
|
||||||
if (resultSet.find(key).equals(resultSet.end())) {
|
if (resultSet.find(key).equals(resultSet.end())) {
|
||||||
resultSet.insert(key);
|
resultSet.insert(key);
|
||||||
@@ -214,7 +191,7 @@ export const genericClosure = (args: NixValue): NixValue => {
|
|||||||
|
|
||||||
for (const newItem of newItems) {
|
for (const newItem of newItems) {
|
||||||
const newItemAttrs = forceAttrs(newItem);
|
const newItemAttrs = forceAttrs(newItem);
|
||||||
const key = force(newItemAttrs.key);
|
const key = force(select(newItemAttrs, ["key"]));
|
||||||
checkComparable(key);
|
checkComparable(key);
|
||||||
if (resultSet.find(key).equals(resultSet.end())) {
|
if (resultSet.find(key).equals(resultSet.end())) {
|
||||||
resultSet.insert(key);
|
resultSet.insert(key);
|
||||||
@@ -227,14 +204,10 @@ export const genericClosure = (args: NixValue): NixValue => {
|
|||||||
return resultList;
|
return resultList;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getFlake = (attrs: NixValue): never => {
|
|
||||||
throw new Error("Not implemented: getFlake");
|
|
||||||
};
|
|
||||||
|
|
||||||
export const outputOf =
|
export const outputOf =
|
||||||
(drv: NixValue) =>
|
(_drv: NixValue) =>
|
||||||
(out: NixValue): never => {
|
(_out: NixValue): never => {
|
||||||
throw new Error("Not implemented: outputOf");
|
throw new Error("Not implemented: outputOf (part of dynamic-derivation)");
|
||||||
};
|
};
|
||||||
|
|
||||||
export const parseDrvName = (s: NixValue): NixAttrs => {
|
export const parseDrvName = (s: NixValue): NixAttrs => {
|
||||||
@@ -242,24 +215,16 @@ export const parseDrvName = (s: NixValue): NixAttrs => {
|
|||||||
let name = fullName;
|
let name = fullName;
|
||||||
let version = "";
|
let version = "";
|
||||||
for (let i = 0; i < fullName.length; ++i) {
|
for (let i = 0; i < fullName.length; ++i) {
|
||||||
if (fullName[i] === '-' && i + 1 < fullName.length && !/[a-zA-Z]/.test(fullName[i + 1])) {
|
if (fullName[i] === "-" && i + 1 < fullName.length && !/[a-zA-Z]/.test(fullName[i + 1])) {
|
||||||
name = fullName.substring(0, i);
|
name = fullName.substring(0, i);
|
||||||
version = fullName.substring(i + 1);
|
version = fullName.substring(i + 1);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return {
|
return new Map<string, NixValue>([
|
||||||
name,
|
["name", name],
|
||||||
version
|
["version", version],
|
||||||
}
|
]);
|
||||||
};
|
|
||||||
|
|
||||||
export const parseFlakeName = (s: NixValue): never => {
|
|
||||||
throw new Error("Not implemented: parseFlakeName");
|
|
||||||
};
|
|
||||||
|
|
||||||
export const parseFlakeRef = (s: NixValue): never => {
|
|
||||||
throw new Error("Not implemented: parseFlakeRef");
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const placeholder = (output: NixValue): NixValue => {
|
export const placeholder = (output: NixValue): NixValue => {
|
||||||
@@ -306,7 +271,7 @@ export const replaceStrings =
|
|||||||
resultContext.add(elem);
|
resultContext.add(elem);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const replacement = toCache.get(i)!;
|
const replacement = toCache.get(i) as string;
|
||||||
|
|
||||||
result += replacement;
|
result += replacement;
|
||||||
|
|
||||||
@@ -353,22 +318,25 @@ export const splitVersion = (s: NixValue): NixValue => {
|
|||||||
return components;
|
return components;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const traceVerbose = (e1: NixValue, e2: NixValue): never => {
|
export const traceVerbose =
|
||||||
throw new Error("Not implemented: traceVerbose");
|
(_e1: NixValue) =>
|
||||||
};
|
(e2: NixValue): NixStrictValue => {
|
||||||
|
// TODO: implement traceVerbose
|
||||||
export const tryEval = (e: NixValue): { success: NixBool; value: NixStrictValue } => {
|
return force(e2);
|
||||||
try {
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
value: force(e),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const tryEval = (e: NixValue): NixAttrs => {
|
||||||
|
try {
|
||||||
|
return new Map<string, NixValue>([
|
||||||
|
["success", true],
|
||||||
|
["value", force(e)],
|
||||||
|
]);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof CatchableError) {
|
if (err instanceof CatchableError) {
|
||||||
return {
|
return new Map<string, NixValue>([
|
||||||
success: false,
|
["success", false],
|
||||||
value: false,
|
["value", false],
|
||||||
};
|
]);
|
||||||
} else {
|
} else {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,9 @@
|
|||||||
/**
|
|
||||||
* Path-related builtin functions
|
|
||||||
*/
|
|
||||||
|
|
||||||
import type { NixValue, NixString, NixPath } from "../types";
|
|
||||||
import { isNixPath, isStringWithContext } from "../types";
|
|
||||||
import { force } from "../thunk";
|
|
||||||
import { mkPath } from "../path";
|
import { mkPath } from "../path";
|
||||||
import { coerceToString, StringCoercionMode, coerceToPath } from "./conversion";
|
|
||||||
import { mkStringWithContext, type NixStringContext } from "../string-context";
|
import { mkStringWithContext, type NixStringContext } from "../string-context";
|
||||||
|
import { force } from "../thunk";
|
||||||
|
import type { NixPath, NixString, NixValue } from "../types";
|
||||||
|
import { isNixPath } from "../types";
|
||||||
|
import { coerceToPath, coerceToString, StringCoercionMode } from "./conversion";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* builtins.baseNameOf
|
* builtins.baseNameOf
|
||||||
@@ -25,36 +21,6 @@ import { mkStringWithContext, type NixStringContext } from "../string-context";
|
|||||||
* - baseNameOf "foo" → "foo"
|
* - baseNameOf "foo" → "foo"
|
||||||
*/
|
*/
|
||||||
export const baseNameOf = (s: NixValue): NixString => {
|
export const baseNameOf = (s: NixValue): NixString => {
|
||||||
const forced = force(s);
|
|
||||||
|
|
||||||
// Path input → string output (no context)
|
|
||||||
if (isNixPath(forced)) {
|
|
||||||
const pathStr = forced.value;
|
|
||||||
|
|
||||||
if (pathStr.length === 0) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
let last = pathStr.length - 1;
|
|
||||||
if (pathStr[last] === "/" && last > 0) {
|
|
||||||
last -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
let pos = last;
|
|
||||||
while (pos >= 0 && pathStr[pos] !== "/") {
|
|
||||||
pos -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (pos === -1) {
|
|
||||||
pos = 0;
|
|
||||||
} else {
|
|
||||||
pos += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return pathStr.substring(pos, last + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// String input → string output (preserve context)
|
|
||||||
const context: NixStringContext = new Set();
|
const context: NixStringContext = new Set();
|
||||||
const pathStr = coerceToString(s, StringCoercionMode.Base, false, context);
|
const pathStr = coerceToString(s, StringCoercionMode.Base, false, context);
|
||||||
|
|
||||||
@@ -120,21 +86,8 @@ export const dirOf = (s: NixValue): NixPath | NixString => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// String input → string output
|
// String input → string output
|
||||||
const strValue: NixString = coerceToString(s, StringCoercionMode.Base, false) as NixString;
|
const outContext: NixStringContext = new Set();
|
||||||
|
const pathStr = coerceToString(s, StringCoercionMode.Base, false, outContext);
|
||||||
let pathStr: string;
|
|
||||||
let hasContext = false;
|
|
||||||
let originalContext: Set<string> | undefined;
|
|
||||||
|
|
||||||
if (typeof strValue === "string") {
|
|
||||||
pathStr = strValue;
|
|
||||||
} else if (isStringWithContext(strValue)) {
|
|
||||||
pathStr = strValue.value;
|
|
||||||
hasContext = strValue.context.size > 0;
|
|
||||||
originalContext = strValue.context;
|
|
||||||
} else {
|
|
||||||
pathStr = strValue as string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const lastSlash = pathStr.lastIndexOf("/");
|
const lastSlash = pathStr.lastIndexOf("/");
|
||||||
|
|
||||||
@@ -147,9 +100,8 @@ export const dirOf = (s: NixValue): NixPath | NixString => {
|
|||||||
|
|
||||||
const result = pathStr.slice(0, lastSlash);
|
const result = pathStr.slice(0, lastSlash);
|
||||||
|
|
||||||
// Preserve string context if present
|
if (outContext.size > 0) {
|
||||||
if (hasContext && originalContext) {
|
return mkStringWithContext(result, outContext);
|
||||||
return mkStringWithContext(result, originalContext);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
|
|||||||
@@ -1,29 +1,15 @@
|
|||||||
/**
|
|
||||||
* String operation builtin functions
|
|
||||||
*/
|
|
||||||
|
|
||||||
import type { NixInt, NixValue, NixString } from "../types";
|
|
||||||
import { forceStringValue, forceList, forceInt, forceString } from "../type-assert";
|
|
||||||
import { coerceToString, StringCoercionMode } from "./conversion";
|
|
||||||
import {
|
import {
|
||||||
type NixStringContext,
|
|
||||||
getStringValue,
|
|
||||||
getStringContext,
|
getStringContext,
|
||||||
|
getStringValue,
|
||||||
mkStringWithContext,
|
mkStringWithContext,
|
||||||
|
type NixStringContext,
|
||||||
} from "../string-context";
|
} from "../string-context";
|
||||||
|
import { forceInt, forceList, forceString, forceStringValue } from "../type-assert";
|
||||||
|
import type { NixInt, NixString, NixValue } from "../types";
|
||||||
|
import { coerceToString, StringCoercionMode } from "./conversion";
|
||||||
|
|
||||||
export const stringLength = (e: NixValue): NixInt => BigInt(forceStringValue(e).length);
|
export const stringLength = (e: NixValue): NixInt => BigInt(forceStringValue(e).length);
|
||||||
|
|
||||||
/**
|
|
||||||
* builtins.substring - Extract substring while preserving string context
|
|
||||||
*
|
|
||||||
* IMPORTANT: String context must be preserved from the source string.
|
|
||||||
* This matches Lix behavior where substring operations maintain references
|
|
||||||
* to store paths and derivations.
|
|
||||||
*
|
|
||||||
* Special case: substring 0 0 str can be used idiomatically to capture
|
|
||||||
* string context efficiently without copying the string value.
|
|
||||||
*/
|
|
||||||
export const substring =
|
export const substring =
|
||||||
(start: NixValue) =>
|
(start: NixValue) =>
|
||||||
(len: NixValue) =>
|
(len: NixValue) =>
|
||||||
@@ -55,13 +41,6 @@ export const substring =
|
|||||||
return mkStringWithContext(result, context);
|
return mkStringWithContext(result, context);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* builtins.concatStringsSep - Concatenate strings with separator, merging contexts
|
|
||||||
*
|
|
||||||
* IMPORTANT: String context must be collected from both the separator and all
|
|
||||||
* list elements, then merged into the result. This ensures that store path
|
|
||||||
* references are preserved when building paths like "/nix/store/xxx/bin:/nix/store/yyy/bin".
|
|
||||||
*/
|
|
||||||
export const concatStringsSep =
|
export const concatStringsSep =
|
||||||
(sep: NixValue) =>
|
(sep: NixValue) =>
|
||||||
(list: NixValue): NixString => {
|
(list: NixValue): NixString => {
|
||||||
@@ -80,81 +59,17 @@ export const concatStringsSep =
|
|||||||
return mkStringWithContext(result, context);
|
return mkStringWithContext(result, context);
|
||||||
};
|
};
|
||||||
|
|
||||||
const POSIX_CLASSES: Record<string, string> = {
|
|
||||||
alnum: "a-zA-Z0-9",
|
|
||||||
alpha: "a-zA-Z",
|
|
||||||
blank: " \\t",
|
|
||||||
digit: "0-9",
|
|
||||||
lower: "a-z",
|
|
||||||
upper: "A-Z",
|
|
||||||
space: "\\s",
|
|
||||||
xdigit: "0-9A-Fa-f",
|
|
||||||
punct: "\\-!\"#$%&'()*+,./:;<=>?@[\\\\\\]^_`{|}~",
|
|
||||||
};
|
|
||||||
|
|
||||||
function posixToJsRegex(pattern: string, fullMatch: boolean = false): RegExp {
|
|
||||||
let jsPattern = pattern;
|
|
||||||
|
|
||||||
jsPattern = jsPattern.replace(/\[(\^?)(?:\[:(\w+):\])+\]/g, (match) => {
|
|
||||||
const isNegated = match[1] === "^";
|
|
||||||
const classNames = [...match.matchAll(/\[:(\w+):\]/g)].map((m) => m[1]);
|
|
||||||
|
|
||||||
const combined = classNames
|
|
||||||
.map((className) => {
|
|
||||||
const replacement = POSIX_CLASSES[className];
|
|
||||||
if (!replacement) {
|
|
||||||
throw new Error(`Unknown POSIX character class: ${className}`);
|
|
||||||
}
|
|
||||||
return replacement;
|
|
||||||
})
|
|
||||||
.join("");
|
|
||||||
|
|
||||||
return isNegated ? `[^${combined}]` : `[${combined}]`;
|
|
||||||
});
|
|
||||||
|
|
||||||
jsPattern = jsPattern.replace(/\[:(\w+):\]/g, (_match, className) => {
|
|
||||||
const replacement = POSIX_CLASSES[className];
|
|
||||||
if (!replacement) {
|
|
||||||
throw new Error(`Unknown POSIX character class: ${className}`);
|
|
||||||
}
|
|
||||||
return replacement;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (fullMatch) {
|
|
||||||
if (!jsPattern.startsWith("^")) {
|
|
||||||
jsPattern = "^" + jsPattern;
|
|
||||||
}
|
|
||||||
if (!jsPattern.endsWith("$")) {
|
|
||||||
jsPattern = jsPattern + "$";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return new RegExp(jsPattern, "u");
|
|
||||||
}
|
|
||||||
|
|
||||||
export const match =
|
export const match =
|
||||||
(regex: NixValue) =>
|
(regex: NixValue) =>
|
||||||
(str: NixValue): NixValue => {
|
(str: NixValue): NixValue => {
|
||||||
const regexStr = forceStringValue(regex);
|
const regexStr = forceStringValue(regex);
|
||||||
const inputStr = forceStringValue(str);
|
const inputStr = forceStringValue(str);
|
||||||
|
|
||||||
try {
|
const result = Deno.core.ops.op_match(regexStr, inputStr);
|
||||||
const re = posixToJsRegex(regexStr, true);
|
if (result === null) {
|
||||||
const result = inputStr.match(re);
|
|
||||||
|
|
||||||
if (!result) {
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
return result.map((g) => (g !== null ? g : null));
|
||||||
const groups: NixValue[] = [];
|
|
||||||
for (let i = 1; i < result.length; i++) {
|
|
||||||
groups.push(result[i] !== undefined ? result[i] : null);
|
|
||||||
}
|
|
||||||
|
|
||||||
return groups;
|
|
||||||
} catch (e) {
|
|
||||||
throw new Error(`Invalid regular expression '${regexStr}': ${e}`);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const split =
|
export const split =
|
||||||
@@ -164,37 +79,16 @@ export const split =
|
|||||||
const inputStr = forceString(str);
|
const inputStr = forceString(str);
|
||||||
const inputStrValue = getStringValue(inputStr);
|
const inputStrValue = getStringValue(inputStr);
|
||||||
|
|
||||||
try {
|
const result = Deno.core.ops.op_split(regexStr, inputStrValue);
|
||||||
const re = posixToJsRegex(regexStr);
|
|
||||||
const reGlobal = new RegExp(re.source, re.flags + "g");
|
|
||||||
|
|
||||||
const result: NixValue[] = [];
|
if (result.length === 1 && typeof result[0] === "string") {
|
||||||
let lastIndex = 0;
|
|
||||||
let match: RegExpExecArray | null;
|
|
||||||
|
|
||||||
while ((match = reGlobal.exec(inputStrValue)) !== null) {
|
|
||||||
result.push(inputStrValue.substring(lastIndex, match.index));
|
|
||||||
|
|
||||||
const groups: NixValue[] = [];
|
|
||||||
for (let i = 1; i < match.length; i++) {
|
|
||||||
groups.push(match[i] !== undefined ? match[i] : null);
|
|
||||||
}
|
|
||||||
result.push(groups);
|
|
||||||
|
|
||||||
lastIndex = match.index + match[0].length;
|
|
||||||
|
|
||||||
if (match[0].length === 0) {
|
|
||||||
reGlobal.lastIndex++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (lastIndex === 0) {
|
|
||||||
return [inputStr];
|
return [inputStr];
|
||||||
}
|
}
|
||||||
|
|
||||||
result.push(inputStrValue.substring(lastIndex));
|
return result.map((item) => {
|
||||||
return result;
|
if (typeof item === "string") {
|
||||||
} catch (e) {
|
return item;
|
||||||
throw new Error(`Invalid regular expression '${regexStr}': ${e}`);
|
|
||||||
}
|
}
|
||||||
|
return item.map((g) => (g !== null ? g : null));
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,12 +1,6 @@
|
|||||||
/**
|
|
||||||
* Type checking builtin functions
|
|
||||||
*/
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
HAS_CONTEXT,
|
|
||||||
isNixPath,
|
isNixPath,
|
||||||
isStringWithContext,
|
isStringWithContext,
|
||||||
type NixPath,
|
|
||||||
type NixAttrs,
|
type NixAttrs,
|
||||||
type NixBool,
|
type NixBool,
|
||||||
type NixFloat,
|
type NixFloat,
|
||||||
@@ -14,23 +8,17 @@ import {
|
|||||||
type NixInt,
|
type NixInt,
|
||||||
type NixList,
|
type NixList,
|
||||||
type NixNull,
|
type NixNull,
|
||||||
type NixString,
|
type NixPath,
|
||||||
type NixStrictValue,
|
type NixStrictValue,
|
||||||
|
type NixString,
|
||||||
} from "../types";
|
} from "../types";
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if a value is a Nix string (plain string or StringWithContext)
|
|
||||||
* This works on already-forced values (NixStrictValue).
|
|
||||||
*/
|
|
||||||
export const isNixString = (v: NixStrictValue): v is NixString => {
|
export const isNixString = (v: NixStrictValue): v is NixString => {
|
||||||
return typeof v === "string" || isStringWithContext(v);
|
return typeof v === "string" || isStringWithContext(v);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const isAttrs = (e: NixStrictValue): e is NixAttrs => {
|
export const isAttrs = (e: NixStrictValue): e is NixAttrs => {
|
||||||
const val = e;
|
return e instanceof Map;
|
||||||
return (
|
|
||||||
typeof val === "object" && !Array.isArray(val) && val !== null && !(HAS_CONTEXT in val) && !isPath(val)
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const isBool = (e: NixStrictValue): e is NixBool => typeof e === "boolean";
|
export const isBool = (e: NixStrictValue): e is NixBool => typeof e === "boolean";
|
||||||
@@ -68,7 +56,7 @@ export const typeOf = (e: NixStrictValue): NixType => {
|
|||||||
if (isNixString(e)) return "string";
|
if (isNixString(e)) return "string";
|
||||||
if (isNixPath(e)) return "path";
|
if (isNixPath(e)) return "path";
|
||||||
if (Array.isArray(e)) return "list";
|
if (Array.isArray(e)) return "list";
|
||||||
if (typeof e === "object") return "set";
|
if (e instanceof Map) return "set";
|
||||||
if (typeof e === "function") return "lambda";
|
if (typeof e === "function") return "lambda";
|
||||||
|
|
||||||
throw new TypeError(`Unknown Nix type: ${typeof e}`);
|
throw new TypeError(`Unknown Nix type: ${typeof e}`);
|
||||||
|
|||||||
@@ -1,81 +0,0 @@
|
|||||||
import { HAS_CONTEXT, NixStringContext } from "./string-context";
|
|
||||||
import { force } from "./thunk";
|
|
||||||
import type { NixValue } from "./types";
|
|
||||||
import { isStringWithContext } from "./types";
|
|
||||||
|
|
||||||
export const nixValueToJson = (
|
|
||||||
value: NixValue,
|
|
||||||
seen = new Set<object>(),
|
|
||||||
outContext?: NixStringContext,
|
|
||||||
): any => {
|
|
||||||
const v = force(value);
|
|
||||||
|
|
||||||
if (v === null) return null;
|
|
||||||
if (typeof v === "boolean") return v;
|
|
||||||
if (typeof v === "string") return v;
|
|
||||||
if (typeof v === "number") return v;
|
|
||||||
|
|
||||||
if (typeof v === "object" && HAS_CONTEXT in v && "context" in v) {
|
|
||||||
if (outContext) {
|
|
||||||
for (const elem of v.context) {
|
|
||||||
outContext.add(elem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return v.value;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof v === "bigint") {
|
|
||||||
const num = Number(v);
|
|
||||||
if (v > Number.MAX_SAFE_INTEGER || v < Number.MIN_SAFE_INTEGER) {
|
|
||||||
console.warn(`derivation: integer ${v} exceeds safe range, precision may be lost in __structuredAttrs`);
|
|
||||||
}
|
|
||||||
return num;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof v === "object" && v !== null) {
|
|
||||||
if (seen.has(v)) {
|
|
||||||
throw new Error("derivation: circular reference detected in __structuredAttrs");
|
|
||||||
}
|
|
||||||
seen.add(v);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Array.isArray(v)) {
|
|
||||||
return v.map((item) => nixValueToJson(item, seen, outContext));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof v === "object") {
|
|
||||||
if ("__toString" in v && typeof force(v.__toString) === "function") {
|
|
||||||
const toStringMethod = force(v.__toString) as (self: typeof v) => NixValue;
|
|
||||||
const result = force(toStringMethod(v));
|
|
||||||
if (typeof result === "string") {
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
if (isStringWithContext(result)) {
|
|
||||||
if (outContext) {
|
|
||||||
for (const elem of result.context) {
|
|
||||||
outContext.add(elem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result.value;
|
|
||||||
}
|
|
||||||
return nixValueToJson(result, seen, outContext);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ("outPath" in v) {
|
|
||||||
return nixValueToJson(v.outPath, seen, outContext);
|
|
||||||
}
|
|
||||||
|
|
||||||
const result: Record<string, any> = {};
|
|
||||||
const keys = Object.keys(v).sort();
|
|
||||||
for (const key of keys) {
|
|
||||||
result[key] = nixValueToJson((v as Record<string, NixValue>)[key], seen, outContext);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof v === "function") {
|
|
||||||
throw new Error("derivation: cannot serialize function in __structuredAttrs");
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(`derivation: cannot serialize ${typeof v} to JSON`);
|
|
||||||
};
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
export interface OutputInfo {
|
|
||||||
path: string;
|
|
||||||
hashAlgo: string;
|
|
||||||
hash: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DerivationData {
|
|
||||||
name: string;
|
|
||||||
outputs: Map<string, OutputInfo>;
|
|
||||||
inputDrvs: Map<string, Set<string>>;
|
|
||||||
inputSrcs: Set<string>;
|
|
||||||
platform: string;
|
|
||||||
builder: string;
|
|
||||||
args: string[];
|
|
||||||
env: Map<string, string>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const escapeString = (s: string): string => {
|
|
||||||
let result = "";
|
|
||||||
for (const char of s) {
|
|
||||||
switch (char) {
|
|
||||||
case '"':
|
|
||||||
result += '\\"';
|
|
||||||
break;
|
|
||||||
case "\\":
|
|
||||||
result += "\\\\";
|
|
||||||
break;
|
|
||||||
case "\n":
|
|
||||||
result += "\\n";
|
|
||||||
break;
|
|
||||||
case "\r":
|
|
||||||
result += "\\r";
|
|
||||||
break;
|
|
||||||
case "\t":
|
|
||||||
result += "\\t";
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
result += char;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return `"${result}"`;
|
|
||||||
};
|
|
||||||
|
|
||||||
const quoteString = (s: string): string => `"${s}"`;
|
|
||||||
|
|
||||||
export const generateAterm = (drv: DerivationData): string => {
|
|
||||||
const outputEntries: string[] = [];
|
|
||||||
const sortedOutputs = Array.from(drv.outputs.entries()).sort();
|
|
||||||
for (const [name, info] of sortedOutputs) {
|
|
||||||
outputEntries.push(
|
|
||||||
`(${quoteString(name)},${quoteString(info.path)},${quoteString(info.hashAlgo)},${quoteString(info.hash)})`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const outputs = outputEntries.join(",");
|
|
||||||
|
|
||||||
const inputDrvEntries: string[] = [];
|
|
||||||
for (const [drvPath, outputs] of drv.inputDrvs) {
|
|
||||||
const outList = `[${Array.from(outputs).map(quoteString).join(",")}]`;
|
|
||||||
inputDrvEntries.push(`(${quoteString(drvPath)},${outList})`);
|
|
||||||
}
|
|
||||||
const inputDrvs = inputDrvEntries.join(",");
|
|
||||||
|
|
||||||
const inputSrcs = Array.from(drv.inputSrcs).map(quoteString).join(",");
|
|
||||||
|
|
||||||
const args = drv.args.map(escapeString).join(",");
|
|
||||||
const envs = Array.from(drv.env.entries())
|
|
||||||
.sort()
|
|
||||||
.map(([k, v]) => `(${escapeString(k)},${escapeString(v)})`);
|
|
||||||
|
|
||||||
return `Derive([${outputs}],[${inputDrvs}],[${inputSrcs}],${quoteString(drv.platform)},${quoteString(drv.builder)},[${args}],[${envs}])`;
|
|
||||||
};
|
|
||||||
@@ -1,18 +1,14 @@
|
|||||||
/**
|
|
||||||
* Helper functions for nix-js runtime
|
|
||||||
*/
|
|
||||||
|
|
||||||
import type { NixValue, NixAttrs, NixBool, NixString, NixPath } from "./types";
|
|
||||||
import { forceAttrs, forceBool, forceFunction, forceStringValue } from "./type-assert";
|
|
||||||
import { isAttrs, typeOf } from "./builtins/type-check";
|
|
||||||
import { coerceToString, StringCoercionMode } from "./builtins/conversion";
|
import { coerceToString, StringCoercionMode } from "./builtins/conversion";
|
||||||
import { type NixStringContext, mkStringWithContext, isStringWithContext } from "./string-context";
|
import { isAttrs, typeOf } from "./builtins/type-check";
|
||||||
import { force } from "./thunk";
|
|
||||||
import { mkPath } from "./path";
|
import { mkPath } from "./path";
|
||||||
|
import { isStringWithContext, mkStringWithContext, type NixStringContext } from "./string-context";
|
||||||
|
import { force } from "./thunk";
|
||||||
|
import { forceAttrs, forceBool, forceFunction, forceStringNoCtx, forceStringValue } from "./type-assert";
|
||||||
|
import type { NixAttrs, NixBool, NixPath, NixString, NixValue } from "./types";
|
||||||
import { CatchableError, isNixPath } from "./types";
|
import { CatchableError, isNixPath } from "./types";
|
||||||
|
|
||||||
interface StackFrame {
|
interface StackFrame {
|
||||||
span: string;
|
span: number;
|
||||||
message: string;
|
message: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,35 +32,18 @@ function enrichError(error: unknown): Error {
|
|||||||
return err;
|
return err;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getTos = (): string => {
|
const pushContext = (message: string, span: number): void => {
|
||||||
const tos = callStack[callStack.length - 2];
|
|
||||||
const { file, line, column } = Deno.core.ops.op_decode_span(tos.span);
|
|
||||||
return `${tos.message} at ${file}:${line}:${column}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Push an error context onto the stack
|
|
||||||
* Used for tracking evaluation context (e.g., "while evaluating the condition")
|
|
||||||
*/
|
|
||||||
export const pushContext = (message: string, span: string): void => {
|
|
||||||
if (callStack.length >= MAX_STACK_DEPTH) {
|
if (callStack.length >= MAX_STACK_DEPTH) {
|
||||||
callStack.shift();
|
callStack.shift();
|
||||||
}
|
}
|
||||||
callStack.push({ span, message });
|
callStack.push({ span, message });
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
const popContext = (): void => {
|
||||||
* Pop an error context from the stack
|
|
||||||
*/
|
|
||||||
export const popContext = (): void => {
|
|
||||||
callStack.pop();
|
callStack.pop();
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
export const withContext = <T>(message: string, span: number, fn: () => T): T => {
|
||||||
* Execute a function with error context tracking
|
|
||||||
* Automatically pushes context before execution and pops after
|
|
||||||
*/
|
|
||||||
export const withContext = <T>(message: string, span: string, fn: () => T): T => {
|
|
||||||
pushContext(message, span);
|
pushContext(message, span);
|
||||||
try {
|
try {
|
||||||
return fn();
|
return fn();
|
||||||
@@ -149,13 +128,6 @@ export const concatStringsWithContext = (parts: NixValue[], forceString: boolean
|
|||||||
return mkStringWithContext(value, context);
|
return mkStringWithContext(value, context);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolve a path (handles both absolute and relative paths)
|
|
||||||
* For relative paths, resolves against current import stack
|
|
||||||
*
|
|
||||||
* @param path - Path string (may be relative or absolute)
|
|
||||||
* @returns NixPath object with absolute path
|
|
||||||
*/
|
|
||||||
export const resolvePath = (currentDir: string, path: NixValue): NixPath => {
|
export const resolvePath = (currentDir: string, path: NixValue): NixPath => {
|
||||||
const forced = force(path);
|
const forced = force(path);
|
||||||
let pathStr: string;
|
let pathStr: string;
|
||||||
@@ -170,86 +142,92 @@ export const resolvePath = (currentDir: string, path: NixValue): NixPath => {
|
|||||||
return mkPath(resolved);
|
return mkPath(resolved);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const select = (obj: NixValue, attrpath: NixValue[], span?: string): NixValue => {
|
export const select = (obj: NixValue, attrpath: NixValue[], span?: number): NixValue => {
|
||||||
if (span) {
|
if (span !== undefined) {
|
||||||
const pathStrings = attrpath.map((a) => forceStringValue(a));
|
|
||||||
const path = pathStrings.join(".");
|
|
||||||
const message = path ? `while selecting attribute [${path}]` : "while selecting attribute";
|
|
||||||
|
|
||||||
if (callStack.length >= MAX_STACK_DEPTH) {
|
if (callStack.length >= MAX_STACK_DEPTH) {
|
||||||
callStack.shift();
|
callStack.shift();
|
||||||
}
|
}
|
||||||
callStack.push({ span, message });
|
const frame: StackFrame = { span, message: "while selecting attribute" };
|
||||||
|
callStack.push(frame);
|
||||||
try {
|
try {
|
||||||
return select_impl(obj, attrpath);
|
return selectImpl(obj, attrpath);
|
||||||
} catch (error) {
|
} 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);
|
throw enrichError(error);
|
||||||
} finally {
|
} finally {
|
||||||
callStack.pop();
|
callStack.pop();
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return select_impl(obj, attrpath);
|
return selectImpl(obj, attrpath);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
function select_impl(obj: NixValue, attrpath: NixValue[]): NixValue {
|
function selectImpl(obj: NixValue, attrpath: NixValue[]): NixValue {
|
||||||
let attrs = forceAttrs(obj);
|
let attrs = forceAttrs(obj);
|
||||||
|
|
||||||
for (const attr of attrpath.slice(0, -1)) {
|
for (let i = 0; i < attrpath.length - 1; i++) {
|
||||||
const key = forceStringValue(attr);
|
const key = forceStringValue(attrpath[i]);
|
||||||
if (!(key in attrs)) {
|
if (!attrs.has(key)) {
|
||||||
throw new Error(`Attribute '${key}' not found`);
|
throw new Error(`Attribute '${key}' not found`);
|
||||||
}
|
}
|
||||||
const cur = forceAttrs(attrs[forceStringValue(attr)]);
|
const cur = forceAttrs(attrs.get(key) as NixValue);
|
||||||
attrs = cur;
|
attrs = cur;
|
||||||
}
|
}
|
||||||
|
|
||||||
const last = forceStringValue(attrpath[attrpath.length - 1]);
|
const last = forceStringValue(attrpath[attrpath.length - 1]);
|
||||||
if (!(last in attrs)) {
|
if (!attrs.has(last)) {
|
||||||
throw new Error(`Attribute '${last}' not found`);
|
throw new Error(`Attribute '${last}' not found`);
|
||||||
}
|
}
|
||||||
return attrs[last];
|
return attrs.get(last) as NixValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const selectWithDefault = (
|
export const selectWithDefault = (
|
||||||
obj: NixValue,
|
obj: NixValue,
|
||||||
attrpath: NixValue[],
|
attrpath: NixValue[],
|
||||||
default_val: NixValue,
|
defaultVal: NixValue,
|
||||||
span?: string,
|
span?: number,
|
||||||
): NixValue => {
|
): NixValue => {
|
||||||
if (span) {
|
if (span !== undefined) {
|
||||||
const pathStrings = attrpath.map((a) => forceStringValue(a));
|
|
||||||
const path = pathStrings.join(".");
|
|
||||||
const message = path ? `while selecting attribute [${path}]` : "while selecting attribute";
|
|
||||||
|
|
||||||
if (callStack.length >= MAX_STACK_DEPTH) {
|
if (callStack.length >= MAX_STACK_DEPTH) {
|
||||||
callStack.shift();
|
callStack.shift();
|
||||||
}
|
}
|
||||||
callStack.push({ span, message });
|
const frame: StackFrame = { span, message: "while selecting attribute" };
|
||||||
|
callStack.push(frame);
|
||||||
try {
|
try {
|
||||||
return selectWithDefault_impl(obj, attrpath, default_val);
|
return selectWithDefaultImpl(obj, attrpath, defaultVal);
|
||||||
} catch (error) {
|
} 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);
|
throw enrichError(error);
|
||||||
} finally {
|
} finally {
|
||||||
callStack.pop();
|
callStack.pop();
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return selectWithDefault_impl(obj, attrpath, default_val);
|
return selectWithDefaultImpl(obj, attrpath, defaultVal);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
function selectWithDefault_impl(obj: NixValue, attrpath: NixValue[], defaultVal: NixValue): NixValue {
|
function selectWithDefaultImpl(obj: NixValue, attrpath: NixValue[], defaultVal: NixValue): NixValue {
|
||||||
let attrs = force(obj);
|
let attrs = force(obj);
|
||||||
if (!isAttrs(attrs)) {
|
if (!isAttrs(attrs)) {
|
||||||
return defaultVal;
|
return defaultVal;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const attr of attrpath.slice(0, -1)) {
|
for (let i = 0; i < attrpath.length - 1; i++) {
|
||||||
const key = forceStringValue(attr);
|
const key = forceStringValue(attrpath[i]);
|
||||||
if (!(key in attrs)) {
|
if (!attrs.has(key)) {
|
||||||
return defaultVal;
|
return defaultVal;
|
||||||
}
|
}
|
||||||
const cur = force(attrs[key]);
|
const cur = force(attrs.get(key) as NixValue);
|
||||||
if (!isAttrs(cur)) {
|
if (!isAttrs(cur)) {
|
||||||
return defaultVal;
|
return defaultVal;
|
||||||
}
|
}
|
||||||
@@ -257,8 +235,8 @@ function selectWithDefault_impl(obj: NixValue, attrpath: NixValue[], defaultVal:
|
|||||||
}
|
}
|
||||||
|
|
||||||
const last = forceStringValue(attrpath[attrpath.length - 1]);
|
const last = forceStringValue(attrpath[attrpath.length - 1]);
|
||||||
if (last in attrs) {
|
if (attrs.has(last)) {
|
||||||
return attrs[last];
|
return attrs.get(last) as NixValue;
|
||||||
}
|
}
|
||||||
return defaultVal;
|
return defaultVal;
|
||||||
}
|
}
|
||||||
@@ -270,97 +248,53 @@ export const hasAttr = (obj: NixValue, attrpath: NixValue[]): NixBool => {
|
|||||||
}
|
}
|
||||||
let attrs = forced;
|
let attrs = forced;
|
||||||
|
|
||||||
for (const attr of attrpath.slice(0, -1)) {
|
for (let i = 0; i < attrpath.length - 1; i++) {
|
||||||
const cur = force(attrs[forceStringValue(attr)]);
|
const key = forceStringNoCtx(attrpath[i]);
|
||||||
|
if (!attrs.has(key)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const cur = force(attrs.get(key) as NixValue);
|
||||||
if (!isAttrs(cur)) {
|
if (!isAttrs(cur)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
attrs = cur;
|
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?: number): NixValue => {
|
||||||
* Validate function parameters
|
if (span !== undefined) {
|
||||||
* Used for pattern matching in function parameters
|
|
||||||
*
|
|
||||||
* Example: { a, b ? 1, ... }: ...
|
|
||||||
* - required: ["a"]
|
|
||||||
* - allowed: ["a", "b"] (or null if ellipsis "..." present)
|
|
||||||
*
|
|
||||||
* @param arg - Argument object to validate
|
|
||||||
* @param required - Array of required parameter names (or null)
|
|
||||||
* @param allowed - Array of allowed parameter names (or null for ellipsis)
|
|
||||||
* @returns The forced argument object
|
|
||||||
* @throws Error if required param missing or unexpected param present
|
|
||||||
*/
|
|
||||||
export const validateParams = (
|
|
||||||
arg: NixValue,
|
|
||||||
required: string[] | null,
|
|
||||||
allowed: string[] | null,
|
|
||||||
): NixAttrs => {
|
|
||||||
const forced_arg = forceAttrs(arg);
|
|
||||||
|
|
||||||
// Check required parameters
|
|
||||||
if (required) {
|
|
||||||
for (const key of required) {
|
|
||||||
if (!Object.hasOwn(forced_arg, key)) {
|
|
||||||
throw new Error(`Function called without required argument '${key}'`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check allowed parameters (if not using ellipsis)
|
|
||||||
if (allowed) {
|
|
||||||
const allowed_set = new Set(allowed);
|
|
||||||
for (const key in forced_arg) {
|
|
||||||
if (!allowed_set.has(key)) {
|
|
||||||
throw new Error(`Function called with unexpected argument '${key}'`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return forced_arg;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const call = (func: NixValue, arg: NixValue, span?: string): NixValue => {
|
|
||||||
if (span) {
|
|
||||||
if (callStack.length >= MAX_STACK_DEPTH) {
|
if (callStack.length >= MAX_STACK_DEPTH) {
|
||||||
callStack.shift();
|
callStack.shift();
|
||||||
}
|
}
|
||||||
callStack.push({ span, message: "from call site" });
|
callStack.push({ span, message: "from call site" });
|
||||||
try {
|
try {
|
||||||
return call_impl(func, arg);
|
return callImpl(func, arg);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw enrichError(error);
|
throw enrichError(error);
|
||||||
} finally {
|
} finally {
|
||||||
callStack.pop();
|
callStack.pop();
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return call_impl(func, arg);
|
return callImpl(func, arg);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
function call_impl(func: NixValue, arg: NixValue): NixValue {
|
function callImpl(func: NixValue, arg: NixValue): NixValue {
|
||||||
const forcedFunc = force(func);
|
const forced = force(func);
|
||||||
if (typeof forcedFunc === "function") {
|
if (typeof forced === "function") {
|
||||||
forcedFunc.args?.check(arg);
|
forced.args?.check(arg);
|
||||||
return forcedFunc(arg);
|
return forced(arg);
|
||||||
}
|
}
|
||||||
if (
|
if (forced instanceof Map && forced.has("__functor")) {
|
||||||
typeof forcedFunc === "object" &&
|
const functor = forceFunction(forced.get("__functor") as NixValue);
|
||||||
!Array.isArray(forcedFunc) &&
|
return call(callImpl(functor, forced), arg);
|
||||||
forcedFunc !== null &&
|
|
||||||
"__functor" in forcedFunc
|
|
||||||
) {
|
|
||||||
const functor = forceFunction(forcedFunc.__functor);
|
|
||||||
return call(functor(forcedFunc), 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)) {
|
if (forceBool(assertion)) {
|
||||||
return expr;
|
return expr;
|
||||||
}
|
}
|
||||||
@@ -370,13 +304,23 @@ export const assert = (assertion: NixValue, expr: NixValue, assertionRaw: string
|
|||||||
throw "unreachable";
|
throw "unreachable";
|
||||||
};
|
};
|
||||||
|
|
||||||
export const ifFunc = (cond: NixValue, consq: NixValue, alter: NixValue) => {
|
export const mkPos = (span: number): NixAttrs => {
|
||||||
if (forceBool(cond)) {
|
|
||||||
return consq;
|
|
||||||
}
|
|
||||||
return alter;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const mkPos = (span: string): NixAttrs => {
|
|
||||||
return Deno.core.ops.op_decode_span(span);
|
return Deno.core.ops.op_decode_span(span);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
interface WithScope {
|
||||||
|
env: NixValue;
|
||||||
|
last: WithScope | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const lookupWith = (name: string, withScope: WithScope): NixValue => {
|
||||||
|
let current: WithScope | null = withScope;
|
||||||
|
while (current !== null) {
|
||||||
|
const attrs = forceAttrs(current.env);
|
||||||
|
if (attrs.has(name)) {
|
||||||
|
return attrs.get(name) as NixValue;
|
||||||
|
}
|
||||||
|
current = current.last;
|
||||||
|
}
|
||||||
|
throw new Error(`undefined variable '${name}'`);
|
||||||
|
};
|
||||||
|
|||||||
@@ -4,68 +4,95 @@
|
|||||||
* All functionality is exported via the global `Nix` object
|
* All functionality is exported via the global `Nix` object
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { createThunk, force, isThunk, IS_THUNK, DEBUG_THUNKS, forceDeepSafe, IS_CYCLE } from "./thunk";
|
import { builtins, PRIMOP_METADATA } from "./builtins";
|
||||||
import {
|
import {
|
||||||
|
assert,
|
||||||
|
call,
|
||||||
|
concatStringsWithContext,
|
||||||
|
hasAttr,
|
||||||
|
lookupWith,
|
||||||
|
mkPos,
|
||||||
|
resolvePath,
|
||||||
select,
|
select,
|
||||||
selectWithDefault,
|
selectWithDefault,
|
||||||
validateParams,
|
|
||||||
resolvePath,
|
|
||||||
hasAttr,
|
|
||||||
concatStringsWithContext,
|
|
||||||
call,
|
|
||||||
assert,
|
|
||||||
pushContext,
|
|
||||||
popContext,
|
|
||||||
withContext,
|
|
||||||
mkPos,
|
|
||||||
} from "./helpers";
|
} from "./helpers";
|
||||||
import { op } from "./operators";
|
import { op } from "./operators";
|
||||||
import { builtins, PRIMOP_METADATA } from "./builtins";
|
|
||||||
import { coerceToString, StringCoercionMode } from "./builtins/conversion";
|
|
||||||
import { HAS_CONTEXT } from "./string-context";
|
import { HAS_CONTEXT } from "./string-context";
|
||||||
import { IS_PATH, mkAttrs, mkFunction, mkAttrsWithPos, ATTR_POSITIONS } from "./types";
|
import { createThunk, DEBUG_THUNKS, force, forceDeep, forceShallow, IS_CYCLE, IS_THUNK } from "./thunk";
|
||||||
import { forceBool } from "./type-assert";
|
import { forceBool } from "./type-assert";
|
||||||
|
import { IS_PATH, mkAttrs, mkFunction, type NixValue } from "./types";
|
||||||
|
import { execBytecode, execBytecodeScoped, vmStrings, vmConstants } from "./vm";
|
||||||
|
|
||||||
export type NixRuntime = typeof Nix;
|
export type NixRuntime = typeof Nix;
|
||||||
|
|
||||||
/**
|
const replBindings: Map<string, NixValue> = new Map();
|
||||||
* The global Nix runtime object
|
|
||||||
*/
|
|
||||||
export const Nix = {
|
export const Nix = {
|
||||||
createThunk,
|
|
||||||
force,
|
|
||||||
forceDeepSafe,
|
|
||||||
forceBool,
|
|
||||||
isThunk,
|
|
||||||
IS_THUNK,
|
IS_THUNK,
|
||||||
IS_CYCLE,
|
IS_CYCLE,
|
||||||
HAS_CONTEXT,
|
HAS_CONTEXT,
|
||||||
IS_PATH,
|
IS_PATH,
|
||||||
|
PRIMOP_METADATA,
|
||||||
DEBUG_THUNKS,
|
DEBUG_THUNKS,
|
||||||
|
|
||||||
|
createThunk,
|
||||||
|
force,
|
||||||
|
forceBool,
|
||||||
|
forceShallow,
|
||||||
|
forceDeep,
|
||||||
|
|
||||||
assert,
|
assert,
|
||||||
call,
|
call,
|
||||||
hasAttr,
|
hasAttr,
|
||||||
select,
|
select,
|
||||||
selectWithDefault,
|
selectWithDefault,
|
||||||
validateParams,
|
lookupWith,
|
||||||
resolvePath,
|
resolvePath,
|
||||||
coerceToString,
|
|
||||||
concatStringsWithContext,
|
concatStringsWithContext,
|
||||||
StringCoercionMode,
|
|
||||||
mkAttrs,
|
mkAttrs,
|
||||||
mkAttrsWithPos,
|
|
||||||
mkFunction,
|
mkFunction,
|
||||||
mkPos,
|
mkPos,
|
||||||
ATTR_POSITIONS,
|
|
||||||
|
|
||||||
pushContext,
|
|
||||||
popContext,
|
|
||||||
withContext,
|
|
||||||
|
|
||||||
op,
|
op,
|
||||||
builtins,
|
builtins,
|
||||||
PRIMOP_METADATA,
|
|
||||||
|
strings: vmStrings,
|
||||||
|
constants: vmConstants,
|
||||||
|
execBytecode,
|
||||||
|
execBytecodeScoped,
|
||||||
|
|
||||||
|
replBindings,
|
||||||
|
setReplBinding: (name: string, value: NixValue) => {
|
||||||
|
replBindings.set(name, value);
|
||||||
|
},
|
||||||
|
getReplBinding: (name: string) => replBindings.get(name),
|
||||||
};
|
};
|
||||||
|
|
||||||
globalThis.Nix = Nix;
|
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();
|
||||||
|
|||||||
@@ -1,31 +1,27 @@
|
|||||||
/**
|
|
||||||
* Nix operators module
|
|
||||||
* Implements all binary and unary operators used by codegen
|
|
||||||
*/
|
|
||||||
|
|
||||||
import type { NixValue, NixList, NixAttrs, NixString, NixPath } from "./types";
|
|
||||||
import { isNixPath } from "./types";
|
|
||||||
import { force } from "./thunk";
|
|
||||||
import { forceNumeric, forceList, forceAttrs, coerceNumeric } from "./type-assert";
|
|
||||||
import { getStringValue, getStringContext, mergeContexts, mkStringWithContext } from "./string-context";
|
|
||||||
import { coerceToString, StringCoercionMode } from "./builtins/conversion";
|
import { coerceToString, StringCoercionMode } from "./builtins/conversion";
|
||||||
|
import { isNixString, typeOf } from "./builtins/type-check";
|
||||||
import { mkPath } from "./path";
|
import { mkPath } from "./path";
|
||||||
import { typeOf, isNixString } from "./builtins/type-check";
|
import {
|
||||||
|
getStringContext,
|
||||||
|
getStringValue,
|
||||||
|
mergeContexts,
|
||||||
|
mkStringWithContext,
|
||||||
|
type NixStringContext,
|
||||||
|
} from "./string-context";
|
||||||
|
import { force } from "./thunk";
|
||||||
|
import { coerceNumeric, forceAttrs, forceBool, forceList, forceNumeric } from "./type-assert";
|
||||||
|
import type { NixAttrs, NixList, NixPath, NixString, NixValue } from "./types";
|
||||||
|
import { isNixPath } from "./types";
|
||||||
|
|
||||||
const canCoerceToString = (v: NixValue): boolean => {
|
const canCoerceToString = (v: NixValue): boolean => {
|
||||||
const forced = force(v);
|
const forced = force(v);
|
||||||
if (isNixString(forced)) return true;
|
if (isNixString(forced)) return true;
|
||||||
if (typeof forced === "object" && forced !== null && !Array.isArray(forced)) {
|
if (forced instanceof Map) {
|
||||||
if ("outPath" in forced || "__toString" in forced) return true;
|
if (forced.has("outPath") || forced.has("__toString")) return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Compare two values, similar to Nix's CompareValues.
|
|
||||||
* Returns: -1 if a < b, 0 if a == b, 1 if a > b
|
|
||||||
* Throws TypeError for incomparable types.
|
|
||||||
*/
|
|
||||||
export const compareValues = (a: NixValue, b: NixValue): -1 | 0 | 1 => {
|
export const compareValues = (a: NixValue, b: NixValue): -1 | 0 | 1 => {
|
||||||
const av = force(a);
|
const av = force(a);
|
||||||
const bv = force(b);
|
const bv = force(b);
|
||||||
@@ -48,32 +44,29 @@ export const compareValues = (a: NixValue, b: NixValue): -1 | 0 | 1 => {
|
|||||||
throw new TypeError(`cannot compare ${typeOf(av)} with ${typeOf(bv)}`);
|
throw new TypeError(`cannot compare ${typeOf(av)} with ${typeOf(bv)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Int and float comparison
|
|
||||||
if (typeA === "int" || typeA === "float") {
|
if (typeA === "int" || typeA === "float") {
|
||||||
return av! < bv! ? -1 : av === bv ? 0 : 1;
|
return (av as never) < (bv as never) ? -1 : av === bv ? 0 : 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// String comparison (handles both plain strings and StringWithContext)
|
|
||||||
if (typeA === "string") {
|
if (typeA === "string") {
|
||||||
const strA = getStringValue(av as NixString);
|
const strA = getStringValue(av as NixString);
|
||||||
const strB = getStringValue(bv as NixString);
|
const strB = getStringValue(bv as NixString);
|
||||||
return strA < strB ? -1 : strA > strB ? 1 : 0;
|
return strA < strB ? -1 : strA > strB ? 1 : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Path comparison
|
|
||||||
if (typeA === "path") {
|
if (typeA === "path") {
|
||||||
const aPath = av as NixPath;
|
const aPath = av as NixPath;
|
||||||
const bPath = bv as NixPath;
|
const bPath = bv as NixPath;
|
||||||
return aPath.value < bPath.value ? -1 : aPath.value > bPath.value ? 1 : 0;
|
return aPath.value < bPath.value ? -1 : aPath.value > bPath.value ? 1 : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// List comparison (lexicographic)
|
|
||||||
if (typeA === "list") {
|
if (typeA === "list") {
|
||||||
const aList = av as NixList;
|
const aList = av as NixList;
|
||||||
const bList = bv as NixList;
|
const bList = bv as NixList;
|
||||||
for (let i = 0; ; i++) {
|
for (let i = 0; ; i++) {
|
||||||
|
// Equal if same length, else aList > bList
|
||||||
if (i === bList.length) {
|
if (i === bList.length) {
|
||||||
return i === aList.length ? 0 : 1; // Equal if same length, else aList > bList
|
return i === aList.length ? 0 : 1;
|
||||||
} else if (i === aList.length) {
|
} else if (i === aList.length) {
|
||||||
return -1; // aList < bList
|
return -1; // aList < bList
|
||||||
} else if (!op.eq(aList[i], bList[i])) {
|
} else if (!op.eq(aList[i], bList[i])) {
|
||||||
@@ -88,10 +81,6 @@ export const compareValues = (a: NixValue, b: NixValue): -1 | 0 | 1 => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Operator object exported as Nix.op
|
|
||||||
* All operators referenced by codegen (e.g., Nix.op.add, Nix.op.eq)
|
|
||||||
*/
|
|
||||||
export const op = {
|
export const op = {
|
||||||
add: (a: NixValue, b: NixValue): bigint | number | NixString | NixPath => {
|
add: (a: NixValue, b: NixValue): bigint | number | NixString | NixPath => {
|
||||||
const av = force(a);
|
const av = force(a);
|
||||||
@@ -103,15 +92,14 @@ export const op = {
|
|||||||
const strB = getStringValue(bv);
|
const strB = getStringValue(bv);
|
||||||
const ctxB = getStringContext(bv);
|
const ctxB = getStringContext(bv);
|
||||||
|
|
||||||
// Lix constraint: cannot append string with store context to path
|
|
||||||
if (ctxB.size > 0) {
|
if (ctxB.size > 0) {
|
||||||
throw new TypeError("a string that refers to a store path cannot be appended to a path");
|
throw new TypeError("a string that refers to a store path cannot be appended to a path");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Concatenate paths
|
|
||||||
return mkPath(av.value + strB);
|
return mkPath(av.value + strB);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FIXME: handle corepkgs
|
||||||
// path + path: concatenate
|
// path + path: concatenate
|
||||||
if (isNixPath(bv)) {
|
if (isNixPath(bv)) {
|
||||||
return mkPath(av.value + bv.value);
|
return mkPath(av.value + bv.value);
|
||||||
@@ -132,6 +120,7 @@ export const op = {
|
|||||||
|
|
||||||
// String concatenation
|
// String concatenation
|
||||||
if (isNixString(av) && isNixString(bv)) {
|
if (isNixString(av) && isNixString(bv)) {
|
||||||
|
// Merge string context
|
||||||
const strA = getStringValue(av);
|
const strA = getStringValue(av);
|
||||||
const strB = getStringValue(bv);
|
const strB = getStringValue(bv);
|
||||||
const ctxA = getStringContext(av);
|
const ctxA = getStringContext(av);
|
||||||
@@ -146,24 +135,29 @@ export const op = {
|
|||||||
|
|
||||||
// Auto-coerce to string if possible
|
// Auto-coerce to string if possible
|
||||||
if (canCoerceToString(a) && canCoerceToString(b)) {
|
if (canCoerceToString(a) && canCoerceToString(b)) {
|
||||||
const strA = coerceToString(a, StringCoercionMode.Interpolation, false);
|
const context: NixStringContext = new Set();
|
||||||
const strB = coerceToString(b, StringCoercionMode.Interpolation, false);
|
const strA = coerceToString(a, StringCoercionMode.Interpolation, false, context);
|
||||||
return strA + strB;
|
const strB = coerceToString(b, StringCoercionMode.Interpolation, false, context);
|
||||||
|
const result = strA + strB;
|
||||||
|
if (context.size === 0) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
return mkStringWithContext(result, context);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Numeric addition
|
// Perform numeric addition otherwise
|
||||||
const [numA, numB] = coerceNumeric(forceNumeric(a), forceNumeric(b));
|
const [numA, numB] = coerceNumeric(forceNumeric(a), forceNumeric(b));
|
||||||
return (numA as any) + (numB as any);
|
return (numA as never) + (numB as never);
|
||||||
},
|
},
|
||||||
|
|
||||||
sub: (a: NixValue, b: NixValue): bigint | number => {
|
sub: (a: NixValue, b: NixValue): bigint | number => {
|
||||||
const [av, bv] = coerceNumeric(forceNumeric(a), forceNumeric(b));
|
const [av, bv] = coerceNumeric(forceNumeric(a), forceNumeric(b));
|
||||||
return (av as any) - (bv as any);
|
return (av as never) - (bv as never);
|
||||||
},
|
},
|
||||||
|
|
||||||
mul: (a: NixValue, b: NixValue): bigint | number => {
|
mul: (a: NixValue, b: NixValue): bigint | number => {
|
||||||
const [av, bv] = coerceNumeric(forceNumeric(a), forceNumeric(b));
|
const [av, bv] = coerceNumeric(forceNumeric(a), forceNumeric(b));
|
||||||
return (av as any) * (bv as any);
|
return (av as never) * (bv as never);
|
||||||
},
|
},
|
||||||
|
|
||||||
div: (a: NixValue, b: NixValue): bigint | number => {
|
div: (a: NixValue, b: NixValue): bigint | number => {
|
||||||
@@ -173,7 +167,7 @@ export const op = {
|
|||||||
throw new RangeError("Division by zero");
|
throw new RangeError("Division by zero");
|
||||||
}
|
}
|
||||||
|
|
||||||
return (av as any) / (bv as any);
|
return (av as never) / (bv as never);
|
||||||
},
|
},
|
||||||
|
|
||||||
eq: (a: NixValue, b: NixValue): boolean => {
|
eq: (a: NixValue, b: NixValue): boolean => {
|
||||||
@@ -191,7 +185,6 @@ export const op = {
|
|||||||
return av === Number(bv);
|
return av === Number(bv);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get type names for comparison (skip if already handled above)
|
|
||||||
const typeA = typeOf(av);
|
const typeA = typeOf(av);
|
||||||
const typeB = typeOf(bv);
|
const typeB = typeOf(bv);
|
||||||
|
|
||||||
@@ -212,10 +205,12 @@ export const op = {
|
|||||||
return (av as NixPath).value === (bv as NixPath).value;
|
return (av as NixPath).value === (bv as NixPath).value;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Array.isArray(av) && Array.isArray(bv)) {
|
if (typeA === "list") {
|
||||||
if (av.length !== bv.length) return false;
|
const aList = av as NixList;
|
||||||
for (let i = 0; i < av.length; i++) {
|
const bList = bv as NixList;
|
||||||
if (!op.eq(av[i], bv[i])) return false;
|
if (aList.length !== bList.length) return false;
|
||||||
|
for (let i = 0; i < aList.length; i++) {
|
||||||
|
if (!op.eq(aList[i], bList[i])) return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -224,37 +219,30 @@ export const op = {
|
|||||||
const attrsA = av as NixAttrs;
|
const attrsA = av as NixAttrs;
|
||||||
const attrsB = bv as NixAttrs;
|
const attrsB = bv as NixAttrs;
|
||||||
|
|
||||||
// Derivation comparison: compare outPaths only
|
if (attrsA.has("type") && attrsB.has("type")) {
|
||||||
// Safe to force 'type' because it's always a string literal, never a computed value
|
const typeValA = force(attrsA.get("type") as NixValue);
|
||||||
if ("type" in attrsA && "type" in attrsB) {
|
const typeValB = force(attrsB.get("type") as NixValue);
|
||||||
const typeValA = force(attrsA.type);
|
|
||||||
const typeValB = force(attrsB.type);
|
|
||||||
if (typeValA === "derivation" && typeValB === "derivation") {
|
if (typeValA === "derivation" && typeValB === "derivation") {
|
||||||
if ("outPath" in attrsA && "outPath" in attrsB) {
|
if (attrsA.has("outPath") && attrsB.has("outPath")) {
|
||||||
return op.eq(attrsA.outPath, attrsB.outPath);
|
return op.eq(attrsA.get("outPath") as NixValue, attrsB.get("outPath") as NixValue);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Otherwise, compare attributes one by one
|
const keysA = Array.from(attrsA.keys()).sort();
|
||||||
const keysA = Object.keys(attrsA).sort();
|
const keysB = Array.from(attrsB.keys()).sort();
|
||||||
const keysB = Object.keys(attrsB).sort();
|
|
||||||
|
|
||||||
if (keysA.length !== keysB.length) return false;
|
if (keysA.length !== keysB.length) return false;
|
||||||
|
|
||||||
for (let i = 0; i < keysA.length; i++) {
|
for (let i = 0; i < keysA.length; i++) {
|
||||||
if (keysA[i] !== keysB[i]) return false;
|
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;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Functions are incomparable
|
// Other types are incomparable
|
||||||
if (typeof av === "function") {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
},
|
},
|
||||||
neq: (a: NixValue, b: NixValue): boolean => {
|
neq: (a: NixValue, b: NixValue): boolean => {
|
||||||
@@ -273,11 +261,25 @@ export const op = {
|
|||||||
return compareValues(a, b) >= 0;
|
return compareValues(a, b) >= 0;
|
||||||
},
|
},
|
||||||
|
|
||||||
bnot: (a: NixValue): boolean => !force(a),
|
bnot: (a: NixValue): boolean => !forceBool(a),
|
||||||
|
|
||||||
concat: (a: NixValue, b: NixValue): NixList => {
|
concat: (a: NixValue, b: NixValue): NixList => {
|
||||||
return Array.prototype.concat.call(forceList(a), forceList(b));
|
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 canonicalizePath = (path: string): string => {
|
||||||
const parts: string[] = [];
|
const parts: string[] = [];
|
||||||
@@ -14,13 +14,11 @@ const canonicalizePath = (path: string): string => {
|
|||||||
const component = path.slice(i, j);
|
const component = path.slice(i, j);
|
||||||
i = j;
|
i = j;
|
||||||
|
|
||||||
if (component === ".") {
|
if (component === "..") {
|
||||||
continue;
|
|
||||||
} else if (component === "..") {
|
|
||||||
if (parts.length > 0) {
|
if (parts.length > 0) {
|
||||||
parts.pop();
|
parts.pop();
|
||||||
}
|
}
|
||||||
} else {
|
} else if (component !== ".") {
|
||||||
parts.push(component);
|
parts.push(component);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -28,11 +26,11 @@ const canonicalizePath = (path: string): string => {
|
|||||||
if (parts.length === 0) {
|
if (parts.length === 0) {
|
||||||
return "/";
|
return "/";
|
||||||
}
|
}
|
||||||
return "/" + parts.join("/");
|
return `/${parts.join("/")}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const mkPath = (value: string): NixPath => {
|
export const mkPath = (value: string): NixPath => {
|
||||||
return { [IS_PATH]: true, value: canonicalizePath(value) };
|
return new NixPath(canonicalizePath(value));
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getPathValue = (p: NixPath): string => {
|
export const getPathValue = (p: NixPath): string => {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { isThunk, IS_CYCLE } from "./thunk";
|
import { getPrimopMetadata, isPrimop } from "./builtins/index";
|
||||||
import { isStringWithContext } from "./string-context";
|
import { isStringWithContext } from "./string-context";
|
||||||
|
import { IS_CYCLE, isThunk } from "./thunk";
|
||||||
import { isNixPath, type NixValue } from "./types";
|
import { isNixPath, type NixValue } from "./types";
|
||||||
import { is_primop, get_primop_metadata } from "./builtins/index";
|
|
||||||
|
|
||||||
export const printValue = (value: NixValue, seen: WeakSet<object> = new WeakSet()): string => {
|
export const printValue = (value: NixValue, seen: WeakSet<object> = new WeakSet()): string => {
|
||||||
if (isThunk(value)) {
|
if (isThunk(value)) {
|
||||||
@@ -29,8 +29,8 @@ export const printValue = (value: NixValue, seen: WeakSet<object> = new WeakSet(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (typeof value === "function") {
|
if (typeof value === "function") {
|
||||||
if (is_primop(value)) {
|
if (isPrimop(value)) {
|
||||||
const meta = get_primop_metadata(value);
|
const meta = getPrimopMetadata(value);
|
||||||
if (meta && meta.applied > 0) {
|
if (meta && meta.applied > 0) {
|
||||||
return "<PRIMOP-APP>";
|
return "<PRIMOP-APP>";
|
||||||
}
|
}
|
||||||
@@ -39,16 +39,10 @@ export const printValue = (value: NixValue, seen: WeakSet<object> = new WeakSet(
|
|||||||
return "<LAMBDA>";
|
return "<LAMBDA>";
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof value === "object") {
|
if (IS_CYCLE in value) {
|
||||||
if (IS_CYCLE in value && (value as any)[IS_CYCLE] === true) {
|
|
||||||
return "«repeated»";
|
return "«repeated»";
|
||||||
}
|
}
|
||||||
|
|
||||||
if (seen.has(value)) {
|
|
||||||
return "«repeated»";
|
|
||||||
}
|
|
||||||
seen.add(value);
|
|
||||||
|
|
||||||
if (isNixPath(value)) {
|
if (isNixPath(value)) {
|
||||||
return value.value;
|
return value.value;
|
||||||
}
|
}
|
||||||
@@ -58,17 +52,27 @@ export const printValue = (value: NixValue, seen: WeakSet<object> = new WeakSet(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (Array.isArray(value)) {
|
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(" ");
|
const items = value.map((v) => printValue(v, seen)).join(" ");
|
||||||
return `[ ${items} ]`;
|
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)};`)
|
.map(([k, v]) => `${printSymbol(k)} = ${printValue(v, seen)};`)
|
||||||
.join(" ");
|
.join(" ");
|
||||||
return `{${entries ? ` ${entries} ` : " "}}`;
|
return `{${entries ? ` ${entries} ` : " "}}`;
|
||||||
}
|
|
||||||
|
|
||||||
return "<unknown>";
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const printString = (s: string): string => {
|
const printString = (s: string): string => {
|
||||||
@@ -94,7 +98,7 @@ const printString = (s: string): string => {
|
|||||||
result += c;
|
result += c;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return result + '"';
|
return `${result}"`;
|
||||||
};
|
};
|
||||||
|
|
||||||
const SYMBOL_REGEX = /^[a-zA-Z_][a-zA-Z0-9_'-]*$/;
|
const SYMBOL_REGEX = /^[a-zA-Z_][a-zA-Z0-9_'-]*$/;
|
||||||
|
|||||||
@@ -1,29 +1,4 @@
|
|||||||
/**
|
import type { NixStrictValue } from "./types";
|
||||||
* String Context System for Nix
|
|
||||||
*
|
|
||||||
* String context tracks references to store paths and derivations within strings.
|
|
||||||
* This is critical for Nix's dependency tracking - when a string containing a
|
|
||||||
* store path is used in a derivation, that store path becomes a build dependency.
|
|
||||||
*
|
|
||||||
* Context Elements (encoded as strings):
|
|
||||||
* - Opaque: Plain store path reference
|
|
||||||
* Format: "/nix/store/..."
|
|
||||||
* Example: "/nix/store/abc123-hello"
|
|
||||||
*
|
|
||||||
* - DrvDeep: Derivation with all outputs
|
|
||||||
* Format: "=/nix/store/...drv"
|
|
||||||
* Example: "=/nix/store/xyz789-hello.drv"
|
|
||||||
* Meaning: All outputs of this derivation and its closure
|
|
||||||
*
|
|
||||||
* - Built: Specific derivation output
|
|
||||||
* Format: "!<output>!/nix/store/...drv"
|
|
||||||
* Example: "!out!/nix/store/xyz789-hello.drv"
|
|
||||||
* Meaning: Specific output (e.g., "out", "dev", "lib") of this derivation
|
|
||||||
*
|
|
||||||
* This implementation matches Lix's NixStringContext system.
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { NixStrictValue } from "./types";
|
|
||||||
|
|
||||||
export const HAS_CONTEXT = Symbol("HAS_CONTEXT");
|
export const HAS_CONTEXT = Symbol("HAS_CONTEXT");
|
||||||
|
|
||||||
@@ -47,18 +22,22 @@ export type StringContextElem = StringContextOpaque | StringContextDrvDeep | Str
|
|||||||
|
|
||||||
export type NixStringContext = Set<string>;
|
export type NixStringContext = Set<string>;
|
||||||
|
|
||||||
export interface StringWithContext {
|
export class StringWithContext {
|
||||||
readonly [HAS_CONTEXT]: true;
|
readonly [HAS_CONTEXT] = true as const;
|
||||||
value: string;
|
value: string;
|
||||||
context: NixStringContext;
|
context: NixStringContext;
|
||||||
|
constructor(value: string, context: NixStringContext) {
|
||||||
|
this.value = value;
|
||||||
|
this.context = context;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const isStringWithContext = (v: NixStrictValue): v is StringWithContext => {
|
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 => {
|
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;
|
export const mkPlainString = (value: string): string => value;
|
||||||
@@ -70,11 +49,12 @@ export const getStringValue = (s: string | StringWithContext): string => {
|
|||||||
return s;
|
return s;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const emptyContext: NixStringContext = new Set();
|
||||||
export const getStringContext = (s: string | StringWithContext): NixStringContext => {
|
export const getStringContext = (s: string | StringWithContext): NixStringContext => {
|
||||||
if (isStringWithContext(s)) {
|
if (isStringWithContext(s)) {
|
||||||
return s.context;
|
return s.context;
|
||||||
}
|
}
|
||||||
return new Set();
|
return emptyContext;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const mergeContexts = (...contexts: NixStringContext[]): NixStringContext => {
|
export const mergeContexts = (...contexts: NixStringContext[]): NixStringContext => {
|
||||||
@@ -171,47 +151,3 @@ export const parseContextToInfoMap = (context: NixStringContext): Map<string, Pa
|
|||||||
|
|
||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Extract input derivations and source paths from context
|
|
||||||
*
|
|
||||||
* IMPORTANT: Used by derivation builder to determine build dependencies.
|
|
||||||
*
|
|
||||||
* Returns:
|
|
||||||
* - inputDrvs: Map of derivation paths to their required output names
|
|
||||||
* - inputSrcs: Set of plain store paths (opaque) and drvDeep references
|
|
||||||
*
|
|
||||||
* Context type handling:
|
|
||||||
* - Opaque: Added to inputSrcs
|
|
||||||
* - DrvDeep: Added to inputSrcs (entire derivation + all outputs)
|
|
||||||
* - Built: Added to inputDrvs with specific output name
|
|
||||||
*/
|
|
||||||
export const extractInputDrvsAndSrcs = (
|
|
||||||
context: NixStringContext,
|
|
||||||
): { inputDrvs: Map<string, Set<string>>; inputSrcs: Set<string> } => {
|
|
||||||
const inputDrvs = new Map<string, Set<string>>();
|
|
||||||
const inputSrcs = new Set<string>();
|
|
||||||
|
|
||||||
for (const encoded of context) {
|
|
||||||
const elem = decodeContextElem(encoded);
|
|
||||||
switch (elem.type) {
|
|
||||||
case "opaque":
|
|
||||||
inputSrcs.add(elem.path);
|
|
||||||
break;
|
|
||||||
case "drvDeep":
|
|
||||||
inputSrcs.add(elem.drvPath);
|
|
||||||
break;
|
|
||||||
case "built": {
|
|
||||||
let outputs = inputDrvs.get(elem.drvPath);
|
|
||||||
if (!outputs) {
|
|
||||||
outputs = new Set<string>();
|
|
||||||
inputDrvs.set(elem.drvPath, outputs);
|
|
||||||
}
|
|
||||||
outputs.add(elem.output);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { inputDrvs, inputSrcs };
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,16 +1,8 @@
|
|||||||
/**
|
import { isAttrs, isList } from "./builtins/type-check";
|
||||||
* Lazy evaluation system for nix-js
|
import { StringWithContext } from "./string-context";
|
||||||
* Implements thunks for lazy evaluation of Nix expressions
|
import type { NixAttrs, NixStrictValue, NixValue } from "./types";
|
||||||
*/
|
import { NixPath } from "./types";
|
||||||
|
|
||||||
import type { NixValue, NixThunkInterface, NixStrictValue } from "./types";
|
|
||||||
import { HAS_CONTEXT } from "./string-context";
|
|
||||||
import { IS_PATH } from "./types";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Symbol used to mark objects as thunks
|
|
||||||
* This is exported to Rust via Nix.IS_THUNK
|
|
||||||
*/
|
|
||||||
export const IS_THUNK = Symbol("is_thunk");
|
export const IS_THUNK = Symbol("is_thunk");
|
||||||
|
|
||||||
const forceStack: NixThunk[] = [];
|
const forceStack: NixThunk[] = [];
|
||||||
@@ -29,8 +21,7 @@ export const DEBUG_THUNKS = { enabled: true };
|
|||||||
* - Evaluating (blackhole): func is undefined, result is undefined
|
* - Evaluating (blackhole): func is undefined, result is undefined
|
||||||
* - Evaluated: func is undefined, result is defined
|
* - Evaluated: func is undefined, result is defined
|
||||||
*/
|
*/
|
||||||
export class NixThunk implements NixThunkInterface {
|
export class NixThunk {
|
||||||
[key: symbol]: any;
|
|
||||||
readonly [IS_THUNK] = true as const;
|
readonly [IS_THUNK] = true as const;
|
||||||
func: (() => NixValue) | undefined;
|
func: (() => NixValue) | undefined;
|
||||||
result: NixStrictValue | undefined;
|
result: NixStrictValue | undefined;
|
||||||
@@ -50,13 +41,8 @@ export class NixThunk implements NixThunkInterface {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export const isThunk = (value: NixValue): value is NixThunk => {
|
||||||
* Type guard to check if a value is a thunk
|
return value instanceof NixThunk;
|
||||||
* @param value - Value to check
|
|
||||||
* @returns true if value is a NixThunk
|
|
||||||
*/
|
|
||||||
export const isThunk = (value: unknown): value is NixThunkInterface => {
|
|
||||||
return value !== null && typeof value === "object" && IS_THUNK in value && value[IS_THUNK] === true;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -95,7 +81,7 @@ export const force = (value: NixValue): NixStrictValue => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const thunk = value as NixThunk;
|
const thunk = value as NixThunk;
|
||||||
const func = thunk.func!;
|
const func = thunk.func as () => NixValue;
|
||||||
thunk.func = undefined;
|
thunk.func = undefined;
|
||||||
|
|
||||||
if (DEBUG_THUNKS.enabled) {
|
if (DEBUG_THUNKS.enabled) {
|
||||||
@@ -125,25 +111,12 @@ export const force = (value: NixValue): NixStrictValue => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
export const createThunk = (func: () => NixValue, label?: string): NixThunk => {
|
||||||
* Create a new thunk from a function
|
|
||||||
* @param func - Function that produces a value when called
|
|
||||||
* @param label - Optional label for debugging
|
|
||||||
* @returns A new NixThunk wrapping the function
|
|
||||||
*/
|
|
||||||
export const createThunk = (func: () => NixValue, label?: string): NixThunkInterface => {
|
|
||||||
return new NixThunk(func, label);
|
return new NixThunk(func, label);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Symbol to mark cyclic references detected during deep forcing
|
|
||||||
*/
|
|
||||||
export const IS_CYCLE = Symbol("is_cycle");
|
export const IS_CYCLE = Symbol("is_cycle");
|
||||||
|
export const CYCLE_MARKER = { [IS_CYCLE]: true as const };
|
||||||
/**
|
|
||||||
* Marker object for cyclic references
|
|
||||||
*/
|
|
||||||
export const CYCLE_MARKER = { [IS_CYCLE]: true };
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deeply force a value, handling cycles by returning a special marker.
|
* Deeply force a value, handling cycles by returning a special marker.
|
||||||
@@ -151,7 +124,7 @@ export const CYCLE_MARKER = { [IS_CYCLE]: true };
|
|||||||
* Returns a fully forced value where thunks are replaced with their results.
|
* Returns a fully forced value where thunks are replaced with their results.
|
||||||
* Cyclic references are replaced with CYCLE_MARKER, preserving the container type.
|
* Cyclic references are replaced with CYCLE_MARKER, preserving the container type.
|
||||||
*/
|
*/
|
||||||
export const forceDeepSafe = (value: NixValue, seen: WeakSet<object> = new WeakSet()): NixStrictValue => {
|
export const forceDeep = (value: NixValue, seen: WeakSet<object> = new WeakSet()): NixStrictValue => {
|
||||||
const forced = force(value);
|
const forced = force(value);
|
||||||
|
|
||||||
if (forced === null || typeof forced !== "object") {
|
if (forced === null || typeof forced !== "object") {
|
||||||
@@ -159,25 +132,54 @@ export const forceDeepSafe = (value: NixValue, seen: WeakSet<object> = new WeakS
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (seen.has(forced)) {
|
if (seen.has(forced)) {
|
||||||
if (Array.isArray(forced)) {
|
|
||||||
return [CYCLE_MARKER];
|
|
||||||
}
|
|
||||||
return CYCLE_MARKER;
|
return CYCLE_MARKER;
|
||||||
}
|
}
|
||||||
|
if ((isAttrs(forced) && forced.size > 0) || (isList(forced) && forced.length > 0)) {
|
||||||
seen.add(forced);
|
seen.add(forced);
|
||||||
|
}
|
||||||
|
|
||||||
if (HAS_CONTEXT in forced || IS_PATH in forced) {
|
if (forced instanceof StringWithContext || forced instanceof NixPath) {
|
||||||
return forced;
|
return forced;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Array.isArray(forced)) {
|
if (Array.isArray(forced)) {
|
||||||
return forced.map((item) => forceDeepSafe(item, seen));
|
return forced.map((item) => forceDeep(item, seen));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof forced === "object") {
|
if (forced instanceof Map) {
|
||||||
const result: Record<string, NixValue> = {};
|
const result: NixAttrs = new Map();
|
||||||
for (const [key, val] of Object.entries(forced)) {
|
for (const [key, val] of forced) {
|
||||||
result[key] = forceDeepSafe(val, seen);
|
result.set(key, forceDeep(val, seen));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
return forced;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const forceShallow = (value: NixValue): NixStrictValue => {
|
||||||
|
const forced = force(value);
|
||||||
|
|
||||||
|
if (forced === null || typeof forced !== "object") {
|
||||||
|
return forced;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(forced)) {
|
||||||
|
return forced.map((item) => {
|
||||||
|
const forcedItem = force(item);
|
||||||
|
if (typeof forcedItem === "object" && forcedItem === forced) {
|
||||||
|
return CYCLE_MARKER;
|
||||||
|
} else {
|
||||||
|
return forcedItem;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isAttrs(forced)) {
|
||||||
|
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;
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +1,18 @@
|
|||||||
/**
|
import { isAttrs, isFunction, typeOf } from "./builtins/type-check";
|
||||||
* Type assertion helpers for runtime type checking
|
import { force } from "./thunk";
|
||||||
* These functions force evaluation and verify the type, throwing errors on mismatch
|
|
||||||
*/
|
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
NixValue,
|
|
||||||
NixList,
|
|
||||||
NixAttrs,
|
NixAttrs,
|
||||||
|
NixFloat,
|
||||||
NixFunction,
|
NixFunction,
|
||||||
NixInt,
|
NixInt,
|
||||||
NixFloat,
|
NixList,
|
||||||
NixNumber,
|
NixNumber,
|
||||||
NixString,
|
|
||||||
NixPath,
|
NixPath,
|
||||||
|
NixString,
|
||||||
|
NixValue,
|
||||||
} from "./types";
|
} from "./types";
|
||||||
import { isStringWithContext, isNixPath } from "./types";
|
import { isNixPath, isStringWithContext } from "./types";
|
||||||
import { force } from "./thunk";
|
|
||||||
import { isAttrs, isFunction, typeOf } from "./builtins/type-check";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Force a value and assert it's a list
|
|
||||||
* @throws TypeError if value is not a list after forcing
|
|
||||||
*/
|
|
||||||
export const forceList = (value: NixValue): NixList => {
|
export const forceList = (value: NixValue): NixList => {
|
||||||
const forced = force(value);
|
const forced = force(value);
|
||||||
if (!Array.isArray(forced)) {
|
if (!Array.isArray(forced)) {
|
||||||
@@ -30,32 +21,19 @@ export const forceList = (value: NixValue): NixList => {
|
|||||||
return forced;
|
return forced;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Force a value and assert it's a function or functor
|
|
||||||
* @throws TypeError if value is not a function or functor after forcing
|
|
||||||
*/
|
|
||||||
export const forceFunction = (value: NixValue): NixFunction => {
|
export const forceFunction = (value: NixValue): NixFunction => {
|
||||||
const forced = force(value);
|
const forced = force(value);
|
||||||
if (isFunction(forced)) {
|
if (isFunction(forced)) {
|
||||||
return forced;
|
return forced;
|
||||||
}
|
}
|
||||||
if (
|
if (forced instanceof Map && forced.has("__functor")) {
|
||||||
typeof forced === "object" &&
|
|
||||||
!Array.isArray(forced) &&
|
|
||||||
forced !== null &&
|
|
||||||
"__functor" in forced
|
|
||||||
) {
|
|
||||||
const functorSet = forced as NixAttrs;
|
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);
|
return (arg: NixValue) => forceFunction(functor(functorSet))(arg);
|
||||||
}
|
}
|
||||||
throw new TypeError(`Expected function, got ${typeOf(forced)}`);
|
throw new TypeError(`Expected function, got ${typeOf(forced)}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Force a value and assert it's an attribute set
|
|
||||||
* @throws TypeError if value is not an attribute set after forcing
|
|
||||||
*/
|
|
||||||
export const forceAttrs = (value: NixValue): NixAttrs => {
|
export const forceAttrs = (value: NixValue): NixAttrs => {
|
||||||
const forced = force(value);
|
const forced = force(value);
|
||||||
if (!isAttrs(forced)) {
|
if (!isAttrs(forced)) {
|
||||||
@@ -64,10 +42,6 @@ export const forceAttrs = (value: NixValue): NixAttrs => {
|
|||||||
return forced;
|
return forced;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Force a value and assert it's a string (plain or with context)
|
|
||||||
* @throws TypeError if value is not a string after forcing
|
|
||||||
*/
|
|
||||||
export const forceStringValue = (value: NixValue): string => {
|
export const forceStringValue = (value: NixValue): string => {
|
||||||
const forced = force(value);
|
const forced = force(value);
|
||||||
if (typeof forced === "string") {
|
if (typeof forced === "string") {
|
||||||
@@ -79,10 +53,6 @@ export const forceStringValue = (value: NixValue): string => {
|
|||||||
throw new TypeError(`Expected string, got ${typeOf(forced)}`);
|
throw new TypeError(`Expected string, got ${typeOf(forced)}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Force a value and assert it's a string, returning NixString (preserving context)
|
|
||||||
* @throws TypeError if value is not a string after forcing
|
|
||||||
*/
|
|
||||||
export const forceString = (value: NixValue): NixString => {
|
export const forceString = (value: NixValue): NixString => {
|
||||||
const forced = force(value);
|
const forced = force(value);
|
||||||
if (typeof forced === "string") {
|
if (typeof forced === "string") {
|
||||||
@@ -100,15 +70,11 @@ export const forceStringNoCtx = (value: NixValue): string => {
|
|||||||
return forced;
|
return forced;
|
||||||
}
|
}
|
||||||
if (isStringWithContext(forced)) {
|
if (isStringWithContext(forced)) {
|
||||||
throw new TypeError(`the string '${forced.value}' is not allowed to refer to a store path`)
|
throw new TypeError(`the string '${forced.value}' is not allowed to refer to a store path`);
|
||||||
}
|
}
|
||||||
throw new TypeError(`Expected string, got ${typeOf(forced)}`);
|
throw new TypeError(`Expected string, got ${typeOf(forced)}`);
|
||||||
}
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Force a value and assert it's a boolean
|
|
||||||
* @throws TypeError if value is not a boolean after forcing
|
|
||||||
*/
|
|
||||||
export const forceBool = (value: NixValue): boolean => {
|
export const forceBool = (value: NixValue): boolean => {
|
||||||
const forced = force(value);
|
const forced = force(value);
|
||||||
if (typeof forced !== "boolean") {
|
if (typeof forced !== "boolean") {
|
||||||
@@ -117,10 +83,6 @@ export const forceBool = (value: NixValue): boolean => {
|
|||||||
return forced;
|
return forced;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Force a value and extract int value
|
|
||||||
* @throws TypeError if value is not an int
|
|
||||||
*/
|
|
||||||
export const forceInt = (value: NixValue): NixInt => {
|
export const forceInt = (value: NixValue): NixInt => {
|
||||||
const forced = force(value);
|
const forced = force(value);
|
||||||
if (typeof forced === "bigint") {
|
if (typeof forced === "bigint") {
|
||||||
@@ -129,10 +91,6 @@ export const forceInt = (value: NixValue): NixInt => {
|
|||||||
throw new TypeError(`Expected int, got ${typeOf(forced)}`);
|
throw new TypeError(`Expected int, got ${typeOf(forced)}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Force a value and extract float value
|
|
||||||
* @throws TypeError if value is not a float
|
|
||||||
*/
|
|
||||||
export const forceFloat = (value: NixValue): NixFloat => {
|
export const forceFloat = (value: NixValue): NixFloat => {
|
||||||
const forced = force(value);
|
const forced = force(value);
|
||||||
if (typeof forced === "number") {
|
if (typeof forced === "number") {
|
||||||
@@ -141,10 +99,6 @@ export const forceFloat = (value: NixValue): NixFloat => {
|
|||||||
throw new TypeError(`Expected float, got ${typeOf(forced)}`);
|
throw new TypeError(`Expected float, got ${typeOf(forced)}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Force a value and extract numeric value (int or float)
|
|
||||||
* @throws TypeError if value is not a numeric type
|
|
||||||
*/
|
|
||||||
export const forceNumeric = (value: NixValue): NixNumber => {
|
export const forceNumeric = (value: NixValue): NixNumber => {
|
||||||
const forced = force(value);
|
const forced = force(value);
|
||||||
if (typeof forced === "bigint" || typeof forced === "number") {
|
if (typeof forced === "bigint" || typeof forced === "number") {
|
||||||
@@ -153,28 +107,17 @@ export const forceNumeric = (value: NixValue): NixNumber => {
|
|||||||
throw new TypeError(`Expected numeric type, got ${typeOf(forced)}`);
|
throw new TypeError(`Expected numeric type, got ${typeOf(forced)}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Coerce two numeric values to a common type for arithmetic
|
|
||||||
* Rule: If either is float, convert both to float; otherwise keep as bigint
|
|
||||||
* @returns [a, b] tuple of coerced values
|
|
||||||
*/
|
|
||||||
export const coerceNumeric = (a: NixNumber, b: NixNumber): [NixFloat, NixFloat] | [NixInt, NixInt] => {
|
export const coerceNumeric = (a: NixNumber, b: NixNumber): [NixFloat, NixFloat] | [NixInt, NixInt] => {
|
||||||
const aIsInt = typeof a === "bigint";
|
const aIsInt = typeof a === "bigint";
|
||||||
const bIsInt = typeof b === "bigint";
|
const bIsInt = typeof b === "bigint";
|
||||||
|
|
||||||
// If either is float, convert both to float
|
|
||||||
if (!aIsInt || !bIsInt) {
|
if (!aIsInt || !bIsInt) {
|
||||||
return [Number(a), Number(b)];
|
return [Number(a), Number(b)];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Both are integers
|
|
||||||
return [a, b];
|
return [a, b];
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Force a value and assert it's a path
|
|
||||||
* @throws TypeError if value is not a path after forcing
|
|
||||||
*/
|
|
||||||
export const forceNixPath = (value: NixValue): NixPath => {
|
export const forceNixPath = (value: NixValue): NixPath => {
|
||||||
const forced = force(value);
|
const forced = force(value);
|
||||||
if (isNixPath(forced)) {
|
if (isNixPath(forced)) {
|
||||||
|
|||||||
@@ -1,27 +1,24 @@
|
|||||||
/**
|
import { PRIMOP_METADATA, type PrimopMetadata } from "./builtins";
|
||||||
* Core TypeScript type definitions for nix-js runtime
|
import { HAS_CONTEXT, isStringWithContext, type StringWithContext } from "./string-context";
|
||||||
*/
|
import { type CYCLE_MARKER, force, type NixThunk } from "./thunk";
|
||||||
|
|
||||||
import { force, IS_THUNK } from "./thunk";
|
|
||||||
import { type StringWithContext, HAS_CONTEXT, isStringWithContext, getStringContext } from "./string-context";
|
|
||||||
import { op } from "./operators";
|
|
||||||
import { forceAttrs, forceStringNoCtx } from "./type-assert";
|
import { forceAttrs, forceStringNoCtx } from "./type-assert";
|
||||||
import { isString, typeOf } from "./builtins/type-check";
|
|
||||||
export { HAS_CONTEXT, isStringWithContext };
|
export { HAS_CONTEXT, isStringWithContext };
|
||||||
export type { StringWithContext };
|
export type { StringWithContext };
|
||||||
|
|
||||||
export const IS_PATH = Symbol("IS_PATH");
|
export const IS_PATH = Symbol("IS_PATH");
|
||||||
|
|
||||||
export interface NixPath {
|
export class NixPath {
|
||||||
readonly [IS_PATH]: true;
|
readonly [IS_PATH] = true as const;
|
||||||
value: string;
|
value: string;
|
||||||
|
constructor(value: string) {
|
||||||
|
this.value = value;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const isNixPath = (v: NixStrictValue): v is NixPath => {
|
export const isNixPath = (v: NixStrictValue): v is NixPath => {
|
||||||
return typeof v === "object" && v !== null && IS_PATH in v;
|
return v instanceof NixPath;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Nix primitive types
|
|
||||||
export type NixInt = bigint;
|
export type NixInt = bigint;
|
||||||
export type NixFloat = number;
|
export type NixFloat = number;
|
||||||
export type NixNumber = NixInt | NixFloat;
|
export type NixNumber = NixInt | NixFloat;
|
||||||
@@ -29,18 +26,20 @@ export type NixBool = boolean;
|
|||||||
export type NixString = string | StringWithContext;
|
export type NixString = string | StringWithContext;
|
||||||
export type NixNull = null;
|
export type NixNull = null;
|
||||||
|
|
||||||
// Nix composite types
|
export const ATTR_POSITIONS = Symbol("attrPositions");
|
||||||
export type NixList = NixValue[];
|
export type NixList = NixValue[];
|
||||||
// FIXME: reject contextful string
|
export type NixAttrs = Map<string, NixValue> & { [ATTR_POSITIONS]?: Map<string, number> };
|
||||||
export type NixAttrs = { [key: string]: NixValue };
|
export type NixFunction = ((arg: NixValue) => NixValue) & {
|
||||||
export type NixFunction = ((arg: NixValue) => NixValue) & { args?: NixArgs };
|
args?: NixArgs;
|
||||||
|
[PRIMOP_METADATA]?: PrimopMetadata;
|
||||||
|
};
|
||||||
export class NixArgs {
|
export class NixArgs {
|
||||||
required: string[];
|
required: string[];
|
||||||
optional: string[];
|
optional: string[];
|
||||||
allowed: Set<string>;
|
allowed: Set<string>;
|
||||||
ellipsis: boolean;
|
ellipsis: boolean;
|
||||||
positions: Record<string, string>;
|
positions: Map<string, number>;
|
||||||
constructor(required: string[], optional: string[], positions: Record<string, string>, ellipsis: boolean) {
|
constructor(required: string[], optional: string[], positions: Map<string, number>, ellipsis: boolean) {
|
||||||
this.required = required;
|
this.required = required;
|
||||||
this.optional = optional;
|
this.optional = optional;
|
||||||
this.positions = positions;
|
this.positions = positions;
|
||||||
@@ -51,13 +50,13 @@ export class NixArgs {
|
|||||||
const attrs = forceAttrs(arg);
|
const attrs = forceAttrs(arg);
|
||||||
|
|
||||||
for (const key of this.required) {
|
for (const key of this.required) {
|
||||||
if (!Object.hasOwn(attrs, key)) {
|
if (!attrs.has(key)) {
|
||||||
throw new Error(`Function called without required argument '${key}'`);
|
throw new Error(`Function called without required argument '${key}'`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!this.ellipsis) {
|
if (!this.ellipsis) {
|
||||||
for (const key in attrs) {
|
for (const key of attrs.keys()) {
|
||||||
if (!this.allowed.has(key)) {
|
if (!this.allowed.has(key)) {
|
||||||
throw new Error(`Function called with unexpected argument '${key}'`);
|
throw new Error(`Function called with unexpected argument '${key}'`);
|
||||||
}
|
}
|
||||||
@@ -69,33 +68,18 @@ export const mkFunction = (
|
|||||||
f: (arg: NixValue) => NixValue,
|
f: (arg: NixValue) => NixValue,
|
||||||
required: string[],
|
required: string[],
|
||||||
optional: string[],
|
optional: string[],
|
||||||
positions: Record<string, string>,
|
positions: Map<string, number>,
|
||||||
ellipsis: boolean,
|
ellipsis: boolean,
|
||||||
): NixFunction => {
|
): NixFunction => {
|
||||||
const func = f as NixFunction;
|
const func: NixFunction = f;
|
||||||
func.args = new NixArgs(required, optional, positions, ellipsis);
|
func.args = new NixArgs(required, optional, positions, ellipsis);
|
||||||
return func;
|
return func;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const mkAttrs = (attrs: NixAttrs, keys: NixValue[], values: NixValue[]): NixAttrs => {
|
export const mkAttrs = (
|
||||||
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;
|
|
||||||
};
|
|
||||||
|
|
||||||
const ATTR_POSITIONS = Symbol("attrPositions");
|
|
||||||
|
|
||||||
export const mkAttrsWithPos = (
|
|
||||||
attrs: NixAttrs,
|
attrs: NixAttrs,
|
||||||
positions: Record<string, string>,
|
positions: Map<string, number>,
|
||||||
dyns?: { dynKeys: NixValue[]; dynVals: NixValue[]; dynSpans: string[] }
|
dyns?: { dynKeys: NixValue[]; dynVals: NixValue[]; dynSpans: number[] },
|
||||||
): NixAttrs => {
|
): NixAttrs => {
|
||||||
if (dyns) {
|
if (dyns) {
|
||||||
const len = dyns.dynKeys.length;
|
const len = dyns.dynKeys.length;
|
||||||
@@ -105,62 +89,27 @@ export const mkAttrsWithPos = (
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const str = forceStringNoCtx(key);
|
const str = forceStringNoCtx(key);
|
||||||
attrs[str] = dyns.dynVals[i];
|
attrs.set(str, dyns.dynVals[i]);
|
||||||
positions[str] = dyns.dynSpans[i];
|
positions.set(str, dyns.dynSpans[i]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Object.keys(positions).length > 0) {
|
if (positions.size > 0) {
|
||||||
Object.defineProperty(attrs, ATTR_POSITIONS, {
|
attrs[ATTR_POSITIONS] = positions;
|
||||||
value: positions,
|
|
||||||
enumerable: false,
|
|
||||||
writable: false,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return attrs;
|
return attrs;
|
||||||
};
|
};
|
||||||
|
|
||||||
export { ATTR_POSITIONS };
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Interface for lazy thunk values
|
|
||||||
* Thunks delay evaluation until forced
|
|
||||||
*/
|
|
||||||
export interface NixThunkInterface {
|
|
||||||
readonly [IS_THUNK]: true;
|
|
||||||
func: (() => NixValue) | undefined;
|
|
||||||
result: NixStrictValue | undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Union of all Nix primitive types
|
|
||||||
export type NixPrimitive = NixNull | NixBool | NixInt | NixFloat | NixString;
|
export type NixPrimitive = NixNull | NixBool | NixInt | NixFloat | NixString;
|
||||||
|
export type NixValue =
|
||||||
|
| NixPrimitive
|
||||||
|
| NixPath
|
||||||
|
| NixList
|
||||||
|
| NixAttrs
|
||||||
|
| NixFunction
|
||||||
|
| NixThunk
|
||||||
|
| typeof CYCLE_MARKER;
|
||||||
|
export type NixStrictValue = Exclude<NixValue, NixThunk>;
|
||||||
|
|
||||||
/**
|
|
||||||
* NixValue: Union type representing any possible Nix value
|
|
||||||
* This is the core type used throughout the runtime
|
|
||||||
*/
|
|
||||||
export type NixValue = NixPrimitive | NixPath | NixList | NixAttrs | NixFunction | NixThunkInterface;
|
|
||||||
|
|
||||||
export type NixStrictValue = Exclude<NixValue, NixThunkInterface>;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* CatchableError: Error type thrown by `builtins.throw`
|
|
||||||
* This can be caught by `builtins.tryEval`
|
|
||||||
*/
|
|
||||||
export class CatchableError extends Error {}
|
export class CatchableError extends Error {}
|
||||||
|
|
||||||
// Operator function signatures
|
|
||||||
export type BinaryOp<T = NixValue, U = NixValue, R = NixValue> = (a: T, b: U) => R;
|
|
||||||
export type UnaryOp<T = NixValue, R = NixValue> = (a: T) => R;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Curried function types - All Nix builtins must be curried!
|
|
||||||
*
|
|
||||||
* Examples:
|
|
||||||
* - add: Curried2<number, number, number> = (a) => (b) => a + b
|
|
||||||
* - map: Curried2<NixFunction, NixList, NixList> = (f) => (list) => list.map(f)
|
|
||||||
*/
|
|
||||||
export type Curried2<A, B, R> = (a: A) => (b: B) => R;
|
|
||||||
export type Curried3<A, B, C, R> = (a: A) => (b: B) => (c: C) => R;
|
|
||||||
export type Curried4<A, B, C, D, R> = (a: A) => (b: B) => (c: C) => (d: D) => R;
|
|
||||||
|
|||||||
165
nix-js/runtime-ts/src/types/global.d.ts
vendored
165
nix-js/runtime-ts/src/types/global.d.ts
vendored
@@ -1,69 +1,123 @@
|
|||||||
import type { NixRuntime } from "..";
|
import type { NixRuntime } from "..";
|
||||||
|
import type { builtins } from "../builtins";
|
||||||
interface FetchUrlResult {
|
import type { FetchGitResult, FetchTarballResult, FetchUrlResult } from "../builtins/io";
|
||||||
store_path: string;
|
import type {
|
||||||
hash: string;
|
assert,
|
||||||
}
|
call,
|
||||||
|
concatStringsWithContext,
|
||||||
interface FetchTarballResult {
|
hasAttr,
|
||||||
store_path: string;
|
lookupWith,
|
||||||
hash: string;
|
mkPos,
|
||||||
nar_hash: string;
|
resolvePath,
|
||||||
}
|
select,
|
||||||
|
selectWithDefault,
|
||||||
interface FetchGitResult {
|
} from "../helpers";
|
||||||
out_path: string;
|
import type { op } from "../operators";
|
||||||
rev: string;
|
import type { createThunk, force } from "../thunk";
|
||||||
short_rev: string;
|
import type { forceBool } from "../type-assert";
|
||||||
rev_count: number;
|
import type { mkAttrs, mkFunction, NixAttrs, NixStrictValue } from "../types";
|
||||||
last_modified: number;
|
|
||||||
last_modified_date: string;
|
|
||||||
submodules: boolean;
|
|
||||||
nar_hash: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface FetchHgResult {
|
|
||||||
out_path: string;
|
|
||||||
branch: string;
|
|
||||||
rev: string;
|
|
||||||
short_rev: string;
|
|
||||||
rev_count: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
var Nix: NixRuntime;
|
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 Deno {
|
||||||
namespace core {
|
namespace core {
|
||||||
namespace ops {
|
namespace ops {
|
||||||
|
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_resolve_path(currentDir: string, path: string): string;
|
||||||
function op_import(path: string): string;
|
|
||||||
function op_read_file(path: string): string;
|
function op_read_file(path: string): string;
|
||||||
function op_read_file_type(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_path_exists(path: string): boolean;
|
||||||
function op_sha256_hex(data: string): string;
|
function op_walk_dir(path: string): [string, string][];
|
||||||
|
|
||||||
function op_make_placeholder(output: string): string;
|
function op_make_placeholder(output: string): string;
|
||||||
function op_decode_span(span: string): { file: string | null; line: number | null; column: number | null };
|
function op_store_path(path: string): string;
|
||||||
function op_make_store_path(ty: string, hash_hex: string, name: string): string;
|
|
||||||
function op_make_text_store_path(hash_hex: string, name: string, references: string[]): string;
|
function op_convert_hash(hash: string, hashAlgo: string | null, toHashFormat: string): string;
|
||||||
function op_output_path_name(drv_name: string, output_name: string): string;
|
function op_hash_string(algo: string, data: string): string;
|
||||||
function op_make_fixed_output_path(
|
function op_hash_file(algo: string, path: string): string;
|
||||||
hash_algo: string,
|
function op_parse_hash(hashStr: string, algo: string | null): { hex: string; algo: string };
|
||||||
hash: string,
|
|
||||||
hash_mode: string,
|
function op_add_path(
|
||||||
name: string,
|
path: string,
|
||||||
|
name: string | null,
|
||||||
|
recursive: boolean,
|
||||||
|
sha256: string | null,
|
||||||
): string;
|
): string;
|
||||||
|
function op_add_filtered_path(
|
||||||
|
path: string,
|
||||||
|
name: string | null,
|
||||||
|
recursive: boolean,
|
||||||
|
sha256: string | null,
|
||||||
|
includePaths: string[],
|
||||||
|
): string;
|
||||||
|
|
||||||
|
function op_decode_span(span: number): NixAttrs;
|
||||||
|
|
||||||
|
function op_to_file(name: string, contents: string, references: string[]): string;
|
||||||
|
|
||||||
|
function op_copy_path_to_store(path: string): string;
|
||||||
|
|
||||||
|
function op_get_env(key: string): string;
|
||||||
|
|
||||||
|
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): NixStrictValue;
|
||||||
|
function op_from_toml(toml: string): NixStrictValue;
|
||||||
|
function op_to_xml(e: NixValue): [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(
|
function op_fetch_url(
|
||||||
url: string,
|
url: string,
|
||||||
expected_hash: string | null,
|
expectedHash: string | null,
|
||||||
name: string | null,
|
name: string | null,
|
||||||
executable: boolean,
|
executable: boolean,
|
||||||
): FetchUrlResult;
|
): FetchUrlResult;
|
||||||
function op_fetch_tarball(
|
function op_fetch_tarball(
|
||||||
url: string,
|
url: string,
|
||||||
expected_hash: string | null,
|
|
||||||
expected_nar_hash: string | null,
|
|
||||||
name: string | null,
|
name: string | null,
|
||||||
|
sha256: string | null,
|
||||||
): FetchTarballResult;
|
): FetchTarballResult;
|
||||||
function op_fetch_git(
|
function op_fetch_git(
|
||||||
url: string,
|
url: string,
|
||||||
@@ -71,28 +125,9 @@ declare global {
|
|||||||
rev: string | null,
|
rev: string | null,
|
||||||
shallow: boolean,
|
shallow: boolean,
|
||||||
submodules: boolean,
|
submodules: boolean,
|
||||||
all_refs: boolean,
|
allRefs: boolean,
|
||||||
name: string | null,
|
name: string | null,
|
||||||
): FetchGitResult;
|
): FetchGitResult;
|
||||||
function op_fetch_hg(url: string, rev: string | null, name: string | null): FetchHgResult;
|
|
||||||
function op_add_path(
|
|
||||||
path: string,
|
|
||||||
name: string | null,
|
|
||||||
recursive: boolean,
|
|
||||||
sha256: string | null,
|
|
||||||
): string;
|
|
||||||
function op_store_path(path: string): string;
|
|
||||||
function op_to_file(name: string, contents: string, references: string[]): string;
|
|
||||||
function op_copy_path_to_store(path: string): string;
|
|
||||||
function op_get_env(key: string): string;
|
|
||||||
function op_walk_dir(path: string): [string, string][];
|
|
||||||
function op_add_filtered_path(
|
|
||||||
path: string,
|
|
||||||
name: string | null,
|
|
||||||
recursive: boolean,
|
|
||||||
sha256: string | null,
|
|
||||||
include_paths: string[],
|
|
||||||
): 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 };
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
use anyhow::Result;
|
|
||||||
use nix_js::{context::Context, error::Source};
|
|
||||||
use std::process::exit;
|
|
||||||
|
|
||||||
fn main() -> Result<()> {
|
|
||||||
nix_js::logging::init_logging();
|
|
||||||
|
|
||||||
let mut args = std::env::args();
|
|
||||||
if args.len() != 2 {
|
|
||||||
eprintln!("Usage: {} expr", args.next().unwrap());
|
|
||||||
exit(1);
|
|
||||||
}
|
|
||||||
args.next();
|
|
||||||
let expr = args.next().unwrap();
|
|
||||||
let src = Source::new_eval(expr)?;
|
|
||||||
match Context::new()?.eval_code(src) {
|
|
||||||
Ok(value) => {
|
|
||||||
println!("{value}");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
eprintln!("{:?}", miette::Report::new(*err));
|
|
||||||
exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
use anyhow::Result;
|
|
||||||
use nix_js::context::Context;
|
|
||||||
use nix_js::error::Source;
|
|
||||||
use regex::Regex;
|
|
||||||
use rustyline::DefaultEditor;
|
|
||||||
use rustyline::error::ReadlineError;
|
|
||||||
|
|
||||||
fn main() -> Result<()> {
|
|
||||||
nix_js::logging::init_logging();
|
|
||||||
|
|
||||||
let mut rl = DefaultEditor::new()?;
|
|
||||||
let mut context = Context::new()?;
|
|
||||||
let re = Regex::new(r"^\s*([a-zA-Z_][a-zA-Z0-9_'-]*)\s*=(.*)$").unwrap();
|
|
||||||
loop {
|
|
||||||
let readline = rl.readline("nix-js-repl> ");
|
|
||||||
match readline {
|
|
||||||
Ok(line) => {
|
|
||||||
if line.trim().is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let _ = rl.add_history_entry(line.as_str());
|
|
||||||
if let Some(_caps) = re.captures(&line) {
|
|
||||||
eprintln!("Error: binding not implemented yet");
|
|
||||||
continue;
|
|
||||||
/* let ident = caps.get(1).unwrap().as_str();
|
|
||||||
let expr = caps.get(2).unwrap().as_str().trim();
|
|
||||||
if expr.is_empty() {
|
|
||||||
eprintln!("Error: missing expression after '='");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if let Err(err) = context.add_binding(ident, expr) {
|
|
||||||
eprintln!("Error: {}", err);
|
|
||||||
} */
|
|
||||||
} else {
|
|
||||||
let src = Source::new_repl(line)?;
|
|
||||||
match context.eval_code(src) {
|
|
||||||
Ok(value) => println!("{value}"),
|
|
||||||
Err(err) => eprintln!("{:?}", miette::Report::new(*err)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(ReadlineError::Interrupted) => {
|
|
||||||
println!();
|
|
||||||
}
|
|
||||||
Err(ReadlineError::Eof) => {
|
|
||||||
println!("CTRL-D");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
eprintln!("Error: {err:?}");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
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,9 +1,51 @@
|
|||||||
use std::fmt::{self, Write as _};
|
use std::fmt::{self, Write as _};
|
||||||
|
use std::ops::Deref;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use crate::ir::*;
|
use rnix::TextRange;
|
||||||
|
|
||||||
pub(crate) struct CodeBuffer {
|
use crate::ir::*;
|
||||||
|
use crate::value::Symbol;
|
||||||
|
|
||||||
|
macro_rules! code {
|
||||||
|
($buf:expr, $ctx:expr; $($item:expr)*) => {{
|
||||||
|
$(
|
||||||
|
($item).compile($ctx, $buf);
|
||||||
|
)*
|
||||||
|
}};
|
||||||
|
|
||||||
|
($buf:expr, $ctx:expr; $($item:expr)*) => {{
|
||||||
|
$(
|
||||||
|
($item).compile($ctx, $buf);
|
||||||
|
)*
|
||||||
|
}};
|
||||||
|
|
||||||
|
($buf:expr, $fmt:literal, $($arg:tt)*) => {
|
||||||
|
write!($buf, $fmt, $($arg)*).unwrap()
|
||||||
|
};
|
||||||
|
|
||||||
|
($buf:expr, $fmt:literal) => {
|
||||||
|
write!($buf, $fmt).unwrap()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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 SCOPED { "_s" } else { "" } } ")=>{"
|
||||||
|
"const _d="
|
||||||
|
quoted(&ctx.get_current_dir().display().to_string())
|
||||||
|
",_w=null;"
|
||||||
|
"return " expr
|
||||||
|
"})" { if SCOPED { "" } else { "()" } }
|
||||||
|
);
|
||||||
|
|
||||||
|
buf.into_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct CodeBuffer {
|
||||||
buf: String,
|
buf: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,49 +124,6 @@ fn joined<Ctx: CodegenContext, I: Iterator, F: Fn(&Ctx, &mut CodeBuffer, I::Item
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
macro_rules! code {
|
|
||||||
($buf:expr, $ctx:expr; $($item:expr),* $(,)?) => {{
|
|
||||||
$(
|
|
||||||
($item).compile($ctx, $buf);
|
|
||||||
)*
|
|
||||||
}};
|
|
||||||
|
|
||||||
($buf:expr, $ctx:expr; $($item:expr)*) => {{
|
|
||||||
$(
|
|
||||||
($item).compile($ctx, $buf);
|
|
||||||
)*
|
|
||||||
}};
|
|
||||||
|
|
||||||
($buf:expr, $fmt:literal, $($arg:tt)*) => {
|
|
||||||
write!($buf, $fmt, $($arg)*).unwrap()
|
|
||||||
};
|
|
||||||
|
|
||||||
($buf:expr, $lit:literal) => {
|
|
||||||
$buf.push_str($lit)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn compile(expr: &Ir, 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;
|
|
||||||
"Nix.builtins.storeDir="
|
|
||||||
quoted(ctx.get_store_dir())
|
|
||||||
";const currentDir="
|
|
||||||
quoted(&ctx.get_current_dir().display().to_string())
|
|
||||||
";return "
|
|
||||||
expr
|
|
||||||
"})()");
|
|
||||||
|
|
||||||
buf.into_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
trait Compile<Ctx: CodegenContext> {
|
trait Compile<Ctx: CodegenContext> {
|
||||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer);
|
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer);
|
||||||
}
|
}
|
||||||
@@ -172,477 +171,448 @@ where
|
|||||||
|
|
||||||
impl<Ctx: CodegenContext> Compile<Ctx> for rnix::TextRange {
|
impl<Ctx: CodegenContext> Compile<Ctx> for rnix::TextRange {
|
||||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||||
code!(
|
code!(buf, "{}", ctx.register_span(*self));
|
||||||
buf,
|
|
||||||
"\"{}:{}:{}\"",
|
|
||||||
ctx.get_current_source_id(),
|
|
||||||
usize::from(self.start()),
|
|
||||||
usize::from(self.end())
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) trait CodegenContext {
|
pub(crate) trait CodegenContext {
|
||||||
fn get_ir(&self, id: ExprId) -> &Ir;
|
fn get_sym(&self, id: SymId) -> Symbol<'_>;
|
||||||
fn get_sym(&self, id: SymId) -> &str;
|
|
||||||
fn get_current_dir(&self) -> &Path;
|
fn get_current_dir(&self) -> &Path;
|
||||||
fn get_store_dir(&self) -> &str;
|
fn get_store_dir(&self) -> &str;
|
||||||
fn get_current_source_id(&self) -> usize;
|
fn get_current_source_id(&self) -> usize;
|
||||||
fn get_current_source(&self) -> crate::error::Source;
|
fn register_span(&self, range: rnix::TextRange) -> usize;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Ctx: CodegenContext> Compile<Ctx> for ExprId {
|
impl<Ctx: CodegenContext> Compile<Ctx> for Symbol<'_> {
|
||||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||||
ctx.get_ir(*self).compile(ctx, buf);
|
quoted(self).compile(ctx, buf);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Ctx: CodegenContext> Compile<Ctx> for Ir {
|
impl<Ctx: CodegenContext> Compile<Ctx> for RawIrRef<'_> {
|
||||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||||
match self {
|
match self.deref() {
|
||||||
Ir::Int(int) => {
|
Ir::Int(int) => {
|
||||||
code!(buf, "{}n", int.inner);
|
code!(buf, "{}n", int);
|
||||||
}
|
}
|
||||||
Ir::Float(float) => {
|
Ir::Float(float) => {
|
||||||
code!(buf, "{}", float.inner);
|
code!(buf, "{}", float);
|
||||||
}
|
}
|
||||||
Ir::Bool(bool) => {
|
Ir::Bool(bool) => {
|
||||||
code!(buf, "{}", bool.inner);
|
code!(buf, "{}", bool);
|
||||||
}
|
}
|
||||||
Ir::Null(_) => {
|
Ir::Null => {
|
||||||
code!(buf, ctx; "null");
|
code!(buf, ctx; "null");
|
||||||
}
|
}
|
||||||
Ir::Str(s) => {
|
Ir::Str(s) => {
|
||||||
code!(buf, ctx; quoted(&s.val));
|
code!(buf, ctx; quoted(s));
|
||||||
}
|
}
|
||||||
Ir::Path(p) => {
|
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::If { cond, consq, alter } => {
|
||||||
Ir::BinOp(x) => x.compile(ctx, buf),
|
code!(buf, ctx; "$fb(" cond ")?(" consq "):(" alter ")");
|
||||||
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::TopLevel(x) => x.compile(ctx, buf),
|
&Ir::BinOp { lhs, rhs, kind } => compile_binop(lhs, rhs, kind, ctx, buf),
|
||||||
Ir::Select(x) => x.compile(ctx, buf),
|
&Ir::UnOp { rhs, kind } => compile_unop(rhs, kind, ctx, buf),
|
||||||
&Ir::Thunk(Thunk { inner: expr_id, .. }) => {
|
&Ir::Func {
|
||||||
code!(buf, "expr{}", expr_id.0);
|
body,
|
||||||
}
|
ref param,
|
||||||
Ir::Builtins(_) => {
|
arg,
|
||||||
code!(buf, ctx; "Nix.builtins");
|
ref thunks,
|
||||||
}
|
} => compile_func(arg, thunks, param, body, ctx, buf),
|
||||||
&Ir::Builtin(Builtin { inner: name, .. }) => {
|
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;
|
code!(buf, ctx;
|
||||||
"Nix.builtins[",
|
"$c("
|
||||||
quoted(ctx.get_sym(name)),
|
func
|
||||||
"]"
|
","
|
||||||
|
arg
|
||||||
|
","
|
||||||
|
span
|
||||||
|
")"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Ir::ConcatStrings(x) => x.compile(ctx, buf),
|
Ir::Arg(x) => {
|
||||||
Ir::HasAttr(x) => x.compile(ctx, buf),
|
code!(buf, "a{}", x.0);
|
||||||
&Ir::Assert(Assert {
|
}
|
||||||
|
&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,
|
assertion,
|
||||||
expr,
|
expr,
|
||||||
ref assertion_raw,
|
assertion_raw,
|
||||||
span: assert_span,
|
span: assert_span,
|
||||||
}) => {
|
} => {
|
||||||
let assertion_ir = ctx.get_ir(assertion);
|
// Nix.assert
|
||||||
let assertion_span = assertion_ir.span();
|
|
||||||
|
|
||||||
code!(buf, ctx;
|
code!(buf, ctx;
|
||||||
"Nix.assert(Nix.withContext(\"while evaluating the condition of the assert statement\",",
|
"$a("
|
||||||
assertion_span,
|
assertion
|
||||||
",()=>(",
|
","
|
||||||
assertion_ir,
|
expr
|
||||||
")),",
|
","
|
||||||
ctx.get_ir(expr),
|
quoted(assertion_raw)
|
||||||
",",
|
","
|
||||||
quoted(assertion_raw),
|
assert_span
|
||||||
",",
|
|
||||||
assert_span,
|
|
||||||
")"
|
")"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Ir::CurPos(cur_pos) => {
|
Ir::CurPos(span) => {
|
||||||
code!(buf, ctx;
|
// Nix.mkPos
|
||||||
"Nix.mkPos(",
|
code!(buf, ctx; "$mp(" span ")");
|
||||||
cur_pos.span,
|
}
|
||||||
")"
|
&Ir::ReplBinding(name) => {
|
||||||
);
|
// Nix.getReplBinding
|
||||||
|
code!(buf, ctx; "$gb(" ctx.get_sym(name) ")");
|
||||||
|
}
|
||||||
|
&Ir::ScopedImportBinding(name) => {
|
||||||
|
code!(buf, ctx; "_s.get(" ctx.get_sym(name) ")");
|
||||||
|
}
|
||||||
|
&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_binop<'ir>(
|
||||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
lhs: RawIrRef<'ir>,
|
||||||
let &If {
|
rhs: RawIrRef<'ir>,
|
||||||
cond,
|
kind: BinOpKind,
|
||||||
consq,
|
ctx: &impl CodegenContext,
|
||||||
alter,
|
buf: &mut CodeBuffer,
|
||||||
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) {
|
|
||||||
use BinOpKind::*;
|
use BinOpKind::*;
|
||||||
|
match kind {
|
||||||
let lhs = ctx.get_ir(self.lhs);
|
|
||||||
let rhs = ctx.get_ir(self.rhs);
|
|
||||||
|
|
||||||
match self.kind {
|
|
||||||
Add | Sub | Mul | Div | Eq | Neq | Lt | Gt | Leq | Geq | Con | Upd => {
|
Add | Sub | Mul | Div | Eq | Neq | Lt | Gt | Leq | Geq | Con | Upd => {
|
||||||
let op_name = match self.kind {
|
let op_func = match kind {
|
||||||
Add => "+",
|
Add => "$oa",
|
||||||
Sub => "-",
|
Sub => "$os",
|
||||||
Mul => "*",
|
Mul => "$om",
|
||||||
Div => "/",
|
Div => "$od",
|
||||||
Eq => "==",
|
Eq => "$oe",
|
||||||
Neq => "!=",
|
Neq => "!$oe",
|
||||||
Lt => "<",
|
Lt => "$ol",
|
||||||
Gt => ">",
|
Gt => "$og",
|
||||||
Leq => "<=",
|
Leq => "!$og",
|
||||||
Geq => ">=",
|
Geq => "!$ol",
|
||||||
Con => "++",
|
Con => "$oc",
|
||||||
Upd => "//",
|
Upd => "$ou",
|
||||||
_ => 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",
|
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
};
|
};
|
||||||
|
|
||||||
code!(
|
code!(
|
||||||
buf, ctx;
|
buf, ctx;
|
||||||
"Nix.withContext(\"while evaluating the " op_name " operator\"," self.span ",()=>(" op_func "(" lhs "," rhs ")))"
|
op_func "(" lhs "," rhs ")"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
And => {
|
And => {
|
||||||
code!(
|
code!(
|
||||||
buf, ctx;
|
buf, ctx;
|
||||||
"Nix.withContext(\"while evaluating the && operator\"," self.span ",()=>(Nix.forceBool(" lhs ")&&Nix.forceBool(" rhs ")))"
|
"$fb(" lhs ")" "&&" "$fb(" rhs ")"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Or => {
|
Or => {
|
||||||
code!(
|
code!(
|
||||||
buf, ctx;
|
buf, ctx;
|
||||||
"Nix.withContext(\"while evaluating the || operator\"," self.span ",()=>(Nix.forceBool(" lhs ")||Nix.forceBool(" rhs ")))"
|
"$fb(" lhs ")" "||" "$fb(" rhs ")"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Impl => {
|
Impl => {
|
||||||
code!(
|
code!(
|
||||||
buf, ctx;
|
buf, ctx;
|
||||||
"Nix.withContext(\"while evaluating the -> operator\"," self.span ",()=>(!Nix.forceBool(" lhs ")||Nix.forceBool(" rhs ")))"
|
"!$fb(" lhs ")" "||" "$fb(" rhs ")"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
PipeL => {
|
PipeL => {
|
||||||
code!(buf, ctx;
|
code!(buf, ctx; "$c(" rhs "," lhs ")");
|
||||||
"Nix.call(",
|
|
||||||
rhs,
|
|
||||||
",",
|
|
||||||
lhs,
|
|
||||||
")"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
PipeR => {
|
PipeR => {
|
||||||
code!(buf, ctx;
|
code!(buf, ctx; "$c(" lhs "," rhs ")");
|
||||||
"Nix.call(",
|
|
||||||
lhs,
|
|
||||||
",",
|
|
||||||
rhs,
|
|
||||||
")"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Ctx: CodegenContext> Compile<Ctx> for UnOp {
|
fn compile_unop(
|
||||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
rhs: RawIrRef<'_>,
|
||||||
|
kind: UnOpKind,
|
||||||
|
ctx: &impl CodegenContext,
|
||||||
|
buf: &mut CodeBuffer,
|
||||||
|
) {
|
||||||
use UnOpKind::*;
|
use UnOpKind::*;
|
||||||
match self.kind {
|
match kind {
|
||||||
Neg => {
|
Neg => {
|
||||||
code!(buf, ctx;
|
// 0 - rhs
|
||||||
"Nix.op.sub(0n,",
|
code!(buf, ctx; "$os(0n," rhs ")");
|
||||||
ctx.get_ir(self.rhs),
|
|
||||||
")"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
Not => {
|
Not => {
|
||||||
code!(buf, ctx;
|
code!(buf, ctx; "!$fb(" rhs ")");
|
||||||
"Nix.op.bnot(",
|
|
||||||
ctx.get_ir(self.rhs),
|
|
||||||
")"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Ctx: CodegenContext> Compile<Ctx> for Func {
|
fn compile_func<'ir, Ctx: CodegenContext>(
|
||||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
ArgId(id): ArgId,
|
||||||
let id = ctx.get_ir(self.arg).as_ref().unwrap_arg().inner.0;
|
thunks: &[(ThunkId, RawIrRef<'ir>)],
|
||||||
|
param: &Option<Param<'ir>>,
|
||||||
let has_thunks = !self.thunks.is_empty();
|
body: RawIrRef<'ir>,
|
||||||
|
ctx: &Ctx,
|
||||||
|
buf: &mut CodeBuffer,
|
||||||
|
) {
|
||||||
|
let has_thunks = !thunks.is_empty();
|
||||||
|
|
||||||
if let Some(Param {
|
if let Some(Param {
|
||||||
required,
|
required,
|
||||||
optional,
|
optional,
|
||||||
ellipsis,
|
ellipsis,
|
||||||
}) = &self.param
|
}) = ¶m
|
||||||
{
|
{
|
||||||
code!(buf, "Nix.mkFunction(arg{}=>", id);
|
code!(buf, "$mf(a{}=>", id);
|
||||||
if has_thunks {
|
if has_thunks {
|
||||||
code!(buf, ctx; "{", &self.thunks, "return ", self.body, "}");
|
code!(buf, ctx; "{" thunks "return " body "}");
|
||||||
} else {
|
} else {
|
||||||
code!(buf, ctx; "(", self.body, ")");
|
code!(buf, ctx; "(" body ")");
|
||||||
}
|
}
|
||||||
code!(buf, ctx;
|
code!(buf, ctx;
|
||||||
",["
|
",["
|
||||||
joined(required.iter(), ",", |ctx: &Ctx, buf, &(sym, _)| {
|
joined(required.iter(), ",", |ctx: &Ctx, buf, &(sym, _)| {
|
||||||
code!(buf, ctx; quoted(ctx.get_sym(sym)));
|
code!(buf, ctx; ctx.get_sym(sym));
|
||||||
})
|
})
|
||||||
"],["
|
"],["
|
||||||
joined(optional.iter(), ",", |ctx: &Ctx, buf, &(sym, _)| {
|
joined(optional.iter(), ",", |ctx: &Ctx, buf, &(sym, _)| {
|
||||||
code!(buf, ctx; quoted(ctx.get_sym(sym)));
|
code!(buf, ctx; ctx.get_sym(sym));
|
||||||
})
|
})
|
||||||
"],{"
|
"],new Map(["
|
||||||
joined(required.iter().chain(optional.iter()), ",", |ctx: &Ctx, buf, &(sym, span)| {
|
joined(required.iter().chain(optional.iter()), ",", |ctx: &Ctx, buf, &(sym, span)| {
|
||||||
code!(buf, ctx; quoted(ctx.get_sym(sym)), ":", span);
|
code!(buf, ctx; "[" ctx.get_sym(sym) "," span "]");
|
||||||
})
|
})
|
||||||
"},"
|
"]),"
|
||||||
);
|
ellipsis
|
||||||
code!(buf, "{})", ellipsis);
|
|
||||||
} else {
|
|
||||||
code!(buf, "arg{}=>", id);
|
|
||||||
if has_thunks {
|
|
||||||
code!(buf, ctx; "{", &self.thunks, "return ", self.body, "}");
|
|
||||||
} else {
|
|
||||||
code!(buf, ctx; "(", self.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,
|
|
||||||
")"
|
")"
|
||||||
);
|
);
|
||||||
|
} else {
|
||||||
|
code!(buf, "a{}=>", id);
|
||||||
|
if has_thunks {
|
||||||
|
code!(buf, ctx; "{" thunks "return " body "}");
|
||||||
|
} else {
|
||||||
|
code!(buf, ctx; "(" body ")");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||||
if self.is_empty() {
|
if self.is_empty() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
for &(slot, inner) in self {
|
|
||||||
let inner_ir = ctx.get_ir(inner);
|
|
||||||
let inner_span = inner_ir.span();
|
|
||||||
|
|
||||||
code!(
|
code!(
|
||||||
buf, ctx;
|
buf, ctx;
|
||||||
"let expr" slot.0 "=Nix.createThunk(()=>(" inner_ir "),"
|
"const "
|
||||||
"\"expr" slot.0 " "
|
joined(self.iter(), ",", |ctx: &Ctx, buf, &(slot, inner)| {
|
||||||
ctx.get_current_source().get_name() ":"
|
code!(buf, ctx; "e" slot.0 "=$t(()=>(" inner ")," "'e" slot.0 "')");
|
||||||
usize::from(inner_span.start()) ":"
|
})
|
||||||
usize::from(inner_span.end())
|
";"
|
||||||
"\");"
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Ctx: CodegenContext> Compile<Ctx> for TopLevel {
|
fn compile_toplevel<'ir, Ctx: CodegenContext>(
|
||||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
body: RawIrRef<'ir>,
|
||||||
if self.thunks.is_empty() {
|
thunks: &[(ThunkId, RawIrRef<'ir>)],
|
||||||
ctx.get_ir(self.body).compile(ctx, buf);
|
ctx: &Ctx,
|
||||||
|
buf: &mut CodeBuffer,
|
||||||
|
) {
|
||||||
|
if thunks.is_empty() {
|
||||||
|
body.compile(ctx, buf);
|
||||||
} else {
|
} else {
|
||||||
code!(buf, "(()=>{");
|
code!(buf, ctx; "(()=>{" thunks "return " body "})()");
|
||||||
code!(buf, ctx; &self.thunks);
|
|
||||||
code!(buf, "return ");
|
|
||||||
ctx.get_ir(self.body).compile(ctx, buf);
|
|
||||||
code!(buf, "})()");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Ctx: CodegenContext> Compile<Ctx> for Select {
|
fn compile_with<'ir>(
|
||||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
namespace: RawIrRef<'ir>,
|
||||||
if let Some(default) = self.default {
|
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; "((_w)=>{" thunks "return " body "})({env:" namespace ",last:_w})");
|
||||||
|
} else {
|
||||||
|
code!(buf, ctx; "((_w)=>(" body "))({env:" namespace ",last:_w})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
code!(buf, ctx;
|
||||||
"Nix.selectWithDefault("
|
"$sd("
|
||||||
ctx.get_ir(self.expr)
|
expr
|
||||||
",["
|
",["
|
||||||
joined(self.attrpath.iter(), ",", |ctx: &Ctx, buf, attr| {
|
joined(attrpath.iter(), ",", |ctx: &Ctx, buf, attr| {
|
||||||
match attr {
|
match attr {
|
||||||
Attr::Str(sym, _) => code!(buf, ctx; quoted(ctx.get_sym(*sym))),
|
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 {
|
} else {
|
||||||
code!(buf, ctx;
|
code!(buf, ctx;
|
||||||
"Nix.select("
|
"$s("
|
||||||
ctx.get_ir(self.expr)
|
expr
|
||||||
",["
|
",["
|
||||||
joined(self.attrpath.iter(), ",", |ctx: &Ctx, buf, attr| {
|
joined(attrpath.iter(), ",", |ctx: &Ctx, buf, attr| {
|
||||||
match attr {
|
match attr {
|
||||||
Attr::Str(sym, _) => code!(buf, ctx; quoted(ctx.get_sym(*sym))),
|
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_attrset<'ir, Ctx: CodegenContext>(
|
||||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
stcs: &HashMap<'ir, SymId, (RawIrRef<'ir>, TextRange)>,
|
||||||
if !self.dyns.is_empty() {
|
dyns: &[(RawIrRef<'ir>, RawIrRef<'ir>, TextRange)],
|
||||||
|
ctx: &Ctx,
|
||||||
|
buf: &mut CodeBuffer,
|
||||||
|
) {
|
||||||
|
if !dyns.is_empty() {
|
||||||
code!(buf, ctx;
|
code!(buf, ctx;
|
||||||
"Nix.mkAttrsWithPos({"
|
"$ma(new Map(["
|
||||||
joined(self.stcs.iter(), ",", |ctx: &Ctx, buf, (&sym, &(expr, _))| {
|
joined(stcs.iter(), ",", |ctx: &Ctx, buf, (&sym, &(val, _))| {
|
||||||
let key = ctx.get_sym(sym);
|
let key = ctx.get_sym(sym);
|
||||||
let val = ctx.get_ir(expr);
|
|
||||||
|
|
||||||
code!(
|
code!(
|
||||||
buf, ctx;
|
buf, ctx;
|
||||||
quoted(key) ":Nix.withContext(\"while evaluating the attribute '" escaped(key) "'\"," val.span() ",()=>(" val "))"
|
"[" key "," val "]"
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
"},{"
|
"]),new Map(["
|
||||||
joined(self.stcs.iter(), ",", |ctx: &Ctx, buf, (&sym, &(_, span))| {
|
joined(stcs.iter(), ",", |ctx: &Ctx, buf, (&sym, &(_, span))| {
|
||||||
code!(buf, ctx; quoted(ctx.get_sym(sym)) ":" span);
|
code!(buf, ctx; "[" ctx.get_sym(sym) "," span "]");
|
||||||
})
|
})
|
||||||
"},{dynKeys:["
|
"]),{dynKeys:["
|
||||||
joined(self.dyns.iter(), ",", |ctx: &Ctx, buf, (key, _, _)| {
|
joined(dyns.iter(), ",", |ctx: &Ctx, buf, (key, _, _)| {
|
||||||
code!(buf, ctx; ctx.get_ir(*key));
|
code!(buf, ctx; key);
|
||||||
})
|
})
|
||||||
"],dynVals:["
|
"],dynVals:["
|
||||||
joined(self.dyns.iter(), ",", |ctx: &Ctx, buf, (_, val, _)| {
|
joined(dyns.iter(), ",", |ctx: &Ctx, buf, (_, val, _)| {
|
||||||
let val = ctx.get_ir(*val);
|
code!(buf, ctx; val);
|
||||||
code!(
|
|
||||||
buf, ctx;
|
|
||||||
"Nix.withContext(\"while evaluating a dynamic attribute\"," val.span() ",()=>(" val "))"
|
|
||||||
);
|
|
||||||
})
|
})
|
||||||
"],dynSpans:["
|
"],dynSpans:["
|
||||||
joined(self.dyns.iter(), ",", |ctx: &Ctx, buf, (_, _, attr_span)| {
|
joined(dyns.iter(), ",", |ctx: &Ctx, buf, (_, _, attr_span)| {
|
||||||
code!(buf, ctx; attr_span);
|
code!(buf, ctx; attr_span);
|
||||||
})
|
})
|
||||||
"]})"
|
"]})"
|
||||||
);
|
);
|
||||||
} else if !self.stcs.is_empty() {
|
} else if !stcs.is_empty() {
|
||||||
code!(buf, ctx;
|
code!(buf, ctx;
|
||||||
"Nix.mkAttrsWithPos({"
|
"$ma(new Map(["
|
||||||
joined(self.stcs.iter(), ",", |ctx: &Ctx, buf, (&sym, &(expr, _))| {
|
joined(stcs.iter(), ",", |ctx: &Ctx, buf, (&sym, &(val, _))| {
|
||||||
let key = ctx.get_sym(sym);
|
let key = ctx.get_sym(sym);
|
||||||
let val = ctx.get_ir(expr);
|
|
||||||
|
|
||||||
code!(
|
code!(
|
||||||
buf, ctx;
|
buf, ctx;
|
||||||
quoted(key) ":Nix.withContext(\"while evaluating the attribute '" escaped(key) "'\"," val.span() ",()=>(" val "))"
|
"[" key "," val "]"
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
"},{"
|
"]),new Map(["
|
||||||
joined(self.stcs.iter(), ",", |ctx: &Ctx, buf, (&sym, &(_, span))| {
|
joined(stcs.iter(), ",", |ctx: &Ctx, buf, (&sym, &(_, span))| {
|
||||||
code!(buf, ctx; quoted(ctx.get_sym(sym)) ":" span);
|
code!(buf, ctx; "[" ctx.get_sym(sym) "," span "]");
|
||||||
})
|
})
|
||||||
"})"
|
"]))"
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
code!(buf, ctx; "{}");
|
code!(buf, ctx; "$e");
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Ctx: CodegenContext> Compile<Ctx> for List {
|
fn compile_list<Ctx: CodegenContext>(items: &[RawIrRef<'_>], ctx: &Ctx, buf: &mut CodeBuffer) {
|
||||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
|
||||||
code!(buf, ctx;
|
code!(buf, ctx;
|
||||||
"["
|
"["
|
||||||
joined(self.items.iter().enumerate(), ",", |ctx: &Ctx, buf, (idx, item)| {
|
joined(items.iter(), ",", |ctx: &Ctx, buf, item| {
|
||||||
let item = ctx.get_ir(*item);
|
code!(buf, ctx; item);
|
||||||
code!(
|
|
||||||
buf, ctx;
|
|
||||||
"Nix.withContext(\"while evaluating list element " idx "\"," item.span() ",()=>(" item "))"
|
|
||||||
);
|
|
||||||
})
|
})
|
||||||
"]"
|
"]"
|
||||||
);
|
);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Ctx: CodegenContext> Compile<Ctx> for ConcatStrings {
|
fn compile_concat_strings<Ctx: CodegenContext>(
|
||||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
parts: &[RawIrRef<'_>],
|
||||||
|
force_string: bool,
|
||||||
|
ctx: &Ctx,
|
||||||
|
buf: &mut CodeBuffer,
|
||||||
|
) {
|
||||||
code!(buf, ctx;
|
code!(buf, ctx;
|
||||||
"Nix.concatStringsWithContext(["
|
"$cs(["
|
||||||
joined(self.parts.iter(), ",", |ctx: &Ctx, buf, part| {
|
joined(parts.iter(), ",", |ctx: &Ctx, buf, part| {
|
||||||
let part = ctx.get_ir(*part);
|
code!(buf, ctx; part);
|
||||||
code!(
|
|
||||||
buf, ctx;
|
|
||||||
"Nix.withContext(\"while evaluating a path segment\"," part.span() ",()=>(" part "))"
|
|
||||||
);
|
|
||||||
})
|
})
|
||||||
"]," self.force_string ")"
|
"]," force_string ")"
|
||||||
);
|
);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<Ctx: CodegenContext> Compile<Ctx> for HasAttr {
|
fn compile_has_attr<'ir, Ctx: CodegenContext>(
|
||||||
fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
|
lhs: RawIrRef<'ir>,
|
||||||
|
rhs: &[Attr<RawIrRef<'ir>>],
|
||||||
|
ctx: &Ctx,
|
||||||
|
buf: &mut CodeBuffer,
|
||||||
|
) {
|
||||||
code!(buf, ctx;
|
code!(buf, ctx;
|
||||||
"Nix.hasAttr("
|
"$h("
|
||||||
ctx.get_ir(self.lhs)
|
lhs
|
||||||
",["
|
",["
|
||||||
joined(self.rhs.iter(), ",", |ctx: &Ctx, buf, attr| {
|
joined(rhs.iter(), ",", |ctx: &Ctx, buf, attr| {
|
||||||
match attr {
|
match attr {
|
||||||
Attr::Str(sym, _) => code!(buf, ctx; quoted(ctx.get_sym(*sym))),
|
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),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
"])"
|
"])"
|
||||||
);
|
);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
142
nix-js/src/derivation.rs
Normal file
142
nix-js/src/derivation.rs
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
|
pub struct OutputInfo {
|
||||||
|
pub path: String,
|
||||||
|
pub hash_algo: String,
|
||||||
|
pub hash: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct DerivationData {
|
||||||
|
pub name: String,
|
||||||
|
pub outputs: BTreeMap<String, OutputInfo>,
|
||||||
|
pub input_drvs: BTreeMap<String, BTreeSet<String>>,
|
||||||
|
pub input_srcs: BTreeSet<String>,
|
||||||
|
pub platform: String,
|
||||||
|
pub builder: String,
|
||||||
|
pub args: Vec<String>,
|
||||||
|
pub env: BTreeMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn escape_string(s: &str) -> String {
|
||||||
|
let mut result = String::with_capacity(s.len() + 2);
|
||||||
|
result.push('"');
|
||||||
|
for c in s.chars() {
|
||||||
|
match c {
|
||||||
|
'"' => result.push_str("\\\""),
|
||||||
|
'\\' => result.push_str("\\\\"),
|
||||||
|
'\n' => result.push_str("\\n"),
|
||||||
|
'\r' => result.push_str("\\r"),
|
||||||
|
'\t' => result.push_str("\\t"),
|
||||||
|
_ => result.push(c),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result.push('"');
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
fn quote_string(s: &str) -> String {
|
||||||
|
format!("\"{}\"", s)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DerivationData {
|
||||||
|
pub fn generate_aterm(&self) -> String {
|
||||||
|
let mut output_entries = Vec::new();
|
||||||
|
for (name, info) in &self.outputs {
|
||||||
|
output_entries.push(format!(
|
||||||
|
"({},{},{},{})",
|
||||||
|
quote_string(name),
|
||||||
|
quote_string(&info.path),
|
||||||
|
quote_string(&info.hash_algo),
|
||||||
|
quote_string(&info.hash),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let outputs = output_entries.join(",");
|
||||||
|
|
||||||
|
let mut input_drv_entries = Vec::new();
|
||||||
|
for (drv_path, output_names) in &self.input_drvs {
|
||||||
|
let sorted_outs: Vec<String> = output_names.iter().map(|s| quote_string(s)).collect();
|
||||||
|
let out_list = format!("[{}]", sorted_outs.join(","));
|
||||||
|
input_drv_entries.push(format!("({},{})", quote_string(drv_path), out_list));
|
||||||
|
}
|
||||||
|
let input_drvs = input_drv_entries.join(",");
|
||||||
|
|
||||||
|
let input_srcs: Vec<String> = self.input_srcs.iter().map(|s| quote_string(s)).collect();
|
||||||
|
let input_srcs = input_srcs.join(",");
|
||||||
|
|
||||||
|
let args: Vec<String> = self.args.iter().map(|s| escape_string(s)).collect();
|
||||||
|
let args = args.join(",");
|
||||||
|
|
||||||
|
let mut env_entries: Vec<String> = Vec::new();
|
||||||
|
for (k, v) in &self.env {
|
||||||
|
env_entries.push(format!("({},{})", escape_string(k), escape_string(v)));
|
||||||
|
}
|
||||||
|
|
||||||
|
format!(
|
||||||
|
"Derive([{}],[{}],[{}],{},{},[{}],[{}])",
|
||||||
|
outputs,
|
||||||
|
input_drvs,
|
||||||
|
input_srcs,
|
||||||
|
quote_string(&self.platform),
|
||||||
|
escape_string(&self.builder),
|
||||||
|
args,
|
||||||
|
env_entries.join(","),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generate_aterm_modulo(&self, input_drv_hashes: &BTreeMap<String, String>) -> String {
|
||||||
|
let mut output_entries = Vec::new();
|
||||||
|
for (name, info) in &self.outputs {
|
||||||
|
output_entries.push(format!(
|
||||||
|
"({},{},{},{})",
|
||||||
|
quote_string(name),
|
||||||
|
quote_string(&info.path),
|
||||||
|
quote_string(&info.hash_algo),
|
||||||
|
quote_string(&info.hash),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let outputs = output_entries.join(",");
|
||||||
|
|
||||||
|
let mut input_drv_entries = Vec::new();
|
||||||
|
for (drv_hash, outputs_csv) in input_drv_hashes {
|
||||||
|
let mut sorted_outs: Vec<&str> = outputs_csv.split(',').collect();
|
||||||
|
sorted_outs.sort();
|
||||||
|
let out_list: Vec<String> = sorted_outs.iter().map(|s| quote_string(s)).collect();
|
||||||
|
let out_list = format!("[{}]", out_list.join(","));
|
||||||
|
input_drv_entries.push(format!("({},{})", quote_string(drv_hash), out_list));
|
||||||
|
}
|
||||||
|
let input_drvs = input_drv_entries.join(",");
|
||||||
|
|
||||||
|
let input_srcs: Vec<String> = self.input_srcs.iter().map(|s| quote_string(s)).collect();
|
||||||
|
let input_srcs = input_srcs.join(",");
|
||||||
|
|
||||||
|
let args: Vec<String> = self.args.iter().map(|s| escape_string(s)).collect();
|
||||||
|
let args = args.join(",");
|
||||||
|
|
||||||
|
let mut env_entries: Vec<String> = Vec::new();
|
||||||
|
for (k, v) in &self.env {
|
||||||
|
env_entries.push(format!("({},{})", escape_string(k), escape_string(v)));
|
||||||
|
}
|
||||||
|
|
||||||
|
format!(
|
||||||
|
"Derive([{}],[{}],[{}],{},{},[{}],[{}])",
|
||||||
|
outputs,
|
||||||
|
input_drvs,
|
||||||
|
input_srcs,
|
||||||
|
quote_string(&self.platform),
|
||||||
|
escape_string(&self.builder),
|
||||||
|
args,
|
||||||
|
env_entries.join(","),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn collect_references(&self) -> Vec<String> {
|
||||||
|
let mut refs = BTreeSet::new();
|
||||||
|
for src in &self.input_srcs {
|
||||||
|
refs.insert(src.clone());
|
||||||
|
}
|
||||||
|
for drv_path in self.input_drvs.keys() {
|
||||||
|
refs.insert(drv_path.clone());
|
||||||
|
}
|
||||||
|
refs.into_iter().collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
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()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
1249
nix-js/src/downgrade.rs
Normal file
1249
nix-js/src/downgrade.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,3 @@
|
|||||||
#![allow(unused_assignments)]
|
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
@@ -21,6 +19,8 @@ pub enum SourceType {
|
|||||||
Repl(Arc<PathBuf>),
|
Repl(Arc<PathBuf>),
|
||||||
/// file
|
/// file
|
||||||
File(Arc<PathBuf>),
|
File(Arc<PathBuf>),
|
||||||
|
/// virtual (name, no path)
|
||||||
|
Virtual(Arc<str>),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
@@ -71,6 +71,13 @@ impl Source {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn new_virtual(name: Arc<str>, src: String) -> Self {
|
||||||
|
Self {
|
||||||
|
ty: SourceType::Virtual(name),
|
||||||
|
src: src.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn get_dir(&self) -> &Path {
|
pub fn get_dir(&self) -> &Path {
|
||||||
use SourceType::*;
|
use SourceType::*;
|
||||||
match &self.ty {
|
match &self.ty {
|
||||||
@@ -79,6 +86,7 @@ impl Source {
|
|||||||
.as_path()
|
.as_path()
|
||||||
.parent()
|
.parent()
|
||||||
.expect("source file must have a parent dir"),
|
.expect("source file must have a parent dir"),
|
||||||
|
Virtual(_) => Path::new("/"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,6 +95,7 @@ impl Source {
|
|||||||
SourceType::Eval(_) => "«eval»".into(),
|
SourceType::Eval(_) => "«eval»".into(),
|
||||||
SourceType::Repl(_) => "«repl»".into(),
|
SourceType::Repl(_) => "«repl»".into(),
|
||||||
SourceType::File(path) => path.as_os_str().to_string_lossy().to_string(),
|
SourceType::File(path) => path.as_os_str().to_string_lossy().to_string(),
|
||||||
|
SourceType::Virtual(name) => name.to_string(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -283,43 +292,32 @@ fn parse_frames(stack: &str, ctx: &impl RuntimeContext) -> Vec<NixStackFrame> {
|
|||||||
let mut frames = Vec::new();
|
let mut frames = Vec::new();
|
||||||
|
|
||||||
for line in stack.lines() {
|
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 {
|
let Some(rest) = line.strip_prefix("NIX_STACK_FRAME:") else {
|
||||||
continue;
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let src = match parts[0].parse() {
|
let span_id: usize = match parts[0].parse() {
|
||||||
Ok(id) => ctx.get_source(id),
|
Ok(id) => 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,
|
|
||||||
Err(_) => continue,
|
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() == 2 {
|
||||||
|
parts[1].to_string()
|
||||||
let message = {
|
|
||||||
if parts.len() == 4 {
|
|
||||||
parts[3].to_string()
|
|
||||||
} else {
|
} else {
|
||||||
String::new()
|
String::new()
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
frames.push(NixStackFrame { span, message, src });
|
frames.push(NixStackFrame { span, message, src });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deduplicate consecutive identical frames
|
|
||||||
frames.dedup_by(|a, b| a.span == b.span && a.message == b.message);
|
frames.dedup_by(|a, b| a.span == b.span && a.message == b.message);
|
||||||
|
|
||||||
frames
|
frames
|
||||||
|
|||||||
@@ -1,16 +1,18 @@
|
|||||||
use deno_core::OpState;
|
use deno_core::OpState;
|
||||||
|
use deno_core::ToV8;
|
||||||
use deno_core::op2;
|
use deno_core::op2;
|
||||||
use serde::Serialize;
|
use nix_compat::nixhash::HashAlgo;
|
||||||
|
use nix_compat::nixhash::NixHash;
|
||||||
use tracing::{debug, info, warn};
|
use tracing::{debug, info, warn};
|
||||||
|
|
||||||
use crate::runtime::OpStateExt;
|
use crate::runtime::OpStateExt;
|
||||||
use crate::runtime::RuntimeContext;
|
use crate::runtime::RuntimeContext;
|
||||||
|
use crate::store::Store as _;
|
||||||
|
|
||||||
mod archive;
|
mod archive;
|
||||||
pub(crate) mod cache;
|
pub(crate) mod cache;
|
||||||
mod download;
|
mod download;
|
||||||
mod git;
|
mod git;
|
||||||
mod hg;
|
|
||||||
mod metadata_cache;
|
mod metadata_cache;
|
||||||
|
|
||||||
pub use cache::FetcherCache;
|
pub use cache::FetcherCache;
|
||||||
@@ -18,22 +20,21 @@ pub use download::Downloader;
|
|||||||
pub use metadata_cache::MetadataCache;
|
pub use metadata_cache::MetadataCache;
|
||||||
|
|
||||||
use crate::nar;
|
use crate::nar;
|
||||||
use crate::runtime::NixError;
|
use crate::runtime::NixRuntimeError;
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(ToV8)]
|
||||||
pub struct FetchUrlResult {
|
pub struct FetchUrlResult {
|
||||||
pub store_path: String,
|
pub store_path: String,
|
||||||
pub hash: String,
|
pub hash: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(ToV8)]
|
||||||
pub struct FetchTarballResult {
|
pub struct FetchTarballResult {
|
||||||
pub store_path: String,
|
pub store_path: String,
|
||||||
pub hash: String,
|
|
||||||
pub nar_hash: String,
|
pub nar_hash: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(ToV8)]
|
||||||
pub struct FetchGitResult {
|
pub struct FetchGitResult {
|
||||||
pub out_path: String,
|
pub out_path: String,
|
||||||
pub rev: String,
|
pub rev: String,
|
||||||
@@ -45,31 +46,22 @@ pub struct FetchGitResult {
|
|||||||
pub nar_hash: Option<String>,
|
pub nar_hash: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
|
||||||
pub struct FetchHgResult {
|
|
||||||
pub out_path: String,
|
|
||||||
pub branch: String,
|
|
||||||
pub rev: String,
|
|
||||||
pub short_rev: String,
|
|
||||||
pub rev_count: u64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[op2]
|
#[op2]
|
||||||
#[serde]
|
|
||||||
pub fn op_fetch_url<Ctx: RuntimeContext>(
|
pub fn op_fetch_url<Ctx: RuntimeContext>(
|
||||||
state: &mut OpState,
|
state: &mut OpState,
|
||||||
#[string] url: String,
|
#[string] url: String,
|
||||||
#[string] expected_hash: Option<String>,
|
#[string] expected_hash: Option<String>,
|
||||||
#[string] name: Option<String>,
|
#[string] name: Option<String>,
|
||||||
executable: bool,
|
executable: bool,
|
||||||
) -> Result<FetchUrlResult, NixError> {
|
) -> Result<FetchUrlResult, NixRuntimeError> {
|
||||||
let _span = tracing::info_span!("op_fetch_url", url = %url).entered();
|
let _span = tracing::info_span!("op_fetch_url", url = %url).entered();
|
||||||
info!("fetchurl started");
|
info!("fetchurl started");
|
||||||
|
|
||||||
let file_name =
|
let file_name =
|
||||||
name.unwrap_or_else(|| url.rsplit('/').next().unwrap_or("download").to_string());
|
name.unwrap_or_else(|| url.rsplit('/').next().unwrap_or("download").to_string());
|
||||||
|
|
||||||
let metadata_cache = MetadataCache::new(3600).map_err(|e| NixError::from(e.to_string()))?;
|
let metadata_cache =
|
||||||
|
MetadataCache::new(3600).map_err(|e| NixRuntimeError::from(e.to_string()))?;
|
||||||
|
|
||||||
let input = serde_json::json!({
|
let input = serde_json::json!({
|
||||||
"type": "file",
|
"type": "file",
|
||||||
@@ -80,7 +72,7 @@ pub fn op_fetch_url<Ctx: RuntimeContext>(
|
|||||||
|
|
||||||
if let Some(cached_entry) = metadata_cache
|
if let Some(cached_entry) = metadata_cache
|
||||||
.lookup(&input)
|
.lookup(&input)
|
||||||
.map_err(|e| NixError::from(e.to_string()))?
|
.map_err(|e| NixRuntimeError::from(e.to_string()))?
|
||||||
{
|
{
|
||||||
let cached_hash = cached_entry
|
let cached_hash = cached_entry
|
||||||
.info
|
.info
|
||||||
@@ -112,16 +104,16 @@ pub fn op_fetch_url<Ctx: RuntimeContext>(
|
|||||||
let downloader = Downloader::new();
|
let downloader = Downloader::new();
|
||||||
let data = downloader
|
let data = downloader
|
||||||
.download(&url)
|
.download(&url)
|
||||||
.map_err(|e| NixError::from(e.to_string()))?;
|
.map_err(|e| NixRuntimeError::from(e.to_string()))?;
|
||||||
|
|
||||||
info!(bytes = data.len(), "Download complete");
|
info!(bytes = data.len(), "Download complete");
|
||||||
|
|
||||||
let hash = crate::nix_hash::sha256_hex(&String::from_utf8_lossy(&data));
|
let hash = crate::nix_utils::sha256_hex(&data);
|
||||||
|
|
||||||
if let Some(ref expected) = expected_hash {
|
if let Some(ref expected) = expected_hash {
|
||||||
let normalized_expected = normalize_hash(expected);
|
let normalized_expected = normalize_hash(expected);
|
||||||
if hash != normalized_expected {
|
if hash != normalized_expected {
|
||||||
return Err(NixError::from(format!(
|
return Err(NixRuntimeError::from(format!(
|
||||||
"hash mismatch for '{}': expected {}, got {}",
|
"hash mismatch for '{}': expected {}, got {}",
|
||||||
url, normalized_expected, hash
|
url, normalized_expected, hash
|
||||||
)));
|
)));
|
||||||
@@ -132,7 +124,7 @@ pub fn op_fetch_url<Ctx: RuntimeContext>(
|
|||||||
let store = ctx.get_store();
|
let store = ctx.get_store();
|
||||||
let store_path = store
|
let store_path = store
|
||||||
.add_to_store(&file_name, &data, false, vec![])
|
.add_to_store(&file_name, &data, false, vec![])
|
||||||
.map_err(|e| NixError::from(e.to_string()))?;
|
.map_err(|e| NixRuntimeError::from(e.to_string()))?;
|
||||||
|
|
||||||
info!(store_path = %store_path, "Added to store");
|
info!(store_path = %store_path, "Added to store");
|
||||||
|
|
||||||
@@ -153,25 +145,24 @@ pub fn op_fetch_url<Ctx: RuntimeContext>(
|
|||||||
|
|
||||||
metadata_cache
|
metadata_cache
|
||||||
.add(&input, &info, &store_path, true)
|
.add(&input, &info, &store_path, true)
|
||||||
.map_err(|e| NixError::from(e.to_string()))?;
|
.map_err(|e| NixRuntimeError::from(e.to_string()))?;
|
||||||
|
|
||||||
Ok(FetchUrlResult { store_path, hash })
|
Ok(FetchUrlResult { store_path, hash })
|
||||||
}
|
}
|
||||||
|
|
||||||
#[op2]
|
#[op2]
|
||||||
#[serde]
|
|
||||||
pub fn op_fetch_tarball<Ctx: RuntimeContext>(
|
pub fn op_fetch_tarball<Ctx: RuntimeContext>(
|
||||||
state: &mut OpState,
|
state: &mut OpState,
|
||||||
#[string] url: String,
|
#[string] url: String,
|
||||||
#[string] expected_hash: Option<String>,
|
|
||||||
#[string] expected_nar_hash: Option<String>,
|
|
||||||
#[string] name: Option<String>,
|
#[string] name: Option<String>,
|
||||||
) -> Result<FetchTarballResult, NixError> {
|
#[string] sha256: Option<String>,
|
||||||
|
) -> Result<FetchTarballResult, NixRuntimeError> {
|
||||||
let _span = tracing::info_span!("op_fetch_tarball", url = %url).entered();
|
let _span = tracing::info_span!("op_fetch_tarball", url = %url).entered();
|
||||||
info!("fetchTarball started");
|
info!("fetchTarball started");
|
||||||
|
|
||||||
let dir_name = name.unwrap_or_else(|| "source".to_string());
|
let dir_name = name.unwrap_or_else(|| "source".to_string());
|
||||||
let metadata_cache = MetadataCache::new(3600).map_err(|e| NixError::from(e.to_string()))?;
|
let metadata_cache =
|
||||||
|
MetadataCache::new(3600).map_err(|e| NixRuntimeError::from(e.to_string()))?;
|
||||||
|
|
||||||
let input = serde_json::json!({
|
let input = serde_json::json!({
|
||||||
"type": "tarball",
|
"type": "tarball",
|
||||||
@@ -179,28 +170,31 @@ pub fn op_fetch_tarball<Ctx: RuntimeContext>(
|
|||||||
"name": dir_name,
|
"name": dir_name,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
let expected_sha256 = sha256
|
||||||
|
.map(
|
||||||
|
|ref sha256| match NixHash::from_str(sha256, Some(HashAlgo::Sha256)) {
|
||||||
|
Ok(NixHash::Sha256(digest)) => Ok(digest),
|
||||||
|
_ => Err(format!("fetchTarball: invalid sha256 '{sha256}'")),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.transpose()?;
|
||||||
|
let expected_hex = expected_sha256.map(hex::encode);
|
||||||
|
|
||||||
if let Some(cached_entry) = metadata_cache
|
if let Some(cached_entry) = metadata_cache
|
||||||
.lookup(&input)
|
.lookup(&input)
|
||||||
.map_err(|e| NixError::from(e.to_string()))?
|
.map_err(|e| NixRuntimeError::from(e.to_string()))?
|
||||||
{
|
{
|
||||||
let cached_nar_hash = cached_entry
|
let cached_nar_hash = cached_entry
|
||||||
.info
|
.info
|
||||||
.get("nar_hash")
|
.get("nar_hash")
|
||||||
.and_then(|v| v.as_str())
|
.and_then(|v| v.as_str())
|
||||||
.unwrap_or("");
|
.unwrap_or("");
|
||||||
let cached_tarball_hash = cached_entry
|
|
||||||
.info
|
|
||||||
.get("tarball_hash")
|
|
||||||
.and_then(|v| v.as_str())
|
|
||||||
.unwrap_or("");
|
|
||||||
|
|
||||||
if let Some(ref expected_nar) = expected_nar_hash {
|
if let Some(ref hex) = expected_hex {
|
||||||
let normalized_expected = normalize_hash(expected_nar);
|
if cached_nar_hash == hex {
|
||||||
if cached_nar_hash == normalized_expected {
|
|
||||||
info!("Cache hit");
|
info!("Cache hit");
|
||||||
return Ok(FetchTarballResult {
|
return Ok(FetchTarballResult {
|
||||||
store_path: cached_entry.store_path.clone(),
|
store_path: cached_entry.store_path.clone(),
|
||||||
hash: cached_tarball_hash.to_string(),
|
|
||||||
nar_hash: cached_nar_hash.to_string(),
|
nar_hash: cached_nar_hash.to_string(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -208,7 +202,6 @@ pub fn op_fetch_tarball<Ctx: RuntimeContext>(
|
|||||||
info!("Cache hit (no hash check)");
|
info!("Cache hit (no hash check)");
|
||||||
return Ok(FetchTarballResult {
|
return Ok(FetchTarballResult {
|
||||||
store_path: cached_entry.store_path.clone(),
|
store_path: cached_entry.store_path.clone(),
|
||||||
hash: cached_tarball_hash.to_string(),
|
|
||||||
nar_hash: cached_nar_hash.to_string(),
|
nar_hash: cached_nar_hash.to_string(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -218,77 +211,59 @@ pub fn op_fetch_tarball<Ctx: RuntimeContext>(
|
|||||||
let downloader = Downloader::new();
|
let downloader = Downloader::new();
|
||||||
let data = downloader
|
let data = downloader
|
||||||
.download(&url)
|
.download(&url)
|
||||||
.map_err(|e| NixError::from(e.to_string()))?;
|
.map_err(|e| NixRuntimeError::from(e.to_string()))?;
|
||||||
|
|
||||||
info!(bytes = data.len(), "Download complete");
|
info!(bytes = data.len(), "Download complete");
|
||||||
|
|
||||||
let tarball_hash = crate::nix_hash::sha256_hex(&String::from_utf8_lossy(&data));
|
|
||||||
|
|
||||||
if let Some(ref expected) = expected_hash {
|
|
||||||
let normalized_expected = normalize_hash(expected);
|
|
||||||
if tarball_hash != normalized_expected {
|
|
||||||
return Err(NixError::from(format!(
|
|
||||||
"Tarball hash mismatch for '{}': expected {}, got {}",
|
|
||||||
url, normalized_expected, tarball_hash
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
info!("Extracting tarball");
|
info!("Extracting tarball");
|
||||||
let cache = FetcherCache::new().map_err(|e| NixError::from(e.to_string()))?;
|
let (extracted_path, _temp_dir) = archive::extract_tarball_to_temp(&data)
|
||||||
let (extracted_path, _temp_dir) = cache
|
.map_err(|e| NixRuntimeError::from(e.to_string()))?;
|
||||||
.extract_tarball_to_temp(&data)
|
|
||||||
.map_err(|e| NixError::from(e.to_string()))?;
|
|
||||||
|
|
||||||
info!("Computing NAR hash");
|
info!("Computing NAR hash");
|
||||||
let nar_hash =
|
let nar_hash =
|
||||||
nar::compute_nar_hash(&extracted_path).map_err(|e| NixError::from(e.to_string()))?;
|
nar::compute_nar_hash(&extracted_path).map_err(|e| NixRuntimeError::from(e.to_string()))?;
|
||||||
|
let nar_hash_hex = hex::encode(nar_hash);
|
||||||
|
|
||||||
debug!(
|
debug!(
|
||||||
tarball_hash = %tarball_hash,
|
nar_hash = %nar_hash_hex,
|
||||||
nar_hash = %nar_hash,
|
|
||||||
"Hash computation complete"
|
"Hash computation complete"
|
||||||
);
|
);
|
||||||
|
|
||||||
if let Some(ref expected) = expected_nar_hash {
|
if let Some(ref expected) = expected_hex
|
||||||
let normalized_expected = normalize_hash(expected);
|
&& nar_hash_hex != *expected
|
||||||
if nar_hash != normalized_expected {
|
{
|
||||||
return Err(NixError::from(format!(
|
return Err(NixRuntimeError::from(format!(
|
||||||
"NAR hash mismatch for '{}': expected {}, got {}",
|
"Tarball hash mismatch for '{}': expected {}, got {}",
|
||||||
url, normalized_expected, nar_hash
|
url, expected, nar_hash_hex
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
info!("Adding to store");
|
info!("Adding to store");
|
||||||
let ctx: &Ctx = state.get_ctx();
|
let ctx: &Ctx = state.get_ctx();
|
||||||
let store = ctx.get_store();
|
let store = ctx.get_store();
|
||||||
let store_path = store
|
let store_path = store
|
||||||
.add_to_store_from_path(&dir_name, &extracted_path, vec![])
|
.add_to_store_from_path(&dir_name, &extracted_path, vec![])
|
||||||
.map_err(|e| NixError::from(e.to_string()))?;
|
.map_err(|e| NixRuntimeError::from(e.to_string()))?;
|
||||||
|
|
||||||
info!(store_path = %store_path, "Added to store");
|
info!(store_path = %store_path, "Added to store");
|
||||||
|
|
||||||
let info = serde_json::json!({
|
let info = serde_json::json!({
|
||||||
"tarball_hash": tarball_hash,
|
"nar_hash": nar_hash_hex,
|
||||||
"nar_hash": nar_hash,
|
|
||||||
"url": url,
|
"url": url,
|
||||||
});
|
});
|
||||||
|
|
||||||
let immutable = expected_nar_hash.is_some();
|
let immutable = expected_sha256.is_some();
|
||||||
metadata_cache
|
metadata_cache
|
||||||
.add(&input, &info, &store_path, immutable)
|
.add(&input, &info, &store_path, immutable)
|
||||||
.map_err(|e| NixError::from(e.to_string()))?;
|
.map_err(|e| NixRuntimeError::from(e.to_string()))?;
|
||||||
|
|
||||||
Ok(FetchTarballResult {
|
Ok(FetchTarballResult {
|
||||||
store_path,
|
store_path,
|
||||||
hash: tarball_hash,
|
nar_hash: nar_hash_hex,
|
||||||
nar_hash,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[op2]
|
#[op2]
|
||||||
#[serde]
|
|
||||||
pub fn op_fetch_git<Ctx: RuntimeContext>(
|
pub fn op_fetch_git<Ctx: RuntimeContext>(
|
||||||
state: &mut OpState,
|
state: &mut OpState,
|
||||||
#[string] url: String,
|
#[string] url: String,
|
||||||
@@ -298,10 +273,10 @@ pub fn op_fetch_git<Ctx: RuntimeContext>(
|
|||||||
submodules: bool,
|
submodules: bool,
|
||||||
all_refs: bool,
|
all_refs: bool,
|
||||||
#[string] name: Option<String>,
|
#[string] name: Option<String>,
|
||||||
) -> Result<FetchGitResult, NixError> {
|
) -> Result<FetchGitResult, NixRuntimeError> {
|
||||||
let _span = tracing::info_span!("op_fetch_git", url = %url).entered();
|
let _span = tracing::info_span!("op_fetch_git", url = %url).entered();
|
||||||
info!("fetchGit started");
|
info!("fetchGit started");
|
||||||
let cache = FetcherCache::new().map_err(|e| NixError::from(e.to_string()))?;
|
let cache = FetcherCache::new().map_err(|e| NixRuntimeError::from(e.to_string()))?;
|
||||||
let dir_name = name.unwrap_or_else(|| "source".to_string());
|
let dir_name = name.unwrap_or_else(|| "source".to_string());
|
||||||
|
|
||||||
let ctx: &Ctx = state.get_ctx();
|
let ctx: &Ctx = state.get_ctx();
|
||||||
@@ -318,65 +293,24 @@ pub fn op_fetch_git<Ctx: RuntimeContext>(
|
|||||||
all_refs,
|
all_refs,
|
||||||
&dir_name,
|
&dir_name,
|
||||||
)
|
)
|
||||||
.map_err(|e| NixError::from(e.to_string()))
|
.map_err(|e| NixRuntimeError::from(e.to_string()))
|
||||||
}
|
|
||||||
|
|
||||||
#[op2]
|
|
||||||
#[serde]
|
|
||||||
pub fn op_fetch_hg(
|
|
||||||
#[string] url: String,
|
|
||||||
#[string] rev: Option<String>,
|
|
||||||
#[string] name: Option<String>,
|
|
||||||
) -> Result<FetchHgResult, NixError> {
|
|
||||||
let cache = FetcherCache::new().map_err(|e| NixError::from(e.to_string()))?;
|
|
||||||
let dir_name = name.unwrap_or_else(|| "source".to_string());
|
|
||||||
|
|
||||||
hg::fetch_hg(&cache, &url, rev.as_deref(), &dir_name).map_err(|e| NixError::from(e.to_string()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn normalize_hash(hash: &str) -> String {
|
fn normalize_hash(hash: &str) -> String {
|
||||||
|
use base64::prelude::*;
|
||||||
if hash.starts_with("sha256-")
|
if hash.starts_with("sha256-")
|
||||||
&& let Some(b64) = hash.strip_prefix("sha256-")
|
&& let Some(b64) = hash.strip_prefix("sha256-")
|
||||||
&& let Ok(bytes) = base64_decode(b64)
|
&& let Ok(bytes) = BASE64_STANDARD.decode(b64)
|
||||||
{
|
{
|
||||||
return hex::encode(bytes);
|
return hex::encode(bytes);
|
||||||
}
|
}
|
||||||
hash.to_string()
|
hash.to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn base64_decode(input: &str) -> Result<Vec<u8>, String> {
|
|
||||||
const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
||||||
|
|
||||||
let input = input.trim_end_matches('=');
|
|
||||||
let mut output = Vec::with_capacity(input.len() * 3 / 4);
|
|
||||||
|
|
||||||
let mut buffer = 0u32;
|
|
||||||
let mut bits = 0;
|
|
||||||
|
|
||||||
for c in input.bytes() {
|
|
||||||
let value = ALPHABET
|
|
||||||
.iter()
|
|
||||||
.position(|&x| x == c)
|
|
||||||
.ok_or_else(|| format!("Invalid base64 character: {}", c as char))?;
|
|
||||||
|
|
||||||
buffer = (buffer << 6) | (value as u32);
|
|
||||||
bits += 6;
|
|
||||||
|
|
||||||
if bits >= 8 {
|
|
||||||
bits -= 8;
|
|
||||||
output.push((buffer >> bits) as u8);
|
|
||||||
buffer &= (1 << bits) - 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(output)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn register_ops<Ctx: RuntimeContext>() -> Vec<deno_core::OpDecl> {
|
pub fn register_ops<Ctx: RuntimeContext>() -> Vec<deno_core::OpDecl> {
|
||||||
vec![
|
vec![
|
||||||
op_fetch_url::<Ctx>(),
|
op_fetch_url::<Ctx>(),
|
||||||
op_fetch_tarball::<Ctx>(),
|
op_fetch_tarball::<Ctx>(),
|
||||||
op_fetch_git::<Ctx>(),
|
op_fetch_git::<Ctx>(),
|
||||||
op_fetch_hg(),
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
use std::fs::{self, File};
|
use std::fs;
|
||||||
use std::io::Cursor;
|
use std::io::Cursor;
|
||||||
|
use std::os::unix::ffi::OsStrExt;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use flate2::read::GzDecoder;
|
use flate2::read::GzDecoder;
|
||||||
@@ -10,7 +11,6 @@ pub enum ArchiveFormat {
|
|||||||
TarXz,
|
TarXz,
|
||||||
TarBz2,
|
TarBz2,
|
||||||
Tar,
|
Tar,
|
||||||
Zip,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ArchiveFormat {
|
impl ArchiveFormat {
|
||||||
@@ -27,9 +27,6 @@ impl ArchiveFormat {
|
|||||||
if url.ends_with(".tar") {
|
if url.ends_with(".tar") {
|
||||||
return ArchiveFormat::Tar;
|
return ArchiveFormat::Tar;
|
||||||
}
|
}
|
||||||
if url.ends_with(".zip") {
|
|
||||||
return ArchiveFormat::Zip;
|
|
||||||
}
|
|
||||||
|
|
||||||
if data.len() >= 2 && data[0] == 0x1f && data[1] == 0x8b {
|
if data.len() >= 2 && data[0] == 0x1f && data[1] == 0x8b {
|
||||||
return ArchiveFormat::TarGz;
|
return ArchiveFormat::TarGz;
|
||||||
@@ -40,15 +37,12 @@ impl ArchiveFormat {
|
|||||||
if data.len() >= 3 && &data[0..3] == b"BZh" {
|
if data.len() >= 3 && &data[0..3] == b"BZh" {
|
||||||
return ArchiveFormat::TarBz2;
|
return ArchiveFormat::TarBz2;
|
||||||
}
|
}
|
||||||
if data.len() >= 4 && &data[0..4] == b"PK\x03\x04" {
|
|
||||||
return ArchiveFormat::Zip;
|
|
||||||
}
|
|
||||||
|
|
||||||
ArchiveFormat::TarGz
|
ArchiveFormat::TarGz
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn extract_archive(data: &[u8], dest: &Path) -> Result<PathBuf, ArchiveError> {
|
pub fn extract_tarball(data: &[u8], dest: &Path) -> Result<PathBuf, ArchiveError> {
|
||||||
let format = ArchiveFormat::detect("", data);
|
let format = ArchiveFormat::detect("", data);
|
||||||
|
|
||||||
let temp_dir = dest.join("_extract_temp");
|
let temp_dir = dest.join("_extract_temp");
|
||||||
@@ -59,7 +53,6 @@ pub fn extract_archive(data: &[u8], dest: &Path) -> Result<PathBuf, ArchiveError
|
|||||||
ArchiveFormat::TarXz => extract_tar_xz(data, &temp_dir)?,
|
ArchiveFormat::TarXz => extract_tar_xz(data, &temp_dir)?,
|
||||||
ArchiveFormat::TarBz2 => extract_tar_bz2(data, &temp_dir)?,
|
ArchiveFormat::TarBz2 => extract_tar_bz2(data, &temp_dir)?,
|
||||||
ArchiveFormat::Tar => extract_tar(data, &temp_dir)?,
|
ArchiveFormat::Tar => extract_tar(data, &temp_dir)?,
|
||||||
ArchiveFormat::Zip => extract_zip(data, &temp_dir)?,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
strip_single_toplevel(&temp_dir, dest)
|
strip_single_toplevel(&temp_dir, dest)
|
||||||
@@ -92,40 +85,10 @@ fn extract_tar(data: &[u8], dest: &Path) -> Result<(), ArchiveError> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn extract_zip(data: &[u8], dest: &Path) -> Result<(), ArchiveError> {
|
|
||||||
let cursor = Cursor::new(data);
|
|
||||||
let mut archive = zip::ZipArchive::new(cursor)?;
|
|
||||||
|
|
||||||
for i in 0..archive.len() {
|
|
||||||
let mut file = archive.by_index(i)?;
|
|
||||||
let outpath = dest.join(file.mangled_name());
|
|
||||||
|
|
||||||
if file.is_dir() {
|
|
||||||
fs::create_dir_all(&outpath)?;
|
|
||||||
} else {
|
|
||||||
if let Some(parent) = outpath.parent() {
|
|
||||||
fs::create_dir_all(parent)?;
|
|
||||||
}
|
|
||||||
let mut outfile = File::create(&outpath)?;
|
|
||||||
std::io::copy(&mut file, &mut outfile)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(unix)]
|
|
||||||
{
|
|
||||||
use std::os::unix::fs::PermissionsExt;
|
|
||||||
if let Some(mode) = file.unix_mode() {
|
|
||||||
fs::set_permissions(&outpath, fs::Permissions::from_mode(mode))?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn strip_single_toplevel(temp_dir: &Path, dest: &Path) -> Result<PathBuf, ArchiveError> {
|
fn strip_single_toplevel(temp_dir: &Path, dest: &Path) -> Result<PathBuf, ArchiveError> {
|
||||||
let entries: Vec<_> = fs::read_dir(temp_dir)?
|
let entries: Vec<_> = fs::read_dir(temp_dir)?
|
||||||
.filter_map(|e| e.ok())
|
.filter_map(|e| e.ok())
|
||||||
.filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
|
.filter(|e| e.file_name().as_os_str().as_bytes()[0] != b'.')
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let source_dir = if entries.len() == 1 && entries[0].file_type()?.is_dir() {
|
let source_dir = if entries.len() == 1 && entries[0].file_type()?.is_dir() {
|
||||||
@@ -182,17 +145,21 @@ fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), std::io::Error> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn extract_tarball_to_temp(data: &[u8]) -> Result<(PathBuf, tempfile::TempDir), ArchiveError> {
|
||||||
|
let temp_dir = tempfile::tempdir()?;
|
||||||
|
let extracted_path = extract_tarball(data, temp_dir.path())?;
|
||||||
|
Ok((extracted_path, temp_dir))
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum ArchiveError {
|
pub enum ArchiveError {
|
||||||
IoError(std::io::Error),
|
IoError(std::io::Error),
|
||||||
ZipError(zip::result::ZipError),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Display for ArchiveError {
|
impl std::fmt::Display for ArchiveError {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
ArchiveError::IoError(e) => write!(f, "I/O error: {}", e),
|
ArchiveError::IoError(e) => write!(f, "I/O error: {}", e),
|
||||||
ArchiveError::ZipError(e) => write!(f, "ZIP error: {}", e),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -204,9 +171,3 @@ impl From<std::io::Error> for ArchiveError {
|
|||||||
ArchiveError::IoError(e)
|
ArchiveError::IoError(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<zip::result::ZipError> for ArchiveError {
|
|
||||||
fn from(e: zip::result::ZipError) -> Self {
|
|
||||||
ArchiveError::ZipError(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,36 +1,5 @@
|
|||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use super::archive::ArchiveError;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum CacheError {
|
|
||||||
Io(std::io::Error),
|
|
||||||
Archive(ArchiveError),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Display for CacheError {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
match self {
|
|
||||||
CacheError::Io(e) => write!(f, "I/O error: {}", e),
|
|
||||||
CacheError::Archive(e) => write!(f, "Archive error: {}", e),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::error::Error for CacheError {}
|
|
||||||
|
|
||||||
impl From<std::io::Error> for CacheError {
|
|
||||||
fn from(e: std::io::Error) -> Self {
|
|
||||||
CacheError::Io(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<ArchiveError> for CacheError {
|
|
||||||
fn from(e: ArchiveError) -> Self {
|
|
||||||
CacheError::Archive(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct FetcherCache {
|
pub struct FetcherCache {
|
||||||
@@ -49,59 +18,12 @@ impl FetcherCache {
|
|||||||
Ok(Self { base_dir })
|
Ok(Self { base_dir })
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn make_store_path(&self, hash: &str, name: &str) -> PathBuf {
|
|
||||||
let short_hash = &hash[..32.min(hash.len())];
|
|
||||||
self.base_dir
|
|
||||||
.join("store")
|
|
||||||
.join(format!("{}-{}", short_hash, name))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn git_cache_dir(&self) -> PathBuf {
|
fn git_cache_dir(&self) -> PathBuf {
|
||||||
self.base_dir.join("gitv3")
|
self.base_dir.join("git")
|
||||||
}
|
|
||||||
|
|
||||||
fn hg_cache_dir(&self) -> PathBuf {
|
|
||||||
self.base_dir.join("hg")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn hash_key(url: &str) -> String {
|
|
||||||
crate::nix_hash::sha256_hex(url)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_git_bare(&self, url: &str) -> PathBuf {
|
pub fn get_git_bare(&self, url: &str) -> PathBuf {
|
||||||
let key = Self::hash_key(url);
|
let key = crate::nix_utils::sha256_hex(url.as_bytes());
|
||||||
self.git_cache_dir().join(key)
|
self.git_cache_dir().join(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_hg_bare(&self, url: &str) -> PathBuf {
|
|
||||||
let key = Self::hash_key(url);
|
|
||||||
self.hg_cache_dir().join(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn extract_tarball_to_temp(
|
|
||||||
&self,
|
|
||||||
data: &[u8],
|
|
||||||
) -> Result<(PathBuf, tempfile::TempDir), CacheError> {
|
|
||||||
let temp_dir = tempfile::tempdir()?;
|
|
||||||
let extracted_path = super::archive::extract_archive(data, temp_dir.path())?;
|
|
||||||
Ok((extracted_path, temp_dir))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), std::io::Error> {
|
|
||||||
fs::create_dir_all(dst)?;
|
|
||||||
|
|
||||||
for entry in fs::read_dir(src)? {
|
|
||||||
let entry = entry?;
|
|
||||||
let path = entry.path();
|
|
||||||
let dest_path = dst.join(entry.file_name());
|
|
||||||
|
|
||||||
if path.is_dir() {
|
|
||||||
copy_dir_recursive(&path, &dest_path)?;
|
|
||||||
} else {
|
|
||||||
fs::copy(&path, &dest_path)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use reqwest::blocking::Client;
|
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use reqwest::blocking::Client;
|
||||||
|
|
||||||
pub struct Downloader {
|
pub struct Downloader {
|
||||||
client: Client,
|
client: Client,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,8 +31,10 @@ pub fn fetch_git(
|
|||||||
let temp_dir = tempfile::tempdir()?;
|
let temp_dir = tempfile::tempdir()?;
|
||||||
let checkout_dir = checkout_rev_to_temp(&bare_repo, &target_rev, submodules, temp_dir.path())?;
|
let checkout_dir = checkout_rev_to_temp(&bare_repo, &target_rev, submodules, temp_dir.path())?;
|
||||||
|
|
||||||
let nar_hash = crate::nar::compute_nar_hash(&checkout_dir)
|
let nar_hash = hex::encode(
|
||||||
.map_err(|e| GitError::NarHashError(e.to_string()))?;
|
crate::nar::compute_nar_hash(&checkout_dir)
|
||||||
|
.map_err(|e| GitError::NarHashError(e.to_string()))?,
|
||||||
|
);
|
||||||
|
|
||||||
let store_path = store
|
let store_path = store
|
||||||
.add_to_store_from_path(name, &checkout_dir, vec![])
|
.add_to_store_from_path(name, &checkout_dir, vec![])
|
||||||
|
|||||||
@@ -1,196 +0,0 @@
|
|||||||
use std::fs;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
use std::process::Command;
|
|
||||||
|
|
||||||
use super::FetchHgResult;
|
|
||||||
use super::cache::FetcherCache;
|
|
||||||
|
|
||||||
pub fn fetch_hg(
|
|
||||||
cache: &FetcherCache,
|
|
||||||
url: &str,
|
|
||||||
rev: Option<&str>,
|
|
||||||
name: &str,
|
|
||||||
) -> Result<FetchHgResult, HgError> {
|
|
||||||
let bare_repo = cache.get_hg_bare(url);
|
|
||||||
|
|
||||||
if !bare_repo.exists() {
|
|
||||||
clone_repo(url, &bare_repo)?;
|
|
||||||
} else {
|
|
||||||
pull_repo(&bare_repo)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
let target_rev = rev.unwrap_or("tip").to_string();
|
|
||||||
let resolved_rev = resolve_rev(&bare_repo, &target_rev)?;
|
|
||||||
let branch = get_branch(&bare_repo, &resolved_rev)?;
|
|
||||||
|
|
||||||
let checkout_dir = checkout_rev(&bare_repo, &resolved_rev, name, cache)?;
|
|
||||||
|
|
||||||
let rev_count = get_rev_count(&bare_repo, &resolved_rev)?;
|
|
||||||
|
|
||||||
let short_rev = if resolved_rev.len() >= 12 {
|
|
||||||
resolved_rev[..12].to_string()
|
|
||||||
} else {
|
|
||||||
resolved_rev.clone()
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(FetchHgResult {
|
|
||||||
out_path: checkout_dir.to_string_lossy().to_string(),
|
|
||||||
branch,
|
|
||||||
rev: resolved_rev,
|
|
||||||
short_rev,
|
|
||||||
rev_count,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn clone_repo(url: &str, dest: &PathBuf) -> Result<(), HgError> {
|
|
||||||
fs::create_dir_all(dest.parent().unwrap_or(dest))?;
|
|
||||||
|
|
||||||
let output = Command::new("hg")
|
|
||||||
.args(["clone", "-U", url])
|
|
||||||
.arg(dest)
|
|
||||||
.env("HGPLAIN", "")
|
|
||||||
.output()?;
|
|
||||||
|
|
||||||
if !output.status.success() {
|
|
||||||
return Err(HgError::CommandFailed {
|
|
||||||
operation: "clone".to_string(),
|
|
||||||
message: String::from_utf8_lossy(&output.stderr).to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn pull_repo(repo: &PathBuf) -> Result<(), HgError> {
|
|
||||||
let output = Command::new("hg")
|
|
||||||
.args(["pull"])
|
|
||||||
.current_dir(repo)
|
|
||||||
.env("HGPLAIN", "")
|
|
||||||
.output()?;
|
|
||||||
|
|
||||||
if !output.status.success() {
|
|
||||||
return Err(HgError::CommandFailed {
|
|
||||||
operation: "pull".to_string(),
|
|
||||||
message: String::from_utf8_lossy(&output.stderr).to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resolve_rev(repo: &PathBuf, rev: &str) -> Result<String, HgError> {
|
|
||||||
let output = Command::new("hg")
|
|
||||||
.args(["log", "-r", rev, "--template", "{node}"])
|
|
||||||
.current_dir(repo)
|
|
||||||
.env("HGPLAIN", "")
|
|
||||||
.output()?;
|
|
||||||
|
|
||||||
if !output.status.success() {
|
|
||||||
return Err(HgError::CommandFailed {
|
|
||||||
operation: "log".to_string(),
|
|
||||||
message: format!(
|
|
||||||
"Could not resolve rev '{}': {}",
|
|
||||||
rev,
|
|
||||||
String::from_utf8_lossy(&output.stderr)
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_branch(repo: &PathBuf, rev: &str) -> Result<String, HgError> {
|
|
||||||
let output = Command::new("hg")
|
|
||||||
.args(["log", "-r", rev, "--template", "{branch}"])
|
|
||||||
.current_dir(repo)
|
|
||||||
.env("HGPLAIN", "")
|
|
||||||
.output()?;
|
|
||||||
|
|
||||||
if !output.status.success() {
|
|
||||||
return Ok("default".to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
let branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
|
||||||
if branch.is_empty() {
|
|
||||||
Ok("default".to_string())
|
|
||||||
} else {
|
|
||||||
Ok(branch)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn checkout_rev(
|
|
||||||
bare_repo: &PathBuf,
|
|
||||||
rev: &str,
|
|
||||||
name: &str,
|
|
||||||
cache: &FetcherCache,
|
|
||||||
) -> Result<PathBuf, HgError> {
|
|
||||||
let hash = crate::nix_hash::sha256_hex(&format!("{}:{}", bare_repo.display(), rev));
|
|
||||||
let checkout_dir = cache.make_store_path(&hash, name);
|
|
||||||
|
|
||||||
if checkout_dir.exists() {
|
|
||||||
return Ok(checkout_dir);
|
|
||||||
}
|
|
||||||
|
|
||||||
fs::create_dir_all(&checkout_dir)?;
|
|
||||||
|
|
||||||
let output = Command::new("hg")
|
|
||||||
.args(["archive", "-r", rev])
|
|
||||||
.arg(&checkout_dir)
|
|
||||||
.current_dir(bare_repo)
|
|
||||||
.env("HGPLAIN", "")
|
|
||||||
.output()?;
|
|
||||||
|
|
||||||
if !output.status.success() {
|
|
||||||
fs::remove_dir_all(&checkout_dir)?;
|
|
||||||
return Err(HgError::CommandFailed {
|
|
||||||
operation: "archive".to_string(),
|
|
||||||
message: String::from_utf8_lossy(&output.stderr).to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let hg_archival = checkout_dir.join(".hg_archival.txt");
|
|
||||||
if hg_archival.exists() {
|
|
||||||
fs::remove_file(&hg_archival)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(checkout_dir)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_rev_count(repo: &PathBuf, rev: &str) -> Result<u64, HgError> {
|
|
||||||
let output = Command::new("hg")
|
|
||||||
.args(["log", "-r", &format!("0::{}", rev), "--template", "x"])
|
|
||||||
.current_dir(repo)
|
|
||||||
.env("HGPLAIN", "")
|
|
||||||
.output()?;
|
|
||||||
|
|
||||||
if !output.status.success() {
|
|
||||||
return Ok(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(output.stdout.len() as u64)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum HgError {
|
|
||||||
IoError(std::io::Error),
|
|
||||||
CommandFailed { operation: String, message: String },
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Display for HgError {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
match self {
|
|
||||||
HgError::IoError(e) => write!(f, "I/O error: {}", e),
|
|
||||||
HgError::CommandFailed { operation, message } => {
|
|
||||||
write!(f, "Mercurial {} failed: {}", operation, message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::error::Error for HgError {}
|
|
||||||
|
|
||||||
impl From<std::io::Error> for HgError {
|
|
||||||
fn from(e: std::io::Error) -> Self {
|
|
||||||
HgError::IoError(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
#![allow(dead_code)]
|
#![allow(dead_code)]
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use rusqlite::{Connection, OptionalExtension, params};
|
use rusqlite::{Connection, OptionalExtension, params};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::path::PathBuf;
|
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum CacheError {
|
pub enum CacheError {
|
||||||
|
|||||||
636
nix-js/src/ir.rs
636
nix-js/src/ir.rs
@@ -1,83 +1,158 @@
|
|||||||
use derive_more::{IsVariant, TryUnwrap, Unwrap};
|
use std::{
|
||||||
use hashbrown::HashMap;
|
hash::{Hash, Hasher},
|
||||||
|
ops::Deref,
|
||||||
|
};
|
||||||
|
|
||||||
|
use bumpalo::{Bump, boxed::Box, collections::Vec};
|
||||||
|
use ghost_cell::{GhostCell, GhostToken};
|
||||||
use rnix::{TextRange, ast};
|
use rnix::{TextRange, ast};
|
||||||
use string_interner::symbol::SymbolU32;
|
use string_interner::symbol::SymbolU32;
|
||||||
|
|
||||||
use crate::error::{Result, Source};
|
pub type HashMap<'ir, K, V> = hashbrown::HashMap<K, V, hashbrown::DefaultHashBuilder, &'ir Bump>;
|
||||||
use nix_js_macros::ir;
|
|
||||||
|
|
||||||
mod downgrade;
|
#[repr(transparent)]
|
||||||
mod span_utils;
|
#[derive(Clone, Copy)]
|
||||||
mod utils;
|
pub struct IrRef<'id, 'ir>(&'ir GhostCell<'id, Ir<'ir, Self>>);
|
||||||
|
|
||||||
use utils::*;
|
impl<'id, 'ir> IrRef<'id, 'ir> {
|
||||||
|
pub fn new(ir: &'ir GhostCell<'id, Ir<'ir, Self>>) -> Self {
|
||||||
|
Self(ir)
|
||||||
|
}
|
||||||
|
|
||||||
pub use downgrade::Downgrade;
|
pub fn alloc(bump: &'ir Bump, ir: Ir<'ir, Self>) -> Self {
|
||||||
pub(crate) use span_utils::*;
|
Self(bump.alloc(GhostCell::new(ir)))
|
||||||
|
}
|
||||||
|
|
||||||
pub trait DowngradeContext {
|
/// Freeze a mutable IR reference into a read-only one, consuming the
|
||||||
fn downgrade(self, expr: rnix::ast::Expr) -> Result<ExprId>;
|
/// `GhostToken` to prevent any further mutation.
|
||||||
|
///
|
||||||
fn new_expr(&mut self, expr: Ir) -> ExprId;
|
/// # Safety
|
||||||
fn new_arg(&mut self, span: TextRange) -> ExprId;
|
/// The transmute is sound because:
|
||||||
fn maybe_thunk(&mut self, id: ExprId) -> ExprId;
|
/// - `GhostCell<'id, T>` is `#[repr(transparent)]` over `T`
|
||||||
|
/// - `IrRef<'id, 'ir>` is `#[repr(transparent)]` over
|
||||||
fn new_sym(&mut self, sym: String) -> SymId;
|
/// `&'ir GhostCell<'id, Ir<'ir, Self>>`
|
||||||
fn get_sym(&self, id: SymId) -> &str;
|
/// - `RawIrRef<'ir>` is `#[repr(transparent)]` over `&'ir Ir<'ir, Self>`
|
||||||
fn lookup(&mut self, sym: SymId, span: TextRange) -> Result<ExprId>;
|
/// - `Ir<'ir, Ref>` is `#[repr(C)]` and both ref types are pointer-sized
|
||||||
|
///
|
||||||
fn get_ir(&self, id: ExprId) -> &Ir;
|
/// Consuming the `GhostToken` guarantees no `borrow_mut` calls can occur
|
||||||
fn replace_ir(&mut self, id: ExprId, expr: Ir);
|
/// afterwards, so the shared `&Ir` references from `RawIrRef::Deref` can
|
||||||
fn reserve_slots(&mut self, slots: usize) -> impl Iterator<Item = ExprId> + Clone + use<Self>;
|
/// never alias with mutable references.
|
||||||
fn get_current_source(&self) -> Source;
|
pub fn freeze(self, _token: GhostToken<'id>) -> RawIrRef<'ir> {
|
||||||
|
unsafe { std::mem::transmute(self) }
|
||||||
fn with_param_scope<F, R>(&mut self, param: SymId, arg: ExprId, f: F) -> R
|
}
|
||||||
where
|
|
||||||
F: FnOnce(&mut Self) -> R;
|
|
||||||
fn with_let_scope<F, R>(&mut self, bindings: HashMap<SymId, ExprId>, f: F) -> R
|
|
||||||
where
|
|
||||||
F: FnOnce(&mut Self) -> R;
|
|
||||||
fn with_with_scope<F, R>(&mut self, namespace: ExprId, f: F) -> R
|
|
||||||
where
|
|
||||||
F: FnOnce(&mut Self) -> R;
|
|
||||||
|
|
||||||
fn push_thunk_scope(&mut self);
|
|
||||||
fn pop_thunk_scope(&mut self) -> Vec<(ExprId, ExprId)>;
|
|
||||||
fn register_thunk(&mut self, slot: ExprId, inner: ExprId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ir! {
|
impl<'id, 'ir> Deref for IrRef<'id, 'ir> {
|
||||||
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),
|
Int(i64),
|
||||||
Float(f64),
|
Float(f64),
|
||||||
Bool(bool),
|
Bool(bool),
|
||||||
Null,
|
Null,
|
||||||
Str { pub val: String },
|
Str(Box<'ir, String>),
|
||||||
AttrSet { pub stcs: HashMap<SymId, (ExprId, rnix::TextRange)>, pub dyns: Vec<(ExprId, ExprId, rnix::TextRange)> },
|
AttrSet {
|
||||||
List { pub items: Vec<ExprId> },
|
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> },
|
// OPs
|
||||||
BinOp { pub lhs: ExprId, pub rhs: ExprId, pub kind: BinOpKind },
|
UnOp {
|
||||||
UnOp { pub rhs: ExprId, pub kind: UnOpKind },
|
rhs: Ref,
|
||||||
Select { pub expr: ExprId, pub attrpath: Vec<Attr>, pub default: Option<ExprId> },
|
kind: UnOpKind,
|
||||||
If { pub cond: ExprId, pub consq: ExprId, pub alter: ExprId },
|
},
|
||||||
Call { pub func: ExprId, pub arg: ExprId },
|
BinOp {
|
||||||
Assert { pub assertion: ExprId, pub expr: ExprId, pub assertion_raw: String },
|
lhs: Ref,
|
||||||
ConcatStrings { pub parts: Vec<ExprId>, pub force_string: bool },
|
rhs: Ref,
|
||||||
Path { pub expr: ExprId },
|
kind: BinOpKind,
|
||||||
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)> },
|
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),
|
Arg(ArgId),
|
||||||
Thunk(ExprId),
|
Call {
|
||||||
|
func: Ref,
|
||||||
|
arg: Ref,
|
||||||
|
span: TextRange,
|
||||||
|
},
|
||||||
|
|
||||||
|
// Builtins
|
||||||
Builtins,
|
Builtins,
|
||||||
Builtin(SymId),
|
Builtin(SymId),
|
||||||
CurPos,
|
|
||||||
|
// Misc
|
||||||
|
TopLevel {
|
||||||
|
body: Ref,
|
||||||
|
thunks: Vec<'ir, (ThunkId, Ref)>,
|
||||||
|
},
|
||||||
|
Thunk(ThunkId),
|
||||||
|
CurPos(TextRange),
|
||||||
|
ReplBinding(SymId),
|
||||||
|
ScopedImportBinding(SymId),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[repr(transparent)]
|
#[repr(transparent)]
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||||
pub struct ExprId(pub usize);
|
pub struct ThunkId(pub usize);
|
||||||
|
|
||||||
pub type SymId = SymbolU32;
|
pub type SymId = SymbolU32;
|
||||||
|
|
||||||
@@ -87,18 +162,18 @@ pub struct ArgId(pub usize);
|
|||||||
|
|
||||||
/// Represents a key in an attribute path.
|
/// Represents a key in an attribute path.
|
||||||
#[allow(unused)]
|
#[allow(unused)]
|
||||||
#[derive(Debug, TryUnwrap)]
|
#[derive(Debug)]
|
||||||
pub enum Attr {
|
pub enum Attr<Ref> {
|
||||||
/// A dynamic attribute key, which is an expression that must evaluate to a string.
|
/// A dynamic attribute key, which is an expression that must evaluate to a string.
|
||||||
/// Example: `attrs.${key}`
|
/// Example: `attrs.${key}`
|
||||||
Dynamic(ExprId, TextRange),
|
Dynamic(Ref, TextRange),
|
||||||
/// A static attribute key.
|
/// A static attribute key.
|
||||||
/// Example: `attrs.key`
|
/// Example: `attrs.key`
|
||||||
Str(SymId, TextRange),
|
Str(SymId, TextRange),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The kinds of binary operations supported in Nix.
|
/// The kinds of binary operations supported in Nix.
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
|
||||||
pub enum BinOpKind {
|
pub enum BinOpKind {
|
||||||
// Arithmetic
|
// Arithmetic
|
||||||
Add,
|
Add,
|
||||||
@@ -155,7 +230,7 @@ impl From<ast::BinOpKind> for BinOpKind {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The kinds of unary operations.
|
/// The kinds of unary operations.
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
|
||||||
pub enum UnOpKind {
|
pub enum UnOpKind {
|
||||||
Neg, // Negation (`-`)
|
Neg, // Negation (`-`)
|
||||||
Not, // Logical not (`!`)
|
Not, // Logical not (`!`)
|
||||||
@@ -172,8 +247,437 @@ impl From<ast::UnaryOpKind> for UnOpKind {
|
|||||||
|
|
||||||
/// Describes the parameters of a function.
|
/// Describes the parameters of a function.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Param {
|
pub struct Param<'ir> {
|
||||||
pub required: Vec<(SymId, TextRange)>,
|
pub required: Vec<'ir, (SymId, TextRange)>,
|
||||||
pub optional: Vec<(SymId, TextRange)>,
|
pub optional: Vec<'ir, (SymId, TextRange)>,
|
||||||
pub ellipsis: bool,
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,453 +0,0 @@
|
|||||||
// Assume no parse error
|
|
||||||
#![allow(clippy::unwrap_used)]
|
|
||||||
|
|
||||||
use rnix::ast::{self, AstToken, Expr, HasEntry};
|
|
||||||
use rowan::ast::AstNode;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::error::{Error, Result};
|
|
||||||
|
|
||||||
pub trait Downgrade<Ctx: DowngradeContext> {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for Expr {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
use Expr::*;
|
|
||||||
match self {
|
|
||||||
Apply(apply) => apply.downgrade(ctx),
|
|
||||||
Assert(assert) => assert.downgrade(ctx),
|
|
||||||
Error(error) => {
|
|
||||||
let span = error.syntax().text_range();
|
|
||||||
Err(self::Error::downgrade_error(
|
|
||||||
error.to_string(),
|
|
||||||
ctx.get_current_source(),
|
|
||||||
span,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
IfElse(ifelse) => ifelse.downgrade(ctx),
|
|
||||||
Select(select) => select.downgrade(ctx),
|
|
||||||
Str(str) => str.downgrade(ctx),
|
|
||||||
Path(path) => path.downgrade(ctx),
|
|
||||||
Literal(lit) => lit.downgrade(ctx),
|
|
||||||
Lambda(lambda) => lambda.downgrade(ctx),
|
|
||||||
LegacyLet(let_) => let_.downgrade(ctx),
|
|
||||||
LetIn(letin) => letin.downgrade(ctx),
|
|
||||||
List(list) => list.downgrade(ctx),
|
|
||||||
BinOp(op) => op.downgrade(ctx),
|
|
||||||
AttrSet(attrs) => attrs.downgrade(ctx),
|
|
||||||
UnaryOp(op) => op.downgrade(ctx),
|
|
||||||
Ident(ident) => ident.downgrade(ctx),
|
|
||||||
With(with) => with.downgrade(ctx),
|
|
||||||
HasAttr(has) => has.downgrade(ctx),
|
|
||||||
Paren(paren) => paren.expr().unwrap().downgrade(ctx),
|
|
||||||
Root(root) => root.expr().unwrap().downgrade(ctx),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::Assert {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
let assertion = self.condition().unwrap();
|
|
||||||
let assertion_raw = assertion.to_string();
|
|
||||||
let assertion = assertion.downgrade(ctx)?;
|
|
||||||
let expr = self.body().unwrap().downgrade(ctx)?;
|
|
||||||
let span = self.syntax().text_range();
|
|
||||||
Ok(ctx.new_expr(
|
|
||||||
Assert {
|
|
||||||
assertion,
|
|
||||||
expr,
|
|
||||||
assertion_raw,
|
|
||||||
span,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::IfElse {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
let cond = self.condition().unwrap().downgrade(ctx)?;
|
|
||||||
let consq = self.body().unwrap().downgrade(ctx)?;
|
|
||||||
let alter = self.else_body().unwrap().downgrade(ctx)?;
|
|
||||||
let span = self.syntax().text_range();
|
|
||||||
Ok(ctx.new_expr(
|
|
||||||
If {
|
|
||||||
cond,
|
|
||||||
consq,
|
|
||||||
alter,
|
|
||||||
span,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::Path {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
let span = self.syntax().text_range();
|
|
||||||
let parts = self
|
|
||||||
.parts()
|
|
||||||
.map(|part| match part {
|
|
||||||
ast::InterpolPart::Literal(lit) => Ok(ctx.new_expr(
|
|
||||||
Str {
|
|
||||||
val: lit.to_string(),
|
|
||||||
span: lit.syntax().text_range(),
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
)),
|
|
||||||
ast::InterpolPart::Interpolation(interpol) => {
|
|
||||||
interpol.expr().unwrap().downgrade(ctx)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<Result<Vec<_>>>()?;
|
|
||||||
|
|
||||||
let expr = if parts.len() == 1 {
|
|
||||||
let part = parts.into_iter().next().unwrap();
|
|
||||||
if let &Ir::Str(Str { ref val, span }) = ctx.get_ir(part)
|
|
||||||
&& let Some(path) = val.strip_prefix("<").map(|path| &path[..path.len() - 1])
|
|
||||||
{
|
|
||||||
ctx.replace_ir(
|
|
||||||
part,
|
|
||||||
Str {
|
|
||||||
val: path.to_string(),
|
|
||||||
span,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
);
|
|
||||||
let sym = ctx.new_sym("findFile".into());
|
|
||||||
let find_file = ctx.new_expr(Builtin { inner: sym, span }.to_ir());
|
|
||||||
let sym = ctx.new_sym("nixPath".into());
|
|
||||||
let nix_path = ctx.new_expr(Builtin { inner: sym, span }.to_ir());
|
|
||||||
let call = ctx.new_expr(
|
|
||||||
Call {
|
|
||||||
func: find_file,
|
|
||||||
arg: nix_path,
|
|
||||||
span,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
);
|
|
||||||
return Ok(ctx.new_expr(
|
|
||||||
Call {
|
|
||||||
func: call,
|
|
||||||
arg: part,
|
|
||||||
span,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
));
|
|
||||||
} else {
|
|
||||||
part
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ctx.new_expr(
|
|
||||||
ConcatStrings {
|
|
||||||
parts,
|
|
||||||
span,
|
|
||||||
force_string: false,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
)
|
|
||||||
};
|
|
||||||
Ok(ctx.new_expr(Path { expr, span }.to_ir()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::Str {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
let span = self.syntax().text_range();
|
|
||||||
let normalized = self.normalized_parts();
|
|
||||||
let is_single_literal = normalized.len() == 1
|
|
||||||
&& matches!(normalized.first(), Some(ast::InterpolPart::Literal(_)));
|
|
||||||
|
|
||||||
let parts = normalized
|
|
||||||
.into_iter()
|
|
||||||
.map(|part| match part {
|
|
||||||
ast::InterpolPart::Literal(lit) => Ok(ctx.new_expr(Str { val: lit, span }.to_ir())),
|
|
||||||
ast::InterpolPart::Interpolation(interpol) => {
|
|
||||||
let inner = interpol.expr().unwrap().downgrade(ctx)?;
|
|
||||||
Ok(ctx.maybe_thunk(inner))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<Result<Vec<_>>>()?;
|
|
||||||
|
|
||||||
Ok(if is_single_literal {
|
|
||||||
parts.into_iter().next().unwrap()
|
|
||||||
} else {
|
|
||||||
ctx.new_expr(
|
|
||||||
ConcatStrings {
|
|
||||||
parts,
|
|
||||||
span,
|
|
||||||
force_string: true,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::Literal {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
let span = self.syntax().text_range();
|
|
||||||
Ok(ctx.new_expr(match self.kind() {
|
|
||||||
ast::LiteralKind::Integer(int) => Int {
|
|
||||||
inner: int.value().unwrap(),
|
|
||||||
span,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
ast::LiteralKind::Float(float) => Float {
|
|
||||||
inner: float.value().unwrap(),
|
|
||||||
span,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
ast::LiteralKind::Uri(uri) => Str {
|
|
||||||
val: uri.to_string(),
|
|
||||||
span,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::Ident {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
let text = self.ident_token().unwrap().to_string();
|
|
||||||
let span = self.syntax().text_range();
|
|
||||||
|
|
||||||
if text == "__curPos" {
|
|
||||||
return Ok(ctx.new_expr(CurPos { span }.to_ir()));
|
|
||||||
}
|
|
||||||
|
|
||||||
let sym = ctx.new_sym(text);
|
|
||||||
ctx.lookup(sym, span)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::AttrSet {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
let rec = self.rec_token().is_some();
|
|
||||||
let span = self.syntax().text_range();
|
|
||||||
|
|
||||||
if !rec {
|
|
||||||
let attrs = downgrade_attrs(self, ctx)?;
|
|
||||||
return Ok(ctx.new_expr(attrs.to_ir()));
|
|
||||||
}
|
|
||||||
|
|
||||||
// rec { a = 1; b = a; } => let a = 1; b = a; in { inherit a b; }
|
|
||||||
let entries: Vec<_> = self.entries().collect();
|
|
||||||
downgrade_rec_bindings(entries, ctx, span)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Downgrades a list.
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::List {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
let items = self
|
|
||||||
.items()
|
|
||||||
.map(|item| {
|
|
||||||
let id = item.downgrade(ctx)?;
|
|
||||||
Ok(ctx.maybe_thunk(id))
|
|
||||||
})
|
|
||||||
.collect::<Result<_>>()?;
|
|
||||||
let span = self.syntax().text_range();
|
|
||||||
Ok(ctx.new_expr(List { items, span }.to_ir()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Downgrades a binary operation.
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::BinOp {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
let lhs = self.lhs().unwrap().downgrade(ctx)?;
|
|
||||||
let rhs = self.rhs().unwrap().downgrade(ctx)?;
|
|
||||||
let kind = self.operator().unwrap().into();
|
|
||||||
let span = self.syntax().text_range();
|
|
||||||
Ok(ctx.new_expr(
|
|
||||||
BinOp {
|
|
||||||
lhs,
|
|
||||||
rhs,
|
|
||||||
kind,
|
|
||||||
span,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Downgrades a "has attribute" (`?`) expression.
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::HasAttr {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
let lhs = self.expr().unwrap().downgrade(ctx)?;
|
|
||||||
let rhs = downgrade_attrpath(self.attrpath().unwrap(), ctx)?;
|
|
||||||
let span = self.syntax().text_range();
|
|
||||||
Ok(ctx.new_expr(HasAttr { lhs, rhs, span }.to_ir()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Downgrades a unary operation.
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::UnaryOp {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
let rhs = self.expr().unwrap().downgrade(ctx)?;
|
|
||||||
let kind = self.operator().unwrap().into();
|
|
||||||
let span = self.syntax().text_range();
|
|
||||||
Ok(ctx.new_expr(UnOp { rhs, kind, span }.to_ir()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Downgrades an attribute selection (`.`).
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::Select {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
let expr = self.expr().unwrap().downgrade(ctx)?;
|
|
||||||
let attrpath = downgrade_attrpath(self.attrpath().unwrap(), ctx)?;
|
|
||||||
let default = if let Some(default) = self.default_expr() {
|
|
||||||
let default_expr = default.downgrade(ctx)?;
|
|
||||||
Some(ctx.maybe_thunk(default_expr))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
let span = self.syntax().text_range();
|
|
||||||
Ok(ctx.new_expr(
|
|
||||||
Select {
|
|
||||||
expr,
|
|
||||||
attrpath,
|
|
||||||
default,
|
|
||||||
span,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Downgrades a `legacy let`, which is essentially a recursive attribute set.
|
|
||||||
/// The body of the `let` is accessed via `let.body`.
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::LegacyLet {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
let span = self.syntax().text_range();
|
|
||||||
let entries: Vec<_> = self.entries().collect();
|
|
||||||
let attrset_expr = downgrade_let_bindings(entries, ctx, span, |ctx, binding_keys| {
|
|
||||||
// Create plain attrset as body with inherit
|
|
||||||
let mut attrs = AttrSet {
|
|
||||||
stcs: HashMap::new(),
|
|
||||||
dyns: Vec::new(),
|
|
||||||
span,
|
|
||||||
};
|
|
||||||
|
|
||||||
for sym in binding_keys {
|
|
||||||
let expr = ctx.lookup(*sym, synthetic_span())?;
|
|
||||||
attrs.stcs.insert(*sym, (expr, synthetic_span()));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(ctx.new_expr(attrs.to_ir()))
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let body_sym = ctx.new_sym("body".to_string());
|
|
||||||
let select = Select {
|
|
||||||
expr: attrset_expr,
|
|
||||||
attrpath: vec![Attr::Str(body_sym, synthetic_span())],
|
|
||||||
default: None,
|
|
||||||
span,
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(ctx.new_expr(select.to_ir()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Downgrades a `let ... in ...` expression.
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::LetIn {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
let entries: Vec<_> = self.entries().collect();
|
|
||||||
let body_expr = self.body().unwrap();
|
|
||||||
let span = self.syntax().text_range();
|
|
||||||
|
|
||||||
downgrade_let_bindings(entries, ctx, span, |ctx, _binding_keys| {
|
|
||||||
body_expr.downgrade(ctx)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Downgrades a `with` expression.
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::With {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
// with namespace; expr
|
|
||||||
let namespace = self.namespace().unwrap().downgrade(ctx)?;
|
|
||||||
|
|
||||||
// Downgrade body in With scope
|
|
||||||
let expr = ctx.with_with_scope(namespace, |ctx| self.body().unwrap().downgrade(ctx))?;
|
|
||||||
|
|
||||||
Ok(expr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Downgrades a lambda (function) expression.
|
|
||||||
/// This involves desugaring pattern-matching arguments into `let` bindings.
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::Lambda {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
let raw_param = self.param().unwrap();
|
|
||||||
let arg = ctx.new_arg(raw_param.syntax().text_range());
|
|
||||||
|
|
||||||
ctx.push_thunk_scope();
|
|
||||||
|
|
||||||
let param;
|
|
||||||
let body;
|
|
||||||
|
|
||||||
match raw_param {
|
|
||||||
ast::Param::IdentParam(id) => {
|
|
||||||
// Simple case: `x: body`
|
|
||||||
let param_sym = ctx.new_sym(id.to_string());
|
|
||||||
param = None;
|
|
||||||
|
|
||||||
// Downgrade body in Param scope
|
|
||||||
body = ctx
|
|
||||||
.with_param_scope(param_sym, arg, |ctx| self.body().unwrap().downgrade(ctx))?;
|
|
||||||
}
|
|
||||||
ast::Param::Pattern(pattern) => {
|
|
||||||
let alias = pattern
|
|
||||||
.pat_bind()
|
|
||||||
.map(|alias| ctx.new_sym(alias.ident().unwrap().to_string()));
|
|
||||||
|
|
||||||
let ellipsis = pattern.ellipsis_token().is_some();
|
|
||||||
let pat_entries = pattern.pat_entries();
|
|
||||||
|
|
||||||
let PatternBindings {
|
|
||||||
body: inner_body,
|
|
||||||
required,
|
|
||||||
optional,
|
|
||||||
} = downgrade_pattern_bindings(pat_entries, alias, arg, ctx, |ctx, _| {
|
|
||||||
self.body().unwrap().downgrade(ctx)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
param = Some(Param {
|
|
||||||
required,
|
|
||||||
optional,
|
|
||||||
ellipsis,
|
|
||||||
});
|
|
||||||
|
|
||||||
body = inner_body;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let thunks = ctx.pop_thunk_scope();
|
|
||||||
let span = self.syntax().text_range();
|
|
||||||
Ok(ctx.new_expr(
|
|
||||||
Func {
|
|
||||||
body,
|
|
||||||
param,
|
|
||||||
arg,
|
|
||||||
thunks,
|
|
||||||
span,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Downgrades a function application.
|
|
||||||
/// In Nix, function application is left-associative, so `f a b` should be parsed as `((f a) b)`.
|
|
||||||
/// Each Apply node represents a single function call with one argument.
|
|
||||||
impl<Ctx: DowngradeContext> Downgrade<Ctx> for ast::Apply {
|
|
||||||
fn downgrade(self, ctx: &mut Ctx) -> Result<ExprId> {
|
|
||||||
let func = self.lambda().unwrap().downgrade(ctx)?;
|
|
||||||
let arg = self.argument().unwrap().downgrade(ctx)?;
|
|
||||||
let arg = ctx.maybe_thunk(arg);
|
|
||||||
let span = self.syntax().text_range();
|
|
||||||
Ok(ctx.new_expr(Call { func, arg, span }.to_ir()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
#![allow(unused)]
|
|
||||||
|
|
||||||
use rnix::TextRange;
|
|
||||||
|
|
||||||
pub fn merge_spans(spans: impl IntoIterator<Item = TextRange>) -> TextRange {
|
|
||||||
let mut spans = spans.into_iter();
|
|
||||||
let first = spans.next().unwrap_or_else(synthetic_span);
|
|
||||||
|
|
||||||
spans.fold(first, |acc, span| {
|
|
||||||
let start = acc.start().min(span.start());
|
|
||||||
let end = acc.end().max(span.end());
|
|
||||||
TextRange::new(start, end)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn synthetic_span() -> TextRange {
|
|
||||||
TextRange::new(0.into(), 0.into())
|
|
||||||
}
|
|
||||||
@@ -1,834 +0,0 @@
|
|||||||
// Assume no parse error
|
|
||||||
#![allow(clippy::unwrap_used)]
|
|
||||||
|
|
||||||
use hashbrown::hash_map::Entry;
|
|
||||||
use hashbrown::{HashMap, HashSet};
|
|
||||||
use itertools::Itertools as _;
|
|
||||||
use rnix::TextRange;
|
|
||||||
use rnix::ast::{self, HasEntry};
|
|
||||||
use rowan::ast::AstNode;
|
|
||||||
|
|
||||||
use crate::error::{Error, Result};
|
|
||||||
use crate::ir::{Attr, AttrSet, ConcatStrings, ExprId, Select, Str, SymId};
|
|
||||||
use crate::value::format_symbol;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
enum PendingValue {
|
|
||||||
Expr(ast::Expr),
|
|
||||||
InheritFrom(ast::Expr, SymId, TextRange),
|
|
||||||
InheritScope(SymId, TextRange),
|
|
||||||
Set(PendingAttrSet),
|
|
||||||
ExtendedRecAttrSet {
|
|
||||||
base: ast::AttrSet,
|
|
||||||
extensions: Vec<ast::Entry>,
|
|
||||||
span: TextRange,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
struct PendingAttrSet {
|
|
||||||
stcs: HashMap<SymId, (PendingValue, TextRange)>,
|
|
||||||
dyns: Vec<(ast::Attr, PendingValue, TextRange)>,
|
|
||||||
span: TextRange,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PendingAttrSet {
|
|
||||||
fn new(span: TextRange) -> Self {
|
|
||||||
Self {
|
|
||||||
stcs: HashMap::new(),
|
|
||||||
dyns: Vec::new(),
|
|
||||||
span,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn insert(
|
|
||||||
&mut self,
|
|
||||||
path: &[ast::Attr],
|
|
||||||
value: ast::Expr,
|
|
||||||
ctx: &mut impl DowngradeContext,
|
|
||||||
) -> Result<()> {
|
|
||||||
let first = path.first().expect("empty attrpath passed. this is a bug");
|
|
||||||
let rest = &path[1..];
|
|
||||||
let span = first.syntax().text_range();
|
|
||||||
|
|
||||||
match first {
|
|
||||||
ast::Attr::Ident(ident) => {
|
|
||||||
let sym = ctx.new_sym(ident.to_string());
|
|
||||||
self.insert_static(sym, span, rest, value, ctx)
|
|
||||||
}
|
|
||||||
ast::Attr::Str(string) => {
|
|
||||||
let parts = string.normalized_parts();
|
|
||||||
if parts.len() == 1
|
|
||||||
&& let ast::InterpolPart::Literal(lit) = parts.into_iter().next().unwrap()
|
|
||||||
{
|
|
||||||
let sym = ctx.new_sym(lit);
|
|
||||||
return self.insert_static(sym, span, rest, value, ctx);
|
|
||||||
}
|
|
||||||
self.insert_dynamic(first.clone(), span, rest, value)
|
|
||||||
}
|
|
||||||
ast::Attr::Dynamic(_) => self.insert_dynamic(first.clone(), span, rest, value),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn insert_static(
|
|
||||||
&mut self,
|
|
||||||
sym: SymId,
|
|
||||||
span: TextRange,
|
|
||||||
path: &[ast::Attr],
|
|
||||||
value: ast::Expr,
|
|
||||||
ctx: &mut impl DowngradeContext,
|
|
||||||
) -> Result<()> {
|
|
||||||
if !path.is_empty() {
|
|
||||||
match self.stcs.entry(sym) {
|
|
||||||
Entry::Occupied(mut entry) => {
|
|
||||||
let (existing, existing_span) = entry.get_mut();
|
|
||||||
|
|
||||||
if let PendingValue::Expr(ast::Expr::AttrSet(attrset)) = existing
|
|
||||||
&& attrset.rec_token().is_some()
|
|
||||||
{
|
|
||||||
let base = attrset.clone();
|
|
||||||
let base_span = attrset.syntax().text_range();
|
|
||||||
let ext_entry = make_attrpath_value_entry(path.to_vec(), value);
|
|
||||||
*existing = PendingValue::ExtendedRecAttrSet {
|
|
||||||
base,
|
|
||||||
extensions: vec![ext_entry],
|
|
||||||
span: base_span,
|
|
||||||
};
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
if let PendingValue::ExtendedRecAttrSet { extensions, .. } = existing {
|
|
||||||
let ext_entry = make_attrpath_value_entry(path.to_vec(), value);
|
|
||||||
extensions.push(ext_entry);
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let nested = Self::ensure_pending_set(existing, ctx, *existing_span)?;
|
|
||||||
nested.insert(path, value, ctx)
|
|
||||||
}
|
|
||||||
Entry::Vacant(entry) => {
|
|
||||||
let mut nested = PendingAttrSet::new(span);
|
|
||||||
nested.insert(path, value, ctx)?;
|
|
||||||
entry.insert((PendingValue::Set(nested), span));
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
match self.stcs.entry(sym) {
|
|
||||||
Entry::Occupied(mut entry) => {
|
|
||||||
let (existing, existing_span) = entry.get_mut();
|
|
||||||
Self::merge_value(existing, *existing_span, value, span, ctx)
|
|
||||||
}
|
|
||||||
Entry::Vacant(entry) => {
|
|
||||||
entry.insert((PendingValue::Expr(value), span));
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn insert_dynamic(
|
|
||||||
&mut self,
|
|
||||||
attr: ast::Attr,
|
|
||||||
span: TextRange,
|
|
||||||
path: &[ast::Attr],
|
|
||||||
value: ast::Expr,
|
|
||||||
) -> Result<()> {
|
|
||||||
if !path.is_empty() {
|
|
||||||
let mut nested = PendingAttrSet::new(span);
|
|
||||||
nested.insert_dynamic(
|
|
||||||
path[0].clone(),
|
|
||||||
path[0].syntax().text_range(),
|
|
||||||
&path[1..],
|
|
||||||
value,
|
|
||||||
)?;
|
|
||||||
self.dyns.push((attr, PendingValue::Set(nested), span));
|
|
||||||
} else {
|
|
||||||
self.dyns.push((attr, PendingValue::Expr(value), span));
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ensure_pending_set<'a>(
|
|
||||||
value: &'a mut PendingValue,
|
|
||||||
ctx: &mut impl DowngradeContext,
|
|
||||||
span: TextRange,
|
|
||||||
) -> Result<&'a mut PendingAttrSet> {
|
|
||||||
match value {
|
|
||||||
PendingValue::Set(set) => Ok(set),
|
|
||||||
PendingValue::Expr(expr) => {
|
|
||||||
if let ast::Expr::AttrSet(attrset) = expr {
|
|
||||||
let mut nested = PendingAttrSet::new(attrset.syntax().text_range());
|
|
||||||
nested.collect_entries(attrset.entries(), ctx)?;
|
|
||||||
*value = PendingValue::Set(nested);
|
|
||||||
match value {
|
|
||||||
PendingValue::Set(set) => Ok(set),
|
|
||||||
_ => unreachable!(),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Err(Error::downgrade_error(
|
|
||||||
"attribute already defined but is not an attribute set".to_string(),
|
|
||||||
ctx.get_current_source(),
|
|
||||||
span,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PendingValue::ExtendedRecAttrSet { .. } => Err(Error::downgrade_error(
|
|
||||||
"cannot add nested attributes to rec attribute set with extensions".to_string(),
|
|
||||||
ctx.get_current_source(),
|
|
||||||
span,
|
|
||||||
)),
|
|
||||||
PendingValue::InheritFrom(..) | PendingValue::InheritScope(..) => {
|
|
||||||
Err(Error::downgrade_error(
|
|
||||||
"attribute already defined (inherited)".to_string(),
|
|
||||||
ctx.get_current_source(),
|
|
||||||
span,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn merge_value(
|
|
||||||
existing: &mut PendingValue,
|
|
||||||
existing_span: TextRange,
|
|
||||||
new_value: ast::Expr,
|
|
||||||
new_span: TextRange,
|
|
||||||
ctx: &mut impl DowngradeContext,
|
|
||||||
) -> Result<()> {
|
|
||||||
match existing {
|
|
||||||
PendingValue::Set(existing_set) => {
|
|
||||||
if let ast::Expr::AttrSet(new_attrset) = new_value {
|
|
||||||
existing_set.collect_entries(new_attrset.entries(), ctx)
|
|
||||||
} else {
|
|
||||||
Err(Error::downgrade_error(
|
|
||||||
"attribute already defined as attribute set".to_string(),
|
|
||||||
ctx.get_current_source(),
|
|
||||||
new_span,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PendingValue::Expr(existing_expr) => {
|
|
||||||
if let ast::Expr::AttrSet(existing_attrset) = existing_expr {
|
|
||||||
if let ast::Expr::AttrSet(new_attrset) = new_value {
|
|
||||||
let is_rec = existing_attrset.rec_token().is_some();
|
|
||||||
if is_rec {
|
|
||||||
let base = existing_attrset.clone();
|
|
||||||
let extensions: Vec<_> = new_attrset.entries().collect();
|
|
||||||
*existing = PendingValue::ExtendedRecAttrSet {
|
|
||||||
base,
|
|
||||||
extensions,
|
|
||||||
span: existing_attrset.syntax().text_range(),
|
|
||||||
};
|
|
||||||
Ok(())
|
|
||||||
} else {
|
|
||||||
let mut merged =
|
|
||||||
PendingAttrSet::new(existing_attrset.syntax().text_range());
|
|
||||||
merged.collect_entries(existing_attrset.entries(), ctx)?;
|
|
||||||
merged.collect_entries(new_attrset.entries(), ctx)?;
|
|
||||||
*existing = PendingValue::Set(merged);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Err(Error::downgrade_error(
|
|
||||||
"attribute already defined as attribute set".to_string(),
|
|
||||||
ctx.get_current_source(),
|
|
||||||
new_span,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Err(Error::downgrade_error(
|
|
||||||
"attribute already defined".to_string(),
|
|
||||||
ctx.get_current_source(),
|
|
||||||
existing_span,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PendingValue::ExtendedRecAttrSet { extensions, .. } => {
|
|
||||||
if let ast::Expr::AttrSet(new_attrset) = new_value {
|
|
||||||
extensions.extend(new_attrset.entries());
|
|
||||||
Ok(())
|
|
||||||
} else {
|
|
||||||
Err(Error::downgrade_error(
|
|
||||||
"attribute already defined as attribute set".to_string(),
|
|
||||||
ctx.get_current_source(),
|
|
||||||
new_span,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PendingValue::InheritFrom(..) | PendingValue::InheritScope(..) => {
|
|
||||||
Err(Error::downgrade_error(
|
|
||||||
"attribute already defined (inherited)".to_string(),
|
|
||||||
ctx.get_current_source(),
|
|
||||||
existing_span,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn collect_entries(
|
|
||||||
&mut self,
|
|
||||||
entries: impl Iterator<Item = ast::Entry>,
|
|
||||||
ctx: &mut impl DowngradeContext,
|
|
||||||
) -> Result<()> {
|
|
||||||
for entry in entries {
|
|
||||||
match entry {
|
|
||||||
ast::Entry::Inherit(inherit) => {
|
|
||||||
self.collect_inherit(inherit, ctx)?;
|
|
||||||
}
|
|
||||||
ast::Entry::AttrpathValue(value) => {
|
|
||||||
let attrpath = value.attrpath().unwrap();
|
|
||||||
let path: Vec<_> = attrpath.attrs().collect();
|
|
||||||
let expr = value.value().unwrap();
|
|
||||||
self.insert(&path, expr, ctx)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn collect_inherit(
|
|
||||||
&mut self,
|
|
||||||
inherit: ast::Inherit,
|
|
||||||
ctx: &mut impl DowngradeContext,
|
|
||||||
) -> Result<()> {
|
|
||||||
let from = inherit.from().map(|f| f.expr().unwrap());
|
|
||||||
for attr in inherit.attrs() {
|
|
||||||
let span = attr.syntax().text_range();
|
|
||||||
let sym = match &attr {
|
|
||||||
ast::Attr::Ident(ident) => ctx.new_sym(ident.to_string()),
|
|
||||||
ast::Attr::Str(s) => {
|
|
||||||
let parts = s.normalized_parts();
|
|
||||||
if parts.len() == 1
|
|
||||||
&& let ast::InterpolPart::Literal(lit) = parts.into_iter().next().unwrap()
|
|
||||||
{
|
|
||||||
ctx.new_sym(lit)
|
|
||||||
} else {
|
|
||||||
return Err(Error::downgrade_error(
|
|
||||||
"dynamic attributes not allowed in inherit".to_string(),
|
|
||||||
ctx.get_current_source(),
|
|
||||||
span,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ast::Attr::Dynamic(_) => {
|
|
||||||
return Err(Error::downgrade_error(
|
|
||||||
"dynamic attributes not allowed in inherit".to_string(),
|
|
||||||
ctx.get_current_source(),
|
|
||||||
span,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if self.stcs.contains_key(&sym) {
|
|
||||||
return Err(Error::downgrade_error(
|
|
||||||
format!(
|
|
||||||
"attribute '{}' already defined",
|
|
||||||
format_symbol(ctx.get_sym(sym))
|
|
||||||
),
|
|
||||||
ctx.get_current_source(),
|
|
||||||
span,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let pending_value = if let Some(ref from_expr) = from {
|
|
||||||
PendingValue::InheritFrom(from_expr.clone(), sym, span)
|
|
||||||
} else {
|
|
||||||
PendingValue::InheritScope(sym, span)
|
|
||||||
};
|
|
||||||
|
|
||||||
self.stcs.insert(sym, (pending_value, span));
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn make_attrpath_value_entry(path: Vec<ast::Attr>, value: ast::Expr) -> ast::Entry {
|
|
||||||
use rnix::{NixLanguage, SyntaxKind};
|
|
||||||
use rowan::{GreenNodeBuilder, Language, NodeOrToken};
|
|
||||||
|
|
||||||
let mut builder = GreenNodeBuilder::new();
|
|
||||||
builder.start_node(NixLanguage::kind_to_raw(SyntaxKind::NODE_ATTRPATH_VALUE));
|
|
||||||
|
|
||||||
builder.start_node(NixLanguage::kind_to_raw(SyntaxKind::NODE_ATTRPATH));
|
|
||||||
for attr in path {
|
|
||||||
fn add_node(builder: &mut GreenNodeBuilder, node: &rowan::SyntaxNode<NixLanguage>) {
|
|
||||||
for child in node.children_with_tokens() {
|
|
||||||
match child {
|
|
||||||
NodeOrToken::Node(n) => {
|
|
||||||
builder.start_node(NixLanguage::kind_to_raw(n.kind()));
|
|
||||||
add_node(builder, &n);
|
|
||||||
builder.finish_node();
|
|
||||||
}
|
|
||||||
NodeOrToken::Token(t) => {
|
|
||||||
builder.token(NixLanguage::kind_to_raw(t.kind()), t.text());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
builder.start_node(NixLanguage::kind_to_raw(attr.syntax().kind()));
|
|
||||||
add_node(&mut builder, attr.syntax());
|
|
||||||
builder.finish_node();
|
|
||||||
}
|
|
||||||
builder.finish_node();
|
|
||||||
|
|
||||||
builder.token(NixLanguage::kind_to_raw(SyntaxKind::TOKEN_ASSIGN), "=");
|
|
||||||
|
|
||||||
builder.start_node(NixLanguage::kind_to_raw(value.syntax().kind()));
|
|
||||||
fn add_node_value(builder: &mut GreenNodeBuilder, node: &rowan::SyntaxNode<NixLanguage>) {
|
|
||||||
for child in node.children_with_tokens() {
|
|
||||||
match child {
|
|
||||||
NodeOrToken::Node(n) => {
|
|
||||||
builder.start_node(NixLanguage::kind_to_raw(n.kind()));
|
|
||||||
add_node_value(builder, &n);
|
|
||||||
builder.finish_node();
|
|
||||||
}
|
|
||||||
NodeOrToken::Token(t) => {
|
|
||||||
builder.token(NixLanguage::kind_to_raw(t.kind()), t.text());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
add_node_value(&mut builder, value.syntax());
|
|
||||||
builder.finish_node();
|
|
||||||
|
|
||||||
builder.token(NixLanguage::kind_to_raw(SyntaxKind::TOKEN_SEMICOLON), ";");
|
|
||||||
|
|
||||||
builder.finish_node();
|
|
||||||
|
|
||||||
let green = builder.finish();
|
|
||||||
let node = rowan::SyntaxNode::<NixLanguage>::new_root(green);
|
|
||||||
ast::Entry::cast(node).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Downgrades the entries of a non-recursive attribute set.
|
|
||||||
pub fn downgrade_attrs(
|
|
||||||
attrs: impl ast::HasEntry + AstNode,
|
|
||||||
ctx: &mut impl DowngradeContext,
|
|
||||||
) -> Result<AttrSet> {
|
|
||||||
let span = attrs.syntax().text_range();
|
|
||||||
let mut pending = PendingAttrSet::new(span);
|
|
||||||
pending.collect_entries(attrs.entries(), ctx)?;
|
|
||||||
finalize_pending_set::<_, true>(pending, &HashMap::new(), ctx)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Downgrades a single attribute key (part of an attribute path).
|
|
||||||
pub fn downgrade_attr(attr: ast::Attr, ctx: &mut impl DowngradeContext) -> Result<Attr> {
|
|
||||||
use ast::Attr::*;
|
|
||||||
use ast::InterpolPart::*;
|
|
||||||
match attr {
|
|
||||||
Ident(ident) => Ok(Attr::Str(
|
|
||||||
ctx.new_sym(ident.to_string()),
|
|
||||||
ident.syntax().text_range(),
|
|
||||||
)),
|
|
||||||
Str(string) => {
|
|
||||||
let parts = string.normalized_parts();
|
|
||||||
let span = string.syntax().text_range();
|
|
||||||
if parts.is_empty() {
|
|
||||||
Ok(Attr::Str(ctx.new_sym("".to_string()), span))
|
|
||||||
} else if parts.len() == 1 {
|
|
||||||
match parts.into_iter().next().unwrap() {
|
|
||||||
Literal(ident) => Ok(Attr::Str(ctx.new_sym(ident), span)),
|
|
||||||
Interpolation(interpol) => Ok(Attr::Dynamic(
|
|
||||||
interpol.expr().unwrap().downgrade(ctx)?,
|
|
||||||
span,
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let parts = parts
|
|
||||||
.into_iter()
|
|
||||||
.map(|part| match part {
|
|
||||||
Literal(lit) => Ok(ctx.new_expr(self::Str { val: lit, span }.to_ir())),
|
|
||||||
Interpolation(interpol) => interpol.expr().unwrap().downgrade(ctx),
|
|
||||||
})
|
|
||||||
.collect::<Result<Vec<_>>>()?;
|
|
||||||
Ok(Attr::Dynamic(
|
|
||||||
ctx.new_expr(
|
|
||||||
ConcatStrings {
|
|
||||||
parts,
|
|
||||||
span,
|
|
||||||
force_string: true,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
),
|
|
||||||
span,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Dynamic(dynamic) => Ok(Attr::Dynamic(
|
|
||||||
dynamic.expr().unwrap().downgrade(ctx)?,
|
|
||||||
dynamic.syntax().text_range(),
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Downgrades an attribute path (e.g., `a.b."${c}".d`) into a `Vec<Attr>`.
|
|
||||||
pub fn downgrade_attrpath(
|
|
||||||
attrpath: ast::Attrpath,
|
|
||||||
ctx: &mut impl DowngradeContext,
|
|
||||||
) -> Result<Vec<Attr>> {
|
|
||||||
attrpath
|
|
||||||
.attrs()
|
|
||||||
.map(|attr| downgrade_attr(attr, ctx))
|
|
||||||
.collect::<Result<Vec<_>>>()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct PatternBindings {
|
|
||||||
pub body: ExprId,
|
|
||||||
pub required: Vec<(SymId, TextRange)>,
|
|
||||||
pub optional: Vec<(SymId, TextRange)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper function for Lambda pattern parameters.
|
|
||||||
pub fn downgrade_pattern_bindings<Ctx>(
|
|
||||||
pat_entries: impl Iterator<Item = ast::PatEntry>,
|
|
||||||
alias: Option<SymId>,
|
|
||||||
arg: ExprId,
|
|
||||||
ctx: &mut Ctx,
|
|
||||||
body_fn: impl FnOnce(&mut Ctx, &[SymId]) -> Result<ExprId>,
|
|
||||||
) -> Result<PatternBindings>
|
|
||||||
where
|
|
||||||
Ctx: DowngradeContext,
|
|
||||||
{
|
|
||||||
struct Param {
|
|
||||||
sym: SymId,
|
|
||||||
sym_span: TextRange,
|
|
||||||
default: Option<ast::Expr>,
|
|
||||||
span: TextRange,
|
|
||||||
}
|
|
||||||
let mut seen_params = HashSet::new();
|
|
||||||
let (params, mut binding_keys) = pat_entries
|
|
||||||
.into_iter()
|
|
||||||
.map(|entry| {
|
|
||||||
let ident = entry.ident().unwrap();
|
|
||||||
let sym_span = ident.syntax().text_range();
|
|
||||||
let sym = ctx.new_sym(ident.syntax().text().to_string());
|
|
||||||
let default = entry.default();
|
|
||||||
let span = entry.syntax().text_range();
|
|
||||||
|
|
||||||
if !seen_params.insert(sym) {
|
|
||||||
return Err(Error::downgrade_error(
|
|
||||||
format!("duplicate parameter '{}'", format_symbol(ctx.get_sym(sym))),
|
|
||||||
ctx.get_current_source(),
|
|
||||||
span,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok((
|
|
||||||
Param {
|
|
||||||
sym,
|
|
||||||
sym_span,
|
|
||||||
default,
|
|
||||||
span,
|
|
||||||
},
|
|
||||||
sym,
|
|
||||||
))
|
|
||||||
})
|
|
||||||
.collect::<Result<(Vec<_>, Vec<_>)>>()?;
|
|
||||||
|
|
||||||
if let Some(alias_sym) = alias {
|
|
||||||
binding_keys.push(alias_sym);
|
|
||||||
}
|
|
||||||
|
|
||||||
let (required, optional) = params.iter().partition_map(
|
|
||||||
|Param {
|
|
||||||
sym,
|
|
||||||
sym_span,
|
|
||||||
default,
|
|
||||||
..
|
|
||||||
}| {
|
|
||||||
use itertools::Either::*;
|
|
||||||
if default.is_none() {
|
|
||||||
Left((*sym, *sym_span))
|
|
||||||
} else {
|
|
||||||
Right((*sym, *sym_span))
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
let slots: Vec<_> = ctx.reserve_slots(binding_keys.len()).collect();
|
|
||||||
let let_bindings: HashMap<_, _> = binding_keys
|
|
||||||
.iter()
|
|
||||||
.copied()
|
|
||||||
.zip(slots.iter().copied())
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
for &slot in &slots {
|
|
||||||
let span = synthetic_span();
|
|
||||||
ctx.replace_ir(slot, Thunk { inner: slot, span }.to_ir());
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.with_let_scope(let_bindings.clone(), |ctx| {
|
|
||||||
for Param {
|
|
||||||
sym,
|
|
||||||
sym_span,
|
|
||||||
default,
|
|
||||||
span,
|
|
||||||
} in params
|
|
||||||
{
|
|
||||||
let slot = *let_bindings.get(&sym).unwrap();
|
|
||||||
|
|
||||||
let default = if let Some(default) = default {
|
|
||||||
let default = default.clone().downgrade(ctx)?;
|
|
||||||
Some(ctx.maybe_thunk(default))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
let select_expr = ctx.new_expr(
|
|
||||||
Select {
|
|
||||||
expr: arg,
|
|
||||||
attrpath: vec![Attr::Str(sym, sym_span)],
|
|
||||||
default,
|
|
||||||
span,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
);
|
|
||||||
ctx.register_thunk(slot, select_expr);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(alias_sym) = alias {
|
|
||||||
let slot = *let_bindings.get(&alias_sym).unwrap();
|
|
||||||
ctx.register_thunk(slot, arg);
|
|
||||||
}
|
|
||||||
|
|
||||||
let body = body_fn(ctx, &binding_keys)?;
|
|
||||||
|
|
||||||
Ok(PatternBindings {
|
|
||||||
body,
|
|
||||||
required,
|
|
||||||
optional,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Downgrades a `let...in` expression. This is a special case of rec attrs
|
|
||||||
/// that disallows dynamic attributes and has a body expression.
|
|
||||||
pub fn downgrade_let_bindings<Ctx, F>(
|
|
||||||
entries: Vec<ast::Entry>,
|
|
||||||
ctx: &mut Ctx,
|
|
||||||
span: TextRange,
|
|
||||||
body_fn: F,
|
|
||||||
) -> Result<ExprId>
|
|
||||||
where
|
|
||||||
Ctx: DowngradeContext,
|
|
||||||
F: FnOnce(&mut Ctx, &[SymId]) -> Result<ExprId>,
|
|
||||||
{
|
|
||||||
downgrade_rec_attrs_impl::<_, _, false>(entries, ctx, span, |ctx, binding_keys, _dyns| {
|
|
||||||
body_fn(ctx, binding_keys)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Downgrades a `rec` attribute set.
|
|
||||||
pub fn downgrade_rec_bindings<Ctx>(
|
|
||||||
entries: Vec<ast::Entry>,
|
|
||||||
ctx: &mut Ctx,
|
|
||||||
span: TextRange,
|
|
||||||
) -> Result<ExprId>
|
|
||||||
where
|
|
||||||
Ctx: DowngradeContext,
|
|
||||||
{
|
|
||||||
downgrade_rec_attrs_impl::<_, _, true>(entries, ctx, span, |ctx, binding_keys, dyns| {
|
|
||||||
let mut attrs = AttrSet {
|
|
||||||
stcs: HashMap::new(),
|
|
||||||
dyns: dyns.to_vec(),
|
|
||||||
span,
|
|
||||||
};
|
|
||||||
|
|
||||||
for sym in binding_keys {
|
|
||||||
let expr = ctx.lookup(*sym, synthetic_span())?;
|
|
||||||
attrs.stcs.insert(*sym, (expr, synthetic_span()));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(ctx.new_expr(attrs.to_ir()))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Core implementation for recursive bindings (rec attrs and let-in).
|
|
||||||
/// ALLOW_DYN controls whether dynamic attributes are allowed.
|
|
||||||
fn downgrade_rec_attrs_impl<Ctx, F, const ALLOW_DYN: bool>(
|
|
||||||
entries: Vec<ast::Entry>,
|
|
||||||
ctx: &mut Ctx,
|
|
||||||
span: TextRange,
|
|
||||||
body_fn: F,
|
|
||||||
) -> Result<ExprId>
|
|
||||||
where
|
|
||||||
Ctx: DowngradeContext,
|
|
||||||
F: FnOnce(&mut Ctx, &[SymId], &[(ExprId, ExprId, TextRange)]) -> Result<ExprId>,
|
|
||||||
{
|
|
||||||
let mut pending = PendingAttrSet::new(span);
|
|
||||||
pending.collect_entries(entries.iter().cloned(), ctx)?;
|
|
||||||
|
|
||||||
let binding_syms = collect_binding_syms::<_, ALLOW_DYN>(&pending, ctx)?;
|
|
||||||
|
|
||||||
let inherit_lookups = collect_inherit_lookups(&entries, ctx)?;
|
|
||||||
|
|
||||||
let binding_keys: Vec<_> = binding_syms.into_iter().collect();
|
|
||||||
let slots: Vec<_> = ctx.reserve_slots(binding_keys.len()).collect();
|
|
||||||
let let_bindings: HashMap<_, _> = binding_keys
|
|
||||||
.iter()
|
|
||||||
.copied()
|
|
||||||
.zip(slots.iter().copied())
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
for &slot in &slots {
|
|
||||||
let slot_span = synthetic_span();
|
|
||||||
ctx.replace_ir(
|
|
||||||
slot,
|
|
||||||
Thunk {
|
|
||||||
inner: slot,
|
|
||||||
span: slot_span,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.with_let_scope(let_bindings.clone(), |ctx| {
|
|
||||||
let finalized = finalize_pending_set::<_, ALLOW_DYN>(pending, &inherit_lookups, ctx)?;
|
|
||||||
|
|
||||||
for (sym, slot) in binding_keys.iter().copied().zip(slots.iter()) {
|
|
||||||
if let Some(&(expr, _)) = finalized.stcs.get(&sym) {
|
|
||||||
ctx.register_thunk(*slot, expr);
|
|
||||||
} else {
|
|
||||||
return Err(Error::internal(format!(
|
|
||||||
"binding '{}' not found",
|
|
||||||
format_symbol(ctx.get_sym(sym))
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
body_fn(ctx, &binding_keys, &finalized.dyns)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Collects `inherit x` lookups from the outer scope before entering the rec scope.
|
|
||||||
fn collect_inherit_lookups<Ctx: DowngradeContext>(
|
|
||||||
entries: &[ast::Entry],
|
|
||||||
ctx: &mut Ctx,
|
|
||||||
) -> Result<HashMap<SymId, (ExprId, TextRange)>> {
|
|
||||||
let mut inherit_lookups = HashMap::new();
|
|
||||||
for entry in entries {
|
|
||||||
if let ast::Entry::Inherit(inherit) = entry
|
|
||||||
&& inherit.from().is_none()
|
|
||||||
{
|
|
||||||
for attr in inherit.attrs() {
|
|
||||||
if let ast::Attr::Ident(ident) = attr {
|
|
||||||
let attr_span = ident.syntax().text_range();
|
|
||||||
let sym = ctx.new_sym(ident.to_string());
|
|
||||||
let expr = ctx.lookup(sym, attr_span)?;
|
|
||||||
inherit_lookups.insert(sym, (expr, attr_span));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(inherit_lookups)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Collects binding symbols from a pending set, checking for duplicates.
|
|
||||||
fn collect_binding_syms<Ctx: DowngradeContext, const ALLOW_DYN: bool>(
|
|
||||||
pending: &PendingAttrSet,
|
|
||||||
ctx: &mut Ctx,
|
|
||||||
) -> Result<HashSet<SymId>> {
|
|
||||||
let mut binding_syms = HashSet::new();
|
|
||||||
|
|
||||||
for (sym, (_, span)) in &pending.stcs {
|
|
||||||
if !binding_syms.insert(*sym) {
|
|
||||||
return Err(Error::downgrade_error(
|
|
||||||
format!(
|
|
||||||
"attribute '{}' already defined",
|
|
||||||
format_symbol(ctx.get_sym(*sym))
|
|
||||||
),
|
|
||||||
ctx.get_current_source(),
|
|
||||||
*span,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(binding_syms)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Unified finalize function for PendingAttrSet.
|
|
||||||
/// ALLOW_DYN controls whether dynamic attributes are allowed.
|
|
||||||
fn finalize_pending_set<Ctx: DowngradeContext, const ALLOW_DYN: bool>(
|
|
||||||
pending: PendingAttrSet,
|
|
||||||
inherit_lookups: &HashMap<SymId, (ExprId, TextRange)>,
|
|
||||||
ctx: &mut Ctx,
|
|
||||||
) -> Result<AttrSet> {
|
|
||||||
let mut stcs = HashMap::new();
|
|
||||||
let mut dyns = Vec::new();
|
|
||||||
|
|
||||||
for (sym, (value, value_span)) in pending.stcs {
|
|
||||||
let expr_id = finalize_pending_value::<_, ALLOW_DYN>(value, inherit_lookups, ctx)?;
|
|
||||||
stcs.insert(sym, (expr_id, value_span));
|
|
||||||
}
|
|
||||||
|
|
||||||
if ALLOW_DYN {
|
|
||||||
for (attr, value, value_span) in pending.dyns {
|
|
||||||
let key_id = downgrade_attr(attr, ctx)?;
|
|
||||||
let key_expr = match key_id {
|
|
||||||
Attr::Dynamic(id, _) => id,
|
|
||||||
Attr::Str(sym, attr_span) => ctx.new_expr(
|
|
||||||
Str {
|
|
||||||
val: ctx.get_sym(sym).to_string(),
|
|
||||||
span: attr_span,
|
|
||||||
}
|
|
||||||
.to_ir(),
|
|
||||||
),
|
|
||||||
};
|
|
||||||
let value_id = finalize_pending_value::<_, ALLOW_DYN>(value, inherit_lookups, ctx)?;
|
|
||||||
dyns.push((key_expr, value_id, value_span));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(AttrSet {
|
|
||||||
stcs,
|
|
||||||
dyns,
|
|
||||||
span: pending.span,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Unified finalize function for PendingValue.
|
|
||||||
/// ALLOW_DYN controls whether dynamic attributes are allowed.
|
|
||||||
fn finalize_pending_value<Ctx: DowngradeContext, const ALLOW_DYN: bool>(
|
|
||||||
value: PendingValue,
|
|
||||||
inherit_lookups: &HashMap<SymId, (ExprId, TextRange)>,
|
|
||||||
ctx: &mut Ctx,
|
|
||||||
) -> Result<ExprId> {
|
|
||||||
match value {
|
|
||||||
PendingValue::Expr(expr) => {
|
|
||||||
let id = Downgrade::downgrade(expr, ctx)?;
|
|
||||||
Ok(ctx.maybe_thunk(id))
|
|
||||||
}
|
|
||||||
PendingValue::InheritFrom(from_expr, sym, span) => {
|
|
||||||
let from_id = Downgrade::downgrade(from_expr, ctx)?;
|
|
||||||
let select = Select {
|
|
||||||
expr: from_id,
|
|
||||||
attrpath: vec![Attr::Str(sym, span)],
|
|
||||||
default: None,
|
|
||||||
span,
|
|
||||||
};
|
|
||||||
let select_id = ctx.new_expr(select.to_ir());
|
|
||||||
Ok(ctx.maybe_thunk(select_id))
|
|
||||||
}
|
|
||||||
PendingValue::InheritScope(sym, span) => {
|
|
||||||
if let Some(&(expr, _)) = inherit_lookups.get(&sym) {
|
|
||||||
Ok(ctx.maybe_thunk(expr))
|
|
||||||
} else {
|
|
||||||
let lookup_id = ctx.lookup(sym, span)?;
|
|
||||||
Ok(ctx.maybe_thunk(lookup_id))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PendingValue::Set(set) => {
|
|
||||||
let attrset = finalize_pending_set::<_, ALLOW_DYN>(set, inherit_lookups, ctx)?;
|
|
||||||
Ok(ctx.new_expr(attrset.to_ir()))
|
|
||||||
}
|
|
||||||
PendingValue::ExtendedRecAttrSet {
|
|
||||||
base,
|
|
||||||
extensions,
|
|
||||||
span,
|
|
||||||
} => {
|
|
||||||
let mut all_entries: Vec<_> = base.entries().collect();
|
|
||||||
all_entries.extend(extensions);
|
|
||||||
downgrade_rec_bindings(all_entries, ctx, span)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,13 +5,18 @@ pub mod error;
|
|||||||
pub mod logging;
|
pub mod logging;
|
||||||
pub mod value;
|
pub mod value;
|
||||||
|
|
||||||
|
mod bytecode;
|
||||||
mod codegen;
|
mod codegen;
|
||||||
|
mod derivation;
|
||||||
|
mod disassembler;
|
||||||
|
mod downgrade;
|
||||||
mod fetcher;
|
mod fetcher;
|
||||||
mod ir;
|
mod ir;
|
||||||
mod nar;
|
mod nar;
|
||||||
mod nix_hash;
|
mod nix_utils;
|
||||||
mod runtime;
|
mod runtime;
|
||||||
mod store;
|
mod store;
|
||||||
|
mod string_context;
|
||||||
|
|
||||||
#[global_allocator]
|
#[global_allocator]
|
||||||
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
|
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
use std::env;
|
use std::env;
|
||||||
use std::io::IsTerminal;
|
use std::io::IsTerminal;
|
||||||
|
|
||||||
use tracing_subscriber::{EnvFilter, Layer, fmt, layer::SubscriberExt, util::SubscriberInitExt};
|
use tracing_subscriber::{EnvFilter, Layer, fmt, layer::SubscriberExt, util::SubscriberInitExt};
|
||||||
|
|
||||||
pub fn init_logging() {
|
pub fn init_logging() {
|
||||||
|
|||||||
187
nix-js/src/main.rs
Normal file
187
nix-js/src/main.rs
Normal file
@@ -0,0 +1,187 @@
|
|||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::exit;
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use clap::{Args, Parser, Subcommand};
|
||||||
|
use hashbrown::HashSet;
|
||||||
|
use nix_js::context::Context;
|
||||||
|
use nix_js::error::Source;
|
||||||
|
use rustyline::DefaultEditor;
|
||||||
|
use rustyline::error::ReadlineError;
|
||||||
|
|
||||||
|
#[derive(Parser)]
|
||||||
|
#[command(name = "nix-js", about = "Nix expression evaluator")]
|
||||||
|
struct Cli {
|
||||||
|
#[cfg(feature = "inspector")]
|
||||||
|
#[arg(long, value_name = "HOST:PORT", num_args = 0..=1, default_missing_value = "127.0.0.1:9229")]
|
||||||
|
inspect: Option<String>,
|
||||||
|
|
||||||
|
#[cfg(feature = "inspector")]
|
||||||
|
#[arg(long, value_name = "HOST:PORT", num_args = 0..=1, default_missing_value = "127.0.0.1:9229")]
|
||||||
|
inspect_brk: Option<String>,
|
||||||
|
|
||||||
|
#[command(subcommand)]
|
||||||
|
command: Command,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Subcommand)]
|
||||||
|
enum Command {
|
||||||
|
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")]
|
||||||
|
{
|
||||||
|
let (addr_str, wait) = if let Some(ref addr) = cli.inspect_brk {
|
||||||
|
(Some(addr.as_str()), true)
|
||||||
|
} else if let Some(ref addr) = cli.inspect {
|
||||||
|
(Some(addr.as_str()), false)
|
||||||
|
} else {
|
||||||
|
(None, false)
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(addr_str) = addr_str {
|
||||||
|
let addr: std::net::SocketAddr = addr_str
|
||||||
|
.parse()
|
||||||
|
.map_err(|e| anyhow::anyhow!("invalid inspector address '{}': {}", addr_str, e))?;
|
||||||
|
return Ok(Context::new_with_inspector(addr, wait)?);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Context::new()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
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.display_compat());
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("{:?}", miette::Report::new(*err));
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
#[cfg(feature = "inspector")]
|
||||||
|
context.wait_for_inspector_disconnect();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_repl(context: &mut Context) -> Result<()> {
|
||||||
|
let mut rl = DefaultEditor::new()?;
|
||||||
|
let mut scope = HashSet::new();
|
||||||
|
const RE: ere::Regex<3> = ere::compile_regex!("^[ \t]*([a-zA-Z_][a-zA-Z0-9_'-]*)[ \t]*(.*)$");
|
||||||
|
loop {
|
||||||
|
let readline = rl.readline("nix-js-repl> ");
|
||||||
|
match readline {
|
||||||
|
Ok(line) => {
|
||||||
|
if line.trim().is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let _ = rl.add_history_entry(line.as_str());
|
||||||
|
if let Some([Some(_), Some(ident), Some(rest)]) = RE.exec(&line) {
|
||||||
|
if let Some(expr) = rest.strip_prefix('=') {
|
||||||
|
let expr = expr.trim_start();
|
||||||
|
if expr.is_empty() {
|
||||||
|
eprintln!("Error: missing expression after '='");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match context.add_binding(ident, expr, &mut scope) {
|
||||||
|
Ok(value) => println!("{} = {}", ident, value),
|
||||||
|
Err(err) => eprintln!("{:?}", miette::Report::new(*err)),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let src = Source::new_repl(line)?;
|
||||||
|
match context.eval_repl(src, &scope) {
|
||||||
|
Ok(value) => println!("{value}"),
|
||||||
|
Err(err) => eprintln!("{:?}", miette::Report::new(*err)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let src = Source::new_repl(line)?;
|
||||||
|
match context.eval_shallow(src) {
|
||||||
|
Ok(value) => println!("{value}"),
|
||||||
|
Err(err) => eprintln!("{:?}", miette::Report::new(*err)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(ReadlineError::Interrupted) => {
|
||||||
|
println!();
|
||||||
|
}
|
||||||
|
Err(ReadlineError::Eof) => {
|
||||||
|
println!("CTRL-D");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Error: {err:?}");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<()> {
|
||||||
|
nix_js::logging::init_logging();
|
||||||
|
|
||||||
|
let cli = Cli::parse();
|
||||||
|
|
||||||
|
let mut context = create_context(
|
||||||
|
#[cfg(feature = "inspector")]
|
||||||
|
&cli,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
match cli.command {
|
||||||
|
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,18 +1,19 @@
|
|||||||
use nix_nar::Encoder;
|
|
||||||
use sha2::{Digest, Sha256};
|
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
|
use nix_nar::Encoder;
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
use crate::error::{Error, Result};
|
use crate::error::{Error, Result};
|
||||||
|
|
||||||
pub fn compute_nar_hash(path: &Path) -> Result<String> {
|
pub fn compute_nar_hash(path: &Path) -> Result<[u8; 32]> {
|
||||||
let mut hasher = Sha256::new();
|
let mut hasher = Sha256::new();
|
||||||
std::io::copy(
|
std::io::copy(
|
||||||
&mut Encoder::new(path).map_err(|err| Error::internal(err.to_string()))?,
|
&mut Encoder::new(path).map_err(|err| Error::internal(err.to_string()))?,
|
||||||
&mut hasher,
|
&mut hasher,
|
||||||
)
|
)
|
||||||
.map_err(|err| Error::internal(err.to_string()))?;
|
.map_err(|err| Error::internal(err.to_string()))?;
|
||||||
Ok(hex::encode(hasher.finalize()))
|
Ok(hasher.finalize().into())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn pack_nar(path: &Path) -> Result<Vec<u8>> {
|
pub fn pack_nar(path: &Path) -> Result<Vec<u8>> {
|
||||||
@@ -27,17 +28,19 @@ pub fn pack_nar(path: &Path) -> Result<Vec<u8>> {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
#[allow(clippy::unwrap_used)]
|
#[allow(clippy::unwrap_used)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
|
|
||||||
use tempfile::TempDir;
|
use tempfile::TempDir;
|
||||||
|
|
||||||
#[test]
|
use super::*;
|
||||||
|
|
||||||
|
#[test_log::test]
|
||||||
fn test_simple_file() {
|
fn test_simple_file() {
|
||||||
let temp = TempDir::new().unwrap();
|
let temp = TempDir::new().unwrap();
|
||||||
let file_path = temp.path().join("test.txt");
|
let file_path = temp.path().join("test.txt");
|
||||||
fs::write(&file_path, "hello").unwrap();
|
fs::write(&file_path, "hello").unwrap();
|
||||||
|
|
||||||
let hash = compute_nar_hash(&file_path).unwrap();
|
let hash = hex::encode(compute_nar_hash(&file_path).unwrap());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
hash,
|
hash,
|
||||||
"0a430879c266f8b57f4092a0f935cf3facd48bbccde5760d4748ca405171e969"
|
"0a430879c266f8b57f4092a0f935cf3facd48bbccde5760d4748ca405171e969"
|
||||||
@@ -46,13 +49,13 @@ mod tests {
|
|||||||
assert_eq!(hash.len(), 64);
|
assert_eq!(hash.len(), 64);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn test_directory() {
|
fn test_directory() {
|
||||||
let temp = TempDir::new().unwrap();
|
let temp = TempDir::new().unwrap();
|
||||||
fs::write(temp.path().join("a.txt"), "aaa").unwrap();
|
fs::write(temp.path().join("a.txt"), "aaa").unwrap();
|
||||||
fs::write(temp.path().join("b.txt"), "bbb").unwrap();
|
fs::write(temp.path().join("b.txt"), "bbb").unwrap();
|
||||||
|
|
||||||
let hash = compute_nar_hash(temp.path()).unwrap();
|
let hash = hex::encode(compute_nar_hash(temp.path()).unwrap());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
hash,
|
hash,
|
||||||
"0036c14209749bc9b9631e2077b108b701c322ab53853cd26f2746268a86fc0f"
|
"0036c14209749bc9b9631e2077b108b701c322ab53853cd26f2746268a86fc0f"
|
||||||
|
|||||||
@@ -1,175 +0,0 @@
|
|||||||
use sha2::{Digest, Sha256};
|
|
||||||
|
|
||||||
const NIX_BASE32_CHARS: &[u8; 32] = b"0123456789abcdfghijklmnpqrsvwxyz";
|
|
||||||
|
|
||||||
pub fn sha256_hex(data: &str) -> String {
|
|
||||||
let mut hasher = Sha256::new();
|
|
||||||
hasher.update(data.as_bytes());
|
|
||||||
hex::encode(hasher.finalize())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn compress_hash(hash: &[u8; 32], new_size: usize) -> Vec<u8> {
|
|
||||||
let mut result = vec![0u8; new_size];
|
|
||||||
for i in 0..32 {
|
|
||||||
result[i % new_size] ^= hash[i];
|
|
||||||
}
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn nix_base32_encode(bytes: &[u8]) -> String {
|
|
||||||
let len = (bytes.len() * 8 - 1) / 5 + 1;
|
|
||||||
let mut result = String::with_capacity(len);
|
|
||||||
|
|
||||||
for n in (0..len).rev() {
|
|
||||||
let b = n * 5;
|
|
||||||
let i = b / 8;
|
|
||||||
let j = b % 8;
|
|
||||||
|
|
||||||
let c = if i >= bytes.len() {
|
|
||||||
0
|
|
||||||
} else {
|
|
||||||
let mut c = (bytes[i] as u16) >> j;
|
|
||||||
if j > 3 && i + 1 < bytes.len() {
|
|
||||||
c |= (bytes[i + 1] as u16) << (8 - j);
|
|
||||||
}
|
|
||||||
c
|
|
||||||
};
|
|
||||||
|
|
||||||
result.push(NIX_BASE32_CHARS[(c & 0x1f) as usize] as char);
|
|
||||||
}
|
|
||||||
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn nix_base32_decode(input: &str) -> Option<Vec<u8>> {
|
|
||||||
let len = input.len() * 5 / 8;
|
|
||||||
let mut bytes = vec![0u8; len];
|
|
||||||
|
|
||||||
for (n, ch) in input.chars().rev().enumerate() {
|
|
||||||
let digit = NIX_BASE32_CHARS.iter().position(|&c| c == ch as u8)? as u16;
|
|
||||||
let b = n * 5;
|
|
||||||
let i = b / 8;
|
|
||||||
let j = b % 8;
|
|
||||||
if i < len {
|
|
||||||
bytes[i] |= (digit << j) as u8;
|
|
||||||
}
|
|
||||||
if j > 3 && i + 1 < len {
|
|
||||||
bytes[i + 1] |= (digit >> (8 - j)) as u8;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn decode_hash_to_hex(hash_str: &str) -> Option<String> {
|
|
||||||
if let Some(rest) = hash_str.strip_prefix("sha256:") {
|
|
||||||
return decode_hash_to_hex(rest);
|
|
||||||
}
|
|
||||||
if let Some(base64_str) = hash_str.strip_prefix("sha256-") {
|
|
||||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
|
||||||
let bytes = STANDARD.decode(base64_str).ok()?;
|
|
||||||
return Some(hex::encode(bytes));
|
|
||||||
}
|
|
||||||
if hash_str.len() == 64 && hash_str.chars().all(|c| c.is_ascii_hexdigit()) {
|
|
||||||
return Some(hash_str.to_string());
|
|
||||||
}
|
|
||||||
if hash_str.len() == 52 {
|
|
||||||
let bytes = nix_base32_decode(hash_str)?;
|
|
||||||
return Some(hex::encode(bytes));
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn make_store_path(store_dir: &str, ty: &str, hash_hex: &str, name: &str) -> String {
|
|
||||||
let s = format!("{}:sha256:{}:{}:{}", ty, hash_hex, store_dir, name);
|
|
||||||
|
|
||||||
let mut hasher = Sha256::new();
|
|
||||||
hasher.update(s.as_bytes());
|
|
||||||
let hash: [u8; 32] = hasher.finalize().into();
|
|
||||||
|
|
||||||
let compressed = compress_hash(&hash, 20);
|
|
||||||
let encoded = nix_base32_encode(&compressed);
|
|
||||||
|
|
||||||
format!("{}/{}-{}", store_dir, encoded, name)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn make_text_store_path(
|
|
||||||
store_dir: &str,
|
|
||||||
hash_hex: &str,
|
|
||||||
name: &str,
|
|
||||||
references: &[String],
|
|
||||||
) -> String {
|
|
||||||
let mut ty = String::from("text");
|
|
||||||
for reference in references {
|
|
||||||
ty.push(':');
|
|
||||||
ty.push_str(reference);
|
|
||||||
}
|
|
||||||
make_store_path(store_dir, &ty, hash_hex, name)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn output_path_name(drv_name: &str, output_name: &str) -> String {
|
|
||||||
if output_name == "out" {
|
|
||||||
drv_name.to_string()
|
|
||||||
} else {
|
|
||||||
format!("{}-{}", drv_name, output_name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_nix_base32_encode() {
|
|
||||||
let bytes = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF];
|
|
||||||
let encoded = nix_base32_encode(&bytes);
|
|
||||||
assert_eq!(encoded.len(), 8);
|
|
||||||
|
|
||||||
let bytes_zero = [0u8; 20];
|
|
||||||
let encoded_zero = nix_base32_encode(&bytes_zero);
|
|
||||||
assert_eq!(encoded_zero.len(), 32);
|
|
||||||
assert!(encoded_zero.chars().all(|c| c == '0'));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_compress_hash() {
|
|
||||||
let hash = [0u8; 32];
|
|
||||||
let compressed = compress_hash(&hash, 20);
|
|
||||||
assert_eq!(compressed.len(), 20);
|
|
||||||
assert!(compressed.iter().all(|&b| b == 0));
|
|
||||||
|
|
||||||
let hash_ones = [0xFF; 32];
|
|
||||||
let compressed_ones = compress_hash(&hash_ones, 20);
|
|
||||||
assert_eq!(compressed_ones.len(), 20);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_sha256_hex() {
|
|
||||||
let data = "hello world";
|
|
||||||
let hash = sha256_hex(data);
|
|
||||||
assert_eq!(hash.len(), 64);
|
|
||||||
assert_eq!(
|
|
||||||
hash,
|
|
||||||
"b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_output_path_name() {
|
|
||||||
assert_eq!(output_path_name("hello", "out"), "hello");
|
|
||||||
assert_eq!(output_path_name("hello", "dev"), "hello-dev");
|
|
||||||
assert_eq!(output_path_name("hello", "doc"), "hello-doc");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_make_store_path() {
|
|
||||||
let path = make_store_path("/nix/store", "output:out", "abc123", "hello");
|
|
||||||
assert!(path.starts_with("/nix/store/"));
|
|
||||||
assert!(path.ends_with("-hello"));
|
|
||||||
|
|
||||||
let hash_parts: Vec<&str> = path.split('/').collect();
|
|
||||||
assert_eq!(hash_parts.len(), 4);
|
|
||||||
let name_part = hash_parts[3];
|
|
||||||
assert!(name_part.contains('-'));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
21
nix-js/src/nix_utils.rs
Normal file
21
nix-js/src/nix_utils.rs
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
use nix_compat::store_path::compress_hash;
|
||||||
|
use sha2::{Digest as _, Sha256};
|
||||||
|
|
||||||
|
pub fn sha256_hex(data: &[u8]) -> String {
|
||||||
|
let mut hasher = Sha256::new();
|
||||||
|
hasher.update(data);
|
||||||
|
hex::encode(hasher.finalize())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn make_store_path(store_dir: &str, ty: &str, hash_hex: &str, name: &str) -> String {
|
||||||
|
let s = format!("{}:sha256:{}:{}:{}", ty, hash_hex, store_dir, name);
|
||||||
|
|
||||||
|
let mut hasher = Sha256::new();
|
||||||
|
hasher.update(s.as_bytes());
|
||||||
|
let hash: [u8; 32] = hasher.finalize().into();
|
||||||
|
|
||||||
|
let compressed = compress_hash::<20>(&hash);
|
||||||
|
let encoded = nix_compat::nixbase32::encode(&compressed);
|
||||||
|
|
||||||
|
format!("{}/{}-{}", store_dir, encoded, name)
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
31
nix-js/src/runtime/corepkgs/derivation.nix
Normal file
31
nix-js/src/runtime/corepkgs/derivation.nix
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
drvAttrs@{
|
||||||
|
outputs ? [ "out" ],
|
||||||
|
...
|
||||||
|
}:
|
||||||
|
|
||||||
|
let
|
||||||
|
|
||||||
|
strict = derivationStrict drvAttrs;
|
||||||
|
|
||||||
|
commonAttrs =
|
||||||
|
drvAttrs
|
||||||
|
// (builtins.listToAttrs outputsList)
|
||||||
|
// {
|
||||||
|
all = map (x: x.value) outputsList;
|
||||||
|
inherit drvAttrs;
|
||||||
|
};
|
||||||
|
|
||||||
|
outputToAttrListElement = outputName: {
|
||||||
|
name = outputName;
|
||||||
|
value = commonAttrs // {
|
||||||
|
outPath = builtins.getAttr outputName strict;
|
||||||
|
drvPath = strict.drvPath;
|
||||||
|
type = "derivation";
|
||||||
|
inherit outputName;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
outputsList = map outputToAttrListElement outputs;
|
||||||
|
|
||||||
|
in
|
||||||
|
(builtins.head outputsList).value
|
||||||
493
nix-js/src/runtime/inspector.rs
Normal file
493
nix-js/src/runtime/inspector.rs
Normal file
@@ -0,0 +1,493 @@
|
|||||||
|
// Copyright 2018-2025 the Deno authors. MIT license.
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
use deno_core::InspectorSessionProxy;
|
||||||
|
use deno_core::JsRuntimeInspector;
|
||||||
|
use deno_core::anyhow::Context;
|
||||||
|
use deno_core::futures::channel::mpsc;
|
||||||
|
use deno_core::futures::channel::mpsc::UnboundedReceiver;
|
||||||
|
use deno_core::futures::channel::mpsc::UnboundedSender;
|
||||||
|
use deno_core::futures::channel::oneshot;
|
||||||
|
use deno_core::futures::prelude::*;
|
||||||
|
use deno_core::futures::stream::StreamExt;
|
||||||
|
use deno_core::serde_json::Value;
|
||||||
|
use deno_core::serde_json::json;
|
||||||
|
use deno_core::unsync::spawn;
|
||||||
|
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 tokio::net::TcpListener;
|
||||||
|
use tokio::sync::broadcast;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
/// Websocket server that is used to proxy connections from
|
||||||
|
/// devtools to the inspector.
|
||||||
|
pub struct InspectorServer {
|
||||||
|
pub host: SocketAddr,
|
||||||
|
register_inspector_tx: UnboundedSender<InspectorInfo>,
|
||||||
|
shutdown_server_tx: Option<broadcast::Sender<()>>,
|
||||||
|
thread_handle: Option<thread::JoinHandle<()>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InspectorServer {
|
||||||
|
pub fn new(host: SocketAddr, name: &'static str) -> Result<Self, anyhow::Error> {
|
||||||
|
let (register_inspector_tx, register_inspector_rx) = mpsc::unbounded::<InspectorInfo>();
|
||||||
|
|
||||||
|
let (shutdown_server_tx, shutdown_server_rx) = broadcast::channel(1);
|
||||||
|
|
||||||
|
let tcp_listener = std::net::TcpListener::bind(host)
|
||||||
|
.with_context(|| format!("Failed to bind inspector server socket at {}", host))?;
|
||||||
|
tcp_listener.set_nonblocking(true)?;
|
||||||
|
|
||||||
|
let thread_handle = thread::spawn(move || {
|
||||||
|
let rt = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.expect("failed to build tokio runtime");
|
||||||
|
let local = tokio::task::LocalSet::new();
|
||||||
|
local.block_on(
|
||||||
|
&rt,
|
||||||
|
server(
|
||||||
|
tcp_listener,
|
||||||
|
register_inspector_rx,
|
||||||
|
shutdown_server_rx,
|
||||||
|
name,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
host,
|
||||||
|
register_inspector_tx,
|
||||||
|
shutdown_server_tx: Some(shutdown_server_tx),
|
||||||
|
thread_handle: Some(thread_handle),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn register_inspector(
|
||||||
|
&self,
|
||||||
|
module_url: String,
|
||||||
|
inspector: Rc<JsRuntimeInspector>,
|
||||||
|
wait_for_session: bool,
|
||||||
|
) {
|
||||||
|
let session_sender = inspector.get_session_sender();
|
||||||
|
let deregister_rx = inspector.add_deregister_handler();
|
||||||
|
|
||||||
|
let info = InspectorInfo::new(
|
||||||
|
self.host,
|
||||||
|
session_sender,
|
||||||
|
deregister_rx,
|
||||||
|
module_url,
|
||||||
|
wait_for_session,
|
||||||
|
);
|
||||||
|
self.register_inspector_tx
|
||||||
|
.unbounded_send(info)
|
||||||
|
.expect("unreachable");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for InspectorServer {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(shutdown_server_tx) = self.shutdown_server_tx.take() {
|
||||||
|
shutdown_server_tx
|
||||||
|
.send(())
|
||||||
|
.expect("unable to send shutdown signal");
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(thread_handle) = self.thread_handle.take() {
|
||||||
|
thread_handle.join().expect("unable to join thread");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_ws_request(
|
||||||
|
req: http::Request<hyper::body::Incoming>,
|
||||||
|
inspector_map_rc: Rc<RefCell<HashMap<Uuid, InspectorInfo>>>,
|
||||||
|
) -> http::Result<http::Response<Box<http_body_util::Full<Bytes>>>> {
|
||||||
|
let (parts, body) = req.into_parts();
|
||||||
|
let req = http::Request::from_parts(parts, ());
|
||||||
|
|
||||||
|
let maybe_uuid = req
|
||||||
|
.uri()
|
||||||
|
.path()
|
||||||
|
.strip_prefix("/ws/")
|
||||||
|
.and_then(|s| Uuid::parse_str(s).ok());
|
||||||
|
|
||||||
|
let Some(uuid) = maybe_uuid else {
|
||||||
|
return http::Response::builder()
|
||||||
|
.status(http::StatusCode::BAD_REQUEST)
|
||||||
|
.body(Box::new(Bytes::from("Malformed inspector UUID").into()));
|
||||||
|
};
|
||||||
|
|
||||||
|
// run in a block to not hold borrow to `inspector_map` for too long
|
||||||
|
let new_session_tx = {
|
||||||
|
let inspector_map = inspector_map_rc.borrow();
|
||||||
|
let maybe_inspector_info = inspector_map.get(&uuid);
|
||||||
|
|
||||||
|
let Some(info) = maybe_inspector_info else {
|
||||||
|
return http::Response::builder()
|
||||||
|
.status(http::StatusCode::NOT_FOUND)
|
||||||
|
.body(Box::new(Bytes::from("Invalid inspector UUID").into()));
|
||||||
|
};
|
||||||
|
info.new_session_tx.clone()
|
||||||
|
};
|
||||||
|
let (parts, _) = req.into_parts();
|
||||||
|
let mut req = http::Request::from_parts(parts, body);
|
||||||
|
|
||||||
|
let Ok((resp, upgrade_fut)) = fastwebsockets::upgrade::upgrade(&mut req) else {
|
||||||
|
return http::Response::builder()
|
||||||
|
.status(http::StatusCode::BAD_REQUEST)
|
||||||
|
.body(Box::new(
|
||||||
|
Bytes::from("Not a valid Websocket Request").into(),
|
||||||
|
));
|
||||||
|
};
|
||||||
|
|
||||||
|
// spawn a task that will wait for websocket connection and then pump messages between
|
||||||
|
// the socket and inspector proxy
|
||||||
|
spawn(async move {
|
||||||
|
let websocket = match upgrade_fut.await {
|
||||||
|
Ok(w) => w,
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!(
|
||||||
|
"Inspector server failed to upgrade to WS connection: {:?}",
|
||||||
|
err
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// The 'outbound' channel carries messages sent to the websocket.
|
||||||
|
let (outbound_tx, outbound_rx) = mpsc::unbounded();
|
||||||
|
// The 'inbound' channel carries messages received from the websocket.
|
||||||
|
let (inbound_tx, inbound_rx) = mpsc::unbounded();
|
||||||
|
|
||||||
|
let inspector_session_proxy = InspectorSessionProxy {
|
||||||
|
channels: InspectorSessionChannels::Regular {
|
||||||
|
tx: outbound_tx,
|
||||||
|
rx: inbound_rx,
|
||||||
|
},
|
||||||
|
kind: InspectorSessionKind::NonBlocking {
|
||||||
|
wait_for_disconnect: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
eprintln!("Debugger session started.");
|
||||||
|
let _ = new_session_tx.unbounded_send(inspector_session_proxy);
|
||||||
|
pump_websocket_messages(websocket, inbound_tx, outbound_rx).await;
|
||||||
|
});
|
||||||
|
|
||||||
|
let (parts, _body) = resp.into_parts();
|
||||||
|
let resp = http::Response::from_parts(parts, Box::new(http_body_util::Full::new(Bytes::new())));
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_json_request(
|
||||||
|
inspector_map: Rc<RefCell<HashMap<Uuid, InspectorInfo>>>,
|
||||||
|
host: Option<String>,
|
||||||
|
) -> http::Result<http::Response<Box<http_body_util::Full<Bytes>>>> {
|
||||||
|
let data = inspector_map
|
||||||
|
.borrow()
|
||||||
|
.values()
|
||||||
|
.map(move |info| info.get_json_metadata(&host))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let body: http_body_util::Full<Bytes> =
|
||||||
|
Bytes::from(serde_json::to_string(&data).expect("unreachable")).into();
|
||||||
|
http::Response::builder()
|
||||||
|
.status(http::StatusCode::OK)
|
||||||
|
.header(http::header::CONTENT_TYPE, "application/json")
|
||||||
|
.body(Box::new(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_json_version_request(
|
||||||
|
version_response: Value,
|
||||||
|
) -> http::Result<http::Response<Box<http_body_util::Full<Bytes>>>> {
|
||||||
|
let body = Box::new(http_body_util::Full::from(
|
||||||
|
serde_json::to_string(&version_response).expect("unreachable"),
|
||||||
|
));
|
||||||
|
|
||||||
|
http::Response::builder()
|
||||||
|
.status(http::StatusCode::OK)
|
||||||
|
.header(http::header::CONTENT_TYPE, "application/json")
|
||||||
|
.body(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn server(
|
||||||
|
listener: std::net::TcpListener,
|
||||||
|
register_inspector_rx: UnboundedReceiver<InspectorInfo>,
|
||||||
|
shutdown_server_rx: broadcast::Receiver<()>,
|
||||||
|
name: &str,
|
||||||
|
) {
|
||||||
|
let inspector_map_ = Rc::new(RefCell::new(HashMap::<Uuid, InspectorInfo>::new()));
|
||||||
|
|
||||||
|
let inspector_map = Rc::clone(&inspector_map_);
|
||||||
|
let register_inspector_handler =
|
||||||
|
listen_for_new_inspectors(register_inspector_rx, inspector_map.clone()).boxed_local();
|
||||||
|
|
||||||
|
let inspector_map = Rc::clone(&inspector_map_);
|
||||||
|
let deregister_inspector_handler = future::poll_fn(|cx| {
|
||||||
|
inspector_map
|
||||||
|
.borrow_mut()
|
||||||
|
.retain(|_, info| info.deregister_rx.poll_unpin(cx) == Poll::Pending);
|
||||||
|
Poll::<Never>::Pending
|
||||||
|
})
|
||||||
|
.boxed_local();
|
||||||
|
|
||||||
|
let json_version_response = json!({
|
||||||
|
"Browser": name,
|
||||||
|
"Protocol-Version": "1.3",
|
||||||
|
"V8-Version": deno_core::v8::VERSION_STRING,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create the server manually so it can use the Local Executor
|
||||||
|
let listener = match TcpListener::from_std(listener) {
|
||||||
|
Ok(l) => l,
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Cannot create async listener from std listener: {:?}", err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let server_handler = async move {
|
||||||
|
loop {
|
||||||
|
let mut rx = shutdown_server_rx.resubscribe();
|
||||||
|
let mut shutdown_rx = pin!(rx.recv());
|
||||||
|
let mut accept = pin!(listener.accept());
|
||||||
|
|
||||||
|
let stream = tokio::select! {
|
||||||
|
accept_result =
|
||||||
|
&mut accept => {
|
||||||
|
match accept_result {
|
||||||
|
Ok((s, _)) => s,
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Failed to accept inspector connection: {:?}", err);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
_ = &mut shutdown_rx => {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let io = TokioIo::new(stream);
|
||||||
|
|
||||||
|
let inspector_map = Rc::clone(&inspector_map_);
|
||||||
|
let json_version_response = json_version_response.clone();
|
||||||
|
let mut shutdown_server_rx = shutdown_server_rx.resubscribe();
|
||||||
|
|
||||||
|
let service =
|
||||||
|
hyper::service::service_fn(move |req: http::Request<hyper::body::Incoming>| {
|
||||||
|
future::ready({
|
||||||
|
// If the host header can make a valid URL, use it
|
||||||
|
let host = req
|
||||||
|
.headers()
|
||||||
|
.get("host")
|
||||||
|
.and_then(|host| host.to_str().ok())
|
||||||
|
.and_then(|host| Url::parse(&format!("http://{host}")).ok())
|
||||||
|
.and_then(|url| match (url.host(), url.port()) {
|
||||||
|
(Some(host), Some(port)) => Some(format!("{host}:{port}")),
|
||||||
|
(Some(host), None) => Some(format!("{host}")),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
match (req.method(), req.uri().path()) {
|
||||||
|
(&http::Method::GET, path) if path.starts_with("/ws/") => {
|
||||||
|
handle_ws_request(req, Rc::clone(&inspector_map))
|
||||||
|
}
|
||||||
|
(&http::Method::GET, "/json/version") => {
|
||||||
|
handle_json_version_request(json_version_response.clone())
|
||||||
|
}
|
||||||
|
(&http::Method::GET, "/json") => {
|
||||||
|
handle_json_request(Rc::clone(&inspector_map), host)
|
||||||
|
}
|
||||||
|
(&http::Method::GET, "/json/list") => {
|
||||||
|
handle_json_request(Rc::clone(&inspector_map), host)
|
||||||
|
}
|
||||||
|
_ => http::Response::builder()
|
||||||
|
.status(http::StatusCode::NOT_FOUND)
|
||||||
|
.body(Box::new(http_body_util::Full::new(Bytes::from(
|
||||||
|
"Not Found",
|
||||||
|
)))),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
deno_core::unsync::spawn(async move {
|
||||||
|
let server = hyper::server::conn::http1::Builder::new();
|
||||||
|
|
||||||
|
let mut conn = pin!(server.serve_connection(io, service).with_upgrades());
|
||||||
|
let mut shutdown_rx = pin!(shutdown_server_rx.recv());
|
||||||
|
|
||||||
|
tokio::select! {
|
||||||
|
result = conn.as_mut() => {
|
||||||
|
if let Err(err) = result {
|
||||||
|
eprintln!("Failed to serve connection: {:?}", err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
_ = &mut shutdown_rx => {
|
||||||
|
conn.as_mut().graceful_shutdown();
|
||||||
|
let _ = conn.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.boxed_local();
|
||||||
|
|
||||||
|
tokio::select! {
|
||||||
|
_ = register_inspector_handler => {},
|
||||||
|
_ = deregister_inspector_handler => unreachable!(),
|
||||||
|
_ = server_handler => {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn listen_for_new_inspectors(
|
||||||
|
mut register_inspector_rx: UnboundedReceiver<InspectorInfo>,
|
||||||
|
inspector_map: Rc<RefCell<HashMap<Uuid, InspectorInfo>>>,
|
||||||
|
) {
|
||||||
|
while let Some(info) = register_inspector_rx.next().await {
|
||||||
|
eprintln!(
|
||||||
|
"Debugger listening on {}",
|
||||||
|
info.get_websocket_debugger_url(&info.host.to_string())
|
||||||
|
);
|
||||||
|
eprintln!("Visit chrome://inspect to connect to the debugger.");
|
||||||
|
if info.wait_for_session {
|
||||||
|
eprintln!("nix-js is waiting for debugger to connect.");
|
||||||
|
}
|
||||||
|
if inspector_map.borrow_mut().insert(info.uuid, info).is_some() {
|
||||||
|
panic!("Inspector UUID already in map");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pump future takes care of forwarding messages between the websocket
|
||||||
|
/// and channels. It resolves when either side disconnects, ignoring any
|
||||||
|
/// errors.
|
||||||
|
///
|
||||||
|
/// The future proxies messages sent and received on a WebSocket
|
||||||
|
/// to a UnboundedSender/UnboundedReceiver pair. We need these "unbounded" channel ends to sidestep
|
||||||
|
/// Tokio's task budget, which causes issues when JsRuntimeInspector::poll_sessions()
|
||||||
|
/// needs to block the thread because JavaScript execution is paused.
|
||||||
|
///
|
||||||
|
/// This works because UnboundedSender/UnboundedReceiver are implemented in the
|
||||||
|
/// 'futures' crate, therefore they can't participate in Tokio's cooperative
|
||||||
|
/// task yielding.
|
||||||
|
async fn pump_websocket_messages(
|
||||||
|
mut websocket: WebSocket<TokioIo<hyper::upgrade::Upgraded>>,
|
||||||
|
inbound_tx: UnboundedSender<String>,
|
||||||
|
mut outbound_rx: UnboundedReceiver<InspectorMsg>,
|
||||||
|
) {
|
||||||
|
'pump: loop {
|
||||||
|
tokio::select! {
|
||||||
|
Some(msg) = outbound_rx.next() => {
|
||||||
|
let msg = Frame::text(msg.content.into_bytes().into());
|
||||||
|
let _ = websocket.write_frame(msg).await;
|
||||||
|
}
|
||||||
|
Ok(msg) = websocket.read_frame() => {
|
||||||
|
match msg.opcode {
|
||||||
|
OpCode::Text => {
|
||||||
|
if let Ok(s) = String::from_utf8(msg.payload.to_vec()) {
|
||||||
|
let _ = inbound_tx.unbounded_send(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
OpCode::Close => {
|
||||||
|
// Users don't care if there was an error coming from debugger,
|
||||||
|
// just about the fact that debugger did disconnect.
|
||||||
|
eprintln!("Debugger session ended");
|
||||||
|
break 'pump;
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
// Ignore other messages.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else => {
|
||||||
|
break 'pump;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inspector information that is sent from the isolate thread to the server
|
||||||
|
/// thread when a new inspector is created.
|
||||||
|
pub struct InspectorInfo {
|
||||||
|
pub host: SocketAddr,
|
||||||
|
pub uuid: Uuid,
|
||||||
|
pub thread_name: Option<String>,
|
||||||
|
pub new_session_tx: UnboundedSender<InspectorSessionProxy>,
|
||||||
|
pub deregister_rx: oneshot::Receiver<()>,
|
||||||
|
pub url: String,
|
||||||
|
pub wait_for_session: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InspectorInfo {
|
||||||
|
pub fn new(
|
||||||
|
host: SocketAddr,
|
||||||
|
new_session_tx: mpsc::UnboundedSender<InspectorSessionProxy>,
|
||||||
|
deregister_rx: oneshot::Receiver<()>,
|
||||||
|
url: String,
|
||||||
|
wait_for_session: bool,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
host,
|
||||||
|
uuid: Uuid::new_v4(),
|
||||||
|
thread_name: thread::current().name().map(|n| n.to_owned()),
|
||||||
|
new_session_tx,
|
||||||
|
deregister_rx,
|
||||||
|
url,
|
||||||
|
wait_for_session,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_json_metadata(&self, host: &Option<String>) -> Value {
|
||||||
|
let host_listen = format!("{}", self.host);
|
||||||
|
let host = host.as_ref().unwrap_or(&host_listen);
|
||||||
|
json!({
|
||||||
|
"description": "nix-js",
|
||||||
|
"devtoolsFrontendUrl": self.get_frontend_url(host),
|
||||||
|
"faviconUrl": "https://deno.land/favicon.ico",
|
||||||
|
"id": self.uuid.to_string(),
|
||||||
|
"title": self.get_title(),
|
||||||
|
"type": "node",
|
||||||
|
"url": self.url.to_string(),
|
||||||
|
"webSocketDebuggerUrl": self.get_websocket_debugger_url(host),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_websocket_debugger_url(&self, host: &str) -> String {
|
||||||
|
format!("ws://{}/ws/{}", host, &self.uuid)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_frontend_url(&self, host: &str) -> String {
|
||||||
|
format!(
|
||||||
|
"devtools://devtools/bundled/js_app.html?ws={}/ws/{}&experiments=true&v8only=true",
|
||||||
|
host, &self.uuid
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_title(&self) -> String {
|
||||||
|
format!(
|
||||||
|
"nix-js{} [pid: {}]",
|
||||||
|
self.thread_name
|
||||||
|
.as_ref()
|
||||||
|
.map(|n| format!(" - {n}"))
|
||||||
|
.unwrap_or_default(),
|
||||||
|
process::id(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
1896
nix-js/src/runtime/ops.rs
Normal file
1896
nix-js/src/runtime/ops.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,14 +1,14 @@
|
|||||||
#![allow(dead_code)]
|
use crate::error::Result;
|
||||||
|
|
||||||
mod config;
|
mod config;
|
||||||
|
mod daemon;
|
||||||
mod error;
|
mod error;
|
||||||
mod validation;
|
mod validation;
|
||||||
|
|
||||||
pub use config::{StoreConfig, StoreMode};
|
pub use config::StoreConfig;
|
||||||
|
pub use daemon::DaemonStore;
|
||||||
pub use validation::validate_store_path;
|
pub use validation::validate_store_path;
|
||||||
|
|
||||||
use crate::error::Result;
|
|
||||||
|
|
||||||
pub trait Store: Send + Sync {
|
pub trait Store: Send + Sync {
|
||||||
fn get_store_dir(&self) -> &str;
|
fn get_store_dir(&self) -> &str;
|
||||||
|
|
||||||
@@ -37,75 +37,4 @@ pub trait Store: Send + Sync {
|
|||||||
content: &str,
|
content: &str,
|
||||||
references: Vec<String>,
|
references: Vec<String>,
|
||||||
) -> Result<String>;
|
) -> Result<String>;
|
||||||
|
|
||||||
fn make_fixed_output_path(
|
|
||||||
&self,
|
|
||||||
hash_algo: &str,
|
|
||||||
hash: &str,
|
|
||||||
hash_mode: &str,
|
|
||||||
name: &str,
|
|
||||||
) -> Result<String>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum StoreBackend {
|
|
||||||
Simulated(SimulatedStore),
|
|
||||||
#[cfg(feature = "daemon")]
|
|
||||||
Daemon(Box<DaemonStore>),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StoreBackend {
|
|
||||||
pub fn new(config: StoreConfig) -> Result<Self> {
|
|
||||||
match config.mode {
|
|
||||||
#[cfg(feature = "daemon")]
|
|
||||||
StoreMode::Daemon => {
|
|
||||||
let daemon = Box::new(DaemonStore::connect(&config.daemon_socket)?);
|
|
||||||
Ok(StoreBackend::Daemon(daemon))
|
|
||||||
}
|
|
||||||
#[cfg(not(feature = "daemon"))]
|
|
||||||
StoreMode::Daemon => {
|
|
||||||
tracing::warn!(
|
|
||||||
"Daemon mode not available (nix-js not compiled with 'daemon' feature), falling back to simulated store"
|
|
||||||
);
|
|
||||||
let simulated = SimulatedStore::new()?;
|
|
||||||
Ok(StoreBackend::Simulated(simulated))
|
|
||||||
}
|
|
||||||
StoreMode::Simulated => {
|
|
||||||
let simulated = SimulatedStore::new()?;
|
|
||||||
Ok(StoreBackend::Simulated(simulated))
|
|
||||||
}
|
|
||||||
#[cfg(feature = "daemon")]
|
|
||||||
StoreMode::Auto => match DaemonStore::connect(&config.daemon_socket) {
|
|
||||||
Ok(daemon) => {
|
|
||||||
tracing::debug!("Using nix-daemon at {}", config.daemon_socket.display());
|
|
||||||
Ok(StoreBackend::Daemon(Box::new(daemon)))
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
tracing::warn!("Daemon unavailable ({}), using simulated store", e);
|
|
||||||
let simulated = SimulatedStore::new()?;
|
|
||||||
Ok(StoreBackend::Simulated(simulated))
|
|
||||||
}
|
|
||||||
},
|
|
||||||
#[cfg(not(feature = "daemon"))]
|
|
||||||
StoreMode::Auto => {
|
|
||||||
let simulated = SimulatedStore::new()?;
|
|
||||||
Ok(StoreBackend::Simulated(simulated))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn as_store(&self) -> &dyn Store {
|
|
||||||
match self {
|
|
||||||
StoreBackend::Simulated(s) => s,
|
|
||||||
#[cfg(feature = "daemon")]
|
|
||||||
StoreBackend::Daemon(d) => d.as_ref(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
mod simulated;
|
|
||||||
pub use simulated::SimulatedStore;
|
|
||||||
|
|
||||||
#[cfg(feature = "daemon")]
|
|
||||||
mod daemon;
|
|
||||||
#[cfg(feature = "daemon")]
|
|
||||||
pub use daemon::DaemonStore;
|
|
||||||
|
|||||||
@@ -1,42 +1,17 @@
|
|||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum StoreMode {
|
|
||||||
Daemon,
|
|
||||||
Simulated,
|
|
||||||
Auto,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct StoreConfig {
|
pub struct StoreConfig {
|
||||||
pub mode: StoreMode,
|
|
||||||
pub daemon_socket: PathBuf,
|
pub daemon_socket: PathBuf,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl StoreConfig {
|
impl StoreConfig {
|
||||||
pub fn from_env() -> Self {
|
pub fn from_env() -> Self {
|
||||||
let mode = match std::env::var("NIX_JS_STORE_MODE")
|
|
||||||
.as_deref()
|
|
||||||
.map(|s| s.to_lowercase())
|
|
||||||
.as_deref()
|
|
||||||
{
|
|
||||||
Ok("daemon") => StoreMode::Daemon,
|
|
||||||
Ok("simulated") => StoreMode::Simulated,
|
|
||||||
Ok("auto") | Err(_) => StoreMode::Auto,
|
|
||||||
Ok(other) => {
|
|
||||||
tracing::warn!("Invalid NIX_JS_STORE_MODE '{}', using 'auto'", other);
|
|
||||||
StoreMode::Auto
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let daemon_socket = std::env::var("NIX_DAEMON_SOCKET")
|
let daemon_socket = std::env::var("NIX_DAEMON_SOCKET")
|
||||||
.map(PathBuf::from)
|
.map(PathBuf::from)
|
||||||
.unwrap_or_else(|_| PathBuf::from("/nix/var/nix/daemon-socket/socket"));
|
.unwrap_or_else(|_| PathBuf::from("/nix/var/nix/daemon-socket/socket"));
|
||||||
|
|
||||||
Self {
|
Self { daemon_socket }
|
||||||
mode,
|
|
||||||
daemon_socket,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
#![allow(dead_code)]
|
|
||||||
|
|
||||||
use std::io::{Error as IoError, ErrorKind as IoErrorKind, Result as IoResult};
|
use std::io::{Error as IoError, ErrorKind as IoErrorKind, Result as IoResult};
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
@@ -9,13 +7,14 @@ use nix_compat::store_path::StorePath;
|
|||||||
use nix_compat::wire::ProtocolVersion;
|
use nix_compat::wire::ProtocolVersion;
|
||||||
use nix_compat::wire::de::{NixRead, NixReader};
|
use nix_compat::wire::de::{NixRead, NixReader};
|
||||||
use nix_compat::wire::ser::{NixSerialize, NixWrite, NixWriter, NixWriterBuilder};
|
use nix_compat::wire::ser::{NixSerialize, NixWrite, NixWriter, NixWriterBuilder};
|
||||||
|
use num_enum::{IntoPrimitive, TryFromPrimitive};
|
||||||
|
use thiserror::Error;
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf, split};
|
use tokio::io::{AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf, split};
|
||||||
use tokio::net::UnixStream;
|
use tokio::net::UnixStream;
|
||||||
use tokio::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
|
|
||||||
use crate::error::{Error, Result};
|
|
||||||
|
|
||||||
use super::Store;
|
use super::Store;
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
|
||||||
pub struct DaemonStore {
|
pub struct DaemonStore {
|
||||||
runtime: tokio::runtime::Runtime,
|
runtime: tokio::runtime::Runtime,
|
||||||
@@ -88,11 +87,12 @@ impl Store for DaemonStore {
|
|||||||
recursive: bool,
|
recursive: bool,
|
||||||
references: Vec<String>,
|
references: Vec<String>,
|
||||||
) -> Result<String> {
|
) -> Result<String> {
|
||||||
|
use std::fs;
|
||||||
|
|
||||||
use nix_compat::nix_daemon::types::AddToStoreNarRequest;
|
use nix_compat::nix_daemon::types::AddToStoreNarRequest;
|
||||||
use nix_compat::nixhash::{CAHash, NixHash};
|
use nix_compat::nixhash::{CAHash, NixHash};
|
||||||
use nix_compat::store_path::{StorePath, build_ca_path};
|
use nix_compat::store_path::{StorePath, build_ca_path};
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
use std::fs;
|
|
||||||
use tempfile::NamedTempFile;
|
use tempfile::NamedTempFile;
|
||||||
|
|
||||||
let temp_file = NamedTempFile::new()
|
let temp_file = NamedTempFile::new()
|
||||||
@@ -238,11 +238,12 @@ impl Store for DaemonStore {
|
|||||||
content: &str,
|
content: &str,
|
||||||
references: Vec<String>,
|
references: Vec<String>,
|
||||||
) -> Result<String> {
|
) -> Result<String> {
|
||||||
|
use std::fs;
|
||||||
|
|
||||||
use nix_compat::nix_daemon::types::AddToStoreNarRequest;
|
use nix_compat::nix_daemon::types::AddToStoreNarRequest;
|
||||||
use nix_compat::nixhash::CAHash;
|
use nix_compat::nixhash::CAHash;
|
||||||
use nix_compat::store_path::{StorePath, build_text_path};
|
use nix_compat::store_path::{StorePath, build_text_path};
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
use std::fs;
|
|
||||||
use tempfile::NamedTempFile;
|
use tempfile::NamedTempFile;
|
||||||
|
|
||||||
let temp_file = NamedTempFile::new()
|
let temp_file = NamedTempFile::new()
|
||||||
@@ -305,51 +306,6 @@ impl Store for DaemonStore {
|
|||||||
|
|
||||||
Ok(store_path_str)
|
Ok(store_path_str)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn make_fixed_output_path(
|
|
||||||
&self,
|
|
||||||
hash_algo: &str,
|
|
||||||
hash: &str,
|
|
||||||
hash_mode: &str,
|
|
||||||
name: &str,
|
|
||||||
) -> Result<String> {
|
|
||||||
use nix_compat::nixhash::{CAHash, NixHash};
|
|
||||||
use nix_compat::store_path::build_ca_path;
|
|
||||||
|
|
||||||
let nix_hash = match hash_algo {
|
|
||||||
"sha256" => {
|
|
||||||
let hash_bytes = hex::decode(hash)
|
|
||||||
.map_err(|e| Error::internal(format!("Invalid hash hex: {}", e)))?;
|
|
||||||
if hash_bytes.len() != 32 {
|
|
||||||
return Err(Error::internal(format!(
|
|
||||||
"Invalid sha256 hash length: expected 32, got {}",
|
|
||||||
hash_bytes.len()
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
let mut arr = [0u8; 32];
|
|
||||||
arr.copy_from_slice(&hash_bytes);
|
|
||||||
NixHash::Sha256(arr)
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
return Err(Error::internal(format!(
|
|
||||||
"Unsupported hash algorithm: {}",
|
|
||||||
hash_algo
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let ca_hash = if hash_mode == "r" {
|
|
||||||
CAHash::Nar(nix_hash)
|
|
||||||
} else {
|
|
||||||
CAHash::Flat(nix_hash)
|
|
||||||
};
|
|
||||||
|
|
||||||
let store_path: nix_compat::store_path::StorePath<String> =
|
|
||||||
build_ca_path(name, &ca_hash, Vec::<String>::new(), false)
|
|
||||||
.map_err(|e| Error::internal(format!("Failed to build store path: {}", e)))?;
|
|
||||||
|
|
||||||
Ok(store_path.to_absolute_path())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::from_parts(1, 37);
|
const PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::from_parts(1, 37);
|
||||||
@@ -472,6 +428,7 @@ pub struct NixDaemonClient {
|
|||||||
protocol_version: ProtocolVersion,
|
protocol_version: ProtocolVersion,
|
||||||
reader: NixReader<ReadHalf<UnixStream>>,
|
reader: NixReader<ReadHalf<UnixStream>>,
|
||||||
writer: NixWriter<WriteHalf<UnixStream>>,
|
writer: NixWriter<WriteHalf<UnixStream>>,
|
||||||
|
_marker: std::marker::PhantomData<std::cell::Cell<()>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NixDaemonClient {
|
impl NixDaemonClient {
|
||||||
@@ -503,26 +460,10 @@ impl NixDaemonClient {
|
|||||||
protocol_version,
|
protocol_version,
|
||||||
reader,
|
reader,
|
||||||
writer,
|
writer,
|
||||||
|
_marker: Default::default(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Execute an operation that returns a typed result
|
|
||||||
///
|
|
||||||
/// This is the main method for implementing protocol operations:
|
|
||||||
/// 1. Send operation code
|
|
||||||
/// 2. Send operation parameters
|
|
||||||
/// 3. Receive response or error
|
|
||||||
async fn execute<T>(&mut self, operation: Operation) -> IoResult<T>
|
|
||||||
where
|
|
||||||
T: nix_compat::wire::de::NixDeserialize,
|
|
||||||
{
|
|
||||||
// Send operation
|
|
||||||
self.writer.write_value(&operation).await?;
|
|
||||||
self.writer.flush().await?;
|
|
||||||
|
|
||||||
self.read_response().await
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Execute an operation with a single parameter
|
/// Execute an operation with a single parameter
|
||||||
async fn execute_with<P, T>(&mut self, operation: Operation, param: &P) -> IoResult<T>
|
async fn execute_with<P, T>(&mut self, operation: Operation, param: &P) -> IoResult<T>
|
||||||
where
|
where
|
||||||
@@ -542,7 +483,7 @@ impl NixDaemonClient {
|
|||||||
///
|
///
|
||||||
/// The daemon sends either:
|
/// The daemon sends either:
|
||||||
/// - STDERR_LAST followed by the result
|
/// - STDERR_LAST followed by the result
|
||||||
/// - STDERR_ERROR followed by an error message
|
/// - STDERR_ERROR followed by a structured error
|
||||||
async fn read_response<T>(&mut self) -> IoResult<T>
|
async fn read_response<T>(&mut self) -> IoResult<T>
|
||||||
where
|
where
|
||||||
T: nix_compat::wire::de::NixDeserialize,
|
T: nix_compat::wire::de::NixDeserialize,
|
||||||
@@ -551,23 +492,47 @@ impl NixDaemonClient {
|
|||||||
let msg = self.reader.read_number().await?;
|
let msg = self.reader.read_number().await?;
|
||||||
|
|
||||||
if msg == STDERR_LAST {
|
if msg == STDERR_LAST {
|
||||||
// Success, read the actual response
|
|
||||||
let result: T = self.reader.read_value().await?;
|
let result: T = self.reader.read_value().await?;
|
||||||
return Ok(result);
|
return Ok(result);
|
||||||
} else if msg == STDERR_ERROR {
|
} else if msg == STDERR_ERROR {
|
||||||
// IoError, read error message
|
let error_msg = self.read_daemon_error().await?;
|
||||||
// The error is sent as a NixIoError struct, but we just read the message
|
|
||||||
let error_msg: String = self.reader.read_value().await?;
|
|
||||||
return Err(IoError::other(error_msg));
|
return Err(IoError::other(error_msg));
|
||||||
} else {
|
} else {
|
||||||
// Other STDERR_* codes (logging, etc.) - for now, we ignore them
|
|
||||||
// Read and discard the associated data
|
|
||||||
let _data: String = self.reader.read_value().await?;
|
let _data: String = self.reader.read_value().await?;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn read_daemon_error(&mut self) -> IoResult<NixDaemonError> {
|
||||||
|
let type_marker: String = self.reader.read_value().await?;
|
||||||
|
assert_eq!(type_marker, "Error");
|
||||||
|
|
||||||
|
let level = NixDaemonErrorLevel::try_from_primitive(
|
||||||
|
self.reader
|
||||||
|
.read_number()
|
||||||
|
.await?
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| IoError::other("invalid nix-daemon error level"))?,
|
||||||
|
)
|
||||||
|
.map_err(|_| IoError::other("invalid nix-daemon error level"))?;
|
||||||
|
// removed
|
||||||
|
let _name: String = self.reader.read_value().await?;
|
||||||
|
let msg: String = self.reader.read_value().await?;
|
||||||
|
let have_pos: u64 = self.reader.read_number().await?;
|
||||||
|
assert_eq!(have_pos, 0);
|
||||||
|
|
||||||
|
let nr_traces: u64 = self.reader.read_number().await?;
|
||||||
|
let mut traces = Vec::new();
|
||||||
|
for _ in 0..nr_traces {
|
||||||
|
let _trace_pos: u64 = self.reader.read_number().await?;
|
||||||
|
let trace_hint: String = self.reader.read_value().await?;
|
||||||
|
traces.push(trace_hint);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(NixDaemonError { level, msg, traces })
|
||||||
|
}
|
||||||
|
|
||||||
/// Check if a path is valid in the store
|
/// Check if a path is valid in the store
|
||||||
pub async fn is_valid_path(&mut self, path: &str) -> IoResult<bool> {
|
pub async fn is_valid_path(&mut self, path: &str) -> IoResult<bool> {
|
||||||
let store_path = StorePath::<String>::from_absolute_path(path.as_bytes())
|
let store_path = StorePath::<String>::from_absolute_path(path.as_bytes())
|
||||||
@@ -577,23 +542,20 @@ impl NixDaemonClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Query information about a store path
|
/// Query information about a store path
|
||||||
|
#[allow(dead_code)]
|
||||||
pub async fn query_path_info(&mut self, path: &str) -> IoResult<Option<UnkeyedValidPathInfo>> {
|
pub async fn query_path_info(&mut self, path: &str) -> IoResult<Option<UnkeyedValidPathInfo>> {
|
||||||
let store_path = StorePath::<String>::from_absolute_path(path.as_bytes())
|
let store_path = StorePath::<String>::from_absolute_path(path.as_bytes())
|
||||||
.map_err(|e| IoError::new(IoErrorKind::InvalidInput, e.to_string()))?;
|
.map_err(|e| IoError::new(IoErrorKind::InvalidInput, e.to_string()))?;
|
||||||
|
|
||||||
// QueryPathInfo returns Option<UnkeyedValidPathInfo> which is serialized
|
|
||||||
// as a bool followed by the value if true
|
|
||||||
self.writer.write_value(&Operation::QueryPathInfo).await?;
|
self.writer.write_value(&Operation::QueryPathInfo).await?;
|
||||||
self.writer.write_value(&store_path).await?;
|
self.writer.write_value(&store_path).await?;
|
||||||
self.writer.flush().await?;
|
self.writer.flush().await?;
|
||||||
|
|
||||||
// Read response - it's serialized as bool + optional value
|
|
||||||
loop {
|
loop {
|
||||||
let msg = self.reader.read_number().await?;
|
let msg = self.reader.read_number().await?;
|
||||||
if msg == STDERR_LAST {
|
if msg == STDERR_LAST {
|
||||||
let has_value: bool = self.reader.read_value().await?;
|
let has_value: bool = self.reader.read_value().await?;
|
||||||
if has_value {
|
if has_value {
|
||||||
// Manually deserialize UnkeyedValidPathInfo
|
|
||||||
use nix_compat::narinfo::Signature;
|
use nix_compat::narinfo::Signature;
|
||||||
use nix_compat::nixhash::CAHash;
|
use nix_compat::nixhash::CAHash;
|
||||||
|
|
||||||
@@ -621,7 +583,7 @@ impl NixDaemonClient {
|
|||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
} else if msg == STDERR_ERROR {
|
} else if msg == STDERR_ERROR {
|
||||||
let error_msg: String = self.reader.read_value().await?;
|
let error_msg = self.read_daemon_error().await?;
|
||||||
return Err(IoError::other(error_msg));
|
return Err(IoError::other(error_msg));
|
||||||
} else {
|
} else {
|
||||||
let _data: String = self.reader.read_value().await?;
|
let _data: String = self.reader.read_value().await?;
|
||||||
@@ -635,18 +597,16 @@ impl NixDaemonClient {
|
|||||||
let store_path = StorePath::<String>::from_absolute_path(path.as_bytes())
|
let store_path = StorePath::<String>::from_absolute_path(path.as_bytes())
|
||||||
.map_err(|e| IoError::new(IoErrorKind::InvalidInput, e.to_string()))?;
|
.map_err(|e| IoError::new(IoErrorKind::InvalidInput, e.to_string()))?;
|
||||||
|
|
||||||
// EnsurePath returns void (no value)
|
|
||||||
self.writer.write_value(&Operation::EnsurePath).await?;
|
self.writer.write_value(&Operation::EnsurePath).await?;
|
||||||
self.writer.write_value(&store_path).await?;
|
self.writer.write_value(&store_path).await?;
|
||||||
self.writer.flush().await?;
|
self.writer.flush().await?;
|
||||||
|
|
||||||
// Read response - expect STDERR_LAST with no value
|
|
||||||
loop {
|
loop {
|
||||||
let msg = self.reader.read_number().await?;
|
let msg = self.reader.read_number().await?;
|
||||||
if msg == STDERR_LAST {
|
if msg == STDERR_LAST {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
} else if msg == STDERR_ERROR {
|
} else if msg == STDERR_ERROR {
|
||||||
let error_msg: String = self.reader.read_value().await?;
|
let error_msg = self.read_daemon_error().await?;
|
||||||
return Err(IoError::other(error_msg));
|
return Err(IoError::other(error_msg));
|
||||||
} else {
|
} else {
|
||||||
let _data: String = self.reader.read_value().await?;
|
let _data: String = self.reader.read_value().await?;
|
||||||
@@ -656,6 +616,7 @@ impl NixDaemonClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Query which paths are valid
|
/// Query which paths are valid
|
||||||
|
#[allow(dead_code)]
|
||||||
pub async fn query_valid_paths(&mut self, paths: Vec<String>) -> IoResult<Vec<String>> {
|
pub async fn query_valid_paths(&mut self, paths: Vec<String>) -> IoResult<Vec<String>> {
|
||||||
let store_paths: IoResult<Vec<StorePath<String>>> = paths
|
let store_paths: IoResult<Vec<StorePath<String>>> = paths
|
||||||
.iter()
|
.iter()
|
||||||
@@ -729,7 +690,7 @@ impl NixDaemonClient {
|
|||||||
if msg == STDERR_LAST {
|
if msg == STDERR_LAST {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
} else if msg == STDERR_ERROR {
|
} else if msg == STDERR_ERROR {
|
||||||
let error_msg: String = self.reader.read_value().await?;
|
let error_msg = self.read_daemon_error().await?;
|
||||||
return Err(IoError::other(error_msg));
|
return Err(IoError::other(error_msg));
|
||||||
} else {
|
} else {
|
||||||
let _data: String = self.reader.read_value().await?;
|
let _data: String = self.reader.read_value().await?;
|
||||||
@@ -760,6 +721,7 @@ impl NixDaemonConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Query information about a store path
|
/// Query information about a store path
|
||||||
|
#[allow(dead_code)]
|
||||||
pub async fn query_path_info(&self, path: &str) -> IoResult<Option<UnkeyedValidPathInfo>> {
|
pub async fn query_path_info(&self, path: &str) -> IoResult<Option<UnkeyedValidPathInfo>> {
|
||||||
let mut client = self.client.lock().await;
|
let mut client = self.client.lock().await;
|
||||||
client.query_path_info(path).await
|
client.query_path_info(path).await
|
||||||
@@ -772,6 +734,7 @@ impl NixDaemonConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Query which paths are valid
|
/// Query which paths are valid
|
||||||
|
#[allow(dead_code)]
|
||||||
pub async fn query_valid_paths(&self, paths: Vec<String>) -> IoResult<Vec<String>> {
|
pub async fn query_valid_paths(&self, paths: Vec<String>) -> IoResult<Vec<String>> {
|
||||||
let mut client = self.client.lock().await;
|
let mut client = self.client.lock().await;
|
||||||
client.query_valid_paths(paths).await
|
client.query_valid_paths(paths).await
|
||||||
@@ -787,3 +750,24 @@ impl NixDaemonConnection {
|
|||||||
client.add_to_store_nar(request, nar_data).await
|
client.add_to_store_nar(request, nar_data).await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, IntoPrimitive, TryFromPrimitive)]
|
||||||
|
#[repr(u8)]
|
||||||
|
pub enum NixDaemonErrorLevel {
|
||||||
|
Error = 0,
|
||||||
|
Warn,
|
||||||
|
Notice,
|
||||||
|
Info,
|
||||||
|
Talkative,
|
||||||
|
Chatty,
|
||||||
|
Debug,
|
||||||
|
Vomit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
#[error("{msg}")]
|
||||||
|
pub struct NixDaemonError {
|
||||||
|
level: NixDaemonErrorLevel,
|
||||||
|
msg: String,
|
||||||
|
traces: Vec<String>,
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
#![allow(dead_code)]
|
||||||
|
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
|
|||||||
@@ -1,121 +0,0 @@
|
|||||||
use super::Store;
|
|
||||||
use crate::error::{Error, Result};
|
|
||||||
use crate::fetcher::cache::FetcherCache;
|
|
||||||
use std::fs;
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
pub struct SimulatedStore {
|
|
||||||
cache: FetcherCache,
|
|
||||||
store_dir: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SimulatedStore {
|
|
||||||
pub fn new() -> Result<Self> {
|
|
||||||
let cache = FetcherCache::new()
|
|
||||||
.map_err(|e| Error::internal(format!("Failed to create simulated store: {}", e)))?;
|
|
||||||
|
|
||||||
let store_dir = dirs::cache_dir()
|
|
||||||
.unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
|
|
||||||
.join("nix-js")
|
|
||||||
.join("fetchers")
|
|
||||||
.join("store")
|
|
||||||
.to_string_lossy()
|
|
||||||
.to_string();
|
|
||||||
|
|
||||||
Ok(Self { cache, store_dir })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Store for SimulatedStore {
|
|
||||||
fn get_store_dir(&self) -> &str {
|
|
||||||
&self.store_dir
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_valid_path(&self, path: &str) -> Result<bool> {
|
|
||||||
Ok(Path::new(path).exists())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ensure_path(&self, path: &str) -> Result<()> {
|
|
||||||
if !Path::new(path).exists() {
|
|
||||||
return Err(Error::eval_error(
|
|
||||||
format!(
|
|
||||||
"builtins.storePath: path '{}' does not exist in the simulated store",
|
|
||||||
path
|
|
||||||
),
|
|
||||||
None,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn add_to_store(
|
|
||||||
&self,
|
|
||||||
name: &str,
|
|
||||||
content: &[u8],
|
|
||||||
_recursive: bool,
|
|
||||||
_references: Vec<String>,
|
|
||||||
) -> Result<String> {
|
|
||||||
let hash = crate::nix_hash::sha256_hex(&String::from_utf8_lossy(content));
|
|
||||||
|
|
||||||
let store_path = self.cache.make_store_path(&hash, name);
|
|
||||||
|
|
||||||
if !store_path.exists() {
|
|
||||||
fs::create_dir_all(store_path.parent().unwrap_or(&store_path))
|
|
||||||
.map_err(|e| Error::internal(format!("Failed to create store directory: {}", e)))?;
|
|
||||||
|
|
||||||
fs::write(&store_path, content)
|
|
||||||
.map_err(|e| Error::internal(format!("Failed to write to store: {}", e)))?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(store_path.to_string_lossy().to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn add_to_store_from_path(
|
|
||||||
&self,
|
|
||||||
name: &str,
|
|
||||||
source_path: &Path,
|
|
||||||
_references: Vec<String>,
|
|
||||||
) -> Result<String> {
|
|
||||||
use crate::fetcher::cache::copy_dir_recursive;
|
|
||||||
|
|
||||||
let nar_hash = crate::nar::compute_nar_hash(source_path)
|
|
||||||
.map_err(|e| Error::internal(format!("Failed to compute NAR hash: {}", e)))?;
|
|
||||||
|
|
||||||
let store_path = self.cache.make_store_path(&nar_hash, name);
|
|
||||||
|
|
||||||
if !store_path.exists() {
|
|
||||||
fs::create_dir_all(&store_path)
|
|
||||||
.map_err(|e| Error::internal(format!("Failed to create store directory: {}", e)))?;
|
|
||||||
|
|
||||||
if source_path.is_dir() {
|
|
||||||
copy_dir_recursive(source_path, &store_path)
|
|
||||||
.map_err(|e| Error::internal(format!("Failed to copy to store: {}", e)))?;
|
|
||||||
} else {
|
|
||||||
fs::copy(source_path, &store_path)
|
|
||||||
.map_err(|e| Error::internal(format!("Failed to copy to store: {}", e)))?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(store_path.to_string_lossy().to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn add_text_to_store(
|
|
||||||
&self,
|
|
||||||
name: &str,
|
|
||||||
content: &str,
|
|
||||||
references: Vec<String>,
|
|
||||||
) -> Result<String> {
|
|
||||||
self.add_to_store(name, content.as_bytes(), false, references)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn make_fixed_output_path(
|
|
||||||
&self,
|
|
||||||
_hash_algo: &str,
|
|
||||||
hash: &str,
|
|
||||||
_hash_mode: &str,
|
|
||||||
name: &str,
|
|
||||||
) -> Result<String> {
|
|
||||||
let store_path = self.cache.make_store_path(hash, name);
|
|
||||||
Ok(store_path.to_string_lossy().to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -81,7 +81,7 @@ pub fn validate_store_path(store_dir: &str, path: &str) -> Result<()> {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn test_valid_store_paths() {
|
fn test_valid_store_paths() {
|
||||||
let store_dir = "/nix/store";
|
let store_dir = "/nix/store";
|
||||||
let valid_paths = vec![
|
let valid_paths = vec![
|
||||||
@@ -100,7 +100,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn test_invalid_store_paths() {
|
fn test_invalid_store_paths() {
|
||||||
let store_dir = "/nix/store";
|
let store_dir = "/nix/store";
|
||||||
let invalid_paths = vec![
|
let invalid_paths = vec![
|
||||||
|
|||||||
209
nix-js/src/string_context.rs
Normal file
209
nix-js/src/string_context.rs
Normal file
@@ -0,0 +1,209 @@
|
|||||||
|
use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
||||||
|
|
||||||
|
pub enum StringContextElem {
|
||||||
|
Opaque { path: String },
|
||||||
|
DrvDeep { drv_path: String },
|
||||||
|
Built { drv_path: String, output: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StringContextElem {
|
||||||
|
pub fn decode(encoded: &str) -> Self {
|
||||||
|
if let Some(drv_path) = encoded.strip_prefix('=') {
|
||||||
|
StringContextElem::DrvDeep {
|
||||||
|
drv_path: drv_path.to_string(),
|
||||||
|
}
|
||||||
|
} else if let Some(rest) = encoded.strip_prefix('!') {
|
||||||
|
if let Some(second_bang) = rest.find('!') {
|
||||||
|
let output = rest[..second_bang].to_string();
|
||||||
|
let drv_path = rest[second_bang + 1..].to_string();
|
||||||
|
StringContextElem::Built { drv_path, output }
|
||||||
|
} else {
|
||||||
|
StringContextElem::Opaque {
|
||||||
|
path: encoded.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
StringContextElem::Opaque {
|
||||||
|
path: encoded.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type InputDrvs = BTreeMap<String, BTreeSet<String>>;
|
||||||
|
pub type Srcs = BTreeSet<String>;
|
||||||
|
pub fn extract_input_drvs_and_srcs(context: &[String]) -> Result<(InputDrvs, Srcs), String> {
|
||||||
|
let mut input_drvs: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
|
||||||
|
let mut input_srcs: BTreeSet<String> = BTreeSet::new();
|
||||||
|
|
||||||
|
for encoded in context {
|
||||||
|
match StringContextElem::decode(encoded) {
|
||||||
|
StringContextElem::Opaque { path } => {
|
||||||
|
input_srcs.insert(path);
|
||||||
|
}
|
||||||
|
StringContextElem::DrvDeep { drv_path } => {
|
||||||
|
compute_fs_closure(&drv_path, &mut input_drvs, &mut input_srcs)?;
|
||||||
|
}
|
||||||
|
StringContextElem::Built { drv_path, output } => {
|
||||||
|
input_drvs.entry(drv_path).or_default().insert(output);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok((input_drvs, input_srcs))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compute_fs_closure(
|
||||||
|
drv_path: &str,
|
||||||
|
input_drvs: &mut BTreeMap<String, BTreeSet<String>>,
|
||||||
|
input_srcs: &mut BTreeSet<String>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let mut queue: VecDeque<String> = VecDeque::new();
|
||||||
|
let mut visited: BTreeSet<String> = BTreeSet::new();
|
||||||
|
|
||||||
|
queue.push_back(drv_path.to_string());
|
||||||
|
|
||||||
|
while let Some(current_path) = queue.pop_front() {
|
||||||
|
if visited.contains(¤t_path) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
visited.insert(current_path.clone());
|
||||||
|
input_srcs.insert(current_path.clone());
|
||||||
|
|
||||||
|
if !current_path.ends_with(".drv") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let content = std::fs::read_to_string(¤t_path)
|
||||||
|
.map_err(|e| format!("failed to read derivation {}: {}", current_path, e))?;
|
||||||
|
|
||||||
|
let inputs = parse_derivation_inputs(&content)
|
||||||
|
.ok_or_else(|| format!("failed to parse derivation {}", current_path))?;
|
||||||
|
|
||||||
|
for src in inputs.input_srcs {
|
||||||
|
input_srcs.insert(src.clone());
|
||||||
|
if !visited.contains(&src) {
|
||||||
|
queue.push_back(src);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (dep_drv, outputs) in inputs.input_drvs {
|
||||||
|
input_srcs.insert(dep_drv.clone());
|
||||||
|
let entry = input_drvs.entry(dep_drv.clone()).or_default();
|
||||||
|
for output in outputs {
|
||||||
|
entry.insert(output);
|
||||||
|
}
|
||||||
|
if !visited.contains(&dep_drv) {
|
||||||
|
queue.push_back(dep_drv);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
struct DerivationInputs {
|
||||||
|
input_drvs: Vec<(String, Vec<String>)>,
|
||||||
|
input_srcs: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_derivation_inputs(aterm: &str) -> Option<DerivationInputs> {
|
||||||
|
let aterm = aterm.strip_prefix("Derive([")?;
|
||||||
|
|
||||||
|
let mut bracket_count: i32 = 1;
|
||||||
|
let mut pos = 0;
|
||||||
|
let bytes = aterm.as_bytes();
|
||||||
|
while pos < bytes.len() && bracket_count > 0 {
|
||||||
|
match bytes[pos] {
|
||||||
|
b'[' => bracket_count += 1,
|
||||||
|
b']' => bracket_count -= 1,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
if bracket_count != 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let rest = &aterm[pos..];
|
||||||
|
let rest = rest.strip_prefix(",[")?;
|
||||||
|
|
||||||
|
let mut input_drvs = Vec::new();
|
||||||
|
let mut bracket_count: i32 = 1;
|
||||||
|
let mut start = 0;
|
||||||
|
pos = 0;
|
||||||
|
let bytes = rest.as_bytes();
|
||||||
|
|
||||||
|
while pos < bytes.len() && bracket_count > 0 {
|
||||||
|
match bytes[pos] {
|
||||||
|
b'[' => bracket_count += 1,
|
||||||
|
b']' => bracket_count -= 1,
|
||||||
|
b'(' if bracket_count == 1 => {
|
||||||
|
start = pos;
|
||||||
|
}
|
||||||
|
b')' if bracket_count == 1 => {
|
||||||
|
let entry = &rest[start + 1..pos];
|
||||||
|
if let Some((drv_path, outputs)) = parse_input_drv_entry(entry) {
|
||||||
|
input_drvs.push((drv_path, outputs));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let rest = &rest[pos..];
|
||||||
|
let rest = rest.strip_prefix(",[")?;
|
||||||
|
|
||||||
|
let mut input_srcs = Vec::new();
|
||||||
|
bracket_count = 1;
|
||||||
|
pos = 0;
|
||||||
|
let bytes = rest.as_bytes();
|
||||||
|
|
||||||
|
while pos < bytes.len() && bracket_count > 0 {
|
||||||
|
match bytes[pos] {
|
||||||
|
b'[' => bracket_count += 1,
|
||||||
|
b']' => bracket_count -= 1,
|
||||||
|
b'"' if bracket_count == 1 => {
|
||||||
|
pos += 1;
|
||||||
|
let src_start = pos;
|
||||||
|
while pos < bytes.len() && bytes[pos] != b'"' {
|
||||||
|
if bytes[pos] == b'\\' && pos + 1 < bytes.len() {
|
||||||
|
pos += 2;
|
||||||
|
} else {
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let src = std::str::from_utf8(&bytes[src_start..pos]).ok()?;
|
||||||
|
input_srcs.push(src.to_string());
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(DerivationInputs {
|
||||||
|
input_drvs,
|
||||||
|
input_srcs,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_input_drv_entry(entry: &str) -> Option<(String, Vec<String>)> {
|
||||||
|
let entry = entry.strip_prefix('"')?;
|
||||||
|
let quote_end = entry.find('"')?;
|
||||||
|
let drv_path = entry[..quote_end].to_string();
|
||||||
|
|
||||||
|
let rest = &entry[quote_end + 1..];
|
||||||
|
let rest = rest.strip_prefix(",[")?;
|
||||||
|
let rest = rest.strip_suffix(']')?;
|
||||||
|
|
||||||
|
let mut outputs = Vec::new();
|
||||||
|
for part in rest.split(',') {
|
||||||
|
let part = part.trim();
|
||||||
|
if let Some(name) = part.strip_prefix('"').and_then(|s| s.strip_suffix('"')) {
|
||||||
|
outputs.push(name.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Some((drv_path, outputs))
|
||||||
|
}
|
||||||
@@ -1,36 +1,41 @@
|
|||||||
use core::fmt::{Debug, Display, Formatter, Result as FmtResult};
|
use core::fmt::{Debug, Display, Formatter, Result as FmtResult};
|
||||||
use core::hash::Hash;
|
use core::hash::Hash;
|
||||||
use core::ops::Deref;
|
use core::ops::Deref;
|
||||||
|
|
||||||
use std::borrow::Cow;
|
use std::borrow::Cow;
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use std::ops::DerefMut;
|
use std::ops::DerefMut;
|
||||||
use std::sync::LazyLock;
|
|
||||||
|
|
||||||
use derive_more::{Constructor, IsVariant, Unwrap};
|
use derive_more::{Constructor, IsVariant, Unwrap};
|
||||||
use regex::Regex;
|
|
||||||
|
|
||||||
/// Represents a Nix symbol, which is used as a key in attribute sets.
|
/// Represents a Nix symbol, which is used as a key in attribute sets.
|
||||||
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Constructor)]
|
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Constructor)]
|
||||||
pub struct Symbol(String);
|
pub struct Symbol<'a>(Cow<'a, str>);
|
||||||
|
|
||||||
impl<T: Into<String>> From<T> for Symbol {
|
pub type StaticSymbol = Symbol<'static>;
|
||||||
fn from(value: T) -> Self {
|
|
||||||
Symbol(value.into())
|
impl From<String> for Symbol<'_> {
|
||||||
|
fn from(value: String) -> Self {
|
||||||
|
Symbol(Cow::Owned(value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> From<&'a str> for Symbol<'a> {
|
||||||
|
fn from(value: &'a str) -> Self {
|
||||||
|
Symbol(Cow::Borrowed(value))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Formats a string slice as a Nix symbol, quoting it if necessary.
|
/// Formats a string slice as a Nix symbol, quoting it if necessary.
|
||||||
pub fn format_symbol<'a>(sym: impl Into<Cow<'a, str>>) -> Cow<'a, str> {
|
pub fn format_symbol<'a>(sym: impl Into<Cow<'a, str>>) -> Cow<'a, str> {
|
||||||
let sym = sym.into();
|
let sym = sym.into();
|
||||||
if REGEX.is_match(&sym) {
|
if Symbol::NORMAL_REGEX.test(&sym) {
|
||||||
sym
|
sym
|
||||||
} else {
|
} else {
|
||||||
Cow::Owned(format!(r#""{sym}""#))
|
Cow::Owned(escape_quote_string(&sym))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for Symbol {
|
impl Display for Symbol<'_> {
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
|
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
|
||||||
if self.normal() {
|
if self.normal() {
|
||||||
write!(f, "{}", self.0)
|
write!(f, "{}", self.0)
|
||||||
@@ -40,55 +45,41 @@ impl Display for Symbol {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static REGEX: LazyLock<Regex> = LazyLock::new(|| {
|
impl Symbol<'_> {
|
||||||
Regex::new(r"^[a-zA-Z_][a-zA-Z0-9_'-]*$").expect("hardcoded regex is always valid")
|
const NORMAL_REGEX: ere::Regex<1> = ere::compile_regex!("^[a-zA-Z_][a-zA-Z0-9_'-]*$");
|
||||||
});
|
|
||||||
impl Symbol {
|
|
||||||
/// Checks if the symbol is a "normal" identifier that doesn't require quotes.
|
/// Checks if the symbol is a "normal" identifier that doesn't require quotes.
|
||||||
fn normal(&self) -> bool {
|
fn normal(&self) -> bool {
|
||||||
REGEX.is_match(self)
|
Self::NORMAL_REGEX.test(self)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Deref for Symbol {
|
impl Deref for Symbol<'_> {
|
||||||
type Target = str;
|
type Target = str;
|
||||||
fn deref(&self) -> &Self::Target {
|
fn deref(&self) -> &Self::Target {
|
||||||
&self.0
|
&self.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Symbol {
|
|
||||||
/// Consumes the `Symbol`, returning its inner `String`.
|
|
||||||
pub fn into_inner(self) -> String {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns a reference to the inner `String`.
|
|
||||||
pub fn as_inner(&self) -> &String {
|
|
||||||
&self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Represents a Nix attribute set, which is a map from symbols to values.
|
/// Represents a Nix attribute set, which is a map from symbols to values.
|
||||||
#[derive(Constructor, Default, Clone, PartialEq)]
|
#[derive(Constructor, Default, Clone, PartialEq)]
|
||||||
pub struct AttrSet {
|
pub struct AttrSet {
|
||||||
data: BTreeMap<Symbol, Value>,
|
data: BTreeMap<StaticSymbol, Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AttrSet {
|
impl AttrSet {
|
||||||
/// Gets a value by key (string or Symbol).
|
/// Gets a value by key (string or Symbol).
|
||||||
pub fn get(&self, key: impl Into<Symbol>) -> Option<&Value> {
|
pub fn get<'a, 'sym: 'a>(&'a self, key: impl Into<Symbol<'sym>>) -> Option<&'a Value> {
|
||||||
self.data.get(&key.into())
|
self.data.get(&key.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Checks if a key exists in the attribute set.
|
/// Checks if a key exists in the attribute set.
|
||||||
pub fn contains_key(&self, key: impl Into<Symbol>) -> bool {
|
pub fn contains_key<'a, 'sym: 'a>(&'a self, key: impl Into<Symbol<'sym>>) -> bool {
|
||||||
self.data.contains_key(&key.into())
|
self.data.contains_key(&key.into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Deref for AttrSet {
|
impl Deref for AttrSet {
|
||||||
type Target = BTreeMap<Symbol, Value>;
|
type Target = BTreeMap<StaticSymbol, Value>;
|
||||||
fn deref(&self) -> &Self::Target {
|
fn deref(&self) -> &Self::Target {
|
||||||
&self.data
|
&self.data
|
||||||
}
|
}
|
||||||
@@ -117,12 +108,31 @@ impl Debug for AttrSet {
|
|||||||
|
|
||||||
impl Display for AttrSet {
|
impl Display for AttrSet {
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
|
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
|
||||||
|
use Value::*;
|
||||||
|
if self.data.len() > 1 {
|
||||||
|
writeln!(f, "{{")?;
|
||||||
|
for (k, v) in self.data.iter() {
|
||||||
|
write!(f, " {k} = ")?;
|
||||||
|
match v {
|
||||||
|
List(_) => writeln!(f, "[ ... ];")?,
|
||||||
|
AttrSet(_) => writeln!(f, "{{ ... }};")?,
|
||||||
|
v => writeln!(f, "{v};")?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
write!(f, "}}")
|
||||||
|
} else {
|
||||||
write!(f, "{{")?;
|
write!(f, "{{")?;
|
||||||
for (k, v) in self.data.iter() {
|
for (k, v) in self.data.iter() {
|
||||||
write!(f, " {k} = {v};")?;
|
write!(f, " {k} = ")?;
|
||||||
|
match v {
|
||||||
|
List(_) => write!(f, "[ ... ];")?,
|
||||||
|
AttrSet(_) => write!(f, "{{ ... }};")?,
|
||||||
|
v => write!(f, "{v};")?,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
write!(f, " }}")
|
write!(f, " }}")
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AttrSet {
|
impl AttrSet {
|
||||||
@@ -163,11 +173,28 @@ impl DerefMut for List {
|
|||||||
|
|
||||||
impl Display for List {
|
impl Display for List {
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
|
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
|
||||||
write!(f, "[ ")?;
|
use Value::*;
|
||||||
|
if self.data.len() > 1 {
|
||||||
|
writeln!(f, "[")?;
|
||||||
for v in self.data.iter() {
|
for v in self.data.iter() {
|
||||||
write!(f, "{v} ")?;
|
match v {
|
||||||
|
List(_) => writeln!(f, " [ ... ]")?,
|
||||||
|
AttrSet(_) => writeln!(f, " {{ ... }}")?,
|
||||||
|
v => writeln!(f, " {v}")?,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
write!(f, "]")
|
write!(f, "]")
|
||||||
|
} else {
|
||||||
|
write!(f, "[ ")?;
|
||||||
|
for v in self.data.iter() {
|
||||||
|
match v {
|
||||||
|
List(_) => write!(f, "[ ... ] ")?,
|
||||||
|
AttrSet(_) => write!(f, "{{ ... }} ")?,
|
||||||
|
v => write!(f, "{v} ")?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
write!(f, "]")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -240,12 +267,66 @@ fn escape_quote_string(s: &str) -> String {
|
|||||||
ret
|
ret
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Format a float matching C's `printf("%g", x)` with default precision 6.
|
||||||
|
fn fmt_nix_float(f: &mut Formatter<'_>, x: f64) -> FmtResult {
|
||||||
|
if !x.is_finite() {
|
||||||
|
return write!(f, "{x}");
|
||||||
|
}
|
||||||
|
if x == 0.0 {
|
||||||
|
return if x.is_sign_negative() {
|
||||||
|
write!(f, "-0")
|
||||||
|
} else {
|
||||||
|
write!(f, "0")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let precision: i32 = 6;
|
||||||
|
let exp = x.abs().log10().floor() as i32;
|
||||||
|
|
||||||
|
let formatted = if exp >= -4 && exp < precision {
|
||||||
|
let decimal_places = (precision - 1 - exp) as usize;
|
||||||
|
format!("{x:.decimal_places$}")
|
||||||
|
} else {
|
||||||
|
let sig_digits = (precision - 1) as usize;
|
||||||
|
let s = format!("{x:.sig_digits$e}");
|
||||||
|
let (mantissa, exp_part) = s
|
||||||
|
.split_once('e')
|
||||||
|
.expect("scientific notation must contain 'e'");
|
||||||
|
let (sign, digits) = if let Some(d) = exp_part.strip_prefix('-') {
|
||||||
|
("-", d)
|
||||||
|
} else if let Some(d) = exp_part.strip_prefix('+') {
|
||||||
|
("+", d)
|
||||||
|
} else {
|
||||||
|
("+", exp_part)
|
||||||
|
};
|
||||||
|
if digits.len() < 2 {
|
||||||
|
format!("{mantissa}e{sign}0{digits}")
|
||||||
|
} else {
|
||||||
|
format!("{mantissa}e{sign}{digits}")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if formatted.contains('.') {
|
||||||
|
if let Some(e_pos) = formatted.find('e') {
|
||||||
|
let trimmed = formatted[..e_pos]
|
||||||
|
.trim_end_matches('0')
|
||||||
|
.trim_end_matches('.');
|
||||||
|
write!(f, "{}{}", trimmed, &formatted[e_pos..])
|
||||||
|
} else {
|
||||||
|
let trimmed = formatted.trim_end_matches('0').trim_end_matches('.');
|
||||||
|
write!(f, "{trimmed}")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
write!(f, "{formatted}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Display for Value {
|
impl Display for Value {
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
|
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
|
||||||
use Value::*;
|
use Value::*;
|
||||||
match self {
|
match self {
|
||||||
&Int(x) => write!(f, "{x}"),
|
&Int(x) => write!(f, "{x}"),
|
||||||
&Float(x) => write!(f, "{x}"),
|
&Float(x) => fmt_nix_float(f, x),
|
||||||
&Bool(x) => write!(f, "{x}"),
|
&Bool(x) => write!(f, "{x}"),
|
||||||
Null => write!(f, "null"),
|
Null => write!(f, "null"),
|
||||||
String(x) => write!(f, "{}", escape_quote_string(x)),
|
String(x) => write!(f, "{}", escape_quote_string(x)),
|
||||||
@@ -274,7 +355,7 @@ impl Display for ValueCompatDisplay<'_> {
|
|||||||
use Value::*;
|
use Value::*;
|
||||||
match self.0 {
|
match self.0 {
|
||||||
&Int(x) => write!(f, "{x}"),
|
&Int(x) => write!(f, "{x}"),
|
||||||
&Float(x) => write!(f, "{x}"),
|
&Float(x) => fmt_nix_float(f, x),
|
||||||
&Bool(x) => write!(f, "{x}"),
|
&Bool(x) => write!(f, "{x}"),
|
||||||
Null => write!(f, "null"),
|
Null => write!(f, "null"),
|
||||||
String(x) => write!(f, "{}", escape_quote_string(x)),
|
String(x) => write!(f, "{}", escape_quote_string(x)),
|
||||||
|
|||||||
@@ -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 nix_js::value::Value;
|
||||||
use utils::eval;
|
|
||||||
|
|
||||||
use crate::utils::eval_result;
|
use crate::utils::{eval, eval_result};
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn arithmetic() {
|
fn arithmetic() {
|
||||||
assert_eq!(eval("1 + 1"), Value::Int(2));
|
assert_eq!(eval("1 + 1"), Value::Int(2));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn simple_function_application() {
|
fn simple_function_application() {
|
||||||
assert_eq!(eval("(x: x) 1"), Value::Int(1));
|
assert_eq!(eval("(x: x) 1"), Value::Int(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn curried_function() {
|
fn curried_function() {
|
||||||
assert_eq!(eval("(x: y: x - y) 2 1"), Value::Int(1));
|
assert_eq!(eval("(x: y: x - y) 2 1"), Value::Int(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn rec_attrset() {
|
fn rec_attrset() {
|
||||||
assert_eq!(eval("rec { b = a; a = 1; }.b"), Value::Int(1));
|
assert_eq!(eval("rec { b = a; a = 1; }.b"), Value::Int(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn let_binding() {
|
fn let_binding() {
|
||||||
assert_eq!(eval("let b = a; a = 1; in b"), Value::Int(1));
|
assert_eq!(eval("let b = a; a = 1; in b"), Value::Int(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn fibonacci() {
|
fn fibonacci() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval(
|
eval(
|
||||||
@@ -40,7 +37,7 @@ fn fibonacci() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn fixed_point_combinator() {
|
fn fixed_point_combinator() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("((f: let x = f x; in x)(self: { x = 1; y = self.x + 1; })).y"),
|
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() {
|
fn conditional_true() {
|
||||||
assert_eq!(eval("if true then 1 else 0"), Value::Int(1));
|
assert_eq!(eval("if true then 1 else 0"), Value::Int(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn conditional_false() {
|
fn conditional_false() {
|
||||||
assert_eq!(eval("if false then 1 else 0"), Value::Int(0));
|
assert_eq!(eval("if false then 1 else 0"), Value::Int(0));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn nested_let() {
|
fn nested_let() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("let x = 1; in let y = x + 1; z = y + 1; in z"),
|
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() {
|
fn rec_inherit_fails() {
|
||||||
assert!(eval_result("{ inherit x; }").is_err());
|
assert!(eval_result("{ inherit x; }").is_err());
|
||||||
}
|
}
|
||||||
@@ -1,33 +1,32 @@
|
|||||||
mod utils;
|
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use nix_js::value::{AttrSet, List, Value};
|
use nix_js::value::{AttrSet, List, Value};
|
||||||
use utils::eval;
|
|
||||||
|
|
||||||
#[test]
|
use crate::utils::eval;
|
||||||
|
|
||||||
|
#[test_log::test]
|
||||||
fn builtins_accessible() {
|
fn builtins_accessible() {
|
||||||
let result = eval("builtins");
|
let result = eval("builtins");
|
||||||
assert!(matches!(result, Value::AttrSet(_)));
|
assert!(matches!(result, Value::AttrSet(_)));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_self_reference() {
|
fn builtins_self_reference() {
|
||||||
let result = eval("builtins.builtins");
|
let result = eval("builtins.builtins");
|
||||||
assert!(matches!(result, Value::AttrSet(_)));
|
assert!(matches!(result, Value::AttrSet(_)));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_add() {
|
fn builtins_add() {
|
||||||
assert_eq!(eval("builtins.add 1 2"), Value::Int(3));
|
assert_eq!(eval("builtins.add 1 2"), Value::Int(3));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_length() {
|
fn builtins_length() {
|
||||||
assert_eq!(eval("builtins.length [1 2 3]"), Value::Int(3));
|
assert_eq!(eval("builtins.length [1 2 3]"), Value::Int(3));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_map() {
|
fn builtins_map() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("builtins.map (x: x * 2) [1 2 3]"),
|
eval("builtins.map (x: x * 2) [1 2 3]"),
|
||||||
@@ -35,7 +34,7 @@ fn builtins_map() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_filter() {
|
fn builtins_filter() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("builtins.filter (x: x > 1) [1 2 3]"),
|
eval("builtins.filter (x: x > 1) [1 2 3]"),
|
||||||
@@ -43,7 +42,7 @@ fn builtins_filter() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_attrnames() {
|
fn builtins_attrnames() {
|
||||||
let result = eval("builtins.attrNames { a = 1; b = 2; }");
|
let result = eval("builtins.attrNames { a = 1; b = 2; }");
|
||||||
assert!(matches!(result, Value::List(_)));
|
assert!(matches!(result, Value::List(_)));
|
||||||
@@ -52,12 +51,12 @@ fn builtins_attrnames() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_head() {
|
fn builtins_head() {
|
||||||
assert_eq!(eval("builtins.head [1 2 3]"), Value::Int(1));
|
assert_eq!(eval("builtins.head [1 2 3]"), Value::Int(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_tail() {
|
fn builtins_tail() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("builtins.tail [1 2 3]"),
|
eval("builtins.tail [1 2 3]"),
|
||||||
@@ -65,17 +64,17 @@ fn builtins_tail() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_in_let() {
|
fn builtins_in_let() {
|
||||||
assert_eq!(eval("let b = builtins; in b.add 5 3"), Value::Int(8));
|
assert_eq!(eval("let b = builtins; in b.add 5 3"), Value::Int(8));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_in_with() {
|
fn builtins_in_with() {
|
||||||
assert_eq!(eval("with builtins; add 10 20"), Value::Int(30));
|
assert_eq!(eval("with builtins; add 10 20"), Value::Int(30));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_nested_calls() {
|
fn builtins_nested_calls() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("builtins.add (builtins.mul 2 3) (builtins.sub 10 5)"),
|
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() {
|
fn builtins_is_list() {
|
||||||
assert_eq!(eval("builtins.isList [1 2 3]"), Value::Bool(true));
|
assert_eq!(eval("builtins.isList [1 2 3]"), Value::Bool(true));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_is_attrs() {
|
fn builtins_is_attrs() {
|
||||||
assert_eq!(eval("builtins.isAttrs { a = 1; }"), Value::Bool(true));
|
assert_eq!(eval("builtins.isAttrs { a = 1; }"), Value::Bool(true));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_is_function() {
|
fn builtins_is_function() {
|
||||||
assert_eq!(eval("builtins.isFunction (x: x)"), Value::Bool(true));
|
assert_eq!(eval("builtins.isFunction (x: x)"), Value::Bool(true));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_is_null() {
|
fn builtins_is_null() {
|
||||||
assert_eq!(eval("builtins.isNull null"), Value::Bool(true));
|
assert_eq!(eval("builtins.isNull null"), Value::Bool(true));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_is_bool() {
|
fn builtins_is_bool() {
|
||||||
assert_eq!(eval("builtins.isBool true"), Value::Bool(true));
|
assert_eq!(eval("builtins.isBool true"), Value::Bool(true));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_shadowing() {
|
fn builtins_shadowing() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("let builtins = { add = x: y: x - y; }; in builtins.add 5 3"),
|
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() {
|
fn builtins_lazy_evaluation() {
|
||||||
let result = eval("builtins.builtins.builtins.add 1 1");
|
let result = eval("builtins.builtins.builtins.add 1 1");
|
||||||
assert_eq!(result, Value::Int(2));
|
assert_eq!(result, Value::Int(2));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_foldl() {
|
fn builtins_foldl() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("builtins.foldl' (acc: x: acc + x) 0 [1 2 3 4 5]"),
|
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() {
|
fn builtins_elem() {
|
||||||
assert_eq!(eval("builtins.elem 2 [1 2 3]"), Value::Bool(true));
|
assert_eq!(eval("builtins.elem 2 [1 2 3]"), Value::Bool(true));
|
||||||
assert_eq!(eval("builtins.elem 5 [1 2 3]"), Value::Bool(false));
|
assert_eq!(eval("builtins.elem 5 [1 2 3]"), Value::Bool(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_concat_lists() {
|
fn builtins_concat_lists() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("builtins.concatLists [[1 2] [3 4] [5]]"),
|
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() {
|
fn builtins_compare_versions_basic() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("builtins.compareVersions \"1.0\" \"2.3\""),
|
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() {
|
fn builtins_compare_versions_components() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("builtins.compareVersions \"2.3.1\" \"2.3\""),
|
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() {
|
fn builtins_compare_versions_numeric_vs_alpha() {
|
||||||
// Numeric component comes before alpha component
|
// Numeric component comes before alpha component
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -199,7 +198,7 @@ fn builtins_compare_versions_numeric_vs_alpha() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_compare_versions_pre() {
|
fn builtins_compare_versions_pre() {
|
||||||
// "pre" is special: comes before everything except another "pre"
|
// "pre" is special: comes before everything except another "pre"
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -220,7 +219,7 @@ fn builtins_compare_versions_pre() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_compare_versions_alpha() {
|
fn builtins_compare_versions_alpha() {
|
||||||
// Alphabetic comparison
|
// Alphabetic comparison
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -233,7 +232,7 @@ fn builtins_compare_versions_alpha() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_compare_versions_symmetry() {
|
fn builtins_compare_versions_symmetry() {
|
||||||
// Test symmetry: compareVersions(a, b) == -compareVersions(b, a)
|
// Test symmetry: compareVersions(a, b) == -compareVersions(b, a)
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -246,7 +245,7 @@ fn builtins_compare_versions_symmetry() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_compare_versions_complex() {
|
fn builtins_compare_versions_complex() {
|
||||||
// Complex version strings with multiple components
|
// Complex version strings with multiple components
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -263,7 +262,7 @@ fn builtins_compare_versions_complex() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_generic_closure() {
|
fn builtins_generic_closure() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval(
|
eval(
|
||||||
@@ -279,7 +278,7 @@ fn builtins_generic_closure() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_function_args() {
|
fn builtins_function_args() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("builtins.functionArgs (x: 1)"),
|
eval("builtins.functionArgs (x: 1)"),
|
||||||
@@ -316,7 +315,7 @@ fn builtins_function_args() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn builtins_parse_drv_name() {
|
fn builtins_parse_drv_name() {
|
||||||
let result = eval(r#"builtins.parseDrvName "nix-js-0.1.0pre""#).unwrap_attr_set();
|
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())));
|
assert_eq!(result.get("name"), Some(&Value::String("nix-js".into())));
|
||||||
@@ -1,28 +1,9 @@
|
|||||||
mod utils;
|
|
||||||
|
|
||||||
use std::sync::Once;
|
|
||||||
|
|
||||||
use nix_js::value::Value;
|
use nix_js::value::Value;
|
||||||
use utils::eval_result;
|
|
||||||
|
|
||||||
fn init() {
|
use crate::utils::eval_result;
|
||||||
static INIT: Once = Once::new();
|
|
||||||
INIT.call_once(|| {
|
|
||||||
#[cfg(not(feature = "daemon"))]
|
|
||||||
unsafe {
|
|
||||||
std::env::set_var("NIX_JS_STORE_MODE", "simulated")
|
|
||||||
};
|
|
||||||
#[cfg(feature = "daemon")]
|
|
||||||
unsafe {
|
|
||||||
std::env::set_var("NIX_JS_STORE_MODE", "daemon")
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn to_file_simple() {
|
fn to_file_simple() {
|
||||||
init();
|
|
||||||
|
|
||||||
let result =
|
let result =
|
||||||
eval_result(r#"builtins.toFile "hello.txt" "Hello, World!""#).expect("Failed to evaluate");
|
eval_result(r#"builtins.toFile "hello.txt" "Hello, World!""#).expect("Failed to evaluate");
|
||||||
|
|
||||||
@@ -38,10 +19,8 @@ fn to_file_simple() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn to_file_with_references() {
|
fn to_file_with_references() {
|
||||||
init();
|
|
||||||
|
|
||||||
let result = eval_result(
|
let result = eval_result(
|
||||||
r#"
|
r#"
|
||||||
let
|
let
|
||||||
@@ -63,10 +42,8 @@ fn to_file_with_references() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn to_file_invalid_name_with_slash() {
|
fn to_file_invalid_name_with_slash() {
|
||||||
init();
|
|
||||||
|
|
||||||
let result = eval_result(r#"builtins.toFile "foo/bar.txt" "content""#);
|
let result = eval_result(r#"builtins.toFile "foo/bar.txt" "content""#);
|
||||||
|
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
@@ -78,30 +55,24 @@ fn to_file_invalid_name_with_slash() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn to_file_invalid_name_dot() {
|
fn to_file_invalid_name_dot() {
|
||||||
init();
|
|
||||||
|
|
||||||
let result = eval_result(r#"builtins.toFile "." "content""#);
|
let result = eval_result(r#"builtins.toFile "." "content""#);
|
||||||
|
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
assert!(result.unwrap_err().to_string().contains("invalid name"));
|
assert!(result.unwrap_err().to_string().contains("invalid name"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn to_file_invalid_name_dotdot() {
|
fn to_file_invalid_name_dotdot() {
|
||||||
init();
|
|
||||||
|
|
||||||
let result = eval_result(r#"builtins.toFile ".." "content""#);
|
let result = eval_result(r#"builtins.toFile ".." "content""#);
|
||||||
|
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
assert!(result.unwrap_err().to_string().contains("invalid name"));
|
assert!(result.unwrap_err().to_string().contains("invalid name"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn store_path_validation_not_in_store() {
|
fn store_path_validation_not_in_store() {
|
||||||
init();
|
|
||||||
|
|
||||||
let result = eval_result(r#"builtins.storePath "/tmp/foo""#);
|
let result = eval_result(r#"builtins.storePath "/tmp/foo""#);
|
||||||
|
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
@@ -113,10 +84,8 @@ fn store_path_validation_not_in_store() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn store_path_validation_malformed_hash() {
|
fn store_path_validation_malformed_hash() {
|
||||||
init();
|
|
||||||
|
|
||||||
let dummy_file_result = eval_result(r#"builtins.toFile "dummy.txt" "content""#)
|
let dummy_file_result = eval_result(r#"builtins.toFile "dummy.txt" "content""#)
|
||||||
.expect("Failed to create dummy file");
|
.expect("Failed to create dummy file");
|
||||||
|
|
||||||
@@ -143,10 +112,8 @@ fn store_path_validation_malformed_hash() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn store_path_validation_missing_name() {
|
fn store_path_validation_missing_name() {
|
||||||
init();
|
|
||||||
|
|
||||||
let dummy_file_result = eval_result(r#"builtins.toFile "dummy.txt" "content""#)
|
let dummy_file_result = eval_result(r#"builtins.toFile "dummy.txt" "content""#)
|
||||||
.expect("Failed to create dummy file");
|
.expect("Failed to create dummy file");
|
||||||
|
|
||||||
@@ -173,10 +140,8 @@ fn store_path_validation_missing_name() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn to_file_curried_application() {
|
fn to_file_curried_application() {
|
||||||
init();
|
|
||||||
|
|
||||||
let result = eval_result(
|
let result = eval_result(
|
||||||
r#"
|
r#"
|
||||||
let
|
let
|
||||||
@@ -197,10 +162,8 @@ fn to_file_curried_application() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn to_file_number_conversion() {
|
fn to_file_number_conversion() {
|
||||||
init();
|
|
||||||
|
|
||||||
let result = eval_result(r#"builtins.toFile "number.txt" (builtins.toString 42)"#)
|
let result = eval_result(r#"builtins.toFile "number.txt" (builtins.toString 42)"#)
|
||||||
.expect("Failed to evaluate");
|
.expect("Failed to evaluate");
|
||||||
|
|
||||||
@@ -213,10 +176,8 @@ fn to_file_number_conversion() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn to_file_list_conversion() {
|
fn to_file_list_conversion() {
|
||||||
init();
|
|
||||||
|
|
||||||
let result = eval_result(
|
let result = eval_result(
|
||||||
r#"builtins.toFile "list.txt" (builtins.concatStringsSep "\n" ["line1" "line2" "line3"])"#,
|
r#"builtins.toFile "list.txt" (builtins.concatStringsSep "\n" ["line1" "line2" "line3"])"#,
|
||||||
)
|
)
|
||||||
@@ -1,14 +1,48 @@
|
|||||||
#![cfg(feature = "daemon")]
|
|
||||||
|
|
||||||
mod utils;
|
|
||||||
|
|
||||||
use nix_js::value::Value;
|
use nix_js::value::Value;
|
||||||
use utils::{eval, eval_result};
|
|
||||||
|
|
||||||
#[test]
|
use crate::utils::{eval_deep, eval_deep_result};
|
||||||
|
|
||||||
|
#[test_log::test]
|
||||||
|
fn add_operator_preserves_derivation_context() {
|
||||||
|
let result = eval_deep(
|
||||||
|
r#"
|
||||||
|
let
|
||||||
|
dep = derivation { name = "dep"; builder = "/bin/sh"; system = "x86_64-linux"; outputs = ["out" "dev"]; };
|
||||||
|
getOutput = output: pkg: pkg.${output} or pkg.out or pkg;
|
||||||
|
user = derivation {
|
||||||
|
name = "user";
|
||||||
|
builder = "/bin/sh";
|
||||||
|
system = "x86_64-linux";
|
||||||
|
libPath = (getOutput "lib" dep) + "/lib";
|
||||||
|
devPath = dep.dev + "/include";
|
||||||
|
};
|
||||||
|
in user.drvPath
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
|
||||||
|
let nix_result = eval_deep(
|
||||||
|
r#"
|
||||||
|
let
|
||||||
|
dep = derivation { name = "dep"; builder = "/bin/sh"; system = "x86_64-linux"; outputs = ["out" "dev"]; };
|
||||||
|
user = derivation {
|
||||||
|
name = "user";
|
||||||
|
builder = "/bin/sh";
|
||||||
|
system = "x86_64-linux";
|
||||||
|
libPath = "${dep.out}/lib";
|
||||||
|
devPath = "${dep.dev}/include";
|
||||||
|
};
|
||||||
|
in user.drvPath
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(result, nix_result);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test_log::test]
|
||||||
fn derivation_minimal() {
|
fn derivation_minimal() {
|
||||||
let result =
|
let result = eval_deep(
|
||||||
eval(r#"derivation { name = "hello"; builder = "/bin/sh"; system = "x86_64-linux"; }"#);
|
r#"derivation { name = "hello"; builder = "/bin/sh"; system = "x86_64-linux"; }"#,
|
||||||
|
);
|
||||||
|
|
||||||
match result {
|
match result {
|
||||||
Value::AttrSet(attrs) => {
|
Value::AttrSet(attrs) => {
|
||||||
@@ -42,9 +76,9 @@ fn derivation_minimal() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn derivation_with_args() {
|
fn derivation_with_args() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "test";
|
name = "test";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -64,9 +98,9 @@ fn derivation_with_args() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn derivation_to_string() {
|
fn derivation_to_string() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"toString (derivation { name = "foo"; builder = "/bin/sh"; system = "x86_64-linux"; })"#,
|
r#"toString (derivation { name = "foo"; builder = "/bin/sh"; system = "x86_64-linux"; })"#,
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -76,18 +110,19 @@ fn derivation_to_string() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn derivation_missing_name() {
|
fn derivation_missing_name() {
|
||||||
let result = eval_result(r#"derivation { builder = "/bin/sh"; system = "x86_64-linux"; }"#);
|
let result =
|
||||||
|
eval_deep_result(r#"derivation { builder = "/bin/sh"; system = "x86_64-linux"; }"#);
|
||||||
|
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
let err_msg = result.unwrap_err().to_string();
|
let err_msg = result.unwrap_err().to_string();
|
||||||
assert!(err_msg.contains("missing required attribute 'name'"));
|
assert!(err_msg.contains("missing required attribute 'name'"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn derivation_invalid_name_with_drv_suffix() {
|
fn derivation_invalid_name_with_drv_suffix() {
|
||||||
let result = eval_result(
|
let result = eval_deep_result(
|
||||||
r#"derivation { name = "foo.drv"; builder = "/bin/sh"; system = "x86_64-linux"; }"#,
|
r#"derivation { name = "foo.drv"; builder = "/bin/sh"; system = "x86_64-linux"; }"#,
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -96,27 +131,27 @@ fn derivation_invalid_name_with_drv_suffix() {
|
|||||||
assert!(err_msg.contains("cannot end with .drv"));
|
assert!(err_msg.contains("cannot end with .drv"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn derivation_missing_builder() {
|
fn derivation_missing_builder() {
|
||||||
let result = eval_result(r#"derivation { name = "test"; system = "x86_64-linux"; }"#);
|
let result = eval_deep_result(r#"derivation { name = "test"; system = "x86_64-linux"; }"#);
|
||||||
|
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
let err_msg = result.unwrap_err().to_string();
|
let err_msg = result.unwrap_err().to_string();
|
||||||
assert!(err_msg.contains("missing required attribute 'builder'"));
|
assert!(err_msg.contains("missing required attribute 'builder'"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn derivation_missing_system() {
|
fn derivation_missing_system() {
|
||||||
let result = eval_result(r#"derivation { name = "test"; builder = "/bin/sh"; }"#);
|
let result = eval_deep_result(r#"derivation { name = "test"; builder = "/bin/sh"; }"#);
|
||||||
|
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
let err_msg = result.unwrap_err().to_string();
|
let err_msg = result.unwrap_err().to_string();
|
||||||
assert!(err_msg.contains("missing required attribute 'system'"));
|
assert!(err_msg.contains("missing required attribute 'system'"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn derivation_with_env_vars() {
|
fn derivation_with_env_vars() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "test";
|
name = "test";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -135,9 +170,9 @@ fn derivation_with_env_vars() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn derivation_strict() {
|
fn derivation_strict() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"builtins.derivationStrict { name = "test"; builder = "/bin/sh"; system = "x86_64-linux"; }"#,
|
r#"builtins.derivationStrict { name = "test"; builder = "/bin/sh"; system = "x86_64-linux"; }"#,
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -152,12 +187,12 @@ fn derivation_strict() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn derivation_deterministic_paths() {
|
fn derivation_deterministic_paths() {
|
||||||
let expr = r#"derivation { name = "hello"; builder = "/bin/sh"; system = "x86_64-linux"; }"#;
|
let expr = r#"derivation { name = "hello"; builder = "/bin/sh"; system = "x86_64-linux"; }"#;
|
||||||
|
|
||||||
let result1 = eval(expr);
|
let result1 = eval_deep(expr);
|
||||||
let result2 = eval(expr);
|
let result2 = eval_deep(expr);
|
||||||
|
|
||||||
match (result1, result2) {
|
match (result1, result2) {
|
||||||
(Value::AttrSet(attrs1), Value::AttrSet(attrs2)) => {
|
(Value::AttrSet(attrs1), Value::AttrSet(attrs2)) => {
|
||||||
@@ -168,9 +203,9 @@ fn derivation_deterministic_paths() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn derivation_escaping_in_aterm() {
|
fn derivation_escaping_in_aterm() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "test";
|
name = "test";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -188,9 +223,9 @@ fn derivation_escaping_in_aterm() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn multi_output_two_outputs() {
|
fn multi_output_two_outputs() {
|
||||||
let drv = eval(
|
let drv = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "multi";
|
name = "multi";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -231,9 +266,9 @@ fn multi_output_two_outputs() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn multi_output_three_outputs() {
|
fn multi_output_three_outputs() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "three";
|
name = "three";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -279,9 +314,9 @@ fn multi_output_three_outputs() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn multi_output_backward_compat() {
|
fn multi_output_backward_compat() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "compat";
|
name = "compat";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -305,9 +340,9 @@ fn multi_output_backward_compat() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn multi_output_deterministic() {
|
fn multi_output_deterministic() {
|
||||||
let result1 = eval(
|
let result1 = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "determ";
|
name = "determ";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -316,7 +351,7 @@ fn multi_output_deterministic() {
|
|||||||
}"#,
|
}"#,
|
||||||
);
|
);
|
||||||
|
|
||||||
let result2 = eval(
|
let result2 = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "determ";
|
name = "determ";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -328,9 +363,9 @@ fn multi_output_deterministic() {
|
|||||||
assert_eq!(result1, result2);
|
assert_eq!(result1, result2);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn fixed_output_sha256_flat() {
|
fn fixed_output_sha256_flat() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "fixed";
|
name = "fixed";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -365,32 +400,24 @@ fn fixed_output_sha256_flat() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn fixed_output_default_algo() {
|
fn fixed_output_missing_hashalgo() {
|
||||||
let result = eval(
|
assert!(
|
||||||
|
eval_deep_result(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "default";
|
name = "default";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
system = "x86_64-linux";
|
system = "x86_64-linux";
|
||||||
outputHash = "0000000000000000000000000000000000000000000000000000000000000000";
|
outputHash = "0000000000000000000000000000000000000000000000000000000000000000";
|
||||||
}"#,
|
}"#,
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
);
|
);
|
||||||
|
|
||||||
match result {
|
|
||||||
Value::AttrSet(attrs) => {
|
|
||||||
assert!(attrs.contains_key("outPath"));
|
|
||||||
// Verify it defaults to sha256 (same as explicitly specifying it)
|
|
||||||
if let Some(Value::String(out_path)) = attrs.get("outPath") {
|
|
||||||
assert!(out_path.contains("/nix/store/"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => panic!("Expected AttrSet"),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn fixed_output_recursive_mode() {
|
fn fixed_output_recursive_mode() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "recursive";
|
name = "recursive";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -418,14 +445,15 @@ fn fixed_output_recursive_mode() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn fixed_output_rejects_multi_output() {
|
fn fixed_output_rejects_multi_output() {
|
||||||
let result = eval_result(
|
let result = eval_deep_result(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "invalid";
|
name = "invalid";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
system = "x86_64-linux";
|
system = "x86_64-linux";
|
||||||
outputHash = "0000000000000000000000000000000000000000000000000000000000000000";
|
outputHash = "0000000000000000000000000000000000000000000000000000000000000000";
|
||||||
|
outputHashAlgo = "sha256";
|
||||||
outputs = ["out" "dev"];
|
outputs = ["out" "dev"];
|
||||||
}"#,
|
}"#,
|
||||||
);
|
);
|
||||||
@@ -435,9 +463,9 @@ fn fixed_output_rejects_multi_output() {
|
|||||||
assert!(err_msg.contains("fixed-output") && err_msg.contains("one"));
|
assert!(err_msg.contains("fixed-output") && err_msg.contains("one"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn fixed_output_invalid_hash_mode() {
|
fn fixed_output_invalid_hash_mode() {
|
||||||
let result = eval_result(
|
let result = eval_deep_result(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "invalid";
|
name = "invalid";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -452,9 +480,9 @@ fn fixed_output_invalid_hash_mode() {
|
|||||||
assert!(err_msg.contains("outputHashMode") && err_msg.contains("invalid"));
|
assert!(err_msg.contains("outputHashMode") && err_msg.contains("invalid"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn structured_attrs_basic() {
|
fn structured_attrs_basic() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "struct";
|
name = "struct";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -477,9 +505,9 @@ fn structured_attrs_basic() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn structured_attrs_nested() {
|
fn structured_attrs_nested() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "nested";
|
name = "nested";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -498,9 +526,9 @@ fn structured_attrs_nested() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn structured_attrs_rejects_functions() {
|
fn structured_attrs_rejects_functions() {
|
||||||
let result = eval_result(
|
let result = eval_deep_result(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "invalid";
|
name = "invalid";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -512,12 +540,12 @@ fn structured_attrs_rejects_functions() {
|
|||||||
|
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
let err_msg = result.unwrap_err().to_string();
|
let err_msg = result.unwrap_err().to_string();
|
||||||
assert!(err_msg.contains("function") && err_msg.contains("serialize"));
|
assert!(err_msg.contains("cannot convert lambda to JSON"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn structured_attrs_false() {
|
fn structured_attrs_false() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "normal";
|
name = "normal";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -538,9 +566,9 @@ fn structured_attrs_false() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn ignore_nulls_true() {
|
fn ignore_nulls_true() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "ignore";
|
name = "ignore";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -560,9 +588,9 @@ fn ignore_nulls_true() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn ignore_nulls_false() {
|
fn ignore_nulls_false() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "keep";
|
name = "keep";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -583,9 +611,9 @@ fn ignore_nulls_false() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn ignore_nulls_with_structured_attrs() {
|
fn ignore_nulls_with_structured_attrs() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "combined";
|
name = "combined";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -607,9 +635,9 @@ fn ignore_nulls_with_structured_attrs() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn all_features_combined() {
|
fn all_features_combined() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "all";
|
name = "all";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
@@ -634,14 +662,15 @@ fn all_features_combined() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn fixed_output_with_structured_attrs() {
|
fn fixed_output_with_structured_attrs() {
|
||||||
let result = eval(
|
let result = eval_deep(
|
||||||
r#"derivation {
|
r#"derivation {
|
||||||
name = "fixstruct";
|
name = "fixstruct";
|
||||||
builder = "/bin/sh";
|
builder = "/bin/sh";
|
||||||
system = "x86_64-linux";
|
system = "x86_64-linux";
|
||||||
outputHash = "abc123";
|
outputHash = "0000000000000000000000000000000000000000000000000000000000000000";
|
||||||
|
outputHashAlgo = "sha256";
|
||||||
__structuredAttrs = true;
|
__structuredAttrs = true;
|
||||||
data = { key = "value"; };
|
data = { key = "value"; };
|
||||||
}"#,
|
}"#,
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
mod utils;
|
use crate::utils::eval;
|
||||||
|
|
||||||
use utils::eval;
|
#[test_log::test]
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_find_file_corepkg_fetchurl() {
|
fn test_find_file_corepkg_fetchurl() {
|
||||||
let result = eval(
|
let result = eval(
|
||||||
r#"
|
r#"
|
||||||
@@ -17,13 +15,13 @@ fn test_find_file_corepkg_fetchurl() {
|
|||||||
assert!(result.to_string().contains("fetchurl.nix"));
|
assert!(result.to_string().contains("fetchurl.nix"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn test_lookup_path_syntax() {
|
fn test_lookup_path_syntax() {
|
||||||
let result = eval(r#"<nix/fetchurl.nix>"#);
|
let result = eval(r#"<nix/fetchurl.nix>"#);
|
||||||
assert!(result.to_string().contains("fetchurl.nix"));
|
assert!(result.to_string().contains("fetchurl.nix"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn test_import_corepkg() {
|
fn test_import_corepkg() {
|
||||||
let result = eval(
|
let result = eval(
|
||||||
r#"
|
r#"
|
||||||
@@ -1,24 +1,23 @@
|
|||||||
mod utils;
|
|
||||||
|
|
||||||
use nix_js::value::{List, Value};
|
use nix_js::value::{List, Value};
|
||||||
use utils::eval;
|
|
||||||
|
|
||||||
#[test]
|
use crate::utils::{eval, eval_result};
|
||||||
|
|
||||||
|
#[test_log::test]
|
||||||
fn true_literal() {
|
fn true_literal() {
|
||||||
assert_eq!(eval("true"), Value::Bool(true));
|
assert_eq!(eval("true"), Value::Bool(true));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn false_literal() {
|
fn false_literal() {
|
||||||
assert_eq!(eval("false"), Value::Bool(false));
|
assert_eq!(eval("false"), Value::Bool(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn null_literal() {
|
fn null_literal() {
|
||||||
assert_eq!(eval("null"), Value::Null);
|
assert_eq!(eval("null"), Value::Null);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn map_function() {
|
fn map_function() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("map (x: x * 2) [1 2 3]"),
|
eval("map (x: x * 2) [1 2 3]"),
|
||||||
@@ -26,23 +25,23 @@ fn map_function() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn is_null_function() {
|
fn is_null_function() {
|
||||||
assert_eq!(eval("isNull null"), Value::Bool(true));
|
assert_eq!(eval("isNull null"), Value::Bool(true));
|
||||||
assert_eq!(eval("isNull 5"), Value::Bool(false));
|
assert_eq!(eval("isNull 5"), Value::Bool(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn shadow_true() {
|
fn shadow_true() {
|
||||||
assert_eq!(eval("let true = false; in true"), Value::Bool(false));
|
assert_eq!(eval("let true = false; in true"), Value::Bool(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn shadow_map() {
|
fn shadow_map() {
|
||||||
assert_eq!(eval("let map = x: y: x; in map 1 2"), Value::Int(1));
|
assert_eq!(eval("let map = x: y: x; in map 1 2"), Value::Int(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn mixed_usage() {
|
fn mixed_usage() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("if true then map (x: x + 1) [1 2] else []"),
|
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() {
|
fn in_let_bindings() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("let x = true; y = false; in x && y"),
|
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() {
|
fn shadow_in_function() {
|
||||||
assert_eq!(eval("(true: true) false"), Value::Bool(false));
|
assert_eq!(eval("(true: true) false"), Value::Bool(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn throw_function() {
|
fn throw_function() {
|
||||||
let result = utils::eval_result("throw \"error message\"");
|
let result = eval_result("throw \"error message\"");
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn to_string_function() {
|
fn to_string_function() {
|
||||||
assert_eq!(eval("toString 42"), Value::String("42".to_string()));
|
assert_eq!(eval("toString 42"), Value::String("42".to_string()));
|
||||||
}
|
}
|
||||||
@@ -1,20 +1,19 @@
|
|||||||
mod utils;
|
|
||||||
|
|
||||||
use nix_js::value::Value;
|
use nix_js::value::Value;
|
||||||
use utils::{eval, eval_result};
|
|
||||||
|
|
||||||
#[test]
|
use crate::utils::{eval, eval_result};
|
||||||
|
|
||||||
|
#[test_log::test]
|
||||||
fn required_parameters() {
|
fn required_parameters() {
|
||||||
assert_eq!(eval("({ a, b }: a + b) { a = 1; b = 2; }"), Value::Int(3));
|
assert_eq!(eval("({ a, b }: a + b) { a = 1; b = 2; }"), Value::Int(3));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn missing_required_parameter() {
|
fn missing_required_parameter() {
|
||||||
let result = eval_result("({ a, b }: a + b) { a = 1; }");
|
let result = eval_result("({ a, b }: a + b) { a = 1; }");
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn all_required_parameters_present() {
|
fn all_required_parameters_present() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("({ x, y, z }: x + y + z) { x = 1; y = 2; z = 3; }"),
|
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() {
|
fn reject_unexpected_arguments() {
|
||||||
let result = eval_result("({ a, b }: a + b) { a = 1; b = 2; c = 3; }");
|
let result = eval_result("({ a, b }: a + b) { a = 1; b = 2; c = 3; }");
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn ellipsis_accepts_extra_arguments() {
|
fn ellipsis_accepts_extra_arguments() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("({ a, b, ... }: a + b) { a = 1; b = 2; c = 3; }"),
|
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() {
|
fn default_parameters() {
|
||||||
assert_eq!(eval("({ a, b ? 5 }: a + b) { a = 1; }"), Value::Int(6));
|
assert_eq!(eval("({ a, b ? 5 }: a + b) { a = 1; }"), Value::Int(6));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn override_default_parameter() {
|
fn override_default_parameter() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("({ a, b ? 5 }: a + b) { a = 1; b = 10; }"),
|
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() {
|
fn at_pattern_alias() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("(args@{ a, b }: args.a + args.b) { a = 1; b = 2; }"),
|
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() {
|
fn simple_parameter_no_validation() {
|
||||||
assert_eq!(eval("(x: x.a + x.b) { a = 1; b = 2; }"), Value::Int(3));
|
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() {
|
fn simple_parameter_accepts_any_argument() {
|
||||||
assert_eq!(eval("(x: x) 42"), Value::Int(42));
|
assert_eq!(eval("(x: x) 42"), Value::Int(42));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn nested_function_parameters() {
|
fn nested_function_parameters() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("({ a }: { b }: a + b) { a = 5; } { b = 3; }"),
|
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() {
|
fn pattern_param_simple_reference_in_default() {
|
||||||
assert_eq!(eval("({ a, b ? a }: b) { a = 10; }"), Value::Int(10));
|
assert_eq!(eval("({ a, b ? a }: b) { a = 10; }"), Value::Int(10));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn pattern_param_multiple_references_in_default() {
|
fn pattern_param_multiple_references_in_default() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("({ a, b ? a + 5, c ? 1 }: b + c) { a = 10; }"),
|
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() {
|
fn pattern_param_mutual_reference() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("({ a, b ? c + 1, c ? 5 }: b) { a = 1; }"),
|
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() {
|
fn pattern_param_override_mutual_reference() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("({ a, b ? c + 1, c ? 5 }: b) { a = 1; c = 10; }"),
|
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() {
|
fn pattern_param_reference_list() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("({ a, b ? [ a 2 ] }: builtins.elemAt b 0) { a = 42; }"),
|
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() {
|
fn pattern_param_alias_in_default() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
eval("(args@{ a, b ? args.a + 10 }: b) { a = 5; }"),
|
eval("(args@{ a, b ? args.a + 10 }: b) { a = 5; }"),
|
||||||
@@ -1,12 +1,10 @@
|
|||||||
mod utils;
|
|
||||||
|
|
||||||
use nix_js::context::Context;
|
use nix_js::context::Context;
|
||||||
use nix_js::error::Source;
|
use nix_js::error::Source;
|
||||||
use nix_js::value::Value;
|
use nix_js::value::Value;
|
||||||
|
|
||||||
use crate::utils::{eval, eval_result};
|
use crate::utils::{eval, eval_result};
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn import_absolute_path() {
|
fn import_absolute_path() {
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
let lib_path = temp_dir.path().join("nix_test_lib.nix");
|
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));
|
assert_eq!(eval(&expr), Value::Int(8));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn import_nested() {
|
fn import_nested() {
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
|
|
||||||
@@ -35,7 +33,7 @@ fn import_nested() {
|
|||||||
assert_eq!(eval(&expr), Value::Int(30));
|
assert_eq!(eval(&expr), Value::Int(30));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn import_relative_path() {
|
fn import_relative_path() {
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
let subdir = temp_dir.path().join("subdir");
|
let subdir = temp_dir.path().join("subdir");
|
||||||
@@ -66,7 +64,7 @@ fn import_relative_path() {
|
|||||||
assert_eq!(eval(&expr), Value::Int(7));
|
assert_eq!(eval(&expr), Value::Int(7));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn import_returns_function() {
|
fn import_returns_function() {
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
let func_path = temp_dir.path().join("nix_test_func.nix");
|
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));
|
assert_eq!(eval(&expr), Value::Int(10));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn import_with_complex_dependency_graph() {
|
fn import_with_complex_dependency_graph() {
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
|
|
||||||
@@ -97,7 +95,7 @@ fn import_with_complex_dependency_graph() {
|
|||||||
|
|
||||||
// Tests for builtins.path
|
// Tests for builtins.path
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn path_with_file() {
|
fn path_with_file() {
|
||||||
let mut ctx = Context::new().unwrap();
|
let mut ctx = Context::new().unwrap();
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
@@ -105,7 +103,7 @@ fn path_with_file() {
|
|||||||
std::fs::write(&test_file, "Hello, World!").unwrap();
|
std::fs::write(&test_file, "Hello, World!").unwrap();
|
||||||
|
|
||||||
let expr = format!(r#"builtins.path {{ path = {}; }}"#, test_file.display());
|
let expr = format!(r#"builtins.path {{ path = {}; }}"#, test_file.display());
|
||||||
let result = ctx.eval_code(Source::new_eval(expr).unwrap()).unwrap();
|
let result = ctx.eval(Source::new_eval(expr).unwrap()).unwrap();
|
||||||
|
|
||||||
// Should return a store path string
|
// Should return a store path string
|
||||||
if let Value::String(store_path) = result {
|
if let Value::String(store_path) = result {
|
||||||
@@ -116,7 +114,7 @@ fn path_with_file() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn path_with_custom_name() {
|
fn path_with_custom_name() {
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
let test_file = temp_dir.path().join("original.txt");
|
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() {
|
fn path_with_directory_recursive() {
|
||||||
let mut ctx = Context::new().unwrap();
|
let mut ctx = Context::new().unwrap();
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
@@ -149,7 +147,7 @@ fn path_with_directory_recursive() {
|
|||||||
r#"builtins.path {{ path = {}; recursive = true; }}"#,
|
r#"builtins.path {{ path = {}; recursive = true; }}"#,
|
||||||
test_dir.display()
|
test_dir.display()
|
||||||
);
|
);
|
||||||
let result = ctx.eval_code(Source::new_eval(expr).unwrap()).unwrap();
|
let result = ctx.eval(Source::new_eval(expr).unwrap()).unwrap();
|
||||||
|
|
||||||
if let Value::String(store_path) = result {
|
if let Value::String(store_path) = result {
|
||||||
assert!(store_path.starts_with(ctx.get_store_dir()));
|
assert!(store_path.starts_with(ctx.get_store_dir()));
|
||||||
@@ -159,7 +157,7 @@ fn path_with_directory_recursive() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn path_flat_with_file() {
|
fn path_flat_with_file() {
|
||||||
let mut ctx = Context::new().unwrap();
|
let mut ctx = Context::new().unwrap();
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
@@ -170,7 +168,7 @@ fn path_flat_with_file() {
|
|||||||
r#"builtins.path {{ path = {}; recursive = false; }}"#,
|
r#"builtins.path {{ path = {}; recursive = false; }}"#,
|
||||||
test_file.display()
|
test_file.display()
|
||||||
);
|
);
|
||||||
let result = ctx.eval_code(Source::new_eval(expr).unwrap()).unwrap();
|
let result = ctx.eval(Source::new_eval(expr).unwrap()).unwrap();
|
||||||
|
|
||||||
if let Value::String(store_path) = result {
|
if let Value::String(store_path) = result {
|
||||||
assert!(store_path.starts_with(ctx.get_store_dir()));
|
assert!(store_path.starts_with(ctx.get_store_dir()));
|
||||||
@@ -179,7 +177,7 @@ fn path_flat_with_file() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn path_flat_with_directory_fails() {
|
fn path_flat_with_directory_fails() {
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
let test_dir = temp_dir.path().join("mydir");
|
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"));
|
assert!(err_msg.contains("recursive") || err_msg.contains("regular file"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn path_nonexistent_fails() {
|
fn path_nonexistent_fails() {
|
||||||
let expr = r#"builtins.path { path = "/nonexistent/path/that/should/not/exist"; }"#;
|
let expr = r#"builtins.path { path = "/nonexistent/path/that/should/not/exist"; }"#;
|
||||||
let result = eval_result(expr);
|
let result = eval_result(expr);
|
||||||
@@ -206,7 +204,7 @@ fn path_nonexistent_fails() {
|
|||||||
assert!(err_msg.contains("does not exist"));
|
assert!(err_msg.contains("does not exist"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn path_missing_path_param() {
|
fn path_missing_path_param() {
|
||||||
let expr = r#"builtins.path { name = "test"; }"#;
|
let expr = r#"builtins.path { name = "test"; }"#;
|
||||||
let result = eval_result(expr);
|
let result = eval_result(expr);
|
||||||
@@ -216,7 +214,7 @@ fn path_missing_path_param() {
|
|||||||
assert!(err_msg.contains("path") && err_msg.contains("required"));
|
assert!(err_msg.contains("path") && err_msg.contains("required"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn path_with_sha256() {
|
fn path_with_sha256() {
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
let test_file = temp_dir.path().join("hash_test.txt");
|
let test_file = temp_dir.path().join("hash_test.txt");
|
||||||
@@ -243,7 +241,7 @@ fn path_with_sha256() {
|
|||||||
assert_eq!(store_path1, store_path2);
|
assert_eq!(store_path1, store_path2);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn path_deterministic() {
|
fn path_deterministic() {
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
let test_file = temp_dir.path().join("deterministic.txt");
|
let test_file = temp_dir.path().join("deterministic.txt");
|
||||||
@@ -261,7 +259,7 @@ fn path_deterministic() {
|
|||||||
assert_eq!(result1, result2);
|
assert_eq!(result1, result2);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn read_file_type_regular_file() {
|
fn read_file_type_regular_file() {
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
let test_file = temp_dir.path().join("test.txt");
|
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()));
|
assert_eq!(eval(&expr), Value::String("regular".to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn read_file_type_directory() {
|
fn read_file_type_directory() {
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
let test_dir = temp_dir.path().join("testdir");
|
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()));
|
assert_eq!(eval(&expr), Value::String("directory".to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn read_file_type_symlink() {
|
fn read_file_type_symlink() {
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
let target = temp_dir.path().join("target.txt");
|
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() {
|
fn read_dir_basic() {
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
let test_dir = temp_dir.path().join("readdir_test");
|
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() {
|
fn read_dir_empty() {
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
let test_dir = temp_dir.path().join("empty_dir");
|
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() {
|
fn read_dir_nonexistent_fails() {
|
||||||
let expr = r#"builtins.readDir "/nonexistent/directory""#;
|
let expr = r#"builtins.readDir "/nonexistent/directory""#;
|
||||||
let result = eval_result(expr);
|
let result = eval_result(expr);
|
||||||
@@ -355,7 +353,7 @@ fn read_dir_nonexistent_fails() {
|
|||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn read_dir_on_file_fails() {
|
fn read_dir_on_file_fails() {
|
||||||
let temp_dir = tempfile::tempdir().unwrap();
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
let test_file = temp_dir.path().join("test.txt");
|
let test_file = temp_dir.path().join("test.txt");
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
#![allow(non_snake_case)]
|
#![allow(non_snake_case)]
|
||||||
|
|
||||||
mod utils;
|
|
||||||
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use nix_js::context::Context;
|
use nix_js::context::Context;
|
||||||
@@ -9,7 +7,7 @@ use nix_js::error::Source;
|
|||||||
use nix_js::value::Value;
|
use nix_js::value::Value;
|
||||||
|
|
||||||
fn get_lang_dir() -> PathBuf {
|
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> {
|
fn eval_file(name: &str) -> Result<(Value, Source), String> {
|
||||||
@@ -23,7 +21,7 @@ fn eval_file(name: &str) -> Result<(Value, Source), String> {
|
|||||||
ty: nix_js::error::SourceType::File(nix_path.into()),
|
ty: nix_js::error::SourceType::File(nix_path.into()),
|
||||||
src: expr.into(),
|
src: expr.into(),
|
||||||
};
|
};
|
||||||
ctx.eval_code(source.clone())
|
ctx.eval_deep(source.clone())
|
||||||
.map(|val| (val, source))
|
.map(|val| (val, source))
|
||||||
.map_err(|e| e.to_string())
|
.map_err(|e| e.to_string())
|
||||||
}
|
}
|
||||||
@@ -44,7 +42,7 @@ fn format_value(value: &Value) -> String {
|
|||||||
macro_rules! eval_okay_test {
|
macro_rules! eval_okay_test {
|
||||||
($(#[$attr:meta])* $name:ident$(, $pre:expr)?) => {
|
($(#[$attr:meta])* $name:ident$(, $pre:expr)?) => {
|
||||||
$(#[$attr])*
|
$(#[$attr])*
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn $name() {
|
fn $name() {
|
||||||
$(($pre)();)?
|
$(($pre)();)?
|
||||||
let test_name = concat!("eval-okay-", stringify!($name))
|
let test_name = concat!("eval-okay-", stringify!($name))
|
||||||
@@ -76,7 +74,7 @@ macro_rules! eval_okay_test {
|
|||||||
|
|
||||||
macro_rules! eval_fail_test {
|
macro_rules! eval_fail_test {
|
||||||
($name:ident) => {
|
($name:ident) => {
|
||||||
#[test]
|
#[test_log::test]
|
||||||
fn $name() {
|
fn $name() {
|
||||||
let test_name = concat!("eval-fail-", stringify!($name))
|
let test_name = concat!("eval-fail-", stringify!($name))
|
||||||
.replace("_", "-")
|
.replace("_", "-")
|
||||||
@@ -122,10 +120,7 @@ eval_okay_test!(concatmap);
|
|||||||
eval_okay_test!(concatstringssep);
|
eval_okay_test!(concatstringssep);
|
||||||
eval_okay_test!(context);
|
eval_okay_test!(context);
|
||||||
eval_okay_test!(context_introspection);
|
eval_okay_test!(context_introspection);
|
||||||
eval_okay_test!(
|
eval_okay_test!(convertHash);
|
||||||
#[ignore = "not implemented: convertHash"]
|
|
||||||
convertHash
|
|
||||||
);
|
|
||||||
eval_okay_test!(curpos);
|
eval_okay_test!(curpos);
|
||||||
eval_okay_test!(deepseq);
|
eval_okay_test!(deepseq);
|
||||||
eval_okay_test!(delayed_with);
|
eval_okay_test!(delayed_with);
|
||||||
@@ -152,39 +147,24 @@ eval_okay_test!(foldlStrict_lazy_elements);
|
|||||||
eval_okay_test!(foldlStrict_lazy_initial_accumulator);
|
eval_okay_test!(foldlStrict_lazy_initial_accumulator);
|
||||||
eval_okay_test!(fromjson);
|
eval_okay_test!(fromjson);
|
||||||
eval_okay_test!(fromjson_escapes);
|
eval_okay_test!(fromjson_escapes);
|
||||||
|
eval_okay_test!(fromTOML);
|
||||||
eval_okay_test!(
|
eval_okay_test!(
|
||||||
#[ignore = "not implemented: fromTOML"]
|
#[ignore = "timestamps are not supported"]
|
||||||
fromTOML
|
|
||||||
);
|
|
||||||
eval_okay_test!(
|
|
||||||
#[ignore = "not implemented: fromTOML"]
|
|
||||||
fromTOML_timestamps
|
fromTOML_timestamps
|
||||||
);
|
);
|
||||||
eval_okay_test!(functionargs);
|
eval_okay_test!(functionargs);
|
||||||
eval_okay_test!(
|
eval_okay_test!(hashfile);
|
||||||
#[ignore = "not implemented: hashFile"]
|
eval_okay_test!(hashstring);
|
||||||
hashfile
|
|
||||||
);
|
|
||||||
eval_okay_test!(
|
|
||||||
#[ignore = "not implemented: hashString"]
|
|
||||||
hashstring
|
|
||||||
);
|
|
||||||
eval_okay_test!(getattrpos);
|
eval_okay_test!(getattrpos);
|
||||||
eval_okay_test!(getattrpos_functionargs);
|
eval_okay_test!(getattrpos_functionargs);
|
||||||
eval_okay_test!(getattrpos_undefined);
|
eval_okay_test!(getattrpos_undefined);
|
||||||
eval_okay_test!(getenv, || {
|
eval_okay_test!(getenv, || {
|
||||||
unsafe { std::env::set_var("TEST_VAR", "foo") };
|
unsafe { std::env::set_var("TEST_VAR", "foo") };
|
||||||
});
|
});
|
||||||
eval_okay_test!(
|
eval_okay_test!(groupBy);
|
||||||
#[ignore = "not implemented: hashString"]
|
|
||||||
groupBy
|
|
||||||
);
|
|
||||||
eval_okay_test!(r#if);
|
eval_okay_test!(r#if);
|
||||||
eval_okay_test!(ind_string);
|
eval_okay_test!(ind_string);
|
||||||
eval_okay_test!(
|
eval_okay_test!(import);
|
||||||
#[ignore = "not implemented: scopedImport"]
|
|
||||||
import
|
|
||||||
);
|
|
||||||
eval_okay_test!(inherit_attr_pos);
|
eval_okay_test!(inherit_attr_pos);
|
||||||
eval_okay_test!(
|
eval_okay_test!(
|
||||||
#[ignore = "__overrides is not supported"]
|
#[ignore = "__overrides is not supported"]
|
||||||
@@ -255,22 +235,13 @@ eval_okay_test!(
|
|||||||
tail_call_1
|
tail_call_1
|
||||||
);
|
);
|
||||||
eval_okay_test!(tojson);
|
eval_okay_test!(tojson);
|
||||||
eval_okay_test!(
|
eval_okay_test!(toxml);
|
||||||
#[ignore = "not implemented: toXML"]
|
eval_okay_test!(toxml2);
|
||||||
toxml
|
|
||||||
);
|
|
||||||
eval_okay_test!(
|
|
||||||
#[ignore = "not implemented: toXML"]
|
|
||||||
toxml2
|
|
||||||
);
|
|
||||||
eval_okay_test!(tryeval);
|
eval_okay_test!(tryeval);
|
||||||
eval_okay_test!(types);
|
eval_okay_test!(types);
|
||||||
eval_okay_test!(versions);
|
eval_okay_test!(versions);
|
||||||
eval_okay_test!(with);
|
eval_okay_test!(with);
|
||||||
eval_okay_test!(
|
eval_okay_test!(zipAttrsWith);
|
||||||
#[ignore = "not implemented: hashString"]
|
|
||||||
zipAttrsWith
|
|
||||||
);
|
|
||||||
|
|
||||||
eval_fail_test!(fail_abort);
|
eval_fail_test!(fail_abort);
|
||||||
eval_fail_test!(fail_addDrvOutputDependencies_empty_context);
|
eval_fail_test!(fail_addDrvOutputDependencies_empty_context);
|
||||||
BIN
nix-js/tests/tests/lang/binary-data
Normal file
BIN
nix-js/tests/tests/lang/binary-data
Normal file
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user