nix-bindings 0.2347.2

Rust binding for Nix, the build tool
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
#![warn(missing_docs)]
//! High-level, safe Rust bindings for the Nix build tool.
//!
//! This crate provides ergonomic and idiomatic Rust APIs for interacting
//! with Nix using its C API.
//!
//! # Quick Start
//!
//! ```no_run
//! #[cfg(feature = "store")]
//! {
//!   use std::sync::Arc;
//!
//!   use nix_bindings::{Context, EvalStateBuilder, Store};
//!
//!   fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let ctx = Arc::new(Context::new()?);
//!     let store = Arc::new(Store::open(&ctx, None)?);
//!     let state = EvalStateBuilder::new(&store)?.build()?;
//!
//!     let result = state.eval_from_string("1 + 2", "<eval>")?;
//!     println!("Result: {}", result.as_int()?);
//!
//!     Ok(())
//!   }
//! }
//! ```
//!
//! # Value Formatting
//!
//! Values support multiple formatting options:
//!
//! ```no_run
//! #[cfg(feature = "expr")]
//! {
//!   use std::sync::Arc;
//!
//!   use nix_bindings::{Context, EvalStateBuilder, Store};
//!   fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let ctx = Arc::new(Context::new()?);
//!     let store = Arc::new(Store::open(&ctx, None)?);
//!     let state = EvalStateBuilder::new(&store)?.build()?;
//!     let value = state.eval_from_string("\"hello world\"", "<eval>")?;
//!
//!     // Display formatting (user-friendly)
//!     println!("{}", value); // => hello world
//!
//!     // Debug formatting (with type info)
//!     println!("{:?}", value); // => Value::String("hello world")
//!
//!     // Nix syntax formatting
//!     println!("{}", value.to_nix_string()?); // => "hello world"
//!     //
//!     Ok(())
//!   }
//! }
//! ```

use std::fmt;
#[cfg(any(
  feature = "store",
  feature = "expr",
  feature = "flake",
  feature = "external",
  feature = "primop"
))]
use std::{
  ffi::{CStr, CString},
  ptr::NonNull,
};
#[cfg(any(
  feature = "expr",
  feature = "flake",
  feature = "external",
  feature = "primop"
))]
use std::{path::Path, sync::Arc};

#[cfg(feature = "expr")] mod attrs;
#[cfg(feature = "expr")] mod lists;

#[cfg(feature = "external")] pub mod external;
#[cfg(feature = "flake")] pub mod flake;
#[cfg(feature = "primop")] pub mod primop;

#[cfg(all(test, any(feature = "store", feature = "expr")))]
use serial_test::serial;

/// Raw, unsafe FFI bindings to the Nix C API.
///
/// # Warning
///
/// This module exposes the low-level, unsafe C bindings. Prefer using the safe,
/// high-level APIs provided by this crate. Use at your own risk.
#[doc(hidden)]
pub mod sys {
  pub use nix_bindings_sys::*;
}

/// Result type for Nix operations.
pub type Result<T> = std::result::Result<T, Error>;

/// Error types for Nix operations.
#[derive(Debug)]
pub enum Error {
  /// Unknown error from Nix C API.
  Unknown(String),

  /// Overflow error.
  Overflow,

  /// Key not found error.
  KeyNotFound(String),

  /// List index out of bounds.
  IndexOutOfBounds {
    /// The index that was requested.
    index:  usize,
    /// The actual length of the list.
    length: usize,
  },

  /// Nix evaluation error.
  EvalError(String),

  /// Invalid value type conversion.
  InvalidType {
    /// Expected type.
    expected: &'static str,
    /// Actual type.
    actual:   String,
  },
  /// Null pointer error.
  NullPointer,

  /// String conversion error.
  StringConversion(std::ffi::NulError),
}

impl fmt::Display for Error {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Error::Unknown(msg) => write!(f, "Unknown error: {msg}"),
      Error::Overflow => write!(f, "Overflow error"),
      Error::KeyNotFound(key) => write!(f, "Key not found: {key}"),
      Error::IndexOutOfBounds { index, length } => {
        write!(f, "Index out of bounds: index {index}, length {length}")
      },
      Error::EvalError(msg) => write!(f, "Evaluation error: {msg}"),
      Error::InvalidType { expected, actual } => {
        write!(f, "Invalid type: expected {expected}, got {actual}")
      },
      Error::NullPointer => write!(f, "Null pointer error"),
      Error::StringConversion(e) => write!(f, "String conversion error: {e}"),
    }
  }
}

impl std::error::Error for Error {}

impl From<std::ffi::NulError> for Error {
  fn from(e: std::ffi::NulError) -> Self {
    Error::StringConversion(e)
  }
}

#[cfg(feature = "store")] mod store;
#[cfg(feature = "store")]
pub use store::{Derivation, Store, StorePath};

/// Extract a string from a Nix context using a callback-based API.
///
/// Many Nix C API functions return strings via callbacks. This helper
/// makes that pattern ergonomic.
///
/// # Safety
///
/// `call` must invoke `callback` with a valid string pointer and length.
#[cfg(feature = "store")]
unsafe fn string_from_callback<F>(call: F) -> Option<String>
where
  F: FnOnce(sys::nix_get_string_callback, *mut std::os::raw::c_void),
{
  unsafe extern "C" fn collect(
    start: *const std::os::raw::c_char,
    n: std::os::raw::c_uint,
    user_data: *mut std::os::raw::c_void,
  ) {
    let result = unsafe { &mut *(user_data as *mut Option<String>) };
    if !start.is_null() {
      let bytes =
        unsafe { std::slice::from_raw_parts(start.cast::<u8>(), n as usize) };
      *result = std::str::from_utf8(bytes).ok().map(|s| s.to_owned());
    }
  }

  let mut result: Option<String> = None;
  let user_data = &mut result as *mut _ as *mut std::os::raw::c_void;
  call(Some(collect), user_data);
  result
}

/// Check a Nix error code and convert to `Result`, extracting the real
/// error message from the context.
#[cfg(feature = "store")]
fn check_err(ctx: *mut sys::nix_c_context, err: sys::nix_err) -> Result<()> {
  if err == sys::nix_err_NIX_OK {
    return Ok(());
  }

  // Extract the real error message from the context.
  // nix_err_msg returns a borrowed pointer valid until the next Nix call.
  // We must copy it to a String immediately.
  let msg = unsafe {
    let ptr = sys::nix_err_msg(std::ptr::null_mut(), ctx, std::ptr::null_mut());
    if ptr.is_null() {
      None
    } else {
      Some(CStr::from_ptr(ptr).to_string_lossy().into_owned())
    }
  };

  // For NIX_ERR_NIX_ERROR, also try to get the richer info message.
  let detail = if err == sys::nix_err_NIX_ERR_NIX_ERROR {
    unsafe {
      string_from_callback(|cb, ud| {
        sys::nix_err_info_msg(std::ptr::null_mut(), ctx, cb, ud);
      })
    }
  } else {
    None
  };

  let message = detail
    .or(msg)
    .unwrap_or_else(|| format!("Nix error code: {err}"));

  match err {
    sys::nix_err_NIX_ERR_UNKNOWN => Err(Error::Unknown(message)),
    sys::nix_err_NIX_ERR_OVERFLOW => Err(Error::Overflow),
    sys::nix_err_NIX_ERR_KEY => Err(Error::KeyNotFound(message)),
    sys::nix_err_NIX_ERR_NIX_ERROR => Err(Error::EvalError(message)),
    _ => Err(Error::Unknown(message)),
  }
}

