refactor(codegen): less allocation

This commit is contained in:
2026-01-27 11:08:53 +08:00
parent 86953dd9d3
commit 8635da3559

View File

@@ -1,34 +1,110 @@
use std::fmt::Write as _;
use std::path::Path; use std::path::Path;
use itertools::Itertools as _;
use crate::ir::*; use crate::ir::*;
pub(crate) fn compile(expr: &Ir, ctx: &impl CodegenContext) -> String { /// High-performance code buffer for JavaScript generation
let code = expr.compile(ctx); pub(crate) struct CodeBuffer {
buf: String,
}
let mut debug_flags = Vec::new(); impl CodeBuffer {
if std::env::var("NIX_JS_DEBUG_THUNKS").is_ok() { #[inline]
debug_flags.push("Nix.DEBUG_THUNKS.enabled=true"); fn with_capacity(capacity: usize) -> Self {
Self {
buf: String::with_capacity(capacity),
}
} }
let debug_prefix = if debug_flags.is_empty() {
String::new()
} else {
format!("{};", debug_flags.join(";"))
};
let cur_dir = ctx.get_current_dir().display().to_string().escape_quote(); #[inline]
format!( pub fn push_str(&mut self, s: &str) {
"(()=>{{{}Nix.builtins.storeDir={};const currentDir={};return {}}})()", self.buf.push_str(s);
debug_prefix, }
ctx.get_store_dir().escape_quote(),
cur_dir, #[inline]
code pub fn push(&mut self, c: char) {
self.buf.push(c);
}
#[inline]
pub fn push_escaped_quote(&mut self, s: &str) {
self.buf.push('"');
for c in s.chars() {
match c {
'\\' => self.buf.push_str("\\\\"),
'"' => self.buf.push_str("\\\""),
'\n' => self.buf.push_str("\\n"),
'\r' => self.buf.push_str("\\r"),
'\t' => self.buf.push_str("\\t"),
_ => self.buf.push(c),
}
}
self.buf.push('"');
}
#[inline]
pub fn push_span(&mut self, span: rnix::TextRange, ctx: &impl CodegenContext) {
write!(
self.buf,
"\"{}:{}:{}\"",
ctx.get_current_source_id(),
usize::from(span.start()),
usize::from(span.end())
) )
.unwrap();
}
/// Write items joined by separator, using a closure to write each item
#[inline]
pub fn write_join<I, F>(&mut self, mut items: I, sep: &str, mut f: F)
where
I: Iterator,
F: FnMut(&mut Self, I::Item),
{
if let Some(first) = items.next() {
f(self, first);
for item in items {
self.buf.push_str(sep);
f(self, item);
}
}
}
#[inline]
fn into_string(self) -> String {
self.buf
}
}
/// Write-style macro for ergonomic code generation
macro_rules! write_code {
($buf:expr, $($arg:tt)*) => {
write!($buf.buf, $($arg)*).unwrap()
};
}
pub(crate) fn compile(expr: &Ir, ctx: &impl CodegenContext) -> String {
let mut buf = CodeBuffer::with_capacity(8192);
buf.push_str("(()=>{");
if std::env::var("NIX_JS_DEBUG_THUNKS").is_ok() {
buf.push_str("Nix.DEBUG_THUNKS.enabled=true;");
}
buf.push_str("Nix.builtins.storeDir=");
buf.push_escaped_quote(ctx.get_store_dir());
buf.push_str(";const currentDir=");
buf.push_escaped_quote(&ctx.get_current_dir().display().to_string());
buf.push_str(";return ");
expr.compile(ctx, &mut buf);
buf.push_str("})()");
buf.into_string()
} }
trait Compile<Ctx: CodegenContext> { trait Compile<Ctx: CodegenContext> {
fn compile(&self, ctx: &Ctx) -> String; fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer);
} }
pub(crate) trait CodegenContext { pub(crate) trait CodegenContext {
@@ -40,50 +116,28 @@ pub(crate) trait CodegenContext {
fn get_current_source(&self) -> crate::error::Source; fn get_current_source(&self) -> crate::error::Source;
} }
trait EscapeQuote {
fn escape_quote(&self) -> String;
}
impl EscapeQuote for str {
fn escape_quote(&self) -> String {
let mut escaped = String::with_capacity(self.len() + 2);
escaped.push('"');
for c in self.chars() {
match c {
'\\' => escaped.push_str("\\\\"),
'\"' => escaped.push_str("\\\""),
'\n' => escaped.push_str("\\n"),
'\r' => escaped.push_str("\\r"),
'\t' => escaped.push_str("\\t"),
_ => escaped.push(c),
}
}
escaped.push('"');
escaped
}
}
fn encode_span(span: rnix::TextRange, ctx: &impl CodegenContext) -> String {
format!(
"\"{}:{}:{}\"",
ctx.get_current_source_id(),
usize::from(span.start()),
usize::from(span.end())
)
}
impl<Ctx: CodegenContext> Compile<Ctx> for Ir { impl<Ctx: CodegenContext> Compile<Ctx> for Ir {
fn compile(&self, ctx: &Ctx) -> String { fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
match self { match self {
Ir::Int(int) => format!("{}n", int.inner), // Generate BigInt literal Ir::Int(int) => {
Ir::Float(float) => float.inner.to_string(), write_code!(buf, "{}n", int.inner);
Ir::Bool(bool) => bool.inner.to_string(), }
Ir::Null(_) => "null".to_string(), Ir::Float(float) => {
Ir::Str(s) => s.val.escape_quote(), write_code!(buf, "{}", float.inner);
}
Ir::Bool(bool) => {
write_code!(buf, "{}", bool.inner);
}
Ir::Null(_) => {
buf.push_str("null");
}
Ir::Str(s) => {
buf.push_escaped_quote(&s.val);
}
Ir::Path(p) => { Ir::Path(p) => {
// Path needs runtime resolution buf.push_str("Nix.resolvePath(currentDir,");
let path_expr = ctx.get_ir(p.expr).compile(ctx); ctx.get_ir(p.expr).compile(ctx, buf);
format!("Nix.resolvePath(currentDir,{})", path_expr) buf.push(')');
} }
&Ir::If(If { &Ir::If(If {
cond, cond,
@@ -91,128 +145,192 @@ impl<Ctx: CodegenContext> Compile<Ctx> for Ir {
alter, alter,
span: _, span: _,
}) => { }) => {
let cond_code = ctx.get_ir(cond).compile(ctx); let cond_ir = ctx.get_ir(cond);
let consq = ctx.get_ir(consq).compile(ctx); let cond_span = cond_ir.span();
let alter = ctx.get_ir(alter).compile(ctx);
let cond_span = encode_span(ctx.get_ir(cond).span(), ctx); buf.push_str("(Nix.withContext(\"while evaluating a branch condition\",");
format!( buf.push_span(cond_span, ctx);
"(Nix.withContext(\"while evaluating a branch condition\",{},()=>Nix.forceBool({})))?({}):({})", buf.push_str(",()=>Nix.forceBool(");
cond_span, cond_code, consq, alter cond_ir.compile(ctx, buf);
) buf.push_str(")))?(");
ctx.get_ir(consq).compile(ctx, buf);
buf.push_str("):(");
ctx.get_ir(alter).compile(ctx, buf);
buf.push(')');
} }
Ir::BinOp(x) => x.compile(ctx), Ir::BinOp(x) => x.compile(ctx, buf),
Ir::UnOp(x) => x.compile(ctx), Ir::UnOp(x) => x.compile(ctx, buf),
Ir::Func(x) => x.compile(ctx), Ir::Func(x) => x.compile(ctx, buf),
Ir::AttrSet(x) => x.compile(ctx), Ir::AttrSet(x) => x.compile(ctx, buf),
Ir::List(x) => x.compile(ctx), Ir::List(x) => x.compile(ctx, buf),
Ir::Call(x) => x.compile(ctx), Ir::Call(x) => x.compile(ctx, buf),
Ir::Arg(x) => format!("arg{}", x.inner.0), Ir::Arg(x) => {
Ir::TopLevel(x) => x.compile(ctx), write_code!(buf, "arg{}", x.inner.0);
Ir::Select(x) => x.compile(ctx), }
Ir::TopLevel(x) => x.compile(ctx, buf),
Ir::Select(x) => x.compile(ctx, buf),
&Ir::Thunk(Thunk { inner: expr_id, .. }) => { &Ir::Thunk(Thunk { inner: expr_id, .. }) => {
format!("expr{}", expr_id.0) write_code!(buf, "expr{}", expr_id.0);
}
Ir::Builtins(_) => {
buf.push_str("Nix.builtins");
} }
Ir::Builtins(_) => "Nix.builtins".to_string(),
&Ir::Builtin(Builtin { inner: name, .. }) => { &Ir::Builtin(Builtin { inner: name, .. }) => {
format!("Nix.builtins[{}]", ctx.get_sym(name).escape_quote()) buf.push_str("Nix.builtins[");
buf.push_escaped_quote(ctx.get_sym(name));
buf.push(']');
} }
Ir::ConcatStrings(x) => x.compile(ctx), Ir::ConcatStrings(x) => x.compile(ctx, buf),
Ir::HasAttr(x) => x.compile(ctx), Ir::HasAttr(x) => x.compile(ctx, buf),
&Ir::Assert(Assert { &Ir::Assert(Assert {
assertion, assertion,
expr, expr,
ref assertion_raw, ref assertion_raw,
span, span,
}) => { }) => {
let assertion_code = ctx.get_ir(assertion).compile(ctx); let assertion_ir = ctx.get_ir(assertion);
let expr = ctx.get_ir(expr).compile(ctx); let assertion_span = assertion_ir.span();
let assertion_span = encode_span(ctx.get_ir(assertion).span(), ctx);
let span = encode_span(span, ctx); buf.push_str("Nix.assert(Nix.withContext(\"while evaluating the condition of the assert statement\",");
format!( buf.push_span(assertion_span, ctx);
"Nix.assert(Nix.withContext(\"while evaluating the condition of the assert statement\",{},()=>({})),{},{},{})", buf.push_str(",()=>(");
assertion_span, assertion_ir.compile(ctx, buf);
assertion_code, buf.push_str(")),");
expr, ctx.get_ir(expr).compile(ctx, buf);
assertion_raw.escape_quote(), buf.push(',');
span buf.push_escaped_quote(assertion_raw);
) buf.push(',');
buf.push_span(span, ctx);
buf.push(')');
} }
Ir::CurPos(cur_pos) => { Ir::CurPos(cur_pos) => {
let span_str = encode_span(cur_pos.span, ctx); buf.push_str("Nix.mkPos(");
format!("Nix.mkPos({})", span_str) buf.push_span(cur_pos.span, ctx);
buf.push(')');
} }
} }
} }
} }
impl<Ctx: CodegenContext> Compile<Ctx> for BinOp { impl<Ctx: CodegenContext> Compile<Ctx> for BinOp {
fn compile(&self, ctx: &Ctx) -> String { fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
use BinOpKind::*; use BinOpKind::*;
let lhs = ctx.get_ir(self.lhs).compile(ctx); let lhs = ctx.get_ir(self.lhs);
let rhs = ctx.get_ir(self.rhs).compile(ctx); let rhs = ctx.get_ir(self.rhs);
let with_ctx = |op_name: &str, op_call: String| {
let span = encode_span(self.span, ctx);
format!(
"Nix.withContext(\"while evaluating the {} operator\",{},()=>({}))",
op_name, span, op_call
)
};
match self.kind { match self.kind {
Add => with_ctx("+", format!("Nix.op.add({},{})", lhs, rhs)), Add | Sub | Mul | Div | Eq | Neq | Lt | Gt | Leq | Geq | Con | Upd => {
Sub => with_ctx("-", format!("Nix.op.sub({},{})", lhs, rhs)), let op_name = match self.kind {
Mul => with_ctx("*", format!("Nix.op.mul({},{})", lhs, rhs)), Add => "+",
Div => with_ctx("/", format!("Nix.op.div({},{})", lhs, rhs)), Sub => "-",
Eq => with_ctx("==", format!("Nix.op.eq({},{})", lhs, rhs)), Mul => "*",
Neq => with_ctx("!=", format!("Nix.op.neq({},{})", lhs, rhs)), Div => "/",
Lt => with_ctx("<", format!("Nix.op.lt({},{})", lhs, rhs)), Eq => "==",
Gt => with_ctx(">", format!("Nix.op.gt({},{})", lhs, rhs)), Neq => "!=",
Leq => with_ctx("<=", format!("Nix.op.lte({},{})", lhs, rhs)), Lt => "<",
Geq => with_ctx(">=", format!("Nix.op.gte({},{})", lhs, rhs)), Gt => ">",
// Short-circuit operators: use JavaScript native && and || Leq => "<=",
And => with_ctx( Geq => ">=",
"&&", Con => "++",
format!("Nix.forceBool({})&&Nix.forceBool({})", lhs, rhs), Upd => "//",
), _ => unreachable!(),
Or => with_ctx( };
"||", let op_func = match self.kind {
format!("Nix.forceBool({})||Nix.forceBool({})", lhs, rhs), Add => "Nix.op.add(",
), Sub => "Nix.op.sub(",
Impl => with_ctx( Mul => "Nix.op.mul(",
"->", Div => "Nix.op.div(",
format!("(!Nix.forceBool({})||Nix.forceBool({}))", lhs, rhs), Eq => "Nix.op.eq(",
), Neq => "Nix.op.neq(",
Con => with_ctx("++", format!("Nix.op.concat({},{})", lhs, rhs)), Lt => "Nix.op.lt(",
Upd => with_ctx("//", format!("Nix.op.update({},{})", lhs, rhs)), Gt => "Nix.op.gt(",
PipeL => format!("Nix.call({},{})", rhs, lhs), Leq => "Nix.op.lte(",
PipeR => format!("Nix.call({},{})", lhs, rhs), Geq => "Nix.op.gte(",
Con => "Nix.op.concat(",
Upd => "Nix.op.update(",
_ => unreachable!(),
};
buf.push_str("Nix.withContext(\"while evaluating the ");
buf.push_str(op_name);
buf.push_str(" operator\",");
buf.push_span(self.span, ctx);
buf.push_str(",()=>(");
buf.push_str(op_func);
lhs.compile(ctx, buf);
buf.push(',');
rhs.compile(ctx, buf);
buf.push_str(")))");
}
And => {
buf.push_str("Nix.withContext(\"while evaluating the && operator\",");
buf.push_span(self.span, ctx);
buf.push_str(",()=>(Nix.forceBool(");
lhs.compile(ctx, buf);
buf.push_str(")&&Nix.forceBool(");
rhs.compile(ctx, buf);
buf.push_str(")))");
}
Or => {
buf.push_str("Nix.withContext(\"while evaluating the || operator\",");
buf.push_span(self.span, ctx);
buf.push_str(",()=>(Nix.forceBool(");
lhs.compile(ctx, buf);
buf.push_str(")||Nix.forceBool(");
rhs.compile(ctx, buf);
buf.push_str(")))");
}
Impl => {
buf.push_str("Nix.withContext(\"while evaluating the -> operator\",");
buf.push_span(self.span, ctx);
buf.push_str(",()=>((!Nix.forceBool(");
lhs.compile(ctx, buf);
buf.push_str(")||Nix.forceBool(");
rhs.compile(ctx, buf);
buf.push_str("))))");
}
PipeL => {
buf.push_str("Nix.call(");
rhs.compile(ctx, buf);
buf.push(',');
lhs.compile(ctx, buf);
buf.push(')');
}
PipeR => {
buf.push_str("Nix.call(");
lhs.compile(ctx, buf);
buf.push(',');
rhs.compile(ctx, buf);
buf.push(')');
}
} }
} }
} }
impl<Ctx: CodegenContext> Compile<Ctx> for UnOp { impl<Ctx: CodegenContext> Compile<Ctx> for UnOp {
fn compile(&self, ctx: &Ctx) -> String { fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
use UnOpKind::*; use UnOpKind::*;
let rhs = ctx.get_ir(self.rhs).compile(ctx);
match self.kind { match self.kind {
Neg => format!("Nix.op.sub(0n,{rhs})"), Neg => {
Not => format!("Nix.op.bnot({rhs})"), buf.push_str("Nix.op.sub(0n,");
ctx.get_ir(self.rhs).compile(ctx, buf);
buf.push(')');
}
Not => {
buf.push_str("Nix.op.bnot(");
ctx.get_ir(self.rhs).compile(ctx, buf);
buf.push(')');
}
} }
} }
} }
impl<Ctx: CodegenContext> Compile<Ctx> for Func { impl<Ctx: CodegenContext> Compile<Ctx> for Func {
fn compile(&self, ctx: &Ctx) -> String { fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
let id = ctx.get_ir(self.arg).as_ref().unwrap_arg().inner.0; let id = ctx.get_ir(self.arg).as_ref().unwrap_arg().inner.0;
let thunk_defs = compile_thunks(&self.thunks, ctx);
let body_code = ctx.get_ir(self.body).compile(ctx); let has_thunks = !self.thunks.is_empty();
let body = if thunk_defs.is_empty() {
body_code
} else {
format!("{{{}return {}}}", thunk_defs, body_code)
};
if let Some(Param { if let Some(Param {
required, required,
@@ -220,199 +338,277 @@ impl<Ctx: CodegenContext> Compile<Ctx> for Func {
ellipsis, ellipsis,
}) = &self.param }) = &self.param
{ {
let mut required = required.iter().map(|&sym| ctx.get_sym(sym).escape_quote()); buf.push_str("Nix.mkFunction(arg");
let required = format!("[{}]", required.join(",")); write_code!(buf, "{}", id);
let mut optional = optional.iter().map(|&sym| ctx.get_sym(sym).escape_quote()); buf.push_str("=>");
let optional = format!("[{}]", optional.join(",")); if has_thunks {
if thunk_defs.is_empty() { buf.push('{');
format!("Nix.mkFunction(arg{id}=>({body}),{required},{optional},{ellipsis})") compile_thunks(&self.thunks, ctx, buf);
buf.push_str("return ");
ctx.get_ir(self.body).compile(ctx, buf);
buf.push('}');
} else { } else {
format!("Nix.mkFunction(arg{id}=>{body},{required},{optional},{ellipsis})") buf.push('(');
ctx.get_ir(self.body).compile(ctx, buf);
buf.push(')');
} }
buf.push_str(",[");
buf.write_join(required.iter(), ",", |b, &sym| {
b.push_escaped_quote(ctx.get_sym(sym));
});
buf.push_str("],[");
buf.write_join(optional.iter(), ",", |b, &sym| {
b.push_escaped_quote(ctx.get_sym(sym));
});
buf.push_str("],");
write_code!(buf, "{}", ellipsis);
buf.push(')');
} else { } else {
if thunk_defs.is_empty() { buf.push_str("arg");
format!("arg{id}=>({body})") write_code!(buf, "{}", id);
buf.push_str("=>");
if has_thunks {
buf.push('{');
compile_thunks(&self.thunks, ctx, buf);
buf.push_str("return ");
ctx.get_ir(self.body).compile(ctx, buf);
buf.push('}');
} else { } else {
format!("arg{id}=>{body}") buf.push('(');
ctx.get_ir(self.body).compile(ctx, buf);
buf.push(')');
} }
} }
} }
} }
impl<Ctx: CodegenContext> Compile<Ctx> for Call { impl<Ctx: CodegenContext> Compile<Ctx> for Call {
fn compile(&self, ctx: &Ctx) -> String { fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
let func = ctx.get_ir(self.func).compile(ctx); buf.push_str("Nix.call(");
let arg = ctx.get_ir(self.arg).compile(ctx); ctx.get_ir(self.func).compile(ctx, buf);
let span_str = encode_span(self.span, ctx); buf.push(',');
format!("Nix.call({func},{arg},{span_str})") ctx.get_ir(self.arg).compile(ctx, buf);
buf.push(',');
buf.push_span(self.span, ctx);
buf.push(')');
} }
} }
fn compile_thunks<Ctx: CodegenContext>(thunks: &[(ExprId, ExprId)], ctx: &Ctx) -> String { fn compile_thunks<Ctx: CodegenContext>(
thunks: &[(ExprId, ExprId)],
ctx: &Ctx,
buf: &mut CodeBuffer,
) {
if thunks.is_empty() { if thunks.is_empty() {
return String::new(); return;
} }
thunks
.iter() for &(slot, inner) in thunks {
.map(|&(slot, inner)| { let inner_ir = ctx.get_ir(inner);
let inner_code = ctx.get_ir(inner).compile(ctx); let inner_span = inner_ir.span();
let inner_span = ctx.get_ir(inner).span();
format!( write_code!(buf, "let expr{}=Nix.createThunk(()=>(", slot.0);
"let expr{}=Nix.createThunk(()=>({}),\"expr{} {}:{}:{}\")", inner_ir.compile(ctx, buf);
slot.0, write_code!(
inner_code, buf,
"),\"expr{} {}:{}:{}\");",
slot.0, slot.0,
ctx.get_current_source().get_name(), ctx.get_current_source().get_name(),
usize::from(inner_span.start()), usize::from(inner_span.start()),
usize::from(inner_span.end()) usize::from(inner_span.end())
) );
}) }
.join(";")
+ ";"
} }
impl<Ctx: CodegenContext> Compile<Ctx> for TopLevel { impl<Ctx: CodegenContext> Compile<Ctx> for TopLevel {
fn compile(&self, ctx: &Ctx) -> String { fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
let thunk_defs = compile_thunks(&self.thunks, ctx); if self.thunks.is_empty() {
let body = ctx.get_ir(self.body).compile(ctx); ctx.get_ir(self.body).compile(ctx, buf);
if thunk_defs.is_empty() {
body
} else { } else {
format!("(()=>{{{}return {}}})()", thunk_defs, body) buf.push_str("(()=>{");
compile_thunks(&self.thunks, ctx, buf);
buf.push_str("return ");
ctx.get_ir(self.body).compile(ctx, buf);
buf.push_str("})()");
} }
} }
} }
impl<Ctx: CodegenContext> Compile<Ctx> for Select { impl<Ctx: CodegenContext> Compile<Ctx> for Select {
fn compile(&self, ctx: &Ctx) -> String { fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
let lhs = ctx.get_ir(self.expr).compile(ctx);
let attrpath = self
.attrpath
.iter()
.map(|attr| match attr {
Attr::Str(sym, _) => ctx.get_sym(*sym).escape_quote(),
Attr::Dynamic(expr_id, _) => ctx.get_ir(*expr_id).compile(ctx),
})
.join(",");
let span_str = encode_span(self.span, ctx);
if let Some(default) = self.default { if let Some(default) = self.default {
format!( buf.push_str("Nix.selectWithDefault(");
"Nix.selectWithDefault({lhs},[{attrpath}],{},{span_str})", ctx.get_ir(self.expr).compile(ctx, buf);
ctx.get_ir(default).compile(ctx) buf.push_str(",[");
) buf.write_join(self.attrpath.iter(), ",", |b, attr| match attr {
Attr::Str(sym, _) => b.push_escaped_quote(ctx.get_sym(*sym)),
Attr::Dynamic(expr_id, _) => ctx.get_ir(*expr_id).compile(ctx, b),
});
buf.push_str("],");
ctx.get_ir(default).compile(ctx, buf);
buf.push(',');
buf.push_span(self.span, ctx);
buf.push(')');
} else { } else {
format!("Nix.select({lhs},[{attrpath}],{span_str})") buf.push_str("Nix.select(");
ctx.get_ir(self.expr).compile(ctx, buf);
buf.push_str(",[");
buf.write_join(self.attrpath.iter(), ",", |b, attr| match attr {
Attr::Str(sym, _) => b.push_escaped_quote(ctx.get_sym(*sym)),
Attr::Dynamic(expr_id, _) => ctx.get_ir(*expr_id).compile(ctx, b),
});
buf.push_str("],");
buf.push_span(self.span, ctx);
buf.push(')');
} }
} }
} }
impl<Ctx: CodegenContext> Compile<Ctx> for AttrSet { impl<Ctx: CodegenContext> Compile<Ctx> for AttrSet {
fn compile(&self, ctx: &Ctx) -> String { fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
let mut attrs = Vec::new(); if !self.dyns.is_empty() {
let mut attr_positions = Vec::new(); buf.push_str("Nix.mkAttrsWithPos({");
let mut first = true;
for (&sym, &(expr, _)) in &self.stcs {
if !first {
buf.push(',');
}
first = false;
for (&sym, &(expr, attr_span)) in &self.stcs {
let key = ctx.get_sym(sym); let key = ctx.get_sym(sym);
let value_code = ctx.get_ir(expr).compile(ctx); let value_ir = ctx.get_ir(expr);
let value_span = encode_span(ctx.get_ir(expr).span(), ctx); buf.push_escaped_quote(key);
let value = format!( buf.push_str(":Nix.withContext(\"while evaluating the attribute '");
"Nix.withContext(\"while evaluating the attribute '{}'\",{},()=>({}))", buf.push_str(key);
key, value_span, value_code buf.push_str("'\",");
); buf.push_span(value_ir.span(), ctx);
attrs.push(format!("{}:{}", key.escape_quote(), value)); buf.push_str(",()=>(");
value_ir.compile(ctx, buf);
let attr_pos_str = encode_span(attr_span, ctx); buf.push_str("))");
attr_positions.push(format!("{}:{}", key.escape_quote(), attr_pos_str));
} }
if !self.dyns.is_empty() { buf.push_str("},{");
let (keys, vals, dyn_spans) = self
.dyns let mut first = true;
.iter() for (&sym, &(_, attr_span)) in &self.stcs {
.map(|(key, val, attr_span)| { if !first {
let key = ctx.get_ir(*key).compile(ctx); buf.push(',');
let val_expr = ctx.get_ir(*val); }
let val = val_expr.compile(ctx); first = false;
let span = val_expr.span();
let span = encode_span(span, ctx); buf.push_escaped_quote(ctx.get_sym(sym));
let val = format!( buf.push(':');
"Nix.withContext(\"while evaluating a dynamic attribute\",{},()=>({}))", buf.push_span(attr_span, ctx);
span, val }
);
let dyn_span_str = encode_span(*attr_span, ctx); buf.push_str("},{dynKeys:[");
(key, val, dyn_span_str) buf.write_join(self.dyns.iter(), ",", |b, (key, _, _)| {
}) ctx.get_ir(*key).compile(ctx, b);
.multiunzip::<(Vec<_>, Vec<_>, Vec<_>)>(); });
format!(
"Nix.mkAttrsWithPos({{{}}},{{{}}},{{dynKeys:[{}],dynVals:[{}],dynSpans:[{}]}})", buf.push_str("],dynVals:[");
attrs.join(","), buf.write_join(self.dyns.iter(), ",", |b, (_, val, _)| {
attr_positions.join(","), let val_ir = ctx.get_ir(*val);
keys.join(","), b.push_str("Nix.withContext(\"while evaluating a dynamic attribute\",");
vals.join(","), b.push_span(val_ir.span(), ctx);
dyn_spans.join(",") b.push_str(",()=>(");
) val_ir.compile(ctx, b);
} else if !attr_positions.is_empty() { b.push_str("))");
format!( });
"Nix.mkAttrsWithPos({{{}}},{{{}}})",
attrs.join(","), buf.push_str("],dynSpans:[");
attr_positions.join(",") buf.write_join(self.dyns.iter(), ",", |b, (_, _, attr_span)| {
) b.push_span(*attr_span, ctx);
});
buf.push_str("]})");
} else if !self.stcs.is_empty() {
buf.push_str("Nix.mkAttrsWithPos({");
let mut first = true;
for (&sym, &(expr, _)) in &self.stcs {
if !first {
buf.push(',');
}
first = false;
let key = ctx.get_sym(sym);
let value_ir = ctx.get_ir(expr);
buf.push_escaped_quote(key);
buf.push_str(":Nix.withContext(\"while evaluating the attribute '");
buf.push_str(key);
buf.push_str("'\",");
buf.push_span(value_ir.span(), ctx);
buf.push_str(",()=>(");
value_ir.compile(ctx, buf);
buf.push_str("))");
}
buf.push_str("},{");
let mut first = true;
for (&sym, &(_, attr_span)) in &self.stcs {
if !first {
buf.push(',');
}
first = false;
buf.push_escaped_quote(ctx.get_sym(sym));
buf.push(':');
buf.push_span(attr_span, ctx);
}
buf.push_str("})");
} else { } else {
format!("{{{}}}", attrs.join(",")) buf.push_str("{}");
} }
} }
} }
impl<Ctx: CodegenContext> Compile<Ctx> for List { impl<Ctx: CodegenContext> Compile<Ctx> for List {
fn compile(&self, ctx: &Ctx) -> String { fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
let list = self buf.push('[');
.items buf.write_join(self.items.iter().enumerate(), ",", |b, (idx, item)| {
.iter() let item_ir = ctx.get_ir(*item);
.enumerate() b.push_str("Nix.withContext(\"while evaluating list element ");
.map(|(idx, item)| { write_code!(b, "{}", idx);
let item_code = ctx.get_ir(*item).compile(ctx); b.push_str("\",");
let item_span = encode_span(ctx.get_ir(*item).span(), ctx); b.push_span(item_ir.span(), ctx);
format!( b.push_str(",()=>(");
"Nix.withContext(\"while evaluating list element {}\",{},()=>({}))", item_ir.compile(ctx, b);
idx, item_span, item_code b.push_str("))");
) });
}) buf.push(']');
.join(",");
format!("[{list}]")
} }
} }
impl<Ctx: CodegenContext> Compile<Ctx> for ConcatStrings { impl<Ctx: CodegenContext> Compile<Ctx> for ConcatStrings {
fn compile(&self, ctx: &Ctx) -> String { fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
let parts: Vec<String> = self buf.push_str("Nix.concatStringsWithContext([");
.parts buf.write_join(self.parts.iter(), ",", |b, part| {
.iter() let part_ir = ctx.get_ir(*part);
.map(|part| { b.push_str("Nix.withContext(\"while evaluating a path segment\",");
let part_code = ctx.get_ir(*part).compile(ctx); b.push_span(part_ir.span(), ctx);
let part_span = encode_span(ctx.get_ir(*part).span(), ctx); b.push_str(",()=>(");
format!( part_ir.compile(ctx, b);
"Nix.withContext(\"while evaluating a path segment\",{},()=>({}))", b.push_str("))");
part_span, part_code });
) buf.push_str("])");
})
.collect();
format!("Nix.concatStringsWithContext([{}])", parts.join(","))
} }
} }
impl<Ctx: CodegenContext> Compile<Ctx> for HasAttr { impl<Ctx: CodegenContext> Compile<Ctx> for HasAttr {
fn compile(&self, ctx: &Ctx) -> String { fn compile(&self, ctx: &Ctx, buf: &mut CodeBuffer) {
let lhs = ctx.get_ir(self.lhs).compile(ctx); buf.push_str("Nix.hasAttr(");
let attrpath = self ctx.get_ir(self.lhs).compile(ctx, buf);
.rhs buf.push_str(",[");
.iter() buf.write_join(self.rhs.iter(), ",", |b, attr| match attr {
.map(|attr| match attr { Attr::Str(sym, _) => b.push_escaped_quote(ctx.get_sym(*sym)),
Attr::Str(sym, _) => ctx.get_sym(*sym).escape_quote(), Attr::Dynamic(expr_id, _) => ctx.get_ir(*expr_id).compile(ctx, b),
Attr::Dynamic(expr_id, _) => ctx.get_ir(*expr_id).compile(ctx), });
}) buf.push_str("])");
.join(",");
format!("Nix.hasAttr({lhs},[{attrpath}])")
} }
} }