git.delta.rocks / jrsonnet / refs/commits / fb316679bd24

difftreelog

feat attrlist update is now lazy

ytruupusYaroslav Bolyukin2025-10-18parent: #b3fc719.patch.diff
in: trunk

1 file changed

modifiedcrates/nix-eval/src/lib.rsdiffbeforeafterboth
after · crates/nix-eval/src/lib.rs
1use std::borrow::Cow;2use std::cell::RefCell;3use std::ffi::{CStr, CString, c_char, c_int, c_uint, c_void};4use std::ptr::null_mut;5use std::sync::LazyLock;6use std::{collections::HashMap, path::PathBuf};7use std::{fmt, slice};89use anyhow::{Context, anyhow, bail};10use serde::Serialize;11use serde::de::DeserializeOwned;1213pub use anyhow::Result;14use tracing::instrument;1516use self::logging::nix_logging_cxx;17use self::nix_cxx::set_fetcher_setting;18use self::nix_raw::{19	BindingsBuilder as c_bindings_builder, EvalState as c_eval_state, GC_SUCCESS,20	GC_allow_register_threads, GC_get_stack_base, GC_register_my_thread, GC_stack_base,21	GC_thread_is_registered, GC_unregister_my_thread, ListBuilder as c_list_builder,22	Store as c_store, StorePath as c_store_path, alloc_value, bindings_builder_free,23	bindings_builder_insert, c_context, c_context_create, c_context_free, clear_err, err_code,24	err_info_msg, err_msg, eval_state_build, eval_state_builder_load, eval_state_builder_new,25	eval_state_builder_set_eval_setting, expr_eval_from_string, fetchers_settings,26	fetchers_settings_free, fetchers_settings_new, flake_lock, flake_lock_flags,27	flake_lock_flags_free, flake_lock_flags_new, flake_reference,28	flake_reference_and_fragment_from_string, flake_reference_parse_flags,29	flake_reference_parse_flags_free, flake_reference_parse_flags_new,30	flake_reference_parse_flags_set_base_directory, flake_settings, flake_settings_free,31	flake_settings_new, gc_now as gc_now_raw, get_attr_byname, get_attr_name_byidx, get_attrs_size,32	get_list_byidx, get_list_size, get_string, get_type, has_attr_byname, init_bool, init_int,33	init_string, libexpr_init, libstore_init, libutil_init, list_builder_free, list_builder_insert,34	locked_flake, locked_flake_free, locked_flake_get_output_attrs, make_attrs,35	make_bindings_builder, make_list, make_list_builder, realised_string, realised_string_free,36	realised_string_get_buffer_size, realised_string_get_buffer_start,37	realised_string_get_store_path, realised_string_get_store_path_count, set_err_msg, setting_set,38	state_free, store_open, store_parse_path, store_path_free, store_path_name, string_realise,39	value, value_call, value_decref, value_incref,40};4142// Contains macros helpers43pub mod logging;44#[doc(hidden)]45pub mod macros;46pub mod util;4748#[allow(49	non_upper_case_globals,50	non_camel_case_types,51	non_snake_case,52	dead_code53)]54mod nix_raw {55	include!(concat!(env!("OUT_DIR"), "/bindings.rs"));56}57#[cxx::bridge]58pub mod nix_cxx {59	unsafe extern "C++" {60		type nix_fetchers_settings;61		include!("nix-eval/src/lib.hh");6263		unsafe fn set_fetcher_setting(64			settings: *mut nix_fetchers_settings,65			setting: *const c_char,66			value: *const c_char,67		);68	}69}7071#[derive(Debug, PartialEq, Eq)]72pub enum NixType {73	Thunk,74	Int,75	Float,76	Bool,77	String,78	Path,79	Null,80	Attrs,81	List,82	Function,83	External,84}85impl NixType {86	fn from_int(c: c_uint) -> Self {87		match c {88			0 => Self::Thunk,89			1 => Self::Int,90			2 => Self::Float,91			3 => Self::Bool,92			4 => Self::String,93			5 => Self::Path,94			6 => Self::Null,95			7 => Self::Attrs,96			8 => Self::List,97			9 => Self::Function,98			10 => Self::External,99			_ => unreachable!("unknown nix type: {c}"),100		}101	}102}103104enum FunctorKind {105	Function,106	Functor,107}108109#[derive(Debug)]110#[repr(i32)]111pub enum NixErrorKind {112	Unknown = 1,113	Overflow = 2,114	Key = 3,115	Generic = 4,116}117impl NixErrorKind {118	fn from_int(v: c_int) -> Option<Self> {119		Some(match v {120			0 => return None,121			-1 => Self::Unknown,122			-2 => Self::Overflow,123			-3 => Self::Key,124			-4 => Self::Generic,125			_ => {126				debug_assert!(false, "unexpected nix error kind: {v}");127				Self::Unknown128			}129		})130	}131}132133pub fn gc_now() {134	unsafe { gc_now_raw() };135}136137pub fn gc_register_my_thread() {138	assert_eq!(unsafe { GC_thread_is_registered() }, 0);139140	let mut sb = GC_stack_base {141		mem_base: null_mut(),142	};143	let r = unsafe { GC_get_stack_base(&mut sb) };144	if r as u32 != GC_SUCCESS {145		panic!("failed to get thread stack base");146	}147	unsafe { GC_register_my_thread(&sb) };148}149pub fn gc_unregister_my_thread() {150	assert_eq!(unsafe { GC_thread_is_registered() }, 1);151152	unsafe { GC_unregister_my_thread() };153}154155pub struct ThreadRegisterGuard {}156impl ThreadRegisterGuard {157	#[allow(clippy::new_without_default)]158	pub fn new() -> Self {159		gc_register_my_thread();160		Self {}161	}162}163impl Drop for ThreadRegisterGuard {164	fn drop(&mut self) {165		gc_unregister_my_thread();166	}167}168169pub struct NixContext(*mut c_context);170impl NixContext {171	pub fn set_err(&mut self, err: NixErrorKind, msg: &CStr) {172		unsafe { set_err_msg(self.0, err as c_int, msg.as_ptr()) };173	}174	pub fn new() -> Self {175		let ctx = unsafe { c_context_create() };176		Self(ctx)177	}178	fn error_kind(&self) -> Option<NixErrorKind> {179		let code = unsafe { err_code(self.0) };180		NixErrorKind::from_int(code)181	}182	fn error<'t>(&self) -> Option<Cow<'t, str>> {183		if let NixErrorKind::Generic = self.error_kind()? {184			let mut err_out = String::new();185			unsafe {186				err_info_msg(187					null_mut(),188					self.0,189					Some(copy_nix_str),190					(&raw mut err_out).cast(),191				)192			};193			return Some(Cow::Owned(err_out));194		};195196		// TODO: Can throw error (resulting in panic) if unable to retrieve error. Should be able to resolve by passing context as a first argument,197		// but it looks ugly198		let str = unsafe { err_msg(null_mut(), self.0, null_mut()) };199		Some(unsafe { CStr::from_ptr(str) }.to_string_lossy())200	}201	fn clean_err(&mut self) {202		unsafe {203			clear_err(self.0);204		}205	}206207	fn bail_if_error(&self) -> Result<()> {208		if let Some(err) = self.error() {209			bail!("{err}");210		};211		Ok(())212	}213214	fn run_in_context<T>(&mut self, f: impl FnOnce(*mut c_context) -> T) -> Result<T> {215		self.clean_err();216		let o = f(self.0);217		self.bail_if_error()?;218		self.clean_err();219		Ok(o)220	}221}222223impl Default for NixContext {224	fn default() -> Self {225		Self::new()226	}227}228impl Drop for NixContext {229	fn drop(&mut self) {230		unsafe {231			c_context_free(self.0);232		}233	}234}235struct GlobalState {236	// Store should be valid as long as EvalState is valid237	#[allow(dead_code)]238	store: Store,239	state: EvalState,240}241impl GlobalState {242	fn new() -> Result<Self> {243		let mut ctx = NixContext::new();244		let store = ctx245			.run_in_context(|c| unsafe { store_open(c, c"auto".as_ptr(), null_mut()) })246			.map(Store)?;247248		let builder = ctx.run_in_context(|c| unsafe { eval_state_builder_new(c, store.0) })?;249		ctx.run_in_context(|c| unsafe { eval_state_builder_load(c, builder) })?;250		ctx.run_in_context(|c| unsafe {251			eval_state_builder_set_eval_setting(252				c,253				builder,254				c"lazy-trees".as_ptr(),255				c"true".as_ptr(),256			)257		})?;258		ctx.run_in_context(|c| unsafe {259			eval_state_builder_set_eval_setting(260				c,261				builder,262				c"lazy-locks".as_ptr(),263				c"true".as_ptr(),264			)265		})?;266		let state = ctx267			.run_in_context(|c| unsafe { eval_state_build(c, builder) })268			.map(EvalState)?;269270		Ok(Self { store, state })271	}272}273274struct ThreadState {275	ctx: NixContext,276}277impl ThreadState {278	fn new() -> Result<Self> {279		let ctx = NixContext::new();280281		Ok(Self { ctx })282	}283}284285static GLOBAL_STATE: LazyLock<GlobalState> =286	LazyLock::new(|| GlobalState::new().expect("global state init shouldn't fail"));287288thread_local! {289	static THREAD_STATE: RefCell<ThreadState> = RefCell::new(ThreadState::new().expect("thread state init shouldn't fail"));290}291fn with_default_context<T>(f: impl FnOnce(*mut c_context, *mut c_eval_state) -> T) -> Result<T> {292	let global = &GLOBAL_STATE.state;293	let (ctx, state) = THREAD_STATE.with_borrow_mut(|w| (w.ctx.0, global.0));294	let mut ctx = NixContext(ctx);295	let v = ctx.run_in_context(|c| f(c, state));296	// It is reused for thread297	std::mem::forget(ctx);298	v299}300301pub fn set_setting(s: &CStr, v: &CStr) -> Result<()> {302	with_default_context(|c, _| unsafe { setting_set(c, s.as_ptr(), v.as_ptr()) }).map(|_| ())303}304305pub struct FetchSettings(*mut fetchers_settings);306impl FetchSettings {307	pub fn new() -> Self {308		Self::try_new().expect("allocation should not fail")309	}310	fn try_new() -> Result<Self> {311		with_default_context(|c, _| unsafe { fetchers_settings_new(c) }).map(Self)312	}313	pub fn set(&mut self, setting: &CStr, value: &CStr) {314		unsafe {315			set_fetcher_setting(self.0.cast(), setting.as_ptr(), value.as_ptr());316		};317	}318}319unsafe impl Send for FetchSettings {}320unsafe impl Sync for FetchSettings {}321322impl Default for FetchSettings {323	fn default() -> Self {324		Self::new()325	}326}327328impl Drop for FetchSettings {329	fn drop(&mut self) {330		unsafe { fetchers_settings_free(self.0) };331	}332}333pub struct FlakeSettings(*mut flake_settings);334impl FlakeSettings {335	pub fn new() -> Result<Self> {336		with_default_context(|c, _| unsafe { flake_settings_new(c) }).map(Self)337	}338}339unsafe impl Send for FlakeSettings {}340unsafe impl Sync for FlakeSettings {}341impl Drop for FlakeSettings {342	fn drop(&mut self) {343		unsafe {344			flake_settings_free(self.0);345		}346	}347}348349pub struct FlakeReferenceParseFlags(*mut flake_reference_parse_flags);350impl FlakeReferenceParseFlags {351	pub fn new(settings: &FlakeSettings) -> Result<Self> {352		with_default_context(|c, _| unsafe { flake_reference_parse_flags_new(c, settings.0) })353			.map(Self)354	}355	pub fn set_base_dir(&mut self, dir: &str) -> Result<()> {356		with_default_context(|c, _| {357			unsafe {358				flake_reference_parse_flags_set_base_directory(359					c,360					self.0,361					dir.as_ptr().cast(),362					dir.len(),363				)364			};365		})366	}367}368impl Drop for FlakeReferenceParseFlags {369	fn drop(&mut self) {370		unsafe {371			flake_reference_parse_flags_free(self.0);372		}373	}374}375pub struct FlakeLockFlags(*mut flake_lock_flags);376impl FlakeLockFlags {377	pub fn new(settings: &FlakeSettings) -> Result<Self> {378		let o = with_default_context(|c, _| unsafe { flake_lock_flags_new(c, settings.0) })379			.map(Self)?;380		// with_default_context(|c, _| unsafe { flake_lock_flags_set_mode_virtual(c, o.0) })?;381382		Ok(o)383	}384}385impl Drop for FlakeLockFlags {386	fn drop(&mut self) {387		unsafe {388			flake_lock_flags_free(self.0);389		}390	}391}392393unsafe extern "C" fn copy_nix_str(start: *const c_char, n: c_uint, user_data: *mut c_void) {394	let s = unsafe { slice::from_raw_parts(start.cast::<u8>(), n as usize) };395	let s = std::str::from_utf8(s).expect("c string has invalid utf-8");396	unsafe { *user_data.cast::<String>() = s.to_owned() };397}398399struct Store(*mut c_store);400unsafe impl Send for Store {}401unsafe impl Sync for Store {}402403impl Store {404	fn parse_path(&self, path: &CStr) -> Result<StorePath> {405		with_default_context(|c, _| {406			StorePath(unsafe { store_parse_path(c, self.0, path.as_ptr()) })407		})408	}409}410411struct EvalState(*mut c_eval_state);412unsafe impl Send for EvalState {}413unsafe impl Sync for EvalState {}414415impl Drop for EvalState {416	fn drop(&mut self) {417		unsafe {418			state_free(self.0);419		}420	}421}422423pub struct FlakeReference(*mut flake_reference);424impl FlakeReference {425	#[instrument(name = "new-flake-reference", skip(flake, parse, fetch))]426	pub fn new(427		s: &str,428		flake: &FlakeSettings,429		parse: &FlakeReferenceParseFlags,430		fetch: &FetchSettings,431	) -> Result<(Self, String)> {432		let mut out = null_mut();433		let mut fragment = String::new();434		// let fetch_settings = fetcher_settings;435		with_default_context(|c, _| unsafe {436			flake_reference_and_fragment_from_string(437				c,438				fetch.0,439				flake.0,440				parse.0,441				s.as_ptr().cast(),442				s.len(),443				&mut out,444				Some(copy_nix_str),445				(&raw mut fragment).cast(),446			)447		})?;448		assert!(!out.is_null());449450		Ok((Self(out), fragment))451	}452	#[instrument(name = "lock-flake", skip(self, fetch, flake, lock))]453	pub fn lock(454		&mut self,455		fetch: &FetchSettings,456		flake: &FlakeSettings,457		lock: &FlakeLockFlags,458	) -> Result<LockedFlake> {459		with_default_context(|c, es| unsafe { flake_lock(c, fetch.0, flake.0, es, lock.0, self.0) })460			.map(LockedFlake)461	}462}463unsafe impl Send for FlakeReference {}464unsafe impl Sync for FlakeReference {}465466pub struct LockedFlake(*mut locked_flake);467impl LockedFlake {468	pub fn get_attrs(&self, settings: &mut FlakeSettings) -> Result<Value> {469		with_default_context(|c, es| unsafe {470			locked_flake_get_output_attrs(c, settings.0, es, self.0)471		})472		.map(Value)473	}474}475unsafe impl Send for LockedFlake {}476unsafe impl Sync for LockedFlake {}477impl Drop for LockedFlake {478	fn drop(&mut self) {479		unsafe {480			locked_flake_free(self.0);481		};482	}483}484485type FieldName = [u8; 64];486fn init_field_name(v: &str) -> FieldName {487	let mut f = [0; 64];488	assert!(v.len() < 64, "max field name is 63 chars");489	assert!(490		v.bytes().all(|v| v != 0),491		"nul bytes are unsupported in field name"492	);493	f[0..v.len()].copy_from_slice(v.as_bytes());494	f495}496497pub struct RealisedString(*mut realised_string);498impl fmt::Debug for RealisedString {499	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {500		self.as_str().fmt(f)501	}502}503504impl RealisedString {505	pub fn as_str(&self) -> &str {506		let len = unsafe { realised_string_get_buffer_size(self.0) };507		let data: *const u8 = unsafe { realised_string_get_buffer_start(self.0) }.cast();508		let data = unsafe { slice::from_raw_parts(data, len) };509		std::str::from_utf8(data).expect("non-utf8 strings not supported")510	}511	pub fn path_count(&self) -> usize {512		unsafe { realised_string_get_store_path_count(self.0) }513	}514	pub fn path(&self, i: usize) -> String {515		assert!(i < self.path_count());516		let path = unsafe { realised_string_get_store_path(self.0, i) };517		let mut err_out = String::new();518		unsafe { store_path_name(path, Some(copy_nix_str), (&raw mut err_out).cast()) };519		err_out520	}521}522523unsafe impl Send for RealisedString {}524impl Drop for RealisedString {525	fn drop(&mut self) {526		unsafe { realised_string_free(self.0) }527	}528}529530pub struct Value(*mut value);531532unsafe impl Send for Value {}533unsafe impl Sync for Value {}534535pub trait AsFieldName {536	fn as_field_name<T>(&self, v: impl FnOnce(FieldName) -> Result<T>) -> Result<T>;537	fn to_field_name(&self) -> Result<String>;538}539impl AsFieldName for Value {540	fn as_field_name<T>(&self, v: impl FnOnce(FieldName) -> Result<T>) -> Result<T> {541		let f = self.to_string()?;542		v(init_field_name(&f))543	}544	fn to_field_name(&self) -> Result<String> {545		self.to_string()546	}547}548impl<E> AsFieldName for E549where550	E: AsRef<str>,551{552	fn as_field_name<T>(&self, v: impl FnOnce(FieldName) -> Result<T>) -> Result<T> {553		let f = self.as_ref();554		v(init_field_name(f))555	}556	fn to_field_name(&self) -> Result<String> {557		Ok(self.as_ref().to_owned())558	}559}560561struct AttrsBuilder(*mut c_bindings_builder);562impl AttrsBuilder {563	fn new(capacity: usize) -> Self {564		with_default_context(|c, es| unsafe { make_bindings_builder(c, es, capacity) })565			.map(Self)566			.expect("alloc should not fail")567	}568	fn insert(&mut self, k: &impl AsFieldName, v: Value) {569		k.as_field_name(|name| {570			with_default_context(|c, _| unsafe {571				bindings_builder_insert(c, self.0, name.as_ptr().cast(), v.0);572				// bindings_builder_insert doesn't do incref573			})574		})575		.expect("builder insert shouldn't fail");576	}577}578impl Drop for AttrsBuilder {579	fn drop(&mut self) {580		unsafe { bindings_builder_free(self.0) };581	}582}583584struct ListBuilder(*mut c_list_builder, c_uint);585impl ListBuilder {586	fn new(capacity: usize) -> Self {587		with_default_context(|c, es| unsafe { make_list_builder(c, es, capacity) })588			.map(|l| Self(l, 0))589			.expect("alloc should not fail")590	}591}592impl ListBuilder {593	fn push(&mut self, v: Value) {594		with_default_context(|c, _| unsafe {595			list_builder_insert(596				c,597				self.0,598				{599					let v = self.1;600					self.1 += 1;601					v602				},603				v.0,604			)605		})606		.expect("list insert shouldn't fail");607	}608}609impl Drop for ListBuilder {610	fn drop(&mut self) {611		unsafe { list_builder_free(self.0) };612	}613}614615impl Value {616	pub fn new_attrs(v: HashMap<&str, Value>) -> Self {617		let out = Self::new_uninit();618		let mut b = AttrsBuilder::new(v.len());619		for (k, v) in v {620			b.insert(&k, v);621		}622		with_default_context(|c, _| unsafe { make_attrs(c, out.0, b.0) })623			.expect("attrs initialization should not fail");624625		out626	}627	fn new_list<T: Into<Self>>(v: Vec<T>) -> Self {628		let out = Self::new_uninit();629		let mut b = ListBuilder::new(v.len());630		for v in v {631			b.push(v.into());632		}633		with_default_context(|c, _| unsafe { make_list(c, b.0, out.0) })634			.expect("list initialization should not fail");635636		out637	}638	fn new_uninit() -> Self {639		let out = with_default_context(|c, es| unsafe { alloc_value(c, es) })640			.expect("value allocation should not fail");641		Self(out)642	}643	pub fn new_str(v: &str) -> Self {644		let s = CString::new(v).expect("string should not contain NULs");645		let out = Self::new_uninit();646		// String is copied, `s` is free to be dropped647		with_default_context(|c, _| unsafe { init_string(c, out.0, s.as_ptr()) })648			.expect("string initialization should not fail");649		out650	}651	pub fn new_int(i: i64) -> Self {652		let out = Self::new_uninit();653		with_default_context(|c, _| unsafe { init_int(c, out.0, i) })654			.expect("int initialization should not fail");655		out656	}657	pub fn new_bool(v: bool) -> Self {658		let out = Self::new_uninit();659		with_default_context(|c, _| unsafe { init_bool(c, out.0, v) })660			.expect("bool initialization should not fail");661		out662	}663	// TODO: As far as I can see, there is no way to get Thunks from nix public C api, so this function is useless664	// fn force(&mut self, st: &mut EvalState) -> Result<()> {665	// 	with_default_context(|c, _| unsafe { value_force(c, st.0, self.0) })?;666	// 	Ok(())667	// }668	pub fn type_of(&self) -> NixType {669		let ty = with_default_context(|c, _| unsafe { get_type(c, self.0) })670			.expect("get_type should not fail");671		NixType::from_int(ty)672	}673	fn builtin_to_string(&self) -> Result<Self> {674		let builtin = Self::eval("builtins.toString")?;675		builtin.call(self.clone())676	}677	pub fn to_string(&self) -> Result<String> {678		let mut str_out = String::new();679		with_default_context(|c, _| unsafe {680			get_string(c, self.0, Some(copy_nix_str), (&raw mut str_out).cast())681		})?;682683		Ok(str_out)684	}685	pub fn to_realised_string(&self) -> Result<RealisedString> {686		with_default_context(|c, es| unsafe { string_realise(c, es, self.0, false) })687			.map(RealisedString)688689		// let store_paths = unsafe { nix_raw::realised_string_get_store_path_count(str) };690		// for i in 0..store_paths {691		// 	let store_path = unsafe { nix_raw::realised_string_get_store_path(str, i) };692		// 	nix_raw::store_path_name(store_path, callback, user_data);693		// }694		// dbg!(store_paths);695		// todo!();696	}697698	pub fn has_field(&self, field: &str) -> Result<bool> {699		let f = init_field_name(field);700		with_default_context(|c, es| unsafe { has_attr_byname(c, self.0, es, f.as_ptr().cast()) })701	}702	// pub fn derivation_path(&self) {703	// 	nix_raw::real704	// }705	pub fn list_fields(&self) -> Result<Vec<String>> {706		if !matches!(self.type_of(), NixType::Attrs) {707			bail!("invalid type: expected attrs");708		}709710		let len = with_default_context(|c, _| unsafe { get_attrs_size(c, self.0) })?;711		let mut out = Vec::with_capacity(len as usize);712713		for i in 0..len {714			let name =715				with_default_context(|c, es| unsafe { get_attr_name_byidx(c, self.0, es, i) })?;716			let c = unsafe { CStr::from_ptr(name) };717			out.push(c.to_str().expect("nix field names are utf-8").to_owned());718		}719		Ok(out)720	}721	pub fn get_elem(&self, v: usize) -> Result<Self> {722		if !matches!(self.type_of(), NixType::List) {723			bail!("invalid type: expected list");724		}725		let len = with_default_context(|c, _| unsafe { get_list_size(c, self.0) })? as usize;726		if v >= len {727			bail!("oob list get: {v} >= {len}");728		}729730		with_default_context(|c, es| unsafe { get_list_byidx(c, self.0, es, v as u32) }).map(Self)731	}732	pub fn attrs_update(self, other: Value/*, ignore_errors: bool*/) -> Result<Self> {733		let attrs_update_fn = Self::eval("a: b: a // b")?;734735		attrs_update_fn.call(self)?.call(other).context("attrs update")736	}737	pub fn get_field(&self, name: impl AsFieldName) -> Result<Self> {738		if !matches!(self.type_of(), NixType::Attrs) {739			bail!("invalid type: expected attrs");740		}741742		name.as_field_name(|name| {743			with_default_context(|c, es| unsafe {744				get_attr_byname(c, self.0, es, name.as_ptr().cast())745			})746			.map(Self)747		})748		.with_context(|| format!("getting field {:?}", name.to_field_name()))749	}750	pub fn call(&self, v: Value) -> Result<Self> {751		let kind = self752			.functor_kind()753			.ok_or_else(|| anyhow!("can only call function or functor"))?;754755		let function = match kind {756			FunctorKind::Function => self.clone(),757			FunctorKind::Functor => {758				let f = self759					.get_field("__functor")760					.context("getting functor value")?;761				assert_eq!(762					f.type_of(),763					NixType::Function,764					"invalid functor encountered"765				);766				f767			}768		};769770		let out = Value::new_uninit();771		with_default_context(|c, es| unsafe { value_call(c, es, function.0, v.0, out.0) })?;772773		Ok(out)774	}775	pub fn eval(v: &str) -> Result<Self> {776		let s = CString::new(v).expect("expression shouldn't have internal NULs");777		let out = Self::new_uninit();778		with_default_context(|c, es| unsafe {779			expr_eval_from_string(c, es, s.as_ptr(), c"/root".as_ptr(), out.0)780		})?;781		Ok(out)782	}783	pub fn build(&self, output: &str) -> Result<PathBuf> {784		if !self.is_derivation() {785			bail!("expected derivation to build")786		}787		let output_name = self788			.get_field("outputName")789			.context("getting output name field")?790			.to_string()?;791		let v = if output_name != output {792			let out = self.get_field(output).context("getting target output")?;793			if !out.is_derivation() {794				bail!("unknown output: {output}");795			}796			out797		} else {798			self.clone()799		};800		// to_string here blocks until the path is built801		let s = v.builtin_to_string()?;802		let rs = s.to_realised_string()?;803		let drv_path = rs.as_str().to_owned();804		Ok(PathBuf::from(drv_path))805	}806	pub fn as_json<T: DeserializeOwned>(&self) -> Result<T> {807		let to_json = Self::eval("builtins.toJSON")?;808		let s = to_json.call(self.clone())?.to_string()?;809		Ok(serde_json::from_str(&s)?)810	}811	pub fn serialized<T: Serialize>(v: &T) -> Result<Self> {812		Self::eval(&nixlike::serialize(v)?)813	}814815	// Convert to string/evaluate derivations/etc816	// fn to_string_weak(&self) -> Result<String> {817	// 	// TODO: For now, it works exactly like to_string, see the comment for fn force()818	// 	self.to_string()819	// }820821	fn is_derivation(&self) -> bool {822		if !matches!(self.type_of(), NixType::Attrs) {823			return false;824		}825		let Some(ty) = self.get_field("type").ok() else {826			return false;827		};828		matches!(ty.to_string().as_deref(), Ok("derivation"))829	}830	fn functor_kind(&self) -> Option<FunctorKind> {831		match self.type_of() {832			NixType::Attrs => self833				.has_field("__functor")834				.expect("has_field shouldn't fail for attrs")835				.then_some(FunctorKind::Functor),836			NixType::Function => Some(FunctorKind::Function),837			_ => None,838		}839	}840	pub fn is_function(&self) -> bool {841		self.functor_kind().is_some()842	}843}844845impl From<String> for Value {846	fn from(value: String) -> Self {847		Value::new_str(&value)848	}849}850impl From<bool> for Value {851	fn from(value: bool) -> Self {852		Value::new_bool(value)853	}854}855impl From<&str> for Value {856	fn from(value: &str) -> Self {857		Value::new_str(value)858	}859}860impl<T> From<Vec<T>> for Value861where862	T: Into<Value>,863{864	fn from(value: Vec<T>) -> Self {865		Value::new_list(value)866	}867}868869impl Clone for Value {870	fn clone(&self) -> Self {871		with_default_context(|c, _| unsafe { value_incref(c, self.0) })872			.expect("value incref should not fail");873		Self(self.0)874	}875}876impl Drop for Value {877	fn drop(&mut self) {878		with_default_context(|c, _| unsafe { value_decref(c, self.0) })879			.expect("value drop should not fail");880	}881}882883pub fn init_libraries() {884	unsafe { GC_allow_register_threads() };885886	let mut ctx = NixContext::new();887	ctx.run_in_context(|c| unsafe { libutil_init(c) })888		.expect("util init should not fail");889	ctx.run_in_context(|c| unsafe { libstore_init(c) })890		.expect("store init should not fail");891	ctx.run_in_context(|c| unsafe { libexpr_init(c) })892		.expect("expr init should not fail");893894	nix_logging_cxx::apply_tracing_logger();895}896897struct StorePath(*mut c_store_path);898impl StorePath {}899900impl Drop for StorePath {901	fn drop(&mut self) {902		unsafe { store_path_free(self.0) }903	}904}905906#[test_log::test]907fn test_native() -> Result<()> {908	init_libraries();909910	let mut fetch_settings = FetchSettings::new();911	fetch_settings.set(c"warn-dirty", c"false");912913	let manifest = format!("git+file://{}/../../", env!("CARGO_MANIFEST_DIR"));914	let flake = FlakeSettings::new()?;915	let parse = FlakeReferenceParseFlags::new(&flake)?;916	let (mut r, _) = FlakeReference::new(&manifest, &flake, &parse, &fetch_settings)?;917	let lock = FlakeLockFlags::new(&flake)?;918	let locked = r.lock(&fetch_settings, &flake, &lock)?;919	let attrs = locked.get_attrs(&mut FlakeSettings::new()?)?;920921	let builtins = Value::eval("builtins")?;922	assert_eq!(builtins.type_of(), NixType::Attrs);923924	assert_eq!(attrs.type_of(), NixType::Attrs);925	let test_data = nix_go!(attrs.testData);926927	let test_string: String = nix_go_json!(test_data.testString);928	assert_eq!(test_string, "hello");929930	let s = nix_go!(attrs.packages["x86_64-linux"].fleet.drvPath);931	let s = CString::new(s.to_string()?).expect("path str is cstring");932933	let nix_ctx = NixContext::new();934	let store = GLOBAL_STATE.store.parse_path(s.as_c_str())?;935936	// nix_raw::store_get_fs_closure(1);937938	Ok(())939}940941// pub struct GcAlloc;942// unsafe impl GlobalAlloc for GcAlloc {943// 	unsafe fn alloc(&self, l: Layout) -> *mut u8 {944// 		let ptr = unsafe { GC_malloc(l.size()) };945// 		ptr.cast()946// 	}947// 	unsafe fn dealloc(&self, ptr: *mut u8, _: Layout) {948// 		// unsafe { GC_free(ptr.cast()) };949// 	}950//951// 	unsafe fn realloc(&self, ptr: *mut u8, _: Layout, new_size: usize) -> *mut u8 {952// 		let ptr = unsafe { GC_realloc(ptr.cast(), new_size) };953// 		ptr.cast()954// 	}955// }956//957// #[global_allocator]958// static GC: GcAlloc = GcAlloc;