/// Return the version of the Nix library being used.
///
/// This is a free function that does not require a context.
#[cfg(feature = "store")]
#[must_use]
pub fn nix_version() -> &'static str {
  // SAFETY: nix_version_get returns a pointer to a static string literal
  unsafe {
    let ptr = sys::nix_version_get();
    if ptr.is_null() {
      "<unknown>"
    } else {
      CStr::from_ptr(ptr).to_str().unwrap_or("<unknown>")
    }
  }
}

/// Verbosity level for Nix log output.
#[cfg(feature = "store")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verbosity {
  /// Only errors.
  Error,
  /// Warnings and errors.
  Warn,
  /// Notices, warnings, and errors.
  Notice,
  /// Info messages.
  Info,
  /// Talkative output.
  Talkative,
  /// Chatty output.
  Chatty,
  /// Debug output.
  Debug,
  /// Maximum verbosity (vomit).
  Vomit,
}

#[cfg(feature = "store")]
impl Verbosity {
  fn to_c(self) -> sys::nix_verbosity {
    match self {
      Verbosity::Error => sys::nix_verbosity_NIX_LVL_ERROR,
      Verbosity::Warn => sys::nix_verbosity_NIX_LVL_WARN,
      Verbosity::Notice => sys::nix_verbosity_NIX_LVL_NOTICE,
      Verbosity::Info => sys::nix_verbosity_NIX_LVL_INFO,
      Verbosity::Talkative => sys::nix_verbosity_NIX_LVL_TALKATIVE,
      Verbosity::Chatty => sys::nix_verbosity_NIX_LVL_CHATTY,
      Verbosity::Debug => sys::nix_verbosity_NIX_LVL_DEBUG,
      Verbosity::Vomit => sys::nix_verbosity_NIX_LVL_VOMIT,
    }
  }
}

/// Nix context for managing library state.
///
/// This is the root object for all Nix operations. It manages the lifetime
/// of the Nix C API context and provides automatic cleanup.
#[cfg(feature = "store")]
pub struct Context {
  inner: NonNull<sys::nix_c_context>,
}

#[cfg(feature = "store")]
impl Context {
  /// Create a new Nix context.
  ///
  /// This initializes the Nix C API context and the required libraries.
  ///
  /// # Errors
  ///
  /// Returns an error if context creation or library initialization fails.
  pub fn new() -> Result<Self> {
    // SAFETY: nix_c_context_create is safe to call
    let ctx_ptr = unsafe { sys::nix_c_context_create() };
    let inner = NonNull::new(ctx_ptr).ok_or(Error::NullPointer)?;

    let ctx = Context { inner };

    // Initialize required libraries
    unsafe {
      check_err(
        ctx.inner.as_ptr(),
        sys::nix_libutil_init(ctx.inner.as_ptr()),
      )?;
      check_err(
        ctx.inner.as_ptr(),
        sys::nix_libstore_init(ctx.inner.as_ptr()),
      )?;
      check_err(
        ctx.inner.as_ptr(),
        sys::nix_libexpr_init(ctx.inner.as_ptr()),
      )?;
    }

    Ok(ctx)
  }

  /// Set a global Nix configuration setting.
  ///
  /// Settings take effect for new [`EvalState`] instances. Use
  /// `"extra-<name>"` to append to an existing setting's value.
  ///
  /// # Errors
  ///
  /// Returns [`Error::KeyNotFound`] if the setting key is unknown.
  pub fn set_setting(&self, key: &str, value: &str) -> Result<()> {
    let key_c = CString::new(key)?;
    let value_c = CString::new(value)?;
    // SAFETY: context and strings are valid
    unsafe {
      check_err(
        self.inner.as_ptr(),
        sys::nix_setting_set(
          self.inner.as_ptr(),
          key_c.as_ptr(),
          value_c.as_ptr(),
        ),
      )
    }
  }

  /// Get the value of a global Nix configuration setting.
  ///
  /// # Errors
  ///
  /// Returns [`Error::KeyNotFound`] if the setting key is unknown.
  pub fn get_setting(&self, key: &str) -> Result<String> {
    let key_c = CString::new(key)?;
    let mut err_code = sys::nix_err_NIX_OK;
    // SAFETY: context and key are valid
    let result = unsafe {
      string_from_callback(|cb, ud| {
        err_code =
          sys::nix_setting_get(self.inner.as_ptr(), key_c.as_ptr(), cb, ud);
      })
    };
    check_err(self.inner.as_ptr(), err_code)?;
    result.ok_or_else(|| Error::KeyNotFound(key.to_string()))
  }

  /// Set the verbosity level for Nix log output.
  ///
  /// # Errors
  ///
  /// Returns an error if the verbosity level cannot be set.
  pub fn set_verbosity(&self, level: Verbosity) -> Result<()> {
    // SAFETY: context is valid
    unsafe {
      check_err(
        self.inner.as_ptr(),
        sys::nix_set_verbosity(self.inner.as_ptr(), level.to_c()),
      )
    }
  }

  /// Get the raw context pointer.
  ///
  /// # Safety
  ///
  /// The caller must ensure the pointer is used safely.
  pub(crate) unsafe fn as_ptr(&self) -> *mut sys::nix_c_context {
    self.inner.as_ptr()
  }
}

#[cfg(feature = "store")]
impl Drop for Context {
  fn drop(&mut self) {
    // SAFETY: We own the context and it's valid until drop
    unsafe {
      sys::nix_c_context_free(self.inner.as_ptr());
    }
  }
}

#[cfg(feature = "store")]
unsafe impl Send for Context {}

#[cfg(feature = "store")]
unsafe impl Sync for Context {}

/// Builder for Nix evaluation state.
///
/// This allows configuring the evaluation environment before creating
/// the evaluation state.
#[cfg(feature = "expr")]
pub struct EvalStateBuilder {
  inner:     NonNull<sys::nix_eval_state_builder>,
  store:     Arc<Store>,
  context:   Arc<Context>,
  skip_load: bool,
}

