pub(super) const HEADER: &str = r#"// Auto-generated by nybl-compile — do not edit.
// Regenerate from Nybl source rather than editing this file.
#![allow(unused_mut, unused_variables, unused_parens, unused_braces, unreachable_code, dead_code)]
"#;
pub(super) const RUNTIME_HEADER: &str =
"// ─── Runtime context and helpers ────────────────────────────────\n\n";
pub(super) const CTX_BASE: &str = r#"pub struct Ctx<'h> {
pub host: &'h mut dyn ::nybl::NyblHost,
pub memory: ::nybl::memory::MemoryContext,
pub rand_state: u64,
/// Per-program module cache keyed by the Nybl module path (the
/// dot-joined string). `load` fns use this to memoise imports
/// and to spot circular dependencies via the `__ModuleLoading`
/// sentinel.
pub module_cache:
::std::collections::HashMap<::std::string::String, ::std::boxed::Box<dyn ::core::any::Any + 'static>>,
pub module_aliases: ::std::collections::HashMap<
(::std::string::String, ::std::string::String),
::nybl::value::Value,
>,
pub bindings: ::std::collections::HashMap<
::std::string::String,
::std::collections::HashMap<::std::string::String, ::nybl::value::Value>,
>,
pub binding_origins: ::std::collections::HashMap<
::std::string::String,
::std::collections::HashMap<
::std::string::String,
(::std::string::String, ::std::string::String),
>,
>,
pub binding_claims: ::std::collections::HashMap<
::std::string::String,
::std::collections::HashSet<::std::string::String>,
>,
pub active_function_sites: ::std::collections::HashMap<
(::std::string::String, ::std::string::String),
usize,
>,
pub reached_function_sites: ::std::vec::Vec<bool>,
pub module_imported_function_sites: ::std::collections::HashMap<
(::std::string::String, ::std::string::String),
usize,
>,
pub abi_declarations: ::std::vec::Vec<usize>,
pub module_type_bindings: ::std::collections::HashMap<
::std::string::String,
::std::rc::Rc<
::std::collections::BTreeMap<::std::string::String, ::std::string::String>,
>,
>,
pub struct_defs: ::std::collections::HashMap<
::std::string::String,
::std::collections::HashMap<::std::string::String, &'static [&'static str]>,
>,
pub enum_defs: ::std::collections::HashMap<
::std::string::String,
::std::collections::HashMap<
::std::string::String,
&'static [(&'static str, __NyblDynamicVariantShape)],
>,
>,
/*__NYBL_METHOD_SLOTS__*/
}
"#;
pub(super) const CTX_SANDBOX: &str = r#"/// Opaque generated program state. This type and its fields are implementation
/// details; sandbox embedders should use `run` and the generated `NyblInstance`.
struct __NyblState {
function_origin: ::nybl::value::NyblFnOrigin,
rand_state: u64,
/// Per-program module cache keyed by the Nybl module path (the
/// dot-joined string). `load` fns use this to memoise imports
/// and to spot circular dependencies via the `__ModuleLoading`
/// sentinel.
module_cache:
::std::collections::HashMap<::std::string::String, ::std::boxed::Box<dyn ::core::any::Any + 'static>>,
module_aliases: ::std::collections::HashMap<
(::std::string::String, ::std::string::String),
::nybl::value::Value,
>,
module_type_bindings: ::std::collections::HashMap<
::std::string::String,
::std::rc::Rc<
::std::collections::BTreeMap<::std::string::String, ::std::string::String>,
>,
>,
struct_defs: ::std::collections::HashMap<
::std::string::String,
::std::collections::HashMap<::std::string::String, &'static [&'static str]>,
>,
enum_defs: ::std::collections::HashMap<
::std::string::String,
::std::collections::HashMap<
::std::string::String,
&'static [(&'static str, __NyblDynamicVariantShape)],
>,
>,
active_function_sites: ::std::collections::HashMap<
(::std::string::String, ::std::string::String),
usize,
>,
module_imported_function_sites: ::std::collections::HashMap<
(::std::string::String, ::std::string::String),
usize,
>,
bindings: ::std::collections::HashMap<
::std::string::String,
::std::collections::HashMap<::std::string::String, ::nybl::value::Value>,
>,
binding_origins: ::std::collections::HashMap<
::std::string::String,
::std::collections::HashMap<
::std::string::String,
(::std::string::String, ::std::string::String),
>,
>,
binding_claims: ::std::collections::HashMap<
::std::string::String,
::std::collections::HashSet<::std::string::String>,
>,
abi_declarations: ::std::vec::Vec<usize>,
/*__NYBL_METHOD_SLOTS__*/
}
/// Per-operation adapter borrowing a host and opaque program state. Its layout
/// is not a supported embedding API.
struct Ctx<'h> {
host: &'h mut dyn ::nybl::NyblHost,
state: &'h mut __NyblState,
memory: ::nybl::memory::MemoryContext,
/// Tick counter — bumped by `__nybl_tick` at every loop
/// backedge and fn entry so runaway programs hit the step
/// budget before they exhaust the host.
steps: u64,
/// User-call depth is reset for every public operation.
call_depth: usize,
/// Upper bound on `steps`, populated from
/// `NyblLimits::max_steps` at operation entry.
max_steps: u64,
}
impl<'h> ::core::ops::Deref for Ctx<'h> {
type Target = __NyblState;
fn deref(&self) -> &Self::Target {
self.state
}
}
impl<'h> ::core::ops::DerefMut for Ctx<'h> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.state
}
}
"#;
pub(super) const TICK_HELPER: &str = r#"/// Step / memory / on_tick checkpoint. Emitted by `nybl-compile` at
/// the head of every loop iteration and at function entry when the
/// `sandbox` option is on. Mirrors `Evaluator::tick` in `nybl-lang`.
#[inline]
fn __nybl_tick(ctx: &mut Ctx<'_>, line: u32) -> Result<(), ::nybl::error::NyblError> {
ctx.steps += 1;
if ctx.steps > ctx.max_steps {
return Err(::nybl::builtins::error_fatal_with_hint(
line,
"Your code took too many steps (possible infinite loop)",
"Check your loops — make sure they have a condition that eventually stops them.",
));
}
if ctx.memory.__exceeded() {
return Err(::nybl::builtins::error_fatal_with_hint(
line,
"Memory limit exceeded",
"Your code is using too much memory. Check for large strings or arrays growing in loops.",
));
}
ctx.host.on_tick()?;
Ok(())
}
fn __nybl_validate_aot_function(
ctx: &Ctx<'_>,
function: &::std::rc::Rc<::nybl::value::NyblFn>,
line: u32,
) -> Result<(), ::nybl::error::NyblError> {
if function.__is_allowed_by(&ctx.function_origin, "aot") {
Ok(())
} else {
Err(::nybl::error::NyblError::runtime(
"This function belongs to a different Nybl engine instance",
line,
))
}
}
fn __nybl_enter_aot_call(
ctx: &mut Ctx<'_>,
line: u32,
) -> Result<(), ::nybl::error::NyblError> {
const MAX_CALL_DEPTH: usize = 64;
if ctx.call_depth >= MAX_CALL_DEPTH {
let mut error = ::nybl::error::NyblError::runtime(
"Too many nested function calls (possible infinite recursion)",
line,
);
error.friendly_hint = ::std::option::Option::Some(
"Check that your recursive function has a base case that stops calling itself."
.to_string(),
);
return Err(error);
}
ctx.call_depth += 1;
Ok(())
}
fn __nybl_leave_aot_call(ctx: &mut Ctx<'_>) {
ctx.call_depth = ctx.call_depth.saturating_sub(1);
}
fn __nybl_host_call(
ctx: &mut Ctx<'_>,
name: &str,
args: &[::nybl::value::Value],
line: u32,
) -> ::std::option::Option<Result<::nybl::value::Value, ::nybl::error::NyblError>> {
ctx.host.call(name, args, line)
}
fn __nybl_host_function_hint(ctx: &mut Ctx<'_>) -> String {
ctx.host.function_hint().to_string()
}
"#;
pub(super) const RUNTIME_SHARED: &str = r#"fn __nybl_host_print(
ctx: &mut Ctx<'_>,
message: &str,
line: u32,
) -> Result<(), ::nybl::error::NyblError> {
ctx.host.on_print(message);
if let Some(error) = ctx.host.print_error(line) {
return Err(error);
}
Ok(())
}
#[derive(Clone, Copy)]
struct __NyblFunctionSite {
id: usize,
module_path: &'static str,
name: &'static str,
params: &'static [&'static str],
param_modes: &'static [::nybl::parser::ParamMode],
is_public: bool,
abi_eligible: bool,
line: u32,
}
#[derive(Clone)]
enum __NyblExport {
Value(::nybl::value::Value),
Function(usize),
}
/*__NYBL_MEMORY_HELPER__*/
/// Sentinel type inserted into `module_cache` while a module's
/// body is evaluating. If a load fn hits its own entry in this
/// state it means a circular import — the runtime returns a clear
/// error and halts.
pub struct __ModuleLoading;
/// Borrowed, allocation-free binding resolution: chase
/// `binding_origins` from `(module_path, name)` to the deepest live
/// binding, borrowing each hop's key straight from the origin table.
/// The `remaining` guard bounds the walk the same way the key-based
/// resolver always has, so origin cycles can't spin.
fn __nybl_binding_entry<'a>(
ctx: &'a Ctx<'_>,
module_path: &str,
name: &str,
) -> ::std::option::Option<&'a ::nybl::value::Value> {
let mut module_path: &str = module_path;
let mut name: &str = name;
let mut remaining = ctx
.binding_origins
.values()
.map(::std::collections::HashMap::len)
.sum::<usize>()
+ 1;
loop {
if let ::std::option::Option::Some(value) = ctx
.bindings
.get(module_path)
.and_then(|bindings| bindings.get(name))
{
return ::std::option::Option::Some(value);
}
if remaining == 0 {
return ::std::option::Option::None;
}
let (next_module, next_name) = ctx.binding_origins.get(module_path)?.get(name)?;
module_path = next_module;
name = next_name;
remaining -= 1;
}
}
/// Owned-key twin of `__nybl_binding_entry` for the mutation paths,
/// which need the resolved key after releasing the shared borrow.
fn __nybl_resolve_binding_key(
ctx: &Ctx<'_>,
module_path: &str,
name: &str,
) -> ::std::option::Option<(::std::string::String, ::std::string::String)> {
let mut module_path: &str = module_path;
let mut name: &str = name;
let mut remaining = ctx
.binding_origins
.values()
.map(::std::collections::HashMap::len)
.sum::<usize>()
+ 1;
loop {
if ctx
.bindings
.get(module_path)
.is_some_and(|bindings| bindings.contains_key(name))
{
return ::std::option::Option::Some((module_path.to_string(), name.to_string()));
}
if remaining == 0 {
return ::std::option::Option::None;
}
let (next_module, next_name) = ctx.binding_origins.get(module_path)?.get(name)?;
module_path = next_module;
name = next_name;
remaining -= 1;
}
}
fn __nybl_binding_value(
ctx: &Ctx<'_>,
module_path: &str,
name: &str,
) -> ::std::option::Option<::nybl::value::Value> {
__nybl_binding_entry(ctx, module_path, name).cloned()
}
fn __nybl_has_binding(ctx: &Ctx<'_>, module_path: &str, name: &str) -> bool {
ctx.bindings
.get(module_path)
.is_some_and(|bindings| bindings.contains_key(name))
|| ctx
.binding_origins
.get(module_path)
.is_some_and(|origins| origins.contains_key(name))
|| ctx
.binding_claims
.get(module_path)
.is_some_and(|claims| claims.contains(name))
}
fn __nybl_warn_glob_shadow(name: &str, path: &str) {
::std::eprintln!(
"warning: {}",
::nybl::error_messages::glob_shadow_warning(name, path),
);
}
fn __nybl_define_binding(
ctx: &mut Ctx<'_>,
module_path: &str,
name: &str,
value: ::nybl::value::Value,
) {
if let ::std::option::Option::Some(origins) = ctx.binding_origins.get_mut(module_path) {
origins.remove(name);
}
ctx.binding_claims
.entry(module_path.to_string())
.or_default()
.insert(name.to_string());
ctx.bindings
.entry(module_path.to_string())
.or_default()
.insert(name.to_string(), value);
}
fn __nybl_claim_binding(ctx: &mut Ctx<'_>, module_path: &str, name: &str) {
if !__nybl_has_binding(ctx, module_path, name) {
ctx.binding_claims
.entry(module_path.to_string())
.or_default()
.insert(name.to_string());
}
}
fn __nybl_import_binding_alias(
ctx: &mut Ctx<'_>,
module_path: &str,
name: &str,
origin_module_path: &str,
origin_name: &str,
) {
if __nybl_has_binding(ctx, module_path, name) {
return;
}
ctx.binding_origins
.entry(module_path.to_string())
.or_default()
.insert(
name.to_string(),
(origin_module_path.to_string(), origin_name.to_string()),
);
ctx.binding_claims
.entry(module_path.to_string())
.or_default()
.insert(name.to_string());
}
fn __nybl_import_binding_value(
ctx: &mut Ctx<'_>,
module_path: &str,
name: &str,
value: ::nybl::value::Value,
) {
if __nybl_has_binding(ctx, module_path, name) {
return;
}
ctx.binding_claims
.entry(module_path.to_string())
.or_default()
.insert(name.to_string());
ctx.bindings
.entry(module_path.to_string())
.or_default()
.insert(name.to_string(), value);
}
/// Current value of a module-alias member. The live binding wins when
/// the name (or its re-export origin — `__nybl_binding_value` chases
/// `binding_origins`, so facades resolve to the deepest origin) is
/// still tracked as a rebindable binding; fn exports and anything the
/// module never defined as a binding fall back to the import-time
/// snapshot. Mirrors the walker's `module_binding`.
fn __nybl_module_member(
ctx: &Ctx<'_>,
module: &::nybl::value::NyblModule,
name: &str,
) -> ::std::option::Option<::nybl::value::Value> {
__nybl_binding_value(ctx, &module.path, name).or_else(|| module.__binding(name))
}
fn __nybl_read_binding(
ctx: &Ctx<'_>,
module_path: &str,
name: &str,
line: u32,
) -> Result<::nybl::value::Value, ::nybl::error::NyblError> {
__nybl_binding_value(ctx, module_path, name)
.ok_or_else(|| ::nybl::error::NyblError::runtime(
::nybl::error_messages::variable_not_found(name),
line,
))
}
fn __nybl_binding_mut<'a>(
ctx: &'a mut Ctx<'_>,
module_path: &str,
name: &str,
line: u32,
) -> Result<&'a mut ::nybl::value::Value, ::nybl::error::NyblError> {
let key = __nybl_resolve_binding_key(ctx, module_path, name);
key.and_then(|(module, name)| {
ctx.bindings
.get_mut(&module)
.and_then(|bindings| bindings.get_mut(&name))
})
.ok_or_else(|| ::nybl::error::NyblError::runtime(
::nybl::error_messages::variable_not_found(name),
line,
))
}
fn __nybl_binding_mut_option<'a>(
ctx: &'a mut Ctx<'_>,
module_path: &str,
name: &str,
) -> ::std::option::Option<&'a mut ::nybl::value::Value> {
let (module, name) = __nybl_resolve_binding_key(ctx, module_path, name)?;
ctx.bindings
.get_mut(&module)
.and_then(|bindings| bindings.get_mut(&name))
}
/// Accessors for a ref target whose authoritative binding key was resolved
/// during preflight. Nybl has no binding-deletion operation, so disappearance
/// after preflight is an internal invariant violation rather than a
/// user-visible/fallible commit step.
fn __nybl_binding_key_value<'a>(
ctx: &'a Ctx<'_>,
key: &(::std::string::String, ::std::string::String),
) -> &'a ::nybl::value::Value {
ctx.bindings
.get(&key.0)
.and_then(|bindings| bindings.get(&key.1))
.expect("pre-resolved ref binding remains live")
}
fn __nybl_binding_key_mut<'a>(
ctx: &'a mut Ctx<'_>,
key: &(::std::string::String, ::std::string::String),
) -> &'a mut ::nybl::value::Value {
ctx.bindings
.get_mut(&key.0)
.and_then(|bindings| bindings.get_mut(&key.1))
.expect("pre-resolved ref binding remains live")
}
fn __nybl_binding_is_array(
ctx: &Ctx<'_>,
module_path: &str,
name: &str,
line: u32,
) -> Result<bool, ::nybl::error::NyblError> {
Ok(matches!(
__nybl_binding_entry(ctx, module_path, name)
.ok_or_else(|| ::nybl::error::NyblError::runtime(
::nybl::error_messages::variable_not_found(name),
line,
))?,
::nybl::value::Value::Array(_)
))
}
type __NyblTypeFrame =
::std::collections::BTreeMap<::std::string::String, ::std::string::String>;
type __NyblTypeBindings = ::std::vec::Vec<::std::rc::Rc<__NyblTypeFrame>>;
fn __nybl_builtin_type_frame() -> __NyblTypeFrame {
let mut bindings = __NyblTypeFrame::new();
bindings.insert("Result".to_string(), "<builtin>".to_string());
bindings.insert("RuntimeError".to_string(), "<builtin>".to_string());
bindings.insert("Iter".to_string(), "<builtin>".to_string());
bindings
}
fn __nybl_fresh_module_type_bindings() -> __NyblTypeBindings {
::std::vec![::std::rc::Rc::new(__nybl_builtin_type_frame())]
}
fn __nybl_callable_type_bindings(ctx: &Ctx<'_>, module: &str) -> __NyblTypeBindings {
let committed = ctx
.module_type_bindings
.get(module)
.cloned()
.unwrap_or_else(|| ::std::rc::Rc::new(__nybl_builtin_type_frame()));
::std::vec![committed, ::std::rc::Rc::new(__NyblTypeFrame::new())]
}
fn __nybl_reset_type_bindings(ctx: &mut Ctx<'_>, module: &str) {
ctx.module_type_bindings
.insert(module.to_string(), ::std::rc::Rc::new(__nybl_builtin_type_frame()));
}
fn __nybl_publish_type_binding(
ctx: &mut Ctx<'_>,
module: &str,
name: &str,
origin: &str,
) {
let bindings = ctx.module_type_bindings
.entry(module.to_string())
.or_insert_with(|| ::std::rc::Rc::new(__nybl_builtin_type_frame()));
::std::rc::Rc::make_mut(bindings)
.insert(name.to_string(), origin.to_string());
}
fn __nybl_publish_imported_type_binding(
ctx: &mut Ctx<'_>,
module: &str,
name: &str,
origin: &str,
) {
let bindings = ctx.module_type_bindings
.entry(module.to_string())
.or_insert_with(|| ::std::rc::Rc::new(__nybl_builtin_type_frame()));
::std::rc::Rc::make_mut(bindings)
.entry(name.to_string())
.or_insert_with(|| origin.to_string());
}
fn __nybl_bind_type(bindings: &mut __NyblTypeBindings, name: &str, origin: &str) {
let frame = bindings
.last_mut()
.expect("type bindings always have a frame");
::std::rc::Rc::make_mut(frame)
.insert(name.to_string(), origin.to_string());
}
fn __nybl_bind_imported_type(
bindings: &mut __NyblTypeBindings,
name: &str,
origin: &str,
) {
let frame = bindings
.last_mut()
.expect("type bindings always have a frame");
::std::rc::Rc::make_mut(frame)
.entry(name.to_string())
.or_insert_with(|| origin.to_string());
}
fn __nybl_resolve_bare_type(
bindings: &__NyblTypeBindings,
type_name: &str,
is_struct: bool,
line: u32,
) -> Result<::std::string::String, ::nybl::error::NyblError> {
for frame in bindings.iter().rev() {
if let ::std::option::Option::Some(origin) = frame.get(type_name) {
return Ok(origin.clone());
}
}
let message = if is_struct {
::nybl::error_messages::struct_not_declared(type_name)
} else {
::nybl::error_messages::enum_not_declared(type_name)
};
Err(::nybl::error::NyblError::runtime(message, line))
}
struct __NyblDeclarationAliasBinding {
overlay: ::std::option::Option<::nybl::value::Value>,
cached: ::std::option::Option<::nybl::value::Value>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum __NyblDynamicVariantShape {
Unit,
Tuple(&'static [&'static str]),
Struct(&'static [&'static str]),
}
fn __nybl_register_struct(
ctx: &mut Ctx<'_>,
module: &str,
type_name: &str,
fields: &'static [&'static str],
line: u32,
) -> Result<(), ::nybl::error::NyblError> {
for (index, field) in fields.iter().enumerate() {
if fields[..index].contains(field) {
return Err(::nybl::error::NyblError::runtime(
format!("Struct `{}` has duplicate field `{}`", type_name, field),
line,
));
}
}
if let ::std::option::Option::Some(existing) = ctx
.struct_defs
.get(module)
.and_then(|defs| defs.get(type_name))
.copied()
{
if existing == fields {
return Ok(());
}
return Err(::nybl::error::NyblError::runtime(
format!("Struct `{}` is already declared", type_name),
line,
));
}
ctx.struct_defs
.entry(module.to_string())
.or_default()
.insert(type_name.to_string(), fields);
Ok(())
}
fn __nybl_enum_shapes_match(
left: &[(&str, __NyblDynamicVariantShape)],
right: &[(&str, __NyblDynamicVariantShape)],
) -> bool {
left.len() == right.len()
&& left.iter().zip(right).all(|((left_name, left_shape), (right_name, right_shape))| {
if left_name != right_name {
return false;
}
match (left_shape, right_shape) {
(__NyblDynamicVariantShape::Unit, __NyblDynamicVariantShape::Unit) => true,
(__NyblDynamicVariantShape::Tuple(left_fields), __NyblDynamicVariantShape::Tuple(right_fields)) => {
left_fields.len() == right_fields.len()
}
(__NyblDynamicVariantShape::Struct(left_fields), __NyblDynamicVariantShape::Struct(right_fields)) => {
left_fields == right_fields
}
_ => false,
}
})
}
fn __nybl_register_enum(
ctx: &mut Ctx<'_>,
module: &str,
type_name: &str,
variants: &'static [(&'static str, __NyblDynamicVariantShape)],
line: u32,
) -> Result<(), ::nybl::error::NyblError> {
if let ::std::option::Option::Some(existing) = ctx
.enum_defs
.get(module)
.and_then(|defs| defs.get(type_name))
.copied()
{
if __nybl_enum_shapes_match(existing, variants) {
return Ok(());
}
return Err(::nybl::error::NyblError::runtime(
format!("Enum `{}` is already declared", type_name),
line,
));
}
for (variant_index, (variant, shape)) in variants.iter().enumerate() {
if variants[..variant_index]
.iter()
.any(|(seen, _)| seen == variant)
{
return Err(::nybl::error::NyblError::runtime(
format!("Enum `{}` has duplicate variant `{}`", type_name, variant),
line,
));
}
let fields = match shape {
__NyblDynamicVariantShape::Unit => continue,
__NyblDynamicVariantShape::Tuple(fields)
| __NyblDynamicVariantShape::Struct(fields) => *fields,
};
for (field_index, field) in fields.iter().enumerate() {
if fields[..field_index].contains(field) {
return Err(::nybl::error::NyblError::runtime(
format!(
"Enum variant `{}::{}` has duplicate field `{}`",
type_name, variant, field
),
line,
));
}
}
}
ctx.enum_defs
.entry(module.to_string())
.or_default()
.insert(type_name.to_string(), variants);
Ok(())
}
fn __nybl_struct_fields(
ctx: &Ctx<'_>,
module: &str,
type_name: &str,
line: u32,
) -> Result<&'static [&'static str], ::nybl::error::NyblError> {
ctx.struct_defs
.get(module)
.and_then(|defs| defs.get(type_name))
.copied()
.ok_or_else(|| ::nybl::error::NyblError::runtime(
::nybl::error_messages::struct_not_declared(type_name),
line,
))
}
fn __nybl_enum_variant_shape(
ctx: &Ctx<'_>,
module: &str,
type_name: &str,
variant: &str,
line: u32,
) -> Result<__NyblDynamicVariantShape, ::nybl::error::NyblError> {
let variants = ctx
.enum_defs
.get(module)
.and_then(|defs| defs.get(type_name))
.copied()
.ok_or_else(|| ::nybl::error::NyblError::runtime(
::nybl::error_messages::enum_not_declared(type_name),
line,
))?;
variants
.iter()
.find_map(|(name, shape)| (*name == variant).then_some(*shape))
.ok_or_else(|| {
let mut error = ::nybl::error::NyblError::runtime(
::nybl::error_messages::enum_has_no_variant(type_name, variant),
line,
);
if let ::std::option::Option::Some(hint) = ::nybl::suggest::did_you_mean(
variant,
variants.iter().map(|(name, _)| *name),
) {
error.friendly_hint = ::std::option::Option::Some(hint);
}
error
})
}
fn __nybl_seed_builtin_type_defs(ctx: &mut Ctx<'_>) -> Result<(), ::nybl::error::NyblError> {
const RUNTIME_ERROR: &'static [&'static str] = &["message", "line"];
const RESULT: &'static [(&'static str, __NyblDynamicVariantShape)] = &[
("Ok", __NyblDynamicVariantShape::Tuple(&["value"])),
("Err", __NyblDynamicVariantShape::Tuple(&["error"])),
];
const ITER: &'static [(&'static str, __NyblDynamicVariantShape)] = &[
("Next", __NyblDynamicVariantShape::Tuple(&["value"])),
("Done", __NyblDynamicVariantShape::Unit),
];
__nybl_register_struct(ctx, "<builtin>", "RuntimeError", RUNTIME_ERROR, 0)?;
__nybl_register_enum(ctx, "<builtin>", "Result", RESULT, 0)?;
__nybl_register_enum(ctx, "<builtin>", "Iter", ITER, 0)?;
Ok(())
}
fn __nybl_clear_module_type_defs(ctx: &mut Ctx<'_>, module: &str) {
ctx.struct_defs.remove(module);
ctx.enum_defs.remove(module);
}
struct __NyblModuleTypeDefs {
structs: ::std::option::Option<
::std::collections::HashMap<::std::string::String, &'static [&'static str]>,
>,
enums: ::std::option::Option<
::std::collections::HashMap<
::std::string::String,
&'static [(&'static str, __NyblDynamicVariantShape)],
>,
>,
}
fn __nybl_take_module_type_defs(ctx: &mut Ctx<'_>, module: &str) -> __NyblModuleTypeDefs {
__NyblModuleTypeDefs {
structs: ctx.struct_defs.remove(module),
enums: ctx.enum_defs.remove(module),
}
}
fn __nybl_restore_module_type_defs(
ctx: &mut Ctx<'_>,
module: &str,
saved: __NyblModuleTypeDefs,
) {
if let ::std::option::Option::Some(defs) = saved.structs {
ctx.struct_defs.insert(module.to_string(), defs);
}
if let ::std::option::Option::Some(defs) = saved.enums {
ctx.enum_defs.insert(module.to_string(), defs);
}
}
fn __nybl_declaration_alias_optional(
ctx: &Ctx<'_>,
binding: &mut __NyblDeclarationAliasBinding,
module: &str,
alias: &str,
) -> ::std::option::Option<::nybl::value::Value> {
if let ::std::option::Option::Some(value) = &binding.overlay {
return ::std::option::Option::Some(value.clone());
}
if let ::std::option::Option::Some(value) = &binding.cached {
return ::std::option::Option::Some(value.clone());
}
let value = ctx
.module_aliases
.get(&(module.to_string(), alias.to_string()))
.cloned()?;
binding.cached = ::std::option::Option::Some(value.clone());
::std::option::Option::Some(value)
}
fn __nybl_declaration_alias_read(
ctx: &Ctx<'_>,
binding: &mut __NyblDeclarationAliasBinding,
module: &str,
alias: &str,
line: u32,
) -> Result<::nybl::value::Value, ::nybl::error::NyblError> {
__nybl_declaration_alias_optional(ctx, binding, module, alias).ok_or_else(|| {
::nybl::error::NyblError::runtime(
::nybl::error_messages::variable_not_found(alias),
line,
)
})
}
fn __nybl_declaration_alias_namespace(
ctx: &Ctx<'_>,
binding: &mut __NyblDeclarationAliasBinding,
module: &str,
alias: &str,
line: u32,
) -> Result<::nybl::value::Value, ::nybl::error::NyblError> {
__nybl_declaration_alias_optional(ctx, binding, module, alias).ok_or_else(|| {
::nybl::error::NyblError::runtime(
format!("`{}` isn't a module alias in scope", alias),
line,
)
})
}
fn __nybl_declaration_alias_assign(
ctx: &Ctx<'_>,
binding: &mut __NyblDeclarationAliasBinding,
value: ::nybl::value::Value,
module: &str,
alias: &str,
line: u32,
) -> Result<(), ::nybl::error::NyblError> {
if binding.overlay.is_none()
&& binding.cached.is_none()
&& !ctx
.module_aliases
.contains_key(&(module.to_string(), alias.to_string()))
{
return Err(::nybl::error::NyblError::runtime(
format!("Variable `{}` doesn't exist yet", alias),
line,
));
}
binding.overlay = ::std::option::Option::Some(value);
Ok(())
}
fn __nybl_declaration_alias_mut<'v>(
binding: &'v mut __NyblDeclarationAliasBinding,
alias: &str,
line: u32,
) -> Result<&'v mut ::nybl::value::Value, ::nybl::error::NyblError> {
binding.overlay.as_mut().ok_or_else(|| {
::nybl::error::NyblError::runtime(
::nybl::error_messages::variable_not_found(alias),
line,
)
})
}
/// Opaque body that a `Value::Fn` carries around in AOT-emitted
/// code. The callable is a higher-ranked `Fn` so the same Rc can
/// satisfy any lifetime of `Ctx`, which lets us store closures in
/// `Value::Fn` (whose body is `Rc<dyn Any + 'static>`) regardless
/// of where they're eventually called from.
/*__NYBL_RUNTIME_VIS__*/struct __NyblCallOutcome {
/*__NYBL_RUNTIME_VIS__*/value: ::nybl::value::Value,
/*__NYBL_RUNTIME_VIS__*/args: ::std::vec::Vec<::nybl::value::Value>,
}
/*__NYBL_RUNTIME_VIS__*/struct __NyblMethodOutcome {
/*__NYBL_RUNTIME_VIS__*/value: ::nybl::value::Value,
/*__NYBL_RUNTIME_VIS__*/receiver: ::nybl::value::Value,
/*__NYBL_RUNTIME_VIS__*/args: ::std::vec::Vec<::nybl::value::Value>,
}
fn __nybl_arity_error(callable: &str, modes: &[::nybl::parser::ParamMode], actual: usize, line: u32) -> ::nybl::error::NyblError {
let required = ::nybl::ref_params::required_arity(modes);
let expectation = if matches!(modes.last(), Some(::nybl::parser::ParamMode::Rest)) {
format!("at least {} argument{}", required, if required == 1 { "" } else { "s" })
} else {
format!("{} argument{}", required, if required == 1 { "" } else { "s" })
};
::nybl::error::NyblError::runtime(format!("`{}` expects {}, but got {}", callable, expectation, actual), line)
}
fn __nybl_pack_rest_args(
mut args: ::std::vec::Vec<::nybl::value::Value>,
modes: &[::nybl::parser::ParamMode],
line: u32,
memory: &::nybl::memory::MemoryContext,
) -> Result<::std::vec::Vec<::nybl::value::Value>, ::nybl::error::NyblError> {
if !::nybl::ref_params::accepts_arity(modes, args.len()) {
return Err(__nybl_arity_error("fn", modes, args.len(), line));
}
if matches!(modes.last(), Some(::nybl::parser::ParamMode::Rest)) {
let fixed = ::nybl::ref_params::required_arity(modes);
let extras = args.split_off(fixed);
args.push(::nybl::value::Value::__try_new_array_in(extras, line, memory)?);
}
Ok(args)
}
/*__NYBL_RUNTIME_VIS__*/struct AotClosure {
/*__NYBL_RUNTIME_VIS__*/callable: ::std::rc::Rc<
dyn for<'__a> Fn(
&mut Ctx<'__a>,
::std::vec::Vec<::nybl::value::Value>,
) -> Result<__NyblCallOutcome, ::nybl::error::NyblError>,
>,
}
/*__NYBL_INVOKE_HELPER__*/
fn __nybl_preflight_value_call(
ctx: &Ctx<'_>,
callee: &::nybl::value::Value,
actual_modes: &[::nybl::parser::ParamMode],
line: u32,
) -> Result<(), ::nybl::error::NyblError> {
let function = match callee {
::nybl::value::Value::Fn(function) => function,
other => {
return Err(::nybl::error::NyblError::runtime(
::nybl::error_messages::cant_call_a(other.type_name()),
line,
));
}
};
/*__NYBL_PREFLIGHT_AOT_ORIGIN__*/
let callable = function
.self_name
.as_deref()
.unwrap_or("fn");
if !::nybl::ref_params::accepts_arity(&function.param_modes, actual_modes.len()) {
return Err(__nybl_arity_error(callable, &function.param_modes, actual_modes.len(), line));
}
::nybl::validate_call_modes(
callable,
&function.param_modes,
actual_modes,
line,
)
}
/// Resolve and preflight a module export used with method-call syntax
/// (`module.export(...)`). The returned callable is the exact value that must
/// later be invoked, so neither the receiver nor a live export is resolved a
/// second time after argument side effects.
fn __nybl_preflight_module_call(
ctx: &Ctx<'_>,
receiver: &::nybl::value::Value,
method: &str,
actual_modes: &[::nybl::parser::ParamMode],
line: u32,
) -> Result<::std::option::Option<::nybl::value::Value>, ::nybl::error::NyblError> {
let ::nybl::value::Value::Module(module) = receiver else {
return Ok(None);
};
// Universal value methods have precedence over module exports.
if matches!(method, "type" | "to_str" | "inspect") {
return Ok(None);
}
let callable = __nybl_module_member(ctx, module, method).ok_or_else(|| {
::nybl::error::NyblError::runtime(
format!("`{}` isn't exported from `{}`", method, module.path),
line,
)
})?;
__nybl_preflight_value_call(ctx, &callable, actual_modes, line)?;
Ok(Some(callable))
}
/// Build a `Value::Fn` around an `AotClosure`. Used by the emitted
/// `__nybl_user_fn_value_*` wrappers and by `MakeLambda` emission.
fn __nybl_wrap_callable(
/*__NYBL_WRAP_CTX_PARAM__*/
params: ::std::vec::Vec<String>,
param_modes: ::std::vec::Vec<::nybl::parser::ParamMode>,
captures: ::std::vec::Vec<(String, ::nybl::value::Value)>,
self_name: ::std::option::Option<String>,
opaque_body_depth: u16,
line: u32,
callable: ::std::rc::Rc<
dyn for<'__a> Fn(
&mut Ctx<'__a>,
::std::vec::Vec<::nybl::value::Value>,
) -> Result<__NyblCallOutcome, ::nybl::error::NyblError>,
>,
) -> Result<::nybl::value::Value, ::nybl::error::NyblError> {
let closure = ::std::rc::Rc::new(AotClosure { callable });
let body: ::std::rc::Rc<dyn ::core::any::Any + 'static> = closure;
/*__NYBL_WRAP_CONSTRUCTOR__*/
}
/// Runtime dispatch for a value-based call: the callee is a
/// `Value::Fn` whose body must be an `AotClosure` we recognise.
/// Walker-created closures carrying an AST body come back as a
/// clear error rather than silently misbehaving.
fn __nybl_call_value(
ctx: &mut Ctx<'_>,
callee: ::nybl::value::Value,
args: ::std::vec::Vec<::nybl::value::Value>,
line: u32,
) -> Result<__NyblCallOutcome, ::nybl::error::NyblError> {
match &callee {
::nybl::value::Value::Fn(f) => {
/*__NYBL_VALIDATE_AOT_ORIGIN__*/
/*__NYBL_VALIDATE_AOT_ARITY__*/
match &f.body {
::nybl::value::FnBody::Compiled(body) => {
if let Some(aot) = body.downcast_ref::<AotClosure>() {
let callable = ::std::rc::Rc::clone(&aot.callable);
drop(callee);
/*__NYBL_CALL_VALUE_INVOKE__*/
} else {
Err(::nybl::error::NyblError::runtime(
"Closure body wasn't compiled by the AOT transpiler",
line,
))
}
}
::nybl::value::FnBody::Ast(_) => Err(::nybl::error::NyblError::runtime(
"Closure wasn't compiled for the AOT — use `nybl::run` for tree-walker closures",
line,
)),
}
}
other => Err(::nybl::error::NyblError::runtime(
::nybl::error_messages::cant_call_a(other.type_name()),
line,
)),
}
}
fn __nybl_call_named_value(
ctx: &mut Ctx<'_>,
callee: ::nybl::value::Value,
args: ::std::vec::Vec<::nybl::value::Value>,
name: &str,
line: u32,
) -> Result<::nybl::value::Value, ::nybl::error::NyblError> {
if !matches!(&callee, ::nybl::value::Value::Fn(_)) {
return Err(::nybl::error::NyblError::runtime(
format!("`{}` is a {}, not a function", name, callee.type_name()),
line,
));
}
__nybl_call_value(ctx, callee, args, line).map(|outcome| outcome.value)
}
/// `try_call(f)` implementation. Invokes `f` with no args via
/// the existing `AotClosure` pathway, then wraps the outcome
/// for the caller: `Ok(value)` on normal return, `Err(RuntimeError
/// { message, line })` on a non-fatal error, and re-raised on
/// fatal errors (resource-limit violations). `Result` and
/// `RuntimeError` values are built directly by
/// `nybl::builtins::make_try_call_ok` / `_err`, so the
/// program doesn't need to have declared those types itself.
fn __nybl_try_call(
ctx: &mut Ctx<'_>,
callable: ::nybl::value::Value,
line: u32,
) -> Result<::nybl::value::Value, ::nybl::error::NyblError> {
let func = match &callable {
::nybl::value::Value::Fn(f) => ::std::rc::Rc::clone(f),
other => {
return Err(::nybl::error::NyblError::runtime(
format!(
"`try_call` expects a function, got {}",
other.type_name()
),
line,
));
}
};
drop(callable);
/*__NYBL_TRY_ATTEMPT_START__*/
/*__NYBL_VALIDATE_AOT_FUNC_ORIGIN__*/
let callable_fn = match &func.body {
::nybl::value::FnBody::Compiled(body) => match body.downcast_ref::<AotClosure>() {
Some(aot) => ::std::rc::Rc::clone(&aot.callable),
None => {
return Err(::nybl::error::NyblError::runtime(
"try_call: callee wasn't compiled by the AOT transpiler",
line,
));
}
},
::nybl::value::FnBody::Ast(_) => {
return Err(::nybl::error::NyblError::runtime(
"try_call: callee was compiled for the walker, not AOT",
line,
));
}
};
/*__NYBL_TRY_ATTEMPT_INVOKE__*/
/*__NYBL_TRY_ATTEMPT_END__*/
drop(func);
let wrapped = match attempted {
Ok(outcome) => ::nybl::builtins::make_try_call_ok_in(
outcome.value,
line,
&ctx.memory,
),
Err(err) => {
if err.is_fatal {
Err(err)
} else {
Ok(::nybl::builtins::make_try_call_err_in(&err, &ctx.memory))
}
}
};
/*__NYBL_TRY_MEMORY_CHECK__*/
}
/// Handle `r.map(f)` / `r.map_err(f)` / `r.and_then(f)` for a
/// built-in `Result`. Invokes the callable synchronously via
/// the AOT closure pathway and wraps the result according to
/// the method kind. Short-circuit branches (map on Err,
/// map_err on Ok) skip the call and pass the Result through.
fn __nybl_result_callable_method(
ctx: &mut Ctx<'_>,
receiver: &::nybl::value::Value,
kind: ::nybl::methods::ResultCallableKind,
method: &str,
args: &[::nybl::value::Value],
line: u32,
) -> Result<::nybl::value::Value, ::nybl::error::NyblError> {
use ::nybl::methods::{make_result_err_in, make_result_ok_in, ResultCallableKind};
if args.len() != 1 {
return Err(::nybl::error::NyblError::runtime(
format!("`{}` expects 1 argument, but got {}", method, args.len()),
line,
));
}
let callable = args[0].clone();
let (is_ok, payload) = match receiver {
::nybl::value::Value::EnumVariant(e) => {
let payload = match e.payload() {
::nybl::value::EnumPayload::Tuple(items) if items.len() == 1 => {
items[0].clone()
}
_ => {
return Err(::nybl::error::NyblError::runtime(
format!("malformed Result::{} payload", e.variant()),
line,
));
}
};
(e.variant() == "Ok", payload)
}
_ => {
return Err(::nybl::error::NyblError::runtime(
"Result method called on non-Result",
line,
));
}
};
// Short-circuit: these branches don't invoke the callable,
// they just rebuild the Result with the existing payload.
match kind {
ResultCallableKind::Map if !is_ok => {
let wrapped = make_result_err_in(payload, line, &ctx.memory)?;
/*__NYBL_MEMORY_CHECK__*/
return Ok(wrapped);
}
ResultCallableKind::MapErr if is_ok => {
let wrapped = make_result_ok_in(payload, line, &ctx.memory)?;
/*__NYBL_MEMORY_CHECK__*/
return Ok(wrapped);
}
ResultCallableKind::AndThen if !is_ok => {
let wrapped = make_result_err_in(payload, line, &ctx.memory)?;
/*__NYBL_MEMORY_CHECK__*/
return Ok(wrapped);
}
_ => {}
}
let func = match &callable {
::nybl::value::Value::Fn(f) => ::std::rc::Rc::clone(f),
other => {
return Err(::nybl::error::NyblError::runtime(
format!("`{}` expects a function, got {}", method, other.type_name()),
line,
));
}
};
drop(callable);
/*__NYBL_VALIDATE_AOT_FUNC_ORIGIN__*/
let callable_fn = match &func.body {
::nybl::value::FnBody::Compiled(body) => match body.downcast_ref::<AotClosure>() {
Some(aot) => ::std::rc::Rc::clone(&aot.callable),
None => {
return Err(::nybl::error::NyblError::runtime(
format!("{}: callee wasn't compiled by the AOT transpiler", method),
line,
));
}
},
::nybl::value::FnBody::Ast(_) => {
return Err(::nybl::error::NyblError::runtime(
format!("{}: callee was compiled for the walker, not AOT", method),
line,
));
}
};
drop(func);
/*__NYBL_RESULT_INVOKE__*/
let wrapped = match kind {
ResultCallableKind::Map => make_result_ok_in(result.value, line, &ctx.memory),
ResultCallableKind::MapErr => make_result_err_in(result.value, line, &ctx.memory),
// `and_then` trusts the closure to have produced a
// Result already — pass it through untouched.
ResultCallableKind::AndThen => Ok(result.value),
};
let wrapped = wrapped?;
/*__NYBL_MEMORY_CHECK__*/
Ok(wrapped)
}
/// Field read for `Value::Struct`, struct-payload enum variants,
/// and `Value::Module`. Returns a cloned value; misses surface as
/// a runtime error with the type name in the message.
///
/// Module field reads resolve against the module's `bindings`
/// list. A field name that matches the module's public type exports
/// raises a targeted error — types aren't first-class values at
/// this stage, so `m.MyType` by itself is a programming mistake
/// (callers reach types through `m.MyType { ... }` or
/// `m.MyEnum::Variant(...)`, which go through namespace-aware
/// construct codegen, not `__nybl_field_get`).
#[inline]
fn __nybl_field_get(
obj: &::nybl::value::Value,
field: &str,
line: u32,
) -> Result<::nybl::value::Value, ::nybl::error::NyblError> {
match obj {
::nybl::value::Value::Struct(s) => s.field(field).cloned().ok_or_else(|| {
let mut err = ::nybl::error::NyblError::runtime(
::nybl::error_messages::struct_has_no_field(s.type_name(), field),
line,
);
let names = s.fields().iter().map(|(k, _)| k.as_str());
if let Some(hint) = ::nybl::suggest::did_you_mean(field, names) {
err.friendly_hint = Some(hint);
}
err
}),
::nybl::value::Value::EnumVariant(e) => e.field(field).cloned().ok_or_else(|| {
::nybl::error::NyblError::runtime(
::nybl::error_messages::variant_has_no_field(
e.type_name(),
e.variant(),
field,
),
line,
)
}),
::nybl::value::Value::Module(m) => {
if let Some(v) = m.__binding(field) {
return Ok(v);
}
if m.has_type(field) {
return Err(::nybl::error::NyblError::runtime(
format!(
"`{}.{}` is a type, not a value — construct it with `{{ ... }}` or `::Variant(...)`",
m.path, field
),
line,
));
}
Err(::nybl::error::NyblError::runtime(
format!("`{}` isn't exported from `{}`", field, m.path),
line,
))
}
other => Err(::nybl::error::NyblError::runtime(
::nybl::error_messages::cant_read_field(field, other.type_name()),
line,
)),
}
}
/// Live-module-aware variant of `__nybl_field_get` for expression
/// field reads. Module members resolve through `__nybl_module_member`
/// so mutations a module fn makes to its own globals stay visible
/// through `alias.member`; every other receiver (and the module
/// miss / type errors) delegates to `__nybl_field_get`. The compound
/// field-assignment path keeps the ctx-free helper because its
/// receiver already holds a mutable borrow of `ctx`.
#[inline]
fn __nybl_field_get_live(
ctx: &Ctx<'_>,
obj: &::nybl::value::Value,
field: &str,
line: u32,
) -> Result<::nybl::value::Value, ::nybl::error::NyblError> {
if let ::nybl::value::Value::Module(m) = obj {
if let ::std::option::Option::Some(v) = __nybl_module_member(ctx, m, field) {
return Ok(v);
}
}
__nybl_field_get(obj, field, line)
}
/// Runtime guard for namespaced type access: verifies that the
/// value behind the alias is actually a `Value::Module`, and that
/// the module's published type exports contain the name, then returns
/// the module path that defines the constructed value's runtime identity. Used by
/// struct / enum construct emission when `namespace` is `Some(...)`,
/// so the AOT surfaces the same error as walker + VM when someone
/// writes `m.MissingType { ... }` or uses a non-module as a namespace.
#[inline]
fn __nybl_validate_namespace_type(
ns: &::nybl::value::Value,
alias: &str,
type_name: &str,
line: u32,
) -> Result<String, ::nybl::error::NyblError> {
match ns {
::nybl::value::Value::Module(m) => {
m.type_origin(type_name).map(str::to_string).ok_or_else(|| {
::nybl::error::NyblError::runtime(
format!("`{}` isn't a type exported from `{}`", type_name, m.path),
line,
)
})
}
other => Err(::nybl::error::NyblError::runtime(
format!(
"`{}` is a {}, not a module alias — can't reach `{}` through it",
alias,
other.type_name(),
type_name
),
line,
)),
}
}
#[inline]
fn __nybl_optional_alias_namespace(
value: ::std::option::Option<::nybl::value::Value>,
alias: &str,
line: u32,
) -> Result<::nybl::value::Value, ::nybl::error::NyblError> {
value.ok_or_else(|| ::nybl::error::NyblError::runtime(
format!("`{}` isn't a module alias in scope", alias),
line,
))
}
fn __nybl_validate_named_fields(
declared: &[&str],
provided: &[&str],
type_name: &str,
variant: ::std::option::Option<&str>,
line: u32,
) -> Result<(), ::nybl::error::NyblError> {
for (index, field) in provided.iter().enumerate() {
if provided[..index].contains(field) {
let owner = match variant {
::std::option::Option::Some(variant) => format!("{}::{}", type_name, variant),
::std::option::Option::None => type_name.to_string(),
};
return Err(::nybl::error::NyblError::runtime(
format!("Field `{}` specified twice in `{}` construction", field, owner),
line,
));
}
if !declared.contains(field) {
let message = match variant {
::std::option::Option::Some(variant) => {
::nybl::error_messages::variant_has_no_field(type_name, variant, field)
}
::std::option::Option::None => {
::nybl::error_messages::struct_has_no_field(type_name, field)
}
};
let mut error = ::nybl::error::NyblError::runtime(message, line);
if variant.is_none() {
if let ::std::option::Option::Some(hint) = ::nybl::suggest::did_you_mean(
field,
declared.iter().copied(),
) {
error.friendly_hint = ::std::option::Option::Some(hint);
}
}
return Err(error);
}
}
for field in declared {
if !provided.contains(field) {
let owner = match variant {
::std::option::Option::Some(variant) => format!("{}::{}", type_name, variant),
::std::option::Option::None => type_name.to_string(),
};
return Err(::nybl::error::NyblError::runtime(
format!("Missing field `{}` in `{}` construction", field, owner),
line,
));
}
}
Ok(())
}
fn __nybl_order_named_fields(
declared: &[&str],
mut provided: ::std::vec::Vec<(String, ::nybl::value::Value)>,
) -> ::std::vec::Vec<(String, ::nybl::value::Value)> {
let mut ordered = ::std::vec::Vec::with_capacity(declared.len());
for field in declared {
let index = provided
.iter()
.position(|(name, _)| name == field)
.expect("dynamic construction shape was validated before payload evaluation");
ordered.push(provided.remove(index));
}
ordered
}
/// Write a struct field on the owned live-binding value and return it.
/// Moving the value into this helper keeps a unique CoW backing store unique.
#[inline]
fn __nybl_field_set(
memory: &::nybl::memory::MemoryContext,
mut obj: ::nybl::value::Value,
field: &str,
value: ::nybl::value::Value,
line: u32,
) -> Result<::nybl::value::Value, ::nybl::error::NyblError> {
match &mut obj {
::nybl::value::Value::Struct(s) => {
let type_name = s.type_name().to_string();
if !s.__try_set_field_in(field, value, line, memory)? {
return Err(::nybl::error::NyblError::runtime(
::nybl::error_messages::struct_has_no_field(&type_name, field),
line,
));
}
Ok(obj)
}
other => Err(::nybl::error::NyblError::runtime(
::nybl::error_messages::cant_assign_field(field, other.type_name()),
line,
)),
}
}
#[derive(Clone)]
enum __NyblPlaceStep {
Field(&'static str),
Index(::nybl::value::Value),
}
/// Read a leaf from an identifier-rooted field/index place. Projection
/// expressions have already been evaluated by generated code, so this helper
/// is deliberately side-effect free.
fn __nybl_place_get(
root: &::nybl::value::Value,
steps: &[__NyblPlaceStep],
line: u32,
memory: &::nybl::memory::MemoryContext,
) -> Result<::nybl::value::Value, ::nybl::error::NyblError> {
let mut value = root.clone();
for step in steps {
value = match step {
__NyblPlaceStep::Field(field) => __nybl_field_get(&value, field, line)?,
__NyblPlaceStep::Index(index) =>
::nybl::ops::index_get_in(&value, index, line, memory)?,
};
}
Ok(value)
}
/// Rebuild an owned root with one nested leaf replaced. All potentially
/// fallible CoW detach/depth/accounting work happens on this candidate before
/// generated code writes it into the live root binding.
fn __nybl_place_set(
memory: &::nybl::memory::MemoryContext,
root: ::nybl::value::Value,
steps: &[__NyblPlaceStep],
value: ::nybl::value::Value,
line: u32,
) -> Result<::nybl::value::Value, ::nybl::error::NyblError> {
fn replace(
memory: &::nybl::memory::MemoryContext,
mut owner: ::nybl::value::Value,
steps: &[__NyblPlaceStep],
value: ::nybl::value::Value,
line: u32,
) -> Result<::nybl::value::Value, ::nybl::error::NyblError> {
let Some((head, tail)) = steps.split_first() else {
return Ok(value);
};
match head {
__NyblPlaceStep::Field(field) => {
let child = __nybl_field_get(&owner, field, line)?;
let child = replace(memory, child, tail, value, line)?;
__nybl_field_set(memory, owner, field, child, line)
}
__NyblPlaceStep::Index(index) => {
let child = ::nybl::ops::index_get_in(&owner, index, line, memory)?;
let child = replace(memory, child, tail, value, line)?;
::nybl::ops::index_set_in(&mut owner, index, child, line, memory)?;
Ok(owner)
}
}
}
replace(memory, root, steps, value, line)
}
/// Mirror of Evaluator::call_method from nybl-lang: dispatches a
/// method call to the right family for the receiver's type.
///
/// For `Value::Module`, `m.helper(args)` reads the binding and
/// invokes it via the value-call path — the resulting value has
/// no "self" to write back, so the back-assign slot is always
/// `None`.
#[inline]
fn __nybl_call_method(
ctx: &mut Ctx<'_>,
obj: &::nybl::value::Value,
method: &str,
args: &[::nybl::value::Value],
line: u32,
) -> Result<(::nybl::value::Value, Option<::nybl::value::Value>), ::nybl::error::NyblError> {
// `type` / `to_str` / `inspect` work on every value —
// check them first so walker / VM / AOT agree on the
// common method surface without duplicating entries per
// type-specific dispatcher.
if let Some(result) =
::nybl::methods::common_method_in(obj, method, args, line, &ctx.memory)?
{
return Ok(result);
}
// Built-in `Result` combinators — pure methods inline;
// callable-taking variants (`map`, `map_err`, `and_then`)
// dispatch through `__nybl_result_callable_method`.
if ::nybl::methods::is_builtin_result(obj) {
if let Some(v) = ::nybl::methods::result_method(obj, method, args, line)? {
return Ok((v, None));
}
if let Some(kind) = ::nybl::methods::is_result_callable_method(method) {
let value = __nybl_result_callable_method(ctx, obj, kind, method, args, line)?;
return Ok((value, None));
}
}
match obj {
::nybl::value::Value::Array(arr) => {
::nybl::methods::array_method_in(arr, method, args, line, &ctx.memory)
}
::nybl::value::Value::Str(s) => {
::nybl::methods::string_method_in(s.as_str(), method, args, line, &ctx.memory)
}
::nybl::value::Value::Dict(d) => {
::nybl::methods::dict_method_in(d, method, args, line, &ctx.memory)
}
::nybl::value::Value::Int(_) | ::nybl::value::Value::Number(_) => {
::nybl::methods::numeric_method(obj, method, args, line)
}
::nybl::value::Value::Bool(_) => {
::nybl::methods::bool_method(obj, method, args, line)
}
::nybl::value::Value::Iter(_) => {
::nybl::methods::iter_method_in(obj, method, args, line, &ctx.memory)
}
::nybl::value::Value::Module(m) => {
let binding = __nybl_module_member(ctx, m, method).ok_or_else(|| {
::nybl::error::NyblError::runtime(
format!("`{}` isn't exported from `{}`", method, m.path),
line,
)
})?;
let result = __nybl_call_value(ctx, binding, args.to_vec(), line)?;
Ok((result.value, None))
}
::nybl::value::Value::Host(value) => match ctx.host.call_method(value, method, args, line) {
Some(result) => result.map(|value| (value, None)),
None => Err(::nybl::error::NyblError::runtime(
::nybl::error_messages::no_such_method(obj.type_name(), method),
line,
)),
},
_ => Err(::nybl::error::NyblError::runtime(
::nybl::error_messages::no_such_method(obj.type_name(), method),
line,
)),
}
}
/// Runtime state for a `for x in v` loop. Fast path for the
/// three built-in iterables (eager materialisation into a Vec
/// with a cursor); protocol path for `Value::Iter` or user
/// types with an `.iter()` method (carries the iterator value
/// and calls `.next()` on each step).
enum __NyblIterState {
Eager {
items: ::std::vec::Vec<::nybl::value::Value>,
pos: usize,
},
Protocol(::nybl::value::Value),
}
/// Build the iterator state for a `for x in v` loop. Matches
/// the walker/VM rule: Array/Str/Dict take the fast path,
/// `Value::Iter` is used as-is, Struct/Enum go through their
/// `.iter()` method, everything else surfaces the "can't
/// iterate over X" error.
fn __nybl_iter_start(
ctx: &mut Ctx<'_>,
mut v: ::nybl::value::Value,
line: u32,
) -> Result<__NyblIterState, ::nybl::error::NyblError> {
match &mut v {
::nybl::value::Value::Array(arr) => Ok(__NyblIterState::Eager {
items: arr.__take_in(&ctx.memory),
pos: 0,
}),
::nybl::value::Value::Str(s) => Ok(__NyblIterState::Eager {
items: s
.chars()
.map(|c| ::nybl::value::Value::__new_str_in(c.to_string(), &ctx.memory))
.collect(),
pos: 0,
}),
::nybl::value::Value::Dict(d) => Ok(__NyblIterState::Eager {
items: d
.iter()
.map(|(k, _)| ::nybl::value::Value::__new_str_in(k.clone(), &ctx.memory))
.collect(),
pos: 0,
}),
::nybl::value::Value::Iter(_) => Ok(__NyblIterState::Protocol(v)),
::nybl::value::Value::Struct(_) | ::nybl::value::Value::EnumVariant(_) => {
// Dispatch `.iter()` through the full method
// resolution — user-declared methods (`fn
// Bag.iter(self) { ... }`) must win before we fall
// back to the built-in `__nybl_call_method`.
let iter_val = match __nybl_try_user_method(
ctx, &v, "iter", &[], line,
)? {
Some(iter_val) => iter_val,
None => {
let (iter_val, _) =
__nybl_call_method(ctx, &v, "iter", &[], line)?;
iter_val
}
};
Ok(__NyblIterState::Protocol(iter_val))
}
_ => Err(::nybl::error::NyblError::runtime(
::nybl::error_messages::cant_iterate_over(v.type_name()),
line,
)),
}
}
/// Advance the iterator by one, returning the next value or
/// `None` on exhaustion. Protocol-path advancement calls the
/// iterator's `.next()` method and pattern-matches the
/// resulting `Iter::Next(v)` / `Iter::Done` shape.
fn __nybl_iter_step(
ctx: &mut Ctx<'_>,
state: &mut __NyblIterState,
line: u32,
) -> Result<Option<::nybl::value::Value>, ::nybl::error::NyblError> {
match state {
__NyblIterState::Eager { items, pos } => {
if *pos < items.len() {
// `items` was already taken from the source
// array / string / dict, so the clone is of an
// independent Vec — no aliasing.
let v = items[*pos].clone();
*pos += 1;
Ok(Some(v))
} else {
Ok(None)
}
}
__NyblIterState::Protocol(iter_val) => {
// Same user-first dispatch: a Bag that returns
// `self` from `.iter()` plus a user `.next()` must
// hit the user method, not the built-in iter table.
let step = match __nybl_try_user_method(
ctx, iter_val, "next", &[], line,
)? {
Some(v) => v,
None => {
let (v, _) =
__nybl_call_method(ctx, iter_val, "next", &[], line)?;
v
}
};
match &step {
::nybl::value::Value::EnumVariant(e)
if e.type_name() == "Iter" =>
{
match (e.variant(), e.payload()) {
(
"Next",
::nybl::value::EnumPayload::Tuple(items),
) if items.len() == 1 => Ok(Some(items[0].clone())),
("Done", ::nybl::value::EnumPayload::Unit) => Ok(None),
_ => Err(::nybl::error::NyblError::runtime(
format!(
"`.next()` on a `for` iterator must return `Iter::Next(v)` or `Iter::Done`, got {}",
step.inspect()
),
line,
)),
}
}
_ => Err(::nybl::error::NyblError::runtime(
format!(
"`.next()` on a `for` iterator must return `Iter::Next(v)` or `Iter::Done`, got {}",
step.inspect()
),
line,
)),
}
}
}
}
"#;
pub(super) const PUBLIC_ENTRY: &str = r#"// ─── Public entry points ────────────────────────────────────────
/// Run the compiled program with the supplied host. Unchecked output uses an
/// explicit untracked allocation context. Embedders that need resource limits
/// should compile with `Options::sandbox = true`.
pub fn run<H: ::nybl::NyblHost>(host: &mut H) -> Result<(), ::nybl::error::NyblError> {
let mut ctx = Ctx {
host: host as &mut dyn ::nybl::NyblHost,
memory: ::nybl::memory::MemoryContext::__untracked(),
rand_state: 0,
module_cache: ::std::collections::HashMap::new(),
module_aliases: ::std::collections::HashMap::new(),
bindings: ::std::collections::HashMap::new(),
binding_origins: ::std::collections::HashMap::new(),
binding_claims: ::std::collections::HashMap::new(),
active_function_sites: ::std::collections::HashMap::new(),
reached_function_sites: ::std::vec![false; __NYBL_FUNCTION_SITES.len()],
module_imported_function_sites: ::std::collections::HashMap::new(),
abi_declarations: ::std::vec::Vec::new(),
module_type_bindings: ::std::collections::HashMap::new(),
struct_defs: ::std::collections::HashMap::new(),
enum_defs: ::std::collections::HashMap::new(),
/*__NYBL_METHOD_SLOTS_INIT__*/
};
__nybl_seed_builtin_type_defs(&mut ctx)?;
run_program(&mut ctx)
}
"#;
pub(super) const MAIN_FN: &str = r#"fn main() {
let mut host = ::nybl_sys::StandardHost::new();
let result = run(&mut host);
if host.is_broken_pipe() {
return;
}
if let Err(err) = result {
eprintln!("{}", err);
if let Some(hint) = &err.friendly_hint {
eprintln!("hint: {}", hint);
}
::std::process::exit(1);
}
}
"#;
pub(super) const PUBLIC_ENTRY_SANDBOX: &str = r#"// ─── Public entry points ────────────────────────────────────────
fn __nybl_load_state(
host: &mut dyn ::nybl::NyblHost,
limits: &::nybl::NyblLimits,
memory: ::nybl::memory::MemoryContext,
) -> Result<__NyblState, ::nybl::error::NyblError> {
let mut state = __NyblState {
function_origin: ::nybl::value::NyblFnOrigin::__instance("aot"),
rand_state: 0,
module_cache: ::std::collections::HashMap::new(),
module_aliases: ::std::collections::HashMap::new(),
module_type_bindings: ::std::collections::HashMap::new(),
struct_defs: ::std::collections::HashMap::new(),
enum_defs: ::std::collections::HashMap::new(),
active_function_sites: ::std::collections::HashMap::new(),
module_imported_function_sites: ::std::collections::HashMap::new(),
bindings: ::std::collections::HashMap::new(),
binding_origins: ::std::collections::HashMap::new(),
binding_claims: ::std::collections::HashMap::new(),
abi_declarations: ::std::vec::Vec::new(),
/*__NYBL_METHOD_SLOTS_INIT__*/
};
{
let mut ctx = Ctx {
host,
state: &mut state,
memory,
steps: 0,
call_depth: 0,
max_steps: limits.max_steps,
};
__nybl_seed_builtin_type_defs(&mut ctx)?;
run_program(&mut ctx)?;
}
Ok(state)
}
/// A loaded sandboxed AOT program. Top-level code runs once in [`Self::load`]
/// and all root/module/type/method state remains live for later host calls.
/// Hosts are borrowed only for one operation and are never retained.
pub struct NyblInstance {
state: __NyblState,
entries: ::std::vec::Vec<::nybl::EntryPoint>,
limits: ::nybl::NyblLimits,
in_operation: ::core::cell::Cell<bool>,
memory: ::nybl::memory::MemoryContext,
}
impl NyblInstance {
/// Run the compiled top level once and retain its resulting state.
pub fn load(
host: &mut dyn ::nybl::NyblHost,
limits: &::nybl::NyblLimits,
) -> Result<Self, ::nybl::error::NyblError> {
let memory = ::nybl::memory::MemoryContext::__new(limits.max_memory);
let state = __nybl_load_state(host, limits, memory.clone())?;
if memory.__exceeded() {
return Err(__nybl_instance_memory_error());
}
let entries = __nybl_instance_entry_points(&state);
Ok(Self {
state,
entries,
limits: limits.clone(),
in_operation: ::core::cell::Cell::new(false),
memory,
})
}
/// Final executed direct-root public functions, in final-site order.
pub fn entry_points(&self) -> &[::nybl::EntryPoint] {
&self.entries
}
/// Invoke a declared public root entry point. This bypasses host, builtin,
/// import, and mutable ordinary-name dispatch.
pub fn call(
&mut self,
name: &str,
args: &[::nybl::value::Value],
host: &mut dyn ::nybl::NyblHost,
) -> Result<::nybl::value::Value, ::nybl::error::NyblError> {
let _operation = __NyblOperationGuard::begin(&self.in_operation)?;
let site_id = self
.state
.abi_declarations
.iter()
.copied()
.find(|site_id| {
let site = &__NYBL_FUNCTION_SITES[*site_id];
site.is_public && site.name == name
})
.ok_or_else(|| ::nybl::error::NyblError::runtime(
format!("Public entry point `{}` was not found", name),
0,
))?;
let site = &__NYBL_FUNCTION_SITES[site_id];
if !::nybl::ref_params::accepts_arity(site.param_modes, args.len()) {
return Err(__nybl_arity_error(name, site.param_modes, args.len(), 0));
}
::nybl::validate_call_modes(
name,
site.param_modes,
&vec![::nybl::parser::ParamMode::Value; args.len()],
0,
)?;
if self.memory.__exceeded() {
return Err(__nybl_instance_memory_error());
}
let result = {
let mut ctx = Ctx {
host,
state: &mut self.state,
memory: self.memory.clone(),
steps: 0,
call_depth: 0,
max_steps: self.limits.max_steps,
};
__nybl_call_function_site(&mut ctx, site_id, args.to_vec(), 0)
};
if self.memory.__exceeded() {
Err(__nybl_instance_memory_error())
} else {
result
}
}
/// Invoke a function value created by this exact generated instance.
pub fn call_value(
&mut self,
callable: &::nybl::value::Value,
args: &[::nybl::value::Value],
host: &mut dyn ::nybl::NyblHost,
) -> Result<::nybl::value::Value, ::nybl::error::NyblError> {
let _operation = __NyblOperationGuard::begin(&self.in_operation)?;
let function = match callable {
::nybl::value::Value::Fn(function) => ::std::rc::Rc::clone(function),
other => {
return Err(::nybl::error::NyblError::runtime(
format!("expected function, got {}", other.type_name()),
0,
));
}
};
if !function.__is_allowed_by(&self.state.function_origin, "aot") {
return Err(::nybl::error::NyblError::runtime(
"This function belongs to a different Nybl engine instance",
0,
));
}
if !::nybl::ref_params::accepts_arity(&function.param_modes, args.len()) {
return Err(__nybl_arity_error(
function.self_name.as_deref().unwrap_or("lambda"),
&function.param_modes,
args.len(),
0,
));
}
::nybl::validate_call_modes(
function.self_name.as_deref().unwrap_or("lambda"),
&function.param_modes,
&vec![::nybl::parser::ParamMode::Value; args.len()],
0,
)?;
if self.memory.__exceeded() {
return Err(__nybl_instance_memory_error());
}
let result = {
let mut ctx = Ctx {
host,
state: &mut self.state,
memory: self.memory.clone(),
steps: 0,
call_depth: 0,
max_steps: self.limits.max_steps,
};
__nybl_call_value(&mut ctx, callable.clone(), args.to_vec(), 0)
.map(|outcome| outcome.value)
};
if self.memory.__exceeded() {
Err(__nybl_instance_memory_error())
} else {
result
}
}
}
fn __nybl_instance_memory_error() -> ::nybl::error::NyblError {
::nybl::error::NyblError::fatal("Memory limit exceeded", 0)
}
struct __NyblOperationGuard<'a>(&'a ::core::cell::Cell<bool>);
impl<'a> __NyblOperationGuard<'a> {
fn begin(
active: &'a ::core::cell::Cell<bool>,
) -> Result<Self, ::nybl::error::NyblError> {
if active.replace(true) {
return Err(::nybl::error::NyblError::runtime(
"A Nybl instance cannot be re-entered",
0,
));
}
Ok(Self(active))
}
}
impl Drop for __NyblOperationGuard<'_> {
fn drop(&mut self) {
self.0.set(false);
}
}
/// One-shot compatibility adapter: load the generated instance, then drop it.
pub fn run<H: ::nybl::NyblHost>(
host: &mut H,
limits: &::nybl::NyblLimits,
) -> Result<(), ::nybl::error::NyblError> {
NyblInstance::load(host as &mut dyn ::nybl::NyblHost, limits).map(|_| ())
}
"#;
pub(super) const MAIN_FN_SANDBOX: &str = r#"fn main() {
let mut host = ::nybl_sys::StandardHost::new();
let limits = ::nybl::NyblLimits::standard();
let result = run(&mut host, &limits);
if host.is_broken_pipe() {
return;
}
if let Err(err) = result {
eprintln!("{}", err);
if let Some(hint) = &err.friendly_hint {
eprintln!("hint: {}", hint);
}
::std::process::exit(1);
}
}
"#;