refactor(codegen): less allocation
This commit is contained in:
@@ -1,34 +1,158 @@
|
|||||||
|
use std::fmt::{self, Display, 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();
|
|
||||||
if std::env::var("NIX_JS_DEBUG_THUNKS").is_ok() {
|
|
||||||
debug_flags.push("Nix.DEBUG_THUNKS.enabled=true");
|
|
||||||
}
|
}
|
||||||
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();
|
impl fmt::Write for CodeBuffer {
|
||||||
format!(
|
#[inline]
|
||||||
"(()=>{{{}Nix.builtins.storeDir={};const currentDir={};return {}}})()",
|
fn write_str(&mut self, s: &str) -> fmt::Result {
|
||||||
debug_prefix,
|
self.buf.push_str(s);
|
||||||
ctx.get_store_dir().escape_quote(),
|
Ok(())
|
||||||
cur_dir,
|
}
|
||||||
code
|
}
|
||||||
|
|
||||||
|
impl CodeBuffer {
|
||||||
|
#[inline]
|
||||||
|
fn with_capacity(capacity: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
buf: String::with_capacity(capacity),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn push_str(&mut self, s: &str) {
|
||||||
|
self.buf.push_str(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
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('"');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Helper type for automatically escaping and quoting strings
|
||||||
|
struct Quoted<'a>(&'a str);
|
||||||
|
|
||||||
|
impl Display for Quoted<'_> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_char('"')?;
|
||||||
|
for c in self.0.chars() {
|
||||||
|
match c {
|
||||||
|
'\\' => f.write_str("\\\\")?,
|
||||||
|
'"' => f.write_str("\\\"")?,
|
||||||
|
'\n' => f.write_str("\\n")?,
|
||||||
|
'\r' => f.write_str("\\r")?,
|
||||||
|
'\t' => f.write_str("\\t")?,
|
||||||
|
_ => f.write_char(c)?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
f.write_char('"')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Helper function to create a quoted string
|
||||||
|
#[inline]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
fn quoted(s: &str) -> Quoted<'_> {
|
||||||
|
Quoted(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Helper type for formatting spans
|
||||||
|
struct Span<'a, Ctx> {
|
||||||
|
span: rnix::TextRange,
|
||||||
|
ctx: &'a Ctx,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Ctx: CodegenContext> Display for Span<'_, Ctx> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(
|
||||||
|
f,
|
||||||
|
"\"{}:{}:{}\"",
|
||||||
|
self.ctx.get_current_source_id(),
|
||||||
|
usize::from(self.span.start()),
|
||||||
|
usize::from(self.span.end())
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Helper function to create a span formatter
|
||||||
|
#[inline]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
fn span<Ctx>(s: rnix::TextRange, ctx: &Ctx) -> Span<'_, Ctx> {
|
||||||
|
Span { span: s, ctx }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ergonomic macro for code generation
|
||||||
|
macro_rules! code {
|
||||||
|
($buf:expr, $($arg:tt)*) => {
|
||||||
|
write!($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 +164,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(),
|
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(),
|
code!(buf, "{}", float.inner);
|
||||||
|
}
|
||||||
|
Ir::Bool(bool) => {
|
||||||
|
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 +193,195 @@ 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);
|
code!(
|
||||||
format!(
|
buf,
|
||||||
"(Nix.withContext(\"while evaluating a branch condition\",{},()=>Nix.forceBool({})))?({}):({})",
|
"(Nix.withContext(\"while evaluating a branch condition\",{},()=>Nix.forceBool(",
|
||||||
cond_span, cond_code, consq, alter
|
span(cond_span, ctx)
|
||||||
)
|
);
|
||||||
|
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),
|
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)
|
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())
|
code!(buf, "Nix.builtins[{}]", quoted(ctx.get_sym(name)));
|
||||||
}
|
}
|
||||||
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: assert_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);
|
code!(
|
||||||
format!(
|
buf,
|
||||||
"Nix.assert(Nix.withContext(\"while evaluating the condition of the assert statement\",{},()=>({})),{},{},{})",
|
"Nix.assert(Nix.withContext(\"while evaluating the condition of the assert statement\",{},()=>(",
|
||||||
assertion_span,
|
span(assertion_span, ctx)
|
||||||
assertion_code,
|
);
|
||||||
expr,
|
assertion_ir.compile(ctx, buf);
|
||||||
assertion_raw.escape_quote(),
|
buf.push_str(")),");
|
||||||
span
|
ctx.get_ir(expr).compile(ctx, buf);
|
||||||
)
|
code!(buf, ",{},{})", quoted(assertion_raw), span(assert_span, ctx));
|
||||||
}
|
}
|
||||||
Ir::CurPos(cur_pos) => {
|
Ir::CurPos(cur_pos) => {
|
||||||
let span_str = encode_span(cur_pos.span, ctx);
|
code!(buf, "Nix.mkPos({})", span(cur_pos.span, ctx));
|
||||||
format!("Nix.mkPos({})", span_str)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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!(),
|
||||||
|
};
|
||||||
|
|
||||||
|
code!(
|
||||||
|
buf,
|
||||||
|
"Nix.withContext(\"while evaluating the {} operator\",{},()=>({}",
|
||||||
|
op_name,
|
||||||
|
span(self.span, ctx),
|
||||||
|
op_func
|
||||||
|
);
|
||||||
|
lhs.compile(ctx, buf);
|
||||||
|
buf.push(',');
|
||||||
|
rhs.compile(ctx, buf);
|
||||||
|
buf.push_str(")))");
|
||||||
|
}
|
||||||
|
And => {
|
||||||
|
code!(
|
||||||
|
buf,
|
||||||
|
"Nix.withContext(\"while evaluating the && operator\",{},()=>(Nix.forceBool(",
|
||||||
|
span(self.span, ctx)
|
||||||
|
);
|
||||||
|
lhs.compile(ctx, buf);
|
||||||
|
buf.push_str(")&&Nix.forceBool(");
|
||||||
|
rhs.compile(ctx, buf);
|
||||||
|
buf.push_str(")))");
|
||||||
|
}
|
||||||
|
Or => {
|
||||||
|
code!(
|
||||||
|
buf,
|
||||||
|
"Nix.withContext(\"while evaluating the || operator\",{},()=>(Nix.forceBool(",
|
||||||
|
span(self.span, ctx)
|
||||||
|
);
|
||||||
|
lhs.compile(ctx, buf);
|
||||||
|
buf.push_str(")||Nix.forceBool(");
|
||||||
|
rhs.compile(ctx, buf);
|
||||||
|
buf.push_str(")))");
|
||||||
|
}
|
||||||
|
Impl => {
|
||||||
|
code!(
|
||||||
|
buf,
|
||||||
|
"Nix.withContext(\"while evaluating the -> operator\",{},()=>((!Nix.forceBool(",
|
||||||
|
span(self.span, ctx)
|
||||||
|
);
|
||||||
|
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 +389,268 @@ 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());
|
code!(buf, "Nix.mkFunction(arg{}=>", id);
|
||||||
let required = format!("[{}]", required.join(","));
|
if has_thunks {
|
||||||
let mut optional = optional.iter().map(|&sym| ctx.get_sym(sym).escape_quote());
|
buf.push('{');
|
||||||
let optional = format!("[{}]", optional.join(","));
|
compile_thunks(&self.thunks, ctx, buf);
|
||||||
if thunk_defs.is_empty() {
|
buf.push_str("return ");
|
||||||
format!("Nix.mkFunction(arg{id}=>({body}),{required},{optional},{ellipsis})")
|
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));
|
||||||
|
});
|
||||||
|
code!(buf, "],{})", ellipsis);
|
||||||
} else {
|
} else {
|
||||||
if thunk_defs.is_empty() {
|
code!(buf, "arg{}=>", id);
|
||||||
format!("arg{id}=>({body})")
|
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);
|
||||||
|
code!(buf, ",{})", span(self.span, ctx));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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!(
|
code!(buf, "let expr{}=Nix.createThunk(()=>(", slot.0);
|
||||||
"let expr{}=Nix.createThunk(()=>({}),\"expr{} {}:{}:{}\")",
|
inner_ir.compile(ctx, buf);
|
||||||
slot.0,
|
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, _) => code!(b, "{}", quoted(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);
|
||||||
|
code!(buf, ",{})", span(self.span, ctx));
|
||||||
} 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, _) => code!(b, "{}", quoted(ctx.get_sym(*sym))),
|
||||||
|
Attr::Dynamic(expr_id, _) => ctx.get_ir(*expr_id).compile(ctx, b),
|
||||||
|
});
|
||||||
|
code!(buf, "],{})", span(self.span, ctx));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
code!(
|
||||||
let value = format!(
|
buf,
|
||||||
"Nix.withContext(\"while evaluating the attribute '{}'\",{},()=>({}))",
|
"{}:Nix.withContext(\"while evaluating the attribute '{}'\",{},()=>(",
|
||||||
key, value_span, value_code
|
quoted(key),
|
||||||
|
key,
|
||||||
|
span(value_ir.span(), ctx)
|
||||||
);
|
);
|
||||||
attrs.push(format!("{}:{}", key.escape_quote(), value));
|
value_ir.compile(ctx, buf);
|
||||||
|
buf.push_str("))");
|
||||||
let attr_pos_str = encode_span(attr_span, ctx);
|
|
||||||
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);
|
code!(buf, "{}:{}", quoted(ctx.get_sym(sym)), span(attr_span, ctx));
|
||||||
let val = format!(
|
}
|
||||||
"Nix.withContext(\"while evaluating a dynamic attribute\",{},()=>({}))",
|
|
||||||
span, val
|
buf.push_str("},{dynKeys:[");
|
||||||
|
buf.write_join(self.dyns.iter(), ",", |b, (key, _, _)| {
|
||||||
|
ctx.get_ir(*key).compile(ctx, b);
|
||||||
|
});
|
||||||
|
|
||||||
|
buf.push_str("],dynVals:[");
|
||||||
|
buf.write_join(self.dyns.iter(), ",", |b, (_, val, _)| {
|
||||||
|
let val_ir = ctx.get_ir(*val);
|
||||||
|
code!(
|
||||||
|
b,
|
||||||
|
"Nix.withContext(\"while evaluating a dynamic attribute\",{},()=>(",
|
||||||
|
span(val_ir.span(), ctx)
|
||||||
);
|
);
|
||||||
let dyn_span_str = encode_span(*attr_span, ctx);
|
val_ir.compile(ctx, b);
|
||||||
(key, val, dyn_span_str)
|
b.push_str("))");
|
||||||
})
|
});
|
||||||
.multiunzip::<(Vec<_>, Vec<_>, Vec<_>)>();
|
|
||||||
format!(
|
buf.push_str("],dynSpans:[");
|
||||||
"Nix.mkAttrsWithPos({{{}}},{{{}}},{{dynKeys:[{}],dynVals:[{}],dynSpans:[{}]}})",
|
buf.write_join(self.dyns.iter(), ",", |b, (_, _, attr_span)| {
|
||||||
attrs.join(","),
|
code!(b, "{}", span(*attr_span, ctx));
|
||||||
attr_positions.join(","),
|
});
|
||||||
keys.join(","),
|
|
||||||
vals.join(","),
|
buf.push_str("]})");
|
||||||
dyn_spans.join(",")
|
} else if !self.stcs.is_empty() {
|
||||||
)
|
buf.push_str("Nix.mkAttrsWithPos({");
|
||||||
} else if !attr_positions.is_empty() {
|
|
||||||
format!(
|
let mut first = true;
|
||||||
"Nix.mkAttrsWithPos({{{}}},{{{}}})",
|
for (&sym, &(expr, _)) in &self.stcs {
|
||||||
attrs.join(","),
|
if !first {
|
||||||
attr_positions.join(",")
|
buf.push(',');
|
||||||
)
|
}
|
||||||
|
first = false;
|
||||||
|
|
||||||
|
let key = ctx.get_sym(sym);
|
||||||
|
let value_ir = ctx.get_ir(expr);
|
||||||
|
|
||||||
|
code!(
|
||||||
|
buf,
|
||||||
|
"{}:Nix.withContext(\"while evaluating the attribute '{}'\",{},()=>(",
|
||||||
|
quoted(key),
|
||||||
|
key,
|
||||||
|
span(value_ir.span(), ctx)
|
||||||
|
);
|
||||||
|
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;
|
||||||
|
|
||||||
|
code!(buf, "{}:{}", quoted(ctx.get_sym(sym)), 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()
|
code!(
|
||||||
.map(|(idx, item)| {
|
b,
|
||||||
let item_code = ctx.get_ir(*item).compile(ctx);
|
"Nix.withContext(\"while evaluating list element {}\",{},()=>(",
|
||||||
let item_span = encode_span(ctx.get_ir(*item).span(), ctx);
|
idx,
|
||||||
format!(
|
span(item_ir.span(), ctx)
|
||||||
"Nix.withContext(\"while evaluating list element {}\",{},()=>({}))",
|
);
|
||||||
idx, item_span, item_code
|
item_ir.compile(ctx, b);
|
||||||
)
|
b.push_str("))");
|
||||||
})
|
});
|
||||||
.join(",");
|
buf.push(']');
|
||||||
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| {
|
code!(
|
||||||
let part_code = ctx.get_ir(*part).compile(ctx);
|
b,
|
||||||
let part_span = encode_span(ctx.get_ir(*part).span(), ctx);
|
"Nix.withContext(\"while evaluating a path segment\",{},()=>(",
|
||||||
format!(
|
span(part_ir.span(), ctx)
|
||||||
"Nix.withContext(\"while evaluating a path segment\",{},()=>({}))",
|
);
|
||||||
part_span, part_code
|
part_ir.compile(ctx, b);
|
||||||
)
|
b.push_str("))");
|
||||||
})
|
});
|
||||||
.collect();
|
buf.push_str("])");
|
||||||
|
|
||||||
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, _) => code!(b, "{}", quoted(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}])")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user