#[cfg(feature = "expr")]
impl EvalStateBuilder {
  /// Create a new evaluation state builder.
  ///
  /// # Arguments
  ///
  /// * `store` - The Nix store to use for evaluation
  ///
  /// # Errors
  ///
  /// Returns an error if the builder cannot be created.
  pub fn new(store: &Arc<Store>) -> Result<Self> {
    // SAFETY: store context and store are valid
    let builder_ptr = unsafe {
      sys::nix_eval_state_builder_new(store._context.as_ptr(), store.as_ptr())
    };

    let inner = NonNull::new(builder_ptr).ok_or(Error::NullPointer)?;

    Ok(EvalStateBuilder {
      inner,
      store: Arc::clone(store),
      context: Arc::clone(&store._context),
      skip_load: false,
    })
  }

  /// Set the lookup path (`NIX_PATH`) for `<...>` expressions.
  ///
  /// Each entry should be in the form `"name=path"` or just `"path"`,
  /// matching the format of `NIX_PATH` entries.
  ///
  /// # Errors
  ///
  /// Returns an error if the lookup path cannot be set.
  pub fn set_lookup_path(self, paths: &[impl AsRef<str>]) -> Result<Self> {
    // Build null-terminated array of C strings.
    let c_strings: Vec<CString> = paths
      .iter()
      .map(|s| CString::new(s.as_ref()))
      .collect::<std::result::Result<_, _>>()?;

    let mut ptrs: Vec<*const std::os::raw::c_char> =
      c_strings.iter().map(|cs| cs.as_ptr()).collect();
    ptrs.push(std::ptr::null()); // null terminator

    // SAFETY: context and builder are valid, ptrs is null-terminated
    unsafe {
      check_err(
        self.context.as_ptr(),
        sys::nix_eval_state_builder_set_lookup_path(
          self.context.as_ptr(),
          self.inner.as_ptr(),
          ptrs.as_mut_ptr(),
        ),
      )?;
    }

    Ok(self)
  }

  /// Apply flake settings to the evaluation state builder.
  ///
  /// This enables `builtins.getFlake` and related flake functionality
  /// in the resulting [`EvalState`].
  ///
  /// # Errors
  ///
  /// Returns an error if the flake settings cannot be applied.
  #[cfg(feature = "flake")]
  pub fn with_flake_settings(
    self,
    settings: &flake::FlakeSettings,
  ) -> Result<Self> {
    // SAFETY: context, settings, and builder are valid
    unsafe {
      check_err(
        self.context.as_ptr(),
        sys::nix_flake_settings_add_to_eval_state_builder(
          self.context.as_ptr(),
          settings.as_ptr(),
          self.inner.as_ptr(),
        ),
      )?;
    }

    Ok(self)
  }

  /// Skip loading Nix configuration from the environment.
  ///
  /// By default [`build`](Self::build) calls `nix_eval_state_builder_load` to
  /// read configuration from environment variables and config files. Call
  /// this method to skip that step, which is useful in tests or sandboxed
  /// environments.
  #[must_use]
  pub fn no_load_config(mut self) -> Self {
    self.skip_load = true;
    self
  }

  /// Build the evaluation state.
  ///
  /// # Errors
  ///
  /// Returns an error if the evaluation state cannot be built.
  pub fn build(self) -> Result<EvalState> {
    // Load configuration from environment first (unless suppressed).
    // SAFETY: context and builder are valid
    if !self.skip_load {
      unsafe {
        check_err(
          self.context.as_ptr(),
          sys::nix_eval_state_builder_load(
            self.context.as_ptr(),
            self.inner.as_ptr(),
          ),
        )?;
      }
    }

    // Build the state
    // SAFETY: context and builder are valid
    let state_ptr = unsafe {
      sys::nix_eval_state_build(self.context.as_ptr(), self.inner.as_ptr())
    };

    let inner = NonNull::new(state_ptr).ok_or(Error::NullPointer)?;

    Ok(EvalState {
      inner,
      store: self.store.clone(),
      context: self.context.clone(),
    })
  }
}

#[cfg(feature = "expr")]
impl Drop for EvalStateBuilder {
  fn drop(&mut self) {
    // SAFETY: We own the builder and it's valid until drop
    unsafe {
      sys::nix_eval_state_builder_free(self.inner.as_ptr());
    }
  }
}

/// Nix evaluation state for evaluating expressions.
///
/// This provides the main interface for evaluating Nix expressions
/// and creating values.
#[cfg(feature = "expr")]
pub struct EvalState {
  pub(crate) inner:   NonNull<sys::EvalState>,
  #[expect(dead_code, reason = "keeps the Arc<Store> alive Drop side-effects")]
  store:              Arc<Store>,
  pub(crate) context: Arc<Context>,
}

#[cfg(feature = "expr")]
impl EvalState {
  /// Evaluate a Nix expression from a string.
  ///
  /// # Arguments
  ///
  /// * `expr` - The Nix expression to evaluate
  /// * `path` - The path to use for error reporting (e.g., `"<eval>"`)
  ///
  /// # Errors
  ///
  /// Returns an error if evaluation fails.
  pub fn eval_from_string(&self, expr: &str, path: &str) -> Result<Value<'_>> {
    let expr_c = CString::new(expr)?;
    let path_c = CString::new(path)?;

    // Allocate value for result
    // SAFETY: context and state are valid
    let value_ptr = unsafe {
      sys::nix_alloc_value(self.context.as_ptr(), self.inner.as_ptr())
    };
    if value_ptr.is_null() {
      return Err(Error::NullPointer);
    }

    // Evaluate expression
    // SAFETY: all pointers are valid
    unsafe {
      check_err(
        self.context.as_ptr(),
        sys::nix_expr_eval_from_string(
          self.context.as_ptr(),
          self.inner.as_ptr(),
          expr_c.as_ptr(),
          path_c.as_ptr(),
          value_ptr,
        ),
      )?;
    }

    let inner = NonNull::new(value_ptr).ok_or(Error::NullPointer)?;

