Compare commits

..
1 Commits
66 changed files with 1762 additions and 3322 deletions
Generated
+381 -300
View File
File diff suppressed because it is too large Load Diff
+7 -67
View File
@@ -22,77 +22,17 @@ bumpalo = {
}
ere = "0.2"
ghost-cell = "0.2"
hashbrown = "0.17"
num_enum = "0.7"
hashbrown = "0.16"
num_enum = "0.7.5"
rnix = "0.14"
rowan = "0.16"
smallvec = { version = "1.15", features = ["const_generics", "const_new"] }
string-interner = "0.20"
gc-arena = { version = "0.7", features = ["hashbrown", "smallvec"] }
string-interner = "0.19"
# https://emschwartz.me/your-clippy-config-should-be-stricter/
# tombi: format.rules.table-keys-order.disabled = true
[workspace.lints.clippy]
# Don't Panic - prevent panics from unwraps and unsafe slicing or indexing
string_slice = "warn"
indexing_slicing = "warn"
unwrap_used = "warn"
panic = "warn"
# WIP evaluator: several features are deliberately stubbed with todo!/unimplemented!
todo = "allow"
unimplemented = "allow"
unreachable = "warn"
get_unwrap = "warn"
unwrap_in_result = "warn"
unchecked_time_subtraction = "warn"
panic_in_result_fn = "warn"
# Optional - see post for caveats
# expect_used = "warn"
# arithmetic_side_effects = "warn"
# Don't Fail Silently - prevent dropped futures and swallowed errors
let_underscore_future = "warn"
let_underscore_must_use = "warn"
unused_result_ok = "warn"
map_err_ignore = "warn"
assertions_on_result_states = "warn"
# Don't Do Bad Async Stuff - prevent deadlocks and concurrency bugs
await_holding_lock = "warn"
await_holding_refcell_ref = "warn"
if_let_mutex = "warn" # only relevant on editions before 2024
large_futures = "warn"
# Don't Do Unsafe Things with Memory
mem_forget = "warn"
undocumented_unsafe_blocks = "warn"
multiple_unsafe_ops_per_block = "warn"
unnecessary_safety_doc = "warn"
unnecessary_safety_comment = "warn"
# Don't Do Potentially Incorrect Things with Numbers
float_cmp = "warn"
float_cmp_const = "warn"
lossy_float_literal = "warn"
cast_sign_loss = "warn"
invalid_upcast_comparisons = "warn"
# Optional - these effectively force you to document numeric invariants
# cast_possible_wrap = "warn"
# cast_precision_loss = "warn"
# cast_possible_truncation = "warn"
# Don't Do Bad Things That are Easy to Avoid
rc_mutex = "warn"
debug_assert_with_mut_call = "warn"
iter_not_returning_iterator = "warn"
expl_impl_clone_on_copy = "warn"
infallible_try_from = "warn"
dbg_macro = "warn"
# Don't `allow` Your Way Around These Lints - every suppression must be
# a deliberate #[expect(..., reason = "…")] rather than a silent #[allow]
allow_attributes = "warn"
allow_attributes_without_reason = "warn"
[workspace.dependencies.gc-arena]
git = "https://github.com/kyren/gc-arena"
rev = "75671ae03f53718357b741ed4027560f14e90836"
features = ["allocator-api2", "hashbrown", "smallvec"]
[profile.lto]
inherits = "release"
+16
View File
@@ -14,6 +14,22 @@
@evalr expr:
cargo run --release -- eval --expr '{{expr}}'
[no-exit-message]
@repli:
cargo run --release --features inspector -- --inspect-brk 127.0.0.1:9229 repl
[no-exit-message]
@evali expr:
cargo run --release --features inspector -- --inspect-brk 127.0.0.1:9229 eval --expr '{{expr}}'
[no-exit-message]
@replp:
cargo run --release --features prof -- repl
[no-exit-message]
@evalp expr:
cargo run --release --features prof -- eval --expr '{{expr}}'
[no-exit-message]
[positional-arguments]
@cg *args='':
-5
View File
@@ -1,5 +0,0 @@
allow-indexing-slicing-in-tests = true
allow-panic-in-tests = true
allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-dbg-in-tests = true
-24
View File
@@ -1,24 +0,0 @@
{ pkgs }:
pkgs.mkShell {
packages = with pkgs; [
(fenix.latest.withComponents [
"cargo"
"clippy"
"rust-src"
"rustc"
"rustfmt"
"rust-analyzer"
])
cargo-machete
cargo-bloat
cargo-expand
lldb
valgrind
kdePackages.kcachegrind
hyperfine
just
samply
tokei
tombi
];
}
-3
View File
@@ -9,6 +9,3 @@ num_enum = { workspace = true }
string-interner = { workspace = true }
fix-lang = { path = "../fix-lang" }
[lints]
workspace = true
+152 -79
View File
@@ -2,7 +2,7 @@ use std::fmt::Write;
use colored::Colorize as _;
use crate::{BytecodeReader, Continuation, InstructionPtr, Op};
use crate::{Continuation, InstructionPtr, Op, OperandType};
pub trait DisassemblerContext {
fn resolve_string(&self, id: u32) -> &str;
@@ -10,15 +10,99 @@ pub trait DisassemblerContext {
}
pub struct Disassembler<'a, Ctx> {
reader: BytecodeReader<'a>,
code: &'a [u8],
ctx: &'a Ctx,
pc: usize,
}
impl<'a, Ctx: DisassemblerContext> Disassembler<'a, Ctx> {
pub fn new(ip: InstructionPtr, ctx: &'a Ctx) -> Self {
Self {
reader: BytecodeReader::new(ctx.get_code(), ip.0),
code: ctx.get_code(),
ctx,
pc: ip.0,
}
}
#[inline(always)]
fn read_u8(&mut self) -> u8 {
let b = self.code[self.pc];
self.pc += 1;
b
}
#[inline(always)]
fn read_u16(&mut self) -> u16 {
let bytes = self.code[self.pc..self.pc + 2]
.try_into()
.expect("no enough bytes");
self.pc += 2;
u16::from_le_bytes(bytes)
}
#[inline(always)]
fn read_u32(&mut self) -> u32 {
let bytes = self.code[self.pc..self.pc + 4]
.try_into()
.expect("no enough bytes");
self.pc += 4;
u32::from_le_bytes(bytes)
}
#[inline(always)]
fn read_i32(&mut self) -> i32 {
let bytes = self.code[self.pc..self.pc + 4]
.try_into()
.expect("no enough bytes");
self.pc += 4;
i32::from_le_bytes(bytes)
}
#[inline(always)]
fn read_i64(&mut self) -> i64 {
let bytes = self.code[self.pc..self.pc + 8]
.try_into()
.expect("no enough bytes");
self.pc += 8;
i64::from_le_bytes(bytes)
}
#[inline(always)]
fn read_f64(&mut self) -> f64 {
let bytes = self.code[self.pc..self.pc + 8]
.try_into()
.expect("no enough bytes");
self.pc += 8;
f64::from_le_bytes(bytes)
}
#[inline(always)]
fn read_operand_data(&mut self) {
use OperandType::*;
let tag = self.read_u8();
let ty = OperandType::try_from(tag).expect("invalid operand type");
match ty {
Const => {
self.read_u32();
}
BigInt => {
self.read_i64();
}
Local => {
self.read_u8();
self.read_u32();
}
BuiltinConst => {
self.read_u32();
}
Builtins => {}
ReplBinding => {
self.read_u32();
}
ScopedImportBinding => {
self.read_u32();
self.read_u32();
}
}
}
@@ -30,11 +114,6 @@ impl<'a, Ctx: DisassemblerContext> Disassembler<'a, Ctx> {
self.disassemble_impl(true)
}
#[expect(
clippy::let_underscore_must_use,
clippy::indexing_slicing,
reason = "disassembler operates on well-formed bytecode; writes target an in-memory String via fmt::Write, which is infallible"
)]
fn disassemble_impl(&mut self, color: bool) -> String {
let mut out = String::new();
if color {
@@ -43,24 +122,24 @@ impl<'a, Ctx: DisassemblerContext> Disassembler<'a, Ctx> {
out,
"{} {}",
"Length:".white(),
format!("{} bytes", self.reader.len()).cyan()
format!("{} bytes", self.code.len()).cyan()
);
} else {
let _ = writeln!(out, "=== Bytecode Disassembly ===");
let _ = writeln!(out, "Length: {} bytes", self.reader.len());
let _ = writeln!(out, "Length: {} bytes", self.code.len());
}
while self.reader.pc() < self.reader.len() {
let start_pos = self.reader.pc();
let op_byte = self.reader.read_u8();
while self.pc < self.code.len() {
let start_pos = self.pc;
let op_byte = self.read_u8();
let (mnemonic, args) = self.decode_instruction(op_byte, start_pos);
let bytes_slice = &self.reader[start_pos + 1..self.reader.pc()];
let bytes_slice = &self.code[start_pos + 1..self.pc];
let mut chunks = bytes_slice.chunks(4);
let first_chunk = chunks.next().unwrap_or(&[]);
let bytes_str = {
let mut temp = format!("{:02x}", self.reader[start_pos]);
let mut temp = format!("{:02x}", self.code[start_pos]);
for b in first_chunk {
let _ = write!(&mut temp, " {:02x}", b);
}
@@ -120,36 +199,31 @@ impl<'a, Ctx: DisassemblerContext> Disassembler<'a, Ctx> {
out
}
#[expect(
clippy::let_underscore_must_use,
clippy::cast_sign_loss,
reason = "disassembler operates on well-formed bytecode; jump targets are valid non-negative PCs and writes to String are infallible"
)]
fn decode_instruction(&mut self, op_byte: u8, current_pc: usize) -> (&'static str, String) {
let op = Op::try_from(op_byte).expect("invalid op code");
match op {
Op::PushSmi => {
let val = self.reader.read_i32();
let val = self.read_i32();
("PushSmi", format!("{}", val))
}
Op::PushBigInt => {
let val = self.reader.read_i64();
let val = self.read_i64();
("PushBigInt", format!("{}", val))
}
Op::PushFloat => {
let val = self.reader.read_f64();
let val = self.read_f64();
("PushFloat", format!("{}", val))
}
Op::PushString => {
let idx = self.reader.read_u32();
let idx = self.read_u32();
let s = self.ctx.resolve_string(idx);
let len = s.len();
let mut s_fmt = format!("{:?}", s);
if s_fmt.len() > 60 {
s_fmt.truncate(57);
write!(s_fmt, "...\" (total {len} bytes)")
.expect("writing to String is infallible");
#[allow(clippy::unwrap_used)]
write!(s_fmt, "...\" (total {len} bytes)").unwrap();
}
("PushString", format!("@{} {}", idx, s_fmt))
}
@@ -158,38 +232,38 @@ impl<'a, Ctx: DisassemblerContext> Disassembler<'a, Ctx> {
Op::PushFalse => ("PushFalse", String::new()),
Op::LoadLocal => {
let idx = self.reader.read_u32();
let idx = self.read_u32();
("LoadLocal", format!("[{}]", idx))
}
Op::LoadOuter => {
let depth = self.reader.read_u8();
let idx = self.reader.read_u32();
let depth = self.read_u8();
let idx = self.read_u32();
("LoadOuter", format!("depth={} [{}]", depth, idx))
}
Op::StoreLocal => {
let idx = self.reader.read_u32();
let idx = self.read_u32();
("StoreLocal", format!("[{}]", idx))
}
Op::AllocLocals => {
let count = self.reader.read_u32();
let count = self.read_u32();
("AllocLocals", format!("count={}", count))
}
Op::MakeThunk => {
let offset = self.reader.read_u32();
let offset = self.read_u32();
("MakeThunk", format!("-> {:04x}", offset))
}
Op::MakeClosure => {
let offset = self.reader.read_u32();
let slots = self.reader.read_u32();
let offset = self.read_u32();
let slots = self.read_u32();
("MakeClosure", format!("-> {:04x} slots={}", offset, slots))
}
Op::MakePatternClosure => {
let offset = self.reader.read_u32();
let slots = self.reader.read_u32();
let req_count = self.reader.read_u16();
let opt_count = self.reader.read_u16();
let ellipsis = self.reader.read_u8() != 0;
let offset = self.read_u32();
let slots = self.read_u32();
let req_count = self.read_u16();
let opt_count = self.read_u16();
let ellipsis = self.read_u8() != 0;
let mut arg_str = format!(
"-> {:04x} slots={} req={} opt={} ...={})",
@@ -198,18 +272,18 @@ impl<'a, Ctx: DisassemblerContext> Disassembler<'a, Ctx> {
arg_str.push_str(" Args=[");
for _ in 0..req_count {
let idx = self.reader.read_u32();
let idx = self.read_u32();
arg_str.push_str(&format!("Req({}) ", self.ctx.resolve_string(idx)));
}
for _ in 0..opt_count {
let idx = self.reader.read_u32();
let idx = self.read_u32();
arg_str.push_str(&format!("Opt({}) ", self.ctx.resolve_string(idx)));
}
let total_args = req_count + opt_count;
for _ in 0..total_args {
let _name_idx = self.reader.read_u32();
let _span_id = self.reader.read_u32();
let _name_idx = self.read_u32();
let _span_id = self.read_u32();
}
arg_str.push(']');
@@ -217,32 +291,31 @@ impl<'a, Ctx: DisassemblerContext> Disassembler<'a, Ctx> {
}
Op::Call => {
let _ = self.reader.read_operand_data();
self.read_operand_data();
("Call", "arg=?".into())
}
Op::DispatchCont => {
let phase =
Continuation::try_from(self.reader.read_u8()).expect("invalid primop phase");
let phase = Continuation::try_from(self.read_u8()).expect("invalid primop phase");
("DispatchPrimOp", format!("phase={phase:?}"))
}
Op::MakeAttrs => {
let static_count = self.reader.read_u32();
let dynamic_count = self.reader.read_u32();
let static_count = self.read_u32();
let dynamic_count = self.read_u32();
let mut args = format!("static={} dynamic={}", static_count, dynamic_count);
for _ in 0..static_count {
let key_id = self.reader.read_u32();
let key_id = self.read_u32();
let _ = write!(args, " [{}={}", self.ctx.resolve_string(key_id), key_id);
let _ = self.reader.read_operand_data();
let _span_id = self.reader.read_u32();
self.read_operand_data();
let _span_id = self.read_u32();
args.push(']');
}
for _ in 0..dynamic_count {
let _ = write!(args, " [dyn");
let _ = self.reader.read_operand_data();
let _span_id = self.reader.read_u32();
self.read_operand_data();
let _span_id = self.read_u32();
args.push(']');
}
@@ -251,31 +324,31 @@ impl<'a, Ctx: DisassemblerContext> Disassembler<'a, Ctx> {
Op::MakeEmptyAttrs => ("MakeEmptyAttrs", String::new()),
Op::SelectStatic => {
let span_id = self.reader.read_u32();
let key_id = self.reader.read_u32();
let span_id = self.read_u32();
let key_id = self.read_u32();
(
"SelectStatic",
format!("key={} span={}", self.ctx.resolve_string(key_id), span_id),
)
}
Op::SelectDynamic => {
let span_id = self.reader.read_u32();
let span_id = self.read_u32();
("SelectDynamic", format!("span={}", span_id))
}
Op::HasAttrPathStatic => {
let span_id = self.reader.read_u32();
let key_id = self.reader.read_u32();
let span_id = self.read_u32();
let key_id = self.read_u32();
(
"HasAttrPathStatic",
format!("key={} span={}", self.ctx.resolve_string(key_id), span_id),
)
}
Op::HasAttrPathDynamic => {
let span_id = self.reader.read_u32();
let span_id = self.read_u32();
("HasAttrPathDynamic", format!("span={}", span_id))
}
Op::HasAttrStatic => {
let key_id = self.reader.read_u32();
let key_id = self.read_u32();
(
"HasAttrStatic",
format!("key={}", self.ctx.resolve_string(key_id)),
@@ -284,7 +357,7 @@ impl<'a, Ctx: DisassemblerContext> Disassembler<'a, Ctx> {
Op::HasAttrDynamic => ("HasAttrDynamic", String::new()),
Op::HasAttrResolve => ("HasAttrResolve", String::new()),
Op::JumpIfSelectSucceeded => {
let offset = self.reader.read_i32();
let offset = self.read_i32();
let target = (current_pc as isize + 1 + 4 + offset as isize) as usize;
(
"JumpIfSelectSucceeded",
@@ -292,7 +365,7 @@ impl<'a, Ctx: DisassemblerContext> Disassembler<'a, Ctx> {
)
}
Op::JumpIfSelectFailed => {
let offset = self.reader.read_i32();
let offset = self.read_i32();
let target = (current_pc as isize + 1 + 4 + offset as isize) as usize;
(
"JumpIfSelectFailed",
@@ -301,9 +374,9 @@ impl<'a, Ctx: DisassemblerContext> Disassembler<'a, Ctx> {
}
Op::MakeList => {
let count = self.reader.read_u32();
let count = self.read_u32();
for _ in 0..count {
let _ = self.reader.read_operand_data();
self.read_operand_data();
}
("MakeList", format!("size={}", count))
}
@@ -325,7 +398,7 @@ impl<'a, Ctx: DisassemblerContext> Disassembler<'a, Ctx> {
Op::OpNot => ("OpNot", String::new()),
Op::JumpIfFalse => {
let offset = self.reader.read_i32();
let offset = self.read_i32();
let target = (current_pc as isize + 1 + 4 + offset as isize) as usize;
(
"JumpIfFalse",
@@ -333,55 +406,55 @@ impl<'a, Ctx: DisassemblerContext> Disassembler<'a, Ctx> {
)
}
Op::JumpIfTrue => {
let offset = self.reader.read_i32();
let offset = self.read_i32();
let target = (current_pc as isize + 1 + 4 + offset as isize) as usize;
("JumpIfTrue", format!("-> {:04x} offset={}", target, offset))
}
Op::Jump => {
let offset = self.reader.read_i32();
let offset = self.read_i32();
let target = (current_pc as isize + 1 + 4 + offset as isize) as usize;
("Jump", format!("-> {:04x} offset={}", target, offset))
}
Op::ConcatStrings => {
let count = self.reader.read_u16();
let force = self.reader.read_u8();
let count = self.read_u16();
let force = self.read_u8();
("ConcatStrings", format!("count={} force={}", count, force))
}
Op::CoerceToString => ("CoerceToString", String::new()),
Op::ResolvePath => {
let dir_id = self.reader.read_u32();
let dir_id = self.read_u32();
let dir = self.ctx.resolve_string(dir_id);
("ResolvePath", format!("dir={:?}", dir))
}
Op::Assert => {
let raw_idx = self.reader.read_u32();
let span_id = self.reader.read_u32();
let raw_idx = self.read_u32();
let span_id = self.read_u32();
("Assert", format!("text_id={} span={}", raw_idx, span_id))
}
Op::LookupWith => {
let idx = self.reader.read_u32();
let idx = self.read_u32();
let name = self.ctx.resolve_string(idx);
let n = self.reader.read_u8();
let n = self.read_u8();
for _ in 0..n {
let _ = self.reader.read_operand_data();
self.read_operand_data();
}
("LookupWith", format!("sym={:?} n={}", name, n))
}
Op::LoadBuiltins => ("LoadBuiltins", String::new()),
Op::LoadBuiltin => {
let id = self.reader.read_u8();
let id = self.read_u8();
("LoadBuiltin", format!("id={}", id))
}
Op::LoadReplBinding => {
let idx = self.reader.read_u32();
let idx = self.read_u32();
let name = self.ctx.resolve_string(idx);
("LoadReplBinding", format!("{:?}", name))
}
Op::LoadScopedBinding => {
let slot = self.reader.read_u32();
let idx = self.reader.read_u32();
let slot = self.read_u32();
let idx = self.read_u32();
let name = self.ctx.resolve_string(idx);
("LoadScopedBinding", format!("slot={} {:?}", slot, name))
}
+114 -195
View File
@@ -1,7 +1,4 @@
#![allow(
dead_code,
reason = "crate is under active development; some opcodes and helpers are not yet wired up"
)]
#![allow(dead_code)]
use fix_lang::{BuiltinId, StringId};
use num_enum::TryFromPrimitive;
@@ -13,7 +10,8 @@ pub mod disassembler;
pub struct InstructionPtr(pub usize);
#[repr(u8)]
#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone, Copy, TryFromPrimitive)]
#[allow(clippy::enum_variant_names)]
pub enum Op {
PushSmi,
PushBigInt,
@@ -90,21 +88,6 @@ pub enum Op {
Illegal,
}
impl TryFrom<u8> for Op {
type Error = u8;
#[inline(always)]
fn try_from(value: u8) -> Result<Self, Self::Error> {
if (0..Self::Illegal as u8).contains(&value) {
// SAFETY: `value` is in `0..Illegal`, which are exactly the valid
// discriminants of this `#[repr(u8)]` enum, so the transmute is sound.
Ok(unsafe { std::mem::transmute::<u8, Self>(value) })
} else {
Err(value)
}
}
}
#[repr(u8)]
#[derive(Debug, Clone, Copy, TryFromPrimitive)]
pub enum OperandType {
@@ -123,7 +106,11 @@ pub enum Const {
Bool(bool),
String(StringId),
Path(StringId),
PrimOp(BuiltinId),
PrimOp {
id: BuiltinId,
arity: u8,
dispatch_ip: u32,
},
Null,
}
@@ -152,15 +139,13 @@ pub enum Continuation {
PAdd,
PAddErrorContext,
PAll0,
PAll1,
PAll2,
PAll3,
PAll,
PAllCallPred,
PAllCheck,
PAny0,
PAny1,
PAny2,
PAny3,
PAny,
PAnyCallPred,
PAnyCheck,
PAppendContext,
PAppendContextLoop,
@@ -184,12 +169,9 @@ pub enum Continuation {
PConcatStringsSep,
PConvertHash,
PDeepSeq0,
PDeepSeq1,
PDeepSeq2,
PDeepSeq3,
PDeepSeq4,
PDeepSeq5,
PDeepSeq,
PDeepSeqPush,
PDeepSeqLoop,
PDerivation,
PDerivationStrict,
@@ -203,21 +185,18 @@ pub enum Continuation {
PFetchTree,
PFetchUrl,
PFilter0,
PFilter1,
PFilter2,
PFilter3,
PFilter4,
PFilterForceList,
PFilterCallPred,
PFilterCheck,
PFilterSource,
PFindFile,
PFloor,
PFoldlStrict0,
PFoldlStrict1,
PFoldlStrict2,
PFoldlStrict3,
PFoldlStrict4,
PFoldlStrict5,
PFoldlStrict,
PFoldlStrictEmpty,
PFoldlStrictCall1,
PFoldlStrictCall2,
PFoldlStrictUpdate,
PFromJSON,
PFromTOML,
PFunctionArgs,
@@ -265,8 +244,7 @@ pub enum Continuation {
PReadFileType,
PRemoveAttrs,
PReplaceStrings,
PSeq0,
PSeq1,
PSeq,
PSort,
PSplit,
PSplitVersion,
@@ -308,11 +286,8 @@ pub enum Continuation {
impl TryFrom<u8> for Continuation {
type Error = u8;
#[inline(always)]
fn try_from(value: u8) -> Result<Self, Self::Error> {
if (0..Self::Illegal as u8).contains(&value) {
// SAFETY: `value` is in `0..Illegal`, which are exactly the valid
// discriminants of this `#[repr(u8)]` enum, so the transmute is sound.
Ok(unsafe { std::mem::transmute::<u8, Self>(value) })
} else {
Err(value)
@@ -321,14 +296,14 @@ impl TryFrom<u8> for Continuation {
}
impl Continuation {
pub const fn entry_for_builtin(id: BuiltinId) -> Self {
pub fn entry_for_builtin(id: BuiltinId) -> Self {
use BuiltinId::*;
match id {
Abort => Self::PAbort,
Add => Self::PAdd,
AddErrorContext => Self::PAddErrorContext,
All => Self::PAll0,
Any => Self::PAny0,
All => Self::PAll,
Any => Self::PAny,
AppendContext => Self::PAppendContext,
AttrNames => Self::PAttrNames,
AttrValues => Self::PAttrValues,
@@ -344,7 +319,7 @@ impl Continuation {
ConcatMap => Self::PConcatMap,
ConcatStringsSep => Self::PConcatStringsSep,
ConvertHash => Self::PConvertHash,
DeepSeq => Self::PDeepSeq0,
DeepSeq => Self::PDeepSeq,
Derivation => Self::PDerivation,
DerivationStrict => Self::PDerivationStrict,
DirOf => Self::PDirOf,
@@ -356,11 +331,11 @@ impl Continuation {
FetchTarball => Self::PFetchTarball,
FetchTree => Self::PFetchTree,
FetchUrl => Self::PFetchUrl,
Filter => Self::PFilter0,
Filter => Self::PFilterForceList,
FilterSource => Self::PFilterSource,
FindFile => Self::PFindFile,
Floor => Self::PFloor,
FoldlStrict => Self::PFoldlStrict0,
FoldlStrict => Self::PFoldlStrict,
FromJSON => Self::PFromJSON,
FromTOML => Self::PFromTOML,
FunctionArgs => Self::PFunctionArgs,
@@ -404,7 +379,7 @@ impl Continuation {
RemoveAttrs => Self::PRemoveAttrs,
ReplaceStrings => Self::PReplaceStrings,
ScopedImport => Self::PScopedImport,
Seq => Self::PSeq0,
Seq => Self::PSeq,
Sort => Self::PSort,
Split => Self::PSplit,
SplitVersion => Self::PSplitVersion,
@@ -430,7 +405,7 @@ impl Continuation {
}
}
pub const fn ip(self) -> u32 {
pub fn ip(self) -> u32 {
self as u32 * 2
}
}
@@ -441,129 +416,7 @@ pub struct BytecodeReader<'a> {
inst_start_pc: usize,
}
impl std::ops::Deref for BytecodeReader<'_> {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.bytecode
}
}
pub trait FromBytecode {
#[must_use]
fn read(reader: &mut BytecodeReader<'_>) -> Self;
}
impl<const N: usize> FromBytecode for [u8; N] {
#[inline(always)]
#[expect(
clippy::indexing_slicing,
reason = "reads well-formed bytecode; an out-of-range PC indicates a codegen bug and should panic loudly"
)]
fn read(reader: &mut BytecodeReader<'_>) -> Self {
let ret = reader.bytecode[reader.pc..reader.pc + N]
.try_into()
.expect("read_array failed");
reader.pc += N;
ret
}
}
impl FromBytecode for u8 {
#[inline(always)]
fn read(reader: &mut BytecodeReader<'_>) -> Self {
let [byte] = reader.read();
byte
}
}
macro_rules! numbers_impl {
( $($ty:ty),* ) => {
$(
impl FromBytecode for $ty {
#[inline(always)]
fn read(reader: &mut BytecodeReader<'_>) -> Self {
<$ty>::from_le_bytes(FromBytecode::read(reader))
}
}
)*
};
}
numbers_impl!(u16, u32, i32, i64, f64);
impl FromBytecode for Op {
#[inline(always)]
#[expect(
clippy::panic,
reason = "reads well-formed bytecode; an unknown opcode indicates a codegen bug and should panic loudly"
)]
fn read(reader: &mut BytecodeReader<'_>) -> Self {
reader.inst_start_pc = reader.pc;
let byte: u8 = reader.read();
byte.try_into().unwrap_or_else(|byte| {
std::hint::cold_path();
panic!("unknown opcode: {byte:#04x}")
})
}
}
impl FromBytecode for StringId {
#[inline(always)]
fn read(reader: &mut BytecodeReader<'_>) -> Self {
let raw: u32 = reader.read();
StringId(
string_interner::symbol::SymbolU32::try_from_usize(raw as usize)
.expect("raw is a valid interner symbol index"),
)
}
}
impl FromBytecode for OperandData {
#[inline(always)]
#[expect(
clippy::panic,
reason = "an unknown operand tag in well-formed bytecode indicates a codegen bug and should panic loudly"
)]
fn read(reader: &mut BytecodeReader<'_>) -> Self {
let tag = reader.read();
let ty = OperandType::try_from_primitive(tag).unwrap_or_else(|err| {
std::hint::cold_path();
panic!("unknown operand tag: {:#04x}", err.number)
});
match ty {
OperandType::Const => OperandData::Const(reader.read()),
OperandType::BigInt => OperandData::BigInt(reader.read()),
OperandType::Local => {
let layer = reader.read();
let idx = reader.read();
OperandData::Local { layer, idx }
}
OperandType::BuiltinConst => OperandData::BuiltinConst(reader.read()),
OperandType::Builtins => OperandData::Builtins,
OperandType::ReplBinding => OperandData::ReplBinding(reader.read()),
OperandType::ScopedImportBinding => {
let slot_id = reader.read();
let name = reader.read();
OperandData::ScopedImportBinding { slot_id, name }
}
}
}
}
macro_rules! read_aliases {
{ $($alias:ident -> $ty:ty),*$(,)? } => {
$(
#[inline(always)]
#[must_use]
pub fn $alias(&mut self) -> $ty {
<$ty>::read(self)
}
)*
};
}
impl<'a> BytecodeReader<'a> {
#[must_use]
pub fn new(bytecode: &'a [u8], pc: usize) -> Self {
Self {
bytecode,
@@ -573,7 +426,6 @@ impl<'a> BytecodeReader<'a> {
}
#[inline(always)]
#[must_use]
pub fn from_after_op(bytecode: &'a [u8], inst_start_pc: usize) -> Self {
Self {
bytecode,
@@ -583,21 +435,88 @@ impl<'a> BytecodeReader<'a> {
}
#[inline(always)]
#[must_use]
pub fn read<T: FromBytecode>(&mut self) -> T {
T::read(self)
#[cfg_attr(debug_assertions, track_caller)]
fn read_array<const N: usize>(&mut self) -> [u8; N] {
let ret = self.bytecode[self.pc..self.pc + N]
.try_into()
.expect("read_array failed");
self.pc += N;
ret
}
read_aliases! {
read_op -> Op,
read_u8 -> u8,
read_u16 -> u16,
read_u32 -> u32,
read_i32 -> i32,
read_i64 -> i64,
read_f64 -> f64,
read_string_id -> StringId,
read_operand_data -> OperandData,
#[inline(always)]
pub fn read_op(&mut self) -> Op {
self.inst_start_pc = self.pc;
let byte = self.bytecode[self.pc];
if !(0..Op::Illegal as u8).contains(&byte) {
std::hint::cold_path();
panic!("unknown opcode: {byte:#04x}")
}
self.pc += 1;
unsafe { std::mem::transmute::<u8, Op>(byte) }
}
#[inline(always)]
pub fn read_u8(&mut self) -> u8 {
let val = self.bytecode[self.pc];
self.pc += 1;
val
}
#[inline(always)]
pub fn read_u16(&mut self) -> u16 {
u16::from_le_bytes(self.read_array())
}
#[inline(always)]
pub fn read_u32(&mut self) -> u32 {
u32::from_le_bytes(self.read_array())
}
#[inline(always)]
pub fn read_i32(&mut self) -> i32 {
i32::from_le_bytes(self.read_array())
}
#[inline(always)]
pub fn read_i64(&mut self) -> i64 {
i64::from_le_bytes(self.read_array())
}
#[inline(always)]
pub fn read_f64(&mut self) -> f64 {
f64::from_le_bytes(self.read_array())
}
#[inline(always)]
pub fn read_string_id(&mut self) -> StringId {
let raw = self.read_u32();
#[allow(clippy::unwrap_used)]
StringId(string_interner::symbol::SymbolU32::try_from_usize(raw as usize).unwrap())
}
#[inline(always)]
pub fn read_operand_data(&mut self) -> OperandData {
let tag = self.read_u8();
let Ok(ty) = OperandType::try_from_primitive(tag)
.map_err(|err| panic!("unknown operand tag: {:#04x}", err.number));
match ty {
OperandType::Const => OperandData::Const(self.read_u32()),
OperandType::BigInt => OperandData::BigInt(self.read_i64()),
OperandType::Local => {
let layer = self.read_u8();
let idx = self.read_u32();
OperandData::Local { layer, idx }
}
OperandType::BuiltinConst => OperandData::BuiltinConst(self.read_string_id()),
OperandType::Builtins => OperandData::Builtins,
OperandType::ReplBinding => OperandData::ReplBinding(self.read_string_id()),
OperandType::ScopedImportBinding => {
let slot_id = self.read_u32();
let name = self.read_string_id();
OperandData::ScopedImportBinding { slot_id, name }
}
}
}
pub fn pc(&self) -> usize {
-3
View File
@@ -17,6 +17,3 @@ fix-error = { path = "../fix-error" }
fix-lang = { path = "../fix-lang" }
fix-runtime = { path = "../fix-runtime" }
tracing = "0.1"
[lints]
workspace = true
+16 -44
View File
@@ -114,13 +114,8 @@ impl<'a, R: VmRuntimeCtx> CompilerCtx<'a, R> {
source,
);
let ir = downgrade_ctx.downgrade_toplevel(expr)?;
// SAFETY: `ir` borrows from `bump`, which is moved into the returned
// `OwnedIr` alongside the reference. The `'static` lifetime is a
// storage token that is re-narrowed to the `OwnedIr`'s own borrow in
// `as_ref`, so no reference ever outlives the arena backing it.
let ir = unsafe { std::mem::transmute::<RawIrRef<'_>, RawIrRef<'static>>(ir) };
// SAFETY: `ir` borrows from `bump`
Ok(unsafe { OwnedIr::new(bump, ir) })
Ok(OwnedIr { _bump: bump, ir })
})
}
}
@@ -154,11 +149,15 @@ impl<'a, R: VmRuntimeCtx> BytecodeContext for CompilerCtx<'a, R> {
use Const::*;
let val = match val {
Smi(x) => StaticValue::new(x),
Float(x) => StaticValue::new(x),
Float(x) => StaticValue::new_float(x),
Bool(x) => StaticValue::new(x),
String(x) => StaticValue::new(x),
Path(x) => StaticValue::new(fix_runtime::Path(x)),
PrimOp(id) => StaticValue::new(fix_runtime::PrimOp::from(id)),
PrimOp {
id,
arity,
dispatch_ip,
} => StaticValue::new_primop(id, arity, dispatch_ip),
Null => StaticValue::default(),
};
self.runtime.add_const(val)
@@ -285,10 +284,6 @@ impl<'ctx: 'ir, 'id, 'ir, R: VmRuntimeCtx> DowngradeContext<'id, 'ir>
self.runtime.resolve_string(id).into()
}
#[expect(
clippy::unwrap_in_result,
reason = "exceeding u8::MAX thunk scope layers is a compiler invariant violation, not a user-facing error"
)]
fn lookup(
&mut self,
sym: StringId,
@@ -365,10 +360,6 @@ impl<'ctx: 'ir, 'id, 'ir, R: VmRuntimeCtx> DowngradeContext<'id, 'ir>
self.source.clone()
}
#[expect(
clippy::panic_in_result_fn,
reason = "assert_eq guards an internal invariant (bindings and values have equal length); a mismatch is a compiler bug, not a user error"
)]
fn with_let_scope<F, Ret>(&mut self, keys: &[StringId], f: F) -> Result<Ret>
where
F: FnOnce(
@@ -430,10 +421,6 @@ impl<'ctx: 'ir, 'id, 'ir, R: VmRuntimeCtx> DowngradeContext<'id, 'ir>
ret
}
#[expect(
clippy::panic,
reason = "exceeding u8::MAX thunk scope layers is a compiler invariant violation, not a user-facing error"
)]
fn with_thunk_scope<F, Ret>(
&mut self,
f: F,
@@ -499,6 +486,7 @@ enum Scope<'ctx, 'id, 'ir> {
Repl(&'ctx HashSet<StringId>),
ScopedImport {
keys: HashSet<StringId>,
#[allow(dead_code)]
slot_id: u32,
},
Let(HashMap<StringId, GhostMaybeThunkRef<'id, 'ir>>),
@@ -542,29 +530,13 @@ impl<'a, 'ctx, 'id, 'ir, R: VmRuntimeCtx> ScopeGuard<'a, 'ctx, 'id, 'ir, R> {
}
}
mod sealed {
use super::*;
pub struct OwnedIr {
_bump: Bump,
ir: RawIrRef<'static>,
}
impl OwnedIr {
/// # Safety
/// `ir` must borrows from `bump`
pub unsafe fn new(bump: Bump, ir: RawIrRef<'static>) -> Self {
Self { _bump: bump, ir }
}
pub fn as_ref<'ir>(&'ir self) -> RawIrRef<'ir> {
// SAFETY: `self.ir`'s `'static` lifetime is a storage token; the IR is
// backed by `self._bump`, which lives as long as `self`. Narrowing to
// `'ir` (tied to `&self`) hands out a reference that cannot outlive the
// arena.
unsafe { std::mem::transmute::<RawIrRef<'static>, RawIrRef<'ir>>(self.ir) }
}
}
struct OwnedIr {
_bump: Bump,
ir: RawIrRef<'static>,
}
pub use sealed::OwnedIr;
impl OwnedIr {
fn as_ref<'ir>(&'ir self) -> RawIrRef<'ir> {
unsafe { std::mem::transmute::<RawIrRef<'static>, RawIrRef<'ir>>(self.ir) }
}
}
+5 -3
View File
@@ -3,7 +3,7 @@ use std::marker::PhantomData;
use bumpalo::Bump;
use bumpalo::collections::Vec;
use fix_lang::{BuiltinId, StringId};
use fix_lang::{BUILTINS, BuiltinId, StringId};
use ghost_cell::{GhostCell, GhostToken};
use rnix::{TextRange, ast};
use string_interner::DefaultStringInterner;
@@ -222,6 +222,7 @@ pub enum Ir<'ir, R: RefExt<'ir> + ?Sized + 'ir> {
pub struct ThunkId(pub usize);
/// Represents a key in an attribute path.
#[allow(unused)]
#[derive(Debug)]
pub enum Attr<Ref> {
/// A dynamic attribute key, which is an expression that must evaluate to a string.
@@ -290,8 +291,9 @@ pub fn new_global_env(
let builtins_sym = StringId(strings.get_or_intern("builtins"));
global_env.insert(builtins_sym, MaybeThunk::Builtins);
for id in BuiltinId::ALL {
let name = StringId(strings.get_or_intern(id.info().global_name));
for (idx, &(name, _)) in BUILTINS.iter().enumerate() {
let id = BuiltinId::try_from(idx as u8).expect("infallible");
let name = StringId(strings.get_or_intern(name));
global_env.insert(name, MaybeThunk::Builtin(id));
}
+18 -33
View File
@@ -156,10 +156,6 @@ impl<'id: 'ir, 'ir, Ctx: DowngradeContext<'id, 'ir>> Downgrade<'id, 'ir, Ctx> fo
let path = {
let temp = self.content().require(ctx, span)?;
let text = temp.text();
#[expect(
clippy::string_slice,
reason = "PathSearch text is <...> wrapped in ASCII angle brackets, so byte indices 1 and len-1 are char boundaries"
)]
let id = ctx.intern_string(&text[1..text.len() - 1]);
let expr = ctx.new_expr(Ir::Str(id));
ctx.maybe_thunk(expr)
@@ -466,14 +462,16 @@ impl<'id: 'ir, 'ir, Ctx: DowngradeContext<'id, 'ir>> Downgrade<'id, 'ir, Ctx> fo
body: GhostRoIrRef<'id, 'ir>,
}
let (ret, thunks) = ctx.with_thunk_scope(|ctx| -> Result<Ret> {
let (param, body) = match raw_param {
let (ret, thunks) = ctx.with_thunk_scope(|ctx| {
let param;
let body;
match raw_param {
ast::Param::IdentParam(id) => {
let param_sym = ctx.intern_string(id.to_string());
(
None,
ctx.with_param_scope(param_sym, |ctx| body_ast.downgrade(ctx))?,
)
param = None;
body = ctx.with_param_scope(param_sym, |ctx| body_ast.downgrade(ctx))?;
}
ast::Param::Pattern(pattern) => {
let alias = pattern
@@ -495,18 +493,17 @@ impl<'id: 'ir, 'ir, Ctx: DowngradeContext<'id, 'ir>> Downgrade<'id, 'ir, Ctx> fo
body_ast.clone().downgrade(ctx)
})?;
(
Some(Param {
required,
optional,
ellipsis,
}),
inner_body,
)
}
};
param = Some(Param {
required,
optional,
ellipsis,
});
Ok(Ret { param, body })
body = inner_body;
}
}
Result::Ok(Ret { param, body })
});
let Ret { param, body } = ret?;
@@ -553,10 +550,6 @@ impl<'id: 'ir, 'ir> PendingAttrSet<'ir> {
}
}
#[expect(
clippy::indexing_slicing,
reason = "path is non-empty here: path.first() was just unwrapped above, so path[1..] is in bounds"
)]
fn insert(
&mut self,
path: &[ast::Attr],
@@ -658,10 +651,6 @@ impl<'id: 'ir, 'ir> PendingAttrSet<'ir> {
) -> Result<()> {
if !path.is_empty() {
let mut nested = PendingAttrSet::new_in(ctx.bump());
#[expect(
clippy::indexing_slicing,
reason = "path is non-empty in this branch, so path[0] and path[1..] are in bounds"
)]
nested.insert_dynamic(
path[0].clone(),
path[0].syntax().text_range(),
@@ -676,10 +665,6 @@ impl<'id: 'ir, 'ir> PendingAttrSet<'ir> {
Ok(())
}
#[expect(
clippy::unreachable,
reason = "value was just reassigned to PendingValue::Set on the line above, so the re-match always hits the Set arm"
)]
fn ensure_pending_set<'a>(
value: &'a mut PendingValue<'ir>,
ctx: &mut impl DowngradeContext<'id, 'ir>,
+13 -32
View File
@@ -1,5 +1,5 @@
use fix_bytecode::{Const, InstructionPtr, Op, OperandType};
use fix_lang::StringId;
use fix_bytecode::{Const, Continuation, InstructionPtr, Op, OperandType};
use fix_lang::{BUILTINS, StringId};
use hashbrown::HashMap;
use rnix::TextRange;
use string_interner::Symbol as _;
@@ -54,6 +54,7 @@ impl<'a, Ctx: BytecodeContext> BytecodeEmitter<'a, Ctx> {
}
}
#[must_use]
fn inline_maybe_thunk(&self, val: &MaybeThunk) -> InlineOperand {
use MaybeThunk::*;
match *val {
@@ -74,7 +75,14 @@ impl<'a, Ctx: BytecodeContext> BytecodeEmitter<'a, Ctx> {
InlineOperand::Local { layer, local }
}
Arg { layer } => InlineOperand::Local { layer, local: 0 },
Builtin(id) => InlineOperand::Const(Const::PrimOp(id)),
Builtin(id) => {
let (_, arity) = BUILTINS[id as usize];
InlineOperand::Const(Const::PrimOp {
id,
arity,
dispatch_ip: Continuation::entry_for_builtin(id).ip(),
})
}
BuiltinConst(id) => InlineOperand::BuiltinConst(id),
Builtins => InlineOperand::Builtins,
ReplBinding(id) => InlineOperand::ReplBinding(id),
@@ -178,10 +186,6 @@ impl<'a, Ctx: BytecodeContext> BytecodeEmitter<'a, Ctx> {
offset
}
#[inline]
#[expect(
clippy::indexing_slicing,
reason = "offset addresses a 4-byte i32 placeholder this compiler previously emitted, so it is in bounds"
)]
fn patch_i32(&mut self, offset: usize, val: i32) {
self.ctx.get_code_mut()[offset..offset + 4].copy_from_slice(&val.to_le_bytes());
}
@@ -210,10 +214,6 @@ impl<'a, Ctx: BytecodeContext> BytecodeEmitter<'a, Ctx> {
self.scope_stack.last().map_or(0, |s| s.depth)
}
#[expect(
clippy::panic,
reason = "a ThunkId must resolve in some enclosing scope; failure indicates a compiler bug"
)]
fn resolve_thunk(&self, id: ThunkId) -> (u8, u32) {
for scope in self.scope_stack.iter().rev() {
if let Some(&local_idx) = scope.thunk_map.get(&id) {
@@ -520,10 +520,6 @@ impl<'a, Ctx: BytecodeContext> BytecodeEmitter<'a, Ctx> {
}
}
#[expect(
clippy::unreachable,
reason = "the outer match only reaches this arm for the binary operator kinds enumerated above"
)]
fn emit_binop(&mut self, lhs: RawIrRef<'_>, rhs: RawIrRef<'_>, kind: BinOpKind) {
use BinOpKind::*;
match kind {
@@ -716,25 +712,14 @@ impl<'a, Ctx: BytecodeContext> BytecodeEmitter<'a, Ctx> {
}
if let Some(default) = default {
// FIXME: i32???
let before: i32 = self
.ctx
.get_code()
.len()
.try_into()
.expect("emitted code length fits in i32");
let before: i32 = self.ctx.get_code().len().try_into().unwrap();
for patch in dynamic_patches {
self.patch_jump_target(patch);
}
self.emit_op(Op::JumpIfSelectSucceeded);
let placeholder = self.emit_i32_placeholder();
self.emit_expr(default);
let after: i32 = self
.ctx
.get_code()
.len()
.try_into()
.expect("emitted code length fits in i32");
let after: i32 = self.ctx.get_code().len().try_into().unwrap();
// Offset is relative to after the placeholder, so subtract the
// size of JumpIfSelectSucceeded (1) + placeholder (4).
self.patch_i32(placeholder, after - before - 5);
@@ -745,10 +730,6 @@ impl<'a, Ctx: BytecodeContext> BytecodeEmitter<'a, Ctx> {
}
}
#[expect(
clippy::panic,
reason = "a hasAttr attrpath always has at least one attr by construction of the AST"
)]
fn emit_has_attr(&mut self, lhs: RawIrRef<'_>, rhs: &[Attr<RawIrRef<'_>>]) {
self.emit_expr(lhs);
-3
View File
@@ -7,6 +7,3 @@ edition = "2024"
miette = { version = "7.6", features = ["fancy"] }
rnix = { workspace = true }
thiserror = "2.0"
[lints]
workspace = true
+1 -1
View File
@@ -4,7 +4,7 @@ use std::sync::Arc;
use miette::{Diagnostic, NamedSource, SourceSpan};
use thiserror::Error;
pub type Result<T, E = Box<Error>> = core::result::Result<T, E>;
pub type Result<T> = core::result::Result<T, Box<Error>>;
#[derive(Clone, Debug)]
pub enum SourceType {
-3
View File
@@ -8,6 +8,3 @@ ere = { workspace = true }
gc-arena = { workspace = true }
num_enum = { workspace = true }
string-interner = { workspace = true }
[lints]
workspace = true
+6 -42
View File
@@ -8,7 +8,7 @@ use num_enum::TryFromPrimitive;
macro_rules! define_builtins {
($(($name:literal, $variant:ident, $arity:expr)),* $(,)?) => {
const BUILTINS: &[(&str, u8)] = &[
pub const BUILTINS: &[(&str, u8)] = &[
$(($name, $arity),)*
];
@@ -18,10 +18,6 @@ macro_rules! define_builtins {
pub enum BuiltinId {
$($variant,)*
}
impl BuiltinId {
pub const ALL: [Self; BUILTINS.len()] = [$(Self::$variant,)*];
}
};
}
@@ -131,36 +127,6 @@ define_builtins! {
("__zipAttrsWith", ZipAttrsWith, 2),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct BuiltinInfo {
pub name: &'static str,
pub global_name: &'static str,
pub global: bool,
pub arity: u8,
}
impl BuiltinId {
pub const TOTAL: usize = BUILTINS.len();
#[expect(
clippy::indexing_slicing,
reason = "a `BuiltinId` discriminant is always a valid index into the `BUILTINS` table"
)]
#[inline(always)]
pub fn info(self) -> BuiltinInfo {
let (global_name, arity) = BUILTINS[self as usize];
let (name, global) = global_name
.strip_prefix("__")
.map_or((global_name, true), |name| (name, false));
BuiltinInfo {
name,
global_name,
global,
arity,
}
}
}
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Collect)]
#[collect(require_static)]
@@ -461,10 +427,6 @@ fn fmt_nix_float(f: &mut Formatter<'_>, x: f64) -> FmtResult {
let precision: i32 = 6;
let exp = x.abs().log10().floor() as i32;
#[expect(
clippy::cast_sign_loss,
reason = "this branch runs only when exp < precision, so precision-1-exp and precision-1 are non-negative"
)]
let formatted = if exp >= -4 && exp < precision {
let decimal_places = (precision - 1 - exp) as usize;
format!("{x:.decimal_places$}")
@@ -489,9 +451,11 @@ fn fmt_nix_float(f: &mut Formatter<'_>, x: f64) -> FmtResult {
};
if formatted.contains('.') {
if let Some((head, tail)) = formatted.split_once('e') {
let trimmed = head.trim_end_matches('0').trim_end_matches('.');
write!(f, "{trimmed}e{tail}")
if let Some(e_pos) = formatted.find('e') {
let trimmed = formatted[..e_pos]
.trim_end_matches('0')
.trim_end_matches('.');
write!(f, "{}{}", trimmed, &formatted[e_pos..])
} else {
let trimmed = formatted.trim_end_matches('0').trim_end_matches('.');
write!(f, "{trimmed}")
+2 -4
View File
@@ -7,9 +7,7 @@ edition = "2024"
proc-macro = true
[dependencies]
manyhow = "0.11"
proc-macro2 = "1.0"
quote = "1.0"
syn = { version = "3.0", features = ["full", "visit", "visit-mut"] }
[lints]
workspace = true
syn = { version = "2.0", features = ["full", "visit"] }
File diff suppressed because it is too large Load Diff
-13
View File
@@ -1,18 +1,5 @@
extern crate proc_macro;
mod handler;
#[proc_macro_attribute]
pub fn handler(
attr: proc_macro::TokenStream,
item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
handler::handler(attr.into(), item.into()).into()
}
// Adapted from `__unelide_lifetimes` in `gc-arena-derive`.
// Licensed under the MIT license.
// See: https://github.com/kyren/gc-arena
#[proc_macro]
pub fn unelide_lifetimes(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
use quote::ToTokens;
-3
View File
@@ -14,6 +14,3 @@ fix-bytecode = { path = "../fix-bytecode" }
fix-error = { path = "../fix-error" }
fix-lang = { path = "../fix-lang" }
fix-macros = { path = "../fix-macros" }
[lints]
workspace = true
+30 -76
View File
@@ -1,7 +1,4 @@
#![allow(
dead_code,
reason = "boxing layer exposes a full API surface; some helpers are used only on specific targets or not yet wired up"
)]
#![allow(dead_code)]
use std::fmt;
use std::num::NonZeroU8;
@@ -82,48 +79,41 @@ int_store!(i16);
int_store!(i32);
fn store_ptr<P: Strict + Copy>(value: &mut Value, ptr: P) {
cfg_select! {
target_pointer_width = "64" => {
assert!(
ptr.addr() <= 0x0000_FFFF_FFFF_FFFF,
"Pointer too large to store in NaN box"
);
#[cfg(target_pointer_width = "64")]
{
assert!(
ptr.addr() <= 0x0000_FFFF_FFFF_FFFF,
"Pointer too large to store in NaN box"
);
// SAFETY: `Value` is `#[repr(C, align(8))]` and exactly 8 bytes, so it is
// sound to reinterpret its storage as a `[u8; 8]` that we then treat as `P`
// (a pointer-sized value).
let val = (unsafe { value.whole_mut() } as *mut [u8; 8]).cast::<P>();
let val = (unsafe { value.whole_mut() } as *mut [u8; 8]).cast::<P>();
let ptr = Strict::map_addr(ptr, |addr| {
addr | (usize::from(value.header().into_raw()) << 48)
});
let ptr = Strict::map_addr(ptr, |addr| {
addr | (usize::from(value.header().into_raw()) << 48)
});
// SAFETY: `val` points to the `Value`'s 8-byte storage, which is valid and
// suitably aligned to hold `P`.
unsafe { val.write(ptr) };
}
_ => {
compile_error!("unsupported pointer width");
}
unsafe { val.write(ptr) };
}
#[cfg(target_pointer_width = "32")]
{
let _ = (value, ptr);
unimplemented!("32-bit pointer storage not supported");
}
}
fn load_ptr<P: Strict>(value: &Value) -> P {
cfg_select! {
target_pointer_width = "64" => {
// SAFETY: `Value` is `#[repr(C, align(8))]` and exactly 8 bytes, so it
// is sound to reinterpret its storage as a `[u8; 8]` cast to `P`; the
// pointer was originally written through this same `P` layout by
// `store_ptr`.
let val = (unsafe { value.whole() } as *const [u8; 8]).cast::<P>();
// SAFETY: `val` points to the `Value`'s 8-byte storage, which is valid
// and suitably aligned to hold `P`.
let ptr = unsafe { val.read() };
Strict::map_addr(ptr, |addr| addr & 0x0000_FFFF_FFFF_FFFF)
}
_ => {
compile_error!("unsupported pointer width");
}
#[cfg(target_pointer_width = "64")]
{
let val = (unsafe { value.whole() } as *const [u8; 8]).cast::<P>();
let ptr = unsafe { val.read() };
Strict::map_addr(ptr, |addr| addr & 0x0000_FFFF_FFFF_FFFF)
}
#[cfg(target_pointer_width = "32")]
{
let _ = value;
unimplemented!("32-bit pointer storage not supported");
}
}
@@ -189,10 +179,6 @@ impl RawTag {
#[inline]
#[must_use]
pub(crate) fn new(neg: bool, val: NonZeroU8) -> RawTag {
// SAFETY: masking a `NonZeroU8` with `0x07` yields a value in `0..8`;
// callers only construct tags from valid tag discriminants in `1..8`,
// so the low three bits are in the `1..8` range required by
// `new_unchecked`.
unsafe { Self::new_unchecked(neg, val.get() & 0x07) }
}
@@ -243,9 +229,6 @@ impl RawTag {
(true, 6) => TagVal::_N6,
(true, 7) => TagVal::_N7,
// SAFETY: the caller guarantees `val` is in `1..8`; every
// `(neg, val)` combination in that range is matched above, so this
// arm cannot be reached.
_ => unsafe { core::hint::unreachable_unchecked() },
})
}
@@ -319,10 +302,6 @@ impl Header {
#[inline]
const fn tag(self) -> RawTag {
// SAFETY: a `Header` is only ever constructed by `Header::new` from a
// `RawTag` whose value is in `1..8`, stored in the low three bits;
// `get_tag` recovers exactly those bits, so the argument passed to
// `new_unchecked` is in the required `1..8` range.
unsafe { RawTag::new_unchecked(self.get_sign(), self.get_tag()) }
}
@@ -344,7 +323,7 @@ impl Header {
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(C, align(8))]
pub(crate) struct Value {
pub struct Value {
#[cfg(target_endian = "big")]
header: Header,
data: [u8; 6],
@@ -408,9 +387,6 @@ impl Value {
#[must_use]
unsafe fn whole(&self) -> &[u8; 8] {
let ptr = (self as *const Value).cast::<[u8; 8]>();
// SAFETY: `Value` is `#[repr(C, align(8))]` and exactly 8 bytes with no
// padding, so it shares its layout with `[u8; 8]`; `ptr` is derived
// from a valid `&Value`, so the reference is valid for reads.
unsafe { &*ptr }
}
@@ -418,10 +394,6 @@ impl Value {
#[must_use]
unsafe fn whole_mut(&mut self) -> &mut [u8; 8] {
let ptr = (self as *mut Value).cast::<[u8; 8]>();
// SAFETY: `Value` is `#[repr(C, align(8))]` and exactly 8 bytes with no
// padding, so it shares its layout with `[u8; 8]`; `ptr` is derived
// from a unique `&mut Value`, so the reference is valid for reads and
// writes.
unsafe { &mut *ptr }
}
}
@@ -463,9 +435,6 @@ impl RawBox {
#[must_use]
pub(crate) const fn tag(&self) -> Option<RawTag> {
if self.is_value() {
// SAFETY: `is_value()` returned true, so the union holds a `Value`
// (a tagged-NaN bit pattern) rather than a float, making the read
// of the `value` field sound.
Some(unsafe { self.value.tag() })
} else {
None
@@ -475,18 +444,12 @@ impl RawBox {
#[inline]
#[must_use]
pub(crate) fn is_float(&self) -> bool {
// SAFETY: every 8-byte pattern is simultaneously a valid `f64` and a
// valid `u64`, so reading the `float` and `bits` union fields is
// always sound.
(unsafe { !self.float.is_nan() } || unsafe { self.bits & SIGN_MASK == QUIET_NAN })
}
#[inline]
#[must_use]
pub(crate) const fn is_value(&self) -> bool {
// SAFETY: every 8-byte pattern is simultaneously a valid `f64` and a
// valid `u64`, so reading the `float` and `bits` union fields is
// always sound.
(unsafe { self.float.is_nan() } && unsafe { self.bits & SIGN_MASK != QUIET_NAN })
}
@@ -494,8 +457,6 @@ impl RawBox {
#[must_use]
pub(crate) fn float(&self) -> Option<&f64> {
if self.is_float() {
// SAFETY: reading the `float` field is sound because any 8-byte
// pattern is a valid `f64`.
Some(unsafe { &self.float })
} else {
None
@@ -506,9 +467,6 @@ impl RawBox {
#[must_use]
pub(crate) fn value(&self) -> Option<&Value> {
if self.is_value() {
// SAFETY: `is_value()` returned true, so the union holds a `Value`;
// `Value` has no invalid bit patterns, so reading the `value` field
// is sound.
Some(unsafe { &self.value })
} else {
None
@@ -517,16 +475,12 @@ impl RawBox {
#[inline]
pub(crate) fn into_float_unchecked(self) -> f64 {
// SAFETY: reading the `float` field is sound because any 8-byte pattern
// is a valid `f64`.
unsafe { self.float }
}
#[inline]
#[must_use]
pub(crate) fn to_bits(self) -> u64 {
// SAFETY: reading the `bits` field is sound because any 8-byte pattern
// is a valid `u64`.
unsafe { self.bits }
}
}
+69 -32
View File
@@ -1,9 +1,9 @@
use fix_lang::StringId;
use gc_arena::Mutation;
use gc_arena::{Gc, Mutation};
use crate::{
AttrSet, BytecodeReader, Closure, List, Machine, NixNum, NixString, NixType, Null, PrimOp,
PrimOpApp, Step, StrictValue, ValueVariant,
AttrSet, Break, BytecodeReader, Closure, List, Machine, NixNum, NixString, NixType, Null,
PrimOp, PrimOpApp, Step, StrictValue,
};
pub trait Forced<'gc>: Sized {
@@ -47,10 +47,10 @@ impl<'gc> Forced<'gc> for StrictValue<'gc> {
}
}
macro_rules! impl_forced {
($($ty:ty),* $(,)?) => {
macro_rules! impl_forced_inline {
($($ty:ty => $nix_ty:expr),* $(,)?) => {
$(
impl<'gc> Forced<'gc> for <$ty as ValueVariant<'gc>>::Ty {
impl<'gc> Forced<'gc> for $ty {
const WIDTH: usize = 1;
#[inline(always)]
@@ -63,11 +63,11 @@ macro_rules! impl_forced {
) -> Step {
m.force_slot_to_pc(base_depth, reader, mc, resume_pc)?;
let v = m.peek_forced(base_depth);
if !v.is::<$ty>() {
m.finish_type_err(<$ty as ValueVariant>::TYPE, v.ty())
} else {
Step::Continue(())
if v.downcast::<$ty>().is_none() {
let _: Step = m.finish_type_err($nix_ty, v.ty());
return Step::Break(Break::Done);
}
Step::Continue(())
}
#[inline(always)]
@@ -81,18 +81,55 @@ macro_rules! impl_forced {
};
}
impl_forced! {
i32,
bool,
Null,
StringId,
PrimOp,
i64,
NixString,
AttrSet<'gc>,
List<'gc>,
Closure<'gc>,
PrimOpApp<'gc>,
macro_rules! impl_forced_gc {
($($ty:ty => $nix_ty:expr),* $(,)?) => {
$(
impl<'gc> Forced<'gc> for Gc<'gc, $ty> {
const WIDTH: usize = 1;
#[inline(always)]
fn force_and_check<M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
base_depth: usize,
resume_pc: usize,
) -> Step {
m.force_slot_to_pc(base_depth, reader, mc, resume_pc)?;
let v = m.peek_forced(base_depth);
if v.downcast::<$ty>().is_none() {
let _: Step = m.finish_type_err($nix_ty, v.ty());
return Step::Break(Break::Done);
}
Step::Continue(())
}
#[inline(always)]
fn pop_converted<M: Machine<'gc>>(m: &mut M) -> Self {
m.pop_forced()
.downcast::<$ty>()
.expect("type checked in force_and_check")
}
}
)*
};
}
impl_forced_inline! {
i32 => NixType::Int,
bool => NixType::Bool,
Null => NixType::Null,
StringId => NixType::String,
PrimOp => NixType::PrimOp,
}
impl_forced_gc! {
i64 => NixType::Int,
NixString => NixType::String,
AttrSet<'gc> => NixType::AttrSet,
List<'gc> => NixType::List,
Closure<'gc> => NixType::Closure,
PrimOpApp<'gc> => NixType::PrimOpApp,
}
impl<'gc> Forced<'gc> for NixNum {
@@ -108,17 +145,17 @@ impl<'gc> Forced<'gc> for NixNum {
) -> Step {
m.force_slot_to_pc(base_depth, reader, mc, resume_pc)?;
let v = m.peek_forced(base_depth);
if v.downcast_num().is_none() {
m.finish_type_err(NixType::Int, v.ty())
} else {
Step::Continue(())
if v.as_num().is_none() {
let _: Step = m.finish_type_err(NixType::Int, v.ty());
return Step::Break(Break::Done);
}
Step::Continue(())
}
#[inline(always)]
fn pop_converted<M: Machine<'gc>>(m: &mut M) -> Self {
m.pop_forced()
.downcast_num()
.as_num()
.expect("type checked in force_and_check")
}
}
@@ -136,17 +173,17 @@ impl<'gc> Forced<'gc> for f64 {
) -> Step {
m.force_slot_to_pc(base_depth, reader, mc, resume_pc)?;
let v = m.peek_forced(base_depth);
if !v.is::<f64>() {
m.finish_type_err(NixType::Float, v.ty())
} else {
Step::Continue(())
if v.downcast_float().is_none() {
let _: Step = m.finish_type_err(NixType::Float, v.ty());
return Step::Break(Break::Done);
}
Step::Continue(())
}
#[inline(always)]
fn pop_converted<M: Machine<'gc>>(m: &mut M) -> Self {
m.pop_forced()
.downcast::<f64>()
.downcast_float()
.expect("type checked in force_and_check")
}
}
+6 -4
View File
@@ -1,6 +1,6 @@
use fix_bytecode::InstructionPtr;
use fix_error::Source;
use fix_lang::{self, StringId};
use fix_lang::{self, BUILTINS, StringId};
use hashbrown::HashSet;
use crate::{
@@ -100,7 +100,7 @@ impl<T: VmRuntimeCtx> ConvertValueWithSeen for T {
Value::Int(i as i64)
} else if let Some(gc_i) = val.downcast::<i64>() {
Value::Int(*gc_i)
} else if let Some(f) = val.downcast::<f64>() {
} else if let Some(f) = val.downcast_float() {
Value::Float(f)
} else if let Some(b) = val.downcast::<bool>() {
Value::Bool(b)
@@ -153,9 +153,11 @@ impl<T: VmRuntimeCtx> ConvertValueWithSeen for T {
Value::Thunk
}
} else if let Some(primop) = val.downcast::<PrimOp>() {
Value::PrimOp(primop.id.info().name)
let name = BUILTINS[primop.id as usize].0;
Value::PrimOp(name.strip_prefix("__").unwrap_or(name))
} else if let Some(app) = val.downcast::<PrimOpApp>() {
Value::PrimOpApp(app.primop.id.info().name)
let name = BUILTINS[app.primop.id as usize].0;
Value::PrimOpApp(name.strip_prefix("__").unwrap_or(name))
} else {
Value::Null
}
-4
View File
@@ -2,10 +2,8 @@ mod boxing;
mod forced;
mod host;
mod machine;
mod macro_support;
mod path_util;
mod resolve;
mod slot;
mod state;
mod string_context;
mod value;
@@ -14,10 +12,8 @@ pub use fix_bytecode::{BytecodeReader, OperandData};
pub use forced::*;
pub use host::*;
pub use machine::*;
pub use macro_support::*;
pub use path_util::*;
pub use resolve::*;
pub use slot::*;
pub use state::*;
pub use string_context::*;
pub use value::*;
+4 -13
View File
@@ -3,11 +3,11 @@ use std::path::{Path, PathBuf};
use fix_error::Error;
use fix_lang::{self, StringId};
use gc_arena::{Gc, Mutation};
use gc_arena::Mutation;
use crate::{
AttrSet, Break, BytecodeReader, CallFrame, ForceMode, Forced, GcEnv, NixType, PendingLoad,
Step, StrictValue, Value, VmError,
Break, BytecodeReader, CallFrame, ForceMode, Forced, GcEnv, NixType, PendingLoad, Step,
StrictValue, Value, VmError,
};
/// Abstract VM-side operations consumed by instruction handlers and primops.
@@ -65,17 +65,12 @@ pub trait Machine<'gc> {
) -> Step;
#[inline(always)]
#[expect(
clippy::unreachable,
reason = "a primop only returns via `return_from_primop` while its call frame is still on the stack, so `pop_call_frame` is always `Some`"
)]
fn return_from_primop(&mut self, val: Value<'gc>, reader: &mut BytecodeReader<'_>) -> Step {
self.push(val);
let Some(CallFrame {
pc: ret_pc,
thunk: _,
env,
depth: None,
}) = self.pop_call_frame()
else {
unreachable!()
@@ -96,10 +91,6 @@ pub trait Machine<'gc> {
fn set_env(&mut self, env: GcEnv<'gc>);
#[inline(always)]
#[expect(
clippy::indexing_slicing,
reason = "codegen guarantees the local index is within the resolved frame's `locals`"
)]
fn local(&self, layer: u8, idx: u32) -> Value<'gc> {
let mut cur = self.env();
for _ in 0..layer {
@@ -118,7 +109,7 @@ pub trait Machine<'gc> {
self.finish_err(err.into_error())
}
fn builtins(&self) -> Gc<'gc, AttrSet<'gc>>;
fn builtins(&self) -> Value<'gc>;
fn functor_sym(&self) -> StringId;
fn empty_list(&self) -> Value<'gc>;
fn empty_attrs(&self) -> Value<'gc>;
-165
View File
@@ -1,165 +0,0 @@
use std::ops::ControlFlow;
use gc_arena::Mutation;
use crate::{
Break, BytecodeReader, Forced, Machine, MachineExt, Slot, SlotContent, Step, StrictValue,
Value, ValueVariant,
};
pub trait UnwrapSlot {
type Unwrapped;
}
impl<T> UnwrapSlot for Slot<T> {
type Unwrapped = T;
}
/// Force-target protocol behind the `#[primop]` `force` form: `Value` only
/// needs WHNF, `StrictValue` *is* WHNF, and content types are checked through
/// [`Forced`] on their stored representation.
pub trait ForceTarget<'gc>: SlotContent<'gc> {
/// Type-check the stack slot refined by the previous `force(slot)`; the
/// slot is already WHNF when this runs.
fn refine_check<M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
depth: usize,
) -> Step;
/// Pop and convert the previous suspension's result into the annotated
/// binding's stored representation.
fn conv_force<M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> ControlFlow<Break, <Self as SlotContent<'gc>>::Ty>;
}
impl<'gc> ForceTarget<'gc> for Value<'gc> {
#[inline(always)]
fn refine_check<M: Machine<'gc>>(
_m: &mut M,
_reader: &mut BytecodeReader<'_>,
_mc: &Mutation<'gc>,
_depth: usize,
) -> Step {
Step::Continue(())
}
#[inline(always)]
fn conv_force<M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> ControlFlow<Break, Value<'gc>> {
match m.force_and_retry::<StrictValue<'gc>>(reader, mc) {
ControlFlow::Continue(v) => ControlFlow::Continue(v.relax()),
ControlFlow::Break(b) => ControlFlow::Break(b),
}
}
}
impl<'gc> ForceTarget<'gc> for StrictValue<'gc> {
#[inline(always)]
fn refine_check<M: Machine<'gc>>(
_m: &mut M,
_reader: &mut BytecodeReader<'_>,
_mc: &Mutation<'gc>,
_depth: usize,
) -> Step {
Step::Continue(())
}
#[inline(always)]
fn conv_force<M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> ControlFlow<Break, StrictValue<'gc>> {
m.force_and_retry::<StrictValue<'gc>>(reader, mc)
}
}
impl<'gc, T> ForceTarget<'gc> for T
where
T: ValueVariant<'gc>,
<T as ValueVariant<'gc>>::Ty: Forced<'gc>,
{
#[inline(always)]
fn refine_check<M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
depth: usize,
) -> Step {
<<T as ValueVariant<'gc>>::Ty as Forced<'gc>>::force_and_check(
m,
reader,
mc,
depth,
reader.inst_start_pc(),
)
}
#[inline(always)]
fn conv_force<M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> ControlFlow<Break, <T as SlotContent<'gc>>::Ty> {
m.force_and_retry::<<T as ValueVariant<'gc>>::Ty>(reader, mc)
}
}
/// Callee protocol behind `call(&slot, ..)`: an unforced `Slot<Value>` is
/// WHNF'd before the call; refined slots already hold strict values.
pub trait CalleeReady<'gc> {
fn callee_ready<M: Machine<'gc>>(
&self,
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> ControlFlow<Break>;
}
impl<'gc> CalleeReady<'gc> for Slot<Value<'gc>> {
#[inline(always)]
fn callee_ready<M: Machine<'gc>>(
&self,
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> ControlFlow<Break> {
self.force::<StrictValue<'gc>, M>(m, reader, mc)?;
ControlFlow::Continue(())
}
}
impl<'gc> CalleeReady<'gc> for Slot<StrictValue<'gc>> {
#[inline(always)]
fn callee_ready<M: Machine<'gc>>(
&self,
_m: &mut M,
_reader: &mut BytecodeReader<'_>,
_mc: &Mutation<'gc>,
) -> ControlFlow<Break> {
ControlFlow::Continue(())
}
}
impl<'gc, T> CalleeReady<'gc> for Slot<T>
where
T: ValueVariant<'gc>,
{
#[inline(always)]
fn callee_ready<M: Machine<'gc>>(
&self,
_m: &mut M,
_reader: &mut BytecodeReader<'_>,
_mc: &Mutation<'gc>,
) -> ControlFlow<Break> {
ControlFlow::Continue(())
}
}
+10 -2
View File
@@ -20,12 +20,20 @@ pub fn resolve_operand<'gc, M: Machine<'gc>>(
Const(id) => ctx.get_const(id).into(),
BigInt(val) => Value::new(Gc::new(mc, val)),
Local { layer, idx } => m.local(layer, idx),
BuiltinConst(id) => m.builtins().lookup(id).expect("builtin const must exist"),
Builtins => m.builtins().into(),
#[allow(clippy::unwrap_used)]
BuiltinConst(id) => m
.builtins()
.downcast::<AttrSet>()
.unwrap()
.lookup(id)
.unwrap(),
Builtins => m.builtins(),
ReplBinding(_id) => todo!(),
ScopedImportBinding { slot_id, name } => {
let scope = m.scope_slot(slot_id);
#[allow(clippy::unwrap_used)]
let attrs = scope.downcast::<AttrSet>().expect("scope must be attrset");
#[allow(clippy::unwrap_used)]
attrs.lookup(name).expect("scoped binding not found")
}
}
-86
View File
@@ -1,86 +0,0 @@
use std::marker::PhantomData;
use std::ops::ControlFlow;
use fix_bytecode::BytecodeReader;
use gc_arena::Mutation;
use crate::{Break, Forced, Machine, NixType, Step, StrictValue, Value, ValueVariant};
pub struct TypeError {
pub expected: NixType,
pub got: NixType,
}
pub trait SlotContent<'gc> {
type Ty: Into<Value<'gc>> + TryFrom<Value<'gc>> + 'gc;
}
impl<'gc> SlotContent<'gc> for Value<'gc> {
type Ty = Value<'gc>;
}
impl<'gc> SlotContent<'gc> for StrictValue<'gc> {
type Ty = StrictValue<'gc>;
}
impl<'gc, T> SlotContent<'gc> for T
where
T: ValueVariant<'gc>,
{
type Ty = T::Ty;
}
pub struct Slot<T> {
depth: u8,
_marker: PhantomData<T>,
}
impl<T> Slot<T> {
#[inline(always)]
pub const fn new(depth: u8) -> Self {
Self {
depth,
_marker: PhantomData,
}
}
}
impl<'gc, T> Slot<T>
where
T: SlotContent<'gc>,
<T::Ty as TryFrom<Value<'gc>>>::Error: std::fmt::Debug,
{
#[inline(always)]
pub fn read<M: Machine<'gc>>(&self, m: &M) -> T::Ty {
T::Ty::try_from(m.peek(self.depth as usize)).expect("slot held a value of the wrong type")
}
#[inline(always)]
pub fn write<M: Machine<'gc>>(&self, m: &mut M, val: T::Ty) {
m.replace(self.depth as usize, T::Ty::into(val));
}
}
impl<'gc> Slot<Value<'gc>> {
#[inline(always)]
pub fn force<T: Forced<'gc>, M: Machine<'gc>>(
&self,
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> ControlFlow<Break, Slot<T>> {
T::force_and_check(m, reader, mc, self.depth as usize, reader.inst_start_pc())?;
ControlFlow::Continue(Slot::new(self.depth))
}
#[inline(always)]
pub fn force_to_pc<M: Machine<'gc>>(
&self,
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
pc: usize,
) -> Step {
m.force_slot_to_pc(self.depth as usize, reader, mc, pc)
}
}
+3 -2
View File
@@ -8,6 +8,7 @@ use hashbrown::HashSet;
use crate::{GcEnv, Thunk};
#[allow(dead_code)]
pub enum VmError {
Catchable(String),
Uncatchable(Box<Error>),
@@ -50,6 +51,7 @@ pub enum Break {
pub type Step = ControlFlow<Break>;
#[allow(dead_code)]
pub struct ErrorFrame {
pub span_id: u32,
pub message: Option<String>,
@@ -59,9 +61,8 @@ pub struct ErrorFrame {
#[collect(no_drop)]
pub struct CallFrame<'gc> {
pub pc: usize,
pub env: GcEnv<'gc>,
pub thunk: Option<Gc<'gc, Thunk<'gc>>>,
pub depth: Option<usize>,
pub env: GcEnv<'gc>,
}
#[derive(Debug)]
+3 -7
View File
@@ -31,10 +31,10 @@ impl StringContextElem {
drv_path: drv_path.into(),
}
} else if let Some(rest) = encoded.strip_prefix('!') {
if let Some((output, drv_path)) = rest.split_once('!') {
if let Some(second_bang) = rest.find('!') {
Self::Built {
output: output.into(),
drv_path: drv_path.into(),
output: rest[..second_bang].into(),
drv_path: rest[second_bang + 1..].into(),
}
} else {
Self::Opaque {
@@ -117,10 +117,6 @@ impl StringContext {
}
}
#[expect(
clippy::indexing_slicing,
reason = "`i`/`j` stay strictly below their lengths inside the loop, and the trailing slices use those in-bounds cursors as start indices"
)]
pub fn merge(&self, other: &Self) -> Self {
if self.data.is_empty() {
return other.clone();
+137 -180
View File
@@ -4,9 +4,7 @@ use std::marker::PhantomData;
use std::mem::size_of;
use std::ops::Deref;
use fix_bytecode::Continuation;
use fix_lang::*;
use fix_macros::unelide_lifetimes;
use gc_arena::barrier::Unlock;
use gc_arena::collect::Trace;
use gc_arena::{Collect, Gc, GcRefLock, Mutation, RefLock};
@@ -21,98 +19,80 @@ mod private {
pub trait Cealed {}
}
pub trait ValueVariant<'gc>: private::Cealed {
#[expect(
private_bounds,
reason = "Storable is a sealed implementation detail of the value system"
)]
type Ty: Storable<'gc>;
const TYPE: NixType;
pub trait ValueVariant: private::Cealed {
type Ty<'gc>: 'gc;
fn is_value(value: &Value<'_>) -> bool;
/// # Safety
///
/// [`Self::is_value`] must hold for `value`.
unsafe fn from_raw<'gc>(value: &Value<'gc>) -> Self::Ty<'gc>;
}
trait Storable<'gc>: TryFrom<Value<'gc>> + Into<Value<'gc>> + private::Cealed + 'gc {
fn is(raw: &RawBox) -> bool;
/// # Safety
///
/// Each implementor must round-trip through [`Self::to_raw_box`] /
/// [`Self::from_raw_box`] and must be the sole owner of its NaN-boxed
/// representation (tagged payload or float).
pub(crate) unsafe trait Storable: private::Cealed {
fn to_raw_box(self) -> RawBox;
/// # Safety
///
/// `raw` must represent a valid `Self`.
unsafe fn from_raw_box(raw: RawBox) -> Self;
unsafe fn from_raw_box(raw: &RawBox) -> Self;
}
macro_rules! define_value_types {
(
inline { $($itype:ty => $itag:path, $ity:path, $iname:literal;)* }
gc { $($gtype:ty => $gtag:path, $gty:path, $gname:literal;)* }
inline { $($itype:ty => $itag:path, $iname:literal;)* }
gc { $($gtype:ty => $gtag:path, $gname:literal;)* }
) => {
$(
impl Storable<'_> for $itype {
#[inline(always)]
fn is(value: &RawBox) -> bool {
value.tag() == Some($itag)
}
#[inline(always)]
unsafe impl Storable for $itype {
fn to_raw_box(self) -> RawBox {
RawBox::from_value(RawValue::store($itag, self))
}
#[inline(always)]
unsafe fn from_raw_box(raw: RawBox) -> Self {
// SAFETY: the caller guarantees `raw` represents a valid
// `Self` of this inline type, so it holds a `Value` (making
// `value()` `Some`) whose payload decodes to this type.
unsafe fn from_raw_box(raw: &RawBox) -> Self {
unsafe { <Self as RawStore>::from_val(raw.value().unwrap_unchecked()) }
}
}
impl private::Cealed for $itype {}
impl<'gc> ValueVariant<'gc> for $itype {
type Ty = $itype;
const TYPE: NixType = $ity;
}
impl<'gc> TryFrom<Value<'gc>> for $itype {
type Error = ();
fn try_from(val: Value<'gc>) -> Result<Self, Self::Error> {
<Self as Storable>::is(&val.raw)
// SAFETY: `is` returned true, so `val.raw` represents a
// valid `Self` of this GC type.
.then(|| unsafe { <Self as Storable>::from_raw_box(val.raw) })
.ok_or(())
impl ValueVariant for $itype {
type Ty<'gc> = $itype;
#[inline(always)]
fn is_value(value: &Value<'_>) -> bool {
value.raw.tag() == Some($itag)
}
#[inline(always)]
unsafe fn from_raw<'gc>(value: &Value<'gc>) -> Self::Ty<'gc> {
unsafe { <$itype as Storable>::from_raw_box(&value.raw) }
}
}
)*
$(
impl<'gc> Storable<'gc> for Gc<'gc, unelide_lifetimes!('gc; $gtype)> {
#[inline(always)]
fn is(value: &RawBox) -> bool {
value.tag() == Some($gtag)
}
#[inline(always)]
unsafe impl Storable for Gc<'_, $gtype> {
fn to_raw_box(self) -> RawBox {
RawBox::from_value(RawValue::store($gtag, Gc::as_ptr(self)))
}
#[inline(always)]
unsafe fn from_raw_box(raw: RawBox) -> Self {
// SAFETY: the caller guarantees `raw` represents a valid
// `Self` of this GC type, so it holds a `Value` (making
// `value()` `Some`) whose payload is the pointer originally
// produced by `Gc::as_ptr` in `to_raw_box`.
unsafe fn from_raw_box(raw: &RawBox) -> Self {
unsafe { Gc::from_ptr(<*mut $gtype as RawStore>::from_val(raw.value().unwrap_unchecked())) }
}
}
impl<'gc> TryFrom<Value<'gc>> for Gc<'gc, unelide_lifetimes!('gc; $gtype)> {
type Error = ();
fn try_from(val: Value<'gc>) -> Result<Self, Self::Error> {
<Self as Storable>::is(&val.raw)
// SAFETY: `is` returned true, so `val.raw` represents a
// valid `Self` of this GC type.
.then(|| unsafe { <Self as Storable>::from_raw_box(val.raw) })
.ok_or(())
}
}
impl private::Cealed for Gc<'_, $gtype> {}
impl private::Cealed for $gtype {}
impl<'gc> ValueVariant<'gc> for unelide_lifetimes!('gc; $gtype) {
type Ty = Gc<'gc, unelide_lifetimes!('gc; $gtype)>;
const TYPE: NixType = $gty;
impl ValueVariant for $gtype {
type Ty<'gc> = Gc<'gc, fix_macros::unelide_lifetimes!('gc; $gtype)>;
#[inline(always)]
fn is_value(value: &Value<'_>) -> bool {
value.raw.tag() == Some($gtag)
}
#[inline(always)]
unsafe fn from_raw<'gc>(value: &Value<'gc>) -> Self::Ty<'gc> {
unsafe {
<Gc<'gc, fix_macros::unelide_lifetimes!('gc; $gtype)> as Storable>::from_raw_box(
&value.raw,
)
}
}
}
)*
@@ -125,7 +105,6 @@ macro_rules! define_value_types {
let mut mask_true: u8 = 0;
let mut i = 0;
while i < tags.len() {
#[expect(clippy::indexing_slicing, reason = "loop condition guarantees `i < tags.len()`")]
let (neg, val) = tags[i];
let bit = 1 << val;
if neg {
@@ -139,17 +118,12 @@ macro_rules! define_value_types {
}
};
// SAFETY: `trace` visits every reachable `Gc` pointer: for each GC
// tag it downcasts to the concrete `Gc` type and forwards `trace`,
// while inline tags hold no GC pointers and need no tracing.
unsafe impl<'gc> Collect<'gc> for Value<'gc> {
const NEEDS_TRACE: bool = true;
fn trace<T: Trace<'gc>>(&self, cc: &mut T) {
let Some(tag) = self.raw.tag() else { return };
match tag {
$($gtag => unsafe {
// SAFETY: `tag` matched `$gtag`, so `downcast` to the
// corresponding GC type is guaranteed to be `Some`.
self.downcast::<$gtype>().unwrap_unchecked().trace(cc)
},)*
$($itag => (),)*
@@ -161,13 +135,9 @@ macro_rules! define_value_types {
impl fmt::Debug for Value<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.tag() {
// SAFETY: `tag()` is `None`, meaning the `RawBox` holds a
// float, so `float()` is guaranteed to be `Some`.
None => write!(f, "Float({:?})", unsafe {
self.raw.float().unwrap_unchecked()
}),
// SAFETY: `tag()` matched `$itag`, so `downcast` to the
// corresponding inline type is guaranteed to be `Some`.
$(Some($itag) => write!(f, "{}({:?})", $iname, unsafe {
self.downcast::<$itype>().unwrap_unchecked()
}),)*
@@ -182,58 +152,44 @@ macro_rules! define_value_types {
define_value_types! {
inline {
i32 => RawTag::P1, NixType::Int, "SmallInt";
bool => RawTag::P2, NixType::Bool, "Bool";
Null => RawTag::P3, NixType::Null, "Null";
StringId => RawTag::P4, NixType::String, "SmallString";
PrimOp => RawTag::P5, NixType::PrimOp, "PrimOp";
Path => RawTag::P6, NixType::Path, "Path";
i32 => RawTag::P1, "SmallInt";
bool => RawTag::P2, "Bool";
Null => RawTag::P3, "Null";
StringId => RawTag::P4, "SmallString";
PrimOp => RawTag::P5, "PrimOp";
Path => RawTag::P6, "Path";
}
gc {
i64 => RawTag::P7, NixType::Int, "BigInt";
NixString => RawTag::N1, NixType::String, "String";
AttrSet<'_> => RawTag::N2, NixType::AttrSet, "AttrSet";
List<'_> => RawTag::N3, NixType::List, "List";
Thunk<'_> => RawTag::N4, NixType::Thunk, "Thunk";
Closure<'_> => RawTag::N5, NixType::Closure, "Closure";
PrimOpApp<'_> => RawTag::N6, NixType::PrimOpApp, "PrimOpApp";
i64 => RawTag::P7, "BigInt";
NixString => RawTag::N1, "String";
AttrSet<'_> => RawTag::N2, "AttrSet";
List<'_> => RawTag::N3, "List";
Thunk<'_> => RawTag::N4, "Thunk";
Closure<'_> => RawTag::N5, "Closure";
PrimOpApp<'_> => RawTag::N6, "PrimOpApp";
}
}
impl private::Cealed for f64 {}
impl Storable<'_> for f64 {
#[inline(always)]
fn is(value: &RawBox) -> bool {
value.is_float()
}
#[inline(always)]
unsafe impl Storable for f64 {
fn to_raw_box(self) -> RawBox {
RawBox::from_float(self)
}
#[inline(always)]
unsafe fn from_raw_box(raw: RawBox) -> Self {
// SAFETY: the caller guarantees `raw` represents a valid `f64`, so
// `float()` is guaranteed to be `Some`.
unsafe fn from_raw_box(raw: &RawBox) -> Self {
unsafe { raw.float().copied().unwrap_unchecked() }
}
}
impl<'gc> ValueVariant<'gc> for f64 {
type Ty = f64;
const TYPE: NixType = NixType::Float;
}
impl<'gc> TryFrom<Value<'gc>> for f64 {
type Error = ();
fn try_from(value: Value<'gc>) -> Result<Self, Self::Error> {
value.downcast::<f64>().ok_or(())
impl ValueVariant for f64 {
type Ty<'gc> = f64;
#[inline(always)]
fn is_value(value: &Value<'_>) -> bool {
value.raw.is_float()
}
}
impl<'gc, T: Storable<'gc>> From<T> for Value<'gc> {
fn from(value: T) -> Self {
Value::new(value)
#[inline(always)]
unsafe fn from_raw<'gc>(value: &Value<'gc>) -> Self::Ty<'gc> {
unsafe { <f64 as Storable>::from_raw_box(&value.raw) }
}
}
@@ -263,11 +219,16 @@ impl<'gc> Value<'gc> {
impl<'gc> Value<'gc> {
#[inline]
#[expect(
private_bounds,
reason = "Storable is a sealed implementation detail of the value system"
)]
pub fn new<T: Storable<'gc>>(val: T) -> Self {
pub fn new_float(val: f64) -> Self {
Self {
raw: RawBox::from_float(val),
_marker: PhantomData,
}
}
#[inline]
#[allow(private_bounds)]
pub fn new<T: Storable>(val: T) -> Self {
Self {
raw: val.to_raw_box(),
_marker: PhantomData,
@@ -282,18 +243,29 @@ impl<'gc> Value<'gc> {
Value::new(Gc::new(mc, val))
}
}
}
impl<'gc> Value<'gc> {
#[inline]
pub fn is<T: ValueVariant<'gc>>(self) -> bool {
T::Ty::is(&self.raw)
pub fn is_float(self) -> bool {
self.raw.is_float()
}
#[inline]
pub fn downcast<T: ValueVariant<'gc>>(self) -> Option<T::Ty> {
self.is::<T>()
// SAFETY: `is::<T>()` returned true, so `self.raw` represents a
// valid `T::Ty`.
.then(|| unsafe { T::Ty::from_raw_box(self.raw) })
pub fn is<T: ValueVariant>(self) -> bool {
T::is_value(&self)
}
}
impl<'gc> Value<'gc> {
#[inline]
pub fn downcast_float(self) -> Option<f64> {
self.raw.float().copied()
}
#[inline]
pub fn downcast<T: ValueVariant>(self) -> Option<T::Ty<'gc>> {
self.is::<T>().then(|| unsafe { T::from_raw(&self) })
}
#[inline]
@@ -302,13 +274,13 @@ impl<'gc> Value<'gc> {
}
#[inline]
pub fn downcast_num(self) -> Option<NixNum> {
pub fn as_num(self) -> Option<NixNum> {
if let Some(i) = self.downcast::<i32>() {
Some(NixNum::Int(i as i64))
} else if let Some(gc_i) = self.downcast::<i64>() {
Some(NixNum::Int(*gc_i))
} else {
self.downcast::<f64>().map(NixNum::Float)
self.downcast_float().map(NixNum::Float)
}
}
@@ -322,12 +294,8 @@ impl<'gc> Value<'gc> {
}
#[inline]
#[expect(
clippy::unreachable,
reason = "the preceding `if`/`else if` chain exhausts every registered value tag"
)]
pub fn ty(self) -> NixType {
if self.is::<f64>() {
if self.is_float() {
NixType::Float
} else if self.is::<i32>() || self.is::<i64>() {
NixType::Int
@@ -359,13 +327,18 @@ impl<'gc> Value<'gc> {
}
#[inline]
pub fn expect<T: ValueVariant<'gc>>(self) -> Result<T::Ty, NixType> {
pub fn expect<T: ValueVariant>(self) -> Result<T::Ty<'gc>, NixType> {
self.downcast::<T>().ok_or_else(|| self.ty())
}
#[inline]
pub fn expect_num(self) -> Result<NixNum, NixType> {
self.downcast_num().ok_or_else(|| self.ty())
self.as_num().ok_or_else(|| self.ty())
}
#[inline]
pub fn expect_float(self) -> Result<f64, NixType> {
self.downcast_float().ok_or_else(|| self.ty())
}
}
@@ -383,22 +356,38 @@ impl<'gc> From<StaticValue> for Value<'gc> {
impl StaticValue {
#[inline]
#[expect(
private_bounds,
reason = "Storable is a sealed implementation detail of the value system"
)]
pub fn new<T: Storable<'static>>(val: T) -> Self {
pub fn new_float(val: f64) -> Self {
Self(Value::new_float(val))
}
#[inline]
#[allow(private_bounds)]
pub fn new<T: Storable + 'static>(val: T) -> Self {
Self(Value::new(val))
}
#[inline]
pub fn is<T: ValueVariant<'static>>(self) -> bool {
pub fn new_primop(id: BuiltinId, arity: u8, dispatch_ip: u32) -> Self {
Self::new(PrimOp {
id,
arity,
dispatch_ip,
})
}
#[inline]
pub fn is_float(self) -> bool {
self.0.is_float()
}
#[inline]
pub fn is<T: ValueVariant>(self) -> bool {
self.0.is::<T>()
}
#[inline]
pub fn downcast<T: ValueVariant>(self) -> Option<T::Ty<'static>> {
self.0.downcast::<T>()
}
#[inline]
pub fn downcast<T: ValueVariant<'static>>(self) -> Option<T::Ty> {
self.0.downcast::<T>()
pub fn downcast_float(self) -> Option<f64> {
self.0.downcast_float()
}
#[inline]
@@ -499,10 +488,6 @@ impl<'gc> AttrSet<'gc> {
Self { entries }
}
#[expect(
clippy::indexing_slicing,
reason = "index comes from a successful `binary_search_by_key`, so it is a valid entry index"
)]
pub fn lookup(&self, key: StringId) -> Option<Value<'gc>> {
self.entries
.binary_search_by_key(&key, |(k, _)| *k)
@@ -514,10 +499,6 @@ impl<'gc> AttrSet<'gc> {
self.entries.binary_search_by_key(&key, |(k, _)| *k).is_ok()
}
#[expect(
clippy::indexing_slicing,
reason = "`i`/`j` stay strictly below their lengths inside the loop, and the trailing slices use those in-bounds cursors as start indices"
)]
pub fn merge(&self, other: &Self, mc: &Mutation<'gc>) -> Gc<'gc, Self> {
use std::cmp::Ordering::*;
@@ -578,9 +559,6 @@ impl<'gc> List<'gc> {
impl<'gc> Unlock for List<'gc> {
type Unlocked = RefCell<SmallVec<[Value<'gc>; 4]>>;
unsafe fn unlock_unchecked(&self) -> &Self::Unlocked {
// SAFETY: the caller upholds the `Unlock` contract (mutation happens
// behind a write barrier); we forward that obligation to the inner
// `RefLock`'s `unlock_unchecked`.
unsafe { self.inner.unlock_unchecked() }
}
}
@@ -604,6 +582,14 @@ pub struct Env<'gc> {
}
pub type GcEnv<'gc> = GcRefLock<'gc, Env<'gc>>;
#[derive(Collect, Debug)]
#[collect(no_drop)]
pub struct WithEnv<'gc> {
pub env: Value<'gc>,
pub prev: Option<GcWithEnv<'gc>>,
}
pub type GcWithEnv<'gc> = Gc<'gc, WithEnv<'gc>>;
impl<'gc> Env<'gc> {
pub fn empty() -> Self {
Env {
@@ -612,10 +598,6 @@ impl<'gc> Env<'gc> {
}
}
#[expect(
clippy::indexing_slicing,
reason = "`locals` was just created with `1 + n_locals` elements, so index 0 is always valid"
)]
pub fn with_arg(arg: Value<'gc>, n_locals: u32, prev: Gc<'gc, RefLock<Env<'gc>>>) -> Self {
let mut locals = smallvec::smallvec![Value::default(); 1 + n_locals as usize];
locals[0] = arg;
@@ -653,18 +635,6 @@ pub struct PrimOp {
pub dispatch_ip: u32,
}
impl From<BuiltinId> for PrimOp {
fn from(id: BuiltinId) -> Self {
let BuiltinInfo { arity, .. } = id.info();
let dispatch_ip = Continuation::entry_for_builtin(id).ip();
Self {
id,
arity,
dispatch_ip,
}
}
}
impl RawStore for PrimOp {
fn to_val(self, value: &mut RawValue) {
let bytes = self.dispatch_ip.to_le_bytes();
@@ -715,19 +685,6 @@ impl<'gc> Deref for StrictValue<'gc> {
}
}
impl<'gc> From<StrictValue<'gc>> for Value<'gc> {
fn from(value: StrictValue<'gc>) -> Self {
value.0
}
}
impl<'gc> TryFrom<Value<'gc>> for StrictValue<'gc> {
type Error = Gc<'gc, Thunk<'gc>>;
fn try_from(value: Value<'gc>) -> Result<Self, Self::Error> {
value.restrict()
}
}
impl fmt::Debug for StrictValue<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
+1 -5
View File
@@ -7,16 +7,12 @@ edition = "2024"
gc-arena = { workspace = true }
hashbrown = { workspace = true }
smallvec = { workspace = true }
sysinfo = { version = "0.39", default-features = false, features = ["system"] }
sysinfo = { version = "0.38", default-features = false, features = ["system"] }
fix-bytecode = { path = "../fix-bytecode" }
fix-error = { path = "../fix-error" }
fix-lang = { path = "../fix-lang" }
fix-macros = { path = "../fix-macros" }
fix-runtime = { path = "../fix-runtime" }
[features]
tailcall = []
[lints]
workspace = true
+1 -6
View File
@@ -22,7 +22,6 @@ pub(crate) type OpFn<'gc, C> = extern "rust-preserve-none" fn(
pub(crate) struct DispatchTable<'gc, C: VmRuntimeCtx>(pub(crate) [OpFn<'gc, C>; 256]);
#[expect(clippy::panic, reason = "illegal opcode should panic")]
extern "rust-preserve-none" fn op_illegal<'gc, C: VmRuntimeCtx>(
_vm: &mut Vm<'gc>,
_mc: &Mutation<'gc>,
@@ -201,7 +200,6 @@ tail_fn!(op_load_scoped_binding, (ctx, reader, mc));
macro_rules! table {
($($variant:ident => $fn:ident),* $(,)?) => {
impl<'gc, C: VmRuntimeCtx> DispatchTable<'gc, C> {
#[expect(clippy::indexing_slicing, reason = "Op is repr(u8)")]
pub(crate) const NEW: Self = {
let mut arr: [OpFn<'gc, C>; 256] = [op_illegal; 256];
$( arr[fix_bytecode::Op::$variant as usize] = $fn; )*
@@ -211,6 +209,7 @@ macro_rules! table {
// Exhaustiveness check: fails to compile if `fix_bytecode::Op` gains,
// loses, or renames a variant that isn't wired up above.
#[allow(dead_code)]
const _: fn(fix_bytecode::Op) = |op| match op {
$( fix_bytecode::Op::$variant => (), )*
};
@@ -292,10 +291,6 @@ table! {
Illegal => op_illegal,
}
#[expect(
clippy::indexing_slicing,
reason = "assume well-formed bytecode; Op is repr(u8)"
)]
pub(crate) fn run_tailcall<'gc, C: VmRuntimeCtx>(
vm: &mut Vm<'gc>,
mc: &Mutation<'gc>,
+9 -5
View File
@@ -229,7 +229,7 @@ pub(crate) fn op_neg<'gc, M: Machine<'gc>>(
let rhs = m.force_and_retry::<NixNum>(reader, mc)?;
match rhs {
NixNum::Int(int) => m.push(Value::make_int(-int, mc)),
NixNum::Float(float) => m.push(Value::new(-float)),
NixNum::Float(float) => m.push(Value::new_float(-float)),
}
Step::Continue(())
}
@@ -290,7 +290,7 @@ pub(crate) fn get_num(val: StrictValue<'_>) -> Option<NixNum> {
} else if let Some(gc_i) = val.downcast::<i64>() {
Some(NixNum::Int(*gc_i))
} else {
val.downcast::<f64>().map(NixNum::Float)
val.downcast_float().map(NixNum::Float)
}
}
@@ -304,9 +304,13 @@ fn numeric_binop<'gc>(
) -> crate::VmResult<Value<'gc>> {
match (get_num(lhs), get_num(rhs)) {
(Some(NixNum::Int(a)), Some(NixNum::Int(b))) => Ok(Value::make_int(int_op(a, b), mc)),
(Some(NixNum::Float(a)), Some(NixNum::Float(b))) => Ok(Value::new(float_op(a, b))),
(Some(NixNum::Int(a)), Some(NixNum::Float(b))) => Ok(Value::new(float_op(a as f64, b))),
(Some(NixNum::Float(a)), Some(NixNum::Int(b))) => Ok(Value::new(float_op(a, b as f64))),
(Some(NixNum::Float(a)), Some(NixNum::Float(b))) => Ok(Value::new_float(float_op(a, b))),
(Some(NixNum::Int(a)), Some(NixNum::Float(b))) => {
Ok(Value::new_float(float_op(a as f64, b)))
}
(Some(NixNum::Float(a)), Some(NixNum::Int(b))) => {
Ok(Value::new_float(float_op(a, b as f64)))
}
_ => Err(crate::vm_err(format!(
"cannot perform arithmetic on non-numbers: {:?}",
(lhs.ty(), rhs.ty())
+1 -15
View File
@@ -9,10 +9,6 @@ use crate::{
};
#[inline(always)]
#[expect(
clippy::indexing_slicing,
reason = "app.args is a fixed [Value; 3]; indices are bounded by primop arity (<= 3) validated at PrimOpApp construction"
)]
pub(crate) fn call<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
@@ -34,7 +30,6 @@ pub(crate) fn call<'gc, M: Machine<'gc>>(
pc: resume_pc,
thunk: None,
env: m.env(),
depth: None,
});
reader.set_pc(Continuation::CallPattern.ip() as usize);
return Step::Continue(());
@@ -48,7 +43,6 @@ pub(crate) fn call<'gc, M: Machine<'gc>>(
pc: resume_pc,
thunk: None,
env: m.env(),
depth: None,
});
reader.set_pc(ip as usize);
m.set_env(new_env);
@@ -59,7 +53,6 @@ pub(crate) fn call<'gc, M: Machine<'gc>>(
pc: resume_pc,
thunk: None,
env: m.env(),
depth: None,
});
reader.set_pc(primop.dispatch_ip as usize)
} else {
@@ -80,7 +73,6 @@ pub(crate) fn call<'gc, M: Machine<'gc>>(
pc: resume_pc,
thunk: None,
env: m.env(),
depth: None,
});
reader.set_pc(app.primop.dispatch_ip as usize)
} else {
@@ -105,7 +97,6 @@ pub(crate) fn call<'gc, M: Machine<'gc>>(
pc: resume_pc,
thunk: None,
env: m.env(),
depth: None,
});
m.push(arg);
m.push(func.relax());
@@ -145,7 +136,6 @@ pub(crate) fn op_return<'gc, M: Machine<'gc>>(
pc: ret_pc,
thunk,
env,
depth,
}) = m.pop_call_frame()
else {
match m.force_mode() {
@@ -162,10 +152,9 @@ pub(crate) fn op_return<'gc, M: Machine<'gc>>(
pc: Continuation::ForceResultDeepFinish.ip() as usize,
thunk: None,
env: m.env(),
depth: None,
});
m.inc_call_depth();
reader.set_pc(Continuation::PDeepSeq0.ip() as usize);
reader.set_pc(Continuation::PDeepSeq.ip() as usize);
return Step::Continue(());
}
}
@@ -173,9 +162,6 @@ pub(crate) fn op_return<'gc, M: Machine<'gc>>(
reader.set_pc(ret_pc);
if let Some(outer_thunk) = thunk {
*outer_thunk.borrow_mut(mc) = ThunkState::Evaluated(val);
if let Some(depth) = depth {
m.replace(depth, val.relax());
}
} else {
m.dec_call_depth();
m.push(val.relax())
-21
View File
@@ -117,10 +117,6 @@ pub(crate) fn op_select_dynamic<'gc, M: Machine<'gc>>(
/// Only recognises Select opcodes and jumps; encountering any other
/// opcode means we've reached the end of the select sequence and
/// should report the missing-attribute error.
#[expect(
clippy::cast_sign_loss,
reason = "jump target = pc + offset is a non-negative bytecode address by codegen invariant"
)]
fn select_skip<'gc, M: Machine<'gc>>(
m: &mut M,
key: StringId,
@@ -130,7 +126,6 @@ fn select_skip<'gc, M: Machine<'gc>>(
use fix_bytecode::Op::*;
loop {
match reader.read_op() {
// Skip rest of the attrpath
SelectStatic => {
reader.set_pc(reader.pc() + 4 + 4);
}
@@ -141,14 +136,10 @@ fn select_skip<'gc, M: Machine<'gc>>(
reader.set_pc(reader.pc() + 4);
break Step::Continue(());
}
// Default (`a.b or c`)
JumpIfSelectFailed => {
let offset = reader.read_i32();
reader.set_pc(((reader.pc() as isize) + (offset as isize)) as usize);
}
// Report error
_ => {
let name = ctx.resolve_string(key);
return m.finish_err(Error::eval_error(format!("attribute '{name}' missing")));
@@ -159,14 +150,6 @@ fn select_skip<'gc, M: Machine<'gc>>(
/// Skip the rest of a **HasAttr** attrpath after an intermediate
/// lookup failed. Only recognises HasAttr opcodes and jumps.
#[expect(
clippy::cast_sign_loss,
reason = "jump target = pc + offset is a non-negative bytecode address by codegen invariant"
)]
#[expect(
clippy::unreachable,
reason = "has_attr_skip only runs over a codegen-produced HasAttr attrpath sequence; any other opcode is a codegen bug"
)]
fn has_attr_skip(reader: &mut BytecodeReader<'_>) -> Step {
use fix_bytecode::Op::*;
loop {
@@ -262,10 +245,6 @@ pub(crate) fn op_jump_if_select_failed<'gc, M: Machine<'gc>>(
}
#[inline(always)]
#[expect(
clippy::cast_sign_loss,
reason = "jump target = pc + offset is a non-negative bytecode address by codegen invariant"
)]
pub(crate) fn op_jump_if_select_succeeded<'gc, M: Machine<'gc>>(
_m: &mut M,
reader: &mut BytecodeReader<'_>,
-12
View File
@@ -5,10 +5,6 @@ use gc_arena::Mutation;
use crate::{BytecodeReader, Step, VmRuntimeCtx};
#[inline(always)]
#[expect(
clippy::cast_sign_loss,
reason = "jump target = pc + offset is a non-negative bytecode address by codegen invariant"
)]
pub(crate) fn op_jump_if_false<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
@@ -23,10 +19,6 @@ pub(crate) fn op_jump_if_false<'gc, M: Machine<'gc>>(
}
#[inline(always)]
#[expect(
clippy::cast_sign_loss,
reason = "jump target = pc + offset is a non-negative bytecode address by codegen invariant"
)]
pub(crate) fn op_jump_if_true<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
@@ -41,10 +33,6 @@ pub(crate) fn op_jump_if_true<'gc, M: Machine<'gc>>(
}
#[inline(always)]
#[expect(
clippy::cast_sign_loss,
reason = "jump target = pc + offset is a non-negative bytecode address by codegen invariant"
)]
pub(crate) fn op_jump<'gc, M: Machine<'gc>>(_m: &mut M, reader: &mut BytecodeReader<'_>) -> Step {
let offset = reader.read_i32();
reader.set_pc(((reader.pc() as isize) + (offset as isize)) as usize);
+1 -1
View File
@@ -30,7 +30,7 @@ pub(crate) fn op_push_float<'gc, M: Machine<'gc>>(
reader: &mut BytecodeReader<'_>,
) -> Step {
let val = reader.read_f64();
m.push(Value::new(val));
m.push(Value::new_float(val));
Step::Continue(())
}
+3 -7
View File
@@ -2,7 +2,7 @@ use std::path::PathBuf;
use fix_bytecode::Continuation;
use fix_error::Error;
use fix_lang::{BuiltinId, StringId};
use fix_lang::{BUILTINS, BuiltinId, StringId};
use fix_runtime::{
AttrSet, Machine, MachineExt, NixString, Path, StrictValue, StringContext, canon_path_str,
};
@@ -11,15 +11,11 @@ use crate::{BytecodeReader, PrimOp, Step, Value, VmRuntimeCtx, VmRuntimeCtxExt};
#[inline(always)]
pub(crate) fn op_load_builtins<'gc, M: Machine<'gc>>(m: &mut M) -> Step {
m.push(m.builtins().into());
m.push(m.builtins());
Step::Continue(())
}
#[inline(always)]
#[expect(
clippy::panic,
reason = "codegen only emits LoadBuiltin with valid BuiltinId bytes; an unknown id is a codegen/bytecode-corruption bug"
)]
pub(crate) fn op_load_builtin<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
@@ -28,7 +24,7 @@ pub(crate) fn op_load_builtin<'gc, M: Machine<'gc>>(
.map_err(|err| panic!("unknown builtin id: {}", err.number));
m.push(Value::new(PrimOp {
id,
arity: id.info().arity,
arity: BUILTINS[id as usize].1,
dispatch_ip: Continuation::entry_for_builtin(id).ip(),
}));
Step::Continue(())
-12
View File
@@ -3,10 +3,6 @@ use fix_runtime::Machine;
use crate::{BytecodeReader, Mutation, Step, Value};
#[inline(always)]
#[expect(
clippy::indexing_slicing,
reason = "local slot index is produced by codegen and bounded by the frame's AllocLocals count"
)]
pub(crate) fn op_load_local<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
@@ -17,10 +13,6 @@ pub(crate) fn op_load_local<'gc, M: Machine<'gc>>(
}
#[inline(always)]
#[expect(
clippy::indexing_slicing,
reason = "local slot index is produced by codegen and bounded by the target frame's AllocLocals count"
)]
pub(crate) fn op_load_outer<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
@@ -38,10 +30,6 @@ pub(crate) fn op_load_outer<'gc, M: Machine<'gc>>(
}
#[inline(always)]
#[expect(
clippy::indexing_slicing,
reason = "local slot index is produced by codegen and bounded by the frame's AllocLocals count"
)]
pub(crate) fn op_store_local<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
+2 -11
View File
@@ -6,21 +6,14 @@ use smallvec::SmallVec;
use crate::{Break, BytecodeReader, CallFrame, Step, VmRuntimeCtx};
#[inline(always)]
#[expect(
clippy::indexing_slicing,
clippy::cast_sign_loss,
reason = "counter is a non-negative with-scope index in 0..n, staying within the namespaces vec of length n"
)]
pub(crate) fn op_lookup_with<'gc, M: Machine<'gc>>(
m: &mut M,
ctx: &mut impl VmRuntimeCtx,
reader: &mut BytecodeReader<'_>,
mc: &gc_arena::Mutation<'gc>,
) -> Step {
let counter = m
.peek_forced(0)
.downcast::<i32>()
.expect("stack slot must be an integer");
#[allow(clippy::unwrap_used)]
let counter = m.peek_forced(0).downcast::<i32>().unwrap();
let name = reader.read_string_id();
let n = reader.read_u8();
@@ -41,7 +34,6 @@ pub(crate) fn op_lookup_with<'gc, M: Machine<'gc>>(
thunk: Some(thunk),
pc: resume_pc,
env: m.env(),
depth: None,
});
m.set_env(env);
reader.set_pc(ip);
@@ -53,7 +45,6 @@ pub(crate) fn op_lookup_with<'gc, M: Machine<'gc>>(
thunk: Some(thunk),
pc: resume_pc,
env: m.env(),
depth: None,
});
m.push(func);
return m.call(reader, mc, arg, resume_pc);
+13 -27
View File
@@ -1,7 +1,5 @@
#![cfg_attr(
feature = "tailcall",
expect(incomplete_features, reason = "for testing purpose only")
)]
#![warn(clippy::unwrap_used)]
#![cfg_attr(feature = "tailcall", expect(incomplete_features))]
#![cfg_attr(
feature = "tailcall",
feature(explicit_tail_calls, rust_preserve_none_cc)
@@ -11,7 +9,7 @@ use std::path::PathBuf;
use fix_bytecode::{Continuation, InstructionPtr};
use fix_error::{Error, Result, Source};
use fix_lang::{BuiltinId, StringId};
use fix_lang::{BUILTINS, BuiltinId, StringId};
use gc_arena::metrics::Pacing;
use gc_arena::{Arena, Collect, Gc, Mutation, RefLock, Rootable};
use hashbrown::HashMap;
@@ -20,12 +18,8 @@ use smallvec::SmallVec;
#[cfg(feature = "tailcall")]
mod dispatch_tailcall;
pub use fix_runtime::*;
#[doc(hidden)]
#[path = "macro_support.rs"]
pub mod __macro_support;
mod instructions;
mod primops;
extern crate self as fix_vm;
type VmResult<T> = std::result::Result<T, VmError>;
@@ -35,10 +29,7 @@ pub struct Vm<'gc> {
stack: Vec<Value<'gc>>,
call_stack: Vec<CallFrame<'gc>>,
call_depth: usize,
#[expect(
dead_code,
reason = "error_context is reserved for tryEval catch-frame tracking, not yet wired up"
)]
#[allow(dead_code)]
#[collect(require_static)]
error_context: Vec<ErrorFrame>,
@@ -47,7 +38,7 @@ pub struct Vm<'gc> {
import_cache: HashMap<PathBuf, Value<'gc>>,
scope_slots: Vec<Value<'gc>>,
builtins: Gc<'gc, AttrSet<'gc>>,
builtins: Value<'gc>,
empty_list: Value<'gc>,
empty_attrs: Value<'gc>,
@@ -62,12 +53,13 @@ pub struct Vm<'gc> {
functor_sym: StringId,
}
fn init_builtins<'gc>(mc: &Mutation<'gc>, ctx: &mut impl VmRuntimeCtx) -> Gc<'gc, AttrSet<'gc>> {
let mut entries = SmallVec::with_capacity(BuiltinId::TOTAL);
fn init_builtins<'gc>(mc: &Mutation<'gc>, ctx: &mut impl VmRuntimeCtx) -> Value<'gc> {
let mut entries = SmallVec::with_capacity(BUILTINS.len());
for id in BuiltinId::ALL {
let arity = id.info().arity;
let name = ctx.intern_string(id.info().name);
for (idx, &(name, arity)) in BUILTINS.iter().enumerate() {
let id = BuiltinId::try_from(idx as u8).expect("infallible");
let name = name.strip_prefix("__").unwrap_or(name);
let name = ctx.intern_string(name);
let dispatch_ip = Continuation::entry_for_builtin(id).ip();
entries.push((
name,
@@ -109,7 +101,7 @@ fn init_builtins<'gc>(mc: &Mutation<'gc>, ctx: &mut impl VmRuntimeCtx) -> Gc<'gc
let builtins_value = Value::new(builtins_set);
*self_ref_thunk.borrow_mut(mc) =
ThunkState::Evaluated(builtins_value.restrict().expect("builtins is not a thunk"));
builtins_set
builtins_value
}
impl<'gc> Vm<'gc> {
@@ -215,7 +207,6 @@ impl<'gc> Machine<'gc> for Vm<'gc> {
thunk: Some(thunk),
pc: resume_pc,
env: self.env,
depth: Some(depth),
});
self.env = env;
reader.set_pc(ip);
@@ -230,7 +221,6 @@ impl<'gc> Machine<'gc> for Vm<'gc> {
thunk: Some(thunk),
pc: resume_pc,
env: self.env,
depth: Some(depth),
});
self.push(func);
self.call(reader, mc, arg, resume_pc)
@@ -308,7 +298,7 @@ impl<'gc> Machine<'gc> for Vm<'gc> {
}
#[inline(always)]
fn builtins(&self) -> Gc<'gc, AttrSet<'gc>> {
fn builtins(&self) -> Value<'gc> {
self.builtins
}
@@ -466,10 +456,6 @@ impl<'gc> Vm<'gc> {
#[inline(always)]
#[cfg(not(feature = "tailcall"))]
#[expect(
clippy::unreachable,
reason = "Op::Illegal is a sentinel never emitted by codegen; reaching it is a codegen bug"
)]
fn execute_batch(
&mut self,
bytecode: &[u8],
-36
View File
@@ -1,36 +0,0 @@
//! Single macro-facing path for the `#[primop]` support surface: the traits
//! generated code type-checks through (defined in `fix_runtime`, where the
//! impl sets are coherent) and the stub trio that keeps un-expanded primop
//! sources resolving in tooling.
use std::future::Future;
pub use fix_runtime::{CalleeReady, ForceTarget, UnwrapSlot};
use fix_runtime::{Slot, Value};
macro_rules! type_hint {
() => {
if false {
return async {
unreachable!();
};
}
};
}
#[expect(clippy::panic, reason = "deliberately panic when the stub is called")]
pub fn force<T>(_: Slot<Value<'_>>) -> impl Future<Output = Slot<T>> {
type_hint!();
panic!("stub `force` called at runtime")
}
#[expect(clippy::panic, reason = "deliberately panic when the stub is called")]
pub fn call<T, A, R>(_: &T, _: A) -> impl Future<Output = R> {
type_hint!();
panic!("stub `call` called at runtime")
}
#[expect(clippy::panic, reason = "deliberately panic when the stub is called")]
pub fn spill<T>(_: T) -> Slot<T> {
panic!("stub `spill` called at runtime")
}
+37 -89
View File
@@ -200,25 +200,16 @@ pub fn append_context<'gc, M: Machine<'gc>>(
Step::Continue(())
}
#[expect(
clippy::indexing_slicing,
clippy::cast_sign_loss,
reason = "idx is a non-negative loop counter guarded by `idx as usize >= attrs.entries.len()`, so it indexes attrs.entries in bounds"
)]
pub fn append_context_loop<'gc, M: Machine<'gc>>(
m: &mut M,
ctx: &mut impl VmRuntimeCtx,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> Step {
let idx = m
.peek(1)
.downcast::<i32>()
.expect("stack slot must be an integer");
let attrs = m
.peek_forced(2)
.downcast::<AttrSet>()
.expect("stack slot must be an attrset");
#[allow(clippy::unwrap_used)]
let idx = m.peek(1).downcast::<i32>().unwrap();
#[allow(clippy::unwrap_used)]
let attrs = m.peek_forced(2).downcast::<AttrSet>().unwrap();
if idx as usize >= attrs.entries.len() {
return append_context_finalize(m, ctx, reader, mc);
@@ -236,11 +227,6 @@ pub fn append_context_loop<'gc, M: Machine<'gc>>(
Step::Continue(())
}
#[expect(
clippy::indexing_slicing,
clippy::cast_sign_loss,
reason = "idx is the same non-negative outer-loop counter, in range for outer.entries validated by append_context_loop"
)]
pub fn append_context_entry_forced<'gc, M: Machine<'gc>>(
m: &mut M,
ctx: &mut impl VmRuntimeCtx,
@@ -256,14 +242,10 @@ pub fn append_context_entry_forced<'gc, M: Machine<'gc>>(
return m.finish_type_err(NixType::AttrSet, entry_val.ty());
};
let idx = m
.peek(2)
.downcast::<i32>()
.expect("stack slot must be an integer");
let outer = m
.peek_forced(3)
.downcast::<AttrSet>()
.expect("stack slot must be an attrset");
#[allow(clippy::unwrap_used)]
let idx = m.peek(2).downcast::<i32>().unwrap();
#[allow(clippy::unwrap_used)]
let outer = m.peek_forced(3).downcast::<AttrSet>().unwrap();
let path_key = outer.entries[idx as usize].0;
let path_str_owned: Box<str> = ctx.resolve_string(path_key).into();
if !path_str_owned.starts_with("/nix/store/") {
@@ -280,10 +262,8 @@ pub fn append_context_entry_forced<'gc, M: Machine<'gc>>(
let all_outputs_id = ctx.intern_string("allOutputs");
let outputs_id = ctx.intern_string("outputs");
let acc_gc = m
.peek(1)
.downcast::<NixString>()
.expect("stack slot must be a string");
#[allow(clippy::unwrap_used)]
let acc_gc = m.peek(1).downcast::<NixString>().unwrap();
let mut new_acc: StringContext = acc_gc.context().iter().cloned().collect();
if let Some(v) = entry_attrs.lookup(path_id)
@@ -322,11 +302,9 @@ pub fn append_context_entry_forced<'gc, M: Machine<'gc>>(
return Step::Continue(());
}
m.drop_n(1);
let idx_back = m
.peek(1)
.downcast::<i32>()
.expect("stack slot must be an integer");
let _ = m.pop();
#[allow(clippy::unwrap_used)]
let idx_back = m.peek(1).downcast::<i32>().unwrap();
m.replace(1, Value::new(idx_back + 1));
reader.set_pc(Continuation::PAppendContextLoop.ip() as usize);
Step::Continue(())
@@ -345,11 +323,9 @@ pub fn append_context_outputs_forced<'gc, M: Machine<'gc>>(
};
if list.inner.borrow().is_empty() {
// Stack: [strVal, attrs, idx, acc, list] -> drop list, bump idx.
m.drop_n(1);
let idx_back = m
.peek(1)
.downcast::<i32>()
.expect("stack slot must be an integer");
let _ = m.pop();
#[allow(clippy::unwrap_used)]
let idx_back = m.peek(1).downcast::<i32>().unwrap();
m.replace(1, Value::new(idx_back + 1));
reader.set_pc(Continuation::PAppendContextLoop.ip() as usize);
return Step::Continue(());
@@ -360,34 +336,24 @@ pub fn append_context_outputs_forced<'gc, M: Machine<'gc>>(
Step::Continue(())
}
#[expect(
clippy::indexing_slicing,
clippy::cast_sign_loss,
reason = "oidx is a non-negative loop counter guarded by `oidx as usize >= len`, so it indexes the list in bounds"
)]
pub fn append_context_output_element_loop<'gc, M: Machine<'gc>>(
m: &mut M,
_ctx: &mut impl VmRuntimeCtx,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> Step {
let oidx = m
.peek(0)
.downcast::<i32>()
.expect("stack slot must be an integer");
let list = m
.peek_forced(1)
.downcast::<VmList>()
.expect("stack slot must be a list");
#[allow(clippy::unwrap_used)]
let oidx = m.peek(0).downcast::<i32>().unwrap();
#[allow(clippy::unwrap_used)]
let list = m.peek_forced(1).downcast::<VmList>().unwrap();
let len = list.inner.borrow().len();
if oidx as usize >= len {
// Stack: [strVal, attrs, idx, acc, list, oidx] -> drop oidx & list,
// bump idx in place.
m.drop_n(2);
let idx_back = m
.peek(1)
.downcast::<i32>()
.expect("stack slot must be an integer");
let _ = m.pop();
let _ = m.pop();
#[allow(clippy::unwrap_used)]
let idx_back = m.peek(1).downcast::<i32>().unwrap();
m.replace(1, Value::new(idx_back + 1));
reader.set_pc(Continuation::PAppendContextLoop.ip() as usize);
return Step::Continue(());
@@ -405,11 +371,6 @@ pub fn append_context_output_element_loop<'gc, M: Machine<'gc>>(
Step::Continue(())
}
#[expect(
clippy::indexing_slicing,
clippy::cast_sign_loss,
reason = "idx is the non-negative outer-loop counter, in range for outer.entries validated by append_context_loop"
)]
pub fn append_context_output_element_forced<'gc, M: Machine<'gc>>(
m: &mut M,
ctx: &mut impl VmRuntimeCtx,
@@ -423,14 +384,10 @@ pub fn append_context_output_element_forced<'gc, M: Machine<'gc>>(
};
let output_name: Box<str> = output_name.into();
let idx = m
.peek(4)
.downcast::<i32>()
.expect("stack slot must be an integer");
let outer = m
.peek_forced(5)
.downcast::<AttrSet>()
.expect("stack slot must be an attrset");
#[allow(clippy::unwrap_used)]
let idx = m.peek(4).downcast::<i32>().unwrap();
#[allow(clippy::unwrap_used)]
let outer = m.peek_forced(5).downcast::<AttrSet>().unwrap();
let path_key = outer.entries[idx as usize].0;
let path_str: Box<str> = ctx.resolve_string(path_key).into();
if !path_str.ends_with(".drv") {
@@ -439,10 +396,8 @@ pub fn append_context_output_element_forced<'gc, M: Machine<'gc>>(
)));
}
let acc_gc = m
.peek(3)
.downcast::<NixString>()
.expect("stack slot must be a string");
#[allow(clippy::unwrap_used)]
let acc_gc = m.peek(3).downcast::<NixString>().unwrap();
let mut new_acc: StringContext = acc_gc.context().iter().cloned().collect();
new_acc.insert(StringContextElem::Built {
drv_path: path_str,
@@ -453,20 +408,14 @@ pub fn append_context_output_element_forced<'gc, M: Machine<'gc>>(
// Stack: [strVal, attrs, idx, acc, list, oidx, outElem] -> drop outElem,
// bump oidx in place.
m.drop_n(1);
let oidx = m
.peek(0)
.downcast::<i32>()
.expect("stack slot must be an integer");
let _ = m.pop();
#[allow(clippy::unwrap_used)]
let oidx = m.peek(0).downcast::<i32>().unwrap();
m.replace(0, Value::new(oidx + 1));
reader.set_pc(Continuation::PAppendContextOutputElementLoop.ip() as usize);
Step::Continue(())
}
#[expect(
clippy::panic,
reason = "strVal was forced to WHNF at appendContext entry, so restrict() can never observe a thunk here"
)]
fn append_context_finalize<'gc, M: Machine<'gc>>(
m: &mut M,
ctx: &mut impl VmRuntimeCtx,
@@ -474,11 +423,10 @@ fn append_context_finalize<'gc, M: Machine<'gc>>(
mc: &Mutation<'gc>,
) -> Step {
// Stack: [strVal, attrs, idx, acc]
let acc_gc = m
.pop()
.downcast::<NixString>()
.expect("stack slot must be a string");
m.drop_n(2);
#[allow(clippy::unwrap_used)]
let acc_gc = m.pop().downcast::<NixString>().unwrap();
let _ = m.pop(); // idx
let _ = m.pop(); // attrs
let str_val_raw = m.pop();
// The strVal was already forced at entry; restrict() is infallible here.
+146 -97
View File
@@ -1,89 +1,22 @@
use fix_bytecode::Continuation;
use fix_error::{Error, Result};
use fix_macros::handler;
use fix_error::Error;
use fix_runtime::{
AttrSet, BytecodeReader, Closure, Env, List, Machine, MachineExt, Slot, Step, StrictValue,
Value, VmRuntimeCtx, VmRuntimeCtxExt,
AttrSet, BytecodeReader, Closure, Env, List, Machine, MachineExt, Step, StrictValue, Value,
VmRuntimeCtx, VmRuntimeCtxExt,
};
use gc_arena::{Gc, Mutation, RefLock};
use smallvec::SmallVec;
use crate::primops::stubs::*;
#[handler(name = PSeq)]
fn seq<'gc>(mc: &Mutation<'gc>, e1: Slot<Value<'gc>>, e2: Slot<Value<'gc>>) -> Result<Value<'gc>> {
let _e1: Slot<StrictValue<'gc>> = force(e1).await?;
Ok(e2.get())
}
#[handler(name = PDeepSeq)]
fn deep_seq<'gc>(
pub fn seq<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
e1: Slot<Value<'gc>>,
e2: Slot<Value<'gc>>,
) -> Result<Value<'gc>> {
let e1: Slot<StrictValue<'gc>> = force(e1).await?;
if collect_children(e1.get()).is_empty() {
return Ok(e2.get());
}
let seen: Slot<List<'gc>> = spill(Gc::new(mc, List::default()));
let worklist: Slot<List<'gc>> = spill(List::new(mc, collect_children(e1.get())));
let count: Slot<i32> = spill(worklist.get().inner.borrow().len() as i32);
loop {
if count.get() == 0 {
return Ok(e2.get());
}
let item = worklist
.get()
.unlock(mc)
.borrow_mut()
.pop()
.expect("worklist is non-empty while count > 0");
count.set(count.get() - 1);
let item: Slot<StrictValue<'gc>> = force(item).await?;
let added = push_children(mc, seen.get(), worklist.get(), item);
count.set(count.get() + added);
}
}
fn collect_children<'gc>(val: StrictValue<'gc>) -> SmallVec<[Value<'gc>; 4]> {
if let Some(attrs) = val.downcast::<AttrSet<'gc>>() {
attrs.entries.iter().map(|&(_, v)| v).collect()
} else if let Some(list) = val.downcast::<List<'gc>>() {
list.inner.borrow().iter().copied().collect()
} else {
SmallVec::new()
}
}
fn push_children<'gc>(
mc: &Mutation<'gc>,
seen: Gc<'gc, List<'gc>>,
worklist: Gc<'gc, List<'gc>>,
item: StrictValue<'gc>,
) -> i32 {
let mut added = 0i32;
if let Some(attrs) = item.downcast::<AttrSet<'gc>>()
&& !is_value_in_seen(seen, item.relax())
{
add_value_to_seen(seen, mc, item.relax());
let mut wl = worklist.unlock(mc).borrow_mut();
for &(_, v) in attrs.entries.iter() {
wl.push(v);
}
added = attrs.entries.len() as i32;
} else if let Some(list) = item.downcast::<List<'gc>>()
&& !is_value_in_seen(seen, item.relax())
{
add_value_to_seen(seen, mc, item.relax());
let inner = list.inner.borrow();
let mut wl = worklist.unlock(mc).borrow_mut();
for &v in inner.iter() {
wl.push(v);
}
added = inner.len() as i32;
}
added
) -> Step {
// stack: [e1, e2] - force e1, return e2
m.force_slot(1, reader, mc)?;
let e2 = m.pop();
let _ = m.pop();
m.return_from_primop(e2, reader)
}
pub fn abort<'gc, M: Machine<'gc>>(
@@ -101,6 +34,133 @@ pub fn abort<'gc, M: Machine<'gc>>(
)))
}
pub fn deep_seq_force_top<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> Step {
// stack: [e1, e2] - force e1, return e2
m.force_slot(1, reader, mc)?;
let e1 = m.peek_forced(1);
let children: SmallVec<_> = if let Some(attrs) = e1.downcast::<AttrSet>() {
let attrs = &attrs.entries;
if attrs.is_empty() {
SmallVec::new()
} else {
attrs.iter().map(|&(_, v)| v).collect()
}
} else if let Some(list) = e1.downcast::<List>() {
let inner = list.inner.borrow();
if inner.is_empty() {
SmallVec::new()
} else {
inner.iter().copied().collect()
}
} else {
SmallVec::new()
};
if children.is_empty() {
let e2 = m.pop();
let _ = m.pop();
return m.return_from_primop(e2, reader);
}
let count = children.len() as i32;
let seen = Gc::new(mc, List::default());
let worklist = List::new(mc, children);
let e2 = m.pop();
let _ = m.pop();
m.push(e2);
m.push(Value::new(seen));
m.push(Value::new(worklist));
m.push(Value::new(count));
reader.set_pc(Continuation::PDeepSeqPush.ip() as usize);
Step::Continue(())
}
pub fn deep_seq_push<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> Step {
// stack: [e2, seen, worklist, counter]
#[allow(clippy::unwrap_used)]
let counter = m.peek(0).downcast::<i32>().unwrap();
if counter == 0 {
let _ = m.pop(); // counter
let _ = m.pop(); // worklist
let _ = m.pop(); // seen
let val = m.pop();
return m.return_from_primop(val, reader);
}
#[allow(clippy::unwrap_used)]
let worklist = m.peek_forced(1).downcast::<List>().unwrap();
#[allow(clippy::unwrap_used)]
let item = worklist.unlock(mc).borrow_mut().pop().unwrap();
m.replace(0, Value::new(counter - 1));
m.push(item);
// force item at TOS, resume at DeepSeqLoop after force
m.force_slot_to_pc(0, reader, mc, Continuation::PDeepSeqLoop.ip() as usize)?;
reader.set_pc(Continuation::PDeepSeqLoop.ip() as usize);
Step::Continue(())
}
pub fn deep_seq_loop<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> Step {
// stack after pop: [e2, seen, worklist, counter]
let item = m.pop();
#[allow(clippy::unwrap_used)]
let counter = m.peek(0).downcast::<i32>().unwrap();
let mut added: usize = 0;
if let Some(attrs) = item.downcast::<AttrSet>() {
let attrs = &attrs.entries;
#[allow(clippy::unwrap_used)]
let seen = m.peek_forced(2).downcast::<List>().unwrap();
if !is_value_in_seen(seen, item) {
add_value_to_seen(seen, mc, item);
#[allow(clippy::unwrap_used)]
let worklist = m.peek_forced(1).downcast::<List>().unwrap();
{
let mut wl = worklist.unlock(mc).borrow_mut();
for &(_, v) in attrs.iter() {
wl.push(v);
}
added = attrs.len();
}
}
} else if let Some(list) = item.downcast::<List>() {
#[allow(clippy::unwrap_used)]
let seen = m.peek_forced(2).downcast::<List>().unwrap();
if !is_value_in_seen(seen, item) {
add_value_to_seen(seen, mc, item);
#[allow(clippy::unwrap_used)]
let worklist = m.peek_forced(1).downcast::<List>().unwrap();
{
let inner = list.inner.borrow();
let mut wl = worklist.unlock(mc).borrow_mut();
for &v in inner.iter() {
wl.push(v);
}
added = inner.len();
}
}
}
m.replace(0, Value::new(counter + added as i32));
reader.set_pc(Continuation::PDeepSeqPush.ip() as usize);
Step::Continue(())
}
pub fn force_result_shallow<'gc, M: Machine<'gc>>(
m: &mut M,
ctx: &mut impl VmRuntimeCtx,
@@ -131,27 +191,20 @@ pub fn force_result_shallow<'gc, M: Machine<'gc>>(
Step::Continue(())
}
#[expect(
clippy::cast_sign_loss,
reason = "idx is a non-negative loop counter (0..=len); used only with .get(), so the cast is always a valid index or safely out of range"
)]
pub fn force_result_shallow_push<'gc, M: Machine<'gc>>(
m: &mut M,
ctx: &mut impl VmRuntimeCtx,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> Step {
let idx = m
.peek(1)
.downcast::<i32>()
.expect("stack slot must be an integer");
let len = m
.peek(0)
.downcast::<i32>()
.expect("stack slot must be an integer");
#[allow(clippy::unwrap_used)]
let idx = m.peek(1).downcast::<i32>().unwrap();
#[allow(clippy::unwrap_used)]
let len = m.peek(0).downcast::<i32>().unwrap();
if idx == len {
m.drop_n(2);
let _ = m.pop(); // len
let _ = m.pop(); // idx
let val = m.pop();
return m.finish_ok(ctx.convert_value(val));
}
@@ -184,7 +237,7 @@ pub fn force_result_shallow_loop<'gc, M: Machine<'gc>>(
reader: &mut BytecodeReader<'_>,
_mc: &Mutation<'gc>,
) -> Step {
m.drop_n(1);
let _ = m.pop(); // forced child
reader.set_pc(Continuation::ForceResultShallowPush.ip() as usize);
Step::Continue(())
}
@@ -255,10 +308,6 @@ pub fn call_functor_2<'gc, M: Machine<'gc>>(
m.call(reader, mc, orig_arg, saved.pc)
}
#[expect(
clippy::unreachable,
reason = "CallPattern is only dispatched for closures whose pattern is Some, established when the Call opcode routed here"
)]
pub fn call_pattern<'gc, M: Machine<'gc>>(
m: &mut M,
ctx: &mut impl VmRuntimeCtx,
-4
View File
@@ -27,10 +27,6 @@ pub fn to_string<'gc, M: Machine<'gc>>(
)))
}
#[expect(
clippy::unreachable,
reason = "val was forced to WHNF by force_and_retry, so its type is never Thunk here"
)]
pub fn type_of<'gc, M: Machine<'gc>>(
m: &mut M,
ctx: &mut impl VmRuntimeCtx,
+3 -3
View File
@@ -88,7 +88,8 @@ pub fn eq_force<'gc, M: Machine<'gc>>(
}
fn finalize<'gc, M: Machine<'gc>>(m: &mut M, reader: &mut BytecodeReader<'_>) -> Step {
m.drop_n(2);
let _ = m.pop();
let _ = m.pop();
let result = m
.pop()
.downcast::<bool>()
@@ -166,7 +167,6 @@ fn enter_eq_machine<'gc, M: Machine<'gc>>(
pc: resume_pc,
thunk: None,
env: m.env(),
depth: None,
});
m.inc_call_depth();
m.push(Value::new(negate));
@@ -189,7 +189,7 @@ fn shallow_eq<'gc>(
lhs: StrictValue<'gc>,
rhs: StrictValue<'gc>,
) -> ShallowEq<'gc> {
if let (Some(a), Some(b)) = (lhs.downcast_num(), rhs.downcast_num()) {
if let (Some(a), Some(b)) = (lhs.as_num(), rhs.as_num()) {
let eq = match (a, b) {
(NixNum::Int(a), NixNum::Int(b)) => a == b,
(NixNum::Float(a), NixNum::Float(b)) => a == b,
+2 -11
View File
@@ -46,7 +46,6 @@ pub fn import<'gc, M: Machine<'gc>>(
pc: Continuation::PImportFinalize.ip() as usize,
thunk: None,
env,
depth: None,
});
m.set_pending_load(PendingLoad {
@@ -56,10 +55,6 @@ pub fn import<'gc, M: Machine<'gc>>(
Step::Break(Break::LoadFile)
}
#[expect(
clippy::unreachable,
reason = "import always pushes the PImportFinalize call frame before this runs, so pop_call_frame is always Some"
)]
pub fn import_finalize<'gc, M: Machine<'gc>>(
m: &mut M,
ctx: &mut impl VmRuntimeCtx,
@@ -67,10 +62,8 @@ pub fn import_finalize<'gc, M: Machine<'gc>>(
) -> Step {
// stack: [path_sid, return_value]
let val = m.pop();
let path_sid = m
.pop()
.downcast::<StringId>()
.expect("stack slot must be a string");
#[allow(clippy::unwrap_used)]
let path_sid = m.pop().downcast::<StringId>().unwrap();
// The cache key is keyed by the absolute path string we interned in
// `import`. Resolve it back to the host PathBuf.
let path_str = ctx.resolve_string(path_sid).to_owned();
@@ -80,7 +73,6 @@ pub fn import_finalize<'gc, M: Machine<'gc>>(
pc: ret_pc,
thunk: _,
env,
depth: None,
}) = m.pop_call_frame()
else {
unreachable!()
@@ -122,7 +114,6 @@ pub fn scoped_import<'gc, M: Machine<'gc>>(
pc: Continuation::PScopedImportFinalize.ip() as usize,
thunk: None,
env,
depth: None,
});
m.set_pending_load(PendingLoad {
+271 -99
View File
@@ -1,116 +1,288 @@
use fix_error::Result;
use fix_macros::handler;
use fix_runtime::{List, Slot, StrictValue, Value};
use fix_bytecode::Continuation;
use fix_runtime::{BytecodeReader, List, Machine, MachineExt, NixType, Step, StrictValue, Value};
use gc_arena::Mutation;
use crate::primops::stubs::*;
#[handler(name = PFilter)]
fn filter<'gc>(
pub fn filter_force_list<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
pred: Slot<Value<'gc>>,
list: Slot<Value<'gc>>,
) -> Result<Value<'gc>> {
let list: Slot<List<'gc>> = force(list).await?;
if list.get().inner.borrow().is_empty() {
return Ok(Value::new(list.get()));
}
let idx: Slot<i32> = spill(0i32);
let acc: Slot<List<'gc>> = spill(List::new_gc(mc));
loop {
#[expect(
clippy::indexing_slicing,
reason = "idx is a non-negative loop counter in 0..list.len(), so it indexes the list in bounds"
)]
let keep: bool = call(&pred, list.get().inner.borrow()[idx.get() as usize]).await?;
if keep {
#[expect(
clippy::indexing_slicing,
reason = "idx is a non-negative loop counter in 0..list.len(), so it indexes the list in bounds"
)]
let elem = list.get().inner.borrow()[idx.get() as usize];
acc.get().unlock(mc).borrow_mut().push(elem);
}
if idx.get() as usize == list.get().inner.borrow().len() - 1 {
return Ok(Value::new(acc.get()));
}
idx.set(idx.get() + 1);
) -> Step {
m.force_slot(0, reader, mc)?;
let list = match m.peek_forced(0).expect::<List>() {
Ok(list) => list,
Err(got) => return m.finish_type_err(NixType::List, got),
};
if list.inner.borrow().is_empty() {
let val = m.pop();
let _pred = m.pop();
return m.return_from_primop(val, reader);
}
// prepare stack layout: [ pred list idx acc ]
m.push(Value::new(0));
m.push(Value::new(List::new_gc(mc)));
reader.set_pc(Continuation::PFilterCallPred.ip() as usize);
Step::Continue(())
}
#[handler(name = PAll)]
fn all<'gc>(
pub fn filter_call_pred<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
pred: Slot<Value<'gc>>,
list: Slot<Value<'gc>>,
) -> Result<Value<'gc>> {
let list: Slot<List<'gc>> = force(list).await?;
if list.get().inner.borrow().is_empty() {
return Ok(Value::new(true));
}
let idx: Slot<i32> = spill(0i32);
loop {
#[expect(
clippy::indexing_slicing,
reason = "idx is a non-negative loop counter in 0..list.len(), so it indexes the list in bounds"
)]
let keep: bool = call(&pred, list.get().inner.borrow()[idx.get() as usize]).await?;
if !keep || idx.get() as usize + 1 == list.get().inner.borrow().len() {
return Ok(Value::new(keep));
}
idx.set(idx.get() + 1);
}
) -> Step {
m.force_slot(3, reader, mc)?;
let pred = m.peek_forced(3);
#[allow(clippy::unwrap_used)]
let idx = m.peek(1).downcast::<i32>().unwrap();
#[allow(clippy::unwrap_used)]
let elem = m.peek_forced(2).downcast::<List>().unwrap().inner.borrow()[idx as usize];
m.push(pred.relax());
m.call(reader, mc, elem, Continuation::PFilterCheck.ip() as usize)
}
#[handler(name = PAny)]
fn any<'gc>(
pub fn filter_check<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
pred: Slot<Value<'gc>>,
list: Slot<Value<'gc>>,
) -> Result<Value<'gc>> {
let list: Slot<List<'gc>> = force(list).await?;
if list.get().inner.borrow().is_empty() {
return Ok(Value::new(false));
) -> Step {
let ret = m.force_and_retry::<bool>(reader, mc)?;
#[allow(clippy::unwrap_used)]
let idx = m.peek(1).downcast::<i32>().unwrap();
#[allow(clippy::unwrap_used)]
let list = m.peek_forced(2).downcast::<List>().unwrap();
let list = list.inner.borrow();
#[allow(clippy::unwrap_used)]
let acc = m.peek_forced(0).downcast::<List>().unwrap();
if ret {
let mut acc = acc.unlock(mc).borrow_mut();
acc.push(list[idx as usize]);
}
let idx: Slot<i32> = spill(0i32);
loop {
#[expect(
clippy::indexing_slicing,
reason = "idx is a non-negative loop counter in 0..list.len(), so it indexes the list in bounds"
)]
let keep: bool = call(&pred, list.get().inner.borrow()[idx.get() as usize]).await?;
if keep || idx.get() as usize + 1 == list.get().inner.borrow().len() {
return Ok(Value::new(keep));
}
idx.set(idx.get() + 1);
if idx as usize == list.len() - 1 {
let acc = m.pop();
let _ = m.pop(); // idx
let _ = m.pop(); // list
let _ = m.pop(); // pred
return m.return_from_primop(acc, reader);
}
m.replace(1, Value::new(idx + 1));
reader.set_pc(Continuation::PFilterCallPred.ip() as usize);
Step::Continue(())
}
#[handler(name = PFoldlStrict)]
fn foldl_strict<'gc>(
// foldl' op nul list
//
// Stack layouts across phases:
// Entry: [op, nul, list]
// Empty: [op, nul]
// Call1: [op, list, idx, acc]
// Call2: [op, list, idx, acc, intermediate]
// Update: [op, list, idx, acc, result]
pub fn foldl_strict_entry<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
op: Slot<Value<'gc>>,
nul: Slot<Value<'gc>>,
list: Slot<Value<'gc>>,
) -> Result<Value<'gc>> {
let list: Slot<List<'gc>> = force(list).await?;
if list.get().inner.borrow().is_empty() {
return Ok(nul.get());
}
let idx: Slot<i32> = spill(0i32);
let acc = spill(nul.get());
loop {
let f = call(&op, acc.get()).await?;
#[expect(
clippy::indexing_slicing,
reason = "idx is a non-negative loop counter in 0..list.len(), so it indexes the list in bounds"
)]
let new_acc: StrictValue<'gc> =
call(&f, list.get().inner.borrow()[idx.get() as usize]).await?;
acc.set(new_acc.relax());
if idx.get() as usize + 1 == list.get().inner.borrow().len() {
return Ok(acc.get());
}
idx.set(idx.get() + 1);
) -> Step {
m.force_slot(0, reader, mc)?;
let list_val = m.peek_forced(0);
let Some(list) = list_val.downcast::<List>() else {
return m.finish_type_err(NixType::List, list_val.ty());
};
if list.inner.borrow().is_empty() {
let _ = m.pop(); // list
reader.set_pc(Continuation::PFoldlStrictEmpty.ip() as usize);
return Step::Continue(());
}
let list_val = m.pop();
let nul_val = m.pop();
m.push(list_val);
m.push(Value::new(0i32));
m.push(nul_val);
reader.set_pc(Continuation::PFoldlStrictCall1.ip() as usize);
Step::Continue(())
}
pub fn foldl_strict_empty<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> Step {
let nul = m.force_and_retry::<StrictValue>(reader, mc)?;
let _ = m.pop(); // op
m.return_from_primop(nul.relax(), reader)
}
pub fn foldl_strict_call1<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> Step {
m.force_slot(3, reader, mc)?;
let op = m.peek_forced(3);
let acc = m.peek(0);
m.push(op.relax());
m.call(
reader,
mc,
acc,
Continuation::PFoldlStrictCall2.ip() as usize,
)
}
pub fn foldl_strict_call2<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> Step {
#[allow(clippy::unwrap_used)]
let idx = m.peek(2).downcast::<i32>().unwrap();
#[allow(clippy::unwrap_used)]
let list = m.peek_forced(3).downcast::<List>().unwrap();
let elem = list.inner.borrow()[idx as usize];
m.call(
reader,
mc,
elem,
Continuation::PFoldlStrictUpdate.ip() as usize,
)
}
pub fn foldl_strict_update<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
_mc: &Mutation<'gc>,
) -> Step {
let result = m.pop();
m.replace(0, result);
#[allow(clippy::unwrap_used)]
let idx = m.peek(1).downcast::<i32>().unwrap();
#[allow(clippy::unwrap_used)]
let list = m.peek_forced(2).downcast::<List>().unwrap();
let len = list.inner.borrow().len();
if (idx as usize) + 1 == len {
let acc = m.pop();
let _ = m.pop(); // idx
let _ = m.pop(); // list
let _ = m.pop(); // op
return m.return_from_primop(acc, reader);
}
m.replace(1, Value::new(idx + 1));
reader.set_pc(Continuation::PFoldlStrictCall1.ip() as usize);
Step::Continue(())
}
pub fn all_entry<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> Step {
m.force_slot(0, reader, mc)?;
let list = match m.peek_forced(0).expect::<List>() {
Ok(list) => list,
Err(got) => return m.finish_type_err(NixType::List, got),
};
// FIXME: force callable
m.force_slot(1, reader, mc)?;
if list.inner.borrow().is_empty() {
let _list = m.pop();
let _pred = m.pop();
return m.return_from_primop(Value::new(true), reader);
}
// prepare stack layout: [ pred list idx ]
m.push(Value::new(0));
reader.set_pc(Continuation::PAllCallPred.ip() as usize);
Step::Continue(())
}
pub fn all_call_pred<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> Step {
let pred = m.peek_forced(2);
#[allow(clippy::unwrap_used)]
let idx = m.peek(0).downcast::<i32>().unwrap();
#[allow(clippy::unwrap_used)]
let elem = m.peek_forced(1).downcast::<List>().unwrap().inner.borrow()[idx as usize];
m.push(pred.relax());
m.call(reader, mc, elem, Continuation::PAllCheck.ip() as usize)
}
pub fn all_check<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> Step {
let ret = m.force_and_retry::<bool>(reader, mc)?;
#[allow(clippy::unwrap_used)]
let idx = m.peek(0).downcast::<i32>().unwrap();
#[allow(clippy::unwrap_used)]
let list = m.peek_forced(1).downcast::<List>().unwrap();
let list = list.inner.borrow();
if idx as usize == list.len() - 1 || !ret {
let _ = m.pop(); // idx
let _ = m.pop(); // list
let _ = m.pop(); // pred
return m.return_from_primop(Value::new(ret), reader);
}
m.replace(0, Value::new(idx + 1));
reader.set_pc(Continuation::PAllCallPred.ip() as usize);
Step::Continue(())
}
pub fn any_entry<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> Step {
m.force_slot(0, reader, mc)?;
let list = match m.peek_forced(0).expect::<List>() {
Ok(list) => list,
Err(got) => return m.finish_type_err(NixType::List, got),
};
// FIXME: force callable
m.force_slot(1, reader, mc)?;
if list.inner.borrow().is_empty() {
let _list = m.pop();
let _pred = m.pop();
return m.return_from_primop(Value::new(false), reader);
}
// prepare stack layout: [ pred list idx ]
m.push(Value::new(0));
reader.set_pc(Continuation::PAnyCallPred.ip() as usize);
Step::Continue(())
}
pub fn any_call_pred<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> Step {
let pred = m.peek_forced(2);
#[allow(clippy::unwrap_used)]
let idx = m.peek(0).downcast::<i32>().unwrap();
#[allow(clippy::unwrap_used)]
let elem = m.peek_forced(1).downcast::<List>().unwrap().inner.borrow()[idx as usize];
m.push(pred.relax());
m.call(reader, mc, elem, Continuation::PAnyCheck.ip() as usize)
}
pub fn any_check<'gc, M: Machine<'gc>>(
m: &mut M,
reader: &mut BytecodeReader<'_>,
mc: &Mutation<'gc>,
) -> Step {
let ret = m.force_and_retry::<bool>(reader, mc)?;
#[allow(clippy::unwrap_used)]
let idx = m.peek(0).downcast::<i32>().unwrap();
#[allow(clippy::unwrap_used)]
let list = m.peek_forced(1).downcast::<List>().unwrap();
let list = list.inner.borrow();
if idx as usize == list.len() - 1 || ret {
let _ = m.pop(); // idx
let _ = m.pop(); // list
let _ = m.pop(); // pred
return m.return_from_primop(Value::new(ret), reader);
}
m.replace(0, Value::new(idx + 1));
reader.set_pc(Continuation::PAnyCallPred.ip() as usize);
Step::Continue(())
}
+21 -11
View File
@@ -5,7 +5,6 @@ mod eq;
mod io;
mod list;
mod path;
mod stubs;
pub use context::*;
pub use control::*;
@@ -19,6 +18,7 @@ pub use io::*;
pub use list::*;
pub use path::*;
#[allow(clippy::too_many_lines)]
pub fn dispatch_cont<'gc, M: Machine<'gc>>(
m: &mut M,
ctx: &mut impl VmRuntimeCtx,
@@ -33,18 +33,28 @@ pub fn dispatch_cont<'gc, M: Machine<'gc>>(
match cont {
PAbort => abort(m, ctx, reader, mc),
PAll0 | PAll1 | PAll2 | PAll3 => all(m, reader, mc, cont),
PAny0 | PAny1 | PAny2 | PAny3 => any(m, reader, mc, cont),
PDeepSeq0 | PDeepSeq1 | PDeepSeq2 | PDeepSeq3 | PDeepSeq4 | PDeepSeq5 => {
deep_seq(m, reader, mc, cont)
}
PSeq0 | PSeq1 => seq(m, reader, mc, cont),
PAll => all_entry(m, reader, mc),
PAllCallPred => all_call_pred(m, reader, mc),
PAllCheck => all_check(m, reader, mc),
PFilter0 | PFilter1 | PFilter2 | PFilter3 | PFilter4 => filter(m, reader, mc, cont),
PAny => any_entry(m, reader, mc),
PAnyCallPred => any_call_pred(m, reader, mc),
PAnyCheck => any_check(m, reader, mc),
PFoldlStrict0 | PFoldlStrict1 | PFoldlStrict2 | PFoldlStrict3 | PFoldlStrict4 | PFoldlStrict5 => {
foldl_strict(m, reader, mc, cont)
}
PDeepSeq => deep_seq_force_top(m, reader, mc),
PDeepSeqPush => deep_seq_push(m, reader, mc),
PDeepSeqLoop => deep_seq_loop(m, reader, mc),
PSeq => seq(m, reader, mc),
PFilterForceList => filter_force_list(m, reader, mc),
PFilterCallPred => filter_call_pred(m, reader, mc),
PFilterCheck => filter_check(m, reader, mc),
PFoldlStrict => foldl_strict_entry(m, reader, mc),
PFoldlStrictEmpty => foldl_strict_empty(m, reader, mc),
PFoldlStrictCall1 => foldl_strict_call1(m, reader, mc),
PFoldlStrictCall2 => foldl_strict_call2(m, reader, mc),
PFoldlStrictUpdate => foldl_strict_update(m, reader, mc),
ForceResultShallow => force_result_shallow(m, ctx, reader, mc),
ForceResultShallowPush => force_result_shallow_push(m, ctx, reader, mc),
-9
View File
@@ -1,9 +0,0 @@
//! Fallback definitions for the `#[primop]` surface syntax.
//!
//! `force`, `call`, and `spill` are recognized and rewritten by the
//! `#[primop]` proc macro, so compiled code never calls them. They exist only
//! so the un-expanded source name-resolves in tooling that does not run the
//! macro (e.g. rust-analyzer while the macro crate is being rebuilt). Calling
//! one for real is impossible: they never return.
pub use crate::__macro_support::{call, force, spill};
-4
View File
@@ -48,9 +48,5 @@ fix-vm = { path = "../fix-vm" }
[dev-dependencies]
criterion = { version = "0.8", features = ["html_reports"] }
serial_test = "4.0"
tempfile = "3.24"
test-log = { version = "0.2", features = ["trace"] }
[lints]
workspace = true
+1 -2
View File
@@ -1,5 +1,4 @@
#![allow(clippy::allow_attributes_without_reason)]
#![allow(dead_code, clippy::unwrap_used, clippy::unwrap_in_result)]
#![allow(dead_code)]
use fix::Evaluator;
use fix_error::{Result, Source};
+11 -7
View File
@@ -1,3 +1,6 @@
#![warn(clippy::unwrap_used)]
#![allow(dead_code)]
use fix_bytecode::InstructionPtr;
use fix_bytecode::disassembler::{Disassembler, DisassemblerContext};
use fix_compiler::{CodeState, ExtraScope};
@@ -8,6 +11,7 @@ use fix_vm::Vm;
use hashbrown::{HashMap, HashSet};
use string_interner::{DefaultStringInterner, Symbol as _};
mod derivation;
pub mod logging;
#[global_allocator]
@@ -97,12 +101,12 @@ impl VmRuntimeCtx for RuntimeState {
StringId(self.strings.get_or_intern(s))
}
fn resolve_string(&self, id: StringId) -> &str {
self.strings
.resolve(id.0)
.expect("interned string id must resolve")
#[allow(clippy::unwrap_used)]
self.strings.resolve(id.0).unwrap()
}
fn get_const(&self, id: u32) -> StaticValue {
self.constants.get(id).expect("const id must be valid")
#[allow(clippy::unwrap_used)]
self.constants.get(id).unwrap()
}
fn add_const(&mut self, val: StaticValue) -> u32 {
self.constants.insert(val)
@@ -141,9 +145,9 @@ impl DisassemblerContext for Evaluator {
&self.code.bytecode
}
#[allow(clippy::unwrap_used)]
fn resolve_string(&self, id: u32) -> &str {
let id = string_interner::symbol::SymbolU32::try_from_usize(id as usize)
.expect("invalid string id");
self.runtime.strings.resolve(id).expect("invalid string id")
let id = string_interner::symbol::SymbolU32::try_from_usize(id as usize).unwrap();
self.runtime.strings.resolve(id).unwrap()
}
}
+4 -3
View File
@@ -5,7 +5,7 @@ use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{EnvFilter, Layer, fmt};
pub fn init_logging() -> Result<(), miette::InstallError> {
pub fn init_logging() {
let is_terminal = std::io::stderr().is_terminal();
let show_time = env::var("NIX_JS_LOG_TIME")
.map(|v| v == "1" || v.to_lowercase() == "true")
@@ -32,10 +32,10 @@ pub fn init_logging() -> Result<(), miette::InstallError> {
.with(fmt_layer)
.init();
init_miette_handler()
init_miette_handler();
}
fn init_miette_handler() -> Result<(), miette::InstallError> {
fn init_miette_handler() {
let is_terminal = std::io::stderr().is_terminal();
miette::set_hook(Box::new(move |_| {
Box::new(
@@ -46,4 +46,5 @@ fn init_miette_handler() -> Result<(), miette::InstallError> {
.build(),
)
}))
.ok();
}
+19 -34
View File
@@ -20,49 +20,33 @@ struct Cli {
enum Command {
Compile {
#[clap(flatten)]
source: ExprSourceArgs,
source: ExprSource,
#[arg(long)]
silent: bool,
},
Eval {
#[clap(flatten)]
source: ExprSourceArgs,
source: ExprSource,
},
Repl,
}
#[derive(Args)]
#[group(required = true, multiple = false)]
struct ExprSourceArgs {
struct ExprSource {
#[clap(short, long)]
expr: Option<String>,
#[clap(short, long)]
file: Option<PathBuf>,
}
enum ExprSource {
Expr(String),
File(PathBuf),
}
#[expect(
clippy::unreachable,
reason = "clap's arg group guarantees exactly one of --expr/--file is set"
)]
impl From<ExprSourceArgs> for ExprSource {
fn from(args: ExprSourceArgs) -> Self {
match (args.expr, args.file) {
(Some(expr), None) => ExprSource::Expr(expr),
(None, Some(file)) => ExprSource::File(file),
_ => unreachable!(),
}
}
}
fn run_compile(eval: &mut Evaluator, src: ExprSource, silent: bool) -> Result<()> {
let src = match src {
ExprSource::Expr(expr) => Source::new_eval(expr)?,
ExprSource::File(file) => Source::new_file(file)?,
let src = if let Some(expr) = src.expr {
Source::new_eval(expr)?
} else if let Some(file) = src.file {
Source::new_file(file)?
} else {
unreachable!()
};
match eval.compile_bytecode(src) {
Ok(ip) => {
@@ -79,9 +63,12 @@ fn run_compile(eval: &mut Evaluator, src: ExprSource, silent: bool) -> Result<()
}
fn run_eval(eval: &mut Evaluator, src: ExprSource) -> Result<()> {
let src = match src {
ExprSource::Expr(expr) => Source::new_eval(expr)?,
ExprSource::File(file) => Source::new_file(file)?,
let src = if let Some(expr) = src.expr {
Source::new_eval(expr)?
} else if let Some(file) = src.file {
Source::new_file(file)?
} else {
unreachable!()
};
match eval.eval_deep(src) {
Ok(value) => {
@@ -106,9 +93,7 @@ fn run_repl(eval: &mut Evaluator) -> Result<()> {
if line.trim().is_empty() {
continue;
}
if let Err(err) = rl.add_history_entry(line.as_str()) {
eprintln!("[WARN] Failed to add history entry: {err}");
}
let _ = rl.add_history_entry(line.as_str());
if let Some([Some(_), Some(ident), Some(rest)]) = RE.exec(&line) {
if let Some(expr) = rest.strip_prefix('=') {
let expr = expr.trim_start();
@@ -152,15 +137,15 @@ fn run_repl(eval: &mut Evaluator) -> Result<()> {
}
fn main() -> Result<()> {
fix::logging::init_logging()?;
fix::logging::init_logging();
let cli = Cli::parse();
let mut eval = Evaluator::new();
match cli.command {
Command::Compile { source, silent } => run_compile(&mut eval, source.into(), silent),
Command::Eval { source } => run_eval(&mut eval, source.into()),
Command::Compile { source, silent } => run_compile(&mut eval, source, silent),
Command::Eval { source } => run_eval(&mut eval, source),
Command::Repl => run_repl(&mut eval),
}
}
+6 -4
View File
@@ -402,15 +402,17 @@ fn fixed_output_sha256_flat() {
#[test_log::test]
fn fixed_output_missing_hashalgo() {
eval_deep_result(
r#"derivation {
assert!(
eval_deep_result(
r#"derivation {
name = "default";
builder = "/bin/sh";
system = "x86_64-linux";
outputHash = "0000000000000000000000000000000000000000000000000000000000000000";
}"#,
)
.unwrap_err();
)
.is_err()
);
}
#[test_log::test]
+1 -1
View File
@@ -350,7 +350,7 @@ fn read_dir_nonexistent_fails() {
let expr = r#"builtins.readDir "/nonexistent/directory""#;
let result = eval_result(expr);
result.unwrap_err();
assert!(result.is_err());
}
#[test_log::test]
+7 -18
View File
@@ -5,7 +5,6 @@ use std::path::PathBuf;
use fix::Evaluator;
use fix_error::{Source, SourceType};
use fix_lang::Value;
use serial_test::serial;
fn get_lang_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/tests/lang")
@@ -161,14 +160,9 @@ mod okay {
eval_okay_test!(getattrpos);
eval_okay_test!(getattrpos_functionargs);
eval_okay_test!(getattrpos_undefined);
eval_okay_test!(
#[serial(env)]
getenv,
|| {
// SAFETY: guarded with #[serial_test::serial]
unsafe { std::env::set_var("TEST_VAR", "foo") };
}
);
eval_okay_test!(getenv, || {
unsafe { std::env::set_var("TEST_VAR", "foo") };
});
eval_okay_test!(groupBy);
eval_okay_test!(r#if);
eval_okay_test!(ind_string);
@@ -200,16 +194,11 @@ mod okay {
eval_okay_test!(partition);
eval_okay_test!(path);
eval_okay_test!(pathexists);
eval_okay_test!(
#[serial(env)]
path_string_interpolation,
|| {
// SAFETY: guarded with #[serial_test::serial]
unsafe {
std::env::set_var("HOME", "/fake-home");
}
eval_okay_test!(path_string_interpolation, || {
unsafe {
std::env::set_var("HOME", "/fake-home");
}
);
});
eval_okay_test!(patterns);
eval_okay_test!(print);
eval_okay_test!(readDir);
-8
View File
@@ -1,11 +1,3 @@
#![allow(clippy::allow_attributes_without_reason)]
#![allow(
dead_code,
clippy::unwrap_used,
clippy::unwrap_in_result,
clippy::panic
)]
mod derivation;
mod findfile;
mod io_operations;
+8 -8
View File
@@ -348,7 +348,7 @@ fn substring_zero_length_empty_value() {
}
#[test_log::test]
#[expect(non_snake_case)]
#[allow(non_snake_case)]
fn concatStringsSep_preserves_context() {
let result = eval(
r#"
@@ -365,7 +365,7 @@ fn concatStringsSep_preserves_context() {
}
#[test_log::test]
#[expect(non_snake_case)]
#[allow(non_snake_case)]
fn concatStringsSep_merges_contexts() {
let result = eval(
r#"
@@ -383,7 +383,7 @@ fn concatStringsSep_merges_contexts() {
}
#[test_log::test]
#[expect(non_snake_case)]
#[allow(non_snake_case)]
fn concatStringsSep_separator_has_context() {
let result = eval(
r#"
@@ -398,7 +398,7 @@ fn concatStringsSep_separator_has_context() {
}
#[test_log::test]
#[expect(non_snake_case)]
#[allow(non_snake_case)]
fn replaceStrings_input_context_preserved() {
let result = eval(
r#"
@@ -413,7 +413,7 @@ fn replaceStrings_input_context_preserved() {
}
#[test_log::test]
#[expect(non_snake_case)]
#[allow(non_snake_case)]
fn replaceStrings_replacement_context_collected() {
let result = eval(
r#"
@@ -428,7 +428,7 @@ fn replaceStrings_replacement_context_collected() {
}
#[test_log::test]
#[expect(non_snake_case)]
#[allow(non_snake_case)]
fn replaceStrings_merges_contexts() {
let result = eval(
r#"
@@ -446,7 +446,7 @@ fn replaceStrings_merges_contexts() {
}
#[test_log::test]
#[expect(non_snake_case)]
#[allow(non_snake_case)]
fn replaceStrings_lazy_evaluation_context() {
let result = eval(
r#"
@@ -461,7 +461,7 @@ fn replaceStrings_lazy_evaluation_context() {
}
#[test_log::test]
#[expect(non_snake_case)]
#[allow(non_snake_case)]
fn baseNameOf_preserves_context() {
let result = eval(
r#"
+2
View File
@@ -1,3 +1,5 @@
#![allow(dead_code)]
use fix::Evaluator;
use fix_error::{Result, Source};
use fix_lang::Value;
Generated
+150 -9
View File
@@ -1,5 +1,63 @@
{
"nodes": {
"blueprint": {
"inputs": {
"nixpkgs": [
"llm-agents",
"nixpkgs"
],
"systems": [
"llm-agents",
"systems"
]
},
"locked": {
"lastModified": 1776249299,
"narHash": "sha256-Dt9t1TGRmJFc0xVYhttNBD6QsAgHOHCArqGa0AyjrJY=",
"owner": "numtide",
"repo": "blueprint",
"rev": "56131e8628f173d24a27f6d27c0215eff57e40dd",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "blueprint",
"type": "github"
}
},
"bun2nix": {
"inputs": {
"flake-parts": [
"llm-agents",
"flake-parts"
],
"nixpkgs": [
"llm-agents",
"nixpkgs"
],
"systems": [
"llm-agents",
"systems"
],
"treefmt-nix": [
"llm-agents",
"treefmt-nix"
]
},
"locked": {
"lastModified": 1778446047,
"narHash": "sha256-oQvcadh2BCkrog+SGrG6YffKJrveYpjj3TdQJWaKhaM=",
"owner": "nix-community",
"repo": "bun2nix",
"rev": "f2bc12af1a6369648aac41041ceeaa0b866599c6",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "bun2nix",
"type": "github"
}
},
"fenix": {
"inputs": {
"nixpkgs": [
@@ -8,11 +66,11 @@
"rust-analyzer-src": "rust-analyzer-src"
},
"locked": {
"lastModified": 1784017020,
"narHash": "sha256-49WO85egjNtN1vMgJ3zUjDh5IqO+ou4zZY80WQ6EKGg=",
"lastModified": 1781343250,
"narHash": "sha256-KBJktAwDG9+10j2wMfvOVkBEhZr3yS769xoqqdFI62s=",
"owner": "nix-community",
"repo": "fenix",
"rev": "fa2a0be0f712d7147d1677d33d15ea7b0589cdb4",
"rev": "aad7d8bb6936d473c2b9d1a5846a1fe1bc92767a",
"type": "github"
},
"original": {
@@ -35,13 +93,59 @@
"url": "https://git.lix.systems/lix-project/flake-compat/archive/main.tar.gz"
}
},
"flake-parts": {
"inputs": {
"nixpkgs-lib": [
"llm-agents",
"nixpkgs"
]
},
"locked": {
"lastModified": 1778716662,
"narHash": "sha256-m1Yf0wZ8j1OHjTc2UwHwyQRSnNeSgLJOd7q5Y45hzi4=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "f7c1a2d347e4c52d5fb8d10cb4d94b5884e546fb",
"type": "github"
},
"original": {
"owner": "hercules-ci",
"repo": "flake-parts",
"type": "github"
}
},
"llm-agents": {
"inputs": {
"blueprint": "blueprint",
"bun2nix": "bun2nix",
"flake-parts": "flake-parts",
"nixpkgs": [
"nixpkgs"
],
"systems": "systems",
"treefmt-nix": "treefmt-nix"
},
"locked": {
"lastModified": 1781330261,
"narHash": "sha256-2fFAGel2VVXr5mwrTXldqXva2ng3T3HHxyuBKRIxauI=",
"owner": "numtide",
"repo": "llm-agents.nix",
"rev": "24ec6b7b1ddf8896ac8df3b65dc564575e0a1928",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "llm-agents.nix",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1784007870,
"narHash": "sha256-djcLt/JJphyNt4eDY9XTly+/WbCK5lqWq9lSgCmJkkQ=",
"lastModified": 1781074563,
"narHash": "sha256-md8WlXOlfnIeHeOScMTTHFyf2d6iaTwPl2apR5EQ3P4=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "18b9261cb3294b6d2a06d03f96872827b8fe2698",
"rev": "9ae611a455b90cf061d8f332b977e387bda8e1ca",
"type": "github"
},
"original": {
@@ -55,17 +159,18 @@
"inputs": {
"fenix": "fenix",
"flake-compat": "flake-compat",
"llm-agents": "llm-agents",
"nixpkgs": "nixpkgs"
}
},
"rust-analyzer-src": {
"flake": false,
"locked": {
"lastModified": 1783975201,
"narHash": "sha256-oyHWTfKWk06nTynCO8ByEAx/KEARvOOyTVnwinOmK3Q=",
"lastModified": 1781294997,
"narHash": "sha256-XjCyIvJw4JtcwItTKRdQz5h1pLF9hr8ZSYeMP+/1d3A=",
"owner": "rust-lang",
"repo": "rust-analyzer",
"rev": "63a6f0d4bcfd3bbcf36383fcbcbcd93456ed1653",
"rev": "3f92cd1612268995d5667bd04fa03ba2916413d9",
"type": "github"
},
"original": {
@@ -74,6 +179,42 @@
"repo": "rust-analyzer",
"type": "github"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
},
"treefmt-nix": {
"inputs": {
"nixpkgs": [
"llm-agents",
"nixpkgs"
]
},
"locked": {
"lastModified": 1780220602,
"narHash": "sha256-eynAfOmbmxJnkp7YewvCEbShNnnYJ9gLLqkzsYtBPeM=",
"owner": "numtide",
"repo": "treefmt-nix",
"rev": "db947814a175b7ca6ded66e21383d938df01c227",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "treefmt-nix",
"type": "github"
}
}
},
"root": "root",
+33 -3
View File
@@ -3,13 +3,17 @@
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
fenix.url = "github:nix-community/fenix";
fenix.inputs.nixpkgs.follows = "nixpkgs";
llm-agents = {
url = "github:numtide/llm-agents.nix";
inputs.nixpkgs.follows = "nixpkgs";
};
flake-compat = {
url = "https://git.lix.systems/lix-project/flake-compat/archive/main.tar.gz";
flake = false;
};
};
outputs =
{ nixpkgs, fenix, ... }:
inputs@{ nixpkgs, fenix, ... }:
let
forAllSystems = nixpkgs.lib.genAttrs nixpkgs.lib.systems.flakeExposed;
in
@@ -20,11 +24,37 @@
pkgs = import nixpkgs {
inherit system;
config.allowUnfree = true;
overlays = [ fenix.overlays.default ];
};
llm-agents = inputs.llm-agents.packages.${pkgs.stdenv.hostPlatform.system};
in
{
default = import ./devShell.nix { inherit pkgs; };
default = pkgs.mkShell {
packages = with pkgs; [
(fenix.packages.${system}.latest.withComponents [
"cargo"
"clippy"
"rust-src"
"rustc"
"rustfmt"
"rust-analyzer"
])
cargo-machete
cargo-bloat
lldb
valgrind
kdePackages.kcachegrind
hyperfine
just
samply
tokei
tombi
# llm-agents.codex
llm-agents.claude-code
llm-agents.opencode
# llm-agents.forge
];
};
}
);
};
+16
View File
@@ -0,0 +1,16 @@
let
lockFile = builtins.fromJSON (builtins.readFile ./flake.lock);
flake-compat-node = lockFile.nodes.${lockFile.nodes.root.inputs.flake-compat};
flake-compat = builtins.fetchTarball {
inherit (flake-compat-node.locked) url;
sha256 = flake-compat-node.locked.narHash;
};
flake = (
import flake-compat {
src = ./.;
copySourceTreeToStore = false;
}
);
in
flake.shellNix