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

difftreelog

feat list building

wrvutuluYaroslav Bolyukin2025-10-18parent: #d581a02.patch.diff
in: trunk

1 file changed

modifiedcrates/nix-eval/src/lib.rsdiffbeforeafterboth
before · crates/nix-eval/src/lib.rs
1use std::alloc::{GlobalAlloc, Layout};2use std::borrow::Cow;3use std::cell::RefCell;4use std::ffi::{CStr, CString, c_char, c_int, c_uint, c_void};5use std::ptr::null_mut;6use std::sync::LazyLock;7use std::{collections::HashMap, path::PathBuf};8use std::{fmt, slice};910use anyhow::{Context, anyhow, bail};11use serde::Serialize;12use serde::de::DeserializeOwned;1314pub use anyhow::Result;15use tracing::instrument;1617use self::logging::nix_logging_cxx;18use self::nix_cxx::set_fetcher_setting;19use self::nix_raw::{20	BindingsBuilder as c_bindings_builder, EvalState as c_eval_state, GC_SUCCESS,21	GC_allow_register_threads, GC_get_stack_base, GC_register_my_thread, GC_stack_base,22	GC_thread_is_registered, GC_unregister_my_thread, ListBuilder as c_list_builder,23	Store as c_store, StorePath as c_store_path, alloc_value, bindings_builder_free,24	bindings_builder_insert, c_context, c_context_create, c_context_free, clear_err, err_code,25	err_info_msg, err_msg, eval_state_build, eval_state_builder_load, eval_state_builder_new,26	eval_state_builder_set_eval_setting, expr_eval_from_string, fetchers_settings,27	fetchers_settings_free, fetchers_settings_new, flake_lock, flake_lock_flags,28	flake_lock_flags_free, flake_lock_flags_new, flake_reference,29	flake_reference_and_fragment_from_string, flake_reference_parse_flags,30	flake_reference_parse_flags_free, flake_reference_parse_flags_new,31	flake_reference_parse_flags_set_base_directory, flake_settings, flake_settings_free,32	flake_settings_new, gc_now as gc_now_raw, get_attr_byname, get_attr_name_byidx, get_attrs_size,33	get_list_byidx, get_list_size, get_string, get_type, has_attr_byname, init_bool, init_int,34	init_string, libexpr_init, libstore_init, libutil_init, list_builder_free, list_builder_insert,35	locked_flake, locked_flake_free, locked_flake_get_output_attrs, make_attrs,36	make_bindings_builder, make_list, make_list_builder, realised_string, realised_string_free,37	realised_string_get_buffer_size, realised_string_get_buffer_start,38	realised_string_get_store_path, realised_string_get_store_path_count, set_err_msg, setting_set,39	state_free, store_open, store_parse_path, store_path_free, store_path_name, string_realise,40	value, value_call, value_decref, value_incref,41};4243// Contains macros helpers44pub mod logging;45#[doc(hidden)]46pub mod macros;47pub mod util;4849#[allow(50	non_upper_case_globals,51	non_camel_case_types,52	non_snake_case,53	dead_code54)]55mod nix_raw {56	include!(concat!(env!("OUT_DIR"), "/bindings.rs"));57}58#[cxx::bridge]59pub mod nix_cxx {60	unsafe extern "C++" {61		type nix_fetchers_settings;62		include!("nix-eval/src/lib.hh");6364		unsafe fn set_fetcher_setting(65			settings: *mut nix_fetchers_settings,66			setting: *const c_char,67			value: *const c_char,68		);69	}70}7172#[derive(Debug, PartialEq, Eq)]73pub enum NixType {74	Thunk,75	Int,76	Float,77	Bool,78	String,79	Path,80	Null,81	Attrs,82	List,83	Function,84	External,85}86impl NixType {87	fn from_int(c: c_uint) -> Self {88		match c {89			0 => Self::Thunk,90			1 => Self::Int,91			2 => Self::Float,92			3 => Self::Bool,93			4 => Self::String,94			5 => Self::Path,95			6 => Self::Null,96			7 => Self::Attrs,97			8 => Self::List,98			9 => Self::Function,99			10 => Self::External,100			_ => unreachable!("unknown nix type: {c}"),101		}102	}103}104105enum FunctorKind {106	Function,107	Functor,108}109110#[derive(Debug)]111#[repr(i32)]112pub enum NixErrorKind {113	Unknown = 1,114	Overflow = 2,115	Key = 3,116	Generic = 4,117}118impl NixErrorKind {119	fn from_int(v: c_int) -> Option<Self> {120		Some(match v {121			0 => return None,122			-1 => Self::Unknown,123			-2 => Self::Overflow,124			-3 => Self::Key,125			-4 => Self::Generic,126			_ => {127				debug_assert!(false, "unexpected nix error kind: {v}");128				Self::Unknown129			}130		})131	}132}133134pub fn gc_now() {135	unsafe { gc_now_raw() };136}137138pub fn gc_register_my_thread() {139	assert_eq!(unsafe { GC_thread_is_registered() }, 0);140141	let mut sb = GC_stack_base {142		mem_base: null_mut(),143	};144	let r = unsafe { GC_get_stack_base(&mut sb) };145	if r as u32 != GC_SUCCESS {146		panic!("failed to get thread stack base");147	}148	unsafe { GC_register_my_thread(&sb) };149}150pub fn gc_unregister_my_thread() {151	assert_eq!(unsafe { GC_thread_is_registered() }, 1);152153	unsafe { GC_unregister_my_thread() };154}155156pub struct ThreadRegisterGuard {}157impl ThreadRegisterGuard {158	#[allow(clippy::new_without_default)]159	pub fn new() -> Self {160		gc_register_my_thread();161		Self {}162	}163}164impl Drop for ThreadRegisterGuard {165	fn drop(&mut self) {166		gc_unregister_my_thread();167	}168}169170pub struct NixContext(*mut c_context);171impl NixContext {172	pub fn set_err(&mut self, err: NixErrorKind, msg: &CStr) {173		unsafe { set_err_msg(self.0, err as c_int, msg.as_ptr()) };174	}175	pub fn new() -> Self {176		let ctx = unsafe { c_context_create() };177		Self(ctx)178	}179	fn error_kind(&self) -> Option<NixErrorKind> {180		let code = unsafe { err_code(self.0) };181		NixErrorKind::from_int(code)182	}183	fn error<'t>(&self) -> Option<Cow<'t, str>> {184		if let NixErrorKind::Generic = self.error_kind()? {185			let mut err_out = String::new();186			unsafe {187				err_info_msg(188					null_mut(),189					self.0,190					Some(copy_nix_str),191					(&raw mut err_out).cast(),192				)193			};194			return Some(Cow::Owned(err_out));195		};196197		// TODO: Can throw error (resulting in panic) if unable to retrieve error. Should be able to resolve by passing context as a first argument,198		// but it looks ugly199		let str = unsafe { err_msg(null_mut(), self.0, null_mut()) };200		Some(unsafe { CStr::from_ptr(str) }.to_string_lossy())201	}202	fn clean_err(&mut self) {203		unsafe {204			clear_err(self.0);205		}206	}207208	fn bail_if_error(&self) -> Result<()> {209		if let Some(err) = self.error() {210			bail!("{err}");211		};212		Ok(())213	}214215	fn run_in_context<T>(&mut self, f: impl FnOnce(*mut c_context) -> T) -> Result<T> {216		self.clean_err();217		let o = f(self.0);218		self.bail_if_error()?;219		self.clean_err();220		Ok(o)221	}222}223224impl Default for NixContext {225	fn default() -> Self {226		Self::new()227	}228}229impl Drop for NixContext {230	fn drop(&mut self) {231		unsafe {232			c_context_free(self.0);233		}234	}235}236struct GlobalState {237	// Store should be valid as long as EvalState is valid238	#[allow(dead_code)]239	store: Store,240	state: EvalState,241}242impl GlobalState {243	fn new() -> Result<Self> {244		let mut ctx = NixContext::new();245		let store = ctx246			.run_in_context(|c| unsafe { store_open(c, c"auto".as_ptr(), null_mut()) })247			.map(Store)?;248249		let builder = ctx.run_in_context(|c| unsafe { eval_state_builder_new(c, store.0) })?;250		ctx.run_in_context(|c| unsafe { eval_state_builder_load(c, builder) })?;251		ctx.run_in_context(|c| unsafe {252			eval_state_builder_set_eval_setting(253				c,254				builder,255				c"lazy-trees".as_ptr(),256				c"true".as_ptr(),257			)258		})?;259		ctx.run_in_context(|c| unsafe {260			eval_state_builder_set_eval_setting(261				c,262				builder,263				c"lazy-locks".as_ptr(),264				c"true".as_ptr(),265			)266		})?;267		let state = ctx268			.run_in_context(|c| unsafe { eval_state_build(c, builder) })269			.map(EvalState)?;270271		Ok(Self { store, state })272	}273}274275struct ThreadState {276	ctx: NixContext,277}278impl ThreadState {279	fn new() -> Result<Self> {280		let ctx = NixContext::new();281282		Ok(Self { ctx })283	}284}285286static GLOBAL_STATE: LazyLock<GlobalState> =287	LazyLock::new(|| GlobalState::new().expect("global state init shouldn't fail"));288289thread_local! {290	static THREAD_STATE: RefCell<ThreadState> = RefCell::new(ThreadState::new().expect("thread state init shouldn't fail"));291}292fn with_default_context<T>(f: impl FnOnce(*mut c_context, *mut c_eval_state) -> T) -> Result<T> {293	let global = &GLOBAL_STATE.state;294	let (ctx, state) = THREAD_STATE.with_borrow_mut(|w| (w.ctx.0, global.0));295	let mut ctx = NixContext(ctx);296	let v = ctx.run_in_context(|c| f(c, state));297	// It is reused for thread298	std::mem::forget(ctx);299	v300}301302pub fn set_setting(s: &CStr, v: &CStr) -> Result<()> {303	with_default_context(|c, _| unsafe { setting_set(c, s.as_ptr(), v.as_ptr()) }).map(|_| ())304}305306pub struct FetchSettings(*mut fetchers_settings);307impl FetchSettings {308	pub fn new() -> Self {309		Self::try_new().expect("allocation should not fail")310	}311	fn try_new() -> Result<Self> {312		with_default_context(|c, _| unsafe { fetchers_settings_new(c) }).map(Self)313	}314	pub fn set(&mut self, setting: &CStr, value: &CStr) {315		unsafe {316			set_fetcher_setting(self.0.cast(), setting.as_ptr(), value.as_ptr());317		};318	}319}320unsafe impl Send for FetchSettings {}321unsafe impl Sync for FetchSettings {}322323impl Default for FetchSettings {324	fn default() -> Self {325		Self::new()326	}327}328329impl Drop for FetchSettings {330	fn drop(&mut self) {331		unsafe { fetchers_settings_free(self.0) };332	}333}334pub struct FlakeSettings(*mut flake_settings);335impl FlakeSettings {336	pub fn new() -> Result<Self> {337		with_default_context(|c, _| unsafe { flake_settings_new(c) }).map(Self)338	}339}340unsafe impl Send for FlakeSettings {}341unsafe impl Sync for FlakeSettings {}342impl Drop for FlakeSettings {343	fn drop(&mut self) {344		unsafe {345			flake_settings_free(self.0);346		}347	}348}349350pub struct FlakeReferenceParseFlags(*mut flake_reference_parse_flags);351impl FlakeReferenceParseFlags {352	pub fn new(settings: &FlakeSettings) -> Result<Self> {353		with_default_context(|c, _| unsafe { flake_reference_parse_flags_new(c, settings.0) })354			.map(Self)355	}356	pub fn set_base_dir(&mut self, dir: &str) -> Result<()> {357		with_default_context(|c, _| {358			unsafe {359				flake_reference_parse_flags_set_base_directory(360					c,361					self.0,362					dir.as_ptr().cast(),363					dir.len(),364				)365			};366		})367	}368}369impl Drop for FlakeReferenceParseFlags {370	fn drop(&mut self) {371		unsafe {372			flake_reference_parse_flags_free(self.0);373		}374	}375}376pub struct FlakeLockFlags(*mut flake_lock_flags);377impl FlakeLockFlags {378	pub fn new(settings: &FlakeSettings) -> Result<Self> {379		let o = with_default_context(|c, _| unsafe { flake_lock_flags_new(c, settings.0) })380			.map(Self)?;381		// with_default_context(|c, _| unsafe { flake_lock_flags_set_mode_virtual(c, o.0) })?;382383		Ok(o)384	}385}386impl Drop for FlakeLockFlags {387	fn drop(&mut self) {388		unsafe {389			flake_lock_flags_free(self.0);390		}391	}392}393394unsafe extern "C" fn copy_nix_str(start: *const c_char, n: c_uint, user_data: *mut c_void) {395	let s = unsafe { slice::from_raw_parts(start.cast::<u8>(), n as usize) };396	let s = std::str::from_utf8(s).expect("c string has invalid utf-8");397	unsafe { *user_data.cast::<String>() = s.to_owned() };398}399400struct Store(*mut c_store);401unsafe impl Send for Store {}402unsafe impl Sync for Store {}403404impl Store {405	fn parse_path(&self, path: &CStr) -> Result<StorePath> {406		with_default_context(|c, _| {407			StorePath(unsafe { store_parse_path(c, self.0, path.as_ptr()) })408		})409	}410}411412struct EvalState(*mut c_eval_state);413unsafe impl Send for EvalState {}414unsafe impl Sync for EvalState {}415416impl Drop for EvalState {417	fn drop(&mut self) {418		unsafe {419			state_free(self.0);420		}421	}422}423424pub struct FlakeReference(*mut flake_reference);425impl FlakeReference {426	#[instrument(name = "new-flake-reference", skip(flake, parse, fetch))]427	pub fn new(428		s: &str,429		flake: &FlakeSettings,430		parse: &FlakeReferenceParseFlags,431		fetch: &FetchSettings,432	) -> Result<(Self, String)> {433		let mut out = null_mut();434		let mut fragment = String::new();435		// let fetch_settings = fetcher_settings;436		with_default_context(|c, _| unsafe {437			flake_reference_and_fragment_from_string(438				c,439				fetch.0,440				flake.0,441				parse.0,442				s.as_ptr().cast(),443				s.len(),444				&mut out,445				Some(copy_nix_str),446				(&raw mut fragment).cast(),447			)448		})?;449		assert!(!out.is_null());450451		Ok((Self(out), fragment))452	}453	#[instrument(name = "lock-flake", skip(self, fetch, flake, lock))]454	pub fn lock(455		&mut self,456		fetch: &FetchSettings,457		flake: &FlakeSettings,458		lock: &FlakeLockFlags,459	) -> Result<LockedFlake> {460		with_default_context(|c, es| unsafe { flake_lock(c, fetch.0, flake.0, es, lock.0, self.0) })461			.map(LockedFlake)462	}463}464unsafe impl Send for FlakeReference {}465unsafe impl Sync for FlakeReference {}466467pub struct LockedFlake(*mut locked_flake);468impl LockedFlake {469	pub fn get_attrs(&self, settings: &mut FlakeSettings) -> Result<Value> {470		with_default_context(|c, es| unsafe {471			locked_flake_get_output_attrs(c, settings.0, es, self.0)472		})473		.map(Value)474	}475}476unsafe impl Send for LockedFlake {}477unsafe impl Sync for LockedFlake {}478impl Drop for LockedFlake {479	fn drop(&mut self) {480		unsafe {481			locked_flake_free(self.0);482		};483	}484}485486type FieldName = [u8; 64];487fn init_field_name(v: &str) -> FieldName {488	let mut f = [0; 64];489	assert!(v.len() < 64, "max field name is 63 chars");490	assert!(491		v.bytes().all(|v| v != 0),492		"nul bytes are unsupported in field name"493	);494	f[0..v.len()].copy_from_slice(v.as_bytes());495	f496}497498pub struct RealisedString(*mut realised_string);499impl fmt::Debug for RealisedString {500	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {501		self.as_str().fmt(f)502	}503}504505impl RealisedString {506	pub fn as_str(&self) -> &str {507		let len = unsafe { realised_string_get_buffer_size(self.0) };508		let data: *const u8 = unsafe { realised_string_get_buffer_start(self.0) }.cast();509		let data = unsafe { slice::from_raw_parts(data, len) };510		std::str::from_utf8(data).expect("non-utf8 strings not supported")511	}512	pub fn path_count(&self) -> usize {513		unsafe { realised_string_get_store_path_count(self.0) }514	}515	pub fn path(&self, i: usize) -> String {516		assert!(i < self.path_count());517		let path = unsafe { realised_string_get_store_path(self.0, i) };518		let mut err_out = String::new();519		unsafe { store_path_name(path, Some(copy_nix_str), (&raw mut err_out).cast()) };520		err_out521	}522}523524unsafe impl Send for RealisedString {}525impl Drop for RealisedString {526	fn drop(&mut self) {527		unsafe { realised_string_free(self.0) }528	}529}530531pub struct Value(*mut value);532533unsafe impl Send for Value {}534unsafe impl Sync for Value {}535536pub trait AsFieldName {537	fn as_field_name<T>(&self, v: impl FnOnce(FieldName) -> Result<T>) -> Result<T>;538	fn to_field_name(&self) -> Result<String>;539}540impl AsFieldName for Value {541	fn as_field_name<T>(&self, v: impl FnOnce(FieldName) -> Result<T>) -> Result<T> {542		let f = self.to_string()?;543		v(init_field_name(&f))544	}545	fn to_field_name(&self) -> Result<String> {546		self.to_string()547	}548}549impl<E> AsFieldName for E550where551	E: AsRef<str>,552{553	fn as_field_name<T>(&self, v: impl FnOnce(FieldName) -> Result<T>) -> Result<T> {554		let f = self.as_ref();555		v(init_field_name(f))556	}557	fn to_field_name(&self) -> Result<String> {558		Ok(self.as_ref().to_owned())559	}560}561562struct AttrsBuilder(*mut c_bindings_builder);563impl AttrsBuilder {564	fn new(capacity: usize) -> Self {565		with_default_context(|c, es| unsafe { make_bindings_builder(c, es, capacity) })566			.map(Self)567			.expect("alloc should not fail")568	}569	fn insert(&mut self, k: &impl AsFieldName, v: Value) {570		k.as_field_name(|name| {571			with_default_context(|c, _| unsafe {572				bindings_builder_insert(c, self.0, name.as_ptr().cast(), v.0);573				// bindings_builder_insert doesn't do incref574			})575		})576		.expect("builder insert shouldn't fail");577	}578}579impl Drop for AttrsBuilder {580	fn drop(&mut self) {581		unsafe { bindings_builder_free(self.0) };582	}583}584585impl Value {586	pub fn new_attrs(v: HashMap<&str, Value>) -> Self {587		let out = Self::new_uninit();588		let mut b = AttrsBuilder::new(v.len());589		for (k, v) in v {590			b.insert(&k, v);591		}592		with_default_context(|c, _| unsafe { make_attrs(c, out.0, b.0) })593			.expect("attrs initialization should not fail");594595		out596	}597	fn new_list<T: Into<Self>>(v: Vec<T>) -> Self {598		todo!()599	}600	fn new_uninit() -> Self {601		let out = with_default_context(|c, es| unsafe { alloc_value(c, es) })602			.expect("value allocation should not fail");603		Self(out)604	}605	pub fn new_str(v: &str) -> Self {606		let s = CString::new(v).expect("string should not contain NULs");607		let out = Self::new_uninit();608		// String is copied, `s` is free to be dropped609		with_default_context(|c, _| unsafe { init_string(c, out.0, s.as_ptr()) })610			.expect("string initialization should not fail");611		out612	}613	pub fn new_int(i: i64) -> Self {614		let out = Self::new_uninit();615		with_default_context(|c, _| unsafe { init_int(c, out.0, i) })616			.expect("int initialization should not fail");617		out618	}619	pub fn new_bool(v: bool) -> Self {620		let out = Self::new_uninit();621		with_default_context(|c, _| unsafe { init_bool(c, out.0, v) })622			.expect("bool initialization should not fail");623		out624	}625	// TODO: As far as I can see, there is no way to get Thunks from nix public C api, so this function is useless626	// fn force(&mut self, st: &mut EvalState) -> Result<()> {627	// 	with_default_context(|c, _| unsafe { value_force(c, st.0, self.0) })?;628	// 	Ok(())629	// }630	pub fn type_of(&self) -> NixType {631		let ty = with_default_context(|c, _| unsafe { get_type(c, self.0) })632			.expect("get_type should not fail");633		NixType::from_int(ty)634	}635	fn builtin_to_string(&self) -> Result<Self> {636		let builtin = Self::eval("builtins.toString")?;637		builtin.call(self.clone())638	}639	pub fn to_string(&self) -> Result<String> {640		let mut str_out = String::new();641		with_default_context(|c, _| unsafe {642			get_string(c, self.0, Some(copy_nix_str), (&raw mut str_out).cast())643		})?;644645		Ok(str_out)646	}647	pub fn to_realised_string(&self) -> Result<RealisedString> {648		with_default_context(|c, es| unsafe { string_realise(c, es, self.0, false) })649			.map(RealisedString)650651		// let store_paths = unsafe { nix_raw::realised_string_get_store_path_count(str) };652		// for i in 0..store_paths {653		// 	let store_path = unsafe { nix_raw::realised_string_get_store_path(str, i) };654		// 	nix_raw::store_path_name(store_path, callback, user_data);655		// }656		// dbg!(store_paths);657		// todo!();658	}659660	pub fn has_field(&self, field: &str) -> Result<bool> {661		let f = init_field_name(field);662		with_default_context(|c, es| unsafe { has_attr_byname(c, self.0, es, f.as_ptr().cast()) })663	}664	// pub fn derivation_path(&self) {665	// 	nix_raw::real666	// }667	pub fn list_fields(&self) -> Result<Vec<String>> {668		if !matches!(self.type_of(), NixType::Attrs) {669			bail!("invalid type: expected attrs");670		}671672		let len = with_default_context(|c, _| unsafe { get_attrs_size(c, self.0) })?;673		let mut out = Vec::with_capacity(len as usize);674675		for i in 0..len {676			let name =677				with_default_context(|c, es| unsafe { get_attr_name_byidx(c, self.0, es, i) })?;678			let c = unsafe { CStr::from_ptr(name) };679			out.push(c.to_str().expect("nix field names are utf-8").to_owned());680		}681		Ok(out)682	}683	pub fn get_elem(&self, v: usize) -> Result<Self> {684		if !matches!(self.type_of(), NixType::List) {685			bail!("invalid type: expected list");686		}687		let len = with_default_context(|c, _| unsafe { get_list_size(c, self.0) })? as usize;688		if v >= len {689			bail!("oob list get: {v} >= {len}");690		}691692		with_default_context(|c, es| unsafe { get_list_byidx(c, self.0, es, v as u32) }).map(Self)693	}694	pub fn attrs_update(self, other: Value) -> Result<Self> {695		let a_fields = self.list_fields()?;696		let b_fields = other.list_fields()?;697		match (a_fields.len(), b_fields.len()) {698			(_, 0) => return Ok(self),699			(0, _) => return Ok(other),700			_ => {}701		}702		let mut out = HashMap::new();703		for f in a_fields.iter() {704			if b_fields.contains(f) {705				break;706			}707			out.insert(f.as_str(), self.get_field(f)?);708		}709		if out.is_empty() {710			// All fields from lhs are overriden by rhs711			return Ok(other);712		}713		for f in b_fields.iter() {714			out.insert(f.as_str(), other.get_field(f)?);715		}716		Ok(Self::new_attrs(out))717	}718	pub fn get_field(&self, name: impl AsFieldName) -> Result<Self> {719		if !matches!(self.type_of(), NixType::Attrs) {720			bail!("invalid type: expected attrs");721		}722723		name.as_field_name(|name| {724			with_default_context(|c, es| unsafe {725				get_attr_byname(c, self.0, es, name.as_ptr().cast())726			})727			.map(Self)728		})729		.with_context(|| format!("getting field {:?}", name.to_field_name()))730	}731	pub fn call(&self, v: Value) -> Result<Self> {732		let kind = self733			.functor_kind()734			.ok_or_else(|| anyhow!("can only call function or functor"))?;735736		let function = match kind {737			FunctorKind::Function => self.clone(),738			FunctorKind::Functor => {739				let f = self740					.get_field("__functor")741					.context("getting functor value")?;742				assert_eq!(743					f.type_of(),744					NixType::Function,745					"invalid functor encountered"746				);747				f748			}749		};750751		let out = Value::new_uninit();752		with_default_context(|c, es| unsafe { value_call(c, es, function.0, v.0, out.0) })?;753754		Ok(out)755	}756	pub fn eval(v: &str) -> Result<Self> {757		let s = CString::new(v).expect("expression shouldn't have internal NULs");758		let out = Self::new_uninit();759		with_default_context(|c, es| unsafe {760			expr_eval_from_string(c, es, s.as_ptr(), c"/root".as_ptr(), out.0)761		})?;762		Ok(out)763	}764	pub fn build(&self, output: &str) -> Result<PathBuf> {765		if !self.is_derivation() {766			bail!("expected derivation to build")767		}768		let output_name = self769			.get_field("outputName")770			.context("getting output name field")?771			.to_string()?;772		let v = if output_name != output {773			let out = self.get_field(output).context("getting target output")?;774			if !out.is_derivation() {775				bail!("unknown output: {output}");776			}777			out778		} else {779			self.clone()780		};781		// to_string here blocks until the path is built782		let s = v.builtin_to_string()?;783		let rs = s.to_realised_string()?;784		let drv_path = rs.as_str().to_owned();785		Ok(PathBuf::from(drv_path))786	}787	pub fn as_json<T: DeserializeOwned>(&self) -> Result<T> {788		let to_json = Self::eval("builtins.toJSON")?;789		let s = to_json.call(self.clone())?.to_string()?;790		Ok(serde_json::from_str(&s)?)791	}792	pub fn serialized<T: Serialize>(v: &T) -> Result<Self> {793		Self::eval(&nixlike::serialize(v)?)794	}795796	// Convert to string/evaluate derivations/etc797	// fn to_string_weak(&self) -> Result<String> {798	// 	// TODO: For now, it works exactly like to_string, see the comment for fn force()799	// 	self.to_string()800	// }801802	fn is_derivation(&self) -> bool {803		if !matches!(self.type_of(), NixType::Attrs) {804			return false;805		}806		let Some(ty) = self.get_field("type").ok() else {807			return false;808		};809		matches!(ty.to_string().as_deref(), Ok("derivation"))810	}811	fn functor_kind(&self) -> Option<FunctorKind> {812		match self.type_of() {813			NixType::Attrs => self814				.has_field("__functor")815				.expect("has_field shouldn't fail for attrs")816				.then_some(FunctorKind::Functor),817			NixType::Function => Some(FunctorKind::Function),818			_ => None,819		}820	}821	pub fn is_function(&self) -> bool {822		self.functor_kind().is_some()823	}824}825826impl From<String> for Value {827	fn from(value: String) -> Self {828		Value::new_str(&value)829	}830}831impl From<bool> for Value {832	fn from(value: bool) -> Self {833		Value::new_bool(value)834	}835}836impl From<&str> for Value {837	fn from(value: &str) -> Self {838		Value::new_str(value)839	}840}841impl<T> From<Vec<T>> for Value842where843	T: Into<Value>,844{845	fn from(value: Vec<T>) -> Self {846		Value::new_list(value)847	}848}849850impl Clone for Value {851	fn clone(&self) -> Self {852		with_default_context(|c, _| unsafe { value_incref(c, self.0) })853			.expect("value incref should not fail");854		Self(self.0)855	}856}857impl Drop for Value {858	fn drop(&mut self) {859		with_default_context(|c, _| unsafe { value_decref(c, self.0) })860			.expect("value drop should not fail");861	}862}863864pub fn init_libraries() {865	unsafe { GC_allow_register_threads() };866867	let mut ctx = NixContext::new();868	ctx.run_in_context(|c| unsafe { libutil_init(c) })869		.expect("util init should not fail");870	ctx.run_in_context(|c| unsafe { libstore_init(c) })871		.expect("store init should not fail");872	ctx.run_in_context(|c| unsafe { libexpr_init(c) })873		.expect("expr init should not fail");874875	nix_logging_cxx::apply_tracing_logger();876}877878struct StorePath(*mut c_store_path);879impl StorePath {}880881impl Drop for StorePath {882	fn drop(&mut self) {883		unsafe { store_path_free(self.0) }884	}885}886887#[test_log::test]888fn test_native() -> Result<()> {889	init_libraries();890891	let mut fetch_settings = FetchSettings::new();892	fetch_settings.set(c"warn-dirty", c"false");893894	let manifest = format!("git+file://{}/../../", env!("CARGO_MANIFEST_DIR"));895	let flake = FlakeSettings::new()?;896	let parse = FlakeReferenceParseFlags::new(&flake)?;897	let (mut r, _) = FlakeReference::new(&manifest, &flake, &parse, &fetch_settings)?;898	let lock = FlakeLockFlags::new(&flake)?;899	let locked = r.lock(&fetch_settings, &flake, &lock)?;900	let attrs = locked.get_attrs(&mut FlakeSettings::new()?)?;901902	let builtins = Value::eval("builtins")?;903	assert_eq!(builtins.type_of(), NixType::Attrs);904905	assert_eq!(attrs.type_of(), NixType::Attrs);906	let test_data = nix_go!(attrs.testData);907908	let test_string: String = nix_go_json!(test_data.testString);909	assert_eq!(test_string, "hello");910911	let s = nix_go!(attrs.packages["x86_64-linux"].fleet.drvPath);912	let s = CString::new(s.to_string()?).expect("path str is cstring");913914	let nix_ctx = NixContext::new();915	let store = GLOBAL_STATE.store.parse_path(s.as_c_str())?;916917	nix_raw::store_get_fs_closure(1);918919	Ok(())920}921922// pub struct GcAlloc;923// unsafe impl GlobalAlloc for GcAlloc {924// 	unsafe fn alloc(&self, l: Layout) -> *mut u8 {925// 		let ptr = unsafe { GC_malloc(l.size()) };926// 		ptr.cast()927// 	}928// 	unsafe fn dealloc(&self, ptr: *mut u8, _: Layout) {929// 		// unsafe { GC_free(ptr.cast()) };930// 	}931//932// 	unsafe fn realloc(&self, ptr: *mut u8, _: Layout, new_size: usize) -> *mut u8 {933// 		let ptr = unsafe { GC_realloc(ptr.cast(), new_size) };934// 		ptr.cast()935// 	}936// }937//938// #[global_allocator]939// static GC: GcAlloc = GcAlloc;