    Ok(Value { inner, state: self })
  }

  /// Evaluate a Nix expression from a file.
  ///
  /// Reads the file at `path`, then evaluates its contents using the parent
  /// directory as the base path for relative imports.
  ///
  /// # Errors
  ///
  /// Returns an error if the file cannot be read or if evaluation fails.
  pub fn eval_from_file(&self, path: impl AsRef<Path>) -> Result<Value<'_>> {
    let path = path.as_ref();
    let expr = std::fs::read_to_string(path).map_err(|e| {
      Error::Unknown(format!("Failed to read file {}: {e}", path.display()))
    })?;
    let base = path
      .parent()
      .unwrap_or_else(|| Path::new("."))
      .to_str()
      .ok_or_else(|| {
        Error::Unknown("File path is not valid UTF-8".to_string())
      })?;
    self.eval_from_string(&expr, base)
  }

  /// Allocate a new uninitialized value.
  ///
  /// # Errors
  ///
  /// Returns an error if value allocation fails.
  pub fn alloc_value(&self) -> Result<Value<'_>> {
    // SAFETY: context and state are valid
    let value_ptr = unsafe {
      sys::nix_alloc_value(self.context.as_ptr(), self.inner.as_ptr())
    };
    let inner = NonNull::new(value_ptr).ok_or(Error::NullPointer)?;

    Ok(Value { inner, state: self })
  }

  /// Create a Nix integer value.
  ///
  /// # Errors
  ///
  /// Returns an error if value allocation or initialization fails.
  pub fn make_int(&self, i: i64) -> Result<Value<'_>> {
    let v = self.alloc_value()?;
    // SAFETY: context and value are valid
    unsafe {
      check_err(
        self.context.as_ptr(),
        sys::nix_init_int(self.context.as_ptr(), v.inner.as_ptr(), i),
      )?;
    }
    Ok(v)
  }

  /// Create a Nix float value.
  ///
  /// # Errors
  ///
  /// Returns an error if value allocation or initialization fails.
  pub fn make_float(&self, f: f64) -> Result<Value<'_>> {
    let v = self.alloc_value()?;
    // SAFETY: context and value are valid
    unsafe {
      check_err(
        self.context.as_ptr(),
        sys::nix_init_float(self.context.as_ptr(), v.inner.as_ptr(), f),
      )?;
    }
    Ok(v)
  }

  /// Create a Nix boolean value.
  ///
  /// # Errors
  ///
  /// Returns an error if value allocation or initialization fails.
  pub fn make_bool(&self, b: bool) -> Result<Value<'_>> {
    let v = self.alloc_value()?;
    // SAFETY: context and value are valid
    unsafe {
      check_err(
        self.context.as_ptr(),
        sys::nix_init_bool(self.context.as_ptr(), v.inner.as_ptr(), b),
      )?;
    }
    Ok(v)
  }

  /// Create a Nix null value.
  ///
  /// # Errors
  ///
  /// Returns an error if value allocation or initialization fails.
  pub fn make_null(&self) -> Result<Value<'_>> {
    let v = self.alloc_value()?;
    // SAFETY: context and value are valid
    unsafe {
      check_err(
        self.context.as_ptr(),
        sys::nix_init_null(self.context.as_ptr(), v.inner.as_ptr()),
      )?;
    }
    Ok(v)
  }

  /// Create a Nix string value.
  ///
  /// # Errors
  ///
  /// Returns an error if value allocation, string conversion, or
  /// initialization fails.
  pub fn make_string(&self, s: &str) -> Result<Value<'_>> {
    let v = self.alloc_value()?;
    let s_c = CString::new(s)?;
    // SAFETY: context and value are valid
    unsafe {
      check_err(
        self.context.as_ptr(),
        sys::nix_init_string(
          self.context.as_ptr(),
          v.inner.as_ptr(),
          s_c.as_ptr(),
        ),
      )?;
    }
    Ok(v)
  }

  /// Create a Nix path value.
  ///
  /// # Errors
  ///
  /// Returns an error if value allocation, path conversion, or
  /// initialization fails.
  pub fn make_path(&self, path: impl AsRef<Path>) -> Result<Value<'_>> {
    let v = self.alloc_value()?;
    let path_str = path
      .as_ref()
      .to_str()
      .ok_or_else(|| Error::Unknown("Path is not valid UTF-8".to_string()))?;
    let path_c = CString::new(path_str)?;
    // SAFETY: context, state, and value are valid
    unsafe {
      check_err(
        self.context.as_ptr(),
        sys::nix_init_path_string(
          self.context.as_ptr(),
          self.inner.as_ptr(),
          v.inner.as_ptr(),
          path_c.as_ptr(),
        ),
      )?;
    }
    Ok(v)
  }

  /// Create a Nix list value from a slice of values.
  ///
  /// # Errors
  ///
  /// Returns an error if value allocation or list construction fails.
  pub fn make_list(&self, items: &[&Value<'_>]) -> Result<Value<'_>> {
    // SAFETY: context and state are valid
    let builder = unsafe {
      sys::nix_make_list_builder(
        self.context.as_ptr(),
        self.inner.as_ptr(),
        items.len(),
      )
    };
    if builder.is_null() {
      return Err(Error::NullPointer);
    }

    // Free the builder on all paths, including early returns on error.
    struct ListBuilderGuard(*mut sys::ListBuilder);
    impl Drop for ListBuilderGuard {
      fn drop(&mut self) {
        unsafe { sys::nix_list_builder_free(self.0) };
      }
    }
    let _guard = ListBuilderGuard(builder);

    // Insert each item
    for (i, item) in items.iter().enumerate() {
      // SAFETY: context, builder, and value are valid; index is in bounds
      unsafe {
        check_err(
          self.context.as_ptr(),
          sys::nix_list_builder_insert(
            self.context.as_ptr(),
            builder,
            i as std::os::raw::c_uint,
            item.inner.as_ptr(),
          ),
        )?;
      }
    }

    let result = self.alloc_value()?;
    // SAFETY: context, builder, and result value are valid
    unsafe {
      check_err(
        self.context.as_ptr(),
        sys::nix_make_list(
          self.context.as_ptr(),
          builder,
          result.inner.as_ptr(),
        ),
      )?;
    }

    Ok(result)
  }

  /// Create a Nix attribute set from key-value pairs.
  ///
  /// # Errors
  ///
  /// Returns an error if value allocation or attribute set construction fails.
  pub fn make_attrs<'s>(
    &'s self,
    pairs: &[(&str, &Value<'_>)],
  ) -> Result<Value<'s>> {
    // SAFETY: context and state are valid
    let builder = unsafe {
      sys::nix_make_bindings_builder(
        self.context.as_ptr(),
        self.inner.as_ptr(),
        pairs.len(),
      )
    };
    if builder.is_null() {
      return Err(Error::NullPointer);
    }

    // Free the builder on all paths, including early returns on error.
    struct BindingsBuilderGuard(*mut sys::BindingsBuilder);
    impl Drop for BindingsBuilderGuard {
      fn drop(&mut self) {
        unsafe { sys::nix_bindings_builder_free(self.0) };
      }
    }
    let _guard = BindingsBuilderGuard(builder);

    // Insert each key-value pair
    for (key, value) in pairs {
      let key_c = CString::new(*key)?;
      // SAFETY: context, builder, key, and value are valid
      unsafe {
        check_err(
          self.context.as_ptr(),
          sys::nix_bindings_builder_insert(
            self.context.as_ptr(),
            builder,
            key_c.as_ptr(),
            value.inner.as_ptr(),
          ),
        )?;
      }
    }

    let result = self.alloc_value()?;
    // SAFETY: context, builder, and result value are valid
    unsafe {
      check_err(
        self.context.as_ptr(),
        sys::nix_make_attrs(
          self.context.as_ptr(),
          result.inner.as_ptr(),
          builder,
        ),
      )?;
    }

    Ok(result)
  }

  /// Get the raw state pointer.
  ///
  /// # Safety
  ///
  /// The caller must ensure the pointer is used safely.
  pub(crate) unsafe fn as_ptr(&self) -> *mut sys::EvalState {
    self.inner.as_ptr()
  }
}

#[cfg(feature = "expr")]
impl Drop for EvalState {
  fn drop(&mut self) {
    // SAFETY: We own the state and it's valid until drop
    unsafe {
      sys::nix_state_free(self.inner.as_ptr());
    }
  }
}

#[cfg(feature = "expr")]
unsafe impl Send for EvalState {}

#[cfg(feature = "expr")]
unsafe impl Sync for EvalState {}

/// Nix value types.
#[cfg(feature = "expr")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueType {
  /// Thunk (unevaluated expression).
  Thunk,
  /// Integer value.
  Int,
  /// Float value.
  Float,
  /// Boolean value.
  Bool,
  /// String value.
  String,
  /// Path value.
  Path,
  /// Null value.
  Null,
  /// Attribute set.
  Attrs,
  /// List.
  List,
  /// Function.
  Function,
  /// External value.
  External,
}

