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
//! Miscellaneous builtins: genericClosure, functionArgs, placeholder, import,
//! scopedImport, getEnv, currentTime, findFile, unsafeGetAttrPos, toFile.
use super::*;
pub(crate) fn register(builtins: &mut NixAttrs) {
register_builtin(builtins, "functionArgs", |args| {
match &args[0] {
Value::Lambda(closure) => {
let mut result = NixAttrs::new();
if let rnix::ast::Param::Pattern(pat) = &closure.param {
for entry in pat.pat_entries() {
if let Some(ident) = entry.ident() {
let has_default = entry.default().is_some();
result.insert(ident.to_string(), Value::Bool(has_default));
}
}
}
Ok(Value::Attrs(Rc::new(result)))
}
Value::Builtin(_) => Ok(Value::Attrs(Rc::new(NixAttrs::new()))),
_ => Err(EvalError::TypeError("functionArgs: expected function".to_string())),
}
});
// Impure builtins
register_builtin(builtins, "getEnv", |args| {
let name = args[0].as_string()?;
Ok(Value::string(std::env::var(name).unwrap_or_default()))
});
register_builtin(builtins, "currentTime", |_args| {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
Ok(Value::Int(now))
});
register_builtin(builtins, "placeholder", |args| {
// CppNix `hashPlaceholder`: "/" + nix-base32(sha256("nix-output:" + name)).
// (Not a hex digest, not a "placeholder-" prefix — the byte-exact form is
// load-bearing: it is embedded verbatim in derivation env/args, so any
// divergence changes every drv hash that self-references an output.)
let output = args[0].as_string()?;
use sha2::{Digest, Sha256};
let hash = Sha256::digest(format!("nix-output:{output}").as_bytes());
Ok(Value::string(format!(
"/{}",
sui_compat::store_path::nix_base32_encode(hash.as_slice())
)))
});
// genericClosure
register_builtin(builtins, "genericClosure", |args| {
use std::collections::VecDeque;
let input = args[0].to_attrs()?;
let start_set = input
.get("startSet")
.ok_or_else(|| EvalError::AttrNotFound("startSet".into()))?
.to_list()?;
let operator = input
.get("operator")
.ok_or_else(|| EvalError::AttrNotFound("operator".into()))?
.clone();
let mut result: Vec<Value> = Vec::new();
let mut work_list: VecDeque<Value> = start_set.into();
let mut seen: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
while let Some(item) = work_list.pop_front() {
let item_attrs = item.to_attrs()?;
let key_val = item_attrs
.get("key")
.ok_or_else(|| EvalError::AttrNotFound("key".into()))?
.clone();
let key_str = format!("{}", crate::eval::force_value(&key_val)?);
if seen.contains(&key_str) {
continue;
}
seen.insert(key_str);
result.push(item.clone());
let new_items = crate::eval::apply_and_force(operator.clone(), item)?;
let new_list = new_items.to_list()?;
work_list.extend(new_list);
}
Ok(Value::List(Rc::new(NixList::new(result))))
});
// scopedImport
register_curried(builtins, "scopedImport", |scope_val, path_val| {
let scope = scope_val.to_attrs()?.clone();
// IFD: `scopedImport … <drv>` realizes the derivation output before read.
let raw_path = path_val.coerce_to_realized_path("scopedImport")?;
let resolved = crate::path::resolve_import(
crate::eval::current_eval_dir().as_deref(),
&raw_path,
).unwrap_or_else(|_| std::path::PathBuf::from(&raw_path));
let path = resolved.to_string_lossy().into_owned();
let read_path = crate::path::materialize_str(&path);
let source = std::fs::read_to_string(&read_path).map_err(|e| EvalError::IoError {
context: format!("scopedImport {path}"),
message: e.to_string(),
})?;
fn render_scope_attrs(attrs: &NixAttrs) -> Result<String, EvalError> {
let mut out = String::from("{");
for (k, v) in attrs.iter() {
let forced = crate::eval::force_value(v)?;
let rhs = match &forced {
Value::Int(n) => n.to_string(),
Value::Float(f) => format!("{f:.6}"),
Value::Bool(true) => "true".to_string(),
Value::Bool(false) => "false".to_string(),
Value::Null => "null".to_string(),
Value::String(ns) => {
let escaped = ns
.chars
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('$', "\\$");
format!("\"{escaped}\"")
}
Value::Path(p) => format!("\"{p}\""),
other => {
return Err(EvalError::NotImplemented(format!(
"scopedImport: cannot render scope value of type {} as literal",
other.type_name()
)))
}
};
out.push_str(&format!(" {k} = {rhs};"));
}
out.push_str(" }");
Ok(out)
}
let scope_src = render_scope_attrs(&scope)?;
let wrapped = format!("with {scope_src}; ({source})");
let path_buf = std::path::PathBuf::from(&path);
let _guard = crate::eval::push_eval_file(path_buf.clone());
crate::eval::eval_with_file(&wrapped, Some(path_buf))
});
// import
register_builtin(builtins, "import", |args| {
crate::perf::inc(crate::perf::Counter::Import);
// IFD: `import <drv>` realizes the derivation output before reading it.
// This is the marquee darwin root — `import ishou.stylix-fonts` (a
// `runCommand` derivation) demands its built output mid-eval.
let raw_path = args[0].coerce_to_realized_path("import")?;
let resolved = crate::path::resolve_import(
crate::eval::current_eval_dir().as_deref(),
&raw_path,
).unwrap_or_else(|_| std::path::PathBuf::from(&raw_path));
let path = resolved.to_string_lossy().into_owned();
let canonical = crate::path::normalize(std::path::Path::new(&path));
let cached = IMPORT_CACHE.with(|c| c.borrow().get(&canonical).cloned());
if let Some(value) = cached {
crate::perf::inc(crate::perf::Counter::ImportHit);
return Ok(value);
}
// Redirect the on-disk read to the input's real source tree when
// `path` lies under a fetched flake input's `-source` store prefix;
// the store-path `path`/`path_buf` (below) is unchanged so relative
// imports re-enter the remap and eval-dir/string tracking stays
// byte-correct.
let read_path = crate::path::materialize_str(&path);
let source = std::fs::read_to_string(&read_path)
.map_err(|e| EvalError::IoError { context: format!("import {path}"), message: e.to_string() })?;
let path_buf = std::path::PathBuf::from(&path);
let _guard = crate::eval::push_eval_file(path_buf.clone());
let value = crate::eval::eval_with_file(&source, Some(path_buf))?;
IMPORT_CACHE.with(|c| c.borrow_mut().insert(canonical, value.clone()));
Ok(value)
});
// unsafeGetAttrPos name set
//
// Returns `{ file; line; column; }` for the source position of key
// `name` in `set` (or `null` when the key/position is unknown). nixpkgs
// `lib/types.nix`'s `attrTag` derives each tag's `declarations` from
// `[ pos.file ]`; a `null`-returning stub made every `attrTag` sub-option
// `declarations` empty (the options.json dock-declarations divergence:
// `system.defaults.dock.persistent-{apps,others}.*`).
//
// The position table is attached to `set` by `eval_attrset` when the set
// was built from a literal with static keys; `pos_for` resolves the key's
// byte offset to a file (store-source-lifted) + 1-based line/column.
register_curried(builtins, "unsafeGetAttrPos", |name, set| {
let name = crate::eval::force_value(name)?;
let name = name.as_string()?;
let set = crate::eval::force_value(set)?;
let attrs = match &set {
Value::Attrs(a) => a,
// CppNix returns null when the first arg isn't found in an
// attrset; a non-attrset second arg is a type error there, but
// returning null is the safe, byte-faithful behavior for the
// paths nixpkgs exercises (it always passes an attrset).
_ => return Ok(Value::Null),
};
match attrs.pos_for(&name) {
Some(p) => {
let mut result = NixAttrs::new();
result.insert("file".to_string(), Value::string(p.file));
result.insert("line".to_string(), Value::Int(p.line as i64));
result.insert("column".to_string(), Value::Int(p.column as i64));
Ok(Value::Attrs(Rc::new(result)))
}
None => Ok(Value::Null),
}
});
// findFile (curried)
register_curried(builtins, "findFile", |search_path, name_val| {
let entries = search_path.as_list()?;
let name = name_val.as_string()?;
for entry in entries {
let entry = crate::eval::force_value(entry)?;
let attrs = entry.to_attrs()?;
let prefix = attrs
.get("prefix")
.ok_or_else(|| EvalError::AttrNotFound("prefix".into()))?
.to_str()?;
let path = attrs
.get("path")
.ok_or_else(|| EvalError::AttrNotFound("path".into()))?
.to_str()?;
if name == prefix || name.starts_with(&format!("{prefix}/")) {
let suffix = if name == prefix {
String::new()
} else {
name[prefix.len()..].to_string()
};
let full_path = format!("{path}{suffix}");
if std::path::Path::new(&full_path).exists() {
return Ok(Value::Path(Box::new(SmolStr::from(full_path.as_str()))));
}
}
}
Err(EvalError::TypeError(format!("findFile: file '{name}' not found in search path")))
});
// toFile (curried) — compute the CppNix text:sha256 store path
// (byte-equivalent with cppnix) AND write the content so a
// subsequent `builtins.readFile` can read it back. Tries
// /nix/store first; on PermissionDenied falls back to a
// process-local sui-tofile-cache so the round-trip succeeds even
// when the operator isn't a nixbld user.
register_curried(builtins, "toFile", |name_val, content_val| {
let name = name_val.as_string()?;
let content = content_val.as_string()?;
// ★ The content's STRING CONTEXT is the reference set, and passing
// `&[]` here silently produced a wrong store path for every `toFile`
// whose content interpolates another store path — i.e. exactly the
// non-trivial ones. A wrong store path is a wrong drvPath for every
// derivation that consumes the file.
//
// CppNix sorts the reference set (it is a `StorePathSet`, ordered by
// the full path string), so the fingerprint is order-independent
// across evaluations.
let ctx_elems: Vec<crate::value::ContextElement> = match content_val.demand()? {
Concrete::String(ns) => ns.context.iter().cloned().collect(),
_ => Vec::new(),
};
// ★ CppNix REFUSES a derivation reference here — a text store object
// has no way to depend on something that has not been built yet:
//
// error: files created by builtins.toFile may not reference
// derivations, but t references !out!…-d.drv
//
// sui returned a store path instead, so `toFile "t" "${drv}"` produced
// a legal-looking path for a file whose reference set nix considers
// unrepresentable. Refuse loudly rather than invent one.
//
// Only `Plain` (an already-realised store path) is admissible;
// `Output` and `DrvDeep` are both derivation references.
for e in &ctx_elems {
let rendered = match e {
crate::value::ContextElement::Output { drv, output } => {
// nix renders this as `!<output>!<drv-basename>`; sui's
// own Display is `<drv>!<output>`, so render nix's shape
// here rather than reuse Display for the message.
let base = drv.rsplit('/').next().unwrap_or(drv);
format!("!{output}!{base}")
}
crate::value::ContextElement::DrvDeep(d) => {
let base = d.rsplit('/').next().unwrap_or(d);
format!("={base}")
}
crate::value::ContextElement::Plain(_) => continue,
};
return Err(EvalError::TypeError(format!(
"files created by builtins.toFile may not reference \
derivations, but {name} references {rendered}"
)));
}
let mut references: Vec<String> = ctx_elems
.iter()
.map(std::string::ToString::to_string)
.collect();
references.sort();
references.dedup();
let store_path =
sui_compat::content_address::compute_text_store_path(
&name,
content.as_bytes(),
&references,
)
.map_err(|e| EvalError::TypeError(
format!("toFile: store-path computation failed: {e}"),
))?
.to_absolute_path();
write_store_text_object(&store_path, content.as_bytes())
.map_err(|e| EvalError::IoError {
context: format!("toFile {store_path}"),
message: e.to_string(),
})?;
// CppNix's `builtins.toFile` returns a STRING carrying the store
// path as opaque (`Plain`) context — NOT a Path value. A Path
// value would be RE-copied when coerced into a derivation env
// (per the copy-to-store "a Path is always copied" rule), yielding
// a doubled `<newhash>-<storehash>-name` path and diverging every
// consumer (e.g. lua's `setupHook` → neovim, redis). Referencing a
// String-with-context is verbatim, exactly like nix.
let mut ctx = StringContext::new();
ctx.add_plain(store_path.clone());
Ok(Value::String(std::rc::Rc::new(NixString::with_context(
SmolStr::from(store_path.as_str()),
ctx,
))))
});
}
/// Try to materialize `content` at `store_path`, falling back to a
/// per-user sui-tofile-cache when /nix/store is read-only. Idempotent:
/// writes the file only when missing (or, in the fallback, only when
/// the cached basename hasn't been materialized yet this session).
///
/// Pairs with [`read_store_text_object`] in `paths.rs`, which
/// transparently consults the same fallback location when reading.
pub(crate) fn write_store_text_object(
store_path: &str,
content: &[u8],
) -> Result<(), std::io::Error> {
let primary = std::path::Path::new(store_path);
if primary.exists() {
return Ok(());
}
match std::fs::write(primary, content) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
let fallback_dir = std::env::temp_dir().join("sui-tofile-cache");
std::fs::create_dir_all(&fallback_dir)?;
let basename = primary
.file_name()
.ok_or_else(|| std::io::Error::other(
format!("toFile: cannot derive basename from {store_path}"),
))?;
let fallback_path = fallback_dir.join(basename);
if !fallback_path.exists() {
std::fs::write(&fallback_path, content)?;
}
Ok(())
}
Err(e) => Err(e),
}
}