Compare commits
20
Commits
new
..
c1c5681d13
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1c5681d13
|
||
|
|
eb59f4fb67
|
||
|
|
2fd034965b
|
||
|
|
b5246c04ae
|
||
|
|
b8e14c62a4
|
||
|
|
2656b0bc11
|
||
|
|
8192e60063
|
||
|
|
0ecf01204e
|
||
|
|
f666bb498f
|
||
|
|
4f7d94f41b
|
||
|
|
a66748e42d
|
||
|
|
f39fc5fc49
|
||
|
|
5dd160cc43
|
||
|
|
0df38f374f
|
||
|
|
0ca5e8af92
|
||
|
|
260bea9ff1
|
||
|
|
c85423ae79
|
||
|
|
bc16596dd3
|
||
|
|
ac76d4a9e4
|
||
|
|
d77dcc8929
|
Generated
+400
-491
File diff suppressed because it is too large
Load Diff
+30
-93
@@ -1,103 +1,40 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = [
|
||||
"fix",
|
||||
"fix-bytecode",
|
||||
"fix-compiler",
|
||||
"fix-error",
|
||||
"fix-lang",
|
||||
"fix-macros",
|
||||
"fix-runtime",
|
||||
"fix-vm",
|
||||
"fix",
|
||||
"fix-builtins",
|
||||
"fix-codegen",
|
||||
"fix-common",
|
||||
"fix-error",
|
||||
"fix-ir",
|
||||
"fix-vm",
|
||||
]
|
||||
|
||||
[workspace.dependencies]
|
||||
bumpalo = {
|
||||
version = "3.20",
|
||||
features = [
|
||||
"allocator-api2",
|
||||
"boxed",
|
||||
"collections",
|
||||
]
|
||||
}
|
||||
ere = "0.2"
|
||||
ghost-cell = "0.2"
|
||||
hashbrown = "0.17"
|
||||
num_enum = "0.7"
|
||||
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"] }
|
||||
|
||||
# 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"
|
||||
[profile.profiling]
|
||||
inherits = "release"
|
||||
debug = true
|
||||
|
||||
[profile.lto]
|
||||
inherits = "release"
|
||||
lto = true
|
||||
|
||||
[profile.profiling]
|
||||
inherits = "release"
|
||||
debug = true
|
||||
[workspace.dependencies]
|
||||
bumpalo = { version = "3.20", features = [
|
||||
"allocator-api2",
|
||||
"boxed",
|
||||
"collections",
|
||||
] }
|
||||
ghost-cell = "0.2"
|
||||
hashbrown = "0.16"
|
||||
num_enum = "0.7.5"
|
||||
smallvec = "1.15"
|
||||
ere = "0.2"
|
||||
string-interner = "0.19"
|
||||
rnix = "0.14"
|
||||
rowan = "0.16"
|
||||
likely_stable = "0.1"
|
||||
|
||||
[workspace.dependencies.gc-arena]
|
||||
git = "https://github.com/kyren/gc-arena"
|
||||
rev = "75671ae03f53718357b741ed4027560f14e90836"
|
||||
features = ["allocator-api2", "hashbrown", "smallvec"]
|
||||
|
||||
@@ -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='':
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "fix-builtins"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
num_enum = { workspace = true }
|
||||
gc-arena = { workspace = true }
|
||||
@@ -0,0 +1,371 @@
|
||||
use gc_arena::Collect;
|
||||
use num_enum::TryFromPrimitive;
|
||||
|
||||
macro_rules! define_builtins {
|
||||
($(($name:literal, $variant:ident, $arity:expr)),* $(,)?) => {
|
||||
/// Builtin function registry.
|
||||
/// Array index IS the PrimOp id. (name, arity) pairs.
|
||||
pub const BUILTINS: &[(&str, u8)] = &[
|
||||
$(($name, $arity),)*
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, Collect)]
|
||||
#[repr(u8)]
|
||||
#[collect(require_static)]
|
||||
pub enum BuiltinId {
|
||||
$($variant,)*
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
define_builtins! {
|
||||
("abort", Abort, 1),
|
||||
("__add", Add, 2),
|
||||
("__addErrorContext", AddErrorContext, 2),
|
||||
("__all", All, 2),
|
||||
("__any", Any, 2),
|
||||
("__appendContext", AppendContext, 2),
|
||||
("__attrNames", AttrNames, 1),
|
||||
("__attrValues", AttrValues, 1),
|
||||
("baseNameOf", BaseNameOf, 1),
|
||||
("__bitAnd", BitAnd, 2),
|
||||
("__bitOr", BitOr, 2),
|
||||
("__bitXor", BitXor, 2),
|
||||
("break", Break, 1),
|
||||
("__catAttrs", CatAttrs, 2),
|
||||
("__ceil", Ceil, 1),
|
||||
("__compareVersions", CompareVersions, 2),
|
||||
("__concatLists", ConcatLists, 1),
|
||||
("__concatMap", ConcatMap, 2),
|
||||
("__concatStringsSep", ConcatStringsSep, 2),
|
||||
("__convertHash", ConvertHash, 1),
|
||||
("__deepSeq", DeepSeq, 2),
|
||||
("derivation", Derivation, 1),
|
||||
("derivationStrict", DerivationStrict, 1),
|
||||
("dirOf", DirOf, 1),
|
||||
("__div", Div, 2),
|
||||
("__elem", Elem, 2),
|
||||
("__elemAt", ElemAt, 2),
|
||||
("fetchGit", FetchGit, 1),
|
||||
("fetchMercurial", FetchMercurial, 1),
|
||||
("fetchTarball", FetchTarball, 1),
|
||||
("fetchTree", FetchTree, 1),
|
||||
("__fetchurl", FetchUrl, 1),
|
||||
("__filter", Filter, 2),
|
||||
("__filterSource", FilterSource, 2),
|
||||
("__findFile", FindFile, 2),
|
||||
("__floor", Floor, 1),
|
||||
("__foldl'", FoldlStrict, 3),
|
||||
("__fromJSON", FromJSON, 1),
|
||||
("fromTOML", FromTOML, 1),
|
||||
("__functionArgs", FunctionArgs, 1),
|
||||
("__genList", GenList, 2),
|
||||
("__genericClosure", GenericClosure, 1),
|
||||
("__getAttr", GetAttr, 2),
|
||||
("__getContext", GetContext, 1),
|
||||
("__getEnv", GetEnv, 1),
|
||||
("__groupBy", GroupBy, 2),
|
||||
("__hasAttr", HasAttr, 2),
|
||||
("__hasContext", HasContext, 1),
|
||||
("__hashFile", HashFile, 2),
|
||||
("__hashString", HashString, 2),
|
||||
("__head", Head, 1),
|
||||
("import", Import, 1),
|
||||
("__intersectAttrs", IntersectAttrs, 2),
|
||||
("__isAttrs", IsAttrs, 1),
|
||||
("__isBool", IsBool, 1),
|
||||
("__isFloat", IsFloat, 1),
|
||||
("__isFunction", IsFunction, 1),
|
||||
("__isInt", IsInt, 1),
|
||||
("__isList", IsList, 1),
|
||||
("isNull", IsNull, 1),
|
||||
("__isPath", IsPath, 1),
|
||||
("__isString", IsString, 1),
|
||||
("__length", Length, 1),
|
||||
("__lessThan", LessThan, 2),
|
||||
("__listToAttrs", ListToAttrs, 1),
|
||||
("map", Map, 2),
|
||||
("__mapAttrs", MapAttrs, 2),
|
||||
("__match", Match, 2),
|
||||
("__mul", Mul, 2),
|
||||
("__parseDrvName", ParseDrvName, 1),
|
||||
("__partition", Partition, 2),
|
||||
("__path", Path, 1),
|
||||
("__pathExists", PathExists, 1),
|
||||
("placeholder", Placeholder, 1),
|
||||
("__readDir", ReadDir, 1),
|
||||
("__readFile", ReadFile, 1),
|
||||
("__readFileType", ReadFileType, 1),
|
||||
("removeAttrs", RemoveAttrs, 2),
|
||||
("__replaceStrings", ReplaceStrings, 3),
|
||||
("scopedImport", ScopedImport, 2),
|
||||
("__seq", Seq, 2),
|
||||
("__sort", Sort, 2),
|
||||
("__split", Split, 2),
|
||||
("__splitVersion", SplitVersion, 1),
|
||||
("__storePath", StorePath, 1),
|
||||
("__stringLength", StringLength, 1),
|
||||
("__sub", Sub, 2),
|
||||
("__substring", Substring, 3),
|
||||
("__tail", Tail, 1),
|
||||
("throw", Throw, 1),
|
||||
("__toFile", ToFile, 2),
|
||||
("__toJSON", ToJSON, 1),
|
||||
("__toPath", ToPath, 1),
|
||||
("toString", ToString, 1),
|
||||
("__toXML", ToXML, 1),
|
||||
("__trace", Trace, 2),
|
||||
("__tryEval", TryEval, 1),
|
||||
("__typeOf", TypeOf, 1),
|
||||
("__unsafeDiscardStringContext", UnsafeDiscardStringContext, 1),
|
||||
("__unsafeGetAttrPos", UnsafeGetAttrPos, 2),
|
||||
("__warn", Warn, 2),
|
||||
("__zipAttrsWith", ZipAttrsWith, 2),
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, TryFromPrimitive)]
|
||||
pub enum PrimOpPhase {
|
||||
Abort,
|
||||
Add,
|
||||
AddErrorContext,
|
||||
All,
|
||||
Any,
|
||||
AppendContext,
|
||||
AttrNames,
|
||||
AttrValues,
|
||||
BaseNameOf,
|
||||
BitAnd,
|
||||
BitOr,
|
||||
BitXor,
|
||||
Break,
|
||||
CatAttrs,
|
||||
Ceil,
|
||||
CompareVersions,
|
||||
ConcatLists,
|
||||
ConcatMap,
|
||||
ConcatStringsSep,
|
||||
ConvertHash,
|
||||
|
||||
DeepSeq,
|
||||
DeepSeqPush,
|
||||
DeepSeqLoop,
|
||||
|
||||
Derivation,
|
||||
DerivationStrict,
|
||||
DirOf,
|
||||
Div,
|
||||
Elem,
|
||||
ElemAt,
|
||||
FetchGit,
|
||||
FetchMercurial,
|
||||
FetchTarball,
|
||||
FetchTree,
|
||||
FetchUrl,
|
||||
|
||||
FilterForceList,
|
||||
FilterCallPred,
|
||||
FilterCheck,
|
||||
|
||||
FilterSource,
|
||||
FindFile,
|
||||
Floor,
|
||||
FoldlStrict,
|
||||
FromJSON,
|
||||
FromTOML,
|
||||
FunctionArgs,
|
||||
GenList,
|
||||
GenericClosure,
|
||||
GetAttr,
|
||||
GetContext,
|
||||
GetEnv,
|
||||
GroupBy,
|
||||
HasAttr,
|
||||
HasContext,
|
||||
HashFile,
|
||||
HashString,
|
||||
Head,
|
||||
Import,
|
||||
IntersectAttrs,
|
||||
IsAttrs,
|
||||
IsBool,
|
||||
IsFloat,
|
||||
IsFunction,
|
||||
IsInt,
|
||||
IsList,
|
||||
IsNull,
|
||||
IsPath,
|
||||
IsString,
|
||||
Length,
|
||||
LessThan,
|
||||
ListToAttrs,
|
||||
Map,
|
||||
MapAttrs,
|
||||
Match,
|
||||
Mul,
|
||||
ParseDrvName,
|
||||
Partition,
|
||||
Path,
|
||||
PathExists,
|
||||
Placeholder,
|
||||
ReadDir,
|
||||
ReadFile,
|
||||
ReadFileType,
|
||||
RemoveAttrs,
|
||||
ReplaceStrings,
|
||||
ScopedImport,
|
||||
Seq,
|
||||
Sort,
|
||||
Split,
|
||||
SplitVersion,
|
||||
StorePath,
|
||||
StringLength,
|
||||
Sub,
|
||||
Substring,
|
||||
Tail,
|
||||
Throw,
|
||||
ToFile,
|
||||
ToJSON,
|
||||
ToPath,
|
||||
ToString,
|
||||
ToXML,
|
||||
Trace,
|
||||
TryEval,
|
||||
TypeOf,
|
||||
UnsafeDiscardStringContext,
|
||||
UnsafeGetAttrPos,
|
||||
Warn,
|
||||
ZipAttrsWith,
|
||||
|
||||
ForceResultShallow,
|
||||
ForceResultShallowPush,
|
||||
ForceResultShallowLoop,
|
||||
ForceResultDeepFinish,
|
||||
|
||||
// TODO: split into separate enums
|
||||
CallPattern,
|
||||
CallFunctor1,
|
||||
CallFunctor2,
|
||||
|
||||
ImportFinalize,
|
||||
ScopedImportFinalize,
|
||||
|
||||
Illegal,
|
||||
}
|
||||
|
||||
impl BuiltinId {
|
||||
#[inline(always)]
|
||||
pub fn entry_phase(self) -> PrimOpPhase {
|
||||
use BuiltinId::*;
|
||||
match self {
|
||||
Abort => PrimOpPhase::Abort,
|
||||
Add => PrimOpPhase::Add,
|
||||
AddErrorContext => PrimOpPhase::AddErrorContext,
|
||||
All => PrimOpPhase::All,
|
||||
Any => PrimOpPhase::Any,
|
||||
AppendContext => PrimOpPhase::AppendContext,
|
||||
AttrNames => PrimOpPhase::AttrNames,
|
||||
AttrValues => PrimOpPhase::AttrValues,
|
||||
BaseNameOf => PrimOpPhase::BaseNameOf,
|
||||
BitAnd => PrimOpPhase::BitAnd,
|
||||
BitOr => PrimOpPhase::BitOr,
|
||||
BitXor => PrimOpPhase::BitXor,
|
||||
Break => PrimOpPhase::Break,
|
||||
CatAttrs => PrimOpPhase::CatAttrs,
|
||||
Ceil => PrimOpPhase::Ceil,
|
||||
CompareVersions => PrimOpPhase::CompareVersions,
|
||||
ConcatLists => PrimOpPhase::ConcatLists,
|
||||
ConcatMap => PrimOpPhase::ConcatMap,
|
||||
ConcatStringsSep => PrimOpPhase::ConcatStringsSep,
|
||||
ConvertHash => PrimOpPhase::ConvertHash,
|
||||
DeepSeq => PrimOpPhase::DeepSeq,
|
||||
Derivation => PrimOpPhase::Derivation,
|
||||
DerivationStrict => PrimOpPhase::DerivationStrict,
|
||||
DirOf => PrimOpPhase::DirOf,
|
||||
Div => PrimOpPhase::Div,
|
||||
Elem => PrimOpPhase::Elem,
|
||||
ElemAt => PrimOpPhase::ElemAt,
|
||||
FetchGit => PrimOpPhase::FetchGit,
|
||||
FetchMercurial => PrimOpPhase::FetchMercurial,
|
||||
FetchTarball => PrimOpPhase::FetchTarball,
|
||||
FetchTree => PrimOpPhase::FetchTree,
|
||||
FetchUrl => PrimOpPhase::FetchUrl,
|
||||
Filter => PrimOpPhase::FilterForceList,
|
||||
FilterSource => PrimOpPhase::FilterSource,
|
||||
FindFile => PrimOpPhase::FindFile,
|
||||
Floor => PrimOpPhase::Floor,
|
||||
FoldlStrict => PrimOpPhase::FoldlStrict,
|
||||
FromJSON => PrimOpPhase::FromJSON,
|
||||
FromTOML => PrimOpPhase::FromTOML,
|
||||
FunctionArgs => PrimOpPhase::FunctionArgs,
|
||||
GenList => PrimOpPhase::GenList,
|
||||
GenericClosure => PrimOpPhase::GenericClosure,
|
||||
GetAttr => PrimOpPhase::GetAttr,
|
||||
GetContext => PrimOpPhase::GetContext,
|
||||
GetEnv => PrimOpPhase::GetEnv,
|
||||
GroupBy => PrimOpPhase::GroupBy,
|
||||
HasAttr => PrimOpPhase::HasAttr,
|
||||
HasContext => PrimOpPhase::HasContext,
|
||||
HashFile => PrimOpPhase::HashFile,
|
||||
HashString => PrimOpPhase::HashString,
|
||||
Head => PrimOpPhase::Head,
|
||||
Import => PrimOpPhase::Import,
|
||||
IntersectAttrs => PrimOpPhase::IntersectAttrs,
|
||||
IsAttrs => PrimOpPhase::IsAttrs,
|
||||
IsBool => PrimOpPhase::IsBool,
|
||||
IsFloat => PrimOpPhase::IsFloat,
|
||||
IsFunction => PrimOpPhase::IsFunction,
|
||||
IsInt => PrimOpPhase::IsInt,
|
||||
IsList => PrimOpPhase::IsList,
|
||||
IsNull => PrimOpPhase::IsNull,
|
||||
IsPath => PrimOpPhase::IsPath,
|
||||
IsString => PrimOpPhase::IsString,
|
||||
Length => PrimOpPhase::Length,
|
||||
LessThan => PrimOpPhase::LessThan,
|
||||
ListToAttrs => PrimOpPhase::ListToAttrs,
|
||||
Map => PrimOpPhase::Map,
|
||||
MapAttrs => PrimOpPhase::MapAttrs,
|
||||
Match => PrimOpPhase::Match,
|
||||
Mul => PrimOpPhase::Mul,
|
||||
ParseDrvName => PrimOpPhase::ParseDrvName,
|
||||
Partition => PrimOpPhase::Partition,
|
||||
Path => PrimOpPhase::Path,
|
||||
PathExists => PrimOpPhase::PathExists,
|
||||
Placeholder => PrimOpPhase::Placeholder,
|
||||
ReadDir => PrimOpPhase::ReadDir,
|
||||
ReadFile => PrimOpPhase::ReadFile,
|
||||
ReadFileType => PrimOpPhase::ReadFileType,
|
||||
RemoveAttrs => PrimOpPhase::RemoveAttrs,
|
||||
ReplaceStrings => PrimOpPhase::ReplaceStrings,
|
||||
ScopedImport => PrimOpPhase::ScopedImport,
|
||||
Seq => PrimOpPhase::Seq,
|
||||
Sort => PrimOpPhase::Sort,
|
||||
Split => PrimOpPhase::Split,
|
||||
SplitVersion => PrimOpPhase::SplitVersion,
|
||||
StorePath => PrimOpPhase::StorePath,
|
||||
StringLength => PrimOpPhase::StringLength,
|
||||
Sub => PrimOpPhase::Sub,
|
||||
Substring => PrimOpPhase::Substring,
|
||||
Tail => PrimOpPhase::Tail,
|
||||
Throw => PrimOpPhase::Throw,
|
||||
ToFile => PrimOpPhase::ToFile,
|
||||
ToJSON => PrimOpPhase::ToJSON,
|
||||
ToPath => PrimOpPhase::ToPath,
|
||||
ToString => PrimOpPhase::ToString,
|
||||
ToXML => PrimOpPhase::ToXML,
|
||||
Trace => PrimOpPhase::Trace,
|
||||
TryEval => PrimOpPhase::TryEval,
|
||||
TypeOf => PrimOpPhase::TypeOf,
|
||||
UnsafeDiscardStringContext => PrimOpPhase::UnsafeDiscardStringContext,
|
||||
UnsafeGetAttrPos => PrimOpPhase::UnsafeGetAttrPos,
|
||||
Warn => PrimOpPhase::Warn,
|
||||
ZipAttrsWith => PrimOpPhase::ZipAttrsWith,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PrimOpPhase {
|
||||
pub fn ip(self) -> u32 {
|
||||
self as u32 * 2
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
[package]
|
||||
name = "fix-bytecode"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
colored = "3.1.1"
|
||||
num_enum = { workspace = true }
|
||||
string-interner = { workspace = true }
|
||||
|
||||
fix-lang = { path = "../fix-lang" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,614 +0,0 @@
|
||||
#![allow(
|
||||
dead_code,
|
||||
reason = "crate is under active development; some opcodes and helpers are not yet wired up"
|
||||
)]
|
||||
|
||||
use fix_lang::{BuiltinId, StringId};
|
||||
use num_enum::TryFromPrimitive;
|
||||
use string_interner::Symbol as _;
|
||||
|
||||
pub mod disassembler;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct InstructionPtr(pub usize);
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Op {
|
||||
PushSmi,
|
||||
PushBigInt,
|
||||
PushFloat,
|
||||
PushString,
|
||||
PushNull,
|
||||
PushTrue,
|
||||
PushFalse,
|
||||
|
||||
LoadLocal,
|
||||
LoadOuter,
|
||||
StoreLocal,
|
||||
AllocLocals,
|
||||
|
||||
MakeThunk,
|
||||
MakeClosure,
|
||||
MakePatternClosure,
|
||||
|
||||
Call,
|
||||
DispatchCont,
|
||||
|
||||
MakeAttrs,
|
||||
MakeEmptyAttrs,
|
||||
SelectStatic,
|
||||
SelectDynamic,
|
||||
HasAttrPathStatic,
|
||||
HasAttrPathDynamic,
|
||||
HasAttrStatic,
|
||||
HasAttrDynamic,
|
||||
HasAttrResolve,
|
||||
JumpIfSelectSucceeded,
|
||||
JumpIfSelectFailed,
|
||||
|
||||
MakeList,
|
||||
MakeEmptyList,
|
||||
|
||||
OpAdd,
|
||||
OpSub,
|
||||
OpMul,
|
||||
OpDiv,
|
||||
OpEq,
|
||||
OpNeq,
|
||||
OpLt,
|
||||
OpGt,
|
||||
OpLeq,
|
||||
OpGeq,
|
||||
OpConcat,
|
||||
OpUpdate,
|
||||
|
||||
OpNeg,
|
||||
OpNot,
|
||||
|
||||
JumpIfFalse,
|
||||
JumpIfTrue,
|
||||
Jump,
|
||||
|
||||
CoerceToString,
|
||||
|
||||
ConcatStrings,
|
||||
ResolvePath,
|
||||
|
||||
Assert,
|
||||
|
||||
LookupWith,
|
||||
|
||||
LoadBuiltins,
|
||||
LoadBuiltin,
|
||||
|
||||
LoadReplBinding,
|
||||
LoadScopedBinding,
|
||||
|
||||
Return,
|
||||
|
||||
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 {
|
||||
Const,
|
||||
BigInt,
|
||||
Local,
|
||||
BuiltinConst,
|
||||
Builtins,
|
||||
ReplBinding,
|
||||
ScopedImportBinding,
|
||||
}
|
||||
|
||||
pub enum Const {
|
||||
Smi(i32),
|
||||
Float(f64),
|
||||
Bool(bool),
|
||||
String(StringId),
|
||||
Path(StringId),
|
||||
PrimOp(BuiltinId),
|
||||
Null,
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Clone, Copy, TryFromPrimitive)]
|
||||
pub enum AttrKeyType {
|
||||
Static,
|
||||
Dynamic,
|
||||
}
|
||||
|
||||
pub enum OperandData {
|
||||
Const(u32),
|
||||
BigInt(i64),
|
||||
Local { layer: u8, idx: u32 },
|
||||
BuiltinConst(StringId),
|
||||
Builtins,
|
||||
ReplBinding(StringId),
|
||||
ScopedImportBinding { slot_id: u32, name: StringId },
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
|
||||
pub enum Continuation {
|
||||
// primops
|
||||
PAbort,
|
||||
PAdd,
|
||||
PAddErrorContext,
|
||||
|
||||
PAll0,
|
||||
PAll1,
|
||||
PAll2,
|
||||
PAll3,
|
||||
|
||||
PAny0,
|
||||
PAny1,
|
||||
PAny2,
|
||||
PAny3,
|
||||
|
||||
PAppendContext,
|
||||
PAppendContextLoop,
|
||||
PAppendContextEntryForced,
|
||||
PAppendContextOutputsForced,
|
||||
PAppendContextOutputElementLoop,
|
||||
PAppendContextOutputElementForced,
|
||||
|
||||
PAttrNames,
|
||||
PAttrValues,
|
||||
PBaseNameOf,
|
||||
PBitAnd,
|
||||
PBitOr,
|
||||
PBitXor,
|
||||
PBreak,
|
||||
PCatAttrs,
|
||||
PCeil,
|
||||
PCompareVersions,
|
||||
PConcatLists,
|
||||
PConcatMap,
|
||||
PConcatStringsSep,
|
||||
PConvertHash,
|
||||
|
||||
PDeepSeq0,
|
||||
PDeepSeq1,
|
||||
PDeepSeq2,
|
||||
PDeepSeq3,
|
||||
PDeepSeq4,
|
||||
PDeepSeq5,
|
||||
|
||||
PDerivation,
|
||||
PDerivationStrict,
|
||||
PDirOf,
|
||||
PDiv,
|
||||
PElem,
|
||||
PElemAt,
|
||||
PFetchGit,
|
||||
PFetchMercurial,
|
||||
PFetchTarball,
|
||||
PFetchTree,
|
||||
PFetchUrl,
|
||||
|
||||
PFilter0,
|
||||
PFilter1,
|
||||
PFilter2,
|
||||
PFilter3,
|
||||
PFilter4,
|
||||
|
||||
PFilterSource,
|
||||
PFindFile,
|
||||
PFloor,
|
||||
PFoldlStrict0,
|
||||
PFoldlStrict1,
|
||||
PFoldlStrict2,
|
||||
PFoldlStrict3,
|
||||
PFoldlStrict4,
|
||||
PFoldlStrict5,
|
||||
PFromJSON,
|
||||
PFromTOML,
|
||||
PFunctionArgs,
|
||||
PGenList,
|
||||
PGenericClosure,
|
||||
PGetAttr,
|
||||
PGetContext,
|
||||
PGetEnv,
|
||||
PGroupBy,
|
||||
PHasAttr,
|
||||
PHasContext,
|
||||
PHashFile,
|
||||
PHashString,
|
||||
PHead,
|
||||
|
||||
PImport,
|
||||
PImportFinalize,
|
||||
PScopedImport,
|
||||
PScopedImportFinalize,
|
||||
|
||||
PIntersectAttrs,
|
||||
PIsAttrs,
|
||||
PIsBool,
|
||||
PIsFloat,
|
||||
PIsFunction,
|
||||
PIsInt,
|
||||
PIsList,
|
||||
PIsNull,
|
||||
PIsPath,
|
||||
PIsString,
|
||||
PLength,
|
||||
PLessThan,
|
||||
PListToAttrs,
|
||||
PMap,
|
||||
PMapAttrs,
|
||||
PMatch,
|
||||
PMul,
|
||||
PParseDrvName,
|
||||
PPartition,
|
||||
PPath,
|
||||
PPathExists,
|
||||
PPlaceholder,
|
||||
PReadDir,
|
||||
PReadFile,
|
||||
PReadFileType,
|
||||
PRemoveAttrs,
|
||||
PReplaceStrings,
|
||||
PSeq0,
|
||||
PSeq1,
|
||||
PSort,
|
||||
PSplit,
|
||||
PSplitVersion,
|
||||
PStorePath,
|
||||
PStringLength,
|
||||
PSub,
|
||||
PSubstring,
|
||||
PTail,
|
||||
PThrow,
|
||||
PToFile,
|
||||
PToJSON,
|
||||
PToPath,
|
||||
PToString,
|
||||
PToXML,
|
||||
PTrace,
|
||||
PTryEval,
|
||||
PTypeOf,
|
||||
PUnsafeDiscardStringContext,
|
||||
PUnsafeGetAttrPos,
|
||||
PWarn,
|
||||
PZipAttrsWith,
|
||||
PUnsafeDiscardOutputDependency,
|
||||
|
||||
ForceResultShallow,
|
||||
ForceResultShallowPush,
|
||||
ForceResultShallowLoop,
|
||||
ForceResultDeepFinish,
|
||||
|
||||
EqStep,
|
||||
EqForce,
|
||||
|
||||
CallPattern,
|
||||
CallFunctor1,
|
||||
CallFunctor2,
|
||||
|
||||
Illegal,
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Continuation {
|
||||
pub const 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,
|
||||
AppendContext => Self::PAppendContext,
|
||||
AttrNames => Self::PAttrNames,
|
||||
AttrValues => Self::PAttrValues,
|
||||
BaseNameOf => Self::PBaseNameOf,
|
||||
BitAnd => Self::PBitAnd,
|
||||
BitOr => Self::PBitOr,
|
||||
BitXor => Self::PBitXor,
|
||||
Break => Self::PBreak,
|
||||
CatAttrs => Self::PCatAttrs,
|
||||
Ceil => Self::PCeil,
|
||||
CompareVersions => Self::PCompareVersions,
|
||||
ConcatLists => Self::PConcatLists,
|
||||
ConcatMap => Self::PConcatMap,
|
||||
ConcatStringsSep => Self::PConcatStringsSep,
|
||||
ConvertHash => Self::PConvertHash,
|
||||
DeepSeq => Self::PDeepSeq0,
|
||||
Derivation => Self::PDerivation,
|
||||
DerivationStrict => Self::PDerivationStrict,
|
||||
DirOf => Self::PDirOf,
|
||||
Div => Self::PDiv,
|
||||
Elem => Self::PElem,
|
||||
ElemAt => Self::PElemAt,
|
||||
FetchGit => Self::PFetchGit,
|
||||
FetchMercurial => Self::PFetchMercurial,
|
||||
FetchTarball => Self::PFetchTarball,
|
||||
FetchTree => Self::PFetchTree,
|
||||
FetchUrl => Self::PFetchUrl,
|
||||
Filter => Self::PFilter0,
|
||||
FilterSource => Self::PFilterSource,
|
||||
FindFile => Self::PFindFile,
|
||||
Floor => Self::PFloor,
|
||||
FoldlStrict => Self::PFoldlStrict0,
|
||||
FromJSON => Self::PFromJSON,
|
||||
FromTOML => Self::PFromTOML,
|
||||
FunctionArgs => Self::PFunctionArgs,
|
||||
GenList => Self::PGenList,
|
||||
GenericClosure => Self::PGenericClosure,
|
||||
GetAttr => Self::PGetAttr,
|
||||
GetContext => Self::PGetContext,
|
||||
GetEnv => Self::PGetEnv,
|
||||
GroupBy => Self::PGroupBy,
|
||||
HasAttr => Self::PHasAttr,
|
||||
HasContext => Self::PHasContext,
|
||||
HashFile => Self::PHashFile,
|
||||
HashString => Self::PHashString,
|
||||
Head => Self::PHead,
|
||||
Import => Self::PImport,
|
||||
IntersectAttrs => Self::PIntersectAttrs,
|
||||
IsAttrs => Self::PIsAttrs,
|
||||
IsBool => Self::PIsBool,
|
||||
IsFloat => Self::PIsFloat,
|
||||
IsFunction => Self::PIsFunction,
|
||||
IsInt => Self::PIsInt,
|
||||
IsList => Self::PIsList,
|
||||
IsNull => Self::PIsNull,
|
||||
IsPath => Self::PIsPath,
|
||||
IsString => Self::PIsString,
|
||||
Length => Self::PLength,
|
||||
LessThan => Self::PLessThan,
|
||||
ListToAttrs => Self::PListToAttrs,
|
||||
Map => Self::PMap,
|
||||
MapAttrs => Self::PMapAttrs,
|
||||
Match => Self::PMatch,
|
||||
Mul => Self::PMul,
|
||||
ParseDrvName => Self::PParseDrvName,
|
||||
Partition => Self::PPartition,
|
||||
Path => Self::PPath,
|
||||
PathExists => Self::PPathExists,
|
||||
Placeholder => Self::PPlaceholder,
|
||||
ReadDir => Self::PReadDir,
|
||||
ReadFile => Self::PReadFile,
|
||||
ReadFileType => Self::PReadFileType,
|
||||
RemoveAttrs => Self::PRemoveAttrs,
|
||||
ReplaceStrings => Self::PReplaceStrings,
|
||||
ScopedImport => Self::PScopedImport,
|
||||
Seq => Self::PSeq0,
|
||||
Sort => Self::PSort,
|
||||
Split => Self::PSplit,
|
||||
SplitVersion => Self::PSplitVersion,
|
||||
StorePath => Self::PStorePath,
|
||||
StringLength => Self::PStringLength,
|
||||
Sub => Self::PSub,
|
||||
Substring => Self::PSubstring,
|
||||
Tail => Self::PTail,
|
||||
Throw => Self::PThrow,
|
||||
ToFile => Self::PToFile,
|
||||
ToJSON => Self::PToJSON,
|
||||
ToPath => Self::PToPath,
|
||||
ToString => Self::PToString,
|
||||
ToXML => Self::PToXML,
|
||||
Trace => Self::PTrace,
|
||||
TryEval => Self::PTryEval,
|
||||
TypeOf => Self::PTypeOf,
|
||||
UnsafeDiscardStringContext => Self::PUnsafeDiscardStringContext,
|
||||
UnsafeDiscardOutputDependency => Self::PUnsafeDiscardOutputDependency,
|
||||
UnsafeGetAttrPos => Self::PUnsafeGetAttrPos,
|
||||
Warn => Self::PWarn,
|
||||
ZipAttrsWith => Self::PZipAttrsWith,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn ip(self) -> u32 {
|
||||
self as u32 * 2
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BytecodeReader<'a> {
|
||||
bytecode: &'a [u8],
|
||||
pc: usize,
|
||||
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,
|
||||
pc,
|
||||
inst_start_pc: pc,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
#[must_use]
|
||||
pub fn from_after_op(bytecode: &'a [u8], inst_start_pc: usize) -> Self {
|
||||
Self {
|
||||
bytecode,
|
||||
pc: inst_start_pc + 1,
|
||||
inst_start_pc,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
#[must_use]
|
||||
pub fn read<T: FromBytecode>(&mut self) -> T {
|
||||
T::read(self)
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
pub fn pc(&self) -> usize {
|
||||
self.pc
|
||||
}
|
||||
|
||||
pub fn set_pc(&mut self, pc: usize) {
|
||||
self.pc = pc;
|
||||
}
|
||||
|
||||
pub fn inst_start_pc(&self) -> usize {
|
||||
self.inst_start_pc
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "fix-codegen"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
hashbrown = { workspace = true }
|
||||
num_enum = { workspace = true }
|
||||
rnix = { workspace = true }
|
||||
string-interner = { workspace = true }
|
||||
colored = "3.1.1"
|
||||
|
||||
fix-builtins = { path = "../fix-builtins" }
|
||||
fix-common = { path = "../fix-common" }
|
||||
fix-ir = { path = "../fix-ir" }
|
||||
@@ -1,8 +1,10 @@
|
||||
use std::fmt::Write;
|
||||
|
||||
use colored::Colorize as _;
|
||||
use colored::Colorize;
|
||||
use fix_builtins::BuiltinId;
|
||||
use num_enum::TryFromPrimitive;
|
||||
|
||||
use crate::{BytecodeReader, Continuation, InstructionPtr, Op};
|
||||
use crate::{InstructionPtr, Op, OperandType};
|
||||
|
||||
pub trait DisassemblerContext {
|
||||
fn resolve_string(&self, id: u32) -> &str;
|
||||
@@ -10,15 +12,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_primitive(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 +116,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 +124,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 +201,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");
|
||||
let op = Op::try_from_primitive(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 +234,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 +274,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 +293,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");
|
||||
("DispatchPrimOp", format!("phase={phase:?}"))
|
||||
Op::DispatchPrimOp => {
|
||||
let id = BuiltinId::try_from_primitive(self.read_u8()).expect("invalid builtin id");
|
||||
("DispatchPrimOp", format!("id={id:?}"))
|
||||
}
|
||||
|
||||
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 +326,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 +359,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 +367,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 +376,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 +400,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 +408,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))
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
use fix_bytecode::{Const, InstructionPtr, Op, OperandType};
|
||||
use fix_lang::StringId;
|
||||
use fix_builtins::{BUILTINS, BuiltinId};
|
||||
use fix_common::StringId;
|
||||
use fix_ir::{Attr, BinOpKind, Ir, MaybeThunk, Param, RawIrRef, ThunkId, UnOpKind};
|
||||
use hashbrown::HashMap;
|
||||
use num_enum::TryFromPrimitive;
|
||||
use rnix::TextRange;
|
||||
use string_interner::Symbol as _;
|
||||
|
||||
mod context;
|
||||
pub mod ir;
|
||||
pub use context::{CodeState, ExtraScope};
|
||||
pub use fix_bytecode::disassembler;
|
||||
pub use ir::{Attr, BinOpKind, Ir, MaybeThunk, Param, RawIrRef, ThunkId, UnOpKind};
|
||||
pub mod disassembler;
|
||||
|
||||
pub struct InstructionPtr(pub usize);
|
||||
|
||||
pub trait BytecodeContext {
|
||||
fn intern_string(&mut self, s: &str) -> StringId;
|
||||
@@ -17,6 +17,86 @@ pub trait BytecodeContext {
|
||||
fn get_code_mut(&mut self) -> &mut Vec<u8>;
|
||||
fn add_constant(&mut self, val: Const) -> u32;
|
||||
fn current_source_dir(&mut self) -> StringId;
|
||||
fn current_scope_slot(&self) -> Option<u32>;
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Clone, Copy, TryFromPrimitive)]
|
||||
#[allow(clippy::enum_variant_names)]
|
||||
pub enum Op {
|
||||
PushSmi,
|
||||
PushBigInt,
|
||||
PushFloat,
|
||||
PushString,
|
||||
PushNull,
|
||||
PushTrue,
|
||||
PushFalse,
|
||||
|
||||
LoadLocal,
|
||||
LoadOuter,
|
||||
StoreLocal,
|
||||
AllocLocals,
|
||||
|
||||
MakeThunk,
|
||||
MakeClosure,
|
||||
MakePatternClosure,
|
||||
|
||||
Call,
|
||||
DispatchPrimOp,
|
||||
|
||||
MakeAttrs,
|
||||
MakeEmptyAttrs,
|
||||
SelectStatic,
|
||||
SelectDynamic,
|
||||
HasAttrPathStatic,
|
||||
HasAttrPathDynamic,
|
||||
HasAttrStatic,
|
||||
HasAttrDynamic,
|
||||
HasAttrResolve,
|
||||
JumpIfSelectSucceeded,
|
||||
JumpIfSelectFailed,
|
||||
|
||||
MakeList,
|
||||
MakeEmptyList,
|
||||
|
||||
OpAdd,
|
||||
OpSub,
|
||||
OpMul,
|
||||
OpDiv,
|
||||
OpEq,
|
||||
OpNeq,
|
||||
OpLt,
|
||||
OpGt,
|
||||
OpLeq,
|
||||
OpGeq,
|
||||
OpConcat,
|
||||
OpUpdate,
|
||||
|
||||
OpNeg,
|
||||
OpNot,
|
||||
|
||||
JumpIfFalse,
|
||||
JumpIfTrue,
|
||||
Jump,
|
||||
|
||||
CoerceToString,
|
||||
|
||||
ConcatStrings,
|
||||
ResolvePath,
|
||||
|
||||
Assert,
|
||||
|
||||
LookupWith,
|
||||
|
||||
LoadBuiltins,
|
||||
LoadBuiltin,
|
||||
|
||||
LoadReplBinding,
|
||||
LoadScopedBinding,
|
||||
|
||||
Return,
|
||||
|
||||
Illegal,
|
||||
}
|
||||
|
||||
struct ScopeInfo {
|
||||
@@ -29,6 +109,39 @@ struct BytecodeEmitter<'a, Ctx: BytecodeContext> {
|
||||
scope_stack: Vec<ScopeInfo>,
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Clone, Copy, TryFromPrimitive)]
|
||||
pub enum OperandType {
|
||||
Const,
|
||||
BigInt,
|
||||
Local,
|
||||
BuiltinConst,
|
||||
Builtins,
|
||||
ReplBinding,
|
||||
ScopedImportBinding,
|
||||
}
|
||||
|
||||
pub enum Const {
|
||||
Smi(i32),
|
||||
Float(f64),
|
||||
Bool(bool),
|
||||
String(StringId),
|
||||
Path(StringId),
|
||||
PrimOp {
|
||||
id: BuiltinId,
|
||||
arity: u8,
|
||||
dispatch_ip: u32,
|
||||
},
|
||||
Null,
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Clone, Copy, TryFromPrimitive)]
|
||||
pub enum AttrKeyType {
|
||||
Static,
|
||||
Dynamic,
|
||||
}
|
||||
|
||||
pub enum InlineOperand {
|
||||
Const(Const),
|
||||
BigInt(i64),
|
||||
@@ -36,7 +149,7 @@ pub enum InlineOperand {
|
||||
BuiltinConst(StringId),
|
||||
Builtins,
|
||||
ReplBinding(StringId),
|
||||
ScopedImportBinding { id: StringId, slot_id: u32 },
|
||||
ScopedImportBinding(StringId),
|
||||
}
|
||||
|
||||
pub fn compile_bytecode(ir: RawIrRef<'_>, ctx: &mut impl BytecodeContext) -> InstructionPtr {
|
||||
@@ -54,6 +167,7 @@ impl<'a, Ctx: BytecodeContext> BytecodeEmitter<'a, Ctx> {
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
fn inline_maybe_thunk(&self, val: &MaybeThunk) -> InlineOperand {
|
||||
use MaybeThunk::*;
|
||||
match *val {
|
||||
@@ -74,13 +188,18 @@ 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: id.entry_phase().ip(),
|
||||
})
|
||||
}
|
||||
BuiltinConst(id) => InlineOperand::BuiltinConst(id),
|
||||
Builtins => InlineOperand::Builtins,
|
||||
ReplBinding(id) => InlineOperand::ReplBinding(id),
|
||||
ScopedImportBinding { slot_id, sym: id } => {
|
||||
InlineOperand::ScopedImportBinding { slot_id, id }
|
||||
}
|
||||
ScopedImportBinding(id) => InlineOperand::ScopedImportBinding(id),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,9 +232,13 @@ impl<'a, Ctx: BytecodeContext> BytecodeEmitter<'a, Ctx> {
|
||||
self.emit_u8(OperandType::ReplBinding as u8);
|
||||
self.emit_str_id(id);
|
||||
}
|
||||
ScopedImportBinding { id, slot_id } => {
|
||||
ScopedImportBinding(id) => {
|
||||
self.emit_u8(OperandType::ScopedImportBinding as u8);
|
||||
self.emit_u32(slot_id);
|
||||
let slot = self
|
||||
.ctx
|
||||
.current_scope_slot()
|
||||
.expect("ScopedImportBinding outside scoped compilation");
|
||||
self.emit_u32(slot);
|
||||
self.emit_str_id(id);
|
||||
}
|
||||
}
|
||||
@@ -178,10 +301,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 +329,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) {
|
||||
@@ -440,10 +555,14 @@ impl<'a, Ctx: BytecodeContext> BytecodeEmitter<'a, Ctx> {
|
||||
self.emit_op(Op::LoadReplBinding);
|
||||
self.emit_str_id(name);
|
||||
}
|
||||
&Ir::ScopedImportBinding { sym, slot_id } => {
|
||||
&Ir::ScopedImportBinding(name) => {
|
||||
self.emit_op(Op::LoadScopedBinding);
|
||||
self.emit_u32(slot_id);
|
||||
self.emit_str_id(sym);
|
||||
let slot = self
|
||||
.ctx
|
||||
.current_scope_slot()
|
||||
.expect("ScopedImportBinding outside scoped compilation");
|
||||
self.emit_u32(slot);
|
||||
self.emit_str_id(name);
|
||||
}
|
||||
Ir::WithLookup { sym, namespaces } => {
|
||||
// counter
|
||||
@@ -510,20 +629,20 @@ impl<'a, Ctx: BytecodeContext> BytecodeEmitter<'a, Ctx> {
|
||||
self.emit_op(Op::LoadReplBinding);
|
||||
self.emit_str_id(name);
|
||||
}
|
||||
ScopedImportBinding { slot_id, sym } => {
|
||||
ScopedImportBinding(name) => {
|
||||
self.emit_op(Op::LoadScopedBinding);
|
||||
self.emit_u32(slot_id);
|
||||
self.emit_str_id(sym);
|
||||
let slot = self
|
||||
.ctx
|
||||
.current_scope_slot()
|
||||
.expect("ScopedImportBinding outside scoped compilation");
|
||||
self.emit_u32(slot);
|
||||
self.emit_str_id(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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 {
|
||||
@@ -656,7 +775,7 @@ impl<'a, Ctx: BytecodeContext> BytecodeEmitter<'a, Ctx> {
|
||||
|
||||
fn emit_attrset(
|
||||
&mut self,
|
||||
stcs: &ir::HashMap<'_, StringId, (&MaybeThunk, TextRange)>,
|
||||
stcs: &fix_ir::HashMap<'_, StringId, (&MaybeThunk, TextRange)>,
|
||||
dyns: &[(RawIrRef<'_>, &MaybeThunk, TextRange)],
|
||||
) {
|
||||
if stcs.is_empty() && dyns.is_empty() {
|
||||
@@ -716,25 +835,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 +853,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);
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
[package]
|
||||
name = "fix-lang"
|
||||
name = "fix-common"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
ere = { workspace = true }
|
||||
gc-arena = { workspace = true }
|
||||
num_enum = { workspace = true }
|
||||
string-interner = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
ere = { workspace = true }
|
||||
@@ -4,162 +4,6 @@ use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
||||
use gc_arena::Collect;
|
||||
use num_enum::TryFromPrimitive;
|
||||
|
||||
macro_rules! define_builtins {
|
||||
($(($name:literal, $variant:ident, $arity:expr)),* $(,)?) => {
|
||||
const BUILTINS: &[(&str, u8)] = &[
|
||||
$(($name, $arity),)*
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive, Collect)]
|
||||
#[repr(u8)]
|
||||
#[collect(require_static)]
|
||||
pub enum BuiltinId {
|
||||
$($variant,)*
|
||||
}
|
||||
|
||||
impl BuiltinId {
|
||||
pub const ALL: [Self; BUILTINS.len()] = [$(Self::$variant,)*];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
define_builtins! {
|
||||
("abort", Abort, 1),
|
||||
("__add", Add, 2),
|
||||
("__addErrorContext", AddErrorContext, 2),
|
||||
("__all", All, 2),
|
||||
("__any", Any, 2),
|
||||
("__appendContext", AppendContext, 2),
|
||||
("__attrNames", AttrNames, 1),
|
||||
("__attrValues", AttrValues, 1),
|
||||
("baseNameOf", BaseNameOf, 1),
|
||||
("__bitAnd", BitAnd, 2),
|
||||
("__bitOr", BitOr, 2),
|
||||
("__bitXor", BitXor, 2),
|
||||
("break", Break, 1),
|
||||
("__catAttrs", CatAttrs, 2),
|
||||
("__ceil", Ceil, 1),
|
||||
("__compareVersions", CompareVersions, 2),
|
||||
("__concatLists", ConcatLists, 1),
|
||||
("__concatMap", ConcatMap, 2),
|
||||
("__concatStringsSep", ConcatStringsSep, 2),
|
||||
("__convertHash", ConvertHash, 1),
|
||||
("__deepSeq", DeepSeq, 2),
|
||||
("derivation", Derivation, 1),
|
||||
("derivationStrict", DerivationStrict, 1),
|
||||
("dirOf", DirOf, 1),
|
||||
("__div", Div, 2),
|
||||
("__elem", Elem, 2),
|
||||
("__elemAt", ElemAt, 2),
|
||||
("fetchGit", FetchGit, 1),
|
||||
("fetchMercurial", FetchMercurial, 1),
|
||||
("fetchTarball", FetchTarball, 1),
|
||||
("fetchTree", FetchTree, 1),
|
||||
("__fetchurl", FetchUrl, 1),
|
||||
("__filter", Filter, 2),
|
||||
("__filterSource", FilterSource, 2),
|
||||
("__findFile", FindFile, 2),
|
||||
("__floor", Floor, 1),
|
||||
("__foldl'", FoldlStrict, 3),
|
||||
("__fromJSON", FromJSON, 1),
|
||||
("fromTOML", FromTOML, 1),
|
||||
("__functionArgs", FunctionArgs, 1),
|
||||
("__genList", GenList, 2),
|
||||
("__genericClosure", GenericClosure, 1),
|
||||
("__getAttr", GetAttr, 2),
|
||||
("__getContext", GetContext, 1),
|
||||
("__getEnv", GetEnv, 1),
|
||||
("__groupBy", GroupBy, 2),
|
||||
("__hasAttr", HasAttr, 2),
|
||||
("__hasContext", HasContext, 1),
|
||||
("__hashFile", HashFile, 2),
|
||||
("__hashString", HashString, 2),
|
||||
("__head", Head, 1),
|
||||
("import", Import, 1),
|
||||
("__intersectAttrs", IntersectAttrs, 2),
|
||||
("__isAttrs", IsAttrs, 1),
|
||||
("__isBool", IsBool, 1),
|
||||
("__isFloat", IsFloat, 1),
|
||||
("__isFunction", IsFunction, 1),
|
||||
("__isInt", IsInt, 1),
|
||||
("__isList", IsList, 1),
|
||||
("isNull", IsNull, 1),
|
||||
("__isPath", IsPath, 1),
|
||||
("__isString", IsString, 1),
|
||||
("__length", Length, 1),
|
||||
("__lessThan", LessThan, 2),
|
||||
("__listToAttrs", ListToAttrs, 1),
|
||||
("map", Map, 2),
|
||||
("__mapAttrs", MapAttrs, 2),
|
||||
("__match", Match, 2),
|
||||
("__mul", Mul, 2),
|
||||
("__parseDrvName", ParseDrvName, 1),
|
||||
("__partition", Partition, 2),
|
||||
("__path", Path, 1),
|
||||
("__pathExists", PathExists, 1),
|
||||
("placeholder", Placeholder, 1),
|
||||
("__readDir", ReadDir, 1),
|
||||
("__readFile", ReadFile, 1),
|
||||
("__readFileType", ReadFileType, 1),
|
||||
("removeAttrs", RemoveAttrs, 2),
|
||||
("__replaceStrings", ReplaceStrings, 3),
|
||||
("scopedImport", ScopedImport, 2),
|
||||
("__seq", Seq, 2),
|
||||
("__sort", Sort, 2),
|
||||
("__split", Split, 2),
|
||||
("__splitVersion", SplitVersion, 1),
|
||||
("__storePath", StorePath, 1),
|
||||
("__stringLength", StringLength, 1),
|
||||
("__sub", Sub, 2),
|
||||
("__substring", Substring, 3),
|
||||
("__tail", Tail, 1),
|
||||
("throw", Throw, 1),
|
||||
("__toFile", ToFile, 2),
|
||||
("__toJSON", ToJSON, 1),
|
||||
("__toPath", ToPath, 1),
|
||||
("toString", ToString, 1),
|
||||
("__toXML", ToXML, 1),
|
||||
("__trace", Trace, 2),
|
||||
("__tryEval", TryEval, 1),
|
||||
("__typeOf", TypeOf, 1),
|
||||
("__unsafeDiscardStringContext", UnsafeDiscardStringContext, 1),
|
||||
("__unsafeDiscardOutputDependency", UnsafeDiscardOutputDependency, 1),
|
||||
("__unsafeGetAttrPos", UnsafeGetAttrPos, 2),
|
||||
("__warn", Warn, 2),
|
||||
("__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)]
|
||||
@@ -461,10 +305,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 +329,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}")
|
||||
@@ -1,570 +0,0 @@
|
||||
use bumpalo::Bump;
|
||||
use fix_bytecode::{Const, Continuation, InstructionPtr, Op};
|
||||
use fix_error::{Error, Result, Source};
|
||||
use fix_lang::{StringId, Symbol};
|
||||
use fix_runtime::{StaticValue, VmCode, VmRuntimeCtx};
|
||||
use ghost_cell::{GhostCell, GhostToken};
|
||||
use hashbrown::{HashMap, HashSet};
|
||||
use string_interner::DefaultStringInterner;
|
||||
|
||||
use crate::BytecodeContext;
|
||||
use crate::ir::downgrade::{Downgrade as _, DowngradeContext};
|
||||
use crate::ir::{
|
||||
GhostMaybeThunkRef, GhostRoIrRef, GhostRoMaybeThunkRef, GhostRoRef, Ir, MaybeThunk, RawIrRef,
|
||||
ThunkId,
|
||||
};
|
||||
|
||||
pub struct CodeState {
|
||||
pub bytecode: Vec<u8>,
|
||||
pub sources: Vec<Source>,
|
||||
pub spans: Vec<(usize, rnix::TextRange)>,
|
||||
pub thunk_count: usize,
|
||||
pub global_env: HashMap<StringId, MaybeThunk>,
|
||||
}
|
||||
|
||||
impl CodeState {
|
||||
pub fn new(strings: &mut DefaultStringInterner) -> Self {
|
||||
let global_env = crate::ir::new_global_env(strings);
|
||||
let mut bytecode = Vec::with_capacity(Continuation::Illegal as usize * 2);
|
||||
for phase in 0..=Continuation::Illegal as u8 {
|
||||
bytecode.push(Op::DispatchCont as u8);
|
||||
bytecode.push(phase);
|
||||
}
|
||||
Self {
|
||||
sources: Vec::new(),
|
||||
spans: Vec::new(),
|
||||
thunk_count: 0,
|
||||
bytecode,
|
||||
global_env,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn compile_bytecode<'ctx>(
|
||||
&'ctx mut self,
|
||||
source: Source,
|
||||
extra_scope: Option<ExtraScope<'ctx>>,
|
||||
runtime: &'ctx mut impl VmRuntimeCtx,
|
||||
) -> Result<InstructionPtr> {
|
||||
let mut compiler = CompilerCtx {
|
||||
code: self,
|
||||
runtime,
|
||||
};
|
||||
compiler.compile_bytecode(source, extra_scope)
|
||||
}
|
||||
}
|
||||
|
||||
impl VmCode for CodeState {
|
||||
fn bytecode(&self) -> &[u8] {
|
||||
&self.bytecode
|
||||
}
|
||||
|
||||
fn compile_with_scope(
|
||||
&mut self,
|
||||
source: Source,
|
||||
extra_scope: Option<fix_runtime::ExtraScope>,
|
||||
runtime: &mut impl VmRuntimeCtx,
|
||||
) -> Result<InstructionPtr> {
|
||||
let extra = extra_scope.map(|s| match s {
|
||||
fix_runtime::ExtraScope::ScopedImport { keys, slot_id } => {
|
||||
ExtraScope::ScopedImport { keys, slot_id }
|
||||
}
|
||||
});
|
||||
CodeState::compile_bytecode(self, source, extra, runtime)
|
||||
}
|
||||
}
|
||||
|
||||
struct CompilerCtx<'a, R: VmRuntimeCtx> {
|
||||
code: &'a mut CodeState,
|
||||
runtime: &'a mut R,
|
||||
}
|
||||
|
||||
impl<'a, R: VmRuntimeCtx> CompilerCtx<'a, R> {
|
||||
fn compile_bytecode(
|
||||
&mut self,
|
||||
source: Source,
|
||||
extra_scope: Option<ExtraScope>,
|
||||
) -> Result<InstructionPtr> {
|
||||
let root = self.downgrade(source, extra_scope)?;
|
||||
let ip = crate::compile_bytecode(root.as_ref(), self);
|
||||
Ok(ip)
|
||||
}
|
||||
|
||||
fn downgrade(&mut self, source: Source, extra_scope: Option<ExtraScope>) -> Result<OwnedIr> {
|
||||
tracing::debug!("Parsing Nix expression");
|
||||
|
||||
self.code.sources.push(source.clone());
|
||||
|
||||
let root = rnix::Root::parse(&source.src);
|
||||
handle_parse_error(root.errors(), source.clone()).map_or(Ok(()), Err)?;
|
||||
|
||||
tracing::debug!("Downgrading Nix expression");
|
||||
let expr = root
|
||||
.tree()
|
||||
.expr()
|
||||
.ok_or_else(|| Error::parse_error("unexpected EOF".into()))?;
|
||||
let bump = Bump::new();
|
||||
GhostToken::new(|token| {
|
||||
let downgrade_ctx = DowngradeCtx::new(
|
||||
&bump,
|
||||
token,
|
||||
self.runtime,
|
||||
&self.code.global_env,
|
||||
extra_scope.map(Into::into),
|
||||
&mut self.code.thunk_count,
|
||||
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) })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, R: VmRuntimeCtx> BytecodeContext for CompilerCtx<'a, R> {
|
||||
fn intern_string(&mut self, s: &str) -> StringId {
|
||||
self.runtime.intern_string(s)
|
||||
}
|
||||
|
||||
fn register_span(&mut self, range: rnix::TextRange) -> u32 {
|
||||
let id = self.code.spans.len();
|
||||
let source_id = self
|
||||
.code
|
||||
.sources
|
||||
.len()
|
||||
.checked_sub(1)
|
||||
.expect("current_source not set");
|
||||
self.code.spans.push((source_id, range));
|
||||
id as u32
|
||||
}
|
||||
|
||||
fn get_code(&self) -> &[u8] {
|
||||
&self.code.bytecode
|
||||
}
|
||||
|
||||
fn get_code_mut(&mut self) -> &mut Vec<u8> {
|
||||
&mut self.code.bytecode
|
||||
}
|
||||
|
||||
fn add_constant(&mut self, val: Const) -> u32 {
|
||||
use Const::*;
|
||||
let val = match val {
|
||||
Smi(x) => StaticValue::new(x),
|
||||
Float(x) => StaticValue::new(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)),
|
||||
Null => StaticValue::default(),
|
||||
};
|
||||
self.runtime.add_const(val)
|
||||
}
|
||||
|
||||
fn current_source_dir(&mut self) -> StringId {
|
||||
let dir = self
|
||||
.code
|
||||
.sources
|
||||
.last()
|
||||
.expect("current_source not set")
|
||||
.get_dir()
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
self.runtime.intern_string(dir)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_error_span(error: &rnix::ParseError) -> Option<rnix::TextRange> {
|
||||
use rnix::ParseError::*;
|
||||
match error {
|
||||
Unexpected(range)
|
||||
| UnexpectedExtra(range)
|
||||
| UnexpectedWanted(_, range, _)
|
||||
| UnexpectedDoubleBind(range)
|
||||
| DuplicatedArgs(range, _) => Some(*range),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_parse_error<'a>(
|
||||
errors: impl IntoIterator<Item = &'a rnix::ParseError>,
|
||||
source: Source,
|
||||
) -> Option<Box<Error>> {
|
||||
for err in errors {
|
||||
if let Some(span) = parse_error_span(err) {
|
||||
return Some(
|
||||
Error::parse_error(err.to_string())
|
||||
.with_source(source)
|
||||
.with_span(span),
|
||||
);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
struct DowngradeCtx<'ctx, 'id, 'ir, R: VmRuntimeCtx> {
|
||||
bump: &'ir Bump,
|
||||
token: GhostToken<'id>,
|
||||
runtime: &'ctx mut R,
|
||||
source: Source,
|
||||
scopes: Vec<Scope<'ctx, 'id, 'ir>>,
|
||||
with_stack: Vec<GhostRoMaybeThunkRef<'id, 'ir>>,
|
||||
thunk_count: &'ctx mut usize,
|
||||
thunk_scopes: Vec<ThunkScope<'id, 'ir>>,
|
||||
}
|
||||
|
||||
impl<'ctx, 'id, 'ir, R: VmRuntimeCtx> DowngradeCtx<'ctx, 'id, 'ir, R> {
|
||||
fn new(
|
||||
bump: &'ir Bump,
|
||||
token: GhostToken<'id>,
|
||||
runtime: &'ctx mut R,
|
||||
global: &'ctx HashMap<StringId, MaybeThunk>,
|
||||
extra_scope: Option<Scope<'ctx, 'id, 'ir>>,
|
||||
thunk_count: &'ctx mut usize,
|
||||
source: Source,
|
||||
) -> Self {
|
||||
Self {
|
||||
bump,
|
||||
token,
|
||||
runtime,
|
||||
source,
|
||||
scopes: std::iter::once(Scope::Global(global))
|
||||
.chain(extra_scope)
|
||||
.collect(),
|
||||
thunk_count,
|
||||
with_stack: Vec::new(),
|
||||
thunk_scopes: vec![ThunkScope::new_in(bump)],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx: 'ir, 'id, 'ir, R: VmRuntimeCtx> DowngradeContext<'id, 'ir>
|
||||
for DowngradeCtx<'ctx, 'id, 'ir, R>
|
||||
{
|
||||
fn new_expr(&self, expr: Ir<'ir, GhostRoRef<'id, 'ir>>) -> GhostRoIrRef<'id, 'ir> {
|
||||
self.bump.alloc(GhostCell::new(expr).into())
|
||||
}
|
||||
|
||||
fn maybe_thunk(&mut self, ir: GhostRoIrRef<'id, 'ir>) -> GhostRoMaybeThunkRef<'id, 'ir> {
|
||||
use MaybeThunk::*;
|
||||
let expr = (|| {
|
||||
let expr = match *ir.borrow(&self.token) {
|
||||
Ir::Builtin(x) => Builtin(x),
|
||||
Ir::Int(x) => Int(x),
|
||||
Ir::Float(x) => Float(x),
|
||||
Ir::Bool(x) => Bool(x),
|
||||
Ir::Str(x) => Str(x),
|
||||
Ir::Arg { layer } => Arg { layer },
|
||||
Ir::Builtins => Builtins,
|
||||
Ir::Null => Null,
|
||||
Ir::MaybeThunk(thunk) => return Some(thunk),
|
||||
_ => return None,
|
||||
};
|
||||
Some(self.bump.alloc(GhostCell::new(expr).into()))
|
||||
})();
|
||||
if let Some(thunk) = expr {
|
||||
return thunk;
|
||||
}
|
||||
let id = ThunkId(*self.thunk_count);
|
||||
*self.thunk_count = self.thunk_count.checked_add(1).expect("thunk id overflow");
|
||||
self.thunk_scopes
|
||||
.last_mut()
|
||||
.expect("no active cache scope")
|
||||
.add_binding(id, ir);
|
||||
self.bump.alloc(GhostCell::new(Thunk(id)).into())
|
||||
}
|
||||
|
||||
fn intern_string(&mut self, sym: impl AsRef<str>) -> StringId {
|
||||
self.runtime.intern_string(sym)
|
||||
}
|
||||
|
||||
fn resolve_sym(&self, id: StringId) -> Symbol<'_> {
|
||||
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,
|
||||
span: rnix::TextRange,
|
||||
) -> Result<GhostRoMaybeThunkRef<'id, 'ir>> {
|
||||
for scope in self.scopes.iter().rev() {
|
||||
match scope {
|
||||
&Scope::Global(global_scope) => {
|
||||
if let Some(expr) = global_scope.get(&sym) {
|
||||
return Ok(expr.into());
|
||||
}
|
||||
}
|
||||
&Scope::Repl(repl_bindings) => {
|
||||
if repl_bindings.contains(&sym) {
|
||||
return Ok(self
|
||||
.bump
|
||||
.alloc(GhostCell::new(MaybeThunk::ReplBinding(sym)).into()));
|
||||
}
|
||||
}
|
||||
&Scope::ScopedImport { ref keys, slot_id } => {
|
||||
if keys.contains(&sym) {
|
||||
return Ok(self.bump.alloc(
|
||||
GhostCell::new(MaybeThunk::ScopedImportBinding { sym, slot_id }).into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Scope::Let(let_scope) => {
|
||||
if let Some(&expr) = let_scope.get(&sym) {
|
||||
return Ok(expr.into());
|
||||
}
|
||||
}
|
||||
&Scope::Param {
|
||||
sym: param_sym,
|
||||
abs_layer,
|
||||
} => {
|
||||
if param_sym == sym {
|
||||
let layers: u8 =
|
||||
self.thunk_scopes.len().try_into().expect("scope too deep!");
|
||||
let layer = layers - abs_layer;
|
||||
return Ok(self
|
||||
.bump
|
||||
.alloc(GhostCell::new(MaybeThunk::Arg { layer }).into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !self.with_stack.is_empty() {
|
||||
let id = ThunkId(*self.thunk_count);
|
||||
*self.thunk_count = self.thunk_count.checked_add(1).expect("thunk id overflow");
|
||||
let mut namespaces =
|
||||
bumpalo::collections::Vec::with_capacity_in(self.with_stack.len(), self.bump);
|
||||
namespaces.extend(self.with_stack.iter().rev().copied());
|
||||
let body = self
|
||||
.bump
|
||||
.alloc(GhostCell::new(Ir::WithLookup { sym, namespaces }).into());
|
||||
self.thunk_scopes
|
||||
.last_mut()
|
||||
.expect("no active thunk scope")
|
||||
.add_binding(id, body);
|
||||
Ok(self
|
||||
.bump
|
||||
.alloc(GhostCell::new(MaybeThunk::Thunk(id)).into()))
|
||||
} else {
|
||||
Err(Error::downgrade_error(
|
||||
format!("'{}' not found", self.resolve_sym(sym)),
|
||||
self.get_current_source(),
|
||||
span,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn get_current_source(&self) -> Source {
|
||||
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(
|
||||
&mut Self,
|
||||
) -> Result<(
|
||||
bumpalo::collections::Vec<'ir, GhostRoMaybeThunkRef<'id, 'ir>>,
|
||||
Ret,
|
||||
)>,
|
||||
{
|
||||
let base = *self.thunk_count;
|
||||
*self.thunk_count = self
|
||||
.thunk_count
|
||||
.checked_add(keys.len())
|
||||
.expect("thunk id overflow");
|
||||
let handles = (base..base + keys.len())
|
||||
.map(|id| {
|
||||
&*self
|
||||
.bump
|
||||
.alloc(GhostCell::new(MaybeThunk::Thunk(ThunkId(id))))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let scope = keys.iter().copied().zip(handles.iter().copied()).collect();
|
||||
self.scopes.push(Scope::Let(scope));
|
||||
let (vals, ret) = { f(self)? };
|
||||
self.scopes.pop();
|
||||
assert_eq!(keys.len(), vals.len());
|
||||
let scope = self.thunk_scopes.last_mut().expect("no active thunk scope");
|
||||
for (i, (val, handle)) in vals.into_iter().zip(handles).enumerate() {
|
||||
let thunk = *val.borrow(&self.token);
|
||||
*handle.borrow_mut(&mut self.token) = thunk;
|
||||
let id = ThunkId(base + i);
|
||||
let ir_ref = self
|
||||
.bump
|
||||
.alloc(GhostCell::new(Ir::MaybeThunk(handle.into())).into());
|
||||
scope.add_binding(id, ir_ref);
|
||||
}
|
||||
Ok(ret)
|
||||
}
|
||||
|
||||
fn with_param_scope<F, Ret>(&mut self, sym: StringId, f: F) -> Ret
|
||||
where
|
||||
F: FnOnce(&mut Self) -> Ret,
|
||||
{
|
||||
self.scopes.push(Scope::Param {
|
||||
sym,
|
||||
abs_layer: self.thunk_scopes.len().try_into().expect("scope too deep!"),
|
||||
});
|
||||
let mut guard = ScopeGuard { ctx: self };
|
||||
f(guard.as_ctx())
|
||||
}
|
||||
|
||||
fn with_with_scope<F, Ret>(&mut self, namespace: GhostRoMaybeThunkRef<'id, 'ir>, f: F) -> Ret
|
||||
where
|
||||
F: FnOnce(&mut Self) -> Ret,
|
||||
{
|
||||
self.with_stack.push(namespace);
|
||||
let ret = f(self);
|
||||
self.with_stack.pop();
|
||||
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,
|
||||
) -> (
|
||||
Ret,
|
||||
bumpalo::collections::Vec<'ir, (ThunkId, GhostRoIrRef<'id, 'ir>)>,
|
||||
)
|
||||
where
|
||||
F: FnOnce(&mut Self) -> Ret,
|
||||
{
|
||||
if self.thunk_scopes.len() == u8::MAX as usize {
|
||||
panic!("scope too deep!");
|
||||
}
|
||||
self.thunk_scopes.push(ThunkScope::new_in(self.bump));
|
||||
let ret = f(self);
|
||||
(
|
||||
ret,
|
||||
self.thunk_scopes
|
||||
.pop()
|
||||
.expect("no thunk scope left???")
|
||||
.bindings,
|
||||
)
|
||||
}
|
||||
|
||||
fn bump(&self) -> &'ir bumpalo::Bump {
|
||||
self.bump
|
||||
}
|
||||
}
|
||||
|
||||
impl<'id, 'ir, 'ctx: 'ir, R: VmRuntimeCtx> DowngradeCtx<'ctx, 'id, 'ir, R> {
|
||||
fn downgrade_toplevel(mut self, root: rnix::ast::Expr) -> Result<RawIrRef<'ir>> {
|
||||
let body = root.downgrade(&mut self)?;
|
||||
let thunks = self
|
||||
.thunk_scopes
|
||||
.pop()
|
||||
.expect("no thunk scope left???")
|
||||
.bindings;
|
||||
Ok(Ir::freeze(
|
||||
self.new_expr(Ir::TopLevel { body, thunks }),
|
||||
self.token,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
struct ThunkScope<'id, 'ir> {
|
||||
bindings: bumpalo::collections::Vec<'ir, (ThunkId, GhostRoIrRef<'id, 'ir>)>,
|
||||
}
|
||||
|
||||
impl<'id, 'ir> ThunkScope<'id, 'ir> {
|
||||
fn new_in(bump: &'ir Bump) -> Self {
|
||||
Self {
|
||||
bindings: bumpalo::collections::Vec::new_in(bump),
|
||||
}
|
||||
}
|
||||
|
||||
fn add_binding(&mut self, id: ThunkId, ir: GhostRoIrRef<'id, 'ir>) {
|
||||
self.bindings.push((id, ir));
|
||||
}
|
||||
}
|
||||
|
||||
enum Scope<'ctx, 'id, 'ir> {
|
||||
Global(&'ctx HashMap<StringId, MaybeThunk>),
|
||||
Repl(&'ctx HashSet<StringId>),
|
||||
ScopedImport {
|
||||
keys: HashSet<StringId>,
|
||||
slot_id: u32,
|
||||
},
|
||||
Let(HashMap<StringId, GhostMaybeThunkRef<'id, 'ir>>),
|
||||
Param {
|
||||
sym: StringId,
|
||||
abs_layer: u8,
|
||||
},
|
||||
}
|
||||
|
||||
pub enum ExtraScope<'ctx> {
|
||||
Repl(&'ctx HashSet<StringId>),
|
||||
ScopedImport {
|
||||
keys: HashSet<StringId>,
|
||||
slot_id: u32,
|
||||
},
|
||||
}
|
||||
|
||||
impl<'ctx> From<ExtraScope<'ctx>> for Scope<'ctx, '_, '_> {
|
||||
fn from(value: ExtraScope<'ctx>) -> Self {
|
||||
use ExtraScope::*;
|
||||
match value {
|
||||
ScopedImport { keys, slot_id } => Scope::ScopedImport { keys, slot_id },
|
||||
Repl(scope) => Scope::Repl(scope),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ScopeGuard<'a, 'ctx, 'id, 'ir, R: VmRuntimeCtx> {
|
||||
ctx: &'a mut DowngradeCtx<'ctx, 'id, 'ir, R>,
|
||||
}
|
||||
|
||||
impl<'a, 'ctx, 'id, 'ir, R: VmRuntimeCtx> Drop for ScopeGuard<'a, 'ctx, 'id, 'ir, R> {
|
||||
fn drop(&mut self) {
|
||||
self.ctx.scopes.pop();
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'ctx, 'id, 'ir, R: VmRuntimeCtx> ScopeGuard<'a, 'ctx, 'id, 'ir, R> {
|
||||
fn as_ctx(&mut self) -> &mut DowngradeCtx<'ctx, 'id, 'ir, R> {
|
||||
self.ctx
|
||||
}
|
||||
}
|
||||
|
||||
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) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub use sealed::OwnedIr;
|
||||
@@ -5,8 +5,5 @@ edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
miette = { version = "7.6", features = ["fancy"] }
|
||||
rnix = { workspace = true }
|
||||
thiserror = "2.0"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
rnix = { workspace = true }
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,22 +1,17 @@
|
||||
[package]
|
||||
name = "fix-compiler"
|
||||
name = "fix-ir"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
bumpalo = { workspace = true }
|
||||
colored = "3.1.1"
|
||||
ghost-cell = { workspace = true }
|
||||
hashbrown = { workspace = true }
|
||||
rnix = { workspace = true }
|
||||
rowan = { workspace = true }
|
||||
string-interner = { workspace = true }
|
||||
hashbrown = { workspace = true }
|
||||
num_enum = { workspace = true }
|
||||
|
||||
fix-bytecode = { path = "../fix-bytecode" }
|
||||
fix-builtins = { path = "../fix-builtins" }
|
||||
fix-common = { path = "../fix-common" }
|
||||
fix-error = { path = "../fix-error" }
|
||||
fix-lang = { path = "../fix-lang" }
|
||||
fix-runtime = { path = "../fix-runtime" }
|
||||
tracing = "0.1"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,6 +1,7 @@
|
||||
use bumpalo::collections::{CollectIn, Vec};
|
||||
use fix_builtins::BuiltinId;
|
||||
use fix_common::Symbol;
|
||||
use fix_error::{Error, Result, Source};
|
||||
use fix_lang::{BuiltinId, Symbol};
|
||||
use hashbrown::HashSet;
|
||||
use hashbrown::hash_map::Entry;
|
||||
use rnix::TextRange;
|
||||
@@ -156,10 +157,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 +463,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 +494,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 +551,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 +652,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 +666,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>,
|
||||
@@ -3,8 +3,10 @@ use std::marker::PhantomData;
|
||||
|
||||
use bumpalo::Bump;
|
||||
use bumpalo::collections::Vec;
|
||||
use fix_lang::{BuiltinId, StringId};
|
||||
use fix_builtins::{BUILTINS, BuiltinId};
|
||||
use fix_common::StringId;
|
||||
use ghost_cell::{GhostCell, GhostToken};
|
||||
use num_enum::TryFromPrimitive as _;
|
||||
use rnix::{TextRange, ast};
|
||||
use string_interner::DefaultStringInterner;
|
||||
|
||||
@@ -28,7 +30,7 @@ impl<'id, 'ir> Ir<'ir, GhostRoRef<'id, 'ir>> {
|
||||
// - `Ir<'ir, R>` is `#[repr(C)]`, and for every field that depends on
|
||||
// `R`, instantiating `R = GhostRef<'id, 'ir>` vs `R = RawRef<'ir>`
|
||||
// produces types of identical layout:
|
||||
// - `R::IrRef` becomes `&'ir GhostCell<'id, Ir<...>>` vs `&'ir Ir<...>`
|
||||
// - `R::IrRef` becomes `&'ir GhostCell<'id, Ir<…>>` vs `&'ir Ir<…>`
|
||||
// - `R::MaybeThunkRef` becomes `&'ir GhostCell<'id, MaybeThunk>`
|
||||
// vs `&'ir MaybeThunk`
|
||||
// - `R::Ref<Ir<'ir, R>>` (used in `ConcatStrings::parts`) reduces
|
||||
@@ -90,7 +92,7 @@ pub enum MaybeThunk {
|
||||
BuiltinConst(StringId),
|
||||
Builtins,
|
||||
ReplBinding(StringId),
|
||||
ScopedImportBinding { slot_id: u32, sym: StringId },
|
||||
ScopedImportBinding(StringId),
|
||||
}
|
||||
|
||||
pub trait Ref<'ir> {
|
||||
@@ -211,17 +213,19 @@ pub enum Ir<'ir, R: RefExt<'ir> + ?Sized + 'ir> {
|
||||
},
|
||||
MaybeThunk(R::MaybeThunkRef),
|
||||
ReplBinding(StringId),
|
||||
ScopedImportBinding {
|
||||
sym: StringId,
|
||||
slot_id: u32,
|
||||
},
|
||||
ScopedImportBinding(StringId),
|
||||
}
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct ThunkId(pub usize);
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct SpanId(pub u32);
|
||||
|
||||
/// 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 +294,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_primitive(idx as u8).expect("infallible");
|
||||
let name = StringId(strings.get_or_intern(name));
|
||||
global_env.insert(name, MaybeThunk::Builtin(id));
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
[package]
|
||||
name = "fix-macros"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
proc-macro2 = "1.0"
|
||||
quote = "1.0"
|
||||
syn = { version = "3.0", features = ["full", "visit", "visit-mut"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,49 +0,0 @@
|
||||
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;
|
||||
use syn::parse::{Parse, ParseStream};
|
||||
use syn::visit_mut::VisitMut;
|
||||
|
||||
struct Input {
|
||||
lt: syn::Lifetime,
|
||||
ty: syn::Type,
|
||||
}
|
||||
|
||||
impl Parse for Input {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let lt: syn::Lifetime = input.parse()?;
|
||||
let _: syn::Token!(;) = input.parse()?;
|
||||
let ty: syn::Type = input.parse()?;
|
||||
Ok(Self { lt, ty })
|
||||
}
|
||||
}
|
||||
|
||||
struct UnelideLifetimes(syn::Lifetime);
|
||||
|
||||
impl VisitMut for UnelideLifetimes {
|
||||
fn visit_lifetime_mut(&mut self, i: &mut syn::Lifetime) {
|
||||
if i.ident == "_" {
|
||||
*i = self.0.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut input = syn::parse_macro_input!(input as Input);
|
||||
UnelideLifetimes(input.lt).visit_type_mut(&mut input.ty);
|
||||
input.ty.to_token_stream().into()
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
[package]
|
||||
name = "fix-runtime"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
gc-arena = { workspace = true }
|
||||
hashbrown = { workspace = true }
|
||||
smallvec = { workspace = true }
|
||||
sptr = "0.3"
|
||||
string-interner = { workspace = true }
|
||||
|
||||
fix-bytecode = { path = "../fix-bytecode" }
|
||||
fix-error = { path = "../fix-error" }
|
||||
fix-lang = { path = "../fix-lang" }
|
||||
fix-macros = { path = "../fix-macros" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,235 +0,0 @@
|
||||
use fix_lang::StringId;
|
||||
use gc_arena::Mutation;
|
||||
|
||||
use crate::{
|
||||
AttrSet, BytecodeReader, Closure, List, Machine, NixNum, NixString, NixType, Null, PrimOp,
|
||||
PrimOpApp, Step, StrictValue, ValueVariant,
|
||||
};
|
||||
|
||||
pub trait Forced<'gc>: Sized {
|
||||
const WIDTH: usize;
|
||||
|
||||
/// Force and type-check the `WIDTH` slots starting at `base_depth` from
|
||||
/// TOS, deepest-first. If a slot holds a thunk, enter it and return
|
||||
/// `Break::Force`. If a slot holds a value of the wrong type, call
|
||||
/// `finish_type_err` and return `Break::Done`.
|
||||
fn force_and_check<M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
base_depth: usize,
|
||||
resume_pc: usize,
|
||||
) -> Step;
|
||||
|
||||
/// After `force_and_check` returned `Continue`, pop `WIDTH` slots
|
||||
/// (TOS first) and convert. Type assertions are infallible because
|
||||
/// `force_and_check` already validated every slot.
|
||||
fn pop_converted<M: Machine<'gc>>(m: &mut M) -> Self;
|
||||
}
|
||||
|
||||
impl<'gc> Forced<'gc> for StrictValue<'gc> {
|
||||
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)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop_converted<M: Machine<'gc>>(m: &mut M) -> Self {
|
||||
m.pop_forced()
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_forced {
|
||||
($($ty:ty),* $(,)?) => {
|
||||
$(
|
||||
impl<'gc> Forced<'gc> for <$ty as ValueVariant<'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.is::<$ty>() {
|
||||
m.finish_type_err(<$ty as ValueVariant>::TYPE, v.ty())
|
||||
} else {
|
||||
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! {
|
||||
i32,
|
||||
bool,
|
||||
Null,
|
||||
StringId,
|
||||
PrimOp,
|
||||
i64,
|
||||
NixString,
|
||||
AttrSet<'gc>,
|
||||
List<'gc>,
|
||||
Closure<'gc>,
|
||||
PrimOpApp<'gc>,
|
||||
}
|
||||
|
||||
impl<'gc> Forced<'gc> for NixNum {
|
||||
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_num().is_none() {
|
||||
m.finish_type_err(NixType::Int, v.ty())
|
||||
} else {
|
||||
Step::Continue(())
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop_converted<M: Machine<'gc>>(m: &mut M) -> Self {
|
||||
m.pop_forced()
|
||||
.downcast_num()
|
||||
.expect("type checked in force_and_check")
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc> Forced<'gc> for f64 {
|
||||
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.is::<f64>() {
|
||||
m.finish_type_err(NixType::Float, v.ty())
|
||||
} else {
|
||||
Step::Continue(())
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop_converted<M: Machine<'gc>>(m: &mut M) -> Self {
|
||||
m.pop_forced()
|
||||
.downcast::<f64>()
|
||||
.expect("type checked in force_and_check")
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc, A: Forced<'gc>, B: Forced<'gc>> Forced<'gc> for (A, B) {
|
||||
const WIDTH: usize = A::WIDTH + B::WIDTH;
|
||||
|
||||
#[inline(always)]
|
||||
fn force_and_check<M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
base: usize,
|
||||
resume_pc: usize,
|
||||
) -> Step {
|
||||
A::force_and_check(m, reader, mc, base + B::WIDTH, resume_pc)?;
|
||||
B::force_and_check(m, reader, mc, base, resume_pc)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop_converted<M: Machine<'gc>>(m: &mut M) -> Self {
|
||||
let b = B::pop_converted(m);
|
||||
let a = A::pop_converted(m);
|
||||
(a, b)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc, A: Forced<'gc>, B: Forced<'gc>, C: Forced<'gc>> Forced<'gc> for (A, B, C) {
|
||||
const WIDTH: usize = A::WIDTH + B::WIDTH + C::WIDTH;
|
||||
|
||||
#[inline(always)]
|
||||
fn force_and_check<M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
base: usize,
|
||||
resume_pc: usize,
|
||||
) -> Step {
|
||||
A::force_and_check(m, reader, mc, base + B::WIDTH + C::WIDTH, resume_pc)?;
|
||||
B::force_and_check(m, reader, mc, base + C::WIDTH, resume_pc)?;
|
||||
C::force_and_check(m, reader, mc, base, resume_pc)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop_converted<M: Machine<'gc>>(m: &mut M) -> Self {
|
||||
let c = C::pop_converted(m);
|
||||
let b = B::pop_converted(m);
|
||||
let a = A::pop_converted(m);
|
||||
(a, b, c)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc, A: Forced<'gc>, B: Forced<'gc>, C: Forced<'gc>, D: Forced<'gc>> Forced<'gc>
|
||||
for (A, B, C, D)
|
||||
{
|
||||
const WIDTH: usize = A::WIDTH + B::WIDTH + C::WIDTH + D::WIDTH;
|
||||
|
||||
#[inline(always)]
|
||||
fn force_and_check<M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
base: usize,
|
||||
resume_pc: usize,
|
||||
) -> Step {
|
||||
A::force_and_check(
|
||||
m,
|
||||
reader,
|
||||
mc,
|
||||
base + B::WIDTH + C::WIDTH + D::WIDTH,
|
||||
resume_pc,
|
||||
)?;
|
||||
B::force_and_check(m, reader, mc, base + C::WIDTH + D::WIDTH, resume_pc)?;
|
||||
C::force_and_check(m, reader, mc, base + D::WIDTH, resume_pc)?;
|
||||
D::force_and_check(m, reader, mc, base, resume_pc)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop_converted<M: Machine<'gc>>(m: &mut M) -> Self {
|
||||
let d = D::pop_converted(m);
|
||||
let c = C::pop_converted(m);
|
||||
let b = B::pop_converted(m);
|
||||
let a = A::pop_converted(m);
|
||||
(a, b, c, d)
|
||||
}
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
use fix_bytecode::InstructionPtr;
|
||||
use fix_error::Source;
|
||||
use fix_lang::{self, StringId};
|
||||
use hashbrown::HashSet;
|
||||
|
||||
use crate::{
|
||||
AttrSet, Closure, ExtraScope, List, NixString, NixType, Null, Path, PrimOp, PrimOpApp,
|
||||
StaticValue, StrictValue, StringContext, Thunk, ThunkState, Value,
|
||||
};
|
||||
|
||||
pub trait VmContext {
|
||||
fn split(&mut self) -> (&mut impl VmCode, &mut impl VmRuntimeCtx);
|
||||
}
|
||||
|
||||
pub trait VmRuntimeCtx {
|
||||
fn intern_string(&mut self, s: impl AsRef<str>) -> StringId;
|
||||
fn resolve_string(&self, id: StringId) -> &str;
|
||||
fn get_const(&self, id: u32) -> StaticValue;
|
||||
fn add_const(&mut self, val: StaticValue) -> u32;
|
||||
}
|
||||
|
||||
pub trait VmCode {
|
||||
fn bytecode(&self) -> &[u8];
|
||||
fn compile_with_scope(
|
||||
&mut self,
|
||||
source: Source,
|
||||
extra_scope: Option<ExtraScope>,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
) -> fix_error::Result<InstructionPtr>;
|
||||
}
|
||||
|
||||
pub trait VmRuntimeCtxExt: VmRuntimeCtx {
|
||||
fn get_string<'a, 'gc: 'a>(&'a self, val: StrictValue<'gc>) -> Option<&'a str>;
|
||||
fn get_string_or_path<'a, 'gc: 'a>(&'a self, val: StrictValue<'gc>) -> Option<&'a str>;
|
||||
fn get_string_id<'a, 'gc: 'a>(
|
||||
&'a mut self,
|
||||
val: StrictValue<'gc>,
|
||||
) -> std::result::Result<StringId, NixType>;
|
||||
/// Returns the string context attached to `val`, or `&[]` if `val` is
|
||||
/// either a non-string or a string without context.
|
||||
fn get_string_context<'gc>(&self, val: StrictValue<'gc>) -> &'gc StringContext;
|
||||
fn convert_value(&self, val: Value) -> fix_lang::Value;
|
||||
}
|
||||
|
||||
impl<T: VmRuntimeCtx> VmRuntimeCtxExt for T {
|
||||
fn get_string<'a, 'gc: 'a>(&'a self, val: StrictValue<'gc>) -> Option<&'a str> {
|
||||
if let Some(sid) = val.downcast::<StringId>() {
|
||||
Some(self.resolve_string(sid))
|
||||
} else {
|
||||
val.downcast::<NixString>().map(|ns| ns.as_ref().as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// Like `get_string`, but also accepts `Path` values (returning their
|
||||
/// underlying canonical-path string). Use this in places where Nix
|
||||
/// would coerce a path to a string (string interpolation, file IO
|
||||
/// builtins, etc.).
|
||||
fn get_string_or_path<'a, 'gc: 'a>(&'a self, val: StrictValue<'gc>) -> Option<&'a str> {
|
||||
if let Some(p) = val.downcast::<Path>() {
|
||||
Some(self.resolve_string(p.0))
|
||||
} else {
|
||||
self.get_string(val)
|
||||
}
|
||||
}
|
||||
|
||||
fn get_string_id<'a, 'gc: 'a>(
|
||||
&'a mut self,
|
||||
val: StrictValue<'gc>,
|
||||
) -> std::result::Result<StringId, NixType> {
|
||||
if let Some(sid) = val.downcast::<StringId>() {
|
||||
Ok(sid)
|
||||
} else if let Some(s) = val.downcast::<NixString>().map(|ns| ns.as_ref().as_str()) {
|
||||
Ok(self.intern_string(s))
|
||||
} else {
|
||||
Err(val.ty())
|
||||
}
|
||||
}
|
||||
|
||||
fn get_string_context<'gc>(&self, val: StrictValue<'gc>) -> &'gc StringContext {
|
||||
if let Some(ns) = val.downcast::<NixString>() {
|
||||
ns.as_ref().context()
|
||||
} else {
|
||||
StringContext::empty()
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_value(&self, val: Value) -> fix_lang::Value {
|
||||
self.convert_value_with_seen(val, &mut HashSet::new())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) trait ConvertValueWithSeen: VmRuntimeCtx {
|
||||
fn convert_value_with_seen(&self, val: Value, seen: &mut HashSet<u64>) -> fix_lang::Value;
|
||||
}
|
||||
|
||||
impl<T: VmRuntimeCtx> ConvertValueWithSeen for T {
|
||||
fn convert_value_with_seen(&self, val: Value, seen: &mut HashSet<u64>) -> fix_lang::Value {
|
||||
use fix_lang::Value;
|
||||
if let Some(i) = val.downcast::<i32>() {
|
||||
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>() {
|
||||
Value::Float(f)
|
||||
} else if let Some(b) = val.downcast::<bool>() {
|
||||
Value::Bool(b)
|
||||
} else if val.is::<Null>() {
|
||||
Value::Null
|
||||
} else if let Some(sid) = val.downcast::<StringId>() {
|
||||
let s = self.resolve_string(sid).to_owned();
|
||||
Value::String(s)
|
||||
} else if let Some(ns) = val.downcast::<NixString>() {
|
||||
Value::String(ns.as_str().to_owned())
|
||||
} else if let Some(p) = val.downcast::<Path>() {
|
||||
Value::Path(self.resolve_string(p.0).to_owned())
|
||||
} else if let Some(attrs) = val.downcast::<AttrSet>() {
|
||||
let bits = val.to_bits();
|
||||
if attrs.entries.is_empty() {
|
||||
return Value::AttrSet(Default::default());
|
||||
}
|
||||
if !seen.insert(bits) {
|
||||
return Value::Repeated;
|
||||
}
|
||||
let mut map = std::collections::BTreeMap::new();
|
||||
for &(key, val) in attrs.entries.iter() {
|
||||
let key = self.resolve_string(key).to_owned();
|
||||
let converted = self.convert_value_with_seen(val, seen);
|
||||
map.insert(fix_lang::Symbol::from(key), converted);
|
||||
}
|
||||
Value::AttrSet(fix_lang::AttrSet::new(map))
|
||||
} else if let Some(list) = val.downcast::<List>() {
|
||||
let bits = val.to_bits();
|
||||
if list.inner.borrow().is_empty() {
|
||||
return Value::List(Default::default());
|
||||
}
|
||||
if !seen.insert(bits) {
|
||||
return Value::Repeated;
|
||||
}
|
||||
let items: Vec<_> = list
|
||||
.inner
|
||||
.borrow()
|
||||
.iter()
|
||||
.copied()
|
||||
.map(|v| self.convert_value_with_seen(v, seen))
|
||||
.collect();
|
||||
Value::List(fix_lang::List::new(items))
|
||||
} else if val.is::<Closure>() {
|
||||
Value::Func
|
||||
} else if let Some(thunk) = val.downcast::<Thunk>() {
|
||||
if let ThunkState::Evaluated(v) = *thunk.borrow() {
|
||||
self.convert_value_with_seen(v.relax(), seen)
|
||||
} else {
|
||||
Value::Thunk
|
||||
}
|
||||
} else if let Some(primop) = val.downcast::<PrimOp>() {
|
||||
Value::PrimOp(primop.id.info().name)
|
||||
} else if let Some(app) = val.downcast::<PrimOpApp>() {
|
||||
Value::PrimOpApp(app.primop.id.info().name)
|
||||
} else {
|
||||
Value::Null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
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;
|
||||
|
||||
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::*;
|
||||
@@ -1,187 +0,0 @@
|
||||
use std::ops::ControlFlow;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use fix_error::Error;
|
||||
use fix_lang::{self, StringId};
|
||||
use gc_arena::{Gc, Mutation};
|
||||
|
||||
use crate::{
|
||||
AttrSet, Break, BytecodeReader, CallFrame, ForceMode, Forced, GcEnv, NixType, PendingLoad,
|
||||
Step, StrictValue, Value, VmError,
|
||||
};
|
||||
|
||||
/// Abstract VM-side operations consumed by instruction handlers and primops.
|
||||
///
|
||||
/// Implementors maintain a value stack, a call stack, an environment chain,
|
||||
/// pending result/error state, and a set of GC-allocated globals. Methods
|
||||
/// fall into a few groups:
|
||||
///
|
||||
/// - Stack ops (`push` / `pop` / `peek` / `replace` / `pop_forced` / ...)
|
||||
/// - Forcing primitives (`force_slot` / `force_slot_to_pc`)
|
||||
/// - Calling (`call` / `return_from_primop`)
|
||||
/// - Call-frame management (`push_call_frame` / `pop_call_frame` / call-depth)
|
||||
/// - Environment access (`env` / `set_env` / `local`)
|
||||
/// - Result finalization (`finish_ok` / `finish_err` / ...)
|
||||
/// - Global lookup (`builtins` / `empty_list` / `empty_attrs` / ...)
|
||||
/// - Imports and scope slots (`import_cache_*` / `scope_slot*` / `set_pending_load`)
|
||||
pub trait Machine<'gc> {
|
||||
fn push(&mut self, val: Value<'gc>);
|
||||
#[must_use]
|
||||
fn pop(&mut self) -> Value<'gc>;
|
||||
#[must_use]
|
||||
fn peek(&self, depth: usize) -> Value<'gc>;
|
||||
#[must_use]
|
||||
fn peek_forced(&self, depth: usize) -> StrictValue<'gc>;
|
||||
fn pop_forced(&mut self) -> StrictValue<'gc>;
|
||||
fn replace(&mut self, depth: usize, val: Value<'gc>);
|
||||
fn drop_n(&mut self, depth: usize);
|
||||
fn stack_len(&self) -> usize;
|
||||
|
||||
fn force_slot_to_pc(
|
||||
&mut self,
|
||||
depth: usize,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
resume_pc: usize,
|
||||
) -> Step;
|
||||
|
||||
#[inline(always)]
|
||||
fn force_slot(
|
||||
&mut self,
|
||||
depth: usize,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let pc = reader.inst_start_pc();
|
||||
self.force_slot_to_pc(depth, reader, mc, pc)
|
||||
}
|
||||
|
||||
fn call(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
arg: Value<'gc>,
|
||||
resume_pc: usize,
|
||||
) -> 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!()
|
||||
};
|
||||
reader.set_pc(ret_pc);
|
||||
self.dec_call_depth();
|
||||
self.set_env(env);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
fn push_call_frame(&mut self, frame: CallFrame<'gc>);
|
||||
fn pop_call_frame(&mut self) -> Option<CallFrame<'gc>>;
|
||||
fn call_depth(&self) -> usize;
|
||||
fn inc_call_depth(&mut self);
|
||||
fn dec_call_depth(&mut self);
|
||||
|
||||
fn env(&self) -> GcEnv<'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 {
|
||||
let prev = cur.borrow().prev.expect("env chain too short");
|
||||
cur = prev;
|
||||
}
|
||||
cur.borrow().locals[idx as usize]
|
||||
}
|
||||
|
||||
fn finish_ok(&mut self, val: fix_lang::Value) -> Step;
|
||||
fn finish_err(&mut self, err: Box<Error>) -> Step;
|
||||
fn finish_type_err(&mut self, expected: NixType, got: NixType) -> Step;
|
||||
|
||||
#[inline(always)]
|
||||
fn finish_vm_err(&mut self, err: VmError) -> Step {
|
||||
self.finish_err(err.into_error())
|
||||
}
|
||||
|
||||
fn builtins(&self) -> Gc<'gc, AttrSet<'gc>>;
|
||||
fn functor_sym(&self) -> StringId;
|
||||
fn empty_list(&self) -> Value<'gc>;
|
||||
fn empty_attrs(&self) -> Value<'gc>;
|
||||
fn force_mode(&self) -> ForceMode;
|
||||
|
||||
fn import_cache_get(&self, path: &Path) -> Option<Value<'gc>>;
|
||||
fn import_cache_insert(&mut self, path: PathBuf, val: Value<'gc>);
|
||||
fn scope_slot(&self, idx: u32) -> Value<'gc>;
|
||||
fn scope_slots_push(&mut self, val: Value<'gc>) -> u32;
|
||||
fn set_pending_load(&mut self, load: PendingLoad);
|
||||
}
|
||||
|
||||
/// Extension trait with convenience helpers built on top of [`Machine`].
|
||||
///
|
||||
/// Auto-implemented for every `Machine<'gc>` so callers just need to bring
|
||||
/// `MachineExt` (or `Machine`) into scope.
|
||||
pub trait MachineExt<'gc>: Machine<'gc> {
|
||||
/// Force the top `T::WIDTH` stack slots and return them as `T`.
|
||||
///
|
||||
/// If any slot holds a pending thunk, this method pushes a call frame
|
||||
/// whose resume PC is the **start of the current instruction**
|
||||
/// (`reader.inst_start_pc()`), enters the thunk, and returns
|
||||
/// `Break::Force`. When the thunk eventually returns, the VM will
|
||||
/// **re-execute the entire opcode handler from the beginning**.
|
||||
///
|
||||
/// # Invariants
|
||||
///
|
||||
/// * **Do not call this method more than once in a single handler.**
|
||||
/// If you need to force multiple values, use a tuple type such as
|
||||
/// `(StrictValue, StrictValue)` so they are forced and popped in one
|
||||
/// atomic operation.
|
||||
/// * The stack layout at the call site must be **identical** every time
|
||||
/// the handler is re-entered.
|
||||
/// * Propagate the return value with `?` so `Break::Force` correctly
|
||||
/// unwinds to the dispatch loop.
|
||||
#[inline(always)]
|
||||
fn force_and_retry<T: Forced<'gc>>(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> ControlFlow<Break, T>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
let pc = reader.inst_start_pc();
|
||||
self.force_and_retry_pc(reader, mc, pc)
|
||||
}
|
||||
|
||||
/// Same as [`force_and_retry`](Self::force_and_retry) but allows
|
||||
/// specifying a custom resume PC.
|
||||
#[inline(always)]
|
||||
fn force_and_retry_pc<T: Forced<'gc>>(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
resume_pc: usize,
|
||||
) -> ControlFlow<Break, T>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
T::force_and_check(self, reader, mc, 0, resume_pc)?;
|
||||
ControlFlow::Continue(T::pop_converted(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc, M: Machine<'gc>> MachineExt<'gc> for M {}
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
use std::path::{Component, PathBuf};
|
||||
|
||||
pub fn canon_path_str(path: impl AsRef<std::path::Path>) -> String {
|
||||
let p = path.as_ref();
|
||||
let mut normalized = PathBuf::new();
|
||||
for component in p.components() {
|
||||
match component {
|
||||
Component::Prefix(p) => normalized.push(p.as_os_str()),
|
||||
Component::RootDir => normalized.push("/"),
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
normalized.pop();
|
||||
}
|
||||
Component::Normal(c) => normalized.push(c),
|
||||
}
|
||||
}
|
||||
normalized.to_string_lossy().into_owned()
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
use fix_bytecode::OperandData;
|
||||
use gc_arena::{Gc, Mutation};
|
||||
|
||||
use crate::{AttrSet, Machine, Value, VmRuntimeCtx};
|
||||
|
||||
/// Resolve a decoded operand into a runtime [`Value`].
|
||||
///
|
||||
/// The operand decoder ([`crate::BytecodeReader::read_operand_data`])
|
||||
/// produces a static enum; this function materializes it against the
|
||||
/// running [`Machine`] (env chain, builtins, scope slots, ...).
|
||||
#[inline]
|
||||
pub fn resolve_operand<'gc, M: Machine<'gc>>(
|
||||
op: &OperandData,
|
||||
mc: &Mutation<'gc>,
|
||||
ctx: &impl VmRuntimeCtx,
|
||||
m: &M,
|
||||
) -> Value<'gc> {
|
||||
use OperandData::*;
|
||||
match *op {
|
||||
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(),
|
||||
ReplBinding(_id) => todo!(),
|
||||
ScopedImportBinding { slot_id, name } => {
|
||||
let scope = m.scope_slot(slot_id);
|
||||
let attrs = scope.downcast::<AttrSet>().expect("scope must be attrset");
|
||||
attrs.lookup(name).expect("scoped binding not found")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
use std::ops::ControlFlow;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use fix_error::Error;
|
||||
use fix_lang::StringId;
|
||||
use gc_arena::{Collect, Gc};
|
||||
use hashbrown::HashSet;
|
||||
|
||||
use crate::{GcEnv, Thunk};
|
||||
|
||||
pub enum VmError {
|
||||
Catchable(String),
|
||||
Uncatchable(Box<Error>),
|
||||
}
|
||||
|
||||
impl From<Box<Error>> for VmError {
|
||||
fn from(e: Box<Error>) -> Self {
|
||||
VmError::Uncatchable(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl VmError {
|
||||
pub fn into_error(self) -> Box<Error> {
|
||||
match self {
|
||||
VmError::Catchable(_) => todo!("Check for tryEval catch frames"),
|
||||
VmError::Uncatchable(e) => e,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn vm_err(msg: impl Into<String>) -> VmError {
|
||||
VmError::Uncatchable(Error::eval_error(msg.into()))
|
||||
}
|
||||
|
||||
#[derive(Collect, Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
#[collect(require_static)]
|
||||
pub enum ForceMode {
|
||||
#[default]
|
||||
AsIs,
|
||||
Shallow,
|
||||
Deep,
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
pub enum Break {
|
||||
Force,
|
||||
Done,
|
||||
LoadFile,
|
||||
}
|
||||
|
||||
pub type Step = ControlFlow<Break>;
|
||||
|
||||
pub struct ErrorFrame {
|
||||
pub span_id: u32,
|
||||
pub message: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Collect, Debug)]
|
||||
#[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>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PendingLoad {
|
||||
pub path: PathBuf,
|
||||
pub scope: Option<PendingScope>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PendingScope {
|
||||
pub keys: HashSet<StringId>,
|
||||
pub slot_id: u32,
|
||||
}
|
||||
|
||||
/// Extra scope passed to a re-entrant compile from inside a running VM.
|
||||
///
|
||||
/// Currently only `ScopedImport` is produced (by the `scopedImport` builtin),
|
||||
/// but the variant is kept open so REPL bindings could later land here too.
|
||||
pub enum ExtraScope {
|
||||
ScopedImport {
|
||||
keys: HashSet<StringId>,
|
||||
slot_id: u32,
|
||||
},
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
use std::cmp::Ordering;
|
||||
|
||||
use smallvec::SmallVec;
|
||||
|
||||
/// A string context element
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum StringContextElem {
|
||||
// Plain store path reference
|
||||
Opaque {
|
||||
path: Box<str>,
|
||||
},
|
||||
// All outputs of a derivation
|
||||
// encoded `=<drvPath>`
|
||||
DrvDeep {
|
||||
drv_path: Box<str>,
|
||||
},
|
||||
// A specific output of a derivation
|
||||
// encoded `!<output>!<drvPath>`
|
||||
Built {
|
||||
drv_path: Box<str>,
|
||||
output: Box<str>,
|
||||
},
|
||||
}
|
||||
|
||||
impl StringContextElem {
|
||||
/// Decode the CppNix wire form (`!out!/p`, `=/p`, `/p`). Falls back to
|
||||
/// `Opaque` for malformed `!`-prefixed inputs (matching nix-js).
|
||||
pub fn decode(encoded: &str) -> Self {
|
||||
if let Some(drv_path) = encoded.strip_prefix('=') {
|
||||
Self::DrvDeep {
|
||||
drv_path: drv_path.into(),
|
||||
}
|
||||
} else if let Some(rest) = encoded.strip_prefix('!') {
|
||||
if let Some((output, drv_path)) = rest.split_once('!') {
|
||||
Self::Built {
|
||||
output: output.into(),
|
||||
drv_path: drv_path.into(),
|
||||
}
|
||||
} else {
|
||||
Self::Opaque {
|
||||
path: encoded.into(),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Self::Opaque {
|
||||
path: encoded.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encode(&self) -> String {
|
||||
match self {
|
||||
Self::Opaque { path } => path.to_string(),
|
||||
Self::DrvDeep { drv_path } => format!("={drv_path}"),
|
||||
Self::Built { drv_path, output } => format!("!{output}!{drv_path}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct StringContext {
|
||||
data: SmallVec<[StringContextElem; 1]>,
|
||||
}
|
||||
|
||||
impl IntoIterator for StringContext {
|
||||
type Item = StringContextElem;
|
||||
type IntoIter = <SmallVec<[StringContextElem; 1]> as IntoIterator>::IntoIter;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.data.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoIterator for &'a StringContext {
|
||||
type Item = &'a StringContextElem;
|
||||
type IntoIter = <&'a SmallVec<[StringContextElem; 1]> as IntoIterator>::IntoIter;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.data.iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoIterator for &'a mut StringContext {
|
||||
type Item = &'a mut StringContextElem;
|
||||
type IntoIter = <&'a mut SmallVec<[StringContextElem; 1]> as IntoIterator>::IntoIter;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.data.iter_mut()
|
||||
}
|
||||
}
|
||||
|
||||
impl FromIterator<StringContextElem> for StringContext {
|
||||
fn from_iter<T: IntoIterator<Item = StringContextElem>>(iter: T) -> Self {
|
||||
Self {
|
||||
data: iter.into_iter().collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StringContext {
|
||||
pub fn empty() -> &'static Self {
|
||||
static EMPTY: StringContext = StringContext {
|
||||
data: SmallVec::new_const(),
|
||||
};
|
||||
&EMPTY
|
||||
}
|
||||
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.data.is_empty()
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, elem: StringContextElem) {
|
||||
match self.data.binary_search(&elem) {
|
||||
Ok(_) => {}
|
||||
Err(pos) => self.data.insert(pos, elem),
|
||||
}
|
||||
}
|
||||
|
||||
#[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();
|
||||
}
|
||||
if other.data.is_empty() {
|
||||
return self.clone();
|
||||
}
|
||||
|
||||
let a = &self.data;
|
||||
let b = &other.data;
|
||||
let mut out = SmallVec::with_capacity(a.len() + b.len());
|
||||
let (mut i, mut j) = (0, 0);
|
||||
while i < a.len() && j < b.len() {
|
||||
match a[i].cmp(&b[j]) {
|
||||
Ordering::Less => {
|
||||
out.push(a[i].clone());
|
||||
i += 1;
|
||||
}
|
||||
Ordering::Greater => {
|
||||
out.push(b[j].clone());
|
||||
j += 1;
|
||||
}
|
||||
Ordering::Equal => {
|
||||
out.push(a[i].clone());
|
||||
i += 1;
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.extend(a[i..].iter().cloned());
|
||||
out.extend(b[j..].iter().cloned());
|
||||
Self { data: out }
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> <&Self as IntoIterator>::IntoIter {
|
||||
self.into_iter()
|
||||
}
|
||||
|
||||
pub fn iter_mut(&mut self) -> <&mut Self as IntoIterator>::IntoIter {
|
||||
self.into_iter()
|
||||
}
|
||||
}
|
||||
@@ -1,783 +0,0 @@
|
||||
use std::cell::RefCell;
|
||||
use std::fmt;
|
||||
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};
|
||||
use smallvec::SmallVec;
|
||||
use string_interner::Symbol;
|
||||
use string_interner::symbol::SymbolU32;
|
||||
|
||||
use crate::boxing::{RawBox, RawStore, RawTag, Value as RawValue};
|
||||
use crate::string_context::StringContext;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
trait Storable<'gc>: TryFrom<Value<'gc>> + Into<Value<'gc>> + private::Cealed + 'gc {
|
||||
fn is(raw: &RawBox) -> bool;
|
||||
|
||||
fn to_raw_box(self) -> RawBox;
|
||||
/// # Safety
|
||||
///
|
||||
/// `raw` must represent a valid `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;)* }
|
||||
) => {
|
||||
$(
|
||||
impl Storable<'_> for $itype {
|
||||
#[inline(always)]
|
||||
fn is(value: &RawBox) -> bool {
|
||||
value.tag() == Some($itag)
|
||||
}
|
||||
#[inline(always)]
|
||||
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 { <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<'gc> Storable<'gc> for Gc<'gc, unelide_lifetimes!('gc; $gtype)> {
|
||||
#[inline(always)]
|
||||
fn is(value: &RawBox) -> bool {
|
||||
value.tag() == Some($gtag)
|
||||
}
|
||||
#[inline(always)]
|
||||
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 { 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;
|
||||
}
|
||||
)*
|
||||
|
||||
const _: () = assert!(size_of::<Value<'static>>() == 8);
|
||||
$(const _: () = assert!(size_of::<$itype>() <= 6);)*
|
||||
|
||||
const _: () = {
|
||||
let tags: &[(bool, u8)] = &[$(RawTag::neg_val($itag)),*, $(RawTag::neg_val($gtag)),*];
|
||||
let mut mask_false: u8 = 0;
|
||||
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 {
|
||||
assert!(mask_true & bit == 0, "duplicate true tag id");
|
||||
mask_true |= bit;
|
||||
} else {
|
||||
assert!(mask_false & bit == 0, "duplicate false tag id");
|
||||
mask_false |= bit;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
};
|
||||
|
||||
// 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 => (),)*
|
||||
_ => unreachable!("invalid value tag"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}),)*
|
||||
$(Some($gtag) =>
|
||||
write!(f, "{}(..)", $gname),)*
|
||||
_ => unreachable!("invalid value tag"),
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
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";
|
||||
}
|
||||
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";
|
||||
}
|
||||
}
|
||||
|
||||
impl private::Cealed for f64 {}
|
||||
|
||||
impl Storable<'_> for f64 {
|
||||
#[inline(always)]
|
||||
fn is(value: &RawBox) -> bool {
|
||||
value.is_float()
|
||||
}
|
||||
#[inline(always)]
|
||||
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 { 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<'gc, T: Storable<'gc>> From<T> for Value<'gc> {
|
||||
fn from(value: T) -> Self {
|
||||
Value::new(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// # Nix runtime value representation
|
||||
///
|
||||
/// NaN-boxed value fitting in 8 bytes.
|
||||
#[derive(Copy, Clone)]
|
||||
#[repr(transparent)]
|
||||
pub struct Value<'gc> {
|
||||
raw: RawBox,
|
||||
_marker: PhantomData<Gc<'gc, ()>>,
|
||||
}
|
||||
|
||||
impl Default for Value<'_> {
|
||||
#[inline(always)]
|
||||
fn default() -> Self {
|
||||
Self::new(Null)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc> Value<'gc> {
|
||||
#[inline(always)]
|
||||
const fn tag(self) -> Option<RawTag> {
|
||||
self.raw.tag()
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
Self {
|
||||
raw: val.to_raw_box(),
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn make_int(val: i64, mc: &Mutation<'gc>) -> Self {
|
||||
if val >= i32::MIN as i64 && val <= i32::MAX as i64 {
|
||||
Value::new(val as i32)
|
||||
} else {
|
||||
Value::new(Gc::new(mc, val))
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is<T: ValueVariant<'gc>>(self) -> bool {
|
||||
T::Ty::is(&self.raw)
|
||||
}
|
||||
|
||||
#[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) })
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_bits(self) -> u64 {
|
||||
self.raw.to_bits()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn downcast_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)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn restrict(self) -> Result<StrictValue<'gc>, Gc<'gc, Thunk<'gc>>> {
|
||||
if let Some(thunk) = self.downcast::<Thunk>() {
|
||||
Err(thunk)
|
||||
} else {
|
||||
Ok(StrictValue(self))
|
||||
}
|
||||
}
|
||||
|
||||
#[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>() {
|
||||
NixType::Float
|
||||
} else if self.is::<i32>() || self.is::<i64>() {
|
||||
NixType::Int
|
||||
} else if self.is::<bool>() {
|
||||
NixType::Bool
|
||||
} else if self.is::<Null>() {
|
||||
NixType::Null
|
||||
} else if self.is::<StringId>() {
|
||||
NixType::String
|
||||
} else if self.is::<PrimOp>() {
|
||||
NixType::PrimOp
|
||||
} else if self.is::<NixString>() {
|
||||
NixType::String
|
||||
} else if self.is::<Path>() {
|
||||
NixType::Path
|
||||
} else if self.is::<AttrSet>() {
|
||||
NixType::AttrSet
|
||||
} else if self.is::<List>() {
|
||||
NixType::List
|
||||
} else if self.is::<Thunk>() {
|
||||
NixType::Thunk
|
||||
} else if self.is::<Closure>() {
|
||||
NixType::Closure
|
||||
} else if self.is::<PrimOpApp>() {
|
||||
NixType::PrimOpApp
|
||||
} else {
|
||||
unreachable!("value has no recognized type tag")
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn expect<T: ValueVariant<'gc>>(self) -> Result<T::Ty, 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())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Default)]
|
||||
#[repr(transparent)]
|
||||
pub struct StaticValue(Value<'static>);
|
||||
|
||||
impl<'gc> From<StaticValue> for Value<'gc> {
|
||||
#[inline]
|
||||
fn from(value: StaticValue) -> Self {
|
||||
// SAFETY: StaticValue is guaranteed to not contain any `Gc`.
|
||||
unsafe { std::mem::transmute::<Value<'static>, Value<'gc>>(value.0) }
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
Self(Value::new(val))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is<T: ValueVariant<'static>>(self) -> bool {
|
||||
self.0.is::<T>()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn downcast<T: ValueVariant<'static>>(self) -> Option<T::Ty> {
|
||||
self.0.downcast::<T>()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn to_bits(self) -> u64 {
|
||||
self.0.raw.to_bits()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Null;
|
||||
impl RawStore for Null {
|
||||
fn to_val(self, value: &mut RawValue) {
|
||||
value.set_data([0; 6]);
|
||||
}
|
||||
fn from_val(_: &RawValue) -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl RawStore for StringId {
|
||||
fn to_val(self, value: &mut RawValue) {
|
||||
(self.0.to_usize() as u32).to_val(value);
|
||||
}
|
||||
fn from_val(value: &RawValue) -> Self {
|
||||
Self(
|
||||
SymbolU32::try_from_usize(u32::from_val(value) as usize)
|
||||
.expect("failed to read StringId from Value"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A canonicalized absolute path. Inline value carrying an interned
|
||||
/// `StringId` whose contents are the path's absolute, dot-resolved form.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Path(pub StringId);
|
||||
|
||||
impl RawStore for Path {
|
||||
fn to_val(self, value: &mut RawValue) {
|
||||
self.0.to_val(value);
|
||||
}
|
||||
fn from_val(value: &RawValue) -> Self {
|
||||
Self(StringId::from_val(value))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Collect)]
|
||||
#[collect(require_static)]
|
||||
pub struct NixString {
|
||||
data: Box<str>,
|
||||
context: StringContext,
|
||||
}
|
||||
|
||||
impl NixString {
|
||||
pub fn new(s: impl Into<Box<str>>) -> Self {
|
||||
Self {
|
||||
data: s.into(),
|
||||
context: StringContext::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct a `NixString` whose `context` is already sorted+deduped.
|
||||
/// The caller is responsible for invariant maintenance.
|
||||
pub fn with_context(s: impl Into<Box<str>>, context: StringContext) -> Self {
|
||||
Self {
|
||||
data: s.into(),
|
||||
context,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.data
|
||||
}
|
||||
|
||||
pub fn context(&self) -> &StringContext {
|
||||
&self.context
|
||||
}
|
||||
|
||||
pub fn has_context(&self) -> bool {
|
||||
!self.context.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for NixString {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
fmt::Debug::fmt(&self.data, f)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Collect, Debug, Default)]
|
||||
#[collect(no_drop)]
|
||||
pub struct AttrSet<'gc> {
|
||||
pub entries: SmallVec<[(StringId, Value<'gc>); 4]>,
|
||||
}
|
||||
|
||||
impl<'gc> AttrSet<'gc> {
|
||||
pub fn from_sorted_unchecked(entries: SmallVec<[(StringId, Value<'gc>); 4]>) -> Self {
|
||||
debug_assert!(entries.is_sorted_by_key(|(key, _)| *key));
|
||||
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)
|
||||
.ok()
|
||||
.map(|i| self.entries[i].1)
|
||||
}
|
||||
|
||||
pub fn has(&self, key: StringId) -> bool {
|
||||
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::*;
|
||||
|
||||
debug_assert!(self.entries.is_sorted_by_key(|(key, _)| *key));
|
||||
debug_assert!(other.entries.is_sorted_by_key(|(key, _)| *key));
|
||||
|
||||
let mut entries = SmallVec::new();
|
||||
let mut i = 0;
|
||||
let mut j = 0;
|
||||
while i < self.entries.len() && j < other.entries.len() {
|
||||
match self.entries[i].0.cmp(&other.entries[j].0) {
|
||||
Less => {
|
||||
entries.push(self.entries[i]);
|
||||
i += 1;
|
||||
}
|
||||
Greater => {
|
||||
entries.push(other.entries[j]);
|
||||
j += 1;
|
||||
}
|
||||
Equal => {
|
||||
entries.push(other.entries[j]);
|
||||
i += 1;
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
entries.extend(other.entries[j..].iter().cloned());
|
||||
entries.extend(self.entries[i..].iter().cloned());
|
||||
|
||||
debug_assert!(entries.is_sorted_by_key(|(key, _)| *key));
|
||||
|
||||
Gc::new(mc, AttrSet { entries })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Collect, Debug, Default)]
|
||||
#[repr(transparent)]
|
||||
#[collect(no_drop)]
|
||||
pub struct List<'gc> {
|
||||
pub inner: RefLock<SmallVec<[Value<'gc>; 4]>>,
|
||||
}
|
||||
|
||||
impl<'gc> List<'gc> {
|
||||
pub fn new(mc: &Mutation<'gc>, data: SmallVec<[Value<'gc>; 4]>) -> Gc<'gc, Self> {
|
||||
Gc::new(
|
||||
mc,
|
||||
Self {
|
||||
inner: RefLock::new(data),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn new_gc(mc: &Mutation<'gc>) -> Gc<'gc, Self> {
|
||||
Gc::new(mc, Self::default())
|
||||
}
|
||||
}
|
||||
|
||||
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() }
|
||||
}
|
||||
}
|
||||
|
||||
pub type Thunk<'gc> = RefLock<ThunkState<'gc>>;
|
||||
|
||||
#[derive(Collect, Debug)]
|
||||
#[collect(no_drop)]
|
||||
pub enum ThunkState<'gc> {
|
||||
Pending { ip: usize, env: GcEnv<'gc> },
|
||||
Apply { func: Value<'gc>, arg: Value<'gc> },
|
||||
Blackhole,
|
||||
Evaluated(StrictValue<'gc>),
|
||||
}
|
||||
|
||||
#[derive(Collect, Debug)]
|
||||
#[collect(no_drop)]
|
||||
pub struct Env<'gc> {
|
||||
pub locals: SmallVec<[Value<'gc>; 4]>,
|
||||
pub prev: Option<GcEnv<'gc>>,
|
||||
}
|
||||
pub type GcEnv<'gc> = GcRefLock<'gc, Env<'gc>>;
|
||||
|
||||
impl<'gc> Env<'gc> {
|
||||
pub fn empty() -> Self {
|
||||
Env {
|
||||
locals: SmallVec::new(),
|
||||
prev: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[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;
|
||||
Env {
|
||||
locals,
|
||||
prev: Some(prev),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Collect, Debug)]
|
||||
#[collect(no_drop)]
|
||||
pub struct Closure<'gc> {
|
||||
pub ip: u32,
|
||||
pub n_locals: u32,
|
||||
pub env: Gc<'gc, RefLock<Env<'gc>>>,
|
||||
pub pattern: Option<Gc<'gc, PatternInfo>>,
|
||||
}
|
||||
|
||||
#[derive(Collect, Debug)]
|
||||
#[collect(require_static)]
|
||||
pub struct PatternInfo {
|
||||
pub required: SmallVec<[StringId; 4]>,
|
||||
pub optional: SmallVec<[StringId; 4]>,
|
||||
pub ellipsis: bool,
|
||||
pub param_spans: Box<[(StringId, u32)]>,
|
||||
}
|
||||
|
||||
#[repr(packed, Rust)]
|
||||
#[derive(Clone, Copy, Debug, Collect)]
|
||||
#[collect(require_static)]
|
||||
pub struct PrimOp {
|
||||
pub id: BuiltinId,
|
||||
pub arity: u8,
|
||||
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();
|
||||
value.set_data([
|
||||
self.id as u8,
|
||||
self.arity,
|
||||
bytes[0],
|
||||
bytes[1],
|
||||
bytes[2],
|
||||
bytes[3],
|
||||
]);
|
||||
}
|
||||
fn from_val(value: &RawValue) -> Self {
|
||||
let [id, arity, bytes @ ..] = *value.data();
|
||||
Self {
|
||||
id: BuiltinId::try_from(id).expect("invalid BuiltinId"),
|
||||
arity,
|
||||
dispatch_ip: u32::from_le_bytes(bytes),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Collect, Debug)]
|
||||
#[collect(no_drop)]
|
||||
pub struct PrimOpApp<'gc> {
|
||||
pub primop: PrimOp,
|
||||
pub arity: u8,
|
||||
pub args: [Value<'gc>; 3],
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Default, Collect)]
|
||||
#[repr(transparent)]
|
||||
#[collect(no_drop)]
|
||||
pub struct StrictValue<'gc>(Value<'gc>);
|
||||
|
||||
impl<'gc> StrictValue<'gc> {
|
||||
#[inline]
|
||||
pub fn relax(self) -> Value<'gc> {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc> Deref for StrictValue<'gc> {
|
||||
type Target = Value<'gc>;
|
||||
#[inline]
|
||||
fn deref(&self) -> &Value<'gc> {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Collect)]
|
||||
#[collect(require_static)]
|
||||
pub enum NixType {
|
||||
Int,
|
||||
Float,
|
||||
Bool,
|
||||
Null,
|
||||
String,
|
||||
Path,
|
||||
AttrSet,
|
||||
List,
|
||||
Thunk,
|
||||
Closure,
|
||||
PrimOp,
|
||||
PrimOpApp,
|
||||
}
|
||||
|
||||
impl NixType {
|
||||
pub fn display(self) -> &'static str {
|
||||
use NixType::*;
|
||||
match self {
|
||||
Int => "an integer",
|
||||
Float => "a float",
|
||||
Bool => "a boolean",
|
||||
Null => "null",
|
||||
String => "a string",
|
||||
Path => "a path",
|
||||
AttrSet => "a set",
|
||||
List => "a list",
|
||||
Thunk => "a thunk",
|
||||
Closure => "a function",
|
||||
PrimOp => "a built-in function",
|
||||
PrimOpApp => "a partially applied built-in function",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for NixType {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.display())
|
||||
}
|
||||
}
|
||||
|
||||
pub enum NixNum {
|
||||
Int(i64),
|
||||
Float(f64),
|
||||
}
|
||||
+13
-14
@@ -3,20 +3,19 @@ name = "fix-vm"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
gc-arena = { workspace = true }
|
||||
hashbrown = { workspace = true }
|
||||
smallvec = { workspace = true }
|
||||
sysinfo = { version = "0.39", 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
|
||||
[dependencies]
|
||||
gc-arena = { workspace = true }
|
||||
hashbrown = { workspace = true }
|
||||
num_enum = { workspace = true }
|
||||
smallvec = { workspace = true }
|
||||
string-interner = { workspace = true }
|
||||
likely_stable = { workspace = true }
|
||||
sptr = "0.3"
|
||||
|
||||
fix-builtins = { path = "../fix-builtins" }
|
||||
fix-codegen = { path = "../fix-codegen" }
|
||||
fix-common = { path = "../fix-common" }
|
||||
fix-error = { path = "../fix-error" }
|
||||
|
||||
@@ -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;
|
||||
@@ -27,7 +24,7 @@ impl<T: Default + Copy, const N: usize> ArrayExt<N> for [T; N] {
|
||||
}
|
||||
}
|
||||
|
||||
pub trait RawStore: Sized {
|
||||
pub(crate) trait RawStore: Sized {
|
||||
fn to_val(self, value: &mut Value);
|
||||
fn from_val(value: &Value) -> Self;
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,32 +157,28 @@ enum TagVal {
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq)]
|
||||
pub struct RawTag(TagVal);
|
||||
pub(crate) struct RawTag(TagVal);
|
||||
|
||||
impl RawTag {
|
||||
pub const P1: RawTag = RawTag(TagVal::_P1);
|
||||
pub const P2: RawTag = RawTag(TagVal::_P2);
|
||||
pub const P3: RawTag = RawTag(TagVal::_P3);
|
||||
pub const P4: RawTag = RawTag(TagVal::_P4);
|
||||
pub const P5: RawTag = RawTag(TagVal::_P5);
|
||||
pub const P6: RawTag = RawTag(TagVal::_P6);
|
||||
pub const P7: RawTag = RawTag(TagVal::_P7);
|
||||
pub(crate) const P1: RawTag = RawTag(TagVal::_P1);
|
||||
pub(crate) const P2: RawTag = RawTag(TagVal::_P2);
|
||||
pub(crate) const P3: RawTag = RawTag(TagVal::_P3);
|
||||
pub(crate) const P4: RawTag = RawTag(TagVal::_P4);
|
||||
pub(crate) const P5: RawTag = RawTag(TagVal::_P5);
|
||||
pub(crate) const P6: RawTag = RawTag(TagVal::_P6);
|
||||
pub(crate) const P7: RawTag = RawTag(TagVal::_P7);
|
||||
|
||||
pub const N1: RawTag = RawTag(TagVal::_N1);
|
||||
pub const N2: RawTag = RawTag(TagVal::_N2);
|
||||
pub const N3: RawTag = RawTag(TagVal::_N3);
|
||||
pub const N4: RawTag = RawTag(TagVal::_N4);
|
||||
pub const N5: RawTag = RawTag(TagVal::_N5);
|
||||
pub const N6: RawTag = RawTag(TagVal::_N6);
|
||||
pub const N7: RawTag = RawTag(TagVal::_N7);
|
||||
pub(crate) const N1: RawTag = RawTag(TagVal::_N1);
|
||||
pub(crate) const N2: RawTag = RawTag(TagVal::_N2);
|
||||
pub(crate) const N3: RawTag = RawTag(TagVal::_N3);
|
||||
pub(crate) const N4: RawTag = RawTag(TagVal::_N4);
|
||||
pub(crate) const N5: RawTag = RawTag(TagVal::_N5);
|
||||
pub(crate) const N6: RawTag = RawTag(TagVal::_N6);
|
||||
pub(crate) const N7: RawTag = RawTag(TagVal::_N7);
|
||||
|
||||
#[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() },
|
||||
})
|
||||
}
|
||||
@@ -277,7 +260,7 @@ impl RawTag {
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub const fn neg_val(self) -> (bool, u8) {
|
||||
pub(crate) const fn neg_val(self) -> (bool, u8) {
|
||||
match self.0 {
|
||||
TagVal::_P1 => (false, 1),
|
||||
TagVal::_P2 => (false, 2),
|
||||
@@ -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()) }
|
||||
}
|
||||
|
||||
@@ -394,7 +373,7 @@ impl Value {
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn data(&self) -> &[u8; 6] {
|
||||
pub(crate) fn data(&self) -> &[u8; 6] {
|
||||
&self.data
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
use fix_codegen::OperandType;
|
||||
use fix_common::StringId;
|
||||
use num_enum::TryFromPrimitive;
|
||||
use string_interner::Symbol as _;
|
||||
|
||||
use crate::{OperandData, VmRuntimeCtx};
|
||||
|
||||
pub(crate) struct BytecodeReader<'a> {
|
||||
bytecode: &'a [u8],
|
||||
pc: usize,
|
||||
inst_start_pc: usize,
|
||||
}
|
||||
|
||||
impl<'a> BytecodeReader<'a> {
|
||||
#[cfg_attr(feature = "tailcall", allow(dead_code))]
|
||||
pub(crate) fn new(bytecode: &'a [u8], pc: usize) -> Self {
|
||||
Self {
|
||||
bytecode,
|
||||
pc,
|
||||
inst_start_pc: pc,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
#[cfg_attr(not(feature = "tailcall"), allow(dead_code))]
|
||||
pub(crate) fn from_after_op(bytecode: &'a [u8], inst_start_pc: usize) -> Self {
|
||||
Self {
|
||||
bytecode,
|
||||
pc: inst_start_pc + 1,
|
||||
inst_start_pc,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
#[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
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
#[cfg_attr(feature = "tailcall", allow(dead_code))]
|
||||
pub(crate) fn read_op(&mut self) -> fix_codegen::Op {
|
||||
use fix_codegen::Op;
|
||||
self.inst_start_pc = self.pc;
|
||||
let byte = self.bytecode[self.pc];
|
||||
if !likely_stable::likely((0..Op::Illegal as u8).contains(&byte)) {
|
||||
panic!("unknown opcode: {byte:#04x}")
|
||||
}
|
||||
self.pc += 1;
|
||||
unsafe { std::mem::transmute::<u8, Op>(byte) }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn read_u8(&mut self) -> u8 {
|
||||
let val = self.bytecode[self.pc];
|
||||
self.pc += 1;
|
||||
val
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn read_u16(&mut self) -> u16 {
|
||||
u16::from_le_bytes(self.read_array())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn read_u32(&mut self) -> u32 {
|
||||
u32::from_le_bytes(self.read_array())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn read_i32(&mut self) -> i32 {
|
||||
i32::from_le_bytes(self.read_array())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn read_i64(&mut self) -> i64 {
|
||||
i64::from_le_bytes(self.read_array())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn read_f64(&mut self) -> f64 {
|
||||
f64::from_le_bytes(self.read_array())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) 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(crate) fn read_operand_data<C: VmRuntimeCtx>(&mut self, ctx: &C) -> 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 => {
|
||||
let id = self.read_u32();
|
||||
OperandData::Const(ctx.get_const(id))
|
||||
}
|
||||
OperandType::BigInt => {
|
||||
let val = self.read_i64();
|
||||
OperandData::BigInt(val)
|
||||
}
|
||||
OperandType::Local => {
|
||||
let layer = self.read_u8();
|
||||
let idx = self.read_u32();
|
||||
OperandData::Local { layer, idx }
|
||||
}
|
||||
OperandType::BuiltinConst => {
|
||||
let id = self.read_string_id();
|
||||
OperandData::BuiltinConst(id)
|
||||
}
|
||||
OperandType::Builtins => OperandData::Builtins,
|
||||
OperandType::ReplBinding => {
|
||||
let id = self.read_string_id();
|
||||
OperandData::ReplBinding(id)
|
||||
}
|
||||
OperandType::ScopedImportBinding => {
|
||||
let slot_id = self.read_u32();
|
||||
let name = self.read_string_id();
|
||||
OperandData::ScopedImportBinding { slot_id, name }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn pc(&self) -> usize {
|
||||
self.pc
|
||||
}
|
||||
|
||||
pub(crate) fn set_pc(&mut self, pc: usize) {
|
||||
self.pc = pc;
|
||||
}
|
||||
|
||||
pub(crate) fn inst_start_pc(&self) -> usize {
|
||||
self.inst_start_pc
|
||||
}
|
||||
}
|
||||
@@ -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>,
|
||||
@@ -62,7 +61,7 @@ macro_rules! tail_fn {
|
||||
pc: u32,
|
||||
fuel: u32,
|
||||
) -> TailResult {
|
||||
let result = crate::instructions::$name(vm);
|
||||
let result = vm.$name();
|
||||
tail_dispatch_after!(result, pc + 1, vm, mc, ctx, bc, table, fuel)
|
||||
}
|
||||
};
|
||||
@@ -77,7 +76,7 @@ macro_rules! tail_fn {
|
||||
fuel: u32,
|
||||
) -> TailResult {
|
||||
let mut reader = BytecodeReader::from_after_op(bc, pc as usize);
|
||||
let result = crate::instructions::$name(vm, &mut reader);
|
||||
let result = vm.$name(&mut reader);
|
||||
tail_dispatch_after!(result, reader.pc() as u32, vm, mc, ctx, bc, table, fuel)
|
||||
}
|
||||
};
|
||||
@@ -92,7 +91,7 @@ macro_rules! tail_fn {
|
||||
fuel: u32,
|
||||
) -> TailResult {
|
||||
let mut reader = BytecodeReader::from_after_op(bc, pc as usize);
|
||||
let result = crate::instructions::$name(vm, &mut reader, mc);
|
||||
let result = vm.$name(&mut reader, mc);
|
||||
tail_dispatch_after!(result, reader.pc() as u32, vm, mc, ctx, bc, table, fuel)
|
||||
}
|
||||
};
|
||||
@@ -107,7 +106,7 @@ macro_rules! tail_fn {
|
||||
fuel: u32,
|
||||
) -> TailResult {
|
||||
let mut reader = BytecodeReader::from_after_op(bc, pc as usize);
|
||||
let result = crate::instructions::$name(vm, ctx, &mut reader, mc);
|
||||
let result = vm.$name(ctx, &mut reader, mc);
|
||||
tail_dispatch_after!(result, reader.pc() as u32, vm, mc, ctx, bc, table, fuel)
|
||||
}
|
||||
};
|
||||
@@ -121,7 +120,7 @@ macro_rules! tail_fn {
|
||||
pc: u32,
|
||||
fuel: u32,
|
||||
) -> TailResult {
|
||||
let result = crate::instructions::$name(vm, ctx);
|
||||
let result = vm.$name(ctx);
|
||||
tail_dispatch_after!(result, pc + 1, vm, mc, ctx, bc, table, fuel)
|
||||
}
|
||||
};
|
||||
@@ -145,7 +144,7 @@ tail_fn!(op_make_closure, (reader, mc));
|
||||
tail_fn!(op_make_pattern_closure, (reader, mc));
|
||||
|
||||
tail_fn!(op_call, (ctx, reader, mc));
|
||||
tail_fn!(op_dispatch_cont, (ctx, reader, mc));
|
||||
tail_fn!(op_dispatch_primop, (ctx, reader, mc));
|
||||
tail_fn!(op_return, (ctx, reader, mc));
|
||||
|
||||
tail_fn!(op_make_attrs, (ctx, reader, mc));
|
||||
@@ -201,18 +200,18 @@ 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; )*
|
||||
$( arr[fix_codegen::Op::$variant as usize] = $fn; )*
|
||||
DispatchTable(arr)
|
||||
};
|
||||
}
|
||||
|
||||
// Exhaustiveness check: fails to compile if `fix_bytecode::Op` gains,
|
||||
// Exhaustiveness check: fails to compile if `fix_codegen::Op` gains,
|
||||
// loses, or renames a variant that isn't wired up above.
|
||||
const _: fn(fix_bytecode::Op) = |op| match op {
|
||||
$( fix_bytecode::Op::$variant => (), )*
|
||||
#[allow(dead_code)]
|
||||
const _: fn(fix_codegen::Op) = |op| match op {
|
||||
$( fix_codegen::Op::$variant => (), )*
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -236,7 +235,7 @@ table! {
|
||||
MakePatternClosure => op_make_pattern_closure,
|
||||
|
||||
Call => op_call,
|
||||
DispatchCont => op_dispatch_cont,
|
||||
DispatchPrimOp => op_dispatch_primop,
|
||||
Return => op_return,
|
||||
|
||||
MakeAttrs => op_make_attrs,
|
||||
@@ -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>,
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
use fix_common::StringId;
|
||||
use gc_arena::{Gc, Mutation};
|
||||
|
||||
use crate::value::*;
|
||||
use crate::{Break, BytecodeReader, NixNum, Step, Vm};
|
||||
|
||||
pub(crate) trait Forced<'gc>: Sized {
|
||||
const WIDTH: usize;
|
||||
|
||||
/// Force and type-check the `WIDTH` slots starting at `base_depth` from
|
||||
/// TOS, deepest-first. If a slot holds a thunk, enter it and return
|
||||
/// `Break::Force`. If a slot holds a value of the wrong type, call
|
||||
/// `finish_type_err` and return `Break::Done`.
|
||||
fn force_and_check(
|
||||
vm: &mut Vm<'gc>,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
base_depth: usize,
|
||||
resume_pc: usize,
|
||||
) -> Step;
|
||||
|
||||
/// After `force_and_check` returned `Continue`, pop `WIDTH` slots
|
||||
/// (TOS first) and convert. Type assertions are infallible because
|
||||
/// `force_and_check` already validated every slot.
|
||||
fn pop_converted(vm: &mut Vm<'gc>) -> Self;
|
||||
}
|
||||
|
||||
impl<'gc> Forced<'gc> for StrictValue<'gc> {
|
||||
const WIDTH: usize = 1;
|
||||
|
||||
#[inline(always)]
|
||||
fn force_and_check(
|
||||
vm: &mut Vm<'gc>,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
base_depth: usize,
|
||||
resume_pc: usize,
|
||||
) -> Step {
|
||||
vm.force_slot_to_pc(base_depth, reader, mc, resume_pc)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop_converted(vm: &mut Vm<'gc>) -> Self {
|
||||
vm.pop_forced()
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_forced_inline {
|
||||
($($ty:ty => $nix_ty:expr),* $(,)?) => {
|
||||
$(
|
||||
impl<'gc> Forced<'gc> for $ty {
|
||||
const WIDTH: usize = 1;
|
||||
|
||||
#[inline(always)]
|
||||
fn force_and_check(
|
||||
vm: &mut Vm<'gc>,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
base_depth: usize,
|
||||
resume_pc: usize,
|
||||
) -> Step {
|
||||
vm.force_slot_to_pc(base_depth, reader, mc, resume_pc)?;
|
||||
let v = vm.peek_forced(base_depth);
|
||||
if v.as_inline::<$ty>().is_none() {
|
||||
let _: Step = vm.finish_type_err($nix_ty, v.ty());
|
||||
return Step::Break(Break::Done);
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop_converted(vm: &mut Vm<'gc>) -> Self {
|
||||
vm.pop_forced()
|
||||
.as_inline::<$ty>()
|
||||
.expect("type checked in force_and_check")
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
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(
|
||||
vm: &mut Vm<'gc>,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
base_depth: usize,
|
||||
resume_pc: usize,
|
||||
) -> Step {
|
||||
vm.force_slot_to_pc(base_depth, reader, mc, resume_pc)?;
|
||||
let v = vm.peek_forced(base_depth);
|
||||
if v.as_gc::<$ty>().is_none() {
|
||||
let _: Step = vm.finish_type_err($nix_ty, v.ty());
|
||||
return Step::Break(Break::Done);
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop_converted(vm: &mut Vm<'gc>) -> Self {
|
||||
vm.pop_forced()
|
||||
.as_gc::<$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 {
|
||||
const WIDTH: usize = 1;
|
||||
|
||||
#[inline(always)]
|
||||
fn force_and_check(
|
||||
vm: &mut Vm<'gc>,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
base_depth: usize,
|
||||
resume_pc: usize,
|
||||
) -> Step {
|
||||
vm.force_slot_to_pc(base_depth, reader, mc, resume_pc)?;
|
||||
let v = vm.peek_forced(base_depth);
|
||||
if v.as_num().is_none() {
|
||||
let _: Step = vm.finish_type_err(NixType::Int, v.ty());
|
||||
return Step::Break(Break::Done);
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop_converted(vm: &mut Vm<'gc>) -> Self {
|
||||
vm.pop_forced()
|
||||
.as_num()
|
||||
.expect("type checked in force_and_check")
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc> Forced<'gc> for f64 {
|
||||
const WIDTH: usize = 1;
|
||||
|
||||
#[inline(always)]
|
||||
fn force_and_check(
|
||||
vm: &mut Vm<'gc>,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
base_depth: usize,
|
||||
resume_pc: usize,
|
||||
) -> Step {
|
||||
vm.force_slot_to_pc(base_depth, reader, mc, resume_pc)?;
|
||||
let v = vm.peek_forced(base_depth);
|
||||
if v.as_float().is_none() {
|
||||
let _: Step = vm.finish_type_err(NixType::Float, v.ty());
|
||||
return Step::Break(Break::Done);
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop_converted(vm: &mut Vm<'gc>) -> Self {
|
||||
vm.pop_forced()
|
||||
.as_float()
|
||||
.expect("type checked in force_and_check")
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc, A: Forced<'gc>, B: Forced<'gc>> Forced<'gc> for (A, B) {
|
||||
const WIDTH: usize = A::WIDTH + B::WIDTH;
|
||||
|
||||
#[inline(always)]
|
||||
fn force_and_check(
|
||||
vm: &mut Vm<'gc>,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
base: usize,
|
||||
resume_pc: usize,
|
||||
) -> Step {
|
||||
A::force_and_check(vm, reader, mc, base + B::WIDTH, resume_pc)?;
|
||||
B::force_and_check(vm, reader, mc, base, resume_pc)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop_converted(vm: &mut Vm<'gc>) -> Self {
|
||||
let b = B::pop_converted(vm);
|
||||
let a = A::pop_converted(vm);
|
||||
(a, b)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc, A: Forced<'gc>, B: Forced<'gc>, C: Forced<'gc>> Forced<'gc> for (A, B, C) {
|
||||
const WIDTH: usize = A::WIDTH + B::WIDTH + C::WIDTH;
|
||||
|
||||
#[inline(always)]
|
||||
fn force_and_check(
|
||||
vm: &mut Vm<'gc>,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
base: usize,
|
||||
resume_pc: usize,
|
||||
) -> Step {
|
||||
A::force_and_check(vm, reader, mc, base + B::WIDTH + C::WIDTH, resume_pc)?;
|
||||
B::force_and_check(vm, reader, mc, base + C::WIDTH, resume_pc)?;
|
||||
C::force_and_check(vm, reader, mc, base, resume_pc)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop_converted(vm: &mut Vm<'gc>) -> Self {
|
||||
let c = C::pop_converted(vm);
|
||||
let b = B::pop_converted(vm);
|
||||
let a = A::pop_converted(vm);
|
||||
(a, b, c)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc, A: Forced<'gc>, B: Forced<'gc>, C: Forced<'gc>, D: Forced<'gc>> Forced<'gc>
|
||||
for (A, B, C, D)
|
||||
{
|
||||
const WIDTH: usize = A::WIDTH + B::WIDTH + C::WIDTH + D::WIDTH;
|
||||
|
||||
#[inline(always)]
|
||||
fn force_and_check(
|
||||
vm: &mut Vm<'gc>,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
base: usize,
|
||||
resume_pc: usize,
|
||||
) -> Step {
|
||||
A::force_and_check(
|
||||
vm,
|
||||
reader,
|
||||
mc,
|
||||
base + B::WIDTH + C::WIDTH + D::WIDTH,
|
||||
resume_pc,
|
||||
)?;
|
||||
B::force_and_check(vm, reader, mc, base + C::WIDTH + D::WIDTH, resume_pc)?;
|
||||
C::force_and_check(vm, reader, mc, base + D::WIDTH, resume_pc)?;
|
||||
D::force_and_check(vm, reader, mc, base, resume_pc)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop_converted(vm: &mut Vm<'gc>) -> Self {
|
||||
let d = D::pop_converted(vm);
|
||||
let c = C::pop_converted(vm);
|
||||
let b = B::pop_converted(vm);
|
||||
let a = A::pop_converted(vm);
|
||||
(a, b, c, d)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
use fix_error::Error;
|
||||
|
||||
use crate::VmError;
|
||||
|
||||
pub(crate) fn vm_err(msg: impl Into<String>) -> VmError {
|
||||
VmError::Uncatchable(Error::eval_error(msg.into()))
|
||||
}
|
||||
@@ -1,296 +1,311 @@
|
||||
use std::cmp::Ordering;
|
||||
|
||||
use fix_runtime::*;
|
||||
use gc_arena::{Gc, Mutation, RefLock};
|
||||
|
||||
use crate::{BytecodeReader, NixNum, Step, VmError, VmRuntimeCtx};
|
||||
use crate::value::*;
|
||||
use crate::{BytecodeReader, NixNum, Step, VmError, VmRuntimeCtx, VmRuntimeCtxExt as _};
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_add<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (lhs, rhs) = m.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
// if the LHS is a path, the result is a path obtained by
|
||||
// canonicalizing the concatenated string. RHS may be a path or a
|
||||
// string. (A `string + path` keeps the string-typed result, handled
|
||||
// by the next branch.)
|
||||
if lhs.is::<Path>() {
|
||||
let (Some(ls), Some(rs)) = (ctx.get_string_or_path(lhs), ctx.get_string_or_path(rhs))
|
||||
else {
|
||||
return m.finish_err(fix_error::Error::eval_error(format!(
|
||||
"cannot append {} to a path",
|
||||
rhs.ty()
|
||||
)));
|
||||
};
|
||||
let combined = format!("{ls}{rs}");
|
||||
let canon = canon_path_str(&combined);
|
||||
let sid = ctx.intern_string(canon);
|
||||
m.push(Value::new(fix_runtime::Path(sid)));
|
||||
return Step::Continue(());
|
||||
impl<'gc> crate::Vm<'gc> {
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_add(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (lhs, rhs) = self.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
if let (Some(ls), Some(rs)) = (ctx.get_string(lhs), ctx.get_string(rhs)) {
|
||||
let ns = Gc::new(mc, crate::NixString::new(format!("{ls}{rs}")));
|
||||
self.push(Value::new_gc(ns));
|
||||
return Step::Continue(());
|
||||
}
|
||||
let res = numeric_binop(lhs, rhs, mc, i64::wrapping_add, |a, b| a + b);
|
||||
match res {
|
||||
Ok(val) => {
|
||||
self.push(val);
|
||||
Step::Continue(())
|
||||
}
|
||||
Err(e) => self.finish_vm_err(e),
|
||||
}
|
||||
}
|
||||
if let (Some(ls), Some(rs)) = (ctx.get_string(lhs), ctx.get_string_or_path(rhs)) {
|
||||
let merged = ctx
|
||||
.get_string_context(lhs)
|
||||
.merge(ctx.get_string_context(rhs));
|
||||
let ns = Gc::new(
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_sub(&mut self, reader: &mut BytecodeReader<'_>, mc: &Mutation<'gc>) -> Step {
|
||||
self.op_arith(reader, mc, i64::wrapping_sub, |a, b| a - b)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_mul(&mut self, reader: &mut BytecodeReader<'_>, mc: &Mutation<'gc>) -> Step {
|
||||
self.op_arith(reader, mc, i64::wrapping_mul, |a, b| a * b)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn op_arith(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
int_op: fn(i64, i64) -> i64,
|
||||
float_op: fn(f64, f64) -> f64,
|
||||
) -> Step {
|
||||
let (lhs, rhs) = self.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
let res = numeric_binop(lhs, rhs, mc, int_op, float_op);
|
||||
match res {
|
||||
Ok(val) => {
|
||||
self.push(val);
|
||||
Step::Continue(())
|
||||
}
|
||||
Err(e) => self.finish_vm_err(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_div(&mut self, reader: &mut BytecodeReader<'_>, mc: &Mutation<'gc>) -> Step {
|
||||
let (lhs, rhs) = self.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
match (get_num(lhs), get_num(rhs)) {
|
||||
(_, Some(NixNum::Int(0))) | (_, Some(NixNum::Float(0.))) => {
|
||||
return self.finish_vm_err(VmError::Uncatchable(fix_error::Error::eval_error(
|
||||
"division by zero",
|
||||
)));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let res = numeric_binop(lhs, rhs, mc, |a, b| a / b, |a, b| a / b);
|
||||
match res {
|
||||
Ok(val) => {
|
||||
self.push(val);
|
||||
Step::Continue(())
|
||||
}
|
||||
Err(e) => self.finish_vm_err(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_eq(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (lhs, rhs) = self.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
let eq = match self.values_equal(ctx, lhs, rhs) {
|
||||
Ok(eq) => eq,
|
||||
Err(e) => return self.finish_vm_err(e),
|
||||
};
|
||||
self.push(Value::new_inline(eq));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_neq(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (lhs, rhs) = self.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
let eq = match self.values_equal(ctx, lhs, rhs) {
|
||||
Ok(eq) => eq,
|
||||
Err(e) => return self.finish_vm_err(e),
|
||||
};
|
||||
self.push(Value::new_inline(!eq));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_lt(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
self.compare_values(ctx, reader, mc, Ordering::is_lt)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_gt(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
self.compare_values(ctx, reader, mc, Ordering::is_gt)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_leq(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
self.compare_values(ctx, reader, mc, Ordering::is_le)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_geq(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
self.compare_values(ctx, reader, mc, Ordering::is_ge)
|
||||
}
|
||||
|
||||
fn compare_values(
|
||||
&mut self,
|
||||
ctx: &impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
pred: fn(Ordering) -> bool,
|
||||
) -> Step {
|
||||
let (lhs, rhs) = self.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
match self.compare_values_inner(ctx, pred, lhs, rhs) {
|
||||
Ok(()) => Step::Continue(()),
|
||||
Err(e) => self.finish_vm_err(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_concat(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (l, r) = self.force_and_retry::<(Gc<List>, Gc<List>)>(reader, mc)?;
|
||||
let mut items = smallvec::SmallVec::new();
|
||||
items.extend_from_slice(&l.inner.borrow());
|
||||
items.extend_from_slice(&r.inner.borrow());
|
||||
self.push(Value::new_gc(Gc::new(
|
||||
mc,
|
||||
crate::NixString::with_context(format!("{ls}{rs}"), merged),
|
||||
);
|
||||
m.push(Value::new(ns));
|
||||
return Step::Continue(());
|
||||
crate::List {
|
||||
inner: RefLock::new(items),
|
||||
},
|
||||
)));
|
||||
Step::Continue(())
|
||||
}
|
||||
let res = numeric_binop(lhs, rhs, mc, i64::wrapping_add, |a, b| a + b);
|
||||
match res {
|
||||
Ok(val) => {
|
||||
m.push(val);
|
||||
Step::Continue(())
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_update(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (l, r) = self.force_and_retry::<(Gc<AttrSet>, Gc<AttrSet>)>(reader, mc)?;
|
||||
self.push(Value::new_gc(l.merge(&r, mc)));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_neg(&mut self, reader: &mut BytecodeReader<'_>, mc: &Mutation<'gc>) -> Step {
|
||||
let rhs = self.force_and_retry::<NixNum>(reader, mc)?;
|
||||
match rhs {
|
||||
NixNum::Int(int) => self.push(Value::make_int(-int, mc)),
|
||||
NixNum::Float(float) => self.push(Value::new_float(-float)),
|
||||
}
|
||||
Err(e) => m.finish_vm_err(e),
|
||||
Step::Continue(())
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_sub<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
op_arith(m, reader, mc, i64::wrapping_sub, |a, b| a - b)
|
||||
}
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_not(&mut self, reader: &mut BytecodeReader<'_>, mc: &Mutation<'gc>) -> Step {
|
||||
let rhs = self.force_and_retry::<bool>(reader, mc)?;
|
||||
self.push(Value::new_inline(!rhs));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_mul<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
op_arith(m, reader, mc, i64::wrapping_mul, |a, b| a * b)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn op_arith<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
int_op: fn(i64, i64) -> i64,
|
||||
float_op: fn(f64, f64) -> f64,
|
||||
) -> Step {
|
||||
let (lhs, rhs) = m.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
let res = numeric_binop(lhs, rhs, mc, int_op, float_op);
|
||||
match res {
|
||||
Ok(val) => {
|
||||
m.push(val);
|
||||
Step::Continue(())
|
||||
pub(crate) fn values_equal(
|
||||
&mut self,
|
||||
ctx: &impl VmRuntimeCtx,
|
||||
lhs: StrictValue<'gc>,
|
||||
rhs: StrictValue<'gc>,
|
||||
) -> crate::VmResult<bool> {
|
||||
if let (Some(a), Some(b)) = (get_num(lhs), get_num(rhs)) {
|
||||
return Ok(match (a, b) {
|
||||
(NixNum::Int(a), NixNum::Int(b)) => a == b,
|
||||
(NixNum::Float(a), NixNum::Float(b)) => a == b,
|
||||
(NixNum::Int(a), NixNum::Float(b)) => a as f64 == b,
|
||||
(NixNum::Float(a), NixNum::Int(b)) => a == b as f64,
|
||||
});
|
||||
}
|
||||
Err(e) => m.finish_vm_err(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_div<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (lhs, rhs) = m.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
match (get_num(lhs), get_num(rhs)) {
|
||||
(_, Some(NixNum::Int(0))) | (_, Some(NixNum::Float(0.))) => {
|
||||
return m.finish_vm_err(VmError::Uncatchable(fix_error::Error::eval_error(
|
||||
"division by zero",
|
||||
)));
|
||||
if let (Some(a), Some(b)) = (lhs.as_inline::<bool>(), rhs.as_inline::<bool>()) {
|
||||
return Ok(a == b);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let res = numeric_binop(lhs, rhs, mc, |a, b| a / b, |a, b| a / b);
|
||||
match res {
|
||||
Ok(val) => {
|
||||
m.push(val);
|
||||
Step::Continue(())
|
||||
if lhs.is::<crate::Null>() && rhs.is::<crate::Null>() {
|
||||
return Ok(true);
|
||||
}
|
||||
Err(e) => m.finish_vm_err(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_eq<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (lhs, rhs) = m.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
crate::primops::start_eq(m, ctx, reader, mc, lhs, rhs, false)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_neq<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (lhs, rhs) = m.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
crate::primops::start_eq(m, ctx, reader, mc, lhs, rhs, true)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_lt<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
compare_values(m, ctx, reader, mc, Ordering::is_lt)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_gt<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
compare_values(m, ctx, reader, mc, Ordering::is_gt)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_leq<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
compare_values(m, ctx, reader, mc, Ordering::is_le)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_geq<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
compare_values(m, ctx, reader, mc, Ordering::is_ge)
|
||||
}
|
||||
|
||||
fn compare_values<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
pred: fn(Ordering) -> bool,
|
||||
) -> Step {
|
||||
let (lhs, rhs) = m.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
match compare_values_inner(m, ctx, pred, lhs, rhs) {
|
||||
Ok(()) => Step::Continue(()),
|
||||
Err(e) => m.finish_vm_err(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_concat<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (l, r) = m.force_and_retry::<(Gc<List>, Gc<List>)>(reader, mc)?;
|
||||
let mut items = smallvec::SmallVec::new();
|
||||
items.extend_from_slice(&l.inner.borrow());
|
||||
items.extend_from_slice(&r.inner.borrow());
|
||||
m.push(Value::new(Gc::new(
|
||||
mc,
|
||||
crate::List {
|
||||
inner: RefLock::new(items),
|
||||
},
|
||||
)));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_update<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (l, r) = m.force_and_retry::<(Gc<AttrSet>, Gc<AttrSet>)>(reader, mc)?;
|
||||
m.push(Value::new(l.merge(&r, mc)));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_neg<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
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)),
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_not<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let rhs = m.force_and_retry::<bool>(reader, mc)?;
|
||||
m.push(Value::new(!rhs));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
fn compare_values_inner<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &impl VmRuntimeCtx,
|
||||
pred: fn(Ordering) -> bool,
|
||||
lhs: StrictValue<'gc>,
|
||||
rhs: StrictValue<'gc>,
|
||||
) -> crate::VmResult<()> {
|
||||
if let (Some(a), Some(b)) = (get_num(lhs), get_num(rhs)) {
|
||||
let ord = match (a, b) {
|
||||
(NixNum::Int(a), NixNum::Int(b)) => a.cmp(&b),
|
||||
(NixNum::Float(a), NixNum::Float(b)) => a.partial_cmp(&b).unwrap_or(Ordering::Less),
|
||||
(NixNum::Int(a), NixNum::Float(b)) => {
|
||||
(a as f64).partial_cmp(&b).unwrap_or(Ordering::Less)
|
||||
if let (Some(a), Some(b)) = (ctx.get_string(lhs), ctx.get_string(rhs)) {
|
||||
return Ok(a == b);
|
||||
}
|
||||
if let (Some(a), Some(b)) = (lhs.as_gc::<crate::List>(), rhs.as_gc::<crate::List>()) {
|
||||
if a.inner.borrow().len() != b.inner.borrow().len() {
|
||||
return Ok(false);
|
||||
}
|
||||
(NixNum::Float(a), NixNum::Int(b)) => {
|
||||
a.partial_cmp(&(b as f64)).unwrap_or(Ordering::Less)
|
||||
for (x, y) in a.inner.borrow().iter().zip(b.inner.borrow().iter()) {
|
||||
let lx = x.restrict().expect("forced");
|
||||
let ly = y.restrict().expect("forced");
|
||||
if !self.values_equal(ctx, lx, ly)? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
m.push(Value::new(pred(ord)));
|
||||
return Ok(());
|
||||
return Ok(true);
|
||||
}
|
||||
if let (Some(a), Some(b)) = (lhs.as_gc::<crate::AttrSet>(), rhs.as_gc::<crate::AttrSet>()) {
|
||||
let a = &a.entries;
|
||||
let b = &b.entries;
|
||||
if a.len() != b.len() {
|
||||
return Ok(false);
|
||||
}
|
||||
for ((k1, v1), (k2, v2)) in a.iter().zip(b.iter()) {
|
||||
if k1 != k2 {
|
||||
return Ok(false);
|
||||
}
|
||||
let lv1 = v1.restrict().expect("forced");
|
||||
let lv2 = v2.restrict().expect("forced");
|
||||
if !self.values_equal(ctx, lv1, lv2)? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
if let (Some(a), Some(b)) = (ctx.get_string(lhs), ctx.get_string(rhs)) {
|
||||
m.push(Value::new(pred(a.cmp(b))));
|
||||
return Ok(());
|
||||
|
||||
fn compare_values_inner(
|
||||
&mut self,
|
||||
ctx: &impl VmRuntimeCtx,
|
||||
pred: fn(Ordering) -> bool,
|
||||
lhs: StrictValue<'gc>,
|
||||
rhs: StrictValue<'gc>,
|
||||
) -> crate::VmResult<()> {
|
||||
if let (Some(a), Some(b)) = (get_num(lhs), get_num(rhs)) {
|
||||
let ord = match (a, b) {
|
||||
(NixNum::Int(a), NixNum::Int(b)) => a.cmp(&b),
|
||||
(NixNum::Float(a), NixNum::Float(b)) => a.partial_cmp(&b).unwrap_or(Ordering::Less),
|
||||
(NixNum::Int(a), NixNum::Float(b)) => {
|
||||
(a as f64).partial_cmp(&b).unwrap_or(Ordering::Less)
|
||||
}
|
||||
(NixNum::Float(a), NixNum::Int(b)) => {
|
||||
a.partial_cmp(&(b as f64)).unwrap_or(Ordering::Less)
|
||||
}
|
||||
};
|
||||
self.push(Value::new_inline(pred(ord)));
|
||||
return Ok(());
|
||||
}
|
||||
if let (Some(a), Some(b)) = (ctx.get_string(lhs), ctx.get_string(rhs)) {
|
||||
self.push(Value::new_inline(pred(a.cmp(b))));
|
||||
return Ok(());
|
||||
}
|
||||
// TODO: compare other types
|
||||
Err(crate::vm_err("cannot compare these types"))
|
||||
}
|
||||
if let (Some(a), Some(b)) = (lhs.downcast::<Path>(), rhs.downcast::<Path>()) {
|
||||
let a = ctx.resolve_string(a.0);
|
||||
let b = ctx.resolve_string(b.0);
|
||||
m.push(Value::new(pred(a.cmp(b))));
|
||||
return Ok(());
|
||||
}
|
||||
// TODO: compare other types
|
||||
Err(crate::vm_err(format!(
|
||||
"cannot compare {} with {}",
|
||||
lhs.ty(),
|
||||
rhs.ty()
|
||||
)))
|
||||
}
|
||||
|
||||
pub(crate) fn get_num(val: StrictValue<'_>) -> Option<NixNum> {
|
||||
if let Some(i) = val.downcast::<i32>() {
|
||||
Some(NixNum::Int(i64::from(i)))
|
||||
} else if let Some(gc_i) = val.downcast::<i64>() {
|
||||
if let Some(i) = val.as_inline::<i32>() {
|
||||
Some(NixNum::Int(i as i64))
|
||||
} else if let Some(gc_i) = val.as_gc::<i64>() {
|
||||
Some(NixNum::Int(*gc_i))
|
||||
} else {
|
||||
val.downcast::<f64>().map(NixNum::Float)
|
||||
val.as_float().map(NixNum::Float)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -304,9 +319,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())
|
||||
|
||||
+156
-180
@@ -1,195 +1,171 @@
|
||||
use fix_bytecode::Continuation;
|
||||
use fix_builtins::PrimOpPhase;
|
||||
use fix_error::Error;
|
||||
use fix_runtime::{resolve_operand, *};
|
||||
use gc_arena::{Gc, Mutation, RefLock};
|
||||
|
||||
use crate::value::*;
|
||||
use crate::{
|
||||
BytecodeReader, CallFrame, Closure, Env, ForceMode, Step, ThunkState, VmRuntimeCtx,
|
||||
VmRuntimeCtxExt,
|
||||
};
|
||||
|
||||
#[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<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
arg: Value<'gc>,
|
||||
resume_pc: usize,
|
||||
) -> Step {
|
||||
let func = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
if m.call_depth() > 10000 {
|
||||
return m.finish_err(Error::eval_error("stack overflow; max-call-depth exceeded"));
|
||||
}
|
||||
m.inc_call_depth();
|
||||
if let Some(closure) = func.downcast::<Closure>() {
|
||||
if closure.pattern.is_some() {
|
||||
// FIXME: better DX...
|
||||
m.push(func.relax());
|
||||
m.push(arg);
|
||||
m.push_call_frame(CallFrame {
|
||||
pc: resume_pc,
|
||||
thunk: None,
|
||||
env: m.env(),
|
||||
depth: None,
|
||||
});
|
||||
reader.set_pc(Continuation::CallPattern.ip() as usize);
|
||||
return Step::Continue(());
|
||||
impl<'gc> crate::Vm<'gc> {
|
||||
#[inline(always)]
|
||||
pub(crate) fn call(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
arg: Value<'gc>,
|
||||
resume_pc: usize,
|
||||
) -> Step {
|
||||
let func = self.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
if self.call_depth > 10000 {
|
||||
return self.finish_err(Error::eval_error("stack overflow; max-call-depth exceeded"));
|
||||
}
|
||||
|
||||
let ip = closure.ip;
|
||||
let n_locals = closure.n_locals;
|
||||
let env = closure.env;
|
||||
let new_env = Gc::new(mc, RefLock::new(Env::with_arg(arg, n_locals, env)));
|
||||
m.push_call_frame(CallFrame {
|
||||
pc: resume_pc,
|
||||
thunk: None,
|
||||
env: m.env(),
|
||||
depth: None,
|
||||
});
|
||||
reader.set_pc(ip as usize);
|
||||
m.set_env(new_env);
|
||||
} else if let Some(primop) = func.downcast::<PrimOp>() {
|
||||
if primop.arity == 1 {
|
||||
m.push(arg);
|
||||
m.push_call_frame(CallFrame {
|
||||
pc: resume_pc,
|
||||
thunk: None,
|
||||
env: m.env(),
|
||||
depth: None,
|
||||
});
|
||||
reader.set_pc(primop.dispatch_ip as usize)
|
||||
} else {
|
||||
let app = PrimOpApp {
|
||||
primop,
|
||||
arity: primop.arity - 1,
|
||||
args: [arg, Value::default(), Value::default()],
|
||||
};
|
||||
m.push(Value::new(Gc::new(mc, app)));
|
||||
}
|
||||
} else if let Some(app) = func.downcast::<PrimOpApp>() {
|
||||
if app.arity == 1 {
|
||||
for i in 0..app.primop.arity - 1 {
|
||||
m.push(app.args[i as usize]);
|
||||
}
|
||||
m.push(arg);
|
||||
m.push_call_frame(CallFrame {
|
||||
pc: resume_pc,
|
||||
thunk: None,
|
||||
env: m.env(),
|
||||
depth: None,
|
||||
});
|
||||
reader.set_pc(app.primop.dispatch_ip as usize)
|
||||
} else {
|
||||
let position = (app.primop.arity - app.arity) as usize;
|
||||
let mut new_app = PrimOpApp {
|
||||
arity: app.arity - 1,
|
||||
..*app
|
||||
};
|
||||
new_app.args[position] = arg;
|
||||
m.push(Value::new(Gc::new(mc, new_app)))
|
||||
}
|
||||
} else if let Some(attrs) = func.downcast::<AttrSet>()
|
||||
&& let Some(functor) = attrs.lookup(m.functor_sym())
|
||||
{
|
||||
// f arg => (f.__functor f) arg
|
||||
//
|
||||
// Stage the work for `CallFunctor1` so retries during force are
|
||||
// safe: the stack invariant `[..., orig_arg, self, functor]`
|
||||
// holds every time control re-enters phase 1.
|
||||
m.dec_call_depth();
|
||||
m.push_call_frame(CallFrame {
|
||||
pc: resume_pc,
|
||||
thunk: None,
|
||||
env: m.env(),
|
||||
depth: None,
|
||||
});
|
||||
m.push(arg);
|
||||
m.push(func.relax());
|
||||
m.push(functor);
|
||||
reader.set_pc(Continuation::CallFunctor1.ip() as usize);
|
||||
return Step::Continue(());
|
||||
} else {
|
||||
return m.finish_err(Error::eval_error(format!(
|
||||
"attempt to call something which is not a function but {}",
|
||||
func.ty()
|
||||
)));
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_call<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let arg = resolve_operand(&reader.read_operand_data(), mc, ctx, m);
|
||||
let pc = reader.pc();
|
||||
m.call(reader, mc, arg, pc)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_return<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let val = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
let Some(CallFrame {
|
||||
pc: ret_pc,
|
||||
thunk,
|
||||
env,
|
||||
depth,
|
||||
}) = m.pop_call_frame()
|
||||
else {
|
||||
match m.force_mode() {
|
||||
ForceMode::AsIs => return m.finish_ok(ctx.convert_value(val.relax())),
|
||||
ForceMode::Shallow => {
|
||||
m.push(val.relax());
|
||||
reader.set_pc(Continuation::ForceResultShallow.ip() as usize);
|
||||
return Step::Continue(());
|
||||
}
|
||||
ForceMode::Deep => {
|
||||
m.push(val.relax());
|
||||
m.push(val.relax());
|
||||
m.push_call_frame(CallFrame {
|
||||
pc: Continuation::ForceResultDeepFinish.ip() as usize,
|
||||
self.call_depth += 1;
|
||||
if let Some(closure) = func.as_gc::<Closure>() {
|
||||
if closure.pattern.is_some() {
|
||||
// FIXME: better DX...
|
||||
self.push(func.relax());
|
||||
self.push(arg);
|
||||
self.call_stack.push(CallFrame {
|
||||
pc: resume_pc,
|
||||
thunk: None,
|
||||
env: m.env(),
|
||||
depth: None,
|
||||
env: self.env,
|
||||
});
|
||||
m.inc_call_depth();
|
||||
reader.set_pc(Continuation::PDeepSeq0.ip() as usize);
|
||||
reader.set_pc(PrimOpPhase::CallPattern.ip() as usize);
|
||||
return Step::Continue(());
|
||||
}
|
||||
}
|
||||
};
|
||||
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())
|
||||
}
|
||||
m.set_env(env);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_dispatch_cont<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
crate::primops::dispatch_cont(m, ctx, reader, mc)
|
||||
let ip = closure.ip;
|
||||
let n_locals = closure.n_locals;
|
||||
let env = closure.env;
|
||||
let new_env = Gc::new(mc, RefLock::new(Env::with_arg(arg, n_locals, env)));
|
||||
self.call_stack.push(CallFrame {
|
||||
pc: resume_pc,
|
||||
thunk: None,
|
||||
env: self.env,
|
||||
});
|
||||
reader.set_pc(ip as usize);
|
||||
self.env = new_env;
|
||||
} else if let Some(primop) = func.as_inline::<PrimOp>() {
|
||||
if primop.arity == 1 {
|
||||
self.push(arg);
|
||||
self.call_stack.push(CallFrame {
|
||||
pc: resume_pc,
|
||||
thunk: None,
|
||||
env: self.env,
|
||||
});
|
||||
reader.set_pc(primop.dispatch_ip as usize)
|
||||
} else {
|
||||
let app = PrimOpApp {
|
||||
primop,
|
||||
arity: primop.arity - 1,
|
||||
args: [arg, Value::default(), Value::default()],
|
||||
};
|
||||
self.push(Value::new_gc(Gc::new(mc, app)));
|
||||
}
|
||||
} else if let Some(app) = func.as_gc::<PrimOpApp>() {
|
||||
if app.arity == 1 {
|
||||
for i in 0..app.primop.arity - 1 {
|
||||
self.push(app.args[i as usize]);
|
||||
}
|
||||
self.push(arg);
|
||||
self.call_stack.push(CallFrame {
|
||||
pc: resume_pc,
|
||||
thunk: None,
|
||||
env: self.env,
|
||||
});
|
||||
reader.set_pc(app.primop.dispatch_ip as usize)
|
||||
} else {
|
||||
let new_app = PrimOpApp {
|
||||
arity: app.arity - 1,
|
||||
..*app
|
||||
};
|
||||
self.push(Value::new_gc(Gc::new(mc, new_app)))
|
||||
}
|
||||
} else if let Some(attrs) = func.as_gc::<AttrSet>()
|
||||
&& let Some(functor) = attrs.lookup(self.functor_sym)
|
||||
{
|
||||
// f arg => (f.__functor f) arg
|
||||
//
|
||||
// Stage the work for `CallFunctor1` so retries during force are
|
||||
// safe: the stack invariant `[..., orig_arg, self, functor]`
|
||||
// holds every time control re-enters phase 1.
|
||||
self.call_depth -= 1;
|
||||
self.call_stack.push(CallFrame {
|
||||
pc: resume_pc,
|
||||
thunk: None,
|
||||
env: self.env,
|
||||
});
|
||||
self.push(arg);
|
||||
self.push(func.relax());
|
||||
self.push(functor);
|
||||
reader.set_pc(PrimOpPhase::CallFunctor1.ip() as usize);
|
||||
return Step::Continue(());
|
||||
} else {
|
||||
return self.finish_err(Error::eval_error(format!(
|
||||
"attempt to call something which is not a function but {}",
|
||||
func.ty()
|
||||
)));
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_call(
|
||||
&mut self,
|
||||
ctx: &impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let arg = reader.read_operand_data(ctx).resolve(mc, self);
|
||||
let pc = reader.pc();
|
||||
self.call(reader, mc, arg, pc)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_return(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let val = self.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
let Some(CallFrame {
|
||||
pc: ret_pc,
|
||||
thunk,
|
||||
env,
|
||||
}) = self.call_stack.pop()
|
||||
else {
|
||||
match self.force_mode {
|
||||
ForceMode::AsIs => return self.finish_ok(ctx.convert_value(val.relax())),
|
||||
ForceMode::Shallow => {
|
||||
self.push(val.relax());
|
||||
reader.set_pc(PrimOpPhase::ForceResultShallow.ip() as usize);
|
||||
return Step::Continue(());
|
||||
}
|
||||
ForceMode::Deep => {
|
||||
self.push(val.relax());
|
||||
self.push(val.relax());
|
||||
self.call_stack.push(CallFrame {
|
||||
pc: PrimOpPhase::ForceResultDeepFinish.ip() as usize,
|
||||
thunk: None,
|
||||
env: self.env,
|
||||
});
|
||||
self.call_depth += 1;
|
||||
reader.set_pc(PrimOpPhase::DeepSeq.ip() as usize);
|
||||
return Step::Continue(());
|
||||
}
|
||||
}
|
||||
};
|
||||
reader.set_pc(ret_pc);
|
||||
if let Some(outer_thunk) = thunk {
|
||||
*outer_thunk.borrow_mut(mc) = ThunkState::Evaluated(val);
|
||||
} else {
|
||||
self.call_depth -= 1;
|
||||
self.push(val.relax())
|
||||
}
|
||||
self.env = env;
|
||||
Step::Continue(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,93 +1,94 @@
|
||||
use fix_runtime::Machine;
|
||||
use gc_arena::{Gc, Mutation, RefLock};
|
||||
|
||||
use crate::{BytecodeReader, Step, ThunkState, Value};
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_make_thunk<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let entry_point = reader.read_u32();
|
||||
let thunk = Gc::new(
|
||||
mc,
|
||||
RefLock::new(ThunkState::Pending {
|
||||
ip: entry_point as usize,
|
||||
env: m.env(),
|
||||
}),
|
||||
);
|
||||
m.push(Value::new(thunk));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_make_closure<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let entry_point = reader.read_u32();
|
||||
let n_locals = reader.read_u32();
|
||||
let closure = Gc::new(
|
||||
mc,
|
||||
crate::Closure {
|
||||
ip: entry_point,
|
||||
n_locals,
|
||||
env: m.env(),
|
||||
pattern: None,
|
||||
},
|
||||
);
|
||||
m.push(Value::new(closure));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_make_pattern_closure<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let entry_point = reader.read_u32();
|
||||
let n_locals = reader.read_u32();
|
||||
let req_count = reader.read_u16() as usize;
|
||||
let opt_count = reader.read_u16() as usize;
|
||||
let has_ellipsis = reader.read_u8() != 0;
|
||||
|
||||
let mut required = smallvec::SmallVec::new();
|
||||
for _ in 0..req_count {
|
||||
required.push(reader.read_string_id());
|
||||
}
|
||||
let mut optional = smallvec::SmallVec::new();
|
||||
for _ in 0..opt_count {
|
||||
optional.push(reader.read_string_id());
|
||||
}
|
||||
let total = req_count + opt_count;
|
||||
let mut param_spans = Vec::with_capacity(total);
|
||||
for _ in 0..total {
|
||||
let name = reader.read_string_id();
|
||||
let span_id = reader.read_u32();
|
||||
param_spans.push((name, span_id));
|
||||
impl<'gc> crate::Vm<'gc> {
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_make_thunk(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let entry_point = reader.read_u32();
|
||||
let thunk = Gc::new(
|
||||
mc,
|
||||
RefLock::new(ThunkState::Pending {
|
||||
ip: entry_point as usize,
|
||||
env: self.env,
|
||||
}),
|
||||
);
|
||||
self.push(Value::new_gc(thunk));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
let pattern = Gc::new(
|
||||
mc,
|
||||
crate::PatternInfo {
|
||||
required,
|
||||
optional,
|
||||
ellipsis: has_ellipsis,
|
||||
param_spans: param_spans.into_boxed_slice(),
|
||||
},
|
||||
);
|
||||
let closure = Gc::new(
|
||||
mc,
|
||||
crate::Closure {
|
||||
ip: entry_point,
|
||||
n_locals,
|
||||
env: m.env(),
|
||||
pattern: Some(pattern),
|
||||
},
|
||||
);
|
||||
m.push(Value::new(closure));
|
||||
Step::Continue(())
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_make_closure(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let entry_point = reader.read_u32();
|
||||
let n_locals = reader.read_u32();
|
||||
let closure = Gc::new(
|
||||
mc,
|
||||
crate::Closure {
|
||||
ip: entry_point,
|
||||
n_locals,
|
||||
env: self.env,
|
||||
pattern: None,
|
||||
},
|
||||
);
|
||||
self.push(Value::new_gc(closure));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_make_pattern_closure(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let entry_point = reader.read_u32();
|
||||
let n_locals = reader.read_u32();
|
||||
let req_count = reader.read_u16() as usize;
|
||||
let opt_count = reader.read_u16() as usize;
|
||||
let has_ellipsis = reader.read_u8() != 0;
|
||||
|
||||
let mut required = smallvec::SmallVec::new();
|
||||
for _ in 0..req_count {
|
||||
required.push(reader.read_string_id());
|
||||
}
|
||||
let mut optional = smallvec::SmallVec::new();
|
||||
for _ in 0..opt_count {
|
||||
optional.push(reader.read_string_id());
|
||||
}
|
||||
let total = req_count + opt_count;
|
||||
let mut param_spans = Vec::with_capacity(total);
|
||||
for _ in 0..total {
|
||||
let name = reader.read_string_id();
|
||||
let span_id = reader.read_u32();
|
||||
param_spans.push((name, span_id));
|
||||
}
|
||||
|
||||
let pattern = Gc::new(
|
||||
mc,
|
||||
crate::PatternInfo {
|
||||
required,
|
||||
optional,
|
||||
ellipsis: has_ellipsis,
|
||||
param_spans: param_spans.into_boxed_slice(),
|
||||
},
|
||||
);
|
||||
let closure = Gc::new(
|
||||
mc,
|
||||
crate::Closure {
|
||||
ip: entry_point,
|
||||
n_locals,
|
||||
env: self.env,
|
||||
pattern: Some(pattern),
|
||||
},
|
||||
);
|
||||
self.push(Value::new_gc(closure));
|
||||
Step::Continue(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,358 +1,334 @@
|
||||
use fix_common::StringId;
|
||||
use fix_error::Error;
|
||||
use fix_lang::StringId;
|
||||
use fix_runtime::{Machine, MachineExt, NixType, resolve_operand};
|
||||
use gc_arena::{Gc, RefLock};
|
||||
use smallvec::SmallVec;
|
||||
|
||||
use crate::value::NixType;
|
||||
use crate::{
|
||||
AttrSet, BytecodeReader, List, Step, StrictValue, Value, VmRuntimeCtx, VmRuntimeCtxExt,
|
||||
};
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_make_attrs<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let static_count = reader.read_u32() as usize;
|
||||
let dynamic_count = reader.read_u32() as usize;
|
||||
impl<'gc> crate::Vm<'gc> {
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_make_attrs(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let static_count = reader.read_u32() as usize;
|
||||
let dynamic_count = reader.read_u32() as usize;
|
||||
|
||||
for i in 0..dynamic_count {
|
||||
let depth = dynamic_count - 1 - i;
|
||||
m.force_slot_to_pc(depth, reader, mc, reader.inst_start_pc())?;
|
||||
for i in 0..dynamic_count {
|
||||
let depth = dynamic_count - 1 - i;
|
||||
self.force_slot_to_pc(depth, reader, mc, reader.inst_start_pc())?;
|
||||
}
|
||||
|
||||
let mut dyn_keys: SmallVec<[_; 2]> = SmallVec::with_capacity(dynamic_count);
|
||||
for i in 0..dynamic_count {
|
||||
let depth = dynamic_count - 1 - i;
|
||||
let key_val = self.peek_forced(depth);
|
||||
let key_sid = match ctx.get_string_id(key_val) {
|
||||
Ok(id) => Some(id),
|
||||
Err(NixType::Null) => None,
|
||||
Err(got) => return self.finish_type_err(NixType::String, got),
|
||||
};
|
||||
dyn_keys.push(key_sid);
|
||||
}
|
||||
|
||||
self.stack.truncate(self.stack.len() - dynamic_count);
|
||||
|
||||
let mut kv: SmallVec<[(crate::StringId, Value); 4]> =
|
||||
SmallVec::with_capacity(static_count + dynamic_count);
|
||||
|
||||
for _ in 0..static_count {
|
||||
let key = reader.read_string_id();
|
||||
let val = reader.read_operand_data(ctx).resolve(mc, self);
|
||||
let _span_id = reader.read_u32();
|
||||
kv.push((key, val));
|
||||
}
|
||||
|
||||
for key in dyn_keys {
|
||||
let val = reader.read_operand_data(ctx).resolve(mc, self);
|
||||
let _span_id = reader.read_u32();
|
||||
if let Some(key) = key {
|
||||
kv.push((key, val))
|
||||
}
|
||||
}
|
||||
|
||||
kv.sort_by_key(|(k, _)| *k);
|
||||
let attrs = Gc::new(mc, AttrSet::from_sorted_unchecked(kv));
|
||||
self.push(Value::new_gc(attrs));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
let mut dyn_keys: SmallVec<[_; 2]> = SmallVec::with_capacity(dynamic_count);
|
||||
for i in 0..dynamic_count {
|
||||
let depth = dynamic_count - 1 - i;
|
||||
let key_val = m.peek_forced(depth);
|
||||
let key_sid = match ctx.get_string_id(key_val) {
|
||||
Ok(id) => Some(id),
|
||||
Err(NixType::Null) => None,
|
||||
Err(got) => return m.finish_type_err(NixType::String, got),
|
||||
};
|
||||
dyn_keys.push(key_sid);
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_make_empty_attrs(&mut self) -> Step {
|
||||
self.push(self.empty_attrs);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
m.drop_n(dynamic_count);
|
||||
|
||||
let mut kv: SmallVec<[(crate::StringId, Value); 4]> =
|
||||
SmallVec::with_capacity(static_count + dynamic_count);
|
||||
|
||||
for _ in 0..static_count {
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_select_static(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let _span_id = reader.read_u32();
|
||||
let key = reader.read_string_id();
|
||||
let val = resolve_operand(&reader.read_operand_data(), mc, ctx, m);
|
||||
|
||||
let attrset = self.force_and_retry::<Gc<AttrSet>>(reader, mc)?;
|
||||
|
||||
match attrset.lookup(key) {
|
||||
Some(v) => {
|
||||
self.push(v);
|
||||
}
|
||||
None => return self.select_skip(key, ctx, reader),
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_select_dynamic(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let _span_id = reader.read_u32();
|
||||
kv.push((key, val));
|
||||
|
||||
let (attrset, key_val) = self.force_and_retry::<(Gc<AttrSet>, StrictValue)>(reader, mc)?;
|
||||
|
||||
let key_sid = match ctx.get_string_id(key_val) {
|
||||
Ok(id) => id,
|
||||
Err(got) => return self.finish_type_err(NixType::String, got),
|
||||
};
|
||||
|
||||
match attrset.lookup(key_sid) {
|
||||
Some(v) => {
|
||||
self.push(v);
|
||||
}
|
||||
None => return self.select_skip(key_sid, ctx, reader),
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
for key in dyn_keys {
|
||||
let val = resolve_operand(&reader.read_operand_data(), mc, ctx, m);
|
||||
/// Skip the rest of a **Select** attrpath after a missing attribute.
|
||||
/// 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.
|
||||
fn select_skip(
|
||||
&mut self,
|
||||
key: StringId,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
) -> Step {
|
||||
use fix_codegen::Op::*;
|
||||
loop {
|
||||
match reader.read_op() {
|
||||
SelectStatic => {
|
||||
reader.set_pc(reader.pc() + 4 + 4);
|
||||
}
|
||||
SelectDynamic => {
|
||||
reader.set_pc(reader.pc() + 4);
|
||||
}
|
||||
JumpIfSelectSucceeded => {
|
||||
reader.set_pc(reader.pc() + 4);
|
||||
break Step::Continue(());
|
||||
}
|
||||
JumpIfSelectFailed => {
|
||||
let offset = reader.read_i32();
|
||||
reader.set_pc(((reader.pc() as isize) + (offset as isize)) as usize);
|
||||
}
|
||||
_ => {
|
||||
let name = ctx.resolve_string(key);
|
||||
return self
|
||||
.finish_err(Error::eval_error(format!("attribute '{name}' missing")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Skip the rest of a **HasAttr** attrpath after an intermediate
|
||||
/// lookup failed. Only recognises HasAttr opcodes and jumps.
|
||||
fn has_attr_skip(&mut self, reader: &mut BytecodeReader<'_>) -> Step {
|
||||
use fix_codegen::Op::*;
|
||||
loop {
|
||||
match reader.read_op() {
|
||||
HasAttrPathStatic => {
|
||||
reader.set_pc(reader.pc() + 4 + 4);
|
||||
}
|
||||
HasAttrPathDynamic => {
|
||||
reader.set_pc(reader.pc() + 4);
|
||||
}
|
||||
HasAttrStatic => {
|
||||
reader.set_pc(reader.pc() + 4);
|
||||
break Step::Continue(());
|
||||
}
|
||||
JumpIfSelectFailed => {
|
||||
let offset = reader.read_i32();
|
||||
reader.set_pc(((reader.pc() as isize) + (offset as isize)) as usize);
|
||||
}
|
||||
HasAttrDynamic => {
|
||||
break Step::Continue(());
|
||||
}
|
||||
HasAttrResolve => {
|
||||
reader.set_pc(reader.pc() - 1);
|
||||
break Step::Continue(());
|
||||
}
|
||||
other => {
|
||||
unreachable!("unexpected opcode {:?} in has_attr_skip", other as u8)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_has_attr_path_static(
|
||||
&mut self,
|
||||
_ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let _span_id = reader.read_u32();
|
||||
if let Some(key) = key {
|
||||
kv.push((key, val))
|
||||
}
|
||||
}
|
||||
let key = reader.read_string_id();
|
||||
|
||||
kv.sort_by_key(|(k, _)| *k);
|
||||
let attrs = Gc::new(mc, AttrSet::from_sorted_unchecked(kv));
|
||||
m.push(Value::new(attrs));
|
||||
Step::Continue(())
|
||||
}
|
||||
let current = self.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_make_empty_attrs<'gc, M: Machine<'gc>>(m: &mut M) -> Step {
|
||||
m.push(m.empty_attrs());
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_select_static<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let _span_id = reader.read_u32();
|
||||
let key = reader.read_string_id();
|
||||
|
||||
let attrset = m.force_and_retry::<Gc<AttrSet>>(reader, mc)?;
|
||||
|
||||
match attrset.lookup(key) {
|
||||
Some(v) => {
|
||||
m.push(v);
|
||||
}
|
||||
None => return select_skip(m, key, ctx, reader),
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_select_dynamic<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let _span_id = reader.read_u32();
|
||||
|
||||
let (attrset, key_val) = m.force_and_retry::<(Gc<AttrSet>, StrictValue)>(reader, mc)?;
|
||||
|
||||
let key_sid = match ctx.get_string_id(key_val) {
|
||||
Ok(id) => id,
|
||||
Err(got) => return m.finish_type_err(NixType::String, got),
|
||||
};
|
||||
|
||||
match attrset.lookup(key_sid) {
|
||||
Some(v) => {
|
||||
m.push(v);
|
||||
}
|
||||
None => return select_skip(m, key_sid, ctx, reader),
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
/// Skip the rest of a **Select** attrpath after a missing attribute.
|
||||
/// 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,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
) -> Step {
|
||||
use fix_bytecode::Op::*;
|
||||
loop {
|
||||
match reader.read_op() {
|
||||
// Skip rest of the attrpath
|
||||
SelectStatic => {
|
||||
reader.set_pc(reader.pc() + 4 + 4);
|
||||
}
|
||||
SelectDynamic => {
|
||||
reader.set_pc(reader.pc() + 4);
|
||||
}
|
||||
JumpIfSelectSucceeded => {
|
||||
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")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
match reader.read_op() {
|
||||
HasAttrPathStatic => {
|
||||
reader.set_pc(reader.pc() + 4 + 4);
|
||||
}
|
||||
HasAttrPathDynamic => {
|
||||
reader.set_pc(reader.pc() + 4);
|
||||
}
|
||||
HasAttrStatic => {
|
||||
reader.set_pc(reader.pc() + 4);
|
||||
break Step::Continue(());
|
||||
}
|
||||
JumpIfSelectFailed => {
|
||||
let offset = reader.read_i32();
|
||||
reader.set_pc(((reader.pc() as isize) + (offset as isize)) as usize);
|
||||
}
|
||||
HasAttrDynamic => {
|
||||
break Step::Continue(());
|
||||
}
|
||||
HasAttrResolve => {
|
||||
reader.set_pc(reader.pc() - 1);
|
||||
break Step::Continue(());
|
||||
}
|
||||
other => {
|
||||
unreachable!("unexpected opcode {:?} in has_attr_skip", other as u8)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_has_attr_path_static<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
_ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let _span_id = reader.read_u32();
|
||||
let key = reader.read_string_id();
|
||||
|
||||
let current = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
|
||||
match current
|
||||
.downcast::<AttrSet>()
|
||||
.and_then(|attrs| attrs.lookup(key))
|
||||
{
|
||||
Some(v) => {
|
||||
m.push(v);
|
||||
}
|
||||
None => return has_attr_skip(reader),
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_has_attr_path_dynamic<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let _span_id = reader.read_u32();
|
||||
|
||||
let (current, key_val) = m.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
|
||||
let key_sid = match ctx.get_string_id(key_val) {
|
||||
Ok(id) => id,
|
||||
Err(got) => return m.finish_type_err(NixType::String, got),
|
||||
};
|
||||
|
||||
match current
|
||||
.downcast::<AttrSet>()
|
||||
.and_then(|attrs| attrs.lookup(key_sid))
|
||||
{
|
||||
Some(v) => {
|
||||
m.push(v);
|
||||
}
|
||||
None => return has_attr_skip(reader),
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_jump_if_select_failed<'gc, M: Machine<'gc>>(
|
||||
_m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
) -> Step {
|
||||
// No-op
|
||||
let _offset = reader.read_i32();
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[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<'_>,
|
||||
) -> Step {
|
||||
let offset = reader.read_i32();
|
||||
reader.set_pc(((reader.pc() as isize) + (offset as isize)) as usize);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_has_attr_static<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let key = reader.read_string_id();
|
||||
let current = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
|
||||
m.push(Value::new(
|
||||
current
|
||||
.downcast::<AttrSet>()
|
||||
match current
|
||||
.as_gc::<AttrSet>()
|
||||
.and_then(|attrs| attrs.lookup(key))
|
||||
.is_some(),
|
||||
));
|
||||
// Skip HasAttrResolve
|
||||
reader.set_pc(reader.pc() + 1);
|
||||
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_has_attr_dynamic<'gc, M: MachineExt<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (current, dyn_key) = m.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
|
||||
let key_sid = match ctx.get_string_id(dyn_key) {
|
||||
Ok(id) => id,
|
||||
Err(got) => return m.finish_type_err(NixType::String, got),
|
||||
};
|
||||
|
||||
m.push(Value::new(
|
||||
current
|
||||
.downcast::<AttrSet>()
|
||||
.and_then(|attrs| attrs.lookup(key_sid))
|
||||
.is_some(),
|
||||
));
|
||||
// Skip HasAttrResolve
|
||||
reader.set_pc(reader.pc() + 1);
|
||||
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_has_attr_resolve<'gc, M: Machine<'gc>>(m: &mut M) -> Step {
|
||||
// If we reach here, has_attr check has failed, push false (AttrSet is already popped)
|
||||
m.push(Value::new(false));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_make_list<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let count = reader.read_u32() as usize;
|
||||
let mut items: SmallVec<[Value; 4]> = SmallVec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
items.push(resolve_operand(&reader.read_operand_data(), mc, ctx, m));
|
||||
{
|
||||
Some(v) => {
|
||||
self.push(v);
|
||||
}
|
||||
None => return self.has_attr_skip(reader),
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
let list = Gc::new(
|
||||
mc,
|
||||
List {
|
||||
inner: RefLock::new(items),
|
||||
},
|
||||
);
|
||||
m.push(Value::new(list));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_make_empty_list<'gc, M: Machine<'gc>>(m: &mut M) -> Step {
|
||||
m.push(m.empty_list());
|
||||
Step::Continue(())
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_has_attr_path_dynamic(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let _span_id = reader.read_u32();
|
||||
|
||||
let (current, key_val) = self.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
|
||||
let key_sid = match ctx.get_string_id(key_val) {
|
||||
Ok(id) => id,
|
||||
Err(got) => return self.finish_type_err(NixType::String, got),
|
||||
};
|
||||
|
||||
match current
|
||||
.as_gc::<AttrSet>()
|
||||
.and_then(|attrs| attrs.lookup(key_sid))
|
||||
{
|
||||
Some(v) => {
|
||||
self.push(v);
|
||||
}
|
||||
None => return self.has_attr_skip(reader),
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_jump_if_select_failed(&mut self, reader: &mut BytecodeReader<'_>) -> Step {
|
||||
// No-op
|
||||
let _offset = reader.read_i32();
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_jump_if_select_succeeded(&mut self, reader: &mut BytecodeReader<'_>) -> Step {
|
||||
let offset = reader.read_i32();
|
||||
reader.set_pc(((reader.pc() as isize) + (offset as isize)) as usize);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_has_attr_static(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let key = reader.read_string_id();
|
||||
let current = self.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
|
||||
self.push(Value::new_inline(
|
||||
current
|
||||
.as_gc::<AttrSet>()
|
||||
.and_then(|attrs| attrs.lookup(key))
|
||||
.is_some(),
|
||||
));
|
||||
// Skip HasAttrResolve
|
||||
reader.set_pc(reader.pc() + 1);
|
||||
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_has_attr_dynamic(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (current, dyn_key) = self.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
|
||||
let key_sid = match ctx.get_string_id(dyn_key) {
|
||||
Ok(id) => id,
|
||||
Err(got) => return self.finish_type_err(NixType::String, got),
|
||||
};
|
||||
|
||||
self.push(Value::new_inline(
|
||||
current
|
||||
.as_gc::<AttrSet>()
|
||||
.and_then(|attrs| attrs.lookup(key_sid))
|
||||
.is_some(),
|
||||
));
|
||||
// Skip HasAttrResolve
|
||||
reader.set_pc(reader.pc() + 1);
|
||||
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_has_attr_resolve(&mut self) -> Step {
|
||||
// If we reach here, has_attr check has failed, push false (AttrSet is already popped)
|
||||
self.push(Value::new_inline(false));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_make_list(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let count = reader.read_u32() as usize;
|
||||
let mut items: SmallVec<[Value; 4]> = SmallVec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
items.push(reader.read_operand_data(ctx).resolve(mc, self));
|
||||
}
|
||||
let list = Gc::new(
|
||||
mc,
|
||||
List {
|
||||
inner: RefLock::new(items),
|
||||
},
|
||||
);
|
||||
self.push(Value::new_gc(list));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_make_empty_list(&mut self) -> Step {
|
||||
self.push(self.empty_list);
|
||||
Step::Continue(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,70 +1,60 @@
|
||||
use fix_error::Error;
|
||||
use fix_runtime::*;
|
||||
use gc_arena::Mutation;
|
||||
|
||||
use crate::value::*;
|
||||
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<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let offset = reader.read_i32();
|
||||
let cond = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
if cond.downcast::<bool>() == Some(false) {
|
||||
impl<'gc> crate::Vm<'gc> {
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_jump_if_false(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let offset = reader.read_i32();
|
||||
let cond = self.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
if cond.as_inline::<bool>() == Some(false) {
|
||||
reader.set_pc(((reader.pc() as isize) + (offset as isize)) as usize);
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_jump_if_true(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let offset = reader.read_i32();
|
||||
let cond = self.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
if cond.as_inline::<bool>() == Some(true) {
|
||||
reader.set_pc(((reader.pc() as isize) + (offset as isize)) as usize);
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_jump(&mut self, reader: &mut BytecodeReader<'_>) -> Step {
|
||||
let offset = reader.read_i32();
|
||||
reader.set_pc(((reader.pc() as isize) + (offset as isize)) as usize);
|
||||
Step::Continue(())
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[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<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let offset = reader.read_i32();
|
||||
let cond = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
if cond.downcast::<bool>() == Some(true) {
|
||||
reader.set_pc(((reader.pc() as isize) + (offset as isize)) as usize);
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_assert(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let raw_id = reader.read_string_id();
|
||||
let raw = ctx.resolve_string(raw_id);
|
||||
let _span_id = reader.read_u32();
|
||||
let assertion = self.force_and_retry::<bool>(reader, mc)?;
|
||||
if !assertion {
|
||||
// FIXME: use catchable error
|
||||
return self.finish_err(Error::eval_error(format!("assertion '{raw}' failed")));
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[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);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_assert<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let raw_id = reader.read_string_id();
|
||||
let raw = ctx.resolve_string(raw_id);
|
||||
let _span_id = reader.read_u32();
|
||||
let assertion = m.force_and_retry::<bool>(reader, mc)?;
|
||||
if !assertion {
|
||||
// FIXME: use catchable error
|
||||
return m.finish_err(Error::eval_error(format!("assertion '{raw}' failed")));
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
@@ -1,63 +1,55 @@
|
||||
use fix_runtime::Machine;
|
||||
use gc_arena::{Gc, Mutation};
|
||||
|
||||
use crate::{BytecodeReader, Step, Value};
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_push_smi<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
) -> Step {
|
||||
let val = reader.read_i32();
|
||||
m.push(Value::new(val));
|
||||
Step::Continue(())
|
||||
}
|
||||
impl<'gc> crate::Vm<'gc> {
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_push_smi(&mut self, reader: &mut BytecodeReader<'_>) -> Step {
|
||||
let val = reader.read_i32();
|
||||
self.push(Value::new_inline(val));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_push_bigint<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let val = reader.read_i64();
|
||||
m.push(Value::new(Gc::new(mc, val)));
|
||||
Step::Continue(())
|
||||
}
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_push_bigint(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let val = reader.read_i64();
|
||||
self.push(Value::new_gc(Gc::new(mc, val)));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_push_float<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
) -> Step {
|
||||
let val = reader.read_f64();
|
||||
m.push(Value::new(val));
|
||||
Step::Continue(())
|
||||
}
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_push_float(&mut self, reader: &mut BytecodeReader<'_>) -> Step {
|
||||
let val = reader.read_f64();
|
||||
self.push(Value::new_float(val));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_push_string<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
) -> Step {
|
||||
let sid = reader.read_string_id();
|
||||
m.push(Value::new(sid));
|
||||
Step::Continue(())
|
||||
}
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_push_string(&mut self, reader: &mut BytecodeReader<'_>) -> Step {
|
||||
let sid = reader.read_string_id();
|
||||
self.push(Value::new_inline(sid));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_push_null<'gc, M: Machine<'gc>>(m: &mut M) -> Step {
|
||||
m.push(Value::new(crate::Null));
|
||||
Step::Continue(())
|
||||
}
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_push_null(&mut self) -> Step {
|
||||
self.push(Value::new_inline(crate::Null));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_push_true<'gc, M: Machine<'gc>>(m: &mut M) -> Step {
|
||||
m.push(Value::new(true));
|
||||
Step::Continue(())
|
||||
}
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_push_true(&mut self) -> Step {
|
||||
self.push(Value::new_inline(true));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_push_false<'gc, M: Machine<'gc>>(m: &mut M) -> Step {
|
||||
m.push(Value::new(false));
|
||||
Step::Continue(())
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_push_false(&mut self) -> Step {
|
||||
self.push(Value::new_inline(false));
|
||||
Step::Continue(())
|
||||
}
|
||||
}
|
||||
|
||||
+148
-154
@@ -1,177 +1,159 @@
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Component, PathBuf};
|
||||
|
||||
use fix_bytecode::Continuation;
|
||||
use fix_builtins::BuiltinId;
|
||||
use fix_common::StringId;
|
||||
use fix_error::Error;
|
||||
use fix_lang::{BuiltinId, StringId};
|
||||
use fix_runtime::{
|
||||
AttrSet, Machine, MachineExt, NixString, Path, StrictValue, StringContext, canon_path_str,
|
||||
};
|
||||
use num_enum::TryFromPrimitive;
|
||||
|
||||
use crate::value::{AttrSet, NixString, StrictValue};
|
||||
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());
|
||||
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<'_>,
|
||||
) -> Step {
|
||||
let Ok(id) = BuiltinId::try_from(reader.read_u8())
|
||||
.map_err(|err| panic!("unknown builtin id: {}", err.number));
|
||||
m.push(Value::new(PrimOp {
|
||||
id,
|
||||
arity: id.info().arity,
|
||||
dispatch_ip: Continuation::entry_for_builtin(id).ip(),
|
||||
}));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_load_repl_binding<'gc, M: Machine<'gc>>(
|
||||
_m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
) -> Step {
|
||||
let _name = reader.read_string_id();
|
||||
todo!("LoadReplBinding");
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_load_scoped_binding<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
_mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let slot_id = reader.read_u32();
|
||||
let name = reader.read_string_id();
|
||||
let scope = m.scope_slot(slot_id);
|
||||
let Some(attrs) = scope.downcast::<AttrSet>() else {
|
||||
return m.finish_err(Error::eval_error("internal: scope slot is not an attrset"));
|
||||
};
|
||||
match attrs.lookup(name) {
|
||||
Some(val) => {
|
||||
m.push(val);
|
||||
Step::Continue(())
|
||||
}
|
||||
None => m.finish_err(Error::eval_error(format!(
|
||||
"scoped binding '{}' not found",
|
||||
ctx.resolve_string(name)
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_coerce_to_string<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let val = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
if val.is::<StringId>() || val.is::<NixString>() {
|
||||
m.push(val.relax());
|
||||
} else if let Some(p) = val.downcast::<Path>() {
|
||||
// Coercing a path to a string yields the canonical path text.
|
||||
// FIXME: copy to store
|
||||
m.push(Value::new(p.0));
|
||||
} else {
|
||||
todo!("coerce other types to string: {:?}", val.ty());
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_concat_strings<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let count = reader.read_u16() as usize;
|
||||
let _force_string = reader.read_u8() != 0;
|
||||
|
||||
let mut total_len = 0;
|
||||
let mut has_any_context = false;
|
||||
for i in 0..count {
|
||||
let val = m.peek_forced(count - 1 - i);
|
||||
let s = ctx.get_string(val).expect("coerced");
|
||||
total_len += s.len();
|
||||
if !ctx.get_string_context(val).is_empty() {
|
||||
has_any_context = true;
|
||||
}
|
||||
impl<'gc> crate::Vm<'gc> {
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_load_builtins(&mut self) -> Step {
|
||||
self.push(self.builtins);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
let mut result = String::with_capacity(total_len);
|
||||
let mut merged = StringContext::new();
|
||||
for i in 0..count {
|
||||
let val = m.peek_forced(count - 1 - i);
|
||||
let s = ctx.get_string(val).expect("coerced");
|
||||
result.push_str(s);
|
||||
if has_any_context {
|
||||
let ctx = ctx.get_string_context(val);
|
||||
if !ctx.is_empty() {
|
||||
merged = merged.merge(ctx);
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_load_builtin(&mut self, reader: &mut BytecodeReader<'_>) -> Step {
|
||||
let Ok(id) = BuiltinId::try_from_primitive(reader.read_u8())
|
||||
.map_err(|err| panic!("unknown builtin id: {}", err.number));
|
||||
self.push(Value::new_inline(PrimOp {
|
||||
id,
|
||||
arity: fix_builtins::BUILTINS[id as usize].1,
|
||||
dispatch_ip: id.entry_phase().ip(),
|
||||
}));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_load_repl_binding(&mut self, reader: &mut BytecodeReader<'_>) -> Step {
|
||||
let _name = reader.read_string_id();
|
||||
todo!("LoadReplBinding");
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_load_scoped_binding(
|
||||
&mut self,
|
||||
ctx: &impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
_mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let slot_id = reader.read_u32();
|
||||
let name = reader.read_string_id();
|
||||
let scope = match self.scope_slots.get(slot_id as usize).copied() {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
return self.finish_err(Error::eval_error(format!(
|
||||
"internal: invalid scope slot {slot_id}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
let Some(attrs) = scope.as_gc::<AttrSet>() else {
|
||||
return self.finish_err(Error::eval_error(
|
||||
"internal: scope slot is not an attrset",
|
||||
));
|
||||
};
|
||||
match attrs.lookup(name) {
|
||||
Some(val) => {
|
||||
self.push(val);
|
||||
Step::Continue(())
|
||||
}
|
||||
None => self.finish_err(Error::eval_error(format!(
|
||||
"scoped binding '{}' not found",
|
||||
ctx.resolve_string(name)
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
m.drop_n(count);
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_coerce_to_string(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let val = self.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
if val.is::<StringId>() || val.is::<NixString>() {
|
||||
self.push(val.relax());
|
||||
} else {
|
||||
todo!("coerce other types to string: {:?}", val.ty());
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_concat_strings(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
_mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let count = reader.read_u16() as usize;
|
||||
let _force_string = reader.read_u8() != 0;
|
||||
|
||||
let mut total_len = 0;
|
||||
for i in 0..count {
|
||||
let val = self.peek_forced(count - 1 - i);
|
||||
let s = ctx.get_string(val).expect("coerced");
|
||||
total_len += s.len();
|
||||
}
|
||||
|
||||
let mut result = String::with_capacity(total_len);
|
||||
for i in 0..count {
|
||||
let val = self.peek_forced(count - 1 - i);
|
||||
let s = ctx.get_string(val).expect("coerced");
|
||||
result.push_str(s);
|
||||
}
|
||||
|
||||
self.stack.truncate(self.stack.len() - count);
|
||||
|
||||
if merged.is_empty() {
|
||||
let sid = ctx.intern_string(result);
|
||||
m.push(Value::new(sid));
|
||||
} else {
|
||||
let ns = gc_arena::Gc::new(mc, NixString::with_context(result, merged));
|
||||
m.push(Value::new(ns));
|
||||
self.push(Value::new_inline(sid));
|
||||
Step::Continue(())
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_resolve_path<'gc, M: MachineExt<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let path_val = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
let dir_id = reader.read_string_id();
|
||||
// Already a path: keep as-is. ResolvePath is idempotent on paths.
|
||||
if let Some(p) = path_val.downcast::<Path>() {
|
||||
m.push(Value::new(p));
|
||||
return Step::Continue(());
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_resolve_path(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
let path_val = self.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
let dir_id = reader.read_string_id();
|
||||
let path = match ctx.get_string(path_val) {
|
||||
Some(s) => s.to_owned(),
|
||||
None => {
|
||||
return self.finish_err(Error::eval_error(format!(
|
||||
"expected a string for path, got {}",
|
||||
path_val.ty()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let resolved = match resolve_path_str(ctx.resolve_string(dir_id), &path) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return self.finish_err(e),
|
||||
};
|
||||
let sid = ctx.intern_string(resolved);
|
||||
self.push(Value::new_inline(sid));
|
||||
Step::Continue(())
|
||||
}
|
||||
let path = match ctx.get_string(path_val) {
|
||||
Some(s) => s.to_owned(),
|
||||
None => {
|
||||
return m.finish_err(Error::eval_error(format!(
|
||||
"expected a string for path, got {}",
|
||||
path_val.ty()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let resolved = match resolve_path_str(ctx.resolve_string(dir_id), &path) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return m.finish_err(e),
|
||||
};
|
||||
let sid = ctx.intern_string(resolved);
|
||||
m.push(Value::new(Path(sid)));
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
/// Resolve a Nix path literal against `current_dir`.
|
||||
///
|
||||
/// Mirrors nix-js's `op_resolve_path`: absolute paths returned as-is, `~/X`
|
||||
/// expanded against `$HOME`, otherwise joined onto `current_dir`. The result
|
||||
/// is normalized by removing `.` components and resolving `..` lexically
|
||||
/// (no symlink resolution).
|
||||
fn resolve_path_str(current_dir: &str, path: &str) -> Result<String, Box<Error>> {
|
||||
let raw = if path.starts_with('/') {
|
||||
return Ok(canon_path_str(path));
|
||||
return Ok(path.to_owned());
|
||||
} else if let Some(rest) = path.strip_prefix("~/") {
|
||||
let mut dir =
|
||||
std::env::home_dir().ok_or_else(|| Error::eval_error("home dir not defined"))?;
|
||||
#[allow(deprecated)]
|
||||
let mut dir = std::env::home_dir()
|
||||
.ok_or_else(|| Error::eval_error("home dir not defined"))?;
|
||||
dir.push(rest);
|
||||
dir
|
||||
} else {
|
||||
@@ -179,5 +161,17 @@ fn resolve_path_str(current_dir: &str, path: &str) -> Result<String, Box<Error>>
|
||||
dir.push(path);
|
||||
dir
|
||||
};
|
||||
Ok(canon_path_str(&raw))
|
||||
let mut normalized = PathBuf::new();
|
||||
for component in raw.components() {
|
||||
match component {
|
||||
Component::Prefix(p) => normalized.push(p.as_os_str()),
|
||||
Component::RootDir => normalized.push("/"),
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
normalized.pop();
|
||||
}
|
||||
Component::Normal(c) => normalized.push(c),
|
||||
}
|
||||
}
|
||||
Ok(normalized.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
@@ -7,13 +7,3 @@ pub(crate) mod literals;
|
||||
pub(crate) mod misc;
|
||||
pub(crate) mod variables;
|
||||
pub(crate) mod with_scope;
|
||||
|
||||
pub(crate) use arithmetic::*;
|
||||
pub(crate) use calls::*;
|
||||
pub(crate) use closures::*;
|
||||
pub(crate) use collections::*;
|
||||
pub(crate) use control::*;
|
||||
pub(crate) use literals::*;
|
||||
pub(crate) use misc::*;
|
||||
pub(crate) use variables::*;
|
||||
pub(crate) use with_scope::*;
|
||||
|
||||
@@ -1,68 +1,50 @@
|
||||
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<'_>,
|
||||
) -> Step {
|
||||
let idx = reader.read_u32() as usize;
|
||||
m.push(m.env().borrow().locals[idx]);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[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<'_>,
|
||||
) -> Step {
|
||||
let layer = reader.read_u8();
|
||||
let idx = reader.read_u32() as usize;
|
||||
let mut cur = m.env();
|
||||
for _ in 0..layer {
|
||||
let prev = cur.borrow().prev.expect("LoadOuter: env chain too short");
|
||||
cur = prev;
|
||||
impl<'gc> crate::Vm<'gc> {
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_load_local(&mut self, reader: &mut BytecodeReader<'_>) -> Step {
|
||||
let idx = reader.read_u32() as usize;
|
||||
self.push(self.env.borrow().locals[idx]);
|
||||
Step::Continue(())
|
||||
}
|
||||
let val = cur.borrow().locals[idx];
|
||||
m.push(val);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[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<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let idx = reader.read_u32() as usize;
|
||||
let val = m.pop();
|
||||
m.env().borrow_mut(mc).locals[idx] = val;
|
||||
Step::Continue(())
|
||||
}
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_load_outer(&mut self, reader: &mut BytecodeReader<'_>) -> Step {
|
||||
let layer = reader.read_u8();
|
||||
let idx = reader.read_u32() as usize;
|
||||
let mut cur = self.env;
|
||||
for _ in 0..layer {
|
||||
let prev = cur.borrow().prev.expect("LoadOuter: env chain too short");
|
||||
cur = prev;
|
||||
}
|
||||
let val = cur.borrow().locals[idx];
|
||||
self.push(val);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_alloc_locals<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let count = reader.read_u32() as usize;
|
||||
m.env()
|
||||
.borrow_mut(mc)
|
||||
.locals
|
||||
.extend(std::iter::repeat_n(Value::default(), count));
|
||||
Step::Continue(())
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_store_local(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let idx = reader.read_u32() as usize;
|
||||
let val = self.pop();
|
||||
self.env.borrow_mut(mc).locals[idx] = val;
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_alloc_locals(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let count = reader.read_u32() as usize;
|
||||
self.env
|
||||
.borrow_mut(mc)
|
||||
.locals
|
||||
.extend(std::iter::repeat_n(Value::default(), count));
|
||||
Step::Continue(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,84 +1,78 @@
|
||||
use fix_common::Symbol;
|
||||
use fix_error::Error;
|
||||
use fix_lang::Symbol;
|
||||
use fix_runtime::{resolve_operand, *};
|
||||
use smallvec::SmallVec;
|
||||
|
||||
use crate::value::*;
|
||||
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");
|
||||
impl<'gc> crate::Vm<'gc> {
|
||||
#[inline(always)]
|
||||
pub(crate) fn op_lookup_with(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &gc_arena::Mutation<'gc>,
|
||||
) -> Step {
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let counter = self.peek_forced(0).as_inline::<i32>().unwrap();
|
||||
|
||||
let name = reader.read_string_id();
|
||||
let n = reader.read_u8();
|
||||
let mut namespaces = SmallVec::<[_; 2]>::new();
|
||||
for _ in 0..n {
|
||||
namespaces.push(resolve_operand(&reader.read_operand_data(), mc, ctx, m));
|
||||
}
|
||||
let name = reader.read_string_id();
|
||||
let n = reader.read_u8();
|
||||
let mut namespaces = SmallVec::<[_; 2]>::new();
|
||||
for _ in 0..n {
|
||||
namespaces.push(reader.read_operand_data(ctx).resolve(mc, self));
|
||||
}
|
||||
|
||||
let resume_pc = reader.inst_start_pc();
|
||||
let namespace = match namespaces[counter as usize].restrict() {
|
||||
Ok(val) => val,
|
||||
Err(thunk) => {
|
||||
let mut state = thunk.borrow_mut(mc);
|
||||
match *state {
|
||||
ThunkState::Pending { ip, env } => {
|
||||
*state = ThunkState::Blackhole;
|
||||
m.push_call_frame(CallFrame {
|
||||
thunk: Some(thunk),
|
||||
pc: resume_pc,
|
||||
env: m.env(),
|
||||
depth: None,
|
||||
});
|
||||
m.set_env(env);
|
||||
reader.set_pc(ip);
|
||||
return Step::Break(Break::Force);
|
||||
}
|
||||
ThunkState::Evaluated(v) => v,
|
||||
ThunkState::Apply { func, arg } => {
|
||||
m.push_call_frame(CallFrame {
|
||||
thunk: Some(thunk),
|
||||
pc: resume_pc,
|
||||
env: m.env(),
|
||||
depth: None,
|
||||
});
|
||||
m.push(func);
|
||||
return m.call(reader, mc, arg, resume_pc);
|
||||
}
|
||||
ThunkState::Blackhole => {
|
||||
return m.finish_err(Error::eval_error("infinite recursion encountered"));
|
||||
let resume_pc = reader.inst_start_pc();
|
||||
let namespace = match namespaces[counter as usize].restrict() {
|
||||
Ok(val) => val,
|
||||
Err(thunk) => {
|
||||
let mut state = thunk.borrow_mut(mc);
|
||||
match *state {
|
||||
ThunkState::Pending { ip, env } => {
|
||||
*state = ThunkState::Blackhole;
|
||||
self.call_stack.push(CallFrame {
|
||||
thunk: Some(thunk),
|
||||
pc: resume_pc,
|
||||
env: self.env,
|
||||
});
|
||||
self.env = env;
|
||||
reader.set_pc(ip);
|
||||
return Step::Break(Break::Force);
|
||||
}
|
||||
ThunkState::Evaluated(v) => v,
|
||||
ThunkState::Apply { func, arg } => {
|
||||
self.call_stack.push(CallFrame {
|
||||
thunk: Some(thunk),
|
||||
pc: resume_pc,
|
||||
env: self.env,
|
||||
});
|
||||
self.push(func);
|
||||
return self.call(reader, mc, arg, resume_pc);
|
||||
}
|
||||
ThunkState::Blackhole => {
|
||||
return self
|
||||
.finish_err(Error::eval_error("infinite recursion encountered"));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(val) = namespace
|
||||
.as_gc::<AttrSet>()
|
||||
.and_then(|attrs| attrs.lookup(name))
|
||||
{
|
||||
self.replace(0, val);
|
||||
} else if counter + 1 == n as i32 {
|
||||
return self.finish_err(Error::eval_error(format!(
|
||||
"undefined variable '{}'",
|
||||
Symbol::from(ctx.resolve_string(name))
|
||||
)));
|
||||
} else {
|
||||
self.replace(0, Value::new_inline(counter + 1));
|
||||
reader.set_pc(resume_pc);
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(val) = namespace
|
||||
.downcast::<AttrSet>()
|
||||
.and_then(|attrs| attrs.lookup(name))
|
||||
{
|
||||
m.replace(0, val);
|
||||
} else if counter + 1 == n as i32 {
|
||||
return m.finish_err(Error::eval_error(format!(
|
||||
"undefined variable '{}'",
|
||||
Symbol::from(ctx.resolve_string(name))
|
||||
)));
|
||||
} else {
|
||||
m.replace(0, Value::new(counter + 1));
|
||||
reader.set_pc(resume_pc);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
+510
-311
@@ -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)
|
||||
@@ -9,36 +7,220 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use fix_bytecode::{Continuation, InstructionPtr};
|
||||
use fix_builtins::{BUILTINS, BuiltinId};
|
||||
use fix_codegen::InstructionPtr;
|
||||
use fix_common::StringId;
|
||||
use fix_error::{Error, Result, Source};
|
||||
use fix_lang::{BuiltinId, StringId};
|
||||
use gc_arena::metrics::Pacing;
|
||||
use gc_arena::arena::CollectionPhase;
|
||||
use gc_arena::{Arena, Collect, Gc, Mutation, RefLock, Rootable};
|
||||
use hashbrown::HashMap;
|
||||
use hashbrown::{HashMap, HashSet};
|
||||
use num_enum::TryFromPrimitive;
|
||||
use smallvec::SmallVec;
|
||||
|
||||
mod boxing;
|
||||
mod bytecode_reader;
|
||||
#[cfg(feature = "tailcall")]
|
||||
mod dispatch_tailcall;
|
||||
pub use fix_runtime::*;
|
||||
#[doc(hidden)]
|
||||
#[path = "macro_support.rs"]
|
||||
pub mod __macro_support;
|
||||
mod forced;
|
||||
mod value;
|
||||
pub use value::StaticValue;
|
||||
use value::*;
|
||||
mod helpers;
|
||||
mod instructions;
|
||||
use bytecode_reader::BytecodeReader;
|
||||
use forced::Forced;
|
||||
use helpers::*;
|
||||
mod primops;
|
||||
extern crate self as fix_vm;
|
||||
|
||||
type VmResult<T> = std::result::Result<T, VmError>;
|
||||
|
||||
#[allow(dead_code)]
|
||||
enum VmError {
|
||||
Catchable(String),
|
||||
Uncatchable(Box<Error>),
|
||||
}
|
||||
|
||||
impl From<Box<Error>> for VmError {
|
||||
fn from(e: Box<Error>) -> Self {
|
||||
VmError::Uncatchable(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl VmError {
|
||||
fn into_error(self) -> Box<Error> {
|
||||
match self {
|
||||
VmError::Catchable(_) => todo!("Check for tryEval catch frames"),
|
||||
VmError::Uncatchable(e) => e,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Collect, Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
#[collect(require_static)]
|
||||
pub enum ForceMode {
|
||||
#[default]
|
||||
AsIs,
|
||||
Shallow,
|
||||
Deep,
|
||||
}
|
||||
|
||||
pub trait VmContext {
|
||||
fn split(&mut self) -> (&mut impl VmCode, &mut impl VmRuntimeCtx);
|
||||
}
|
||||
|
||||
pub trait VmRuntimeCtx {
|
||||
fn intern_string(&mut self, s: impl AsRef<str>) -> StringId;
|
||||
fn resolve_string(&self, id: StringId) -> &str;
|
||||
fn get_const(&self, id: u32) -> StaticValue;
|
||||
fn add_const(&mut self, val: StaticValue) -> u32;
|
||||
}
|
||||
|
||||
pub trait VmCode {
|
||||
fn bytecode(&self) -> &[u8];
|
||||
fn compile_with_scope(
|
||||
&mut self,
|
||||
source: Source,
|
||||
extra_scope: Option<ExtraScope>,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
) -> fix_error::Result<InstructionPtr>;
|
||||
}
|
||||
|
||||
/// Extra scope passed to a re-entrant compile from inside a running VM.
|
||||
///
|
||||
/// Currently only `ScopedImport` is produced (by the `scopedImport` builtin),
|
||||
/// but the variant is kept open so REPL bindings could later land here too.
|
||||
pub enum ExtraScope {
|
||||
ScopedImport {
|
||||
keys: HashSet<StringId>,
|
||||
slot_id: u32,
|
||||
},
|
||||
}
|
||||
|
||||
trait VmRuntimeCtxExt: VmRuntimeCtx {
|
||||
fn get_string<'a, 'gc: 'a>(&'a self, val: StrictValue<'gc>) -> Option<&'a str>;
|
||||
fn get_string_id<'a, 'gc: 'a>(
|
||||
&'a mut self,
|
||||
val: StrictValue<'gc>,
|
||||
) -> std::result::Result<StringId, NixType>;
|
||||
fn convert_value(&self, val: Value) -> fix_common::Value;
|
||||
}
|
||||
|
||||
impl<T: VmRuntimeCtx> VmRuntimeCtxExt for T {
|
||||
fn get_string<'a, 'gc: 'a>(&'a self, val: StrictValue<'gc>) -> Option<&'a str> {
|
||||
if let Some(sid) = val.as_inline::<StringId>() {
|
||||
Some(self.resolve_string(sid))
|
||||
} else {
|
||||
val.as_gc::<NixString>().map(|ns| ns.as_ref().as_str())
|
||||
}
|
||||
}
|
||||
|
||||
fn get_string_id<'a, 'gc: 'a>(
|
||||
&'a mut self,
|
||||
val: StrictValue<'gc>,
|
||||
) -> std::result::Result<StringId, NixType> {
|
||||
if let Some(sid) = val.as_inline::<StringId>() {
|
||||
Ok(sid)
|
||||
} else if let Some(s) = val.as_gc::<NixString>().map(|ns| ns.as_ref().as_str()) {
|
||||
Ok(self.intern_string(s))
|
||||
} else {
|
||||
Err(val.ty())
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_value(&self, val: Value) -> fix_common::Value {
|
||||
self.convert_value_with_seen(val, &mut HashSet::new())
|
||||
}
|
||||
}
|
||||
|
||||
trait ConvertValueWithSeen: VmRuntimeCtx {
|
||||
fn convert_value_with_seen(&self, val: Value, seen: &mut HashSet<u64>) -> fix_common::Value;
|
||||
}
|
||||
|
||||
impl<T: VmRuntimeCtx> ConvertValueWithSeen for T {
|
||||
fn convert_value_with_seen(&self, val: Value, seen: &mut HashSet<u64>) -> fix_common::Value {
|
||||
use fix_common::Value;
|
||||
if let Some(i) = val.as_inline::<i32>() {
|
||||
Value::Int(i as i64)
|
||||
} else if let Some(gc_i) = val.as_gc::<i64>() {
|
||||
Value::Int(*gc_i)
|
||||
} else if let Some(f) = val.as_float() {
|
||||
Value::Float(f)
|
||||
} else if let Some(b) = val.as_inline::<bool>() {
|
||||
Value::Bool(b)
|
||||
} else if val.is::<Null>() {
|
||||
Value::Null
|
||||
} else if let Some(sid) = val.as_inline::<StringId>() {
|
||||
let s = self.resolve_string(sid).to_owned();
|
||||
Value::String(s)
|
||||
} else if let Some(ns) = val.as_gc::<NixString>() {
|
||||
Value::String(ns.as_str().to_owned())
|
||||
} else if let Some(attrs) = val.as_gc::<AttrSet>() {
|
||||
let bits = val.to_bits();
|
||||
if attrs.entries.is_empty() {
|
||||
return Value::AttrSet(Default::default());
|
||||
}
|
||||
if !seen.insert(bits) {
|
||||
return Value::Repeated;
|
||||
}
|
||||
let mut map = std::collections::BTreeMap::new();
|
||||
for &(key, val) in attrs.entries.iter() {
|
||||
let key = self.resolve_string(key).to_owned();
|
||||
let converted = self.convert_value_with_seen(val, seen);
|
||||
map.insert(fix_common::Symbol::from(key), converted);
|
||||
}
|
||||
Value::AttrSet(fix_common::AttrSet::new(map))
|
||||
} else if let Some(list) = val.as_gc::<List>() {
|
||||
let bits = val.to_bits();
|
||||
if list.inner.borrow().is_empty() {
|
||||
return Value::List(Default::default());
|
||||
}
|
||||
if !seen.insert(bits) {
|
||||
return Value::Repeated;
|
||||
}
|
||||
let items: Vec<_> = list
|
||||
.inner
|
||||
.borrow()
|
||||
.iter()
|
||||
.copied()
|
||||
.map(|v| self.convert_value_with_seen(v, seen))
|
||||
.collect();
|
||||
Value::List(fix_common::List::new(items))
|
||||
} else if val.is::<Closure>() {
|
||||
Value::Func
|
||||
} else if let Some(thunk) = val.as_gc::<Thunk>() {
|
||||
if let ThunkState::Evaluated(v) = *thunk.borrow() {
|
||||
self.convert_value_with_seen(v.relax(), seen)
|
||||
} else {
|
||||
Value::Thunk
|
||||
}
|
||||
} else if let Some(primop) = val.as_inline::<PrimOp>() {
|
||||
let name = fix_builtins::BUILTINS[primop.id as usize].0;
|
||||
Value::PrimOp(name.strip_prefix("__").unwrap_or(name))
|
||||
} else if let Some(app) = val.as_gc::<PrimOpApp>() {
|
||||
let name = fix_builtins::BUILTINS[app.primop.id as usize].0;
|
||||
Value::PrimOpApp(name.strip_prefix("__").unwrap_or(name))
|
||||
} else {
|
||||
Value::Null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(u8)]
|
||||
enum Break {
|
||||
Force,
|
||||
Done,
|
||||
LoadFile,
|
||||
}
|
||||
|
||||
type Step = std::ops::ControlFlow<Break>;
|
||||
|
||||
#[derive(Collect)]
|
||||
#[collect(no_drop)]
|
||||
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,14 +229,14 @@ 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>,
|
||||
|
||||
force_mode: ForceMode,
|
||||
|
||||
#[collect(require_static)]
|
||||
result: Option<Result<fix_lang::Value>>,
|
||||
result: Option<Result<fix_common::Value>>,
|
||||
|
||||
#[collect(require_static)]
|
||||
pending_load: Option<PendingLoad>,
|
||||
@@ -62,16 +244,77 @@ 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);
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct PendingLoad {
|
||||
pub path: PathBuf,
|
||||
pub scope: Option<PendingScope>,
|
||||
}
|
||||
|
||||
for id in BuiltinId::ALL {
|
||||
let arity = id.info().arity;
|
||||
let name = ctx.intern_string(id.info().name);
|
||||
let dispatch_ip = Continuation::entry_for_builtin(id).ip();
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct PendingScope {
|
||||
pub keys: HashSet<StringId>,
|
||||
pub slot_id: u32,
|
||||
}
|
||||
|
||||
enum OperandData {
|
||||
Const(StaticValue),
|
||||
BigInt(i64),
|
||||
Local { layer: u8, idx: u32 },
|
||||
BuiltinConst(StringId),
|
||||
Builtins,
|
||||
ReplBinding(StringId),
|
||||
ScopedImportBinding { slot_id: u32, name: StringId },
|
||||
}
|
||||
|
||||
impl OperandData {
|
||||
fn resolve<'gc>(&self, mc: &Mutation<'gc>, root: &Vm<'gc>) -> Value<'gc> {
|
||||
use OperandData::*;
|
||||
match *self {
|
||||
Const(sv) => sv.into(),
|
||||
BigInt(val) => Value::new_gc(Gc::new(mc, val)),
|
||||
Local { layer, idx } => {
|
||||
let mut cur = root.env;
|
||||
for _ in 0..layer {
|
||||
let prev = cur.borrow().prev.expect("env chain too short");
|
||||
cur = prev;
|
||||
}
|
||||
cur.borrow().locals[idx as usize]
|
||||
}
|
||||
#[allow(clippy::unwrap_used)]
|
||||
BuiltinConst(id) => root
|
||||
.builtins
|
||||
.as_gc::<AttrSet>()
|
||||
.unwrap()
|
||||
.lookup(id)
|
||||
.unwrap(),
|
||||
Builtins => root.builtins,
|
||||
ReplBinding(_id) => todo!(),
|
||||
ScopedImportBinding { slot_id, name } => {
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let scope = root
|
||||
.scope_slots
|
||||
.get(slot_id as usize)
|
||||
.expect("invalid scope slot");
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let attrs = scope.as_gc::<AttrSet>().expect("scope must be attrset");
|
||||
#[allow(clippy::unwrap_used)]
|
||||
attrs.lookup(name).expect("scoped binding not found")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn init_builtins<'gc>(mc: &Mutation<'gc>, ctx: &mut impl VmRuntimeCtx) -> Value<'gc> {
|
||||
let mut entries = SmallVec::with_capacity(BUILTINS.len());
|
||||
|
||||
for (idx, &(name, arity)) in BUILTINS.iter().enumerate() {
|
||||
let id = BuiltinId::try_from_primitive(idx as u8).expect("infallible");
|
||||
let name = name.strip_prefix("__").unwrap_or(name);
|
||||
let name = ctx.intern_string(name);
|
||||
let dispatch_ip = id.entry_phase().ip();
|
||||
entries.push((
|
||||
name,
|
||||
Value::new(PrimOp {
|
||||
Value::new_inline(PrimOp {
|
||||
id,
|
||||
arity,
|
||||
dispatch_ip,
|
||||
@@ -82,15 +325,21 @@ fn init_builtins<'gc>(mc: &Mutation<'gc>, ctx: &mut impl VmRuntimeCtx) -> Gc<'gc
|
||||
let consts = [
|
||||
(
|
||||
"__currentSystem",
|
||||
Value::new(ctx.intern_string("x86_64-linux")),
|
||||
Value::new_inline(ctx.intern_string("x86_64-linux")),
|
||||
),
|
||||
("__langVersion", Value::new(6i32)),
|
||||
("__nixVersion", Value::new(ctx.intern_string("2.24.0"))),
|
||||
("__storeDir", Value::new(ctx.intern_string("/nix/store"))),
|
||||
("__nixPath", Value::new(Gc::new(mc, List::default()))),
|
||||
("null", Value::new(Null)),
|
||||
("true", Value::new(true)),
|
||||
("false", Value::new(false)),
|
||||
("__langVersion", Value::new_inline(6i32)),
|
||||
(
|
||||
"__nixVersion",
|
||||
Value::new_inline(ctx.intern_string("2.24.0")),
|
||||
),
|
||||
(
|
||||
"__storeDir",
|
||||
Value::new_inline(ctx.intern_string("/nix/store")),
|
||||
),
|
||||
("__nixPath", Value::new_gc(Gc::new(mc, List::default()))),
|
||||
("null", Value::new_inline(Null)),
|
||||
("true", Value::new_inline(true)),
|
||||
("false", Value::new_inline(false)),
|
||||
];
|
||||
|
||||
for (name, val) in consts {
|
||||
@@ -101,15 +350,15 @@ fn init_builtins<'gc>(mc: &Mutation<'gc>, ctx: &mut impl VmRuntimeCtx) -> Gc<'gc
|
||||
|
||||
let self_ref_thunk = Gc::new(mc, RefLock::new(ThunkState::Blackhole));
|
||||
let sym = ctx.intern_string("builtins");
|
||||
entries.push((sym, Value::new(self_ref_thunk)));
|
||||
entries.push((sym, Value::new_gc(self_ref_thunk)));
|
||||
|
||||
entries.sort_by_key(|(k, _)| *k);
|
||||
|
||||
let builtins_set = Gc::new(mc, AttrSet::from_sorted_unchecked(entries));
|
||||
let builtins_value = Value::new(builtins_set);
|
||||
let builtins_value = Value::new_gc(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> {
|
||||
@@ -127,8 +376,8 @@ impl<'gc> Vm<'gc> {
|
||||
scope_slots: Vec::new(),
|
||||
|
||||
builtins,
|
||||
empty_list: Value::new(Gc::new(mc, List::default())),
|
||||
empty_attrs: Value::new(Gc::new(mc, AttrSet::default())),
|
||||
empty_list: Value::new_gc(Gc::new(mc, List::default())),
|
||||
empty_attrs: Value::new_gc(Gc::new(mc, AttrSet::default())),
|
||||
|
||||
force_mode,
|
||||
|
||||
@@ -138,157 +387,9 @@ impl<'gc> Vm<'gc> {
|
||||
functor_sym: ctx.intern_string("__functor"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc> Machine<'gc> for Vm<'gc> {
|
||||
#[inline(always)]
|
||||
fn push(&mut self, val: Value<'gc>) {
|
||||
self.stack.push(val);
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop(&mut self) -> Value<'gc> {
|
||||
self.stack.pop().expect("stack underflow")
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn peek(&self, depth: usize) -> Value<'gc> {
|
||||
*self
|
||||
.stack
|
||||
.get(self.stack.len() - depth - 1)
|
||||
.expect("stack underflow")
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn peek_forced(&self, depth: usize) -> StrictValue<'gc> {
|
||||
self.stack
|
||||
.get(self.stack.len() - depth - 1)
|
||||
.expect("stack underflow")
|
||||
.restrict()
|
||||
.expect("forced")
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop_forced(&mut self) -> StrictValue<'gc> {
|
||||
self.stack
|
||||
.pop()
|
||||
.expect("stack underflow")
|
||||
.restrict()
|
||||
.expect("forced")
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn replace(&mut self, depth: usize, val: Value<'gc>) {
|
||||
let len = self.stack.len();
|
||||
*self
|
||||
.stack
|
||||
.get_mut(len - depth - 1)
|
||||
.expect("stack underflow") = val;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn drop_n(&mut self, depth: usize) {
|
||||
self.stack.truncate(self.stack.len() - depth);
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn stack_len(&self) -> usize {
|
||||
self.stack.len()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn force_slot_to_pc(
|
||||
&mut self,
|
||||
depth: usize,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
resume_pc: usize,
|
||||
) -> Step {
|
||||
let Some(thunk) = self.peek(depth).downcast::<Thunk>() else {
|
||||
return Step::Continue(());
|
||||
};
|
||||
let mut state = thunk.borrow_mut(mc);
|
||||
match *state {
|
||||
ThunkState::Pending { ip, env } => {
|
||||
*state = ThunkState::Blackhole;
|
||||
self.call_stack.push(CallFrame {
|
||||
thunk: Some(thunk),
|
||||
pc: resume_pc,
|
||||
env: self.env,
|
||||
depth: Some(depth),
|
||||
});
|
||||
self.env = env;
|
||||
reader.set_pc(ip);
|
||||
Step::Break(Break::Force)
|
||||
}
|
||||
ThunkState::Evaluated(v) => {
|
||||
self.replace(depth, v.relax());
|
||||
Step::Continue(())
|
||||
}
|
||||
ThunkState::Apply { func, arg } => {
|
||||
self.call_stack.push(CallFrame {
|
||||
thunk: Some(thunk),
|
||||
pc: resume_pc,
|
||||
env: self.env,
|
||||
depth: Some(depth),
|
||||
});
|
||||
self.push(func);
|
||||
self.call(reader, mc, arg, resume_pc)
|
||||
}
|
||||
ThunkState::Blackhole => {
|
||||
self.finish_err(Error::eval_error("infinite recursion encountered"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn call(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
arg: Value<'gc>,
|
||||
resume_pc: usize,
|
||||
) -> Step {
|
||||
instructions::call(self, reader, mc, arg, resume_pc)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn push_call_frame(&mut self, frame: CallFrame<'gc>) {
|
||||
self.call_stack.push(frame);
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn pop_call_frame(&mut self) -> Option<CallFrame<'gc>> {
|
||||
self.call_stack.pop()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn call_depth(&self) -> usize {
|
||||
self.call_depth
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn inc_call_depth(&mut self) {
|
||||
self.call_depth += 1;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn dec_call_depth(&mut self) {
|
||||
self.call_depth -= 1;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn env(&self) -> GcEnv<'gc> {
|
||||
self.env
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn set_env(&mut self, env: GcEnv<'gc>) {
|
||||
self.env = env;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn finish_ok(&mut self, val: fix_lang::Value) -> Step {
|
||||
fn finish_ok(&mut self, val: fix_common::Value) -> Step {
|
||||
self.result = Some(Ok(val));
|
||||
Step::Break(Break::Done)
|
||||
}
|
||||
@@ -308,79 +409,185 @@ impl<'gc> Machine<'gc> for Vm<'gc> {
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn builtins(&self) -> Gc<'gc, AttrSet<'gc>> {
|
||||
self.builtins
|
||||
fn finish_vm_err(&mut self, err: VmError) -> Step {
|
||||
self.finish_err(err.into_error())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn functor_sym(&self) -> StringId {
|
||||
self.functor_sym
|
||||
fn push(&mut self, val: Value<'gc>) {
|
||||
self.stack.push(val);
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn empty_list(&self) -> Value<'gc> {
|
||||
self.empty_list
|
||||
#[must_use]
|
||||
fn pop(&mut self) -> Value<'gc> {
|
||||
self.stack.pop().expect("stack underflow")
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn empty_attrs(&self) -> Value<'gc> {
|
||||
self.empty_attrs
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn force_mode(&self) -> ForceMode {
|
||||
self.force_mode
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn import_cache_get(&self, path: &std::path::Path) -> Option<Value<'gc>> {
|
||||
self.import_cache.get(path).copied()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn import_cache_insert(&mut self, path: PathBuf, val: Value<'gc>) {
|
||||
self.import_cache.insert(path, val);
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn scope_slot(&self, idx: u32) -> Value<'gc> {
|
||||
#[must_use]
|
||||
fn peek(&mut self, depth: usize) -> Value<'gc> {
|
||||
*self
|
||||
.scope_slots
|
||||
.get(idx as usize)
|
||||
.expect("invalid scope slot")
|
||||
.stack
|
||||
.get(self.stack.len() - depth - 1)
|
||||
.expect("stack underflow")
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn scope_slots_push(&mut self, val: Value<'gc>) -> u32 {
|
||||
let idx = self.scope_slots.len() as u32;
|
||||
self.scope_slots.push(val);
|
||||
idx
|
||||
#[must_use]
|
||||
fn peek_forced(&mut self, depth: usize) -> StrictValue<'gc> {
|
||||
self.stack
|
||||
.get(self.stack.len() - depth - 1)
|
||||
.expect("stack underflow")
|
||||
.restrict()
|
||||
.expect("forced")
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn set_pending_load(&mut self, load: PendingLoad) {
|
||||
self.pending_load = Some(load);
|
||||
fn replace(&mut self, depth: usize, val: Value<'gc>) {
|
||||
let len = self.stack.len();
|
||||
*self
|
||||
.stack
|
||||
.get_mut(len - depth - 1)
|
||||
.expect("stack underflow") = val;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
#[cfg_attr(debug_assertions, track_caller)]
|
||||
fn pop_forced(&mut self) -> StrictValue<'gc> {
|
||||
self.stack
|
||||
.pop()
|
||||
.expect("stack underflow")
|
||||
.restrict()
|
||||
.expect("forced")
|
||||
}
|
||||
|
||||
/// Force the top `T::WIDTH` stack slots and return them as `T`.
|
||||
///
|
||||
/// If any slot holds a pending thunk, this method pushes a call frame
|
||||
/// whose resume PC is the **start of the current instruction**
|
||||
/// (`reader.inst_start_pc()`), enters the thunk, and returns
|
||||
/// `Break::Force`. When the thunk eventually returns, the VM will
|
||||
/// **re-execute the entire opcode handler from the beginning**.
|
||||
///
|
||||
/// # Invariants
|
||||
///
|
||||
/// * **Do not call this method more than once in a single handler.**
|
||||
/// If you need to force multiple values, use a tuple type such as
|
||||
/// `(StrictValue, StrictValue)` so they are forced and popped in one
|
||||
/// atomic operation. Calling `force_and_retry` twice (or more)
|
||||
/// means the handler will be re-run from the top after each retry;
|
||||
/// any stack modifications between the two calls would be duplicated
|
||||
/// and corrupt the stack layout.
|
||||
///
|
||||
/// * The caller must ensure that the stack layout at the point of
|
||||
/// invocation is **identical** every time the handler is re-entered.
|
||||
/// In practice this means no pushes, pops, or local mutations may
|
||||
/// happen before the call, and the call must be the first thing
|
||||
/// that consumes the instruction's operand values.
|
||||
///
|
||||
/// * The return value must be propagated with `?` so that
|
||||
/// `Break::Force` correctly unwinds to the dispatch loop.
|
||||
#[inline(always)]
|
||||
fn force_and_retry<T: Forced<'gc>>(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> std::ops::ControlFlow<Break, T> {
|
||||
self.force_and_retry_pc(reader, mc, reader.inst_start_pc())
|
||||
}
|
||||
|
||||
/// Same as [`force_and_retry`](Self::force_and_retry) but allows
|
||||
/// specifying a custom resume PC.
|
||||
#[inline(always)]
|
||||
fn force_and_retry_pc<T: Forced<'gc>>(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
resume_pc: usize,
|
||||
) -> std::ops::ControlFlow<Break, T> {
|
||||
T::force_and_check(self, reader, mc, 0, resume_pc)?;
|
||||
std::ops::ControlFlow::Continue(T::pop_converted(self))
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
#[allow(unused)]
|
||||
fn force_slot(
|
||||
&mut self,
|
||||
depth: usize,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
self.force_slot_to_pc(depth, reader, mc, reader.inst_start_pc())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn force_slot_to_pc(
|
||||
&mut self,
|
||||
depth: usize,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
resume_pc: usize,
|
||||
) -> Step {
|
||||
let Some(thunk) = self.peek(depth).as_gc::<Thunk>() else {
|
||||
return Step::Continue(());
|
||||
};
|
||||
let mut state = thunk.borrow_mut(mc);
|
||||
match *state {
|
||||
ThunkState::Pending { ip, env } => {
|
||||
*state = ThunkState::Blackhole;
|
||||
self.call_stack.push(CallFrame {
|
||||
thunk: Some(thunk),
|
||||
pc: resume_pc,
|
||||
env: self.env,
|
||||
});
|
||||
self.env = env;
|
||||
reader.set_pc(ip);
|
||||
Step::Break(Break::Force)
|
||||
}
|
||||
ThunkState::Evaluated(v) => {
|
||||
self.replace(depth, v.relax());
|
||||
Step::Continue(())
|
||||
}
|
||||
ThunkState::Apply { func, arg } => {
|
||||
self.call_stack.push(CallFrame {
|
||||
thunk: Some(thunk),
|
||||
pc: resume_pc,
|
||||
env: self.env,
|
||||
});
|
||||
self.push(func);
|
||||
self.call(reader, mc, arg, resume_pc)
|
||||
}
|
||||
ThunkState::Blackhole => {
|
||||
self.finish_err(Error::eval_error("infinite recursion encountered"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
struct ErrorFrame {
|
||||
span_id: u32,
|
||||
message: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Collect, Debug)]
|
||||
#[collect(no_drop)]
|
||||
struct CallFrame<'gc> {
|
||||
pc: usize,
|
||||
thunk: Option<Gc<'gc, Thunk<'gc>>>,
|
||||
env: Gc<'gc, RefLock<Env<'gc>>>,
|
||||
}
|
||||
|
||||
enum Action {
|
||||
Continue { pc: usize },
|
||||
Done(Result<fix_lang::Value>),
|
||||
Done(Result<fix_common::Value>),
|
||||
LoadFile(PendingLoad),
|
||||
}
|
||||
|
||||
/// Compute initial heap size mirroring CppNix's strategy: 25% of physical RAM,
|
||||
/// clamped to [32 MiB, 384 MiB]. Used as `Pacing::min_sleep` so the collector
|
||||
/// defers the first cycle until the heap reaches this size.
|
||||
fn initial_heap_size() -> usize {
|
||||
const MIN_SIZE: usize = 32 * 1024 * 1024;
|
||||
const MAX_SIZE: usize = 384 * 1024 * 1024;
|
||||
|
||||
let mut sys = sysinfo::System::new();
|
||||
sys.refresh_memory();
|
||||
let total = sys.total_memory() as usize;
|
||||
let quarter = total / 4;
|
||||
quarter.clamp(MIN_SIZE, MAX_SIZE)
|
||||
enum NixNum {
|
||||
Int(i64),
|
||||
Float(f64),
|
||||
}
|
||||
|
||||
impl Vm<'_> {
|
||||
@@ -388,13 +595,11 @@ impl Vm<'_> {
|
||||
ctx: &mut C,
|
||||
ip: InstructionPtr,
|
||||
force_mode: ForceMode,
|
||||
) -> Result<fix_lang::Value> {
|
||||
) -> Result<fix_common::Value> {
|
||||
let (code, runtime) = ctx.split();
|
||||
let mut arena: Arena<Rootable![Vm<'_>]> = Arena::new(|mc| Vm::new(force_mode, mc, runtime));
|
||||
arena.metrics().set_pacing(Pacing {
|
||||
min_sleep: initial_heap_size(),
|
||||
..Pacing::STOP_THE_WORLD
|
||||
});
|
||||
|
||||
const COLLECTOR_GRANULARITY: f64 = 1024.0;
|
||||
|
||||
let mut pc = ip.0;
|
||||
loop {
|
||||
@@ -402,8 +607,12 @@ impl Vm<'_> {
|
||||
match arena.mutate_root(|mc, root| root.dispatch_batch(bytecode, runtime, pc, mc)) {
|
||||
Action::Continue { pc: new_pc } => {
|
||||
pc = new_pc;
|
||||
if arena.metrics().allocation_debt() > 0.0 {
|
||||
arena.finish_cycle();
|
||||
if arena.metrics().allocation_debt() > COLLECTOR_GRANULARITY {
|
||||
if arena.collection_phase() == CollectionPhase::Sweeping {
|
||||
arena.collect_debt();
|
||||
} else if let Some(marked) = arena.mark_debt() {
|
||||
marked.start_sweeping();
|
||||
}
|
||||
}
|
||||
}
|
||||
Action::LoadFile(load) => {
|
||||
@@ -420,9 +629,6 @@ impl Vm<'_> {
|
||||
Err(err) => break Err(err),
|
||||
};
|
||||
pc = new_ip.0;
|
||||
arena.mutate_root(|mc, root| {
|
||||
root.env = Gc::new(mc, RefLock::new(Env::empty()));
|
||||
});
|
||||
}
|
||||
Action::Done(done) => break done,
|
||||
}
|
||||
@@ -466,10 +672,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],
|
||||
@@ -477,15 +679,12 @@ impl<'gc> Vm<'gc> {
|
||||
pc: usize,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Action {
|
||||
use fix_bytecode::Op::*;
|
||||
use instructions::*;
|
||||
use fix_codegen::Op::*;
|
||||
|
||||
let mut reader = BytecodeReader::new(bytecode, pc);
|
||||
let mut fuel = Self::DEFAULT_FUEL_AMOUNT;
|
||||
|
||||
loop {
|
||||
use crate::instructions::op_dispatch_cont;
|
||||
|
||||
if fuel == 0 {
|
||||
return Action::Continue { pc: reader.pc() };
|
||||
}
|
||||
@@ -494,75 +693,75 @@ impl<'gc> Vm<'gc> {
|
||||
let op = reader.read_op();
|
||||
|
||||
let result = match op {
|
||||
PushSmi => op_push_smi(self, &mut reader),
|
||||
PushBigInt => op_push_bigint(self, &mut reader, mc),
|
||||
PushFloat => op_push_float(self, &mut reader),
|
||||
PushString => op_push_string(self, &mut reader),
|
||||
PushNull => op_push_null(self),
|
||||
PushTrue => op_push_true(self),
|
||||
PushFalse => op_push_false(self),
|
||||
PushSmi => self.op_push_smi(&mut reader),
|
||||
PushBigInt => self.op_push_bigint(&mut reader, mc),
|
||||
PushFloat => self.op_push_float(&mut reader),
|
||||
PushString => self.op_push_string(&mut reader),
|
||||
PushNull => self.op_push_null(),
|
||||
PushTrue => self.op_push_true(),
|
||||
PushFalse => self.op_push_false(),
|
||||
|
||||
LoadLocal => op_load_local(self, &mut reader),
|
||||
LoadOuter => op_load_outer(self, &mut reader),
|
||||
StoreLocal => op_store_local(self, &mut reader, mc),
|
||||
AllocLocals => op_alloc_locals(self, &mut reader, mc),
|
||||
LoadLocal => self.op_load_local(&mut reader),
|
||||
LoadOuter => self.op_load_outer(&mut reader),
|
||||
StoreLocal => self.op_store_local(&mut reader, mc),
|
||||
AllocLocals => self.op_alloc_locals(&mut reader, mc),
|
||||
|
||||
MakeThunk => op_make_thunk(self, &mut reader, mc),
|
||||
MakeClosure => op_make_closure(self, &mut reader, mc),
|
||||
MakePatternClosure => op_make_pattern_closure(self, &mut reader, mc),
|
||||
MakeThunk => self.op_make_thunk(&mut reader, mc),
|
||||
MakeClosure => self.op_make_closure(&mut reader, mc),
|
||||
MakePatternClosure => self.op_make_pattern_closure(&mut reader, mc),
|
||||
|
||||
Call => op_call(self, ctx, &mut reader, mc),
|
||||
DispatchCont => op_dispatch_cont(self, ctx, &mut reader, mc),
|
||||
Return => op_return(self, ctx, &mut reader, mc),
|
||||
Call => self.op_call(ctx, &mut reader, mc),
|
||||
DispatchPrimOp => self.op_dispatch_primop(ctx, &mut reader, mc),
|
||||
Return => self.op_return(ctx, &mut reader, mc),
|
||||
|
||||
MakeAttrs => op_make_attrs(self, ctx, &mut reader, mc),
|
||||
MakeEmptyAttrs => op_make_empty_attrs(self),
|
||||
SelectStatic => op_select_static(self, ctx, &mut reader, mc),
|
||||
SelectDynamic => op_select_dynamic(self, ctx, &mut reader, mc),
|
||||
HasAttrPathStatic => op_has_attr_path_static(self, ctx, &mut reader, mc),
|
||||
HasAttrPathDynamic => op_has_attr_path_dynamic(self, ctx, &mut reader, mc),
|
||||
HasAttrStatic => op_has_attr_static(self, &mut reader, mc),
|
||||
HasAttrDynamic => op_has_attr_dynamic(self, ctx, &mut reader, mc),
|
||||
HasAttrResolve => op_has_attr_resolve(self),
|
||||
JumpIfSelectFailed => op_jump_if_select_failed(self, &mut reader),
|
||||
JumpIfSelectSucceeded => op_jump_if_select_succeeded(self, &mut reader),
|
||||
MakeAttrs => self.op_make_attrs(ctx, &mut reader, mc),
|
||||
MakeEmptyAttrs => self.op_make_empty_attrs(),
|
||||
SelectStatic => self.op_select_static(ctx, &mut reader, mc),
|
||||
SelectDynamic => self.op_select_dynamic(ctx, &mut reader, mc),
|
||||
HasAttrPathStatic => self.op_has_attr_path_static(ctx, &mut reader, mc),
|
||||
HasAttrPathDynamic => self.op_has_attr_path_dynamic(ctx, &mut reader, mc),
|
||||
HasAttrStatic => self.op_has_attr_static(&mut reader, mc),
|
||||
HasAttrDynamic => self.op_has_attr_dynamic(ctx, &mut reader, mc),
|
||||
HasAttrResolve => self.op_has_attr_resolve(),
|
||||
JumpIfSelectFailed => self.op_jump_if_select_failed(&mut reader),
|
||||
JumpIfSelectSucceeded => self.op_jump_if_select_succeeded(&mut reader),
|
||||
|
||||
MakeList => op_make_list(self, ctx, &mut reader, mc),
|
||||
MakeEmptyList => op_make_empty_list(self),
|
||||
MakeList => self.op_make_list(ctx, &mut reader, mc),
|
||||
MakeEmptyList => self.op_make_empty_list(),
|
||||
|
||||
OpAdd => op_add(self, ctx, &mut reader, mc),
|
||||
OpSub => op_sub(self, &mut reader, mc),
|
||||
OpMul => op_mul(self, &mut reader, mc),
|
||||
OpDiv => op_div(self, &mut reader, mc),
|
||||
OpEq => op_eq(self, ctx, &mut reader, mc),
|
||||
OpNeq => op_neq(self, ctx, &mut reader, mc),
|
||||
OpLt => op_lt(self, ctx, &mut reader, mc),
|
||||
OpGt => op_gt(self, ctx, &mut reader, mc),
|
||||
OpLeq => op_leq(self, ctx, &mut reader, mc),
|
||||
OpGeq => op_geq(self, ctx, &mut reader, mc),
|
||||
OpConcat => op_concat(self, &mut reader, mc),
|
||||
OpUpdate => op_update(self, &mut reader, mc),
|
||||
OpAdd => self.op_add(ctx, &mut reader, mc),
|
||||
OpSub => self.op_sub(&mut reader, mc),
|
||||
OpMul => self.op_mul(&mut reader, mc),
|
||||
OpDiv => self.op_div(&mut reader, mc),
|
||||
OpEq => self.op_eq(ctx, &mut reader, mc),
|
||||
OpNeq => self.op_neq(ctx, &mut reader, mc),
|
||||
OpLt => self.op_lt(ctx, &mut reader, mc),
|
||||
OpGt => self.op_gt(ctx, &mut reader, mc),
|
||||
OpLeq => self.op_leq(ctx, &mut reader, mc),
|
||||
OpGeq => self.op_geq(ctx, &mut reader, mc),
|
||||
OpConcat => self.op_concat(&mut reader, mc),
|
||||
OpUpdate => self.op_update(&mut reader, mc),
|
||||
|
||||
OpNeg => op_neg(self, &mut reader, mc),
|
||||
OpNot => op_not(self, &mut reader, mc),
|
||||
OpNeg => self.op_neg(&mut reader, mc),
|
||||
OpNot => self.op_not(&mut reader, mc),
|
||||
|
||||
JumpIfFalse => op_jump_if_false(self, &mut reader, mc),
|
||||
JumpIfTrue => op_jump_if_true(self, &mut reader, mc),
|
||||
Jump => op_jump(self, &mut reader),
|
||||
JumpIfFalse => self.op_jump_if_false(&mut reader, mc),
|
||||
JumpIfTrue => self.op_jump_if_true(&mut reader, mc),
|
||||
Jump => self.op_jump(&mut reader),
|
||||
|
||||
ConcatStrings => op_concat_strings(self, ctx, &mut reader, mc),
|
||||
CoerceToString => op_coerce_to_string(self, &mut reader, mc),
|
||||
ResolvePath => op_resolve_path(self, ctx, &mut reader, mc),
|
||||
ConcatStrings => self.op_concat_strings(ctx, &mut reader, mc),
|
||||
CoerceToString => self.op_coerce_to_string(&mut reader, mc),
|
||||
ResolvePath => self.op_resolve_path(ctx, &mut reader, mc),
|
||||
|
||||
Assert => op_assert(self, ctx, &mut reader, mc),
|
||||
Assert => self.op_assert(ctx, &mut reader, mc),
|
||||
|
||||
LookupWith => op_lookup_with(self, ctx, &mut reader, mc),
|
||||
LookupWith => self.op_lookup_with(ctx, &mut reader, mc),
|
||||
|
||||
LoadBuiltins => op_load_builtins(self),
|
||||
LoadBuiltin => op_load_builtin(self, &mut reader),
|
||||
LoadBuiltins => self.op_load_builtins(),
|
||||
LoadBuiltin => self.op_load_builtin(&mut reader),
|
||||
|
||||
LoadReplBinding => op_load_repl_binding(self, &mut reader),
|
||||
LoadScopedBinding => op_load_scoped_binding(self, ctx, &mut reader, mc),
|
||||
LoadReplBinding => self.op_load_repl_binding(&mut reader),
|
||||
LoadScopedBinding => self.op_load_scoped_binding(ctx, &mut reader, mc),
|
||||
|
||||
Illegal => unreachable!(),
|
||||
};
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -1,499 +0,0 @@
|
||||
//! `builtins.hasContext`, `builtins.getContext`, `builtins.appendContext`,
|
||||
//! `builtins.unsafeDiscardStringContext`,
|
||||
//! `builtins.unsafeDiscardOutputDependency`.
|
||||
//!
|
||||
//! See `fix-runtime/src/string_context.rs` for the
|
||||
//! `StringContextElem` type.
|
||||
|
||||
use fix_bytecode::Continuation;
|
||||
use fix_error::Error;
|
||||
use fix_lang::StringId;
|
||||
use fix_runtime::{
|
||||
AttrSet, BytecodeReader, List as VmList, Machine, MachineExt, NixString, NixType, Step,
|
||||
StrictValue, StringContext, StringContextElem, Value, VmRuntimeCtx, VmRuntimeCtxExt,
|
||||
};
|
||||
use gc_arena::{Gc, Mutation};
|
||||
use smallvec::SmallVec;
|
||||
|
||||
pub fn has_context<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let val = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
if !val.is::<StringId>() && val.downcast::<NixString>().is_none() {
|
||||
return m.finish_type_err(NixType::String, val.ty());
|
||||
}
|
||||
let has_ctx = !ctx.get_string_context(val).is_empty();
|
||||
m.return_from_primop(Value::new(has_ctx), reader)
|
||||
}
|
||||
|
||||
pub fn unsafe_discard_string_context<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let val = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
if let Some(sid) = val.downcast::<StringId>() {
|
||||
return m.return_from_primop(Value::new(sid), reader);
|
||||
}
|
||||
let Some(ns) = val.downcast::<NixString>() else {
|
||||
return m.finish_type_err(NixType::String, val.ty());
|
||||
};
|
||||
let sid = ctx.intern_string(ns.as_str());
|
||||
m.return_from_primop(Value::new(sid), reader)
|
||||
}
|
||||
|
||||
pub fn unsafe_discard_output_dependency<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let val = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
if let Some(sid) = val.downcast::<StringId>() {
|
||||
return m.return_from_primop(Value::new(sid), reader);
|
||||
}
|
||||
let Some(ns) = val.downcast::<NixString>() else {
|
||||
return m.finish_type_err(NixType::String, val.ty());
|
||||
};
|
||||
if ns.context().is_empty() {
|
||||
let sid = ctx.intern_string(ns.as_str());
|
||||
return m.return_from_primop(Value::new(sid), reader);
|
||||
}
|
||||
|
||||
let mut new_ctx = StringContext::new();
|
||||
for elem in ns.context() {
|
||||
let replacement = match elem {
|
||||
StringContextElem::DrvDeep { drv_path } => StringContextElem::Opaque {
|
||||
path: drv_path.clone(),
|
||||
},
|
||||
other => other.clone(),
|
||||
};
|
||||
new_ctx.insert(replacement);
|
||||
}
|
||||
|
||||
let s: Box<str> = ns.as_str().into();
|
||||
let new_ns = Gc::new(mc, NixString::with_context(s, new_ctx));
|
||||
m.return_from_primop(Value::new(new_ns), reader)
|
||||
}
|
||||
|
||||
pub fn get_context<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let val = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
if !val.is::<StringId>() && val.downcast::<NixString>().is_none() {
|
||||
return m.finish_type_err(NixType::String, val.ty());
|
||||
}
|
||||
let elems = ctx.get_string_context(val);
|
||||
|
||||
struct Info {
|
||||
path: bool,
|
||||
all_outputs: bool,
|
||||
outputs: SmallVec<[Box<str>; 2]>,
|
||||
}
|
||||
impl Info {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
path: false,
|
||||
all_outputs: false,
|
||||
outputs: SmallVec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut by_path: std::collections::BTreeMap<Box<str>, Info> = std::collections::BTreeMap::new();
|
||||
for elem in elems {
|
||||
match elem {
|
||||
StringContextElem::Opaque { path } => {
|
||||
by_path.entry(path.clone()).or_insert_with(Info::new).path = true;
|
||||
}
|
||||
StringContextElem::DrvDeep { drv_path } => {
|
||||
by_path
|
||||
.entry(drv_path.clone())
|
||||
.or_insert_with(Info::new)
|
||||
.all_outputs = true;
|
||||
}
|
||||
StringContextElem::Built { drv_path, output } => {
|
||||
by_path
|
||||
.entry(drv_path.clone())
|
||||
.or_insert_with(Info::new)
|
||||
.outputs
|
||||
.push(output.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut outer_entries: SmallVec<[(StringId, Value<'gc>); 4]> = SmallVec::new();
|
||||
for (path, mut info) in by_path {
|
||||
info.outputs.sort();
|
||||
info.outputs.dedup();
|
||||
|
||||
let mut sub: SmallVec<[(StringId, Value<'gc>); 4]> = SmallVec::new();
|
||||
if info.all_outputs {
|
||||
sub.push((ctx.intern_string("allOutputs"), Value::new(true)));
|
||||
}
|
||||
if !info.outputs.is_empty() {
|
||||
let items: smallvec::SmallVec<[Value<'gc>; 4]> = info
|
||||
.outputs
|
||||
.iter()
|
||||
.map(|o| Value::new(ctx.intern_string(o)))
|
||||
.collect();
|
||||
let list = VmList::new(mc, items);
|
||||
sub.push((ctx.intern_string("outputs"), Value::new(list)));
|
||||
}
|
||||
if info.path {
|
||||
sub.push((ctx.intern_string("path"), Value::new(true)));
|
||||
}
|
||||
sub.sort_by_key(|(k, _)| *k);
|
||||
let sub_attrs = Gc::new(mc, AttrSet::from_sorted_unchecked(sub));
|
||||
|
||||
outer_entries.push((ctx.intern_string(&path), Value::new(sub_attrs)));
|
||||
}
|
||||
outer_entries.sort_by_key(|(k, _)| *k);
|
||||
|
||||
let outer = Gc::new(mc, AttrSet::from_sorted_unchecked(outer_entries));
|
||||
m.return_from_primop(Value::new(outer), reader)
|
||||
}
|
||||
|
||||
/// appendContext :: String -> AttrSet -> String
|
||||
/// The context AttrSet maps store-path strings to `{ path?: Bool, allOutputs?:
|
||||
/// Bool, outputs?: [String] }`. Each present field contributes one
|
||||
/// StringContextElem to the result.
|
||||
///
|
||||
/// Requires forcing nested attrset values and list elements lazily, so it's
|
||||
/// structured as a state machine with the following stack layout:
|
||||
///
|
||||
/// [strVal, attrs, idx, acc] - outer loop
|
||||
/// [strVal, attrs, idx, acc, entryAttrs] - after entry forced
|
||||
/// [strVal, attrs, idx, acc, list] - after `outputs` forced
|
||||
/// [strVal, attrs, idx, acc, list, oidx] - output-element loop
|
||||
/// [strVal, attrs, idx, acc, list, oidx, outElem] - after element forced
|
||||
///
|
||||
/// `acc` is a sentinel `NixString` whose `data` is empty and whose `context`
|
||||
/// is the accumulator. The string value itself is preserved in `strVal` and
|
||||
/// retrieved at finalization.
|
||||
///
|
||||
// TODO: handle thunk-valued `path` and `allOutputs` sub-attrs; currently they
|
||||
// must be already-evaluated booleans.
|
||||
pub fn append_context<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (str_val, attrs) = m.force_and_retry::<(StrictValue, Gc<AttrSet>)>(reader, mc)?;
|
||||
|
||||
let initial_ctx: StringContext = ctx.get_string_context(str_val).clone();
|
||||
let acc = Gc::new(mc, NixString::with_context("", initial_ctx));
|
||||
|
||||
m.push(str_val.relax());
|
||||
m.push(Value::new(attrs));
|
||||
m.push(Value::new(0i32));
|
||||
m.push(Value::new(acc));
|
||||
|
||||
reader.set_pc(Continuation::PAppendContextLoop.ip() as usize);
|
||||
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");
|
||||
|
||||
if idx as usize >= attrs.entries.len() {
|
||||
return append_context_finalize(m, ctx, reader, mc);
|
||||
}
|
||||
|
||||
let entry_val = attrs.entries[idx as usize].1;
|
||||
m.push(entry_val);
|
||||
m.force_slot_to_pc(
|
||||
0,
|
||||
reader,
|
||||
mc,
|
||||
Continuation::PAppendContextEntryForced.ip() as usize,
|
||||
)?;
|
||||
reader.set_pc(Continuation::PAppendContextEntryForced.ip() as usize);
|
||||
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,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// Stack: [strVal, attrs, idx, acc, entryAttrs(thunk)]
|
||||
// The slot still holds the Thunk pointer; re-force to extract the now-
|
||||
// Evaluated value into the slot.
|
||||
m.force_slot(0, reader, mc)?;
|
||||
let entry_val = m.peek_forced(0);
|
||||
let Some(entry_attrs) = entry_val.downcast::<AttrSet>() else {
|
||||
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");
|
||||
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/") {
|
||||
return m.finish_err(Error::eval_error(format!(
|
||||
"context key '{path_str_owned}' is not a store path"
|
||||
)));
|
||||
}
|
||||
|
||||
// Eagerly handle `path` and `allOutputs` (assumed already-forced
|
||||
// booleans - most callers either set them to literal `true` or omit
|
||||
// them entirely).
|
||||
// TODO: force these two attributes correctly
|
||||
let path_id = ctx.intern_string("path");
|
||||
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");
|
||||
let mut new_acc: StringContext = acc_gc.context().iter().cloned().collect();
|
||||
|
||||
if let Some(v) = entry_attrs.lookup(path_id)
|
||||
&& v.downcast::<bool>() == Some(true)
|
||||
{
|
||||
new_acc.insert(StringContextElem::Opaque {
|
||||
path: path_str_owned.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(v) = entry_attrs.lookup(all_outputs_id)
|
||||
&& v.downcast::<bool>() == Some(true)
|
||||
{
|
||||
if !path_str_owned.ends_with(".drv") {
|
||||
return m.finish_err(Error::eval_error(format!(
|
||||
"tried to add all-outputs context of {path_str_owned}, which is not a derivation, to a string"
|
||||
)));
|
||||
}
|
||||
new_acc.insert(StringContextElem::DrvDeep {
|
||||
drv_path: path_str_owned.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
let new_acc_gc = Gc::new(mc, NixString::with_context("", new_acc));
|
||||
m.replace(1, Value::new(new_acc_gc));
|
||||
|
||||
if let Some(outputs_val) = entry_attrs.lookup(outputs_id) {
|
||||
m.replace(0, outputs_val);
|
||||
m.force_slot_to_pc(
|
||||
0,
|
||||
reader,
|
||||
mc,
|
||||
Continuation::PAppendContextOutputsForced.ip() as usize,
|
||||
)?;
|
||||
reader.set_pc(Continuation::PAppendContextOutputsForced.ip() as usize);
|
||||
return Step::Continue(());
|
||||
}
|
||||
|
||||
m.drop_n(1);
|
||||
let idx_back = m
|
||||
.peek(1)
|
||||
.downcast::<i32>()
|
||||
.expect("stack slot must be an integer");
|
||||
m.replace(1, Value::new(idx_back + 1));
|
||||
reader.set_pc(Continuation::PAppendContextLoop.ip() as usize);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
pub fn append_context_outputs_forced<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
_ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
m.force_slot(0, reader, mc)?;
|
||||
let list_val = m.peek_forced(0);
|
||||
let Some(list) = list_val.downcast::<VmList>() else {
|
||||
return m.finish_type_err(NixType::List, list_val.ty());
|
||||
};
|
||||
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");
|
||||
m.replace(1, Value::new(idx_back + 1));
|
||||
reader.set_pc(Continuation::PAppendContextLoop.ip() as usize);
|
||||
return Step::Continue(());
|
||||
}
|
||||
|
||||
m.push(Value::new(0i32));
|
||||
reader.set_pc(Continuation::PAppendContextOutputElementLoop.ip() as usize);
|
||||
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");
|
||||
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");
|
||||
m.replace(1, Value::new(idx_back + 1));
|
||||
reader.set_pc(Continuation::PAppendContextLoop.ip() as usize);
|
||||
return Step::Continue(());
|
||||
}
|
||||
|
||||
let elem = list.inner.borrow()[oidx as usize];
|
||||
m.push(elem);
|
||||
m.force_slot_to_pc(
|
||||
0,
|
||||
reader,
|
||||
mc,
|
||||
Continuation::PAppendContextOutputElementForced.ip() as usize,
|
||||
)?;
|
||||
reader.set_pc(Continuation::PAppendContextOutputElementForced.ip() as usize);
|
||||
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,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
m.force_slot(0, reader, mc)?;
|
||||
let elem = m.peek_forced(0);
|
||||
let Some(output_name) = ctx.get_string(elem) else {
|
||||
return m.finish_type_err(NixType::String, elem.ty());
|
||||
};
|
||||
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");
|
||||
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") {
|
||||
return m.finish_err(Error::eval_error(format!(
|
||||
"tried to add derivation output context of {path_str}, which is not a derivation, to a string"
|
||||
)));
|
||||
}
|
||||
|
||||
let acc_gc = m
|
||||
.peek(3)
|
||||
.downcast::<NixString>()
|
||||
.expect("stack slot must be a string");
|
||||
let mut new_acc: StringContext = acc_gc.context().iter().cloned().collect();
|
||||
new_acc.insert(StringContextElem::Built {
|
||||
drv_path: path_str,
|
||||
output: output_name,
|
||||
});
|
||||
let new_acc_gc = Gc::new(mc, NixString::with_context("", new_acc));
|
||||
m.replace(3, Value::new(new_acc_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");
|
||||
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,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
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);
|
||||
let str_val_raw = m.pop();
|
||||
|
||||
// The strVal was already forced at entry; restrict() is infallible here.
|
||||
let str_val = str_val_raw
|
||||
.restrict()
|
||||
.unwrap_or_else(|_| panic!("appendContext: strVal unexpectedly a thunk"));
|
||||
|
||||
let s_str = ctx.get_string(str_val).unwrap_or("").to_owned();
|
||||
let context: StringContext = acc_gc.context().iter().cloned().collect();
|
||||
let result = if context.is_empty() {
|
||||
let sid = ctx.intern_string(s_str);
|
||||
Value::new(sid)
|
||||
} else {
|
||||
let ns = Gc::new(mc, NixString::with_context(s_str, context));
|
||||
Value::new(ns)
|
||||
};
|
||||
m.return_from_primop(result, reader)
|
||||
}
|
||||
+330
-279
@@ -1,311 +1,362 @@
|
||||
use fix_bytecode::Continuation;
|
||||
use fix_error::{Error, Result};
|
||||
use fix_macros::handler;
|
||||
use fix_runtime::{
|
||||
AttrSet, BytecodeReader, Closure, Env, List, Machine, MachineExt, Slot, Step, StrictValue,
|
||||
Value, VmRuntimeCtx, VmRuntimeCtxExt,
|
||||
};
|
||||
use fix_builtins::PrimOpPhase;
|
||||
use fix_error::Error;
|
||||
use gc_arena::{Gc, Mutation, RefLock};
|
||||
use smallvec::SmallVec;
|
||||
|
||||
use crate::primops::stubs::*;
|
||||
use crate::value::*;
|
||||
use crate::{BytecodeReader, Step, Vm, VmRuntimeCtx, VmRuntimeCtxExt};
|
||||
|
||||
#[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>(
|
||||
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());
|
||||
impl<'gc> Vm<'gc> {
|
||||
pub(crate) fn primop_seq(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// stack: [e1, e2] - force e1, return e2
|
||||
self.force_slot(1, reader, mc)?;
|
||||
let e2 = self.pop();
|
||||
let _ = self.pop();
|
||||
self.return_from_primop(e2, reader)
|
||||
}
|
||||
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());
|
||||
|
||||
pub(crate) fn primop_abort(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// stack: [msg] - force msg, then abort with it
|
||||
self.force_slot(0, reader, mc)?;
|
||||
let msg_val = self.peek_forced(0);
|
||||
let msg = ctx.get_string(msg_val).unwrap_or("<non-string-value>");
|
||||
self.finish_err(Error::eval_error(format!(
|
||||
"evaluation aborted with the following error message: '{msg}'"
|
||||
)))
|
||||
}
|
||||
|
||||
pub(crate) fn primop_deep_seq_force_top(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// stack: [e1, e2] - force e1, return e2
|
||||
self.force_slot(1, reader, mc)?;
|
||||
|
||||
let e1 = self.peek_forced(1);
|
||||
|
||||
let children: SmallVec<_> = if let Some(attrs) = e1.as_gc::<AttrSet>() {
|
||||
let attrs = &attrs.entries;
|
||||
if attrs.is_empty() {
|
||||
SmallVec::new()
|
||||
} else {
|
||||
attrs.iter().map(|&(_, v)| v).collect()
|
||||
}
|
||||
} else if let Some(list) = e1.as_gc::<List<'gc>>() {
|
||||
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 = self.pop();
|
||||
let _ = self.pop();
|
||||
return self.return_from_primop(e2, reader);
|
||||
}
|
||||
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()
|
||||
}
|
||||
}
|
||||
let count = children.len() as i32;
|
||||
let seen: Gc<'gc, List<'gc>> = Gc::new(mc, List::default());
|
||||
let worklist: Gc<'gc, List<'gc>> = List::new(mc, children);
|
||||
|
||||
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);
|
||||
let e2 = self.pop();
|
||||
let _ = self.pop();
|
||||
self.push(e2);
|
||||
self.push(Value::new_gc(seen));
|
||||
self.push(Value::new_gc(worklist));
|
||||
self.push(Value::new_inline(count));
|
||||
reader.set_pc(PrimOpPhase::DeepSeqPush.ip() as usize);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
pub(crate) fn primop_deep_seq_push(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// stack: [e2, seen, worklist, counter]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let counter = self.peek(0).as_inline::<i32>().unwrap();
|
||||
if counter == 0 {
|
||||
let _ = self.pop(); // counter
|
||||
let _ = self.pop(); // worklist
|
||||
let _ = self.pop(); // seen
|
||||
let val = self.pop();
|
||||
return self.return_from_primop(val, reader);
|
||||
}
|
||||
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);
|
||||
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let worklist = self.peek_forced(1).as_gc::<List<'gc>>().unwrap();
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let item = worklist.unlock(mc).borrow_mut().pop().unwrap();
|
||||
self.replace(0, Value::new_inline(counter - 1));
|
||||
self.push(item);
|
||||
|
||||
// force item at TOS, resume at DeepSeqLoop after force
|
||||
self.force_slot_to_pc(0, reader, mc, PrimOpPhase::DeepSeqLoop.ip() as usize)?;
|
||||
reader.set_pc(PrimOpPhase::DeepSeqLoop.ip() as usize);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
pub(crate) fn primop_deep_seq_loop(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// stack after pop: [e2, seen, worklist, counter]
|
||||
let item = self.pop();
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let counter = self.peek(0).as_inline::<i32>().unwrap();
|
||||
|
||||
let mut added: usize = 0;
|
||||
if let Some(attrs) = item.as_gc::<AttrSet>() {
|
||||
let attrs = &attrs.entries;
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let seen = self.peek_forced(2).as_gc::<List<'gc>>().unwrap();
|
||||
if !self.is_value_in_seen(seen, item) {
|
||||
self.add_value_to_seen(seen, mc, item);
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let worklist = self.peek_forced(1).as_gc::<List<'gc>>().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.as_gc::<List<'gc>>() {
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let seen = self.peek_forced(2).as_gc::<List<'gc>>().unwrap();
|
||||
if !self.is_value_in_seen(seen, item) {
|
||||
self.add_value_to_seen(seen, mc, item);
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let worklist = self.peek_forced(1).as_gc::<List<'gc>>().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();
|
||||
}
|
||||
}
|
||||
}
|
||||
added = inner.len() as i32;
|
||||
}
|
||||
added
|
||||
}
|
||||
|
||||
pub fn abort<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// stack: [msg] - force msg, then abort with it
|
||||
m.force_slot(0, reader, mc)?;
|
||||
let msg_val = m.peek_forced(0);
|
||||
let msg = ctx.get_string(msg_val).unwrap_or("<non-string-value>");
|
||||
m.finish_err(Error::eval_error(format!(
|
||||
"evaluation aborted with the following error message: '{msg}'"
|
||||
)))
|
||||
}
|
||||
|
||||
pub fn force_result_shallow<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
m.force_slot(0, reader, mc)?;
|
||||
let val = m.peek_forced(0);
|
||||
|
||||
let (count, has_children) = if let Some(attrs) = val.downcast::<AttrSet>() {
|
||||
let len = attrs.entries.len();
|
||||
(len, len > 0)
|
||||
} else if let Some(list) = val.downcast::<List>() {
|
||||
let len = list.inner.borrow().len();
|
||||
(len, len > 0)
|
||||
} else {
|
||||
(0, false)
|
||||
};
|
||||
|
||||
if !has_children {
|
||||
let val = m.pop();
|
||||
return m.finish_ok(ctx.convert_value(val));
|
||||
self.replace(0, Value::new_inline(counter + added as i32));
|
||||
reader.set_pc(PrimOpPhase::DeepSeqPush.ip() as usize);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
m.push(Value::new(0i32));
|
||||
m.push(Value::new(count as i32));
|
||||
reader.set_pc(Continuation::ForceResultShallowPush.ip() as usize);
|
||||
Step::Continue(())
|
||||
}
|
||||
pub(crate) fn primop_force_result_shallow(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
self.force_slot(0, reader, mc)?;
|
||||
let val = self.peek_forced(0);
|
||||
|
||||
#[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");
|
||||
let (count, has_children) = if let Some(attrs) = val.as_gc::<AttrSet>() {
|
||||
let len = attrs.entries.len();
|
||||
(len, len > 0)
|
||||
} else if let Some(list) = val.as_gc::<List<'gc>>() {
|
||||
let len = list.inner.borrow().len();
|
||||
(len, len > 0)
|
||||
} else {
|
||||
(0, false)
|
||||
};
|
||||
|
||||
if idx == len {
|
||||
m.drop_n(2);
|
||||
let val = m.pop();
|
||||
return m.finish_ok(ctx.convert_value(val));
|
||||
if !has_children {
|
||||
let val = self.pop();
|
||||
return self.finish_ok(ctx.convert_value(val));
|
||||
}
|
||||
|
||||
self.push(Value::new_inline(0i32));
|
||||
self.push(Value::new_inline(count as i32));
|
||||
reader.set_pc(PrimOpPhase::ForceResultShallowPush.ip() as usize);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
let val = m.peek_forced(2);
|
||||
let child = if let Some(attrs) = val.downcast::<AttrSet>() {
|
||||
attrs.entries.get(idx as usize).map(|&(_, v)| v)
|
||||
} else if let Some(list) = val.downcast::<List>() {
|
||||
list.inner.borrow().get(idx as usize).copied()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
pub(crate) fn primop_force_result_shallow_push(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let idx = self.peek(1).as_inline::<i32>().unwrap();
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let len = self.peek(0).as_inline::<i32>().unwrap();
|
||||
|
||||
if let Some(child) = child {
|
||||
m.replace(1, Value::new(idx + 1));
|
||||
m.push(child);
|
||||
m.force_slot_to_pc(
|
||||
0,
|
||||
if idx == len {
|
||||
let _ = self.pop(); // len
|
||||
let _ = self.pop(); // idx
|
||||
let val = self.pop();
|
||||
return self.finish_ok(ctx.convert_value(val));
|
||||
}
|
||||
|
||||
let val = self.peek_forced(2);
|
||||
let child = if let Some(attrs) = val.as_gc::<AttrSet>() {
|
||||
attrs.entries.get(idx as usize).map(|&(_, v)| v)
|
||||
} else if let Some(list) = val.as_gc::<List<'gc>>() {
|
||||
list.inner.borrow().get(idx as usize).copied()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(child) = child {
|
||||
self.replace(1, Value::new_inline(idx + 1));
|
||||
self.push(child);
|
||||
self.force_slot_to_pc(
|
||||
0,
|
||||
reader,
|
||||
mc,
|
||||
PrimOpPhase::ForceResultShallowLoop.ip() as usize,
|
||||
)?;
|
||||
reader.set_pc(PrimOpPhase::ForceResultShallowLoop.ip() as usize);
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
pub(crate) fn primop_force_result_shallow_loop(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
_mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let _ = self.pop(); // forced child
|
||||
reader.set_pc(PrimOpPhase::ForceResultShallowPush.ip() as usize);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
pub(crate) fn primop_force_result_deep_finish(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let val = self.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
self.finish_ok(ctx.convert_value(val.relax()))
|
||||
}
|
||||
|
||||
fn is_value_in_seen(&self, seen: Gc<'gc, List<'gc>>, val: Value<'gc>) -> bool {
|
||||
if !is_container(val) {
|
||||
return false;
|
||||
}
|
||||
let target = val.to_bits();
|
||||
for &v in seen.inner.borrow().iter() {
|
||||
if v.to_bits() == target {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn add_value_to_seen(&self, seen: Gc<'gc, List<'gc>>, mc: &Mutation<'gc>, val: Value<'gc>) {
|
||||
if is_container(val) {
|
||||
seen.unlock(mc).borrow_mut().push(val);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn primop_call_functor_1(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// Stack invariant on every (re-)entry: [..., orig_arg, self, functor]
|
||||
// where `functor` is TOS. Retries during force land back here safely.
|
||||
let functor = self.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
// Stack now: [..., orig_arg, self]
|
||||
let self_val = self.pop();
|
||||
self.push(functor.relax());
|
||||
// Stack: [..., orig_arg, functor]
|
||||
// Call 1: functor(self). Resume into CallFunctor2 once it returns.
|
||||
self.call(
|
||||
reader,
|
||||
mc,
|
||||
Continuation::ForceResultShallowLoop.ip() as usize,
|
||||
)?;
|
||||
reader.set_pc(Continuation::ForceResultShallowLoop.ip() as usize);
|
||||
self_val,
|
||||
PrimOpPhase::CallFunctor2.ip() as usize,
|
||||
)
|
||||
}
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
pub fn force_result_shallow_loop<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
_mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
m.drop_n(1);
|
||||
reader.set_pc(Continuation::ForceResultShallowPush.ip() as usize);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
pub fn force_result_deep_finish<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let val = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
m.finish_ok(ctx.convert_value(val.relax()))
|
||||
}
|
||||
|
||||
fn is_value_in_seen<'gc>(seen: Gc<'gc, List<'gc>>, val: Value<'gc>) -> bool {
|
||||
if !is_container(val) {
|
||||
return false;
|
||||
pub(crate) fn primop_call_functor_2(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// Stack on entry: [..., orig_arg, intermediate]
|
||||
// call_stack top: synthetic frame with caller's resume_pc.
|
||||
let intermediate = self.pop();
|
||||
let orig_arg = self.pop();
|
||||
let saved = self.call_stack.pop().expect("functor outer frame missing");
|
||||
self.env = saved.env;
|
||||
self.push(intermediate);
|
||||
// Call 2: intermediate(orig_arg). Resume to caller.
|
||||
self.call(reader, mc, orig_arg, saved.pc)
|
||||
}
|
||||
let target = val.to_bits();
|
||||
for &v in seen.inner.borrow().iter() {
|
||||
if v.to_bits() == target {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn add_value_to_seen<'gc>(seen: Gc<'gc, List<'gc>>, mc: &Mutation<'gc>, val: Value<'gc>) {
|
||||
if is_container(val) {
|
||||
seen.unlock(mc).borrow_mut().push(val);
|
||||
}
|
||||
}
|
||||
pub(crate) fn primop_call_pattern(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (func, attrset) = self.force_and_retry::<(Gc<Closure>, Gc<AttrSet>)>(reader, mc)?;
|
||||
|
||||
pub fn call_functor_1<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// Stack invariant on every (re-)entry: [..., orig_arg, self, functor]
|
||||
// where `functor` is TOS. Retries during force land back here safely.
|
||||
let functor = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
// Stack now: [..., orig_arg, self]
|
||||
let self_val = m.pop();
|
||||
m.push(functor.relax());
|
||||
// Stack: [..., orig_arg, functor]
|
||||
// Call 1: functor(self). Resume into CallFunctor2 once it returns.
|
||||
m.call(
|
||||
reader,
|
||||
mc,
|
||||
self_val,
|
||||
Continuation::CallFunctor2.ip() as usize,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn call_functor_2<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// Stack on entry: [..., orig_arg, intermediate]
|
||||
// call_stack top: synthetic frame with caller's resume_pc.
|
||||
let intermediate = m.pop();
|
||||
let orig_arg = m.pop();
|
||||
let saved = m.pop_call_frame().expect("functor outer frame missing");
|
||||
m.set_env(saved.env);
|
||||
m.push(intermediate);
|
||||
// Call 2: intermediate(orig_arg). Resume to caller.
|
||||
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,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (func, attrset) = m.force_and_retry::<(Gc<Closure>, Gc<AttrSet>)>(reader, mc)?;
|
||||
|
||||
let Closure {
|
||||
ip,
|
||||
n_locals,
|
||||
env,
|
||||
pattern,
|
||||
} = *func;
|
||||
let Some(pattern) = pattern else {
|
||||
unreachable!()
|
||||
};
|
||||
// TODO: get function name
|
||||
// TODO: param spans
|
||||
if !pattern.ellipsis {
|
||||
for key in pattern.required.iter().copied() {
|
||||
if attrset.lookup(key).is_none() {
|
||||
let name = ctx.resolve_string(key);
|
||||
return m.finish_err(Error::eval_error(format!(
|
||||
"function 'anonymous lambda' called without required argument '{name}'"
|
||||
)));
|
||||
let Closure {
|
||||
ip,
|
||||
n_locals,
|
||||
env,
|
||||
pattern,
|
||||
} = *func;
|
||||
let Some(pattern) = pattern else {
|
||||
unreachable!()
|
||||
};
|
||||
// TODO: get function name
|
||||
// TODO: param spans
|
||||
if !pattern.ellipsis {
|
||||
for key in pattern.required.iter().copied() {
|
||||
if attrset.lookup(key).is_none() {
|
||||
let name = ctx.resolve_string(key);
|
||||
return self.finish_err(Error::eval_error(format!(
|
||||
"function 'anonymous lambda' called without required argument '{name}'"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
for &(key, _) in attrset.entries.iter() {
|
||||
let is_expected = pattern.required.contains(&key) || pattern.optional.contains(&key);
|
||||
if !is_expected {
|
||||
let name = ctx.resolve_string(key);
|
||||
return m.finish_err(Error::eval_error(format!(
|
||||
"function 'anonymous lambda' called with unexpected argument '{name}'"
|
||||
)));
|
||||
for &(key, _) in attrset.entries.iter() {
|
||||
let is_expected =
|
||||
pattern.required.contains(&key) || pattern.optional.contains(&key);
|
||||
if !is_expected {
|
||||
let name = ctx.resolve_string(key);
|
||||
return self.finish_err(Error::eval_error(format!(
|
||||
"function 'anonymous lambda' called with unexpected argument '{name}'"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let new_env = Gc::new(
|
||||
mc,
|
||||
RefLock::new(Env::with_arg(Value::new_gc(attrset), n_locals, env)),
|
||||
);
|
||||
reader.set_pc(ip as usize);
|
||||
self.env = new_env;
|
||||
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
let new_env = Gc::new(
|
||||
mc,
|
||||
RefLock::new(Env::with_arg(Value::new(attrset), n_locals, env)),
|
||||
);
|
||||
reader.set_pc(ip as usize);
|
||||
m.set_env(new_env);
|
||||
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
fn is_container(val: Value<'_>) -> bool {
|
||||
|
||||
@@ -1,55 +1 @@
|
||||
use fix_error::Error;
|
||||
use fix_lang::StringId;
|
||||
use fix_runtime::{
|
||||
BytecodeReader, Machine, MachineExt, NixString, NixType, Path, Step, StrictValue, Value,
|
||||
VmRuntimeCtx,
|
||||
};
|
||||
use gc_arena::Mutation;
|
||||
|
||||
pub fn to_string<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
_ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let val = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
if val.is::<StringId>() || val.is::<NixString>() {
|
||||
return m.return_from_primop(val.relax(), reader);
|
||||
}
|
||||
if let Some(p) = val.downcast::<Path>() {
|
||||
return m.return_from_primop(Value::new(p.0), reader);
|
||||
}
|
||||
// TODO: derivations / `__toString` / `outPath`,
|
||||
// numbers, lists.
|
||||
m.finish_err(Error::eval_error(format!(
|
||||
"cannot coerce {} to a string",
|
||||
val.ty()
|
||||
)))
|
||||
}
|
||||
|
||||
#[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,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let val = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
let name: &str = match val.ty() {
|
||||
NixType::Int => "int",
|
||||
NixType::Float => "float",
|
||||
NixType::Bool => "bool",
|
||||
NixType::Null => "null",
|
||||
NixType::String => "string",
|
||||
NixType::Path => "path",
|
||||
NixType::AttrSet => "set",
|
||||
NixType::List => "list",
|
||||
NixType::Closure | NixType::PrimOp | NixType::PrimOpApp => "lambda",
|
||||
NixType::Thunk => unreachable!("forced"),
|
||||
};
|
||||
let sid = ctx.intern_string(name);
|
||||
m.return_from_primop(Value::new(sid), reader)
|
||||
}
|
||||
|
||||
@@ -1,240 +0,0 @@
|
||||
use fix_bytecode::Continuation;
|
||||
use fix_runtime::{
|
||||
AttrSet, BytecodeReader, CallFrame, List, Machine, MachineExt, NixNum, Null, Path, Step,
|
||||
StrictValue, Value, VmRuntimeCtx, VmRuntimeCtxExt,
|
||||
};
|
||||
use gc_arena::{Gc, Mutation};
|
||||
use smallvec::SmallVec;
|
||||
|
||||
pub fn start_eq<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
lhs: StrictValue<'gc>,
|
||||
rhs: StrictValue<'gc>,
|
||||
negate: bool,
|
||||
) -> Step {
|
||||
match shallow_eq(ctx, lhs, rhs) {
|
||||
ShallowEq::True => {
|
||||
m.push(Value::new(!negate));
|
||||
Step::Continue(())
|
||||
}
|
||||
ShallowEq::False => {
|
||||
m.push(Value::new(negate));
|
||||
Step::Continue(())
|
||||
}
|
||||
ShallowEq::RecurseList(la, lb) => {
|
||||
let lhs_init: SmallVec<[Value<'gc>; 4]> = la.inner.borrow().iter().copied().collect();
|
||||
let rhs_init: SmallVec<[Value<'gc>; 4]> = lb.inner.borrow().iter().copied().collect();
|
||||
enter_eq_machine(m, reader, mc, negate, lhs_init, rhs_init)
|
||||
}
|
||||
ShallowEq::RecurseAttrs(a, b) => {
|
||||
let lhs_init: SmallVec<[Value<'gc>; 4]> = a.entries.iter().map(|&(_, v)| v).collect();
|
||||
let rhs_init: SmallVec<[Value<'gc>; 4]> = b.entries.iter().map(|&(_, v)| v).collect();
|
||||
enter_eq_machine(m, reader, mc, negate, lhs_init, rhs_init)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn eq_step<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let rhs_q = m
|
||||
.peek(0)
|
||||
.downcast::<List>()
|
||||
.expect("eq state corrupted: rhs_queue");
|
||||
let lhs_q = m
|
||||
.peek(1)
|
||||
.downcast::<List>()
|
||||
.expect("eq state corrupted: lhs_queue");
|
||||
let result = m
|
||||
.peek(2)
|
||||
.downcast::<bool>()
|
||||
.expect("eq state corrupted: result");
|
||||
|
||||
if !result || lhs_q.inner.borrow().is_empty() {
|
||||
return finalize(m, reader);
|
||||
}
|
||||
|
||||
let lhs = lhs_q
|
||||
.unlock(mc)
|
||||
.borrow_mut()
|
||||
.pop()
|
||||
.expect("non-empty lhs queue");
|
||||
let rhs = rhs_q
|
||||
.unlock(mc)
|
||||
.borrow_mut()
|
||||
.pop()
|
||||
.expect("non-empty rhs queue");
|
||||
m.push(lhs);
|
||||
m.push(rhs);
|
||||
reader.set_pc(Continuation::EqForce.ip() as usize);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
pub fn eq_force<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let (lhs, rhs) = m.force_and_retry::<(StrictValue, StrictValue)>(reader, mc)?;
|
||||
apply_pair(m, ctx, mc, lhs, rhs);
|
||||
reader.set_pc(Continuation::EqStep.ip() as usize);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
fn finalize<'gc, M: Machine<'gc>>(m: &mut M, reader: &mut BytecodeReader<'_>) -> Step {
|
||||
m.drop_n(2);
|
||||
let result = m
|
||||
.pop()
|
||||
.downcast::<bool>()
|
||||
.expect("eq state corrupted: result");
|
||||
let negate = m
|
||||
.pop()
|
||||
.downcast::<bool>()
|
||||
.expect("eq state corrupted: negate");
|
||||
m.return_from_primop(Value::new(result ^ negate), reader)
|
||||
}
|
||||
|
||||
fn apply_pair<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &impl VmRuntimeCtx,
|
||||
mc: &Mutation<'gc>,
|
||||
lhs: StrictValue<'gc>,
|
||||
rhs: StrictValue<'gc>,
|
||||
) {
|
||||
match shallow_eq(ctx, lhs, rhs) {
|
||||
ShallowEq::True => {}
|
||||
ShallowEq::False => {
|
||||
m.replace(2, Value::new(false));
|
||||
}
|
||||
ShallowEq::RecurseList(la, lb) => {
|
||||
extend_queues(
|
||||
m,
|
||||
mc,
|
||||
la.inner.borrow().iter().copied(),
|
||||
lb.inner.borrow().iter().copied(),
|
||||
);
|
||||
}
|
||||
ShallowEq::RecurseAttrs(a, b) => {
|
||||
extend_queues(
|
||||
m,
|
||||
mc,
|
||||
a.entries.iter().map(|&(_, v)| v),
|
||||
b.entries.iter().map(|&(_, v)| v),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn extend_queues<'gc, M, L, R>(m: &mut M, mc: &Mutation<'gc>, lhs_iter: L, rhs_iter: R)
|
||||
where
|
||||
M: Machine<'gc>,
|
||||
L: IntoIterator<Item = Value<'gc>>,
|
||||
R: IntoIterator<Item = Value<'gc>>,
|
||||
{
|
||||
let rhs_q = m
|
||||
.peek(0)
|
||||
.downcast::<List>()
|
||||
.expect("eq state corrupted: rhs_queue");
|
||||
let lhs_q = m
|
||||
.peek(1)
|
||||
.downcast::<List>()
|
||||
.expect("eq state corrupted: lhs_queue");
|
||||
let mut lq = lhs_q.unlock(mc).borrow_mut();
|
||||
let mut rq = rhs_q.unlock(mc).borrow_mut();
|
||||
for (x, y) in lhs_iter.into_iter().zip(rhs_iter) {
|
||||
lq.push(x);
|
||||
rq.push(y);
|
||||
}
|
||||
}
|
||||
|
||||
fn enter_eq_machine<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
negate: bool,
|
||||
lhs_init: SmallVec<[Value<'gc>; 4]>,
|
||||
rhs_init: SmallVec<[Value<'gc>; 4]>,
|
||||
) -> Step {
|
||||
let resume_pc = reader.pc();
|
||||
m.push_call_frame(CallFrame {
|
||||
pc: resume_pc,
|
||||
thunk: None,
|
||||
env: m.env(),
|
||||
depth: None,
|
||||
});
|
||||
m.inc_call_depth();
|
||||
m.push(Value::new(negate));
|
||||
m.push(Value::new(true));
|
||||
m.push(Value::new(List::new(mc, lhs_init)));
|
||||
m.push(Value::new(List::new(mc, rhs_init)));
|
||||
reader.set_pc(Continuation::EqStep.ip() as usize);
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
enum ShallowEq<'gc> {
|
||||
True,
|
||||
False,
|
||||
RecurseList(Gc<'gc, List<'gc>>, Gc<'gc, List<'gc>>),
|
||||
RecurseAttrs(Gc<'gc, AttrSet<'gc>>, Gc<'gc, AttrSet<'gc>>),
|
||||
}
|
||||
|
||||
fn shallow_eq<'gc>(
|
||||
ctx: &impl VmRuntimeCtx,
|
||||
lhs: StrictValue<'gc>,
|
||||
rhs: StrictValue<'gc>,
|
||||
) -> ShallowEq<'gc> {
|
||||
if let (Some(a), Some(b)) = (lhs.downcast_num(), rhs.downcast_num()) {
|
||||
let eq = match (a, b) {
|
||||
(NixNum::Int(a), NixNum::Int(b)) => a == b,
|
||||
(NixNum::Float(a), NixNum::Float(b)) => a == b,
|
||||
(NixNum::Int(a), NixNum::Float(b)) => a as f64 == b,
|
||||
(NixNum::Float(a), NixNum::Int(b)) => a == b as f64,
|
||||
};
|
||||
return bool_outcome(eq);
|
||||
}
|
||||
if let (Some(a), Some(b)) = (lhs.downcast::<bool>(), rhs.downcast::<bool>()) {
|
||||
return bool_outcome(a == b);
|
||||
}
|
||||
if lhs.is::<Null>() && rhs.is::<Null>() {
|
||||
return ShallowEq::True;
|
||||
}
|
||||
if let (Some(a), Some(b)) = (lhs.downcast::<Path>(), rhs.downcast::<Path>()) {
|
||||
return bool_outcome(a.0 == b.0);
|
||||
}
|
||||
if let (Some(a), Some(b)) = (ctx.get_string(lhs), ctx.get_string(rhs)) {
|
||||
return bool_outcome(a == b);
|
||||
}
|
||||
if let (Some(a), Some(b)) = (lhs.downcast::<List>(), rhs.downcast::<List>()) {
|
||||
if a.inner.borrow().len() != b.inner.borrow().len() {
|
||||
return ShallowEq::False;
|
||||
}
|
||||
return ShallowEq::RecurseList(a, b);
|
||||
}
|
||||
if let (Some(a), Some(b)) = (
|
||||
lhs.downcast::<AttrSet<'gc>>(),
|
||||
rhs.downcast::<AttrSet<'gc>>(),
|
||||
) {
|
||||
let ae = &a.entries;
|
||||
let be = &b.entries;
|
||||
if ae.len() != be.len() {
|
||||
return ShallowEq::False;
|
||||
}
|
||||
for (l, r) in ae.iter().zip(be.iter()) {
|
||||
if l.0 != r.0 {
|
||||
return ShallowEq::False;
|
||||
}
|
||||
}
|
||||
return ShallowEq::RecurseAttrs(a, b);
|
||||
}
|
||||
ShallowEq::False
|
||||
}
|
||||
|
||||
fn bool_outcome<'gc>(b: bool) -> ShallowEq<'gc> {
|
||||
if b { ShallowEq::True } else { ShallowEq::False }
|
||||
}
|
||||
+149
-167
@@ -1,186 +1,168 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use fix_bytecode::Continuation;
|
||||
use fix_builtins::PrimOpPhase;
|
||||
use fix_common::StringId;
|
||||
use fix_error::Error;
|
||||
use fix_lang::StringId;
|
||||
use fix_runtime::{
|
||||
AttrSet, Break, BytecodeReader, CallFrame, Machine, MachineExt, Path, PendingLoad,
|
||||
PendingScope, Step, StrictValue, Value, VmRuntimeCtx, VmRuntimeCtxExt, canon_path_str,
|
||||
};
|
||||
use gc_arena::{Gc, Mutation};
|
||||
use hashbrown::HashSet;
|
||||
|
||||
pub fn import<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// stack: [path]
|
||||
let path_val = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
let path_str = match ctx.get_string_or_path(path_val) {
|
||||
Some(s) => s.to_owned(),
|
||||
None => {
|
||||
return m.finish_err(Error::eval_error(format!(
|
||||
"expected a path or string, got {}",
|
||||
path_val.ty()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let abs = match resolve_import_target(&path_str) {
|
||||
Ok(p) => p,
|
||||
Err(e) => return m.finish_err(e),
|
||||
};
|
||||
use crate::bytecode_reader::BytecodeReader;
|
||||
use crate::value::*;
|
||||
use crate::{Break, CallFrame, PendingLoad, PendingScope, Step, Vm, VmRuntimeCtx, VmRuntimeCtxExt};
|
||||
|
||||
if let Some(cached) = m.import_cache_get(&abs) {
|
||||
return m.return_from_primop(cached, reader);
|
||||
impl<'gc> Vm<'gc> {
|
||||
pub(crate) fn primop_import(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// stack: [path]
|
||||
let path_val = self.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
let path_str = match ctx.get_string(path_val) {
|
||||
Some(s) => s.to_owned(),
|
||||
None => {
|
||||
return self.finish_err(Error::eval_error(format!(
|
||||
"expected a path string, got {}",
|
||||
path_val.ty()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let abs = match resolve_import_target(&path_str) {
|
||||
Ok(p) => p,
|
||||
Err(e) => return self.finish_err(e),
|
||||
};
|
||||
|
||||
if let Some(&cached) = self.import_cache.get(&abs) {
|
||||
return self.return_from_primop(cached, reader);
|
||||
}
|
||||
|
||||
// Stash the resolved path on the stack as a string-id so the
|
||||
// finalizer can use it as the cache key. The slot we pop here was
|
||||
// freed by `force_and_retry`, so we simply push.
|
||||
let path_sid = ctx.intern_string(abs.to_string_lossy());
|
||||
self.push(Value::new_inline(path_sid));
|
||||
self.call_stack.push(CallFrame {
|
||||
pc: PrimOpPhase::ImportFinalize.ip() as usize,
|
||||
thunk: None,
|
||||
env: self.env,
|
||||
});
|
||||
|
||||
self.pending_load = Some(PendingLoad {
|
||||
path: abs,
|
||||
scope: None,
|
||||
});
|
||||
Step::Break(Break::LoadFile)
|
||||
}
|
||||
|
||||
// Stash the resolved path on the stack as a string-id so the
|
||||
// finalizer can use it as the cache key. The slot we pop here was
|
||||
// freed by `force_and_retry`, so we simply push.
|
||||
let path_sid = ctx.intern_string(abs.to_string_lossy());
|
||||
m.push(Value::new(path_sid));
|
||||
let env = m.env();
|
||||
m.push_call_frame(CallFrame {
|
||||
pc: Continuation::PImportFinalize.ip() as usize,
|
||||
thunk: None,
|
||||
env,
|
||||
depth: None,
|
||||
});
|
||||
pub(crate) fn primop_import_finalize(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
) -> Step {
|
||||
// stack: [path_sid, return_value]
|
||||
let val = self.pop();
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let path_sid = self.pop().as_inline::<StringId>().unwrap();
|
||||
// The cache key is keyed by the absolute path string we interned in
|
||||
// `primop_import`. Resolve it back to the host PathBuf.
|
||||
let path_str = ctx.resolve_string(path_sid).to_owned();
|
||||
self.import_cache.insert(PathBuf::from(path_str), val);
|
||||
self.push(val);
|
||||
let Some(CallFrame {
|
||||
pc: ret_pc,
|
||||
thunk: _,
|
||||
env,
|
||||
}) = self.call_stack.pop()
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
reader.set_pc(ret_pc);
|
||||
// FIXME:
|
||||
// self.call_depth -= 1;
|
||||
self.env = env;
|
||||
Step::Continue(())
|
||||
}
|
||||
|
||||
m.set_pending_load(PendingLoad {
|
||||
path: abs,
|
||||
scope: None,
|
||||
});
|
||||
Step::Break(Break::LoadFile)
|
||||
}
|
||||
pub(crate) fn primop_scoped_import(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// stack: [scope, path]
|
||||
let (scope_attrs, path_val) =
|
||||
self.force_and_retry::<(Gc<AttrSet>, StrictValue)>(reader, mc)?;
|
||||
let path_str = match ctx.get_string(path_val) {
|
||||
Some(s) => s.to_owned(),
|
||||
None => {
|
||||
return self.finish_err(Error::eval_error(format!(
|
||||
"expected a path string, got {}",
|
||||
path_val.ty()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let abs = match resolve_import_target(&path_str) {
|
||||
Ok(p) => p,
|
||||
Err(e) => return self.finish_err(e),
|
||||
};
|
||||
|
||||
#[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,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
) -> Step {
|
||||
// stack: [path_sid, return_value]
|
||||
let val = m.pop();
|
||||
let path_sid = m
|
||||
.pop()
|
||||
.downcast::<StringId>()
|
||||
.expect("stack slot must be a string");
|
||||
// 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();
|
||||
m.import_cache_insert(PathBuf::from(path_str), val);
|
||||
m.push(val);
|
||||
let Some(CallFrame {
|
||||
pc: ret_pc,
|
||||
thunk: _,
|
||||
env,
|
||||
depth: None,
|
||||
}) = m.pop_call_frame()
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
reader.set_pc(ret_pc);
|
||||
// FIXME:
|
||||
// m.dec_call_depth();
|
||||
m.set_env(env);
|
||||
Step::Continue(())
|
||||
}
|
||||
let keys: HashSet<StringId> = scope_attrs.entries.iter().map(|&(k, _)| k).collect();
|
||||
let slot_id = self.scope_slots.len() as u32;
|
||||
self.scope_slots.push(Value::new_gc(scope_attrs));
|
||||
|
||||
pub fn scoped_import<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// stack: [scope, path]
|
||||
let (scope_attrs, path_val) = m.force_and_retry::<(Gc<AttrSet>, StrictValue)>(reader, mc)?;
|
||||
let path_str = match ctx.get_string_or_path(path_val) {
|
||||
Some(s) => s.to_owned(),
|
||||
None => {
|
||||
return m.finish_err(Error::eval_error(format!(
|
||||
"expected a path or string, got {}",
|
||||
path_val.ty()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let abs = match resolve_import_target(&path_str) {
|
||||
Ok(p) => p,
|
||||
Err(e) => return m.finish_err(e),
|
||||
};
|
||||
self.call_stack.push(CallFrame {
|
||||
pc: PrimOpPhase::ScopedImportFinalize.ip() as usize,
|
||||
thunk: None,
|
||||
env: self.env,
|
||||
});
|
||||
|
||||
let keys: HashSet<StringId> = scope_attrs.entries.iter().map(|&(k, _)| k).collect();
|
||||
let slot_id = m.scope_slots_push(Value::new(scope_attrs));
|
||||
self.pending_load = Some(PendingLoad {
|
||||
path: abs,
|
||||
scope: Some(PendingScope { keys, slot_id }),
|
||||
});
|
||||
Step::Break(Break::LoadFile)
|
||||
}
|
||||
|
||||
let env = m.env();
|
||||
m.push_call_frame(CallFrame {
|
||||
pc: Continuation::PScopedImportFinalize.ip() as usize,
|
||||
thunk: None,
|
||||
env,
|
||||
depth: None,
|
||||
});
|
||||
pub(crate) fn primop_scoped_import_finalize(
|
||||
&mut self,
|
||||
_ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
_mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// stack: [return_value]
|
||||
// We intentionally do NOT pop the slot from `scope_slots` so that
|
||||
// closures or thunks created inside the imported file can still
|
||||
// resolve their scope after `scopedImport` returns.
|
||||
let val = self.pop();
|
||||
self.return_from_primop(val, reader)
|
||||
}
|
||||
|
||||
m.set_pending_load(PendingLoad {
|
||||
path: abs,
|
||||
scope: Some(PendingScope { keys, slot_id }),
|
||||
});
|
||||
Step::Break(Break::LoadFile)
|
||||
}
|
||||
|
||||
pub fn scoped_import_finalize<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
_ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
_mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// stack: [return_value]
|
||||
// We intentionally do NOT pop the slot from `scope_slots` so that
|
||||
// closures or thunks created inside the imported file can still
|
||||
// resolve their scope after `scopedImport` returns.
|
||||
let val = m.pop();
|
||||
m.return_from_primop(val, reader)
|
||||
}
|
||||
|
||||
pub fn path_exists<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let path_val = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
// pathExists requires an absolute path. A `Path` value is
|
||||
// always absolute; a string is accepted only if it starts with `/`.
|
||||
let (path, is_path_value) = if let Some(p) = path_val.downcast::<Path>() {
|
||||
(ctx.resolve_string(p.0).to_owned(), true)
|
||||
} else if let Some(s) = ctx.get_string(path_val) {
|
||||
(s.to_owned(), false)
|
||||
} else {
|
||||
return m.finish_err(Error::eval_error(format!(
|
||||
"expected a path or string, got {}",
|
||||
path_val.ty()
|
||||
)));
|
||||
};
|
||||
if !is_path_value && !path.starts_with('/') {
|
||||
return m.finish_err(Error::eval_error(format!(
|
||||
"string '{path}' doesn't represent an absolute path"
|
||||
)));
|
||||
pub(crate) fn primop_path_exists(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let path_val = self.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
let path = match ctx.get_string(path_val) {
|
||||
Some(s) => s.to_owned(),
|
||||
None => {
|
||||
return self.finish_err(Error::eval_error(format!(
|
||||
"expected a path string, got {}",
|
||||
path_val.ty()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let must_be_dir = path.ends_with('/') || path.ends_with("/.");
|
||||
let p = std::path::Path::new(&path);
|
||||
let exists = if must_be_dir {
|
||||
std::fs::metadata(p).map(|m| m.is_dir()).unwrap_or(false)
|
||||
} else {
|
||||
std::fs::symlink_metadata(p).is_ok()
|
||||
};
|
||||
self.return_from_primop(Value::new_inline(exists), reader)
|
||||
}
|
||||
// CppNix collapses consecutive slashes and resolves `.` / `..` lexically
|
||||
// before checking. Trailing-slash / trailing-dot mean "must be a directory".
|
||||
let must_be_dir = path.ends_with('/') || path.ends_with("/.");
|
||||
let canon = canon_path_str(&path);
|
||||
let p = std::path::Path::new(&canon);
|
||||
let exists = if must_be_dir {
|
||||
std::fs::metadata(p).map(|m| m.is_dir()).unwrap_or(false)
|
||||
} else {
|
||||
std::fs::symlink_metadata(p).is_ok()
|
||||
};
|
||||
m.return_from_primop(Value::new(exists), reader)
|
||||
}
|
||||
|
||||
/// Convert the user-supplied path string into an absolute, dotted-segment
|
||||
|
||||
+65
-108
@@ -1,116 +1,73 @@
|
||||
use fix_error::Result;
|
||||
use fix_macros::handler;
|
||||
use fix_runtime::{List, Slot, StrictValue, Value};
|
||||
use fix_builtins::PrimOpPhase;
|
||||
use gc_arena::Mutation;
|
||||
|
||||
use crate::primops::stubs::*;
|
||||
use crate::bytecode_reader::BytecodeReader;
|
||||
use crate::value::*;
|
||||
use crate::{Step, Vm};
|
||||
|
||||
#[handler(name = PFilter)]
|
||||
fn filter<'gc>(
|
||||
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()));
|
||||
impl<'gc> Vm<'gc> {
|
||||
pub(crate) fn primop_filter_force_list(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
self.force_slot(0, reader, mc)?;
|
||||
let list = match self.peek_forced(0).expect_gc::<List>() {
|
||||
Ok(list) => list,
|
||||
Err(got) => return self.finish_type_err(NixType::List, got),
|
||||
};
|
||||
if list.inner.borrow().is_empty() {
|
||||
let val = self.pop();
|
||||
return self.return_from_primop(val, reader);
|
||||
}
|
||||
// prepare stack layout: [ pred list idx acc ]
|
||||
self.push(Value::new_inline(0));
|
||||
self.push(Value::new_gc(List::new_gc(mc)));
|
||||
reader.set_pc(PrimOpPhase::FilterCallPred.ip() as usize);
|
||||
Step::Continue(())
|
||||
}
|
||||
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);
|
||||
|
||||
pub(crate) fn primop_filter_call_pred(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
self.force_slot(3, reader, mc)?;
|
||||
let pred = self.peek_forced(3);
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let idx = self.peek(1).as_inline::<i32>().unwrap();
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let elem = self.peek_forced(2).as_gc::<List>().unwrap().inner.borrow()[idx as usize];
|
||||
self.push(pred.relax());
|
||||
self.call(reader, mc, elem, PrimOpPhase::FilterCheck.ip() as usize)
|
||||
}
|
||||
|
||||
pub(crate) fn primop_filter_check(
|
||||
&mut self,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let ret = self.force_and_retry::<bool>(reader, mc)?;
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let idx = self.peek(1).as_inline::<i32>().unwrap();
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let list = self.peek_forced(2).as_gc::<List>().unwrap();
|
||||
let list = list.inner.borrow();
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let acc = self.peek_forced(0).as_gc::<List>().unwrap();
|
||||
if ret {
|
||||
let mut acc = acc.unlock(mc).borrow_mut();
|
||||
acc.push(list[idx as usize]);
|
||||
}
|
||||
if idx.get() as usize == list.get().inner.borrow().len() - 1 {
|
||||
return Ok(Value::new(acc.get()));
|
||||
if idx as usize == list.len() - 1 {
|
||||
let acc = self.pop();
|
||||
let _ = self.pop(); // idx
|
||||
let _ = self.pop(); // list
|
||||
let _ = self.pop(); // pred
|
||||
return self.return_from_primop(acc, reader);
|
||||
}
|
||||
idx.set(idx.get() + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[handler(name = PAll)]
|
||||
fn all<'gc>(
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
#[handler(name = PAny)]
|
||||
fn any<'gc>(
|
||||
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));
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
#[handler(name = PFoldlStrict)]
|
||||
fn foldl_strict<'gc>(
|
||||
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);
|
||||
self.replace(1, Value::new_inline(idx + 1));
|
||||
reader.set_pc(PrimOpPhase::FilterCallPred.ip() as usize);
|
||||
Step::Continue(())
|
||||
}
|
||||
}
|
||||
|
||||
+68
-76
@@ -1,88 +1,80 @@
|
||||
mod context;
|
||||
use fix_builtins::PrimOpPhase;
|
||||
use fix_error::Error;
|
||||
use gc_arena::Mutation;
|
||||
use num_enum::TryFromPrimitive;
|
||||
|
||||
use crate::bytecode_reader::BytecodeReader;
|
||||
use crate::value::Value;
|
||||
use crate::{CallFrame, Step, Vm, VmRuntimeCtx};
|
||||
|
||||
mod attrs;
|
||||
mod control;
|
||||
mod conv;
|
||||
mod eq;
|
||||
mod io;
|
||||
mod list;
|
||||
mod path;
|
||||
mod stubs;
|
||||
mod regex;
|
||||
mod version;
|
||||
|
||||
pub use context::*;
|
||||
pub use control::*;
|
||||
pub use conv::*;
|
||||
pub use eq::*;
|
||||
use fix_bytecode::Continuation;
|
||||
use fix_error::Error;
|
||||
use fix_runtime::{BytecodeReader, Machine, Step, VmRuntimeCtx};
|
||||
use gc_arena::Mutation;
|
||||
pub use io::*;
|
||||
pub use list::*;
|
||||
pub use path::*;
|
||||
impl<'gc> Vm<'gc> {
|
||||
#[allow(clippy::too_many_lines)]
|
||||
pub(crate) fn op_dispatch_primop(
|
||||
&mut self,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
use PrimOpPhase::*;
|
||||
let phase_disc = reader.read_u8();
|
||||
let Ok(phase) = PrimOpPhase::try_from_primitive(phase_disc) else {
|
||||
return self.finish_err(Error::eval_error("invalid primop phase"));
|
||||
};
|
||||
match phase {
|
||||
Abort => self.primop_abort(ctx, reader, mc),
|
||||
|
||||
pub fn dispatch_cont<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
use Continuation::*;
|
||||
let cont = reader.read_u8();
|
||||
let Ok(cont) = Continuation::try_from(cont) else {
|
||||
return m.finish_err(Error::eval_error("invalid primop phase"));
|
||||
};
|
||||
match cont {
|
||||
PAbort => abort(m, ctx, reader, mc),
|
||||
DeepSeq => self.primop_deep_seq_force_top(reader, mc),
|
||||
DeepSeqPush => self.primop_deep_seq_push(reader, mc),
|
||||
DeepSeqLoop => self.primop_deep_seq_loop(reader, mc),
|
||||
Seq => self.primop_seq(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)
|
||||
FilterForceList => self.primop_filter_force_list(reader, mc),
|
||||
FilterCallPred => self.primop_filter_call_pred(reader, mc),
|
||||
FilterCheck => self.primop_filter_check(reader, mc),
|
||||
|
||||
ForceResultShallow => self.primop_force_result_shallow(ctx, reader, mc),
|
||||
ForceResultShallowPush => self.primop_force_result_shallow_push(ctx, reader, mc),
|
||||
ForceResultShallowLoop => self.primop_force_result_shallow_loop(reader, mc),
|
||||
ForceResultDeepFinish => self.primop_force_result_deep_finish(ctx, reader, mc),
|
||||
|
||||
CallPattern => self.primop_call_pattern(ctx, reader, mc),
|
||||
CallFunctor1 => self.primop_call_functor_1(reader, mc),
|
||||
CallFunctor2 => self.primop_call_functor_2(reader, mc),
|
||||
|
||||
Import => self.primop_import(ctx, reader, mc),
|
||||
ImportFinalize => self.primop_import_finalize(ctx, reader),
|
||||
ScopedImport => self.primop_scoped_import(ctx, reader, mc),
|
||||
ScopedImportFinalize => self.primop_scoped_import_finalize(ctx, reader, mc),
|
||||
|
||||
PathExists => self.primop_path_exists(ctx, reader, mc),
|
||||
|
||||
phase => todo!("primop phase {phase:?}"),
|
||||
}
|
||||
PSeq0 | PSeq1 => seq(m, reader, mc, cont),
|
||||
}
|
||||
|
||||
PFilter0 | PFilter1 | PFilter2 | PFilter3 | PFilter4 => filter(m, reader, mc, cont),
|
||||
|
||||
PFoldlStrict0 | PFoldlStrict1 | PFoldlStrict2 | PFoldlStrict3 | PFoldlStrict4 | PFoldlStrict5 => {
|
||||
foldl_strict(m, reader, mc, cont)
|
||||
}
|
||||
|
||||
ForceResultShallow => force_result_shallow(m, ctx, reader, mc),
|
||||
ForceResultShallowPush => force_result_shallow_push(m, ctx, reader, mc),
|
||||
ForceResultShallowLoop => force_result_shallow_loop(m, reader, mc),
|
||||
ForceResultDeepFinish => force_result_deep_finish(m, ctx, reader, mc),
|
||||
|
||||
EqStep => eq_step(m, reader, mc),
|
||||
EqForce => eq_force(m, ctx, reader, mc),
|
||||
|
||||
CallPattern => call_pattern(m, ctx, reader, mc),
|
||||
CallFunctor1 => call_functor_1(m, reader, mc),
|
||||
CallFunctor2 => call_functor_2(m, reader, mc),
|
||||
|
||||
PImport => import(m, ctx, reader, mc),
|
||||
PImportFinalize => import_finalize(m, ctx, reader),
|
||||
PScopedImport => scoped_import(m, ctx, reader, mc),
|
||||
PScopedImportFinalize => scoped_import_finalize(m, ctx, reader, mc),
|
||||
|
||||
PPathExists => path_exists(m, ctx, reader, mc),
|
||||
PToPath => to_path(m, ctx, reader, mc),
|
||||
PIsPath => is_path(m, reader, mc),
|
||||
PToString => to_string(m, ctx, reader, mc),
|
||||
PTypeOf => type_of(m, ctx, reader, mc),
|
||||
|
||||
PHasContext => has_context(m, ctx, reader, mc),
|
||||
PGetContext => get_context(m, ctx, reader, mc),
|
||||
PAppendContext => append_context(m, ctx, reader, mc),
|
||||
PAppendContextLoop => append_context_loop(m, ctx, reader, mc),
|
||||
PAppendContextEntryForced => append_context_entry_forced(m, ctx, reader, mc),
|
||||
PAppendContextOutputsForced => append_context_outputs_forced(m, ctx, reader, mc),
|
||||
PAppendContextOutputElementLoop => append_context_output_element_loop(m, ctx, reader, mc),
|
||||
PAppendContextOutputElementForced => {
|
||||
append_context_output_element_forced(m, ctx, reader, mc)
|
||||
}
|
||||
|
||||
PUnsafeDiscardStringContext => unsafe_discard_string_context(m, ctx, reader, mc),
|
||||
PUnsafeDiscardOutputDependency => unsafe_discard_output_dependency(m, ctx, reader, mc),
|
||||
|
||||
phase => todo!("primop phase {phase:?}"),
|
||||
#[inline(always)]
|
||||
fn return_from_primop(&mut self, val: Value<'gc>, reader: &mut BytecodeReader<'_>) -> Step {
|
||||
self.push(val);
|
||||
let Some(CallFrame {
|
||||
pc: ret_pc,
|
||||
thunk: _,
|
||||
env,
|
||||
}) = self.call_stack.pop()
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
reader.set_pc(ret_pc);
|
||||
self.call_depth -= 1;
|
||||
self.env = env;
|
||||
Step::Continue(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,43 +1 @@
|
||||
use fix_error::Error;
|
||||
use fix_runtime::{
|
||||
BytecodeReader, Machine, MachineExt, Path, Step, StrictValue, Value, VmRuntimeCtx,
|
||||
VmRuntimeCtxExt, canon_path_str,
|
||||
};
|
||||
use gc_arena::Mutation;
|
||||
|
||||
pub fn to_path<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
ctx: &mut impl VmRuntimeCtx,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
// coerce to path THEN TO STRING
|
||||
let val = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
if let Some(Path(s)) = val.downcast::<Path>() {
|
||||
return m.return_from_primop(Value::new(s), reader);
|
||||
}
|
||||
let Some(s) = ctx.get_string(val) else {
|
||||
return m.finish_err(Error::eval_error(format!(
|
||||
"cannot coerce {} to a path",
|
||||
val.ty()
|
||||
)));
|
||||
};
|
||||
if !s.starts_with('/') {
|
||||
return m.finish_err(Error::eval_error(format!(
|
||||
"string '{s}' doesn't represent an absolute path"
|
||||
)));
|
||||
}
|
||||
let canon = canon_path_str(s);
|
||||
let sid = ctx.intern_string(canon);
|
||||
m.return_from_primop(Value::new(sid), reader)
|
||||
}
|
||||
|
||||
pub fn is_path<'gc, M: Machine<'gc>>(
|
||||
m: &mut M,
|
||||
reader: &mut BytecodeReader<'_>,
|
||||
mc: &Mutation<'gc>,
|
||||
) -> Step {
|
||||
let val = m.force_and_retry::<StrictValue>(reader, mc)?;
|
||||
let is_path = val.is::<Path>();
|
||||
m.return_from_primop(Value::new(is_path), reader)
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -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};
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,693 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::fmt;
|
||||
use std::marker::PhantomData;
|
||||
use std::mem::size_of;
|
||||
use std::ops::Deref;
|
||||
|
||||
use fix_builtins::BuiltinId;
|
||||
use fix_common::*;
|
||||
use gc_arena::barrier::Unlock;
|
||||
use gc_arena::collect::Trace;
|
||||
use gc_arena::{Collect, Gc, GcRefLock, Mutation, RefLock};
|
||||
use num_enum::TryFromPrimitive;
|
||||
use smallvec::SmallVec;
|
||||
use string_interner::Symbol;
|
||||
use string_interner::symbol::SymbolU32;
|
||||
|
||||
use crate::NixNum;
|
||||
use crate::boxing::{RawBox, RawStore, RawTag, Value as RawValue};
|
||||
|
||||
mod private {
|
||||
pub trait Cealed {}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
///
|
||||
/// TAG must be unique among all implementors.
|
||||
#[allow(private_interfaces)]
|
||||
pub unsafe trait Storable: private::Cealed {
|
||||
const TAG: RawTag;
|
||||
}
|
||||
#[allow(private_bounds)]
|
||||
pub trait InlineStorable: Storable + RawStore {}
|
||||
pub trait GcStorable: Storable {}
|
||||
|
||||
macro_rules! define_value_types {
|
||||
(
|
||||
inline { $($itype:ty => $itag:expr, $iname:literal;)* }
|
||||
gc { $($gtype:ty => $gtag:expr, $gname:literal;)* }
|
||||
) => {
|
||||
$(
|
||||
#[allow(private_interfaces)]
|
||||
unsafe impl Storable for $itype {
|
||||
const TAG: RawTag = $itag;
|
||||
}
|
||||
impl InlineStorable for $itype {}
|
||||
impl private::Cealed for $itype {}
|
||||
)*
|
||||
$(
|
||||
#[allow(private_interfaces)]
|
||||
unsafe impl Storable for $gtype {
|
||||
const TAG: RawTag = $gtag;
|
||||
}
|
||||
impl GcStorable for $gtype {}
|
||||
impl private::Cealed for $gtype {}
|
||||
)*
|
||||
|
||||
const _: () = assert!(size_of::<Value<'static>>() == 8);
|
||||
$(const _: () = assert!(size_of::<$itype>() <= 6);)*
|
||||
|
||||
const _: () = {
|
||||
let tags: &[(bool, u8)] = &[$(RawTag::neg_val($itag)),*, $(RawTag::neg_val($gtag)),*];
|
||||
let mut mask_false: u8 = 0;
|
||||
let mut mask_true: u8 = 0;
|
||||
let mut i = 0;
|
||||
while i < tags.len() {
|
||||
let (neg, val) = tags[i];
|
||||
let bit = 1 << val;
|
||||
if neg {
|
||||
assert!(mask_true & bit == 0, "duplicate true tag id");
|
||||
mask_true |= bit;
|
||||
} else {
|
||||
assert!(mask_false & bit == 0, "duplicate false tag id");
|
||||
mask_false |= bit;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
};
|
||||
|
||||
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 {
|
||||
$(<$gtype as Storable>::TAG => unsafe {
|
||||
self.load_gc::<$gtype>().trace(cc)
|
||||
},)*
|
||||
$(<$itype as Storable>::TAG => (),)*
|
||||
_ => unreachable!("invalid value tag"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Value<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self.tag() {
|
||||
None => write!(f, "Float({:?})", unsafe {
|
||||
self.raw.float().unwrap_unchecked()
|
||||
}),
|
||||
$(Some(<$itype as Storable>::TAG) => write!(f, "{}({:?})", $iname, unsafe {
|
||||
self.as_inline::<$itype>().unwrap_unchecked()
|
||||
}),)*
|
||||
$(Some(<$gtype as Storable>::TAG) =>
|
||||
write!(f, "{}(..)", $gname),)*
|
||||
_ => unreachable!("invalid value tag"),
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
define_value_types! {
|
||||
inline {
|
||||
i32 => RawTag::P1, "SmallInt";
|
||||
bool => RawTag::P2, "Bool";
|
||||
Null => RawTag::P3, "Null";
|
||||
StringId => RawTag::P4, "SmallString";
|
||||
PrimOp => RawTag::P5, "PrimOp";
|
||||
}
|
||||
gc {
|
||||
i64 => RawTag::P6, "BigInt";
|
||||
NixString => RawTag::P7, "String";
|
||||
AttrSet<'_> => RawTag::N1, "AttrSet";
|
||||
List<'_> => RawTag::N2, "List";
|
||||
Thunk<'_> => RawTag::N3, "Thunk";
|
||||
Closure<'_> => RawTag::N4, "Closure";
|
||||
PrimOpApp<'_> => RawTag::N5, "PrimOpApp";
|
||||
}
|
||||
}
|
||||
|
||||
/// # Nix runtime value representation
|
||||
///
|
||||
/// NaN-boxed value fitting in 8 bytes.
|
||||
#[derive(Copy, Clone)]
|
||||
#[repr(transparent)]
|
||||
pub struct Value<'gc> {
|
||||
raw: RawBox,
|
||||
_marker: PhantomData<Gc<'gc, ()>>,
|
||||
}
|
||||
|
||||
impl Default for Value<'_> {
|
||||
#[inline(always)]
|
||||
fn default() -> Self {
|
||||
Self::new_inline(Null)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc> Value<'gc> {
|
||||
#[inline(always)]
|
||||
fn from_raw_value(rv: RawValue) -> Self {
|
||||
Self {
|
||||
raw: RawBox::from_value(rv),
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Load a GC pointer from a value with a negative tag.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// The value must actually store a `Gc<'gc, T>` with the matching type.
|
||||
#[inline(always)]
|
||||
unsafe fn load_gc<T: GcStorable>(self) -> Gc<'gc, T> {
|
||||
unsafe {
|
||||
let rv = self.raw.value().unwrap_unchecked();
|
||||
let ptr: *const T = <*const T as RawStore>::from_val(rv);
|
||||
Gc::from_ptr(ptr)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
const fn tag(self) -> Option<RawTag> {
|
||||
self.raw.tag()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc> Value<'gc> {
|
||||
#[inline]
|
||||
pub fn new_float(val: f64) -> Self {
|
||||
Self {
|
||||
raw: RawBox::from_float(val),
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn new_inline<T: InlineStorable>(val: T) -> Self {
|
||||
Self::from_raw_value(RawValue::store(T::TAG, val))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn new_gc<T: GcStorable>(gc: Gc<'gc, T>) -> Self {
|
||||
let ptr = Gc::as_ptr(gc);
|
||||
Self::from_raw_value(RawValue::store(T::TAG, ptr))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn make_int(val: i64, mc: &Mutation<'gc>) -> Self {
|
||||
if val >= i32::MIN as i64 && val <= i32::MAX as i64 {
|
||||
Value::new_inline(val as i32)
|
||||
} else {
|
||||
Value::new_gc(Gc::new(mc, val))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc> Value<'gc> {
|
||||
#[inline]
|
||||
pub fn is_float(self) -> bool {
|
||||
self.raw.is_float()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is<T: Storable>(self) -> bool {
|
||||
self.tag() == Some(T::TAG)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc> Value<'gc> {
|
||||
#[inline]
|
||||
pub fn as_float(self) -> Option<f64> {
|
||||
self.raw.float().copied()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn as_inline<T: InlineStorable>(self) -> Option<T> {
|
||||
if self.is::<T>() {
|
||||
Some(unsafe {
|
||||
let rv = self.raw.value().unwrap_unchecked();
|
||||
T::from_val(rv)
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn as_gc<T: GcStorable>(self) -> Option<Gc<'gc, T>> {
|
||||
if self.is::<T>() {
|
||||
Some(unsafe {
|
||||
let rv = self.raw.value().unwrap_unchecked();
|
||||
let ptr: *const T = <*const T as RawStore>::from_val(rv);
|
||||
Gc::from_ptr(ptr)
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn to_bits(self) -> u64 {
|
||||
self.raw.to_bits()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn as_num(self) -> Option<NixNum> {
|
||||
if let Some(i) = self.as_inline::<i32>() {
|
||||
Some(NixNum::Int(i as i64))
|
||||
} else if let Some(gc_i) = self.as_gc::<i64>() {
|
||||
Some(NixNum::Int(*gc_i))
|
||||
} else {
|
||||
self.as_float().map(NixNum::Float)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn restrict(self) -> Result<StrictValue<'gc>, Gc<'gc, Thunk<'gc>>> {
|
||||
if let Some(thunk) = self.as_gc::<Thunk<'gc>>() {
|
||||
Err(thunk)
|
||||
} else {
|
||||
Ok(StrictValue(self))
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn ty(self) -> NixType {
|
||||
if self.is_float() {
|
||||
NixType::Float
|
||||
} else if self.is::<i32>() || self.is::<i64>() {
|
||||
NixType::Int
|
||||
} else if self.is::<bool>() {
|
||||
NixType::Bool
|
||||
} else if self.is::<Null>() {
|
||||
NixType::Null
|
||||
} else if self.is::<StringId>() {
|
||||
NixType::String
|
||||
} else if self.is::<PrimOp>() {
|
||||
NixType::PrimOp
|
||||
} else if self.is::<NixString>() {
|
||||
NixType::String
|
||||
} else if self.is::<AttrSet>() {
|
||||
NixType::AttrSet
|
||||
} else if self.is::<List>() {
|
||||
NixType::List
|
||||
} else if self.is::<Thunk>() {
|
||||
NixType::Thunk
|
||||
} else if self.is::<Closure>() {
|
||||
NixType::Closure
|
||||
} else if self.is::<PrimOpApp>() {
|
||||
NixType::PrimOpApp
|
||||
} else {
|
||||
unreachable!("value has no recognized type tag")
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn expect_inline<T: InlineStorable>(self) -> Result<T, NixType> {
|
||||
self.as_inline::<T>().ok_or_else(|| self.ty())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn expect_gc<T: GcStorable>(self) -> Result<Gc<'gc, T>, NixType> {
|
||||
self.as_gc::<T>().ok_or_else(|| self.ty())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn expect_num(self) -> Result<NixNum, NixType> {
|
||||
self.as_num().ok_or_else(|| self.ty())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn expect_bool(self) -> Result<bool, NixType> {
|
||||
self.as_inline::<bool>().ok_or_else(|| self.ty())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn expect_float(self) -> Result<f64, NixType> {
|
||||
self.as_float().ok_or_else(|| self.ty())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Default)]
|
||||
#[repr(transparent)]
|
||||
pub struct StaticValue(Value<'static>);
|
||||
|
||||
impl<'gc> From<StaticValue> for Value<'gc> {
|
||||
#[inline]
|
||||
fn from(value: StaticValue) -> Self {
|
||||
// SAFETY: StaticValue is guaranteed to not contain any `Gc`.
|
||||
unsafe { std::mem::transmute::<Value<'static>, Value<'gc>>(value.0) }
|
||||
}
|
||||
}
|
||||
|
||||
impl StaticValue {
|
||||
#[inline]
|
||||
pub fn new_float(val: f64) -> Self {
|
||||
Self(Value::new_float(val))
|
||||
}
|
||||
#[inline]
|
||||
pub fn new_inline<T: InlineStorable>(val: T) -> Self {
|
||||
Self(Value::new_inline(val))
|
||||
}
|
||||
#[inline]
|
||||
pub fn new_primop(id: BuiltinId, arity: u8, dispatch_ip: u32) -> Self {
|
||||
Self(Value::new_inline(PrimOp {
|
||||
id,
|
||||
arity,
|
||||
dispatch_ip,
|
||||
}))
|
||||
}
|
||||
#[inline]
|
||||
pub fn is_float(self) -> bool {
|
||||
self.0.is_float()
|
||||
}
|
||||
#[inline]
|
||||
pub fn is<T: InlineStorable>(self) -> bool {
|
||||
self.0.is::<T>()
|
||||
}
|
||||
#[inline]
|
||||
pub fn as_float(self) -> Option<f64> {
|
||||
self.0.as_float()
|
||||
}
|
||||
#[inline]
|
||||
pub fn as_inline<T: InlineStorable>(self) -> Option<T> {
|
||||
self.0.as_inline::<T>()
|
||||
}
|
||||
#[inline]
|
||||
pub fn to_bits(self) -> u64 {
|
||||
self.0.raw.to_bits()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Null;
|
||||
impl RawStore for Null {
|
||||
fn to_val(self, value: &mut RawValue) {
|
||||
value.set_data([0; 6]);
|
||||
}
|
||||
fn from_val(_: &RawValue) -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl RawStore for StringId {
|
||||
fn to_val(self, value: &mut RawValue) {
|
||||
(self.0.to_usize() as u32).to_val(value);
|
||||
}
|
||||
fn from_val(value: &RawValue) -> Self {
|
||||
Self(
|
||||
SymbolU32::try_from_usize(u32::from_val(value) as usize)
|
||||
.expect("failed to read StringId from Value"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Heap-allocated Nix string.
|
||||
///
|
||||
/// Stored on the GC heap via `Gc<'gc, NixString>`. The string data itself
|
||||
/// lives in a standard `Box<str>` owned by this struct; the GC only manages
|
||||
/// the outer allocation.
|
||||
#[derive(Collect)]
|
||||
#[collect(require_static)]
|
||||
pub(crate) struct NixString {
|
||||
data: Box<str>,
|
||||
// TODO: string context for derivation dependency tracking
|
||||
}
|
||||
|
||||
impl NixString {
|
||||
pub(crate) fn new(s: impl Into<Box<str>>) -> Self {
|
||||
Self { data: s.into() }
|
||||
}
|
||||
|
||||
pub(crate) fn as_str(&self) -> &str {
|
||||
&self.data
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for NixString {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
fmt::Debug::fmt(&self.data, f)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Collect, Debug, Default)]
|
||||
#[collect(no_drop)]
|
||||
pub(crate) struct AttrSet<'gc> {
|
||||
pub(crate) entries: SmallVec<[(StringId, Value<'gc>); 4]>,
|
||||
}
|
||||
|
||||
impl<'gc> AttrSet<'gc> {
|
||||
pub(crate) fn from_sorted_unchecked(entries: SmallVec<[(StringId, Value<'gc>); 4]>) -> Self {
|
||||
debug_assert!(entries.is_sorted_by_key(|(key, _)| *key));
|
||||
Self { entries }
|
||||
}
|
||||
|
||||
pub(crate) fn lookup(&self, key: StringId) -> Option<Value<'gc>> {
|
||||
self.entries
|
||||
.binary_search_by_key(&key, |(k, _)| *k)
|
||||
.ok()
|
||||
.map(|i| self.entries[i].1)
|
||||
}
|
||||
|
||||
pub(crate) fn has(&self, key: StringId) -> bool {
|
||||
self.entries.binary_search_by_key(&key, |(k, _)| *k).is_ok()
|
||||
}
|
||||
|
||||
pub(crate) fn merge(&self, other: &Self, mc: &Mutation<'gc>) -> Gc<'gc, Self> {
|
||||
use std::cmp::Ordering::*;
|
||||
|
||||
debug_assert!(self.entries.is_sorted_by_key(|(key, _)| *key));
|
||||
debug_assert!(other.entries.is_sorted_by_key(|(key, _)| *key));
|
||||
|
||||
let mut entries = SmallVec::new();
|
||||
let mut i = 0;
|
||||
let mut j = 0;
|
||||
while i < self.entries.len() && j < other.entries.len() {
|
||||
match self.entries[i].0.cmp(&other.entries[j].0) {
|
||||
Less => {
|
||||
entries.push(self.entries[i]);
|
||||
i += 1;
|
||||
}
|
||||
Greater => {
|
||||
entries.push(other.entries[j]);
|
||||
j += 1;
|
||||
}
|
||||
Equal => {
|
||||
entries.push(other.entries[j]);
|
||||
i += 1;
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
entries.extend(other.entries[j..].iter().cloned());
|
||||
entries.extend(self.entries[i..].iter().cloned());
|
||||
|
||||
debug_assert!(entries.is_sorted_by_key(|(key, _)| *key));
|
||||
|
||||
Gc::new(mc, AttrSet { entries })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Collect, Debug, Default)]
|
||||
#[repr(transparent)]
|
||||
#[collect(no_drop)]
|
||||
pub(crate) struct List<'gc> {
|
||||
pub(crate) inner: RefLock<SmallVec<[Value<'gc>; 4]>>,
|
||||
}
|
||||
|
||||
impl<'gc> List<'gc> {
|
||||
pub(crate) fn new(mc: &Mutation<'gc>, data: SmallVec<[Value<'gc>; 4]>) -> Gc<'gc, Self> {
|
||||
Gc::new(
|
||||
mc,
|
||||
Self {
|
||||
inner: RefLock::new(data),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn new_gc(mc: &Mutation<'gc>) -> Gc<'gc, Self> {
|
||||
Gc::new(mc, Self::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc> Unlock for List<'gc> {
|
||||
type Unlocked = RefCell<SmallVec<[Value<'gc>; 4]>>;
|
||||
unsafe fn unlock_unchecked(&self) -> &Self::Unlocked {
|
||||
unsafe { self.inner.unlock_unchecked() }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) type Thunk<'gc> = RefLock<ThunkState<'gc>>;
|
||||
|
||||
#[derive(Collect, Debug)]
|
||||
#[collect(no_drop)]
|
||||
pub(crate) enum ThunkState<'gc> {
|
||||
Pending { ip: usize, env: GcEnv<'gc> },
|
||||
Apply { func: Value<'gc>, arg: Value<'gc> },
|
||||
Blackhole,
|
||||
Evaluated(StrictValue<'gc>),
|
||||
}
|
||||
|
||||
#[derive(Collect, Debug)]
|
||||
#[collect(no_drop)]
|
||||
pub(crate) struct Env<'gc> {
|
||||
pub(crate) locals: SmallVec<[Value<'gc>; 4]>,
|
||||
pub(crate) prev: Option<GcEnv<'gc>>,
|
||||
}
|
||||
pub(crate) type GcEnv<'gc> = GcRefLock<'gc, Env<'gc>>;
|
||||
|
||||
#[derive(Collect, Debug)]
|
||||
#[collect(no_drop)]
|
||||
pub(crate) struct WithEnv<'gc> {
|
||||
pub(crate) env: Value<'gc>,
|
||||
pub(crate) prev: Option<GcWithEnv<'gc>>,
|
||||
}
|
||||
pub(crate) type GcWithEnv<'gc> = Gc<'gc, WithEnv<'gc>>;
|
||||
|
||||
impl<'gc> Env<'gc> {
|
||||
pub(crate) fn empty() -> Self {
|
||||
Env {
|
||||
locals: SmallVec::new(),
|
||||
prev: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) 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;
|
||||
Env {
|
||||
locals,
|
||||
prev: Some(prev),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Collect, Debug)]
|
||||
#[collect(no_drop)]
|
||||
pub(crate) struct Closure<'gc> {
|
||||
pub(crate) ip: u32,
|
||||
pub(crate) n_locals: u32,
|
||||
pub(crate) env: Gc<'gc, RefLock<Env<'gc>>>,
|
||||
pub(crate) pattern: Option<Gc<'gc, PatternInfo>>,
|
||||
}
|
||||
|
||||
#[derive(Collect, Debug)]
|
||||
#[collect(require_static)]
|
||||
pub(crate) struct PatternInfo {
|
||||
pub(crate) required: SmallVec<[StringId; 4]>,
|
||||
pub(crate) optional: SmallVec<[StringId; 4]>,
|
||||
pub(crate) ellipsis: bool,
|
||||
pub(crate) param_spans: Box<[(StringId, u32)]>,
|
||||
}
|
||||
|
||||
#[repr(packed, Rust)]
|
||||
#[derive(Clone, Copy, Debug, Collect)]
|
||||
#[collect(require_static)]
|
||||
pub(crate) struct PrimOp {
|
||||
pub(crate) id: BuiltinId,
|
||||
pub(crate) arity: u8,
|
||||
pub(crate) dispatch_ip: u32,
|
||||
}
|
||||
|
||||
impl RawStore for PrimOp {
|
||||
fn to_val(self, value: &mut RawValue) {
|
||||
let bytes = self.dispatch_ip.to_le_bytes();
|
||||
value.set_data([
|
||||
self.id as u8,
|
||||
self.arity,
|
||||
bytes[0],
|
||||
bytes[1],
|
||||
bytes[2],
|
||||
bytes[3],
|
||||
]);
|
||||
}
|
||||
fn from_val(value: &RawValue) -> Self {
|
||||
let [id, arity, bytes @ ..] = *value.data();
|
||||
Self {
|
||||
id: BuiltinId::try_from_primitive(id).expect("invalid BuiltinId"),
|
||||
arity,
|
||||
dispatch_ip: u32::from_le_bytes(bytes),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Collect, Debug)]
|
||||
#[collect(no_drop)]
|
||||
pub(crate) struct PrimOpApp<'gc> {
|
||||
pub(crate) primop: PrimOp,
|
||||
pub(crate) arity: u8,
|
||||
pub(crate) args: [Value<'gc>; 3],
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Default, Collect)]
|
||||
#[repr(transparent)]
|
||||
#[collect(no_drop)]
|
||||
pub(crate) struct StrictValue<'gc>(Value<'gc>);
|
||||
|
||||
impl<'gc> StrictValue<'gc> {
|
||||
#[inline]
|
||||
pub(crate) fn relax(self) -> Value<'gc> {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<'gc> Deref for StrictValue<'gc> {
|
||||
type Target = Value<'gc>;
|
||||
#[inline]
|
||||
fn deref(&self) -> &Value<'gc> {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for StrictValue<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
fmt::Debug::fmt(&self.0, f)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Collect)]
|
||||
#[collect(require_static)]
|
||||
pub(crate) enum NixType {
|
||||
Int,
|
||||
Float,
|
||||
Bool,
|
||||
Null,
|
||||
String,
|
||||
AttrSet,
|
||||
List,
|
||||
Thunk,
|
||||
Closure,
|
||||
PrimOp,
|
||||
PrimOpApp,
|
||||
}
|
||||
|
||||
impl NixType {
|
||||
pub fn display(self) -> &'static str {
|
||||
use NixType::*;
|
||||
match self {
|
||||
Int => "an integer",
|
||||
Float => "a float",
|
||||
Bool => "a boolean",
|
||||
Null => "null",
|
||||
String => "a string",
|
||||
AttrSet => "a set",
|
||||
List => "a list",
|
||||
Thunk => "a thunk",
|
||||
Closure => "a function",
|
||||
PrimOp => "a built-in function",
|
||||
PrimOpApp => "a partially applied built-in function",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for NixType {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.display())
|
||||
}
|
||||
}
|
||||
+23
-21
@@ -3,18 +3,6 @@ name = "fix"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[[bench]]
|
||||
harness = false
|
||||
name = "basic_ops"
|
||||
|
||||
[[bench]]
|
||||
harness = false
|
||||
name = "builtins"
|
||||
|
||||
[[bench]]
|
||||
harness = false
|
||||
name = "thunk_scope"
|
||||
|
||||
[dependencies]
|
||||
mimalloc = "0.1"
|
||||
|
||||
@@ -29,28 +17,42 @@ clap = { version = "4", features = ["derive"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
miette = { version = "7.4", features = ["fancy"] }
|
||||
# Error Reporting
|
||||
thiserror = "2"
|
||||
miette = { version = "7.4", features = ["fancy"] }
|
||||
|
||||
# Data Structure
|
||||
hashbrown = { workspace = true }
|
||||
string-interner = { workspace = true }
|
||||
|
||||
ere = { workspace = true }
|
||||
# Memory Management
|
||||
bumpalo = { workspace = true }
|
||||
|
||||
fix-bytecode = { path = "../fix-bytecode" }
|
||||
fix-compiler = { path = "../fix-compiler" }
|
||||
rnix = { workspace = true }
|
||||
|
||||
ere = { workspace = true }
|
||||
ghost-cell = { workspace = true }
|
||||
|
||||
fix-builtins = { path = "../fix-builtins" }
|
||||
fix-common = { path = "../fix-common" }
|
||||
fix-codegen = { path = "../fix-codegen" }
|
||||
fix-error = { path = "../fix-error" }
|
||||
fix-lang = { path = "../fix-lang" }
|
||||
fix-runtime = { path = "../fix-runtime" }
|
||||
fix-ir = { path = "../fix-ir" }
|
||||
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
|
||||
[[bench]]
|
||||
name = "basic_ops"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "builtins"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "thunk_scope"
|
||||
harness = false
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
#![allow(clippy::allow_attributes_without_reason)]
|
||||
#![allow(dead_code, clippy::unwrap_used, clippy::unwrap_in_result)]
|
||||
#![allow(dead_code)]
|
||||
|
||||
use fix::Evaluator;
|
||||
use fix_common::Value;
|
||||
use fix_error::{Result, Source};
|
||||
use fix_lang::Value;
|
||||
|
||||
pub fn eval(expr: &str) -> Value {
|
||||
Evaluator::new()
|
||||
|
||||
+599
-26
@@ -1,13 +1,23 @@
|
||||
use fix_bytecode::InstructionPtr;
|
||||
use fix_bytecode::disassembler::{Disassembler, DisassemblerContext};
|
||||
use fix_compiler::{CodeState, ExtraScope};
|
||||
use fix_error::{Result, Source};
|
||||
use fix_lang::StringId;
|
||||
use fix_runtime::{ForceMode, StaticValue, VmCode, VmContext, VmRuntimeCtx};
|
||||
use fix_vm::Vm;
|
||||
#![warn(clippy::unwrap_used)]
|
||||
#![allow(dead_code)]
|
||||
|
||||
use bumpalo::Bump;
|
||||
use fix_builtins::PrimOpPhase;
|
||||
use fix_codegen::disassembler::{Disassembler, DisassemblerContext};
|
||||
use fix_codegen::{BytecodeContext, InstructionPtr, Op};
|
||||
use fix_common::{StringId, Symbol};
|
||||
use fix_error::{Error, Result, Source};
|
||||
use fix_ir::downgrade::{Downgrade as _, DowngradeContext};
|
||||
use fix_ir::{
|
||||
GhostMaybeThunkRef, GhostRoIrRef, GhostRoMaybeThunkRef, GhostRoRef, Ir, MaybeThunk, RawIrRef,
|
||||
ThunkId,
|
||||
};
|
||||
use fix_vm::{ForceMode, StaticValue, Vm, VmCode, VmContext, VmRuntimeCtx};
|
||||
use ghost_cell::{GhostCell, GhostToken};
|
||||
use hashbrown::{HashMap, HashSet};
|
||||
use string_interner::{DefaultStringInterner, Symbol as _};
|
||||
|
||||
mod derivation;
|
||||
pub mod logging;
|
||||
|
||||
#[global_allocator]
|
||||
@@ -18,6 +28,17 @@ pub struct RuntimeState {
|
||||
pub constants: Constants,
|
||||
}
|
||||
|
||||
pub struct CodeState {
|
||||
pub bytecode: Vec<u8>,
|
||||
pub sources: Vec<Source>,
|
||||
pub spans: Vec<(usize, rnix::TextRange)>,
|
||||
pub thunk_count: usize,
|
||||
pub global_env: HashMap<StringId, MaybeThunk>,
|
||||
/// Set during a compilation pass when the code is being compiled under a
|
||||
/// `scopedImport` scope. Read by [`CompilerCtx::current_scope_slot`].
|
||||
pub current_scope_slot: Option<u32>,
|
||||
}
|
||||
|
||||
pub struct Evaluator {
|
||||
pub runtime: RuntimeState,
|
||||
pub code: CodeState,
|
||||
@@ -32,25 +53,37 @@ impl Default for Evaluator {
|
||||
impl Evaluator {
|
||||
pub fn new() -> Self {
|
||||
let mut strings = DefaultStringInterner::new();
|
||||
let code = CodeState::new(&mut strings);
|
||||
let global_env = fix_ir::new_global_env(&mut strings);
|
||||
let mut bytecode = Vec::with_capacity(PrimOpPhase::Illegal as usize * 2);
|
||||
for phase in 0..=PrimOpPhase::Illegal as u8 {
|
||||
bytecode.push(Op::DispatchPrimOp as u8);
|
||||
bytecode.push(phase);
|
||||
}
|
||||
Self {
|
||||
runtime: RuntimeState {
|
||||
strings,
|
||||
constants: Constants::default(),
|
||||
},
|
||||
code,
|
||||
code: CodeState {
|
||||
sources: Vec::new(),
|
||||
spans: Vec::new(),
|
||||
thunk_count: 0,
|
||||
bytecode,
|
||||
global_env,
|
||||
current_scope_slot: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn eval(&mut self, source: Source) -> Result<fix_lang::Value> {
|
||||
pub fn eval(&mut self, source: Source) -> Result<fix_common::Value> {
|
||||
self.do_eval(source, None, ForceMode::AsIs)
|
||||
}
|
||||
|
||||
pub fn eval_shallow(&mut self, source: Source) -> Result<fix_lang::Value> {
|
||||
pub fn eval_shallow(&mut self, source: Source) -> Result<fix_common::Value> {
|
||||
self.do_eval(source, None, ForceMode::Shallow)
|
||||
}
|
||||
|
||||
pub fn eval_deep(&mut self, source: Source) -> Result<fix_lang::Value> {
|
||||
pub fn eval_deep(&mut self, source: Source) -> Result<fix_common::Value> {
|
||||
self.do_eval(source, None, ForceMode::Deep)
|
||||
}
|
||||
|
||||
@@ -58,7 +91,7 @@ impl Evaluator {
|
||||
&mut self,
|
||||
source: Source,
|
||||
scope: &HashSet<StringId>,
|
||||
) -> Result<fix_lang::Value> {
|
||||
) -> Result<fix_common::Value> {
|
||||
self.do_eval(source, Some(ExtraScope::Repl(scope)), ForceMode::Shallow)
|
||||
}
|
||||
|
||||
@@ -67,10 +100,14 @@ impl Evaluator {
|
||||
source: Source,
|
||||
extra_scope: Option<ExtraScope<'ctx>>,
|
||||
force_mode: ForceMode,
|
||||
) -> Result<fix_lang::Value> {
|
||||
let ip = self
|
||||
.code
|
||||
.compile_bytecode(source, extra_scope, &mut self.runtime)?;
|
||||
) -> Result<fix_common::Value> {
|
||||
let ip = {
|
||||
let mut compiler = CompilerCtx {
|
||||
code: &mut self.code,
|
||||
runtime: &mut self.runtime,
|
||||
};
|
||||
compiler.compile_bytecode(source, extra_scope)?
|
||||
};
|
||||
Vm::run(self, ip, force_mode)
|
||||
}
|
||||
|
||||
@@ -79,12 +116,16 @@ impl Evaluator {
|
||||
_ident: &str,
|
||||
_expr: &str,
|
||||
_scope: &mut HashSet<StringId>,
|
||||
) -> Result<fix_lang::Value> {
|
||||
) -> Result<fix_common::Value> {
|
||||
todo!("add_binding")
|
||||
}
|
||||
|
||||
pub fn compile_bytecode(&mut self, source: Source) -> Result<InstructionPtr> {
|
||||
self.code.compile_bytecode(source, None, &mut self.runtime)
|
||||
let mut compiler = CompilerCtx {
|
||||
code: &mut self.code,
|
||||
runtime: &mut self.runtime,
|
||||
};
|
||||
compiler.compile_bytecode(source, None)
|
||||
}
|
||||
|
||||
pub fn disassemble_colored(&self, ip: InstructionPtr) -> String {
|
||||
@@ -97,24 +138,163 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
impl VmCode for CodeState {
|
||||
fn bytecode(&self) -> &[u8] {
|
||||
&self.bytecode
|
||||
}
|
||||
fn compile_with_scope(
|
||||
&mut self,
|
||||
source: Source,
|
||||
extra_scope: Option<fix_vm::ExtraScope>,
|
||||
runtime: &mut impl VmRuntimeCtx,
|
||||
) -> Result<InstructionPtr> {
|
||||
let mut compiler = CompilerCtx {
|
||||
code: self,
|
||||
runtime,
|
||||
};
|
||||
let extra = extra_scope.map(|s| match s {
|
||||
fix_vm::ExtraScope::ScopedImport { keys, slot_id } => {
|
||||
ExtraScope::ScopedImport { keys, slot_id }
|
||||
}
|
||||
});
|
||||
compiler.compile_bytecode(source, extra)
|
||||
}
|
||||
}
|
||||
|
||||
impl VmContext for Evaluator {
|
||||
fn split(&mut self) -> (&mut impl VmCode, &mut impl VmRuntimeCtx) {
|
||||
(&mut self.code, &mut self.runtime)
|
||||
}
|
||||
}
|
||||
|
||||
struct CompilerCtx<'a, R: VmRuntimeCtx> {
|
||||
code: &'a mut CodeState,
|
||||
runtime: &'a mut R,
|
||||
}
|
||||
|
||||
impl<'a, R: VmRuntimeCtx> CompilerCtx<'a, R> {
|
||||
fn compile_bytecode(
|
||||
&mut self,
|
||||
source: Source,
|
||||
extra_scope: Option<ExtraScope>,
|
||||
) -> Result<InstructionPtr> {
|
||||
let prev_scope_slot = self.code.current_scope_slot;
|
||||
self.code.current_scope_slot = match &extra_scope {
|
||||
Some(ExtraScope::ScopedImport { slot_id, .. }) => Some(*slot_id),
|
||||
_ => None,
|
||||
};
|
||||
let result = (|| -> Result<InstructionPtr> {
|
||||
let root = self.downgrade(source, extra_scope)?;
|
||||
let ip = fix_codegen::compile_bytecode(root.as_ref(), self);
|
||||
Ok(ip)
|
||||
})();
|
||||
self.code.current_scope_slot = prev_scope_slot;
|
||||
result
|
||||
}
|
||||
|
||||
fn downgrade(&mut self, source: Source, extra_scope: Option<ExtraScope>) -> Result<OwnedIr> {
|
||||
tracing::debug!("Parsing Nix expression");
|
||||
|
||||
self.code.sources.push(source.clone());
|
||||
|
||||
let root = rnix::Root::parse(&source.src);
|
||||
handle_parse_error(root.errors(), source.clone()).map_or(Ok(()), Err)?;
|
||||
|
||||
tracing::debug!("Downgrading Nix expression");
|
||||
let expr = root
|
||||
.tree()
|
||||
.expr()
|
||||
.ok_or_else(|| Error::parse_error("unexpected EOF".into()))?;
|
||||
let bump = Bump::new();
|
||||
GhostToken::new(|token| {
|
||||
let downgrade_ctx = DowngradeCtx::new(
|
||||
&bump,
|
||||
token,
|
||||
self.runtime,
|
||||
&self.code.global_env,
|
||||
extra_scope.map(Into::into),
|
||||
&mut self.code.thunk_count,
|
||||
source,
|
||||
);
|
||||
let ir = downgrade_ctx.downgrade_toplevel(expr)?;
|
||||
let ir = unsafe { std::mem::transmute::<RawIrRef<'_>, RawIrRef<'static>>(ir) };
|
||||
Ok(OwnedIr { _bump: bump, ir })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, R: VmRuntimeCtx> BytecodeContext for CompilerCtx<'a, R> {
|
||||
fn intern_string(&mut self, s: &str) -> StringId {
|
||||
self.runtime.intern_string(s)
|
||||
}
|
||||
|
||||
fn register_span(&mut self, range: rnix::TextRange) -> u32 {
|
||||
let id = self.code.spans.len();
|
||||
let source_id = self
|
||||
.code
|
||||
.sources
|
||||
.len()
|
||||
.checked_sub(1)
|
||||
.expect("current_source not set");
|
||||
self.code.spans.push((source_id, range));
|
||||
id as u32
|
||||
}
|
||||
|
||||
fn get_code(&self) -> &[u8] {
|
||||
&self.code.bytecode
|
||||
}
|
||||
|
||||
fn get_code_mut(&mut self) -> &mut Vec<u8> {
|
||||
&mut self.code.bytecode
|
||||
}
|
||||
|
||||
fn add_constant(&mut self, val: fix_codegen::Const) -> u32 {
|
||||
use fix_codegen::Const::*;
|
||||
let val = match val {
|
||||
Smi(x) => StaticValue::new_inline(x),
|
||||
Float(x) => StaticValue::new_float(x),
|
||||
Bool(x) => StaticValue::new_inline(x),
|
||||
String(x) => StaticValue::new_inline(x),
|
||||
Path(_) => todo!("path value type"),
|
||||
PrimOp {
|
||||
id,
|
||||
arity,
|
||||
dispatch_ip,
|
||||
} => StaticValue::new_primop(id, arity, dispatch_ip),
|
||||
Null => StaticValue::default(),
|
||||
};
|
||||
self.runtime.add_const(val)
|
||||
}
|
||||
|
||||
fn current_source_dir(&mut self) -> StringId {
|
||||
let dir = self
|
||||
.code
|
||||
.sources
|
||||
.last()
|
||||
.expect("current_source not set")
|
||||
.get_dir()
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
self.runtime.intern_string(dir)
|
||||
}
|
||||
|
||||
fn current_scope_slot(&self) -> Option<u32> {
|
||||
self.code.current_scope_slot
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Constants {
|
||||
data: Vec<StaticValue>,
|
||||
@@ -136,14 +316,407 @@ impl Constants {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_error_span(error: &rnix::ParseError) -> Option<rnix::TextRange> {
|
||||
use rnix::ParseError::*;
|
||||
match error {
|
||||
Unexpected(range)
|
||||
| UnexpectedExtra(range)
|
||||
| UnexpectedWanted(_, range, _)
|
||||
| UnexpectedDoubleBind(range)
|
||||
| DuplicatedArgs(range, _) => Some(*range),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_parse_error<'a>(
|
||||
errors: impl IntoIterator<Item = &'a rnix::ParseError>,
|
||||
source: Source,
|
||||
) -> Option<Box<Error>> {
|
||||
for err in errors {
|
||||
if let Some(span) = parse_error_span(err) {
|
||||
return Some(
|
||||
Error::parse_error(err.to_string())
|
||||
.with_source(source)
|
||||
.with_span(span),
|
||||
);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
struct DowngradeCtx<'ctx, 'id, 'ir, R: VmRuntimeCtx> {
|
||||
bump: &'ir Bump,
|
||||
token: GhostToken<'id>,
|
||||
runtime: &'ctx mut R,
|
||||
source: Source,
|
||||
scopes: Vec<Scope<'ctx, 'id, 'ir>>,
|
||||
with_stack: Vec<GhostRoMaybeThunkRef<'id, 'ir>>,
|
||||
arg_count: u32,
|
||||
thunk_count: &'ctx mut usize,
|
||||
thunk_scopes: Vec<ThunkScope<'id, 'ir>>,
|
||||
}
|
||||
|
||||
impl<'ctx, 'id, 'ir, R: VmRuntimeCtx> DowngradeCtx<'ctx, 'id, 'ir, R> {
|
||||
fn new(
|
||||
bump: &'ir Bump,
|
||||
token: GhostToken<'id>,
|
||||
runtime: &'ctx mut R,
|
||||
global: &'ctx HashMap<StringId, MaybeThunk>,
|
||||
extra_scope: Option<Scope<'ctx, 'id, 'ir>>,
|
||||
thunk_count: &'ctx mut usize,
|
||||
source: Source,
|
||||
) -> Self {
|
||||
Self {
|
||||
bump,
|
||||
token,
|
||||
runtime,
|
||||
source,
|
||||
scopes: std::iter::once(Scope::Global(global))
|
||||
.chain(extra_scope)
|
||||
.collect(),
|
||||
thunk_count,
|
||||
arg_count: 0,
|
||||
with_stack: Vec::new(),
|
||||
thunk_scopes: vec![ThunkScope::new_in(bump)],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ctx: 'ir, 'id, 'ir, R: VmRuntimeCtx> DowngradeContext<'id, 'ir>
|
||||
for DowngradeCtx<'ctx, 'id, 'ir, R>
|
||||
{
|
||||
fn new_expr(&self, expr: Ir<'ir, GhostRoRef<'id, 'ir>>) -> GhostRoIrRef<'id, 'ir> {
|
||||
self.bump.alloc(GhostCell::new(expr).into())
|
||||
}
|
||||
|
||||
fn maybe_thunk(&mut self, ir: GhostRoIrRef<'id, 'ir>) -> GhostRoMaybeThunkRef<'id, 'ir> {
|
||||
use MaybeThunk::*;
|
||||
let expr = (|| {
|
||||
let expr = match *ir.borrow(&self.token) {
|
||||
Ir::Builtin(x) => Builtin(x),
|
||||
Ir::Int(x) => Int(x),
|
||||
Ir::Float(x) => Float(x),
|
||||
Ir::Bool(x) => Bool(x),
|
||||
Ir::Str(x) => Str(x),
|
||||
Ir::Arg { layer } => Arg { layer },
|
||||
Ir::Builtins => Builtins,
|
||||
Ir::Null => Null,
|
||||
Ir::MaybeThunk(thunk) => return Some(thunk),
|
||||
_ => return None,
|
||||
};
|
||||
Some(self.bump.alloc(GhostCell::new(expr).into()))
|
||||
})();
|
||||
if let Some(thunk) = expr {
|
||||
return thunk;
|
||||
}
|
||||
let id = ThunkId(*self.thunk_count);
|
||||
*self.thunk_count = self.thunk_count.checked_add(1).expect("thunk id overflow");
|
||||
self.thunk_scopes
|
||||
.last_mut()
|
||||
.expect("no active cache scope")
|
||||
.add_binding(id, ir);
|
||||
self.bump.alloc(GhostCell::new(Thunk(id)).into())
|
||||
}
|
||||
|
||||
fn intern_string(&mut self, sym: impl AsRef<str>) -> StringId {
|
||||
self.runtime.intern_string(sym)
|
||||
}
|
||||
|
||||
fn resolve_sym(&self, id: StringId) -> Symbol<'_> {
|
||||
self.runtime.resolve_string(id).into()
|
||||
}
|
||||
|
||||
fn lookup(
|
||||
&mut self,
|
||||
sym: StringId,
|
||||
span: rnix::TextRange,
|
||||
) -> Result<GhostRoMaybeThunkRef<'id, 'ir>> {
|
||||
for scope in self.scopes.iter().rev() {
|
||||
match scope {
|
||||
&Scope::Global(global_scope) => {
|
||||
if let Some(expr) = global_scope.get(&sym) {
|
||||
return Ok(expr.into());
|
||||
}
|
||||
}
|
||||
&Scope::Repl(repl_bindings) => {
|
||||
if repl_bindings.contains(&sym) {
|
||||
return Ok(self
|
||||
.bump
|
||||
.alloc(GhostCell::new(MaybeThunk::ReplBinding(sym)).into()));
|
||||
}
|
||||
}
|
||||
Scope::ScopedImport { keys, .. } => {
|
||||
if keys.contains(&sym) {
|
||||
return Ok(self
|
||||
.bump
|
||||
.alloc(GhostCell::new(MaybeThunk::ScopedImportBinding(sym)).into()));
|
||||
}
|
||||
}
|
||||
Scope::Let(let_scope) => {
|
||||
if let Some(&expr) = let_scope.get(&sym) {
|
||||
return Ok(expr.into());
|
||||
}
|
||||
}
|
||||
&Scope::Param {
|
||||
sym: param_sym,
|
||||
abs_layer,
|
||||
} => {
|
||||
if param_sym == sym {
|
||||
let layers: u8 =
|
||||
self.thunk_scopes.len().try_into().expect("scope too deep!");
|
||||
let layer = layers - abs_layer;
|
||||
return Ok(self
|
||||
.bump
|
||||
.alloc(GhostCell::new(MaybeThunk::Arg { layer }).into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !self.with_stack.is_empty() {
|
||||
let id = ThunkId(*self.thunk_count);
|
||||
*self.thunk_count = self.thunk_count.checked_add(1).expect("thunk id overflow");
|
||||
let mut namespaces =
|
||||
bumpalo::collections::Vec::with_capacity_in(self.with_stack.len(), self.bump);
|
||||
namespaces.extend(self.with_stack.iter().rev().copied());
|
||||
let body = self
|
||||
.bump
|
||||
.alloc(GhostCell::new(Ir::WithLookup { sym, namespaces }).into());
|
||||
self.thunk_scopes
|
||||
.last_mut()
|
||||
.expect("no active thunk scope")
|
||||
.add_binding(id, body);
|
||||
Ok(self
|
||||
.bump
|
||||
.alloc(GhostCell::new(MaybeThunk::Thunk(id)).into()))
|
||||
} else {
|
||||
Err(Error::downgrade_error(
|
||||
format!("'{}' not found", self.resolve_sym(sym)),
|
||||
self.get_current_source(),
|
||||
span,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn get_current_source(&self) -> Source {
|
||||
self.source.clone()
|
||||
}
|
||||
|
||||
fn with_let_scope<F, Ret>(&mut self, keys: &[StringId], f: F) -> Result<Ret>
|
||||
where
|
||||
F: FnOnce(
|
||||
&mut Self,
|
||||
) -> Result<(
|
||||
bumpalo::collections::Vec<'ir, GhostRoMaybeThunkRef<'id, 'ir>>,
|
||||
Ret,
|
||||
)>,
|
||||
{
|
||||
let base = *self.thunk_count;
|
||||
*self.thunk_count = self
|
||||
.thunk_count
|
||||
.checked_add(keys.len())
|
||||
.expect("thunk id overflow");
|
||||
let handles = (base..base + keys.len())
|
||||
.map(|id| {
|
||||
&*self
|
||||
.bump
|
||||
.alloc(GhostCell::new(MaybeThunk::Thunk(ThunkId(id))))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let scope = keys.iter().copied().zip(handles.iter().copied()).collect();
|
||||
self.scopes.push(Scope::Let(scope));
|
||||
let (vals, ret) = { f(self)? };
|
||||
self.scopes.pop();
|
||||
assert_eq!(keys.len(), vals.len());
|
||||
let scope = self.thunk_scopes.last_mut().expect("no active thunk scope");
|
||||
for (i, (val, handle)) in vals.into_iter().zip(handles).enumerate() {
|
||||
let thunk = *val.borrow(&self.token);
|
||||
*handle.borrow_mut(&mut self.token) = thunk;
|
||||
let id = ThunkId(base + i);
|
||||
let ir_ref = self
|
||||
.bump
|
||||
.alloc(GhostCell::new(Ir::MaybeThunk(handle.into())).into());
|
||||
scope.add_binding(id, ir_ref);
|
||||
}
|
||||
Ok(ret)
|
||||
}
|
||||
|
||||
fn with_param_scope<F, Ret>(&mut self, sym: StringId, f: F) -> Ret
|
||||
where
|
||||
F: FnOnce(&mut Self) -> Ret,
|
||||
{
|
||||
self.scopes.push(Scope::Param {
|
||||
sym,
|
||||
abs_layer: self.thunk_scopes.len().try_into().expect("scope too deep!"),
|
||||
});
|
||||
let mut guard = ScopeGuard { ctx: self };
|
||||
f(guard.as_ctx())
|
||||
}
|
||||
|
||||
fn with_with_scope<F, Ret>(&mut self, namespace: GhostRoMaybeThunkRef<'id, 'ir>, f: F) -> Ret
|
||||
where
|
||||
F: FnOnce(&mut Self) -> Ret,
|
||||
{
|
||||
self.with_stack.push(namespace);
|
||||
let ret = f(self);
|
||||
self.with_stack.pop();
|
||||
ret
|
||||
}
|
||||
|
||||
fn with_thunk_scope<F, Ret>(
|
||||
&mut self,
|
||||
f: F,
|
||||
) -> (
|
||||
Ret,
|
||||
bumpalo::collections::Vec<'ir, (ThunkId, GhostRoIrRef<'id, 'ir>)>,
|
||||
)
|
||||
where
|
||||
F: FnOnce(&mut Self) -> Ret,
|
||||
{
|
||||
if self.thunk_scopes.len() == u8::MAX as usize {
|
||||
panic!("scope too deep!");
|
||||
}
|
||||
self.thunk_scopes.push(ThunkScope::new_in(self.bump));
|
||||
let ret = f(self);
|
||||
(
|
||||
ret,
|
||||
self.thunk_scopes
|
||||
.pop()
|
||||
.expect("no thunk scope left???")
|
||||
.bindings,
|
||||
)
|
||||
}
|
||||
|
||||
fn bump(&self) -> &'ir bumpalo::Bump {
|
||||
self.bump
|
||||
}
|
||||
}
|
||||
|
||||
impl<'id, 'ir, 'ctx: 'ir, R: VmRuntimeCtx> DowngradeCtx<'ctx, 'id, 'ir, R> {
|
||||
fn downgrade_toplevel(mut self, root: rnix::ast::Expr) -> Result<RawIrRef<'ir>> {
|
||||
let body = root.downgrade(&mut self)?;
|
||||
let thunks = self
|
||||
.thunk_scopes
|
||||
.pop()
|
||||
.expect("no thunk scope left???")
|
||||
.bindings;
|
||||
Ok(Ir::freeze(
|
||||
self.new_expr(Ir::TopLevel { body, thunks }),
|
||||
self.token,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
struct ThunkScope<'id, 'ir> {
|
||||
bindings: bumpalo::collections::Vec<'ir, (ThunkId, GhostRoIrRef<'id, 'ir>)>,
|
||||
}
|
||||
|
||||
impl<'id, 'ir> ThunkScope<'id, 'ir> {
|
||||
fn new_in(bump: &'ir Bump) -> Self {
|
||||
Self {
|
||||
bindings: bumpalo::collections::Vec::new_in(bump),
|
||||
}
|
||||
}
|
||||
|
||||
fn add_binding(&mut self, id: ThunkId, ir: GhostRoIrRef<'id, 'ir>) {
|
||||
self.bindings.push((id, ir));
|
||||
}
|
||||
|
||||
fn extend_bindings(
|
||||
&mut self,
|
||||
iter: impl IntoIterator<Item = (ThunkId, GhostRoIrRef<'id, 'ir>)>,
|
||||
) {
|
||||
self.bindings.extend(iter);
|
||||
}
|
||||
}
|
||||
|
||||
enum Scope<'ctx, 'id, 'ir> {
|
||||
Global(&'ctx HashMap<StringId, MaybeThunk>),
|
||||
Repl(&'ctx HashSet<StringId>),
|
||||
ScopedImport {
|
||||
keys: HashSet<StringId>,
|
||||
slot_id: u32,
|
||||
},
|
||||
Let(HashMap<StringId, GhostMaybeThunkRef<'id, 'ir>>),
|
||||
Param { sym: StringId, abs_layer: u8 },
|
||||
}
|
||||
|
||||
pub enum ExtraScope<'ctx> {
|
||||
Repl(&'ctx HashSet<StringId>),
|
||||
ScopedImport {
|
||||
keys: HashSet<StringId>,
|
||||
slot_id: u32,
|
||||
},
|
||||
}
|
||||
|
||||
impl<'ctx> From<ExtraScope<'ctx>> for Scope<'ctx, '_, '_> {
|
||||
fn from(value: ExtraScope<'ctx>) -> Self {
|
||||
use ExtraScope::*;
|
||||
match value {
|
||||
ScopedImport { keys, slot_id } => Scope::ScopedImport { keys, slot_id },
|
||||
Repl(scope) => Scope::Repl(scope),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ScopeGuard<'a, 'ctx, 'id, 'ir, R: VmRuntimeCtx> {
|
||||
ctx: &'a mut DowngradeCtx<'ctx, 'id, 'ir, R>,
|
||||
}
|
||||
|
||||
impl<'a, 'ctx, 'id, 'ir, R: VmRuntimeCtx> Drop for ScopeGuard<'a, 'ctx, 'id, 'ir, R> {
|
||||
fn drop(&mut self) {
|
||||
self.ctx.scopes.pop();
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'ctx, 'id, 'ir, R: VmRuntimeCtx> ScopeGuard<'a, 'ctx, 'id, 'ir, R> {
|
||||
fn as_ctx(&mut self) -> &mut DowngradeCtx<'ctx, 'id, 'ir, R> {
|
||||
self.ctx
|
||||
}
|
||||
}
|
||||
|
||||
struct OwnedIr {
|
||||
_bump: Bump,
|
||||
ir: RawIrRef<'static>,
|
||||
}
|
||||
|
||||
impl OwnedIr {
|
||||
/// # Safety
|
||||
/// `ir` must be an allocation backed by `bump`. The reference's
|
||||
/// lifetime is extended to `'static` as a placeholder; the stored IR
|
||||
/// must only be re-borrowed via [`OwnedIr::as_ref`], which narrows
|
||||
/// the lifetime back to that of the `&self` borrow. Moving `bump`
|
||||
/// into the struct keeps the underlying allocation live for the
|
||||
/// lifetime of the `OwnedIr`.
|
||||
unsafe fn new(ir: RawIrRef<'_>, bump: Bump) -> Self {
|
||||
Self {
|
||||
_bump: bump,
|
||||
// SAFETY: see function docs - caller guarantees `ir` is in `bump`,
|
||||
// and the `'static` lifetime is a placeholder narrowed by `as_ref`.
|
||||
ir: unsafe { std::mem::transmute::<RawIrRef<'_>, RawIrRef<'static>>(ir) },
|
||||
}
|
||||
}
|
||||
|
||||
fn as_ref<'ir>(&'ir self) -> RawIrRef<'ir> {
|
||||
// SAFETY: narrows the placeholder `'static` lifetime stored in
|
||||
// `self.ir` down to `'ir = &'ir self`. Lifetime shortening is
|
||||
// logically sound for covariant positions; the transmute is only
|
||||
// needed because `RawRef<'ir>` carries `'ir` through a GAT
|
||||
// (`Ref::Ref<T>`), which prevents the compiler from inferring
|
||||
// covariance automatically. The bump arena that backs the IR is
|
||||
// owned by `self._bump`, so the data is live for at least `'ir`.
|
||||
unsafe { std::mem::transmute::<RawIrRef<'static>, RawIrRef<'ir>>(self.ir) }
|
||||
}
|
||||
}
|
||||
|
||||
impl DisassemblerContext for Evaluator {
|
||||
fn get_code(&self) -> &[u8] {
|
||||
&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
@@ -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
@@ -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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
||||
|
||||
pub enum StringContextElem {
|
||||
Opaque { path: String },
|
||||
DrvDeep { drv_path: String },
|
||||
Built { drv_path: String, output: String },
|
||||
}
|
||||
|
||||
impl StringContextElem {
|
||||
pub fn decode(encoded: &str) -> Self {
|
||||
if let Some(drv_path) = encoded.strip_prefix('=') {
|
||||
StringContextElem::DrvDeep {
|
||||
drv_path: drv_path.to_string(),
|
||||
}
|
||||
} else if let Some(rest) = encoded.strip_prefix('!') {
|
||||
if let Some(second_bang) = rest.find('!') {
|
||||
let output = rest[..second_bang].to_string();
|
||||
let drv_path = rest[second_bang + 1..].to_string();
|
||||
StringContextElem::Built { drv_path, output }
|
||||
} else {
|
||||
StringContextElem::Opaque {
|
||||
path: encoded.to_string(),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
StringContextElem::Opaque {
|
||||
path: encoded.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type InputDrvs = BTreeMap<String, BTreeSet<String>>;
|
||||
pub type Srcs = BTreeSet<String>;
|
||||
pub fn extract_input_drvs_and_srcs(context: &[String]) -> Result<(InputDrvs, Srcs), String> {
|
||||
let mut input_drvs: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
|
||||
let mut input_srcs: BTreeSet<String> = BTreeSet::new();
|
||||
|
||||
for encoded in context {
|
||||
match StringContextElem::decode(encoded) {
|
||||
StringContextElem::Opaque { path } => {
|
||||
input_srcs.insert(path);
|
||||
}
|
||||
StringContextElem::DrvDeep { drv_path } => {
|
||||
compute_fs_closure(&drv_path, &mut input_drvs, &mut input_srcs)?;
|
||||
}
|
||||
StringContextElem::Built { drv_path, output } => {
|
||||
input_drvs.entry(drv_path).or_default().insert(output);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok((input_drvs, input_srcs))
|
||||
}
|
||||
|
||||
fn compute_fs_closure(
|
||||
drv_path: &str,
|
||||
input_drvs: &mut BTreeMap<String, BTreeSet<String>>,
|
||||
input_srcs: &mut BTreeSet<String>,
|
||||
) -> Result<(), String> {
|
||||
let mut queue: VecDeque<String> = VecDeque::new();
|
||||
let mut visited: BTreeSet<String> = BTreeSet::new();
|
||||
|
||||
queue.push_back(drv_path.to_string());
|
||||
|
||||
while let Some(current_path) = queue.pop_front() {
|
||||
if visited.contains(¤t_path) {
|
||||
continue;
|
||||
}
|
||||
visited.insert(current_path.clone());
|
||||
input_srcs.insert(current_path.clone());
|
||||
|
||||
if !current_path.ends_with(".drv") {
|
||||
continue;
|
||||
}
|
||||
|
||||
let content = std::fs::read_to_string(¤t_path)
|
||||
.map_err(|e| format!("failed to read derivation {}: {}", current_path, e))?;
|
||||
|
||||
let inputs = parse_derivation_inputs(&content)
|
||||
.ok_or_else(|| format!("failed to parse derivation {}", current_path))?;
|
||||
|
||||
for src in inputs.input_srcs {
|
||||
input_srcs.insert(src.clone());
|
||||
if !visited.contains(&src) {
|
||||
queue.push_back(src);
|
||||
}
|
||||
}
|
||||
|
||||
for (dep_drv, outputs) in inputs.input_drvs {
|
||||
input_srcs.insert(dep_drv.clone());
|
||||
let entry = input_drvs.entry(dep_drv.clone()).or_default();
|
||||
for output in outputs {
|
||||
entry.insert(output);
|
||||
}
|
||||
if !visited.contains(&dep_drv) {
|
||||
queue.push_back(dep_drv);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct DerivationInputs {
|
||||
input_drvs: Vec<(String, Vec<String>)>,
|
||||
input_srcs: Vec<String>,
|
||||
}
|
||||
|
||||
fn parse_derivation_inputs(aterm: &str) -> Option<DerivationInputs> {
|
||||
let aterm = aterm.strip_prefix("Derive([")?;
|
||||
|
||||
let mut bracket_count: i32 = 1;
|
||||
let mut pos = 0;
|
||||
let bytes = aterm.as_bytes();
|
||||
while pos < bytes.len() && bracket_count > 0 {
|
||||
match bytes[pos] {
|
||||
b'[' => bracket_count += 1,
|
||||
b']' => bracket_count -= 1,
|
||||
_ => {}
|
||||
}
|
||||
pos += 1;
|
||||
}
|
||||
if bracket_count != 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let rest = &aterm[pos..];
|
||||
let rest = rest.strip_prefix(",[")?;
|
||||
|
||||
let mut input_drvs = Vec::new();
|
||||
let mut bracket_count: i32 = 1;
|
||||
let mut start = 0;
|
||||
pos = 0;
|
||||
let bytes = rest.as_bytes();
|
||||
|
||||
while pos < bytes.len() && bracket_count > 0 {
|
||||
match bytes[pos] {
|
||||
b'[' => bracket_count += 1,
|
||||
b']' => bracket_count -= 1,
|
||||
b'(' if bracket_count == 1 => {
|
||||
start = pos;
|
||||
}
|
||||
b')' if bracket_count == 1 => {
|
||||
let entry = &rest[start + 1..pos];
|
||||
if let Some((drv_path, outputs)) = parse_input_drv_entry(entry) {
|
||||
input_drvs.push((drv_path, outputs));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
pos += 1;
|
||||
}
|
||||
|
||||
let rest = &rest[pos..];
|
||||
let rest = rest.strip_prefix(",[")?;
|
||||
|
||||
let mut input_srcs = Vec::new();
|
||||
bracket_count = 1;
|
||||
pos = 0;
|
||||
let bytes = rest.as_bytes();
|
||||
|
||||
while pos < bytes.len() && bracket_count > 0 {
|
||||
match bytes[pos] {
|
||||
b'[' => bracket_count += 1,
|
||||
b']' => bracket_count -= 1,
|
||||
b'"' if bracket_count == 1 => {
|
||||
pos += 1;
|
||||
let src_start = pos;
|
||||
while pos < bytes.len() && bytes[pos] != b'"' {
|
||||
if bytes[pos] == b'\\' && pos + 1 < bytes.len() {
|
||||
pos += 2;
|
||||
} else {
|
||||
pos += 1;
|
||||
}
|
||||
}
|
||||
let src = std::str::from_utf8(&bytes[src_start..pos]).ok()?;
|
||||
input_srcs.push(src.to_string());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
pos += 1;
|
||||
}
|
||||
|
||||
Some(DerivationInputs {
|
||||
input_drvs,
|
||||
input_srcs,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_input_drv_entry(entry: &str) -> Option<(String, Vec<String>)> {
|
||||
let entry = entry.strip_prefix('"')?;
|
||||
let quote_end = entry.find('"')?;
|
||||
let drv_path = entry[..quote_end].to_string();
|
||||
|
||||
let rest = &entry[quote_end + 1..];
|
||||
let rest = rest.strip_prefix(",[")?;
|
||||
let rest = rest.strip_suffix(']')?;
|
||||
|
||||
let mut outputs = Vec::new();
|
||||
for part in rest.split(',') {
|
||||
let part = part.trim();
|
||||
if let Some(name) = part.strip_prefix('"').and_then(|s| s.strip_suffix('"')) {
|
||||
outputs.push(name.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Some((drv_path, outputs))
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use fix_lang::Value;
|
||||
use fix_common::Value;
|
||||
|
||||
use crate::utils::{eval_deep, eval_deep_result};
|
||||
|
||||
@@ -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,6 +1,6 @@
|
||||
use fix::Evaluator;
|
||||
use fix_common::Value;
|
||||
use fix_error::Source;
|
||||
use fix_lang::Value;
|
||||
|
||||
use crate::utils::{eval, eval_result};
|
||||
|
||||
@@ -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]
|
||||
|
||||
+8
-19
@@ -3,9 +3,8 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use fix::Evaluator;
|
||||
use fix_common::Value;
|
||||
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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use fix::Evaluator;
|
||||
use fix_lang::Value;
|
||||
use fix_common::Value;
|
||||
|
||||
use crate::utils::eval_result;
|
||||
|
||||
@@ -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#"
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
use fix::Evaluator;
|
||||
use fix_common::Value;
|
||||
use fix_error::{Result, Source};
|
||||
use fix_lang::Value;
|
||||
|
||||
pub fn eval(expr: &str) -> Value {
|
||||
Evaluator::new()
|
||||
|
||||
Generated
+151
-9
@@ -1,5 +1,64 @@
|
||||
{
|
||||
"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": 1777369708,
|
||||
"narHash": "sha256-1xW7cRZNsFNPQD+cE0fwnLVStnDth0HSoASEIFeT7uI=",
|
||||
"owner": "nix-community",
|
||||
"repo": "bun2nix",
|
||||
"rev": "e659e1cc4b8e1b21d0aa85f1c481f9db61ecfa98",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-community",
|
||||
"ref": "staging-2.1.0",
|
||||
"repo": "bun2nix",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"fenix": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
@@ -8,11 +67,11 @@
|
||||
"rust-analyzer-src": "rust-analyzer-src"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1784017020,
|
||||
"narHash": "sha256-49WO85egjNtN1vMgJ3zUjDh5IqO+ou4zZY80WQ6EKGg=",
|
||||
"lastModified": 1777796307,
|
||||
"narHash": "sha256-L7xLjorTwVf2aLu5b0ZZY2D0RFXwD/a/a/fFFDikB2w=",
|
||||
"owner": "nix-community",
|
||||
"repo": "fenix",
|
||||
"rev": "fa2a0be0f712d7147d1677d33d15ea7b0589cdb4",
|
||||
"rev": "0f9881f2344c0b1c100bd9e774555759b7da6fd5",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -35,13 +94,59 @@
|
||||
"url": "https://git.lix.systems/lix-project/flake-compat/archive/main.tar.gz"
|
||||
}
|
||||
},
|
||||
"flake-parts": {
|
||||
"inputs": {
|
||||
"nixpkgs-lib": [
|
||||
"llm-agents",
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1777678872,
|
||||
"narHash": "sha256-EPIFsulyon7Z1vLQq5Fk64GR8L7cQsT+IPhcsukVbgk=",
|
||||
"owner": "hercules-ci",
|
||||
"repo": "flake-parts",
|
||||
"rev": "5250617bffd85403b14dbf43c3870e7f255d2c16",
|
||||
"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": 1777786380,
|
||||
"narHash": "sha256-GGKC1WrEoTafJwIXn+fim6cZ/w1ZWVc+DUYdk2lvPvA=",
|
||||
"owner": "numtide",
|
||||
"repo": "llm-agents.nix",
|
||||
"rev": "961b1096bc0b2ecc7096e360646cd2f29671c55e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "numtide",
|
||||
"repo": "llm-agents.nix",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1784007870,
|
||||
"narHash": "sha256-djcLt/JJphyNt4eDY9XTly+/WbCK5lqWq9lSgCmJkkQ=",
|
||||
"lastModified": 1777578337,
|
||||
"narHash": "sha256-Ad49moKWeXtKBJNy2ebiTQUEgdLyvGmTeykAQ9xM+Z4=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "18b9261cb3294b6d2a06d03f96872827b8fe2698",
|
||||
"rev": "15f4ee454b1dce334612fa6843b3e05cf546efab",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -55,17 +160,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": 1777768857,
|
||||
"narHash": "sha256-zfekJcaVctfAps1KDHwZpwkvAQn7GObRHh3Gl3xocGI=",
|
||||
"owner": "rust-lang",
|
||||
"repo": "rust-analyzer",
|
||||
"rev": "63a6f0d4bcfd3bbcf36383fcbcbcd93456ed1653",
|
||||
"rev": "1102c0b633599564919e36076d4362d7e68dbddc",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -74,6 +180,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": 1775636079,
|
||||
"narHash": "sha256-pc20NRoMdiar8oPQceQT47UUZMBTiMdUuWrYu2obUP0=",
|
||||
"owner": "numtide",
|
||||
"repo": "treefmt-nix",
|
||||
"rev": "790751ff7fd3801feeaf96d7dc416a8d581265ba",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "numtide",
|
||||
"repo": "treefmt-nix",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
|
||||
@@ -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,36 @@
|
||||
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
|
||||
|
||||
llm-agents.codex
|
||||
llm-agents.claude-code
|
||||
llm-agents.opencode
|
||||
llm-agents.forge
|
||||
];
|
||||
};
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
[files]
|
||||
extend-exclude = [
|
||||
"nix-js/tests/tests/regex.rs",
|
||||
"nix-js/tests/tests/lang",
|
||||
"nix-js/tests/tests/regex.rs",
|
||||
"nix-js/tests/tests/lang",
|
||||
]
|
||||
|
||||
[default.extend-words]
|
||||
|
||||
Reference in New Issue
Block a user