#[cfg(feature = "expr")]
impl ValueType {
  fn from_c(value_type: sys::ValueType) -> Self {
    match value_type {
      sys::ValueType_NIX_TYPE_THUNK => ValueType::Thunk,
      sys::ValueType_NIX_TYPE_INT => ValueType::Int,
      sys::ValueType_NIX_TYPE_FLOAT => ValueType::Float,
      sys::ValueType_NIX_TYPE_BOOL => ValueType::Bool,
      sys::ValueType_NIX_TYPE_STRING => ValueType::String,
      sys::ValueType_NIX_TYPE_PATH => ValueType::Path,
      sys::ValueType_NIX_TYPE_NULL => ValueType::Null,
      sys::ValueType_NIX_TYPE_ATTRS => ValueType::Attrs,
      sys::ValueType_NIX_TYPE_LIST => ValueType::List,
      sys::ValueType_NIX_TYPE_FUNCTION => ValueType::Function,
      sys::ValueType_NIX_TYPE_EXTERNAL => ValueType::External,
      _ => ValueType::Thunk, // fallback
    }
  }
}

#[cfg(feature = "expr")]
impl fmt::Display for ValueType {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let name = match self {
      ValueType::Thunk => "thunk",
      ValueType::Int => "int",
      ValueType::Float => "float",
      ValueType::Bool => "bool",
      ValueType::String => "string",
      ValueType::Path => "path",
      ValueType::Null => "null",
      ValueType::Attrs => "attrs",
      ValueType::List => "list",
      ValueType::Function => "function",
      ValueType::External => "external",
    };
    write!(f, "{name}")
  }
}

/// A Nix value.
///
/// This represents any value in the Nix language, including primitives,
/// collections, and functions. Values are GC-managed; this struct holds
/// a reference count that is released on drop.
#[cfg(feature = "expr")]
pub struct Value<'a> {
  pub(crate) inner: NonNull<sys::nix_value>,
  pub(crate) state: &'a EvalState,
}

#[cfg(feature = "expr")]
impl Value<'_> {
  /// Force evaluation of this value.
  ///
  /// If the value is a thunk, this will evaluate it to its final form.
  ///
  /// # Errors
  ///
  /// Returns an error if evaluation fails.
  pub fn force(&mut self) -> Result<()> {
    // SAFETY: context, state, and value are valid
    unsafe {
      check_err(
        self.state.context.as_ptr(),
        sys::nix_value_force(
          self.state.context.as_ptr(),
          self.state.as_ptr(),
          self.inner.as_ptr(),
        ),
      )
    }
  }

  /// Force deep evaluation of this value.
  ///
  /// This forces evaluation of the value and all its nested components.
  ///
  /// # Errors
  ///
  /// Returns an error if evaluation fails.
  pub fn force_deep(&mut self) -> Result<()> {
    // SAFETY: context, state, and value are valid
    unsafe {
      check_err(
        self.state.context.as_ptr(),
        sys::nix_value_force_deep(
          self.state.context.as_ptr(),
          self.state.as_ptr(),
          self.inner.as_ptr(),
        ),
      )
    }
  }

  /// Get the type of this value.
  #[must_use]
  pub fn value_type(&self) -> ValueType {
    // SAFETY: context and value are valid
    let c_type = unsafe {
      sys::nix_get_type(self.state.context.as_ptr(), self.inner.as_ptr())
    };
    ValueType::from_c(c_type)
  }

  /// Convert this value to an integer.
  ///
  /// # Errors
  ///
  /// Returns an error if the value is not an integer.
  pub fn as_int(&self) -> Result<i64> {
    if self.value_type() != ValueType::Int {
      return Err(Error::InvalidType {
        expected: "int",
        actual:   self.value_type().to_string(),
      });
    }

    // SAFETY: context and value are valid, type is checked
    let result = unsafe {
      sys::nix_get_int(self.state.context.as_ptr(), self.inner.as_ptr())
    };

    Ok(result)
  }

  /// Convert this value to a float.
  ///
  /// # Errors
  ///
  /// Returns an error if the value is not a float.
  pub fn as_float(&self) -> Result<f64> {
    if self.value_type() != ValueType::Float {
      return Err(Error::InvalidType {
        expected: "float",
        actual:   self.value_type().to_string(),
      });
    }

    // SAFETY: context and value are valid, type is checked
    let result = unsafe {
      sys::nix_get_float(self.state.context.as_ptr(), self.inner.as_ptr())
    };

    Ok(result)
  }

  /// Convert this value to a boolean.
  ///
  /// # Errors
  ///
  /// Returns an error if the value is not a boolean.
  pub fn as_bool(&self) -> Result<bool> {
    if self.value_type() != ValueType::Bool {
      return Err(Error::InvalidType {
        expected: "bool",
        actual:   self.value_type().to_string(),
      });
    }

    // SAFETY: context and value are valid, type is checked
    let result = unsafe {
      sys::nix_get_bool(self.state.context.as_ptr(), self.inner.as_ptr())
    };

    Ok(result)
  }

  /// Convert this value to a string.
  ///
  /// This realises the string (resolves any context/store paths) and
  /// returns its content.
  ///
  /// # Errors
  ///
  /// Returns an error if the value is not a string.
  pub fn as_string(&self) -> Result<String> {
    if self.value_type() != ValueType::String {
      return Err(Error::InvalidType {
        expected: "string",
        actual:   self.value_type().to_string(),
      });
    }

    // Use the realised string API to handle string contexts correctly.
    // SAFETY: context, state, and value are valid; type is checked
    let realised_str = unsafe {
      sys::nix_string_realise(
        self.state.context.as_ptr(),
        self.state.as_ptr(),
        self.inner.as_ptr(),
        false,
      )
    };

    if realised_str.is_null() {
      return Err(Error::NullPointer);
    }

    // SAFETY: realised_str is non-null
    let buffer_start =
      unsafe { sys::nix_realised_string_get_buffer_start(realised_str) };

    let buffer_size =
      unsafe { sys::nix_realised_string_get_buffer_size(realised_str) };

    if buffer_start.is_null() {
      unsafe { sys::nix_realised_string_free(realised_str) };
      return Err(Error::NullPointer);
    }

    // SAFETY: buffer_start and buffer_size are valid
    let bytes = unsafe {
      std::slice::from_raw_parts(buffer_start.cast::<u8>(), buffer_size)
    };
    let string = std::str::from_utf8(bytes)
      .map_err(|_| Error::Unknown("Invalid UTF-8 in string".to_string()))?
      .to_owned();

    unsafe { sys::nix_realised_string_free(realised_str) };

    Ok(string)
  }

  /// Convert this value to a string and return its store-path context.
  ///
  /// This is the extended form of [`as_string`](Self::as_string): it returns
  /// the string content together with any store paths embedded in the string's
  /// context. For ordinary strings the context vector is empty.
  ///
  /// # Errors
  ///
  /// Returns an error if the value is not a string.
  pub fn as_string_with_context(
    &self,
  ) -> Result<(String, Vec<store::StorePath>)> {
    if self.value_type() != ValueType::String {
      return Err(Error::InvalidType {
        expected: "string",
        actual:   self.value_type().to_string(),
      });
    }

    // SAFETY: context, state, and value are valid; type is checked
    let realised_str = unsafe {
      sys::nix_string_realise(
        self.state.context.as_ptr(),
        self.state.as_ptr(),
        self.inner.as_ptr(),
        false,
      )
    };

    if realised_str.is_null() {
      return Err(Error::NullPointer);
    }

    // Read the string content.
    let buffer_start =
      unsafe { sys::nix_realised_string_get_buffer_start(realised_str) };
    let buffer_size =
      unsafe { sys::nix_realised_string_get_buffer_size(realised_str) };

    if buffer_start.is_null() {
      unsafe { sys::nix_realised_string_free(realised_str) };
      return Err(Error::NullPointer);
    }

    let bytes = unsafe {
      std::slice::from_raw_parts(buffer_start.cast::<u8>(), buffer_size)
    };
    let string = match std::str::from_utf8(bytes) {
      Ok(s) => s.to_owned(),
      Err(_) => {
        unsafe { sys::nix_realised_string_free(realised_str) };
        return Err(Error::Unknown("Invalid UTF-8 in string".to_string()));
      },
    };

    // Collect store-path context.
    let count =
      unsafe { sys::nix_realised_string_get_store_path_count(realised_str) };
    let mut paths = Vec::with_capacity(count);
    for i in 0..count {
      // SAFETY: index is in bounds
      let raw =
        unsafe { sys::nix_realised_string_get_store_path(realised_str, i) };
      if raw.is_null() {
        continue;
      }
      // Clone the path so we own it independently of the realised_str buffer.
      let cloned =
        unsafe { sys::nix_store_path_clone(raw as *mut sys::StorePath) };
      if let Some(inner) = std::ptr::NonNull::new(cloned) {
        paths.push(store::StorePath {
          inner,
          _context: Arc::clone(&self.state.context),
        });
      }
    }

    unsafe { sys::nix_realised_string_free(realised_str) };

    Ok((string, paths))
  }

  /// Convert this value to a filesystem path.
  ///
  /// # Errors
  ///
  /// Returns an error if the value is not a path.
  pub fn as_path(&self) -> Result<std::path::PathBuf> {
    if self.value_type() != ValueType::Path {
      return Err(Error::InvalidType {
        expected: "path",
        actual:   self.value_type().to_string(),
      });
    }

    // SAFETY: context and value are valid, type is checked
    let path_ptr = unsafe {
      sys::nix_get_path_string(self.state.context.as_ptr(), self.inner.as_ptr())
    };

    if path_ptr.is_null() {
      return Err(Error::NullPointer);
    }

    // SAFETY: path_ptr is a valid C string
    let path_str =
      unsafe { CStr::from_ptr(path_ptr).to_string_lossy().into_owned() };

    Ok(std::path::PathBuf::from(path_str))
  }

  /// Call this value as a function with a single argument.
  ///
  /// # Errors
  ///
  /// Returns an error if this value is not a function or the call fails.
  pub fn call(&self, arg: &Value<'_>) -> Result<Value<'_>> {
    let result = self.state.alloc_value()?;
    // SAFETY: context, state, function value, arg value, and result are valid
    unsafe {
      check_err(
        self.state.context.as_ptr(),
        sys::nix_value_call(
          self.state.context.as_ptr(),
          self.state.as_ptr(),
          self.inner.as_ptr(),
          arg.inner.as_ptr(),
          result.inner.as_ptr(),
        ),
      )?;
    }
    Ok(result)
  }

  /// Call this value as a curried function with multiple arguments.
  ///
  /// # Errors
  ///
  /// Returns an error if this value is not a function or the call fails.
  pub fn call_multi(&self, args: &[&Value<'_>]) -> Result<Value<'_>> {
    let result = self.state.alloc_value()?;
    let mut arg_ptrs: Vec<*mut sys::nix_value> =
      args.iter().map(|a| a.inner.as_ptr()).collect();
    // SAFETY: context, state, fn, args array, and result are valid
    unsafe {
      check_err(
        self.state.context.as_ptr(),
        sys::nix_value_call_multi(
          self.state.context.as_ptr(),
          self.state.as_ptr(),
          self.inner.as_ptr(),
          arg_ptrs.len(),
          arg_ptrs.as_mut_ptr(),
          result.inner.as_ptr(),
        ),
      )?;
    }
    Ok(result)
  }

  /// Create a lazy thunk that applies a function to an argument.
  ///
  /// Unlike [`call`](Self::call), this does not perform the call immediately;
  /// it stores it as a thunk to be evaluated lazily. This is useful for
  /// constructing lazy attribute sets and lists.
  ///
  /// # Errors
  ///
  /// Returns an error if the thunk cannot be created.
  pub fn make_thunk<'a>(
    fn_val: &'a Value<'a>,
    arg: &'a Value<'a>,
  ) -> Result<Value<'a>> {
    let result = fn_val.state.alloc_value()?;
    // SAFETY: context and all value pointers are valid
    unsafe {
      check_err(
        fn_val.state.context.as_ptr(),
        sys::nix_init_apply(
          fn_val.state.context.as_ptr(),
          result.inner.as_ptr(),
          fn_val.inner.as_ptr(),
          arg.inner.as_ptr(),
        ),
      )?;
    }
    Ok(result)
  }

  /// Copy this value into a new owned value.
  ///
  /// # Errors
  ///
  /// Returns an error if the copy fails.
  pub fn copy(&self) -> Result<Value<'_>> {
    let result = self.state.alloc_value()?;
    // SAFETY: context and both value pointers are valid
    unsafe {
      check_err(
        self.state.context.as_ptr(),
        sys::nix_copy_value(
          self.state.context.as_ptr(),
          result.inner.as_ptr(),
          self.inner.as_ptr(),
        ),
      )?;
    }
    Ok(result)
  }

  /// Get the raw value pointer.
  ///
  /// Format this value as Nix syntax.
  ///
  /// This provides a string representation that matches Nix's own syntax,
  /// making it useful for debugging and displaying values to users.
  ///
  /// # Errors
  ///
  /// Returns an error if the value cannot be converted to a string
  /// representation.
  pub fn to_nix_string(&self) -> Result<String> {
    match self.value_type() {
      ValueType::Int => Ok(self.as_int()?.to_string()),
      ValueType::Float => Ok(self.as_float()?.to_string()),
      ValueType::Bool => {
        Ok(if self.as_bool()? {
          "true".to_string()
        } else {
          "false".to_string()
        })
      },
      ValueType::String => {
        Ok(format!("\"{}\"", self.as_string()?.replace('"', "\\\"")))
      },
      ValueType::Null => Ok("null".to_string()),
      ValueType::Attrs => Ok("{ <attrs> }".to_string()),
      ValueType::List => Ok("[ <list> ]".to_string()),
      ValueType::Function => Ok("<function>".to_string()),
      ValueType::Path => {
        Ok(
          self
            .as_path()
            .map(|p| p.display().to_string())
            .unwrap_or_else(|_| "<path>".to_string()),
        )
      },
      ValueType::Thunk => Ok("<thunk>".to_string()),
      ValueType::External => Ok("<external>".to_string()),
    }
  }
}

#[cfg(feature = "expr")]
impl Drop for Value<'_> {
  fn drop(&mut self) {
    // SAFETY: We hold a GC reference (automatically incremented for us by
    // the Nix C API when the value was returned). Release it here.
    unsafe {
      sys::nix_value_decref(self.state.context.as_ptr(), self.inner.as_ptr());
    }
  }
}

#[cfg(feature = "expr")]
impl fmt::Display for Value<'_> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self.value_type() {
      ValueType::Int => {
        if let Ok(val) = self.as_int() {
          write!(f, "{val}")
        } else {
          write!(f, "<int error>")
        }
      },
      ValueType::Float => {
        if let Ok(val) = self.as_float() {
          write!(f, "{val}")
        } else {
          write!(f, "<float error>")
        }
      },
      ValueType::Bool => {
        if let Ok(val) = self.as_bool() {
          write!(f, "{val}")
        } else {
          write!(f, "<bool error>")
        }
      },
      ValueType::String => {
        if let Ok(val) = self.as_string() {
          write!(f, "{val}")
        } else {
          write!(f, "<string error>")
        }
      },
      ValueType::Null => write!(f, "null"),
      ValueType::Attrs => write!(f, "{{ <attrs> }}"),
      ValueType::List => write!(f, "[ <list> ]"),
      ValueType::Function => write!(f, "<function>"),
      ValueType::Path => {
        if let Ok(p) = self.as_path() {
          write!(f, "{}", p.display())
        } else {
          write!(f, "<path>")
        }
      },
      ValueType::Thunk => write!(f, "<thunk>"),
      ValueType::External => write!(f, "<external>"),
    }
  }
}

#[cfg(feature = "expr")]
impl fmt::Debug for Value<'_> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let value_type = self.value_type();
    match value_type {
      ValueType::Int => {
        if let Ok(val) = self.as_int() {
          write!(f, "Value::Int({val})")
        } else {
          write!(f, "Value::Int(<error>)")
        }
      },
      ValueType::Float => {
        if let Ok(val) = self.as_float() {
          write!(f, "Value::Float({val})")
        } else {
          write!(f, "Value::Float(<error>)")
        }
      },
      ValueType::Bool => {
        if let Ok(val) = self.as_bool() {
          write!(f, "Value::Bool({val})")
        } else {
          write!(f, "Value::Bool(<error>)")
        }
      },
      ValueType::String => {
        if let Ok(val) = self.as_string() {
          write!(f, "Value::String({val:?})")
        } else {
          write!(f, "Value::String(<error>)")
        }
      },
      ValueType::Null => write!(f, "Value::Null"),
      ValueType::Attrs => write!(f, "Value::Attrs({{ <attrs> }})"),
      ValueType::List => write!(f, "Value::List([ <list> ])"),
      ValueType::Function => write!(f, "Value::Function(<function>)"),
      ValueType::Path => {
        if let Ok(p) = self.as_path() {
          write!(f, "Value::Path({})", p.display())
        } else {
          write!(f, "Value::Path(<path>)")
        }
      },
      ValueType::Thunk => write!(f, "Value::Thunk(<thunk>)"),
      ValueType::External => write!(f, "Value::External(<external>)"),
    }
  }
}

#[cfg(all(test, any(feature = "store", feature = "expr")))]
mod tests {
  use super::*;

  #[cfg(feature = "store")]
  #[test]
  #[serial]
  fn test_context_creation() {
    let _ctx = Context::new().expect("Failed to create context");
    // Context should be dropped automatically
  }

  #[cfg(feature = "store")]
  #[test]
  #[serial]
  fn test_nix_version() {
    let version = nix_version();
    assert!(!version.is_empty(), "Version should not be empty");
  }

  #[cfg(feature = "expr")]
  #[test]
  #[serial]
  fn test_eval_state_builder() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let store =
      Arc::new(Store::open(&ctx, None).expect("Failed to open store"));
    let _state = EvalStateBuilder::new(&store)
      .expect("Failed to create builder")
      .build()
      .expect("Failed to build state");
    // State should be dropped automatically
  }

  #[cfg(feature = "expr")]
  #[test]
  #[serial]
  fn test_simple_evaluation() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let store =
      Arc::new(Store::open(&ctx, None).expect("Failed to open store"));
    let state = EvalStateBuilder::new(&store)
      .expect("Failed to create builder")
      .build()
      .expect("Failed to build state");

    let result = state
      .eval_from_string("1 + 2", "<eval>")
      .expect("Failed to evaluate expression");

    assert_eq!(result.value_type(), ValueType::Int);
    assert_eq!(result.as_int().expect("Failed to get int value"), 3);
  }

  #[cfg(feature = "expr")]
  #[test]
  #[serial]
  fn test_value_types() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let store =
      Arc::new(Store::open(&ctx, None).expect("Failed to open store"));
    let state = EvalStateBuilder::new(&store)
      .expect("Failed to create builder")
      .build()
      .expect("Failed to build state");

    // Test integer
    let int_val = state
      .eval_from_string("42", "<eval>")
      .expect("Failed to evaluate int");
    assert_eq!(int_val.value_type(), ValueType::Int);
    assert_eq!(int_val.as_int().expect("Failed to get int"), 42);

    // Test boolean
    let bool_val = state
      .eval_from_string("true", "<eval>")
      .expect("Failed to evaluate bool");
    assert_eq!(bool_val.value_type(), ValueType::Bool);
    assert!(bool_val.as_bool().expect("Failed to get bool"));

    // Test string
    let str_val = state
      .eval_from_string("\"hello\"", "<eval>")
      .expect("Failed to evaluate string");
    assert_eq!(str_val.value_type(), ValueType::String);
    assert_eq!(str_val.as_string().expect("Failed to get string"), "hello");
  }

  #[cfg(feature = "expr")]
  #[test]
  #[serial]
  fn test_value_construction() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let store =
      Arc::new(Store::open(&ctx, None).expect("Failed to open store"));
    let state = EvalStateBuilder::new(&store)
      .expect("Failed to create builder")
      .build()
      .expect("Failed to build state");

    let int_val = state.make_int(99).expect("Failed to make int");
    assert_eq!(int_val.as_int().unwrap(), 99);

    let float_val = state.make_float(2.5).expect("Failed to make float");
    assert!((float_val.as_float().unwrap() - 2.5).abs() < 1e-9);

    let bool_val = state.make_bool(true).expect("Failed to make bool");
    assert!(bool_val.as_bool().unwrap());

    let null_val = state.make_null().expect("Failed to make null");
    assert_eq!(null_val.value_type(), ValueType::Null);

    let str_val = state.make_string("hello").expect("Failed to make string");
    assert_eq!(str_val.as_string().unwrap(), "hello");
  }

  #[cfg(feature = "expr")]
  #[test]
  #[serial]
  fn test_make_list() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let store =
      Arc::new(Store::open(&ctx, None).expect("Failed to open store"));
    let state = EvalStateBuilder::new(&store)
      .expect("Failed to create builder")
      .build()
      .expect("Failed to build state");

    let a = state.make_int(1).unwrap();
    let b = state.make_int(2).unwrap();
    let c = state.make_int(3).unwrap();

    let list = state.make_list(&[&a, &b, &c]).expect("Failed to make list");
    assert_eq!(list.value_type(), ValueType::List);
    assert_eq!(list.list_len().unwrap(), 3);
  }

  #[cfg(feature = "expr")]
  #[test]
  #[serial]
  fn test_make_attrs() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let store =
      Arc::new(Store::open(&ctx, None).expect("Failed to open store"));
    let state = EvalStateBuilder::new(&store)
      .expect("Failed to create builder")
      .build()
      .expect("Failed to build state");

    let a = state.make_int(42).unwrap();
    let b = state.make_string("hello").unwrap();

    let attrs = state
      .make_attrs(&[("answer", &a), ("greeting", &b)])
      .expect("Failed to make attrs");
    assert_eq!(attrs.value_type(), ValueType::Attrs);

    let mut answer = attrs.get_attr("answer").unwrap();
    answer.force().unwrap();
    assert_eq!(answer.as_int().unwrap(), 42);
  }

  #[cfg(feature = "expr")]
  #[test]
  #[serial]
  fn test_value_call() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let store =
      Arc::new(Store::open(&ctx, None).expect("Failed to open store"));
    let state = EvalStateBuilder::new(&store)
      .expect("Failed to create builder")
      .build()
      .expect("Failed to build state");

    let f = state
      .eval_from_string("x: x + 1", "<eval>")
      .expect("Failed to evaluate function");
    let arg = state.make_int(41).unwrap();
    let result = f.call(&arg).expect("Failed to call function");
    assert_eq!(result.as_int().unwrap(), 42);
  }

  #[cfg(feature = "expr")]
  #[test]
  #[serial]
  fn test_value_copy() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let store =
      Arc::new(Store::open(&ctx, None).expect("Failed to open store"));
    let state = EvalStateBuilder::new(&store)
      .expect("Failed to create builder")
      .build()
      .expect("Failed to build state");

    let orig = state.make_int(7).unwrap();
    let copy = orig.copy().expect("Failed to copy value");
    assert_eq!(copy.as_int().unwrap(), 7);
  }

  #[cfg(feature = "expr")]
  #[test]
  #[serial]
  fn test_as_string_with_context_plain() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let store =
      Arc::new(Store::open(&ctx, None).expect("Failed to open store"));
    let state = EvalStateBuilder::new(&store)
      .expect("Failed to create builder")
      .build()
      .expect("Failed to build state");

    let val = state
      .eval_from_string("\"hello\"", "<eval>")
      .expect("Failed to evaluate string");
    let (s, ctx_paths) = val
      .as_string_with_context()
      .expect("as_string_with_context failed");
    assert_eq!(s, "hello");
    assert!(
      ctx_paths.is_empty(),
      "Plain string should have no context paths"
    );
  }

  #[cfg(feature = "expr")]
  #[test]
  #[serial]
  fn test_eval_from_file() {
    use std::io::Write as _;
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let store =
      Arc::new(Store::open(&ctx, None).expect("Failed to open store"));
    let state = EvalStateBuilder::new(&store)
      .expect("Failed to create builder")
      .build()
      .expect("Failed to build state");

    let mut tmp =
      tempfile::NamedTempFile::new().expect("Failed to create temp file");
    write!(tmp, "1 + 1").expect("Failed to write temp file");
    let result = state
      .eval_from_file(tmp.path())
      .expect("eval_from_file failed");
    assert_eq!(result.as_int().unwrap(), 2);
  }

  #[cfg(feature = "expr")]
  #[test]
  #[serial]
  fn test_no_load_config() {
    let ctx = Arc::new(Context::new().expect("Failed to create context"));
    let store =
      Arc::new(Store::open(&ctx, None).expect("Failed to open store"));
    let state = EvalStateBuilder::new(&store)
      .expect("Failed to create builder")
      .no_load_config()
      .build()
      .expect("Failed to build state with no_load_config");
    let val = state
      .eval_from_string("1 + 1", "<eval>")
      .expect("Evaluation failed");
    assert_eq!(val.as_int().unwrap(), 2);
  }
}