UnattributedVar,
#[strum_discriminants(strum(props(Arity = "4", Name = "$get_db_refs")))]
GetDBRefs,
- #[strum_discriminants(strum(props(Arity = "2", Name = "$keysort_with_constant_var_ordering")))]
+ #[strum_discriminants(strum(props(
+ Arity = "2",
+ Name = "$keysort_with_constant_var_ordering"
+ )))]
KeySortWithConstantVarOrdering,
REPL(REPLCodePtr),
}
}
fn derive_input(ty: &Type) -> Option<DeriveInput> {
- let clause_type: Type = parse_quote!{ ClauseType };
+ let clause_type: Type = parse_quote! { ClauseType };
let built_in_clause_type: Type = parse_quote! { BuiltInClauseType };
let inlined_clause_type: Type = parse_quote! { InlinedClauseType };
let system_clause_type: Type = parse_quote! { SystemClauseType };
prefix: &'static str,
variant_data: &mut Vec<(&'static str, Arity, Variant)>,
) -> (&'static str, Arity)
- where DiscriminantT: FromStr + strum::EnumProperty + std::fmt::Debug
+where
+ DiscriminantT: FromStr + strum::EnumProperty + std::fmt::Debug,
{
let name = prop_from_ident::<DiscriminantT>(&variant.ident, "Name");
let arity = Arity::from(prop_from_ident::<DiscriminantT>(&variant.ident, "Arity"));
&Instruction::CallMakeDirectoryPath |
&Instruction::CallDeleteFile |
&Instruction::CallRenameFile |
- &Instruction::CallFileCopy |
+ &Instruction::CallFileCopy |
&Instruction::CallWorkingDirectory |
&Instruction::CallDeleteDirectory |
&Instruction::CallPathCanonical |
&Instruction::CallHttpListen |
&Instruction::CallHttpAccept |
&Instruction::CallHttpAnswer |
- &Instruction::CallLoadForeignLib |
- &Instruction::CallForeignCall |
- &Instruction::CallDefineForeignStruct |
+ &Instruction::CallLoadForeignLib |
+ &Instruction::CallForeignCall |
+ &Instruction::CallDefineForeignStruct |
&Instruction::CallPredicateDefined |
&Instruction::CallStripModule |
&Instruction::CallCurrentTime |
&Instruction::ExecuteMakeDirectoryPath |
&Instruction::ExecuteDeleteFile |
&Instruction::ExecuteRenameFile |
- &Instruction::ExecuteFileCopy |
+ &Instruction::ExecuteFileCopy |
&Instruction::ExecuteWorkingDirectory |
&Instruction::ExecuteDeleteDirectory |
&Instruction::ExecutePathCanonical |
&Instruction::ExecuteHttpListen |
&Instruction::ExecuteHttpAccept |
&Instruction::ExecuteHttpAnswer |
- &Instruction::ExecuteLoadForeignLib |
- &Instruction::ExecuteForeignCall |
- &Instruction::ExecuteDefineForeignStruct |
+ &Instruction::ExecuteLoadForeignLib |
+ &Instruction::ExecuteForeignCall |
+ &Instruction::ExecuteDefineForeignStruct |
&Instruction::ExecutePredicateDefined |
&Instruction::ExecuteStripModule |
&Instruction::ExecuteCurrentTime |
instr_data.generate_instruction_enum_loop(input);
- let instr_variants: Vec<_> = instr_data.instr_variants
+ let instr_variants: Vec<_> = instr_data
+ .instr_variants
.iter()
.cloned()
.map(|(_, _, _, variant)| variant)
for (name, arity, variant) in instr_data.compare_number_variants {
let ident = variant.ident.clone();
- let variant_fields: Vec<_> = variant.fields
+ let variant_fields: Vec<_> = variant
+ .fields
.into_iter()
.map(|field| {
let ty = field.ty;
let ident = variant.ident;
let instr_ident = format_ident!("Call{}", ident);
- let placeholder_ids: Vec<_> = (0 .. variant_fields.len())
+ let placeholder_ids: Vec<_> = (0..variant_fields.len())
.map(|n| format_ident!("f_{}", n))
.collect();
- clause_type_to_instr_arms.push(
- quote! {
- ClauseType::Inlined(
- InlinedClauseType::CompareNumber(CompareNumber::#ident(#(#placeholder_ids),*))
- ) => Instruction::#instr_ident(#(*#placeholder_ids),*)
- }
- );
+ clause_type_to_instr_arms.push(quote! {
+ ClauseType::Inlined(
+ InlinedClauseType::CompareNumber(CompareNumber::#ident(#(#placeholder_ids),*))
+ ) => Instruction::#instr_ident(#(*#placeholder_ids),*)
+ });
- is_inbuilt_arms.push(
- quote! {
- (atom!(#name), #arity) => true
- }
- );
+ is_inbuilt_arms.push(quote! {
+ (atom!(#name), #arity) => true
+ });
- is_inlined_arms.push(
- quote! {
- (atom!(#name), #arity) => true
- }
- );
+ is_inlined_arms.push(quote! {
+ (atom!(#name), #arity) => true
+ });
}
for (name, arity, variant) in instr_data.compare_term_variants {
)
});
- clause_type_name_arms.push(
- quote! {
- ClauseType::BuiltIn(
- BuiltInClauseType::CompareTerm(CompareTerm::#ident)
- ) => atom!(#name)
- }
- );
+ clause_type_name_arms.push(quote! {
+ ClauseType::BuiltIn(
+ BuiltInClauseType::CompareTerm(CompareTerm::#ident)
+ ) => atom!(#name)
+ });
let ident = variant.ident;
let instr_ident = format_ident!("Call{}", ident);
- clause_type_to_instr_arms.push(
- quote! {
- ClauseType::BuiltIn(
- BuiltInClauseType::CompareTerm(CompareTerm::#ident)
- ) => Instruction::#instr_ident
- }
- );
+ clause_type_to_instr_arms.push(quote! {
+ ClauseType::BuiltIn(
+ BuiltInClauseType::CompareTerm(CompareTerm::#ident)
+ ) => Instruction::#instr_ident
+ });
- is_inbuilt_arms.push(
- quote! {
- (atom!(#name), #arity) => true
- }
- );
+ is_inbuilt_arms.push(quote! {
+ (atom!(#name), #arity) => true
+ });
}
for (name, arity, variant) in instr_data.builtin_type_variants {
let ident = variant.ident.clone();
- let variant_fields: Vec<_> = variant.fields
+ let variant_fields: Vec<_> = variant
+ .fields
.into_iter()
.map(|field| {
let ty = field.ty;
let ident = variant.ident;
let instr_ident = format_ident!("Call{}", ident);
- let placeholder_ids: Vec<_> = (0 .. variant_fields.len())
+ let placeholder_ids: Vec<_> = (0..variant_fields.len())
.map(|n| format_ident!("f_{}", n))
.collect();
}
});
- is_inbuilt_arms.push(
- quote! {
- (atom!(#name), #arity) => true
- }
- );
+ is_inbuilt_arms.push(quote! {
+ (atom!(#name), #arity) => true
+ });
}
for (name, arity, variant) in instr_data.inlined_type_variants {
let ident = variant.ident.clone();
- let variant_fields: Vec<_> = variant.fields
+ let variant_fields: Vec<_> = variant
+ .fields
.into_iter()
.map(|field| {
if field.ty.type_id() == TypeId::of::<usize>() {
let ident = variant.ident;
let instr_ident = format_ident!("Call{}", ident);
- let placeholder_ids: Vec<_> = (0 .. variant_fields.len())
+ let placeholder_ids: Vec<_> = (0..variant_fields.len())
.map(|n| format_ident!("f_{}", n))
.collect();
- clause_type_to_instr_arms.push(
- quote! {
- ClauseType::Inlined(
- InlinedClauseType::#ident(#(#placeholder_ids),*)
- ) => Instruction::#instr_ident(*#(#placeholder_ids),*)
- }
- );
+ clause_type_to_instr_arms.push(quote! {
+ ClauseType::Inlined(
+ InlinedClauseType::#ident(#(#placeholder_ids),*)
+ ) => Instruction::#instr_ident(*#(#placeholder_ids),*)
+ });
- is_inbuilt_arms.push(
- quote! {
- (atom!(#name), #arity) => true
- }
- );
+ is_inbuilt_arms.push(quote! {
+ (atom!(#name), #arity) => true
+ });
- is_inlined_arms.push(
- quote! {
- (atom!(#name), #arity) => true
- }
- );
+ is_inlined_arms.push(quote! {
+ (atom!(#name), #arity) => true
+ });
}
for (name, arity, variant) in instr_data.system_clause_type_variants {
let ident = variant.ident.clone();
- let variant_fields: Vec<_> = variant.fields
+ let variant_fields: Vec<_> = variant
+ .fields
.into_iter()
.map(|field| {
if field.ty == parse_quote! { usize } {
ident.clone()
};
- let placeholder_ids: Vec<_> = (0 .. variant_fields.len())
+ let placeholder_ids: Vec<_> = (0..variant_fields.len())
.map(|n| format_ident!("f_{}", n))
.collect();
}
});
- is_inbuilt_arms.push(
- if let Arity::Ident("arity") = &arity {
- quote! {
- (atom!(#name), _arity) => true
- }
- } else {
- quote! {
- (atom!(#name), #arity) => true
- }
+ is_inbuilt_arms.push(if let Arity::Ident("arity") = &arity {
+ quote! {
+ (atom!(#name), _arity) => true
+ }
+ } else {
+ quote! {
+ (atom!(#name), #arity) => true
}
- );
+ });
}
for (name, arity, variant) in instr_data.repl_code_ptr_variants {
let ident = variant.ident.clone();
- let variant_fields: Vec<_> = variant.fields
+ let variant_fields: Vec<_> = variant
+ .fields
.into_iter()
.map(|field| {
if field.ty.type_id() == TypeId::of::<usize>() {
let ident = variant.ident;
let instr_ident = format_ident!("Call{}", ident);
- let placeholder_ids: Vec<_> = (0 .. variant_fields.len())
+ let placeholder_ids: Vec<_> = (0..variant_fields.len())
.map(|n| format_ident!("f_{}", n))
.collect();
}
});
- is_inbuilt_arms.push(
- quote! {
- (atom!(#name), #arity) => true
- }
- );
+ is_inbuilt_arms.push(quote! {
+ (atom!(#name), #arity) => true
+ });
}
for (name, arity, variant) in instr_data.clause_type_variants {
continue;
}
- let variant_fields: Vec<_> = variant.fields
+ let variant_fields: Vec<_> = variant
+ .fields
.into_iter()
.map(|field| {
if field.ty == parse_quote! { usize } {
let ident = variant.ident;
- let placeholder_ids: Vec<_> = (0 .. variant_fields.len())
+ let placeholder_ids: Vec<_> = (0..variant_fields.len())
.map(|n| format_ident!("f_{}", n))
.collect();
}
});
- is_inbuilt_arms.push(
- quote! {
- (atom!(#name), _arity) => true
- }
- );
+ is_inbuilt_arms.push(quote! {
+ (atom!(#name), _arity) => true
+ });
}
- let to_execute_arms: Vec<_> = instr_data.instr_variants
+ let to_execute_arms: Vec<_> = instr_data
+ .instr_variants
.iter()
.cloned()
.filter_map(|(_, _, _, variant)| {
0
};
- let placeholder_ids: Vec<_> = (0 .. enum_arity)
- .map(|n| format_ident!("f_{}", n))
- .collect();
+ let placeholder_ids: Vec<_> =
+ (0..enum_arity).map(|n| format_ident!("f_{}", n)).collect();
if variant_string.starts_with("Call") {
- let execute_ident = format_ident!("Execute{}", variant_string["Call".len() ..]);
+ let execute_ident = format_ident!("Execute{}", variant_string["Call".len()..]);
Some(if enum_arity == 0 {
quote! {
})
} else if variant_string.starts_with("DefaultCall") {
let execute_ident =
- format_ident!("DefaultExecute{}", variant_string["DefaultCall".len() ..]);
+ format_ident!("DefaultExecute{}", variant_string["DefaultCall".len()..]);
Some(if enum_arity == 0 {
quote! {
})
.collect();
- let is_execute_arms: Vec<_> = instr_data.instr_variants
+ let is_execute_arms: Vec<_> = instr_data
+ .instr_variants
.iter()
.cloned()
.filter_map(|(_, _, _, variant)| {
})
.collect();
- let to_default_arms: Vec<_> = instr_data.instr_variants
+ let to_default_arms: Vec<_> = instr_data
+ .instr_variants
.iter()
.cloned()
.filter_map(|(_, _, countable_inference, variant)| {
0
};
- let placeholder_ids: Vec<_> = (0 .. enum_arity)
- .map(|n| format_ident!("f_{}", n))
- .collect();
+ let placeholder_ids: Vec<_> =
+ (0..enum_arity).map(|n| format_ident!("f_{}", n)).collect();
Some(if enum_arity == 0 {
quote! {
})
.collect();
- let control_flow_arms: Vec<_> = instr_data.instr_variants
+ let control_flow_arms: Vec<_> = instr_data
+ .instr_variants
.iter()
.cloned()
.filter_map(|(_, _, _, variant)| {
})
.collect();
- let instr_macro_arms: Vec<_> = instr_data.instr_variants
+ let instr_macro_arms: Vec<_> = instr_data
+ .instr_variants
.iter()
.rev() // produce default, execute & default & execute cases first.
.cloned()
let variant_string = variant.ident.to_string();
let arity = match arity {
Arity::Static(arity) => arity,
- _ => 1
+ _ => 1,
};
Some(if variant_string.starts_with("Execute") {
})
.collect();
- let name_and_arity_arms: Vec<_> = instr_data.instr_variants
+ let name_and_arity_arms: Vec<_> = instr_data
+ .instr_variants
.into_iter()
- .map(|(name,arity,_,variant)| {
+ .map(|(name, arity, _, variant)| {
let ident = &variant.ident;
let enum_arity = if let Fields::Unnamed(fields) = &variant.fields {
fn is_callable(id: &Ident) -> bool {
let id = id.to_string();
- id.starts_with("Call") || id.starts_with("Execute") || id.starts_with("DefaultCall") ||
- id.starts_with("DefaultExecute")
+ id.starts_with("Call")
+ || id.starts_with("Execute")
+ || id.starts_with("DefaultCall")
+ || id.starts_with("DefaultExecute")
}
fn is_non_default_callable(id: &Ident) -> bool {
}
fn prop_from_ident<DiscriminantT>(id: &Ident, key: &'static str) -> &'static str
- where DiscriminantT: FromStr + strum::EnumProperty + std::fmt::Debug
+where
+ DiscriminantT: FromStr + strum::EnumProperty + std::fmt::Debug,
{
let disc = match DiscriminantT::from_str(id.to_string().as_str()) {
Ok(disc) => disc,
#[derive(Clone, Copy)]
enum Arity {
Static(usize),
- Ident(&'static str)
+ Ident(&'static str),
}
impl From<&'static str> for Arity {
(name, arity, CountableInference::NotCounted)
} else if id == "InstructionTemplate" {
- ( prop_from_ident::<InstructionTemplateDiscriminants>(&variant.ident, "Name"),
- Arity::from(prop_from_ident::<InstructionTemplateDiscriminants>(&variant.ident, "Arity")),
- CountableInference::NotCounted
+ (
+ prop_from_ident::<InstructionTemplateDiscriminants>(&variant.ident, "Name"),
+ Arity::from(prop_from_ident::<InstructionTemplateDiscriminants>(
+ &variant.ident,
+ "Arity",
+ )),
+ CountableInference::NotCounted,
)
} else if id == "ClauseType" {
let (name, arity) = add_discriminant_data::<ClauseTypeDiscriminants>(
let v_string = variant.ident.to_string();
let v_ident = if v_string.starts_with("Call") {
- format_ident!("{}", v_string["Call".len() ..])
+ format_ident!("{}", v_string["Call".len()..])
} else {
variant.ident.clone()
};
- let generated_variant = create_instr_variant(
- format_ident!("{}{}", prefix, v_ident),
- variant.clone(),
- );
+ let generated_variant =
+ create_instr_variant(format_ident!("{}{}", prefix, v_ident), variant.clone());
- self.instr_variants.push(
- (name, arity, countable_inference, generated_variant)
- );
+ self.instr_variants
+ .push((name, arity, countable_inference, generated_variant));
}
fn generate_instruction_enum_loop(&mut self, input: syn::DeriveInput) {
self.label_variant(&input.ident, "Call", variant.clone());
self.label_variant(&input.ident, "Execute", variant.clone());
- if input.ident == "BuiltInClauseType" ||
- input.ident == "CompareNumber" ||
- input.ident == "CompareTerm" ||
- input.ident == "ClauseType"
+ if input.ident == "BuiltInClauseType"
+ || input.ident == "CompareNumber"
+ || input.ident == "CompareTerm"
+ || input.ident == "ClauseType"
{
self.label_variant(&input.ident, "DefaultCall", variant.clone());
self.label_variant(&input.ident, "DefaultExecute", variant);
use proc_macro2::TokenStream;
-use syn::*;
use syn::parse::*;
use syn::visit::*;
+use syn::*;
use indexmap::IndexSet;
impl StaticStrVisitor {
fn new() -> Self {
- Self { static_strs: IndexSet::new() }
+ Self {
+ static_strs: IndexSet::new(),
+ }
}
}
use crate::raw_block::*;
use crate::read::*;
-use ordered_float::OrderedFloat;
use crate::parser::dashu::{Integer, Rational};
+use ordered_float::OrderedFloat;
use std::alloc;
use std::fmt;
($e:expr, $arena:expr) => {{
let result = $e;
#[allow(unused_unsafe)]
- unsafe { ArenaAllocated::alloc($arena, result) }
+ unsafe {
+ ArenaAllocated::alloc($arena, result)
+ }
}};
}
($e:expr, $arena:expr) => {{
let result = $e;
#[allow(unused_unsafe)]
- unsafe { $arena.f64_tbl.build_with(result) }
+ unsafe {
+ $arena.f64_tbl.build_with(result)
+ }
}};
}
impl F64Table {
#[inline]
pub fn new() -> Self {
- let table = Self { block: RawBlock::new() };
+ let table = Self {
+ block: RawBlock::new(),
+ };
set_f64_tbl_buf_base(table.block.base);
table
}
OutputFileStream = 0b10100,
NamedTcpStream = 0b011100,
NamedTlsStream = 0b100000,
- HttpReadStream = 0b100001,
+ HttpReadStream = 0b100001,
HttpWriteStream = 0b100010,
ReadlineStream = 0b110000,
StaticStringStream = 0b110100,
#[inline]
pub fn set_tag(&mut self, tag: ArenaHeaderTag) {
- unsafe { (*self.header_ptr_mut()).set_tag(tag); }
+ unsafe {
+ (*self.header_ptr_mut()).set_tag(tag);
+ }
}
#[inline]
unsafe fn alloc(arena: &mut Arena, value: Self) -> Self::PtrToAllocated {
let size = value.size() + mem::size_of::<AllocSlab>();
- #[cfg(target_pointer_width="32")]
+ #[cfg(target_pointer_width = "32")]
let align = mem::align_of::<AllocSlab>() * 2;
- #[cfg(target_pointer_width="64")]
+ #[cfg(target_pointer_width = "64")]
let align = mem::align_of::<AllocSlab>();
let layout = alloc::Layout::from_size_align_unchecked(size, align);
impl F64Ptr {
#[inline(always)]
pub fn from_offset(offset: usize) -> Self {
- unsafe {
- F64Ptr(ptr::NonNull::new_unchecked(lookup_float(offset)))
- }
+ unsafe { F64Ptr(ptr::NonNull::new_unchecked(lookup_float(offset))) }
}
#[inline(always)]
#[inline]
fn tag() -> ArenaHeaderTag {
- ArenaHeaderTag::HttpListener
+ ArenaHeaderTag::HttpListener
}
#[inline]
fn size(&self) -> usize {
- mem::size_of::<Self>()
+ mem::size_of::<Self>()
}
#[inline]
fn copy_to_arena(self, dst: *mut Self) -> Self::PtrToAllocated {
- unsafe {
- ptr::write(dst, self);
- TypedArenaPtr::new(dst as *mut Self)
- }
+ unsafe {
+ ptr::write(dst, self);
+ TypedArenaPtr::new(dst as *mut Self)
+ }
}
}
#[inline]
fn tag() -> ArenaHeaderTag {
- ArenaHeaderTag::HttpResponse
+ ArenaHeaderTag::HttpResponse
}
#[inline]
fn size(&self) -> usize {
- mem::size_of::<Self>()
+ mem::size_of::<Self>()
}
#[inline]
fn copy_to_arena(self, dst: *mut Self) -> Self::PtrToAllocated {
- unsafe {
- ptr::write(dst, self);
- TypedArenaPtr::new(dst as *mut Self)
- }
+ unsafe {
+ ptr::write(dst, self);
+ TypedArenaPtr::new(dst as *mut Self)
+ }
}
}
#[derive(Clone, Copy, Debug)]
struct AllocSlab {
next: *mut AllocSlab,
- #[cfg(target_pointer_width="32")]
+ #[cfg(target_pointer_width = "32")]
_padding: u32,
header: ArenaHeader,
}
impl Arena {
#[inline]
pub fn new() -> Self {
- Arena { base: ptr::null_mut(), f64_tbl: F64Table::new() }
+ Arena {
+ base: ptr::null_mut(),
+ f64_tbl: F64Table::new(),
+ }
}
}
#[cfg(feature = "http")]
ptr::drop_in_place(value.payload_offset::<StreamLayout<CharReader<HttpReadStream>>>());
}
- ArenaHeaderTag::HttpWriteStream => {
+ ArenaHeaderTag::HttpWriteStream => {
#[cfg(feature = "http")]
- ptr::drop_in_place(value.payload_offset::<StreamLayout<CharReader<HttpWriteStream>>>());
- }
+ ptr::drop_in_place(value.payload_offset::<StreamLayout<CharReader<HttpWriteStream>>>());
+ }
ArenaHeaderTag::ReadlineStream => {
ptr::drop_in_place(value.payload_offset::<StreamLayout<ReadlineStream>>());
}
ArenaHeaderTag::LiveLoadState | ArenaHeaderTag::InactiveLoadState => {
ptr::drop_in_place(value.payload_offset::<LiveLoadState>());
}
- ArenaHeaderTag::Dropped => {
- }
+ ArenaHeaderTag::Dropped => {}
ArenaHeaderTag::TcpListener => {
ptr::drop_in_place(value.payload_offset::<TcpListener>());
}
- ArenaHeaderTag::HttpListener => {
+ ArenaHeaderTag::HttpListener => {
#[cfg(feature = "http")]
- ptr::drop_in_place(value.payload_offset::<HttpListener>());
- }
- ArenaHeaderTag::HttpResponse => {
+ ptr::drop_in_place(value.payload_offset::<HttpListener>());
+ }
+ ArenaHeaderTag::HttpResponse => {
#[cfg(feature = "http")]
- ptr::drop_in_place(value.payload_offset::<HttpResponse>());
- }
+ ptr::drop_in_place(value.payload_offset::<HttpResponse>());
+ }
ArenaHeaderTag::StandardOutputStream => {
ptr::drop_in_place(value.payload_offset::<StreamLayout<StandardOutputStream>>());
}
ArenaHeaderTag::StandardErrorStream => {
ptr::drop_in_place(value.payload_offset::<StreamLayout<StandardErrorStream>>());
}
- ArenaHeaderTag::NullStream | ArenaHeaderTag::IndexPtrUndefined |
- ArenaHeaderTag::IndexPtrDynamicUndefined | ArenaHeaderTag::IndexPtrDynamicIndex |
- ArenaHeaderTag::IndexPtrIndex => {
- }
+ ArenaHeaderTag::NullStream
+ | ArenaHeaderTag::IndexPtrUndefined
+ | ArenaHeaderTag::IndexPtrDynamicUndefined
+ | ArenaHeaderTag::IndexPtrDynamicIndex
+ | ArenaHeaderTag::IndexPtrIndex => {}
}
}
use crate::machine::mock_wam::*;
use crate::machine::partial_string::*;
- use ordered_float::OrderedFloat;
use crate::parser::dashu::{Integer, Rational};
+ use ordered_float::OrderedFloat;
#[test]
fn float_ptr_cast() {
#[test]
fn heap_cell_value_const_cast() {
let mut wam = MockWAM::new();
- #[cfg(target_pointer_width="32")]
+ #[cfg(target_pointer_width = "32")]
let const_value = HeapCellValue::from(ConsPtr::build_with(
0x0000_0431 as *const _,
ConsPtrMaskTag::Cons,
));
- #[cfg(target_pointer_width="64")]
+ #[cfg(target_pointer_width = "64")]
let const_value = HeapCellValue::from(ConsPtr::build_with(
0x0000_5555_ff00_0431 as *const _,
ConsPtrMaskTag::Cons,
match const_value.to_untyped_arena_ptr() {
Some(arena_ptr) => {
- assert_eq!(arena_ptr.into_bytes(), const_value.to_untyped_arena_ptr_bytes());
+ assert_eq!(
+ arena_ptr.into_bytes(),
+ const_value.to_untyped_arena_ptr_bytes()
+ );
}
None => {
assert!(false);
match stream_cell.to_untyped_arena_ptr() {
Some(arena_ptr) => {
- assert_eq!(arena_ptr.into_bytes(), stream_cell.to_untyped_arena_ptr_bytes());
+ assert_eq!(
+ arena_ptr.into_bytes(),
+ stream_cell.to_untyped_arena_ptr_bytes()
+ );
}
None => {
assert!(false);
// integer
let big_int: Integer = 2 * Integer::from(1u64 << 63);
- let big_int_ptr: TypedArenaPtr<Integer> =
- arena_alloc!(big_int, &mut wam.machine_st.arena);
+ let big_int_ptr: TypedArenaPtr<Integer> = arena_alloc!(big_int, &mut wam.machine_st.arena);
assert!(!big_int_ptr.as_ptr().is_null());
// complete string
- let pstr_var_cell = put_partial_string(&mut wam.machine_st.heap, "ronan", &mut wam.machine_st.atom_tbl);
+ let pstr_var_cell = put_partial_string(
+ &mut wam.machine_st.heap,
+ "ronan",
+ &mut wam.machine_st.atom_tbl,
+ );
let pstr_cell = wam.machine_st.heap[pstr_var_cell.get_value() as usize];
assert_eq!(pstr_cell.get_tag(), HeapCellValueTag::PStr);
Literal::Float(n) => interm.push(ArithmeticTerm::Number(Number::Float(*n.as_ptr()))),
Literal::Rational(n) => interm.push(ArithmeticTerm::Number(Number::Rational(*n))),
Literal::Atom(name) if name == &atom!("e") => interm.push(ArithmeticTerm::Number(
- Number::Float(OrderedFloat(std::f64::consts::E))
+ Number::Float(OrderedFloat(std::f64::consts::E)),
)),
Literal::Atom(name) if name == &atom!("pi") => interm.push(ArithmeticTerm::Number(
- Number::Float(OrderedFloat(std::f64::consts::PI))
+ Number::Float(OrderedFloat(std::f64::consts::PI)),
)),
Literal::Atom(name) if name == &atom!("epsilon") => interm.push(ArithmeticTerm::Number(
- Number::Float(OrderedFloat(std::f64::EPSILON))
+ Number::Float(OrderedFloat(std::f64::EPSILON)),
)),
_ => return Err(ArithmeticError::NonEvaluableFunctor(*c, 0)),
}
let var_num = name.to_var_num().unwrap();
let r = if lvl == Level::Shallow {
- self.marker.mark_non_callable(
- var_num,
- arg,
- term_loc,
- cell,
- &mut code,
- )
+ self.marker
+ .mark_non_callable(var_num, arg, term_loc, cell, &mut code)
} else if term_loc.is_last() || cell.get().norm().reg_num() == 0 {
let r = self.marker.get_binding(var_num);
if r.reg_num() == 0 {
self.marker.mark_var::<QueryInstruction>(
- var_num,
- lvl,
- cell,
- term_loc,
- &mut code,
+ var_num, lvl, cell, term_loc, &mut code,
);
cell.get().norm()
} else {
}
}
FpCategory::Nan => Err(EvalError::Undefined),
- _ => Ok(f)
+ _ => Ok(f),
}
}
(&Number::Fixnum(n1), &Number::Float(n2)) => OrderedFloat(n1.get_num() as f64).eq(&n2),
(&Number::Float(n1), &Number::Fixnum(n2)) => n1.eq(&OrderedFloat(n2.get_num() as f64)),
(&Number::Integer(ref n1), &Number::Integer(ref n2)) => n1.eq(n2),
- (&Number::Integer(ref n1), Number::Float(n2)) => OrderedFloat(n1.to_f64().value()).eq(n2),
- (&Number::Float(n1), &Number::Integer(ref n2)) => n1.eq(&OrderedFloat(n2.to_f64().value())),
+ (&Number::Integer(ref n1), Number::Float(n2)) => {
+ OrderedFloat(n1.to_f64().value()).eq(n2)
+ }
+ (&Number::Float(n1), &Number::Integer(ref n2)) => {
+ n1.eq(&OrderedFloat(n2.to_f64().value()))
+ }
(&Number::Integer(ref n1), &Number::Rational(ref n2)) => {
#[cfg(feature = "num")]
{
&**n1 == &**n2
}
}
- (&Number::Rational(ref n1), &Number::Float(n2)) => OrderedFloat(n1.to_f64().value()).eq(&n2),
- (&Number::Float(n1), &Number::Rational(ref n2)) => n1.eq(&OrderedFloat(n2.to_f64().value())),
+ (&Number::Rational(ref n1), &Number::Float(n2)) => {
+ OrderedFloat(n1.to_f64().value()).eq(&n2)
+ }
+ (&Number::Float(n1), &Number::Rational(ref n2)) => {
+ n1.eq(&OrderedFloat(n2.to_f64().value()))
+ }
(&Number::Float(f1), &Number::Float(f2)) => f1.eq(&f2),
(&Number::Rational(ref r1), &Number::Rational(ref r2)) => r1.eq(&r2),
}
(&Number::Float(n1), &Number::Fixnum(n2)) => n1.cmp(&OrderedFloat(n2.get_num() as f64)),
(&Number::Integer(n1), &Number::Integer(n2)) => (*n1).cmp(&*n2),
(&Number::Integer(n1), Number::Float(n2)) => OrderedFloat(n1.to_f64().value()).cmp(n2),
- (&Number::Float(n1), &Number::Integer(ref n2)) => n1.cmp(&OrderedFloat(n2.to_f64().value())),
+ (&Number::Float(n1), &Number::Integer(ref n2)) => {
+ n1.cmp(&OrderedFloat(n2.to_f64().value()))
+ }
(&Number::Integer(n1), &Number::Rational(n2)) => {
#[cfg(feature = "num")]
{
(&*n1).partial_cmp(&*n2).unwrap_or(Ordering::Less)
}
}
- (&Number::Rational(n1), &Number::Float(n2)) => OrderedFloat(n1.to_f64().value()).cmp(&n2),
- (&Number::Float(n1), &Number::Rational(n2)) => n1.cmp(&OrderedFloat(n2.to_f64().value())),
+ (&Number::Rational(n1), &Number::Float(n2)) => {
+ OrderedFloat(n1.to_f64().value()).cmp(&n2)
+ }
+ (&Number::Float(n1), &Number::Rational(n2)) => {
+ n1.cmp(&OrderedFloat(n2.to_f64().value()))
+ }
(&Number::Float(f1), &Number::Float(f2)) => f1.cmp(&f2),
(&Number::Rational(r1), &Number::Rational(r2)) => (*r1).cmp(&*r2),
}
impl From<bool> for Atom {
#[inline]
fn from(value: bool) -> Self {
- if value { atom!("true") } else { atom!("false") }
+ if value {
+ atom!("true")
+ } else {
+ atom!("false")
+ }
}
}
std::sync::atomic::AtomicPtr::new(ptr::null_mut());
fn set_atom_tbl_buf_base(old_ptr: *const u8, new_ptr: *const u8) -> Result<(), *const u8> {
-#[cfg(test)]
+ #[cfg(test)]
{
- ATOM_TABLE_BUF_BASE.with(|atom_table_buf_base| {
- let mut borrow = atom_table_buf_base.borrow_mut();
+ ATOM_TABLE_BUF_BASE.with(|atom_table_buf_base| {
+ let mut borrow = atom_table_buf_base.borrow_mut();
if *borrow != old_ptr {
Err(*borrow)
} else {
pub(crate) fn get_atom_tbl_buf_base() -> *const u8 {
#[cfg(test)]
{
- ATOM_TABLE_BUF_BASE.with(|atom_table_buf_base| *atom_table_buf_base.borrow())
-}
-#[cfg(not(test))]
+ ATOM_TABLE_BUF_BASE.with(|atom_table_buf_base| *atom_table_buf_base.borrow())
+ }
+ #[cfg(not(test))]
{
ATOM_TABLE_BUF_BASE.load(std::sync::atomic::Ordering::Relaxed)
}
#[bitfield]
#[derive(Copy, Clone, Debug)]
struct AtomHeader {
- #[allow(unused)] m: bool,
+ #[allow(unused)]
+ m: bool,
len: B50,
- #[allow(unused)] padding: B13,
+ #[allow(unused)]
+ padding: B13,
}
impl AtomHeader {
if self.is_static() {
ptr::null()
} else {
- (get_atom_tbl_buf_base() as usize + (self.index as usize) - (STRINGS.len() << 3)) as *const u8
+ (get_atom_tbl_buf_base() as usize + (self.index as usize) - (STRINGS.len() << 3))
+ as *const u8
}
}
let c1 = it.next();
let c2 = it.next();
- if c2.is_none() { c1 } else { None }
+ if c2.is_none() {
+ c1
+ } else {
+ None
+ }
}
#[inline]
#[inline(always)]
fn lookup_str(&self, string: &str) -> Option<Atom> {
- STATIC_ATOMS_MAP.get(string).or_else(|| self.table.get(string)).cloned()
+ STATIC_ATOMS_MAP
+ .get(string)
+ .or_else(|| self.table.get(string))
+ .cloned()
}
pub fn build_with(&mut self, string: &str) -> Atom {
pub struct AtomCell {
name: B46,
arity: B10,
- #[allow(unused)] f: bool,
- #[allow(unused)] m: bool,
- #[allow(unused)] tag: B6,
+ #[allow(unused)]
+ f: bool,
+ #[allow(unused)]
+ m: bool,
+ #[allow(unused)]
+ tag: B6,
}
impl AtomCell {
fn main() -> std::process::ExitCode {
- use std::sync::atomic::Ordering;
use scryer_prolog::*;
+ use std::sync::atomic::Ordering;
#[cfg(feature = "repl")]
ctrlc::set_handler(move || {
scryer_prolog::machine::INTERRUPT.store(true, Ordering::Relaxed);
- }).unwrap();
+ })
+ .unwrap();
let mut wam = machine::Machine::new();
wam.run_top_level()
-use crate::atom_table::*;
-use crate::parser::ast::*;
-use crate::temp_v;
use crate::allocator::*;
use crate::arithmetic::*;
+use crate::atom_table::*;
use crate::debray_allocator::*;
use crate::forms::*;
use crate::indexing::*;
use crate::instructions::*;
use crate::iterators::*;
+use crate::parser::ast::*;
use crate::targets::*;
+use crate::temp_v;
use crate::types::*;
use crate::instr;
}
fn code<'a>(&'a mut self, default_code: &'a mut CodeDeque) -> &'a mut CodeDeque {
- self.stack.last_mut()
+ self.stack
+ .last_mut()
.and_then(|stack| stack.last_mut())
.unwrap_or(default_code)
}
- fn push_missing_vars(&mut self, depth: usize, marker: &mut DebrayAllocator) -> SubsumedBranchHits {
+ fn push_missing_vars(
+ &mut self,
+ depth: usize,
+ marker: &mut DebrayAllocator,
+ ) -> SubsumedBranchHits {
let mut subsumed_hits = SubsumedBranchHits::with_hasher(FxBuildHasher::default());
- for idx in (self.stack.len() - depth .. self.stack.len()).rev() {
+ for idx in (self.stack.len() - depth..self.stack.len()).rev() {
let branch = &mut marker.branch_stack[idx];
let branch_hits = &branch.hits;
fn push_jump_instrs(&mut self, depth: usize) {
// add 2 in each arm length to compensate for each jump
// instruction and each branch instruction not yet added.
- let mut jump_span: usize = self.stack[self.stack.len() - depth ..]
+ let mut jump_span: usize = self.stack[self.stack.len() - depth..]
.iter()
.map(|branch| branch.iter().map(|code| code.len() + 2).sum::<usize>())
.sum();
jump_span -= depth;
- for idx in self.stack.len() - depth .. self.stack.len() {
+ for idx in self.stack.len() - depth..self.stack.len() {
let inner_len = self.stack[idx].len();
for (inner_idx, code) in self.stack[idx].iter_mut().enumerate() {
fn pop_branch(&mut self, depth: usize, settings: CodeGenSettings) -> CodeDeque {
let mut combined_code = CodeDeque::new();
- for mut branch_arm in self.stack.drain(self.stack.len() - depth ..).rev() {
+ for mut branch_arm in self.stack.drain(self.stack.len() - depth..).rev() {
let num_branch_arms = branch_arm.len();
- branch_arm.last_mut().map(|code| code.extend(combined_code.drain(..)));
+ branch_arm
+ .last_mut()
+ .map(|code| code.extend(combined_code.drain(..)));
for (idx, code) in branch_arm.into_iter().enumerate() {
combined_code.push_back(if idx == 0 {
vr: &Cell<VarReg>,
code: &mut CodeDeque,
) -> RegType {
- self.mark_var::<QueryInstruction>(
- var_num,
- Level::Shallow,
- vr,
- term_loc,
- code,
- );
+ self.mark_var::<QueryInstruction>(var_num, Level::Shallow, vr, term_loc, code);
vr.get().norm()
}
// decrement the arity of the PutStructure instruction by 1.
fn trim_structure_by_last_arg(instr: &mut Instruction, last_arg: &Term) {
match instr {
- Instruction::PutStructure(_, ref mut arity, _) |
- Instruction::GetStructure(.., ref mut arity, _) => {
+ Instruction::PutStructure(_, ref mut arity, _)
+ | Instruction::GetStructure(.., ref mut arity, _) => {
if let Term::Literal(_, Literal::CodeIndex(_)) = last_arg {
// it is acceptable if arity == 0 is the result of
// this decrement. call/N will have to read the index
fn structure_cell(term: &Term) -> Option<&Cell<RegType>> {
match term {
- &Term::Cons(ref cell, ..) |
- &Term::Clause(ref cell, ..) |
- Term::PartialString(ref cell, ..) |
- Term::CompleteString(ref cell, ..) => Some(cell),
+ &Term::Cons(ref cell, ..)
+ | &Term::Clause(ref cell, ..)
+ | Term::PartialString(ref cell, ..)
+ | Term::CompleteString(ref cell, ..) => Some(cell),
_ => None,
}
}
target: &mut CodeDeque,
) {
if self.marker.var_data.records[var_num].num_occurrences > 1 {
- self.marker.mark_var::<Target>(var_num, Level::Deep, cell, term_loc, target);
+ self.marker
+ .mark_var::<Target>(var_num, Level::Deep, cell, term_loc, target);
} else {
Self::add_or_increment_void_instr::<Target>(target);
}
&Term::AnonVar => {
Self::add_or_increment_void_instr::<Target>(target);
}
- &Term::Cons(ref cell, ..) |
- &Term::Clause(ref cell, ..) |
- Term::PartialString(ref cell, ..) |
- Term::CompleteString(ref cell, ..) => {
- self.marker.mark_non_var::<Target>(Level::Deep, term_loc, cell, target);
+ &Term::Cons(ref cell, ..)
+ | &Term::Clause(ref cell, ..)
+ | Term::PartialString(ref cell, ..)
+ | Term::CompleteString(ref cell, ..) => {
+ self.marker
+ .mark_non_var::<Target>(Level::Deep, term_loc, cell, target);
target.push_back(Target::clause_arg_to_instr(cell.get()));
}
&Term::Literal(_, ref constant) => {
target.push_back(Target::constant_subterm(constant.clone()));
}
&Term::Var(ref cell, ref var_ptr) => {
- self.deep_var_instr::<Target>(cell, var_ptr.to_var_num().unwrap(), term_loc, target);
+ self.deep_var_instr::<Target>(
+ cell,
+ var_ptr.to_var_num().unwrap(),
+ term_loc,
+ target,
+ );
}
};
}
- fn compile_target<'a, Target, Iter>(
- &mut self,
- iter: Iter,
- term_loc: GenContext,
- ) -> CodeDeque
+ fn compile_target<'a, Target, Iter>(&mut self, iter: Iter, term_loc: GenContext) -> CodeDeque
where
Target: crate::targets::CompilationTarget<'a>,
Iter: Iterator<Item = TermRef<'a>>,
- CodeGenerator<'b>: AddToFreeList<'a, Target>
+ CodeGenerator<'b>: AddToFreeList<'a, Target>,
{
let mut target = CodeDeque::new();
if let GenContext::Head = term_loc {
self.marker.advance_arg();
} else {
- self.marker.mark_anon_var::<Target>(lvl, term_loc, &mut target);
+ self.marker
+ .mark_anon_var::<Target>(lvl, term_loc, &mut target);
}
}
TermRef::Clause(lvl, cell, name, terms) => {
- self.marker.mark_non_var::<Target>(lvl, term_loc, cell, &mut target);
+ self.marker
+ .mark_non_var::<Target>(lvl, term_loc, cell, &mut target);
target.push_back(Target::to_structure(lvl, name, terms.len(), cell.get()));
- <CodeGenerator<'b> as AddToFreeList<'a, Target>>::add_term_to_free_list(self, cell.get());
+ <CodeGenerator<'b> as AddToFreeList<'a, Target>>::add_term_to_free_list(
+ self,
+ cell.get(),
+ );
if let Some(instr) = target.back_mut() {
if let Some(term) = terms.last() {
}
for subterm in terms {
- <CodeGenerator<'b> as AddToFreeList<'a, Target>>::add_subterm_to_free_list(self, subterm);
+ <CodeGenerator<'b> as AddToFreeList<'a, Target>>::add_subterm_to_free_list(
+ self, subterm,
+ );
}
}
TermRef::Cons(lvl, cell, head, tail) => {
- self.marker.mark_non_var::<Target>(lvl, term_loc, cell, &mut target);
+ self.marker
+ .mark_non_var::<Target>(lvl, term_loc, cell, &mut target);
target.push_back(Target::to_list(lvl, cell.get()));
- <CodeGenerator<'b> as AddToFreeList<'a, Target>>::add_term_to_free_list(self, cell.get());
+ <CodeGenerator<'b> as AddToFreeList<'a, Target>>::add_term_to_free_list(
+ self,
+ cell.get(),
+ );
self.subterm_to_instr::<Target>(head, term_loc, &mut target);
self.subterm_to_instr::<Target>(tail, term_loc, &mut target);
- <CodeGenerator<'b> as AddToFreeList<'a, Target>>::add_subterm_to_free_list(self, head);
- <CodeGenerator<'b> as AddToFreeList<'a, Target>>::add_subterm_to_free_list(self, tail);
+ <CodeGenerator<'b> as AddToFreeList<'a, Target>>::add_subterm_to_free_list(
+ self, head,
+ );
+ <CodeGenerator<'b> as AddToFreeList<'a, Target>>::add_subterm_to_free_list(
+ self, tail,
+ );
}
TermRef::Literal(lvl @ Level::Shallow, cell, Literal::String(ref string)) => {
- self.marker.mark_non_var::<Target>(lvl, term_loc, cell, &mut target);
+ self.marker
+ .mark_non_var::<Target>(lvl, term_loc, cell, &mut target);
target.push_back(Target::to_pstr(lvl, *string, cell.get(), false));
}
TermRef::Literal(lvl @ Level::Shallow, cell, constant) => {
- self.marker.mark_non_var::<Target>(lvl, term_loc, cell, &mut target);
+ self.marker
+ .mark_non_var::<Target>(lvl, term_loc, cell, &mut target);
target.push_back(Target::to_constant(lvl, *constant, cell.get()));
}
TermRef::PartialString(lvl, cell, string, tail) => {
- self.marker.mark_non_var::<Target>(lvl, term_loc, cell, &mut target);
+ self.marker
+ .mark_non_var::<Target>(lvl, term_loc, cell, &mut target);
let atom = self.atom_tbl.build_with(&string);
target.push_back(Target::to_pstr(lvl, atom, cell.get(), true));
self.subterm_to_instr::<Target>(tail, term_loc, &mut target);
}
TermRef::CompleteString(lvl, cell, atom) => {
- self.marker.mark_non_var::<Target>(lvl, term_loc, cell, &mut target);
+ self.marker
+ .mark_non_var::<Target>(lvl, term_loc, cell, &mut target);
target.push_back(Target::to_pstr(lvl, atom, cell.get(), false));
}
TermRef::Var(lvl @ Level::Shallow, cell, var) => {
compare_number_instr!(cmp, at_1, at_2)
}
&InlinedClauseType::IsAtom(..) => match &terms[0] {
- &Term::Literal(_, Literal::Char(_)) |
- &Term::Literal(_, Literal::Atom(atom!("[]"))) |
- &Term::Literal(_, Literal::Atom(..)) => {
+ &Term::Literal(_, Literal::Char(_))
+ | &Term::Literal(_, Literal::Atom(atom!("[]")))
+ | &Term::Literal(_, Literal::Atom(..)) => {
instr!("$succeed")
}
&Term::Var(ref vr, ref name) => {
}
},
&InlinedClauseType::IsAtomic(..) => match &terms[0] {
- &Term::AnonVar |
- &Term::Clause(..) |
- &Term::Cons(..) |
- &Term::PartialString(..) |
- &Term::CompleteString(..) => {
+ &Term::AnonVar
+ | &Term::Clause(..)
+ | &Term::Cons(..)
+ | &Term::PartialString(..)
+ | &Term::CompleteString(..) => {
instr!("$fail")
}
&Term::Literal(_, Literal::String(_)) => {
}
},
&InlinedClauseType::IsCompound(..) => match &terms[0] {
- &Term::Clause(..) |
- &Term::Cons(..) |
- &Term::PartialString(..) |
- &Term::CompleteString(..) |
- &Term::Literal(_, Literal::String(..)) => {
+ &Term::Clause(..)
+ | &Term::Cons(..)
+ | &Term::PartialString(..)
+ | &Term::CompleteString(..)
+ | &Term::Literal(_, Literal::String(..)) => {
instr!("$succeed")
}
&Term::Var(ref vr, ref name) => {
}
&Term::Var(ref vr, ref name) => {
self.marker.reset_arg(1);
- let r = self.marker.mark_non_callable(name.to_var_num().unwrap(), 1, term_loc, vr, code);
+ let r = self.marker.mark_non_callable(
+ name.to_var_num().unwrap(),
+ 1,
+ term_loc,
+ vr,
+ code,
+ );
instr!("rational", r)
}
_ => {
}
},
&InlinedClauseType::IsNumber(..) => match &terms[0] {
- &Term::Literal(_, Literal::Float(_)) |
- &Term::Literal(_, Literal::Rational(_)) |
- &Term::Literal(_, Literal::Integer(_)) |
- &Term::Literal(_, Literal::Fixnum(_)) => {
+ &Term::Literal(_, Literal::Float(_))
+ | &Term::Literal(_, Literal::Rational(_))
+ | &Term::Literal(_, Literal::Integer(_))
+ | &Term::Literal(_, Literal::Fixnum(_)) => {
instr!("$succeed")
}
&Term::Var(ref vr, ref name) => {
}
},
&InlinedClauseType::IsInteger(..) => match &terms[0] {
- &Term::Literal(_, Literal::Integer(_)) |
- &Term::Literal(_, Literal::Fixnum(_)) => {
+ &Term::Literal(_, Literal::Integer(_)) | &Term::Literal(_, Literal::Fixnum(_)) => {
instr!("$succeed")
}
&Term::Var(ref vr, ref name) => {
}
},
&InlinedClauseType::IsVar(..) => match &terms[0] {
- &Term::Literal(..) |
- &Term::Clause(..) |
- &Term::Cons(..) |
- &Term::PartialString(..) |
- &Term::CompleteString(..) => {
+ &Term::Literal(..)
+ | &Term::Clause(..)
+ | &Term::Cons(..)
+ | &Term::PartialString(..)
+ | &Term::CompleteString(..) => {
instr!("$fail")
}
&Term::AnonVar => {
call_policy: CallPolicy,
) -> Result<(), CompilationError> {
macro_rules! compile_expr {
- ($self:expr, $terms:expr, $term_loc:expr, $code:expr) => ({
+ ($self:expr, $terms:expr, $term_loc:expr, $code:expr) => {{
let (acode, at) = $self.compile_arith_expr($terms, 1, $term_loc, 2)?;
$code.extend(acode.into_iter());
at
- });
+ }};
}
self.marker.reset_arg(2);
compile_expr!(self, &terms[1], term_loc, code)
}
}
- &Term::Literal(_, c @ Literal::Integer(_) |
- c @ Literal::Float(_) |
- c @ Literal::Rational(_) |
- c @ Literal::Fixnum(_)) => {
+ &Term::Literal(
+ _,
+ c @ Literal::Integer(_)
+ | c @ Literal::Float(_)
+ | c @ Literal::Rational(_)
+ | c @ Literal::Fixnum(_),
+ ) => {
let v = HeapCellValue::from(c);
code.push_back(instr!("put_constant", Level::Shallow, v, temp_v!(1)));
ClauseType::BuiltIn(BuiltInClauseType::Is(..)),
ref terms,
call_policy,
- ) => self.compile_is_call(terms, branch_code_stack.code(code), term_loc, call_policy)?,
+ ) => self.compile_is_call(
+ terms,
+ branch_code_stack.code(code),
+ term_loc,
+ call_policy,
+ )?,
&QueryTerm::Clause(_, ClauseType::Inlined(ref ct), ref terms, _) => {
- self.compile_inlined(ct, terms, term_loc, branch_code_stack.code(code))?
+ self.compile_inlined(
+ ct,
+ terms,
+ term_loc,
+ branch_code_stack.code(code),
+ )?
}
&QueryTerm::Fail => {
branch_code_stack.code(code).push_back(instr!("$fail"));
}
term @ &QueryTerm::Clause(..) => {
- self.compile_query_line(term, term_loc, branch_code_stack.code(code));
+ self.compile_query_line(
+ term,
+ term_loc,
+ branch_code_stack.code(code),
+ );
if self.marker.max_reg_allocated() > MAX_ARITY {
return Err(CompilationError::ExceededMaxArity);
}
ClauseItem::BranchEnd(depth) => {
if !clause_iter.in_tail_position() {
- let subsumed_hits = branch_code_stack.push_missing_vars(depth, &mut self.marker);
+ let subsumed_hits =
+ branch_code_stack.push_missing_vars(depth, &mut self.marker);
self.marker.pop_branch(depth, subsumed_hits);
branch_code_stack.push_jump_instrs(depth);
} else {
Ok(())
}
- pub(crate) fn compile_rule(&mut self, rule: &Rule, var_data: VarData) -> Result<Code, CompilationError> {
- let Rule { head: (_, args), clauses } = rule;
+ pub(crate) fn compile_rule(
+ &mut self,
+ rule: &Rule,
+ var_data: VarData,
+ ) -> Result<Code, CompilationError> {
+ let Rule {
+ head: (_, args),
+ clauses,
+ } = rule;
self.marker.var_data = var_data;
let mut code = VecDeque::new();
Ok(Vec::from(code))
}
- pub(crate) fn compile_fact(&mut self, fact: &Fact, var_data: VarData) -> Result<Code, CompilationError> {
+ pub(crate) fn compile_fact(
+ &mut self,
+ fact: &Fact,
+ var_data: VarData,
+ ) -> Result<Code, CompilationError> {
let mut code = Vec::new();
self.marker.var_data = var_data;
self.marker.reset_at_head(args);
let iter = FactInstruction::iter(&fact.head);
- let compiled_fact = self.compile_target::<FactInstruction, _>(
- iter,
- GenContext::Head,
- );
+ let compiled_fact = self.compile_target::<FactInstruction, _>(iter, GenContext::Head);
if self.marker.max_reg_allocated() > MAX_ARITY {
return Err(CompilationError::ExceededMaxArity);
&QueryTerm::Clause(_, ref ct, _, call_policy) => {
self.add_call(code, ct.to_instr(), call_policy);
}
- _ => unreachable!()
+ _ => unreachable!(),
};
}
if let Some(args) = clause.args() {
for (instantiated_arg_index, arg) in args.iter().enumerate() {
match arg {
- Term::Var(..) | Term::AnonVar => {
- }
+ Term::Var(..) | Term::AnonVar => {}
_ => {
if optimal_index != instantiated_arg_index {
if left >= right {
}
if left < right {
- subseqs.push(ClauseSpan { left, right, instantiated_arg_index: optimal_index });
+ subseqs.push(ClauseSpan {
+ left,
+ right,
+ instantiated_arg_index: optimal_index,
+ });
}
optimal_index = 0;
optimal_index: usize,
) -> Result<Code, CompilationError> {
let mut code = VecDeque::new();
- let mut code_offsets = CodeOffsets::new(
- I::new(),
- optimal_index + 1,
- self.settings.non_counted_bt,
- );
+ let mut code_offsets =
+ CodeOffsets::new(I::new(), optimal_index + 1, self.settings.non_counted_bt);
let mut skip_stub_try_me_else = false;
let clauses_len = clauses.len();
skip_stub_try_me_else = !self.settings.is_dynamic();
}
- let arg = clause.args().and_then(|args| args.iter().nth(optimal_index));
+ let arg = clause
+ .args()
+ .and_then(|args| args.iter().nth(optimal_index));
if let Some(arg) = arg {
let index = code.len();
let split_pred = Self::split_predicate(&clauses);
let multi_seq = split_pred.len() > 1;
- for ClauseSpan { left, right, instantiated_arg_index } in split_pred {
+ for ClauseSpan {
+ left,
+ right,
+ instantiated_arg_index,
+ } in split_pred
+ {
let skel_lower_bound = self.skeleton.clauses.len();
let code_segment = if self.settings.is_dynamic() {
self.compile_pred_subseq::<DynamicCodeIndices>(
if self.settings.is_extensible {
let segment_is_indexed = code_segment[0].to_indexing_line().is_some();
- for clause_index_info in self.skeleton.clauses
- .make_contiguous()[skel_lower_bound..]
- .iter_mut()
+ for clause_index_info in
+ self.skeleton.clauses.make_contiguous()[skel_lower_bound..].iter_mut()
{
clause_index_info.clause_start +=
clause_start_offset + 2 * (segment_is_indexed as usize);
}
}
- fn safety_unneeded_in_branch(&self, safety: &VarSafetyStatus, branch: &BranchDesignator) -> bool {
+ fn safety_unneeded_in_branch(
+ &self,
+ safety: &VarSafetyStatus,
+ branch: &BranchDesignator,
+ ) -> bool {
match safety {
VarSafetyStatus::Needed => false,
- VarSafetyStatus::LocallyUnneeded(planter_branch) =>
- self.branch_subsumes(planter_branch, branch),
+ VarSafetyStatus::LocallyUnneeded(planter_branch) => {
+ self.branch_subsumes(planter_branch, branch)
+ }
VarSafetyStatus::GloballyUnneeded => true,
}
}
let num_branches = occurrences.num_branches;
- let entry = occurrences.hits.entry(var_num)
+ let entry = occurrences
+ .hits
+ .entry(var_num)
.or_insert_with(|| BitVec::repeat(false, num_branches));
entry.set(occurrences.current_branch, true);
pub(crate) fn current_branch_designator(&self) -> BranchDesignator {
let branch_stack_num = self.len();
- let branch_num = self.last()
+ let branch_num = self
+ .last()
.map(|occurrences| occurrences.current_branch)
.unwrap_or(0);
- BranchDesignator { branch_stack_num, branch_num }
+ BranchDesignator {
+ branch_stack_num,
+ branch_num,
+ }
}
#[inline]
#[inline]
pub(crate) fn drain_branches(&mut self, depth: usize) -> std::vec::Drain<BranchOccurrences> {
let start_idx = self.len() - depth;
- self.drain(start_idx ..)
+ self.drain(start_idx..)
}
}
match &mut self.var_data.records[var_num].allocation {
VarAlloc::Perm(_, ref mut allocation) => {
match allocation {
- PermVarAllocation::Done { shallow_safety, deep_safety, .. } => {
- if !self.branch_stack.safety_unneeded_in_branch(shallow_safety, &branch_designator) {
+ PermVarAllocation::Done {
+ shallow_safety,
+ deep_safety,
+ ..
+ } => {
+ if !self
+ .branch_stack
+ .safety_unneeded_in_branch(shallow_safety, &branch_designator)
+ {
let branch_occurrences = self.branch_stack.last_mut().unwrap();
branch_occurrences.shallow_safety.insert(var_num);
}
- if !self.branch_stack.safety_unneeded_in_branch(deep_safety, &branch_designator) {
+ if !self
+ .branch_stack
+ .safety_unneeded_in_branch(deep_safety, &branch_designator)
+ {
let branch_occurrences = self.branch_stack.last_mut().unwrap();
branch_occurrences.deep_safety.insert(var_num);
}
pub(crate) fn pop_branch(&mut self, depth: usize, subsumed_hits: SubsumedBranchHits) {
let removed_branches = self.branch_stack.drain_branches(depth);
- let (deep_safety, shallow_safety) = removed_branches
- .into_iter()
- .fold((BitSet::default(), BitSet::default()),
- |(mut deep_safety, mut shallow_safety), branch_occurrences| {
- deep_safety.union_with(&branch_occurrences.deep_safety);
- shallow_safety.union_with(&branch_occurrences.shallow_safety);
+ let (deep_safety, shallow_safety) = removed_branches.into_iter().fold(
+ (BitSet::default(), BitSet::default()),
+ |(mut deep_safety, mut shallow_safety), branch_occurrences| {
+ deep_safety.union_with(&branch_occurrences.deep_safety);
+ shallow_safety.union_with(&branch_occurrences.shallow_safety);
- (deep_safety, shallow_safety)
- });
+ (deep_safety, shallow_safety)
+ },
+ );
let branch_designator = self.branch_stack.current_branch_designator();
(&latest_branch.deep_safety, &latest_branch.shallow_safety)
}
- None => (&deep_safety, &shallow_safety)
+ None => (&deep_safety, &shallow_safety),
};
for var_num in subsumed_hits.iter().cloned() {
);
if running_count < num_occurrences {
- *allocation = PermVarAllocation::Done { shallow_safety, deep_safety };
+ *allocation = PermVarAllocation::Done {
+ shallow_safety,
+ deep_safety,
+ };
}
}
- _ => unreachable!()
+ _ => unreachable!(),
}
}
fn occurs_shallowly_in_head(&self, var_num: usize, r: usize) -> bool {
match &self.var_data.records[var_num].allocation {
- VarAlloc::Temp { temp_var_data, term_loc: GenContext::Head, .. } => {
- temp_var_data.use_set.contains(&(GenContext::Head, r))
- }
+ VarAlloc::Temp {
+ temp_var_data,
+ term_loc: GenContext::Head,
+ ..
+ } => temp_var_data.use_set.contains(&(GenContext::Head, r)),
_ => false,
}
}
match &self.var_data.records[t_var].allocation {
VarAlloc::Temp { temp_var_data, .. } => {
- if !temp_var_data.use_set.contains(&(GenContext::Last(chunk_num), k)) {
+ if !temp_var_data
+ .use_set
+ .contains(&(GenContext::Last(chunk_num), k))
+ {
return Some((t_var, self.alloc_with_ca(t_var)));
}
}
- _ => {
- }
+ _ => {}
}
None
self.shallow_temp_mappings.swap_remove(&k);
self.shallow_temp_mappings.insert(r.reg_num(), var_num);
- self.var_data.records[var_num].allocation.set_register(r.reg_num());
+ self.var_data.records[var_num]
+ .allocation
+ .set_register(r.reg_num());
self.in_use.insert(r.reg_num());
}
}
fn in_place(&self, var_num: usize, term_loc: GenContext, r: RegType, k: usize) -> bool {
match term_loc {
GenContext::Head if !r.is_perm() => r.reg_num() == k,
- _ => {
- match &self.var_data.records[var_num].allocation {
- &VarAlloc::Temp { temp_reg, .. } if r.reg_num() == k =>
- temp_reg == k,
- _ => false,
- }
+ _ => match &self.var_data.records[var_num].allocation {
+ &VarAlloc::Temp { temp_reg, .. } if r.reg_num() == k => temp_reg == k,
+ _ => false,
},
}
}
VarAlloc::Perm(p, PermVarAllocation::Pending) if *p > 0 => {
return Some(std::mem::replace(p, 0));
}
- _ => {
- }
+ _ => {}
}
} else {
return None;
*allocation = PermVarAllocation::Pending;
self.add_perm_to_free_list(chunk_num, var_num);
}
- _ => {
- }
+ _ => {}
}
}
let branch_designator = self.branch_stack.current_branch_designator();
match &mut self.var_data.records[var_num].allocation {
- VarAlloc::Perm(_, PermVarAllocation::Done { deep_safety, shallow_safety, .. }) => {
+ VarAlloc::Perm(
+ _,
+ PermVarAllocation::Done {
+ deep_safety,
+ shallow_safety,
+ ..
+ },
+ ) => {
*deep_safety = VarSafetyStatus::unneeded(branch_designator);
*shallow_safety = VarSafetyStatus::unneeded(branch_designator);
}
let branch_designator = self.branch_stack.current_branch_designator();
match &mut self.var_data.records[var_num].allocation {
- VarAlloc::Perm(_, PermVarAllocation::Done { deep_safety, shallow_safety, .. }) => {
+ VarAlloc::Perm(
+ _,
+ PermVarAllocation::Done {
+ deep_safety,
+ shallow_safety,
+ ..
+ },
+ ) => {
// GetVariable in head chunk is considered safe.
if lvl == Level::Deep {
*deep_safety = VarSafetyStatus::unneeded(branch_designator);
} else if term_loc == GenContext::Head {
*shallow_safety = VarSafetyStatus::GloballyUnneeded;
} else {
- if let Some(temp_var_num) = self.shallow_temp_mappings.get(&self.arg_c).cloned() {
+ if let Some(temp_var_num) = self.shallow_temp_mappings.get(&self.arg_c).cloned()
+ {
match &mut self.var_data.records[temp_var_num].allocation {
- VarAlloc::Temp { ref mut to_perm_var_num, .. } => {
+ VarAlloc::Temp {
+ ref mut to_perm_var_num,
+ ..
+ } => {
*to_perm_var_num = Some(var_num);
}
- _ => unreachable!()
+ _ => unreachable!(),
}
}
}
let branch_designator = self.branch_stack.current_branch_designator();
match &mut self.var_data.records[var_num].allocation {
- VarAlloc::Perm(_, PermVarAllocation::Done { ref mut shallow_safety, .. }) => {
- if !self.in_tail_position || self.branch_stack.safety_unneeded_in_branch(shallow_safety, &branch_designator) {
+ VarAlloc::Perm(
+ _,
+ PermVarAllocation::Done {
+ ref mut shallow_safety,
+ ..
+ },
+ ) => {
+ if !self.in_tail_position
+ || self
+ .branch_stack
+ .safety_unneeded_in_branch(shallow_safety, &branch_designator)
+ {
Target::argument_to_value(r, arg_c)
} else {
*shallow_safety = VarSafetyStatus::unneeded(branch_designator);
}
}
VarAlloc::Temp { ref mut safety, .. } => {
- if self.branch_stack.safety_unneeded_in_branch(safety, &branch_designator) {
+ if self
+ .branch_stack
+ .safety_unneeded_in_branch(safety, &branch_designator)
+ {
Target::argument_to_value(r, arg_c)
} else {
*safety = VarSafetyStatus::GloballyUnneeded;
let branch_designator = self.branch_stack.current_branch_designator();
match &mut self.var_data.records[var_num].allocation {
- VarAlloc::Perm(_, PermVarAllocation::Done { ref mut deep_safety, .. }) => {
- if self.branch_stack.safety_unneeded_in_branch(deep_safety, &branch_designator) {
+ VarAlloc::Perm(
+ _,
+ PermVarAllocation::Done {
+ ref mut deep_safety,
+ ..
+ },
+ ) => {
+ if self
+ .branch_stack
+ .safety_unneeded_in_branch(deep_safety, &branch_designator)
+ {
Target::subterm_to_value(r)
} else {
*deep_safety = VarSafetyStatus::unneeded(branch_designator);
}
}
VarAlloc::Temp { ref mut safety, .. } => {
- if self.branch_stack.safety_unneeded_in_branch(safety, &branch_designator) {
+ if self
+ .branch_stack
+ .safety_unneeded_in_branch(safety, &branch_designator)
+ {
Target::subterm_to_value(r)
} else {
*safety = VarSafetyStatus::unneeded(branch_designator);
in_use: BitSet::default(),
temp_free_list: vec![],
perm_free_list: VecDeque::new(),
- branch_stack: BranchStack { stack: vec![] }
+ branch_stack: BranchStack { stack: vec![] },
}
}
}
r @ RegType::Perm(_) => {
let is_new_var = match &mut self.var_data.records[var_num].allocation {
- VarAlloc::Perm(_, allocation) => if allocation.pending() {
- *allocation = PermVarAllocation::done();
- true
- } else {
- false
- },
+ VarAlloc::Perm(_, allocation) => {
+ if allocation.pending() {
+ *allocation = PermVarAllocation::done();
+ true
+ } else {
+ false
+ }
+ }
_ => unreachable!(),
};
if !r.is_perm() && r.reg_num() == 0 {
self.in_use.insert(idx + 1);
self.shallow_temp_mappings.insert(idx + 1, var_num);
- self.var_data.records[var_num].allocation.set_register(idx + 1);
+ self.var_data.records[var_num]
+ .allocation
+ .set_register(idx + 1);
}
}
}
use std::alloc::{alloc, Layout};
use std::any::Any;
use std::collections::HashMap;
-use std::error::Error;
-use std::ffi::{CString, c_void};
use std::convert::TryFrom;
+use std::error::Error;
+use std::ffi::{c_void, CString};
-use libffi::low::{ffi_cif, types, CodePtr, ffi_abi_FFI_DEFAULT_ABI, prep_cif, ffi_type, type_tag};
-use libloading::{Symbol, Library};
+use libffi::low::{ffi_abi_FFI_DEFAULT_ABI, ffi_cif, ffi_type, prep_cif, type_tag, types, CodePtr};
+use libloading::{Library, Symbol};
pub struct FunctionDefinition {
pub name: String,
impl ForeignFunctionTable {
pub fn merge(&mut self, other: ForeignFunctionTable) {
- self.table.extend(other.table);
+ self.table.extend(other.table);
}
pub fn define_struct(&mut self, name: &str, atom_fields: Vec<Atom>) {
- let mut fields: Vec<_> = atom_fields.iter().map(|x| self.map_type_ffi(&x)).collect();
- fields.push(std::ptr::null_mut::<ffi_type>());
- let mut struct_type: ffi_type = Default::default();
- struct_type.type_ = type_tag::STRUCT;
- struct_type.elements = fields.as_mut_ptr();
- self.structs.insert(name.to_string(), StructImpl { ffi_type: struct_type, fields, atom_fields});
+ let mut fields: Vec<_> = atom_fields.iter().map(|x| self.map_type_ffi(&x)).collect();
+ fields.push(std::ptr::null_mut::<ffi_type>());
+ let mut struct_type: ffi_type = Default::default();
+ struct_type.type_ = type_tag::STRUCT;
+ struct_type.elements = fields.as_mut_ptr();
+ self.structs.insert(
+ name.to_string(),
+ StructImpl {
+ ffi_type: struct_type,
+ fields,
+ atom_fields,
+ },
+ );
}
fn map_type_ffi(&mut self, source: &Atom) -> *mut ffi_type {
- unsafe {
- match source {
- atom!("sint64") => &mut types::sint64,
- atom!("sint32") => &mut types::sint32,
- atom!("sint16") => &mut types::sint16,
- atom!("sint8") => &mut types::sint8,
- atom!("uint64") => &mut types::uint64,
- atom!("uint32") => &mut types::uint32,
- atom!("uint16") => &mut types::uint16,
- atom!("uint8") => &mut types::uint8,
- atom!("bool") => &mut types::sint8,
- atom!("void") => &mut types::void,
- atom!("cstr") => &mut types::pointer,
- atom!("ptr") => &mut types::pointer,
- atom!("f32") => &mut types::float,
- atom!("f64") => &mut types::double,
- struct_name => {
- match self.structs.get_mut(struct_name.as_str()) {
- Some(ref mut struct_type) => {
- &mut struct_type.ffi_type
- },
- None => unreachable!()
- }
- }
- }
- }
+ unsafe {
+ match source {
+ atom!("sint64") => &mut types::sint64,
+ atom!("sint32") => &mut types::sint32,
+ atom!("sint16") => &mut types::sint16,
+ atom!("sint8") => &mut types::sint8,
+ atom!("uint64") => &mut types::uint64,
+ atom!("uint32") => &mut types::uint32,
+ atom!("uint16") => &mut types::uint16,
+ atom!("uint8") => &mut types::uint8,
+ atom!("bool") => &mut types::sint8,
+ atom!("void") => &mut types::void,
+ atom!("cstr") => &mut types::pointer,
+ atom!("ptr") => &mut types::pointer,
+ atom!("f32") => &mut types::float,
+ atom!("f64") => &mut types::double,
+ struct_name => match self.structs.get_mut(struct_name.as_str()) {
+ Some(ref mut struct_type) => &mut struct_type.ffi_type,
+ None => unreachable!(),
+ },
+ }
+ }
}
- pub(crate) fn load_library(&mut self, library_name: &str, functions: &Vec<FunctionDefinition>) -> Result<(), Box<dyn Error>> {
- let mut ff_table: ForeignFunctionTable = Default::default();
- unsafe {
- let library = Library::new(library_name)?;
- for function in functions {
- let symbol_name: CString = CString::new(function.name.clone())?;
- let code_ptr: Symbol<*mut c_void> = library.get(&symbol_name.into_bytes_with_nul())?;
- let mut args: Vec<_> = function.args.iter().map(|x| self.map_type_ffi(&x)).collect();
- let mut cif: ffi_cif = Default::default();
- prep_cif(
- &mut cif,
- ffi_abi_FFI_DEFAULT_ABI,
- args.len(),
- self.map_type_ffi(&function.return_value),
- args.as_mut_ptr()
- ).unwrap();
-
- let return_struct_name = if (*self.map_type_ffi(&function.return_value)).type_ as u32 == libffi::raw::FFI_TYPE_STRUCT {
- Some(function.return_value.as_str().to_string())
- } else {
- None
- };
-
- ff_table.table.insert(function.name.clone(), FunctionImpl {
- cif,
- args,
- code_ptr: CodePtr(code_ptr.into_raw().into_raw() as *mut _),
- return_struct_name,
- });
- }
- std::mem::forget(library);
- }
- self.merge(ff_table);
- Ok(())
+ pub(crate) fn load_library(
+ &mut self,
+ library_name: &str,
+ functions: &Vec<FunctionDefinition>,
+ ) -> Result<(), Box<dyn Error>> {
+ let mut ff_table: ForeignFunctionTable = Default::default();
+ unsafe {
+ let library = Library::new(library_name)?;
+ for function in functions {
+ let symbol_name: CString = CString::new(function.name.clone())?;
+ let code_ptr: Symbol<*mut c_void> =
+ library.get(&symbol_name.into_bytes_with_nul())?;
+ let mut args: Vec<_> = function
+ .args
+ .iter()
+ .map(|x| self.map_type_ffi(&x))
+ .collect();
+ let mut cif: ffi_cif = Default::default();
+ prep_cif(
+ &mut cif,
+ ffi_abi_FFI_DEFAULT_ABI,
+ args.len(),
+ self.map_type_ffi(&function.return_value),
+ args.as_mut_ptr(),
+ )
+ .unwrap();
+
+ let return_struct_name = if (*self.map_type_ffi(&function.return_value)).type_
+ as u32
+ == libffi::raw::FFI_TYPE_STRUCT
+ {
+ Some(function.return_value.as_str().to_string())
+ } else {
+ None
+ };
+
+ ff_table.table.insert(
+ function.name.clone(),
+ FunctionImpl {
+ cif,
+ args,
+ code_ptr: CodePtr(code_ptr.into_raw().into_raw() as *mut _),
+ return_struct_name,
+ },
+ );
+ }
+ std::mem::forget(library);
+ }
+ self.merge(ff_table);
+ Ok(())
}
- fn build_pointer_args(args: &mut Vec<Value>, type_args: &Vec<*mut ffi_type>, structs_table: &mut HashMap<String, StructImpl>) -> Result<PointerArgs, FFIError> {
- let mut pointers = Vec::with_capacity(args.len());
- let mut _memory = Vec::new();
- for i in 0..args.len() {
- let field_type = type_args[i];
- unsafe {
- macro_rules! push_int {
- ($type:ty) => {
- {
- let n: $type = <$type>::try_from(args[i].as_int()?).map_err(|_| FFIError::ValueDontFit)?;
- let mut box_value = Box::new(n) as Box<dyn Any>;
- pointers.push(&mut *box_value as *mut _ as *mut c_void);
- _memory.push(box_value);
- }
- }
- }
-
- match (*field_type).type_ as u32 {
- libffi::raw::FFI_TYPE_UINT8 => push_int!(u8),
- libffi::raw::FFI_TYPE_SINT8 => push_int!(i8),
- libffi::raw::FFI_TYPE_UINT16 => push_int!(u16),
- libffi::raw::FFI_TYPE_SINT16 => push_int!(i16),
- libffi::raw::FFI_TYPE_UINT32 => push_int!(u32),
- libffi::raw::FFI_TYPE_SINT32 => push_int!(i32),
- libffi::raw::FFI_TYPE_UINT64 => push_int!(u64),
- libffi::raw::FFI_TYPE_SINT64 => push_int!(i64),
- libffi::raw::FFI_TYPE_FLOAT => {
- let n: f32 = args[i].as_float()? as f32;
- let mut box_value = Box::new(n) as Box<dyn Any>;
- pointers.push(&mut *box_value as *mut _ as *mut c_void);
- _memory.push(box_value);
- },
- libffi::raw::FFI_TYPE_DOUBLE => {
- let n: f64 = args[i].as_float()?;
- let mut box_value = Box::new(n) as Box<dyn Any>;
- pointers.push(&mut *box_value as *mut _ as *mut c_void);
- _memory.push(box_value);
- },
- libffi::raw::FFI_TYPE_POINTER => {
- let ptr: *mut c_void = args[i].as_ptr()?;
- pointers.push(ptr);
- },
- libffi::raw::FFI_TYPE_STRUCT => {
- let (mut ptr, _size, _align) = Self::build_struct(&mut args[i], structs_table)?;
- pointers.push(&mut *ptr as *mut _ as *mut c_void);
- _memory.push(ptr);
- },
- _ => return Err(FFIError::InvalidFFIType)
- }
- }
- }
- Ok(PointerArgs {
- pointers,
- _memory
- })
+ fn build_pointer_args(
+ args: &mut Vec<Value>,
+ type_args: &Vec<*mut ffi_type>,
+ structs_table: &mut HashMap<String, StructImpl>,
+ ) -> Result<PointerArgs, FFIError> {
+ let mut pointers = Vec::with_capacity(args.len());
+ let mut _memory = Vec::new();
+ for i in 0..args.len() {
+ let field_type = type_args[i];
+ unsafe {
+ macro_rules! push_int {
+ ($type:ty) => {{
+ let n: $type = <$type>::try_from(args[i].as_int()?)
+ .map_err(|_| FFIError::ValueDontFit)?;
+ let mut box_value = Box::new(n) as Box<dyn Any>;
+ pointers.push(&mut *box_value as *mut _ as *mut c_void);
+ _memory.push(box_value);
+ }};
+ }
+
+ match (*field_type).type_ as u32 {
+ libffi::raw::FFI_TYPE_UINT8 => push_int!(u8),
+ libffi::raw::FFI_TYPE_SINT8 => push_int!(i8),
+ libffi::raw::FFI_TYPE_UINT16 => push_int!(u16),
+ libffi::raw::FFI_TYPE_SINT16 => push_int!(i16),
+ libffi::raw::FFI_TYPE_UINT32 => push_int!(u32),
+ libffi::raw::FFI_TYPE_SINT32 => push_int!(i32),
+ libffi::raw::FFI_TYPE_UINT64 => push_int!(u64),
+ libffi::raw::FFI_TYPE_SINT64 => push_int!(i64),
+ libffi::raw::FFI_TYPE_FLOAT => {
+ let n: f32 = args[i].as_float()? as f32;
+ let mut box_value = Box::new(n) as Box<dyn Any>;
+ pointers.push(&mut *box_value as *mut _ as *mut c_void);
+ _memory.push(box_value);
+ }
+ libffi::raw::FFI_TYPE_DOUBLE => {
+ let n: f64 = args[i].as_float()?;
+ let mut box_value = Box::new(n) as Box<dyn Any>;
+ pointers.push(&mut *box_value as *mut _ as *mut c_void);
+ _memory.push(box_value);
+ }
+ libffi::raw::FFI_TYPE_POINTER => {
+ let ptr: *mut c_void = args[i].as_ptr()?;
+ pointers.push(ptr);
+ }
+ libffi::raw::FFI_TYPE_STRUCT => {
+ let (mut ptr, _size, _align) =
+ Self::build_struct(&mut args[i], structs_table)?;
+ pointers.push(&mut *ptr as *mut _ as *mut c_void);
+ _memory.push(ptr);
+ }
+ _ => return Err(FFIError::InvalidFFIType),
+ }
+ }
+ }
+ Ok(PointerArgs { pointers, _memory })
}
- fn build_struct(arg: &mut Value, structs_table: &mut HashMap<String, StructImpl>) -> Result<(Box<dyn Any>, usize, usize), FFIError> {
- unsafe {
- match arg {
- Value::Struct(ref name, ref mut struct_args) => {
- if let Some(ref mut struct_type) = structs_table.clone().get_mut(name) {
- let layout = Layout::from_size_align(struct_type.ffi_type.size, struct_type.ffi_type.alignment.into()).unwrap();
- let align = struct_type.ffi_type.alignment as usize;
- let size = struct_type.ffi_type.size;
- let ptr = alloc(layout) as *mut c_void;
- let mut field_ptr = ptr;
-
- for i in 0..(struct_type.fields.len()-1) {
- macro_rules! try_write_int {
- ($type:ty) => {
- {
- field_ptr = field_ptr.add(field_ptr.align_offset(std::mem::align_of::<$type>()));
- let n: $type = <$type>::try_from(struct_args[i].as_int()?).map_err(|_| FFIError::ValueDontFit)?;
- std::ptr::write(field_ptr as *mut $type, n);
- field_ptr = field_ptr.add(std::mem::size_of::<$type>());
- }
- }
- }
-
- macro_rules! write {
- ($type:ty, $value:expr) => {
- {
- let data: $type = $value;
- std::ptr::write(field_ptr as *mut $type, data);
- field_ptr = field_ptr.add(align);
- }
- }
- }
-
- let field = struct_type.fields[i];
- match (*field).type_ as u32 {
- libffi::raw::FFI_TYPE_UINT8 => try_write_int!(u8),
- libffi::raw::FFI_TYPE_SINT8 => try_write_int!(i8),
- libffi::raw::FFI_TYPE_UINT16 => try_write_int!(u16),
- libffi::raw::FFI_TYPE_SINT16 => try_write_int!(i16),
- libffi::raw::FFI_TYPE_UINT32 => try_write_int!(u32),
- libffi::raw::FFI_TYPE_SINT32 => try_write_int!(i32),
- libffi::raw::FFI_TYPE_UINT64 => try_write_int!(u64),
- libffi::raw::FFI_TYPE_SINT64 => try_write_int!(i64),
- libffi::raw::FFI_TYPE_POINTER => write!(*mut c_void, struct_args[i].as_ptr()?),
- libffi::raw::FFI_TYPE_FLOAT => write!(f32, struct_args[i].as_float()? as f32),
- libffi::raw::FFI_TYPE_DOUBLE => write!(f64, struct_args[i].as_float()?),
- libffi::raw::FFI_TYPE_STRUCT => {
- let (struct_ptr, struct_size, struct_align) = Self::build_struct(&mut struct_args[i], structs_table)?;
- field_ptr = field_ptr.add(field_ptr.align_offset(struct_align));
-
- std::ptr::copy(& *struct_ptr as *const _ as *const c_void, field_ptr as *mut c_void, struct_size);
- field_ptr = field_ptr.add(struct_size);
- },
- _ => {
- unreachable!()
- }
- }
- }
- return Ok((Box::from_raw(ptr), size, align));
- } else {
- return Err(FFIError::InvalidStructName);
- }
- }
- _ => return Err(FFIError::ValueCast)
- }
- }
+ fn build_struct(
+ arg: &mut Value,
+ structs_table: &mut HashMap<String, StructImpl>,
+ ) -> Result<(Box<dyn Any>, usize, usize), FFIError> {
+ unsafe {
+ match arg {
+ Value::Struct(ref name, ref mut struct_args) => {
+ if let Some(ref mut struct_type) = structs_table.clone().get_mut(name) {
+ let layout = Layout::from_size_align(
+ struct_type.ffi_type.size,
+ struct_type.ffi_type.alignment.into(),
+ )
+ .unwrap();
+ let align = struct_type.ffi_type.alignment as usize;
+ let size = struct_type.ffi_type.size;
+ let ptr = alloc(layout) as *mut c_void;
+ let mut field_ptr = ptr;
+
+ for i in 0..(struct_type.fields.len() - 1) {
+ macro_rules! try_write_int {
+ ($type:ty) => {{
+ field_ptr = field_ptr
+ .add(field_ptr.align_offset(std::mem::align_of::<$type>()));
+ let n: $type = <$type>::try_from(struct_args[i].as_int()?)
+ .map_err(|_| FFIError::ValueDontFit)?;
+ std::ptr::write(field_ptr as *mut $type, n);
+ field_ptr = field_ptr.add(std::mem::size_of::<$type>());
+ }};
+ }
+
+ macro_rules! write {
+ ($type:ty, $value:expr) => {{
+ let data: $type = $value;
+ std::ptr::write(field_ptr as *mut $type, data);
+ field_ptr = field_ptr.add(align);
+ }};
+ }
+
+ let field = struct_type.fields[i];
+ match (*field).type_ as u32 {
+ libffi::raw::FFI_TYPE_UINT8 => try_write_int!(u8),
+ libffi::raw::FFI_TYPE_SINT8 => try_write_int!(i8),
+ libffi::raw::FFI_TYPE_UINT16 => try_write_int!(u16),
+ libffi::raw::FFI_TYPE_SINT16 => try_write_int!(i16),
+ libffi::raw::FFI_TYPE_UINT32 => try_write_int!(u32),
+ libffi::raw::FFI_TYPE_SINT32 => try_write_int!(i32),
+ libffi::raw::FFI_TYPE_UINT64 => try_write_int!(u64),
+ libffi::raw::FFI_TYPE_SINT64 => try_write_int!(i64),
+ libffi::raw::FFI_TYPE_POINTER => {
+ write!(*mut c_void, struct_args[i].as_ptr()?)
+ }
+ libffi::raw::FFI_TYPE_FLOAT => {
+ write!(f32, struct_args[i].as_float()? as f32)
+ }
+ libffi::raw::FFI_TYPE_DOUBLE => {
+ write!(f64, struct_args[i].as_float()?)
+ }
+ libffi::raw::FFI_TYPE_STRUCT => {
+ let (struct_ptr, struct_size, struct_align) =
+ Self::build_struct(&mut struct_args[i], structs_table)?;
+ field_ptr = field_ptr.add(field_ptr.align_offset(struct_align));
+
+ std::ptr::copy(
+ &*struct_ptr as *const _ as *const c_void,
+ field_ptr as *mut c_void,
+ struct_size,
+ );
+ field_ptr = field_ptr.add(struct_size);
+ }
+ _ => {
+ unreachable!()
+ }
+ }
+ }
+ return Ok((Box::from_raw(ptr), size, align));
+ } else {
+ return Err(FFIError::InvalidStructName);
+ }
+ }
+ _ => return Err(FFIError::ValueCast),
+ }
+ }
}
pub fn exec(&mut self, name: &str, mut args: Vec<Value>) -> Result<Value, FFIError> {
- let function_impl = self.table.get_mut(name).ok_or(FFIError::FunctionNotFound)?;
- let mut pointer_args = Self::build_pointer_args(&mut args, &function_impl.args, &mut self.structs)?;
-
- return unsafe {
- macro_rules! call_and_return {
- ($type:ty) => {
- {
- let mut n: Box<u8> = Box::new(0);
- libffi::raw::ffi_call(
- &mut function_impl.cif,
- Some(*function_impl.code_ptr.as_safe_fun()),
- &mut *n as *mut _ as *mut c_void,
- pointer_args.pointers.as_mut_ptr() as *mut *mut c_void
- );
- Ok(Value::Int(i64::from(*n)))
- }
- }
- }
-
- match (*function_impl.cif.rtype).type_ as u32 {
- libffi::raw::FFI_TYPE_VOID => call_and_return!(i32),
- libffi::raw::FFI_TYPE_UINT8 => call_and_return!(u8),
- libffi::raw::FFI_TYPE_SINT8 => call_and_return!(i8),
- libffi::raw::FFI_TYPE_UINT16 => call_and_return!(u16),
- libffi::raw::FFI_TYPE_SINT16 => call_and_return!(i16),
- libffi::raw::FFI_TYPE_UINT32 => call_and_return!(u32),
- libffi::raw::FFI_TYPE_SINT32 => call_and_return!(i32),
- libffi::raw::FFI_TYPE_UINT64 => {
- let mut n: Box<u64> = Box::new(0);
- libffi::raw::ffi_call(
- &mut function_impl.cif,
- Some(*function_impl.code_ptr.as_safe_fun()),
- &mut *n as *mut _ as *mut c_void,
- pointer_args.pointers.as_mut_ptr() as *mut *mut c_void
- );
- Ok(Value::Int(i64::try_from(*n).map_err(|_| FFIError::ValueDontFit)?))
- },
- libffi::raw::FFI_TYPE_SINT64 => call_and_return!(i64),
- libffi::raw::FFI_TYPE_POINTER => call_and_return!(*mut c_void),
- libffi::raw::FFI_TYPE_FLOAT => {
- let mut n: Box<f32> = Box::new(0.0);
- libffi::raw::ffi_call(
- &mut function_impl.cif,
- Some(*function_impl.code_ptr.as_safe_fun()),
- &mut *n as *mut _ as *mut c_void,
- pointer_args.pointers.as_mut_ptr() as *mut *mut c_void
- );
- Ok(Value::Float((*n).into()))
- },
- libffi::raw::FFI_TYPE_DOUBLE => {
- let mut n: Box<f64> = Box::new(0.0);
- libffi::raw::ffi_call(
- &mut function_impl.cif,
- Some(*function_impl.code_ptr.as_safe_fun()),
- &mut *n as *mut _ as *mut c_void,
- pointer_args.pointers.as_mut_ptr() as *mut *mut c_void
- );
- Ok(Value::Float(*n))
- },
- libffi::raw::FFI_TYPE_STRUCT => {
- let name = &function_impl.return_struct_name.clone().ok_or(FFIError::StructNotFound)?;
- let struct_type = self.structs.get(name).ok_or(FFIError::StructNotFound)?;
- let layout = Layout::from_size_align(struct_type.ffi_type.size, struct_type.ffi_type.alignment.into()).unwrap();
- let ptr = alloc(layout) as *mut c_void;
-
- libffi::raw::ffi_call(
- &mut function_impl.cif,
- Some(*function_impl.code_ptr.as_safe_fun()),
- &mut *ptr as *mut _ as *mut c_void,
- pointer_args.pointers.as_mut_ptr() as *mut *mut c_void
- );
- let struct_val = self.read_struct(ptr, name, struct_type);
- drop(Box::from_raw(ptr));
- struct_val
- }
- _ => unreachable!()
- }
- };
+ let function_impl = self.table.get_mut(name).ok_or(FFIError::FunctionNotFound)?;
+ let mut pointer_args =
+ Self::build_pointer_args(&mut args, &function_impl.args, &mut self.structs)?;
+
+ return unsafe {
+ macro_rules! call_and_return {
+ ($type:ty) => {{
+ let mut n: Box<u8> = Box::new(0);
+ libffi::raw::ffi_call(
+ &mut function_impl.cif,
+ Some(*function_impl.code_ptr.as_safe_fun()),
+ &mut *n as *mut _ as *mut c_void,
+ pointer_args.pointers.as_mut_ptr() as *mut *mut c_void,
+ );
+ Ok(Value::Int(i64::from(*n)))
+ }};
+ }
+
+ match (*function_impl.cif.rtype).type_ as u32 {
+ libffi::raw::FFI_TYPE_VOID => call_and_return!(i32),
+ libffi::raw::FFI_TYPE_UINT8 => call_and_return!(u8),
+ libffi::raw::FFI_TYPE_SINT8 => call_and_return!(i8),
+ libffi::raw::FFI_TYPE_UINT16 => call_and_return!(u16),
+ libffi::raw::FFI_TYPE_SINT16 => call_and_return!(i16),
+ libffi::raw::FFI_TYPE_UINT32 => call_and_return!(u32),
+ libffi::raw::FFI_TYPE_SINT32 => call_and_return!(i32),
+ libffi::raw::FFI_TYPE_UINT64 => {
+ let mut n: Box<u64> = Box::new(0);
+ libffi::raw::ffi_call(
+ &mut function_impl.cif,
+ Some(*function_impl.code_ptr.as_safe_fun()),
+ &mut *n as *mut _ as *mut c_void,
+ pointer_args.pointers.as_mut_ptr() as *mut *mut c_void,
+ );
+ Ok(Value::Int(
+ i64::try_from(*n).map_err(|_| FFIError::ValueDontFit)?,
+ ))
+ }
+ libffi::raw::FFI_TYPE_SINT64 => call_and_return!(i64),
+ libffi::raw::FFI_TYPE_POINTER => call_and_return!(*mut c_void),
+ libffi::raw::FFI_TYPE_FLOAT => {
+ let mut n: Box<f32> = Box::new(0.0);
+ libffi::raw::ffi_call(
+ &mut function_impl.cif,
+ Some(*function_impl.code_ptr.as_safe_fun()),
+ &mut *n as *mut _ as *mut c_void,
+ pointer_args.pointers.as_mut_ptr() as *mut *mut c_void,
+ );
+ Ok(Value::Float((*n).into()))
+ }
+ libffi::raw::FFI_TYPE_DOUBLE => {
+ let mut n: Box<f64> = Box::new(0.0);
+ libffi::raw::ffi_call(
+ &mut function_impl.cif,
+ Some(*function_impl.code_ptr.as_safe_fun()),
+ &mut *n as *mut _ as *mut c_void,
+ pointer_args.pointers.as_mut_ptr() as *mut *mut c_void,
+ );
+ Ok(Value::Float(*n))
+ }
+ libffi::raw::FFI_TYPE_STRUCT => {
+ let name = &function_impl
+ .return_struct_name
+ .clone()
+ .ok_or(FFIError::StructNotFound)?;
+ let struct_type = self.structs.get(name).ok_or(FFIError::StructNotFound)?;
+ let layout = Layout::from_size_align(
+ struct_type.ffi_type.size,
+ struct_type.ffi_type.alignment.into(),
+ )
+ .unwrap();
+ let ptr = alloc(layout) as *mut c_void;
+
+ libffi::raw::ffi_call(
+ &mut function_impl.cif,
+ Some(*function_impl.code_ptr.as_safe_fun()),
+ &mut *ptr as *mut _ as *mut c_void,
+ pointer_args.pointers.as_mut_ptr() as *mut *mut c_void,
+ );
+ let struct_val = self.read_struct(ptr, name, struct_type);
+ drop(Box::from_raw(ptr));
+ struct_val
+ }
+ _ => unreachable!(),
+ }
+ };
}
- fn read_struct(&self, ptr: *mut c_void, name: &str, struct_type: &StructImpl) -> Result<Value, FFIError> {
- unsafe {
- let mut returns = Vec::new();
- let mut field_ptr = ptr;
-
- for i in 0..(struct_type.fields.len()-1) {
- let field = struct_type.fields[i];
-
- macro_rules! read_and_push_int {
- ($type:ty) => {
- {
- field_ptr = field_ptr.add(field_ptr.align_offset(std::mem::align_of::<$type>()));
- let n = std::ptr::read(field_ptr as *mut $type);
- returns.push(Value::Int(i64::from(n)));
- field_ptr = field_ptr.add(std::mem::size_of::<$type>());
- }
- }
- }
-
- match (*field).type_ as u32 {
- libffi::raw::FFI_TYPE_UINT8 => read_and_push_int!(u8),
- libffi::raw::FFI_TYPE_SINT8 => read_and_push_int!(i8),
- libffi::raw::FFI_TYPE_UINT16 => read_and_push_int!(u16),
- libffi::raw::FFI_TYPE_SINT16 => read_and_push_int!(i16),
- libffi::raw::FFI_TYPE_UINT32 => read_and_push_int!(u32),
- libffi::raw::FFI_TYPE_SINT32 => read_and_push_int!(i32),
- libffi::raw::FFI_TYPE_UINT64 => {
- field_ptr = field_ptr.add(field_ptr.align_offset(std::mem::align_of::<u64>()));
- let n = std::ptr::read(field_ptr as *mut u64);
- returns.push(Value::Int(i64::try_from(n).map_err(|_| FFIError::ValueDontFit)?));
- field_ptr = field_ptr.add(std::mem::size_of::<u64>());
- },
- libffi::raw::FFI_TYPE_SINT64 => read_and_push_int!(i64),
- libffi::raw::FFI_TYPE_POINTER => read_and_push_int!(i64),
- libffi::raw::FFI_TYPE_STRUCT => {
- let substruct = struct_type.atom_fields[i].as_str();
- let struct_type = self.structs.get(substruct).ok_or(FFIError::StructNotFound)?;
- field_ptr = field_ptr.add(field_ptr.align_offset(struct_type.ffi_type.alignment as usize));
- let struct_val = self.read_struct(field_ptr, substruct, struct_type);
- returns.push(struct_val?);
- field_ptr = field_ptr.add(struct_type.ffi_type.size);
- },
- _ => {
- unreachable!()
- }
- }
- }
- Ok(Value::Struct(name.into(), returns))
- }
+ fn read_struct(
+ &self,
+ ptr: *mut c_void,
+ name: &str,
+ struct_type: &StructImpl,
+ ) -> Result<Value, FFIError> {
+ unsafe {
+ let mut returns = Vec::new();
+ let mut field_ptr = ptr;
+
+ for i in 0..(struct_type.fields.len() - 1) {
+ let field = struct_type.fields[i];
+
+ macro_rules! read_and_push_int {
+ ($type:ty) => {{
+ field_ptr =
+ field_ptr.add(field_ptr.align_offset(std::mem::align_of::<$type>()));
+ let n = std::ptr::read(field_ptr as *mut $type);
+ returns.push(Value::Int(i64::from(n)));
+ field_ptr = field_ptr.add(std::mem::size_of::<$type>());
+ }};
+ }
+
+ match (*field).type_ as u32 {
+ libffi::raw::FFI_TYPE_UINT8 => read_and_push_int!(u8),
+ libffi::raw::FFI_TYPE_SINT8 => read_and_push_int!(i8),
+ libffi::raw::FFI_TYPE_UINT16 => read_and_push_int!(u16),
+ libffi::raw::FFI_TYPE_SINT16 => read_and_push_int!(i16),
+ libffi::raw::FFI_TYPE_UINT32 => read_and_push_int!(u32),
+ libffi::raw::FFI_TYPE_SINT32 => read_and_push_int!(i32),
+ libffi::raw::FFI_TYPE_UINT64 => {
+ field_ptr =
+ field_ptr.add(field_ptr.align_offset(std::mem::align_of::<u64>()));
+ let n = std::ptr::read(field_ptr as *mut u64);
+ returns.push(Value::Int(
+ i64::try_from(n).map_err(|_| FFIError::ValueDontFit)?,
+ ));
+ field_ptr = field_ptr.add(std::mem::size_of::<u64>());
+ }
+ libffi::raw::FFI_TYPE_SINT64 => read_and_push_int!(i64),
+ libffi::raw::FFI_TYPE_POINTER => read_and_push_int!(i64),
+ libffi::raw::FFI_TYPE_STRUCT => {
+ let substruct = struct_type.atom_fields[i].as_str();
+ let struct_type = self
+ .structs
+ .get(substruct)
+ .ok_or(FFIError::StructNotFound)?;
+ field_ptr = field_ptr
+ .add(field_ptr.align_offset(struct_type.ffi_type.alignment as usize));
+ let struct_val = self.read_struct(field_ptr, substruct, struct_type);
+ returns.push(struct_val?);
+ field_ptr = field_ptr.add(struct_type.ffi_type.size);
+ }
+ _ => {
+ unreachable!()
+ }
+ }
+ }
+ Ok(Value::Struct(name.into(), returns))
+ }
}
}
impl Value {
fn as_int(&self) -> Result<i64, FFIError> {
- match self {
- Value::Int(n) => Ok(*n),
- _ => Err(FFIError::ValueCast),
- }
+ match self {
+ Value::Int(n) => Ok(*n),
+ _ => Err(FFIError::ValueCast),
+ }
}
fn as_float(&self) -> Result<f64, FFIError> {
- match self {
- Value::Float(n) => Ok(*n),
- Value::Int(n) => Ok(*n as f64),
- _ => Err(FFIError::ValueCast),
- }
+ match self {
+ Value::Float(n) => Ok(*n),
+ Value::Int(n) => Ok(*n as f64),
+ _ => Err(FFIError::ValueCast),
+ }
}
fn as_ptr(&mut self) -> Result<*mut c_void, FFIError> {
- match self {
- Value::CString(ref mut cstr) => Ok(&mut *cstr as *mut _ as *mut c_void),
- Value::Int(n) => Ok(*n as *mut c_void),
- _ => Err(FFIError::ValueCast)
- }
+ match self {
+ Value::CString(ref mut cstr) => Ok(&mut *cstr as *mut _ as *mut c_void),
+ Value::Int(n) => Ok(*n as *mut c_void),
+ _ => Err(FFIError::ValueCast),
+ }
}
}
use crate::machine::machine_errors::*;
use crate::machine::machine_indices::*;
use crate::parser::ast::*;
-use crate::parser::parser::CompositeOpDesc;
use crate::parser::dashu::{Integer, Rational};
+use crate::parser::parser::CompositeOpDesc;
use crate::types::*;
use fxhash::FxBuildHasher;
#[derive(Debug, Clone, Copy)]
pub enum VarComparison {
Indistinct,
- Distinct
+ Distinct,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
impl ChunkedTermVec {
#[inline]
pub fn new() -> Self {
- Self { chunk_vec: VecDeque::new() }
+ Self {
+ chunk_vec: VecDeque::new(),
+ }
}
pub fn reserve_branch(&mut self, capacity: usize) {
- self.chunk_vec.push_back(ChunkedTerms::Branch(Vec::with_capacity(capacity)));
+ self.chunk_vec
+ .push_back(ChunkedTerms::Branch(Vec::with_capacity(capacity)));
}
pub fn push_branch_arm(&mut self, branch: VecDeque<ChunkedTerms>) {
#[inline]
pub fn add_chunk(&mut self) {
- self.chunk_vec.push_back(ChunkedTerms::Chunk(VecDeque::from(vec![])));
+ self.chunk_vec
+ .push_back(ChunkedTerms::Chunk(VecDeque::from(vec![])));
}
pub fn push_chunk_term(&mut self, term: QueryTerm) {
match self.chunk_vec.back_mut() {
Some(ChunkedTerms::Branch(_)) => {
- self.chunk_vec.push_back(ChunkedTerms::Chunk(VecDeque::from(vec![term])));
+ self.chunk_vec
+ .push_back(ChunkedTerms::Chunk(VecDeque::from(vec![term])));
}
Some(ChunkedTerms::Chunk(chunk)) => {
chunk.push_back(term);
}
None => {
- self.chunk_vec.push_back(ChunkedTerms::Chunk(VecDeque::from(vec![term])));
+ self.chunk_vec
+ .push_back(ChunkedTerms::Chunk(VecDeque::from(vec![term])));
}
}
}
// register, clause type, subterms, clause call policy.
Clause(Cell<RegType>, ClauseType, Vec<Term>, CallPolicy),
Fail,
- LocalCut(usize), // var_num
+ LocalCut(usize), // var_num
GlobalCut(usize), // var_num
GetCutPoint { var_num: usize, prev_b: bool },
GetLevel(usize), // var_num
fn name(&self) -> Option<Atom> {
match self {
Term::Clause(_, name, terms) => {
-
match name {
atom!(":-") => {
match terms.len() {
- 1 => None, // a declaration.
+ 1 => None, // a declaration.
2 => terms[0].name(),
_ => Some(*name),
}
}
}
-
impl OpDecl {
#[inline]
pub(crate) fn new(op_desc: OpDesc, name: Atom) -> Self {
#[inline]
pub fn as_atom(&self, atom_tbl: &mut AtomTable) -> Atom {
match self {
- &AtomOrString::Atom(atom) => {
- atom
- }
- AtomOrString::String(string) => {
- atom_tbl.build_with(&string)
- }
+ &AtomOrString::Atom(atom) => atom,
+ AtomOrString::String(string) => atom_tbl.build_with(&string),
}
}
#[inline]
pub fn to_string(self) -> String {
match self {
- AtomOrString::Atom(atom) => {
- atom.as_str().to_owned()
- }
- AtomOrString::String(string) => {
- string
- }
+ AtomOrString::Atom(atom) => atom.as_str().to_owned(),
+ AtomOrString::String(string) => string,
}
}
}
}
})
}
- 0 => {
- fetch_atom_op_spec(name, None, op_dir)
- }
+ 0 => fetch_atom_op_spec(name, None, op_dir),
_ => None,
}
}
// Module's and related types are defined in forms.
impl Module {
- pub(crate) fn new(
- module_decl: ModuleDecl,
- listing_src: ListingSource,
- ) -> Self {
+ pub(crate) fn new(module_decl: ModuleDecl, listing_src: ListingSource) -> Self {
Module {
module_decl,
code_dir: CodeDir::with_hasher(FxBuildHasher::default()),
meta_predicates: MetaPredicateDir::with_hasher(FxBuildHasher::default()),
extensible_predicates: ExtensiblePredicates::with_hasher(FxBuildHasher::default()),
local_extensible_predicates: LocalExtensiblePredicates::with_hasher(
- FxBuildHasher::default()
+ FxBuildHasher::default(),
),
listing_src: ListingSource::DynamicallyGenerated,
}
#[inline]
pub(crate) fn must_retract_local_clauses(&self, is_cross_module_clause: bool) -> bool {
- self.is_extensible && self.has_clauses && !self.is_discontiguous &&
- !(self.is_multifile && is_cross_module_clause)
+ self.is_extensible
+ && self.has_clauses
+ && !self.is_discontiguous
+ && !(self.is_multifile && is_cross_module_clause)
}
}
&mut self,
clause_clause_loc: usize,
) -> Option<usize> {
- let search_result = self.core.clause_clause_locs
- .make_contiguous()[0..self.core.clause_assert_margin]
+ let search_result = self.core.clause_clause_locs.make_contiguous()
+ [0..self.core.clause_assert_margin]
.binary_search_by(|loc| clause_clause_loc.cmp(&loc));
match search_result {
Ok(loc) => Some(loc),
- Err(_) => {
- self.core.clause_clause_locs
- .make_contiguous()[self.core.clause_assert_margin..]
- .binary_search_by(|loc| loc.cmp(&clause_clause_loc))
- .map(|loc| loc + self.core.clause_assert_margin)
- .ok()
- }
+ Err(_) => self.core.clause_clause_locs.make_contiguous()
+ [self.core.clause_assert_margin..]
+ .binary_search_by(|loc| loc.cmp(&clause_clause_loc))
+ .map(|loc| loc + self.core.clause_assert_margin)
+ .ok(),
}
}
}
#[inline]
pub fn as_ref(self) -> Ref {
match self.heap_or_stack() {
- HeapOrStackTag::Heap => {
- Ref::heap_cell(self.value() as usize)
- }
- HeapOrStackTag::Stack => {
- Ref::stack_cell(self.value() as usize)
- }
+ HeapOrStackTag::Heap => Ref::heap_cell(self.value() as usize),
+ HeapOrStackTag::Stack => Ref::stack_cell(self.value() as usize),
}
}
}
#[inline]
pub fn read_cell_mut(&mut self, loc: IterStackLoc) -> &mut HeapCellValue {
match loc.heap_or_stack() {
- HeapOrStackTag::Heap => {
- &mut self.heap[loc.value() as usize]
- }
- HeapOrStackTag::Stack => {
- &mut self.machine_stack[loc.value() as usize]
- }
+ HeapOrStackTag::Heap => &mut self.heap[loc.value() as usize],
+ HeapOrStackTag::Stack => &mut self.machine_stack[loc.value() as usize],
}
}
#[inline]
pub fn read_cell(&self, loc: IterStackLoc) -> HeapCellValue {
match loc.heap_or_stack() {
- HeapOrStackTag::Heap => {
- self.heap[loc.value() as usize]
- }
- HeapOrStackTag::Stack => {
- self.machine_stack[loc.value() as usize]
- }
+ HeapOrStackTag::Heap => self.heap[loc.value() as usize],
+ HeapOrStackTag::Stack => self.machine_stack[loc.value() as usize],
}
}
if !cell.get_mark_bit() {
cell.set_mark_bit(true);
- self.stack.push(IterStackLoc::iterable_loc(loc.value() as usize, loc.heap_or_stack()));
+ self.stack.push(IterStackLoc::iterable_loc(
+ loc.value() as usize,
+ loc.heap_or_stack(),
+ ));
}
}
while let Some(h) = self.stack.pop() {
if h.is_pending_mark() {
self.push_if_unmarked(h);
- self.stack.push(IterStackLoc::mark_loc(h.value() as usize, h.heap_or_stack()));
+ self.stack.push(IterStackLoc::mark_loc(
+ h.value() as usize,
+ h.heap_or_stack(),
+ ));
self.forward_if_referent_marked(h);
continue;
#[inline]
pub fn pop_stack(&mut self) {
if let Some((child_count, ..)) = self.parent_stack.last() {
- for _ in 0 .. *child_count {
+ for _ in 0..*child_count {
self.base_iter.pop_stack();
}
use super::*;
use crate::machine::mock_wam::*;
-
#[test]
fn heap_stackless_iter_tests() {
let mut wam = MockWAM::new();
let b_atom = atom!("b");
wam.machine_st
- .heap
- .extend(functor!(f_atom, [atom(a_atom), atom(b_atom)]));
+ .heap
+ .extend(functor!(f_atom, [atom(a_atom), atom(b_atom)]));
{
let mut iter = stackless_preorder_iter(&mut wam.machine_st.heap, str_loc_as_cell!(0));
{
wam.machine_st.heap.push(heap_loc_as_cell!(0));
- let mut iter = stackless_preorder_iter(
- &mut wam.machine_st.heap,
- heap_loc_as_cell!(0),
- );
+ let mut iter = stackless_preorder_iter(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
- assert_eq!(unmark_cell_bits!(iter.next().unwrap()), heap_loc_as_cell!(0));
+ assert_eq!(
+ unmark_cell_bits!(iter.next().unwrap()),
+ heap_loc_as_cell!(0)
+ );
assert_eq!(iter.next(), None);
}
wam.machine_st.heap.push(empty_list_as_cell!());
{
- let mut iter = stackless_preorder_iter(
- &mut wam.machine_st.heap,
- heap_loc_as_cell!(0),
- );
+ let mut iter = stackless_preorder_iter(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
assert_eq!(
unmark_cell_bits!(iter.next().unwrap()),
wam.machine_st.heap.push(heap_loc_as_cell!(0));
{
- let mut iter = stackless_preorder_iter(
- &mut wam.machine_st.heap,
- heap_loc_as_cell!(0),
- );
+ let mut iter = stackless_preorder_iter(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
assert_eq!(
unmark_cell_bits!(iter.next().unwrap()),
// first a 'dangling' partial string, later modified to be a two-part complete string,
// then a three-part cyclic string involving an uncompacted list of chars.
- let pstr_var_cell = put_partial_string(&mut wam.machine_st.heap, "abc ", &mut wam.machine_st.atom_tbl);
+ let pstr_var_cell = put_partial_string(
+ &mut wam.machine_st.heap,
+ "abc ",
+ &mut wam.machine_st.atom_tbl,
+ );
let pstr_cell = wam.machine_st.heap[pstr_var_cell.get_value() as usize];
{
wam.machine_st.heap.pop();
wam.machine_st.heap.push(pstr_loc_as_cell!(4));
wam.machine_st.heap.push(pstr_offset_as_cell!(0));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(2)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(2)));
{
- let mut iter = stackless_preorder_iter(
- &mut wam.machine_st.heap,
- pstr_loc_as_cell!(4),
- );
+ let mut iter = stackless_preorder_iter(&mut wam.machine_st.heap, pstr_loc_as_cell!(4));
let pstr_offset_cell = pstr_offset_as_cell!(0);
}
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), pstr_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_loc_as_cell!(2));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ pstr_loc_as_cell!(2)
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), pstr_second_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), pstr_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), pstr_offset_as_cell!(0));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), fixnum_as_cell!(Fixnum::build_with(2)));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ pstr_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ pstr_offset_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ fixnum_as_cell!(Fixnum::build_with(2))
+ );
wam.machine_st.heap.truncate(4);
wam.machine_st.heap.pop();
- wam.machine_st.heap.push(pstr_loc_as_cell!(wam.machine_st.heap.len() + 1));
+ wam.machine_st
+ .heap
+ .push(pstr_loc_as_cell!(wam.machine_st.heap.len() + 1));
wam.machine_st.heap.push(pstr_offset_as_cell!(0));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(0i64)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(0i64)));
{
let mut iter = stackless_preorder_iter(&mut wam.machine_st.heap, pstr_loc_as_cell!(0));
all_cells_unmarked(&wam.machine_st.heap);
wam.machine_st.heap.pop();
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(1i64)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(1i64)));
{
let mut iter = stackless_preorder_iter(&mut wam.machine_st.heap, pstr_loc_as_cell!(0));
assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_cell);
assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_second_cell);
- assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_offset_as_cell!(0));
- assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_offset_as_cell!(0));
+ assert_eq!(
+ unmark_cell_bits!(iter.next().unwrap()),
+ pstr_offset_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(iter.next().unwrap()),
+ pstr_offset_as_cell!(0)
+ );
assert_eq!(iter.next(), None);
all_cells_unmarked(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), heap_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), heap_loc_as_cell!(2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), heap_loc_as_cell!(3));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), heap_loc_as_cell!(3));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ heap_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ heap_loc_as_cell!(2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ heap_loc_as_cell!(3)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ heap_loc_as_cell!(3)
+ );
wam.machine_st.heap.clear();
all_cells_unmarked(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), list_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), list_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), list_loc_as_cell!(1));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ list_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ list_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ list_loc_as_cell!(1)
+ );
wam.machine_st.heap.clear();
assert_eq!(iter.next(), None);
}
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), list_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), heap_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), heap_loc_as_cell!(3));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), list_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), str_loc_as_cell!(6));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), heap_loc_as_cell!(8));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[6]), atom_as_cell!(f_atom, 1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[7]), heap_loc_as_cell!(11));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[8]), list_loc_as_cell!(9));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[9]), heap_loc_as_cell!(9));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[10]), empty_list_as_cell!());
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[11]), attr_var_as_cell!(11));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[12]), heap_loc_as_cell!(13));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[13]), list_loc_as_cell!(14));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[14]), str_loc_as_cell!(16));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[15]), heap_loc_as_cell!(19));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[16]), atom_as_cell!(clpz_atom, 2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[17]), atom_as_cell!(a_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[18]), atom_as_cell!(b_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[19]), list_loc_as_cell!(20));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[20]), str_loc_as_cell!(22));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[21]), empty_list_as_cell!());
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[22]), atom_as_cell!(p_atom, 1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[23]), heap_loc_as_cell!(23));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ list_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ heap_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ heap_loc_as_cell!(3)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ list_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ str_loc_as_cell!(6)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ heap_loc_as_cell!(8)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[6]),
+ atom_as_cell!(f_atom, 1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[7]),
+ heap_loc_as_cell!(11)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[8]),
+ list_loc_as_cell!(9)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[9]),
+ heap_loc_as_cell!(9)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[10]),
+ empty_list_as_cell!()
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[11]),
+ attr_var_as_cell!(11)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[12]),
+ heap_loc_as_cell!(13)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[13]),
+ list_loc_as_cell!(14)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[14]),
+ str_loc_as_cell!(16)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[15]),
+ heap_loc_as_cell!(19)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[16]),
+ atom_as_cell!(clpz_atom, 2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[17]),
+ atom_as_cell!(a_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[18]),
+ atom_as_cell!(b_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[19]),
+ list_loc_as_cell!(20)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[20]),
+ str_loc_as_cell!(22)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[21]),
+ empty_list_as_cell!()
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[22]),
+ atom_as_cell!(p_atom, 1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[23]),
+ heap_loc_as_cell!(23)
+ );
wam.machine_st.heap.clear();
{
let mut iter = stackless_preorder_iter(
&mut wam.machine_st.heap,
- fixnum_as_cell!(Fixnum::build_with(0))
+ fixnum_as_cell!(Fixnum::build_with(0)),
);
assert_eq!(
wam.machine_st.heap.push(str_loc_as_cell!(1));
- wam.machine_st.heap.push(atom_as_cell!(atom!("g"),2));
+ wam.machine_st.heap.push(atom_as_cell!(atom!("g"), 2));
wam.machine_st.heap.push(heap_loc_as_cell!(0));
wam.machine_st.heap.push(atom_as_cell!(atom!("y")));
{
- let mut iter = stackless_preorder_iter(
- &mut wam.machine_st.heap,
- str_loc_as_cell!(1),
- );
+ let mut iter = stackless_preorder_iter(&mut wam.machine_st.heap, str_loc_as_cell!(1));
assert_eq!(
unmark_cell_bits!(iter.next().unwrap()),
- atom_as_cell!(atom!("g"),2)
+ atom_as_cell!(atom!("g"), 2)
);
assert_eq!(
atom_as_cell!(atom!("y"))
);
- assert_eq!(
- unmark_cell_bits!(iter.next().unwrap()),
- str_loc_as_cell!(1)
- );
+ assert_eq!(unmark_cell_bits!(iter.next().unwrap()), str_loc_as_cell!(1));
assert!(iter.next().is_none());
}
wam.machine_st.heap.clear();
- wam.machine_st.heap.push(atom_as_cell!(atom!("g"),2));
+ wam.machine_st.heap.push(atom_as_cell!(atom!("g"), 2));
wam.machine_st.heap.push(str_loc_as_cell!(0));
wam.machine_st.heap.push(atom_as_cell!(atom!("y")));
{
- let mut iter = stackless_preorder_iter(
- &mut wam.machine_st.heap,
- str_loc_as_cell!(0),
- );
+ let mut iter = stackless_preorder_iter(&mut wam.machine_st.heap, str_loc_as_cell!(0));
assert_eq!(
unmark_cell_bits!(iter.next().unwrap()),
- atom_as_cell!(atom!("g"),2)
+ atom_as_cell!(atom!("g"), 2)
);
assert_eq!(
atom_as_cell!(atom!("y"))
);
- assert_eq!(
- unmark_cell_bits!(iter.next().unwrap()),
- str_loc_as_cell!(0)
- );
+ assert_eq!(unmark_cell_bits!(iter.next().unwrap()), str_loc_as_cell!(0));
assert!(iter.next().is_none());
}
wam.machine_st.heap.push(empty_list_as_cell!());
{
- let mut iter = stackless_preorder_iter(
- &mut wam.machine_st.heap,
- heap_loc_as_cell!(7),
- );
+ let mut iter = stackless_preorder_iter(&mut wam.machine_st.heap, heap_loc_as_cell!(7));
assert_eq!(
unmark_cell_bits!(iter.next().unwrap()),
wam.machine_st.heap.push(heap_loc_as_cell!(1));
{
- let mut iter = stackless_preorder_iter(
- &mut wam.machine_st.heap,
- str_loc_as_cell!(0),
- );
+ let mut iter = stackless_preorder_iter(&mut wam.machine_st.heap, str_loc_as_cell!(0));
assert_eq!(
unmark_cell_bits!(iter.next().unwrap()),
wam.machine_st.heap.clear();
// representation of one of the heap terms as in issue #1384.
-/*
- wam.machine_st.heap.push(list_loc_as_cell!(7));
- wam.machine_st.heap.push(heap_loc_as_cell!(0));
- wam.machine_st.heap.push(list_loc_as_cell!(3));
- wam.machine_st.heap.push(list_loc_as_cell!(5));
- wam.machine_st.heap.push(empty_list_as_cell!());
- wam.machine_st.heap.push(heap_loc_as_cell!(2));
- wam.machine_st.heap.push(heap_loc_as_cell!(2));
- wam.machine_st.heap.push(empty_list_as_cell!());
- wam.machine_st.heap.push(heap_loc_as_cell!(3));
-
- {
- let mut iter = stackless_preorder_iter(
- &mut wam.machine_st.heap,
- heap_loc_as_cell!(0),
- );
+ /*
+ wam.machine_st.heap.push(list_loc_as_cell!(7));
+ wam.machine_st.heap.push(heap_loc_as_cell!(0));
+ wam.machine_st.heap.push(list_loc_as_cell!(3));
+ wam.machine_st.heap.push(list_loc_as_cell!(5));
+ wam.machine_st.heap.push(empty_list_as_cell!());
+ wam.machine_st.heap.push(heap_loc_as_cell!(2));
+ wam.machine_st.heap.push(heap_loc_as_cell!(2));
+ wam.machine_st.heap.push(empty_list_as_cell!());
+ wam.machine_st.heap.push(heap_loc_as_cell!(3));
+
+ {
+ let mut iter = stackless_preorder_iter(
+ &mut wam.machine_st.heap,
+ heap_loc_as_cell!(0),
+ );
- while let Some(_) = iter.next() {
- print_heap_terms(iter.heap.iter(), 0);
- println!("");
- }
+ while let Some(_) = iter.next() {
+ print_heap_terms(iter.heap.iter(), 0);
+ println!("");
+ }
- /*
- assert_eq!(
- unmark_cell_bits!(iter.next().unwrap()),
- atom_as_cell!(atom!("f"), 2)
- );
+ /*
+ assert_eq!(
+ unmark_cell_bits!(iter.next().unwrap()),
+ atom_as_cell!(atom!("f"), 2)
+ );
- assert!(iter.next().is_none());
- */
- }
-*/
+ assert!(iter.next().is_none());
+ */
+ }
+ */
}
#[test]
let a_atom = atom!("a");
let b_atom = atom!("b");
- wam.machine_st.heap
+ wam.machine_st
+ .heap
.extend(functor!(f_atom, [atom(a_atom), atom(b_atom)]));
{
// two-part complete string, then a three-part cyclic string
// involving an uncompacted list of chars.
- let pstr_var_cell = put_partial_string(&mut wam.machine_st.heap, "abc ", &mut wam.machine_st.atom_tbl);
+ let pstr_var_cell = put_partial_string(
+ &mut wam.machine_st.heap,
+ "abc ",
+ &mut wam.machine_st.atom_tbl,
+ );
let pstr_cell = wam.machine_st.heap[pstr_var_cell.get_value() as usize];
{
wam.machine_st.heap.pop();
wam.machine_st.heap.push(heap_loc_as_cell!(2));
- let pstr_second_var_cell = put_partial_string(&mut wam.machine_st.heap, "def", &mut wam.machine_st.atom_tbl);
+ let pstr_second_var_cell = put_partial_string(
+ &mut wam.machine_st.heap,
+ "def",
+ &mut wam.machine_st.atom_tbl,
+ );
let pstr_second_cell = wam.machine_st.heap[pstr_second_var_cell.get_value() as usize];
{
}
wam.machine_st.heap.pop();
- wam.machine_st.heap.push(pstr_loc_as_cell!(wam.machine_st.heap.len() + 1));
+ wam.machine_st
+ .heap
+ .push(pstr_loc_as_cell!(wam.machine_st.heap.len() + 1));
wam.machine_st.heap.push(pstr_offset_as_cell!(0));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(0i64)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(0i64)));
{
let mut iter = stackful_preorder_iter(
assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_cell);
assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_second_cell);
assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_offset_cell);
- assert_eq!(iter.next().unwrap(), fixnum_as_cell!(Fixnum::build_with(0i64)));
+ assert_eq!(
+ iter.next().unwrap(),
+ fixnum_as_cell!(Fixnum::build_with(0i64))
+ );
assert_eq!(iter.next(), None);
}
*/
wam.machine_st.heap.pop();
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(1i64)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(1i64)));
{
let mut iter = stackful_preorder_iter(
assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_second_cell);
assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_offset_cell);
- assert_eq!(iter.next().unwrap(), fixnum_as_cell!(Fixnum::build_with(1i64)));
+ assert_eq!(
+ iter.next().unwrap(),
+ fixnum_as_cell!(Fixnum::build_with(1i64))
+ );
let h = iter.focus();
assert_eq!(h.value(), 5);
assert_eq!(unmark_cell_bits!(iter.heap[4]), pstr_offset_as_cell!(0));
- assert_eq!(unmark_cell_bits!(iter.heap[5]), fixnum_as_cell!(Fixnum::build_with(1i64)));
+ assert_eq!(
+ unmark_cell_bits!(iter.heap[5]),
+ fixnum_as_cell!(Fixnum::build_with(1i64))
+ );
assert_eq!(iter.next(), None);
}
pstr_as_cell!(atom!("a string"))
);
- assert_eq!(
- iter.next().unwrap(),
- empty_list_as_cell!()
- );
+ assert_eq!(iter.next().unwrap(), empty_list_as_cell!());
assert_eq!(iter.next(), None);
}
let a_atom = atom!("a");
let b_atom = atom!("b");
- wam.machine_st.heap
+ wam.machine_st
+ .heap
.extend(functor!(f_atom, [atom(a_atom), atom(b_atom)]));
{
]
));
- for _ in 0..20 { // 0000 {
+ for _ in 0..20 {
+ // 0000 {
let mut iter = stackful_post_order_iter(
&mut wam.machine_st.heap,
&mut wam.machine_st.stack,
// two-part complete string, then a three-part cyclic string
// involving an uncompacted list of chars.
- let pstr_var_cell = put_partial_string(&mut wam.machine_st.heap, "abc ", &mut wam.machine_st.atom_tbl);
+ let pstr_var_cell = put_partial_string(
+ &mut wam.machine_st.heap,
+ "abc ",
+ &mut wam.machine_st.atom_tbl,
+ );
let pstr_cell = wam.machine_st.heap[pstr_var_cell.get_value() as usize];
{
wam.machine_st.heap.pop();
wam.machine_st.heap.push(pstr_loc_as_cell!(2));
- let pstr_second_var_cell = put_partial_string(&mut wam.machine_st.heap, "def", &mut wam.machine_st.atom_tbl);
+ let pstr_second_var_cell = put_partial_string(
+ &mut wam.machine_st.heap,
+ "def",
+ &mut wam.machine_st.atom_tbl,
+ );
let pstr_second_cell = wam.machine_st.heap[pstr_second_var_cell.get_value() as usize];
{
}
wam.machine_st.heap.pop();
- wam.machine_st.heap.push(pstr_loc_as_cell!(wam.machine_st.heap.len() + 1));
+ wam.machine_st
+ .heap
+ .push(pstr_loc_as_cell!(wam.machine_st.heap.len() + 1));
wam.machine_st.heap.push(pstr_offset_as_cell!(0));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(0i64)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(0i64)));
{
let mut iter = stackful_post_order_iter(
pstr_loc_as_cell!(0),
);
- assert_eq!(iter.next().unwrap(), fixnum_as_cell!(Fixnum::build_with(0i64)));
- assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_offset_as_cell!(0));
+ assert_eq!(
+ iter.next().unwrap(),
+ fixnum_as_cell!(Fixnum::build_with(0i64))
+ );
+ assert_eq!(
+ unmark_cell_bits!(iter.next().unwrap()),
+ pstr_offset_as_cell!(0)
+ );
assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_second_cell);
assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_cell);
}
wam.machine_st.heap.pop();
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(1i64)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(1i64)));
{
let mut iter = stackful_post_order_iter(
pstr_loc_as_cell!(0),
);
- assert_eq!(iter.next().unwrap(), fixnum_as_cell!(Fixnum::build_with(1i64)));
- assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_offset_as_cell!(0));
+ assert_eq!(
+ iter.next().unwrap(),
+ fixnum_as_cell!(Fixnum::build_with(1i64))
+ );
+ assert_eq!(
+ unmark_cell_bits!(iter.next().unwrap()),
+ pstr_offset_as_cell!(0)
+ );
assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_second_cell);
assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_cell);
let a_atom = atom!("a");
let b_atom = atom!("b");
- wam.machine_st.heap.extend(functor!(f_atom, [atom(a_atom), atom(b_atom)]));
+ wam.machine_st
+ .heap
+ .extend(functor!(f_atom, [atom(a_atom), atom(b_atom)]));
{
- let mut iter = stackless_post_order_iter(
- &mut wam.machine_st.heap,
- str_loc_as_cell!(0),
- );
+ let mut iter = stackless_post_order_iter(&mut wam.machine_st.heap, str_loc_as_cell!(0));
assert_eq!(
unmark_cell_bits!(iter.next().unwrap()),
));
for _ in 0..20 {
- let mut iter = stackless_post_order_iter(
- &mut wam.machine_st.heap,
- str_loc_as_cell!(0),
- );
+ let mut iter = stackless_post_order_iter(&mut wam.machine_st.heap, str_loc_as_cell!(0));
assert_eq!(unmark_cell_bits!(iter.next().unwrap()), str_loc_as_cell!(0));
{
wam.machine_st.heap.push(heap_loc_as_cell!(0));
- let mut iter = stackless_post_order_iter(
- &mut wam.machine_st.heap,
- heap_loc_as_cell!(0),
- );
+ let mut iter =
+ stackless_post_order_iter(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
assert_eq!(
unmark_cell_bits!(iter.next().unwrap()),
wam.machine_st.heap.push(heap_loc_as_cell!(1));
wam.machine_st.heap.push(heap_loc_as_cell!(0));
- let mut iter = stackless_post_order_iter(
- &mut wam.machine_st.heap,
- heap_loc_as_cell!(0),
- );
+ let mut iter =
+ stackless_post_order_iter(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
assert_eq!(
unmark_cell_bits!(iter.next().unwrap()),
wam.machine_st.heap.push(empty_list_as_cell!());
{
- let mut iter = stackless_post_order_iter(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
+ let mut iter =
+ stackless_post_order_iter(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
assert_eq!(
unmark_cell_bits!(iter.next().unwrap()),
wam.machine_st.heap.push(heap_loc_as_cell!(0));
{
- let mut iter = stackless_post_order_iter(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
+ let mut iter =
+ stackless_post_order_iter(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
// the cycle will be iterated twice before being detected.
assert_eq!(
}
{
- let mut iter = stackless_post_order_iter(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
+ let mut iter =
+ stackless_post_order_iter(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
// cut the iteration short to check that all cells are
// unmarked and unforwarded by the Drop instance of
// two-part complete string, then a three-part cyclic string
// involving an uncompacted list of chars.
- let pstr_var_cell = put_partial_string(&mut wam.machine_st.heap, "abc ", &mut wam.machine_st.atom_tbl);
+ let pstr_var_cell = put_partial_string(
+ &mut wam.machine_st.heap,
+ "abc ",
+ &mut wam.machine_st.atom_tbl,
+ );
let pstr_cell = wam.machine_st.heap[pstr_var_cell.get_value() as usize];
{
- let mut iter = stackless_post_order_iter(&mut wam.machine_st.heap, pstr_loc_as_cell!(0));
+ let mut iter =
+ stackless_post_order_iter(&mut wam.machine_st.heap, pstr_loc_as_cell!(0));
assert_eq!(
unmark_cell_bits!(iter.next().unwrap()),
let pstr_second_cell = wam.machine_st.heap[pstr_second_var_cell.get_value() as usize];
{
- let mut iter = stackless_post_order_iter(&mut wam.machine_st.heap, pstr_loc_as_cell!(0));
+ let mut iter =
+ stackless_post_order_iter(&mut wam.machine_st.heap, pstr_loc_as_cell!(0));
assert_eq!(
unmark_cell_bits!(iter.next().unwrap()),
all_cells_unmarked(&wam.machine_st.heap);
wam.machine_st.heap.pop();
- wam.machine_st.heap.push(pstr_loc_as_cell!(wam.machine_st.heap.len() + 1));
+ wam.machine_st
+ .heap
+ .push(pstr_loc_as_cell!(wam.machine_st.heap.len() + 1));
wam.machine_st.heap.push(pstr_offset_as_cell!(0));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(0)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(0)));
{
- let mut iter = stackless_post_order_iter(&mut wam.machine_st.heap, pstr_loc_as_cell!(0));
+ let mut iter =
+ stackless_post_order_iter(&mut wam.machine_st.heap, pstr_loc_as_cell!(0));
let mut pstr_loc_cell = pstr_loc_as_cell!(0);
pstr_loc_cell.set_forwarding_bit(true);
// assert_eq!(iter.next().unwrap(), fixnum_as_cell!(Fixnum::build_with(0i64)));
- assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_offset_as_cell!(0));
- assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_offset_as_cell!(0));
+ assert_eq!(
+ unmark_cell_bits!(iter.next().unwrap()),
+ pstr_offset_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(iter.next().unwrap()),
+ pstr_offset_as_cell!(0)
+ );
assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_second_cell);
assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_cell);
all_cells_unmarked(&wam.machine_st.heap);
wam.machine_st.heap.pop();
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(1)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(1)));
{
- let mut iter = stackless_post_order_iter(&mut wam.machine_st.heap, pstr_loc_as_cell!(0));
+ let mut iter =
+ stackless_post_order_iter(&mut wam.machine_st.heap, pstr_loc_as_cell!(0));
//assert_eq!(iter.next().unwrap(), fixnum_as_cell!(Fixnum::build_with(1)));
- assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_offset_as_cell!(0));
- assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_offset_as_cell!(0));
+ assert_eq!(
+ unmark_cell_bits!(iter.next().unwrap()),
+ pstr_offset_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(iter.next().unwrap()),
+ pstr_offset_as_cell!(0)
+ );
assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_second_cell);
assert_eq!(unmark_cell_bits!(iter.next().unwrap()), pstr_cell);
wam.machine_st.heap.extend(functor);
{
- let mut iter = stackless_post_order_iter(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
+ let mut iter =
+ stackless_post_order_iter(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
assert_eq!(
unmark_cell_bits!(iter.next().unwrap()),
wam.machine_st.heap[4] = list_loc_as_cell!(1);
{
- let mut iter = stackless_post_order_iter(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
+ let mut iter =
+ stackless_post_order_iter(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
assert_eq!(
unmark_cell_bits!(iter.next().unwrap()),
}
#[inline]
- fn is_prefix(&self )-> bool {
+ fn is_prefix(&self) -> bool {
match self {
&DirectedOp::Left(_name, cell) | &DirectedOp::Right(_name, cell) => {
is_prefix!(cell.get_spec() as u32)
'\u{08}' if is_quoted => "\\b".to_string(), // UTF-8 backspace
'\u{07}' if is_quoted => "\\a".to_string(), // UTF-8 alert
'\\' if is_quoted => "\\\\".to_string(),
- ' ' | '\'' | '\n' | '\r' | '\t' | '\u{0b}' | '\u{0c}' | '\u{08}' | '\u{07}' | '"' | '\\' => {
- c.to_string()
- }
- _ =>
+ ' ' | '\'' | '\n' | '\r' | '\t' | '\u{0b}' | '\u{0c}' | '\u{08}' | '\u{07}' | '"'
+ | '\\' => c.to_string(),
+ _ => {
if c.is_whitespace() || c.is_control() {
// print all other control and whitespace characters in hex.
format!("\\x{:x}\\", c as u32)
} else {
c.to_string()
}
+ }
}
}
CompositeRedirect(usize, DirectedOp),
CurlyBracketRedirect(usize),
FunctorRedirect(usize),
- #[allow(unused)] IpAddr(IpAddr),
+ #[allow(unused)]
+ IpAddr(IpAddr),
NumberFocus(usize, NumberFocus, Option<DirectedOp>),
Open,
Close,
*/
if let Some(e_index) = fl_str.find('e') {
- if !fl_str[0 .. e_index].contains('.') {
- return fl_str[0 .. e_index].to_string() + ".0" + &fl_str[e_index ..];
+ if !fl_str[0..e_index].contains('.') {
+ return fl_str[0..e_index].to_string() + ".0" + &fl_str[e_index..];
}
}
} else {
let op = DirectedOp::Left(name, spec);
- self.state_stack.push(TokenOrRedirect::CompositeRedirect(max_depth, op));
+ self.state_stack
+ .push(TokenOrRedirect::CompositeRedirect(max_depth, op));
self.state_stack.push(TokenOrRedirect::Op(name, spec));
}
} else {
let left_directed_op = DirectedOp::Left(name, spec);
let right_directed_op = DirectedOp::Right(name, spec);
- self.state_stack.push(TokenOrRedirect::CompositeRedirect(max_depth, left_directed_op));
+ self.state_stack.push(TokenOrRedirect::CompositeRedirect(
+ max_depth,
+ left_directed_op,
+ ));
self.state_stack.push(TokenOrRedirect::Op(name, spec));
- self.state_stack.push(TokenOrRedirect::CompositeRedirect(max_depth, right_directed_op));
+ self.state_stack.push(TokenOrRedirect::CompositeRedirect(
+ max_depth,
+ right_directed_op,
+ ));
}
}
}
self.state_stack.push(TokenOrRedirect::Close);
for _ in 0..arity {
- self.state_stack.push(TokenOrRedirect::FunctorRedirect(max_depth));
+ self.state_stack
+ .push(TokenOrRedirect::FunctorRedirect(max_depth));
self.state_stack.push(TokenOrRedirect::Comma);
}
return false;
}
-
self.state_stack.push(TokenOrRedirect::RightCurly);
- self.state_stack.push(TokenOrRedirect::CurlyBracketRedirect(max_depth));
+ self.state_stack
+ .push(TokenOrRedirect::CurlyBracketRedirect(max_depth));
self.state_stack.push(TokenOrRedirect::LeftCurly);
true
let h = self.iter.stack_last().unwrap();
let cell = self.iter.read_cell(h);
- let cell = heap_bound_store(
- &self.iter.heap,
- heap_bound_deref(&self.iter.heap, cell),
- );
+ let cell = heap_bound_store(&self.iter.heap, heap_bound_deref(&self.iter.heap, cell));
// 7.10.4
if let Some(var) = numbervar(&self.numbervars_offset, cell) {
if let Some(cell) = self.iter.next() {
let is_cyclic = cell.get_forwarding_bit();
- let cell = heap_bound_store(
- self.iter.heap,
- heap_bound_deref(self.iter.heap, cell),
- );
+ let cell = heap_bound_store(self.iter.heap, heap_bound_deref(self.iter.heap, cell));
let cell = unmark_cell_bits!(cell);
match self.var_names.get(&cell).cloned() {
NumberFocus::Denominator(r),
left_directed_op,
));
- self.state_stack.push(TokenOrRedirect::Op(rdiv_ct, *op_desc));
+ self.state_stack
+ .push(TokenOrRedirect::Op(rdiv_ct, *op_desc));
self.state_stack.push(TokenOrRedirect::NumberFocus(
max_depth,
NumberFocus::Numerator(r),
HeapCellValueTag::PStr | HeapCellValueTag::PStrOffset => {
self.iter.pop_stack();
}
- HeapCellValueTag::CStr => {
- }
+ HeapCellValueTag::CStr => {}
_ => {
unreachable!();
}
append_str!(self, "[]");
}
} else {
- self.state_stack.push(TokenOrRedirect::FunctorRedirect(max_depth));
- self.iter.push_stack(IterStackLoc::iterable_loc(end_h, HeapOrStackTag::Heap));
+ self.state_stack
+ .push(TokenOrRedirect::FunctorRedirect(max_depth));
+ self.iter
+ .push_stack(IterStackLoc::iterable_loc(end_h, HeapOrStackTag::Heap));
}
}
} else {
}
}
- self.state_stack.push(TokenOrRedirect::CloseList(switch.clone()));
+ self.state_stack
+ .push(TokenOrRedirect::CloseList(switch.clone()));
Some(switch)
}
let switch = self.close_list(cell);
- self.state_stack.push(TokenOrRedirect::FunctorRedirect(max_depth));
+ self.state_stack
+ .push(TokenOrRedirect::FunctorRedirect(max_depth));
self.state_stack.push(TokenOrRedirect::HeadTailSeparator); // bar
- self.state_stack.push(TokenOrRedirect::FunctorRedirect(max_depth+1));
+ self.state_stack
+ .push(TokenOrRedirect::FunctorRedirect(max_depth + 1));
self.open_list(switch);
}
max_depth: usize,
) {
let add_brackets = if !self.ignore_ops {
- negated_operand ||
- if let Some(ref op) = op {
+ negated_operand
+ || if let Some(ref op) = op {
if self.numbervars && arity == 1 && name == atom!("$VAR") {
!self.iter.immediate_leaf_has_property(|addr| {
match Number::try_from(addr) {
self.state_stack.push(TokenOrRedirect::Open);
if !self.outputter.ends_with(" ") {
- let parent_op = self.parent_of_first_op
+ let parent_op = self
+ .parent_of_first_op
.and_then(|(parent_op, last_item_idx)| {
// if parent_op isn't printed to the output string
// already, then it doesn't border the present op
for op in &[op, parent_op] {
if let Some(ref op) = &op {
- if op.is_left() && (op.is_prefix() || requires_space(op.as_atom().as_str(), "(")) {
+ if op.is_left()
+ && (op.is_prefix() || requires_space(op.as_atom().as_str(), "("))
+ {
self.state_stack.push(TokenOrRedirect::Space);
return;
}
if let Some(ref op) = op {
let op_is_prefix = op.is_prefix() && op.is_left();
- if op_is_prefix || printer.outputter.ends_with(&format!(" {}", op.as_atom().as_str())) {
+ if op_is_prefix
+ || printer
+ .outputter
+ .ends_with(&format!(" {}", op.as_atom().as_str()))
+ {
result.push(' ');
}
None => return,
};
- if !addr.is_var() && !addr.is_compound(&self.iter.heap) && self.max_depth_exhausted(max_depth) {
+ if !addr.is_var()
+ && !addr.is_compound(&self.iter.heap)
+ && self.max_depth_exhausted(max_depth)
+ {
self.state_stack.push(TokenOrRedirect::Atom(atom!("...")));
return;
}
let b_atom = atom!("b");
let c_atom = atom!("c");
- wam.machine_st.heap.extend(functor!(f_atom, [atom(a_atom), atom(b_atom)]));
+ wam.machine_st
+ .heap
+ .extend(functor!(f_atom, [atom(a_atom), atom(b_atom)]));
{
let printer = HCPrinter::new(
&mut wam.machine_st.stack,
&wam.op_dir,
PrinterOutputter::new(),
- heap_loc_as_cell!(0)
+ heap_loc_as_cell!(0),
);
let output = printer.print();
&mut wam.machine_st.stack,
&wam.op_dir,
PrinterOutputter::new(),
- heap_loc_as_cell!(0)
+ heap_loc_as_cell!(0),
);
let output = printer.print();
&mut wam.machine_st.stack,
&wam.op_dir,
PrinterOutputter::new(),
- heap_loc_as_cell!(0)
+ heap_loc_as_cell!(0),
);
let output = printer.print();
&mut wam.machine_st.stack,
&wam.op_dir,
PrinterOutputter::new(),
- heap_loc_as_cell!(0)
+ heap_loc_as_cell!(0),
);
- printer.var_names.insert(list_loc_as_cell!(1), VarPtr::from("L"));
+ printer
+ .var_names
+ .insert(list_loc_as_cell!(1), VarPtr::from("L"));
let output = printer.print();
&mut wam.machine_st.stack,
&wam.op_dir,
PrinterOutputter::new(),
- heap_loc_as_cell!(0)
+ heap_loc_as_cell!(0),
);
- printer.var_names.insert(list_loc_as_cell!(1), VarPtr::from("L"));
+ printer
+ .var_names
+ .insert(list_loc_as_cell!(1), VarPtr::from("L"));
let output = printer.print();
&mut wam.machine_st.stack,
&wam.op_dir,
PrinterOutputter::new(),
- heap_loc_as_cell!(0)
+ heap_loc_as_cell!(0),
);
printer.max_depth = 5;
wam.machine_st.heap.clear();
- put_partial_string(&mut wam.machine_st.heap, "abc", &mut wam.machine_st.atom_tbl);
+ put_partial_string(
+ &mut wam.machine_st.heap,
+ "abc",
+ &mut wam.machine_st.atom_tbl,
+ );
{
let printer = HCPrinter::new(
&mut wam.machine_st.stack,
&wam.op_dir,
PrinterOutputter::new(),
- pstr_loc_as_cell!(0)
+ pstr_loc_as_cell!(0),
);
let output = printer.print();
all_cells_unmarked(&wam.machine_st.heap);
- wam.op_dir.insert(
- (atom!("+"), Fixity::In),
- OpDesc::build_with(500, YFX as u8),
- );
- wam.op_dir.insert(
- (atom!("*"), Fixity::In),
- OpDesc::build_with(400, YFX as u8),
- );
+ wam.op_dir
+ .insert((atom!("+"), Fixity::In), OpDesc::build_with(500, YFX as u8));
+ wam.op_dir
+ .insert((atom!("*"), Fixity::In), OpDesc::build_with(400, YFX as u8));
- assert_eq!(&wam.parse_and_print_term("[a|[] + b].").unwrap(), "[a|[]+b]");
+ assert_eq!(
+ &wam.parse_and_print_term("[a|[] + b].").unwrap(),
+ "[a|[]+b]"
+ );
all_cells_unmarked(&wam.machine_st.heap);
- assert_eq!(&wam.parse_and_print_term("[a|[b|c]*d].").unwrap(), "[a|[b|c]*d]");
+ assert_eq!(
+ &wam.parse_and_print_term("[a|[b|c]*d].").unwrap(),
+ "[a|[b|c]*d]"
+ );
all_cells_unmarked(&wam.machine_st.heap);
- wam.op_dir.insert(
- (atom!("fy"), Fixity::Pre),
- OpDesc::build_with(9, FY as u8),
- );
+ wam.op_dir
+ .insert((atom!("fy"), Fixity::Pre), OpDesc::build_with(9, FY as u8));
- wam.op_dir.insert(
- (atom!("yf"), Fixity::Post),
- OpDesc::build_with(9, YF as u8),
- );
+ wam.op_dir
+ .insert((atom!("yf"), Fixity::Post), OpDesc::build_with(9, YF as u8));
- assert_eq!(&wam.parse_and_print_term("(fy (fy 1)yf)yf.").unwrap(), "(fy (fy 1)yf)yf");
+ assert_eq!(
+ &wam.parse_and_print_term("(fy (fy 1)yf)yf.").unwrap(),
+ "(fy (fy 1)yf)yf"
+ );
- assert_eq!(&wam.parse_and_print_term("fy(fy(yf(fy(1)))).").unwrap(), "fy fy (fy 1)yf");
+ assert_eq!(
+ &wam.parse_and_print_term("fy(fy(yf(fy(1)))).").unwrap(),
+ "fy fy (fy 1)yf"
+ );
}
}
-use std::sync::{Arc, Mutex, Condvar};
-use std::future::Future;
-use std::pin::Pin;
-use http_body_util::Full;
use bytes::Bytes;
+use http_body_util::Full;
use hyper::service::Service;
use hyper::{body::Incoming as IncomingBody, Request, Response};
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::{Arc, Condvar, Mutex};
pub struct HttpListener {
- pub incoming: std::sync::mpsc::Receiver<HttpRequest>
+ pub incoming: std::sync::mpsc::Receiver<HttpRequest>,
}
#[derive(Debug)]
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn call(&mut self, req: Request<IncomingBody>) -> Self::Future {
- // new connection!
- // we send the Request info to Prolog
- let response = Arc::new((Mutex::new(false), Mutex::new(None), Condvar::new()));
- let http_request = HttpRequest { request: req, response: Arc::clone(&response) };
- self.tx.send(http_request).unwrap();
+ // new connection!
+ // we send the Request info to Prolog
+ let response = Arc::new((Mutex::new(false), Mutex::new(None), Condvar::new()));
+ let http_request = HttpRequest {
+ request: req,
+ response: Arc::clone(&response),
+ };
+ self.tx.send(http_request).unwrap();
- // we wait for the Response info from Prolog
- {
- let (ready, _response, cvar) = &*response;
- let mut ready = ready.lock().unwrap();
- while !*ready {
- ready = cvar.wait(ready).unwrap();
- }
- }
- {
- let (_, response, _) = &*response;
- let response = response.lock().unwrap().take();
- let res = response.expect("Data race error in HTTP Server");
- Box::pin(async move {
- Ok(res)
- })
- }
+ // we wait for the Response info from Prolog
+ {
+ let (ready, _response, cvar) = &*response;
+ let mut ready = ready.lock().unwrap();
+ while !*ready {
+ ready = cvar.wait(ready).unwrap();
+ }
+ }
+ {
+ let (_, response, _) = &*response;
+ let response = response.lock().unwrap().take();
+ let res = response.expect("Data race error in HTTP Server");
+ Box::pin(async move { Ok(res) })
+ }
}
}
let third_level_index = if self.append_or_prepend.is_append() {
vec![
IndexedChoiceInstruction::Try(external),
- IndexedChoiceInstruction::Trust(index)
- ].into()
+ IndexedChoiceInstruction::Trust(index),
+ ]
+ .into()
} else {
vec![
IndexedChoiceInstruction::Try(index),
- IndexedChoiceInstruction::Trust(external)
- ].into()
+ IndexedChoiceInstruction::Trust(external),
+ ]
+ .into()
};
let indexing_code_len = self.indexing_code.len();
- self.indexing_code.push(IndexingLine::IndexedChoice(third_level_index));
+ self.indexing_code
+ .push(IndexingLine::IndexedChoice(third_level_index));
match &mut self.indexing_code[self.offset] {
IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(ref mut constants)) => {
};
let indexing_code_len = self.indexing_code.len();
- self.indexing_code.push(IndexingLine::DynamicIndexedChoice(third_level_index));
+ self.indexing_code
+ .push(IndexingLine::DynamicIndexedChoice(third_level_index));
match &mut self.indexing_code[self.offset] {
IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(ref mut constants)) => {
);
}
None | Some(IndexingCodePtr::Fail) => {
- constants.insert(
- overlapping_constant,
- IndexingCodePtr::External(index),
- );
+ constants
+ .insert(overlapping_constant, IndexingCodePtr::External(index));
}
Some(IndexingCodePtr::DynamicExternal(o)) => {
self.add_dynamic_indexed_choice_for_constant(
IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(constants)) => {
match constants.get(&constant).cloned() {
None | Some(IndexingCodePtr::Fail) if self.is_dynamic => {
- constants.insert(
- constant,
- IndexingCodePtr::DynamicExternal(index),
- );
+ constants.insert(constant, IndexingCodePtr::DynamicExternal(index));
}
None | Some(IndexingCodePtr::Fail) => {
- constants.insert(
- constant,
- IndexingCodePtr::External(index),
- );
+ constants.insert(constant, IndexingCodePtr::External(index));
}
Some(IndexingCodePtr::DynamicExternal(o)) => {
self.add_dynamic_indexed_choice_for_constant(o, constant, index);
let third_level_index = if self.append_or_prepend.is_append() {
vec![
IndexedChoiceInstruction::Try(external),
- IndexedChoiceInstruction::Trust(index)
- ].into()
+ IndexedChoiceInstruction::Trust(index),
+ ]
+ .into()
} else {
vec![
IndexedChoiceInstruction::Try(index),
- IndexedChoiceInstruction::Trust(external)
- ].into()
+ IndexedChoiceInstruction::Trust(external),
+ ]
+ .into()
};
let indexing_code_len = self.indexing_code.len();
- self.indexing_code.push(IndexingLine::IndexedChoice(third_level_index));
+ self.indexing_code
+ .push(IndexingLine::IndexedChoice(third_level_index));
match &mut self.indexing_code[self.offset] {
IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(ref mut structures)) => {
};
let indexing_code_len = self.indexing_code.len();
- self.indexing_code.push(IndexingLine::DynamicIndexedChoice(third_level_index));
+ self.indexing_code
+ .push(IndexingLine::DynamicIndexedChoice(third_level_index));
match &mut self.indexing_code[self.offset] {
IndexingLine::Indexing(IndexingInstruction::SwitchOnStructure(ref mut structures)) => {
let third_level_index = if self.append_or_prepend.is_append() {
vec![
IndexedChoiceInstruction::Try(o),
- IndexedChoiceInstruction::Trust(index)
- ].into()
+ IndexedChoiceInstruction::Trust(index),
+ ]
+ .into()
} else {
vec![
IndexedChoiceInstruction::Try(index),
- IndexedChoiceInstruction::Trust(o)
- ].into()
+ IndexedChoiceInstruction::Trust(o),
+ ]
+ .into()
};
self.indexing_code
target_indexing_code: &mut Vec<IndexingLine>,
skeleton: &mut [ClauseIndexInfo], // the clause to be merged is the last element in the skeleton.
retracted_clauses: &Option<Vec<ClauseIndexInfo>>,
- new_clause_loc: usize, // the absolute location of the new clause in the code vector.
+ new_clause_loc: usize, // the absolute location of the new clause in the code vector.
append_or_prepend: AppendOrPrepend,
) {
let opt_arg_index_key = match append_or_prepend {
for overlapping_constant in overlapping_constants {
merging_ptr.offset = 0;
- merging_ptr.index_overlapping_constant(
- *constant,
- *overlapping_constant,
- offset,
- );
+ merging_ptr.index_overlapping_constant(*constant, *overlapping_constant, offset);
}
}
OptArgIndexKey::Structure(_, index_loc, name, arity) => {
#[inline]
fn cap_choice_seq_with_trust(prelude: &mut [IndexedChoiceInstruction]) {
- prelude.last_mut().map(|instr| {
- match instr {
- IndexedChoiceInstruction::Retry(i) => {
- *instr = IndexedChoiceInstruction::Trust(*i);
- }
- IndexedChoiceInstruction::DefaultRetry(i) => {
- *instr = IndexedChoiceInstruction::DefaultTrust(*i);
- }
- _ => {}
+ prelude.last_mut().map(|instr| match instr {
+ IndexedChoiceInstruction::Retry(i) => {
+ *instr = IndexedChoiceInstruction::Trust(*i);
}
+ IndexedChoiceInstruction::DefaultRetry(i) => {
+ *instr = IndexedChoiceInstruction::DefaultTrust(*i);
+ }
+ _ => {}
});
}
#[inline]
fn uncap_choice_seq_with_trust(prelude: &mut [IndexedChoiceInstruction]) {
- prelude.last_mut().map(|instr| {
- match instr {
- IndexedChoiceInstruction::Trust(i) => {
- *instr = IndexedChoiceInstruction::Retry(*i);
- }
- IndexedChoiceInstruction::DefaultTrust(i) => {
- *instr = IndexedChoiceInstruction::DefaultRetry(*i);
- }
- _ => {}
+ prelude.last_mut().map(|instr| match instr {
+ IndexedChoiceInstruction::Trust(i) => {
+ *instr = IndexedChoiceInstruction::Retry(*i);
+ }
+ IndexedChoiceInstruction::DefaultTrust(i) => {
+ *instr = IndexedChoiceInstruction::DefaultRetry(*i);
}
+ _ => {}
});
}
*/
Literal::Integer(ref n) => {
if let Some(n) = n.to_isize() {
- Fixnum::build_with_checked(n as i64).map(|n| {
- constants.push(Literal::Fixnum(n));
- }).unwrap();
+ Fixnum::build_with_checked(n as i64)
+ .map(|n| {
+ constants.push(Literal::Fixnum(n));
+ })
+ .unwrap();
}
}
_ => {}
fn new() -> Self;
- fn constants(&mut self) -> &mut IndexMap<Literal, VecDeque<Self::ThirdLevelIndex>, FxBuildHasher>;
+ fn constants(
+ &mut self,
+ ) -> &mut IndexMap<Literal, VecDeque<Self::ThirdLevelIndex>, FxBuildHasher>;
fn lists(&mut self) -> &mut VecDeque<Self::ThirdLevelIndex>;
- fn structures(&mut self) -> &mut IndexMap<(Atom, usize), VecDeque<Self::ThirdLevelIndex>, FxBuildHasher>;
+ fn structures(
+ &mut self,
+ ) -> &mut IndexMap<(Atom, usize), VecDeque<Self::ThirdLevelIndex>, FxBuildHasher>;
- fn compute_index(is_initial_index: bool, index: usize, non_counted_bt: bool) -> Self::ThirdLevelIndex;
+ fn compute_index(
+ is_initial_index: bool,
+ index: usize,
+ non_counted_bt: bool,
+ ) -> Self::ThirdLevelIndex;
fn second_level_index<IndexKey: Eq + Hash>(
indices: IndexMap<IndexKey, VecDeque<Self::ThirdLevelIndex>, FxBuildHasher>,
}
#[inline]
- fn constants(&mut self) -> &mut IndexMap<Literal, VecDeque<IndexedChoiceInstruction>, FxBuildHasher> {
+ fn constants(
+ &mut self,
+ ) -> &mut IndexMap<Literal, VecDeque<IndexedChoiceInstruction>, FxBuildHasher> {
&mut self.constants
}
}
#[inline]
- fn structures(&mut self) -> &mut IndexMap<(Atom, usize), VecDeque<IndexedChoiceInstruction>, FxBuildHasher> {
+ fn structures(
+ &mut self,
+ ) -> &mut IndexMap<(Atom, usize), VecDeque<IndexedChoiceInstruction>, FxBuildHasher> {
&mut self.structures
}
- fn compute_index(is_initial_index: bool, index: usize, non_counted_bt: bool) -> IndexedChoiceInstruction {
+ fn compute_index(
+ is_initial_index: bool,
+ index: usize,
+ non_counted_bt: bool,
+ ) -> IndexedChoiceInstruction {
if is_initial_index {
IndexedChoiceInstruction::Try(index + 1)
} else if non_counted_bt {
}
fn switch_on<IndexKey: Eq + Hash>(
- mut instr_fn: impl FnMut(IndexMap<IndexKey, IndexingCodePtr, FxBuildHasher>) -> IndexingInstruction,
+ mut instr_fn: impl FnMut(
+ IndexMap<IndexKey, IndexingCodePtr, FxBuildHasher>,
+ ) -> IndexingInstruction,
index: &mut IndexMap<IndexKey, VecDeque<IndexedChoiceInstruction>, FxBuildHasher>,
prelude: &mut VecDeque<IndexingLine>,
) -> IndexingCodePtr {
for (key, code) in indices.into_iter() {
if code.len() > 1 {
index_locs.insert(key, IndexingCodePtr::Internal(prelude.len() + 1));
- prelude.push_back(IndexingLine::DynamicIndexedChoice(code.into_iter().collect()));
+ prelude.push_back(IndexingLine::DynamicIndexedChoice(
+ code.into_iter().collect(),
+ ));
} else {
code.front().map(|i| {
index_locs.insert(key, IndexingCodePtr::DynamicExternal(*i));
}
fn switch_on<IndexKey: Eq + Hash>(
- mut instr_fn: impl FnMut(IndexMap<IndexKey, IndexingCodePtr, FxBuildHasher>) -> IndexingInstruction,
+ mut instr_fn: impl FnMut(
+ IndexMap<IndexKey, IndexingCodePtr, FxBuildHasher>,
+ ) -> IndexingInstruction,
index: &mut IndexMap<IndexKey, VecDeque<usize>, FxBuildHasher>,
prelude: &mut VecDeque<IndexingLine>,
) -> IndexingCodePtr {
) -> IndexingCodePtr {
if lists.len() > 1 {
let lists = mem::replace(lists, VecDeque::new());
- prelude.push_back(IndexingLine::DynamicIndexedChoice(lists.into_iter().collect()));
+ prelude.push_back(IndexingLine::DynamicIndexedChoice(
+ lists.into_iter().collect(),
+ ));
IndexingCodePtr::Internal(1)
} else {
lists
index: usize,
) -> Vec<Literal> {
let overlapping_constants = constant_key_alternatives(constant, atom_tbl);
- let code = self.indices.constants().entry(constant).or_insert(VecDeque::new());
+ let code = self
+ .indices
+ .constants()
+ .entry(constant)
+ .or_insert(VecDeque::new());
let is_initial_index = code.is_empty();
- code.push_back(I::compute_index(is_initial_index, index, self.non_counted_bt));
+ code.push_back(I::compute_index(
+ is_initial_index,
+ index,
+ self.non_counted_bt,
+ ));
for constant in &overlapping_constants {
let code = self
let code_len = code.len();
let is_initial_index = code.is_empty();
- code.push_back(I::compute_index(is_initial_index, index, self.non_counted_bt));
+ code.push_back(I::compute_index(
+ is_initial_index,
+ index,
+ self.non_counted_bt,
+ ));
code_len
}
Term::PartialString(cell, string_buf, tail) => {
TermIterState::InitialPartialString(lvl, cell, string_buf, tail)
}
- Term::CompleteString(cell, atom) => {
- TermIterState::CompleteString(lvl, cell, *atom)
- }
+ Term::CompleteString(cell, atom) => TermIterState::CompleteString(lvl, cell, *atom),
Term::Var(cell, var_ptr) => TermIterState::Var(lvl, cell, var_ptr.clone()),
}
}
impl<'a> QueryIterator<'a> {
fn push_subterm(&mut self, lvl: Level, term: &'a Term) {
- self.state_stack.push(TermIterState::subterm_to_state(lvl, term));
+ self.state_stack
+ .push(TermIterState::subterm_to_state(lvl, term));
}
/*
fn from_term(term: &'a Term) -> Self {
let state = match term {
- Term::AnonVar | Term::Cons(..) | Term::Literal(..) |
- Term::PartialString(..) | Term::CompleteString(..) => {
+ Term::AnonVar
+ | Term::Cons(..)
+ | Term::Literal(..)
+ | Term::PartialString(..)
+ | Term::CompleteString(..) => {
return QueryIterator {
state_stack: vec![],
}
}
- Term::Clause(r, name, terms) => TermIterState::Clause(
- Level::Root,
- 0,
- r,
- *name,
- terms,
- ),
+ Term::Clause(r, name, terms) => TermIterState::Clause(Level::Root, 0, r, *name, terms),
Term::Var(cell, var_ptr) => TermIterState::Var(Level::Root, cell, var_ptr.clone()),
};
fn extend_state(&mut self, lvl: Level, term: &'a QueryTerm) {
match term {
&QueryTerm::Clause(ref cell, ClauseType::CallN(_), ref terms, _) => {
- self.state_stack.push(TermIterState::Clause(lvl, 1, cell, atom!("$call"), terms));
+ self.state_stack
+ .push(TermIterState::Clause(lvl, 1, cell, atom!("$call"), terms));
}
&QueryTerm::Clause(ref cell, ref ct, ref terms, _) => {
- self.state_stack.push(TermIterState::Clause(lvl, 0, cell, ct.name(), terms));
- }
- _ => {
+ self.state_stack
+ .push(TermIterState::Clause(lvl, 0, cell, ct.name(), terms));
}
+ _ => {}
}
}
pub fn new(term: &'a QueryTerm) -> Self {
- let mut iter = QueryIterator { state_stack: vec![] };
+ let mut iter = QueryIterator {
+ state_stack: vec![],
+ };
iter.extend_state(Level::Root, term);
iter
}
}
}
TermIterState::InitialCons(lvl, cell, head, tail) => {
- self.state_stack.push(TermIterState::FinalCons(lvl, cell, head, tail));
+ self.state_stack
+ .push(TermIterState::FinalCons(lvl, cell, head, tail));
self.push_subterm(lvl.child_level(), tail);
self.push_subterm(lvl.child_level(), head);
}
TermIterState::InitialPartialString(lvl, cell, string, tail) => {
- self.state_stack.push(TermIterState::FinalPartialString(lvl, cell, string, tail));
+ self.state_stack
+ .push(TermIterState::FinalPartialString(lvl, cell, string, tail));
self.push_subterm(lvl.child_level(), tail);
}
TermIterState::FinalPartialString(lvl, cell, atom, tail) => {
)]
}
Term::CompleteString(cell, atom) => {
- vec![TermIterState::CompleteString(
- Level::Root,
- cell,
- *atom,
- )]
+ vec![TermIterState::CompleteString(Level::Root, cell, *atom)]
}
Term::Literal(cell, constant) => {
vec![TermIterState::Literal(Level::Root, cell, constant)]
QueryIterator::from_term(term)
}
-pub(crate) fn breadth_first_iter<'a>(term: &'a Term, iterable_root: RootIterationPolicy) -> FactIterator<'a> {
+pub(crate) fn breadth_first_iter<'a>(
+ term: &'a Term,
+ iterable_root: RootIterationPolicy,
+) -> FactIterator<'a> {
FactIterator::new(term, iterable_root)
}
impl<'a> ClauseIterator<'a> {
pub fn new(clauses: &'a ChunkedTermVec) -> Self {
match state_from_chunked_terms(&clauses.chunk_vec) {
- state @ ClauseIteratorState::RemainingBranches(..) => {
- Self {
- state_stack: vec![state],
- remaining_chunks_on_stack: 0,
- }
- }
- state @ ClauseIteratorState::RemainingChunks(..) => {
- Self {
- state_stack: vec![state],
- remaining_chunks_on_stack: 1,
- }
- }
+ state @ ClauseIteratorState::RemainingBranches(..) => Self {
+ state_stack: vec![state],
+ remaining_chunks_on_stack: 0,
+ },
+ state @ ClauseIteratorState::RemainingChunks(..) => Self {
+ state_stack: vec![state],
+ remaining_chunks_on_stack: 1,
+ },
}
}
match state {
ClauseIteratorState::RemainingChunks(chunks, focus) if focus < chunks.len() => {
if focus + 1 < chunks.len() {
- self.state_stack.push(ClauseIteratorState::RemainingChunks(chunks, focus + 1));
+ self.state_stack
+ .push(ClauseIteratorState::RemainingChunks(chunks, focus + 1));
} else {
self.remaining_chunks_on_stack -= 1;
}
match &chunks[focus] {
ChunkedTerms::Branch(branches) => {
- self.state_stack.push(ClauseIteratorState::RemainingBranches(branches, 0));
+ self.state_stack
+ .push(ClauseIteratorState::RemainingBranches(branches, 0));
}
ChunkedTerms::Chunk(chunk) => {
return Some(ClauseItem::Chunk(chunk));
ClauseIteratorState::RemainingChunks(chunks, focus) => {
debug_assert_eq!(chunks.len(), focus);
}
- ClauseIteratorState::RemainingBranches(branches, focus) if focus < branches.len() => {
- self.state_stack.push(ClauseIteratorState::RemainingBranches(&branches, focus + 1));
+ ClauseIteratorState::RemainingBranches(branches, focus)
+ if focus < branches.len() =>
+ {
+ self.state_stack
+ .push(ClauseIteratorState::RemainingBranches(&branches, focus + 1));
let state = state_from_chunked_terms(&branches[focus]);
if let ClauseIteratorState::RemainingChunks(..) = &state {
mod debray_allocator;
#[cfg(feature = "ffi")]
mod ffi;
-mod variable_records;
mod forms;
mod heap_iter;
pub mod heap_print;
#[cfg(feature = "http")]
mod http;
mod indexing;
+mod variable_records;
#[macro_use]
pub mod instructions {
include!(concat!(env!("OUT_DIR"), "/instructions.rs"));
};
}
-fn zero_divisor_eval_error(
- stub_gen: impl Fn() -> FunctorStub + 'static,
-) -> MachineStubGen {
+fn zero_divisor_eval_error(stub_gen: impl Fn() -> FunctorStub + 'static) -> MachineStubGen {
Box::new(move |machine_st| {
let eval_error = machine_st.evaluation_error(EvalError::ZeroDivisor);
let stub = stub_gen();
})
}
-fn undefined_eval_error(
- stub_gen: impl Fn() -> FunctorStub + 'static,
-) -> MachineStubGen {
+fn undefined_eval_error(stub_gen: impl Fn() -> FunctorStub + 'static) -> MachineStubGen {
Box::new(move |machine_st| {
let eval_error = machine_st.evaluation_error(EvalError::Undefined);
let stub = stub_gen();
Ok(Number::Float(add_f(float_i_to_f(&n1)?, n2)?))
}
(Number::Integer(n1), Number::Rational(n2))
- | (Number::Rational(n2), Number::Integer(n1)) => {
- Ok(Number::arena_from(&*n1 + &*n2, arena))
- }
+ | (Number::Rational(n2), Number::Integer(n1)) => Ok(Number::arena_from(&*n1 + &*n2, arena)),
(Number::Rational(n1), Number::Float(OrderedFloat(n2)))
| (Number::Float(OrderedFloat(n2)), Number::Rational(n1)) => {
Ok(Number::Float(add_f(float_r_to_f(&n1)?, n2)?))
(Number::Float(OrderedFloat(f1)), Number::Float(OrderedFloat(f2))) => {
Ok(Number::Float(add_f(f1, f2)?))
}
- (Number::Rational(r1), Number::Rational(r2)) => {
- Ok(Number::arena_from(&*r1 + &*r2, arena))
- }
+ (Number::Rational(r1), Number::Rational(r2)) => Ok(Number::arena_from(&*r1 + &*r2, arena)),
}
}
Number::Integer(n) => {
let n_clone: Integer = (*n).clone();
Number::arena_from(-Integer::from(n_clone), arena)
- },
+ }
Number::Float(OrderedFloat(f)) => Number::Float(OrderedFloat(-f)),
Number::Rational(r) => {
let r_clone: Rational = (*r).clone();
Number::arena_from(-Rational::from(r_clone), arena)
- },
+ }
}
}
Number::Integer(n) => {
let n_clone: Integer = (*n).clone();
Number::arena_from(Integer::from(n_clone.abs()), arena)
- },
+ }
Number::Float(f) => Number::Float(f.abs()),
Number::Rational(r) => {
let r_clone: Rational = (*r).clone();
Number::arena_from(Rational::from(r_clone.abs()), arena)
- },
+ }
}
}
(Number::Integer(n1), Number::Fixnum(n2)) => {
let n2_i = n2.get_num();
- if !(&*n1 == &Integer::from(1) || &*n1 == &Integer::from(0) || &*n1 == &Integer::from(-1)) && n2_i < 0 {
+ if !(&*n1 == &Integer::from(1)
+ || &*n1 == &Integer::from(0)
+ || &*n1 == &Integer::from(-1))
+ && n2_i < 0
+ {
let n = Number::Integer(n1);
Err(numerical_type_error(ValidType::Float, n, stub_gen))
} else {
}
}
(Number::Integer(n1), Number::Integer(n2)) => {
- if !(&*n1 == &Integer::from(1) || &*n1 == &Integer::from(0) || &*n1 == &Integer::from(-1)) && &*n2 < &Integer::from(0) {
+ if !(&*n1 == &Integer::from(1)
+ || &*n1 == &Integer::from(0)
+ || &*n1 == &Integer::from(-1))
+ && &*n2 < &Integer::from(0)
+ {
let n = Number::Integer(n1);
Err(numerical_type_error(ValidType::Float, n, stub_gen))
} else {
Number::Integer(n) => {
let n_clone: Integer = (*n).clone();
Ok(arena_alloc!(Rational::from(n_clone), arena))
- },
+ }
}
}
if let Ok(n2) = usize::try_from(n2_i) {
return Ok(Number::arena_from(n1 >> n2, arena));
- } else {
+ } else {
return Ok(Number::arena_from(n1 >> usize::max_value(), arena));
}
}
match n2.to_usize() {
Some(n2) => Ok(Number::arena_from(n1 >> n2, arena)),
- _ => {
- Ok(Number::arena_from(n1 >> usize::max_value(), arena))
- },
+ _ => Ok(Number::arena_from(n1 >> usize::max_value(), arena)),
}
}
(Number::Integer(n1), Number::Fixnum(n2)) => match usize::try_from(n2.get_num()) {
Ok(n2) => Ok(Number::arena_from(Integer::from(&*n1 >> n2), arena)),
- _ => {
- Ok(Number::arena_from(Integer::from(&*n1 >> usize::max_value()),arena))
- },
+ _ => Ok(Number::arena_from(
+ Integer::from(&*n1 >> usize::max_value()),
+ arena,
+ )),
},
(Number::Integer(n1), Number::Integer(n2)) => match n2.to_usize() {
Some(n2) => Ok(Number::arena_from(Integer::from(&*n1 >> n2), arena)),
- _ => {
- Ok(Number::arena_from(Integer::from(&*n1 >> usize::max_value()), arena))
- },
+ _ => Ok(Number::arena_from(
+ Integer::from(&*n1 >> usize::max_value()),
+ arena,
+ )),
},
(Number::Integer(_), n2) => Err(numerical_type_error(ValidType::Integer, n2, stub_gen)),
(Number::Fixnum(_), n2) => Err(numerical_type_error(ValidType::Integer, n2, stub_gen)),
if let Ok(n2) = usize::try_from(n2_i) {
return Ok(Number::arena_from(n1 << n2, arena));
- } else {
+ } else {
return Ok(Number::arena_from(n1 << usize::max_value(), arena));
}
}
match n2.to_u32() {
Some(n2) => Ok(Number::arena_from(n1.to_u64().unwrap() << n2, arena)),
- _ => {
- Ok(Number::arena_from(n1 << usize::max_value(), arena))
- }
+ _ => Ok(Number::arena_from(n1 << usize::max_value(), arena)),
}
}
(Number::Integer(n1), Number::Fixnum(n2)) => match usize::try_from(n2.get_num()) {
Ok(n2) => Ok(Number::arena_from(Integer::from(&*n1 << n2), arena)),
- _ => {
- Ok(Number::arena_from(Integer::from(&*n1 << usize::max_value()),arena))
- }
+ _ => Ok(Number::arena_from(
+ Integer::from(&*n1 << usize::max_value()),
+ arena,
+ )),
},
(Number::Integer(n1), Number::Integer(n2)) => match n2.to_u32() {
- Some(n2) => Ok(Number::arena_from(Integer::from(n1.to_u64().unwrap() << n2), arena)),
- _ => {
- Ok(Number::arena_from(Integer::from(&*n1 << usize::max_value()),arena))
- }
+ Some(n2) => Ok(Number::arena_from(
+ Integer::from(n1.to_u64().unwrap() << n2),
+ arena,
+ )),
+ _ => Ok(Number::arena_from(
+ Integer::from(&*n1 << usize::max_value()),
+ arena,
+ )),
},
(Number::Integer(_), n2) => Err(numerical_type_error(ValidType::Integer, n2, stub_gen)),
(Number::Fixnum(_), n2) => Err(numerical_type_error(ValidType::Integer, n2, stub_gen)),
Ok(Number::arena_from(result, arena))
} else {
let value: IBig = Integer::from(n1_i).gcd(&Integer::from(n2_i)).into();
- Ok(Number::arena_from(
- value,
- arena,
- ))
+ Ok(Number::arena_from(value, arena))
}
}
(Number::Fixnum(n1), Number::Integer(n2)) | (Number::Integer(n2), Number::Fixnum(n1)) => {
}
(Number::Integer(n1), Number::Integer(n2)) => {
let n1_clone: Integer = (*n1).clone();
- Ok(Number::arena_from(Integer::from(n1_clone.gcd(&Integer::from(n2.to_isize().unwrap()))) as IBig, arena))
+ Ok(Number::arena_from(
+ Integer::from(n1_clone.gcd(&Integer::from(n2.to_isize().unwrap()))) as IBig,
+ arena,
+ ))
}
(Number::Float(f), _) | (_, Number::Float(f)) => {
let n = Number::Float(f);
let f1 = try_numeric_result!(result_f(&n1), stub_gen)?;
- try_numeric_result!(if f1 == 1.0 || f1 == -1.0 {
- Err(EvalError::Undefined)
- } else {
- result_f(&Number::Float(OrderedFloat(f1.atanh())))
- },
- stub_gen)
+ try_numeric_result!(
+ if f1 == 1.0 || f1 == -1.0 {
+ Err(EvalError::Undefined)
+ } else {
+ result_f(&Number::Float(OrderedFloat(f1.atanh())))
+ },
+ stub_gen
+ )
}
#[inline]
rnd_i(&n1, arena)
}
-
#[inline]
pub(crate) fn ceiling(n1: Number, arena: &mut Arena) -> Number {
let n1 = neg(n1, arena);
pub fn get_number(&mut self, at: &ArithmeticTerm) -> Result<Number, MachineStub> {
match at {
&ArithmeticTerm::Reg(r) => {
- let value = self.store(self.deref(self[r]));
+ let value = self.store(self.deref(self[r]));
match Number::try_from(value) {
Ok(n) => Ok(n),
Err(_) => self.arith_eval_by_metacall(value),
}
}
- &ArithmeticTerm::Interm(i) => {
- Ok(mem::replace(&mut self.interms[i - 1], Number::Fixnum(Fixnum::build_with(0))))
- }
+ &ArithmeticTerm::Interm(i) => Ok(mem::replace(
+ &mut self.interms[i - 1],
+ Number::Fixnum(Fixnum::build_with(0)),
+ )),
&ArithmeticTerm::Number(n) => Ok(n),
}
}
match rational_from_number(n, caller, &mut self.arena) {
Ok(r) => Ok(r),
- Err(e_gen) => Err(e_gen(self))
+ Err(e_gen) => Err(e_gen(self)),
}
}
- pub(crate) fn arith_eval_by_metacall(&mut self, value: HeapCellValue) -> Result<Number, MachineStub> {
+ pub(crate) fn arith_eval_by_metacall(
+ &mut self,
+ value: HeapCellValue,
+ ) -> Result<Number, MachineStub> {
let stub_gen = || functor_stub(atom!("is"), 2);
let mut iter = stackful_post_order_iter(&mut self.heap, &mut self.stack, value);
let mut wam = MachineState::new();
let mut op_dir = default_op_dir();
- op_dir.insert(
- (atom!("+"), Fixity::In),
- OpDesc::build_with(500, YFX as u8),
- );
- op_dir.insert(
- (atom!("-"), Fixity::In),
- OpDesc::build_with(500, YFX as u8),
- );
- op_dir.insert(
- (atom!("-"), Fixity::Pre),
- OpDesc::build_with(200, FY as u8),
- );
- op_dir.insert(
- (atom!("*"), Fixity::In),
- OpDesc::build_with(400, YFX as u8),
- );
- op_dir.insert(
- (atom!("/"), Fixity::In),
- OpDesc::build_with(400, YFX as u8),
- );
+ op_dir.insert((atom!("+"), Fixity::In), OpDesc::build_with(500, YFX as u8));
+ op_dir.insert((atom!("-"), Fixity::In), OpDesc::build_with(500, YFX as u8));
+ op_dir.insert((atom!("-"), Fixity::Pre), OpDesc::build_with(200, FY as u8));
+ op_dir.insert((atom!("*"), Fixity::In), OpDesc::build_with(400, YFX as u8));
+ op_dir.insert((atom!("/"), Fixity::In), OpDesc::build_with(400, YFX as u8));
let term_write_result =
parse_and_write_parsed_term_to_heap(&mut wam, "3 + 4 - 1 + 2.", &op_dir).unwrap();
and_frame[i] = self.registers[i];
}
- and_frame[arity + 1] =
- fixnum_as_cell!(Fixnum::build_with(self.b0 as i64));
- and_frame[arity + 2] =
- fixnum_as_cell!(Fixnum::build_with(self.num_of_args as i64));
- and_frame[arity + 3] =
- fixnum_as_cell!(Fixnum::build_with(self.attr_var_init.cp as i64));
+ and_frame[arity + 1] = fixnum_as_cell!(Fixnum::build_with(self.b0 as i64));
+ and_frame[arity + 2] = fixnum_as_cell!(Fixnum::build_with(self.num_of_args as i64));
+ and_frame[arity + 3] = fixnum_as_cell!(Fixnum::build_with(self.attr_var_init.cp as i64));
self.verify_attributes();
&Instruction::TryMeElse(offset) if offset > 0 => {
stack.push(index + offset);
}
- &Instruction::DefaultRetryMeElse(offset) | &Instruction::RetryMeElse(offset) if offset > 0 => {
+ &Instruction::DefaultRetryMeElse(offset) | &Instruction::RetryMeElse(offset)
+ if offset > 0 =>
+ {
stack.push(index + offset);
}
&Instruction::DynamicElse(_, _, NextOrFail::Next(offset)) if offset > 0 => {
) -> Result<(), SessionError> {
let (wam_prelude, machine_st) = wam.prelude_view_and_machine_st();
- let term_stream = BootstrappingTermStream::from_char_reader(
- stream,
- machine_st,
- listing_src,
- );
+ let term_stream = BootstrappingTermStream::from_char_reader(stream, machine_st, listing_src);
- let payload = BootstrappingLoadState(
- LoadStatePayload::new(wam_prelude.code.len(), term_stream)
- );
+ let payload =
+ BootstrappingLoadState(LoadStatePayload::new(wam_prelude.code.len(), term_stream));
- let loader: Loader<'_, BootstrappingLoadState> = Loader { payload, wam_prelude };
+ let loader: Loader<'_, BootstrappingLoadState> = Loader {
+ payload,
+ wam_prelude,
+ };
loader.load()?;
Ok(())
retraction_info.push_record(RetractionRecord::ReplacedDynamicElseOffset(index, *o));
Some(mem::replace(o, 0))
}
- Instruction::DynamicElse(_, _, NextOrFail::Fail(_)) |
- Instruction::DynamicInternalElse(_, _, NextOrFail::Fail(_)) => None,
+ Instruction::DynamicElse(_, _, NextOrFail::Fail(_))
+ | Instruction::DynamicInternalElse(_, _, NextOrFail::Fail(_)) => None,
Instruction::TryMeElse(0) => None,
Instruction::TryMeElse(ref mut o) => {
retraction_info.push_record(RetractionRecord::ModifiedTryMeElse(index, *o));
fn find_outer_choice_instr(code: &Code, mut index: usize) -> usize {
loop {
match &code[index] {
- Instruction::DynamicElse(_, _, NextOrFail::Next(i)) |
- Instruction::DynamicInternalElse(_, _, NextOrFail::Next(i))
+ Instruction::DynamicElse(_, _, NextOrFail::Next(i))
+ | Instruction::DynamicInternalElse(_, _, NextOrFail::Next(i))
if *i > 0 =>
{
index += i;
fn find_inner_choice_instr(code: &Code, mut index: usize, index_loc: usize) -> usize {
loop {
match &code[index] {
- Instruction::TryMeElse(o) |
- Instruction::RetryMeElse(o) => {
+ Instruction::TryMeElse(o) | Instruction::RetryMeElse(o) => {
if *o > 0 {
return index;
} else {
index = index_loc;
}
}
- &Instruction::DynamicElse(_, _, next_or_fail) => {
- match next_or_fail {
- NextOrFail::Next(i) => {
- if i == 0 {
- index = index_loc;
- } else {
- return index;
- }
- }
- NextOrFail::Fail(_) => {
+ &Instruction::DynamicElse(_, _, next_or_fail) => match next_or_fail {
+ NextOrFail::Next(i) => {
+ if i == 0 {
index = index_loc;
+ } else {
+ return index;
}
}
- }
- &Instruction::DynamicInternalElse(_, _, next_or_fail) => {
- match next_or_fail {
- NextOrFail::Next(i) => {
- if i == 0 {
- index = index_loc;
- } else {
- return index;
- }
- }
- NextOrFail::Fail(_) => {
+ NextOrFail::Fail(_) => {
+ index = index_loc;
+ }
+ },
+ &Instruction::DynamicInternalElse(_, _, next_or_fail) => match next_or_fail {
+ NextOrFail::Next(i) => {
+ if i == 0 {
+ index = index_loc;
+ } else {
return index;
}
}
- }
+ NextOrFail::Fail(_) => {
+ return index;
+ }
+ },
Instruction::TrustMe(_) => {
return index;
}
index += v;
}
IndexingCodePtr::DynamicExternal(v) => match &code[index + v] {
- &Instruction::DynamicInternalElse(
- _,
- _,
- NextOrFail::Next(0),
- ) => {
+ &Instruction::DynamicInternalElse(_, _, NextOrFail::Next(0)) => {
return index + v;
}
_ => {
code[inner_try_me_else_loc] = Instruction::TrustMe(o);
}
_ => {
- code[inner_try_me_else_loc] =
- Instruction::RetryMeElse(o);
+ code[inner_try_me_else_loc] = Instruction::RetryMeElse(o);
}
},
}
}
if skeleton.core.is_dynamic {
- skeleton.core.add_retracted_dynamic_clause_info(clause_index_info);
+ skeleton
+ .core
+ .add_retracted_dynamic_clause_info(clause_index_info);
retraction_info.push_record(RetractionRecord::RemovedDynamicSkeletonClause(
compilation_target,
code[instr_loc] = Instruction::TryMeElse(*o);
return instr_loc;
}
- Instruction::DynamicElse(_, _, NextOrFail::Next(_)) |
- Instruction::DynamicInternalElse(_, _, NextOrFail::Next(_)) => {
+ Instruction::DynamicElse(_, _, NextOrFail::Next(_))
+ | Instruction::DynamicInternalElse(_, _, NextOrFail::Next(_)) => {
return instr_loc;
}
&mut Instruction::DynamicElse(b, d, NextOrFail::Fail(o)) => {
code[instr_loc] = Instruction::DynamicElse(b, d, NextOrFail::Next(0));
return instr_loc;
}
- &mut Instruction::DynamicInternalElse(
- b,
- d,
- NextOrFail::Fail(o),
- ) => {
+ &mut Instruction::DynamicInternalElse(b, d, NextOrFail::Fail(o)) => {
retraction_info.push_record(RetractionRecord::AppendedNextOrFail(
instr_loc,
NextOrFail::Fail(o),
));
- code[instr_loc] = Instruction::DynamicInternalElse(
- b,
- d,
- NextOrFail::Next(0),
- );
+ code[instr_loc] = Instruction::DynamicInternalElse(b, d, NextOrFail::Next(0));
return instr_loc;
}
Instruction::TrustMe(o) => {
- retraction_info.push_record(RetractionRecord::AppendedTrustMe(instr_loc, *o, false));
+ retraction_info
+ .push_record(RetractionRecord::AppendedTrustMe(instr_loc, *o, false));
code[instr_loc] = Instruction::TryMeElse(0);
return instr_loc + 1;
};
match &code[index_loc + v] {
- Instruction::TryMeElse(_) |
- Instruction::DynamicElse(..) |
- Instruction::DynamicInternalElse(..) => {}
+ Instruction::TryMeElse(_)
+ | Instruction::DynamicElse(..)
+ | Instruction::DynamicInternalElse(..) => {}
_ => {
set_switch_var_offset(code, index_loc, offset, retraction_info);
}
retraction_info: &mut RetractionInfo,
) {
match &mut code[instr_loc] {
- Instruction::DynamicElse(_, _, NextOrFail::Fail(_)) |
- Instruction::DynamicInternalElse(_, _, NextOrFail::Fail(_)) => {
- }
+ Instruction::DynamicElse(_, _, NextOrFail::Fail(_))
+ | Instruction::DynamicInternalElse(_, _, NextOrFail::Fail(_)) => {}
Instruction::DynamicElse(_, _, ref mut o @ NextOrFail::Next(0)) => {
retraction_info.push_record(RetractionRecord::ReplacedDynamicElseOffset(instr_loc, 0));
*o = NextOrFail::Fail(0);
match &mut code[instr_loc + o] {
Instruction::RevJmpBy(p) if *p == 0 => {
- code[instr_loc] = Instruction::DynamicInternalElse(
- b,
- d,
- NextOrFail::Fail(o),
- );
+ code[instr_loc] = Instruction::DynamicInternalElse(b, d, NextOrFail::Fail(o));
}
_ => {
- code[instr_loc] = Instruction::DynamicInternalElse(
- b,
- d,
- NextOrFail::Next(o),
- );
+ code[instr_loc] = Instruction::DynamicInternalElse(b, d, NextOrFail::Next(o));
}
}
}
*o = target_loc - instr_loc;
return;
}
- Instruction::DynamicElse(_, _, NextOrFail::Next(ref mut o)) |
- Instruction::DynamicInternalElse(
- _,
- _,
- NextOrFail::Next(ref mut o),
- ) if target_loc >= instr_loc => {
+ Instruction::DynamicElse(_, _, NextOrFail::Next(ref mut o))
+ | Instruction::DynamicInternalElse(_, _, NextOrFail::Next(ref mut o))
+ if target_loc >= instr_loc =>
+ {
retraction_info
.push_record(RetractionRecord::ReplacedDynamicElseOffset(instr_loc, *o));
*o = target_loc - instr_loc;
return;
}
- Instruction::DynamicElse(_, _, NextOrFail::Next(o)) |
- Instruction::DynamicInternalElse(_, _, NextOrFail::Next(o)) => {
+ Instruction::DynamicElse(_, _, NextOrFail::Next(o))
+ | Instruction::DynamicInternalElse(_, _, NextOrFail::Next(o)) => {
instr_loc += *o;
}
- Instruction::TryMeElse(o)
- | Instruction::RetryMeElse(o) => {
+ Instruction::TryMeElse(o) | Instruction::RetryMeElse(o) => {
instr_loc += *o;
}
Instruction::RevJmpBy(ref mut o) if instr_loc >= target_loc => {
{
retraction_info.push_record(RetractionRecord::AppendedNextOrFail(instr_loc, *fail));
- code[instr_loc] = instr!("dynamic_else",
+ code[instr_loc] = instr!(
+ "dynamic_else",
birth,
death,
NextOrFail::Next(target_loc - instr_loc)
Instruction::DynamicElse(_, _, NextOrFail::Fail(o)) if *o > 0 => {
instr_loc += *o;
}
- &mut Instruction::DynamicInternalElse(
- birth,
- death,
- ref mut fail,
- ) if target_loc >= instr_loc => {
+ &mut Instruction::DynamicInternalElse(birth, death, ref mut fail)
+ if target_loc >= instr_loc =>
+ {
retraction_info.push_record(RetractionRecord::AppendedNextOrFail(instr_loc, *fail));
- code[instr_loc] = instr!("dynamic_internal_else",
+ code[instr_loc] = instr!(
+ "dynamic_internal_else",
birth,
death,
NextOrFail::Next(target_loc - instr_loc)
return;
}
- Instruction::DynamicInternalElse(_, _, NextOrFail::Fail(o))
- if *o > 0 =>
- {
+ Instruction::DynamicInternalElse(_, _, NextOrFail::Fail(o)) if *o > 0 => {
instr_loc += *o;
}
Instruction::TrustMe(ref mut o) if target_loc >= instr_loc => {
None
}
- Instruction::TrustMe(_) => {
- match &mut code[preceding_choice_instr_loc] {
- Instruction::RetryMeElse(o) => {
- retraction_info.push_record(RetractionRecord::ModifiedRetryMeElse(
- preceding_choice_instr_loc,
- *o,
- ));
+ Instruction::TrustMe(_) => match &mut code[preceding_choice_instr_loc] {
+ Instruction::RetryMeElse(o) => {
+ retraction_info.push_record(RetractionRecord::ModifiedRetryMeElse(
+ preceding_choice_instr_loc,
+ *o,
+ ));
- code[preceding_choice_instr_loc] = Instruction::TrustMe(0);
+ code[preceding_choice_instr_loc] = Instruction::TrustMe(0);
- None
- }
- Instruction::TryMeElse(ref mut o) => {
- retraction_info.push_record(RetractionRecord::ModifiedTryMeElse(
- preceding_choice_instr_loc,
- *o,
- ));
+ None
+ }
+ Instruction::TryMeElse(ref mut o) => {
+ retraction_info.push_record(RetractionRecord::ModifiedTryMeElse(
+ preceding_choice_instr_loc,
+ *o,
+ ));
- *o = 0;
+ *o = 0;
- Some(IndexPtr::index(preceding_choice_instr_loc + 1))
- }
- _ => {
- unreachable!();
- }
+ Some(IndexPtr::index(preceding_choice_instr_loc + 1))
}
- }
+ _ => {
+ unreachable!();
+ }
+ },
_ => {
unreachable!();
}
Instruction::TryMeElse(ref mut o) if *o == 0 => {
*o = prepend_queue_len - 2;
}
- Instruction::DynamicInternalElse(
- _,
- _,
- ref mut o @ NextOrFail::Next(0),
- ) => {
+ Instruction::DynamicInternalElse(_, _, ref mut o @ NextOrFail::Next(0)) => {
*o = NextOrFail::Fail(prepend_queue_len - 2);
}
_ => {
_ => {}
}
- println!("Warning: overwriting {}/{} because the clauses are discontiguous", key.0.as_str(), key.1);
+ println!(
+ "Warning: overwriting {}/{} because the clauses are discontiguous",
+ key.0.as_str(),
+ key.1
+ );
}
impl<'a, LS: LoadState<'a>> Loader<'a, LS> {
if let Some(path_str) = load_context.path.to_str() {
if !path_str.is_empty() {
- return Some(LS::machine_st(&mut self.payload).atom_tbl.build_with(
- path_str
- ));
+ return Some(
+ LS::machine_st(&mut self.payload)
+ .atom_tbl
+ .build_with(path_str),
+ );
}
}
}
let clause = self.try_term_to_tl(term, &mut preprocessor)?;
// let queue = preprocessor.parse_queue(self)?;
- let mut cg = CodeGenerator::new(
- &mut LS::machine_st(&mut self.payload).atom_tbl,
- settings,
- );
+ let mut cg = CodeGenerator::new(&mut LS::machine_st(&mut self.payload).atom_tbl, settings);
let clause_code = cg.compile_predicate(vec![clause])?;
clauses.push(self.try_term_to_tl(term, &mut preprocessor)?);
}
- let mut cg = CodeGenerator::new(
- &mut LS::machine_st(&mut self.payload).atom_tbl,
- settings,
- );
+ let mut cg = CodeGenerator::new(&mut LS::machine_st(&mut self.payload).atom_tbl, settings);
let mut code = cg.compile_predicate(clauses)?;
.clause_clause_locs
.extend(&clause_clause_locs.make_contiguous()[0..]);
- self.payload.retraction_info
- .push_record(RetractionRecord::SkeletonClauseTruncateBack(
+ self.payload.retraction_info.push_record(
+ RetractionRecord::SkeletonClauseTruncateBack(
predicates.compilation_target,
key,
skeleton_clause_len,
- ));
+ ),
+ );
}
None => {
cg.skeleton
- .core
- .clause_clause_locs
- .extend(&clause_clause_locs.make_contiguous()[0..]);
+ .core
+ .clause_clause_locs
+ .extend(&clause_clause_locs.make_contiguous()[0..]);
let skeleton = cg.skeleton;
- self.add_extensible_predicate(
- key,
- skeleton,
- predicates.compilation_target,
- );
+ self.add_extensible_predicate(key, skeleton, predicates.compilation_target);
}
};
let mut skeleton = LocalPredicateSkeleton::new();
skeleton.clause_clause_locs = clause_clause_locs;
- self.add_local_extensible_predicate(
- *compilation_target,
- *key,
- skeleton,
- );
+ self.add_local_extensible_predicate(*compilation_target, *key, skeleton);
}
}
}
let mut skeleton = LocalPredicateSkeleton::new();
skeleton.clause_clause_locs.push_front(code_len);
- self.add_local_extensible_predicate(
- *compilation_target,
- *key,
- skeleton,
- );
+ self.add_local_extensible_predicate(*compilation_target, *key, skeleton);
}
}
}
let mut skeleton = LocalPredicateSkeleton::new();
skeleton.clause_clause_locs.push_back(code_len);
- self.add_local_extensible_predicate(
- *compilation_target,
- *key,
- skeleton,
- );
+ self.add_local_extensible_predicate(*compilation_target, *key, skeleton);
}
}
}
skeleton.core.clause_clause_locs.push_back(code_len);
- self.payload.retraction_info
+ self.payload
+ .retraction_info
.push_record(RetractionRecord::SkeletonClausePopBack(
compilation_target,
key,
self.push_back_to_local_predicate_skeleton(&compilation_target, &key, code_len);
- let code_index =
- self.get_or_insert_code_index(key, compilation_target);
+ let code_index = self.get_or_insert_code_index(key, compilation_target);
if let Some(new_code_ptr) = result {
set_code_index(
skeleton.core.clause_clause_locs.push_front(code_len);
skeleton.core.clause_assert_margin += 1;
- self.payload.retraction_info
+ self.payload
+ .retraction_info
.push_record(RetractionRecord::SkeletonClausePopFront(
compilation_target,
key,
self.push_front_to_local_predicate_skeleton(&compilation_target, &key, code_len);
- let code_index =
- self.get_or_insert_code_index(key, compilation_target);
+ let code_index = self.get_or_insert_code_index(key, compilation_target);
set_code_index(
&mut self.payload.retraction_info,
.opt_arg_index_key
.switch_on_term_loc()
{
- Some(index_loc) => {
- find_inner_choice_instr(
- &self.wam_prelude.code,
- skeleton.clauses[target_pos].clause_start,
- index_loc,
- )
- }
+ Some(index_loc) => find_inner_choice_instr(
+ &self.wam_prelude.code,
+ skeleton.clauses[target_pos].clause_start,
+ index_loc,
+ ),
None => skeleton.clauses[target_pos].clause_start,
};
match &mut self.wam_prelude.code[clause_loc] {
- Instruction::DynamicElse(_, ref mut d, _) |
- Instruction::DynamicInternalElse(_, ref mut d, _) => {
+ Instruction::DynamicElse(_, ref mut d, _)
+ | Instruction::DynamicInternalElse(_, ref mut d, _) => {
*d = Death::Finite(LS::machine_st(&mut self.payload).global_clock);
}
_ => unreachable!(),
skeleton.clauses[target_pos + 1].clause_start =
skeleton.clauses[target_pos].clause_start;
- let update_code_index = target_pos == 0 &&
- skeleton.clauses[target_pos + 1]
- .opt_arg_index_key
- .switch_on_term_loc()
- .is_none();
+ let update_code_index = target_pos == 0
+ && skeleton.clauses[target_pos + 1]
+ .opt_arg_index_key
+ .switch_on_term_loc()
+ .is_none();
let index_ptr_opt = if update_code_index {
Some(IndexPtr::index(clause_loc))
index_loc,
);
- let lower_bound_clause_start = skeleton.clauses[lower_bound].clause_start;
+ let lower_bound_clause_start =
+ skeleton.clauses[lower_bound].clause_start;
let preceding_choice_instr_loc;
match &mut code[clause_start] {
clause_clauses: ClauseIter,
append_or_prepend: AppendOrPrepend,
) -> Result<(), SessionError> {
- let clause_predicates = clause_clauses.map(|(head, body)| {
- Term::Clause(
- Cell::default(),
- atom!("$clause"),
- vec![head, body],
- )
- });
+ let clause_predicates = clause_clauses
+ .map(|(head, body)| Term::Clause(Cell::default(), atom!("$clause"), vec![head, body]));
let clause_clause_compilation_target = match compilation_target {
CompilationTarget::User => CompilationTarget::Module(atom!("builtins")),
.cloned()
.collect()
}
- Some(skeleton) => {
- skeleton.core.clause_clause_locs.make_contiguous()[0..num_clause_predicates]
- .iter()
- .cloned()
- .collect()
- }
+ Some(skeleton) => skeleton.core.clause_clause_locs.make_contiguous()
+ [0..num_clause_predicates]
+ .iter()
+ .cloned()
+ .collect(),
None => {
unreachable!()
}
};
- match self.wam_prelude.indices.get_predicate_skeleton_mut(
- &clause_clause_compilation_target,
- &(atom!("$clause"), 2),
- ) {
+ match self
+ .wam_prelude
+ .indices
+ .get_predicate_skeleton_mut(&clause_clause_compilation_target, &(atom!("$clause"), 2))
+ {
Some(skeleton) if append_or_prepend.is_append() => {
for _ in 0..num_clause_predicates {
skeleton.core.clause_clause_locs.pop_back();
println!(
"Warning: overwriting multifile predicate {}:{}/{} because \
it was not locally declared multifile.",
- self.payload.predicates.compilation_target, key.0.as_str(), key.1
+ self.payload.predicates.compilation_target,
+ key.0.as_str(),
+ key.1
);
}
- if let Some(skeleton) = self
- .wam_prelude
- .indices
- .remove_predicate_skeleton(&self.payload.predicates.compilation_target, &key)
- {
+ if let Some(skeleton) = self.wam_prelude.indices.remove_predicate_skeleton(
+ &self.payload.predicates.compilation_target,
+ &key,
+ ) {
let compilation_target = self.payload.predicates.compilation_target;
if predicate_info.is_dynamic {
- let clause_clause_compilation_target =
- match compilation_target {
- CompilationTarget::User => {
- CompilationTarget::Module(atom!("builtins"))
- }
- module => module,
- };
+ let clause_clause_compilation_target = match compilation_target {
+ CompilationTarget::User => {
+ CompilationTarget::Module(atom!("builtins"))
+ }
+ module => module,
+ };
self.retract_local_clauses_by_locs(
clause_clause_compilation_target,
}
self.payload.retraction_info.push_record(
- RetractionRecord::RemovedSkeleton(
- compilation_target,
- key,
- skeleton,
- ),
+ RetractionRecord::RemovedSkeleton(compilation_target, key, skeleton),
);
}
}
match self.wam_prelude.indices.modules.get_mut(&filename) {
Some(ref mut module) => {
let index_ptr = code_index.get();
- let code_index = module.code_dir.entry(key)
- .or_insert(code_index)
- .clone();
+ let code_index = module.code_dir.entry(key).or_insert(code_index).clone();
set_code_index(
&mut self.payload.retraction_info,
LS::machine_st(&mut self.payload).global_clock += 1;
let clause_clauses_len = self.payload.clause_clauses.len();
- let clauses_vec: Vec<_> = self.payload
- .clause_clauses.drain(0..std::cmp::min(predicates_len, clause_clauses_len))
+ let clauses_vec: Vec<_> = self
+ .payload
+ .clause_clauses
+ .drain(0..std::cmp::min(predicates_len, clause_clauses_len))
.collect();
let compilation_target = self.payload.predicates.compilation_target;
module_name: HeapCellValue,
key: PredicateKey,
) -> CodeIndex {
- let mut loader: Loader<'_, InlineLoadState<'_>> = Loader::new(
- self,
- InlineTermStream {},
- );
+ let mut loader: Loader<'_, InlineLoadState<'_>> = Loader::new(self, InlineTermStream {});
let module_name = if module_name.get_tag() == HeapCellValueTag::Atom {
cell_as_atom!(module_name)
vars: &[Term],
) -> Result<(), SessionError> {
let mut compile = || {
- let mut loader: Loader<'_, InlineLoadState<'_>> = Loader::new(
- self,
- InlineTermStream {},
- );
+ let mut loader: Loader<'_, InlineLoadState<'_>> =
+ Loader::new(self, InlineTermStream {});
let term = loader.read_term_from_heap(term_loc)?;
let clause = build_rule_body(vars, term);
self.target.push(hcv);
}
- let cdr = self.target.store(self.target.deref(heap_loc_as_cell!(addr + 1)));
+ let cdr = self
+ .target
+ .store(self.target.deref(heap_loc_as_cell!(addr + 1)));
if !cdr.is_var() {
self.trail_list_cell(addr + 1, threshold);
} else {
- let car = self.target.store(self.target.deref(heap_loc_as_cell!(addr)));
+ let car = self
+ .target
+ .store(self.target.deref(heap_loc_as_cell!(addr)));
if !car.is_var() {
self.trail_list_cell(addr, threshold);
while let HeapCellValueTag::Lis = list_addr.get_tag() {
let threshold = self.target.threshold();
let heap_loc = list_addr.get_value() as usize;
- let str_loc = self.target[heap_loc].get_value() as usize;
+ let str_loc = self.target[heap_loc].get_value() as usize;
- self.target.push(heap_loc_as_cell!(threshold+2));
- self.target.push(heap_loc_as_cell!(threshold+1));
+ self.target.push(heap_loc_as_cell!(threshold + 2));
+ self.target.push(heap_loc_as_cell!(threshold + 1));
read_heap_cell!(self.target[str_loc],
(HeapCellValueTag::Atom) => {
let a_atom = atom!("a");
let b_atom = atom!("b");
- wam.machine_st.heap
- .extend(functor!(f_atom, [atom(a_atom), atom(b_atom)]));
+ wam.machine_st
+ .heap
+ .extend(functor!(f_atom, [atom(a_atom), atom(b_atom)]));
assert_eq!(wam.machine_st.heap[0], atom_as_cell!(f_atom, 2));
assert_eq!(wam.machine_st.heap[1], atom_as_cell!(a_atom));
wam.machine_st.heap.clear();
- let pstr_var_cell = put_partial_string(&mut wam.machine_st.heap, "abc ", &mut wam.machine_st.atom_tbl);
+ let pstr_var_cell = put_partial_string(
+ &mut wam.machine_st.heap,
+ "abc ",
+ &mut wam.machine_st.atom_tbl,
+ );
let pstr_cell = wam.machine_st.heap[pstr_var_cell.get_value() as usize];
wam.machine_st.heap.pop();
wam.machine_st.heap.push(pstr_loc_as_cell!(2));
- let pstr_second_var_cell = put_partial_string(&mut wam.machine_st.heap, "def", &mut wam.machine_st.atom_tbl);
+ let pstr_second_var_cell = put_partial_string(
+ &mut wam.machine_st.heap,
+ "def",
+ &mut wam.machine_st.atom_tbl,
+ );
let pstr_second_cell = wam.machine_st.heap[pstr_second_var_cell.get_value() as usize];
wam.machine_st.heap.pop();
- wam.machine_st.heap.push(pstr_loc_as_cell!(wam.machine_st.heap.len() + 1));
+ wam.machine_st
+ .heap
+ .push(pstr_loc_as_cell!(wam.machine_st.heap.len() + 1));
wam.machine_st.heap.push(pstr_offset_as_cell!(0));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(0i64)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(0i64)));
{
let wam = TermCopyingMockWAM { wam: &mut wam };
assert_eq!(wam.machine_st.heap[2], pstr_second_cell);
assert_eq!(wam.machine_st.heap[3], pstr_loc_as_cell!(4));
assert_eq!(wam.machine_st.heap[4], pstr_offset_as_cell!(0));
- assert_eq!(wam.machine_st.heap[5], fixnum_as_cell!(Fixnum::build_with(0i64)));
+ assert_eq!(
+ wam.machine_st.heap[5],
+ fixnum_as_cell!(Fixnum::build_with(0i64))
+ );
assert_eq!(wam.machine_st.heap[7], pstr_cell);
assert_eq!(wam.machine_st.heap[8], pstr_loc_as_cell!(9));
assert_eq!(wam.machine_st.heap[9], pstr_second_cell);
assert_eq!(wam.machine_st.heap[10], pstr_loc_as_cell!(11));
assert_eq!(wam.machine_st.heap[11], pstr_offset_as_cell!(7));
- assert_eq!(wam.machine_st.heap[12], fixnum_as_cell!(Fixnum::build_with(0i64)));
+ assert_eq!(
+ wam.machine_st.heap[12],
+ fixnum_as_cell!(Fixnum::build_with(0i64))
+ );
wam.machine_st.heap.clear();
fn halve_delta(&self) -> BranchNumber {
BranchNumber {
branch_num: self.branch_num.clone(),
- delta : &self.delta / Rational::from(2),
+ delta: &self.delta / Rational::from(2),
}
}
}
impl BranchInfo {
fn new(branch_num: BranchNumber) -> Self {
- Self { branch_num, chunks: vec![] }
+ Self {
+ branch_num,
+ chunks: vec![],
+ }
}
}
// where it leaves off.
BuildFinalDisjunct(usize),
Fail,
- GetCutPoint{ var_num: usize, prev_b: bool },
+ GetCutPoint { var_num: usize, prev_b: bool },
Cut { var_num: usize, is_global: bool },
ResetCallPolicy(CallPolicy),
Term(Term),
- RemoveBranchNum, // pop the current_branch_num and from the root set.
+ RemoveBranchNum, // pop the current_branch_num and from the root set.
AddBranchNum(BranchNumber), // set current_branch_num, add it to the root set
RepBranchNum(BranchNumber), // replace current_branch_num and the latest in the root set
}
impl VarData {
fn emit_initial_get_level(&mut self, build_stack: &mut ChunkedTermVec) {
- let global_cut_var_num =
- if let &Some(global_cut_var_num) = &self.global_cut_var_num {
- match &self.records[global_cut_var_num].allocation {
- VarAlloc::Perm(..) => Some(global_cut_var_num),
- VarAlloc::Temp { term_loc, .. } if term_loc.chunk_num() > 0 => {
- Some(global_cut_var_num)
- }
- _ => None
+ let global_cut_var_num = if let &Some(global_cut_var_num) = &self.global_cut_var_num {
+ match &self.records[global_cut_var_num].allocation {
+ VarAlloc::Perm(..) => Some(global_cut_var_num),
+ VarAlloc::Temp { term_loc, .. } if term_loc.chunk_num() > 0 => {
+ Some(global_cut_var_num)
}
- } else {
- None
- };
+ _ => None,
+ }
+ } else {
+ None
+ };
if let Some(global_cut_var_num) = global_cut_var_num {
let term = QueryTerm::GetLevel(global_cut_var_num);
- self.records[global_cut_var_num].allocation = VarAlloc::Perm(0, PermVarAllocation::Pending);
+ self.records[global_cut_var_num].allocation =
+ VarAlloc::Perm(0, PermVarAllocation::Pending);
match build_stack.front_mut() {
Some(ChunkedTerms::Branch(_)) => {
}
fn flatten_into_disjunct(build_stack: &mut ChunkedTermVec, preceding_len: usize) {
- let branch_vec = build_stack.drain(preceding_len + 1 ..).collect();
+ let branch_vec = build_stack.drain(preceding_len + 1..).collect();
if let ChunkedTerms::Branch(ref mut disjuncts) = &mut build_stack[preceding_len] {
disjuncts.push(branch_vec);
pub fn classify_fact(mut self, term: Term) -> Result<ClassifyFactResult, CompilationError> {
self.classify_head_variables(&term)?;
- Ok((term, self.branch_map.separate_and_classify_variables(
- self.var_num,
- self.global_cut_var_num,
- self.current_chunk_num,
- )))
+ Ok((
+ term,
+ self.branch_map.separate_and_classify_variables(
+ self.var_num,
+ self.global_cut_var_num,
+ self.current_chunk_num,
+ ),
+ ))
}
pub fn classify_rule<'a, LS: LoadState<'a>>(
}
}
- let iter = old_branches.drain(old_branches_len - 1 ..);
+ let iter = old_branches.drain(old_branches_len - 1..);
branches.push(merge_branch_seq(iter));
}
}
fn probe_body_var(&mut self, var_info: VarInfo) {
- let term_loc = self.current_chunk_type.to_gen_context(self.current_chunk_num);
+ let term_loc = self
+ .current_chunk_type
+ .to_gen_context(self.current_chunk_num);
- let branch_info_v = self.branch_map.entry(var_info.var_ptr.clone())
+ let branch_info_v = self
+ .branch_map
+ .entry(var_info.var_ptr.clone())
.or_insert_with(|| vec![]);
let needs_new_branch = if let Some(last_bi) = branch_info_v.last() {
fn classify_head_variables(&mut self, term: &Term) -> Result<(), CompilationError> {
match term {
- Term::Clause(..) | Term::Literal(_, Literal::Atom(_)) => {
- }
+ Term::Clause(..) | Term::Literal(_, Literal::Atom(_)) => {}
_ => return Err(CompilationError::InvalidRuleHead),
}
- let mut classify_info = ClassifyInfo { arg_c: 1, arity: term.arity() };
+ let mut classify_info = ClassifyInfo {
+ arg_c: 1,
+ arity: term.arity(),
+ };
match term {
Term::Clause(_, _, terms) => {
// the body of the if let here is an inlined
// "probe_head_var". note the difference between it
// and "probe_body_var".
- let branch_info_v = self.branch_map.entry(var_ptr.clone())
+ let branch_info_v = self
+ .branch_map
+ .entry(var_ptr.clone())
.or_insert_with(|| vec![]);
let needs_new_branch = branch_info_v.is_empty();
if needs_new_branch {
- branch_info_v.push(BranchInfo::new(self.current_branch_num.clone()));
+ branch_info_v
+ .push(BranchInfo::new(self.current_branch_num.clone()));
}
let branch_info = branch_info_v.last_mut().unwrap();
self.probe_in_situ_var(var_num);
- build_stack.push_chunk_term(
- if is_global {
- QueryTerm::GlobalCut(var_num)
- } else {
- QueryTerm::LocalCut(var_num)
- }
- );
+ build_stack.push_chunk_term(if is_global {
+ QueryTerm::GlobalCut(var_num)
+ } else {
+ QueryTerm::LocalCut(var_num)
+ });
}
TraversalState::Fail => {
build_stack.push_chunk_term(QueryTerm::Fail);
classifier.probe_body_term(arg_c + 1, terms.len(), term);
}
- build_stack.push_chunk_term(
- clause_to_query_term(
- loader,
- name,
- terms,
- classifier.call_policy,
- ),
- );
+ build_stack.push_chunk_term(clause_to_query_term(
+ loader,
+ name,
+ terms,
+ classifier.call_policy,
+ ));
};
match term {
- Term::Clause(_, name @ (atom!("->") | atom!(";") | atom!(",")), mut terms) if terms.len() == 3 => {
+ Term::Clause(
+ _,
+ name @ (atom!("->") | atom!(";") | atom!(",")),
+ mut terms,
+ ) if terms.len() == 3 => {
if let Some(last_arg) = terms.last() {
if let Term::Literal(_, Literal::CodeIndex(_)) = last_arg {
terms.pop();
- state_stack.push(TraversalState::Term(Term::Clause(Cell::default(), name, terms)));
+ state_stack.push(TraversalState::Term(Term::Clause(
+ Cell::default(),
+ name,
+ terms,
+ )));
} else {
add_chunk(self, name, terms);
}
let mut branch_numbers = vec![first_branch_num];
- for idx in 1 .. branches.len() {
+ for idx in 1..branches.len() {
let succ_branch_number = branch_numbers[idx - 1].incr_by_delta();
branch_numbers.push(if idx + 1 < branches.len() {
state_stack.push(TraversalState::AddBranchNum(branch_num));
}
- if let TraversalState::BuildDisjunct(build_stack_len) = state_stack[final_disjunct_loc] {
- state_stack[final_disjunct_loc] = TraversalState::BuildFinalDisjunct(build_stack_len);
+ if let TraversalState::BuildDisjunct(build_stack_len) =
+ state_stack[final_disjunct_loc]
+ {
+ state_stack[final_disjunct_loc] =
+ TraversalState::BuildFinalDisjunct(build_stack_len);
}
self.current_chunk_type = ChunkType::Mid;
let then_term = terms.pop().unwrap();
let if_term = terms.pop().unwrap();
- let prev_b = if matches!(state_stack.last(), Some(TraversalState::RemoveBranchNum)) {
+ let prev_b = if matches!(
+ state_stack.last(),
+ Some(TraversalState::RemoveBranchNum)
+ ) {
// check if the second-to-last element is a regular BuildDisjunct, as we don't
// want to add GetPrevLevel in case of a TrustMe.
- matches!(state_stack.iter().rev().nth(1), Some(TraversalState::BuildDisjunct(..)))
+ matches!(
+ state_stack.iter().rev().nth(1),
+ Some(TraversalState::BuildDisjunct(..))
+ )
} else {
false
};
state_stack.push(TraversalState::Term(then_term));
- state_stack.push(TraversalState::Cut { var_num: self.var_num, is_global: false });
+ state_stack.push(TraversalState::Cut {
+ var_num: self.var_num,
+ is_global: false,
+ });
state_stack.push(TraversalState::Term(if_term));
- state_stack.push(TraversalState::GetCutPoint { var_num: self.var_num, prev_b });
+ state_stack.push(TraversalState::GetCutPoint {
+ var_num: self.var_num,
+ prev_b,
+ });
self.var_num += 1;
}
build_stack.reserve_branch(2);
state_stack.push(TraversalState::BuildFinalDisjunct(build_stack_len));
- state_stack.push(TraversalState::Term(Term::Clause(Cell::default(), atom!("$succeed"), vec![])));
+ state_stack.push(TraversalState::Term(Term::Clause(
+ Cell::default(),
+ atom!("$succeed"),
+ vec![],
+ )));
state_stack.push(TraversalState::BuildDisjunct(build_stack_len));
state_stack.push(TraversalState::Fail);
- state_stack.push(TraversalState::Cut { var_num: self.var_num, is_global: false });
+ state_stack.push(TraversalState::Cut {
+ var_num: self.var_num,
+ is_global: false,
+ });
state_stack.push(TraversalState::Term(not_term));
- state_stack.push(TraversalState::GetCutPoint { var_num: self.var_num, prev_b: true });
+ state_stack.push(TraversalState::GetCutPoint {
+ var_num: self.var_num,
+ prev_b: true,
+ });
self.current_chunk_type = ChunkType::Mid;
self.current_chunk_num += 1;
build_stack.add_chunk();
}
- build_stack.push_chunk_term(
- qualified_clause_to_query_term(
- loader,
- module_name,
- predicate_name,
- vec![],
- self.call_policy,
- ),
- );
+ build_stack.push_chunk_term(qualified_clause_to_query_term(
+ loader,
+ module_name,
+ predicate_name,
+ vec![],
+ self.call_policy,
+ ));
}
(
Term::Literal(_, Literal::Atom(module_name)),
self.probe_body_term(arg_c + 1, terms.len(), term);
}
- build_stack.push_chunk_term(
- qualified_clause_to_query_term(
- loader,
- module_name,
- name,
- terms,
- self.call_policy,
- ),
- );
+ build_stack.push_chunk_term(qualified_clause_to_query_term(
+ loader,
+ module_name,
+ name,
+ terms,
+ self.call_policy,
+ ));
}
(module_name, predicate_name) => {
if update_chunk_data(self, atom!("call"), 2) {
terms.push(module_name);
terms.push(predicate_name);
- build_stack.push_chunk_term(
- clause_to_query_term(
- loader,
- atom!("call"),
- vec![Term::Clause(Cell::default(), atom!(":"), terms)],
- self.call_policy,
- ),
- );
+ build_stack.push_chunk_term(clause_to_query_term(
+ loader,
+ atom!("call"),
+ vec![Term::Clause(Cell::default(), atom!(":"), terms)],
+ self.call_policy,
+ ));
}
}
}
- Term::Clause(_, atom!("$call_with_inference_counting"), mut terms) if terms.len() == 1 => {
+ Term::Clause(_, atom!("$call_with_inference_counting"), mut terms)
+ if terms.len() == 1 =>
+ {
state_stack.push(TraversalState::ResetCallPolicy(self.call_policy));
state_stack.push(TraversalState::Term(terms.pop().unwrap()));
self.probe_body_term(1, 1, &var);
- build_stack.push_chunk_term(
- clause_to_query_term(
- loader,
- atom!("call"),
- vec![var],
- self.call_policy,
- ),
- );
+ build_stack.push_chunk_term(clause_to_query_term(
+ loader,
+ atom!("call"),
+ vec![var],
+ self.call_policy,
+ ));
}
Term::Literal(_, Literal::Atom(atom!("!")) | Literal::Char('!')) => {
if self.global_cut_var_num.is_none() {
build_stack.add_chunk();
}
- build_stack.push_chunk_term(
- clause_to_query_term(
- loader,
- name,
- vec![],
- self.call_policy,
- ),
- );
+ build_stack.push_chunk_term(clause_to_query_term(
+ loader,
+ name,
+ vec![],
+ self.call_policy,
+ ));
}
_ => {
return Err(CompilationError::InadmissibleQueryTerm);
};
for (var, branches) in self.iter_mut() {
- let (mut var_num, var_num_incr) =
- if let Var::InSitu(var_num) = *var.borrow() {
- (var_num, false)
- } else {
- (var_data.records.len(), true)
- };
+ let (mut var_num, var_num_incr) = if let Var::InSitu(var_num) = *var.borrow() {
+ (var_num, false)
+ } else {
+ (var_data.records.len(), true)
+ };
for branch in branches.iter_mut() {
if var_num_incr {
var_data.records.push(VariableRecord::default());
}
- if branch.chunks.len() <= 1 { // true iff var is a temporary variable.
+ if branch.chunks.len() <= 1 {
+ // true iff var is a temporary variable.
debug_assert_eq!(branch.chunks.len(), 1);
let chunk = &mut branch.chunks[0];
for var_info in chunk.vars.iter_mut() {
if var_info.lvl == Level::Shallow {
let term_loc = var_info.chunk_type.to_gen_context(chunk.chunk_num);
- temp_var_data.use_set.insert((term_loc, var_info.classify_info.arg_c));
+ temp_var_data
+ .use_set
+ .insert((term_loc, var_info.classify_info.arg_c));
}
}
use crate::arena::*;
use crate::atom_table::*;
use crate::instructions::*;
-use crate::machine::*;
use crate::machine::arithmetic_ops::*;
use crate::machine::machine_errors::*;
use crate::machine::machine_state::*;
+use crate::machine::*;
use crate::types::*;
use crate::try_numeric_result;
let a2 = self.registers[2];
let a3 = self.registers[3];
- let check_atom = |machine_st: &mut MachineState, name: Atom, arity: usize| -> Result<(), MachineStub> {
- match name {
- atom!(">") | atom!("<") | atom!("=") if arity == 0 => {
- Ok(())
- }
- _ => {
- let err = machine_st.domain_error(DomainErrorType::Order, a1);
- Err(machine_st.error_form(err, stub_gen()))
+ let check_atom =
+ |machine_st: &mut MachineState, name: Atom, arity: usize| -> Result<(), MachineStub> {
+ match name {
+ atom!(">") | atom!("<") | atom!("=") if arity == 0 => Ok(()),
+ _ => {
+ let err = machine_st.domain_error(DomainErrorType::Order, a1);
+ Err(machine_st.error_form(err, stub_gen()))
+ }
}
- }
- };
+ };
read_heap_cell!(a1,
(HeapCellValueTag::Atom, (name, arity)) => {
compare_term_test!(self, *v1, *v2).unwrap_or(Ordering::Less)
});
- list.dedup_by(|v1, v2| {
- compare_term_test!(self, *v1, *v2) == Some(Ordering::Equal)
- });
+ list.dedup_by(|v1, v2| compare_term_test!(self, *v1, *v2) == Some(Ordering::Equal));
- let heap_addr = heap_loc_as_cell!(
- iter_to_heap_list(&mut self.heap, list.into_iter())
- );
+ let heap_addr = heap_loc_as_cell!(iter_to_heap_list(&mut self.heap, list.into_iter()));
let target_addr = self.registers[2];
});
let key_pairs = key_pairs.into_iter().map(|kp| kp.1);
- let heap_addr = heap_loc_as_cell!(
- iter_to_heap_list(&mut self.heap, key_pairs)
- );
+ let heap_addr = heap_loc_as_cell!(iter_to_heap_list(&mut self.heap, key_pairs));
let target_addr = self.registers[2];
pub(super) fn find_living_dynamic_else(&self, mut p: usize) -> Option<(usize, usize)> {
loop {
match &self.code[p] {
- &Instruction::DynamicElse(
- birth,
- death,
- NextOrFail::Next(i),
- ) => {
+ &Instruction::DynamicElse(birth, death, NextOrFail::Next(i)) => {
if birth < self.machine_st.cc && Death::Finite(self.machine_st.cc) <= death {
return Some((p, i));
} else if i > 0 {
return None;
}
}
- &Instruction::DynamicElse(
- birth,
- death,
- NextOrFail::Fail(_),
- ) => {
+ &Instruction::DynamicElse(birth, death, NextOrFail::Fail(_)) => {
if birth < self.machine_st.cc && Death::Finite(self.machine_st.cc) <= death {
return Some((p, 0));
} else {
return None;
}
}
- &Instruction::DynamicInternalElse(
- birth,
- death,
- NextOrFail::Next(i),
- ) => {
+ &Instruction::DynamicInternalElse(birth, death, NextOrFail::Next(i)) => {
if birth < self.machine_st.cc && Death::Finite(self.machine_st.cc) <= death {
return Some((p, i));
} else if i > 0 {
return None;
}
}
- &Instruction::DynamicInternalElse(
- birth,
- death,
- NextOrFail::Fail(_),
- ) => {
+ &Instruction::DynamicInternalElse(birth, death, NextOrFail::Fail(_)) => {
if birth < self.machine_st.cc && Death::Finite(self.machine_st.cc) <= death {
return Some((p, 0));
} else {
}
}
- pub(super) fn find_living_dynamic(&self, oi: u32, mut ii: u32) -> Option<(usize, u32, u32, bool)> {
+ pub(super) fn find_living_dynamic(
+ &self,
+ oi: u32,
+ mut ii: u32,
+ ) -> Option<(usize, u32, u32, bool)> {
let p = self.machine_st.p;
let indexed_choice_instrs = match &self.code[p] {
loop {
match &indexed_choice_instrs.get(ii as usize) {
Some(&offset) => match &self.code[p + offset - 1] {
- &Instruction::DynamicInternalElse(
- birth,
- death,
- next_or_fail,
- ) => {
- if birth < self.machine_st.cc && Death::Finite(self.machine_st.cc) <= death {
+ &Instruction::DynamicInternalElse(birth, death, next_or_fail) => {
+ if birth < self.machine_st.cc && Death::Finite(self.machine_st.cc) <= death
+ {
return Some((offset, oi, ii, next_or_fail.is_next()));
} else {
ii += 1;
match &machine.code[p - 1] {
&Instruction::DynamicInternalElse(birth, death, _) => {
- if birth < machine.machine_st.cc && Death::Finite(machine.machine_st.cc) <= death {
+ if birth < machine.machine_st.cc
+ && Death::Finite(machine.machine_st.cc) <= death
+ {
return true;
} else {
return false;
let mut index = 0;
let addr = match &indexing_lines[0] {
- &IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(arg, ..)) => {
- self.machine_st.store(self.machine_st.deref(self.machine_st.registers[arg]))
- }
+ &IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(arg, ..)) => self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[arg])),
_ => {
unreachable!()
}
loop {
match &indexing_lines[index] {
&IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, v, c, l, s)) => {
- let offset = self.machine_st.select_switch_on_term_index(addr, v, c, l, s);
+ let offset = self
+ .machine_st
+ .select_switch_on_term_index(addr, v, c, l, s);
match offset {
IndexingCodePtr::Fail => {
#[inline(always)]
pub(super) fn dispatch_loop(&mut self) -> std::process::ExitCode {
'outer: loop {
- for _ in 0 .. INSTRUCTIONS_PER_INTERRUPT_POLL {
- match &self.code[self.machine_st.p] {
- &Instruction::BreakFromDispatchLoop => {
- break 'outer;
- }
- &Instruction::InstallVerifyAttr => {
- self.machine_st.p = self.machine_st.attr_var_init.p;
-
- if self.code[self.machine_st.p].is_execute() {
- self.machine_st.p = self.machine_st.attr_var_init.cp;
- } else {
- self.machine_st.p += 1;
- self.machine_st.cp = self.machine_st.attr_var_init.cp;
+ for _ in 0..INSTRUCTIONS_PER_INTERRUPT_POLL {
+ match &self.code[self.machine_st.p] {
+ &Instruction::BreakFromDispatchLoop => {
+ break 'outer;
}
+ &Instruction::InstallVerifyAttr => {
+ self.machine_st.p = self.machine_st.attr_var_init.p;
- let mut p = self.machine_st.p;
+ if self.code[self.machine_st.p].is_execute() {
+ self.machine_st.p = self.machine_st.attr_var_init.cp;
+ } else {
+ self.machine_st.p += 1;
+ self.machine_st.cp = self.machine_st.attr_var_init.cp;
+ }
- while self.code[p].is_head_instr() {
- p += 1;
- }
+ let mut p = self.machine_st.p;
- let instr = std::mem::replace(
- &mut self.code[p],
- Instruction::VerifyAttrInterrupt,
- );
+ while self.code[p].is_head_instr() {
+ p += 1;
+ }
- self.code[VERIFY_ATTR_INTERRUPT_LOC] = instr;
- self.machine_st.attr_var_init.cp = p;
- }
- &Instruction::VerifyAttrInterrupt => {
- let (_, arity) = self.code[VERIFY_ATTR_INTERRUPT_LOC].to_name_and_arity();
- let arity = std::cmp::max(arity, self.machine_st.num_of_args);
- self.run_verify_attr_interrupt(arity);
- }
- &Instruction::Add(ref a1, ref a2, t) => {
- let stub_gen = || functor_stub(atom!("is"), 2);
+ let instr =
+ std::mem::replace(&mut self.code[p], Instruction::VerifyAttrInterrupt);
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.code[VERIFY_ATTR_INTERRUPT_LOC] = instr;
+ self.machine_st.attr_var_init.cp = p;
+ }
+ &Instruction::VerifyAttrInterrupt => {
+ let (_, arity) = self.code[VERIFY_ATTR_INTERRUPT_LOC].to_name_and_arity();
+ let arity = std::cmp::max(arity, self.machine_st.num_of_args);
+ self.run_verify_attr_interrupt(arity);
+ }
+ &Instruction::Add(ref a1, ref a2, t) => {
+ let stub_gen = || functor_stub(atom!("is"), 2);
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- try_numeric_result!(add(n1, n2, &mut self.machine_st.arena), stub_gen)
- );
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::Sub(ref a1, ref a2, t) => {
- let stub_gen = || functor_stub(atom!("is"), 2);
+ self.machine_st.interms[t - 1] = try_or_throw_gen!(
+ &mut self.machine_st,
+ try_numeric_result!(add(n1, n2, &mut self.machine_st.arena), stub_gen)
+ );
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.p += 1;
+ }
+ &Instruction::Sub(ref a1, ref a2, t) => {
+ let stub_gen = || functor_stub(atom!("is"), 2);
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- try_numeric_result!(sub(n1, n2, &mut self.machine_st.arena), stub_gen)
- );
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::Mul(ref a1, ref a2, t) => {
- let stub_gen = || functor_stub(atom!("is"), 2);
+ self.machine_st.interms[t - 1] = try_or_throw_gen!(
+ &mut self.machine_st,
+ try_numeric_result!(sub(n1, n2, &mut self.machine_st.arena), stub_gen)
+ );
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.p += 1;
+ }
+ &Instruction::Mul(ref a1, ref a2, t) => {
+ let stub_gen = || functor_stub(atom!("is"), 2);
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- try_numeric_result!(mul(n1, n2, &mut self.machine_st.arena), stub_gen)
- );
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::Max(ref a1, ref a2, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.interms[t - 1] = try_or_throw_gen!(
+ &mut self.machine_st,
+ try_numeric_result!(mul(n1, n2, &mut self.machine_st.arena), stub_gen)
+ );
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- max(n1, n2)
- );
+ self.machine_st.p += 1;
+ }
+ &Instruction::Max(ref a1, ref a2, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::Min(ref a1, ref a2, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.interms[t - 1] =
+ try_or_throw_gen!(&mut self.machine_st, max(n1, n2));
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- min(n1, n2)
- );
+ self.machine_st.p += 1;
+ }
+ &Instruction::Min(ref a1, ref a2, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::IntPow(ref a1, ref a2, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.interms[t - 1] =
+ try_or_throw_gen!(&mut self.machine_st, min(n1, n2));
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- int_pow(n1, n2, &mut self.machine_st.arena)
- );
+ self.machine_st.p += 1;
+ }
+ &Instruction::IntPow(ref a1, ref a2, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::Gcd(ref a1, ref a2, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.interms[t - 1] = try_or_throw_gen!(
+ &mut self.machine_st,
+ int_pow(n1, n2, &mut self.machine_st.arena)
+ );
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- gcd(n1, n2, &mut self.machine_st.arena)
- );
+ self.machine_st.p += 1;
+ }
+ &Instruction::Gcd(ref a1, ref a2, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::Pow(ref a1, ref a2, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.interms[t - 1] = try_or_throw_gen!(
+ &mut self.machine_st,
+ gcd(n1, n2, &mut self.machine_st.arena)
+ );
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- pow(n1, n2, atom!("**"))
- );
+ self.machine_st.p += 1;
+ }
+ &Instruction::Pow(ref a1, ref a2, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::RDiv(ref a1, ref a2, t) => {
- let stub_gen = || functor_stub(atom!("(rdiv)"), 2);
+ self.machine_st.interms[t - 1] =
+ try_or_throw_gen!(&mut self.machine_st, pow(n1, n2, atom!("**")));
- let r1 = try_or_throw!(self.machine_st, self.machine_st.get_rational(a1, stub_gen));
- let r2 = try_or_throw!(self.machine_st, self.machine_st.get_rational(a2, stub_gen));
+ self.machine_st.p += 1;
+ }
+ &Instruction::RDiv(ref a1, ref a2, t) => {
+ let stub_gen = || functor_stub(atom!("(rdiv)"), 2);
- self.machine_st.interms[t - 1] = Number::Rational(arena_alloc!(
- try_or_throw_gen!(&mut self.machine_st, rdiv(r1, r2)),
- &mut self.machine_st.arena
- ));
+ let r1 = try_or_throw!(
+ self.machine_st,
+ self.machine_st.get_rational(a1, stub_gen)
+ );
+ let r2 = try_or_throw!(
+ self.machine_st,
+ self.machine_st.get_rational(a2, stub_gen)
+ );
- self.machine_st.p += 1;
- }
- &Instruction::IntFloorDiv(ref a1, ref a2, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.interms[t - 1] = Number::Rational(arena_alloc!(
+ try_or_throw_gen!(&mut self.machine_st, rdiv(r1, r2)),
+ &mut self.machine_st.arena
+ ));
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- int_floor_div(n1, n2, &mut self.machine_st.arena)
- );
+ self.machine_st.p += 1;
+ }
+ &Instruction::IntFloorDiv(ref a1, ref a2, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::IDiv(ref a1, ref a2, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.interms[t - 1] = try_or_throw_gen!(
+ &mut self.machine_st,
+ int_floor_div(n1, n2, &mut self.machine_st.arena)
+ );
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- idiv(n1, n2, &mut self.machine_st.arena)
- );
+ self.machine_st.p += 1;
+ }
+ &Instruction::IDiv(ref a1, ref a2, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::Abs(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = try_or_throw_gen!(
+ &mut self.machine_st,
+ idiv(n1, n2, &mut self.machine_st.arena)
+ );
- self.machine_st.interms[t - 1] = abs(n1, &mut self.machine_st.arena);
- self.machine_st.p += 1;
- }
- &Instruction::Sign(ref a1, t) => {
- let n = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.p += 1;
+ }
+ &Instruction::Abs(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.interms[t - 1] = n.sign();
- self.machine_st.p += 1;
- }
- &Instruction::Neg(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = abs(n1, &mut self.machine_st.arena);
+ self.machine_st.p += 1;
+ }
+ &Instruction::Sign(ref a1, t) => {
+ let n = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.interms[t - 1] = neg(n1, &mut self.machine_st.arena);
- self.machine_st.p += 1;
- }
- &Instruction::BitwiseComplement(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = n.sign();
+ self.machine_st.p += 1;
+ }
+ &Instruction::Neg(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- bitwise_complement(n1, &mut self.machine_st.arena)
- );
+ self.machine_st.interms[t - 1] = neg(n1, &mut self.machine_st.arena);
+ self.machine_st.p += 1;
+ }
+ &Instruction::BitwiseComplement(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::Div(ref a1, ref a2, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.interms[t - 1] = try_or_throw_gen!(
+ &mut self.machine_st,
+ bitwise_complement(n1, &mut self.machine_st.arena)
+ );
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- div(n1, n2)
- );
+ self.machine_st.p += 1;
+ }
+ &Instruction::Div(ref a1, ref a2, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::Shr(ref a1, ref a2, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.interms[t - 1] =
+ try_or_throw_gen!(&mut self.machine_st, div(n1, n2));
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- shr(n1, n2, &mut self.machine_st.arena)
- );
+ self.machine_st.p += 1;
+ }
+ &Instruction::Shr(ref a1, ref a2, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::Shl(ref a1, ref a2, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.interms[t - 1] = try_or_throw_gen!(
+ &mut self.machine_st,
+ shr(n1, n2, &mut self.machine_st.arena)
+ );
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- shl(n1, n2, &mut self.machine_st.arena)
- );
+ self.machine_st.p += 1;
+ }
+ &Instruction::Shl(ref a1, ref a2, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::Xor(ref a1, ref a2, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.interms[t - 1] = try_or_throw_gen!(
+ &mut self.machine_st,
+ shl(n1, n2, &mut self.machine_st.arena)
+ );
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- xor(n1, n2, &mut self.machine_st.arena)
- );
+ self.machine_st.p += 1;
+ }
+ &Instruction::Xor(ref a1, ref a2, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::And(ref a1, ref a2, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.interms[t - 1] = try_or_throw_gen!(
+ &mut self.machine_st,
+ xor(n1, n2, &mut self.machine_st.arena)
+ );
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- and(n1, n2, &mut self.machine_st.arena)
- );
+ self.machine_st.p += 1;
+ }
+ &Instruction::And(ref a1, ref a2, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::Or(ref a1, ref a2, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.interms[t - 1] = try_or_throw_gen!(
+ &mut self.machine_st,
+ and(n1, n2, &mut self.machine_st.arena)
+ );
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- or(n1, n2, &mut self.machine_st.arena)
- );
+ self.machine_st.p += 1;
+ }
+ &Instruction::Or(ref a1, ref a2, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::Mod(ref a1, ref a2, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.interms[t - 1] = try_or_throw_gen!(
+ &mut self.machine_st,
+ or(n1, n2, &mut self.machine_st.arena)
+ );
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- modulus(n1, n2, &mut self.machine_st.arena)
- );
+ self.machine_st.p += 1;
+ }
+ &Instruction::Mod(ref a1, ref a2, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::Rem(ref a1, ref a2, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.interms[t - 1] = try_or_throw_gen!(
+ &mut self.machine_st,
+ modulus(n1, n2, &mut self.machine_st.arena)
+ );
- self.machine_st.interms[t - 1] = try_or_throw_gen!(
- &mut self.machine_st,
- remainder(n1, n2, &mut self.machine_st.arena)
- );
+ self.machine_st.p += 1;
+ }
+ &Instruction::Rem(ref a1, ref a2, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::Cos(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = try_or_throw_gen!(
+ &mut self.machine_st,
+ remainder(n1, n2, &mut self.machine_st.arena)
+ );
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, cos(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::Cos(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::Sin(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, cos(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, sin(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::Sin(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::Tan(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, sin(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, tan(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::Tan(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::Sqrt(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, tan(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, sqrt(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::Sqrt(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::Log(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, sqrt(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, log(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::Log(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::Exp(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, log(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, exp(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::Exp(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::ACos(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, exp(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, acos(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::ACos(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::ASin(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, acos(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, asin(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::ASin(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::ATan(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, asin(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, atan(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::ATan(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::ATan2(ref a1, ref a2, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, atan(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, atan2(n1, n2))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::ATan2(ref a1, ref a2, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(a2));
- self.machine_st.p += 1;
- }
- &Instruction::ACosh(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, atan2(n1, n2)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, acosh(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::ACosh(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::ASinh(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, acosh(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, asinh(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::ASinh(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::ATanh(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, asinh(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, atanh(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::ATanh(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::Cosh(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, atanh(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, cosh(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::Cosh(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::Sinh(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, cosh(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, sinh(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::Sinh(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::Tanh(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, sinh(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, tanh(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::Tanh(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::Log10(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, tanh(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, log10(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::Log10(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::Float(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, log10(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, float(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::Float(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::Truncate(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, float(n1)),
+ ));
- self.machine_st.interms[t - 1] = truncate(n1, &mut self.machine_st.arena);
- self.machine_st.p += 1;
- }
- &Instruction::Round(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.p += 1;
+ }
+ &Instruction::Truncate(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.interms[t - 1] =
- try_or_throw_gen!(&mut self.machine_st, round(n1, &mut self.machine_st.arena));
+ self.machine_st.interms[t - 1] = truncate(n1, &mut self.machine_st.arena);
+ self.machine_st.p += 1;
+ }
+ &Instruction::Round(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::Ceiling(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = try_or_throw_gen!(
+ &mut self.machine_st,
+ round(n1, &mut self.machine_st.arena)
+ );
- self.machine_st.interms[t - 1] = ceiling(n1, &mut self.machine_st.arena);
- self.machine_st.p += 1;
- }
- &Instruction::Floor(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.p += 1;
+ }
+ &Instruction::Ceiling(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.interms[t - 1] = floor(n1, &mut self.machine_st.arena);
- self.machine_st.p += 1;
- }
- &Instruction::FloatFractionalPart(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = ceiling(n1, &mut self.machine_st.arena);
+ self.machine_st.p += 1;
+ }
+ &Instruction::Floor(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, float_fractional_part(n1))
- ));
+ self.machine_st.interms[t - 1] = floor(n1, &mut self.machine_st.arena);
+ self.machine_st.p += 1;
+ }
+ &Instruction::FloatFractionalPart(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::FloatIntegerPart(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, float_fractional_part(n1)),
+ ));
- self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
- try_or_throw_gen!(&mut self.machine_st, float_integer_part(n1))
- ));
+ self.machine_st.p += 1;
+ }
+ &Instruction::FloatIntegerPart(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- self.machine_st.p += 1;
- }
- &Instruction::Plus(ref a1, t) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
+ self.machine_st.interms[t - 1] = Number::Float(OrderedFloat(
+ try_or_throw_gen!(&mut self.machine_st, float_integer_part(n1)),
+ ));
- self.machine_st.interms[t - 1] = n1;
- self.machine_st.p += 1;
- }
- &Instruction::DynamicElse(..) => {
- if let FirstOrNext::First = self.machine_st.dynamic_mode {
- self.machine_st.cc = self.machine_st.global_clock;
+ self.machine_st.p += 1;
}
+ &Instruction::Plus(ref a1, t) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(a1));
- let p = self.machine_st.p;
-
- match self.find_living_dynamic_else(p) {
- Some((p, next_i)) => {
- self.machine_st.p = p;
- self.machine_st.oip = 0;
- self.machine_st.iip = 0;
+ self.machine_st.interms[t - 1] = n1;
+ self.machine_st.p += 1;
+ }
+ &Instruction::DynamicElse(..) => {
+ if let FirstOrNext::First = self.machine_st.dynamic_mode {
+ self.machine_st.cc = self.machine_st.global_clock;
+ }
- match self.machine_st.dynamic_mode {
- FirstOrNext::First if next_i == 0 => {
- self.machine_st.p += 1;
- }
- FirstOrNext::First => {
- self.machine_st.cc = self.machine_st.global_clock;
+ let p = self.machine_st.p;
- match self.find_living_dynamic_else(p + next_i) {
- Some(_) => {
- self.machine_st.registers[self.machine_st.num_of_args + 1] =
- fixnum_as_cell!(Fixnum::build_with(self.machine_st.cc as i64));
+ match self.find_living_dynamic_else(p) {
+ Some((p, next_i)) => {
+ self.machine_st.p = p;
+ self.machine_st.oip = 0;
+ self.machine_st.iip = 0;
- self.machine_st.num_of_args += 1;
- self.try_me_else(next_i);
- self.machine_st.num_of_args -= 1;
- }
- None => {
- self.machine_st.p += 1;
- }
+ match self.machine_st.dynamic_mode {
+ FirstOrNext::First if next_i == 0 => {
+ self.machine_st.p += 1;
}
- }
- FirstOrNext::Next => {
- let n = self.machine_st
- .stack
- .index_or_frame(self.machine_st.b)
- .prelude
- .num_cells;
-
- self.machine_st.cc = cell_as_fixnum!(
- self.machine_st.stack[stack_loc!(OrFrame, self.machine_st.b, n-1)]
- ).get_num() as usize;
-
- if next_i > 0 {
+ FirstOrNext::First => {
+ self.machine_st.cc = self.machine_st.global_clock;
+
match self.find_living_dynamic_else(p + next_i) {
Some(_) => {
- self.retry_me_else(next_i);
+ self.machine_st.registers
+ [self.machine_st.num_of_args + 1] = fixnum_as_cell!(
+ Fixnum::build_with(self.machine_st.cc as i64)
+ );
+
+ self.machine_st.num_of_args += 1;
+ self.try_me_else(next_i);
+ self.machine_st.num_of_args -= 1;
}
None => {
- self.trust_me();
+ self.machine_st.p += 1;
}
}
- } else {
- self.trust_me();
}
+ FirstOrNext::Next => {
+ let n = self
+ .machine_st
+ .stack
+ .index_or_frame(self.machine_st.b)
+ .prelude
+ .num_cells;
+
+ self.machine_st.cc = cell_as_fixnum!(
+ self.machine_st.stack
+ [stack_loc!(OrFrame, self.machine_st.b, n - 1)]
+ )
+ .get_num()
+ as usize;
+
+ if next_i > 0 {
+ match self.find_living_dynamic_else(p + next_i) {
+ Some(_) => {
+ self.retry_me_else(next_i);
+ }
+ None => {
+ self.trust_me();
+ }
+ }
+ } else {
+ self.trust_me();
+ }
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(
+ &mut self.machine_st
+ )
+ );
+ }
}
}
+ None => {
+ self.machine_st.fail = true;
+ }
}
- None => {
- self.machine_st.fail = true;
- }
- }
- self.machine_st.dynamic_mode = FirstOrNext::Next;
+ self.machine_st.dynamic_mode = FirstOrNext::Next;
- if self.machine_st.fail {
- self.machine_st.backtrack();
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ }
}
- }
- &Instruction::DynamicInternalElse(..) => {
- let p = self.machine_st.p;
+ &Instruction::DynamicInternalElse(..) => {
+ let p = self.machine_st.p;
- match self.find_living_dynamic_else(p) {
- Some((p, next_i)) => {
- self.machine_st.p = p;
- self.machine_st.oip = 0;
- self.machine_st.iip = 0;
+ match self.find_living_dynamic_else(p) {
+ Some((p, next_i)) => {
+ self.machine_st.p = p;
+ self.machine_st.oip = 0;
+ self.machine_st.iip = 0;
- match self.machine_st.dynamic_mode {
- FirstOrNext::First if next_i == 0 => {
- self.machine_st.p += 1;
- }
- FirstOrNext::First => {
- match self.find_living_dynamic_else(p + next_i) {
- Some(_) => {
- self.machine_st.registers[self.machine_st.num_of_args + 1] =
- fixnum_as_cell!(Fixnum::build_with(self.machine_st.cc as i64));
-
- self.machine_st.num_of_args += 1;
- self.try_me_else(next_i);
- self.machine_st.num_of_args -= 1;
- }
- None => {
- self.machine_st.p += 1;
- }
+ match self.machine_st.dynamic_mode {
+ FirstOrNext::First if next_i == 0 => {
+ self.machine_st.p += 1;
}
- }
- FirstOrNext::Next => {
- let n = self.machine_st
- .stack
- .index_or_frame(self.machine_st.b)
- .prelude
- .num_cells;
-
- self.machine_st.cc = cell_as_fixnum!(
- self.machine_st.stack[stack_loc!(OrFrame, self.machine_st.b, n-1)]
- ).get_num() as usize;
-
- if next_i > 0 {
+ FirstOrNext::First => {
match self.find_living_dynamic_else(p + next_i) {
Some(_) => {
- self.retry_me_else(next_i);
+ self.machine_st.registers
+ [self.machine_st.num_of_args + 1] = fixnum_as_cell!(
+ Fixnum::build_with(self.machine_st.cc as i64)
+ );
+
+ self.machine_st.num_of_args += 1;
+ self.try_me_else(next_i);
+ self.machine_st.num_of_args -= 1;
}
None => {
- self.trust_me();
+ self.machine_st.p += 1;
}
}
- } else {
- self.trust_me();
}
+ FirstOrNext::Next => {
+ let n = self
+ .machine_st
+ .stack
+ .index_or_frame(self.machine_st.b)
+ .prelude
+ .num_cells;
+
+ self.machine_st.cc = cell_as_fixnum!(
+ self.machine_st.stack
+ [stack_loc!(OrFrame, self.machine_st.b, n - 1)]
+ )
+ .get_num()
+ as usize;
+
+ if next_i > 0 {
+ match self.find_living_dynamic_else(p + next_i) {
+ Some(_) => {
+ self.retry_me_else(next_i);
+ }
+ None => {
+ self.trust_me();
+ }
+ }
+ } else {
+ self.trust_me();
+ }
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(
+ &mut self.machine_st
+ )
+ );
+ }
}
}
+ None => {
+ self.machine_st.fail = true;
+ }
}
- None => {
- self.machine_st.fail = true;
- }
- }
- self.machine_st.dynamic_mode = FirstOrNext::Next;
+ self.machine_st.dynamic_mode = FirstOrNext::Next;
- if self.machine_st.fail {
- self.machine_st.backtrack();
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ }
}
- }
- &Instruction::TryMeElse(offset) => {
- self.try_me_else(offset);
- }
- &Instruction::DefaultRetryMeElse(offset) => {
- self.retry_me_else(offset);
- }
- &Instruction::DefaultTrustMe(_) => {
- self.trust_me();
- }
- &Instruction::RetryMeElse(offset) => {
- self.retry_me_else(offset);
-
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
- }
- &Instruction::TrustMe(_) => {
- self.trust_me();
-
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
- }
- &Instruction::NeckCut => {
- self.machine_st.neck_cut();
- self.machine_st.p += 1;
- }
- &Instruction::GetLevel(r) => {
- let b0 = self.machine_st.b0;
-
- self.machine_st[r] = fixnum_as_cell!(Fixnum::as_cutpoint(b0 as i64));
- self.machine_st.p += 1;
- }
- &Instruction::GetPrevLevel(r) => {
- let prev_b = self.machine_st.stack.index_or_frame(self.machine_st.b).prelude.b;
-
- self.machine_st[r] = fixnum_as_cell!(Fixnum::as_cutpoint(prev_b as i64));
- self.machine_st.p += 1;
- }
- &Instruction::GetCutPoint(r) => {
- self.machine_st[r] = fixnum_as_cell!(Fixnum::as_cutpoint(self.machine_st.b as i64));
- self.machine_st.p += 1;
- }
- &Instruction::Cut(r) => {
- let value = self.machine_st[r];
- self.machine_st.cut_body(value);
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
- continue;
+ &Instruction::TryMeElse(offset) => {
+ self.try_me_else(offset);
}
-
- if (self.machine_st.run_cleaners_fn)(self) {
- continue;
+ &Instruction::DefaultRetryMeElse(offset) => {
+ self.retry_me_else(offset);
+ }
+ &Instruction::DefaultTrustMe(_) => {
+ self.trust_me();
}
+ &Instruction::RetryMeElse(offset) => {
+ self.retry_me_else(offset);
- self.machine_st.p += 1;
- }
- &Instruction::Allocate(num_cells) => {
- self.machine_st.allocate(num_cells);
- }
- &Instruction::DefaultCallAcyclicTerm => {
- let addr = self.machine_st.registers[1];
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
+ }
+ &Instruction::TrustMe(_) => {
+ self.trust_me();
- if self.machine_st.is_cyclic_term(addr) {
- self.machine_st.backtrack();
- } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
+ }
+ &Instruction::NeckCut => {
+ self.machine_st.neck_cut();
self.machine_st.p += 1;
}
- }
- &Instruction::DefaultExecuteAcyclicTerm => {
- let addr = self.machine_st.registers[1];
+ &Instruction::GetLevel(r) => {
+ let b0 = self.machine_st.b0;
- if self.machine_st.is_cyclic_term(addr) {
- self.machine_st.backtrack();
- } else {
- self.machine_st.p = self.machine_st.cp;
+ self.machine_st[r] = fixnum_as_cell!(Fixnum::as_cutpoint(b0 as i64));
+ self.machine_st.p += 1;
}
- }
- &Instruction::DefaultCallArg => {
- try_or_throw!(self.machine_st, self.machine_st.try_arg());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::DefaultExecuteArg => {
- try_or_throw!(self.machine_st, self.machine_st.try_arg());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::DefaultCallCompare => {
- try_or_throw!(self.machine_st, self.machine_st.compare());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::DefaultExecuteCompare => {
- try_or_throw!(self.machine_st, self.machine_st.compare());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::DefaultCallTermGreaterThan => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::GetPrevLevel(r) => {
+ let prev_b = self
+ .machine_st
+ .stack
+ .index_or_frame(self.machine_st.b)
+ .prelude
+ .b;
- if let Some(Ordering::Greater) = compare_term_test!(self.machine_st, a1, a2) {
+ self.machine_st[r] = fixnum_as_cell!(Fixnum::as_cutpoint(prev_b as i64));
self.machine_st.p += 1;
- } else {
- self.machine_st.backtrack();
}
- }
- &Instruction::DefaultExecuteTermGreaterThan => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
-
- if let Some(Ordering::Greater) = compare_term_test!(self.machine_st, a1, a2) {
- self.machine_st.p = self.machine_st.cp;
- } else {
- self.machine_st.backtrack();
+ &Instruction::GetCutPoint(r) => {
+ self.machine_st[r] =
+ fixnum_as_cell!(Fixnum::as_cutpoint(self.machine_st.b as i64));
+ self.machine_st.p += 1;
}
- }
- &Instruction::DefaultCallTermLessThan => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::Cut(r) => {
+ let value = self.machine_st[r];
+ self.machine_st.cut_body(value);
+
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ continue;
+ }
+
+ if (self.machine_st.run_cleaners_fn)(self) {
+ continue;
+ }
- if let Some(Ordering::Less) = compare_term_test!(self.machine_st, a1, a2) {
self.machine_st.p += 1;
- } else {
- self.machine_st.backtrack();
}
- }
- &Instruction::DefaultExecuteTermLessThan => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
-
- if let Some(Ordering::Less) = compare_term_test!(self.machine_st, a1, a2) {
- self.machine_st.p = self.machine_st.cp;
- } else {
- self.machine_st.backtrack();
+ &Instruction::Allocate(num_cells) => {
+ self.machine_st.allocate(num_cells);
}
- }
- &Instruction::DefaultCallTermGreaterThanOrEqual => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::DefaultCallAcyclicTerm => {
+ let addr = self.machine_st.registers[1];
- match compare_term_test!(self.machine_st, a1, a2) {
- Some(Ordering::Greater | Ordering::Equal) => {
+ if self.machine_st.is_cyclic_term(addr) {
+ self.machine_st.backtrack();
+ } else {
self.machine_st.p += 1;
}
- _ => {
+ }
+ &Instruction::DefaultExecuteAcyclicTerm => {
+ let addr = self.machine_st.registers[1];
+
+ if self.machine_st.is_cyclic_term(addr) {
self.machine_st.backtrack();
+ } else {
+ self.machine_st.p = self.machine_st.cp;
}
}
- }
- &Instruction::DefaultExecuteTermGreaterThanOrEqual => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::DefaultCallArg => {
+ try_or_throw!(self.machine_st, self.machine_st.try_arg());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::DefaultExecuteArg => {
+ try_or_throw!(self.machine_st, self.machine_st.try_arg());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::DefaultCallCompare => {
+ try_or_throw!(self.machine_st, self.machine_st.compare());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::DefaultExecuteCompare => {
+ try_or_throw!(self.machine_st, self.machine_st.compare());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::DefaultCallTermGreaterThan => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- match compare_term_test!(self.machine_st, a1, a2) {
- Some(Ordering::Greater | Ordering::Equal) => {
- self.machine_st.p = self.machine_st.cp;
+ if let Some(Ordering::Greater) = compare_term_test!(self.machine_st, a1, a2)
+ {
+ self.machine_st.p += 1;
+ } else {
+ self.machine_st.backtrack();
}
- _ => {
+ }
+ &Instruction::DefaultExecuteTermGreaterThan => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
+
+ if let Some(Ordering::Greater) = compare_term_test!(self.machine_st, a1, a2)
+ {
+ self.machine_st.p = self.machine_st.cp;
+ } else {
self.machine_st.backtrack();
}
}
- }
- &Instruction::DefaultCallTermLessThanOrEqual => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::DefaultCallTermLessThan => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- match compare_term_test!(self.machine_st, a1, a2) {
- Some(Ordering::Less | Ordering::Equal) => {
+ if let Some(Ordering::Less) = compare_term_test!(self.machine_st, a1, a2) {
self.machine_st.p += 1;
- }
- _ => {
+ } else {
self.machine_st.backtrack();
}
}
- }
- &Instruction::DefaultExecuteTermLessThanOrEqual => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::DefaultExecuteTermLessThan => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- match compare_term_test!(self.machine_st, a1, a2) {
- Some(Ordering::Less | Ordering::Equal) => {
+ if let Some(Ordering::Less) = compare_term_test!(self.machine_st, a1, a2) {
self.machine_st.p = self.machine_st.cp;
- }
- _ => {
+ } else {
self.machine_st.backtrack();
}
}
- }
- &Instruction::DefaultCallCopyTerm => {
- self.machine_st.copy_term(AttrVarPolicy::DeepCopy);
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::DefaultExecuteCopyTerm => {
- self.machine_st.copy_term(AttrVarPolicy::DeepCopy);
+ &Instruction::DefaultCallTermGreaterThanOrEqual => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- self.machine_st.p = self.machine_st.cp;
+ match compare_term_test!(self.machine_st, a1, a2) {
+ Some(Ordering::Greater | Ordering::Equal) => {
+ self.machine_st.p += 1;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ }
}
- }
- &Instruction::DefaultCallTermEqual => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::DefaultExecuteTermGreaterThanOrEqual => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- if self.machine_st.eq_test(a1, a2) {
- self.machine_st.backtrack();
- } else {
- self.machine_st.p += 1;
+ match compare_term_test!(self.machine_st, a1, a2) {
+ Some(Ordering::Greater | Ordering::Equal) => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ }
}
- }
- &Instruction::DefaultExecuteTermEqual => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::DefaultCallTermLessThanOrEqual => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- if self.machine_st.eq_test(a1, a2) {
- self.machine_st.backtrack();
- } else {
- self.machine_st.p = self.machine_st.cp;
+ match compare_term_test!(self.machine_st, a1, a2) {
+ Some(Ordering::Less | Ordering::Equal) => {
+ self.machine_st.p += 1;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ }
}
- }
- &Instruction::DefaultCallGround => {
- if self.machine_st.ground_test() {
- self.machine_st.backtrack();
- } else {
- self.machine_st.p += 1;
+ &Instruction::DefaultExecuteTermLessThanOrEqual => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
+
+ match compare_term_test!(self.machine_st, a1, a2) {
+ Some(Ordering::Less | Ordering::Equal) => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ }
}
- }
- &Instruction::DefaultExecuteGround => {
- if self.machine_st.ground_test() {
- self.machine_st.backtrack();
- } else {
- self.machine_st.p = self.machine_st.cp;
+ &Instruction::DefaultCallCopyTerm => {
+ self.machine_st.copy_term(AttrVarPolicy::DeepCopy);
+ step_or_fail!(self, self.machine_st.p += 1);
}
- }
- &Instruction::DefaultCallFunctor => {
- try_or_throw!(self.machine_st, self.machine_st.try_functor());
-
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::DefaultExecuteFunctor => {
- try_or_throw!(self.machine_st, self.machine_st.try_functor());
+ &Instruction::DefaultExecuteCopyTerm => {
+ self.machine_st.copy_term(AttrVarPolicy::DeepCopy);
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- self.machine_st.p = self.machine_st.cp;
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
+ self.machine_st.p = self.machine_st.cp;
+ }
}
- }
- &Instruction::DefaultCallTermNotEqual => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::DefaultCallTermEqual => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- if let Some(Ordering::Equal) = compare_term_test!(self.machine_st, a1, a2) {
- self.machine_st.backtrack();
- } else {
- self.machine_st.p += 1;
+ if self.machine_st.eq_test(a1, a2) {
+ self.machine_st.backtrack();
+ } else {
+ self.machine_st.p += 1;
+ }
}
- }
- &Instruction::DefaultExecuteTermNotEqual => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::DefaultExecuteTermEqual => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- if let Some(Ordering::Equal) = compare_term_test!(self.machine_st, a1, a2) {
- self.machine_st.backtrack();
- } else {
- self.machine_st.p = self.machine_st.cp;
+ if self.machine_st.eq_test(a1, a2) {
+ self.machine_st.backtrack();
+ } else {
+ self.machine_st.p = self.machine_st.cp;
+ }
}
- }
- &Instruction::DefaultCallSort => {
- try_or_throw!(self.machine_st, self.machine_st.sort());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::DefaultExecuteSort => {
- try_or_throw!(self.machine_st, self.machine_st.sort());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::DefaultCallKeySort => {
- try_or_throw!(self.machine_st, self.machine_st.keysort(VarComparison::Distinct));
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::DefaultExecuteKeySort => {
- try_or_throw!(self.machine_st, self.machine_st.keysort(VarComparison::Distinct));
+ &Instruction::DefaultCallGround => {
+ if self.machine_st.ground_test() {
+ self.machine_st.backtrack();
+ } else {
+ self.machine_st.p += 1;
+ }
+ }
+ &Instruction::DefaultExecuteGround => {
+ if self.machine_st.ground_test() {
+ self.machine_st.backtrack();
+ } else {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ }
+ &Instruction::DefaultCallFunctor => {
+ try_or_throw!(self.machine_st, self.machine_st.try_functor());
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- self.machine_st.p = self.machine_st.cp;
+ step_or_fail!(self, self.machine_st.p += 1);
}
- }
- &Instruction::DefaultCallIs(r, at) => {
- try_or_throw!(self.machine_st, self.machine_st.is(r, at));
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::DefaultExecuteIs(r, at) => {
- try_or_throw!(self.machine_st, self.machine_st.is(r, at));
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- Instruction::DefaultCallGetNumber(at) => {
- try_or_throw!(self.machine_st, self.machine_st.get_number(at));
- step_or_fail!(self, self.machine_st.p += 1);
- }
- Instruction::DefaultExecuteGetNumber(at) => {
- try_or_throw!(self.machine_st, self.machine_st.get_number(at));
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallAcyclicTerm => {
- let addr = self.machine_st.registers[1];
+ &Instruction::DefaultExecuteFunctor => {
+ try_or_throw!(self.machine_st, self.machine_st.try_functor());
- if self.machine_st.is_cyclic_term(addr) {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ }
+ &Instruction::DefaultCallTermNotEqual => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- self.machine_st.p += 1;
+ if let Some(Ordering::Equal) = compare_term_test!(self.machine_st, a1, a2) {
+ self.machine_st.backtrack();
+ } else {
+ self.machine_st.p += 1;
+ }
}
- }
- &Instruction::ExecuteAcyclicTerm => {
- let addr = self.machine_st.registers[1];
+ &Instruction::DefaultExecuteTermNotEqual => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- if self.machine_st.is_cyclic_term(addr) {
- self.machine_st.backtrack();
- } else {
+ if let Some(Ordering::Equal) = compare_term_test!(self.machine_st, a1, a2) {
+ self.machine_st.backtrack();
+ } else {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ }
+ &Instruction::DefaultCallSort => {
+ try_or_throw!(self.machine_st, self.machine_st.sort());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::DefaultExecuteSort => {
+ try_or_throw!(self.machine_st, self.machine_st.sort());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::DefaultCallKeySort => {
try_or_throw!(
self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ self.machine_st.keysort(VarComparison::Distinct)
);
-
- self.machine_st.p = self.machine_st.cp;
+ step_or_fail!(self, self.machine_st.p += 1);
}
- }
- &Instruction::CallArg => {
- try_or_throw!(self.machine_st, self.machine_st.try_arg());
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
+ &Instruction::DefaultExecuteKeySort => {
try_or_throw!(
self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ self.machine_st.keysort(VarComparison::Distinct)
);
- self.machine_st.p += 1;
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
+ self.machine_st.p = self.machine_st.cp;
+ }
}
- }
- &Instruction::ExecuteArg => {
- try_or_throw!(self.machine_st, self.machine_st.try_arg());
+ &Instruction::DefaultCallIs(r, at) => {
+ try_or_throw!(self.machine_st, self.machine_st.is(r, at));
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::DefaultExecuteIs(r, at) => {
+ try_or_throw!(self.machine_st, self.machine_st.is(r, at));
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ Instruction::DefaultCallGetNumber(at) => {
+ try_or_throw!(self.machine_st, self.machine_st.get_number(at));
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ Instruction::DefaultExecuteGetNumber(at) => {
+ try_or_throw!(self.machine_st, self.machine_st.get_number(at));
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallAcyclicTerm => {
+ let addr = self.machine_st.registers[1];
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ if self.machine_st.is_cyclic_term(addr) {
+ self.machine_st.backtrack();
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- self.machine_st.p = self.machine_st.cp;
+ self.machine_st.p += 1;
+ }
}
- }
- &Instruction::CallCompare => {
- try_or_throw!(self.machine_st, self.machine_st.compare());
+ &Instruction::ExecuteAcyclicTerm => {
+ let addr = self.machine_st.registers[1];
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ if self.machine_st.is_cyclic_term(addr) {
+ self.machine_st.backtrack();
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- self.machine_st.p += 1;
+ self.machine_st.p = self.machine_st.cp;
+ }
}
- }
- &Instruction::ExecuteCompare => {
- try_or_throw!(self.machine_st, self.machine_st.compare());
+ &Instruction::CallArg => {
+ try_or_throw!(self.machine_st, self.machine_st.try_arg());
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
-
- self.machine_st.p = self.machine_st.cp;
- }
- }
- &Instruction::CallTermGreaterThan => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
-
- if let Some(Ordering::Greater) = compare_term_test!(self.machine_st, a1, a2) {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- self.machine_st.p += 1;
- } else {
- self.machine_st.backtrack();
+ self.machine_st.p += 1;
+ }
}
- }
- &Instruction::ExecuteTermGreaterThan => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::ExecuteArg => {
+ try_or_throw!(self.machine_st, self.machine_st.try_arg());
- if let Some(Ordering::Greater) = compare_term_test!(self.machine_st, a1, a2) {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- self.machine_st.p = self.machine_st.cp;
- } else {
- self.machine_st.backtrack();
+ self.machine_st.p = self.machine_st.cp;
+ }
}
- }
- &Instruction::CallTermLessThan => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::CallCompare => {
+ try_or_throw!(self.machine_st, self.machine_st.compare());
- if let Some(Ordering::Less) = compare_term_test!(self.machine_st, a1, a2) {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- self.machine_st.p += 1;
- } else {
- self.machine_st.backtrack();
+ self.machine_st.p += 1;
+ }
}
- }
- &Instruction::ExecuteTermLessThan => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::ExecuteCompare => {
+ try_or_throw!(self.machine_st, self.machine_st.compare());
- if let Some(Ordering::Less) = compare_term_test!(self.machine_st, a1, a2) {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- self.machine_st.p = self.machine_st.cp;
- } else {
- self.machine_st.backtrack();
+ self.machine_st.p = self.machine_st.cp;
+ }
}
- }
- &Instruction::CallTermGreaterThanOrEqual => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::CallTermGreaterThan => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- match compare_term_test!(self.machine_st, a1, a2) {
- Some(Ordering::Greater | Ordering::Equal) => {
+ if let Some(Ordering::Greater) = compare_term_test!(self.machine_st, a1, a2)
+ {
try_or_throw!(
self.machine_st,
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
);
self.machine_st.p += 1;
- }
- _ => {
+ } else {
self.machine_st.backtrack();
}
}
- }
- &Instruction::ExecuteTermGreaterThanOrEqual => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::ExecuteTermGreaterThan => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- match compare_term_test!(self.machine_st, a1, a2) {
- Some(Ordering::Greater | Ordering::Equal) => {
+ if let Some(Ordering::Greater) = compare_term_test!(self.machine_st, a1, a2)
+ {
try_or_throw!(
self.machine_st,
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
);
self.machine_st.p = self.machine_st.cp;
- }
- _ => {
+ } else {
self.machine_st.backtrack();
}
}
- }
- &Instruction::CallTermLessThanOrEqual => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::CallTermLessThan => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- match compare_term_test!(self.machine_st, a1, a2) {
- Some(Ordering::Less | Ordering::Equal) => {
+ if let Some(Ordering::Less) = compare_term_test!(self.machine_st, a1, a2) {
try_or_throw!(
self.machine_st,
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
);
self.machine_st.p += 1;
- }
- _ => {
+ } else {
self.machine_st.backtrack();
}
}
- }
- &Instruction::ExecuteTermLessThanOrEqual => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::ExecuteTermLessThan => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- match compare_term_test!(self.machine_st, a1, a2) {
- Some(Ordering::Less | Ordering::Equal) => {
+ if let Some(Ordering::Less) = compare_term_test!(self.machine_st, a1, a2) {
try_or_throw!(
self.machine_st,
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
);
self.machine_st.p = self.machine_st.cp;
- }
- _ => {
+ } else {
self.machine_st.backtrack();
}
}
- }
- &Instruction::CallCopyTerm => {
- self.machine_st.copy_term(AttrVarPolicy::DeepCopy);
+ &Instruction::CallTermGreaterThanOrEqual => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ match compare_term_test!(self.machine_st, a1, a2) {
+ Some(Ordering::Greater | Ordering::Equal) => {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- self.machine_st.p += 1;
+ self.machine_st.p += 1;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ }
}
- }
- &Instruction::ExecuteCopyTerm => {
- self.machine_st.copy_term(AttrVarPolicy::DeepCopy);
+ &Instruction::ExecuteTermGreaterThanOrEqual => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ match compare_term_test!(self.machine_st, a1, a2) {
+ Some(Ordering::Greater | Ordering::Equal) => {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- self.machine_st.p = self.machine_st.cp;
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ }
}
- }
- &Instruction::CallTermEqual => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::CallTermLessThanOrEqual => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- if self.machine_st.eq_test(a1, a2) {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ match compare_term_test!(self.machine_st, a1, a2) {
+ Some(Ordering::Less | Ordering::Equal) => {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- self.machine_st.p += 1;
+ self.machine_st.p += 1;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ }
}
- }
- &Instruction::ExecuteTermEqual => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::ExecuteTermLessThanOrEqual => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- if self.machine_st.eq_test(a1, a2) {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ match compare_term_test!(self.machine_st, a1, a2) {
+ Some(Ordering::Less | Ordering::Equal) => {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- self.machine_st.p = self.machine_st.cp;
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ }
}
- }
- &Instruction::CallGround => {
- if self.machine_st.ground_test() {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ &Instruction::CallCopyTerm => {
+ self.machine_st.copy_term(AttrVarPolicy::DeepCopy);
- self.machine_st.p += 1;
- }
- }
- &Instruction::ExecuteGround => {
- if self.machine_st.ground_test() {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- self.machine_st.p = self.machine_st.cp;
+ self.machine_st.p += 1;
+ }
}
- }
- &Instruction::CallFunctor => {
- try_or_throw!(self.machine_st, self.machine_st.try_functor());
+ &Instruction::ExecuteCopyTerm => {
+ self.machine_st.copy_term(AttrVarPolicy::DeepCopy);
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- self.machine_st.p += 1;
+ self.machine_st.p = self.machine_st.cp;
+ }
}
- }
- &Instruction::ExecuteFunctor => {
- try_or_throw!(self.machine_st, self.machine_st.try_functor());
+ &Instruction::CallTermEqual => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ if self.machine_st.eq_test(a1, a2) {
+ self.machine_st.backtrack();
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- self.machine_st.p = self.machine_st.cp;
+ self.machine_st.p += 1;
+ }
}
- }
- &Instruction::CallTermNotEqual => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::ExecuteTermEqual => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- if let Some(Ordering::Equal) = compare_term_test!(self.machine_st, a1, a2) {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ if self.machine_st.eq_test(a1, a2) {
+ self.machine_st.backtrack();
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- self.machine_st.p += 1;
+ self.machine_st.p = self.machine_st.cp;
+ }
}
- }
- &Instruction::ExecuteTermNotEqual => {
- let a1 = self.machine_st.registers[1];
- let a2 = self.machine_st.registers[2];
+ &Instruction::CallGround => {
+ if self.machine_st.ground_test() {
+ self.machine_st.backtrack();
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- if let Some(Ordering::Equal) = compare_term_test!(self.machine_st, a1, a2) {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ self.machine_st.p += 1;
+ }
+ }
+ &Instruction::ExecuteGround => {
+ if self.machine_st.ground_test() {
+ self.machine_st.backtrack();
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- self.machine_st.p = self.machine_st.cp;
+ self.machine_st.p = self.machine_st.cp;
+ }
}
- }
- &Instruction::CallSort => {
- try_or_throw!(self.machine_st, self.machine_st.sort());
+ &Instruction::CallFunctor => {
+ try_or_throw!(self.machine_st, self.machine_st.try_functor());
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- self.machine_st.p += 1;
+ self.machine_st.p += 1;
+ }
}
- }
- &Instruction::ExecuteSort => {
- try_or_throw!(self.machine_st, self.machine_st.sort());
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ &Instruction::ExecuteFunctor => {
+ try_or_throw!(self.machine_st, self.machine_st.try_functor());
- self.machine_st.p = self.machine_st.cp;
- }
- }
- &Instruction::CallKeySort => {
- try_or_throw!(self.machine_st, self.machine_st.keysort(VarComparison::Distinct));
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
-
- self.machine_st.p += 1;
- }
- }
- &Instruction::ExecuteKeySort => {
- try_or_throw!(self.machine_st, self.machine_st.keysort(VarComparison::Distinct));
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
-
- self.machine_st.p = self.machine_st.cp;
- }
- }
- &Instruction::CallKeySortWithConstantVarOrdering => {
- try_or_throw!(self.machine_st, self.machine_st.keysort(VarComparison::Indistinct));
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
-
- self.machine_st.p += 1;
- }
- }
- &Instruction::ExecuteKeySortWithConstantVarOrdering => {
- try_or_throw!(self.machine_st, self.machine_st.keysort(VarComparison::Indistinct));
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
-
- self.machine_st.p = self.machine_st.cp;
- }
- }
- &Instruction::CallIs(r, at) => {
- try_or_throw!(self.machine_st, self.machine_st.is(r, at));
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
-
- self.machine_st.p += 1;
- }
- }
- &Instruction::ExecuteIs(r, at) => {
- try_or_throw!(self.machine_st, self.machine_st.is(r, at));
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
-
- self.machine_st.p = self.machine_st.cp;
- }
- }
- Instruction::CallGetNumber(at) => {
- try_or_throw!(self.machine_st, self.machine_st.get_number(at));
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
-
- self.machine_st.p += 1;
- }
- }
- Instruction::ExecuteGetNumber(at) => {
- try_or_throw!(self.machine_st, self.machine_st.get_number(at));
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
-
- self.machine_st.p = self.machine_st.cp;
- }
- }
- &Instruction::CallN(arity) => {
- let pred = self.machine_st.registers[1];
-
- for i in 2..arity + 1 {
- self.machine_st.registers[i - 1] = self.machine_st.registers[i];
- }
-
- self.machine_st.registers[arity] = pred;
-
- try_or_throw!(
- self.machine_st,
- self.call_n(atom!("user"), arity)
- );
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
- }
- }
- &Instruction::ExecuteN(arity) => {
- let pred = self.machine_st.registers[1];
-
- for i in 2..arity + 1 {
- self.machine_st.registers[i - 1] = self.machine_st.registers[i];
- }
-
- self.machine_st.registers[arity] = pred;
-
- try_or_throw!(
- self.machine_st,
- self.execute_n(atom!("user"), arity)
- );
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
- }
- }
- &Instruction::DefaultCallN(arity) => {
- let pred = self.machine_st.registers[1];
-
- for i in 2..arity + 1 {
- self.machine_st.registers[i - 1] = self.machine_st.registers[i];
- }
-
- self.machine_st.registers[arity] = pred;
-
- try_or_throw!(
- self.machine_st,
- self.call_n(atom!("user"), arity)
- );
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
- }
- }
- &Instruction::DefaultExecuteN(arity) => {
- let pred = self.machine_st.registers[1];
-
- for i in 2..arity + 1 {
- self.machine_st.registers[i - 1] = self.machine_st.registers[i];
- }
-
- self.machine_st.registers[arity] = pred;
-
- try_or_throw!(
- self.machine_st,
- self.execute_n(atom!("user"), arity)
- );
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- if self.machine_st.fail {
- self.machine_st.backtrack();
+ self.machine_st.p = self.machine_st.cp;
+ }
}
- }
- &Instruction::CallNumberLessThanOrEqual(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::CallTermNotEqual => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- match n1.cmp(&n2) {
- Ordering::Less | Ordering::Equal => {
+ if let Some(Ordering::Equal) = compare_term_test!(self.machine_st, a1, a2) {
+ self.machine_st.backtrack();
+ } else {
try_or_throw!(
self.machine_st,
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
self.machine_st.p += 1;
}
- _ => {
- self.machine_st.backtrack();
- }
}
- }
- &Instruction::ExecuteNumberLessThanOrEqual(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::ExecuteTermNotEqual => {
+ let a1 = self.machine_st.registers[1];
+ let a2 = self.machine_st.registers[2];
- match n1.cmp(&n2) {
- Ordering::Less | Ordering::Equal => {
+ if let Some(Ordering::Equal) = compare_term_test!(self.machine_st, a1, a2) {
+ self.machine_st.backtrack();
+ } else {
try_or_throw!(
self.machine_st,
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
self.machine_st.p = self.machine_st.cp;
}
- _ => {
- self.machine_st.backtrack();
- }
}
- }
- &Instruction::CallNumberEqual(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::CallSort => {
+ try_or_throw!(self.machine_st, self.machine_st.sort());
- match n1.cmp(&n2) {
- Ordering::Equal => {
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
try_or_throw!(
self.machine_st,
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
self.machine_st.p += 1;
}
- _ => {
- self.machine_st.backtrack();
- }
}
- }
- &Instruction::ExecuteNumberEqual(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::ExecuteSort => {
+ try_or_throw!(self.machine_st, self.machine_st.sort());
- match n1.cmp(&n2) {
- Ordering::Equal => {
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
try_or_throw!(
self.machine_st,
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
self.machine_st.p = self.machine_st.cp;
}
- _ => {
- self.machine_st.backtrack();
- }
}
- }
- &Instruction::CallNumberNotEqual(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::CallKeySort => {
+ try_or_throw!(
+ self.machine_st,
+ self.machine_st.keysort(VarComparison::Distinct)
+ );
- match n1.cmp(&n2) {
- Ordering::Equal => {
+ if self.machine_st.fail {
self.machine_st.backtrack();
- }
- _ => {
+ } else {
try_or_throw!(
self.machine_st,
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
self.machine_st.p += 1;
}
}
- }
- &Instruction::ExecuteNumberNotEqual(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::ExecuteKeySort => {
+ try_or_throw!(
+ self.machine_st,
+ self.machine_st.keysort(VarComparison::Distinct)
+ );
- match n1.cmp(&n2) {
- Ordering::Equal => {
+ if self.machine_st.fail {
self.machine_st.backtrack();
- }
- _ => {
+ } else {
try_or_throw!(
self.machine_st,
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
self.machine_st.p = self.machine_st.cp;
}
}
- }
- &Instruction::CallNumberGreaterThanOrEqual(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::CallKeySortWithConstantVarOrdering => {
+ try_or_throw!(
+ self.machine_st,
+ self.machine_st.keysort(VarComparison::Indistinct)
+ );
- match n1.cmp(&n2) {
- Ordering::Greater | Ordering::Equal => {
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
try_or_throw!(
self.machine_st,
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
self.machine_st.p += 1;
}
- _ => {
- self.machine_st.backtrack();
- }
}
- }
- &Instruction::ExecuteNumberGreaterThanOrEqual(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::ExecuteKeySortWithConstantVarOrdering => {
+ try_or_throw!(
+ self.machine_st,
+ self.machine_st.keysort(VarComparison::Indistinct)
+ );
- match n1.cmp(&n2) {
- Ordering::Greater | Ordering::Equal => {
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
try_or_throw!(
self.machine_st,
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
self.machine_st.p = self.machine_st.cp;
}
- _ => {
- self.machine_st.backtrack();
- }
}
- }
- &Instruction::CallNumberGreaterThan(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::CallIs(r, at) => {
+ try_or_throw!(self.machine_st, self.machine_st.is(r, at));
- match n1.cmp(&n2) {
- Ordering::Greater => {
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
try_or_throw!(
self.machine_st,
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
self.machine_st.p += 1;
}
- _ => {
- self.machine_st.backtrack();
- }
}
- }
- &Instruction::ExecuteNumberGreaterThan(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::ExecuteIs(r, at) => {
+ try_or_throw!(self.machine_st, self.machine_st.is(r, at));
- match n1.cmp(&n2) {
- Ordering::Greater => {
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
try_or_throw!(
self.machine_st,
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
self.machine_st.p = self.machine_st.cp;
}
- _ => {
- self.machine_st.backtrack();
- }
}
- }
- &Instruction::CallNumberLessThan(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ Instruction::CallGetNumber(at) => {
+ try_or_throw!(self.machine_st, self.machine_st.get_number(at));
- match n1.cmp(&n2) {
- Ordering::Less => {
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
try_or_throw!(
self.machine_st,
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
self.machine_st.p += 1;
}
- _ => {
- self.machine_st.backtrack();
- }
}
- }
- &Instruction::ExecuteNumberLessThan(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ Instruction::ExecuteGetNumber(at) => {
+ try_or_throw!(self.machine_st, self.machine_st.get_number(at));
- match n1.cmp(&n2) {
- Ordering::Less => {
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
try_or_throw!(
self.machine_st,
(self.machine_st.increment_call_count_fn)(&mut self.machine_st)
self.machine_st.p = self.machine_st.cp;
}
- _ => {
- self.machine_st.backtrack();
- }
}
- }
- &Instruction::DefaultCallNumberLessThanOrEqual(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::CallN(arity) => {
+ let pred = self.machine_st.registers[1];
- match n1.cmp(&n2) {
- Ordering::Less | Ordering::Equal => {
- self.machine_st.p += 1;
+ for i in 2..arity + 1 {
+ self.machine_st.registers[i - 1] = self.machine_st.registers[i];
}
- _ => {
- self.machine_st.backtrack();
- }
- }
- }
- &Instruction::DefaultExecuteNumberLessThanOrEqual(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- match n1.cmp(&n2) {
- Ordering::Less | Ordering::Equal => {
- self.machine_st.p = self.machine_st.cp;
- }
- _ => {
+ self.machine_st.registers[arity] = pred;
+
+ try_or_throw!(self.machine_st, self.call_n(atom!("user"), arity));
+
+ if self.machine_st.fail {
self.machine_st.backtrack();
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
}
}
- }
- &Instruction::DefaultCallNumberNotEqual(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::ExecuteN(arity) => {
+ let pred = self.machine_st.registers[1];
- match n1.cmp(&n2) {
- Ordering::Equal => {
- self.machine_st.backtrack();
- }
- _ => {
- self.machine_st.p += 1;
+ for i in 2..arity + 1 {
+ self.machine_st.registers[i - 1] = self.machine_st.registers[i];
}
- }
- }
- &Instruction::DefaultExecuteNumberNotEqual(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- match n1.cmp(&n2) {
- Ordering::Equal => {
+ self.machine_st.registers[arity] = pred;
+
+ try_or_throw!(self.machine_st, self.execute_n(atom!("user"), arity));
+
+ if self.machine_st.fail {
self.machine_st.backtrack();
- }
- _ => {
- self.machine_st.p = self.machine_st.cp;
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
}
}
- }
- &Instruction::DefaultCallNumberEqual(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::DefaultCallN(arity) => {
+ let pred = self.machine_st.registers[1];
- match n1.cmp(&n2) {
- Ordering::Equal => {
- self.machine_st.p += 1;
+ for i in 2..arity + 1 {
+ self.machine_st.registers[i - 1] = self.machine_st.registers[i];
}
- _ => {
+
+ self.machine_st.registers[arity] = pred;
+
+ try_or_throw!(self.machine_st, self.call_n(atom!("user"), arity));
+
+ if self.machine_st.fail {
self.machine_st.backtrack();
}
}
- }
- &Instruction::DefaultExecuteNumberEqual(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::DefaultExecuteN(arity) => {
+ let pred = self.machine_st.registers[1];
- match n1.cmp(&n2) {
- Ordering::Equal => {
- self.machine_st.p = self.machine_st.cp;
+ for i in 2..arity + 1 {
+ self.machine_st.registers[i - 1] = self.machine_st.registers[i];
}
- _ => {
+
+ self.machine_st.registers[arity] = pred;
+
+ try_or_throw!(self.machine_st, self.execute_n(atom!("user"), arity));
+
+ if self.machine_st.fail {
self.machine_st.backtrack();
}
}
- }
- &Instruction::DefaultCallNumberGreaterThanOrEqual(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::CallNumberLessThanOrEqual(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- match n1.cmp(&n2) {
- Ordering::Greater | Ordering::Equal => {
- self.machine_st.p += 1;
- }
- _ => {
- self.machine_st.backtrack();
+ match n1.cmp(&n2) {
+ Ordering::Less | Ordering::Equal => {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
+
+ self.machine_st.p += 1;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
}
- }
- &Instruction::DefaultExecuteNumberGreaterThanOrEqual(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::ExecuteNumberLessThanOrEqual(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- match n1.cmp(&n2) {
- Ordering::Greater | Ordering::Equal => {
- self.machine_st.p = self.machine_st.cp;
- }
- _ => {
- self.machine_st.backtrack();
- }
- }
- }
- &Instruction::DefaultCallNumberGreaterThan(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ match n1.cmp(&n2) {
+ Ordering::Less | Ordering::Equal => {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- match n1.cmp(&n2) {
- Ordering::Greater => {
- self.machine_st.p += 1;
- }
- _ => {
- self.machine_st.backtrack();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
}
- }
- &Instruction::DefaultExecuteNumberGreaterThan(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::CallNumberEqual(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- match n1.cmp(&n2) {
- Ordering::Greater => {
- self.machine_st.p = self.machine_st.cp;
- }
- _ => {
- self.machine_st.backtrack();
- }
- }
- }
- &Instruction::DefaultCallNumberLessThan(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ match n1.cmp(&n2) {
+ Ordering::Equal => {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- match n1.cmp(&n2) {
- Ordering::Less => {
- self.machine_st.p += 1;
- }
- _ => {
- self.machine_st.backtrack();
+ self.machine_st.p += 1;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
}
- }
- &Instruction::DefaultExecuteNumberLessThan(ref at_1, ref at_2) => {
- let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
- let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+ &Instruction::ExecuteNumberEqual(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- match n1.cmp(&n2) {
- Ordering::Less => {
- self.machine_st.p = self.machine_st.cp;
- }
- _ => {
- self.machine_st.backtrack();
+ match n1.cmp(&n2) {
+ Ordering::Equal => {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
+
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
}
- }
- //
- &Instruction::CallIsAtom(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ &Instruction::CallNumberNotEqual(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- read_heap_cell!(d,
- (HeapCellValueTag::Atom, (_name, arity)) => {
- if arity == 0 {
- self.machine_st.p += 1;
- } else {
+ match n1.cmp(&n2) {
+ Ordering::Equal => {
self.machine_st.backtrack();
}
- }
- (HeapCellValueTag::Str, s) => {
- let arity = cell_as_atom_cell!(self.machine_st.heap[s])
- .get_arity();
+ _ => {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- if arity == 0 {
self.machine_st.p += 1;
- } else {
- self.machine_st.backtrack();
}
}
- (HeapCellValueTag::Char) => {
- self.machine_st.p += 1;
- }
- _ => {
- self.machine_st.backtrack();
- }
- );
- }
- &Instruction::ExecuteIsAtom(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ }
+ &Instruction::ExecuteNumberNotEqual(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- read_heap_cell!(d,
- (HeapCellValueTag::Atom, (_name, arity)) => {
- if arity == 0 {
- self.machine_st.p = self.machine_st.cp;
- } else {
+ match n1.cmp(&n2) {
+ Ordering::Equal => {
self.machine_st.backtrack();
}
- }
- (HeapCellValueTag::Str, s) => {
- let arity = cell_as_atom_cell!(self.machine_st.heap[s])
- .get_arity();
+ _ => {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- if arity == 0 {
self.machine_st.p = self.machine_st.cp;
- } else {
- self.machine_st.backtrack();
}
}
- (HeapCellValueTag::Char) => {
- self.machine_st.p = self.machine_st.cp;
- }
- _ => {
- self.machine_st.backtrack();
- }
- );
- }
- &Instruction::CallIsAtomic(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ }
+ &Instruction::CallNumberGreaterThanOrEqual(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+
+ match n1.cmp(&n2) {
+ Ordering::Greater | Ordering::Equal => {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- read_heap_cell!(d,
- (HeapCellValueTag::Char | HeapCellValueTag::Fixnum | HeapCellValueTag::F64 |
- HeapCellValueTag::Cons) => {
- self.machine_st.p += 1;
- }
- (HeapCellValueTag::Atom, (_name, arity)) => {
- if arity == 0 {
self.machine_st.p += 1;
- } else {
+ }
+ _ => {
self.machine_st.backtrack();
}
}
- (HeapCellValueTag::Str, s) => {
- let arity = cell_as_atom_cell!(self.machine_st.heap[s])
- .get_arity();
+ }
+ &Instruction::ExecuteNumberGreaterThanOrEqual(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- if arity == 0 {
- self.machine_st.p += 1;
- } else {
+ match n1.cmp(&n2) {
+ Ordering::Greater | Ordering::Equal => {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
+
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
self.machine_st.backtrack();
}
}
- _ => {
- self.machine_st.backtrack();
- }
- );
- }
- &Instruction::ExecuteIsAtomic(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ }
+ &Instruction::CallNumberGreaterThan(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- read_heap_cell!(d,
- (HeapCellValueTag::Char | HeapCellValueTag::Fixnum | HeapCellValueTag::F64 |
- HeapCellValueTag::Cons) => {
- self.machine_st.p = self.machine_st.cp;
- }
- (HeapCellValueTag::Atom, (_name, arity)) => {
- if arity == 0 {
- self.machine_st.p = self.machine_st.cp;
- } else {
+ match n1.cmp(&n2) {
+ Ordering::Greater => {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
+
+ self.machine_st.p += 1;
+ }
+ _ => {
self.machine_st.backtrack();
}
}
- (HeapCellValueTag::Str, s) => {
- let arity = cell_as_atom_cell!(self.machine_st.heap[s])
- .get_arity();
+ }
+ &Instruction::ExecuteNumberGreaterThan(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+
+ match n1.cmp(&n2) {
+ Ordering::Greater => {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- if arity == 0 {
self.machine_st.p = self.machine_st.cp;
- } else {
+ }
+ _ => {
self.machine_st.backtrack();
}
}
- _ => {
- self.machine_st.backtrack();
- }
- );
- }
- &Instruction::CallIsCompound(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ }
+ &Instruction::CallNumberLessThan(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- read_heap_cell!(d,
- (HeapCellValueTag::Lis |
- HeapCellValueTag::PStrLoc |
- HeapCellValueTag::CStr) => {
- self.machine_st.p += 1;
- }
- (HeapCellValueTag::Str, s) => {
- let arity = cell_as_atom_cell!(self.machine_st.heap[s])
- .get_arity();
+ match n1.cmp(&n2) {
+ Ordering::Less => {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- if arity > 0 {
self.machine_st.p += 1;
- } else {
- self.machine_st.backtrack();
}
- }
- (HeapCellValueTag::Atom, (_name, arity)) => {
- if arity > 0 {
- self.machine_st.p += 1;
- } else {
+ _ => {
self.machine_st.backtrack();
}
}
- _ => {
- self.machine_st.backtrack();
- }
- );
- }
- &Instruction::ExecuteIsCompound(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ }
+ &Instruction::ExecuteNumberLessThan(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- read_heap_cell!(d,
- (HeapCellValueTag::Lis |
- HeapCellValueTag::PStrLoc |
- HeapCellValueTag::CStr) => {
- self.machine_st.p = self.machine_st.cp;
- }
- (HeapCellValueTag::Str, s) => {
- let arity = cell_as_atom_cell!(self.machine_st.heap[s])
- .get_arity();
+ match n1.cmp(&n2) {
+ Ordering::Less => {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
- if arity > 0 {
self.machine_st.p = self.machine_st.cp;
- } else {
- self.machine_st.backtrack();
}
- }
- (HeapCellValueTag::Atom, (_name, arity)) => {
- if arity > 0 {
- self.machine_st.p = self.machine_st.cp;
- } else {
+ _ => {
self.machine_st.backtrack();
}
}
- _ => {
- self.machine_st.backtrack();
- }
- );
- }
- &Instruction::CallIsInteger(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ }
+ &Instruction::DefaultCallNumberLessThanOrEqual(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- match Number::try_from(d) {
- Ok(Number::Fixnum(_) | Number::Integer(_)) => {
- self.machine_st.p += 1;
- }
- Ok(Number::Rational(n)) => {
- if n.denominator().is_one() {
+ match n1.cmp(&n2) {
+ Ordering::Less | Ordering::Equal => {
self.machine_st.p += 1;
- } else {
+ }
+ _ => {
self.machine_st.backtrack();
}
}
- _ => {
- self.machine_st.backtrack();
- }
}
- }
- &Instruction::ExecuteIsInteger(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ &Instruction::DefaultExecuteNumberLessThanOrEqual(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- match Number::try_from(d) {
- Ok(Number::Fixnum(_) | Number::Integer(_)) => {
- self.machine_st.p = self.machine_st.cp;
- }
- Ok(Number::Rational(n)) => {
- if n.denominator().is_one() {
+ match n1.cmp(&n2) {
+ Ordering::Less | Ordering::Equal => {
self.machine_st.p = self.machine_st.cp;
- } else {
+ }
+ _ => {
self.machine_st.backtrack();
}
}
- _ => {
- self.machine_st.backtrack();
- }
}
- }
- &Instruction::CallIsNumber(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ &Instruction::DefaultCallNumberNotEqual(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- match Number::try_from(d) {
- Ok(_) => {
- self.machine_st.p += 1;
- }
- _ => {
- self.machine_st.backtrack();
+ match n1.cmp(&n2) {
+ Ordering::Equal => {
+ self.machine_st.backtrack();
+ }
+ _ => {
+ self.machine_st.p += 1;
+ }
}
}
- }
- &Instruction::ExecuteIsNumber(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ &Instruction::DefaultExecuteNumberNotEqual(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- match Number::try_from(d) {
- Ok(_) => {
- self.machine_st.p = self.machine_st.cp;
- }
- _ => {
- self.machine_st.backtrack();
+ match n1.cmp(&n2) {
+ Ordering::Equal => {
+ self.machine_st.backtrack();
+ }
+ _ => {
+ self.machine_st.p = self.machine_st.cp;
+ }
}
}
- }
- &Instruction::CallIsRational(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
-
- read_heap_cell!(d,
- (HeapCellValueTag::Cons, ptr) => {
- match_untyped_arena_ptr!(ptr,
- (ArenaHeaderTag::Rational | ArenaHeaderTag::Integer, _r) => {
- self.machine_st.p += 1;
- }
- _ => {
- self.machine_st.backtrack();
- }
- );
- }
- (HeapCellValueTag::Fixnum) => {
- self.machine_st.p += 1;
- }
- _ => {
- self.machine_st.backtrack();
- }
- );
- }
- &Instruction::ExecuteIsRational(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
-
- read_heap_cell!(d,
- (HeapCellValueTag::Cons, ptr) => {
- match_untyped_arena_ptr!(ptr,
- (ArenaHeaderTag::Rational | ArenaHeaderTag::Integer, _r) => {
- self.machine_st.p = self.machine_st.cp;
- }
- _ => {
- self.machine_st.backtrack();
- }
- );
- }
- (HeapCellValueTag::Fixnum) => {
- self.machine_st.p = self.machine_st.cp;
- }
- _ => {
- self.machine_st.backtrack();
- }
- );
- }
- &Instruction::CallIsFloat(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ &Instruction::DefaultCallNumberEqual(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- match Number::try_from(d) {
- Ok(Number::Float(_)) => {
- self.machine_st.p += 1;
- }
- _ => {
- self.machine_st.backtrack();
+ match n1.cmp(&n2) {
+ Ordering::Equal => {
+ self.machine_st.p += 1;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
}
- }
- &Instruction::ExecuteIsFloat(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ &Instruction::DefaultExecuteNumberEqual(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- match Number::try_from(d) {
- Ok(Number::Float(_)) => {
- self.machine_st.p = self.machine_st.cp;
- }
- _ => {
- self.machine_st.backtrack();
+ match n1.cmp(&n2) {
+ Ordering::Equal => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
}
- }
- &Instruction::CallIsNonVar(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ &Instruction::DefaultCallNumberGreaterThanOrEqual(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- match d.get_tag() {
- HeapCellValueTag::AttrVar |
- HeapCellValueTag::Var |
- HeapCellValueTag::StackVar => {
- self.machine_st.backtrack();
- }
- _ => {
- self.machine_st.p += 1;
+ match n1.cmp(&n2) {
+ Ordering::Greater | Ordering::Equal => {
+ self.machine_st.p += 1;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
}
- }
- &Instruction::ExecuteIsNonVar(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ &Instruction::DefaultExecuteNumberGreaterThanOrEqual(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- match d.get_tag() {
- HeapCellValueTag::AttrVar |
- HeapCellValueTag::Var |
- HeapCellValueTag::StackVar => {
- self.machine_st.backtrack();
- }
- _ => {
- self.machine_st.p = self.machine_st.cp;
+ match n1.cmp(&n2) {
+ Ordering::Greater | Ordering::Equal => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
}
- }
- &Instruction::CallIsVar(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ &Instruction::DefaultCallNumberGreaterThan(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- match d.get_tag() {
- HeapCellValueTag::AttrVar |
- HeapCellValueTag::Var |
- HeapCellValueTag::StackVar => {
- self.machine_st.p += 1;
+ match n1.cmp(&n2) {
+ Ordering::Greater => {
+ self.machine_st.p += 1;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
- _ => {
- self.machine_st.backtrack();
+ }
+ &Instruction::DefaultExecuteNumberGreaterThan(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+
+ match n1.cmp(&n2) {
+ Ordering::Greater => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
}
- }
- &Instruction::ExecuteIsVar(r) => {
- let d = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ &Instruction::DefaultCallNumberLessThan(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
- match d.get_tag() {
- HeapCellValueTag::AttrVar |
- HeapCellValueTag::Var |
- HeapCellValueTag::StackVar => {
- self.machine_st.p = self.machine_st.cp;
+ match n1.cmp(&n2) {
+ Ordering::Less => {
+ self.machine_st.p += 1;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
- _ => {
- self.machine_st.backtrack();
+ }
+ &Instruction::DefaultExecuteNumberLessThan(ref at_1, ref at_2) => {
+ let n1 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_1));
+ let n2 = try_or_throw!(self.machine_st, self.machine_st.get_number(at_2));
+
+ match n1.cmp(&n2) {
+ Ordering::Less => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
}
- }
- &Instruction::CallNamed(arity, name, ref idx) => {
- let idx = idx.get();
+ //
+ &Instruction::CallIsAtom(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
- try_or_throw!(
- self.machine_st,
- self.try_call(name, arity, idx)
- );
+ read_heap_cell!(d,
+ (HeapCellValueTag::Atom, (_name, arity)) => {
+ if arity == 0 {
+ self.machine_st.p += 1;
+ } else {
+ self.machine_st.backtrack();
+ }
+ }
+ (HeapCellValueTag::Str, s) => {
+ let arity = cell_as_atom_cell!(self.machine_st.heap[s])
+ .get_arity();
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ if arity == 0 {
+ self.machine_st.p += 1;
+ } else {
+ self.machine_st.backtrack();
+ }
+ }
+ (HeapCellValueTag::Char) => {
+ self.machine_st.p += 1;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
);
}
- }
- &Instruction::ExecuteNamed(arity, name, ref idx) => {
- let idx = idx.get();
+ &Instruction::ExecuteIsAtom(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
+
+ read_heap_cell!(d,
+ (HeapCellValueTag::Atom, (_name, arity)) => {
+ if arity == 0 {
+ self.machine_st.p = self.machine_st.cp;
+ } else {
+ self.machine_st.backtrack();
+ }
+ }
+ (HeapCellValueTag::Str, s) => {
+ let arity = cell_as_atom_cell!(self.machine_st.heap[s])
+ .get_arity();
+
+ if arity == 0 {
+ self.machine_st.p = self.machine_st.cp;
+ } else {
+ self.machine_st.backtrack();
+ }
+ }
+ (HeapCellValueTag::Char) => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ );
+ }
+ &Instruction::CallIsAtomic(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
- try_or_throw!(
- self.machine_st,
- self.try_execute(name, arity, idx)
- );
+ read_heap_cell!(d,
+ (HeapCellValueTag::Char | HeapCellValueTag::Fixnum | HeapCellValueTag::F64 |
+ HeapCellValueTag::Cons) => {
+ self.machine_st.p += 1;
+ }
+ (HeapCellValueTag::Atom, (_name, arity)) => {
+ if arity == 0 {
+ self.machine_st.p += 1;
+ } else {
+ self.machine_st.backtrack();
+ }
+ }
+ (HeapCellValueTag::Str, s) => {
+ let arity = cell_as_atom_cell!(self.machine_st.heap[s])
+ .get_arity();
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ if arity == 0 {
+ self.machine_st.p += 1;
+ } else {
+ self.machine_st.backtrack();
+ }
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
);
}
- }
- &Instruction::DefaultCallNamed(arity, name, ref idx) => {
- let idx = idx.get();
-
- try_or_throw!(
- self.machine_st,
- self.try_call(name, arity, idx)
- );
+ &Instruction::ExecuteIsAtomic(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
- if self.machine_st.fail {
- self.machine_st.backtrack();
+ read_heap_cell!(d,
+ (HeapCellValueTag::Char | HeapCellValueTag::Fixnum | HeapCellValueTag::F64 |
+ HeapCellValueTag::Cons) => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ (HeapCellValueTag::Atom, (_name, arity)) => {
+ if arity == 0 {
+ self.machine_st.p = self.machine_st.cp;
+ } else {
+ self.machine_st.backtrack();
+ }
+ }
+ (HeapCellValueTag::Str, s) => {
+ let arity = cell_as_atom_cell!(self.machine_st.heap[s])
+ .get_arity();
+
+ if arity == 0 {
+ self.machine_st.p = self.machine_st.cp;
+ } else {
+ self.machine_st.backtrack();
+ }
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ );
}
- }
- &Instruction::DefaultExecuteNamed(arity, name, ref idx) => {
- let idx = idx.get();
+ &Instruction::CallIsCompound(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
- try_or_throw!(
- self.machine_st,
- self.try_execute(name, arity, idx)
- );
+ read_heap_cell!(d,
+ (HeapCellValueTag::Lis |
+ HeapCellValueTag::PStrLoc |
+ HeapCellValueTag::CStr) => {
+ self.machine_st.p += 1;
+ }
+ (HeapCellValueTag::Str, s) => {
+ let arity = cell_as_atom_cell!(self.machine_st.heap[s])
+ .get_arity();
- if self.machine_st.fail {
- self.machine_st.backtrack();
+ if arity > 0 {
+ self.machine_st.p += 1;
+ } else {
+ self.machine_st.backtrack();
+ }
+ }
+ (HeapCellValueTag::Atom, (_name, arity)) => {
+ if arity > 0 {
+ self.machine_st.p += 1;
+ } else {
+ self.machine_st.backtrack();
+ }
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ );
}
- }
- &Instruction::Deallocate => {
- self.machine_st.deallocate()
- }
- &Instruction::JmpByCall(offset) => {
- self.machine_st.p += offset;
- }
- &Instruction::RevJmpBy(offset) => {
- self.machine_st.p -= offset;
- }
- &Instruction::Proceed => {
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::GetConstant(_, c, reg) => {
- let value = self.machine_st.deref(self.machine_st[reg]);
- self.machine_st.write_literal_to_var(value, c);
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::GetList(_, reg) => {
- let deref_v = self.machine_st.deref(self.machine_st[reg]);
- let store_v = self.machine_st.store(deref_v);
+ &Instruction::ExecuteIsCompound(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
- read_heap_cell!(store_v,
- (HeapCellValueTag::PStrLoc, h) => {
- let (h, n) = pstr_loc_and_offset(&self.machine_st.heap, h);
+ read_heap_cell!(d,
+ (HeapCellValueTag::Lis |
+ HeapCellValueTag::PStrLoc |
+ HeapCellValueTag::CStr) => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ (HeapCellValueTag::Str, s) => {
+ let arity = cell_as_atom_cell!(self.machine_st.heap[s])
+ .get_arity();
+
+ if arity > 0 {
+ self.machine_st.p = self.machine_st.cp;
+ } else {
+ self.machine_st.backtrack();
+ }
+ }
+ (HeapCellValueTag::Atom, (_name, arity)) => {
+ if arity > 0 {
+ self.machine_st.p = self.machine_st.cp;
+ } else {
+ self.machine_st.backtrack();
+ }
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ );
+ }
+ &Instruction::CallIsInteger(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
- self.machine_st.s = HeapPtr::PStrChar(h, n.get_num() as usize);
- self.machine_st.s_offset = 0;
- self.machine_st.mode = MachineMode::Read;
+ match Number::try_from(d) {
+ Ok(Number::Fixnum(_) | Number::Integer(_)) => {
+ self.machine_st.p += 1;
+ }
+ Ok(Number::Rational(n)) => {
+ if n.denominator().is_one() {
+ self.machine_st.p += 1;
+ } else {
+ self.machine_st.backtrack();
+ }
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
- (HeapCellValueTag::CStr) => {
- let h = self.machine_st.heap.len();
- self.machine_st.heap.push(store_v);
+ }
+ &Instruction::ExecuteIsInteger(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
- self.machine_st.s = HeapPtr::PStrChar(h, 0);
- self.machine_st.s_offset = 0;
- self.machine_st.mode = MachineMode::Read;
+ match Number::try_from(d) {
+ Ok(Number::Fixnum(_) | Number::Integer(_)) => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ Ok(Number::Rational(n)) => {
+ if n.denominator().is_one() {
+ self.machine_st.p = self.machine_st.cp;
+ } else {
+ self.machine_st.backtrack();
+ }
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
- (HeapCellValueTag::Str, s) => {
- let (name, arity) = cell_as_atom_cell!(self.machine_st.heap[s])
- .get_name_and_arity();
+ }
+ &Instruction::CallIsNumber(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
- if name == atom!(".") && arity == 2 {
- self.machine_st.s = HeapPtr::HeapCell(s+1);
- self.machine_st.s_offset = 0;
- self.machine_st.mode = MachineMode::Read;
- } else {
+ match Number::try_from(d) {
+ Ok(_) => {
+ self.machine_st.p += 1;
+ }
+ _ => {
self.machine_st.backtrack();
- continue;
}
}
- (HeapCellValueTag::Lis, l) => {
- self.machine_st.s = HeapPtr::HeapCell(l);
- self.machine_st.s_offset = 0;
- self.machine_st.mode = MachineMode::Read;
+ }
+ &Instruction::ExecuteIsNumber(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
+
+ match Number::try_from(d) {
+ Ok(_) => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
- (HeapCellValueTag::AttrVar | HeapCellValueTag::Var | HeapCellValueTag::StackVar) => {
- let h = self.machine_st.heap.len();
+ }
+ &Instruction::CallIsRational(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
+
+ read_heap_cell!(d,
+ (HeapCellValueTag::Cons, ptr) => {
+ match_untyped_arena_ptr!(ptr,
+ (ArenaHeaderTag::Rational | ArenaHeaderTag::Integer, _r) => {
+ self.machine_st.p += 1;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ );
+ }
+ (HeapCellValueTag::Fixnum) => {
+ self.machine_st.p += 1;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ );
+ }
+ &Instruction::ExecuteIsRational(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
+
+ read_heap_cell!(d,
+ (HeapCellValueTag::Cons, ptr) => {
+ match_untyped_arena_ptr!(ptr,
+ (ArenaHeaderTag::Rational | ArenaHeaderTag::Integer, _r) => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ );
+ }
+ (HeapCellValueTag::Fixnum) => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ );
+ }
+ &Instruction::CallIsFloat(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
- self.machine_st.heap.push(list_loc_as_cell!(h+1));
- self.machine_st.bind(store_v.as_var().unwrap(), heap_loc_as_cell!(h));
+ match Number::try_from(d) {
+ Ok(Number::Float(_)) => {
+ self.machine_st.p += 1;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
+ }
+ }
+ &Instruction::ExecuteIsFloat(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
- self.machine_st.mode = MachineMode::Write;
+ match Number::try_from(d) {
+ Ok(Number::Float(_)) => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
- _ => {
- self.machine_st.backtrack();
- continue;
+ }
+ &Instruction::CallIsNonVar(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
+
+ match d.get_tag() {
+ HeapCellValueTag::AttrVar
+ | HeapCellValueTag::Var
+ | HeapCellValueTag::StackVar => {
+ self.machine_st.backtrack();
+ }
+ _ => {
+ self.machine_st.p += 1;
+ }
}
- );
+ }
+ &Instruction::ExecuteIsNonVar(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
- self.machine_st.p += 1;
- }
- &Instruction::GetPartialString(_, string, reg, has_tail) => {
- let deref_v = self.machine_st.deref(self.machine_st[reg]);
- let store_v = self.machine_st.store(deref_v);
-
- read_heap_cell!(store_v,
- (HeapCellValueTag::Str |
- HeapCellValueTag::Lis |
- HeapCellValueTag::PStrLoc |
- HeapCellValueTag::CStr) => {
- self.machine_st.match_partial_string(store_v, string, has_tail);
- }
- (HeapCellValueTag::AttrVar |
- HeapCellValueTag::StackVar |
- HeapCellValueTag::Var) => {
- let target_cell = self.machine_st.push_str_to_heap(
- string.as_str(),
- has_tail,
- );
+ match d.get_tag() {
+ HeapCellValueTag::AttrVar
+ | HeapCellValueTag::Var
+ | HeapCellValueTag::StackVar => {
+ self.machine_st.backtrack();
+ }
+ _ => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ }
+ }
+ &Instruction::CallIsVar(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
- self.machine_st.bind(
- store_v.as_var().unwrap(),
- target_cell,
- );
+ match d.get_tag() {
+ HeapCellValueTag::AttrVar
+ | HeapCellValueTag::Var
+ | HeapCellValueTag::StackVar => {
+ self.machine_st.p += 1;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
- _ => {
- self.machine_st.backtrack();
- continue;
+ }
+ &Instruction::ExecuteIsVar(r) => {
+ let d = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
+
+ match d.get_tag() {
+ HeapCellValueTag::AttrVar
+ | HeapCellValueTag::Var
+ | HeapCellValueTag::StackVar => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ _ => {
+ self.machine_st.backtrack();
+ }
}
- );
+ }
+ &Instruction::CallNamed(arity, name, ref idx) => {
+ let idx = idx.get();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::GetStructure(_lvl, name, arity, reg) => {
- let deref_v = self.machine_st.deref(self.machine_st[reg]);
- let store_v = self.machine_st.store(deref_v);
-
- read_heap_cell!(store_v,
- (HeapCellValueTag::Str, a) => {
- read_heap_cell!(self.machine_st.heap[a],
- (HeapCellValueTag::Atom, (result_name, result_arity)) => {
- if arity == result_arity && name == result_name {
- self.machine_st.s = HeapPtr::HeapCell(a + 1);
- self.machine_st.s_offset = 0;
- self.machine_st.mode = MachineMode::Read;
- } else {
- self.machine_st.backtrack();
- continue;
- }
- }
- _ => {
- unreachable!();
- }
+ try_or_throw!(self.machine_st, self.try_call(name, arity, idx));
+
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
);
}
- (HeapCellValueTag::AttrVar | HeapCellValueTag::Var | HeapCellValueTag::StackVar) => {
- let h = self.machine_st.heap.len();
+ }
+ &Instruction::ExecuteNamed(arity, name, ref idx) => {
+ let idx = idx.get();
- self.machine_st.heap.push(str_loc_as_cell!(h+1));
- self.machine_st.heap.push(atom_as_cell!(name, arity));
+ try_or_throw!(self.machine_st, self.try_execute(name, arity, idx));
- self.machine_st.bind(store_v.as_var().unwrap(), heap_loc_as_cell!(h));
- self.machine_st.mode = MachineMode::Write;
- }
- _ => {
+ if self.machine_st.fail {
self.machine_st.backtrack();
- continue;
+ } else {
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
+ );
}
- );
-
- self.machine_st.p += 1;
- }
- &Instruction::GetVariable(norm, arg) => {
- self.machine_st[norm] = self.machine_st.registers[arg];
- self.machine_st.p += 1;
- }
- &Instruction::GetValue(norm, arg) => {
- let norm_addr = self.machine_st[norm];
- let reg_addr = self.machine_st.registers[arg];
+ }
+ &Instruction::DefaultCallNamed(arity, name, ref idx) => {
+ let idx = idx.get();
- unify_fn!(&mut self.machine_st, norm_addr, reg_addr);
+ try_or_throw!(self.machine_st, self.try_call(name, arity, idx));
- if self.machine_st.fail {
- self.machine_st.backtrack();
- continue;
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ }
}
+ &Instruction::DefaultExecuteNamed(arity, name, ref idx) => {
+ let idx = idx.get();
- self.machine_st.p += 1;
- }
- &Instruction::UnifyConstant(v) => {
- match self.machine_st.mode {
- MachineMode::Read => {
- let addr = self.machine_st.read_s();
-
- self.machine_st.write_literal_to_var(addr, v);
+ try_or_throw!(self.machine_st, self.try_execute(name, arity, idx));
- if self.machine_st.fail {
- self.machine_st.backtrack();
- continue;
- } else {
- self.machine_st.s_offset += 1;
- }
- }
- MachineMode::Write => {
- self.machine_st.heap.push(v);
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
}
}
+ &Instruction::Deallocate => self.machine_st.deallocate(),
+ &Instruction::JmpByCall(offset) => {
+ self.machine_st.p += offset;
+ }
+ &Instruction::RevJmpBy(offset) => {
+ self.machine_st.p -= offset;
+ }
+ &Instruction::Proceed => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::GetConstant(_, c, reg) => {
+ let value = self.machine_st.deref(self.machine_st[reg]);
+ self.machine_st.write_literal_to_var(value, c);
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::GetList(_, reg) => {
+ let deref_v = self.machine_st.deref(self.machine_st[reg]);
+ let store_v = self.machine_st.store(deref_v);
- self.machine_st.p += 1;
- }
- &Instruction::UnifyLocalValue(reg) => {
- match self.machine_st.mode {
- MachineMode::Read => {
- let reg_addr = self.machine_st[reg];
- let value = self.machine_st.read_s();
+ read_heap_cell!(store_v,
+ (HeapCellValueTag::PStrLoc, h) => {
+ let (h, n) = pstr_loc_and_offset(&self.machine_st.heap, h);
+
+ self.machine_st.s = HeapPtr::PStrChar(h, n.get_num() as usize);
+ self.machine_st.s_offset = 0;
+ self.machine_st.mode = MachineMode::Read;
+ }
+ (HeapCellValueTag::CStr) => {
+ let h = self.machine_st.heap.len();
+ self.machine_st.heap.push(store_v);
+
+ self.machine_st.s = HeapPtr::PStrChar(h, 0);
+ self.machine_st.s_offset = 0;
+ self.machine_st.mode = MachineMode::Read;
+ }
+ (HeapCellValueTag::Str, s) => {
+ let (name, arity) = cell_as_atom_cell!(self.machine_st.heap[s])
+ .get_name_and_arity();
+
+ if name == atom!(".") && arity == 2 {
+ self.machine_st.s = HeapPtr::HeapCell(s+1);
+ self.machine_st.s_offset = 0;
+ self.machine_st.mode = MachineMode::Read;
+ } else {
+ self.machine_st.backtrack();
+ continue;
+ }
+ }
+ (HeapCellValueTag::Lis, l) => {
+ self.machine_st.s = HeapPtr::HeapCell(l);
+ self.machine_st.s_offset = 0;
+ self.machine_st.mode = MachineMode::Read;
+ }
+ (HeapCellValueTag::AttrVar | HeapCellValueTag::Var | HeapCellValueTag::StackVar) => {
+ let h = self.machine_st.heap.len();
- unify_fn!(&mut self.machine_st, reg_addr, value);
+ self.machine_st.heap.push(list_loc_as_cell!(h+1));
+ self.machine_st.bind(store_v.as_var().unwrap(), heap_loc_as_cell!(h));
- if self.machine_st.fail {
+ self.machine_st.mode = MachineMode::Write;
+ }
+ _ => {
self.machine_st.backtrack();
continue;
- } else {
- self.machine_st.s_offset += 1;
}
- }
- MachineMode::Write => {
- let value = self.machine_st.store(self.machine_st.deref(self.machine_st[reg]));
- let h = self.machine_st.heap.len();
-
- read_heap_cell!(value,
- (HeapCellValueTag::Var | HeapCellValueTag::AttrVar, hc) => {
- let value = self.machine_st.heap[hc];
+ );
- self.machine_st.heap.push(value);
- self.machine_st.s_offset += 1;
- }
- _ => {
- self.machine_st.heap.push(heap_loc_as_cell!(h));
- (self.machine_st.bind_fn)(
- &mut self.machine_st,
- Ref::heap_cell(h),
- value,
- );
- }
- );
- }
+ self.machine_st.p += 1;
}
+ &Instruction::GetPartialString(_, string, reg, has_tail) => {
+ let deref_v = self.machine_st.deref(self.machine_st[reg]);
+ let store_v = self.machine_st.store(deref_v);
- self.machine_st.p += 1;
- }
- &Instruction::UnifyVariable(reg) => {
- match self.machine_st.mode {
- MachineMode::Read => {
- self.machine_st[reg] = self.machine_st.read_s();
- self.machine_st.s_offset += 1;
- }
- MachineMode::Write => {
- let h = self.machine_st.heap.len();
+ read_heap_cell!(store_v,
+ (HeapCellValueTag::Str |
+ HeapCellValueTag::Lis |
+ HeapCellValueTag::PStrLoc |
+ HeapCellValueTag::CStr) => {
+ self.machine_st.match_partial_string(store_v, string, has_tail);
+ }
+ (HeapCellValueTag::AttrVar |
+ HeapCellValueTag::StackVar |
+ HeapCellValueTag::Var) => {
+ let target_cell = self.machine_st.push_str_to_heap(
+ string.as_str(),
+ has_tail,
+ );
+
+ self.machine_st.bind(
+ store_v.as_var().unwrap(),
+ target_cell,
+ );
+ }
+ _ => {
+ self.machine_st.backtrack();
+ continue;
+ }
+ );
- self.machine_st.heap.push(heap_loc_as_cell!(h));
- self.machine_st[reg] = heap_loc_as_cell!(h);
- }
+ step_or_fail!(self, self.machine_st.p += 1);
}
+ &Instruction::GetStructure(_lvl, name, arity, reg) => {
+ let deref_v = self.machine_st.deref(self.machine_st[reg]);
+ let store_v = self.machine_st.store(deref_v);
+
+ read_heap_cell!(store_v,
+ (HeapCellValueTag::Str, a) => {
+ read_heap_cell!(self.machine_st.heap[a],
+ (HeapCellValueTag::Atom, (result_name, result_arity)) => {
+ if arity == result_arity && name == result_name {
+ self.machine_st.s = HeapPtr::HeapCell(a + 1);
+ self.machine_st.s_offset = 0;
+ self.machine_st.mode = MachineMode::Read;
+ } else {
+ self.machine_st.backtrack();
+ continue;
+ }
+ }
+ _ => {
+ unreachable!();
+ }
+ );
+ }
+ (HeapCellValueTag::AttrVar | HeapCellValueTag::Var | HeapCellValueTag::StackVar) => {
+ let h = self.machine_st.heap.len();
- self.machine_st.p += 1;
- }
- &Instruction::UnifyValue(reg) => {
- match self.machine_st.mode {
- MachineMode::Read => {
- let reg_addr = self.machine_st[reg];
- let value = self.machine_st.read_s();
-
- unify_fn!(&mut self.machine_st, reg_addr, value);
+ self.machine_st.heap.push(str_loc_as_cell!(h+1));
+ self.machine_st.heap.push(atom_as_cell!(name, arity));
- if self.machine_st.fail {
+ self.machine_st.bind(store_v.as_var().unwrap(), heap_loc_as_cell!(h));
+ self.machine_st.mode = MachineMode::Write;
+ }
+ _ => {
self.machine_st.backtrack();
continue;
- } else {
- self.machine_st.s_offset += 1;
}
- }
- MachineMode::Write => {
- let h = self.machine_st.heap.len();
- self.machine_st.heap.push(heap_loc_as_cell!(h));
-
- let addr = self.machine_st.store(self.machine_st[reg]);
- (self.machine_st.bind_fn)(&mut self.machine_st, Ref::heap_cell(h), addr);
+ );
- // the former code of this match arm was:
+ self.machine_st.p += 1;
+ }
+ &Instruction::GetVariable(norm, arg) => {
+ self.machine_st[norm] = self.machine_st.registers[arg];
+ self.machine_st.p += 1;
+ }
+ &Instruction::GetValue(norm, arg) => {
+ let norm_addr = self.machine_st[norm];
+ let reg_addr = self.machine_st.registers[arg];
- // let addr = self.machine_st.store(self.machine_st[reg]);
- // self.machine_st.heap.push(HeapCellValue::Addr(addr));
+ unify_fn!(&mut self.machine_st, norm_addr, reg_addr);
- // the old code didn't perform the occurs
- // check when enabled and so it was changed to
- // the above, which is only slightly less
- // efficient when the occurs_check is disabled.
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ continue;
}
+
+ self.machine_st.p += 1;
}
+ &Instruction::UnifyConstant(v) => {
+ match self.machine_st.mode {
+ MachineMode::Read => {
+ let addr = self.machine_st.read_s();
- self.machine_st.p += 1;
- }
- &Instruction::UnifyVoid(n) => {
- match self.machine_st.mode {
- MachineMode::Read => {
- self.machine_st.s_offset += n;
- }
- MachineMode::Write => {
- let h = self.machine_st.heap.len();
+ self.machine_st.write_literal_to_var(addr, v);
- for i in h..h + n {
- self.machine_st.heap.push(heap_loc_as_cell!(i));
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ continue;
+ } else {
+ self.machine_st.s_offset += 1;
+ }
+ }
+ MachineMode::Write => {
+ self.machine_st.heap.push(v);
}
}
+
+ self.machine_st.p += 1;
}
+ &Instruction::UnifyLocalValue(reg) => {
+ match self.machine_st.mode {
+ MachineMode::Read => {
+ let reg_addr = self.machine_st[reg];
+ let value = self.machine_st.read_s();
- self.machine_st.p += 1;
- }
- &Instruction::IndexingCode(ref indexing_lines) => {
- match &indexing_lines[self.machine_st.oip as usize] {
- IndexingLine::Indexing(_) => {
- self.execute_switch_on_term();
+ unify_fn!(&mut self.machine_st, reg_addr, value);
- if self.machine_st.fail {
- self.machine_st.backtrack();
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ continue;
+ } else {
+ self.machine_st.s_offset += 1;
+ }
+ }
+ MachineMode::Write => {
+ let value = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[reg]));
+ let h = self.machine_st.heap.len();
+
+ read_heap_cell!(value,
+ (HeapCellValueTag::Var | HeapCellValueTag::AttrVar, hc) => {
+ let value = self.machine_st.heap[hc];
+
+ self.machine_st.heap.push(value);
+ self.machine_st.s_offset += 1;
+ }
+ _ => {
+ self.machine_st.heap.push(heap_loc_as_cell!(h));
+ (self.machine_st.bind_fn)(
+ &mut self.machine_st,
+ Ref::heap_cell(h),
+ value,
+ );
+ }
+ );
}
}
- IndexingLine::IndexedChoice(ref indexed_choice) => {
- match &indexed_choice[self.machine_st.iip as usize] {
- &IndexedChoiceInstruction::Try(offset) => {
- self.indexed_try(offset);
- }
- &IndexedChoiceInstruction::Retry(l) => {
- self.retry(l);
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
- }
- &IndexedChoiceInstruction::DefaultRetry(l) => {
- self.retry(l);
- }
- &IndexedChoiceInstruction::Trust(l) => {
- self.trust(l);
+ self.machine_st.p += 1;
+ }
+ &Instruction::UnifyVariable(reg) => {
+ match self.machine_st.mode {
+ MachineMode::Read => {
+ self.machine_st[reg] = self.machine_st.read_s();
+ self.machine_st.s_offset += 1;
+ }
+ MachineMode::Write => {
+ let h = self.machine_st.heap.len();
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
- }
- &IndexedChoiceInstruction::DefaultTrust(l) => {
- self.trust(l);
- }
+ self.machine_st.heap.push(heap_loc_as_cell!(h));
+ self.machine_st[reg] = heap_loc_as_cell!(h);
}
}
- IndexingLine::DynamicIndexedChoice(_) => {
- let p = self.machine_st.p;
- match self.find_living_dynamic(self.machine_st.oip, self.machine_st.iip) {
- Some((offset, oi, ii, is_next_clause)) => {
- self.machine_st.p = p;
- self.machine_st.oip = oi;
- self.machine_st.iip = ii;
+ self.machine_st.p += 1;
+ }
+ &Instruction::UnifyValue(reg) => {
+ match self.machine_st.mode {
+ MachineMode::Read => {
+ let reg_addr = self.machine_st[reg];
+ let value = self.machine_st.read_s();
- match self.machine_st.dynamic_mode {
- FirstOrNext::First if !is_next_clause => {
- self.machine_st.p = p + offset;
- }
- FirstOrNext::First => {
- // there's a leading DynamicElse that sets self.machine_st.cc.
- // self.machine_st.cc = self.machine_st.global_clock;
-
- // see that there is a following dynamic_else
- // clause so we avoid generating a choice
- // point in case there isn't.
- match self.find_living_dynamic(oi, ii + 1) {
- Some(_) => {
- self.machine_st.registers[self.machine_st.num_of_args + 1] =
- fixnum_as_cell!(Fixnum::build_with(self.machine_st.cc as i64));
+ unify_fn!(&mut self.machine_st, reg_addr, value);
- self.machine_st.num_of_args += 1;
- self.indexed_try(offset);
- self.machine_st.num_of_args -= 1;
- }
- None => {
- self.machine_st.p = p + offset;
- self.machine_st.oip = 0;
- self.machine_st.iip = 0;
- }
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ continue;
+ } else {
+ self.machine_st.s_offset += 1;
+ }
+ }
+ MachineMode::Write => {
+ let h = self.machine_st.heap.len();
+ self.machine_st.heap.push(heap_loc_as_cell!(h));
+
+ let addr = self.machine_st.store(self.machine_st[reg]);
+ (self.machine_st.bind_fn)(
+ &mut self.machine_st,
+ Ref::heap_cell(h),
+ addr,
+ );
+
+ // the former code of this match arm was:
+
+ // let addr = self.machine_st.store(self.machine_st[reg]);
+ // self.machine_st.heap.push(HeapCellValue::Addr(addr));
+
+ // the old code didn't perform the occurs
+ // check when enabled and so it was changed to
+ // the above, which is only slightly less
+ // efficient when the occurs_check is disabled.
+ }
+ }
+
+ self.machine_st.p += 1;
+ }
+ &Instruction::UnifyVoid(n) => {
+ match self.machine_st.mode {
+ MachineMode::Read => {
+ self.machine_st.s_offset += n;
+ }
+ MachineMode::Write => {
+ let h = self.machine_st.heap.len();
+
+ for i in h..h + n {
+ self.machine_st.heap.push(heap_loc_as_cell!(i));
+ }
+ }
+ }
+
+ self.machine_st.p += 1;
+ }
+ &Instruction::IndexingCode(ref indexing_lines) => {
+ match &indexing_lines[self.machine_st.oip as usize] {
+ IndexingLine::Indexing(_) => {
+ self.execute_switch_on_term();
+
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ }
+ }
+ IndexingLine::IndexedChoice(ref indexed_choice) => {
+ match &indexed_choice[self.machine_st.iip as usize] {
+ &IndexedChoiceInstruction::Try(offset) => {
+ self.indexed_try(offset);
+ }
+ &IndexedChoiceInstruction::Retry(l) => {
+ self.retry(l);
+
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(
+ &mut self.machine_st
+ )
+ );
+ }
+ &IndexedChoiceInstruction::DefaultRetry(l) => {
+ self.retry(l);
+ }
+ &IndexedChoiceInstruction::Trust(l) => {
+ self.trust(l);
+
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(
+ &mut self.machine_st
+ )
+ );
+ }
+ &IndexedChoiceInstruction::DefaultTrust(l) => {
+ self.trust(l);
+ }
+ }
+ }
+ IndexingLine::DynamicIndexedChoice(_) => {
+ let p = self.machine_st.p;
+
+ match self
+ .find_living_dynamic(self.machine_st.oip, self.machine_st.iip)
+ {
+ Some((offset, oi, ii, is_next_clause)) => {
+ self.machine_st.p = p;
+ self.machine_st.oip = oi;
+ self.machine_st.iip = ii;
+
+ match self.machine_st.dynamic_mode {
+ FirstOrNext::First if !is_next_clause => {
+ self.machine_st.p = p + offset;
}
- }
- FirstOrNext::Next => {
- let b = self.machine_st.b;
- let n = self.machine_st
- .stack
- .index_or_frame(b)
- .prelude
- .num_cells;
-
- self.machine_st.cc = cell_as_fixnum!(
- self.machine_st.stack[stack_loc!(OrFrame, b, n-1)]
- ).get_num() as usize;
-
- if is_next_clause {
- match self.find_living_dynamic(self.machine_st.oip, self.machine_st.iip + 1) {
- // if we're executing the last instruction
- // of the internal block pointed to by
- // self.machine_st.iip, we want trust, not retry.
- // this is true iff ii + 1 < len.
+ FirstOrNext::First => {
+ // there's a leading DynamicElse that sets self.machine_st.cc.
+ // self.machine_st.cc = self.machine_st.global_clock;
+
+ // see that there is a following dynamic_else
+ // clause so we avoid generating a choice
+ // point in case there isn't.
+ match self.find_living_dynamic(oi, ii + 1) {
Some(_) => {
- self.retry(offset);
-
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ self.machine_st.registers
+ [self.machine_st.num_of_args + 1] =
+ fixnum_as_cell!(Fixnum::build_with(
+ self.machine_st.cc as i64
+ ));
+
+ self.machine_st.num_of_args += 1;
+ self.indexed_try(offset);
+ self.machine_st.num_of_args -= 1;
}
- _ => {
- self.trust(offset);
-
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ None => {
+ self.machine_st.p = p + offset;
+ self.machine_st.oip = 0;
+ self.machine_st.iip = 0;
}
}
- } else {
- self.trust(offset);
-
- try_or_throw!(
- self.machine_st,
- (self.machine_st.increment_call_count_fn)(&mut self.machine_st)
- );
+ }
+ FirstOrNext::Next => {
+ let b = self.machine_st.b;
+ let n = self
+ .machine_st
+ .stack
+ .index_or_frame(b)
+ .prelude
+ .num_cells;
+
+ self.machine_st.cc = cell_as_fixnum!(
+ self.machine_st.stack
+ [stack_loc!(OrFrame, b, n - 1)]
+ )
+ .get_num()
+ as usize;
+
+ if is_next_clause {
+ match self.find_living_dynamic(
+ self.machine_st.oip,
+ self.machine_st.iip + 1,
+ ) {
+ // if we're executing the last instruction
+ // of the internal block pointed to by
+ // self.machine_st.iip, we want trust, not retry.
+ // this is true iff ii + 1 < len.
+ Some(_) => {
+ self.retry(offset);
+
+ try_or_throw!(
+ self.machine_st,
+ (self
+ .machine_st
+ .increment_call_count_fn)(
+ &mut self.machine_st
+ )
+ );
+ }
+ _ => {
+ self.trust(offset);
+
+ try_or_throw!(
+ self.machine_st,
+ (self
+ .machine_st
+ .increment_call_count_fn)(
+ &mut self.machine_st
+ )
+ );
+ }
+ }
+ } else {
+ self.trust(offset);
+
+ try_or_throw!(
+ self.machine_st,
+ (self.machine_st.increment_call_count_fn)(
+ &mut self.machine_st
+ )
+ );
+ }
}
}
}
+ None => {
+ self.machine_st.fail = true;
+ }
}
- None => {
- self.machine_st.fail = true;
- }
- }
- self.machine_st.dynamic_mode = FirstOrNext::Next;
+ self.machine_st.dynamic_mode = FirstOrNext::Next;
- if self.machine_st.fail {
- self.machine_st.backtrack();
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ }
}
}
}
- }
- &Instruction::PutConstant(_, c, reg) => {
- self.machine_st[reg] = c;
- self.machine_st.p += 1;
- }
- &Instruction::PutList(_, reg) => {
- self.machine_st[reg] = list_loc_as_cell!(self.machine_st.heap.len());
- self.machine_st.p += 1;
- }
- &Instruction::PutPartialString(_, string, reg, has_tail) => {
- let pstr_addr = if has_tail {
- if string != atom!("") {
- let h = self.machine_st.heap.len();
- self.machine_st.heap.push(string_as_pstr_cell!(string));
+ &Instruction::PutConstant(_, c, reg) => {
+ self.machine_st[reg] = c;
+ self.machine_st.p += 1;
+ }
+ &Instruction::PutList(_, reg) => {
+ self.machine_st[reg] = list_loc_as_cell!(self.machine_st.heap.len());
+ self.machine_st.p += 1;
+ }
+ &Instruction::PutPartialString(_, string, reg, has_tail) => {
+ let pstr_addr = if has_tail {
+ if string != atom!("") {
+ let h = self.machine_st.heap.len();
+ self.machine_st.heap.push(string_as_pstr_cell!(string));
- // the tail will be pushed by the next
- // instruction, so don't push one here.
+ // the tail will be pushed by the next
+ // instruction, so don't push one here.
- pstr_loc_as_cell!(h)
+ pstr_loc_as_cell!(h)
+ } else {
+ empty_list_as_cell!()
+ }
} else {
- empty_list_as_cell!()
- }
- } else {
- string_as_cstr_cell!(string)
- };
-
- self.machine_st[reg] = pstr_addr;
- self.machine_st.p += 1;
- }
- &Instruction::PutStructure(name, arity, reg) => {
- let h = self.machine_st.heap.len();
+ string_as_cstr_cell!(string)
+ };
- self.machine_st.heap.push(atom_as_cell!(name, arity));
- self.machine_st[reg] = str_loc_as_cell!(h);
-
- self.machine_st.p += 1;
- }
- &Instruction::PutUnsafeValue(perm_slot, arg) => {
- let s = stack_loc!(AndFrame, self.machine_st.e, perm_slot);
- let addr = self.machine_st.store(self.machine_st.deref(stack_loc_as_cell!(s)));
-
- if addr.is_protected(self.machine_st.e) {
- self.machine_st.registers[arg] = addr;
- } else {
+ self.machine_st[reg] = pstr_addr;
+ self.machine_st.p += 1;
+ }
+ &Instruction::PutStructure(name, arity, reg) => {
let h = self.machine_st.heap.len();
- self.machine_st.heap.push(heap_loc_as_cell!(h));
- (self.machine_st.bind_fn)(&mut self.machine_st, Ref::heap_cell(h), addr);
+ self.machine_st.heap.push(atom_as_cell!(name, arity));
+ self.machine_st[reg] = str_loc_as_cell!(h);
- self.machine_st.registers[arg] = heap_loc_as_cell!(h);
+ self.machine_st.p += 1;
}
+ &Instruction::PutUnsafeValue(perm_slot, arg) => {
+ let s = stack_loc!(AndFrame, self.machine_st.e, perm_slot);
+ let addr = self
+ .machine_st
+ .store(self.machine_st.deref(stack_loc_as_cell!(s)));
- self.machine_st.p += 1;
- }
- &Instruction::PutValue(norm, arg) => {
- self.machine_st.registers[arg] = self.machine_st[norm];
- self.machine_st.p += 1;
- }
- &Instruction::PutVariable(norm, arg) => {
- match norm {
- RegType::Perm(n) => {
- self.machine_st[norm] = stack_loc_as_cell!(AndFrame, self.machine_st.e, n);
- self.machine_st.registers[arg] = self.machine_st[norm];
- }
- RegType::Temp(_) => {
+ if addr.is_protected(self.machine_st.e) {
+ self.machine_st.registers[arg] = addr;
+ } else {
let h = self.machine_st.heap.len();
+
self.machine_st.heap.push(heap_loc_as_cell!(h));
+ (self.machine_st.bind_fn)(
+ &mut self.machine_st,
+ Ref::heap_cell(h),
+ addr,
+ );
- self.machine_st[norm] = heap_loc_as_cell!(h);
self.machine_st.registers[arg] = heap_loc_as_cell!(h);
}
- };
- self.machine_st.p += 1;
- }
- &Instruction::SetConstant(c) => {
- self.machine_st.heap.push(c);
- self.machine_st.p += 1;
- }
- &Instruction::SetLocalValue(reg) => {
- let addr = self.machine_st.deref(self.machine_st[reg]);
- let stored_v = self.machine_st.store(addr);
+ self.machine_st.p += 1;
+ }
+ &Instruction::PutValue(norm, arg) => {
+ self.machine_st.registers[arg] = self.machine_st[norm];
+ self.machine_st.p += 1;
+ }
+ &Instruction::PutVariable(norm, arg) => {
+ match norm {
+ RegType::Perm(n) => {
+ self.machine_st[norm] =
+ stack_loc_as_cell!(AndFrame, self.machine_st.e, n);
+ self.machine_st.registers[arg] = self.machine_st[norm];
+ }
+ RegType::Temp(_) => {
+ let h = self.machine_st.heap.len();
+ self.machine_st.heap.push(heap_loc_as_cell!(h));
+
+ self.machine_st[norm] = heap_loc_as_cell!(h);
+ self.machine_st.registers[arg] = heap_loc_as_cell!(h);
+ }
+ };
- if stored_v.is_stack_var() {
+ self.machine_st.p += 1;
+ }
+ &Instruction::SetConstant(c) => {
+ self.machine_st.heap.push(c);
+ self.machine_st.p += 1;
+ }
+ &Instruction::SetLocalValue(reg) => {
+ let addr = self.machine_st.deref(self.machine_st[reg]);
+ let stored_v = self.machine_st.store(addr);
+
+ if stored_v.is_stack_var() {
+ let h = self.machine_st.heap.len();
+ self.machine_st.heap.push(heap_loc_as_cell!(h));
+ (self.machine_st.bind_fn)(
+ &mut self.machine_st,
+ Ref::heap_cell(h),
+ stored_v,
+ );
+ } else {
+ self.machine_st.heap.push(stored_v);
+ }
+
+ self.machine_st.p += 1;
+ }
+ &Instruction::SetVariable(reg) => {
let h = self.machine_st.heap.len();
+
self.machine_st.heap.push(heap_loc_as_cell!(h));
- (self.machine_st.bind_fn)(&mut self.machine_st, Ref::heap_cell(h), stored_v);
- } else {
- self.machine_st.heap.push(stored_v);
- }
+ self.machine_st[reg] = heap_loc_as_cell!(h);
- self.machine_st.p += 1;
- }
- &Instruction::SetVariable(reg) => {
- let h = self.machine_st.heap.len();
+ self.machine_st.p += 1;
+ }
+ &Instruction::SetValue(reg) => {
+ let heap_val = self.machine_st.store(self.machine_st[reg]);
+ self.machine_st.heap.push(heap_val);
+ self.machine_st.p += 1;
+ }
+ &Instruction::SetVoid(n) => {
+ let h = self.machine_st.heap.len();
- self.machine_st.heap.push(heap_loc_as_cell!(h));
- self.machine_st[reg] = heap_loc_as_cell!(h);
+ for i in h..h + n {
+ self.machine_st.heap.push(heap_loc_as_cell!(i));
+ }
- self.machine_st.p += 1;
- }
- &Instruction::SetValue(reg) => {
- let heap_val = self.machine_st.store(self.machine_st[reg]);
- self.machine_st.heap.push(heap_val);
- self.machine_st.p += 1;
- }
- &Instruction::SetVoid(n) => {
- let h = self.machine_st.heap.len();
+ self.machine_st.p += 1;
+ }
+ //
+ &Instruction::CallAtomChars => {
+ self.atom_chars();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteAtomChars => {
+ self.atom_chars();
- for i in h..h + n {
- self.machine_st.heap.push(heap_loc_as_cell!(i));
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
+ self.machine_st.p = self.machine_st.cp;
+ }
}
+ &Instruction::CallAtomCodes => {
+ try_or_throw!(self.machine_st, self.atom_codes());
- self.machine_st.p += 1;
- }
- //
- &Instruction::CallAtomChars => {
- self.atom_chars();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteAtomChars => {
- self.atom_chars();
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
+ self.machine_st.p += 1;
+ }
+ }
+ &Instruction::ExecuteAtomCodes => {
+ try_or_throw!(self.machine_st, self.atom_codes());
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ } else {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ }
+ &Instruction::CallAtomLength => {
+ self.atom_length();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteAtomLength => {
+ self.atom_length();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallBindFromRegister => {
+ self.bind_from_register();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteBindFromRegister => {
+ self.bind_from_register();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallContinuation => {
+ try_or_throw!(self.machine_st, self.call_continuation(false));
+ }
+ &Instruction::ExecuteContinuation => {
+ try_or_throw!(self.machine_st, self.call_continuation(true));
+ }
+ &Instruction::CallCharCode => {
+ try_or_throw!(self.machine_st, self.char_code());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCharCode => {
+ try_or_throw!(self.machine_st, self.char_code());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCharType => {
+ self.char_type();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCharType => {
+ self.char_type();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCharsToNumber => {
+ try_or_throw!(self.machine_st, self.chars_to_number());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCharsToNumber => {
+ try_or_throw!(self.machine_st, self.chars_to_number());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCodesToNumber => {
+ try_or_throw!(self.machine_st, self.codes_to_number());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCodesToNumber => {
+ try_or_throw!(self.machine_st, self.codes_to_number());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCopyTermWithoutAttrVars => {
+ self.copy_term_without_attr_vars();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCopyTermWithoutAttrVars => {
+ self.copy_term_without_attr_vars();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCheckCutPoint => {
+ self.check_cut_point();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCheckCutPoint => {
+ self.check_cut_point();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallClose => {
+ try_or_throw!(self.machine_st, self.close());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteClose => {
+ try_or_throw!(self.machine_st, self.close());
self.machine_st.p = self.machine_st.cp;
}
- }
- &Instruction::CallAtomCodes => {
- try_or_throw!(self.machine_st, self.atom_codes());
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
+ &Instruction::CallCopyToLiftedHeap => {
+ self.copy_to_lifted_heap();
self.machine_st.p += 1;
}
- }
- &Instruction::ExecuteAtomCodes => {
- try_or_throw!(self.machine_st, self.atom_codes());
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
- } else {
+ &Instruction::ExecuteCopyToLiftedHeap => {
+ self.copy_to_lifted_heap();
self.machine_st.p = self.machine_st.cp;
}
- }
- &Instruction::CallAtomLength => {
- self.atom_length();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteAtomLength => {
- self.atom_length();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallBindFromRegister => {
- self.bind_from_register();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteBindFromRegister => {
- self.bind_from_register();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallContinuation => {
- try_or_throw!(self.machine_st, self.call_continuation(false));
- }
- &Instruction::ExecuteContinuation => {
- try_or_throw!(self.machine_st, self.call_continuation(true));
- }
- &Instruction::CallCharCode => {
- try_or_throw!(self.machine_st, self.char_code());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCharCode => {
- try_or_throw!(self.machine_st, self.char_code());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCharType => {
- self.char_type();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCharType => {
- self.char_type();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCharsToNumber => {
- try_or_throw!(self.machine_st, self.chars_to_number());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCharsToNumber => {
- try_or_throw!(self.machine_st, self.chars_to_number());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCodesToNumber => {
- try_or_throw!(self.machine_st, self.codes_to_number());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCodesToNumber => {
- try_or_throw!(self.machine_st, self.codes_to_number());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCopyTermWithoutAttrVars => {
- self.copy_term_without_attr_vars();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCopyTermWithoutAttrVars => {
- self.copy_term_without_attr_vars();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCheckCutPoint => {
- self.check_cut_point();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCheckCutPoint => {
- self.check_cut_point();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallClose => {
- try_or_throw!(self.machine_st, self.close());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteClose => {
- try_or_throw!(self.machine_st, self.close());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallCopyToLiftedHeap => {
- self.copy_to_lifted_heap();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteCopyToLiftedHeap => {
- self.copy_to_lifted_heap();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallCreatePartialString => {
- self.create_partial_string();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCreatePartialString => {
- self.create_partial_string();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCurrentHostname => {
- self.current_hostname();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCurrentHostname => {
- self.current_hostname();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCurrentInput => {
- try_or_throw!(self.machine_st, self.current_input());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCurrentInput => {
- try_or_throw!(self.machine_st, self.current_input());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCurrentOutput => {
- try_or_throw!(self.machine_st, self.current_output());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCurrentOutput => {
- try_or_throw!(self.machine_st, self.current_output());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallDirectoryFiles => {
- try_or_throw!(self.machine_st, self.directory_files());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteDirectoryFiles => {
- try_or_throw!(self.machine_st, self.directory_files());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallFileSize => {
- self.file_size();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteFileSize => {
- self.file_size();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallFileExists => {
- self.file_exists();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteFileExists => {
- self.file_exists();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallDirectoryExists => {
- self.directory_exists();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteDirectoryExists => {
- self.directory_exists();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallDirectorySeparator => {
- self.directory_separator();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteDirectorySeparator => {
- self.directory_separator();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallMakeDirectory => {
- self.make_directory();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteMakeDirectory => {
- self.make_directory();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallMakeDirectoryPath => {
- self.make_directory_path();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteMakeDirectoryPath => {
- self.make_directory_path();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallDeleteFile => {
- self.delete_file();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteDeleteFile => {
- self.delete_file();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallRenameFile => {
- self.rename_file();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteRenameFile => {
- self.rename_file();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallFileCopy => {
- self.file_copy();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteFileCopy => {
- self.file_copy();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallWorkingDirectory => {
- try_or_throw!(self.machine_st, self.working_directory());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteWorkingDirectory => {
- try_or_throw!(self.machine_st, self.working_directory());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallDeleteDirectory => {
- self.delete_directory();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteDeleteDirectory => {
- self.delete_directory();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallPathCanonical => {
- try_or_throw!(self.machine_st, self.path_canonical());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecutePathCanonical => {
- try_or_throw!(self.machine_st, self.path_canonical());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallFileTime => {
- self.file_time();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteFileTime => {
- self.file_time();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallDynamicModuleResolution(arity) => {
- let (module_name, key) = try_or_throw!(
- self.machine_st,
- self.dynamic_module_resolution(arity - 2)
- );
-
- try_or_throw!(
- self.machine_st,
- self.call_clause(module_name, key)
- );
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
+ &Instruction::CallCreatePartialString => {
+ self.create_partial_string();
+ step_or_fail!(self, self.machine_st.p += 1);
}
- }
- &Instruction::ExecuteDynamicModuleResolution(arity) => {
- let (module_name, key) = try_or_throw!(
- self.machine_st,
- self.dynamic_module_resolution(arity - 2)
- );
-
- try_or_throw!(
- self.machine_st,
- self.execute_clause(module_name, key)
- );
-
- if self.machine_st.fail {
- self.machine_st.backtrack();
+ &Instruction::ExecuteCreatePartialString => {
+ self.create_partial_string();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
}
- }
- &Instruction::CallFetchGlobalVar => {
- self.fetch_global_var();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteFetchGlobalVar => {
- self.fetch_global_var();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallFirstStream => {
- self.first_stream();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteFirstStream => {
- self.first_stream();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallFlushOutput => {
- try_or_throw!(self.machine_st, self.flush_output());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteFlushOutput => {
- try_or_throw!(self.machine_st, self.flush_output());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallGetByte => {
- try_or_throw!(self.machine_st, self.get_byte());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetByte => {
- try_or_throw!(self.machine_st, self.get_byte());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetChar => {
- try_or_throw!(self.machine_st, self.get_char());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetChar => {
- try_or_throw!(self.machine_st, self.get_char());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetNChars => {
- try_or_throw!(self.machine_st, self.get_n_chars());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetNChars => {
- try_or_throw!(self.machine_st, self.get_n_chars());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetCode => {
- try_or_throw!(self.machine_st, self.get_code());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetCode => {
- try_or_throw!(self.machine_st, self.get_code());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetSingleChar => {
- try_or_throw!(self.machine_st, self.get_single_char());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetSingleChar => {
- try_or_throw!(self.machine_st, self.get_single_char());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallTruncateIfNoLiftedHeapGrowthDiff => {
- self.truncate_if_no_lifted_heap_growth_diff();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteTruncateIfNoLiftedHeapGrowthDiff => {
- self.truncate_if_no_lifted_heap_growth_diff();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallTruncateIfNoLiftedHeapGrowth => {
- self.truncate_if_no_lifted_heap_growth();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteTruncateIfNoLiftedHeapGrowth => {
- self.truncate_if_no_lifted_heap_growth();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetAttributedVariableList => {
- self.get_attributed_variable_list();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetAttributedVariableList => {
- self.get_attributed_variable_list();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetAttrVarQueueDelimiter => {
- self.get_attr_var_queue_delimiter();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetAttrVarQueueDelimiter => {
- self.get_attr_var_queue_delimiter();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetAttrVarQueueBeyond => {
- self.get_attr_var_queue_beyond();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetAttrVarQueueBeyond => {
- self.get_attr_var_queue_beyond();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetBValue => {
- self.get_b_value();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetBValue => {
- self.get_b_value();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetContinuationChunk => {
- self.get_continuation_chunk();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetContinuationChunk => {
- self.get_continuation_chunk();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallLookupDBRef => {
- self.lookup_db_ref();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteLookupDBRef => {
- self.lookup_db_ref();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetNextOpDBRef => {
- self.get_next_op_db_ref();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetNextOpDBRef => {
- self.get_next_op_db_ref();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallIsPartialString => {
- self.is_partial_string();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteIsPartialString => {
- self.is_partial_string();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallHalt | &Instruction::ExecuteHalt => {
- return self.halt();
- }
- &Instruction::CallGetLiftedHeapFromOffset => {
- self.get_lifted_heap_from_offset();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetLiftedHeapFromOffset => {
- self.get_lifted_heap_from_offset();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetLiftedHeapFromOffsetDiff => {
- self.get_lifted_heap_from_offset_diff();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetLiftedHeapFromOffsetDiff => {
- self.get_lifted_heap_from_offset_diff();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetSCCCleaner => {
- self.get_scc_cleaner();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetSCCCleaner => {
- self.get_scc_cleaner();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallHeadIsDynamic => {
- self.head_is_dynamic();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteHeadIsDynamic => {
- self.head_is_dynamic();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallInstallSCCCleaner => {
- self.install_scc_cleaner();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteInstallSCCCleaner => {
- self.install_scc_cleaner();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallInstallInferenceCounter => {
- try_or_throw!(self.machine_st, self.install_inference_counter());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteInstallInferenceCounter => {
- try_or_throw!(self.machine_st, self.install_inference_counter());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallLiftedHeapLength => {
- self.lifted_heap_length();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteLiftedHeapLength => {
- self.lifted_heap_length();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallLoadLibraryAsStream => {
- try_or_throw!(self.machine_st, self.load_library_as_stream());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteLoadLibraryAsStream => {
- try_or_throw!(self.machine_st, self.load_library_as_stream());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallModuleExists => {
- self.module_exists();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteModuleExists => {
- self.module_exists();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallNextEP => {
- self.next_ep();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteNextEP => {
- self.next_ep();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallNoSuchPredicate => {
- try_or_throw!(self.machine_st, self.no_such_predicate());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteNoSuchPredicate => {
- try_or_throw!(self.machine_st, self.no_such_predicate());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallNumberToChars => {
- self.number_to_chars();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteNumberToChars => {
- self.number_to_chars();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallNumberToCodes => {
- self.number_to_codes();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteNumberToCodes => {
- self.number_to_codes();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallOpDeclaration => {
- try_or_throw!(self.machine_st, self.op_declaration());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteOpDeclaration => {
- try_or_throw!(self.machine_st, self.op_declaration());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallOpen => {
- try_or_throw!(self.machine_st, self.open());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteOpen => {
- try_or_throw!(self.machine_st, self.open());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallSetStreamOptions => {
- try_or_throw!(self.machine_st, self.set_stream_options());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteSetStreamOptions => {
- try_or_throw!(self.machine_st, self.set_stream_options());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallNextStream => {
- self.next_stream();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteNextStream => {
- self.next_stream();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallPartialStringTail => {
- self.partial_string_tail();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecutePartialStringTail => {
- self.partial_string_tail();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallPeekByte => {
- try_or_throw!(self.machine_st, self.peek_byte());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecutePeekByte => {
- try_or_throw!(self.machine_st, self.peek_byte());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallPeekChar => {
- try_or_throw!(self.machine_st, self.peek_char());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecutePeekChar => {
- try_or_throw!(self.machine_st, self.peek_char());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallPeekCode => {
- try_or_throw!(self.machine_st, self.peek_code());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecutePeekCode => {
- try_or_throw!(self.machine_st, self.peek_code());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallPointsToContinuationResetMarker => {
- self.points_to_continuation_reset_marker();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecutePointsToContinuationResetMarker => {
- self.points_to_continuation_reset_marker();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallPutByte => {
- try_or_throw!(self.machine_st, self.put_byte());
- self.machine_st.p += 1;
- }
- &Instruction::ExecutePutByte => {
- try_or_throw!(self.machine_st, self.put_byte());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallPutChar => {
- try_or_throw!(self.machine_st, self.put_char());
- self.machine_st.p += 1;
- }
- &Instruction::ExecutePutChar => {
- try_or_throw!(self.machine_st, self.put_char());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallPutChars => {
- try_or_throw!(self.machine_st, self.put_chars());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecutePutChars => {
- try_or_throw!(self.machine_st, self.put_chars());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallPutCode => {
- try_or_throw!(self.machine_st, self.put_code());
- self.machine_st.p += 1;
- }
- &Instruction::ExecutePutCode => {
- try_or_throw!(self.machine_st, self.put_code());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallReadQueryTerm => {
- try_or_throw!(self.machine_st, self.read_query_term());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteReadQueryTerm => {
- try_or_throw!(self.machine_st, self.read_query_term());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallReadTerm => {
- try_or_throw!(self.machine_st, self.read_term());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteReadTerm => {
- try_or_throw!(self.machine_st, self.read_term());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallRedoAttrVarBinding => {
- self.redo_attr_var_binding();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteRedoAttrVarBinding => {
- self.redo_attr_var_binding();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallRemoveCallPolicyCheck => {
- self.remove_call_policy_check();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteRemoveCallPolicyCheck => {
- self.remove_call_policy_check();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallRemoveInferenceCounter => {
- self.remove_inference_counter();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteRemoveInferenceCounter => {
- self.remove_inference_counter();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallResetContinuationMarker => {
- self.reset_continuation_marker();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteResetContinuationMarker => {
- self.reset_continuation_marker();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallRestoreCutPolicy => {
- self.restore_cut_policy();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteRestoreCutPolicy => {
- self.restore_cut_policy();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallSetCutPoint(r) => {
- if !self.set_cut_point(r) {
+ &Instruction::CallCurrentHostname => {
+ self.current_hostname();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCurrentHostname => {
+ self.current_hostname();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCurrentInput => {
+ try_or_throw!(self.machine_st, self.current_input());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCurrentInput => {
+ try_or_throw!(self.machine_st, self.current_input());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCurrentOutput => {
+ try_or_throw!(self.machine_st, self.current_output());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCurrentOutput => {
+ try_or_throw!(self.machine_st, self.current_output());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallDirectoryFiles => {
+ try_or_throw!(self.machine_st, self.directory_files());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteDirectoryFiles => {
+ try_or_throw!(self.machine_st, self.directory_files());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallFileSize => {
+ self.file_size();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteFileSize => {
+ self.file_size();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallFileExists => {
+ self.file_exists();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteFileExists => {
+ self.file_exists();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallDirectoryExists => {
+ self.directory_exists();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteDirectoryExists => {
+ self.directory_exists();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallDirectorySeparator => {
+ self.directory_separator();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteDirectorySeparator => {
+ self.directory_separator();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallMakeDirectory => {
+ self.make_directory();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteMakeDirectory => {
+ self.make_directory();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallMakeDirectoryPath => {
+ self.make_directory_path();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteMakeDirectoryPath => {
+ self.make_directory_path();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallDeleteFile => {
+ self.delete_file();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteDeleteFile => {
+ self.delete_file();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallRenameFile => {
+ self.rename_file();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteRenameFile => {
+ self.rename_file();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallFileCopy => {
+ self.file_copy();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteFileCopy => {
+ self.file_copy();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallWorkingDirectory => {
+ try_or_throw!(self.machine_st, self.working_directory());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteWorkingDirectory => {
+ try_or_throw!(self.machine_st, self.working_directory());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallDeleteDirectory => {
+ self.delete_directory();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteDeleteDirectory => {
+ self.delete_directory();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallPathCanonical => {
+ try_or_throw!(self.machine_st, self.path_canonical());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecutePathCanonical => {
+ try_or_throw!(self.machine_st, self.path_canonical());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallFileTime => {
+ self.file_time();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteFileTime => {
+ self.file_time();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallDynamicModuleResolution(arity) => {
+ let (module_name, key) = try_or_throw!(
+ self.machine_st,
+ self.dynamic_module_resolution(arity - 2)
+ );
+
+ try_or_throw!(self.machine_st, self.call_clause(module_name, key));
+
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ }
+ }
+ &Instruction::ExecuteDynamicModuleResolution(arity) => {
+ let (module_name, key) = try_or_throw!(
+ self.machine_st,
+ self.dynamic_module_resolution(arity - 2)
+ );
+
+ try_or_throw!(self.machine_st, self.execute_clause(module_name, key));
+
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ }
+ }
+ &Instruction::CallFetchGlobalVar => {
+ self.fetch_global_var();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteFetchGlobalVar => {
+ self.fetch_global_var();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallFirstStream => {
+ self.first_stream();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteFirstStream => {
+ self.first_stream();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallFlushOutput => {
+ try_or_throw!(self.machine_st, self.flush_output());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteFlushOutput => {
+ try_or_throw!(self.machine_st, self.flush_output());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallGetByte => {
+ try_or_throw!(self.machine_st, self.get_byte());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetByte => {
+ try_or_throw!(self.machine_st, self.get_byte());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetChar => {
+ try_or_throw!(self.machine_st, self.get_char());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetChar => {
+ try_or_throw!(self.machine_st, self.get_char());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetNChars => {
+ try_or_throw!(self.machine_st, self.get_n_chars());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetNChars => {
+ try_or_throw!(self.machine_st, self.get_n_chars());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetCode => {
+ try_or_throw!(self.machine_st, self.get_code());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetCode => {
+ try_or_throw!(self.machine_st, self.get_code());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetSingleChar => {
+ try_or_throw!(self.machine_st, self.get_single_char());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetSingleChar => {
+ try_or_throw!(self.machine_st, self.get_single_char());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallTruncateIfNoLiftedHeapGrowthDiff => {
+ self.truncate_if_no_lifted_heap_growth_diff();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteTruncateIfNoLiftedHeapGrowthDiff => {
+ self.truncate_if_no_lifted_heap_growth_diff();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallTruncateIfNoLiftedHeapGrowth => {
+ self.truncate_if_no_lifted_heap_growth();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteTruncateIfNoLiftedHeapGrowth => {
+ self.truncate_if_no_lifted_heap_growth();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetAttributedVariableList => {
+ self.get_attributed_variable_list();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetAttributedVariableList => {
+ self.get_attributed_variable_list();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetAttrVarQueueDelimiter => {
+ self.get_attr_var_queue_delimiter();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetAttrVarQueueDelimiter => {
+ self.get_attr_var_queue_delimiter();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetAttrVarQueueBeyond => {
+ self.get_attr_var_queue_beyond();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetAttrVarQueueBeyond => {
+ self.get_attr_var_queue_beyond();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetBValue => {
+ self.get_b_value();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetBValue => {
+ self.get_b_value();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetContinuationChunk => {
+ self.get_continuation_chunk();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetContinuationChunk => {
+ self.get_continuation_chunk();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallLookupDBRef => {
+ self.lookup_db_ref();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteLookupDBRef => {
+ self.lookup_db_ref();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetNextOpDBRef => {
+ self.get_next_op_db_ref();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetNextOpDBRef => {
+ self.get_next_op_db_ref();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallIsPartialString => {
+ self.is_partial_string();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteIsPartialString => {
+ self.is_partial_string();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallHalt | &Instruction::ExecuteHalt => {
+ return self.halt();
+ }
+ &Instruction::CallGetLiftedHeapFromOffset => {
+ self.get_lifted_heap_from_offset();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetLiftedHeapFromOffset => {
+ self.get_lifted_heap_from_offset();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetLiftedHeapFromOffsetDiff => {
+ self.get_lifted_heap_from_offset_diff();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetLiftedHeapFromOffsetDiff => {
+ self.get_lifted_heap_from_offset_diff();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetSCCCleaner => {
+ self.get_scc_cleaner();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetSCCCleaner => {
+ self.get_scc_cleaner();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallHeadIsDynamic => {
+ self.head_is_dynamic();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteHeadIsDynamic => {
+ self.head_is_dynamic();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallInstallSCCCleaner => {
+ self.install_scc_cleaner();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteInstallSCCCleaner => {
+ self.install_scc_cleaner();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallInstallInferenceCounter => {
+ try_or_throw!(self.machine_st, self.install_inference_counter());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteInstallInferenceCounter => {
+ try_or_throw!(self.machine_st, self.install_inference_counter());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallLiftedHeapLength => {
+ self.lifted_heap_length();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteLiftedHeapLength => {
+ self.lifted_heap_length();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallLoadLibraryAsStream => {
+ try_or_throw!(self.machine_st, self.load_library_as_stream());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteLoadLibraryAsStream => {
+ try_or_throw!(self.machine_st, self.load_library_as_stream());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallModuleExists => {
+ self.module_exists();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteModuleExists => {
+ self.module_exists();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallNextEP => {
+ self.next_ep();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteNextEP => {
+ self.next_ep();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallNoSuchPredicate => {
+ try_or_throw!(self.machine_st, self.no_such_predicate());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteNoSuchPredicate => {
+ try_or_throw!(self.machine_st, self.no_such_predicate());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallNumberToChars => {
+ self.number_to_chars();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteNumberToChars => {
+ self.number_to_chars();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallNumberToCodes => {
+ self.number_to_codes();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteNumberToCodes => {
+ self.number_to_codes();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallOpDeclaration => {
+ try_or_throw!(self.machine_st, self.op_declaration());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteOpDeclaration => {
+ try_or_throw!(self.machine_st, self.op_declaration());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallOpen => {
+ try_or_throw!(self.machine_st, self.open());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteOpen => {
+ try_or_throw!(self.machine_st, self.open());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallSetStreamOptions => {
+ try_or_throw!(self.machine_st, self.set_stream_options());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteSetStreamOptions => {
+ try_or_throw!(self.machine_st, self.set_stream_options());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallNextStream => {
+ self.next_stream();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteNextStream => {
+ self.next_stream();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallPartialStringTail => {
+ self.partial_string_tail();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecutePartialStringTail => {
+ self.partial_string_tail();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallPeekByte => {
+ try_or_throw!(self.machine_st, self.peek_byte());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecutePeekByte => {
+ try_or_throw!(self.machine_st, self.peek_byte());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallPeekChar => {
+ try_or_throw!(self.machine_st, self.peek_char());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecutePeekChar => {
+ try_or_throw!(self.machine_st, self.peek_char());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallPeekCode => {
+ try_or_throw!(self.machine_st, self.peek_code());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecutePeekCode => {
+ try_or_throw!(self.machine_st, self.peek_code());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallPointsToContinuationResetMarker => {
+ self.points_to_continuation_reset_marker();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecutePointsToContinuationResetMarker => {
+ self.points_to_continuation_reset_marker();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallPutByte => {
+ try_or_throw!(self.machine_st, self.put_byte());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecutePutByte => {
+ try_or_throw!(self.machine_st, self.put_byte());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallPutChar => {
+ try_or_throw!(self.machine_st, self.put_char());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecutePutChar => {
+ try_or_throw!(self.machine_st, self.put_char());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallPutChars => {
+ try_or_throw!(self.machine_st, self.put_chars());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecutePutChars => {
+ try_or_throw!(self.machine_st, self.put_chars());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallPutCode => {
+ try_or_throw!(self.machine_st, self.put_code());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecutePutCode => {
+ try_or_throw!(self.machine_st, self.put_code());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallReadQueryTerm => {
+ try_or_throw!(self.machine_st, self.read_query_term());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteReadQueryTerm => {
+ try_or_throw!(self.machine_st, self.read_query_term());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallReadTerm => {
+ try_or_throw!(self.machine_st, self.read_term());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteReadTerm => {
+ try_or_throw!(self.machine_st, self.read_term());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallRedoAttrVarBinding => {
+ self.redo_attr_var_binding();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteRedoAttrVarBinding => {
+ self.redo_attr_var_binding();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallRemoveCallPolicyCheck => {
+ self.remove_call_policy_check();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteRemoveCallPolicyCheck => {
+ self.remove_call_policy_check();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallRemoveInferenceCounter => {
+ self.remove_inference_counter();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteRemoveInferenceCounter => {
+ self.remove_inference_counter();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallResetContinuationMarker => {
+ self.reset_continuation_marker();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteResetContinuationMarker => {
+ self.reset_continuation_marker();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallRestoreCutPolicy => {
+ self.restore_cut_policy();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteRestoreCutPolicy => {
+ self.restore_cut_policy();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallSetCutPoint(r) => {
+ if !self.set_cut_point(r) {
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ }
+ &Instruction::ExecuteSetCutPoint(r) => {
+ let cp = self.machine_st.cp;
+
+ if !self.set_cut_point(r) {
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ } else {
+ // run_cleaners in set_cut_point calls call_by_index.
+ // replace the effect of call_by_index with that
+ // of execute_by_index here.
+
+ self.machine_st.cp = cp;
+ }
+ }
+ &Instruction::CallSetInput => {
+ try_or_throw!(self.machine_st, self.set_input());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteSetInput => {
+ try_or_throw!(self.machine_st, self.set_input());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallSetOutput => {
+ try_or_throw!(self.machine_st, self.set_output());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteSetOutput => {
+ try_or_throw!(self.machine_st, self.set_output());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallStoreBacktrackableGlobalVar => {
+ self.store_backtrackable_global_var();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteStoreBacktrackableGlobalVar => {
+ self.store_backtrackable_global_var();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallStoreGlobalVar => {
+ self.store_global_var();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteStoreGlobalVar => {
+ self.store_global_var();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallStreamProperty => {
+ try_or_throw!(self.machine_st, self.stream_property());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteStreamProperty => {
+ try_or_throw!(self.machine_st, self.stream_property());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallSetStreamPosition => {
+ try_or_throw!(self.machine_st, self.set_stream_position());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteSetStreamPosition => {
+ try_or_throw!(self.machine_st, self.set_stream_position());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallInferenceLevel => {
+ self.inference_level();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteInferenceLevel => {
+ self.inference_level();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCleanUpBlock => {
+ self.clean_up_block();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteCleanUpBlock => {
+ self.clean_up_block();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallFail | &Instruction::ExecuteFail => {
+ self.machine_st.backtrack();
+ }
+ &Instruction::CallGetBall => {
+ self.get_ball();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetBall => {
+ self.get_ball();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetCurrentBlock => {
+ self.get_current_block();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetCurrentBlock => {
+ self.get_current_block();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetCurrentSCCBlock => {
+ self.get_current_scc_block();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetCurrentSCCBlock => {
+ self.get_current_scc_block();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetCutPoint => {
+ self.get_cut_point();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetCutPoint => {
+ self.get_cut_point();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetDoubleQuotes => {
+ self.get_double_quotes();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetDoubleQuotes => {
+ self.get_double_quotes();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetUnknown => {
+ self.get_unknown();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetUnknown => {
+ self.get_unknown();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallInstallNewBlock => {
+ self.machine_st
+ .install_new_block(self.machine_st.registers[1]);
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteInstallNewBlock => {
+ self.machine_st
+ .install_new_block(self.machine_st.registers[1]);
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallMaybe => {
+ self.maybe();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteMaybe => {
+ self.maybe();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCpuNow => {
+ self.cpu_now();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCpuNow => {
+ self.cpu_now();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallDeterministicLengthRundown => {
+ try_or_throw!(self.machine_st, self.det_length_rundown());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteDeterministicLengthRundown => {
+ try_or_throw!(self.machine_st, self.det_length_rundown());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallHttpOpen => {
+ #[cfg(feature = "http")]
+ try_or_throw!(self.machine_st, self.http_open());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteHttpOpen => {
+ #[cfg(feature = "http")]
+ try_or_throw!(self.machine_st, self.http_open());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallHttpListen => {
+ #[cfg(feature = "http")]
+ try_or_throw!(self.machine_st, self.http_listen());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteHttpListen => {
+ #[cfg(feature = "http")]
+ try_or_throw!(self.machine_st, self.http_listen());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallHttpAccept => {
+ #[cfg(feature = "http")]
+ try_or_throw!(self.machine_st, self.http_accept());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteHttpAccept => {
+ #[cfg(feature = "http")]
+ try_or_throw!(self.machine_st, self.http_accept());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallHttpAnswer => {
+ #[cfg(feature = "http")]
+ try_or_throw!(self.machine_st, self.http_answer());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteHttpAnswer => {
+ #[cfg(feature = "http")]
+ try_or_throw!(self.machine_st, self.http_answer());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallLoadForeignLib => {
+ #[cfg(feature = "ffi")]
+ try_or_throw!(self.machine_st, self.load_foreign_lib());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteLoadForeignLib => {
+ #[cfg(feature = "ffi")]
+ try_or_throw!(self.machine_st, self.load_foreign_lib());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallForeignCall => {
+ #[cfg(feature = "ffi")]
+ try_or_throw!(self.machine_st, self.foreign_call());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteForeignCall => {
+ #[cfg(feature = "ffi")]
+ try_or_throw!(self.machine_st, self.foreign_call());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallDefineForeignStruct => {
+ #[cfg(feature = "ffi")]
+ try_or_throw!(self.machine_st, self.define_foreign_struct());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteDefineForeignStruct => {
+ #[cfg(feature = "ffi")]
+ try_or_throw!(self.machine_st, self.define_foreign_struct());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCurrentTime => {
+ self.current_time();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCurrentTime => {
+ self.current_time();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallQuotedToken => {
+ self.quoted_token();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteQuotedToken => {
+ self.quoted_token();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallReadFromChars => {
+ try_or_throw!(self.machine_st, self.read_from_chars());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteReadFromChars => {
+ try_or_throw!(self.machine_st, self.read_from_chars());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallReadTermFromChars => {
+ try_or_throw!(self.machine_st, self.read_term_from_chars());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteReadTermFromChars => {
+ try_or_throw!(self.machine_st, self.read_term_from_chars());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallResetBlock => {
+ self.reset_block();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteResetBlock => {
+ self.reset_block();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallResetSCCBlock => {
+ self.reset_scc_block();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteResetSCCBlock => {
+ self.reset_scc_block();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallReturnFromVerifyAttr
+ | &Instruction::ExecuteReturnFromVerifyAttr => {
+ self.return_from_verify_attr();
+ }
+ &Instruction::CallSetBall => {
+ self.set_ball();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteSetBall => {
+ self.set_ball();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallPushBallStack => {
+ self.push_ball_stack();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecutePushBallStack => {
+ self.push_ball_stack();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallPopBallStack => {
+ self.pop_ball_stack();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecutePopBallStack => {
+ self.pop_ball_stack();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallPopFromBallStack => {
+ self.pop_from_ball_stack();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecutePopFromBallStack => {
+ self.pop_from_ball_stack();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallSetCutPointByDefault(r) => {
+ self.set_cut_point_by_default(r);
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteSetCutPointByDefault(r) => {
+ self.set_cut_point_by_default(r);
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallSetDoubleQuotes => {
+ self.set_double_quotes();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteSetDoubleQuotes => {
+ self.set_double_quotes();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallSetUnknown => {
+ self.set_unknown();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteSetUnknown => {
+ self.set_unknown();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallSetSeed => {
+ self.set_seed();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteSetSeed => {
+ self.set_seed();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallSkipMaxList => {
+ try_or_throw!(self.machine_st, self.machine_st.skip_max_list());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteSkipMaxList => {
+ try_or_throw!(self.machine_st, self.machine_st.skip_max_list());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallSleep => {
+ self.sleep();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteSleep => {
+ self.sleep();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallSocketClientOpen => {
+ try_or_throw!(self.machine_st, self.socket_client_open());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteSocketClientOpen => {
+ try_or_throw!(self.machine_st, self.socket_client_open());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallSocketServerOpen => {
+ try_or_throw!(self.machine_st, self.socket_server_open());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteSocketServerOpen => {
+ try_or_throw!(self.machine_st, self.socket_server_open());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallSocketServerAccept => {
+ try_or_throw!(self.machine_st, self.socket_server_accept());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteSocketServerAccept => {
+ try_or_throw!(self.machine_st, self.socket_server_accept());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallSocketServerClose => {
+ try_or_throw!(self.machine_st, self.socket_server_close());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteSocketServerClose => {
+ try_or_throw!(self.machine_st, self.socket_server_close());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallTLSAcceptClient => {
+ #[cfg(feature = "tls")]
+ try_or_throw!(self.machine_st, self.tls_accept_client());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteTLSAcceptClient => {
+ #[cfg(feature = "tls")]
+ try_or_throw!(self.machine_st, self.tls_accept_client());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallTLSClientConnect => {
+ #[cfg(feature = "tls")]
+ try_or_throw!(self.machine_st, self.tls_client_connect());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteTLSClientConnect => {
+ #[cfg(feature = "tls")]
+ try_or_throw!(self.machine_st, self.tls_client_connect());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallSucceed => {
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteSucceed => {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallTermAttributedVariables => {
+ self.term_attributed_variables();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteTermAttributedVariables => {
+ self.term_attributed_variables();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallTermVariables => {
+ self.term_variables();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteTermVariables => {
+ self.term_variables();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallTermVariablesUnderMaxDepth => {
+ self.term_variables_under_max_depth();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteTermVariablesUnderMaxDepth => {
+ self.term_variables_under_max_depth();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallTruncateLiftedHeapTo => {
+ self.truncate_lifted_heap_to();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteTruncateLiftedHeapTo => {
+ self.truncate_lifted_heap_to();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallUnifyWithOccursCheck => {
+ self.unify_with_occurs_check();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteUnifyWithOccursCheck => {
+ self.unify_with_occurs_check();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallUnwindEnvironments => {
+ if !self.unwind_environments() {
+ self.machine_st.p += 1;
+ }
+ }
+ &Instruction::ExecuteUnwindEnvironments => {
+ if !self.unwind_environments() {
+ self.machine_st.p = self.machine_st.cp;
+ }
+ }
+ &Instruction::CallUnwindStack | &Instruction::ExecuteUnwindStack => {
+ self.machine_st.unwind_stack();
+ self.machine_st.backtrack();
+ }
+ &Instruction::CallWAMInstructions => {
+ try_or_throw!(self.machine_st, self.wam_instructions());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteWAMInstructions => {
+ try_or_throw!(self.machine_st, self.wam_instructions());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallInlinedInstructions => {
+ self.inlined_instructions();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteInlinedInstructions => {
+ self.inlined_instructions();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallWriteTerm => {
+ try_or_throw!(self.machine_st, self.write_term());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteWriteTerm => {
+ try_or_throw!(self.machine_st, self.write_term());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallWriteTermToChars => {
+ try_or_throw!(self.machine_st, self.write_term_to_chars());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteWriteTermToChars => {
+ try_or_throw!(self.machine_st, self.write_term_to_chars());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallScryerPrologVersion => {
+ self.scryer_prolog_version();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteScryerPrologVersion => {
+ self.scryer_prolog_version();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCryptoRandomByte => {
+ self.crypto_random_byte();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCryptoRandomByte => {
+ self.crypto_random_byte();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCryptoDataHash => {
+ self.crypto_data_hash();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCryptoDataHash => {
+ self.crypto_data_hash();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCryptoDataHKDF => {
+ self.crypto_data_hkdf();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCryptoDataHKDF => {
+ self.crypto_data_hkdf();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCryptoPasswordHash => {
+ self.crypto_password_hash();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCryptoPasswordHash => {
+ self.crypto_password_hash();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCryptoDataEncrypt => {
+ self.crypto_data_encrypt();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCryptoDataEncrypt => {
+ self.crypto_data_encrypt();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCryptoDataDecrypt => {
+ self.crypto_data_decrypt();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCryptoDataDecrypt => {
+ self.crypto_data_decrypt();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCryptoCurveScalarMult => {
+ self.crypto_curve_scalar_mult();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCryptoCurveScalarMult => {
+ self.crypto_curve_scalar_mult();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallEd25519Sign => {
+ self.ed25519_sign();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteEd25519Sign => {
+ self.ed25519_sign();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallEd25519Verify => {
+ self.ed25519_verify();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteEd25519Verify => {
+ self.ed25519_verify();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallEd25519NewKeyPair => {
+ self.ed25519_new_key_pair();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteEd25519NewKeyPair => {
+ self.ed25519_new_key_pair();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallEd25519KeyPairPublicKey => {
+ self.ed25519_key_pair_public_key();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteEd25519KeyPairPublicKey => {
+ self.ed25519_key_pair_public_key();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCurve25519ScalarMult => {
+ self.curve25519_scalar_mult();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCurve25519ScalarMult => {
+ self.curve25519_scalar_mult();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallFirstNonOctet => {
+ self.first_non_octet();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteFirstNonOctet => {
+ self.first_non_octet();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallLoadHTML => {
+ self.load_html();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteLoadHTML => {
+ self.load_html();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallLoadXML => {
+ self.load_xml();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteLoadXML => {
+ self.load_xml();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallGetEnv => {
+ self.get_env();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetEnv => {
+ self.get_env();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallSetEnv => {
+ self.set_env();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteSetEnv => {
+ self.set_env();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallUnsetEnv => {
+ self.unset_env();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteUnsetEnv => {
+ self.unset_env();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallShell => {
+ self.shell();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteShell => {
+ self.shell();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallPID => {
+ self.pid();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecutePID => {
+ self.pid();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCharsBase64 => {
+ try_or_throw!(self.machine_st, self.chars_base64());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCharsBase64 => {
+ try_or_throw!(self.machine_st, self.chars_base64());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallDevourWhitespace => {
+ try_or_throw!(self.machine_st, self.devour_whitespace());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteDevourWhitespace => {
+ try_or_throw!(self.machine_st, self.devour_whitespace());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallIsSTOEnabled => {
+ self.is_sto_enabled();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteIsSTOEnabled => {
+ self.is_sto_enabled();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallSetSTOAsUnify => {
+ self.set_sto_as_unify();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteSetSTOAsUnify => {
+ self.set_sto_as_unify();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallSetNSTOAsUnify => {
+ self.set_nsto_as_unify();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteSetNSTOAsUnify => {
+ self.set_nsto_as_unify();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallSetSTOWithErrorAsUnify => {
+ self.set_sto_with_error_as_unify();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteSetSTOWithErrorAsUnify => {
+ self.set_sto_with_error_as_unify();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallHomeDirectory => {
+ self.home_directory();
step_or_fail!(self, self.machine_st.p += 1);
}
- }
- &Instruction::ExecuteSetCutPoint(r) => {
- let cp = self.machine_st.cp;
-
- if !self.set_cut_point(r) {
+ &Instruction::ExecuteHomeDirectory => {
+ self.home_directory();
step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- } else {
- // run_cleaners in set_cut_point calls call_by_index.
- // replace the effect of call_by_index with that
- // of execute_by_index here.
+ }
+ &Instruction::CallDebugHook => {
+ self.debug_hook();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteDebugHook => {
+ self.debug_hook();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallPopCount => {
+ self.pop_count();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecutePopCount => {
+ self.pop_count();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallAddDiscontiguousPredicate => {
+ try_or_throw!(self.machine_st, self.add_discontiguous_predicate());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteAddDiscontiguousPredicate => {
+ try_or_throw!(self.machine_st, self.add_discontiguous_predicate());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallAddDynamicPredicate => {
+ try_or_throw!(self.machine_st, self.add_dynamic_predicate());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteAddDynamicPredicate => {
+ try_or_throw!(self.machine_st, self.add_dynamic_predicate());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallAddMultifilePredicate => {
+ try_or_throw!(self.machine_st, self.add_multifile_predicate());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteAddMultifilePredicate => {
+ try_or_throw!(self.machine_st, self.add_multifile_predicate());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallAddGoalExpansionClause => {
+ try_or_throw!(self.machine_st, self.add_goal_expansion_clause());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteAddGoalExpansionClause => {
+ try_or_throw!(self.machine_st, self.add_goal_expansion_clause());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallAddTermExpansionClause => {
+ try_or_throw!(self.machine_st, self.add_term_expansion_clause());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteAddTermExpansionClause => {
+ try_or_throw!(self.machine_st, self.add_term_expansion_clause());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallAddInSituFilenameModule => {
+ try_or_throw!(self.machine_st, self.add_in_situ_filename_module());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteAddInSituFilenameModule => {
+ try_or_throw!(self.machine_st, self.add_in_situ_filename_module());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallClauseToEvacuable => {
+ try_or_throw!(self.machine_st, self.clause_to_evacuable());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteClauseToEvacuable => {
+ try_or_throw!(self.machine_st, self.clause_to_evacuable());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallScopedClauseToEvacuable => {
+ try_or_throw!(self.machine_st, self.scoped_clause_to_evacuable());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteScopedClauseToEvacuable => {
+ try_or_throw!(self.machine_st, self.scoped_clause_to_evacuable());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallConcludeLoad => {
+ try_or_throw!(self.machine_st, self.conclude_load());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteConcludeLoad => {
+ try_or_throw!(self.machine_st, self.conclude_load());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallDeclareModule => {
+ try_or_throw!(self.machine_st, self.declare_module());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteDeclareModule => {
+ try_or_throw!(self.machine_st, self.declare_module());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallLoadCompiledLibrary => {
+ try_or_throw!(self.machine_st, self.load_compiled_library());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteLoadCompiledLibrary => {
+ try_or_throw!(self.machine_st, self.load_compiled_library());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallLoadContextSource => {
+ self.load_context_source();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteLoadContextSource => {
+ self.load_context_source();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallLoadContextFile => {
+ self.load_context_file();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteLoadContextFile => {
+ self.load_context_file();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallLoadContextDirectory => {
+ self.load_context_directory();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteLoadContextDirectory => {
+ self.load_context_directory();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallLoadContextModule => {
+ self.load_context_module(self.machine_st.registers[1]);
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteLoadContextModule => {
+ self.load_context_module(self.machine_st.registers[1]);
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallLoadContextStream => {
+ self.load_context_stream();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteLoadContextStream => {
+ self.load_context_stream();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallPopLoadContext => {
+ self.pop_load_context();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecutePopLoadContext => {
+ self.pop_load_context();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallPopLoadStatePayload => {
+ self.pop_load_state_payload();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecutePopLoadStatePayload => {
+ self.pop_load_state_payload();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallPushLoadContext => {
+ try_or_throw!(self.machine_st, self.push_load_context());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecutePushLoadContext => {
+ try_or_throw!(self.machine_st, self.push_load_context());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallPushLoadStatePayload => {
+ self.push_load_state_payload();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecutePushLoadStatePayload => {
+ self.push_load_state_payload();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallUseModule => {
+ try_or_throw!(self.machine_st, self.use_module());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteUseModule => {
+ try_or_throw!(self.machine_st, self.use_module());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallBuiltInProperty => {
+ let key = self.machine_st.read_predicate_key(
+ self.machine_st.registers[1],
+ self.machine_st.registers[2],
+ );
- self.machine_st.cp = cp;
+ self.machine_st.fail = !self.indices.builtin_property(key);
+ step_or_fail!(self, self.machine_st.p += 1);
}
- }
- &Instruction::CallSetInput => {
- try_or_throw!(self.machine_st, self.set_input());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteSetInput => {
- try_or_throw!(self.machine_st, self.set_input());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallSetOutput => {
- try_or_throw!(self.machine_st, self.set_output());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteSetOutput => {
- try_or_throw!(self.machine_st, self.set_output());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallStoreBacktrackableGlobalVar => {
- self.store_backtrackable_global_var();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteStoreBacktrackableGlobalVar => {
- self.store_backtrackable_global_var();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallStoreGlobalVar => {
- self.store_global_var();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteStoreGlobalVar => {
- self.store_global_var();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallStreamProperty => {
- try_or_throw!(self.machine_st, self.stream_property());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteStreamProperty => {
- try_or_throw!(self.machine_st, self.stream_property());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallSetStreamPosition => {
- try_or_throw!(self.machine_st, self.set_stream_position());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteSetStreamPosition => {
- try_or_throw!(self.machine_st, self.set_stream_position());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallInferenceLevel => {
- self.inference_level();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteInferenceLevel => {
- self.inference_level();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCleanUpBlock => {
- self.clean_up_block();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteCleanUpBlock => {
- self.clean_up_block();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallFail | &Instruction::ExecuteFail => {
- self.machine_st.backtrack();
- }
- &Instruction::CallGetBall => {
- self.get_ball();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetBall => {
- self.get_ball();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetCurrentBlock => {
- self.get_current_block();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetCurrentBlock => {
- self.get_current_block();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetCurrentSCCBlock => {
- self.get_current_scc_block();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetCurrentSCCBlock => {
- self.get_current_scc_block();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetCutPoint => {
- self.get_cut_point();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetCutPoint => {
- self.get_cut_point();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetDoubleQuotes => {
- self.get_double_quotes();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetDoubleQuotes => {
- self.get_double_quotes();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetUnknown => {
- self.get_unknown();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetUnknown => {
- self.get_unknown();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallInstallNewBlock => {
- self.machine_st.install_new_block(self.machine_st.registers[1]);
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteInstallNewBlock => {
- self.machine_st.install_new_block(self.machine_st.registers[1]);
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallMaybe => {
- self.maybe();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteMaybe => {
- self.maybe();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCpuNow => {
- self.cpu_now();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCpuNow => {
- self.cpu_now();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallDeterministicLengthRundown => {
- try_or_throw!(self.machine_st, self.det_length_rundown());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteDeterministicLengthRundown => {
- try_or_throw!(self.machine_st, self.det_length_rundown());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallHttpOpen => {
- #[cfg(feature = "http")]
- try_or_throw!(self.machine_st, self.http_open());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteHttpOpen => {
- #[cfg(feature = "http")]
- try_or_throw!(self.machine_st, self.http_open());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallHttpListen => {
- #[cfg(feature = "http")]
- try_or_throw!(self.machine_st, self.http_listen());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteHttpListen => {
- #[cfg(feature = "http")]
- try_or_throw!(self.machine_st, self.http_listen());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallHttpAccept => {
- #[cfg(feature = "http")]
- try_or_throw!(self.machine_st, self.http_accept());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteHttpAccept => {
- #[cfg(feature = "http")]
- try_or_throw!(self.machine_st, self.http_accept());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallHttpAnswer => {
- #[cfg(feature = "http")]
- try_or_throw!(self.machine_st, self.http_answer());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteHttpAnswer => {
- #[cfg(feature = "http")]
- try_or_throw!(self.machine_st, self.http_answer());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallLoadForeignLib => {
- #[cfg(feature = "ffi")]
- try_or_throw!(self.machine_st, self.load_foreign_lib());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteLoadForeignLib => {
- #[cfg(feature = "ffi")]
- try_or_throw!(self.machine_st, self.load_foreign_lib());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallForeignCall => {
- #[cfg(feature = "ffi")]
- try_or_throw!(self.machine_st, self.foreign_call());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteForeignCall => {
- #[cfg(feature = "ffi")]
- try_or_throw!(self.machine_st, self.foreign_call());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallDefineForeignStruct => {
- #[cfg(feature = "ffi")]
- try_or_throw!(self.machine_st, self.define_foreign_struct());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteDefineForeignStruct => {
- #[cfg(feature = "ffi")]
- try_or_throw!(self.machine_st, self.define_foreign_struct());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCurrentTime => {
- self.current_time();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCurrentTime => {
- self.current_time();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallQuotedToken => {
- self.quoted_token();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteQuotedToken => {
- self.quoted_token();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallReadFromChars => {
- try_or_throw!(self.machine_st, self.read_from_chars());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteReadFromChars => {
- try_or_throw!(self.machine_st, self.read_from_chars());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallReadTermFromChars => {
- try_or_throw!(self.machine_st, self.read_term_from_chars());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteReadTermFromChars => {
- try_or_throw!(self.machine_st, self.read_term_from_chars());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallResetBlock => {
- self.reset_block();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteResetBlock => {
- self.reset_block();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallResetSCCBlock => {
- self.reset_scc_block();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteResetSCCBlock => {
- self.reset_scc_block();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallReturnFromVerifyAttr |
- &Instruction::ExecuteReturnFromVerifyAttr => {
- self.return_from_verify_attr();
- }
- &Instruction::CallSetBall => {
- self.set_ball();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteSetBall => {
- self.set_ball();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallPushBallStack => {
- self.push_ball_stack();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecutePushBallStack => {
- self.push_ball_stack();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallPopBallStack => {
- self.pop_ball_stack();
- self.machine_st.p += 1;
- }
- &Instruction::ExecutePopBallStack => {
- self.pop_ball_stack();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallPopFromBallStack => {
- self.pop_from_ball_stack();
- self.machine_st.p += 1;
- }
- &Instruction::ExecutePopFromBallStack => {
- self.pop_from_ball_stack();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallSetCutPointByDefault(r) => {
- self.set_cut_point_by_default(r);
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteSetCutPointByDefault(r) => {
- self.set_cut_point_by_default(r);
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallSetDoubleQuotes => {
- self.set_double_quotes();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteSetDoubleQuotes => {
- self.set_double_quotes();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallSetUnknown => {
- self.set_unknown();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteSetUnknown => {
- self.set_unknown();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallSetSeed => {
- self.set_seed();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteSetSeed => {
- self.set_seed();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallSkipMaxList => {
- try_or_throw!(self.machine_st, self.machine_st.skip_max_list());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteSkipMaxList => {
- try_or_throw!(self.machine_st, self.machine_st.skip_max_list());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallSleep => {
- self.sleep();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteSleep => {
- self.sleep();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallSocketClientOpen => {
- try_or_throw!(self.machine_st, self.socket_client_open());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteSocketClientOpen => {
- try_or_throw!(self.machine_st, self.socket_client_open());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallSocketServerOpen => {
- try_or_throw!(self.machine_st, self.socket_server_open());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteSocketServerOpen => {
- try_or_throw!(self.machine_st, self.socket_server_open());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallSocketServerAccept => {
- try_or_throw!(self.machine_st, self.socket_server_accept());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteSocketServerAccept => {
- try_or_throw!(self.machine_st, self.socket_server_accept());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallSocketServerClose => {
- try_or_throw!(self.machine_st, self.socket_server_close());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteSocketServerClose => {
- try_or_throw!(self.machine_st, self.socket_server_close());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallTLSAcceptClient => {
- #[cfg(feature = "tls")]
- try_or_throw!(self.machine_st, self.tls_accept_client());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteTLSAcceptClient => {
- #[cfg(feature = "tls")]
- try_or_throw!(self.machine_st, self.tls_accept_client());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallTLSClientConnect => {
- #[cfg(feature = "tls")]
- try_or_throw!(self.machine_st, self.tls_client_connect());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteTLSClientConnect => {
- #[cfg(feature = "tls")]
- try_or_throw!(self.machine_st, self.tls_client_connect());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallSucceed => {
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteSucceed => {
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallTermAttributedVariables => {
- self.term_attributed_variables();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteTermAttributedVariables => {
- self.term_attributed_variables();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallTermVariables => {
- self.term_variables();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteTermVariables => {
- self.term_variables();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallTermVariablesUnderMaxDepth => {
- self.term_variables_under_max_depth();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteTermVariablesUnderMaxDepth => {
- self.term_variables_under_max_depth();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallTruncateLiftedHeapTo => {
- self.truncate_lifted_heap_to();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteTruncateLiftedHeapTo => {
- self.truncate_lifted_heap_to();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallUnifyWithOccursCheck => {
- self.unify_with_occurs_check();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteUnifyWithOccursCheck => {
- self.unify_with_occurs_check();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallUnwindEnvironments => {
- if !self.unwind_environments() {
+ &Instruction::ExecuteBuiltInProperty => {
+ let key = self.machine_st.read_predicate_key(
+ self.machine_st.registers[1],
+ self.machine_st.registers[2],
+ );
+
+ self.machine_st.fail = !self.indices.builtin_property(key);
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallMetaPredicateProperty => {
+ self.meta_predicate_property();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteMetaPredicateProperty => {
+ self.meta_predicate_property();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallMultifileProperty => {
+ self.multifile_property();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteMultifileProperty => {
+ self.multifile_property();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallDiscontiguousProperty => {
+ self.discontiguous_property();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteDiscontiguousProperty => {
+ self.discontiguous_property();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallDynamicProperty => {
+ self.dynamic_property();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteDynamicProperty => {
+ self.dynamic_property();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallAbolishClause => {
+ try_or_throw!(self.machine_st, self.abolish_clause());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteAbolishClause => {
+ try_or_throw!(self.machine_st, self.abolish_clause());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallAsserta => {
+ try_or_throw!(
+ self.machine_st,
+ self.compile_assert(AppendOrPrepend::Prepend)
+ );
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteAsserta => {
+ try_or_throw!(
+ self.machine_st,
+ self.compile_assert(AppendOrPrepend::Prepend)
+ );
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallAssertz => {
+ try_or_throw!(
+ self.machine_st,
+ self.compile_assert(AppendOrPrepend::Append)
+ );
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteAssertz => {
+ try_or_throw!(
+ self.machine_st,
+ self.compile_assert(AppendOrPrepend::Append)
+ );
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallRetract => {
+ try_or_throw!(self.machine_st, self.retract_clause());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteRetract => {
+ try_or_throw!(self.machine_st, self.retract_clause());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallIsConsistentWithTermQueue => {
+ try_or_throw!(self.machine_st, self.is_consistent_with_term_queue());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteIsConsistentWithTermQueue => {
+ try_or_throw!(self.machine_st, self.is_consistent_with_term_queue());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::CallFlushTermQueue => {
+ try_or_throw!(self.machine_st, self.flush_term_queue());
self.machine_st.p += 1;
}
- }
- &Instruction::ExecuteUnwindEnvironments => {
- if !self.unwind_environments() {
+ &Instruction::ExecuteFlushTermQueue => {
+ try_or_throw!(self.machine_st, self.flush_term_queue());
self.machine_st.p = self.machine_st.cp;
}
- }
- &Instruction::CallUnwindStack | &Instruction::ExecuteUnwindStack => {
- self.machine_st.unwind_stack();
- self.machine_st.backtrack();
- }
- &Instruction::CallWAMInstructions => {
- try_or_throw!(self.machine_st, self.wam_instructions());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteWAMInstructions => {
- try_or_throw!(self.machine_st, self.wam_instructions());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallInlinedInstructions => {
- self.inlined_instructions();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteInlinedInstructions => {
- self.inlined_instructions();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallWriteTerm => {
- try_or_throw!(self.machine_st, self.write_term());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteWriteTerm => {
- try_or_throw!(self.machine_st, self.write_term());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallWriteTermToChars => {
- try_or_throw!(self.machine_st, self.write_term_to_chars());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteWriteTermToChars => {
- try_or_throw!(self.machine_st, self.write_term_to_chars());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallScryerPrologVersion => {
- self.scryer_prolog_version();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteScryerPrologVersion => {
- self.scryer_prolog_version();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCryptoRandomByte => {
- self.crypto_random_byte();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCryptoRandomByte => {
- self.crypto_random_byte();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCryptoDataHash => {
- self.crypto_data_hash();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCryptoDataHash => {
- self.crypto_data_hash();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCryptoDataHKDF => {
- self.crypto_data_hkdf();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCryptoDataHKDF => {
- self.crypto_data_hkdf();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCryptoPasswordHash => {
- self.crypto_password_hash();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCryptoPasswordHash => {
- self.crypto_password_hash();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCryptoDataEncrypt => {
- self.crypto_data_encrypt();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCryptoDataEncrypt => {
- self.crypto_data_encrypt();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCryptoDataDecrypt => {
- self.crypto_data_decrypt();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCryptoDataDecrypt => {
- self.crypto_data_decrypt();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCryptoCurveScalarMult => {
- self.crypto_curve_scalar_mult();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCryptoCurveScalarMult => {
- self.crypto_curve_scalar_mult();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallEd25519Sign => {
- self.ed25519_sign();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteEd25519Sign => {
- self.ed25519_sign();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallEd25519Verify => {
- self.ed25519_verify();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteEd25519Verify => {
- self.ed25519_verify();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallEd25519NewKeyPair => {
- self.ed25519_new_key_pair();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteEd25519NewKeyPair => {
- self.ed25519_new_key_pair();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallEd25519KeyPairPublicKey => {
- self.ed25519_key_pair_public_key();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteEd25519KeyPairPublicKey => {
- self.ed25519_key_pair_public_key();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCurve25519ScalarMult => {
- self.curve25519_scalar_mult();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCurve25519ScalarMult => {
- self.curve25519_scalar_mult();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallFirstNonOctet => {
- self.first_non_octet();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteFirstNonOctet => {
- self.first_non_octet();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallLoadHTML => {
- self.load_html();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteLoadHTML => {
- self.load_html();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallLoadXML => {
- self.load_xml();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteLoadXML => {
- self.load_xml();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallGetEnv => {
- self.get_env();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetEnv => {
- self.get_env();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallSetEnv => {
- self.set_env();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteSetEnv => {
- self.set_env();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallUnsetEnv => {
- self.unset_env();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteUnsetEnv => {
- self.unset_env();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallShell => {
- self.shell();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteShell => {
- self.shell();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallPID => {
- self.pid();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecutePID => {
- self.pid();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCharsBase64 => {
- try_or_throw!(self.machine_st, self.chars_base64());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCharsBase64 => {
- try_or_throw!(self.machine_st, self.chars_base64());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallDevourWhitespace => {
- try_or_throw!(self.machine_st, self.devour_whitespace());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteDevourWhitespace => {
- try_or_throw!(self.machine_st, self.devour_whitespace());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallIsSTOEnabled => {
- self.is_sto_enabled();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteIsSTOEnabled => {
- self.is_sto_enabled();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallSetSTOAsUnify => {
- self.set_sto_as_unify();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteSetSTOAsUnify => {
- self.set_sto_as_unify();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallSetNSTOAsUnify => {
- self.set_nsto_as_unify();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteSetNSTOAsUnify => {
- self.set_nsto_as_unify();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallSetSTOWithErrorAsUnify => {
- self.set_sto_with_error_as_unify();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteSetSTOWithErrorAsUnify => {
- self.set_sto_with_error_as_unify();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallHomeDirectory => {
- self.home_directory();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteHomeDirectory => {
- self.home_directory();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallDebugHook => {
- self.debug_hook();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteDebugHook => {
- self.debug_hook();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallPopCount => {
- self.pop_count();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecutePopCount => {
- self.pop_count();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallAddDiscontiguousPredicate => {
- try_or_throw!(self.machine_st, self.add_discontiguous_predicate());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteAddDiscontiguousPredicate => {
- try_or_throw!(self.machine_st, self.add_discontiguous_predicate());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallAddDynamicPredicate => {
- try_or_throw!(self.machine_st, self.add_dynamic_predicate());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteAddDynamicPredicate => {
- try_or_throw!(self.machine_st, self.add_dynamic_predicate());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallAddMultifilePredicate => {
- try_or_throw!(self.machine_st, self.add_multifile_predicate());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteAddMultifilePredicate => {
- try_or_throw!(self.machine_st, self.add_multifile_predicate());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallAddGoalExpansionClause => {
- try_or_throw!(self.machine_st, self.add_goal_expansion_clause());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteAddGoalExpansionClause => {
- try_or_throw!(self.machine_st, self.add_goal_expansion_clause());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallAddTermExpansionClause => {
- try_or_throw!(self.machine_st, self.add_term_expansion_clause());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteAddTermExpansionClause => {
- try_or_throw!(self.machine_st, self.add_term_expansion_clause());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallAddInSituFilenameModule => {
- try_or_throw!(self.machine_st, self.add_in_situ_filename_module());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteAddInSituFilenameModule => {
- try_or_throw!(self.machine_st, self.add_in_situ_filename_module());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallClauseToEvacuable => {
- try_or_throw!(self.machine_st, self.clause_to_evacuable());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteClauseToEvacuable => {
- try_or_throw!(self.machine_st, self.clause_to_evacuable());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallScopedClauseToEvacuable => {
- try_or_throw!(self.machine_st, self.scoped_clause_to_evacuable());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteScopedClauseToEvacuable => {
- try_or_throw!(self.machine_st, self.scoped_clause_to_evacuable());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallConcludeLoad => {
- try_or_throw!(self.machine_st, self.conclude_load());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteConcludeLoad => {
- try_or_throw!(self.machine_st, self.conclude_load());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallDeclareModule => {
- try_or_throw!(self.machine_st, self.declare_module());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteDeclareModule => {
- try_or_throw!(self.machine_st, self.declare_module());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallLoadCompiledLibrary => {
- try_or_throw!(self.machine_st, self.load_compiled_library());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteLoadCompiledLibrary => {
- try_or_throw!(self.machine_st, self.load_compiled_library());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallLoadContextSource => {
- self.load_context_source();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteLoadContextSource => {
- self.load_context_source();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallLoadContextFile => {
- self.load_context_file();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteLoadContextFile => {
- self.load_context_file();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallLoadContextDirectory => {
- self.load_context_directory();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteLoadContextDirectory => {
- self.load_context_directory();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallLoadContextModule => {
- self.load_context_module(self.machine_st.registers[1]);
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteLoadContextModule => {
- self.load_context_module(self.machine_st.registers[1]);
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallLoadContextStream => {
- self.load_context_stream();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteLoadContextStream => {
- self.load_context_stream();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallPopLoadContext => {
- self.pop_load_context();
- self.machine_st.p += 1;
- }
- &Instruction::ExecutePopLoadContext => {
- self.pop_load_context();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallPopLoadStatePayload => {
- self.pop_load_state_payload();
- self.machine_st.p += 1;
- }
- &Instruction::ExecutePopLoadStatePayload => {
- self.pop_load_state_payload();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallPushLoadContext => {
- try_or_throw!(self.machine_st, self.push_load_context());
- self.machine_st.p += 1;
- }
- &Instruction::ExecutePushLoadContext => {
- try_or_throw!(self.machine_st, self.push_load_context());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallPushLoadStatePayload => {
- self.push_load_state_payload();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecutePushLoadStatePayload => {
- self.push_load_state_payload();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallUseModule => {
- try_or_throw!(self.machine_st, self.use_module());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteUseModule => {
- try_or_throw!(self.machine_st, self.use_module());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallBuiltInProperty => {
- let key = self
- .machine_st
- .read_predicate_key(self.machine_st.registers[1], self.machine_st.registers[2]);
-
- self.machine_st.fail = !self.indices.builtin_property(key);
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteBuiltInProperty => {
- let key = self
- .machine_st
- .read_predicate_key(self.machine_st.registers[1], self.machine_st.registers[2]);
-
- self.machine_st.fail = !self.indices.builtin_property(key);
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallMetaPredicateProperty => {
- self.meta_predicate_property();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteMetaPredicateProperty => {
- self.meta_predicate_property();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallMultifileProperty => {
- self.multifile_property();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteMultifileProperty => {
- self.multifile_property();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallDiscontiguousProperty => {
- self.discontiguous_property();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteDiscontiguousProperty => {
- self.discontiguous_property();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallDynamicProperty => {
- self.dynamic_property();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteDynamicProperty => {
- self.dynamic_property();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallAbolishClause => {
- try_or_throw!(self.machine_st, self.abolish_clause());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteAbolishClause => {
- try_or_throw!(self.machine_st, self.abolish_clause());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallAsserta => {
- try_or_throw!(self.machine_st, self.compile_assert(AppendOrPrepend::Prepend));
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteAsserta => {
- try_or_throw!(self.machine_st, self.compile_assert(AppendOrPrepend::Prepend));
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallAssertz => {
- try_or_throw!(self.machine_st, self.compile_assert(AppendOrPrepend::Append));
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteAssertz => {
- try_or_throw!(self.machine_st, self.compile_assert(AppendOrPrepend::Append));
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallRetract => {
- try_or_throw!(self.machine_st, self.retract_clause());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteRetract => {
- try_or_throw!(self.machine_st, self.retract_clause());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallIsConsistentWithTermQueue => {
- try_or_throw!(self.machine_st, self.is_consistent_with_term_queue());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteIsConsistentWithTermQueue => {
- try_or_throw!(self.machine_st, self.is_consistent_with_term_queue());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::CallFlushTermQueue => {
- try_or_throw!(self.machine_st, self.flush_term_queue());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteFlushTermQueue => {
- try_or_throw!(self.machine_st, self.flush_term_queue());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallRemoveModuleExports => {
- try_or_throw!(self.machine_st, self.remove_module_exports());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteRemoveModuleExports => {
- try_or_throw!(self.machine_st, self.remove_module_exports());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallAddNonCountedBacktracking => {
- try_or_throw!(self.machine_st, self.add_non_counted_backtracking());
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteAddNonCountedBacktracking => {
- try_or_throw!(self.machine_st, self.add_non_counted_backtracking());
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallPredicateDefined => {
- self.machine_st.fail = !self.predicate_defined();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecutePredicateDefined => {
- self.machine_st.fail = !self.predicate_defined();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallStripModule => {
- self.strip_module();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteStripModule => {
- self.strip_module();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallPrepareCallClause(arity) => {
- try_or_throw!(self.machine_st, self.prepare_call_clause(arity));
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecutePrepareCallClause(arity) => {
- try_or_throw!(self.machine_st, self.prepare_call_clause(arity));
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallCompileInlineOrExpandedGoal => {
- try_or_throw!(self.machine_st, self.compile_inline_or_expanded_goal());
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteCompileInlineOrExpandedGoal => {
- try_or_throw!(self.machine_st, self.compile_inline_or_expanded_goal());
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallIsExpandedOrInlined => {
- self.machine_st.fail = !self.is_expanded_or_inlined();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteIsExpandedOrInlined => {
- self.machine_st.fail = !self.is_expanded_or_inlined();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallFastCallN(arity) => {
- let call_at_index = |wam: &mut Machine, name, arity, ptr| {
- wam.try_call(name, arity, ptr)
- };
+ &Instruction::CallRemoveModuleExports => {
+ try_or_throw!(self.machine_st, self.remove_module_exports());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteRemoveModuleExports => {
+ try_or_throw!(self.machine_st, self.remove_module_exports());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallAddNonCountedBacktracking => {
+ try_or_throw!(self.machine_st, self.add_non_counted_backtracking());
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteAddNonCountedBacktracking => {
+ try_or_throw!(self.machine_st, self.add_non_counted_backtracking());
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallPredicateDefined => {
+ self.machine_st.fail = !self.predicate_defined();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecutePredicateDefined => {
+ self.machine_st.fail = !self.predicate_defined();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallStripModule => {
+ self.strip_module();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteStripModule => {
+ self.strip_module();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallPrepareCallClause(arity) => {
+ try_or_throw!(self.machine_st, self.prepare_call_clause(arity));
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecutePrepareCallClause(arity) => {
+ try_or_throw!(self.machine_st, self.prepare_call_clause(arity));
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallCompileInlineOrExpandedGoal => {
+ try_or_throw!(self.machine_st, self.compile_inline_or_expanded_goal());
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteCompileInlineOrExpandedGoal => {
+ try_or_throw!(self.machine_st, self.compile_inline_or_expanded_goal());
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallIsExpandedOrInlined => {
+ self.machine_st.fail = !self.is_expanded_or_inlined();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteIsExpandedOrInlined => {
+ self.machine_st.fail = !self.is_expanded_or_inlined();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallFastCallN(arity) => {
+ let call_at_index =
+ |wam: &mut Machine, name, arity, ptr| wam.try_call(name, arity, ptr);
- try_or_throw!(self.machine_st, self.fast_call(arity, call_at_index));
+ try_or_throw!(self.machine_st, self.fast_call(arity, call_at_index));
- if self.machine_st.fail {
- self.machine_st.backtrack();
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ }
}
- }
- &Instruction::ExecuteFastCallN(arity) => {
- let call_at_index = |wam: &mut Machine, name, arity, ptr| {
- wam.try_execute(name, arity, ptr)
- };
+ &Instruction::ExecuteFastCallN(arity) => {
+ let call_at_index =
+ |wam: &mut Machine, name, arity, ptr| wam.try_execute(name, arity, ptr);
- try_or_throw!(self.machine_st, self.fast_call(arity, call_at_index));
+ try_or_throw!(self.machine_st, self.fast_call(arity, call_at_index));
- if self.machine_st.fail {
- self.machine_st.backtrack();
+ if self.machine_st.fail {
+ self.machine_st.backtrack();
+ }
}
- }
- &Instruction::CallGetClauseP => {
- let module_name = cell_as_atom!(self.deref_register(3));
+ &Instruction::CallGetClauseP => {
+ let module_name = cell_as_atom!(self.deref_register(3));
- let (n, p) = self.get_clause_p(module_name);
+ let (n, p) = self.get_clause_p(module_name);
- let r = self.machine_st.registers[2];
- let r = self.machine_st.store(self.machine_st.deref(r));
+ let r = self.machine_st.registers[2];
+ let r = self.machine_st.store(self.machine_st.deref(r));
- let h = self.machine_st.heap.len();
- self.machine_st.heap.extend(functor!(atom!("-"), [fixnum(n), fixnum(p)]));
+ let h = self.machine_st.heap.len();
+ self.machine_st
+ .heap
+ .extend(functor!(atom!("-"), [fixnum(n), fixnum(p)]));
- let r = r.as_var().unwrap();
- self.machine_st.bind(r, str_loc_as_cell!(h));
+ let r = r.as_var().unwrap();
+ self.machine_st.bind(r, str_loc_as_cell!(h));
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetClauseP => {
- let module_name = cell_as_atom!(self.deref_register(3));
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetClauseP => {
+ let module_name = cell_as_atom!(self.deref_register(3));
- let (n, p) = self.get_clause_p(module_name);
+ let (n, p) = self.get_clause_p(module_name);
- let r = self.machine_st.registers[2];
- let r = self.machine_st.store(self.machine_st.deref(r));
+ let r = self.machine_st.registers[2];
+ let r = self.machine_st.store(self.machine_st.deref(r));
- let h = self.machine_st.heap.len();
- self.machine_st.heap.extend(functor!(atom!("-"), [fixnum(n), fixnum(p)]));
+ let h = self.machine_st.heap.len();
+ self.machine_st
+ .heap
+ .extend(functor!(atom!("-"), [fixnum(n), fixnum(p)]));
- let r = r.as_var().unwrap();
- self.machine_st.bind(r, str_loc_as_cell!(h));
+ let r = r.as_var().unwrap();
+ self.machine_st.bind(r, str_loc_as_cell!(h));
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallInvokeClauseAtP => {
- let key_cell = self.machine_st.registers[1];
- let key = self.machine_st.name_and_arity_from_heap(key_cell).unwrap();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallInvokeClauseAtP => {
+ let key_cell = self.machine_st.registers[1];
+ let key = self.machine_st.name_and_arity_from_heap(key_cell).unwrap();
- let l = self.machine_st.registers[3];
- let l = self.machine_st.store(self.machine_st.deref(l));
+ let l = self.machine_st.registers[3];
+ let l = self.machine_st.store(self.machine_st.deref(l));
- let l = match Number::try_from(l) {
- Ok(Number::Fixnum(l)) => l.get_num() as usize,
- _ => unreachable!(),
- };
+ let l = match Number::try_from(l) {
+ Ok(Number::Fixnum(l)) => l.get_num() as usize,
+ _ => unreachable!(),
+ };
- let p = self.machine_st.registers[4];
- let p = self.machine_st.store(self.machine_st.deref(p));
+ let p = self.machine_st.registers[4];
+ let p = self.machine_st.store(self.machine_st.deref(p));
- let p = match Number::try_from(p) {
- Ok(Number::Fixnum(p)) => p.get_num() as usize,
- _ => unreachable!(),
- };
+ let p = match Number::try_from(p) {
+ Ok(Number::Fixnum(p)) => p.get_num() as usize,
+ _ => unreachable!(),
+ };
- let module_name = cell_as_atom!(self.deref_register(6));
+ let module_name = cell_as_atom!(self.deref_register(6));
- let compilation_target = match module_name {
- atom!("user") => CompilationTarget::User,
- _ => CompilationTarget::Module(module_name),
- };
+ let compilation_target = match module_name {
+ atom!("user") => CompilationTarget::User,
+ _ => CompilationTarget::Module(module_name),
+ };
- let skeleton = self.indices.get_predicate_skeleton_mut(
- &compilation_target,
- &key,
- ).unwrap();
+ let skeleton = self
+ .indices
+ .get_predicate_skeleton_mut(&compilation_target, &key)
+ .unwrap();
- match skeleton.target_pos_of_clause_clause_loc(l) {
- Some(n) => {
- let r = self.machine_st.store(self.machine_st.deref(
- self.machine_st.registers[5],
- ));
+ match skeleton.target_pos_of_clause_clause_loc(l) {
+ Some(n) => {
+ let r = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[5]));
- self.machine_st.unify_fixnum(Fixnum::build_with(n as i64), r);
+ self.machine_st
+ .unify_fixnum(Fixnum::build_with(n as i64), r);
+ }
+ None => {}
}
- None => {}
- }
- self.machine_st.call_at_index(2, p);
- }
- &Instruction::ExecuteInvokeClauseAtP => {
- let key_cell = self.machine_st.registers[1];
- let key = self.machine_st.name_and_arity_from_heap(key_cell).unwrap();
+ self.machine_st.call_at_index(2, p);
+ }
+ &Instruction::ExecuteInvokeClauseAtP => {
+ let key_cell = self.machine_st.registers[1];
+ let key = self.machine_st.name_and_arity_from_heap(key_cell).unwrap();
- let l = self.machine_st.registers[3];
- let l = self.machine_st.store(self.machine_st.deref(l));
+ let l = self.machine_st.registers[3];
+ let l = self.machine_st.store(self.machine_st.deref(l));
- let l = match Number::try_from(l) {
- Ok(Number::Fixnum(l)) => l.get_num() as usize,
- _ => unreachable!(),
- };
+ let l = match Number::try_from(l) {
+ Ok(Number::Fixnum(l)) => l.get_num() as usize,
+ _ => unreachable!(),
+ };
- let p = self.machine_st.registers[4];
- let p = self.machine_st.store(self.machine_st.deref(p));
+ let p = self.machine_st.registers[4];
+ let p = self.machine_st.store(self.machine_st.deref(p));
- let p = match Number::try_from(p) {
- Ok(Number::Fixnum(p)) => p.get_num() as usize,
- _ => unreachable!(),
- };
+ let p = match Number::try_from(p) {
+ Ok(Number::Fixnum(p)) => p.get_num() as usize,
+ _ => unreachable!(),
+ };
- let module_name = cell_as_atom!(self.deref_register(6));
+ let module_name = cell_as_atom!(self.deref_register(6));
- let compilation_target = match module_name {
- atom!("user") => CompilationTarget::User,
- _ => CompilationTarget::Module(module_name),
- };
+ let compilation_target = match module_name {
+ atom!("user") => CompilationTarget::User,
+ _ => CompilationTarget::Module(module_name),
+ };
- let skeleton = self.indices.get_predicate_skeleton_mut(
- &compilation_target,
- &key,
- ).unwrap();
+ let skeleton = self
+ .indices
+ .get_predicate_skeleton_mut(&compilation_target, &key)
+ .unwrap();
- match skeleton.target_pos_of_clause_clause_loc(l) {
- Some(n) => {
- let r = self.machine_st.store(self.machine_st.deref(
- self.machine_st.registers[5],
- ));
+ match skeleton.target_pos_of_clause_clause_loc(l) {
+ Some(n) => {
+ let r = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[5]));
- self.machine_st.unify_fixnum(Fixnum::build_with(n as i64), r);
+ self.machine_st
+ .unify_fixnum(Fixnum::build_with(n as i64), r);
+ }
+ None => {}
}
- None => {}
- }
- self.machine_st.execute_at_index(2, p);
- }
- &Instruction::CallGetFromAttributedVarList => {
- self.get_from_attributed_variable_list();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetFromAttributedVarList => {
- self.get_from_attributed_variable_list();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallPutToAttributedVarList => {
- self.put_to_attributed_variable_list();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecutePutToAttributedVarList => {
- self.put_to_attributed_variable_list();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallDeleteFromAttributedVarList => {
- self.delete_from_attributed_variable_list();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteDeleteFromAttributedVarList => {
- self.delete_from_attributed_variable_list();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
- }
- &Instruction::CallDeleteAllAttributesFromVar => {
- self.delete_all_attributes_from_var();
- self.machine_st.p += 1;
- }
- &Instruction::ExecuteDeleteAllAttributesFromVar => {
- self.delete_all_attributes_from_var();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallUnattributedVar => {
- self.machine_st.unattributed_var();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteUnattributedVar => {
- self.machine_st.unattributed_var();
- self.machine_st.p = self.machine_st.cp;
- }
- &Instruction::CallGetDBRefs => {
- self.get_db_refs();
- step_or_fail!(self, self.machine_st.p += 1);
- }
- &Instruction::ExecuteGetDBRefs => {
- self.get_db_refs();
- step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ self.machine_st.execute_at_index(2, p);
+ }
+ &Instruction::CallGetFromAttributedVarList => {
+ self.get_from_attributed_variable_list();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetFromAttributedVarList => {
+ self.get_from_attributed_variable_list();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallPutToAttributedVarList => {
+ self.put_to_attributed_variable_list();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecutePutToAttributedVarList => {
+ self.put_to_attributed_variable_list();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallDeleteFromAttributedVarList => {
+ self.delete_from_attributed_variable_list();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteDeleteFromAttributedVarList => {
+ self.delete_from_attributed_variable_list();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
+ &Instruction::CallDeleteAllAttributesFromVar => {
+ self.delete_all_attributes_from_var();
+ self.machine_st.p += 1;
+ }
+ &Instruction::ExecuteDeleteAllAttributesFromVar => {
+ self.delete_all_attributes_from_var();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallUnattributedVar => {
+ self.machine_st.unattributed_var();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteUnattributedVar => {
+ self.machine_st.unattributed_var();
+ self.machine_st.p = self.machine_st.cp;
+ }
+ &Instruction::CallGetDBRefs => {
+ self.get_db_refs();
+ step_or_fail!(self, self.machine_st.p += 1);
+ }
+ &Instruction::ExecuteGetDBRefs => {
+ self.get_db_refs();
+ step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
+ }
}
}
- }
- let interrupted = INTERRUPT.load(std::sync::atomic::Ordering::Relaxed);
-
- match INTERRUPT.compare_exchange(
- interrupted,
- false,
- std::sync::atomic::Ordering::Relaxed,
- std::sync::atomic::Ordering::Relaxed,
- ) {
- Ok(interruption) => {
- if interruption {
- self.machine_st.throw_interrupt_exception();
- self.machine_st.backtrack();
+ let interrupted = INTERRUPT.load(std::sync::atomic::Ordering::Relaxed);
+
+ match INTERRUPT.compare_exchange(
+ interrupted,
+ false,
+ std::sync::atomic::Ordering::Relaxed,
+ std::sync::atomic::Ordering::Relaxed,
+ ) {
+ Ok(interruption) => {
+ if interruption {
+ self.machine_st.throw_interrupt_exception();
+ self.machine_st.backtrack();
+ }
}
+ Err(_) => unreachable!(),
}
- Err(_) => unreachable!(),
- }
}
std::process::ExitCode::SUCCESS
use crate::types::*;
#[cfg(test)]
-use crate::heap_iter::{IterStackLoc, FocusedHeapIter, HeapOrStackTag};
+use crate::heap_iter::{FocusedHeapIter, HeapOrStackTag, IterStackLoc};
use core::marker::PhantomData;
match self.heap[self.current].get_tag() {
HeapCellValueTag::AttrVar => {
- if let Some(cell) = UMP::forward_attr_var(self) { return Some(cell); }
+ if let Some(cell) = UMP::forward_attr_var(self) {
+ return Some(cell);
+ }
if self.heap[self.next as usize].get_mark_bit() {
return Some(attr_var_as_cell!(self.current));
}
}
HeapCellValueTag::Var => {
- if let Some(cell) = self.forward_var() { return Some(cell); }
+ if let Some(cell) = self.forward_var() {
+ return Some(cell);
+ }
if self.heap[self.next as usize].get_mark_bit() {
return Some(heap_loc_as_cell!(self.current));
let arity = cell_as_atom_cell!(self.heap[h]).get_arity();
- for cell in &mut self.heap[h + 1 .. h + arity + 1] {
+ for cell in &mut self.heap[h + 1..h + arity + 1] {
cell.set_forwarding_bit(true);
}
let h = self.next as usize;
let cell = self.heap[h];
- if self.heap[h+1].get_forwarding_bit() {
+ if self.heap[h + 1].get_forwarding_bit() {
return self.backward_and_return();
}
if self.heap[h].get_tag() == HeapCellValueTag::PStr {
- let last_cell_loc = h+1;
+ let last_cell_loc = h + 1;
self.heap[last_cell_loc].set_forwarding_bit(true);
self.next = self.heap[last_cell_loc].get_value();
let cell = self.heap[h];
// mark the Fixnum offset.
- UMP::mark(self.heap, self.current+1);
+ UMP::mark(self.heap, self.current + 1);
- let last_cell_loc = h+1;
+ let last_cell_loc = h + 1;
if self.heap[last_cell_loc].get_forwarding_bit() {
return self.backward_and_return();
self.current -= 1;
- let temp = self.heap[self.current+1].get_value();
+ let temp = self.heap[self.current + 1].get_value();
- self.heap[self.current+1].set_value(self.next);
+ self.heap[self.current + 1].set_value(self.next);
self.next = self.heap[self.current].get_value();
self.heap[self.current].set_value(temp);
let b_atom = atom!("b");
wam.machine_st
- .heap
- .extend(functor!(f_atom, [atom(a_atom), atom(b_atom)]));
+ .heap
+ .extend(functor!(f_atom, [atom(a_atom), atom(b_atom)]));
mark_cells(&mut wam.machine_st.heap, str_loc_as_cell!(0));
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), atom_as_cell!(f_atom, 2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), atom_as_cell!(a_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), atom_as_cell!(b_atom));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ atom_as_cell!(f_atom, 2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ atom_as_cell!(a_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ atom_as_cell!(b_atom)
+ );
wam.machine_st.heap.clear();
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), atom_as_cell!(f_atom, 4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), atom_as_cell!(a_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), atom_as_cell!(b_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), atom_as_cell!(a_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), str_loc_as_cell!(0));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ atom_as_cell!(f_atom, 4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ atom_as_cell!(a_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ atom_as_cell!(b_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ atom_as_cell!(a_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ str_loc_as_cell!(0)
+ );
for cell in &mut wam.machine_st.heap {
cell.set_mark_bit(false);
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), str_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), atom_as_cell!(f_atom, 4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), atom_as_cell!(a_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), atom_as_cell!(b_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), atom_as_cell!(a_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), str_loc_as_cell!(1));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ str_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ atom_as_cell!(f_atom, 4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ atom_as_cell!(a_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ atom_as_cell!(b_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ atom_as_cell!(a_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ str_loc_as_cell!(1)
+ );
wam.machine_st.heap.clear();
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), heap_loc_as_cell!(0));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ heap_loc_as_cell!(0)
+ );
wam.machine_st.heap.clear();
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), list_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), atom_as_cell!(a_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), list_loc_as_cell!(3));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), atom_as_cell!(b_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), empty_list_as_cell!());
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ list_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ atom_as_cell!(a_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ list_loc_as_cell!(3)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ atom_as_cell!(b_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ empty_list_as_cell!()
+ );
wam.machine_st.heap.pop();
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), list_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), atom_as_cell!(a_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), list_loc_as_cell!(3));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), atom_as_cell!(b_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), heap_loc_as_cell!(0));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ list_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ atom_as_cell!(a_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ list_loc_as_cell!(3)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ atom_as_cell!(b_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ heap_loc_as_cell!(0)
+ );
for cell in &mut wam.machine_st.heap {
cell.set_mark_bit(false);
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), list_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), atom_as_cell!(a_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), list_loc_as_cell!(3));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ list_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ atom_as_cell!(a_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ list_loc_as_cell!(3)
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), stream_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), empty_list_as_cell!());
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ empty_list_as_cell!()
+ );
wam.machine_st.heap.clear();
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), heap_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), heap_loc_as_cell!(2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), heap_loc_as_cell!(3));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), heap_loc_as_cell!(0));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ heap_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ heap_loc_as_cell!(2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ heap_loc_as_cell!(3)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ heap_loc_as_cell!(0)
+ );
wam.machine_st.heap.clear();
// two-part complete string, then a three-part cyclic string
// involving an uncompacted list of chars.
- let pstr_var_cell = put_partial_string(&mut wam.machine_st.heap, "abc ", &mut wam.machine_st.atom_tbl);
+ let pstr_var_cell = put_partial_string(
+ &mut wam.machine_st.heap,
+ "abc ",
+ &mut wam.machine_st.atom_tbl,
+ );
let pstr_cell = wam.machine_st.heap[pstr_var_cell.get_value() as usize];
mark_cells(&mut wam.machine_st.heap, pstr_loc_as_cell!(0));
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), pstr_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), heap_loc_as_cell!(1));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ heap_loc_as_cell!(1)
+ );
wam.machine_st.heap.pop();
wam.machine_st.heap.push(pstr_loc_as_cell!(2));
- let pstr_second_var_cell = put_partial_string(&mut wam.machine_st.heap, "def", &mut wam.machine_st.atom_tbl);
+ let pstr_second_var_cell = put_partial_string(
+ &mut wam.machine_st.heap,
+ "def",
+ &mut wam.machine_st.atom_tbl,
+ );
let pstr_second_cell = wam.machine_st.heap[pstr_second_var_cell.get_value() as usize];
mark_cells(&mut wam.machine_st.heap, pstr_loc_as_cell!(0));
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), pstr_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_loc_as_cell!(2));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ pstr_loc_as_cell!(2)
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), pstr_second_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), heap_loc_as_cell!(3));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ heap_loc_as_cell!(3)
+ );
for cell in &mut wam.machine_st.heap {
cell.set_mark_bit(false);
wam.machine_st.heap.pop();
wam.machine_st.heap.push(pstr_loc_as_cell!(4));
wam.machine_st.heap.push(pstr_offset_as_cell!(0));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(2)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(2)));
mark_cells(&mut wam.machine_st.heap, pstr_loc_as_cell!(4));
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), pstr_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_loc_as_cell!(2));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ pstr_loc_as_cell!(2)
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), pstr_second_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), pstr_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), pstr_offset_as_cell!(0));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), fixnum_as_cell!(Fixnum::build_with(2)));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ pstr_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ pstr_offset_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ fixnum_as_cell!(Fixnum::build_with(2))
+ );
for cell in &mut wam.machine_st.heap {
cell.set_mark_bit(false);
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), pstr_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_loc_as_cell!(2));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ pstr_loc_as_cell!(2)
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), pstr_second_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), pstr_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), pstr_offset_as_cell!(0));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), fixnum_as_cell!(Fixnum::build_with(2)));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ pstr_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ pstr_offset_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ fixnum_as_cell!(Fixnum::build_with(2))
+ );
for cell in &mut wam.machine_st.heap {
cell.set_mark_bit(false);
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), pstr_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_loc_as_cell!(2));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ pstr_loc_as_cell!(2)
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), pstr_second_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), pstr_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), pstr_offset_as_cell!(0));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), fixnum_as_cell!(Fixnum::build_with(2)));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ pstr_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ pstr_offset_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ fixnum_as_cell!(Fixnum::build_with(2))
+ );
for cell in &mut wam.machine_st.heap {
cell.set_mark_bit(false);
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), pstr_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_loc_as_cell!(2));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ pstr_loc_as_cell!(2)
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), pstr_second_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), pstr_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), pstr_offset_as_cell!(0));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), fixnum_as_cell!(Fixnum::build_with(2)));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ pstr_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ pstr_offset_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ fixnum_as_cell!(Fixnum::build_with(2))
+ );
for cell in &mut wam.machine_st.heap {
cell.set_mark_bit(false);
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), pstr_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_loc_as_cell!(2));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ pstr_loc_as_cell!(2)
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), pstr_second_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), pstr_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), pstr_offset_as_cell!(0));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), fixnum_as_cell!(Fixnum::build_with(2)));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ pstr_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ pstr_offset_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ fixnum_as_cell!(Fixnum::build_with(2))
+ );
wam.machine_st.heap.truncate(4);
cell.set_mark_bit(false);
}
- wam.machine_st.heap.push(atom_as_cell!(atom!("irrelevant stuff")));
+ wam.machine_st
+ .heap
+ .push(atom_as_cell!(atom!("irrelevant stuff")));
wam.machine_st.heap.push(pstr_offset_as_cell!(0));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(2)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(2)));
wam.machine_st.heap[3] = pstr_loc_as_cell!(5);
assert!(wam.machine_st.heap[6].get_mark_bit());
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), pstr_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_loc_as_cell!(2));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ pstr_loc_as_cell!(2)
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), pstr_second_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), pstr_loc_as_cell!(5));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), atom_as_cell!(atom!("irrelevant stuff")));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), pstr_offset_as_cell!(0));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[6]), fixnum_as_cell!(Fixnum::build_with(2)));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ pstr_loc_as_cell!(5)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ atom_as_cell!(atom!("irrelevant stuff"))
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ pstr_offset_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[6]),
+ fixnum_as_cell!(Fixnum::build_with(2))
+ );
wam.machine_st.heap.clear();
- wam.machine_st.heap.push(atom_as_cell!(atom!("irrelevant stuff")));
+ wam.machine_st
+ .heap
+ .push(atom_as_cell!(atom!("irrelevant stuff")));
wam.machine_st.heap.push(pstr_cell);
wam.machine_st.heap.push(pstr_loc_as_cell!(4));
- wam.machine_st.heap.push(atom_as_cell!(atom!("irrelevant stuff")));
+ wam.machine_st
+ .heap
+ .push(atom_as_cell!(atom!("irrelevant stuff")));
wam.machine_st.heap.push(pstr_second_cell);
wam.machine_st.heap.push(pstr_loc_as_cell!(7));
- wam.machine_st.heap.push(atom_as_cell!(atom!("irrelevant stuff")));
+ wam.machine_st
+ .heap
+ .push(atom_as_cell!(atom!("irrelevant stuff")));
wam.machine_st.heap.push(pstr_offset_as_cell!(1));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(2)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(2)));
mark_cells(&mut wam.machine_st.heap, pstr_loc_as_cell!(7));
assert!(wam.machine_st.heap[7].get_mark_bit());
assert!(wam.machine_st.heap[8].get_mark_bit());
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), atom_as_cell!(atom!("irrelevant stuff")));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ atom_as_cell!(atom!("irrelevant stuff"))
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), pstr_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), atom_as_cell!(atom!("irrelevant stuff")));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ pstr_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ atom_as_cell!(atom!("irrelevant stuff"))
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), pstr_second_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), pstr_loc_as_cell!(7));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[6]), atom_as_cell!(atom!("irrelevant stuff")));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[7]), pstr_offset_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[8]), fixnum_as_cell!(Fixnum::build_with(2)));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ pstr_loc_as_cell!(7)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[6]),
+ atom_as_cell!(atom!("irrelevant stuff"))
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[7]),
+ pstr_offset_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[8]),
+ fixnum_as_cell!(Fixnum::build_with(2))
+ );
for cell in &mut wam.machine_st.heap {
cell.set_mark_bit(false);
assert!(!cell.get_forwarding_bit());
}
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), atom_as_cell!(atom!("irrelevant stuff")));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ atom_as_cell!(atom!("irrelevant stuff"))
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), pstr_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), atom_as_cell!(atom!("irrelevant stuff")));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ pstr_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ atom_as_cell!(atom!("irrelevant stuff"))
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), pstr_second_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), pstr_loc_as_cell!(7));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[6]), atom_as_cell!(atom!("irrelevant stuff")));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[7]), pstr_offset_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[8]), fixnum_as_cell!(Fixnum::build_with(2)));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ pstr_loc_as_cell!(7)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[6]),
+ atom_as_cell!(atom!("irrelevant stuff"))
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[7]),
+ pstr_offset_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[8]),
+ fixnum_as_cell!(Fixnum::build_with(2))
+ );
for cell in &mut wam.machine_st.heap {
cell.set_mark_bit(false);
assert!(!cell.get_forwarding_bit());
}
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), atom_as_cell!(atom!("irrelevant stuff")));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ atom_as_cell!(atom!("irrelevant stuff"))
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), pstr_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), atom_as_cell!(atom!("irrelevant stuff")));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ pstr_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ atom_as_cell!(atom!("irrelevant stuff"))
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), pstr_second_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), pstr_loc_as_cell!(7));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[6]), atom_as_cell!(atom!("irrelevant stuff")));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[7]), pstr_offset_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[8]), fixnum_as_cell!(Fixnum::build_with(2)));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ pstr_loc_as_cell!(7)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[6]),
+ atom_as_cell!(atom!("irrelevant stuff"))
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[7]),
+ pstr_offset_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[8]),
+ fixnum_as_cell!(Fixnum::build_with(2))
+ );
for cell in &mut wam.machine_st.heap {
cell.set_mark_bit(false);
assert!(!cell.get_forwarding_bit());
}
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), atom_as_cell!(atom!("irrelevant stuff")));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ atom_as_cell!(atom!("irrelevant stuff"))
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), pstr_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), atom_as_cell!(atom!("irrelevant stuff")));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ pstr_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ atom_as_cell!(atom!("irrelevant stuff"))
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), pstr_second_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), pstr_loc_as_cell!(7));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[6]), atom_as_cell!(atom!("irrelevant stuff")));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[7]), pstr_offset_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[8]), fixnum_as_cell!(Fixnum::build_with(2)));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ pstr_loc_as_cell!(7)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[6]),
+ atom_as_cell!(atom!("irrelevant stuff"))
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[7]),
+ pstr_offset_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[8]),
+ fixnum_as_cell!(Fixnum::build_with(2))
+ );
for cell in &mut wam.machine_st.heap {
cell.set_mark_bit(false);
assert!(!cell.get_forwarding_bit());
}
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), atom_as_cell!(atom!("irrelevant stuff")));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ atom_as_cell!(atom!("irrelevant stuff"))
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), pstr_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), atom_as_cell!(atom!("irrelevant stuff")));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ pstr_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ atom_as_cell!(atom!("irrelevant stuff"))
+ );
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), pstr_second_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), pstr_loc_as_cell!(7));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[6]), atom_as_cell!(atom!("irrelevant stuff")));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[7]), pstr_offset_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[8]), fixnum_as_cell!(Fixnum::build_with(2)));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ pstr_loc_as_cell!(7)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[6]),
+ atom_as_cell!(atom!("irrelevant stuff"))
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[7]),
+ pstr_offset_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[8]),
+ fixnum_as_cell!(Fixnum::build_with(2))
+ );
for cell in &mut wam.machine_st.heap {
cell.set_mark_bit(false);
wam.machine_st.heap.push(pstr_cell);
wam.machine_st.heap.push(pstr_loc_as_cell!(2));
wam.machine_st.heap.push(pstr_offset_as_cell!(0));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(3)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(3)));
wam.machine_st.heap.push(list_loc_as_cell!(5));
wam.machine_st.heap.push(pstr_loc_as_cell!(0));
wam.machine_st.heap.push(empty_list_as_cell!());
}
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), pstr_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_loc_as_cell!(2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), pstr_offset_as_cell!(0));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), fixnum_as_cell!(Fixnum::build_with(3)));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), list_loc_as_cell!(5));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), pstr_loc_as_cell!(0));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[6]), empty_list_as_cell!());
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ pstr_loc_as_cell!(2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ pstr_offset_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ fixnum_as_cell!(Fixnum::build_with(3))
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ list_loc_as_cell!(5)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ pstr_loc_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[6]),
+ empty_list_as_cell!()
+ );
wam.machine_st.heap.clear();
wam.machine_st.heap.push(pstr_cell);
wam.machine_st.heap.push(pstr_loc_as_cell!(2));
wam.machine_st.heap.push(pstr_offset_as_cell!(0));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(3)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(3)));
wam.machine_st.heap.push(list_loc_as_cell!(5));
wam.machine_st.heap.push(pstr_loc_as_cell!(0));
wam.machine_st.heap.push(heap_loc_as_cell!(4));
}
assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), pstr_cell);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), pstr_loc_as_cell!(2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), pstr_offset_as_cell!(0));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), fixnum_as_cell!(Fixnum::build_with(3)));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), list_loc_as_cell!(5));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), pstr_loc_as_cell!(0));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[6]), heap_loc_as_cell!(4));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ pstr_loc_as_cell!(2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ pstr_offset_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ fixnum_as_cell!(Fixnum::build_with(3))
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ list_loc_as_cell!(5)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ pstr_loc_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[6]),
+ heap_loc_as_cell!(4)
+ );
wam.machine_st.heap.clear();
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), heap_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), heap_loc_as_cell!(2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), heap_loc_as_cell!(3));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), heap_loc_as_cell!(3));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ heap_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ heap_loc_as_cell!(2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ heap_loc_as_cell!(3)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ heap_loc_as_cell!(3)
+ );
wam.machine_st.heap.clear();
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), list_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), list_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), list_loc_as_cell!(1));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ list_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ list_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ list_loc_as_cell!(1)
+ );
wam.machine_st.heap.clear();
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), list_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), heap_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), heap_loc_as_cell!(3));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), list_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), str_loc_as_cell!(6));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), heap_loc_as_cell!(8));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[6]), atom_as_cell!(f_atom, 1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[7]), heap_loc_as_cell!(11));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[8]), list_loc_as_cell!(9));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[9]), heap_loc_as_cell!(9));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[10]), empty_list_as_cell!());
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[11]), attr_var_as_cell!(11));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[12]), heap_loc_as_cell!(12));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ list_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ heap_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ heap_loc_as_cell!(3)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ list_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ str_loc_as_cell!(6)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ heap_loc_as_cell!(8)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[6]),
+ atom_as_cell!(f_atom, 1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[7]),
+ heap_loc_as_cell!(11)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[8]),
+ list_loc_as_cell!(9)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[9]),
+ heap_loc_as_cell!(9)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[10]),
+ empty_list_as_cell!()
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[11]),
+ attr_var_as_cell!(11)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[12]),
+ heap_loc_as_cell!(12)
+ );
// now populate the attributes list.
let clpz_atom = atom!("clpz");
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), list_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), heap_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), heap_loc_as_cell!(3));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), list_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), str_loc_as_cell!(6));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), heap_loc_as_cell!(8));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[6]), atom_as_cell!(f_atom, 1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[7]), heap_loc_as_cell!(11));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[8]), list_loc_as_cell!(9));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[9]), heap_loc_as_cell!(9));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[10]), empty_list_as_cell!());
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[11]), attr_var_as_cell!(11));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[12]), heap_loc_as_cell!(13));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[13]), list_loc_as_cell!(14));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[14]), str_loc_as_cell!(16));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[15]), heap_loc_as_cell!(19));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[16]), atom_as_cell!(clpz_atom, 2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[17]), atom_as_cell!(a_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[18]), atom_as_cell!(b_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[19]), list_loc_as_cell!(20));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[20]), str_loc_as_cell!(22));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[21]), empty_list_as_cell!());
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[22]), atom_as_cell!(p_atom, 1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[23]), heap_loc_as_cell!(23));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ list_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ heap_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ heap_loc_as_cell!(3)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ list_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ str_loc_as_cell!(6)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ heap_loc_as_cell!(8)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[6]),
+ atom_as_cell!(f_atom, 1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[7]),
+ heap_loc_as_cell!(11)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[8]),
+ list_loc_as_cell!(9)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[9]),
+ heap_loc_as_cell!(9)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[10]),
+ empty_list_as_cell!()
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[11]),
+ attr_var_as_cell!(11)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[12]),
+ heap_loc_as_cell!(13)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[13]),
+ list_loc_as_cell!(14)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[14]),
+ str_loc_as_cell!(16)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[15]),
+ heap_loc_as_cell!(19)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[16]),
+ atom_as_cell!(clpz_atom, 2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[17]),
+ atom_as_cell!(a_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[18]),
+ atom_as_cell!(b_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[19]),
+ list_loc_as_cell!(20)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[20]),
+ str_loc_as_cell!(22)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[21]),
+ empty_list_as_cell!()
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[22]),
+ atom_as_cell!(p_atom, 1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[23]),
+ heap_loc_as_cell!(23)
+ );
for cell in &mut wam.machine_st.heap {
cell.set_mark_bit(false);
assert_eq!(cell.get_mark_bit(), false);
}
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), list_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), heap_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), heap_loc_as_cell!(3));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), list_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), str_loc_as_cell!(6));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), heap_loc_as_cell!(8));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[6]), atom_as_cell!(f_atom, 1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[7]), heap_loc_as_cell!(11));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[8]), list_loc_as_cell!(9));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[9]), heap_loc_as_cell!(9));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[10]), empty_list_as_cell!());
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[11]), attr_var_as_cell!(11));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[12]), heap_loc_as_cell!(13));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[13]), list_loc_as_cell!(14));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[14]), str_loc_as_cell!(16));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[15]), heap_loc_as_cell!(19));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[16]), atom_as_cell!(clpz_atom, 2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[17]), atom_as_cell!(a_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[18]), atom_as_cell!(b_atom));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[19]), list_loc_as_cell!(20));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[20]), str_loc_as_cell!(22));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[21]), empty_list_as_cell!());
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[22]), atom_as_cell!(p_atom, 1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[23]), heap_loc_as_cell!(23));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[24]), heap_loc_as_cell!(5));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[25]), heap_loc_as_cell!(5));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[26]), list_loc_as_cell!(5));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ list_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ heap_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ heap_loc_as_cell!(3)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ list_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ str_loc_as_cell!(6)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ heap_loc_as_cell!(8)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[6]),
+ atom_as_cell!(f_atom, 1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[7]),
+ heap_loc_as_cell!(11)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[8]),
+ list_loc_as_cell!(9)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[9]),
+ heap_loc_as_cell!(9)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[10]),
+ empty_list_as_cell!()
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[11]),
+ attr_var_as_cell!(11)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[12]),
+ heap_loc_as_cell!(13)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[13]),
+ list_loc_as_cell!(14)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[14]),
+ str_loc_as_cell!(16)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[15]),
+ heap_loc_as_cell!(19)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[16]),
+ atom_as_cell!(clpz_atom, 2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[17]),
+ atom_as_cell!(a_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[18]),
+ atom_as_cell!(b_atom)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[19]),
+ list_loc_as_cell!(20)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[20]),
+ str_loc_as_cell!(22)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[21]),
+ empty_list_as_cell!()
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[22]),
+ atom_as_cell!(p_atom, 1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[23]),
+ heap_loc_as_cell!(23)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[24]),
+ heap_loc_as_cell!(5)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[25]),
+ heap_loc_as_cell!(5)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[26]),
+ list_loc_as_cell!(5)
+ );
wam.machine_st.heap.clear();
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(0)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(0)));
mark_cells(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), str_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), atom_as_cell!(atom!("g"), 2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), heap_loc_as_cell!(0));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), atom_as_cell!(atom!("y")));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), atom_as_cell!(atom!("="), 2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), atom_as_cell!(atom!("X")));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[6]), heap_loc_as_cell!(0));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[7]), list_loc_as_cell!(8));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[8]), str_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[9]), empty_list_as_cell!());
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ str_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ atom_as_cell!(atom!("g"), 2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ heap_loc_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ atom_as_cell!(atom!("y"))
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ atom_as_cell!(atom!("="), 2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ atom_as_cell!(atom!("X"))
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[6]),
+ heap_loc_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[7]),
+ list_loc_as_cell!(8)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[8]),
+ str_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[9]),
+ empty_list_as_cell!()
+ );
wam.machine_st.heap.clear();
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), atom_as_cell!(atom!("f"), 2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), heap_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), heap_loc_as_cell!(1));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ atom_as_cell!(atom!("f"), 2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ heap_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ heap_loc_as_cell!(1)
+ );
wam.machine_st.heap.clear();
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), list_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), empty_list_as_cell!());
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), list_loc_as_cell!(3));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), heap_loc_as_cell!(0));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), heap_loc_as_cell!(0));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), empty_list_as_cell!());
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[6]), heap_loc_as_cell!(2));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ list_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ empty_list_as_cell!()
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ list_loc_as_cell!(3)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ heap_loc_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ heap_loc_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ empty_list_as_cell!()
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[6]),
+ heap_loc_as_cell!(2)
+ );
wam.machine_st.heap.clear();
wam.machine_st.heap.push(list_loc_as_cell!(7));
wam.machine_st.heap.push(heap_loc_as_cell!(0));
- wam.machine_st.heap.push(list_loc_as_cell!(3)); // A = [B|[]].
- wam.machine_st.heap.push(list_loc_as_cell!(5)); // B = [A|A].
+ wam.machine_st.heap.push(list_loc_as_cell!(3)); // A = [B|[]].
+ wam.machine_st.heap.push(list_loc_as_cell!(5)); // B = [A|A].
wam.machine_st.heap.push(empty_list_as_cell!());
wam.machine_st.heap.push(heap_loc_as_cell!(2));
wam.machine_st.heap.push(heap_loc_as_cell!(2));
assert!(wam.machine_st.heap[0].get_mark_bit());
assert!(!wam.machine_st.heap[1].get_mark_bit());
- all_cells_marked_and_unforwarded(&wam.machine_st.heap[2 ..]);
-
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), list_loc_as_cell!(7));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), heap_loc_as_cell!(0));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), list_loc_as_cell!(3));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), list_loc_as_cell!(5));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), empty_list_as_cell!());
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), heap_loc_as_cell!(2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[6]), heap_loc_as_cell!(2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[7]), empty_list_as_cell!());
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[8]), heap_loc_as_cell!(3));
+ all_cells_marked_and_unforwarded(&wam.machine_st.heap[2..]);
+
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ list_loc_as_cell!(7)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ heap_loc_as_cell!(0)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ list_loc_as_cell!(3)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ list_loc_as_cell!(5)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ empty_list_as_cell!()
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ heap_loc_as_cell!(2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[6]),
+ heap_loc_as_cell!(2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[7]),
+ empty_list_as_cell!()
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[8]),
+ heap_loc_as_cell!(3)
+ );
wam.machine_st.heap.clear();
wam.machine_st.heap.push(str_loc_as_cell!(1));
wam.machine_st.heap.push(atom_as_cell!(atom!("+"), 2));
wam.machine_st.heap.push(str_loc_as_cell!(4));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(2)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(2)));
wam.machine_st.heap.push(atom_as_cell!(atom!("-"), 2));
wam.machine_st.heap.push(str_loc_as_cell!(7));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(1)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(1)));
wam.machine_st.heap.push(atom_as_cell!(atom!("+"), 2));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(3)));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(4)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(3)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(4)));
mark_cells(&mut wam.machine_st.heap, heap_loc_as_cell!(0));
all_cells_marked_and_unforwarded(&wam.machine_st.heap);
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[0]), str_loc_as_cell!(1));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[1]), atom_as_cell!(atom!("+"), 2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[2]), str_loc_as_cell!(4));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[3]), fixnum_as_cell!(Fixnum::build_with(2)));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[4]), atom_as_cell!(atom!("-"), 2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[5]), str_loc_as_cell!(7));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[6]), fixnum_as_cell!(Fixnum::build_with(1)));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[7]), atom_as_cell!(atom!("+"), 2));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[8]), fixnum_as_cell!(Fixnum::build_with(3)));
- assert_eq!(unmark_cell_bits!(wam.machine_st.heap[9]), fixnum_as_cell!(Fixnum::build_with(4)));
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[0]),
+ str_loc_as_cell!(1)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[1]),
+ atom_as_cell!(atom!("+"), 2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[2]),
+ str_loc_as_cell!(4)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[3]),
+ fixnum_as_cell!(Fixnum::build_with(2))
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[4]),
+ atom_as_cell!(atom!("-"), 2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[5]),
+ str_loc_as_cell!(7)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[6]),
+ fixnum_as_cell!(Fixnum::build_with(1))
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[7]),
+ atom_as_cell!(atom!("+"), 2)
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[8]),
+ fixnum_as_cell!(Fixnum::build_with(3))
+ );
+ assert_eq!(
+ unmark_cell_bits!(wam.machine_st.heap[9]),
+ fixnum_as_cell!(Fixnum::build_with(4))
+ );
}
}
match op_decl.insert_into_op_dir(wam_op_dir) {
Some(op_desc) => {
- payload.retraction_info.push_record(RetractionRecord::ReplacedUserOp(
- *op_decl,
- op_desc,
- ));
+ payload
+ .retraction_info
+ .push_record(RetractionRecord::ReplacedUserOp(*op_decl, op_desc));
payload.module_op_exports.push((*op_decl, Some(op_desc)));
}
None => {
- payload.retraction_info.push_record(RetractionRecord::AddedUserOp(*op_decl));
+ payload
+ .retraction_info
+ .push_record(RetractionRecord::AddedUserOp(*op_decl));
payload.module_op_exports.push((*op_decl, None));
}
}
let compilation_target = payload.compilation_target;
- add_op_decl(&mut payload.retraction_info, &compilation_target, module_op_dir, op_decl);
+ add_op_decl(
+ &mut payload.retraction_info,
+ &compilation_target,
+ module_op_dir,
+ op_decl,
+ );
}
pub(super) fn add_op_decl(
match op_decl.insert_into_op_dir(op_dir) {
Some(op_desc) => match &compilation_target {
CompilationTarget::User => {
- retraction_info.push_record(RetractionRecord::ReplacedUserOp(
- *op_decl,
- op_desc,
- ));
+ retraction_info.push_record(RetractionRecord::ReplacedUserOp(*op_decl, op_desc));
}
CompilationTarget::Module(ref module_name) => {
retraction_info.push_record(RetractionRecord::ReplacedModuleOp(
retraction_info.push_record(RetractionRecord::AddedUserOp(*op_decl));
}
CompilationTarget::Module(ref module_name) => {
- retraction_info.push_record(RetractionRecord::AddedModuleOp(
- *module_name,
- *op_decl,
- ));
+ retraction_info
+ .push_record(RetractionRecord::AddedModuleOp(*module_name, *op_decl));
}
},
}
}
}
ModuleExport::OpDecl(ref op_decl) => {
- add_op_decl(&mut payload.retraction_info, compilation_target, op_dir, op_decl);
+ add_op_decl(
+ &mut payload.retraction_info,
+ compilation_target,
+ op_dir,
+ op_decl,
+ );
}
}
}
}
}
ModuleExport::OpDecl(ref op_decl) => {
- add_op_decl_as_module_export::<LS>(
- payload,
- op_dir,
- wam_op_dir,
- op_decl,
- );
+ add_op_decl_as_module_export::<LS>(payload, op_dir, wam_op_dir, op_decl);
}
}
}
let key = (*name, *arity);
if let Some(meta_specs) = imported_module.meta_predicates.get(&key) {
- wam_prelude.indices.meta_predicates.insert(key.clone(), meta_specs.clone());
+ wam_prelude
+ .indices
+ .meta_predicates
+ .insert(key.clone(), meta_specs.clone());
}
if let Some(src_code_index) = imported_module.code_dir.get(&key) {
let arena = &mut LS::machine_st(payload).arena;
- let target_code_index = wam_prelude.indices.code_dir
+ let target_code_index = wam_prelude
+ .indices
+ .code_dir
.entry(key.clone())
.or_insert_with(|| CodeIndex::new(IndexPtr::undefined(), arena))
.clone();
}
}
ModuleExport::OpDecl(ref op_decl) => {
- add_op_decl_as_module_export::<LS>(
- payload,
- op_dir,
- wam_op_dir,
- op_decl,
- );
+ add_op_decl_as_module_export::<LS>(payload, op_dir, wam_op_dir, op_decl);
}
}
}
mut clause_target_poses: Vec<Option<usize>>,
is_dynamic: bool,
) {
- let old_compilation_target = mem::replace(
- &mut self.payload.compilation_target,
- compilation_target,
- );
+ let old_compilation_target =
+ mem::replace(&mut self.payload.compilation_target, compilation_target);
while let Some(target_pos_opt) = clause_target_poses.pop() {
match target_pos_opt {
let old_index_ptr = code_index.replace(IndexPtr::undefined());
- self.payload.retraction_info
+ self.payload
+ .retraction_info
.push_record(RetractionRecord::ReplacedModulePredicate(
module_name,
*key,
}
for (key, skeleton) in removed_module.extensible_predicates.drain(..) {
- self.payload.retraction_info
+ self.payload
+ .retraction_info
.push_record(RetractionRecord::RemovedSkeleton(
CompilationTarget::Module(module_name),
key,
));
}
- self.wam_prelude.indices.modules.insert(module_name, removed_module);
+ self.wam_prelude
+ .indices
+ .modules
+ .insert(module_name, removed_module);
}
pub(super) fn remove_module_exports(&mut self, module_name: Atom) {
(Some(module_code_index), Some(target_code_index))
if module_code_index.get() == target_code_index.get() =>
{
- let old_index_ptr = target_code_index.replace(IndexPtr::undefined());
- retraction_info.push_record(predicate_retractor(*key, old_index_ptr));
+ let old_index_ptr =
+ target_code_index.replace(IndexPtr::undefined());
+ retraction_info
+ .push_record(predicate_retractor(*key, old_index_ptr));
}
_ => {}
}
}
ModuleExport::OpDecl(op_decl) => {
- let op_dir_value_opt =
- op_dir.remove(&(op_decl.name, fixity(op_decl.op_desc.get_spec() as u32)));
+ let op_dir_value_opt = op_dir
+ .remove(&(op_decl.name, fixity(op_decl.op_desc.get_spec() as u32)));
if let Some(op_desc) = op_dir_value_opt {
retraction_info.push_record(op_retractor(*op_decl, op_desc));
RetractionRecord::ReplacedUserOp,
);
}
- CompilationTarget::Module(target_module_name)
- if target_module_name != module_name =>
- {
+ CompilationTarget::Module(target_module_name) if target_module_name != module_name => {
let predicate_retractor = |key, index_ptr| {
RetractionRecord::ReplacedModulePredicate(module_name, key, index_ptr)
};
RetractionRecord::ReplacedModuleOp(module_name, op_decl, op_desc)
};
- if let Some(module) = self.wam_prelude.indices.modules.get_mut(&target_module_name) {
+ if let Some(module) = self
+ .wam_prelude
+ .indices
+ .modules
+ .get_mut(&target_module_name)
+ {
remove_module_exports(
&removed_module,
&mut module.code_dir,
CompilationTarget::Module(_) => {}
};
- self.wam_prelude.indices.modules.insert(module_name, removed_module);
+ self.wam_prelude
+ .indices
+ .modules
+ .insert(module_name, removed_module);
}
fn get_or_insert_local_code_index(
Some(ref mut module) => module
.code_dir
.entry(key)
- .or_insert_with(|| CodeIndex::new(
- IndexPtr::undefined(),
- &mut LS::machine_st(&mut self.payload).arena,
- ))
+ .or_insert_with(|| {
+ CodeIndex::new(
+ IndexPtr::undefined(),
+ &mut LS::machine_st(&mut self.payload).arena,
+ )
+ })
.clone(),
None => {
self.add_dynamically_generated_module(module_name);
Some(ref mut module) => module
.code_dir
.entry(key)
- .or_insert_with(|| CodeIndex::new(
- IndexPtr::undefined(),
- &mut LS::machine_st(&mut self.payload).arena,
- ))
+ .or_insert_with(|| {
+ CodeIndex::new(
+ IndexPtr::undefined(),
+ &mut LS::machine_st(&mut self.payload).arena,
+ )
+ })
.clone(),
None => {
unreachable!()
ClauseType::Named(arity, name, _) => {
let payload_compilation_target = self.payload.compilation_target;
- let idx = self.get_or_insert_code_index(
- (name, arity),
- payload_compilation_target,
- );
+ let idx = self.get_or_insert_code_index((name, arity), payload_compilation_target);
ClauseType::Named(arity, name, idx)
}
}
pub(super) fn get_meta_specs(&self, name: Atom, arity: usize) -> Option<&Vec<MetaSpec>> {
- self.wam_prelude
- .indices
- .get_meta_predicate_spec(
- name,
- arity,
- &self.payload.compilation_target,
- )
+ self.wam_prelude.indices.get_meta_predicate_spec(
+ name,
+ arity,
+ &self.payload.compilation_target,
+ )
}
pub(super) fn add_meta_predicate_record(
.insert(key, meta_specs)
{
Some(old_meta_specs) => {
- self.payload.retraction_info
- .push_record(RetractionRecord::ReplacedMetaPredicate(
+ self.payload.retraction_info.push_record(
+ RetractionRecord::ReplacedMetaPredicate(
module_name,
key.0,
old_meta_specs,
- ));
+ ),
+ );
}
None => {
- self.payload.retraction_info
- .push_record(RetractionRecord::AddedMetaPredicate(
- module_name,
- key,
- ));
+ self.payload
+ .retraction_info
+ .push_record(RetractionRecord::AddedMetaPredicate(module_name, key));
}
}
}
None => {
self.add_dynamically_generated_module(module_name);
- if let Some(module) = self.wam_prelude.indices.modules.get_mut(&module_name) {
+ if let Some(module) = self.wam_prelude.indices.modules.get_mut(&module_name)
+ {
module.meta_predicates.insert(key.clone(), meta_specs);
} else {
unreachable!()
}
- self.payload.retraction_info
- .push_record(RetractionRecord::AddedMetaPredicate(
- module_name.clone(),
- key,
- ));
+ self.payload.retraction_info.push_record(
+ RetractionRecord::AddedMetaPredicate(module_name.clone(), key),
+ );
}
}
}
&mut module.meta_predicates,
);
- self.payload.retraction_info
+ self.payload
+ .retraction_info
.push_record(RetractionRecord::AddedModule(module_name.clone()));
- self.wam_prelude.indices.modules.insert(module_name.clone(), module);
+ self.wam_prelude
+ .indices
+ .modules
+ .insert(module_name.clone(), module);
}
fn import_builtins_in_module(
if is_dynamic {
let clause_clause_compilation_target = match compilation_target {
- CompilationTarget::User => {
- CompilationTarget::Module(atom!("builtins"))
- }
+ CompilationTarget::User => CompilationTarget::Module(atom!("builtins")),
module => module.clone(),
};
}
}
- self.payload.retraction_info
+ self.payload
+ .retraction_info
.push_record(RetractionRecord::ReplacedModule(
old_module_decl,
listing_src.clone(),
)?;
}
CompilationTarget::Module(ref defining_module_name) => {
- match self.wam_prelude.indices.modules.get_mut(defining_module_name) {
+ match self
+ .wam_prelude
+ .indices
+ .modules
+ .get_mut(defining_module_name)
+ {
Some(ref mut target_module) => {
import_module_exports_into_module::<LS>(
&mut self.payload,
let payload_compilation_target = self.payload.compilation_target;
let result = match &payload_compilation_target {
- CompilationTarget::User => {
- import_qualified_module_exports::<LS>(
- &mut self.payload,
- &payload_compilation_target,
- &module,
- &exports,
- &mut self.wam_prelude,
- )
- }
+ CompilationTarget::User => import_qualified_module_exports::<LS>(
+ &mut self.payload,
+ &payload_compilation_target,
+ &module,
+ &exports,
+ &mut self.wam_prelude,
+ ),
CompilationTarget::Module(ref defining_module_name) => {
- match self.wam_prelude.indices.modules.get_mut(defining_module_name) {
+ match self
+ .wam_prelude
+ .indices
+ .modules
+ .get_mut(defining_module_name)
+ {
Some(ref mut target_module) => {
import_qualified_module_exports_into_module::<LS>(
&mut self.payload,
&mut self.wam_prelude.indices.op_dir,
)
}
- None => {
- Err(SessionError::ModuleCannotImportSelf(module_name))
- }
+ None => Err(SessionError::ModuleCannotImportSelf(module_name)),
}
}
};
self.wam_prelude.indices.modules.insert(module_name, module);
result
} else {
- Err(SessionError::ExistenceError(ExistenceError::Module(module_name)))
+ Err(SessionError::ExistenceError(ExistenceError::Module(
+ module_name,
+ )))
}
}
let file = File::open(&path_buf)?;
(
- Stream::from_file_as_input(filename, file, &mut LS::machine_st(&mut self.payload).arena),
+ Stream::from_file_as_input(
+ filename,
+ file,
+ &mut LS::machine_st(&mut self.payload).arena,
+ ),
ListingSource::File(filename, path_buf),
)
}
if let Some(ref module) = self.wam_prelude.indices.modules.get(&library) {
if let ListingSource::DynamicallyGenerated = &module.listing_src {
(
- Stream::from_static_string(*code, &mut LS::machine_st(&mut self.payload).arena),
+ Stream::from_static_string(
+ *code,
+ &mut LS::machine_st(&mut self.payload).arena,
+ ),
ListingSource::User,
)
} else {
}
} else {
(
- Stream::from_static_string(*code, &mut LS::machine_st(&mut self.payload).arena),
+ Stream::from_static_string(
+ *code,
+ &mut LS::machine_st(&mut self.payload).arena,
+ ),
ListingSource::User,
)
}
);
let subloader: Loader<'_, BootstrappingLoadState> = Loader {
- payload: BootstrappingLoadState(
- LoadStatePayload::new(self.wam_prelude.code.len(), term_stream)
- ),
+ payload: BootstrappingLoadState(LoadStatePayload::new(
+ self.wam_prelude.code.len(),
+ term_stream,
+ )),
wam_prelude: MachinePreludeView {
indices: self.wam_prelude.indices,
code: self.wam_prelude.code,
let file = File::open(&path_buf)?;
(
- Stream::from_file_as_input(filename, file, &mut LS::machine_st(&mut self.payload).arena),
+ Stream::from_file_as_input(
+ filename,
+ file,
+ &mut LS::machine_st(&mut self.payload).arena,
+ ),
ListingSource::File(filename, path_buf),
)
}
return self.import_qualified_module(library, exports);
} else {
(
- Stream::from_static_string(*code, &mut LS::machine_st(&mut self.payload).arena),
+ Stream::from_static_string(
+ *code,
+ &mut LS::machine_st(&mut self.payload).arena,
+ ),
ListingSource::User,
)
}
);
let subloader: Loader<'_, BootstrappingLoadState> = Loader {
- payload: BootstrappingLoadState(
- LoadStatePayload::new(self.wam_prelude.code.len(), term_stream),
- ),
+ payload: BootstrappingLoadState(LoadStatePayload::new(
+ self.wam_prelude.code.len(),
+ term_stream,
+ )),
wam_prelude: MachinePreludeView {
indices: self.wam_prelude.indices,
code: self.wam_prelude.code,
pub type LiveLoadState = LoadStatePayload<LiveTermStream>;
-pub struct BootstrappingLoadState<'a>(
- pub LoadStatePayload<BootstrappingTermStream<'a>>
-);
+pub struct BootstrappingLoadState<'a>(pub LoadStatePayload<BootstrappingTermStream<'a>>);
impl<'a> Deref for BootstrappingLoadState<'a> {
type Target = LoadStatePayload<BootstrappingTermStream<'a>>;
pub trait LoadState<'a>: Sized {
type Evacuable;
type TS: TermStream;
- type LoaderFieldType: DerefMut<Target=LoadStatePayload<Self::TS>>;
+ type LoaderFieldType: DerefMut<Target = LoadStatePayload<Self::TS>>;
- fn new(machine_st: &'a mut MachineState, payload: LoadStatePayload<Self::TS>) -> Self::LoaderFieldType;
+ fn new(
+ machine_st: &'a mut MachineState,
+ payload: LoadStatePayload<Self::TS>,
+ ) -> Self::LoaderFieldType;
fn evacuate(loader: Loader<'a, Self>) -> Result<Self::Evacuable, SessionError>;
fn should_drop_load_state(loader: &Loader<'a, Self>) -> bool;
fn reset_machine(loader: &mut Loader<'a, Self>);
type Evacuable = TypedArenaPtr<LiveLoadState>;
#[inline(always)]
- fn new(machine_st: &'a mut MachineState, payload: LoadStatePayload<Self::TS>) -> Self::LoaderFieldType {
+ fn new(
+ machine_st: &'a mut MachineState,
+ payload: LoadStatePayload<Self::TS>,
+ ) -> Self::LoaderFieldType {
let load_state = arena_alloc!(payload, &mut machine_st.arena);
- LiveLoadAndMachineState { load_state, machine_st }
+ LiveLoadAndMachineState {
+ load_state,
+ machine_st,
+ }
}
#[inline(always)]
fn evacuate(mut loader: Loader<'a, Self>) -> Result<Self::Evacuable, SessionError> {
- loader.payload.load_state.set_tag(ArenaHeaderTag::InactiveLoadState);
+ loader
+ .payload
+ .load_state
+ .set_tag(ArenaHeaderTag::InactiveLoadState);
Ok(loader.payload.load_state)
}
}
if let Some(builtins) = loader.wam_prelude.indices.modules.get(&atom!("builtins")) {
- if builtins.module_decl.exports.contains(&ModuleExport::PredicateKey(key)) {
+ if builtins
+ .module_decl
+ .exports
+ .contains(&ModuleExport::PredicateKey(key))
+ {
return Err(SessionError::CannotOverwriteBuiltIn(key));
}
}
let repo_len = loader.wam_prelude.code.len();
- loader
- .payload
- .retraction_info
- .reset(repo_len);
+ loader.payload.retraction_info.reset(repo_len);
loader.remove_module_op_exports();
type Evacuable = ();
#[inline(always)]
- fn new(machine_st: &'a mut MachineState, payload: LoadStatePayload<Self::TS>) -> Self::LoaderFieldType {
- InlineLoadState { machine_st, payload }
+ fn new(
+ machine_st: &'a mut MachineState,
+ payload: LoadStatePayload<Self::TS>,
+ ) -> Self::LoaderFieldType {
+ InlineLoadState {
+ machine_st,
+ payload,
+ }
}
fn evacuate(_loader: Loader<'a, Self>) -> Result<Self::Evacuable, SessionError> {
- Ok(())
+ Ok(())
}
#[inline(always)]
fn should_drop_load_state(_loader: &Loader<'a, Self>) -> bool {
- false
+ false
}
#[inline(always)]
- fn reset_machine(_loader: &mut Loader<'a, Self>) {
- }
+ fn reset_machine(_loader: &mut Loader<'a, Self>) {}
#[inline(always)]
fn machine_st(load_state: &mut Self::LoaderFieldType) -> &mut MachineState {
atom!("user") => {
self.wam_prelude.indices.meta_predicates.remove(&key);
}
- _ => match self.wam_prelude.indices.modules.get_mut(&target_module_name) {
+ _ => match self
+ .wam_prelude
+ .indices
+ .modules
+ .get_mut(&target_module_name)
+ {
Some(ref mut module) => {
module.meta_predicates.remove(&key);
}
.meta_predicates
.insert((name, meta_specs.len()), meta_specs);
}
- _ => match self.wam_prelude.indices.modules.get_mut(&target_module_name) {
+ _ => match self
+ .wam_prelude
+ .indices
+ .modules
+ .get_mut(&target_module_name)
+ {
Some(ref mut module) => {
module
.meta_predicates
}
RetractionRecord::ReplacedChoiceOffset(instr_loc, offset) => {
match self.wam_prelude.code[instr_loc] {
- Instruction::TryMeElse(ref mut o) |
- Instruction::RetryMeElse(ref mut o) |
- Instruction::DefaultRetryMeElse(ref mut o) => {
+ Instruction::TryMeElse(ref mut o)
+ | Instruction::RetryMeElse(ref mut o)
+ | Instruction::DefaultRetryMeElse(ref mut o) => {
*o = offset;
}
_ => {
}
RetractionRecord::ReplacedSwitchOnTermVarIndex(index_loc, old_v) => {
match self.wam_prelude.code[index_loc] {
- Instruction::IndexingCode(ref mut indexing_code) => match &mut indexing_code[0] {
- IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(
- _,
- ref mut v,
- ..,
- )) => {
- *v = old_v;
+ Instruction::IndexingCode(ref mut indexing_code) => {
+ match &mut indexing_code[0] {
+ IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(
+ _,
+ ref mut v,
+ ..,
+ )) => {
+ *v = old_v;
+ }
+ _ => {}
}
- _ => {}
- },
+ }
_ => {}
}
}
.get_predicate_skeleton_mut(&compilation_target, &key)
{
Some(skeleton) => {
- if let Some(removed_clauses) = &mut skeleton.core.retracted_dynamic_clauses {
+ if let Some(removed_clauses) =
+ &mut skeleton.core.retracted_dynamic_clauses
+ {
let clause_index_info = removed_clauses.pop().unwrap();
skeleton
RetractionRecord::RemovedSkeleton(compilation_target, key, skeleton) => {
match compilation_target {
CompilationTarget::User => {
- self.wam_prelude.indices.extensible_predicates.insert(key, skeleton);
+ self.wam_prelude
+ .indices
+ .extensible_predicates
+ .insert(key, skeleton);
}
CompilationTarget::Module(module_name) => {
- if let Some(module) = self.wam_prelude.indices.modules.get_mut(&module_name) {
+ if let Some(module) =
+ self.wam_prelude.indices.modules.get_mut(&module_name)
+ {
module.extensible_predicates.insert(key, skeleton);
}
}
}
RetractionRecord::ReplacedDynamicElseOffset(instr_loc, next) => {
match self.wam_prelude.code[instr_loc] {
- Instruction::DynamicElse(
- _,
- _,
- NextOrFail::Next(ref mut o),
- )
- | Instruction::DynamicInternalElse(
- _,
- _,
- NextOrFail::Next(ref mut o),
- ) => {
+ Instruction::DynamicElse(_, _, NextOrFail::Next(ref mut o))
+ | Instruction::DynamicInternalElse(_, _, NextOrFail::Next(ref mut o)) => {
*o = next;
}
_ => {}
}
RetractionRecord::AppendedNextOrFail(instr_loc, fail) => {
match self.wam_prelude.code[instr_loc] {
- Instruction::DynamicElse(
- _,
- _,
- ref mut next_or_fail,
- )
- | Instruction::DynamicInternalElse(
- _,
- _,
- ref mut next_or_fail,
- ) => {
+ Instruction::DynamicElse(_, _, ref mut next_or_fail)
+ | Instruction::DynamicInternalElse(_, _, ref mut next_or_fail) => {
*next_or_fail = fail;
}
_ => {}
fn add_clause_clause(&mut self, term: Term) -> Result<(), CompilationError> {
match term {
- Term::Clause(_, atom!(":-"), mut terms) if terms.len() == 2 =>
- {
+ Term::Clause(_, atom!(":-"), mut terms) if terms.len() == 2 => {
let body = terms.pop().unwrap();
let head = terms.pop().unwrap();
match &compilation_target {
CompilationTarget::User => {
- match self
- .wam_prelude
- .indices
- .extensible_predicates
- .get_mut(&key)
- {
+ match self.wam_prelude.indices.extensible_predicates.get_mut(&key) {
Some(skeleton) => {
if !*flag_accessor(&mut skeleton.core) {
*flag_accessor(&mut skeleton.core) = true;
- self.payload.retraction_info.push_record(retraction_fn(
- compilation_target,
- key,
- ));
+ self.payload
+ .retraction_info
+ .push_record(retraction_fn(compilation_target, key));
}
}
None => {
let mut skeleton = PredicateSkeleton::new();
*flag_accessor(&mut skeleton.core) = true;
- self.add_extensible_predicate(
- key,
- skeleton,
- CompilationTarget::User,
- );
+ self.add_extensible_predicate(key, skeleton, CompilationTarget::User);
} else {
throw_permission_error = true;
}
if !*flag_accessor(&mut skeleton.core) {
*flag_accessor(&mut skeleton.core) = true;
- self.payload.retraction_info.push_record(retraction_fn(
- compilation_target,
- key,
- ));
+ self.payload
+ .retraction_info
+ .push_record(retraction_fn(compilation_target, key));
}
}
None => {
let mut skeleton = PredicateSkeleton::new();
*flag_accessor(&mut skeleton.core) = true;
- self.add_extensible_predicate(
- key,
- skeleton,
- compilation_target,
- );
+ self.add_extensible_predicate(key, skeleton, compilation_target);
} else {
throw_permission_error = true;
}
let mut skeleton = PredicateSkeleton::new();
*flag_accessor(&mut skeleton.core) = true;
- self.add_extensible_predicate(
- key,
- skeleton,
- compilation_target,
- );
+ self.add_extensible_predicate(key, skeleton, compilation_target);
}
}
}
match payload_compilation_target {
CompilationTarget::User => {
- match self
- .wam_prelude
- .indices
- .get_local_predicate_skeleton_mut(
- payload_compilation_target,
- compilation_target,
- listing_src_file_name,
- key,
- ) {
+ match self.wam_prelude.indices.get_local_predicate_skeleton_mut(
+ payload_compilation_target,
+ compilation_target,
+ listing_src_file_name,
+ key,
+ ) {
Some(skeleton) => {
if !*flag_accessor(skeleton) {
*flag_accessor(skeleton) = true;
let mut skeleton = LocalPredicateSkeleton::new();
*flag_accessor(&mut skeleton) = true;
- self.add_local_extensible_predicate(
- compilation_target,
- key,
- skeleton,
- );
+ self.add_local_extensible_predicate(compilation_target, key, skeleton);
}
}
}
let mut skeleton = LocalPredicateSkeleton::new();
*flag_accessor(&mut skeleton) = true;
- self.add_local_extensible_predicate(
- compilation_target,
- key,
- skeleton,
- );
+ self.add_local_extensible_predicate(compilation_target, key, skeleton);
}
}
}
let is_dynamic = self
.wam_prelude
.indices
- .get_predicate_skeleton(
- &predicates_compilation_target,
- &(predicate_name, arity),
- )
+ .get_predicate_skeleton(&predicates_compilation_target, &(predicate_name, arity))
.map(|skeleton| skeleton.core.is_dynamic)
.unwrap_or(false);
let predicates_compilation_target = self.payload.predicates.compilation_target;
let listing_src_file_name = self.listing_src_file_name();
- let clause_locs = match self
- .wam_prelude
- .indices
- .get_local_predicate_skeleton_mut(
- payload_compilation_target,
- predicates_compilation_target,
- listing_src_file_name,
- *key,
- ) {
+ let clause_locs = match self.wam_prelude.indices.get_local_predicate_skeleton_mut(
+ payload_compilation_target,
+ predicates_compilation_target,
+ listing_src_file_name,
+ *key,
+ ) {
Some(skeleton) if !skeleton.clause_clause_locs.is_empty() => {
mem::replace(&mut skeleton.clause_clause_locs, VecDeque::new())
}
),
);
- self.retract_local_clauses_impl(
- predicates_compilation_target,
- *key,
- &clause_locs,
- );
+ self.retract_local_clauses_impl(predicates_compilation_target, *key, &clause_locs);
if is_dynamic {
let clause_clause_compilation_target = match predicates_compilation_target {
impl<'a> MachinePreludeView<'a> {
#[inline]
- pub(super) fn composite_op_dir(&self, compilation_target: &CompilationTarget) -> CompositeOpDir {
+ pub(super) fn composite_op_dir(
+ &self,
+ compilation_target: &CompilationTarget,
+ ) -> CompositeOpDir {
match compilation_target {
CompilationTarget::User => CompositeOpDir::new(&self.indices.op_dir, None),
CompilationTarget::Module(ref module_name) => {
}
impl MachineState {
- pub(super) fn read_term_from_heap(&mut self, term_addr: HeapCellValue) -> Result<Term, SessionError> {
+ pub(super) fn read_term_from_heap(
+ &mut self,
+ term_addr: HeapCellValue,
+ ) -> Result<Term, SessionError> {
let mut term_stack = vec![];
let mut iter = stackful_post_order_iter(&mut self.heap, &mut self.stack, term_addr);
}
pub(crate) fn load_compiled_library(&mut self) -> CallResult {
- let library = cell_as_atom!(
- self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1]))
- );
+ let library = cell_as_atom!(self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[1])));
if let Some(module) = self.indices.modules.get(&library) {
if let ListingSource::DynamicallyGenerated = module.listing_src {
}
pub(crate) fn declare_module(&mut self) -> CallResult {
- let module_name = cell_as_atom!(
- self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1]))
- );
+ let module_name = cell_as_atom!(self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[1])));
let mut loader = self.loader_from_heap_evacuable(temp_v!(3));
let arity = self.deref_register(3);
let arity = match Number::try_from(arity) {
- Ok(Number::Integer(n)) if &*n >= &Integer::from(0) && &*n <= &Integer::from(MAX_ARITY) => Ok(n.to_usize().unwrap()),
+ Ok(Number::Integer(n))
+ if &*n >= &Integer::from(0) && &*n <= &Integer::from(MAX_ARITY) =>
+ {
+ Ok(n.to_usize().unwrap())
+ }
Ok(Number::Fixnum(n)) if n.get_num() >= 0 && n.get_num() <= MAX_ARITY as i64 => {
Ok(usize::try_from(n.get_num()).unwrap())
}
}
pub(crate) fn add_goal_expansion_clause(&mut self) -> CallResult {
- let target_module_name = cell_as_atom!(
- self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1]))
- );
+ let target_module_name = cell_as_atom!(self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[1])));
let mut loader = self.loader_from_heap_evacuable(temp_v!(3));
if let Some(indexing_term) = indexing_arg {
if let Some(indexing_name) = indexing_term.name() {
- loader.wam_prelude
+ loader
+ .wam_prelude
.indices
.goal_expansion_indices
.insert((indexing_name, indexing_term.arity()));
&'a mut self,
r: RegType,
) -> Loader<'a, LiveLoadAndMachineState<'a>> {
- let mut load_state = cell_as_load_state_payload!(
- self.machine_st.store(self.machine_st.deref(self.machine_st[r]))
- );
+ let mut load_state = cell_as_load_state_payload!(self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r])));
load_state.set_tag(ArenaHeaderTag::LiveLoadState);
let (wam_prelude, machine_st) = self.prelude_view_and_machine_st();
Loader {
- payload: LiveLoadAndMachineState { load_state, machine_st },
+ payload: LiveLoadAndMachineState {
+ load_state,
+ machine_st,
+ },
wam_prelude,
}
}
#[inline]
pub(crate) fn push_load_state_payload(&mut self) {
let payload = arena_alloc!(
- LoadStatePayload::new(
- self.code.len(),
- LiveTermStream::new(ListingSource::User),
- ),
+ LoadStatePayload::new(self.code.len(), LiveTermStream::new(ListingSource::User),),
&mut self.machine_st.arena
);
let var = self.machine_st.deref(self.machine_st.registers[1]);
- self.machine_st.bind(
- var.as_var().unwrap(),
- typed_arena_ptr_as_cell!(payload),
- );
+ self.machine_st
+ .bind(var.as_var().unwrap(), typed_arena_ptr_as_cell!(payload));
}
#[inline]
pub(crate) fn pop_load_state_payload(&mut self) {
- let load_state_payload = self.machine_st.store(
- self.machine_st.deref(self.machine_st.registers[1])
- );
+ let load_state_payload = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[1]));
// unlike in loader_from_heap_evacuable,
// pop_load_state_payload is allowed to fail to find a
2,
)?;
- let path = cell_as_atom!(
- self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2]))
- );
+ let path = cell_as_atom!(self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[2])));
- self.load_contexts.push(LoadContext::new(path.as_str(), stream));
+ self.load_contexts
+ .push(LoadContext::new(path.as_str(), stream));
Ok(())
}
result: Result<TypedArenaPtr<LiveLoadState>, SessionError>,
) -> CallResult {
match result {
- Ok(_payload) => {
- Ok(())
- }
+ Ok(_payload) => Ok(()),
Err(e) => {
let err = self.machine_st.session_error(e);
let stub = functor_stub(atom!("load"), 1);
}
pub(crate) fn scoped_clause_to_evacuable(&mut self) -> CallResult {
- let module_name = cell_as_atom!(
- self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1]))
- );
+ let module_name = cell_as_atom!(self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[1])));
let loader = self.loader_from_heap_evacuable(temp_v!(3));
let path_str = load_context.path.to_str().unwrap();
let path_atom = self.machine_st.atom_tbl.build_with(path_str);
- self.machine_st.unify_atom(path_atom, self.machine_st.registers[1]);
+ self.machine_st
+ .unify_atom(path_atom, self.machine_st.registers[1]);
} else {
self.machine_st.fail = true;
}
let file_name_str = file_name.to_str().unwrap();
let file_name_atom = self.machine_st.atom_tbl.build_with(file_name_str);
- self.machine_st.unify_atom(file_name_atom, self.machine_st.registers[1]);
+ self.machine_st
+ .unify_atom(file_name_atom, self.machine_st.registers[1]);
return;
}
_ => {
let directory_str = directory.to_str().unwrap();
let directory_atom = self.machine_st.atom_tbl.build_with(directory_str);
- self.machine_st.unify_atom(directory_atom, self.machine_st.registers[1]);
+ self.machine_st
+ .unify_atom(directory_atom, self.machine_st.registers[1]);
return;
}
}
_ => CompilationTarget::Module(module_name),
};
- let stub_gen = || {
- match append_or_prepend {
- AppendOrPrepend::Append => functor_stub(atom!("assertz"), 1),
- AppendOrPrepend::Prepend => functor_stub(atom!("asserta"), 1),
- }
+ let stub_gen = || match append_or_prepend {
+ AppendOrPrepend::Append => functor_stub(atom!("assertz"), 1),
+ AppendOrPrepend::Prepend => functor_stub(atom!("asserta"), 1),
};
let head = self.deref_register(2);
loader.payload.compilation_target = compilation_target;
- let head = LiveLoadAndMachineState::machine_st(&mut loader.payload).read_term_from_heap(head)?;
+ let head = LiveLoadAndMachineState::machine_st(&mut loader.payload)
+ .read_term_from_heap(head)?;
let name = if let Some(name) = head.name() {
name
let is_builtin = loader.wam_prelude.indices.builtin_property((name, arity));
let is_dynamic_predicate = loader
- .wam_prelude
- .indices
- .is_dynamic_predicate(
- module_name,
- (name, arity),
- );
-
- let no_such_predicate =
- if !is_dynamic_predicate && !is_builtin {
- let idx_tag = loader
- .wam_prelude
- .indices
- .get_predicate_code_index(
- name,
- arity,
- module_name,
- )
- .map(|code_idx| code_idx.get_tag())
- .unwrap_or(IndexPtrTag::DynamicUndefined);
+ .wam_prelude
+ .indices
+ .is_dynamic_predicate(module_name, (name, arity));
- idx_tag == IndexPtrTag::DynamicUndefined || idx_tag == IndexPtrTag::Undefined
- } else if is_builtin {
- return Err(SessionError::CannotOverwriteBuiltIn((name, arity)));
- } else {
- is_dynamic_predicate
- };
+ let no_such_predicate = if !is_dynamic_predicate && !is_builtin {
+ let idx_tag = loader
+ .wam_prelude
+ .indices
+ .get_predicate_code_index(name, arity, module_name)
+ .map(|code_idx| code_idx.get_tag())
+ .unwrap_or(IndexPtrTag::DynamicUndefined);
+
+ idx_tag == IndexPtrTag::DynamicUndefined || idx_tag == IndexPtrTag::Undefined
+ } else if is_builtin {
+ return Err(SessionError::CannotOverwriteBuiltIn((name, arity)));
+ } else {
+ is_dynamic_predicate
+ };
if !no_such_predicate {
LiveLoadAndMachineState::machine_st(&mut loader.payload).fail = true;
match compile_assert() {
Ok(_) => Ok(()),
Err(SessionError::CompilationError(
- CompilationError::InvalidRuleHead |
- CompilationError::InadmissibleFact
+ CompilationError::InvalidRuleHead | CompilationError::InadmissibleFact,
)) => {
- let err = self.machine_st.type_error(
- ValidType::Callable,
- self.machine_st.registers[2],
- );
+ let err = self
+ .machine_st
+ .type_error(ValidType::Callable, self.machine_st.registers[2]);
Err(self.machine_st.error_form(err, stub_gen()))
}
- Err(SessionError::CompilationError(
- CompilationError::InadmissibleQueryTerm
- )) => {
- let err = self.machine_st.type_error(
- ValidType::Callable,
- self.machine_st.registers[3],
- );
+ Err(SessionError::CompilationError(CompilationError::InadmissibleQueryTerm)) => {
+ let err = self
+ .machine_st
+ .type_error(ValidType::Callable, self.machine_st.registers[3]);
Err(self.machine_st.error_form(err, stub_gen()))
}
}
pub(crate) fn abolish_clause(&mut self) -> CallResult {
- let module_name = cell_as_atom!(
- self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1]))
- );
+ let module_name = cell_as_atom!(self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[1])));
let key = self
.machine_st
};
let mut abolish_clause = || {
- let mut loader: Loader<'_, LiveLoadAndMachineState<'_>>
- = Loader::new(self, LiveTermStream::new(ListingSource::User));
+ let mut loader: Loader<'_, LiveLoadAndMachineState<'_>> =
+ Loader::new(self, LiveTermStream::new(ListingSource::User));
loader.payload.compilation_target = compilation_target;
.remove_predicate_skeleton(
&clause_clause_compilation_target,
&(atom!("$clause"), 2),
- ).unwrap();
+ )
+ .unwrap();
- let result = skeleton.core
+ let result = skeleton
+ .core
.clause_clause_locs
.iter()
.map(|clause_clause_loc| {
})
.collect();
- loader.add_extensible_predicate(
- key,
- skeleton,
- compilation_target,
- );
+ loader.add_extensible_predicate(key, skeleton, compilation_target);
loader.add_extensible_predicate(
(atom!("$clause"), 2),
);
result
- }).unwrap();
+ })
+ .unwrap();
- loader.wam_prelude
+ loader
+ .wam_prelude
.indices
.remove_predicate_skeleton(&compilation_target, &key);
- let mut code_index = loader
- .get_or_insert_code_index(key, compilation_target);
+ let mut code_index = loader.get_or_insert_code_index(key, compilation_target);
code_index.set(IndexPtr::undefined());
_ => unreachable!(),
};
- let module_name = cell_as_atom!(
- self.machine_st.store(self.machine_st.deref(self.machine_st.registers[4]))
- );
+ let module_name = cell_as_atom!(self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[4])));
let compilation_target = match module_name {
atom!("user") => CompilationTarget::User,
}
pub(crate) fn is_consistent_with_term_queue(&mut self) -> CallResult {
- let module_name = cell_as_atom!(
- self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1]))
- );
+ let module_name = cell_as_atom!(self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[1])));
let key = self
.machine_st
LiveLoadAndMachineState::machine_st(&mut loader.payload).fail =
(!loader.payload.predicates.is_empty()
- && loader.payload.predicates.compilation_target != compilation_target)
- || !key.is_consistent(&loader.payload.predicates);
+ && loader.payload.predicates.compilation_target != compilation_target)
+ || !key.is_consistent(&loader.payload.predicates);
let result = LiveLoadAndMachineState::evacuate(loader);
self.restore_load_state_payload(result)
}
pub(crate) fn remove_module_exports(&mut self) -> CallResult {
- let module_name = cell_as_atom!(
- self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1]))
- );
+ let module_name = cell_as_atom!(self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[1])));
let mut loader = self.loader_from_heap_evacuable(temp_v!(2));
}
pub(crate) fn meta_predicate_property(&mut self) {
- let module_name = cell_as_atom!(
- self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1]))
- );
+ let module_name = cell_as_atom!(self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[1])));
let (predicate_name, arity) = self
.machine_st
Some(meta_specs) => {
let term_loc = self.machine_st.heap.len();
- self.machine_st.heap.push(atom_as_cell!(predicate_name, arity));
- self.machine_st.heap.extend(
- meta_specs.iter().map(|meta_spec| match meta_spec {
+ self.machine_st
+ .heap
+ .push(atom_as_cell!(predicate_name, arity));
+ self.machine_st
+ .heap
+ .extend(meta_specs.iter().map(|meta_spec| match meta_spec {
MetaSpec::Minus => atom_as_cell!(atom!("+")),
MetaSpec::Plus => atom_as_cell!(atom!("-")),
MetaSpec::Either => atom_as_cell!(atom!("?")),
MetaSpec::RequiresExpansionWithArgument(ref arg_num) => {
fixnum_as_cell!(Fixnum::build_with(*arg_num as i64))
}
- })
- );
+ }));
let heap_loc = self.machine_st.heap.len();
- self.machine_st.heap.push(atom_as_cell!(atom!("meta_predicate"), 1));
+ self.machine_st
+ .heap
+ .push(atom_as_cell!(atom!("meta_predicate"), 1));
self.machine_st.heap.push(str_loc_as_cell!(term_loc));
- unify!(self.machine_st, str_loc_as_cell!(heap_loc), self.machine_st.registers[4]);
+ unify!(
+ self.machine_st,
+ str_loc_as_cell!(heap_loc),
+ self.machine_st.registers[4]
+ );
}
None => {
self.machine_st.fail = true;
}
pub(crate) fn dynamic_property(&mut self) {
- let module_name = cell_as_atom!(
- self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1]))
- );
+ let module_name = cell_as_atom!(self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[1])));
let key = self
.machine_st
}
pub(crate) fn multifile_property(&mut self) {
- let module_name = cell_as_atom!(
- self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1]))
- );
+ let module_name = cell_as_atom!(self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[1])));
let key = self
.machine_st
}
pub(crate) fn discontiguous_property(&mut self) {
- let module_name = cell_as_atom!(
- self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1]))
- );
+ let module_name = cell_as_atom!(self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[1])));
let key = self
.machine_st
InCharacter,
Integer,
List,
- #[allow(unused)] Number,
+ #[allow(unused)]
+ Number,
Pair,
// PredicateIndicator,
// Variable
#[inline(always)]
pub(super) fn functor_stub(name: Atom, arity: usize) -> FunctorStub {
- [atom_as_cell!(atom!("/"), 2),
- atom_as_cell!(name),
- fixnum_as_cell!(Fixnum::build_with(arity as i64))]
+ [
+ atom_as_cell!(atom!("/"), 2),
+ atom_as_cell!(name),
+ fixnum_as_cell!(Fixnum::build_with(arity as i64)),
+ ]
}
impl MachineState {
pub(super) fn session_error(&mut self, err: SessionError) -> MachineError {
match err {
SessionError::CannotOverwriteBuiltIn(key) => {
- // SessionError::CannotOverwriteImport(pred_atom) => {
+ // SessionError::CannotOverwriteImport(pred_atom) => {
self.permission_error(
Permission::Modify,
atom!("static_procedure"),
- functor_stub(key.0, key.1).into_iter().collect::<MachineStub>(),
+ functor_stub(key.0, key.1)
+ .into_iter()
+ .collect::<MachineStub>(),
)
}
SessionError::ExistenceError(err) => self.existence_error(err),
}
SessionError::NamelessEntry => {
let error_atom = atom!("nameless_procedure");
- self.permission_error(Permission::Create, atom!("static_procedure"), functor!(error_atom))
+ self.permission_error(
+ Permission::Create,
+ atom!("static_procedure"),
+ functor!(error_atom),
+ )
}
SessionError::OpIsInfixAndPostFix(op) => {
self.permission_error(Permission::Create, atom!("operator"), functor!(op))
#[cfg(feature = "ffi")]
pub(super) fn ffi_error(&mut self, err: FFIError) -> MachineError {
- let error_atom = match err {
- FFIError::ValueCast => atom!("value_cast"),
- FFIError::ValueDontFit => atom!("value_dont_fit"),
- FFIError::InvalidFFIType => atom!("invalid_ffi_type"),
- FFIError::InvalidStructName => atom!("invalid_struct_name"),
- FFIError::FunctionNotFound => atom!("function_not_found"),
- FFIError::StructNotFound => atom!("struct_not_found"),
- };
- let stub = functor!(atom!("ffi_error"),[atom(error_atom)]);
-
- MachineError {
- stub,
- location: None,
- from: ErrorProvenance::Constructed,
- }
+ let error_atom = match err {
+ FFIError::ValueCast => atom!("value_cast"),
+ FFIError::ValueDontFit => atom!("value_dont_fit"),
+ FFIError::InvalidFFIType => atom!("invalid_ffi_type"),
+ FFIError::InvalidStructName => atom!("invalid_struct_name"),
+ FFIError::FunctionNotFound => atom!("function_not_found"),
+ FFIError::StructNotFound => atom!("struct_not_found"),
+ };
+ let stub = functor!(atom!("ffi_error"), [atom(error_atom)]);
+
+ MachineError {
+ stub,
+ location: None,
+ from: ErrorProvenance::Constructed,
+ }
}
pub(super) fn error_form(&mut self, err: MachineError, src: FunctorStub) -> MachineStub {
&CompilationError::ExpectedRel => {
functor!(atom!("expected_relation"))
}
- &CompilationError::InadmissibleFact => { // TODO: type_error(callable, _).
+ &CompilationError::InadmissibleFact => {
+ // TODO: type_error(callable, _).
functor!(atom!("inadmissible_fact"))
}
- &CompilationError::InadmissibleQueryTerm => { // TODO: type_error(callable, _).
+ &CompilationError::InadmissibleQueryTerm => {
+ // TODO: type_error(callable, _).
functor!(atom!("inadmissible_query_term"))
}
&CompilationError::InconsistentEntry => {
Cyclic(usize),
EmptyList,
NotList(usize, HeapCellValue), // the list length until the second argument in the heap
- PartialList(usize, Ref), // the list length (up to max), and an offset into the heap.
- ProperList(usize), // the list length.
+ PartialList(usize, Ref), // the list length (up to max), and an offset into the heap.
+ ProperList(usize), // the list length.
PStrLocation(usize, usize, usize), // list length (up to max), the heap address of the PStr, the offset
- UntouchedList(usize, usize), // list length (up to max), the address of an uniterated Addr::Lis(address).
+ UntouchedList(usize, usize), // list length (up to max), the address of an uniterated Addr::Lis(address).
UntouchedCStr(Atom, usize),
}
match BrentAlgState::detect_cycles(&self.heap, list) {
CycleSearchResult::PartialList(..) => {
let err = self.instantiation_error();
- return Err(self.error_form(err, stub_gen()))
+ return Err(self.error_form(err, stub_gen()));
}
CycleSearchResult::NotList(..) | CycleSearchResult::Cyclic(_) => {
let err = self.type_error(ValidType::List, list);
use crate::arena::*;
use crate::atom_table::*;
use crate::forms::*;
-use crate::machine::ClauseType;
use crate::machine::loader::*;
use crate::machine::machine_state::*;
use crate::machine::streams::Stream;
+use crate::machine::ClauseType;
use fxhash::FxBuildHasher;
use indexmap::{IndexMap, IndexSet};
-use modular_bitfield::{BitfieldSpecifier, bitfield};
use modular_bitfield::specifiers::*;
+use modular_bitfield::{bitfield, BitfieldSpecifier};
use std::cmp::Ordering;
use std::collections::BTreeSet;
#[derive(Debug, Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct IndexPtr {
pub p: B56,
- #[allow(unused)] m: bool,
+ #[allow(unused)]
+ m: bool,
pub tag: IndexPtrTag,
}
#[derive(Debug, Clone, Copy, Ord, Hash, PartialOrd, Eq, PartialEq)]
pub struct CodeIndex(TypedArenaPtr<IndexPtr>);
-#[cfg(target_pointer_width="32")]
+#[cfg(target_pointer_width = "32")]
const_assert!(std::mem::align_of::<CodeIndex>() == 4);
-#[cfg(target_pointer_width="64")]
+#[cfg(target_pointer_width = "64")]
const_assert!(std::mem::align_of::<CodeIndex>() == 8);
impl Deref for CodeIndex {
let (name, arity) = key;
if !ClauseType::is_inbuilt(name, arity) {
- self.modules.get(&(atom!("builtins")))
+ self.modules
+ .get(&(atom!("builtins")))
.map(|module| module.code_dir.contains_key(&(name, arity)))
.unwrap_or(false)
} else {
}
}
- pub(crate) fn is_dynamic_predicate(
- &self,
- module_name: Atom,
- key: PredicateKey,
- ) -> bool {
+ pub(crate) fn is_dynamic_predicate(&self, module_name: Atom, key: PredicateKey) -> bool {
match module_name {
atom!("user") => self
.extensible_predicates
use crate::forms::*;
use crate::heap_iter::*;
use crate::heap_print::*;
-use crate::machine::Machine;
use crate::machine::attributed_variables::*;
use crate::machine::copier::*;
use crate::machine::heap::*;
use crate::machine::machine_indices::*;
use crate::machine::stack::*;
use crate::machine::streams::*;
+use crate::machine::Machine;
use crate::parser::ast::*;
use crate::read::TermWriteResult;
use crate::types::*;
pub(super) s_offset: usize,
pub(super) p: usize,
pub(super) oip: u32, // first internal code ptr
- pub(super) iip : u32, // second internal code ptr
+ pub(super) iip: u32, // second internal code ptr
pub(super) b: usize,
pub(super) b0: usize,
pub(super) e: usize,
pub(super) trail: Vec<TrailEntry>,
pub(super) tr: usize,
pub(super) hb: usize,
- pub(super) block: usize, // an offset into the OR stack.
+ pub(super) block: usize, // an offset into the OR stack.
pub(super) scc_block: usize, // an offset into the OR stack for setup_call_cleanup/3.
pub(super) ball: Ball,
pub(super) ball_stack: Vec<Ball>, // save current ball before jumping via, e.g., verify_attr interrupt.
pub(super) fn copy_and_align(&self, h: usize) -> Heap {
let diff = self.boundary as i64 - h as i64;
- self.stub.iter().cloned().map(|heap_value| {
- heap_value - diff
- }).collect()
+ self.stub
+ .iter()
+ .cloned()
+ .map(|heap_value| heap_value - diff)
+ .collect()
}
}
if self.cwil.count == *limit {
self.cwil.inference_limit_exceeded = true;
- return Err(
- functor!(atom!("inference_limit_exceeded"), [fixnum(bp)])
- );
+ return Err(functor!(atom!("inference_limit_exceeded"), [fixnum(bp)]));
} else {
self.cwil.count += 1;
}
}
#[allow(dead_code)]
- pub(super) fn try_char_list(&mut self, addrs: Vec<HeapCellValue>) -> Result<String, MachineError> {
+ pub(super) fn try_char_list(
+ &mut self,
+ addrs: Vec<HeapCellValue>,
+ ) -> Result<String, MachineError> {
let mut chars = String::new();
for addr in addrs {
mut var_list: Vec<(VarKey, HeapCellValue, usize)>,
singleton_var_list: Vec<HeapCellValue>,
) -> CallResult {
- var_list.sort_by(|(_,_,idx_1),(_,_,idx_2)| idx_1.cmp(idx_2));
+ var_list.sort_by(|(_, _, idx_1), (_, _, idx_2)| idx_1.cmp(idx_2));
let list_of_var_eqs = push_var_eq_functors(
&mut self.heap,
- var_list.iter().filter_map(|(var_name, var,_)| if var_name.is_anon() { None } else { Some((var_name,var)) }),
+ var_list.iter().filter_map(|(var_name, var, _)| {
+ if var_name.is_anon() {
+ None
+ } else {
+ Some((var_name, var))
+ }
+ }),
&mut self.atom_tbl,
);
let singleton_addr = self.registers[3];
- let singletons_offset = heap_loc_as_cell!(
- iter_to_heap_list(&mut self.heap, singleton_var_list.into_iter())
- );
+ let singletons_offset = heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.heap,
+ singleton_var_list.into_iter()
+ ));
unify_fn!(*self, singletons_offset, singleton_addr);
}
let vars_addr = self.registers[4];
- let vars_offset = heap_loc_as_cell!(
- iter_to_heap_list(&mut self.heap, var_list.into_iter().map(|(_,cell,_)| cell))
- );
+ let vars_offset = heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.heap,
+ var_list.into_iter().map(|(_, cell, _)| cell)
+ ));
unify_fn!(*self, vars_offset, vars_addr);
}
let var_names_addr = self.registers[5];
- let var_names_offset = heap_loc_as_cell!(
- iter_to_heap_list(&mut self.heap, list_of_var_eqs.into_iter())
- );
+ let var_names_offset = heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.heap,
+ list_of_var_eqs.into_iter()
+ ));
Ok(unify_fn!(*self, var_names_offset, var_names_addr))
}
let singleton_var_list = push_var_eq_functors(
&mut self.heap,
- term_write_result.var_dict.iter().filter(|(var_name, binding)| {
- if var_name.is_anon() {
- return false;
- }
+ term_write_result
+ .var_dict
+ .iter()
+ .filter(|(var_name, binding)| {
+ if var_name.is_anon() {
+ return false;
+ }
- if let Some(r) = binding.as_var() {
- *singleton_var_set.get(&r).unwrap_or(&false)
- } else {
- false
- }
- }),
+ if let Some(r) = binding.as_var() {
+ *singleton_var_set.get(&r).unwrap_or(&false)
+ } else {
+ false
+ }
+ }),
&mut self.atom_tbl,
);
self.write_read_term_options(var_list, singleton_var_list)
}
- pub fn read_term_from_user_input_eof_handler(&mut self, stream: Stream) -> Result<OnEOF, MachineStub> {
- self.eof_action(
- self.registers[2],
- stream,
- atom!("read_term"),
- 3,
- )?;
+ pub fn read_term_from_user_input_eof_handler(
+ &mut self,
+ stream: Stream,
+ ) -> Result<OnEOF, MachineStub> {
+ self.eof_action(self.registers[2], stream, atom!("read_term"), 3)?;
if stream.options().eof_action() == EOFAction::Reset {
if self.fail == false {
// Safety: the atom_tbl lives for the lifetime of the machine, as does the helper, so the ptr
// will always be valid.
- pub fn read_term_from_user_input(&mut self, stream: Stream, indices: &mut IndexStore) -> CallResult {
+ pub fn read_term_from_user_input(
+ &mut self,
+ stream: Stream,
+ indices: &mut IndexStore,
+ ) -> CallResult {
let atoms_ptr = (&self.atom_tbl.table) as *const indexmap::IndexSet<Atom>;
if let Stream::Readline(ptr) = stream {
stream.set_past_end_of_stream(true);
return Ok(OnEOF::Return);
} else if stream.past_end_of_stream() {
- self.eof_action(
- self.registers[2],
- stream,
- atom!("read_term"),
- 3,
- )?;
+ self.eof_action(self.registers[2], stream, atom!("read_term"), 3)?;
if stream.options().eof_action() == EOFAction::Reset {
if self.fail == false {
match &err {
CompilationError::ParserError(e) if e.is_unexpected_eof() => {
match eof_handler(self, stream)? {
- OnEOF::Return => return self.write_read_term_options(vec![], vec![]),
+ OnEOF::Return => {
+ return self.write_read_term_options(vec![], vec![])
+ }
OnEOF::Continue => continue,
}
}
Ok(Some(printer))
}
- pub(super) fn read_predicate_key(&self, name: HeapCellValue, arity: HeapCellValue) -> (Atom, usize) {
+ pub(super) fn read_predicate_key(
+ &self,
+ name: HeapCellValue,
+ arity: HeapCellValue,
+ ) -> (Atom, usize) {
let name = cell_as_atom!(self.store(self.deref(name)));
let arity = cell_as_fixnum!(self.store(self.deref(arity)));
use crate::arena::*;
use crate::atom_table::*;
-use crate::types::*;
use crate::forms::*;
use crate::heap_iter::*;
use crate::machine::attributed_variables::*;
use crate::machine::unify::*;
use crate::parser::ast::*;
use crate::parser::dashu::{Integer, Rational};
+use crate::types::*;
use indexmap::IndexSet;
ball: Ball::new(),
ball_stack: vec![],
lifted_heap: Heap::new(),
- interms: vec![Number::default();256],
+ interms: vec![Number::default(); 256],
cont_pts: Vec::with_capacity(256),
cwil: CWIL::new(),
flags: MachineFlags::default(),
dynamic_mode: FirstOrNext::First,
unify_fn: MachineState::unify,
bind_fn: MachineState::bind,
- run_cleaners_fn: |_| { false },
- increment_call_count_fn: |_| { Ok(()) },
+ run_cleaners_fn: |_| false,
+ increment_call_count_fn: |_| Ok(()),
}
}
key_atom.index as u64,
));
- self.trail.push(TrailEntry::from_bytes(
- value_cell.into_bytes(),
- ));
+ self.trail
+ .push(TrailEntry::from_bytes(value_cell.into_bytes()));
self.tr += 2;
}
r: Ref,
value: HeapCellValue,
) {
- let mut unifier = CompositeUnifierForOccursCheckWithError::from(
- DefaultUnifier::from(self),
- );
+ let mut unifier = CompositeUnifierForOccursCheckWithError::from(DefaultUnifier::from(self));
unifier.bind(r, value);
}
}
pub(super) fn unify_with_occurs_check_with_error(&mut self) {
- let mut unifier = CompositeUnifierForOccursCheckWithError::from(
- DefaultUnifier::from(self),
- );
+ let mut unifier = CompositeUnifierForOccursCheckWithError::from(DefaultUnifier::from(self));
unifier.unify_internal();
}
}
)
}
- &mut HeapPtr::PStrChar(h, ref mut n) |
- &mut HeapPtr::PStrLocation(h, ref mut n) => {
+ &mut HeapPtr::PStrChar(h, ref mut n) | &mut HeapPtr::PStrLocation(h, ref mut n) => {
read_heap_cell!(self.heap[h],
(HeapCellValueTag::PStr, pstr_atom) => {
let pstr = PartialString::from(pstr_atom);
// iter2 is continuable, so it
// has a tail in the heap at
// focus+1.
- pdl.push(iter2.heap[focus+1]);
+ pdl.push(iter2.heap[focus + 1]);
return None;
}
let s = string.as_str();
match heap_pstr_iter.compare_pstr_to_string(s) {
- Some(PStrPrefixCmpResult { focus, offset, prefix_len }) if prefix_len == s.len() => {
+ Some(PStrPrefixCmpResult {
+ focus,
+ offset,
+ prefix_len,
+ }) if prefix_len == s.len() => {
let focus_addr = self.heap[focus];
read_heap_cell!(focus_addr,
return;
}
- Some(PStrPrefixCmpResult { prefix_len: inner_prefix_len, .. }) => {
+ Some(PStrPrefixCmpResult {
+ prefix_len: inner_prefix_len,
+ ..
+ }) => {
prefix_len = inner_prefix_len;
}
None => {
let f_a = if name == atom!(".") && arity == 2 {
self.heap.push(heap_loc_as_cell!(h));
- self.heap.push(heap_loc_as_cell!(h+1));
+ self.heap.push(heap_loc_as_cell!(h + 1));
list_loc_as_cell!(h)
} else {
while let Some(iteratee) = heap_pstr_iter.next() {
match iteratee {
- PStrIteratee::Char(_, c) =>
- chars.push(char_as_cell!(c)),
+ PStrIteratee::Char(_, c) => chars.push(char_as_cell!(c)),
PStrIteratee::PStrSegment(_, pstr_atom, n) => {
let pstr = PartialString::from(pstr_atom);
chars.extend(pstr.as_str_from(n).chars().map(|c| char_as_cell!(c)));
let mut value = unmark_cell_bits!(value);
if value.is_var() {
- value = heap_bound_store(
- iter.heap,
- heap_bound_deref(iter.heap, value),
- );
+ value = heap_bound_store(iter.heap, heap_bound_deref(iter.heap, value));
if value.is_var() {
return true;
if value.is_compound(iter.heap) {
if visited.contains(&value) {
- for _ in stack_len .. iter.stack_len() {
+ for _ in stack_len..iter.stack_len() {
iter.pop_stack();
}
} else {
pub use crate::atom_table::*;
use crate::heap_print::*;
pub use crate::machine::heap::*;
-pub use crate::machine::*;
pub use crate::machine::machine_state::*;
pub use crate::machine::stack::*;
pub use crate::machine::streams::*;
+pub use crate::machine::*;
pub use crate::macros::*;
pub use crate::parser::ast::*;
use crate::read::*;
printer.var_names = term_write_result
.var_dict
.into_iter()
- .map(|(var, cell)| {
- match var {
- VarKey::VarPtr(var) => (cell, var.clone()),
- VarKey::AnonVar(_) => (cell, VarPtr::from(var.to_string()))
- }
+ .map(|(var, cell)| match var {
+ VarKey::VarPtr(var) => (cell, var.clone()),
+ VarKey::AnonVar(_) => (cell, VarPtr::from(var.to_string())),
})
.collect();
load_contexts: vec![],
runtime,
#[cfg(feature = "ffi")]
- foreign_function_table: Default::default(),
+ foreign_function_table: Default::default(),
};
let mut lib_path = current_dir();
lib_path.clone(),
),
)
- .unwrap();
+ .unwrap();
bootstrapping_compile(
- Stream::from_static_string(
- LIBRARIES.borrow()["builtins"],
- &mut wam.machine_st.arena,
- ),
+ Stream::from_static_string(LIBRARIES.borrow()["builtins"], &mut wam.machine_st.arena),
&mut wam,
ListingSource::from_file_and_path(atom!("builtins.pl"), lib_path.clone()),
)
- .unwrap();
+ .unwrap();
if let Some(ref mut builtins) = wam.indices.modules.get_mut(&atom!("builtins")) {
load_module(
&mut wam,
ListingSource::from_file_and_path(atom!("loader.pl"), lib_path.clone()),
)
- .unwrap();
+ .unwrap();
wam.configure_modules();
let mut wam = MachineState::new();
let mut op_dir = default_op_dir();
- op_dir.insert(
- (atom!("+"), Fixity::In),
- OpDesc::build_with(500, YFX as u8),
- );
- op_dir.insert(
- (atom!("-"), Fixity::In),
- OpDesc::build_with(500, YFX as u8),
- );
- op_dir.insert(
- (atom!("*"), Fixity::In),
- OpDesc::build_with(500, YFX as u8),
- );
- op_dir.insert(
- (atom!("/"), Fixity::In),
- OpDesc::build_with(400, YFX as u8),
- );
- op_dir.insert(
- (atom!("="), Fixity::In),
- OpDesc::build_with(700, XFX as u8),
- );
+ op_dir.insert((atom!("+"), Fixity::In), OpDesc::build_with(500, YFX as u8));
+ op_dir.insert((atom!("-"), Fixity::In), OpDesc::build_with(500, YFX as u8));
+ op_dir.insert((atom!("*"), Fixity::In), OpDesc::build_with(500, YFX as u8));
+ op_dir.insert((atom!("/"), Fixity::In), OpDesc::build_with(400, YFX as u8));
+ op_dir.insert((atom!("="), Fixity::In), OpDesc::build_with(700, XFX as u8));
{
parse_and_write_parsed_term_to_heap(&mut wam, "f(X,X).", &op_dir).unwrap();
let mut wam = MachineState::new();
let mut op_dir = default_op_dir();
- op_dir.insert(
- (atom!("+"), Fixity::In),
- OpDesc::build_with(500, YFX as u8),
- );
- op_dir.insert(
- (atom!("-"), Fixity::In),
- OpDesc::build_with(500, YFX as u8),
- );
- op_dir.insert(
- (atom!("*"), Fixity::In),
- OpDesc::build_with(400, YFX as u8),
- );
- op_dir.insert(
- (atom!("/"), Fixity::In),
- OpDesc::build_with(400, YFX as u8),
- );
+ op_dir.insert((atom!("+"), Fixity::In), OpDesc::build_with(500, YFX as u8));
+ op_dir.insert((atom!("-"), Fixity::In), OpDesc::build_with(500, YFX as u8));
+ op_dir.insert((atom!("*"), Fixity::In), OpDesc::build_with(400, YFX as u8));
+ op_dir.insert((atom!("/"), Fixity::In), OpDesc::build_with(400, YFX as u8));
{
parse_and_write_parsed_term_to_heap(&mut wam, "f(X,X).", &op_dir).unwrap();
wam.heap.push(heap_loc_as_cell!(1));
assert_eq!(
- compare_term_test!(
- wam,
- heap_loc_as_cell!(0),
- heap_loc_as_cell!(0)
- ),
+ compare_term_test!(wam, heap_loc_as_cell!(0), heap_loc_as_cell!(0)),
Some(Ordering::Equal)
);
assert_eq!(
- compare_term_test!(
- wam,
- heap_loc_as_cell!(0),
- atom_as_cell!(atom!("a"))
- ),
+ compare_term_test!(wam, heap_loc_as_cell!(0), atom_as_cell!(atom!("a"))),
Some(Ordering::Greater)
);
wam.heap.push(empty_list_as_cell!());
assert_eq!(
- compare_term_test!(
- wam,
- heap_loc_as_cell!(7),
- heap_loc_as_cell!(7)
- ),
+ compare_term_test!(wam, heap_loc_as_cell!(7), heap_loc_as_cell!(7)),
Some(Ordering::Equal)
);
assert_eq!(
- compare_term_test!(
- wam,
- heap_loc_as_cell!(0),
- heap_loc_as_cell!(7)
- ),
+ compare_term_test!(wam, heap_loc_as_cell!(0), heap_loc_as_cell!(7)),
Some(Ordering::Greater)
);
assert_eq!(
- compare_term_test!(
- wam,
- empty_list_as_cell!(),
- heap_loc_as_cell!(7)
- ),
+ compare_term_test!(wam, empty_list_as_cell!(), heap_loc_as_cell!(7)),
Some(Ordering::Less)
);
);
assert_eq!(
- compare_term_test!(
- wam,
- empty_list_as_cell!(),
- atom_as_cell!(atom!("atom"))
- ),
+ compare_term_test!(wam, empty_list_as_cell!(), atom_as_cell!(atom!("atom"))),
Some(Ordering::Less)
);
assert_eq!(
- compare_term_test!(
- wam,
- atom_as_cell!(atom!("atom")),
- empty_list_as_cell!()
- ),
+ compare_term_test!(wam, atom_as_cell!(atom!("atom")), empty_list_as_cell!()),
Some(Ordering::Greater)
);
let one_p_one = HeapCellValue::from(float_alloc!(1.1, &mut wam.arena));
assert_eq!(
- compare_term_test!(
- wam,
- one_p_one,
- fixnum_as_cell!(Fixnum::build_with(1))
- ),
+ compare_term_test!(wam, one_p_one, fixnum_as_cell!(Fixnum::build_with(1))),
Some(Ordering::Less)
);
assert_eq!(
- compare_term_test!(
- wam,
- fixnum_as_cell!(Fixnum::build_with(1)),
- one_p_one
- ),
+ compare_term_test!(wam, fixnum_as_cell!(Fixnum::build_with(1)), one_p_one),
Some(Ordering::Greater)
);
}
all_cells_unmarked(&wam.heap);
wam.heap.clear();
- wam.heap.extend(functor!(atom!("f"), [atom(atom!("a")), atom(atom!("b"))]));
+ wam.heap
+ .extend(functor!(atom!("f"), [atom(atom!("a")), atom(atom!("b"))]));
assert!(!wam.is_cyclic_term(str_loc_as_cell!(0)));
pub mod loader;
pub mod compile;
pub mod copier;
+pub mod disjuncts;
pub mod dispatch;
pub mod gc;
pub mod heap;
pub mod machine_state_impl;
pub mod mock_wam;
pub mod partial_string;
-pub mod disjuncts;
pub mod preprocessor;
pub mod stack;
pub mod streams;
use crate::arena::*;
use crate::arithmetic::*;
use crate::atom_table::*;
-use crate::forms::*;
#[cfg(feature = "ffi")]
use crate::ffi::ForeignFunctionTable;
+use crate::forms::*;
use crate::instructions::*;
use crate::machine::args::*;
use crate::machine::compile::*;
for key in keys {
let idx = code_dir.get(&key).unwrap();
builtins.code_dir.insert(key, idx.clone());
- builtins.module_decl.exports.push(ModuleExport::PredicateKey(key));
+ builtins
+ .module_decl
+ .exports
+ .push(ModuleExport::PredicateKey(key));
}
}
code: &mut self.code,
load_contexts: &mut self.load_contexts,
},
- &mut self.machine_st
+ &mut self.machine_st,
)
}
self.machine_st.throw_exception(err);
}
- fn run_module_predicate(&mut self, module_name: Atom, key: PredicateKey) -> std::process::ExitCode {
+ fn run_module_predicate(
+ &mut self,
+ module_name: Atom,
+ key: PredicateKey,
+ ) -> std::process::ExitCode {
if let Some(module) = self.indices.modules.get(&module_name) {
if let Some(ref code_index) = module.code_dir.get(&key) {
let p = code_index.local().unwrap();
pub fn load_file(&mut self, path: &str, stream: Stream) {
self.machine_st.registers[1] = stream_as_cell!(stream);
- self.machine_st.registers[2] = atom_as_cell!(
- self.machine_st.atom_tbl.build_with(path)
- );
+ self.machine_st.registers[2] = atom_as_cell!(self.machine_st.atom_tbl.build_with(path));
self.run_module_predicate(atom!("loader"), (atom!("file_load"), 2));
}
path_buf.push("src/toplevel.pl");
let path = path_buf.to_str().unwrap();
- let toplevel_stream = Stream::from_static_string(
- include_str!("../toplevel.pl"),
- &mut self.machine_st.arena,
- );
+ let toplevel_stream =
+ Stream::from_static_string(include_str!("../toplevel.pl"), &mut self.machine_st.arena);
self.load_file(path, toplevel_stream);
));
}
- self.machine_st.registers[1] = heap_loc_as_cell!(
- iter_to_heap_list(&mut self.machine_st.heap, arg_pstrs.into_iter())
- );
+ self.machine_st.registers[1] = heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ arg_pstrs.into_iter()
+ ));
self.run_module_predicate(atom!("$toplevel"), (atom!("$repl"), 1))
}
pub(crate) fn configure_modules(&mut self) {
- fn update_call_n_indices(loader: &Module, target_code_dir: &mut CodeDir, arena: &mut Arena) {
+ fn update_call_n_indices(
+ loader: &Module,
+ target_code_dir: &mut CodeDir,
+ arena: &mut Arena,
+ ) {
for arity in 1..66 {
let key = (atom!("call"), arity);
}
for (_, target_module) in self.indices.modules.iter_mut() {
- update_call_n_indices(&loader, &mut target_module.code_dir, &mut self.machine_st.arena);
+ update_call_n_indices(
+ &loader,
+ &mut target_module.code_dir,
+ &mut self.machine_st.arena,
+ );
}
- update_call_n_indices(&loader, &mut self.indices.code_dir, &mut self.machine_st.arena);
+ update_call_n_indices(
+ &loader,
+ &mut self.indices.code_dir,
+ &mut self.machine_st.arena,
+ );
self.indices.modules.insert(atom!("loader"), loader);
} else {
pub(crate) fn add_impls_to_indices(&mut self) {
let impls_offset = self.code.len() + 3;
- self.code.extend(vec![
- Instruction::BreakFromDispatchLoop,
- Instruction::InstallVerifyAttr,
- Instruction::VerifyAttrInterrupt,
- Instruction::ExecuteTermGreaterThan,
- Instruction::ExecuteTermLessThan,
- Instruction::ExecuteTermGreaterThanOrEqual,
- Instruction::ExecuteTermLessThanOrEqual,
- Instruction::ExecuteTermEqual,
- Instruction::ExecuteTermNotEqual,
- Instruction::ExecuteNumberGreaterThan(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
- Instruction::ExecuteNumberLessThan(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
- Instruction::ExecuteNumberGreaterThanOrEqual(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
- Instruction::ExecuteNumberLessThanOrEqual(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
- Instruction::ExecuteNumberEqual(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
- Instruction::ExecuteNumberNotEqual(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
- Instruction::ExecuteIs(temp_v!(1), ar_reg!(temp_v!(2))),
- Instruction::ExecuteAcyclicTerm,
- Instruction::ExecuteArg,
- Instruction::ExecuteCompare,
- Instruction::ExecuteCopyTerm,
- Instruction::ExecuteFunctor,
- Instruction::ExecuteGround,
- Instruction::ExecuteKeySort,
- Instruction::ExecuteSort,
- Instruction::ExecuteN(1),
- Instruction::ExecuteN(2),
- Instruction::ExecuteN(3),
- Instruction::ExecuteN(4),
- Instruction::ExecuteN(5),
- Instruction::ExecuteN(6),
- Instruction::ExecuteN(7),
- Instruction::ExecuteN(8),
- Instruction::ExecuteN(9),
- Instruction::ExecuteIsAtom(temp_v!(1)),
- Instruction::ExecuteIsAtomic(temp_v!(1)),
- Instruction::ExecuteIsCompound(temp_v!(1)),
- Instruction::ExecuteIsInteger(temp_v!(1)),
- Instruction::ExecuteIsNumber(temp_v!(1)),
- Instruction::ExecuteIsRational(temp_v!(1)),
- Instruction::ExecuteIsFloat(temp_v!(1)),
- Instruction::ExecuteIsNonVar(temp_v!(1)),
- Instruction::ExecuteIsVar(temp_v!(1))
- ].into_iter());
-
- for (p, instr) in self.code[impls_offset ..].iter().enumerate() {
+ self.code.extend(
+ vec![
+ Instruction::BreakFromDispatchLoop,
+ Instruction::InstallVerifyAttr,
+ Instruction::VerifyAttrInterrupt,
+ Instruction::ExecuteTermGreaterThan,
+ Instruction::ExecuteTermLessThan,
+ Instruction::ExecuteTermGreaterThanOrEqual,
+ Instruction::ExecuteTermLessThanOrEqual,
+ Instruction::ExecuteTermEqual,
+ Instruction::ExecuteTermNotEqual,
+ Instruction::ExecuteNumberGreaterThan(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
+ Instruction::ExecuteNumberLessThan(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
+ Instruction::ExecuteNumberGreaterThanOrEqual(
+ ar_reg!(temp_v!(1)),
+ ar_reg!(temp_v!(2)),
+ ),
+ Instruction::ExecuteNumberLessThanOrEqual(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
+ Instruction::ExecuteNumberEqual(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
+ Instruction::ExecuteNumberNotEqual(ar_reg!(temp_v!(1)), ar_reg!(temp_v!(2))),
+ Instruction::ExecuteIs(temp_v!(1), ar_reg!(temp_v!(2))),
+ Instruction::ExecuteAcyclicTerm,
+ Instruction::ExecuteArg,
+ Instruction::ExecuteCompare,
+ Instruction::ExecuteCopyTerm,
+ Instruction::ExecuteFunctor,
+ Instruction::ExecuteGround,
+ Instruction::ExecuteKeySort,
+ Instruction::ExecuteSort,
+ Instruction::ExecuteN(1),
+ Instruction::ExecuteN(2),
+ Instruction::ExecuteN(3),
+ Instruction::ExecuteN(4),
+ Instruction::ExecuteN(5),
+ Instruction::ExecuteN(6),
+ Instruction::ExecuteN(7),
+ Instruction::ExecuteN(8),
+ Instruction::ExecuteN(9),
+ Instruction::ExecuteIsAtom(temp_v!(1)),
+ Instruction::ExecuteIsAtomic(temp_v!(1)),
+ Instruction::ExecuteIsCompound(temp_v!(1)),
+ Instruction::ExecuteIsInteger(temp_v!(1)),
+ Instruction::ExecuteIsNumber(temp_v!(1)),
+ Instruction::ExecuteIsRational(temp_v!(1)),
+ Instruction::ExecuteIsFloat(temp_v!(1)),
+ Instruction::ExecuteIsNonVar(temp_v!(1)),
+ Instruction::ExecuteIsVar(temp_v!(1)),
+ ]
+ .into_iter(),
+ );
+
+ for (p, instr) in self.code[impls_offset..].iter().enumerate() {
let key = instr.to_name_and_arity();
self.indices.code_dir.insert(
key,
- CodeIndex::new(IndexPtr::index(p + impls_offset), &mut self.machine_st.arena),
+ CodeIndex::new(
+ IndexPtr::index(p + impls_offset),
+ &mut self.machine_st.arena,
+ ),
);
}
}
let user_error = Stream::stderr(&mut machine_st.arena);
#[cfg(not(target_os = "wasi"))]
- let runtime = tokio::runtime::Runtime::new()
- .unwrap();
+ let runtime = tokio::runtime::Runtime::new().unwrap();
#[cfg(target_os = "wasi")]
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
load_contexts: vec![],
runtime,
#[cfg(feature = "ffi")]
- foreign_function_table: Default::default(),
+ foreign_function_table: Default::default(),
};
let mut lib_path = current_dir();
.unwrap();
bootstrapping_compile(
- Stream::from_static_string(
- LIBRARIES.borrow()["builtins"],
- &mut wam.machine_st.arena,
- ),
+ Stream::from_static_string(LIBRARIES.borrow()["builtins"], &mut wam.machine_st.arena),
&mut wam,
ListingSource::from_file_and_path(atom!("builtins.pl"), lib_path.clone()),
)
}
pub(crate) fn configure_streams(&mut self) {
- self.user_input.options_mut().set_alias_to_atom_opt(Some(atom!("user_input")));
+ self.user_input
+ .options_mut()
+ .set_alias_to_atom_opt(Some(atom!("user_input")));
self.indices
.stream_aliases
self.indices.streams.insert(self.user_input);
- self.user_output.options_mut().set_alias_to_atom_opt(Some(atom!("user_output")));
+ self.user_output
+ .options_mut()
+ .set_alias_to_atom_opt(Some(atom!("user_output")));
self.indices
.stream_aliases
loop {
let indexing_code_ptr = match &indexing_lines[oip] {
- &IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(arg, v, c, l, s)) => {
+ &IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(
+ arg,
+ v,
+ c,
+ l,
+ s,
+ )) => {
cell = self.deref_register(arg);
- self.machine_st.select_switch_on_term_index(cell, v, c, l, s)
+ self.machine_st
+ .select_switch_on_term_index(cell, v, c, l, s)
}
IndexingLine::Indexing(IndexingInstruction::SwitchOnConstant(hm)) => {
let lit = self.machine_st.constant_to_literal(cell);
}
);
}
- &Instruction::GetPartialString(Level::Shallow, string, RegType::Temp(t), has_tail) => {
+ &Instruction::GetPartialString(
+ Level::Shallow,
+ string,
+ RegType::Temp(t),
+ has_tail,
+ ) => {
let cell = self.deref_register(t);
read_heap_cell!(cell,
}
);
}
- Instruction::GetConstant(..) |
- Instruction::GetList(..) |
- Instruction::GetStructure(..) |
- Instruction::GetPartialString(..) |
- &Instruction::UnifyVoid(..) |
- &Instruction::UnifyConstant(..) |
- &Instruction::GetVariable(..) |
- &Instruction::GetValue(..) |
- &Instruction::UnifyVariable(..) |
- &Instruction::UnifyValue(..) |
- &Instruction::UnifyLocalValue(..) => {
+ Instruction::GetConstant(..)
+ | Instruction::GetList(..)
+ | Instruction::GetStructure(..)
+ | Instruction::GetPartialString(..)
+ | &Instruction::UnifyVoid(..)
+ | &Instruction::UnifyConstant(..)
+ | &Instruction::GetVariable(..)
+ | &Instruction::GetValue(..)
+ | &Instruction::UnifyVariable(..)
+ | &Instruction::UnifyValue(..)
+ | &Instruction::UnifyLocalValue(..) => {
offset += 1;
}
_ => {
fn next_applicable_clause(&mut self, mut offset: usize) -> Option<usize> {
while !self.next_clause_applicable(self.machine_st.p + offset + 1) {
match &self.code[self.machine_st.p + offset] {
- &Instruction::DefaultRetryMeElse(o) | &Instruction::RetryMeElse(o) |
- &Instruction::DynamicElse(.., NextOrFail::Next(o)) |
- &Instruction::DynamicInternalElse(.., NextOrFail::Next(o)) => offset += o,
+ &Instruction::DefaultRetryMeElse(o)
+ | &Instruction::RetryMeElse(o)
+ | &Instruction::DynamicElse(.., NextOrFail::Next(o))
+ | &Instruction::DynamicInternalElse(.., NextOrFail::Next(o)) => offset += o,
_ => {
return None;
}
match &indexing_lines[self.machine_st.oip as usize] {
IndexingLine::IndexedChoice(indexed_choice) => {
match &indexed_choice[(self.machine_st.iip + inner_offset) as usize] {
- &IndexedChoiceInstruction::Retry(o) |
- &IndexedChoiceInstruction::DefaultRetry(o) => {
+ &IndexedChoiceInstruction::Retry(o)
+ | &IndexedChoiceInstruction::DefaultRetry(o) => {
if self.next_clause_applicable(self.machine_st.p + o) {
return Some(inner_offset);
}
inner_offset += 1;
}
- &IndexedChoiceInstruction::Trust(o) |
- &IndexedChoiceInstruction::DefaultTrust(o) => {
+ &IndexedChoiceInstruction::Trust(o)
+ | &IndexedChoiceInstruction::DefaultTrust(o) => {
return if self.next_clause_applicable(self.machine_st.p + o) {
Some(inner_offset)
} else {
or_frame.prelude.tr = self.machine_st.tr;
or_frame.prelude.h = self.machine_st.heap.len();
or_frame.prelude.b0 = self.machine_st.b0;
- or_frame.prelude.attr_var_queue_len = self.machine_st.attr_var_init.attr_var_queue.len();
+ or_frame.prelude.attr_var_queue_len =
+ self.machine_st.attr_var_init.attr_var_queue.len();
self.machine_st.b = b;
for i in 0..n {
- or_frame[i] = self.machine_st.registers[i+1];
+ or_frame[i] = self.machine_st.registers[i + 1];
}
self.machine_st.hb = self.machine_st.heap.len();
or_frame.prelude.tr = self.machine_st.tr;
or_frame.prelude.h = self.machine_st.heap.len();
or_frame.prelude.b0 = self.machine_st.b0;
- or_frame.prelude.attr_var_queue_len = self.machine_st.attr_var_init.attr_var_queue.len();
+ or_frame.prelude.attr_var_queue_len =
+ self.machine_st.attr_var_init.attr_var_queue.len();
self.machine_st.b = b;
for i in 0..n {
- or_frame[i] = self.machine_st.registers[i+1];
+ or_frame[i] = self.machine_st.registers[i + 1];
}
self.machine_st.hb = self.machine_st.heap.len();
let curr_tr = self.machine_st.tr;
for i in 0..n {
- self.machine_st.registers[i+1] = or_frame[i];
+ self.machine_st.registers[i + 1] = or_frame[i];
}
self.unwind_trail(old_tr, curr_tr);
let curr_tr = self.machine_st.tr;
for i in 0..n {
- self.machine_st.registers[i+1] = or_frame[i];
+ self.machine_st.registers[i + 1] = or_frame[i];
}
self.unwind_trail(old_tr, curr_tr);
let n = or_frame.prelude.num_cells;
for i in 0..n {
- self.machine_st.registers[i+1] = or_frame[i];
+ self.machine_st.registers[i + 1] = or_frame[i];
}
let old_tr = or_frame.prelude.tr;
#[inline(always)]
fn undefined_procedure(&mut self, name: Atom, arity: usize) -> CallResult {
match self.machine_st.flags.unknown {
- Unknown::Error => {
- Err(self.machine_st.throw_undefined_error(name, arity))
- }
+ Unknown::Error => Err(self.machine_st.throw_undefined_error(name, arity)),
Unknown::Fail => {
self.machine_st.fail = true;
Ok(())
}
Unknown::Warn => {
- println!("warning: predicate {}/{} is undefined", name.as_str(), arity);
+ println!(
+ "warning: predicate {}/{} is undefined",
+ name.as_str(),
+ arity
+ );
self.machine_st.fail = true;
Ok(())
}
self.machine_st.dynamic_mode = FirstOrNext::First;
self.machine_st.execute_at_index(arity, compiled_tl_index);
}
- IndexPtrTag::Index => {
- self.machine_st.execute_at_index(arity, compiled_tl_index)
- }
+ IndexPtrTag::Index => self.machine_st.execute_at_index(arity, compiled_tl_index),
}
Ok(())
}
} else {
let stub = functor_stub(name, arity);
- let err = self.machine_st.module_resolution_error(module_name, name, arity);
+ let err = self
+ .machine_st
+ .module_resolution_error(module_name, name, arity);
Err(self.machine_st.error_form(err, stub))
}
}
} else {
let stub = functor_stub(name, arity);
- let err = self.machine_st.module_resolution_error(module_name, name, arity);
+ let err = self
+ .machine_st
+ .module_resolution_error(module_name, name, arity);
Err(self.machine_st.error_form(err, stub))
}
let r_c_wo_h_atom = atom!("run_cleaners_without_handling");
let iso_ext = atom!("iso_ext");
- RCWH = self.indices.get_predicate_code_index(r_c_w_h_atom, 0, iso_ext)
- .and_then(|item| item.local())
- .unwrap();
- RCWOH = self.indices.get_predicate_code_index(r_c_wo_h_atom, 1, iso_ext)
- .and_then(|item| item.local())
- .unwrap();
+ RCWH = self
+ .indices
+ .get_predicate_code_index(r_c_w_h_atom, 0, iso_ext)
+ .and_then(|item| item.local())
+ .unwrap();
+ RCWOH = self
+ .indices
+ .get_predicate_code_index(r_c_wo_h_atom, 1, iso_ext)
+ .and_then(|item| item.local())
+ .unwrap();
});
(RCWH, RCWOH)
let (idx, arity) = if self.machine_st.effective_block() > prev_block {
(r_c_w_h, 0)
} else {
- self.machine_st.registers[1] = fixnum_as_cell!(
- Fixnum::build_with(b_cutoff as i64)
- );
+ self.machine_st.registers[1] =
+ fixnum_as_cell!(Fixnum::build_with(b_cutoff as i64));
(r_c_wo_h, 1)
};
None => unreachable!(),
}
}
- TrailEntryTag::TrailedAttachedValue => {
- }
+ TrailEntryTag::TrailedAttachedValue => {}
}
}
}
#[inline]
pub(super) fn new<'a>(src: &'a str, atom_tbl: &mut AtomTable) -> Option<(Self, &'a str)> {
let terminator_idx = scan_for_terminator(src.chars());
- let pstr = PartialString(atom_tbl.build_with(&src[.. terminator_idx]));
+ let pstr = PartialString(atom_tbl.build_with(&src[..terminator_idx]));
- Some(if terminator_idx < src.as_bytes().len() {
+ Some(if terminator_idx < src.as_bytes().len() {
(pstr, &src[terminator_idx + 1..])
} else {
(pstr, "")
let mut final_result = None;
- while let Some(PStrIterStep { iteratee, next_hare }) = self.step(self.brent_st.hare) {
+ while let Some(PStrIterStep {
+ iteratee,
+ next_hare,
+ }) = self.step(self.brent_st.hare)
+ {
self.brent_st.hare = next_hare;
self.focus = self.heap[iteratee.focus()];
- result.focus = iteratee.focus();
+ result.focus = iteratee.focus();
result.offset = iteratee.offset();
match iteratee {
self.brent_st.hare = self.orig_focus;
self.brent_st.tortoise = self.orig_focus;
- for _ in 0 .. self.brent_st.lam {
+ for _ in 0..self.brent_st.lam {
self.brent_st.hare = self.step(self.brent_st.hare).unwrap().next_hare;
}
let mut focus = self.focus;
loop {
- read_heap_cell!(focus,
- (HeapCellValueTag::CStr | HeapCellValueTag::PStrLoc) => {
- return true;
- }
- (HeapCellValueTag::Atom, (name, arity)) => { // TODO: use Str here?
- return name == atom!(".") && arity == 2;
- }
- (HeapCellValueTag::Lis, h) => {
- let value = self.heap[h];
- let value = heap_bound_store(
- self.heap,
- heap_bound_deref(self.heap, value),
- );
-
- return read_heap_cell!(value,
- (HeapCellValueTag::Atom, (name, arity)) => {
- arity == 0 && name.as_char().is_some()
- }
- (HeapCellValueTag::Char) => {
- true
- }
- _ => {
- false
- }
- );
- }
- (HeapCellValueTag::AttrVar | HeapCellValueTag::Var, h) => {
- if focus == self.heap[h] {
- return false;
- }
-
- focus = self.heap[h];
- }
- _ => {
- return false;
- }
- );
+ read_heap_cell!(focus,
+ (HeapCellValueTag::CStr | HeapCellValueTag::PStrLoc) => {
+ return true;
+ }
+ (HeapCellValueTag::Atom, (name, arity)) => { // TODO: use Str here?
+ return name == atom!(".") && arity == 2;
+ }
+ (HeapCellValueTag::Lis, h) => {
+ let value = self.heap[h];
+ let value = heap_bound_store(
+ self.heap,
+ heap_bound_deref(self.heap, value),
+ );
+
+ return read_heap_cell!(value,
+ (HeapCellValueTag::Atom, (name, arity)) => {
+ arity == 0 && name.as_char().is_some()
+ }
+ (HeapCellValueTag::Char) => {
+ true
+ }
+ _ => {
+ false
+ }
+ );
+ }
+ (HeapCellValueTag::AttrVar | HeapCellValueTag::Var, h) => {
+ if focus == self.heap[h] {
+ return false;
+ }
+
+ focus = self.heap[h];
+ }
+ _ => {
+ return false;
+ }
+ );
}
}
}
fn pre_cycle_discovery_stepper(&mut self) -> Option<PStrIteratee> {
- let PStrIterStep { iteratee, next_hare } =
- match self.step(self.brent_st.hare) {
- Some(results) => results,
- None => {
- return None;
- }
- };
+ let PStrIterStep {
+ iteratee,
+ next_hare,
+ } = match self.step(self.brent_st.hare) {
+ Some(results) => results,
+ None => {
+ return None;
+ }
+ };
self.focus = self.heap[iteratee.focus()];
return None;
}
- let PStrIterStep { iteratee, next_hare } =
- match self.step(self.brent_st.hare) {
- Some(results) => results,
- None => {
- return None;
- }
- };
+ let PStrIterStep {
+ iteratee,
+ next_hare,
+ } = match self.step(self.brent_st.hare) {
+ Some(results) => results,
+ None => {
+ return None;
+ }
+ };
self.focus = self.heap[next_hare];
self.brent_st.hare = next_hare;
match pstr.as_str_from(n).chars().next() {
Some(c) => {
- self.item = Some(PStrIteratee::PStrSegment(
- f1,
- pstr_atom,
- n + c.len_utf8(),
- ));
+ self.item =
+ Some(PStrIteratee::PStrSegment(f1, pstr_atom, n + c.len_utf8()));
return Some(c);
}
}
}
}
- (PStrIteratee::PStrSegment(f1, pstr1_atom, n1),
- PStrIteratee::PStrSegment(f2, pstr2_atom, n2)) => {
+ (
+ PStrIteratee::PStrSegment(f1, pstr1_atom, n1),
+ PStrIteratee::PStrSegment(f2, pstr2_atom, n2),
+ ) => {
if pstr1_atom == pstr2_atom && n1 == n2 {
cycle_detection_step(i1, i2, &step_1);
let both_cyclic = cycle_detection_step(i2, i1, &step_2);
}
}
Ordering::Less if str2.starts_with(str1) => {
- step_2.iteratee = PStrIteratee::PStrSegment(f2, pstr2_atom, n2 + str1.len());
+ step_2.iteratee =
+ PStrIteratee::PStrSegment(f2, pstr2_atom, n2 + str1.len());
let c1_result = cycle_detection_step(i1, i2, &step_1);
r1 = step(i1, i1.brent_st.hare);
}
}
Ordering::Greater if str1.starts_with(str2) => {
- step_1.iteratee = PStrIteratee::PStrSegment(f1, pstr1_atom, n1 + str2.len());
+ step_1.iteratee =
+ PStrIteratee::PStrSegment(f1, pstr1_atom, n1 + str2.len());
let c2_result = cycle_detection_step(i2, i1, &step_2);
r2 = step(i2, i2.brent_st.hare);
);
assert_eq!(
iter.next(),
- Some(PStrIteratee::PStrSegment(2, cell_as_atom!(pstr_second_cell), 0))
+ Some(PStrIteratee::PStrSegment(
+ 2,
+ cell_as_atom!(pstr_second_cell),
+ 0
+ ))
);
assert_eq!(iter.next(), None);
);
assert_eq!(
iter.next(),
- Some(PStrIteratee::PStrSegment(2, cell_as_atom!(pstr_second_cell), 0))
+ Some(PStrIteratee::PStrSegment(
+ 2,
+ cell_as_atom!(pstr_second_cell),
+ 0
+ ))
);
assert_eq!(iter.next(), None);
}
wam.machine_st.heap.pop();
- wam.machine_st.heap.push(pstr_loc_as_cell!(wam.machine_st.heap.len() + 1));
+ wam.machine_st
+ .heap
+ .push(pstr_loc_as_cell!(wam.machine_st.heap.len() + 1));
wam.machine_st.heap.push(pstr_offset_as_cell!(0));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(0)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(0)));
{
let mut iter = HeapPStrIter::new(&wam.machine_st.heap, 0);
// construct a structurally similar but different cyclic partial string
// matching the one beginning at wam.machine_st.heap[0].
- put_partial_string(
- &mut wam.machine_st.heap,
- "ab",
- &mut wam.machine_st.atom_tbl,
- );
+ put_partial_string(&mut wam.machine_st.heap, "ab", &mut wam.machine_st.atom_tbl);
wam.machine_st.heap.pop();
- wam.machine_st.heap.push(pstr_loc_as_cell!(second_h+2));
+ wam.machine_st.heap.push(pstr_loc_as_cell!(second_h + 2));
- put_partial_string(
- &mut wam.machine_st.heap,
- "c ",
- &mut wam.machine_st.atom_tbl,
- );
+ put_partial_string(&mut wam.machine_st.heap, "c ", &mut wam.machine_st.atom_tbl);
wam.machine_st.heap.pop();
- wam.machine_st.heap.push(pstr_loc_as_cell!(second_h+4));
+ wam.machine_st.heap.push(pstr_loc_as_cell!(second_h + 4));
wam.machine_st.heap.push(pstr_second_cell);
- wam.machine_st.heap.push(pstr_loc_as_cell!(second_h+6));
+ wam.machine_st.heap.push(pstr_loc_as_cell!(second_h + 6));
wam.machine_st.heap.push(pstr_offset_as_cell!(second_h));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(0)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(0)));
let mut iter1 = HeapPStrIter::new(&wam.machine_st.heap, 0);
let mut iter2 = HeapPStrIter::new(&wam.machine_st.heap, second_h);
unify!(wam.machine_st, cstr_var_cell, heap_loc_as_cell!(1));
- assert_eq!(
- wam.machine_st.heap[2],
- char_as_cell!('a'),
- );
+ assert_eq!(wam.machine_st.heap[2], char_as_cell!('a'),);
- assert_eq!(
- wam.machine_st.heap[4],
- char_as_cell!('b'),
- );
+ assert_eq!(wam.machine_st.heap[4], char_as_cell!('b'),);
- assert_eq!(
- wam.machine_st.heap[6],
- char_as_cell!('c'),
- );
+ assert_eq!(wam.machine_st.heap[6], char_as_cell!('c'),);
// test "abc" = [X,Y,Z|D].
assert_eq!(wam.machine_st.fail, false);
- assert_eq!(
- wam.machine_st.heap[2],
- char_as_cell!('a'),
- );
+ assert_eq!(wam.machine_st.heap[2], char_as_cell!('a'),);
- assert_eq!(
- wam.machine_st.heap[4],
- char_as_cell!('b'),
- );
+ assert_eq!(wam.machine_st.heap[4], char_as_cell!('b'),);
- assert_eq!(
- wam.machine_st.heap[6],
- char_as_cell!('c'),
- );
+ assert_eq!(wam.machine_st.heap[6], char_as_cell!('c'),);
- assert_eq!(
- wam.machine_st.heap[7],
- empty_list_as_cell!(),
- );
+ assert_eq!(wam.machine_st.heap[7], empty_list_as_cell!(),);
// test "d" = [d].
wam.machine_st.heap.clear();
- let cstr_var_cell = put_complete_string(
- &mut wam.machine_st.heap,
- "d",
- &mut wam.machine_st.atom_tbl,
- );
+ let cstr_var_cell =
+ put_complete_string(&mut wam.machine_st.heap, "d", &mut wam.machine_st.atom_tbl);
wam.machine_st.heap.push(list_loc_as_cell!(2));
wam.machine_st.heap.push(char_as_cell!('d'));
assert_eq!(wam.machine_st.fail, false);
- assert_eq!(
- wam.machine_st.heap[2],
- char_as_cell!('a'),
- );
+ assert_eq!(wam.machine_st.heap[2], char_as_cell!('a'),);
- assert_eq!(
- wam.machine_st.heap[4],
- char_as_cell!('b'),
- );
+ assert_eq!(wam.machine_st.heap[4], char_as_cell!('b'),);
- assert_eq!(
- wam.machine_st.heap[6],
- char_as_cell!('c'),
- );
+ assert_eq!(wam.machine_st.heap[6], char_as_cell!('c'),);
// test "abcdef" = [a,b,c|X].
assert_eq!(wam.machine_st.heap[3], pstr_loc_as_cell!(1));
assert_eq!(wam.machine_st.heap[4], atom_as_cstr_cell!(atom!("abcdef")));
assert_eq!(wam.machine_st.heap[5], pstr_offset_as_cell!(4));
- assert_eq!(wam.machine_st.heap[6], fixnum_as_cell!(Fixnum::build_with("abc".len() as i64)));
+ assert_eq!(
+ wam.machine_st.heap[6],
+ fixnum_as_cell!(Fixnum::build_with("abc".len() as i64))
+ );
// test iteration on X = [b,c,b,c,b,c,b,c|...] as an offset.
wam.machine_st.heap.push(pstr_as_cell!(atom!("abc")));
wam.machine_st.heap.push(pstr_loc_as_cell!(2));
wam.machine_st.heap.push(pstr_offset_as_cell!(0));
- wam.machine_st.heap.push(fixnum_as_cell!(Fixnum::build_with(1)));
+ wam.machine_st
+ .heap
+ .push(fixnum_as_cell!(Fixnum::build_with(1)));
{
let mut iter = HeapPStrIter::new(&wam.machine_st.heap, 2);
use std::cell::Cell;
use std::convert::TryFrom;
-pub(crate) fn to_op_decl(
- prec: u16,
- spec: Atom,
- name: Atom,
-) -> Result<OpDecl, CompilationError> {
+pub(crate) fn to_op_decl(prec: u16, spec: Atom, name: Atom) -> Result<OpDecl, CompilationError> {
match spec {
atom!("xfx") => Ok(OpDecl::new(OpDesc::build_with(prec, XFX as u8), name)),
atom!("xfy") => Ok(OpDecl::new(OpDesc::build_with(prec, XFY as u8), name)),
Term::Literal(_, Literal::Integer(n)) => n.to_usize(),
Term::Literal(_, Literal::Fixnum(n)) => usize::try_from(n.get_num()).ok(),
_ => None,
- }.ok_or(CompilationError::InvalidModuleExport)?;
+ }
+ .ok_or(CompilationError::InvalidModuleExport)?;
let name = match name {
Term::Literal(_, Literal::Atom(name)) => Some(name),
_ => None,
- }.ok_or(CompilationError::InvalidModuleExport)?;
+ }
+ .ok_or(CompilationError::InvalidModuleExport)?;
if *slash == atom!("/") {
Ok((name, arity))
let name = match name {
Term::Literal(_, Literal::Atom(name)) => Some(name),
_ => None,
- }.ok_or(CompilationError::InvalidModuleDecl)?;
+ }
+ .ok_or(CompilationError::InvalidModuleDecl)?;
let exports = setup_module_export_list(export_list, atom_tbl)?;
fn setup_use_module_decl(mut terms: Vec<Term>) -> Result<ModuleSource, CompilationError> {
match terms.pop().unwrap() {
- Term::Clause(_, name, mut terms)
- if name == atom!("library") && terms.len() == 1 =>
- {
+ Term::Clause(_, name, mut terms) if name == atom!("library") && terms.len() == 1 => {
match terms.pop().unwrap() {
Term::Literal(_, Literal::Atom(name)) => Ok(ModuleSource::Library(name)),
_ => Err(CompilationError::InvalidModuleDecl),
) -> Result<UseModuleExport, CompilationError> {
let mut export_list = terms.pop().unwrap();
let module_src = match terms.pop().unwrap() {
- Term::Clause(_, name, mut terms)
- if name == atom!("library") && terms.len() == 1 =>
- {
+ Term::Clause(_, name, mut terms) if name == atom!("library") && terms.len() == 1 => {
match terms.pop().unwrap() {
Term::Literal(_, Literal::Atom(name)) => Ok(ModuleSource::Library(name)),
_ => Err(CompilationError::InvalidModuleDecl),
}
fn tag_with_module_name(module_name: Atom, term: Term) -> Term {
- Term::Clause(Cell::default(), atom!(":"), vec![
- Term::Literal(Cell::default(), Literal::Atom(module_name)),
- term
- ])
+ Term::Clause(
+ Cell::default(),
+ atom!(":"),
+ vec![
+ Term::Literal(Cell::default(), Literal::Atom(module_name)),
+ term,
+ ],
+ )
}
let process_term: fn(Atom, Term) -> Term;
let (module_name, key, term) = match term {
Term::Clause(cell, atom!(":"), mut terms) if terms.len() == 2 => {
- if let Some((module_name, name)) = get_qualified_name(&terms[0], &terms[1]) {
+ if let Some((module_name, name)) = get_qualified_name(&terms[0], &terms[1])
+ {
process_term = tag_with_module_name;
- (module_name, (name, terms[1].arity() + supp_args), terms.pop().unwrap())
+ (
+ module_name,
+ (name, terms[1].arity() + supp_args),
+ terms.pop().unwrap(),
+ )
} else {
arg_terms.push(Term::Clause(cell, atom!(":"), terms));
continue;
let term = match term {
Term::Clause(cell, name, mut terms) => {
if let Some(Term::Literal(_, Literal::CodeIndex(_))) = terms.last() {
- arg_terms.push(process_term(
- module_name,
- Term::Clause(cell, name, terms),
- ));
+ arg_terms
+ .push(process_term(module_name, Term::Clause(cell, name, terms)));
continue;
}
Term::Literal(cell, Literal::Atom(name)) => {
let idx = loader.get_or_insert_qualified_code_index(module_name, key);
- process_term(module_name, Term::Clause(
- cell,
- name,
- vec![Term::Literal(Cell::default(), Literal::CodeIndex(idx))],
- ))
+ process_term(
+ module_name,
+ Term::Clause(
+ cell,
+ name,
+ vec![Term::Literal(Cell::default(), Literal::CodeIndex(idx))],
+ ),
+ )
}
term => term,
};
if let ClauseType::Named(arity, name, idx) = ct {
if let Some(meta_specs) = loader.get_meta_specs(name, arity).cloned() {
let module_name = loader.payload.compilation_target.module_name();
- let terms = build_meta_predicate_clause(
- loader,
- module_name,
- terms,
- meta_specs,
- );
+ let terms = build_meta_predicate_clause(loader, module_name, terms, meta_specs);
return QueryTerm::Clause(
Cell::default(),
if let ClauseType::Named(arity, name, idx) = ct {
if let Some(meta_specs) = loader.get_meta_specs(name, arity).cloned() {
- let terms = build_meta_predicate_clause(
- loader,
- module_name,
- terms,
- meta_specs,
- );
+ let terms = build_meta_predicate_clause(loader, module_name, terms, meta_specs);
return QueryTerm::Clause(
Cell::default(),
impl Preprocessor {
pub(super) fn new(settings: CodeGenSettings) -> Self {
- Preprocessor {
- settings,
- }
+ Preprocessor { settings }
}
fn setup_fact(&mut self, term: Term) -> Result<(Fact, VarData), CompilationError> {
match term {
Term::Clause(..) | Term::Literal(_, Literal::Atom(..)) => {
- let classifier = VariableClassifier::new(
- self.settings.default_call_policy(),
- );
+ let classifier = VariableClassifier::new(self.settings.default_call_policy());
let (head, var_data) = classifier.classify_fact(term)?;
Ok((Fact { head }, var_data))
head: Term,
body: Term,
) -> Result<(Rule, VarData), CompilationError> {
- let classifier = VariableClassifier::new(
- self.settings.default_call_policy(),
- );
+ let classifier = VariableClassifier::new(self.settings.default_call_policy());
let (head, clauses, var_data) = classifier.classify_rule(loader, head, body)?;
match head {
- Term::Clause(_, name, terms) => Ok((Rule {
- head: (name, terms),
- clauses,
- }, var_data)),
- Term::Literal(_, Literal::Atom(name)) => Ok((Rule {
- head: (name, vec![]),
- clauses,
- }, var_data)),
+ Term::Clause(_, name, terms) => Ok((
+ Rule {
+ head: (name, terms),
+ clauses,
+ },
+ var_data,
+ )),
+ Term::Literal(_, Literal::Atom(name)) => Ok((
+ Rule {
+ head: (name, vec![]),
+ clauses,
+ },
+ var_data,
+ )),
_ => Err(CompilationError::InvalidRuleHead),
}
}
assert_eq!(
e,
- 0// 10 * mem::size_of::<HeapCellValue>() + prelude_size::<AndFrame>()
+ 0 // 10 * mem::size_of::<HeapCellValue>() + prelude_size::<AndFrame>()
);
assert_eq!(and_frame.prelude.num_cells, 10);
let and_frame = wam.machine_st.stack.index_and_frame_mut(next_e);
for idx in 0..9 {
- assert_eq!(and_frame[idx + 1], stack_loc_as_cell!(AndFrame, next_e, idx + 1));
+ assert_eq!(
+ and_frame[idx + 1],
+ stack_loc_as_cell!(AndFrame, next_e, idx + 1)
+ );
}
let and_frame = wam.machine_st.stack.index_and_frame(e);
use crate::parser::char_reader::*;
use crate::read::*;
+#[cfg(feature = "http")]
+use crate::http::HttpResponse;
use crate::machine::heap::*;
use crate::machine::machine_errors::*;
use crate::machine::machine_indices::*;
use crate::machine::machine_state::*;
use crate::types::*;
-#[cfg(feature = "http")]
-use crate::http::HttpResponse;
pub use modular_bitfield::prelude::*;
use std::fmt;
use std::fmt::Debug;
use std::fs::{File, OpenOptions};
-use std::hash::{Hash};
+use std::hash::Hash;
use std::io;
use std::io::{BufRead, Cursor, ErrorKind, Read, Seek, SeekFrom, Write};
use std::mem;
-use std::net::{TcpStream, Shutdown};
+use std::net::{Shutdown, TcpStream};
use std::ops::{Deref, DerefMut};
use std::ptr;
fn position(&mut self) -> Option<u64> {
// stream is the internal CharReader. subtract
// its pending buffer length from position.
- self.get_mut().file.seek(SeekFrom::Current(0))
- .map(|pos| pos - self.stream.rem_buf_len() as u64)
+ self.get_mut()
+ .file
+ .seek(SeekFrom::Current(0))
+ .map(|pos| pos - self.stream.rem_buf_len() as u64)
.ok()
}
}
#[inline(always)]
fn peek_char(&mut self) -> Option<std::io::Result<char>> {
let pos = self.stream.position() as usize;
- self.stream.get_ref()[pos ..].chars().next().map(Ok)
+ self.stream.get_ref()[pos..].chars().next().map(Ok)
}
#[inline(always)]
#[inline(always)]
fn put_back_char(&mut self, c: char) {
- self.stream.seek(SeekFrom::Current(- (c.len_utf8() as i64))).unwrap();
+ self.stream
+ .seek(SeekFrom::Current(-(c.len_utf8() as i64)))
+ .unwrap();
}
}
#[cfg(feature = "http")]
impl Debug for HttpWriteStream {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "Http Write Stream")
+ write!(f, "Http Write Stream")
}
}
impl Write for HttpWriteStream {
#[inline]
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
- self.buffer.extend_from_slice(buf);
- Ok(buf.len())
+ self.buffer.extend_from_slice(buf);
+ Ok(buf.len())
}
#[inline]
fn flush(&mut self) -> std::io::Result<()> {
- let (ready, response, cvar) = &**self.response;
-
- let mut ready = ready.lock().unwrap();
- {
- let mut response = response.lock().unwrap();
-
- let bytes = bytes::Bytes::copy_from_slice(&self.buffer);
- let mut response_ = hyper::Response::builder()
- .status(self.status_code);
- *response_.headers_mut().unwrap() = self.headers.clone();
- *response = Some(response_.body(http_body_util::Full::new(bytes)).unwrap());
- }
- *ready = true;
- cvar.notify_one();
-
- Ok(())
+ let (ready, response, cvar) = &**self.response;
+
+ let mut ready = ready.lock().unwrap();
+ {
+ let mut response = response.lock().unwrap();
+
+ let bytes = bytes::Bytes::copy_from_slice(&self.buffer);
+ let mut response_ = hyper::Response::builder().status(self.status_code);
+ *response_.headers_mut().unwrap() = self.headers.clone();
+ *response = Some(response_.body(http_body_util::Full::new(bytes)).unwrap());
+ }
+ *ready = true;
+ cvar.notify_one();
+
+ Ok(())
}
}
#[inline]
pub fn from_owned_string(string: String, arena: &mut Arena) -> Stream {
Stream::Byte(arena_alloc!(
- StreamLayout::new(CharReader::new(ByteStream(Cursor::new(string.into_bytes())))),
+ StreamLayout::new(CharReader::new(ByteStream(Cursor::new(
+ string.into_bytes()
+ )))),
arena
))
}
#[cfg(feature = "http")]
ArenaHeaderTag::HttpReadStream => Stream::HttpRead(TypedArenaPtr::new(ptr as *mut _)),
#[cfg(feature = "http")]
- ArenaHeaderTag::HttpWriteStream => Stream::HttpWrite(TypedArenaPtr::new(ptr as *mut _)),
+ ArenaHeaderTag::HttpWriteStream => Stream::HttpWrite(TypedArenaPtr::new(ptr as *mut _)),
ArenaHeaderTag::ReadlineStream => Stream::Readline(TypedArenaPtr::new(ptr as *mut _)),
ArenaHeaderTag::StaticStringStream => {
Stream::StaticString(TypedArenaPtr::new(ptr as *mut _))
#[cfg(feature = "http")]
Stream::HttpRead(ptr) => ptr.header_ptr(),
#[cfg(feature = "http")]
- Stream::HttpWrite(ptr) => ptr.header_ptr(),
+ Stream::HttpWrite(ptr) => ptr.header_ptr(),
Stream::Null(_) => ptr::null(),
Stream::Readline(ptr) => ptr.header_ptr(),
Stream::StandardOutput(ptr) => ptr.header_ptr(),
Stream::StaticString(src) => (*src).peek_char(),
Stream::Byte(cursor) => (*cursor).peek_char(),
#[cfg(feature = "http")]
- Stream::HttpWrite(_) => Some(Err(std::io::Error::new(
+ Stream::HttpWrite(_) => Some(Err(std::io::Error::new(
ErrorKind::PermissionDenied,
StreamError::ReadFromOutputStream,
))),
- Stream::OutputFile(_) |
- Stream::StandardError(_) |
- Stream::StandardOutput(_) |
- Stream::Null(_) => Some(Err(std::io::Error::new(
+ Stream::OutputFile(_)
+ | Stream::StandardError(_)
+ | Stream::StandardOutput(_)
+ | Stream::Null(_) => Some(Err(std::io::Error::new(
ErrorKind::PermissionDenied,
StreamError::ReadFromOutputStream,
))),
Stream::StaticString(src) => (*src).read_char(),
Stream::Byte(cursor) => (*cursor).read_char(),
#[cfg(feature = "http")]
- Stream::HttpWrite(_) => Some(Err(std::io::Error::new(
+ Stream::HttpWrite(_) => Some(Err(std::io::Error::new(
ErrorKind::PermissionDenied,
StreamError::ReadFromOutputStream,
))),
- Stream::OutputFile(_) |
- Stream::StandardError(_) |
- Stream::StandardOutput(_) |
- Stream::Null(_) => Some(Err(std::io::Error::new(
+ Stream::OutputFile(_)
+ | Stream::StandardError(_)
+ | Stream::StandardOutput(_)
+ | Stream::Null(_) => Some(Err(std::io::Error::new(
ErrorKind::PermissionDenied,
StreamError::ReadFromOutputStream,
))),
Stream::StaticString(src) => src.put_back_char(c),
Stream::Byte(cursor) => cursor.put_back_char(c),
#[cfg(feature = "http")]
- Stream::HttpWrite(_) => {}
- Stream::OutputFile(_) |
- Stream::StandardError(_) |
- Stream::StandardOutput(_) |
- Stream::Null(_) => {}
+ Stream::HttpWrite(_) => {}
+ Stream::OutputFile(_)
+ | Stream::StandardError(_)
+ | Stream::StandardOutput(_)
+ | Stream::Null(_) => {}
}
}
Stream::StaticString(ref mut src) => src.consume(nread),
Stream::Byte(ref mut cursor) => cursor.consume(nread),
#[cfg(feature = "http")]
- Stream::HttpWrite(_) => {}
- Stream::OutputFile(_) |
- Stream::StandardError(_) |
- Stream::StandardOutput(_) |
- Stream::Null(_) => {}
+ Stream::HttpWrite(_) => {}
+ Stream::OutputFile(_)
+ | Stream::StandardError(_)
+ | Stream::StandardOutput(_)
+ | Stream::Null(_) => {}
}
}
}
Stream::StaticString(src) => (*src).read(buf),
Stream::Byte(cursor) => (*cursor).read(buf),
#[cfg(feature = "http")]
- Stream::HttpWrite(_) => Err(std::io::Error::new(
+ Stream::HttpWrite(_) => Err(std::io::Error::new(
ErrorKind::PermissionDenied,
StreamError::ReadFromOutputStream,
)),
Stream::OutputFile(_)
- | Stream::StandardError(_)
- | Stream::StandardOutput(_)
- | Stream::Null(_) => Err(std::io::Error::new(
- ErrorKind::PermissionDenied,
- StreamError::ReadFromOutputStream,
- )),
+ | Stream::StandardError(_)
+ | Stream::StandardOutput(_)
+ | Stream::Null(_) => Err(std::io::Error::new(
+ ErrorKind::PermissionDenied,
+ StreamError::ReadFromOutputStream,
+ )),
};
bytes_read
Stream::StandardOutput(stream) => stream.write(buf),
Stream::StandardError(stream) => stream.write(buf),
#[cfg(feature = "http")]
- Stream::HttpWrite(ref mut stream) => stream.get_mut().write(buf),
+ Stream::HttpWrite(ref mut stream) => stream.get_mut().write(buf),
#[cfg(feature = "http")]
Stream::HttpRead(_) => Err(std::io::Error::new(
ErrorKind::PermissionDenied,
StreamError::WriteToInputStream,
)),
- Stream::StaticString(_) |
- Stream::Readline(_) |
- Stream::InputFile(..) |
- Stream::Null(_) => Err(std::io::Error::new(
+ Stream::StaticString(_)
+ | Stream::Readline(_)
+ | Stream::InputFile(..)
+ | Stream::Null(_) => Err(std::io::Error::new(
ErrorKind::PermissionDenied,
StreamError::WriteToInputStream,
)),
Stream::StandardError(stream) => stream.stream.flush(),
Stream::StandardOutput(stream) => stream.stream.flush(),
#[cfg(feature = "http")]
- Stream::HttpWrite(ref mut stream) => stream.stream.get_mut().flush(),
- #[cfg(feature = "http")]
+ Stream::HttpWrite(ref mut stream) => stream.stream.get_mut().flush(),
+ #[cfg(feature = "http")]
Stream::HttpRead(_) => Err(std::io::Error::new(
ErrorKind::PermissionDenied,
StreamError::FlushToInputStream,
)),
- Stream::StaticString(_) |
- Stream::Readline(_) |
- Stream::InputFile(_) |
- Stream::Null(_) => Err(std::io::Error::new(
+ Stream::StaticString(_)
+ | Stream::Readline(_)
+ | Stream::InputFile(_)
+ | Stream::Null(_) => Err(std::io::Error::new(
ErrorKind::PermissionDenied,
StreamError::FlushToInputStream,
)),
enum StreamError {
PeekByteFailed,
PeekByteFromNonPeekableStream,
- #[allow(unused)] PeekCharFailed,
- #[allow(unused)] PeekCharFromNonPeekableStream,
+ #[allow(unused)]
+ PeekCharFailed,
+ #[allow(unused)]
+ PeekCharFromNonPeekableStream,
ReadFromOutputStream,
WriteToInputStream,
FlushToInputStream,
impl Eq for Stream {}
-fn cursor_position<T>(past_end_of_stream: &mut bool, cursor: &Cursor<T>, cursor_len: u64) -> AtEndOfStream {
+fn cursor_position<T>(
+ past_end_of_stream: &mut bool,
+ cursor: &Cursor<T>,
+ cursor_len: u64,
+) -> AtEndOfStream {
let position = cursor.position();
let at_end_of_stream = match position.cmp(&cursor_len) {
Stream::StaticString(string_stream_layout) => {
Some(string_stream_layout.stream.stream.position())
}
- Stream::InputFile(file_stream) => {
- file_stream.position()
- }
+ Stream::InputFile(file_stream) => file_stream.position(),
#[cfg(feature = "tls")]
- Stream::NamedTls(..) => {
- Some(0)
- }
- Stream::NamedTcp(..)
- | Stream::Readline(..) => {
- Some(0)
- }
+ Stream::NamedTls(..) => Some(0),
+ Stream::NamedTcp(..) | Stream::Readline(..) => Some(0),
_ => None,
};
..
} = &mut **stream_layout;
- stream.get_mut().file.seek(SeekFrom::Start(position)).unwrap();
+ stream
+ .get_mut()
+ .file
+ .seek(SeekFrom::Start(position))
+ .unwrap();
stream.reset_buffer(); // flush the internal buffer.
if let Ok(metadata) = stream.get_ref().file.metadata() {
}
}
}
- _ => {
- AtEndOfStream::Not
- }
+ _ => AtEndOfStream::Not,
}
}
#[cfg(feature = "tls")]
Stream::NamedTls(..) => atom!("read_append"),
Stream::Byte(_)
- | Stream::Readline(_)
- | Stream::StaticString(_)
- | Stream::InputFile(..) => atom!("read"),
+ | Stream::Readline(_)
+ | Stream::StaticString(_)
+ | Stream::InputFile(..) => atom!("read"),
Stream::NamedTcp(..) => atom!("read_append"),
Stream::OutputFile(file) if file.is_append => atom!("append"),
#[cfg(feature = "http")]
Stream::HttpWrite(_) => atom!("write"),
- Stream::OutputFile(_) | Stream::StandardError(_) | Stream::StandardOutput(_) => atom!("write"),
+ Stream::OutputFile(_) | Stream::StandardError(_) | Stream::StandardOutput(_) => {
+ atom!("write")
+ }
Stream::Null(_) => atom!(""),
}
}
}
#[inline]
- pub(crate) fn from_tcp_stream(
- address: Atom,
- tcp_stream: TcpStream,
- arena: &mut Arena,
- ) -> Self {
+ pub(crate) fn from_tcp_stream(address: Atom, tcp_stream: TcpStream, arena: &mut Arena) -> Self {
tcp_stream.set_read_timeout(None).unwrap();
tcp_stream.set_write_timeout(None).unwrap();
#[cfg(feature = "http")]
#[inline]
pub(crate) fn from_http_sender(
- response: TypedArenaPtr<HttpResponse>,
- status_code: u16,
- headers: hyper::HeaderMap,
- arena: &mut Arena,
+ response: TypedArenaPtr<HttpResponse>,
+ status_code: u16,
+ headers: hyper::HeaderMap,
+ arena: &mut Arena,
) -> Self {
- Stream::HttpWrite(arena_alloc!(
- StreamLayout::new(CharReader::new(HttpWriteStream {
- response,
- status_code,
- headers,
- buffer: Vec::new(),
- })),
- arena
- ))
+ Stream::HttpWrite(arena_alloc!(
+ StreamLayout::new(CharReader::new(HttpWriteStream {
+ response,
+ status_code,
+ headers,
+ buffer: Vec::new(),
+ })),
+ arena
+ ))
}
#[inline]
match stream {
Stream::NamedTcp(ref mut tcp_stream) => {
tcp_stream.inner_mut().tcp_stream.shutdown(Shutdown::Both)
- },
- #[cfg(feature = "tls")]
- Stream::NamedTls(ref mut tls_stream) => {
- tls_stream.inner_mut().tls_stream.shutdown()
}
+ #[cfg(feature = "tls")]
+ Stream::NamedTls(ref mut tls_stream) => tls_stream.inner_mut().tls_stream.shutdown(),
#[cfg(feature = "http")]
Stream::HttpRead(ref mut http_stream) => {
unsafe {
Ok(())
}
#[cfg(feature = "http")]
- Stream::HttpWrite(ref mut http_stream) => {
+ Stream::HttpWrite(ref mut http_stream) => {
unsafe {
http_stream.set_tag(ArenaHeaderTag::Dropped);
std::ptr::drop_in_place(&mut http_stream.inner_mut().buffer as *mut _);
}
Ok(())
- }
+ }
Stream::InputFile(mut file_stream) => {
// close the stream by dropping the inner File.
unsafe {
Ok(())
}
- _ => Ok(())
+ _ => Ok(()),
}
}
#[cfg(feature = "http")]
Stream::HttpRead(..) => true,
Stream::NamedTcp(..)
- | Stream::Byte(_)
- | Stream::Readline(_)
- | Stream::StaticString(_)
- | Stream::InputFile(..) => true,
+ | Stream::Byte(_)
+ | Stream::Readline(_)
+ | Stream::StaticString(_)
+ | Stream::InputFile(..) => true,
_ => false,
}
}
#[cfg(feature = "http")]
Stream::HttpWrite(..) => true,
Stream::StandardError(_)
- | Stream::StandardOutput(_)
- | Stream::NamedTcp(..)
- | Stream::Byte(_)
- | Stream::OutputFile(..) => true,
+ | Stream::StandardOutput(_)
+ | Stream::NamedTcp(..)
+ | Stream::Byte(_)
+ | Stream::OutputFile(..) => true,
_ => false,
}
}
return true;
}
Stream::InputFile(ref mut file_stream) => {
- file_stream.stream.get_mut().file.seek(SeekFrom::Start(0)).unwrap();
+ file_stream
+ .stream
+ .get_mut()
+ .file
+ .seek(SeekFrom::Start(0))
+ .unwrap();
return true;
}
Stream::Readline(ref mut readline_stream) => {
_ => Err(std::io::Error::new(ErrorKind::UnexpectedEof, "end of file")),
}
}
- Stream::InputFile(ref mut file) => {
- match file.peek_byte() {
- Some(result) => {
- Ok(result?)
- }
- _ => Err(std::io::Error::new(
- ErrorKind::UnexpectedEof,
- StreamError::PeekByteFailed,
- )),
- }
- }
+ Stream::InputFile(ref mut file) => match file.peek_byte() {
+ Some(result) => Ok(result?),
+ _ => Err(std::io::Error::new(
+ ErrorKind::UnexpectedEof,
+ StreamError::PeekByteFailed,
+ )),
+ },
Stream::Readline(ref mut stream) => stream.stream.peek_byte(),
Stream::NamedTcp(ref mut stream) => {
let mut b = [0u8; 1];
}
}
- pub(crate) fn open_parsing_stream(&mut self, mut stream: Stream) -> Result<Stream, ParserError> {
+ pub(crate) fn open_parsing_stream(
+ &mut self,
+ mut stream: Stream,
+ ) -> Result<Stream, ParserError> {
match stream.peek_char() {
None => Ok(stream), // empty stream is handled gracefully by Lexer::eof
Some(Err(e)) => Err(ParserError::IO(e)),
arity: usize,
) -> MachineStub {
let stub = functor_stub(caller, arity);
- let err = self.permission_error(
+ let err = self.permission_error(
perm,
err_atom,
if let Some(alias) = stream.options().get_alias() {
stub_arity: usize,
) -> MachineStub {
let stub = functor_stub(stub_name, stub_arity);
- let err = self.permission_error(Permission::Open, atom!("source_sink"), culprit);
+ let err = self.permission_error(Permission::Open, atom!("source_sink"), culprit);
self.error_form(err, stub)
}
// 8.11.5.3j)
let stub = functor_stub(atom!("open"), 4);
- let err = self.existence_error(
- ExistenceError::SourceSink(self[temp_v!(1)]),
- );
+ let err =
+ self.existence_error(ExistenceError::SourceSink(self[temp_v!(1)]));
return Err(self.error_form(err, stub));
}
ErrorKind::PermissionDenied => {
// 8.11.5.3k)
- return Err(self.open_permission_error(self.registers[1], atom!("open"), 4));
+ return Err(self.open_permission_error(
+ self.registers[1],
+ atom!("open"),
+ 4,
+ ));
}
_ => {
let stub = functor_stub(atom!("open"), 4);
use crate::arena::*;
use crate::atom_table::*;
-use crate::forms::*;
#[cfg(feature = "ffi")]
use crate::ffi::*;
+use crate::forms::*;
use crate::heap_iter::*;
use crate::heap_print::*;
#[cfg(feature = "http")]
-use crate::http::{HttpService, HttpListener, HttpResponse};
+use crate::http::{HttpListener, HttpResponse, HttpService};
use crate::instructions::*;
use crate::machine;
-use crate::machine::{Machine, VERIFY_ATTR_INTERRUPT_LOC, get_structure_index};
use crate::machine::code_walker::*;
use crate::machine::copier::*;
use crate::machine::heap::*;
use crate::machine::preprocessor::to_op_decl;
use crate::machine::stack::*;
use crate::machine::streams::*;
+use crate::machine::{get_structure_index, Machine, VERIFY_ATTR_INTERRUPT_LOC};
use crate::parser::char_reader::*;
use crate::parser::dashu::Integer;
use crate::read::*;
use crate::types::*;
-use rand::{Rng, SeedableRng};
use rand::rngs::StdRng;
+use rand::{Rng, SeedableRng};
use ordered_float::OrderedFloat;
use std::io::{ErrorKind, Read, Write};
use std::iter::{once, FromIterator};
use std::mem;
-use std::net::{TcpListener, TcpStream, SocketAddr, ToSocketAddrs};
+use std::net::{SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
use std::num::NonZeroU32;
use std::ops::Sub;
use std::process;
use crrl::{secp256k1, x25519};
#[cfg(feature = "tls")]
-use native_tls::{TlsConnector,TlsAcceptor,Identity};
+use native_tls::{Identity, TlsAcceptor, TlsConnector};
use base64;
use roxmltree;
use select;
+use bytes::Buf;
+use http_body_util::BodyExt;
#[cfg(feature = "http")]
-use hyper::server::conn::http1;
+use hyper::header::{HeaderName, HeaderValue};
#[cfg(feature = "http")]
-use hyper::header::{HeaderValue, HeaderName};
+use hyper::server::conn::http1;
#[cfg(feature = "http")]
use hyper::{HeaderMap, Method};
-use http_body_util::BodyExt;
-use bytes::Buf;
#[cfg(feature = "http")]
use reqwest::Url;
}
}
- fn add_pstr_offset_chars(&mut self, heap: &[HeapCellValue], h: usize, offset: usize) -> Option<CycleSearchResult> {
+ fn add_pstr_offset_chars(
+ &mut self,
+ heap: &[HeapCellValue],
+ h: usize,
+ offset: usize,
+ ) -> Option<CycleSearchResult> {
read_heap_cell!(heap[h],
(HeapCellValueTag::CStr, cstr_atom) => {
let cstr = PartialString::from(cstr_atom);
)
}
- fn add_pstr_chars_and_step(&mut self, heap: &[HeapCellValue], h: usize) -> Option<CycleSearchResult> {
+ fn add_pstr_chars_and_step(
+ &mut self,
+ heap: &[HeapCellValue],
+ h: usize,
+ ) -> Option<CycleSearchResult> {
read_heap_cell!(heap[h],
(HeapCellValueTag::PStrOffset, l) => {
let (pstr_loc, offset) = pstr_loc_and_offset(heap, l);
#[derive(Debug)]
enum MatchSite {
NoMatchVarTail(usize), // no match, we refer to the location of the uninstantiated tail instead.
- Match(usize), // a match
+ Match(usize), // a match
}
#[derive(Debug)]
let mut hare = h;
let mut tortoise = hare;
- for _ in 0 .. lam {
+ for _ in 0..lam {
hare = step(&self.heap, self.heap[hare]);
}
fn skip_max_list_result(&mut self, max_steps: i64) {
let search_result = if max_steps == -1 {
- BrentAlgState::detect_cycles(
- &self.heap,
- self.store(self.deref(self.registers[3])),
- )
+ BrentAlgState::detect_cycles(&self.heap, self.store(self.deref(self.registers[3])))
} else {
BrentAlgState::detect_cycles_with_max(
&self.heap,
match search_result {
CycleSearchResult::PStrLocation(steps, pstr_loc, offset) => {
- let steps = if max_steps > - 1 {
+ let steps = if max_steps > -1 {
std::cmp::min(max_steps, steps as i64)
} else {
steps as i64
let h = self.heap.len();
self.heap.push(pstr_offset_as_cell!(pstr_loc));
- self.heap.push(fixnum_as_cell!(Fixnum::build_with(offset as i64)));
+ self.heap
+ .push(fixnum_as_cell!(Fixnum::build_with(offset as i64)));
pstr_loc_as_cell!(h)
} else {
self.heap.push(string_as_cstr_cell!(cstr_atom));
self.heap.push(pstr_offset_as_cell!(h));
- self.heap.push(fixnum_as_cell!(Fixnum::build_with(n as i64)));
+ self.heap
+ .push(fixnum_as_cell!(Fixnum::build_with(n as i64)));
- pstr_loc_as_cell!(h+1)
+ pstr_loc_as_cell!(h + 1)
} else {
string_as_cstr_cell!(cstr_atom)
};
}
}
- let outcome = heap_loc_as_cell!(
- iter_to_heap_list(
- &mut self.heap,
- seen_set.into_iter(),
- )
- );
+ let outcome = heap_loc_as_cell!(iter_to_heap_list(&mut self.heap, seen_set.into_iter(),));
unify_fn!(*self, list_of_vars, outcome);
}
self.block
}
- pub(crate) fn copy_findall_solution(&mut self, lh_offset: usize, copy_target: HeapCellValue) -> usize {
+ pub(crate) fn copy_findall_solution(
+ &mut self,
+ lh_offset: usize,
+ copy_target: HeapCellValue,
+ ) -> usize {
let threshold = self.lifted_heap.len() - lh_offset;
let mut copy_ball_term =
let key = (*name, *arity);
if let Some((last_idx, _, _)) = indices.code_dir.get_full(&key) {
- for idx in last_idx + 1 .. indices.code_dir.len() {
+ for idx in last_idx + 1..indices.code_dir.len() {
let ((name, arity), idx) = indices.code_dir.get_index(idx).unwrap();
if idx.is_undefined() {
let key = (*name, *fixity);
if let Some((last_idx, _, _)) = op_dir.get_full(&key) {
- if let Some(((name, fixity), _)) = op_dir.get_index(last_idx+1) {
+ if let Some(((name, fixity), _)) = op_dir.get_index(last_idx + 1) {
return Some(DBRef::Op(*name, *fixity, *op_dir));
}
}
let add_dot = !string.ends_with(".");
let cursor = std::io::Cursor::new(string);
- let iter = std::io::Read::chain(
- cursor,
- {
- let mut dot_buf: [u8; '.'.len_utf8()] = [0u8];
+ let iter = std::io::Read::chain(cursor, {
+ let mut dot_buf: [u8; '.'.len_utf8()] = [0u8];
- if add_dot {
- '.'.encode_utf8(&mut dot_buf);
- }
+ if add_dot {
+ '.'.encode_utf8(&mut dot_buf);
+ }
- std::io::Cursor::new(dot_buf)
- },
- );
+ std::io::Cursor::new(dot_buf)
+ });
let mut lexer = Lexer::new(CharReader::new(iter), self);
let mut tokens = vec![];
Ok(())
}
- pub(crate) fn call_continuation_chunk(&mut self, chunk: HeapCellValue, return_p: usize) -> usize {
+ pub(crate) fn call_continuation_chunk(
+ &mut self,
+ chunk: HeapCellValue,
+ return_p: usize,
+ ) -> usize {
let chunk = self.store(self.deref(chunk));
let s = chunk.get_value() as usize;
let addr = self.store(self.deref(addr));
match Number::try_from(addr) {
- Ok(Number::Fixnum(n)) => {
- match u32::try_from(n.get_num()) {
- Ok(n) => {
- if let Some(c) = std::char::from_u32(n) {
- string.push(c);
- continue;
- }
+ Ok(Number::Fixnum(n)) => match u32::try_from(n.get_num()) {
+ Ok(n) => {
+ if let Some(c) = std::char::from_u32(n) {
+ string.push(c);
+ continue;
}
- _ => {}
}
- }
+ _ => {}
+ },
Ok(Number::Integer(n)) => {
if let Some(c) = n.to_u32().and_then(std::char::from_u32) {
string.push(c);
if let HeapCellValueTag::AttrVar = attr_var.get_tag() {
let attr_var_loc = attr_var.get_value() as usize;
self.machine_st.heap[attr_var_loc] = heap_loc_as_cell!(attr_var_loc);
- self.machine_st.trail(TrailRef::Ref(Ref::attr_var(attr_var_loc)));
+ self.machine_st
+ .trail(TrailRef::Ref(Ref::attr_var(attr_var_loc)));
}
}
CompilationTarget::Module(module_name)
};
- let skeleton = self.indices.get_predicate_skeleton(
- &compilation_target,
- &key,
- ).unwrap();
+ let skeleton = self
+ .indices
+ .get_predicate_skeleton(&compilation_target, &key)
+ .unwrap();
if self.machine_st.b > self.machine_st.e {
let or_frame = self.machine_st.stack.index_or_frame(self.machine_st.b);
let p = or_frame.prelude.biip as usize - 1;
match &indexed_choice[p] {
- &IndexedChoiceInstruction::Try(offset) |
- &IndexedChoiceInstruction::Retry(offset) |
- &IndexedChoiceInstruction::DefaultRetry(offset) => {
+ &IndexedChoiceInstruction::Try(offset)
+ | &IndexedChoiceInstruction::Retry(offset)
+ | &IndexedChoiceInstruction::DefaultRetry(offset) => {
let clause_clause_loc = skeleton.core.clause_clause_locs[p];
(clause_clause_loc, bp + offset)
}
- &IndexedChoiceInstruction::Trust(_) |
- &IndexedChoiceInstruction::DefaultTrust(_) => {
+ &IndexedChoiceInstruction::Trust(_)
+ | &IndexedChoiceInstruction::DefaultTrust(_) => {
unreachable!()
}
}
}
}
}
- _ => unreachable!()
+ _ => unreachable!(),
}
} else {
let module_name = match compilation_target {
CompilationTarget::Module(target) => target,
};
- let bp = self.indices
+ let bp = self
+ .indices
.get_predicate_code_index(atom!("$clause"), 2, module_name)
.and_then(|idx| idx.local())
.unwrap();
macro_rules! extract_ptr {
($ptr: expr) => {
match $ptr {
- IndexingCodePtr::External(p) => return (
- skeleton.core.clause_clause_locs.back().cloned().unwrap(),
- bp + p,
- ),
+ IndexingCodePtr::External(p) => {
+ return (
+ skeleton.core.clause_clause_locs.back().cloned().unwrap(),
+ bp + p,
+ )
+ }
IndexingCodePtr::Internal(boip) => boip,
_ => unreachable!(),
}
match &self.code[bp] {
&Instruction::IndexingCode(ref indexing_code) => {
let indexing_code_ptr = match &indexing_code[0] {
- &IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(_, _, c, _, s)) => {
- if key.1 > 0 { s } else { c }
+ &IndexingLine::Indexing(IndexingInstruction::SwitchOnTerm(
+ _,
+ _,
+ c,
+ _,
+ s,
+ )) => {
+ if key.1 > 0 {
+ s
+ } else {
+ c
+ }
}
_ => {
unreachable!()
}
}
_ => {
- return (skeleton.core.clause_clause_locs.back().cloned().unwrap(), bp);
+ return (
+ skeleton.core.clause_clause_locs.back().cloned().unwrap(),
+ bp,
+ );
}
}
}
#[inline(always)]
pub(crate) fn deref_register(&self, i: usize) -> HeapCellValue {
- self.machine_st.store(self.machine_st.deref(self.machine_st.registers[i]))
+ self.machine_st
+ .store(self.machine_st.deref(self.machine_st.registers[i]))
}
#[inline(always)]
call_at_index: impl Fn(&mut Machine, Atom, usize, IndexPtr) -> CallResult,
) -> CallResult {
let arity = arity - 1;
- let (mut module_name, mut goal) = self.machine_st.strip_module(
- self.machine_st.registers[1],
- heap_loc_as_cell!(0),
- );
+ let (mut module_name, mut goal) = self
+ .machine_st
+ .strip_module(self.machine_st.registers[1], heap_loc_as_cell!(0));
- let load_registers = |machine_st: &mut MachineState, goal: HeapCellValue, goal_arity: usize| {
+ let load_registers = |machine_st: &mut MachineState,
+ goal: HeapCellValue,
+ goal_arity: usize| {
read_heap_cell!(goal,
(HeapCellValueTag::Str | HeapCellValueTag::Atom, s) => {
if goal_arity > 1 {
} else {
if is_internal_call {
debug_assert_eq!(goal.get_tag(), HeapCellValueTag::Str);
- goal = self.machine_st.heap[goal.get_value() as usize+1];
+ goal = self.machine_st.heap[goal.get_value() as usize + 1];
(module_name, goal) = self.machine_st.strip_module(goal, module_name);
- if let Some((inner_name, inner_arity)) = self.machine_st.name_and_arity_from_heap(goal) {
+ if let Some((inner_name, inner_arity)) =
+ self.machine_st.name_and_arity_from_heap(goal)
+ {
arity -= goal_arity;
(name, goal_arity) = (inner_name, inner_arity);
arity += goal_arity;
cell_as_atom!(module_name)
};
- self.indices.get_predicate_code_index(name, arity, module_name)
+ self.indices
+ .get_predicate_code_index(name, arity, module_name)
}
});
// complete_partial_goal prior to goal_expansion.
let mut supp_vars = IndexSet::with_hasher(FxBuildHasher::default());
- self.machine_st.variable_set(&mut supp_vars, self.machine_st.registers[2]);
+ self.machine_st
+ .variable_set(&mut supp_vars, self.machine_st.registers[2]);
struct GoalAnalysisResult {
is_simple_goal: bool,
let expanded_term = if result.is_simple_goal {
let idx = self.get_or_insert_qualified_code_index(module_name, result.key);
- self.machine_st.heap.push(untyped_arena_ptr_as_cell!(UntypedArenaPtr::from(idx)));
+ self.machine_st
+ .heap
+ .push(untyped_arena_ptr_as_cell!(UntypedArenaPtr::from(idx)));
result.goal
} else {
// all supp_vars must appear later!
let vars = IndexSet::<HeapCellValue, BuildHasherDefault<FxHasher>>::from_iter(
- result.expanded_vars.difference(&result.supp_vars).cloned()
+ result.expanded_vars.difference(&result.supp_vars).cloned(),
);
let vars: Vec<_> = vars
&mut self.machine_st.arena,
);
- self.machine_st.heap.push(untyped_arena_ptr_as_cell!(UntypedArenaPtr::from(idx)));
+ self.machine_st
+ .heap
+ .push(untyped_arena_ptr_as_cell!(UntypedArenaPtr::from(idx)));
str_loc_as_cell!(h)
}
#[inline(always)]
pub(crate) fn is_expanded_or_inlined(&self) -> bool {
- let (_module_loc, qualified_goal) = self.machine_st.strip_module(
- self.machine_st.registers[1],
- empty_list_as_cell!(),
- );
+ let (_module_loc, qualified_goal) = self
+ .machine_st
+ .strip_module(self.machine_st.registers[1], empty_list_as_cell!());
if HeapCellValueTag::Str == qualified_goal.get_tag() {
let s = qualified_goal.get_value() as usize;
- let (name, arity) = cell_as_atom_cell!(self.machine_st.heap[s])
- .get_name_and_arity();
+ let (name, arity) = cell_as_atom_cell!(self.machine_st.heap[s]).get_name_and_arity();
if name == atom!("$call") {
return false;
#[inline(always)]
pub(crate) fn strip_module(&mut self) {
- let (module_loc, qualified_goal) = self.machine_st.strip_module(
- self.machine_st.registers[1],
- self.machine_st.registers[2],
- );
+ let (module_loc, qualified_goal) = self
+ .machine_st
+ .strip_module(self.machine_st.registers[1], self.machine_st.registers[2]);
let target_module_loc = self.machine_st.registers[2];
- unify_fn!(
- &mut self.machine_st,
- module_loc,
- target_module_loc
- );
+ unify_fn!(&mut self.machine_st, module_loc, target_module_loc);
let target_qualified_goal = self.machine_st.registers[3];
- unify_fn!(
- &mut self.machine_st,
- qualified_goal,
- target_qualified_goal
- );
+ unify_fn!(&mut self.machine_st, qualified_goal, target_qualified_goal);
}
#[inline(always)]
// the first two arguments don't belong to the containing call/N.
let arity = arity - 2;
- let (name, narity, s) = self.machine_st.setup_call_n_init_goal_info(
- qualified_goal,
- arity,
- )?;
+ let (name, narity, s) = self
+ .machine_st
+ .setup_call_n_init_goal_info(qualified_goal, arity)?;
// assemble goal from pre-loaded (narity) and supplementary
// (arity) arguments.
let target_goal = if arity == 0 {
qualified_goal
- } else { // if narity + arity > 0 {
+ } else {
+ // if narity + arity > 0 {
let h = self.machine_st.heap.len();
- self.machine_st.heap.push(atom_as_cell!(name, narity + arity));
+ self.machine_st
+ .heap
+ .push(atom_as_cell!(name, narity + arity));
- for idx in 1 .. narity + 1 {
+ for idx in 1..narity + 1 {
self.machine_st.heap.push(self.machine_st.heap[s + idx]);
}
- for idx in 1 .. arity + 1 {
- self.machine_st.heap.push(self.machine_st.registers[2 + idx]);
+ for idx in 1..arity + 1 {
+ self.machine_st
+ .heap
+ .push(self.machine_st.registers[2 + idx]);
}
if narity + arity > 0 {
let target_qualified_goal = self.machine_st.registers[1];
- unify_fn!(
- &mut self.machine_st,
- target_goal,
- target_qualified_goal
- );
+ unify_fn!(&mut self.machine_st, target_goal, target_qualified_goal);
Ok(())
}
#[inline(always)]
pub(crate) fn is_reset_cont_marker(&self, p: usize) -> bool {
match &self.code[p] {
- &Instruction::CallResetContinuationMarker |
- &Instruction::ExecuteResetContinuationMarker => true,
- _ => false
+ &Instruction::CallResetContinuationMarker
+ | &Instruction::ExecuteResetContinuationMarker => true,
+ _ => false,
}
}
let hostname = self.machine_st.atom_tbl.build_with(host);
let a1 = self.deref_register(1);
- self.machine_st.unify_atom(
- hostname,
- a1
- );
+ self.machine_st.unify_atom(hostname, a1);
return;
}
#[inline(always)]
pub(crate) fn directory_files(&mut self) -> CallResult {
- if let Some(dir) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
+ if let Some(dir) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
let path = std::path::Path::new(dir.as_str());
let mut files = Vec::new();
return Err(err);
}
- let files_list = heap_loc_as_cell!(
- iter_to_heap_list(&mut self.machine_st.heap, files.into_iter())
- );
+ let files_list = heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ files.into_iter()
+ ));
unify!(self.machine_st, self.machine_st.registers[2], files_list);
return Ok(());
#[inline(always)]
pub(crate) fn file_size(&mut self) {
- if let Some(file) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
+ if let Some(file) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
let len = Number::arena_from(
fs::metadata(file.as_str()).unwrap().len(),
&mut self.machine_st.arena,
);
match len {
- Number::Fixnum(n) => self.machine_st.unify_fixnum(n, self.machine_st.registers[2]),
- Number::Integer(n) => self.machine_st.unify_big_int(n, self.machine_st.registers[2]),
+ Number::Fixnum(n) => self
+ .machine_st
+ .unify_fixnum(n, self.machine_st.registers[2]),
+ Number::Integer(n) => self
+ .machine_st
+ .unify_big_int(n, self.machine_st.registers[2]),
_ => unreachable!(),
}
} else {
#[inline(always)]
pub(crate) fn file_exists(&mut self) {
- if let Some(file) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
+ if let Some(file) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
let file_str = file.as_str();
- if !std::path::Path::new(file_str).exists() || !fs::metadata(file_str).unwrap().is_file() {
+ if !std::path::Path::new(file_str).exists()
+ || !fs::metadata(file_str).unwrap().is_file()
+ {
self.machine_st.fail = true;
}
} else {
#[inline(always)]
pub(crate) fn directory_exists(&mut self) {
- if let Some(dir) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
+ if let Some(dir) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
let dir_str = dir.as_str();
if !std::path::Path::new(dir_str).exists() || !fs::metadata(dir_str).unwrap().is_dir() {
#[inline(always)]
pub(crate) fn file_time(&mut self) {
- if let Some(file) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
+ if let Some(file) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
let which = cell_as_atom!(self.deref_register(2));
if let Ok(md) = fs::metadata(file.as_str()) {
} {
let chars_atom = self.systemtime_to_timestamp(time);
- self.machine_st.unify_complete_string(
- chars_atom,
- self.machine_st.registers[3],
- );
+ self.machine_st
+ .unify_complete_string(chars_atom, self.machine_st.registers[3]);
return;
}
#[inline(always)]
pub(crate) fn directory_separator(&mut self) {
- self.machine_st.unify_char(std::path::MAIN_SEPARATOR, self.machine_st.registers[1]);
+ self.machine_st
+ .unify_char(std::path::MAIN_SEPARATOR, self.machine_st.registers[1]);
}
#[inline(always)]
pub(crate) fn make_directory(&mut self) {
- if let Some(dir) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
+ if let Some(dir) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
match fs::create_dir(dir.as_str()) {
Ok(_) => {}
_ => {
#[inline(always)]
pub(crate) fn make_directory_path(&mut self) {
- if let Some(dir) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
-
+ if let Some(dir) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
match fs::create_dir_all(dir.as_str()) {
Ok(_) => {}
_ => {
#[inline(always)]
pub(crate) fn delete_file(&mut self) {
- if let Some(file) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
+ if let Some(file) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
match fs::remove_file(file.as_str()) {
Ok(_) => {}
_ => {
#[inline(always)]
pub(crate) fn rename_file(&mut self) {
- if let Some(file) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
- if let Some(renamed) = self.machine_st.value_to_str_like(self.machine_st.registers[2]) {
+ if let Some(file) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
+ if let Some(renamed) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[2])
+ {
if fs::rename(file.as_str(), renamed.as_str()).is_ok() {
return;
}
#[inline(always)]
pub(crate) fn file_copy(&mut self) {
- if let Some(file) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
- if let Some(copied) = self.machine_st.value_to_str_like(self.machine_st.registers[2]) {
- if fs::copy(file.as_str(), copied.as_str()).is_ok() {
- return;
- }
- }
- }
+ if let Some(file) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
+ if let Some(copied) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[2])
+ {
+ if fs::copy(file.as_str(), copied.as_str()).is_ok() {
+ return;
+ }
+ }
+ }
- self.machine_st.fail = true;
+ self.machine_st.fail = true;
}
#[inline(always)]
pub(crate) fn delete_directory(&mut self) {
- if let Some(dir) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
+ if let Some(dir) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
match fs::remove_dir(dir.as_str()) {
Ok(_) => {}
_ => {
let current_atom = self.machine_st.atom_tbl.build_with(¤t);
let a1 = self.deref_register(1);
- self.machine_st.unify_complete_string(
- current_atom,
- a1
- );
+ self.machine_st.unify_complete_string(current_atom, a1);
if self.machine_st.fail {
return Ok(());
#[inline(always)]
pub(crate) fn path_canonical(&mut self) -> CallResult {
- if let Some(path) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
+ if let Some(path) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
match fs::canonicalize(path.as_str()) {
Ok(canonical) => {
let cs = match canonical.to_str() {
let canonical_atom = self.machine_st.atom_tbl.build_with(cs);
let a2 = self.deref_register(2);
- self.machine_st.unify_complete_string(
- canonical_atom,
- a2
- );
+ self.machine_st.unify_complete_string(canonical_atom, a2);
return Ok(());
}
- _ => {
- }
+ _ => {}
}
}
);
let a2 = self.deref_register(2);
- self.machine_st.unify_fixnum(
- Fixnum::build_with(len),
- a2,
- );
+ self.machine_st.unify_fixnum(Fixnum::build_with(len), a2);
}
#[inline(always)]
let a1 = self.deref_register(1);
let atom_or_string = self.machine_st.value_to_str_like(a1).unwrap();
- self.machine_st.parse_number_from_string(
- atom_or_string.as_str(),
- &self.indices,
- stub_gen,
- )
+ self.machine_st
+ .parse_number_from_string(atom_or_string.as_str(), &self.indices, stub_gen)
}
#[inline(always)]
pub(crate) fn create_partial_string(&mut self) {
- let atom = cell_as_atom!(
- self.deref_register(1)
- );
+ let atom = cell_as_atom!(self.deref_register(1));
if atom == atom!("") {
self.machine_st.fail = true;
let pstr_h = self.machine_st.heap.len();
self.machine_st.heap.push(pstr_as_cell!(atom));
- self.machine_st.heap.push(heap_loc_as_cell!(pstr_h+1));
+ self.machine_st.heap.push(heap_loc_as_cell!(pstr_h + 1));
- unify!(self.machine_st, self.machine_st.registers[2], pstr_loc_as_cell!(pstr_h));
+ unify!(
+ self.machine_st,
+ self.machine_st.registers[2],
+ pstr_loc_as_cell!(pstr_h)
+ );
if !self.machine_st.fail {
let tail = self.machine_st.registers[3];
- unify!(self.machine_st, tail, heap_loc_as_cell!(pstr_h+1));
+ unify!(self.machine_st, tail, heap_loc_as_cell!(pstr_h + 1));
}
}
let addr = self.deref_register(2);
if stream.at_end_of_stream() {
- self.machine_st.unify_fixnum(
- Fixnum::build_with(-1),
- addr,
- );
+ self.machine_st.unify_fixnum(Fixnum::build_with(-1), addr);
if self.machine_st.fail {
self.machine_st.fail = false;
loop {
match stream.peek_byte().map_err(|e| e.kind()) {
Ok(b) => {
- self.machine_st.unify_fixnum(Fixnum::build_with(b as i64), addr);
+ self.machine_st
+ .unify_fixnum(Fixnum::build_with(b as i64), addr);
break;
}
Err(ErrorKind::PermissionDenied) => {
if stream.at_end_of_stream() {
let end_of_file = atom!("end_of_file");
- self.machine_st.unify_atom(
- end_of_file,
- a2,
- );
+ self.machine_st.unify_atom(end_of_file, a2);
return Ok(());
}
);
loop {
- match stream.peek_char().map(|result| result.map_err(|e| e.kind())) {
+ match stream
+ .peek_char()
+ .map(|result| result.map_err(|e| e.kind()))
+ {
Some(Ok(d)) => {
self.machine_st.unify_char(d, a2);
break;
let a2 = self.deref_register(2);
if stream.at_end_of_stream() {
- self.machine_st.unify_fixnum(
- Fixnum::build_with(-1),
- a2,
- );
+ self.machine_st.unify_fixnum(Fixnum::build_with(-1), a2);
if self.machine_st.fail {
self.machine_st.fail = false;
match result.map(|result| result.map_err(|e| e.kind())) {
Some(Ok(c)) => {
- self.machine_st.unify_fixnum(Fixnum::build_with(c as i64), addr);
+ self.machine_st
+ .unify_fixnum(Fixnum::build_with(c as i64), addr);
break;
}
Some(Err(ErrorKind::PermissionDenied)) => {
let chs = self.deref_register(2);
let string = match Number::try_from(n) {
- Ok(Number::Float(OrderedFloat(n))) => {
- fmt_float(n)
- }
+ Ok(Number::Float(OrderedFloat(n))) => fmt_float(n),
Ok(Number::Fixnum(n)) => n.get_num().to_string(),
Ok(Number::Integer(n)) => n.to_string(),
Ok(Number::Rational(r)) => {
};
let chars_atom = self.machine_st.atom_tbl.build_with(&string.trim());
- self.machine_st.unify_complete_string(
- chars_atom,
- chs,
- );
+ self.machine_st.unify_complete_string(chars_atom, chs);
}
#[inline(always)]
}
};
- let codes = string.trim().chars().map(|c| {
- fixnum_as_cell!(Fixnum::build_with(c as i64))
- });
+ let codes = string
+ .trim()
+ .chars()
+ .map(|c| fixnum_as_cell!(Fixnum::build_with(c as i64)));
let h = iter_to_heap_list(&mut self.machine_st.heap, codes);
unify!(self.machine_st, heap_loc_as_cell!(h), chs);
pub(crate) fn codes_to_number(&mut self) -> CallResult {
let stub_gen = || functor_stub(atom!("number_codes"), 2);
- match self.machine_st.try_from_list(self.machine_st.registers[1], stub_gen) {
+ match self
+ .machine_st
+ .try_from_list(self.machine_st.registers[1], stub_gen)
+ {
Err(e) => {
return Err(e);
}
Ok(addrs) => {
- let string = self.machine_st.codes_to_string(addrs.into_iter(), stub_gen)?;
- self.machine_st.parse_number_from_string(string.as_str(), &self.indices, stub_gen)?;
+ let string = self
+ .machine_st
+ .codes_to_string(addrs.into_iter(), stub_gen)?;
+ self.machine_st.parse_number_from_string(
+ string.as_str(),
+ &self.indices,
+ stub_gen,
+ )?;
}
}
}
);
- self.machine_st.unify_fixnum(
- Fixnum::build_with(c as i64),
- a2,
- );
+ self.machine_st
+ .unify_fixnum(Fixnum::build_with(c as i64), a2);
Ok(())
}
self.machine_st.fail = true; // This predicate fails by default.
read_heap_cell!(a2,
- (HeapCellValueTag::Atom, (chars, _arity)) => {
- macro_rules! macro_check {
- ($id:ident, $name:expr) => {
- if $id!(c) && chars == $name {
- self.machine_st.fail = false;
- return;
- }
- };
- }
-
- macro_rules! method_check {
- ($id:ident, $name:expr) => {
- if c.$id() && chars == $name {
- self.machine_st.fail = false;
- return;
- }
- };
- }
-
- macro_check!(alpha_char, atom!("alpha"));
- method_check!(is_alphabetic, atom!("alphabetic"));
- method_check!(is_alphanumeric, atom!("alphanumeric"));
- macro_check!(alpha_numeric_char, atom!("alnum"));
- method_check!(is_ascii, atom!("ascii"));
- method_check!(is_ascii_punctuation, atom!("ascii_punctuation"));
- method_check!(is_ascii_graphic, atom!("ascii_graphic"));
- // macro_check!(backslash_char, atom!("backslash"));
- // macro_check!(back_quote_char, atom!("back_quote"));
- macro_check!(binary_digit_char, atom!("binary_digit"));
- // macro_check!(capital_letter_char, atom!("upper"));
- // macro_check!(comment_1_char, "comment_1");
- // macro_check!(comment_2_char, "comment_2");
- method_check!(is_control, atom!("control"));
- // macro_check!(cut_char, atom!("cut"));
- macro_check!(decimal_digit_char, atom!("decimal_digit"));
- // macro_check!(decimal_point_char, atom!("decimal_point"));
- // macro_check!(double_quote_char, atom!("double_quote"));
- macro_check!(exponent_char, atom!("exponent"));
- macro_check!(graphic_char, atom!("graphic"));
- macro_check!(graphic_token_char, atom!("graphic_token"));
- macro_check!(hexadecimal_digit_char, atom!("hexadecimal_digit"));
- macro_check!(layout_char, atom!("layout"));
- method_check!(is_lowercase, atom!("lower"));
- macro_check!(meta_char, atom!("meta"));
- // macro_check!(new_line_char, atom!("new_line"));
- method_check!(is_numeric, atom!("numeric"));
- macro_check!(octal_digit_char, atom!("octal_digit"));
- macro_check!(octet_char, atom!("octet"));
- macro_check!(prolog_char, atom!("prolog"));
- // macro_check!(semicolon_char, atom!("semicolon"));
- macro_check!(sign_char, atom!("sign"));
- // macro_check!(single_quote_char, atom!("single_quote"));
- // macro_check!(small_letter_char, atom!("lower"));
- macro_check!(solo_char, atom!("solo"));
- // macro_check!(space_char, atom!("space"));
- macro_check!(symbolic_hexadecimal_char, atom!("symbolic_hexadecimal"));
- macro_check!(symbolic_control_char, atom!("symbolic_control"));
- method_check!(is_uppercase, atom!("upper"));
- // macro_check!(variable_indicator_char, atom!("variable_indicator"));
- method_check!(is_whitespace, atom!("whitespace"));
- }
- (HeapCellValueTag::Str, s) => {
- let (name, arity) = cell_as_atom_cell!(self.machine_st.heap[s])
- .get_name_and_arity();
-
- match (name, arity) {
- (atom!("to_upper"), 1) => {
- let reg = self.machine_st.deref(self.machine_st.heap[s+1]);
- let atom = self.machine_st.atom_tbl.build_with(&c.to_uppercase().to_string());
- let upper_str = string_as_cstr_cell!(atom);
- unify!(self.machine_st, reg, upper_str);
- self.machine_st.fail = false;
- }
- (atom!("to_lower"), 1) => {
- let reg = self.machine_st.deref(self.machine_st.heap[s+1]);
- let atom = self.machine_st.atom_tbl.build_with(&c.to_lowercase().to_string());
- let lower_str = string_as_cstr_cell!(atom);
- unify!(self.machine_st, reg, lower_str);
- self.machine_st.fail = false;
- }
- _ => {
- unreachable!()
- }
- };
- }
- _ => {
- unreachable!()
- }
- );
+ (HeapCellValueTag::Atom, (chars, _arity)) => {
+ macro_rules! macro_check {
+ ($id:ident, $name:expr) => {
+ if $id!(c) && chars == $name {
+ self.machine_st.fail = false;
+ return;
+ }
+ };
+ }
+ macro_rules! method_check {
+ ($id:ident, $name:expr) => {
+ if c.$id() && chars == $name {
+ self.machine_st.fail = false;
+ return;
+ }
+ };
+ }
+ macro_check!(alpha_char, atom!("alpha"));
+ method_check!(is_alphabetic, atom!("alphabetic"));
+ method_check!(is_alphanumeric, atom!("alphanumeric"));
+ macro_check!(alpha_numeric_char, atom!("alnum"));
+ method_check!(is_ascii, atom!("ascii"));
+ method_check!(is_ascii_punctuation, atom!("ascii_punctuation"));
+ method_check!(is_ascii_graphic, atom!("ascii_graphic"));
+ // macro_check!(backslash_char, atom!("backslash"));
+ // macro_check!(back_quote_char, atom!("back_quote"));
+ macro_check!(binary_digit_char, atom!("binary_digit"));
+ // macro_check!(capital_letter_char, atom!("upper"));
+ // macro_check!(comment_1_char, "comment_1");
+ // macro_check!(comment_2_char, "comment_2");
+ method_check!(is_control, atom!("control"));
+ // macro_check!(cut_char, atom!("cut"));
+ macro_check!(decimal_digit_char, atom!("decimal_digit"));
+ // macro_check!(decimal_point_char, atom!("decimal_point"));
+ // macro_check!(double_quote_char, atom!("double_quote"));
+ macro_check!(exponent_char, atom!("exponent"));
+ macro_check!(graphic_char, atom!("graphic"));
+ macro_check!(graphic_token_char, atom!("graphic_token"));
+ macro_check!(hexadecimal_digit_char, atom!("hexadecimal_digit"));
+ macro_check!(layout_char, atom!("layout"));
+ method_check!(is_lowercase, atom!("lower"));
+ macro_check!(meta_char, atom!("meta"));
+ // macro_check!(new_line_char, atom!("new_line"));
+ method_check!(is_numeric, atom!("numeric"));
+ macro_check!(octal_digit_char, atom!("octal_digit"));
+ macro_check!(octet_char, atom!("octet"));
+ macro_check!(prolog_char, atom!("prolog"));
+ // macro_check!(semicolon_char, atom!("semicolon"));
+ macro_check!(sign_char, atom!("sign"));
+ // macro_check!(single_quote_char, atom!("single_quote"));
+ // macro_check!(small_letter_char, atom!("lower"));
+ macro_check!(solo_char, atom!("solo"));
+ // macro_check!(space_char, atom!("space"));
+ macro_check!(symbolic_hexadecimal_char, atom!("symbolic_hexadecimal"));
+ macro_check!(symbolic_control_char, atom!("symbolic_control"));
+ method_check!(is_uppercase, atom!("upper"));
+ // macro_check!(variable_indicator_char, atom!("variable_indicator"));
+ method_check!(is_whitespace, atom!("whitespace"));
+ }
+ (HeapCellValueTag::Str, s) => {
+ let (name, arity) = cell_as_atom_cell!(self.machine_st.heap[s])
+ .get_name_and_arity();
+ match (name, arity) {
+ (atom!("to_upper"), 1) => {
+ let reg = self.machine_st.deref(self.machine_st.heap[s+1]);
+ let atom = self.machine_st.atom_tbl.build_with(&c.to_uppercase().to_string());
+ let upper_str = string_as_cstr_cell!(atom);
+ unify!(self.machine_st, reg, upper_str);
+ self.machine_st.fail = false;
+ }
+ (atom!("to_lower"), 1) => {
+ let reg = self.machine_st.deref(self.machine_st.heap[s+1]);
+ let atom = self.machine_st.atom_tbl.build_with(&c.to_lowercase().to_string());
+ let lower_str = string_as_cstr_cell!(atom);
+ unify!(self.machine_st, reg, lower_str);
+ self.machine_st.fail = false;
+ }
+ _ => {
+ unreachable!()
+ }
+ };
+ }
+ _ => {
+ unreachable!()
+ }
+ );
}
#[inline(always)]
let addr = self.deref_register(1);
let old_b = cell_as_fixnum!(addr).get_num() as usize;
- let prev_b = self.machine_st.stack.index_or_frame(self.machine_st.b).prelude.b;
+ let prev_b = self
+ .machine_st
+ .stack
+ .index_or_frame(self.machine_st.b)
+ .prelude
+ .b;
let prev_b = self.machine_st.stack.index_or_frame(prev_b).prelude.b;
if prev_b > old_b {
let mut bytes = Vec::new();
let stub_gen = || functor_stub(atom!("$put_chars"), 2);
- if let Some(string) = self.machine_st.value_to_str_like(self.machine_st.registers[2]) {
+ if let Some(string) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[2])
+ {
if stream.options().stream_type() == StreamType::Binary {
for c in string.as_str().chars() {
if c as u32 > 255 {
- let err = self.machine_st.type_error(ValidType::Byte, char_as_cell!(c));
+ let err = self
+ .machine_st
+ .type_error(ValidType::Byte, char_as_cell!(c));
return Err(self.machine_st.error_form(err, stub_gen()));
}
bytes.push(c as u8);
- }
+ }
} else {
bytes = string.as_str().bytes().collect();
}
match stream.write_all(&bytes) {
- Ok(_) => {
- }
+ Ok(_) => {}
_ => {
let addr = stream_as_cell!(stream);
- let err = self.machine_st.existence_error(ExistenceError::Stream(addr));
+ let err = self
+ .machine_st
+ .existence_error(ExistenceError::Stream(addr));
return Err(self.machine_st.error_form(err, stub_gen()));
}
return Ok(());
}
_ => {
- let err = self.machine_st.existence_error(
- ExistenceError::Stream(stream_as_cell!(stream))
- );
+ let err = self.machine_st.existence_error(ExistenceError::Stream(
+ stream_as_cell!(stream),
+ ));
return Err(self.machine_st.error_form(err, stub_gen()));
}
return Ok(());
}
_ => {
- let err = self.machine_st.existence_error(
- ExistenceError::Stream(stream_as_cell!(stream))
- );
+ let err = self.machine_st.existence_error(ExistenceError::Stream(
+ stream_as_cell!(stream),
+ ));
return Err(self.machine_st.error_form(err, stub_gen()));
}
}
}
}
- _ => {
- }
+ _ => {}
}
}
- let err = self.machine_st.type_error(ValidType::Byte, self.machine_st.registers[2]);
+ let err = self
+ .machine_st
+ .type_error(ValidType::Byte, self.machine_st.registers[2]);
Err(self.machine_st.error_form(err, stub_gen()))
}
)?;
if stream.past_end_of_stream() {
- self.machine_st.eof_action(self.machine_st.registers[2], stream, atom!("get_byte"), 2)?;
+ self.machine_st.eof_action(
+ self.machine_st.registers[2],
+ stream,
+ atom!("get_byte"),
+ 2,
+ )?;
if EOFAction::Reset != stream.options().eof_action() {
return Ok(());
match stream.read(&mut b) {
Ok(1) => {
- self.machine_st.unify_fixnum(Fixnum::build_with(b[0] as i64), addr);
+ self.machine_st
+ .unify_fixnum(Fixnum::build_with(b[0] as i64), addr);
break;
}
_ => {
stream.set_past_end_of_stream(true);
- self.machine_st.unify_fixnum(Fixnum::build_with(-1), self.machine_st.registers[2]);
+ self.machine_st
+ .unify_fixnum(Fixnum::build_with(-1), self.machine_st.registers[2]);
break;
}
}
let end_of_file = atom!("end_of_file");
stream.set_past_end_of_stream(true);
- self.machine_st.unify_atom(
- end_of_file,
- addr
- );
+ self.machine_st.unify_atom(end_of_file, addr);
return Ok(());
}
string.push(c as char);
}
} else {
- let mut iter = self.machine_st.open_parsing_stream(stream)
- .map_err(|e| {
- let err = self.machine_st.session_error(SessionError::from(e));
- let stub = functor_stub(atom!("get_n_chars"), 2);
+ let mut iter = self.machine_st.open_parsing_stream(stream).map_err(|e| {
+ let err = self.machine_st.session_error(SessionError::from(e));
+ let stub = functor_stub(atom!("get_n_chars"), 2);
- self.machine_st.error_form(err, stub)
- })?;
+ self.machine_st.error_form(err, stub)
+ })?;
for _ in 0..num {
let result = iter.read_char();
if stream.at_end_of_stream() {
stream.set_past_end_of_stream(true);
- self.machine_st.unify_fixnum(
- Fixnum::build_with(-1),
- addr,
- );
+ self.machine_st.unify_fixnum(Fixnum::build_with(-1), addr);
return Ok(());
}
} else {
match Number::try_from(addr) {
Ok(Number::Integer(n)) => {
- let n = n
- .to_u32()
- .and_then(|n| std::char::from_u32(n));
+ let n = n.to_u32().and_then(|n| std::char::from_u32(n));
if let Some(n) = n {
fixnum_as_cell!(Fixnum::build_with(n as i64))
} else {
- let err = self.machine_st.representation_error(RepFlag::InCharacterCode);
+ let err = self
+ .machine_st
+ .representation_error(RepFlag::InCharacterCode);
return Err(self.machine_st.error_form(err, stub_gen()));
}
}
if nf.is_some() {
fixnum_as_cell!(n)
} else {
- let err = self.machine_st.representation_error(RepFlag::InCharacterCode);
+ let err = self
+ .machine_st
+ .representation_error(RepFlag::InCharacterCode);
return Err(self.machine_st.error_form(err, stub_gen()));
}
}
_ => {
- let err = self.machine_st.type_error(ValidType::Integer, self.machine_st.registers[2]);
+ let err = self
+ .machine_st
+ .type_error(ValidType::Integer, self.machine_st.registers[2]);
return Err(self.machine_st.error_form(err, stub_gen()));
}
}
};
- let mut iter = self.machine_st.open_parsing_stream(stream)
- .map_err(|e| {
- let err = self.machine_st.session_error(SessionError::from(e));
- let stub = functor_stub(atom!("get_code"), 2);
+ let mut iter = self.machine_st.open_parsing_stream(stream).map_err(|e| {
+ let err = self.machine_st.session_error(SessionError::from(e));
+ let stub = functor_stub(atom!("get_code"), 2);
- self.machine_st.error_form(err, stub)
- })?;
+ self.machine_st.error_form(err, stub)
+ })?;
loop {
let result = iter.read_char();
match result {
Some(Ok(c)) => {
- self.machine_st.unify_fixnum(Fixnum::build_with(c as i64), addr);
+ self.machine_st
+ .unify_fixnum(Fixnum::build_with(c as i64), addr);
break;
}
_ => {
let mut next_stream = None;
let mut null_streams = BTreeSet::new();
- for stream in self.indices
- .streams
- .range(prev_stream..)
- .skip(1)
- .cloned()
- {
+ for stream in self.indices.streams.range(prev_stream..).skip(1).cloned() {
if !stream.is_null_stream() {
next_stream = Some(stream);
break;
let stub = functor_stub(atom!("flush_output"), 1);
let addr = stream_as_cell!(stream);
- let err = self.machine_st.permission_error(
- Permission::OutputStream,
- atom!("stream"),
- addr,
- );
+ let err =
+ self.machine_st
+ .permission_error(Permission::OutputStream, atom!("stream"), addr);
return Err(self.machine_st.error_form(err, stub));
}
_ => unreachable!(),
};
let a1 = self.deref_register(1);
- self.machine_st.unify_char(
- c,
- a1,
- );
+ self.machine_st.unify_char(c, a1);
Ok(())
}
}
let c = buffer[0] as char;
let a1 = self.deref_register(1);
- self.machine_st.unify_char(
- c,
- a1,
- );
+ self.machine_st.unify_char(c, a1);
Ok(())
}
pub(crate) fn head_is_dynamic(&mut self) {
let module_name = cell_as_atom!(self.deref_register(1));
- match self.machine_st.name_and_arity_from_heap(self.machine_st.registers[2]) {
+ match self
+ .machine_st
+ .name_and_arity_from_heap(self.machine_st.registers[2])
+ {
Some((name, arity)) => {
- self.machine_st.fail = !self.indices.is_dynamic_predicate(module_name, (name, arity));
+ self.machine_st.fail = !self
+ .indices
+ .is_dynamic_predicate(module_name, (name, arity));
}
None => {
self.machine_st.fail = true;
self.indices.streams.remove(&stream);
if stream == self.user_input {
- self.user_input = self.indices
+ self.user_input = self
+ .indices
.stream_aliases
.get(&atom!("user_input"))
.cloned()
self.indices.streams.insert(self.user_input);
} else if stream == self.user_output {
- self.user_output = self.indices
+ self.user_output = self
+ .indices
.stream_aliases
.get(&atom!("user_output"))
.cloned()
if let Err(_) = close_result {
let stub = functor_stub(atom!("close"), 1);
let addr = stream_as_cell!(stream);
- let err = self.machine_st.existence_error(ExistenceError::Stream(addr));
+ let err = self
+ .machine_st
+ .existence_error(ExistenceError::Stream(addr));
return Err(self.machine_st.error_form(err, stub));
}
#[inline(always)]
pub(crate) fn copy_to_lifted_heap(&mut self) {
- let lh_offset = cell_as_fixnum!(
- self.deref_register(1)
- ).get_num() as usize;
+ let lh_offset = cell_as_fixnum!(self.deref_register(1)).get_num() as usize;
let copy_target = self.machine_st.registers[2];
- let old_threshold = self.machine_st.copy_findall_solution(lh_offset, copy_target);
+ let old_threshold = self
+ .machine_st
+ .copy_findall_solution(lh_offset, copy_target);
let new_threshold = self.machine_st.lifted_heap.len() - lh_offset;
self.machine_st.lifted_heap[old_threshold] = heap_loc_as_cell!(new_threshold);
- for addr in self.machine_st.lifted_heap[old_threshold + 1 ..].iter_mut() {
+ for addr in self.machine_st.lifted_heap[old_threshold + 1..].iter_mut() {
*addr -= self.machine_st.heap.len() + lh_offset;
}
}
}
);
- self.machine_st.fail = self.indices
+ self.machine_st.fail = self
+ .indices
.get_predicate_code_index(name, arity, module_name)
.is_none();
}
let code_dir = if module_name == atom!("user") {
&self.indices.code_dir
} else {
- match self.indices.modules.get(&module_name).map(|module| &module.code_dir) {
+ match self
+ .indices
+ .modules
+ .get(&module_name)
+ .map(|module| &module.code_dir)
+ {
Some(code_dir) => code_dir,
None => {
self.machine_st.fail = true;
for (name, arity) in code_dir.keys() {
if name_match(pred_atom, *name) && arity_match(pred_arity, *arity) {
- self.machine_st.heap.extend(
- functor!(atom!("/"), [cell(atom_as_cell!(name)), fixnum(*arity)]),
- );
+ self.machine_st.heap.extend(functor!(
+ atom!("/"),
+ [cell(atom_as_cell!(name)), fixnum(*arity)]
+ ));
num_functors += 1;
}
if num_functors > 0 {
let h = iter_to_heap_list(
&mut self.machine_st.heap,
- (0 .. num_functors).map(|i| str_loc_as_cell!(h + 3 * i)),
+ (0..num_functors).map(|i| str_loc_as_cell!(h + 3 * i)),
);
- unify!(self.machine_st, heap_loc_as_cell!(h), self.machine_st.registers[4]);
+ unify!(
+ self.machine_st,
+ heap_loc_as_cell!(h),
+ self.machine_st.registers[4]
+ );
} else {
- unify!(self.machine_st, empty_list_as_cell!(), self.machine_st.registers[4]);
+ unify!(
+ self.machine_st,
+ empty_list_as_cell!(),
+ self.machine_st.registers[4]
+ );
}
}
self.indices.op_dir.get_key_value(&(orig_op, Fixity::Post)),
];
- let number_of_keys = op_descs[0].is_some() as usize +
- op_descs[1].is_some() as usize +
- op_descs[2].is_some() as usize;
+ let number_of_keys = op_descs[0].is_some() as usize
+ + op_descs[1].is_some() as usize
+ + op_descs[2].is_some() as usize;
match number_of_keys {
0 => {
1 => {
for op_desc in op_descs {
if let Some((_, op_desc)) = op_desc {
- let (op_prec, op_spec) =
- (op_desc.get_prec(), op_desc.get_spec());
+ let (op_prec, op_spec) = (op_desc.get_prec(), op_desc.get_spec());
if op_prec == 0 {
// 8.14.4, note 2
return None;
}
- if (!orig_op.is_var() && atom_as_cell!(name) != orig_op) ||
- (!spec.is_var() && other_spec != spec_num) {
- return None;
- }
+ if (!orig_op.is_var() && atom_as_cell!(name) != orig_op)
+ || (!spec.is_var() && other_spec != spec_num)
+ {
+ return None;
+ }
Some((*key, (other_prec as usize, other_spec as Specifier)))
- }
+ },
));
unossified_op_dir
let spec_var = spec.as_var().unwrap();
let op_var = op.as_var().unwrap();
- self.machine_st.bind(prec_var, fixnum_as_cell!(Fixnum::build_with(*op_prec as i64)));
+ self.machine_st.bind(
+ prec_var,
+ fixnum_as_cell!(Fixnum::build_with(*op_prec as i64)),
+ );
self.machine_st.bind(spec_var, atom_as_cell!(spec_atom));
self.machine_st.bind(op_var, atom_as_cell!(op_atom));
- self.machine_st.bind(ossified_op_dir_var, typed_arena_ptr_as_cell!(ossified_op_dir));
+ self.machine_st.bind(
+ ossified_op_dir_var,
+ typed_arena_ptr_as_cell!(ossified_op_dir),
+ );
}
None => {
self.machine_st.fail = true;
return;
}
- let ossified_op_dir = cell_as_ossified_op_dir!(
- ossified_op_dir_cell
- );
+ let ossified_op_dir = cell_as_ossified_op_dir!(ossified_op_dir_cell);
let fixity = match spec {
atom!("xfy") | atom!("yfx") | atom!("xfx") => Fixity::In,
}
};
- match self.machine_st.get_next_db_ref(
- &self.indices,
- &DBRef::Op(op_atom, fixity, ossified_op_dir),
- ) {
+ match self
+ .machine_st
+ .get_next_db_ref(&self.indices, &DBRef::Op(op_atom, fixity, ossified_op_dir))
+ {
Some(DBRef::Op(op_atom, fixity, ossified_op_dir)) => {
let (prec, spec) = ossified_op_dir.get(&(op_atom, fixity)).unwrap();
- let prec_var = self.machine_st.deref(self.machine_st.registers[5])
- .as_var().unwrap();
+ let prec_var = self
+ .machine_st
+ .deref(self.machine_st.registers[5])
+ .as_var()
+ .unwrap();
- let spec_var = self.machine_st.deref(self.machine_st.registers[6])
- .as_var().unwrap();
+ let spec_var = self
+ .machine_st
+ .deref(self.machine_st.registers[6])
+ .as_var()
+ .unwrap();
- let op_var = self.machine_st.deref(self.machine_st.registers[7])
- .as_var().unwrap();
+ let op_var = self
+ .machine_st
+ .deref(self.machine_st.registers[7])
+ .as_var()
+ .unwrap();
let spec_atom = match *spec {
FX => atom!("fx"),
}
};
- self.machine_st.bind(prec_var, fixnum_as_cell!(Fixnum::build_with(*prec as i64)));
+ self.machine_st
+ .bind(prec_var, fixnum_as_cell!(Fixnum::build_with(*prec as i64)));
self.machine_st.bind(spec_var, atom_as_cell!(spec_atom));
self.machine_st.bind(op_var, atom_as_cell!(op_atom));
}
random_bits
}
- let result = {
- generate_random_bits(1) == 0
- };
+ let result = { generate_random_bits(1) == 0 };
self.machine_st.fail = result;
}
let secs = ProcessTime::now().as_duration().as_secs_f64();
let secs = float_alloc!(secs, self.machine_st.arena);
- self.machine_st.unify_f64(secs, self.machine_st.registers[1]);
+ self.machine_st
+ .unify_f64(secs, self.machine_st.registers[1]);
}
#[cfg(target_os = "wasi")]
let err = self.machine_st.resource_error(len);
return Err(self.machine_st.error_form(err, stub_gen()));
}
- }
+ },
_ => {
unreachable!()
}
iter_to_heap_list(
&mut self.machine_st.heap,
- (0 .. n).map(|i| heap_loc_as_cell!(h + 2 * i + 1)),
+ (0..n).map(|i| heap_loc_as_cell!(h + 2 * i + 1)),
);
let tail = self.deref_register(1);
- self.machine_st.bind(tail.as_var().unwrap(), heap_loc_as_cell!(h));
+ self.machine_st
+ .bind(tail.as_var().unwrap(), heap_loc_as_cell!(h));
Ok(())
}
#[inline(always)]
pub(crate) fn http_open(&mut self) -> CallResult {
let address_sink = self.deref_register(1);
- let method = read_heap_cell!(self.deref_register(3),
+ let method = read_heap_cell!(self.deref_register(3),
(HeapCellValueTag::Atom, (name, arity)) => {
debug_assert_eq!(arity, 0);
match name {
}
let stub_gen = || functor_stub(atom!("http_open"), 3);
- let headers = match self.machine_st.try_from_list(self.machine_st.registers[7], stub_gen) {
+ let headers = match self
+ .machine_st
+ .try_from_list(self.machine_st.registers[7], stub_gen)
+ {
Ok(addrs) => {
let mut header_map = HeaderMap::new();
- for heap_cell in addrs{
- read_heap_cell!(heap_cell,
- (HeapCellValueTag::Str, s) => {
- let name = cell_as_atom_cell!(self.machine_st.heap[s]).get_name();
- let value = self.machine_st.value_to_str_like(self.machine_st.heap[s + 1]).unwrap();
- header_map.insert(HeaderName::from_str(name.as_str()).unwrap(), HeaderValue::from_str(value.as_str()).unwrap());
- }
- _ => {
- unreachable!()
- }
- )
+ for heap_cell in addrs {
+ read_heap_cell!(heap_cell,
+ (HeapCellValueTag::Str, s) => {
+ let name = cell_as_atom_cell!(self.machine_st.heap[s]).get_name();
+ let value = self.machine_st.value_to_str_like(self.machine_st.heap[s + 1]).unwrap();
+ header_map.insert(HeaderName::from_str(name.as_str()).unwrap(), HeaderValue::from_str(value.as_str()).unwrap());
+ }
+ _ => {
+ unreachable!()
+ }
+ )
}
header_map
- },
- Err(e) => return Err(e)
+ }
+ Err(e) => return Err(e),
};
if let Some(address_sink) = self.machine_st.value_to_str_like(address_sink) {
let address_string = address_sink.as_str(); //to_string();
let address: Url = address_string.parse().unwrap();
- let client = reqwest::blocking::Client::builder()
- .build()
- .unwrap();
-
- // request
- let mut req = reqwest::blocking::Request::new(method, address);
-
- *req.headers_mut() = headers;
- if bytes.len() > 0 {
- *req.body_mut() = Some(reqwest::blocking::Body::from(bytes));
- }
-
- // do it!
- match client.execute(req) {
- Ok(resp) => {
- // status code
- let status = resp.status().as_u16();
- self.machine_st.unify_fixnum(Fixnum::build_with(status as i64), address_status);
- // headers
- let headers: Vec<HeapCellValue> = resp.headers().iter().map(|(header_name, header_value)| {
- let h = self.machine_st.heap.len();
-
- let header_term = functor!(
- self.machine_st.atom_tbl.build_with(header_name.as_str()),
- [cell(string_as_cstr_cell!(self.machine_st.atom_tbl.build_with(header_value.to_str().unwrap())))]
- );
-
- self.machine_st.heap.extend(header_term.into_iter());
- str_loc_as_cell!(h)
- }).collect();
-
- let headers_list = iter_to_heap_list(&mut self.machine_st.heap, headers.into_iter());
- unify!(self.machine_st, heap_loc_as_cell!(headers_list), self.machine_st.registers[6]);
- // body
- let reader = resp.bytes().unwrap().reader();
-
- let mut stream = Stream::from_http_stream(
- self.machine_st.atom_tbl.build_with(&address_string),
- Box::new(reader),
- &mut self.machine_st.arena
- );
- *stream.options_mut() = StreamOptions::default();
- if let Some(alias) = stream.options().get_alias() {
- self.indices.stream_aliases.insert(alias, stream);
- }
-
- self.indices.streams.insert(stream);
-
- let stream = stream_as_cell!(stream);
-
- let stream_addr = self.deref_register(2);
- self.machine_st.bind(stream_addr.as_var().unwrap(), stream);
- },
- Err(_) => {
- self.machine_st.fail = true;
- }
- }
+ let client = reqwest::blocking::Client::builder().build().unwrap();
+
+ // request
+ let mut req = reqwest::blocking::Request::new(method, address);
+
+ *req.headers_mut() = headers;
+ if bytes.len() > 0 {
+ *req.body_mut() = Some(reqwest::blocking::Body::from(bytes));
+ }
+
+ // do it!
+ match client.execute(req) {
+ Ok(resp) => {
+ // status code
+ let status = resp.status().as_u16();
+ self.machine_st
+ .unify_fixnum(Fixnum::build_with(status as i64), address_status);
+ // headers
+ let headers: Vec<HeapCellValue> = resp
+ .headers()
+ .iter()
+ .map(|(header_name, header_value)| {
+ let h = self.machine_st.heap.len();
+
+ let header_term = functor!(
+ self.machine_st.atom_tbl.build_with(header_name.as_str()),
+ [cell(string_as_cstr_cell!(self
+ .machine_st
+ .atom_tbl
+ .build_with(header_value.to_str().unwrap())))]
+ );
+
+ self.machine_st.heap.extend(header_term.into_iter());
+ str_loc_as_cell!(h)
+ })
+ .collect();
+
+ let headers_list =
+ iter_to_heap_list(&mut self.machine_st.heap, headers.into_iter());
+ unify!(
+ self.machine_st,
+ heap_loc_as_cell!(headers_list),
+ self.machine_st.registers[6]
+ );
+ // body
+ let reader = resp.bytes().unwrap().reader();
+
+ let mut stream = Stream::from_http_stream(
+ self.machine_st.atom_tbl.build_with(&address_string),
+ Box::new(reader),
+ &mut self.machine_st.arena,
+ );
+ *stream.options_mut() = StreamOptions::default();
+ if let Some(alias) = stream.options().get_alias() {
+ self.indices.stream_aliases.insert(alias, stream);
+ }
+
+ self.indices.streams.insert(stream);
+
+ let stream = stream_as_cell!(stream);
+
+ let stream_addr = self.deref_register(2);
+ self.machine_st.bind(stream_addr.as_var().unwrap(), stream);
+ }
+ Err(_) => {
+ self.machine_st.fail = true;
+ }
+ }
} else {
- let err = self.machine_st.domain_error(DomainErrorType::SourceSink, address_sink);
+ let err = self
+ .machine_st
+ .domain_error(DomainErrorType::SourceSink, address_sink);
let stub = functor_stub(atom!("http_open"), 3);
return Err(self.machine_st.error_form(err, stub));
#[inline(always)]
pub(crate) fn http_listen(&mut self) -> CallResult {
let address_sink = self.deref_register(1);
- if let Some(address_str) = self.machine_st.value_to_str_like(address_sink) {
- let address_string = address_str.as_str();
- let addr: SocketAddr = match address_string.to_socket_addrs().ok().and_then(|mut s| s.next()) {
- Some(addr) => addr,
+ if let Some(address_str) = self.machine_st.value_to_str_like(address_sink) {
+ let address_string = address_str.as_str();
+ let addr: SocketAddr = match address_string
+ .to_socket_addrs()
+ .ok()
+ .and_then(|mut s| s.next())
+ {
+ Some(addr) => addr,
_ => {
self.machine_st.fail = true;
return Ok(());
}
- };
-
- let (tx, rx) = std::sync::mpsc::sync_channel(1024);
-
- let _guard = self.runtime.enter();
- let listener = match self.runtime.block_on(async { tokio::net::TcpListener::bind(addr).await }) {
- Ok(listener) => listener,
- Err(_) => {
- return Err(self.machine_st.open_permission_error(address_sink, atom!("http_listen"), 2));
- }
- };
-
- self.runtime.spawn(async move {
- loop {
- let tx = tx.clone();
- let (stream, _) = listener.accept().await.unwrap();
-
- tokio::task::spawn(async move {
- if let Err(err) = http1::Builder::new()
- .serve_connection(stream, HttpService {
- tx
- })
- .await
- {
- eprintln!("Error serving connection: {:?}", err);
- }
- });
- }
- });
- let http_listener = HttpListener { incoming: rx };
- let http_listener = arena_alloc!(http_listener, &mut self.machine_st.arena);
+ };
+
+ let (tx, rx) = std::sync::mpsc::sync_channel(1024);
+
+ let _guard = self.runtime.enter();
+ let listener = match self
+ .runtime
+ .block_on(async { tokio::net::TcpListener::bind(addr).await })
+ {
+ Ok(listener) => listener,
+ Err(_) => {
+ return Err(self.machine_st.open_permission_error(
+ address_sink,
+ atom!("http_listen"),
+ 2,
+ ));
+ }
+ };
+
+ self.runtime.spawn(async move {
+ loop {
+ let tx = tx.clone();
+ let (stream, _) = listener.accept().await.unwrap();
+
+ tokio::task::spawn(async move {
+ if let Err(err) = http1::Builder::new()
+ .serve_connection(stream, HttpService { tx })
+ .await
+ {
+ eprintln!("Error serving connection: {:?}", err);
+ }
+ });
+ }
+ });
+ let http_listener = HttpListener { incoming: rx };
+ let http_listener = arena_alloc!(http_listener, &mut self.machine_st.arena);
let addr = self.deref_register(2);
- self.machine_st.bind(addr.as_var().unwrap(), typed_arena_ptr_as_cell!(http_listener));
- }
- Ok(())
+ self.machine_st.bind(
+ addr.as_var().unwrap(),
+ typed_arena_ptr_as_cell!(http_listener),
+ );
+ }
+ Ok(())
}
#[cfg(feature = "http")]
#[inline(always)]
pub(crate) fn http_accept(&mut self) -> CallResult {
- let culprit = self.deref_register(1);
- let method = self.deref_register(2);
- let path = self.deref_register(3);
- let query = self.deref_register(5);
- let stream_addr = self.deref_register(6);
- let handle_addr = self.deref_register(7);
- read_heap_cell!(culprit,
- (HeapCellValueTag::Cons, cons_ptr) => {
- match_untyped_arena_ptr!(cons_ptr,
- (ArenaHeaderTag::HttpListener, http_listener) => {
- match http_listener.incoming.recv() {
- Ok(request) => {
- let method_atom = match *request.request.method() {
- Method::GET => atom!("get"),
- Method::POST => atom!("post"),
- Method::PUT => atom!("put"),
- Method::DELETE => atom!("delete"),
- Method::PATCH => atom!("patch"),
- Method::HEAD => atom!("head"),
- _ => unreachable!(),
- };
- let path_atom = self.machine_st.atom_tbl.build_with(request.request.uri().path());
- let path_cell = atom_as_cstr_cell!(path_atom);
- let headers: Vec<HeapCellValue> = request.request.headers().iter().map(|(header_name, header_value)| {
- let h = self.machine_st.heap.len();
-
- let header_term = functor!(
- self.machine_st.atom_tbl.build_with(header_name.as_str()),
- [cell(string_as_cstr_cell!(self.machine_st.atom_tbl.build_with(header_value.to_str().unwrap())))]
- );
-
- self.machine_st.heap.extend(header_term.into_iter());
- str_loc_as_cell!(h)
- }).collect();
-
- let headers_list = iter_to_heap_list(&mut self.machine_st.heap, headers.into_iter());
-
- let query_str = request.request.uri().query().unwrap_or("");
- let query_atom = self.machine_st.atom_tbl.build_with(query_str);
- let query_cell = string_as_cstr_cell!(query_atom);
-
- let hyper_req = request.request;
- let buf = self.runtime.block_on(async {hyper_req.collect().await.unwrap().aggregate()});
- let reader = buf.reader();
-
- let mut stream = Stream::from_http_stream(
- path_atom,
- Box::new(reader),
- &mut self.machine_st.arena
- );
- *stream.options_mut() = StreamOptions::default();
- stream.options_mut().set_stream_type(StreamType::Binary);
- self.indices.streams.insert(stream);
- let stream = stream_as_cell!(stream);
-
- let handle = arena_alloc!(request.response, &mut self.machine_st.arena);
-
- self.machine_st.bind(method.as_var().unwrap(), atom_as_cell!(method_atom));
- self.machine_st.bind(path.as_var().unwrap(), path_cell);
- unify!(self.machine_st, heap_loc_as_cell!(headers_list), self.machine_st.registers[4]);
- self.machine_st.bind(query.as_var().unwrap(), query_cell);
- self.machine_st.bind(stream_addr.as_var().unwrap(), stream);
- self.machine_st.bind(handle_addr.as_var().unwrap(), typed_arena_ptr_as_cell!(handle));
- }
- Err(_) => {
- self.machine_st.fail = true;
- }
- }
- }
- _ => {
- unreachable!();
- }
- );
- }
- _ => {
- unreachable!();
- }
- );
- Ok(())
- }
-
- #[cfg(feature = "http")]
- #[inline(always)]
- pub(crate) fn http_answer(&mut self) -> CallResult {
- let culprit = self.deref_register(1);
- let status_code = self.deref_register(2);
- let status_code: u16 = match Number::try_from(status_code) {
- Ok(Number::Fixnum(n)) => n.get_num() as u16,
- Ok(Number::Integer(n)) => match n.to_u16() {
- Some(u) => u,
- _ => {
- self.machine_st.fail = true;
- return Ok(());
- }
- }
- _ => unreachable!()
- };
- let stub_gen = || functor_stub(atom!("http_listen"), 2);
- let headers = match self.machine_st.try_from_list(self.machine_st.registers[3], stub_gen) {
- Ok(addrs) => {
- let mut header_map = HeaderMap::new();
- for heap_cell in addrs{
- read_heap_cell!(heap_cell,
- (HeapCellValueTag::Str, s) => {
- let name = cell_as_atom_cell!(self.machine_st.heap[s]).get_name();
- let value = self.machine_st.value_to_str_like(self.machine_st.heap[s + 1]).unwrap();
- header_map.insert(HeaderName::from_str(name.as_str()).unwrap(), HeaderValue::from_str(value.as_str()).unwrap());
- }
- _ => {
- unreachable!()
- }
- )
- }
- header_map
- },
- Err(e) => return Err(e)
- };
- let stream_addr = self.deref_register(4);
-
- read_heap_cell!(culprit,
- (HeapCellValueTag::Cons, cons_ptr) => {
- match_untyped_arena_ptr!(cons_ptr,
- (ArenaHeaderTag::HttpResponse, http_response) => {
- let mut stream = Stream::from_http_sender(
- http_response,
- status_code,
- headers,
- &mut self.machine_st.arena
- );
- *stream.options_mut() = StreamOptions::default();
- stream.options_mut().set_stream_type(StreamType::Binary);
- self.indices.streams.insert(stream);
- let stream = stream_as_cell!(stream);
- self.machine_st.bind(stream_addr.as_var().unwrap(), stream);
- }
- _ => {
- unreachable!();
- }
- );
- }
- _ => {
- unreachable!();
- }
- );
-
- Ok(())
- }
+ let culprit = self.deref_register(1);
+ let method = self.deref_register(2);
+ let path = self.deref_register(3);
+ let query = self.deref_register(5);
+ let stream_addr = self.deref_register(6);
+ let handle_addr = self.deref_register(7);
+ read_heap_cell!(culprit,
+ (HeapCellValueTag::Cons, cons_ptr) => {
+ match_untyped_arena_ptr!(cons_ptr,
+ (ArenaHeaderTag::HttpListener, http_listener) => {
+ match http_listener.incoming.recv() {
+ Ok(request) => {
+ let method_atom = match *request.request.method() {
+ Method::GET => atom!("get"),
+ Method::POST => atom!("post"),
+ Method::PUT => atom!("put"),
+ Method::DELETE => atom!("delete"),
+ Method::PATCH => atom!("patch"),
+ Method::HEAD => atom!("head"),
+ _ => unreachable!(),
+ };
+ let path_atom = self.machine_st.atom_tbl.build_with(request.request.uri().path());
+ let path_cell = atom_as_cstr_cell!(path_atom);
+ let headers: Vec<HeapCellValue> = request.request.headers().iter().map(|(header_name, header_value)| {
+ let h = self.machine_st.heap.len();
+
+ let header_term = functor!(
+ self.machine_st.atom_tbl.build_with(header_name.as_str()),
+ [cell(string_as_cstr_cell!(self.machine_st.atom_tbl.build_with(header_value.to_str().unwrap())))]
+ );
- #[cfg(feature = "ffi")]
- #[inline(always)]
- pub(crate) fn load_foreign_lib(&mut self) -> CallResult {
- let library_name = self.deref_register(1);
- let args_reg = self.deref_register(2);
- if let Some(library_name) = self.machine_st.value_to_str_like(library_name) {
- let stub_gen = || functor_stub(atom!("use_foreign_module"), 2);
- match self.machine_st.try_from_list(args_reg, stub_gen) {
- Ok(addrs) => {
- let mut functions = Vec::new();
- for heap_cell in addrs {
- read_heap_cell!(heap_cell,
- (HeapCellValueTag::Str, s) => {
- let name = cell_as_atom_cell!(self.machine_st.heap[s]).get_name();
- let args: Vec<Atom> = match self.machine_st.try_from_list(self.machine_st.heap[s + 1], stub_gen) {
- Ok(addrs) => {
- let mut args = Vec::new();
- for heap_cell in addrs {
- args.push(cell_as_atom_cell!(heap_cell).get_name());
- }
- args
- }
- Err(e) => return Err(e)
- };
- let return_value = cell_as_atom_cell!(self.machine_st.heap[s + 2]);
- functions.push(FunctionDefinition {
- name: name.as_str().to_string(),
- args,
- return_value: return_value.get_name(),
- });
- }
- _ => {
- unreachable!()
- }
- )
- }
- if let Ok(_) = self.foreign_function_table.load_library(library_name.as_str(), &functions) {
- return Ok(());
- }
- }
- Err(e) => return Err(e)
- };
- }
- self.machine_st.fail = true;
- Ok(())
- }
+ self.machine_st.heap.extend(header_term.into_iter());
+ str_loc_as_cell!(h)
+ }).collect();
- #[cfg(feature = "ffi")]
- #[inline(always)]
- pub(crate) fn foreign_call(&mut self) -> CallResult {
- let function_name = self.deref_register(1);
- let args_reg = self.deref_register(2);
- let return_value = self.deref_register(3);
- if let Some(function_name) = self.machine_st.value_to_str_like(function_name) {
- let stub_gen = || functor_stub(atom!("foreign_call"), 3);
- fn map_arg(mut machine_st: &mut MachineState, source: HeapCellValue) -> crate::ffi::Value {
- match Number::try_from(source) {
- Ok(Number::Fixnum(n)) => {
- Value::Int(n.get_num())
- },
- Ok(Number::Float(n)) => {
- Value::Float(n.into_inner())
- },
- _ => {
- let stub_gen = || functor_stub(atom!("foreign_call"), 3);
- if let Some(string) = machine_st.value_to_str_like(source) {
- Value::CString(CString::new(string.as_str()).unwrap())
- } else {
- match machine_st.try_from_list(source, stub_gen) {
- Ok(args) => {
- let mut iter = args.into_iter();
- if let Some(struct_name) = machine_st.value_to_str_like(iter.next().unwrap()) {
- Value::Struct(struct_name.as_str().to_string(), iter.map(|x| map_arg(&mut machine_st, x)).collect())
- } else {
- unreachable!()
- }
- }
- _ => {
- unreachable!()
- }
- }
- }
- }
- }
- }
-
- match self.machine_st.try_from_list(args_reg, stub_gen) {
- Ok(args) => {
- let args: Vec<_> = args.into_iter().map(|x| map_arg(&mut self.machine_st, x)).collect();
- match self.foreign_function_table.exec(function_name.as_str(), args) {
- Ok(result) => {
- match result {
- Value::Int(n) => self.machine_st.unify_fixnum(Fixnum::build_with(n), return_value),
- Value::Float(n) => {
- let n = float_alloc!(n, self.machine_st.arena);
- self.machine_st.unify_f64(n, return_value)
- },
- Value::Struct(name, args) => {
- let struct_value = self.build_struct(&name, args);
- unify!(self.machine_st, return_value, struct_value);
- }
- Value::CString(cstr) => {
- let cstr = self.machine_st.atom_tbl.build_with(cstr.to_str().unwrap());
- self.machine_st.unify_complete_string(cstr, return_value);
- }
- }
- return Ok(());
- },
- Err(e) => {
- let stub = functor_stub(atom!("current_input"), 1);
- let err = self.machine_st.ffi_error(e);
+ let headers_list = iter_to_heap_list(&mut self.machine_st.heap, headers.into_iter());
- return Err(self.machine_st.error_form(err, stub));
- }
- }
- }
- Err(e) => return Err(e)
- }
- }
- self.machine_st.fail = true;
- Ok(())
- }
+ let query_str = request.request.uri().query().unwrap_or("");
+ let query_atom = self.machine_st.atom_tbl.build_with(query_str);
+ let query_cell = string_as_cstr_cell!(query_atom);
- #[cfg(feature = "ffi")]
- fn build_struct(&mut self, name: &str, mut args: Vec<Value>) -> HeapCellValue {
- args.insert(0, Value::CString(CString::new(name).unwrap()));
- let cells: Vec<_> = args.into_iter()
- .map(|val| {
- match val {
- Value::Int(n) => fixnum_as_cell!(Fixnum::build_with(n)),
- Value::Float(n) => HeapCellValue::from(float_alloc!(n, self.machine_st.arena)),
- Value::CString(cstr) => atom_as_cell!(self.machine_st.atom_tbl.build_with(&cstr.into_string().unwrap())),
- Value::Struct(name, struct_args) => self.build_struct(&name, struct_args),
- }
- }).collect();
-
- heap_loc_as_cell!(
- iter_to_heap_list(
- &mut self.machine_st.heap,
- cells.into_iter()
- )
- )
- }
+ let hyper_req = request.request;
+ let buf = self.runtime.block_on(async {hyper_req.collect().await.unwrap().aggregate()});
+ let reader = buf.reader();
+
+ let mut stream = Stream::from_http_stream(
+ path_atom,
+ Box::new(reader),
+ &mut self.machine_st.arena
+ );
+ *stream.options_mut() = StreamOptions::default();
+ stream.options_mut().set_stream_type(StreamType::Binary);
+ self.indices.streams.insert(stream);
+ let stream = stream_as_cell!(stream);
+
+ let handle = arena_alloc!(request.response, &mut self.machine_st.arena);
+
+ self.machine_st.bind(method.as_var().unwrap(), atom_as_cell!(method_atom));
+ self.machine_st.bind(path.as_var().unwrap(), path_cell);
+ unify!(self.machine_st, heap_loc_as_cell!(headers_list), self.machine_st.registers[4]);
+ self.machine_st.bind(query.as_var().unwrap(), query_cell);
+ self.machine_st.bind(stream_addr.as_var().unwrap(), stream);
+ self.machine_st.bind(handle_addr.as_var().unwrap(), typed_arena_ptr_as_cell!(handle));
+ }
+ Err(_) => {
+ self.machine_st.fail = true;
+ }
+ }
+ }
+ _ => {
+ unreachable!();
+ }
+ );
+ }
+ _ => {
+ unreachable!();
+ }
+ );
+ Ok(())
+ }
+
+ #[cfg(feature = "http")]
+ #[inline(always)]
+ pub(crate) fn http_answer(&mut self) -> CallResult {
+ let culprit = self.deref_register(1);
+ let status_code = self.deref_register(2);
+ let status_code: u16 = match Number::try_from(status_code) {
+ Ok(Number::Fixnum(n)) => n.get_num() as u16,
+ Ok(Number::Integer(n)) => match n.to_u16() {
+ Some(u) => u,
+ _ => {
+ self.machine_st.fail = true;
+ return Ok(());
+ }
+ },
+ _ => unreachable!(),
+ };
+ let stub_gen = || functor_stub(atom!("http_listen"), 2);
+ let headers = match self
+ .machine_st
+ .try_from_list(self.machine_st.registers[3], stub_gen)
+ {
+ Ok(addrs) => {
+ let mut header_map = HeaderMap::new();
+ for heap_cell in addrs {
+ read_heap_cell!(heap_cell,
+ (HeapCellValueTag::Str, s) => {
+ let name = cell_as_atom_cell!(self.machine_st.heap[s]).get_name();
+ let value = self.machine_st.value_to_str_like(self.machine_st.heap[s + 1]).unwrap();
+ header_map.insert(HeaderName::from_str(name.as_str()).unwrap(), HeaderValue::from_str(value.as_str()).unwrap());
+ }
+ _ => {
+ unreachable!()
+ }
+ )
+ }
+ header_map
+ }
+ Err(e) => return Err(e),
+ };
+ let stream_addr = self.deref_register(4);
+
+ read_heap_cell!(culprit,
+ (HeapCellValueTag::Cons, cons_ptr) => {
+ match_untyped_arena_ptr!(cons_ptr,
+ (ArenaHeaderTag::HttpResponse, http_response) => {
+ let mut stream = Stream::from_http_sender(
+ http_response,
+ status_code,
+ headers,
+ &mut self.machine_st.arena
+ );
+ *stream.options_mut() = StreamOptions::default();
+ stream.options_mut().set_stream_type(StreamType::Binary);
+ self.indices.streams.insert(stream);
+ let stream = stream_as_cell!(stream);
+ self.machine_st.bind(stream_addr.as_var().unwrap(), stream);
+ }
+ _ => {
+ unreachable!();
+ }
+ );
+ }
+ _ => {
+ unreachable!();
+ }
+ );
+
+ Ok(())
+ }
+
+ #[cfg(feature = "ffi")]
+ #[inline(always)]
+ pub(crate) fn load_foreign_lib(&mut self) -> CallResult {
+ let library_name = self.deref_register(1);
+ let args_reg = self.deref_register(2);
+ if let Some(library_name) = self.machine_st.value_to_str_like(library_name) {
+ let stub_gen = || functor_stub(atom!("use_foreign_module"), 2);
+ match self.machine_st.try_from_list(args_reg, stub_gen) {
+ Ok(addrs) => {
+ let mut functions = Vec::new();
+ for heap_cell in addrs {
+ read_heap_cell!(heap_cell,
+ (HeapCellValueTag::Str, s) => {
+ let name = cell_as_atom_cell!(self.machine_st.heap[s]).get_name();
+ let args: Vec<Atom> = match self.machine_st.try_from_list(self.machine_st.heap[s + 1], stub_gen) {
+ Ok(addrs) => {
+ let mut args = Vec::new();
+ for heap_cell in addrs {
+ args.push(cell_as_atom_cell!(heap_cell).get_name());
+ }
+ args
+ }
+ Err(e) => return Err(e)
+ };
+ let return_value = cell_as_atom_cell!(self.machine_st.heap[s + 2]);
+ functions.push(FunctionDefinition {
+ name: name.as_str().to_string(),
+ args,
+ return_value: return_value.get_name(),
+ });
+ }
+ _ => {
+ unreachable!()
+ }
+ )
+ }
+ if let Ok(_) = self
+ .foreign_function_table
+ .load_library(library_name.as_str(), &functions)
+ {
+ return Ok(());
+ }
+ }
+ Err(e) => return Err(e),
+ };
+ }
+ self.machine_st.fail = true;
+ Ok(())
+ }
+
+ #[cfg(feature = "ffi")]
+ #[inline(always)]
+ pub(crate) fn foreign_call(&mut self) -> CallResult {
+ let function_name = self.deref_register(1);
+ let args_reg = self.deref_register(2);
+ let return_value = self.deref_register(3);
+ if let Some(function_name) = self.machine_st.value_to_str_like(function_name) {
+ let stub_gen = || functor_stub(atom!("foreign_call"), 3);
+ fn map_arg(
+ mut machine_st: &mut MachineState,
+ source: HeapCellValue,
+ ) -> crate::ffi::Value {
+ match Number::try_from(source) {
+ Ok(Number::Fixnum(n)) => Value::Int(n.get_num()),
+ Ok(Number::Float(n)) => Value::Float(n.into_inner()),
+ _ => {
+ let stub_gen = || functor_stub(atom!("foreign_call"), 3);
+ if let Some(string) = machine_st.value_to_str_like(source) {
+ Value::CString(CString::new(string.as_str()).unwrap())
+ } else {
+ match machine_st.try_from_list(source, stub_gen) {
+ Ok(args) => {
+ let mut iter = args.into_iter();
+ if let Some(struct_name) =
+ machine_st.value_to_str_like(iter.next().unwrap())
+ {
+ Value::Struct(
+ struct_name.as_str().to_string(),
+ iter.map(|x| map_arg(&mut machine_st, x)).collect(),
+ )
+ } else {
+ unreachable!()
+ }
+ }
+ _ => {
+ unreachable!()
+ }
+ }
+ }
+ }
+ }
+ }
+
+ match self.machine_st.try_from_list(args_reg, stub_gen) {
+ Ok(args) => {
+ let args: Vec<_> = args
+ .into_iter()
+ .map(|x| map_arg(&mut self.machine_st, x))
+ .collect();
+ match self
+ .foreign_function_table
+ .exec(function_name.as_str(), args)
+ {
+ Ok(result) => {
+ match result {
+ Value::Int(n) => self
+ .machine_st
+ .unify_fixnum(Fixnum::build_with(n), return_value),
+ Value::Float(n) => {
+ let n = float_alloc!(n, self.machine_st.arena);
+ self.machine_st.unify_f64(n, return_value)
+ }
+ Value::Struct(name, args) => {
+ let struct_value = self.build_struct(&name, args);
+ unify!(self.machine_st, return_value, struct_value);
+ }
+ Value::CString(cstr) => {
+ let cstr =
+ self.machine_st.atom_tbl.build_with(cstr.to_str().unwrap());
+ self.machine_st.unify_complete_string(cstr, return_value);
+ }
+ }
+ return Ok(());
+ }
+ Err(e) => {
+ let stub = functor_stub(atom!("current_input"), 1);
+ let err = self.machine_st.ffi_error(e);
+
+ return Err(self.machine_st.error_form(err, stub));
+ }
+ }
+ }
+ Err(e) => return Err(e),
+ }
+ }
+ self.machine_st.fail = true;
+ Ok(())
+ }
+
+ #[cfg(feature = "ffi")]
+ fn build_struct(&mut self, name: &str, mut args: Vec<Value>) -> HeapCellValue {
+ args.insert(0, Value::CString(CString::new(name).unwrap()));
+ let cells: Vec<_> = args
+ .into_iter()
+ .map(|val| match val {
+ Value::Int(n) => fixnum_as_cell!(Fixnum::build_with(n)),
+ Value::Float(n) => HeapCellValue::from(float_alloc!(n, self.machine_st.arena)),
+ Value::CString(cstr) => atom_as_cell!(self
+ .machine_st
+ .atom_tbl
+ .build_with(&cstr.into_string().unwrap())),
+ Value::Struct(name, struct_args) => self.build_struct(&name, struct_args),
+ })
+ .collect();
+
+ heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ cells.into_iter()
+ ))
+ }
#[cfg(feature = "ffi")]
#[inline(always)]
pub(crate) fn define_foreign_struct(&mut self) -> CallResult {
- let struct_name = self.deref_register(1);
- let fields_reg = self.deref_register(2);
- if let Some(struct_name) = self.machine_st.value_to_str_like(struct_name) {
- let stub_gen = || functor_stub(atom!("define_foreign_struct"), 2);
- let fields: Vec<Atom> = match self.machine_st.try_from_list(fields_reg, stub_gen) {
- Ok(addrs) => {
- let mut args = Vec::new();
- for heap_cell in addrs {
- args.push(cell_as_atom_cell!(heap_cell).get_name());
- }
- args
- }
- Err(e) => return Err(e)
- };
- self.foreign_function_table.define_struct(struct_name.as_str(), fields);
- return Ok(())
- }
- self.machine_st.fail = true;
- Ok(())
+ let struct_name = self.deref_register(1);
+ let fields_reg = self.deref_register(2);
+ if let Some(struct_name) = self.machine_st.value_to_str_like(struct_name) {
+ let stub_gen = || functor_stub(atom!("define_foreign_struct"), 2);
+ let fields: Vec<Atom> = match self.machine_st.try_from_list(fields_reg, stub_gen) {
+ Ok(addrs) => {
+ let mut args = Vec::new();
+ for heap_cell in addrs {
+ args.push(cell_as_atom_cell!(heap_cell).get_name());
+ }
+ args
+ }
+ Err(e) => return Err(e),
+ };
+ self.foreign_function_table
+ .define_struct(struct_name.as_str(), fields);
+ return Ok(());
+ }
+ self.machine_st.fail = true;
+ Ok(())
}
#[inline(always)]
pub(crate) fn current_time(&mut self) {
let timestamp = self.systemtime_to_timestamp(SystemTime::now());
- self.machine_st.unify_complete_string(timestamp, self.machine_st.registers[1]);
+ self.machine_st
+ .unify_complete_string(timestamp, self.machine_st.registers[1]);
}
#[inline(always)]
let reposition = self.machine_st.registers[6];
let stream_type = self.machine_st.registers[7];
- let options = self.machine_st.to_stream_options(alias, eof_action, reposition, stream_type);
+ let options = self
+ .machine_st
+ .to_stream_options(alias, eof_action, reposition, stream_type);
let src_sink = self.deref_register(1);
if let Some(file_spec) = self.machine_st.value_to_str_like(src_sink) {
let file_spec = file_spec.as_atom(&mut self.machine_st.atom_tbl);
- let mut stream = self.machine_st.stream_from_file_spec(
- file_spec,
- &mut self.indices,
- &options,
- )?;
+ let mut stream =
+ self.machine_st
+ .stream_from_file_spec(file_spec, &mut self.indices, &options)?;
*stream.options_mut() = options;
self.indices.streams.insert(stream);
}
let stream_var = self.deref_register(3);
- self.machine_st.bind(stream_var.as_var().unwrap(), stream_as_cell!(stream));
+ self.machine_st
+ .bind(stream_var.as_var().unwrap(), stream_as_cell!(stream));
} else {
- let err = self.machine_st.domain_error(DomainErrorType::SourceSink, src_sink);
+ let err = self
+ .machine_st
+ .domain_error(DomainErrorType::SourceSink, src_sink);
let stub = functor_stub(atom!("open"), 4);
return Err(self.machine_st.error_form(err, stub));
let reposition = self.machine_st.registers[4];
let stream_type = self.machine_st.registers[5];
- let options = self.machine_st.to_stream_options(alias, eof_action, reposition, stream_type);
+ let options = self
+ .machine_st
+ .to_stream_options(alias, eof_action, reposition, stream_type);
*stream.options_mut() = options;
Ok(())
#[inline(always)]
pub(crate) fn truncate_if_no_lifted_heap_growth_diff(&mut self) {
- self.machine_st.truncate_if_no_lifted_heap_diff(|h| heap_loc_as_cell!(h))
+ self.machine_st
+ .truncate_if_no_lifted_heap_diff(|h| heap_loc_as_cell!(h))
}
#[inline(always)]
pub(crate) fn truncate_if_no_lifted_heap_growth(&mut self) {
- self.machine_st.truncate_if_no_lifted_heap_diff(|_| empty_list_as_cell!())
+ self.machine_st
+ .truncate_if_no_lifted_heap_diff(|_| empty_list_as_cell!())
}
#[inline(always)]
);
let list_addr = self.deref_register(2);
- self.machine_st.bind(Ref::heap_cell(attr_var_list), list_addr);
+ self.machine_st
+ .bind(Ref::heap_cell(attr_var_list), list_addr);
}
#[inline(always)]
let module = self.deref_register(2);
match self.match_attribute(attr_var_list, module, attr) {
- Some(AttrListMatch { match_site: MatchSite::Match(match_site), .. }) => {
+ Some(AttrListMatch {
+ match_site: MatchSite::Match(match_site),
+ ..
+ }) => {
let list_head = self.machine_st.heap[match_site];
if list_head.get_value() as usize == match_site {
// at the end of the list, no match found in this case.
self.machine_st.fail = true;
} else {
- let (_, qualified_goal) = self.machine_st.strip_module(
- list_head,
- empty_list_as_cell!(),
- );
+ let (_, qualified_goal) = self
+ .machine_st
+ .strip_module(list_head, empty_list_as_cell!());
unify!(self.machine_st, qualified_goal, attr);
}
if let Some(b) = b {
let iter = self.machine_st.gather_attr_vars_created_since(b);
- let var_list_addr = heap_loc_as_cell!(
- iter_to_heap_list(&mut self.machine_st.heap, iter)
- );
+ let var_list_addr =
+ heap_loc_as_cell!(iter_to_heap_list(&mut self.machine_st.heap, iter));
let list_addr = self.machine_st.registers[2];
unify!(self.machine_st, var_list_addr, list_addr);
let module = self.deref_register(2);
match self.match_attribute(self.machine_st.heap[attr_var_list], module, attr) {
- Some(AttrListMatch { prev_tail, match_site: MatchSite::Match(match_site) }) => {
+ Some(AttrListMatch {
+ prev_tail,
+ match_site: MatchSite::Match(match_site),
+ }) => {
let prev_tail = if let Some(prev_tail) = prev_tail {
// not at the head.
prev_tail
self.machine_st.heap[prev_tail] = heap_loc_as_cell!(prev_tail);
}
- self.machine_st.trail(TrailRef::AttrVarListLink(prev_tail, match_site));
- }
- _ => {
+ self.machine_st
+ .trail(TrailRef::AttrVarListLink(prev_tail, match_site));
}
+ _ => {}
}
}
let h = self.machine_st.heap.len();
- self.machine_st.heap.push(str_loc_as_cell!(h+1));
- self.machine_st.heap.extend(functor!(atom!(":"), [cell(module), cell(attr)]));
+ self.machine_st.heap.push(str_loc_as_cell!(h + 1));
+ self.machine_st
+ .heap
+ .extend(functor!(atom!(":"), [cell(module), cell(attr)]));
match self.match_attribute(self.machine_st.heap[attr_var_list], module, attr) {
Some(AttrListMatch { match_site, .. }) => {
let l = self.machine_st.heap[match_site].get_value();
// at the end of the (non-empty) list here.
- self.machine_st.heap[match_site] = list_loc_as_cell!(h+4);
+ self.machine_st.heap[match_site] = list_loc_as_cell!(h + 4);
self.machine_st.heap.push(heap_loc_as_cell!(h));
- self.machine_st.heap.push(heap_loc_as_cell!(h+5));
+ self.machine_st.heap.push(heap_loc_as_cell!(h + 5));
(match_site, l)
}
}
};
- self.machine_st.trail(TrailRef::AttrVarListLink(match_site, l as usize));
+ self.machine_st
+ .trail(TrailRef::AttrVarListLink(match_site, l as usize));
}
None => {
// the list is empty.
- self.machine_st.heap[attr_var_list] = list_loc_as_cell!(h+4);
+ self.machine_st.heap[attr_var_list] = list_loc_as_cell!(h + 4);
self.machine_st.heap.push(heap_loc_as_cell!(h));
- self.machine_st.heap.push(heap_loc_as_cell!(h+5));
+ self.machine_st.heap.push(heap_loc_as_cell!(h + 5));
- self.machine_st.attr_var_init.attr_var_queue.push(attr_var_list - 1);
- self.machine_st.trail(TrailRef::AttrVarListLink(attr_var_list, attr_var_list));
+ self.machine_st
+ .attr_var_init
+ .attr_var_queue
+ .push(attr_var_list - 1);
+ self.machine_st
+ .trail(TrailRef::AttrVarListLink(attr_var_list, attr_var_list));
}
}
}
let chunk = str_loc_as_cell!(self.machine_st.heap.len());
- self.machine_st.heap.push(atom_as_cell!(atom!("cont_chunk"), 1 + num_cells));
+ self.machine_st
+ .heap
+ .push(atom_as_cell!(atom!("cont_chunk"), 1 + num_cells));
self.machine_st.heap.push(p_functor);
self.machine_st.heap.extend(addrs);
#[inline(always)]
pub(crate) fn get_lifted_heap_from_offset_diff(&mut self) {
let lh_offset = self.machine_st.registers[1];
- let lh_offset = cell_as_fixnum!(
- self.machine_st.store(self.machine_st.deref(lh_offset))
- ).get_num() as usize;
+ let lh_offset = cell_as_fixnum!(self.machine_st.store(self.machine_st.deref(lh_offset)))
+ .get_num() as usize;
if lh_offset >= self.machine_st.lifted_heap.len() {
let solutions = self.machine_st.registers[2];
let h = self.machine_st.heap.len();
let mut last_index = h;
- for value in self.machine_st.lifted_heap[lh_offset ..].iter().cloned() {
+ for value in self.machine_st.lifted_heap[lh_offset..].iter().cloned() {
last_index = self.machine_st.heap.len();
self.machine_st.heap.push(value + h);
}
#[inline(always)]
pub(crate) fn get_lifted_heap_from_offset(&mut self) {
let lh_offset = self.machine_st.registers[1];
- let lh_offset = cell_as_fixnum!(self.machine_st.store(self.machine_st.deref(
- lh_offset
- ))).get_num() as usize;
+ let lh_offset = cell_as_fixnum!(self.machine_st.store(self.machine_st.deref(lh_offset)))
+ .get_num() as usize;
if lh_offset >= self.machine_st.lifted_heap.len() {
let solutions = self.machine_st.registers[2];
let dest = self.machine_st.registers[1];
if let Some((addr, b_cutoff, prev_block)) = self.machine_st.cont_pts.pop() {
- let b = self.machine_st.stack.index_or_frame(self.machine_st.b).prelude.b;
+ let b = self
+ .machine_st
+ .stack
+ .index_or_frame(self.machine_st.b)
+ .prelude
+ .b;
if b <= b_cutoff {
self.machine_st.scc_block = prev_block;
Ok(Number::Fixnum(bp)) => bp.get_num() as usize,
Ok(Number::Integer(n)) => n.to_usize().unwrap(),
_ => {
- let stub = functor_stub(
- atom!("call_with_inference_limit"),
- 3,
- );
+ let stub = functor_stub(atom!("call_with_inference_limit"), 3);
let err = self.machine_st.type_error(ValidType::Integer, a2);
return Err(self.machine_st.error_form(err, stub));
let a3 = self.deref_register(3);
let arity = match Number::try_from(a3) {
- Ok(Number::Fixnum(n)) => n.get_num() as usize,
+ Ok(Number::Fixnum(n)) => n.get_num() as usize,
Ok(Number::Integer(n)) => {
if let Some(n) = n.to_usize() {
n
}
};
- self.indices.get_predicate_code_index(
- name,
- arity,
- module_name,
- ).map(|index| index.local().is_some())
- .unwrap_or(false)
+ self.indices
+ .get_predicate_code_index(name, arity, module_name)
+ .map(|index| index.local().is_some())
+ .unwrap_or(false)
}
#[inline(always)]
if bp == self.machine_st.b && self.machine_st.cwil.is_empty() {
self.machine_st.cwil.reset();
- self.machine_st.increment_call_count_fn = |_| { Ok(()) };
+ self.machine_st.increment_call_count_fn = |_| Ok(());
}
}
self.machine_st.registers[i] = self.machine_st.stack[stack_loc!(AndFrame, e, i)];
}
- self.machine_st.b0 = cell_as_fixnum!(self.machine_st.stack[stack_loc!(AndFrame, e, frame_len - 2)])
- .get_num() as usize;
+ self.machine_st.b0 = cell_as_fixnum!(
+ self.machine_st.stack[stack_loc!(AndFrame, e, frame_len - 2)]
+ )
+ .get_num() as usize;
- self.machine_st.num_of_args = cell_as_fixnum!(self.machine_st.stack[stack_loc!(AndFrame, e, frame_len - 1)])
- .get_num() as usize;
+ self.machine_st.num_of_args = cell_as_fixnum!(
+ self.machine_st.stack[stack_loc!(AndFrame, e, frame_len - 1)]
+ )
+ .get_num() as usize;
- let p = cell_as_fixnum!(self.machine_st.stack[stack_loc!(AndFrame, e, frame_len)]).get_num() as usize;
+ let p = cell_as_fixnum!(self.machine_st.stack[stack_loc!(AndFrame, e, frame_len)]).get_num()
+ as usize;
self.machine_st.deallocate();
self.machine_st.p = p;
#[inline(always)]
pub(crate) fn restore_cut_policy(&mut self) {
if self.machine_st.cont_pts.is_empty() {
- self.machine_st.run_cleaners_fn = |_| { false };
+ self.machine_st.run_cleaners_fn = |_| false;
}
}
#[inline(always)]
pub(crate) fn set_cut_point(&mut self, r: RegType) -> bool {
- let cp = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ let cp = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
self.machine_st.cut_body(cp);
(self.machine_st.run_cleaners_fn)(self)
#[inline(always)]
pub(crate) fn set_cut_point_by_default(&mut self, r: RegType) {
- let cp = self.machine_st.store(self.machine_st.deref(self.machine_st[r]));
+ let cp = self
+ .machine_st
+ .store(self.machine_st.deref(self.machine_st[r]));
self.machine_st.cut_body(cp);
}
let a2 = self.deref_register(2);
let bp = cell_as_fixnum!(a2).get_num() as usize;
- let prev_b = self.machine_st.stack.index_or_frame(self.machine_st.b).prelude.b;
+ let prev_b = self
+ .machine_st
+ .stack
+ .index_or_frame(self.machine_st.b)
+ .prelude
+ .b;
if prev_b <= bp {
self.machine_st.unify_atom(atom!("!"), a1)
#[inline(always)]
pub(crate) fn push_ball_stack(&mut self) {
if self.machine_st.ball.stub.len() > 0 {
- self.machine_st.ball_stack.push(
- mem::replace(&mut self.machine_st.ball, Ball::new())
- );
+ self.machine_st
+ .ball_stack
+ .push(mem::replace(&mut self.machine_st.ball, Ball::new()));
} else {
self.machine_st.fail = true;
}
#[inline(always)]
pub(crate) fn get_b_value(&mut self) {
let n = Fixnum::as_cutpoint(i64::try_from(self.machine_st.b).unwrap());
- self.machine_st.unify_fixnum(n, self.machine_st.registers[1]);
+ self.machine_st
+ .unify_fixnum(n, self.machine_st.registers[1]);
}
#[inline(always)]
pub(crate) fn get_cut_point(&mut self) {
let n = Fixnum::as_cutpoint(i64::try_from(self.machine_st.b0).unwrap());
- self.machine_st.unify_fixnum(n, self.machine_st.registers[1]);
+ self.machine_st
+ .unify_fixnum(n, self.machine_st.registers[1]);
}
#[inline(always)]
let p = str_loc_as_cell!(machine_st.heap.len());
- machine_st.heap.extend(functor!(atom!("dir_entry"), [fixnum(cp)]));
+ machine_st
+ .heap
+ .extend(functor!(atom!("dir_entry"), [fixnum(cp)]));
machine_st.unify_fixnum(e, machine_st.registers[2]);
if !machine_st.fail {
set_prompt(true);
// let result = self.machine_st.read_term(self.user_input, &mut self.indices);
- let result = self.machine_st.read_term_from_user_input(self.user_input, &mut self.indices);
+ let result = self
+ .machine_st
+ .read_term_from_user_input(self.user_input, &mut self.indices);
set_prompt(false);
match result {
)?;
if let Stream::Readline(..) = stream {
- self.machine_st.read_term(stream, &mut self.indices, MachineState::read_term_from_user_input_eof_handler)
+ self.machine_st.read_term(
+ stream,
+ &mut self.indices,
+ MachineState::read_term_from_user_input_eof_handler,
+ )
} else {
- self.machine_st.read_term(stream, &mut self.indices, MachineState::read_term_eof_handler)
+ self.machine_st.read_term(
+ stream,
+ &mut self.indices,
+ MachineState::read_term_eof_handler,
+ )
}
}
let mut parser = Parser::new(chars, &mut self.machine_st);
let op_dir = CompositeOpDir::new(&self.indices.op_dir, None);
- let term_write_result = parser.read_term(&op_dir, Tokens::Default)
+ let term_write_result = parser
+ .read_term(&op_dir, Tokens::Default)
.map_err(|err| error_after_read_term(err, 0, &parser))
.and_then(|term| {
write_term_to_heap(
#[inline(always)]
pub(crate) fn read_from_chars(&mut self) -> CallResult {
- if let Some(atom_or_string) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
+ if let Some(atom_or_string) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
if let Some(term_write_result) = self.read_term_and_write_to_heap(atom_or_string)? {
let result = heap_loc_as_cell!(term_write_result.heap_loc);
let var = self.deref_register(2).as_var().unwrap();
#[inline(always)]
pub(crate) fn read_term_from_chars(&mut self) -> CallResult {
- if let Some(atom_or_string) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
+ if let Some(atom_or_string) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
if let Some(term_write_result) = self.read_term_and_write_to_heap(atom_or_string)? {
self.machine_st.read_term_body(term_write_result)
} else {
pub(crate) fn set_seed(&mut self) {
let seed = self.deref_register(1);
-
match Number::try_from(seed) {
Ok(Number::Fixnum(n)) => {
let _: StdRng = SeedableRng::seed_from_u64(Integer::from(n).to_u64().unwrap());
- },
+ }
Ok(Number::Integer(n)) => {
let _: StdRng = SeedableRng::seed_from_u64(n.to_u64().unwrap());
- },
+ }
Ok(Number::Rational(n)) => {
if n.denominator() == &UBig::from(1 as u32) {
let _: StdRng = SeedableRng::seed_from_u64(n.numerator().to_u64().unwrap());
}
- },
+ }
_ => {
self.machine_st.fail = true;
}
let reposition = self.machine_st.registers[6];
let stream_type = self.machine_st.registers[7];
- let options = self.machine_st.to_stream_options(alias, eof_action, reposition, stream_type);
+ let options = self
+ .machine_st
+ .to_stream_options(alias, eof_action, reposition, stream_type);
if options.reposition() {
- return Err(self.machine_st.reposition_error(atom!("socket_client_open"), 3));
+ return Err(self
+ .machine_st
+ .reposition_error(atom!("socket_client_open"), 3));
}
if let Some(alias) = options.get_alias() {
let stream = match TcpStream::connect(socket_addr.as_str()).map_err(|e| e.kind()) {
Ok(tcp_stream) => {
- let mut stream = Stream::from_tcp_stream(socket_addr, tcp_stream, &mut self.machine_st.arena);
+ let mut stream =
+ Stream::from_tcp_stream(socket_addr, tcp_stream, &mut self.machine_st.arena);
*stream.options_mut() = options;
stream_as_cell!(stream)
}
Err(ErrorKind::PermissionDenied) => {
- return Err(self.machine_st.open_permission_error(addr, atom!("socket_client_open"), 3));
+ return Err(self.machine_st.open_permission_error(
+ addr,
+ atom!("socket_client_open"),
+ 3,
+ ));
}
Err(ErrorKind::NotFound) => {
let stub = functor_stub(atom!("socket_client_open"), 3);
- let err = self.machine_st.existence_error(
- ExistenceError::SourceSink(addr),
- );
+ let err = self
+ .machine_st
+ .existence_error(ExistenceError::SourceSink(addr));
return Err(self.machine_st.error_form(err, stub));
}
format!("{}:{}", socket_atom.as_str(), port)
};
- let (tcp_listener, port) =
- match TcpListener::bind(server_addr).map_err(|e| e.kind()) {
- Ok(tcp_listener) => {
- let port = tcp_listener.local_addr().map(|addr| addr.port()).ok();
+ let (tcp_listener, port) = match TcpListener::bind(server_addr).map_err(|e| e.kind()) {
+ Ok(tcp_listener) => {
+ let port = tcp_listener.local_addr().map(|addr| addr.port()).ok();
- if let Some(port) = port {
- (arena_alloc!(tcp_listener, &mut self.machine_st.arena), port as usize)
- } else {
- self.machine_st.fail = true;
- return Ok(());
- }
- }
- Err(ErrorKind::PermissionDenied) => {
- return Err(self.machine_st.open_permission_error(addr, atom!("socket_server_open"), 2));
- }
- _ => {
+ if let Some(port) = port {
+ (
+ arena_alloc!(tcp_listener, &mut self.machine_st.arena),
+ port as usize,
+ )
+ } else {
self.machine_st.fail = true;
return Ok(());
}
- };
+ }
+ Err(ErrorKind::PermissionDenied) => {
+ return Err(self.machine_st.open_permission_error(
+ addr,
+ atom!("socket_server_open"),
+ 2,
+ ));
+ }
+ _ => {
+ self.machine_st.fail = true;
+ return Ok(());
+ }
+ };
let addr = self.deref_register(3);
- self.machine_st.bind(addr.as_var().unwrap(), typed_arena_ptr_as_cell!(tcp_listener));
+ self.machine_st.bind(
+ addr.as_var().unwrap(),
+ typed_arena_ptr_as_cell!(tcp_listener),
+ );
if had_zero_port {
- self.machine_st.unify_fixnum(Fixnum::build_with(port as i64), self.machine_st.registers[2]);
+ self.machine_st.unify_fixnum(
+ Fixnum::build_with(port as i64),
+ self.machine_st.registers[2],
+ );
}
Ok(())
let reposition = self.machine_st.registers[6];
let stream_type = self.machine_st.registers[7];
- let options = self.machine_st.to_stream_options(alias, eof_action, reposition, stream_type);
+ let options = self
+ .machine_st
+ .to_stream_options(alias, eof_action, reposition, stream_type);
if options.reposition() {
- return Err(self.machine_st.reposition_error(atom!("socket_server_accept"), 4));
+ return Err(self
+ .machine_st
+ .reposition_error(atom!("socket_server_accept"), 4));
}
if let Some(alias) = options.get_alias() {
#[cfg(feature = "tls")]
#[inline(always)]
pub(crate) fn tls_client_connect(&mut self) -> CallResult {
- if let Some(hostname) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
+ if let Some(hostname) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
let stream0 = self.machine_st.get_stream_or_alias(
self.machine_st.registers[2],
&self.indices.stream_aliases,
)?;
let connector = TlsConnector::new().unwrap();
- let stream =
- match connector.connect(hostname.as_str(), stream0) {
- Ok(tls_stream) => tls_stream,
- Err(_) => {
- return Err(self.machine_st.open_permission_error(
- self.machine_st.registers[1],
- atom!("tls_client_negotiate"),
- 3,
- ));
- }
- };
+ let stream = match connector.connect(hostname.as_str(), stream0) {
+ Ok(tls_stream) => tls_stream,
+ Err(_) => {
+ return Err(self.machine_st.open_permission_error(
+ self.machine_st.registers[1],
+ atom!("tls_client_negotiate"),
+ 3,
+ ));
+ }
+ };
let addr = atom!("TLS");
let stream = Stream::from_tls_stream(addr, stream, &mut self.machine_st.arena);
self.machine_st.heap.push(stream_as_cell!(stream));
let stream_addr = self.deref_register(3);
- self.machine_st.bind(stream_addr.as_var().unwrap(), stream_as_cell!(stream));
+ self.machine_st
+ .bind(stream_addr.as_var().unwrap(), stream_as_cell!(stream));
Ok(())
} else {
pub(crate) fn tls_accept_client(&mut self) -> CallResult {
let pkcs12 = self.string_encoding_bytes(self.machine_st.registers[1], atom!("octet"));
- if let Some(password) = self.machine_st.value_to_str_like(self.machine_st.registers[2]) {
- let identity =
- match Identity::from_pkcs12(&pkcs12, password.as_str()) {
- Ok(identity) => identity,
- Err(_) => {
- return Err(self.machine_st.open_permission_error(
- self.machine_st.registers[1],
- atom!("tls_server_negotiate"),
- 3,
- ));
- }
- };
+ if let Some(password) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[2])
+ {
+ let identity = match Identity::from_pkcs12(&pkcs12, password.as_str()) {
+ Ok(identity) => identity,
+ Err(_) => {
+ return Err(self.machine_st.open_permission_error(
+ self.machine_st.registers[1],
+ atom!("tls_server_negotiate"),
+ 3,
+ ));
+ }
+ };
let stream0 = self.machine_st.get_stream_or_alias(
self.machine_st.registers[3],
let acceptor = TlsAcceptor::new(identity).unwrap();
- let stream =
- match acceptor.accept(stream0) {
- Ok(tls_stream) => tls_stream,
- Err(_) => {
- return Err(self.machine_st.open_permission_error(
- self.machine_st.registers[3],
- atom!("tls_server_negotiate"),
- 3,
- ));
- }
- };
+ let stream = match acceptor.accept(stream0) {
+ Ok(tls_stream) => tls_stream,
+ Err(_) => {
+ return Err(self.machine_st.open_permission_error(
+ self.machine_st.registers[3],
+ atom!("tls_server_negotiate"),
+ 3,
+ ));
+ }
+ };
let stream = Stream::from_tls_stream(atom!("TLS"), stream, &mut self.machine_st.arena);
self.indices.streams.insert(stream);
let stream_addr = self.deref_register(4);
- self.machine_st.bind(stream_addr.as_var().unwrap(), stream_as_cell!(stream));
+ self.machine_st
+ .bind(stream_addr.as_var().unwrap(), stream_as_cell!(stream));
} else {
unreachable!();
}
})
}
atom!("mode") => atom_as_cell!(stream.mode()),
- atom!("direction") =>
+ atom!("direction") => {
atom_as_cell!(if stream.is_input_stream() && stream.is_output_stream() {
atom!("input_output")
} else if stream.is_input_stream() {
atom!("input")
} else {
atom!("output")
- }),
+ })
+ }
atom!("alias") => {
atom_as_cell!(if let Some(alias) = stream.options().get_alias() {
alias
let position_term = functor!(
atom!("position_and_lines_read"),
- [integer(position, &mut self.machine_st.arena),
- integer(lines_read, &mut self.machine_st.arena)]
+ [
+ integer(position, &mut self.machine_st.arena),
+ integer(lines_read, &mut self.machine_st.arena)
+ ]
);
self.machine_st.heap.extend(position_term.into_iter());
atom!("eof_action") => {
atom_as_cell!(stream.options().eof_action().as_atom())
}
- atom!("reposition") =>
- atom_as_cell!(if stream.options().reposition() {
- atom!("true")
- } else {
- atom!("false")
- }),
+ atom!("reposition") => atom_as_cell!(if stream.options().reposition() {
+ atom!("true")
+ } else {
+ atom!("false")
+ }),
atom!("type") => {
atom_as_cell!(stream.options().stream_type().as_property_atom())
}
ball.boundary = self.machine_st.heap.len();
copy_term(
- CopyBallTerm::new(&mut self.machine_st.stack, &mut self.machine_st.heap, &mut ball.stub),
+ CopyBallTerm::new(
+ &mut self.machine_st.stack,
+ &mut self.machine_st.heap,
+ &mut ball.stub,
+ ),
value,
AttrVarPolicy::DeepCopy,
);
match self.indices.global_variables.get_mut(&key) {
Some((_, ref mut loc)) => match loc {
Some(ref mut value) => {
- self.machine_st.trail(TrailRef::BlackboardOffset(key, *value));
+ self.machine_st
+ .trail(TrailRef::BlackboardOffset(key, *value));
*value = new_value;
}
loc @ None => {
pub(crate) fn term_attributed_variables(&mut self) {
if self.machine_st.registers[1].is_constant() {
let a2 = self.deref_register(2);
- self.machine_st.unify_atom(
- atom!("[]"),
- a2,
- );
+ self.machine_st.unify_atom(atom!("[]"), a2);
return;
}
- let seen_vars = self.machine_st.attr_vars_of_term(self.machine_st.registers[1]);
- let outcome = heap_loc_as_cell!(
- iter_to_heap_list(&mut self.machine_st.heap, seen_vars.into_iter())
- );
+ let seen_vars = self
+ .machine_st
+ .attr_vars_of_term(self.machine_st.registers[1]);
+ let outcome = heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ seen_vars.into_iter()
+ ));
unify_fn!(self.machine_st, self.machine_st.registers[2], outcome);
}
self.machine_st.variable_set(&mut seen_set, stored_v);
- let outcome = heap_loc_as_cell!(
- iter_to_heap_list(&mut self.machine_st.heap, seen_set.into_iter())
- );
+ let outcome = heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ seen_set.into_iter()
+ ));
unify_fn!(self.machine_st, a2, outcome);
}
#[inline(always)]
pub(crate) fn term_variables_under_max_depth(&mut self) {
// Term, MaxDepth, VarList
- let max_depth = cell_as_fixnum!(
- self.deref_register(2)
- ).get_num() as usize;
+ let max_depth = cell_as_fixnum!(self.deref_register(2)).get_num() as usize;
self.machine_st.term_variables_under_max_depth(
self.machine_st.registers[1],
self.machine_st.heap.extend(functor.into_iter());
}
- heap_loc_as_cell!(
- iter_to_heap_list(&mut self.machine_st.heap, functor_list.into_iter())
- )
+ heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ functor_list.into_iter()
+ ))
}
#[inline(always)]
Some(module) => module.code_dir.get(&key),
None => {
let stub = functor_stub(key.0, key.1);
- let err = self.machine_st.session_error(
- SessionError::from(CompilationError::InvalidModuleResolution(
- module_name,
- )),
- );
+ let err = self.machine_st.session_error(SessionError::from(
+ CompilationError::InvalidModuleResolution(module_name),
+ ));
return Err(self.machine_st.error_form(err, stub));
}
}
_ => {
let stub = functor_stub(name, arity);
- let err = self.machine_st.existence_error(
- ExistenceError::Procedure(name, arity),
- );
+ let err = self
+ .machine_st
+ .existence_error(ExistenceError::Procedure(name, arity));
return Err(self.machine_st.error_form(err, stub));
}
Ok(_) => {}
Err(_) => {
let stub = functor_stub(atom!("open"), 4);
- let err = self.machine_st.existence_error(
- ExistenceError::Stream(self.machine_st.registers[1]),
- );
+ let err = self
+ .machine_st
+ .existence_error(ExistenceError::Stream(self.machine_st.registers[1]));
return Err(self.machine_st.error_form(err, stub));
}
let buffer_atom = self.machine_st.atom_tbl.build_with(buffer);
let a1 = self.deref_register(1);
- self.machine_st.unify_complete_string(
- buffer_atom,
- a1,
- );
+ self.machine_st.unify_complete_string(buffer_atom, a1);
}
#[inline(always)]
let mut context = Sha3_224::new();
context.input(&bytes);
- heap_loc_as_cell!(
- iter_to_heap_list(
- &mut self.machine_st.heap,
- context
- .result()
- .as_ref()
- .iter()
- .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
- )
- )
+ heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ context
+ .result()
+ .as_ref()
+ .iter()
+ .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
+ ))
}
atom!("sha3_256") => {
let mut context = Sha3_256::new();
context.input(&bytes);
- heap_loc_as_cell!(
- iter_to_heap_list(
- &mut self.machine_st.heap,
- context
- .result()
- .as_ref()
- .iter()
- .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
- )
- )
+ heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ context
+ .result()
+ .as_ref()
+ .iter()
+ .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
+ ))
}
atom!("sha3_384") => {
let mut context = Sha3_384::new();
context.input(&bytes);
- heap_loc_as_cell!(
- iter_to_heap_list(
- &mut self.machine_st.heap,
- context
- .result()
- .as_ref()
- .iter()
- .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
- )
- )
+ heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ context
+ .result()
+ .as_ref()
+ .iter()
+ .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
+ ))
}
atom!("sha3_512") => {
let mut context = Sha3_512::new();
context.input(&bytes);
- heap_loc_as_cell!(
- iter_to_heap_list(
- &mut self.machine_st.heap,
- context
- .result()
- .as_ref()
- .iter()
- .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
- )
- )
+ heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ context
+ .result()
+ .as_ref()
+ .iter()
+ .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
+ ))
}
atom!("blake2s256") => {
let mut context = Blake2s::new();
context.input(&bytes);
- heap_loc_as_cell!(
- iter_to_heap_list(
- &mut self.machine_st.heap,
- context
- .result()
- .as_ref()
- .iter()
- .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
- )
- )
+ heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ context
+ .result()
+ .as_ref()
+ .iter()
+ .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
+ ))
}
atom!("blake2b512") => {
let mut context = Blake2b::new();
context.input(&bytes);
- heap_loc_as_cell!(
- iter_to_heap_list(
- &mut self.machine_st.heap,
- context
- .result()
- .as_ref()
- .iter()
- .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
- )
- )
+ heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ context
+ .result()
+ .as_ref()
+ .iter()
+ .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
+ ))
}
atom!("ripemd160") => {
let mut context = Ripemd160::new();
context.input(&bytes);
- heap_loc_as_cell!(
- iter_to_heap_list(
- &mut self.machine_st.heap,
- context
- .result()
- .as_ref()
- .iter()
- .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
- )
- )
+ heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ context
+ .result()
+ .as_ref()
+ .iter()
+ .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
+ ))
}
_ => {
let ints = digest::digest(
&bytes,
);
- heap_loc_as_cell!(
- iter_to_heap_list(
- &mut self.machine_st.heap,
- ints.as_ref()
- .iter()
- .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
- )
- )
+ heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ ints.as_ref()
+ .iter()
+ .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
+ ))
}
};
let data = self.string_encoding_bytes(self.machine_st.registers[1], encoding);
let stub1_gen = || functor_stub(atom!("crypto_data_hkdf"), 4);
- let salt = self.machine_st.integers_to_bytevec(self.machine_st.registers[3], stub1_gen);
+ let salt = self
+ .machine_st
+ .integers_to_bytevec(self.machine_st.registers[3], stub1_gen);
let stub2_gen = || functor_stub(atom!("crypto_data_hkdf"), 4);
- let info = self.machine_st.integers_to_bytevec(self.machine_st.registers[4], stub2_gen);
+ let info = self
+ .machine_st
+ .integers_to_bytevec(self.machine_st.registers[4], stub2_gen);
let algorithm = cell_as_atom!(self.deref_register(5));
}
}
- heap_loc_as_cell!(
- iter_to_heap_list(
- &mut self.machine_st.heap,
- bytes
- .iter()
- .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
- )
- )
+ heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ bytes
+ .iter()
+ .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
+ ))
};
unify!(self.machine_st, self.machine_st.registers[7], ints_list);
#[inline(always)]
pub(crate) fn crypto_password_hash(&mut self) {
let stub1_gen = || functor_stub(atom!("crypto_password_hash"), 3);
- let data = self.machine_st.integers_to_bytevec(self.machine_st.registers[1], stub1_gen);
+ let data = self
+ .machine_st
+ .integers_to_bytevec(self.machine_st.registers[1], stub1_gen);
let stub2_gen = || functor_stub(atom!("crypto_password_hash"), 3);
- let salt = self.machine_st.integers_to_bytevec(self.machine_st.registers[2], stub2_gen);
+ let salt = self
+ .machine_st
+ .integers_to_bytevec(self.machine_st.registers[2], stub2_gen);
let iterations = self.deref_register(3);
&mut bytes,
);
- heap_loc_as_cell!(
- iter_to_heap_list(
- &mut self.machine_st.heap,
- bytes
- .iter()
- .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
- )
- )
+ heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ bytes
+ .iter()
+ .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
+ ))
};
unify!(self.machine_st, self.machine_st.registers[4], ints_list);
let aad = self.string_encoding_bytes(self.machine_st.registers[2], encoding);
let stub2_gen = || functor_stub(atom!("crypto_data_encrypt"), 7);
- let key = self.machine_st.integers_to_bytevec(self.machine_st.registers[4], stub2_gen);
+ let key = self
+ .machine_st
+ .integers_to_bytevec(self.machine_st.registers[4], stub2_gen);
let stub3_gen = || functor_stub(atom!("crypto_data_encrypt"), 7);
- let iv = self.machine_st.integers_to_bytevec(self.machine_st.registers[5], stub3_gen);
+ let iv = self
+ .machine_st
+ .integers_to_bytevec(self.machine_st.registers[5], stub3_gen);
let unbound_key = aead::UnboundKey::new(&aead::CHACHA20_POLY1305, &key).unwrap();
let nonce = aead::Nonce::try_assume_unique_for_key(&iv).unwrap();
let mut in_out = data;
- let tag = match key.seal_in_place_separate_tag(
- nonce,
- aead::Aad::from(aad),
- &mut in_out,
- ) {
+ let tag = match key.seal_in_place_separate_tag(nonce, aead::Aad::from(aad), &mut in_out) {
Ok(d) => d,
_ => {
self.machine_st.fail = true;
}
};
- let tag_list = heap_loc_as_cell!(
- iter_to_heap_list(
- &mut self.machine_st.heap,
- tag.as_ref()
- .iter()
- .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
- )
- );
+ let tag_list = heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ tag.as_ref()
+ .iter()
+ .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
+ ));
let complete_string = self.u8s_to_string(&in_out);
unify!(self.machine_st, self.machine_st.registers[6], tag_list);
- unify!(self.machine_st, self.machine_st.registers[7], complete_string);
+ unify!(
+ self.machine_st,
+ self.machine_st.registers[7],
+ complete_string
+ );
}
#[inline(always)]
let aad = self.string_encoding_bytes(self.machine_st.registers[2], encoding);
let stub1_gen = || functor_stub(atom!("crypto_data_decrypt"), 7);
- let key = self.machine_st.integers_to_bytevec(self.machine_st.registers[3], stub1_gen);
+ let key = self
+ .machine_st
+ .integers_to_bytevec(self.machine_st.registers[3], stub1_gen);
let stub2_gen = || functor_stub(atom!("crypto_data_decrypt"), 7);
- let iv = self.machine_st.integers_to_bytevec(self.machine_st.registers[4], stub2_gen);
+ let iv = self
+ .machine_st
+ .integers_to_bytevec(self.machine_st.registers[4], stub2_gen);
let unbound_key = aead::UnboundKey::new(&aead::CHACHA20_POLY1305, &key).unwrap();
let nonce = aead::Nonce::try_assume_unique_for_key(&iv).unwrap();
let mut in_out = data;
let complete_string = {
- let decrypted_data =
- match key.open_in_place(nonce, aead::Aad::from(aad), &mut in_out) {
- Ok(d) => d,
- _ => {
- self.machine_st.fail = true;
- return;
- }
- };
+ let decrypted_data = match key.open_in_place(nonce, aead::Aad::from(aad), &mut in_out) {
+ Ok(d) => d,
+ _ => {
+ self.machine_st.fail = true;
+ return;
+ }
+ };
let buffer = match encoding {
atom!("octet") => String::from_iter(decrypted_data.iter().map(|b| *b as char)),
}
};
- unify!(self.machine_st, self.machine_st.registers[6], complete_string);
+ unify!(
+ self.machine_st,
+ self.machine_st.registers[6],
+ complete_string
+ );
}
#[inline(always)]
pub(crate) fn crypto_curve_scalar_mult(&mut self) {
-
let stub_gen = || functor_stub(atom!("crypto_curve_scalar_mult"), 4);
- let scalar_bytes = self.machine_st.integers_to_bytevec(self.machine_st.registers[2], stub_gen);
- let point_bytes = self.machine_st.integers_to_bytevec(self.machine_st.registers[3], stub_gen);
+ let scalar_bytes = self
+ .machine_st
+ .integers_to_bytevec(self.machine_st.registers[2], stub_gen);
+ let point_bytes = self
+ .machine_st
+ .integers_to_bytevec(self.machine_st.registers[3], stub_gen);
let mut point = secp256k1::Point::decode(&point_bytes).unwrap();
let scalar = secp256k1::Scalar::decode_reduce(&scalar_bytes);
let pkcs8_bytes = signature::Ed25519KeyPair::generate_pkcs8(rng()).unwrap();
let complete_string = self.u8s_to_string(pkcs8_bytes.as_ref());
- unify!(self.machine_st, self.machine_st.registers[1], complete_string)
+ unify!(
+ self.machine_st,
+ self.machine_st.registers[1],
+ complete_string
+ )
}
#[inline(always)]
let complete_string = self.u8s_to_string(key_pair.public_key().as_ref());
- unify!(self.machine_st, self.machine_st.registers[2], complete_string);
+ unify!(
+ self.machine_st,
+ self.machine_st.registers[2],
+ complete_string
+ );
}
#[inline(always)]
let sig = key_pair.sign(&data);
- let sig_list = heap_loc_as_cell!(
- iter_to_heap_list(
- &mut self.machine_st.heap,
- sig.as_ref()
- .iter()
- .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
- )
- );
+ let sig_list = heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ sig.as_ref()
+ .iter()
+ .map(|b| fixnum_as_cell!(Fixnum::build_with(*b as i64))),
+ ));
unify!(self.machine_st, self.machine_st.registers[4], sig_list);
}
let encoding = cell_as_atom!(self.deref_register(3));
let data = self.string_encoding_bytes(self.machine_st.registers[2], encoding);
let stub_gen = || functor_stub(atom!("ed25519_verify"), 5);
- let signature = self.machine_st.integers_to_bytevec(self.machine_st.registers[4], stub_gen);
+ let signature = self
+ .machine_st
+ .integers_to_bytevec(self.machine_st.registers[4], stub_gen);
let peer_public_key = signature::UnparsedPublicKey::new(&signature::ED25519, &key);
#[inline(always)]
pub(crate) fn curve25519_scalar_mult(&mut self) {
let stub1_gen = || functor_stub(atom!("curve25519_scalar_mult"), 3);
- let scalar_bytes = self.machine_st.integers_to_bytevec(self.machine_st.registers[1], stub1_gen);
+ let scalar_bytes = self
+ .machine_st
+ .integers_to_bytevec(self.machine_st.registers[1], stub1_gen);
let stub2_gen = || functor_stub(atom!("curve25519_scalar_mult"), 3);
- let point_bytes = self.machine_st.integers_to_bytevec(self.machine_st.registers[2], stub2_gen);
+ let point_bytes = self
+ .machine_st
+ .integers_to_bytevec(self.machine_st.registers[2], stub2_gen);
- let result = x25519::x25519(&<[u8; 32]>::try_from(&point_bytes[..]).unwrap(),
- &<[u8; 32]>::try_from(&scalar_bytes[..]).unwrap());
+ let result = x25519::x25519(
+ &<[u8; 32]>::try_from(&point_bytes[..]).unwrap(),
+ &<[u8; 32]>::try_from(&scalar_bytes[..]).unwrap(),
+ );
let string = self.u8s_to_string(&result[..]);
for c in string.as_str().chars() {
if c as u32 > 255 {
let non_octet = self.machine_st.atom_tbl.build_with(&c.to_string());
- self.machine_st.unify_atom(non_octet, self.machine_st.registers[2]);
+ self.machine_st
+ .unify_atom(non_octet, self.machine_st.registers[2]);
return;
}
}
#[inline(always)]
pub(crate) fn load_html(&mut self) {
- if let Some(string) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
+ if let Some(string) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
let doc = select::document::Document::from_read(string.as_str().as_bytes()).unwrap();
let result = self.html_node_to_term(doc.nth(0).unwrap());
#[inline(always)]
pub(crate) fn load_xml(&mut self) {
- if let Some(string) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
+ if let Some(string) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
match roxmltree::Document::parse(string.as_str()) {
Ok(doc) => {
let result = self.xml_node_to_term(doc.root_element());
#[inline(always)]
pub(crate) fn get_env(&mut self) {
- if let Some(key) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) {
+ if let Some(key) = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ {
match env::var(key.as_str()) {
Ok(value) => {
let cstr = put_complete_string(
#[inline(always)]
pub(crate) fn set_env(&mut self) {
- let key = self.machine_st.value_to_str_like(self.machine_st.registers[1]).unwrap();
- let value = self.machine_st.value_to_str_like(self.machine_st.registers[2]).unwrap();
+ let key = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ .unwrap();
+ let value = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[2])
+ .unwrap();
env::set_var(key.as_str(), value.as_str());
}
#[inline(always)]
pub(crate) fn unset_env(&mut self) {
- let key = self.machine_st.value_to_str_like(self.machine_st.registers[1]).unwrap();
+ let key = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ .unwrap();
env::remove_var(key.as_str());
}
match fixnum!(Number, pid as i64, &mut self.machine_st.arena) {
Number::Fixnum(pid) => {
- self.machine_st.unify_fixnum(pid, self.machine_st.registers[1]);
+ self.machine_st
+ .unify_fixnum(pid, self.machine_st.registers[1]);
}
Number::Integer(pid) => {
- self.machine_st.unify_big_int(pid, self.machine_st.registers[1]);
+ self.machine_st
+ .unify_big_int(pid, self.machine_st.registers[1]);
}
_ => {
unreachable!();
// if not found, the code looks for COMSPEC env var to do it in a DOS-style
// the output is printed directly to stdout
// the output status code is returned after finishing
- fn command_result(machine: &mut MachineState, command: std::io::Result<process::ExitStatus>) {
+ fn command_result(
+ machine: &mut MachineState,
+ command: std::io::Result<process::ExitStatus>,
+ ) {
match command {
- Ok(status) => {
- match status.code() {
- Some(code) => {
- let code = integer_as_cell!(Number::arena_from(code, &mut machine.arena));
- unify!(machine, code, machine.registers[2]);
- }
- _ => {
- machine.fail = true;
- }
+ Ok(status) => match status.code() {
+ Some(code) => {
+ let code = integer_as_cell!(Number::arena_from(code, &mut machine.arena));
+ unify!(machine, code, machine.registers[2]);
}
- }
+ _ => {
+ machine.fail = true;
+ }
+ },
_ => {
machine.fail = true;
}
}
let a1 = self.deref_register(1);
- let command = self.machine_st.value_to_str_like(
- a1
- ).unwrap();
+ let command = self.machine_st.value_to_str_like(a1).unwrap();
match env::var("SHELL") {
Ok(value) => {
.status();
command_result(&mut self.machine_st, command);
}
- _ => {
- match env::var("COMSPEC") {
- Ok(value) => {
- let command = process::Command::new(&value)
- .arg("/C")
- .arg(command.as_str())
- .status();
- command_result(&mut self.machine_st, command);
- }
- _ => {
- self.machine_st.fail = true;
- }
+ _ => match env::var("COMSPEC") {
+ Ok(value) => {
+ let command = process::Command::new(&value)
+ .arg("/C")
+ .arg(command.as_str())
+ .status();
+ command_result(&mut self.machine_st, command);
}
- }
+ _ => {
+ self.machine_st.fail = true;
+ }
+ },
};
}
};
if self.deref_register(1).is_var() {
- let b64 = self.machine_st.value_to_str_like(self.machine_st.registers[2]).unwrap();
+ let b64 = self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[2])
+ .unwrap();
let bytes = base64::decode_config(b64.as_str(), config);
match bytes {
}
} else {
let mut bytes = vec![];
- for c in self.machine_st.value_to_str_like(self.machine_st.registers[1]).unwrap().as_str().chars() {
+ for c in self
+ .machine_st
+ .value_to_str_like(self.machine_st.registers[1])
+ .unwrap()
+ .as_str()
+ .chars()
+ {
bytes.push(c as u8);
}
match LIBRARIES.borrow().get(library_name.as_str()) {
Some(library) => {
let lib_stream = Stream::from_static_string(library, &mut self.machine_st.arena);
- unify!(self.machine_st, stream_as_cell!(lib_stream), self.machine_st.registers[2]);
+ unify!(
+ self.machine_st,
+ stream_as_cell!(lib_stream),
+ self.machine_st.registers[2]
+ );
let mut path_buf = machine::current_dir();
let library_path_str = path_buf.to_str().unwrap();
let library_path = self.machine_st.atom_tbl.build_with(library_path_str);
- self.machine_st.unify_atom(library_path, self.machine_st.registers[3]);
+ self.machine_st
+ .unify_atom(library_path, self.machine_st.registers[3]);
}
None => {
let stub = functor_stub(atom!("load"), 1);
- let err = self.machine_st.existence_error(
- ExistenceError::ModuleSource(ModuleSource::Library(library_name))
- );
+ let err = self
+ .machine_st
+ .existence_error(ExistenceError::ModuleSource(ModuleSource::Library(
+ library_name,
+ )));
return Err(self.machine_st.error_form(err, stub));
}
let mut parser = Parser::new(stream, &mut self.machine_st);
match devour_whitespace(&mut parser) {
- Ok(false) => { // not at EOF.
+ Ok(false) => {
+ // not at EOF.
stream.add_lines_read(parser.lines_read());
}
Ok(true) => {
#[inline(always)]
pub(crate) fn is_sto_enabled(&mut self) {
if self.machine_st.unify_fn as usize == MachineState::unify_with_occurs_check as usize {
- self.machine_st.unify_atom(atom!("true"), self.machine_st.registers[1]);
+ self.machine_st
+ .unify_atom(atom!("true"), self.machine_st.registers[1]);
} else if self.machine_st.unify_fn as usize
== MachineState::unify_with_occurs_check_with_error as usize
{
- self.machine_st.unify_atom(atom!("error"), self.machine_st.registers[1]);
+ self.machine_st
+ .unify_atom(atom!("error"), self.machine_st.registers[1]);
} else {
- self.machine_st.unify_atom(atom!("false"), self.machine_st.registers[1]);
+ self.machine_st
+ .unify_atom(atom!("false"), self.machine_st.registers[1]);
}
}
self.machine_st.fail = true;
}
- pub(crate) fn debug_hook(&mut self) {
- }
+ pub(crate) fn debug_hook(&mut self) {}
#[inline(always)]
pub(crate) fn pop_count(&mut self) {
self.machine_st.atom_tbl.build_with(&s)
}
- pub(super) fn string_encoding_bytes(&mut self, data_arg: HeapCellValue, encoding: Atom) -> Vec<u8> {
+ pub(super) fn string_encoding_bytes(
+ &mut self,
+ data_arg: HeapCellValue,
+ encoding: Atom,
+ ) -> Vec<u8> {
let data = self.machine_st.value_to_str_like(data_arg).unwrap();
match encoding {
self.machine_st.heap.push(value);
}
- let attrs = heap_loc_as_cell!(
- iter_to_heap_list(&mut self.machine_st.heap, avec.into_iter())
- );
+ let attrs = heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ avec.into_iter()
+ ));
let mut cvec = Vec::new();
cvec.push(self.xml_node_to_term(child));
}
- let children = heap_loc_as_cell!(
- iter_to_heap_list(&mut self.machine_st.heap, cvec.into_iter())
- );
+ let children = heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ cvec.into_iter()
+ ));
let tag = self.machine_st.atom_tbl.build_with(node.tag_name().name());
let result = str_loc_as_cell!(self.machine_st.heap.len());
- self.machine_st.heap.push(atom_as_cell!(atom!("element"), 3));
+ self.machine_st
+ .heap
+ .push(atom_as_cell!(atom!("element"), 3));
self.machine_st.heap.push(atom_as_cell!(tag));
self.machine_st.heap.push(attrs);
self.machine_st.heap.push(children);
pub(super) fn html_node_to_term(&mut self, node: select::node::Node) -> HeapCellValue {
match node.name() {
- None => {
- put_complete_string(
- &mut self.machine_st.heap,
- &node.text(),
- &mut self.machine_st.atom_tbl,
- )
- }
+ None => put_complete_string(
+ &mut self.machine_st.heap,
+ &node.text(),
+ &mut self.machine_st.atom_tbl,
+ ),
Some(name) => {
let mut avec = Vec::new();
self.machine_st.heap.push(value);
}
- let attrs = heap_loc_as_cell!(
- iter_to_heap_list(&mut self.machine_st.heap, avec.into_iter())
- );
+ let attrs = heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ avec.into_iter()
+ ));
let mut cvec = Vec::new();
cvec.push(self.html_node_to_term(child));
}
- let children = heap_loc_as_cell!(
- iter_to_heap_list(&mut self.machine_st.heap, cvec.into_iter())
- );
+ let children = heap_loc_as_cell!(iter_to_heap_list(
+ &mut self.machine_st.heap,
+ cvec.into_iter()
+ ));
let tag = self.machine_st.atom_tbl.build_with(name);
let result = str_loc_as_cell!(self.machine_st.heap.len());
- self.machine_st.heap.push(atom_as_cell!(atom!("element"), 3));
+ self.machine_st
+ .heap
+ .push(atom_as_cell!(atom!("element"), 3));
self.machine_st.heap.push(atom_as_cell!(tag));
self.machine_st.heap.push(attrs);
self.machine_st.heap.push(children);
use crate::forms::*;
-use crate::machine::*;
use crate::machine::load_state::*;
use crate::machine::loader::*;
use crate::machine::machine_errors::*;
+use crate::machine::*;
use crate::parser::ast::*;
use crate::parser::parser::*;
use crate::read::devour_whitespace;
listing_src: ListingSource,
) -> Self {
let parser = Parser::new(stream, machine_st);
- Self { parser, listing_src }
+ Self {
+ parser,
+ listing_src,
+ }
}
}
non_counted_bt_preds: IndexSet::with_hasher(FxBuildHasher::default()),
predicates: predicate_queue![],
clause_clauses: vec![],
- }
+ }
}
}
}
}
-pub struct InlineTermStream {
-}
+pub struct InlineTermStream {}
impl TermStream for InlineTermStream {
fn next(&mut self, _: &CompositeOpDir) -> Result<Term, CompilationError> {
- Err(CompilationError::from(ParserError::unexpected_eof()))
+ Err(CompilationError::from(ParserError::unexpected_eof()))
}
fn eof(&mut self) -> Result<bool, CompilationError> {
- Ok(true)
+ Ok(true)
}
fn listing_src(&self) -> &ListingSource {
- &ListingSource::User
+ &ListingSource::User
}
}
-
use crate::arena::*;
use crate::forms::*;
use crate::heap_iter::stackful_preorder_iter;
-use crate::machine::*;
use crate::machine::machine_state::*;
use crate::machine::partial_string::*;
+use crate::machine::*;
use crate::types::*;
use std::cmp::Ordering;
machine_st.pdl.push(pstr_iter1.focus);
}
}
- continuable @ PStrCmpResult::FirstIterContinuable(iteratee) |
- continuable @ PStrCmpResult::SecondIterContinuable(iteratee) => {
+ continuable @ PStrCmpResult::FirstIterContinuable(iteratee)
+ | continuable @ PStrCmpResult::SecondIterContinuable(iteratee) => {
if continuable.is_second_iter() {
std::mem::swap(&mut pstr_iter1, &mut pstr_iter2);
}
}
fn unify_big_num<N>(&mut self, n1: TypedArenaPtr<N>, value: HeapCellValue)
- where N: PartialEq<Rational>
- + PartialEq<Integer>
- + PartialEq<i64>
- + ArenaAllocated
+ where
+ N: PartialEq<Rational> + PartialEq<Integer> + PartialEq<i64> + ArenaAllocated,
{
if let Some(r) = value.as_var() {
Self::bind(self, r, typed_arena_ptr_as_cell!(n1));
}
macro_rules! cell_as_load_state_payload {
- ($cell:expr) => { unsafe {
- let ptr = cell_as_untyped_arena_ptr!($cell);
- let ptr = std::mem::transmute::<_, *mut LiveLoadState>(ptr.payload_offset());
+ ($cell:expr) => {
+ unsafe {
+ let ptr = cell_as_untyped_arena_ptr!($cell);
+ let ptr = std::mem::transmute::<_, *mut LiveLoadState>(ptr.payload_offset());
- TypedArenaPtr::new(ptr)
- }};
+ TypedArenaPtr::new(ptr)
+ }
+ };
}
macro_rules! match_untyped_arena_ptr_pat_body {
$code
}};
($ptr:ident, OssifiedOpDir, $n:ident, $code:expr) => {{
- let payload_ptr = unsafe { std::mem::transmute::<_, *mut OssifiedOpDir>($ptr.payload_offset()) };
+ let payload_ptr =
+ unsafe { std::mem::transmute::<_, *mut OssifiedOpDir>($ptr.payload_offset()) };
let $n = TypedArenaPtr::new(payload_ptr);
#[allow(unused_braces)]
$code
}};
($ptr:ident, LiveLoadState, $n:ident, $code:expr) => {{
- let payload_ptr = unsafe { std::mem::transmute::<_, *mut LiveLoadState>($ptr.payload_offset()) };
+ let payload_ptr =
+ unsafe { std::mem::transmute::<_, *mut LiveLoadState>($ptr.payload_offset()) };
let $n = TypedArenaPtr::new(payload_ptr);
#[allow(unused_braces)]
$code
$code
}};
($ptr:ident, TcpListener, $listener:ident, $code:expr) => {{
- let payload_ptr = unsafe { std::mem::transmute::<_, *mut TcpListener>($ptr.payload_offset()) };
+ let payload_ptr =
+ unsafe { std::mem::transmute::<_, *mut TcpListener>($ptr.payload_offset()) };
#[allow(unused_mut)]
let mut $listener = TypedArenaPtr::new(payload_ptr);
#[allow(unused_braces)]
$code
}};
($ptr:ident, HttpListener, $listener:ident, $code:expr) => {{
- let payload_ptr = unsafe { std::mem::transmute::<_, *mut HttpListener>($ptr.payload_offset()) };
+ let payload_ptr =
+ unsafe { std::mem::transmute::<_, *mut HttpListener>($ptr.payload_offset()) };
#[allow(unused_mut)]
let mut $listener = TypedArenaPtr::new(payload_ptr);
#[allow(unused_braces)]
$code
}};
($ptr:ident, HttpResponse, $listener:ident, $code:expr) => {{
- let payload_ptr = unsafe { std::mem::transmute::<_, *mut HttpResponse>($ptr.payload_offset()) };
+ let payload_ptr =
+ unsafe { std::mem::transmute::<_, *mut HttpResponse>($ptr.payload_offset()) };
#[allow(unused_mut)]
let mut $listener = TypedArenaPtr::new(payload_ptr);
#[allow(unused_braces)]
}};
($ptr:ident, IndexPtr, $ip:ident, $code:expr) => {{
#[allow(unused_mut)]
- let mut $ip = TypedArenaPtr::new(unsafe { std::mem::transmute::<_, *mut IndexPtr>($ptr.get_ptr()) });
+ let mut $ip =
+ TypedArenaPtr::new(unsafe { std::mem::transmute::<_, *mut IndexPtr>($ptr.get_ptr()) });
#[allow(unused_braces)]
$code
}};
| ArenaHeaderTag::NamedTcpStream
| ArenaHeaderTag::NamedTlsStream
| ArenaHeaderTag::HttpReadStream
- | ArenaHeaderTag::HttpWriteStream
+ | ArenaHeaderTag::HttpWriteStream
| ArenaHeaderTag::ReadlineStream
| ArenaHeaderTag::StaticStringStream
| ArenaHeaderTag::ByteStream
| ArenaHeaderTag::StandardErrorStream
};
(IndexPtr) => {
- ArenaHeaderTag::IndexPtrUndefined |
- ArenaHeaderTag::IndexPtrDynamicUndefined |
- ArenaHeaderTag::IndexPtrDynamicIndex |
- ArenaHeaderTag::IndexPtrIndex
+ ArenaHeaderTag::IndexPtrUndefined
+ | ArenaHeaderTag::IndexPtrDynamicUndefined
+ | ArenaHeaderTag::IndexPtrDynamicIndex
+ | ArenaHeaderTag::IndexPtrIndex
};
($tag:ident) => {
ArenaHeaderTag::$tag
}
macro_rules! read_heap_cell_pat_body {
- ($cell:ident, Cons, $n:ident, $code:expr) => ({
+ ($cell:ident, Cons, $n:ident, $code:expr) => {{
let $n = cell_as_untyped_arena_ptr!($cell);
#[allow(unused_braces)]
$code
- });
- ($cell:ident, F64, $n:ident, $code:expr) => ({
+ }};
+ ($cell:ident, F64, $n:ident, $code:expr) => {{
let $n = cell_as_f64_ptr!($cell);
#[allow(unused_braces)]
$code
- });
- ($cell:ident, Atom, ($name:ident, $arity:ident), $code:expr) => ({
+ }};
+ ($cell:ident, Atom, ($name:ident, $arity:ident), $code:expr) => {{
let ($name, $arity) = cell_as_atom_cell!($cell).get_name_and_arity();
#[allow(unused_braces)]
$code
- });
- ($cell:ident, PStr, $atom:ident, $code:expr) => ({
+ }};
+ ($cell:ident, PStr, $atom:ident, $code:expr) => {{
let $atom = cell_as_atom!($cell);
#[allow(unused_braces)]
$code
- });
- ($cell:ident, CStr, $atom:ident, $code:expr) => ({
+ }};
+ ($cell:ident, CStr, $atom:ident, $code:expr) => {{
let $atom = cell_as_atom!($cell);
#[allow(unused_braces)]
$code
- });
- ($cell:ident, CStr | PStr, $atom:ident, $code:expr) => ({
+ }};
+ ($cell:ident, CStr | PStr, $atom:ident, $code:expr) => {{
let $atom = cell_as_atom!($cell);
#[allow(unused_braces)]
$code
- });
- ($cell:ident, PStr | CStr, $atom:ident, $code:expr) => ({
+ }};
+ ($cell:ident, PStr | CStr, $atom:ident, $code:expr) => {{
let $atom = cell_as_atom!($cell);
#[allow(unused_braces)]
$code
- });
- ($cell:ident, Fixnum, $value:ident, $code:expr) => ({
+ }};
+ ($cell:ident, Fixnum, $value:ident, $code:expr) => {{
let $value = Fixnum::from_bytes($cell.into_bytes());
#[allow(unused_braces)]
$code
- });
- ($cell:ident, CutPoint, $value:ident, $code:expr) => ({
+ }};
+ ($cell:ident, CutPoint, $value:ident, $code:expr) => {{
let $value = Fixnum::from_bytes($cell.into_bytes());
#[allow(unused_braces)]
$code
- });
- ($cell:ident, Fixnum | CutPoint, $value:ident, $code:expr) => ({
+ }};
+ ($cell:ident, Fixnum | CutPoint, $value:ident, $code:expr) => {{
let $value = Fixnum::from_bytes($cell.into_bytes());
#[allow(unused_braces)]
$code
- });
- ($cell:ident, CutPoint | Fixnum, $value:ident, $code:expr) => ({
+ }};
+ ($cell:ident, CutPoint | Fixnum, $value:ident, $code:expr) => {{
let $value = Fixnum::from_bytes($cell.into_bytes());
#[allow(unused_braces)]
$code
- });
- ($cell:ident, Char, $value:ident, $code:expr) => ({
+ }};
+ ($cell:ident, Char, $value:ident, $code:expr) => {{
let $value = unsafe { char::from_u32_unchecked($cell.get_value() as u32) };
#[allow(unused_braces)]
$code
- });
- ($cell:ident, $($tags:tt)|+, $value:ident, $code:expr) => ({
+ }};
+ ($cell:ident, $($tags:tt)|+, $value:ident, $code:expr) => {{
let $value = $cell.get_value() as usize;
#[allow(unused_braces)]
$code
- });
+ }};
}
macro_rules! read_heap_cell_pat {
IndexStore {
code_dir: $code_dir,
extensible_predicates: ExtensiblePredicates::with_hasher(FxBuildHasher::default()),
- local_extensible_predicates: LocalExtensiblePredicates::with_hasher(FxBuildHasher::default()),
+ local_extensible_predicates: LocalExtensiblePredicates::with_hasher(
+ FxBuildHasher::default(),
+ ),
global_variables: GlobalVarDir::with_hasher(FxBuildHasher::default()),
goal_expansion_indices: GoalExpansionIndices::with_hasher(FxBuildHasher::default()),
meta_predicates: MetaPredicateDir::with_hasher(FxBuildHasher::default()),
pub struct OpDesc {
prec: B11,
spec: B8,
- #[allow(unused)] padding: B13,
+ #[allow(unused)]
+ padding: B13,
}
impl OpDesc {
impl ParserError {
pub fn line_and_col_num(&self) -> Option<(usize, usize)> {
match self {
- &ParserError::BackQuotedString(line_num, col_num) |
- &ParserError::IncompleteReduction(line_num, col_num) |
- &ParserError::MissingQuote(line_num, col_num) |
- &ParserError::NonPrologChar(line_num, col_num) |
- &ParserError::ParseBigInt(line_num, col_num) |
- &ParserError::UnexpectedChar(_, line_num, col_num) |
- &ParserError::Utf8Error(line_num, col_num) => Some((line_num, col_num)),
+ &ParserError::BackQuotedString(line_num, col_num)
+ | &ParserError::IncompleteReduction(line_num, col_num)
+ | &ParserError::MissingQuote(line_num, col_num)
+ | &ParserError::NonPrologChar(line_num, col_num)
+ | &ParserError::ParseBigInt(line_num, col_num)
+ | &ParserError::UnexpectedChar(_, line_num, col_num)
+ | &ParserError::Utf8Error(line_num, col_num) => Some((line_num, col_num)),
_ => None,
}
}
match self {
ParserError::BackQuotedString(..) => atom!("back_quoted_string"),
ParserError::IncompleteReduction(..) => atom!("incomplete_reduction"),
- ParserError::InvalidSingleQuotedCharacter(..) => atom!("invalid_single_quoted_character"),
- ParserError::IO(e) if e.kind() == ErrorKind::UnexpectedEof => atom!("unexpected_end_of_file"),
+ ParserError::InvalidSingleQuotedCharacter(..) => {
+ atom!("invalid_single_quoted_character")
+ }
+ ParserError::IO(e) if e.kind() == ErrorKind::UnexpectedEof => {
+ atom!("unexpected_end_of_file")
+ }
ParserError::IO(_) => atom!("input_output_error"),
ParserError::LexicalError(_) => atom!("lexical_error"),
ParserError::MissingQuote(..) => atom!("missing_quote"),
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub struct Fixnum {
num: B56,
- #[allow(unused)] f: bool,
- #[allow(unused)] m: bool,
- #[allow(unused)] tag: B6,
+ #[allow(unused)]
+ f: bool,
+ #[allow(unused)]
+ m: bool,
+ #[allow(unused)]
+ tag: B6,
}
impl Fixnum {
}
}
-
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VarPtr(Rc<RefCell<Var>>);
pub struct CharReader<R> {
inner: R,
- buf: SmallVec<[u8;32]>,
+ buf: SmallVec<[u8; 32]>,
pos: usize,
}
self.consume(c.len_utf8());
Some(Ok(c))
}
- result => result
+ result => result,
}
}
return Some(Ok(c));
}
- Err(e) => {
- e
- }
+ Err(e) => e,
};
if buf.len() - e.valid_up_to() >= 4 {
// the buffer, it will be returned on the next
// loop.
- return Some(Err(io::Error::new(io::ErrorKind::InvalidData,
- BadUtf8Error { bytes: badbytes })));
+ return Some(Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ BadUtf8Error { bytes: badbytes },
+ )));
} else {
if self.pos >= self.buf.len() {
return None;
} else if self.buf.len() - self.pos >= 4 {
- return match str::from_utf8(&self.buf[self.pos .. e.valid_up_to()]) {
+ return match str::from_utf8(&self.buf[self.pos..e.valid_up_to()]) {
Ok(s) => {
let mut chars = s.chars();
let c = chars.next().unwrap();
Some(Ok(c))
}
Err(e) => {
- let badbytes = self.buf[self.pos .. e.valid_up_to()].to_vec();
+ let badbytes = self.buf[self.pos..e.valid_up_to()].to_vec();
- Some(Err(io::Error::new(io::ErrorKind::InvalidData,
- BadUtf8Error { bytes: badbytes })))
+ Some(Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ BadUtf8Error { bytes: badbytes },
+ )))
}
};
} else {
let buf_len = self.buf.len();
- let mut word = [0u8;4];
+ let mut word = [0u8; 4];
let word_slice = &mut word[buf_len..4];
match self.inner.read(word_slice) {
let c_len = c.len_utf8();
let mut shifted_slice = [0u8; 32];
- shifted_slice[0..src_len].copy_from_slice(&self.buf[self.pos .. self.buf.len()]);
+ shifted_slice[0..src_len].copy_from_slice(&self.buf[self.pos..self.buf.len()]);
self.buf.resize(c_len, 0);
self.buf.extend_from_slice(&shifted_slice[0..src_len]);
}
if !buf.is_empty() {
- Err(io::Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
+ Err(io::Error::new(
+ ErrorKind::UnexpectedEof,
+ "failed to fill whole buffer",
+ ))
} else {
Ok(())
}
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("CharReader")
.field("reader", &self.inner)
- .field("buf", &format_args!("{}/{}", self.buf.capacity() - self.pos, self.buf.len()))
+ .field(
+ "buf",
+ &format_args!("{}/{}", self.buf.capacity() - self.pos, self.buf.len()),
+ )
.finish()
}
}
-
#[cfg(test)]
mod tests {
use crate::parser::char_reader::*;
pub fn lookahead_char(&mut self) -> Result<char, ParserError> {
match self.reader.peek_char() {
Some(Ok(c)) => Ok(c),
- _ => Err(ParserError::unexpected_eof())
+ _ => Err(ParserError::unexpected_eof()),
}
}
pub fn read_char(&mut self) -> Result<char, ParserError> {
match self.reader.read_char() {
Some(Ok(c)) => Ok(c),
- _ => Err(ParserError::unexpected_eof())
+ _ => Err(ParserError::unexpected_eof()),
}
}
match comment_loop() {
Err(e) if e.is_unexpected_eof() => {
- return Err(ParserError::IncompleteReduction(self.line_num, self.col_num));
+ return Err(ParserError::IncompleteReduction(
+ self.line_num,
+ self.col_num,
+ ));
}
Err(e) => {
return Err(e);
}
- Ok(_) => {
- }
+ Ok(_) => {}
}
if prolog_char!(c) {
if hexadecimal_digit_char!(c) {
self.escape_sequence_to_char(|c| hexadecimal_digit_char!(c), 16)
} else {
- Err(ParserError::IncompleteReduction(self.line_num, self.col_num))
+ Err(ParserError::IncompleteReduction(
+ self.line_num,
+ self.col_num,
+ ))
}
}
},
)
} else {
- Err(ParserError::IncompleteReduction(self.line_num, self.col_num))
+ Err(ParserError::IncompleteReduction(
+ self.line_num,
+ self.col_num,
+ ))
}
}
.map(|n| Token::Literal(fixnum!(Literal, n, &mut self.machine_st.arena)))
.or_else(|_| {
Integer::from_str_radix(&token, 16)
- .map(|n| Token::Literal(Literal::Integer(
- arena_alloc!(n, &mut self.machine_st.arena)
- )))
+ .map(|n| {
+ Token::Literal(Literal::Integer(arena_alloc!(
+ n,
+ &mut self.machine_st.arena
+ )))
+ })
.map_err(|_| ParserError::ParseBigInt(self.line_num, self.col_num))
})
} else {
.map(|n| Token::Literal(fixnum!(Literal, n, &mut self.machine_st.arena)))
.or_else(|_| {
Integer::from_str_radix(&token, 8)
- .map(|n| Token::Literal(Literal::Integer(
- arena_alloc!(n, &mut self.machine_st.arena)
- )))
+ .map(|n| {
+ Token::Literal(Literal::Integer(arena_alloc!(
+ n,
+ &mut self.machine_st.arena
+ )))
+ })
.map_err(|_| ParserError::ParseBigInt(self.line_num, self.col_num))
})
} else {
.map(|n| Token::Literal(fixnum!(Literal, n, &mut self.machine_st.arena)))
.or_else(|_| {
Integer::from_str_radix(&token, 2)
- .map(|n| Token::Literal(Literal::Integer(
- arena_alloc!(n, &mut self.machine_st.arena)
- )))
+ .map(|n| {
+ Token::Literal(Literal::Integer(arena_alloc!(
+ n,
+ &mut self.machine_st.arena
+ )))
+ })
.map_err(|_| ParserError::ParseBigInt(self.line_num, self.col_num))
})
} else {
fn vacate_with_float(&mut self, mut token: String) -> Result<Token, ParserError> {
self.return_char(token.pop().unwrap());
let n = parse_lossy::<f64, _>(token.as_bytes())?;
- Ok(Token::Literal(Literal::from(float_alloc!(n, self.machine_st.arena))))
+ Ok(Token::Literal(Literal::from(float_alloc!(
+ n,
+ self.machine_st.arena
+ ))))
}
fn skip_underscore_in_number(&mut self) -> Result<char, ParserError> {
token
.parse::<Integer>()
.map(|n| {
- Token::Literal(Literal::Integer(arena_alloc!(n, &mut self.machine_st.arena)))
+ Token::Literal(Literal::Integer(arena_alloc!(
+ n,
+ &mut self.machine_st.arena
+ )))
})
.map_err(|_| ParserError::ParseBigInt(self.line_num, self.col_num))
})
}
let n = parse_lossy::<f64, _>(token.as_bytes())?;
- Ok(Token::Literal(Literal::from(
- float_alloc!(n, self.machine_st.arena)
- )))
+ Ok(Token::Literal(Literal::from(float_alloc!(
+ n,
+ self.machine_st.arena
+ ))))
} else {
return Ok(self.vacate_with_float(token)?);
}
} else {
let n = parse_lossy::<f64, _>(token.as_bytes())?;
- Ok(Token::Literal(Literal::from(
- float_alloc!(n, self.machine_st.arena)
- )))
+ Ok(Token::Literal(Literal::from(float_alloc!(
+ n,
+ self.machine_st.arena
+ ))))
}
} else {
self.return_char('.');
token
.parse::<Integer>()
.map(|n| {
- Token::Literal(Literal::Integer(arena_alloc!(n, &mut self.machine_st.arena)))
+ Token::Literal(Literal::Integer(arena_alloc!(
+ n,
+ &mut self.machine_st.arena
+ )))
})
.map_err(|_| ParserError::ParseBigInt(self.line_num, self.col_num))
})
self.hexadecimal_constant(c).or_else(|e| {
if let ParserError::ParseBigInt(..) = e {
i64::from_str_radix(&token, 10)
- .map(|n| Token::Literal(fixnum!(Literal, n, &mut self.machine_st.arena)))
+ .map(|n| {
+ Token::Literal(fixnum!(Literal, n, &mut self.machine_st.arena))
+ })
.or_else(|_| {
token
.parse::<Integer>()
self.octal_constant(c).or_else(|e| {
if let ParserError::ParseBigInt(..) = e {
i64::from_str_radix(&token, 10)
- .map(|n| Token::Literal(fixnum!(Literal, n, &mut self.machine_st.arena)))
+ .map(|n| {
+ Token::Literal(fixnum!(Literal, n, &mut self.machine_st.arena))
+ })
.or_else(|_| {
token
.parse::<Integer>()
self.binary_constant(c).or_else(|e| {
if let ParserError::ParseBigInt(..) = e {
i64::from_str_radix(&token, 10)
- .map(|n| Token::Literal(fixnum!(Literal, n, &mut self.machine_st.arena)))
+ .map(|n| {
+ Token::Literal(fixnum!(Literal, n, &mut self.machine_st.arena))
+ })
.or_else(|_| {
token
.parse::<Integer>()
.map(|c| Token::Literal(Literal::Fixnum(Fixnum::build_with(c as i64))))
.or_else(|err| {
match err {
- ParserError::UnexpectedChar('\'', ..) => {
- }
+ ParserError::UnexpectedChar('\'', ..) => {}
err => return Err(err),
}
self.return_char(c);
i64::from_str_radix(&token, 10)
- .map(|n| Token::Literal(fixnum!(Literal, n, &mut self.machine_st.arena)))
+ .map(|n| {
+ Token::Literal(fixnum!(Literal, n, &mut self.machine_st.arena))
+ })
.or_else(|_| {
token
.parse::<Integer>()
token
.parse::<Integer>()
.map(|n| {
- Token::Literal(Literal::Integer(arena_alloc!(n, &mut self.machine_st.arena)))
+ Token::Literal(Literal::Integer(arena_alloc!(
+ n,
+ &mut self.machine_st.arena
+ )))
})
.map_err(|_| ParserError::ParseBigInt(self.line_num, self.col_num))
})
pub fn scan_for_layout(&mut self) -> Result<bool, ParserError> {
match self.lookahead_char() {
- Err(e) => {
- Err(e)
- }
+ Err(e) => Err(e),
Ok(c) => {
- let mut layout_info = LayoutInfo { inserted: false, more: true };
+ let mut layout_info = LayoutInfo {
+ inserted: false,
+ more: true,
+ };
let mut cr = Some(c);
loop {
}
if c == '\u{0}' {
- return Err(ParserError::unexpected_eof())
+ return Err(ParserError::unexpected_eof());
}
self.name_token(c)
#[macro_export]
macro_rules! alpha_char {
($c: expr) => {
- (!$c.is_numeric() &&
- !$c.is_whitespace() &&
- !$c.is_control() &&
- !$crate::graphic_token_char!($c) &&
- !$crate::layout_char!($c) &&
- !$crate::meta_char!($c) &&
- !$crate::solo_char!($c)) || $c == '_'
+ (!$c.is_numeric()
+ && !$c.is_whitespace()
+ && !$c.is_control()
+ && !$crate::graphic_token_char!($c)
+ && !$crate::layout_char!($c)
+ && !$crate::meta_char!($c)
+ && !$crate::solo_char!($c))
+ || $c == '_'
};
}
use crate::parser::char_reader::*;
use crate::parser::lexer::*;
-
use std::cell::Cell;
use std::mem;
use std::ops::Neg;
}
match &tail {
- Term::AnonVar | Term::Var(..) => {
- Ok((string, Some(Box::new(tail))))
- }
- Term::Literal(_, Literal::Atom(atom!("[]"))) => {
- Ok((string, None))
- }
+ Term::AnonVar | Term::Var(..) => Ok((string, Some(Box::new(tail)))),
+ Term::Literal(_, Literal::Atom(atom!("[]"))) => Ok((string, None)),
Term::Literal(_, Literal::String(tail)) => {
string += tail.as_str();
Ok((string, None))
}
- _ => {
- Ok((string, Some(Box::new(tail))))
- }
+ _ => Ok((string, Some(Box::new(tail)))),
}
}
-pub fn get_op_desc(
- name: Atom,
- op_dir: &CompositeOpDir,
-) -> Option<CompositeOpDesc> {
+pub fn get_op_desc(name: Atom, op_dir: &CompositeOpDir) -> Option<CompositeOpDesc> {
let mut op_desc = CompositeOpDesc {
pre: 0,
inf: 0,
}
fn promote_atom_op(&mut self, atom: Atom, priority: usize, assoc: u32) {
- self.terms.push(Term::Literal(Cell::default(), Literal::Atom(atom)));
+ self.terms
+ .push(Term::Literal(Cell::default(), Literal::Atom(atom)));
self.stack.push(TokenDesc {
tt: TokenType::Term,
priority,
fn shift(&mut self, token: Token, priority: usize, spec: Specifier) {
let tt = match token {
- Token::Literal(Literal::String(s)) if self.lexer.machine_st.flags.double_quotes.is_codes() => {
+ Token::Literal(Literal::String(s))
+ if self.lexer.machine_st.flags.double_quotes.is_codes() =>
+ {
let mut list = Term::Literal(Cell::default(), Literal::Atom(atom!("[]")));
for c in s.as_str().chars().rev() {
self.terms.push(list);
TokenType::Term
}
- Token::Literal(Literal::String(s)) if self.lexer.machine_st.flags.double_quotes.is_chars() => {
+ Token::Literal(Literal::String(s))
+ if self.lexer.machine_st.flags.double_quotes.is_chars() =>
+ {
self.terms.push(Term::CompleteString(Cell::default(), s));
TokenType::Term
}
let tail = subterms.pop().unwrap();
let head = subterms.pop().unwrap();
- self.terms.push(
- match as_partial_string(head, tail) {
- Ok((string_buf, Some(tail))) => {
- Term::PartialString(Cell::default(), string_buf, tail)
- }
- Ok((string_buf, None)) => {
- let atom = self.lexer.machine_st.atom_tbl.build_with(&string_buf);
- Term::CompleteString(Cell::default(), atom)
- }
- Err(term) => term,
- },
- );
+ self.terms.push(match as_partial_string(head, tail) {
+ Ok((string_buf, Some(tail))) => {
+ Term::PartialString(Cell::default(), string_buf, tail)
+ }
+ Ok((string_buf, None)) => {
+ let atom = self.lexer.machine_st.atom_tbl.build_with(&string_buf);
+ Term::CompleteString(Cell::default(), atom)
+ }
+ Err(term) => term,
+ });
} else {
- self.terms.push(Term::Clause(Cell::default(), name, subterms));
+ self.terms
+ .push(Term::Clause(Cell::default(), name, subterms));
}
if let Some(&mut TokenDesc {
td.tt = TokenType::Term;
td.priority = 0;
- self.terms.push(Term::Literal(Cell::default(), Literal::Atom(atom!("[]"))));
+ self.terms
+ .push(Term::Literal(Cell::default(), Literal::Atom(atom!("[]"))));
return Ok(true);
}
}
if arity > self.terms.len() {
return Err(ParserError::IncompleteReduction(
self.lexer.line_num,
- self.lexer.col_num
- ))
+ self.lexer.col_num,
+ ));
}
let idx = self.terms.len() - arity;
});
self.terms.push(match list {
- Term::Cons(_, head, tail) => {
- match as_partial_string(*head, *tail) {
- Ok((string_buf, Some(tail))) => {
- Term::PartialString(Cell::default(), string_buf, tail)
- }
- Ok((string_buf, None)) => {
- let atom = self.lexer.machine_st.atom_tbl.build_with(&string_buf);
- Term::CompleteString(Cell::default(), atom)
- }
- Err(term) => term,
+ Term::Cons(_, head, tail) => match as_partial_string(*head, *tail) {
+ Ok((string_buf, Some(tail))) => {
+ Term::PartialString(Cell::default(), string_buf, tail)
}
- }
+ Ok((string_buf, None)) => {
+ let atom = self.lexer.machine_st.atom_tbl.build_with(&string_buf);
+ Term::CompleteString(Cell::default(), atom)
+ }
+ Err(term) => term,
+ },
term => term,
});
td.priority = 0;
td.spec = TERM;
- let term = Term::Literal(
- Cell::default(),
- Literal::Atom(atom!("{}")),
- );
+ let term = Term::Literal(Cell::default(), Literal::Atom(atom!("{}")));
self.terms.push(term);
return Ok(true);
}
};
- self.terms.push(Term::Clause(
- Cell::default(),
- atom!("{}"),
- vec![term],
- ));
+ self.terms
+ .push(Term::Clause(Cell::default(), atom!("{}"), vec![term]));
return Ok(true);
}
if let Some(term) = self.terms.last().cloned() {
match term {
Term::Literal(_, Literal::Atom(name))
- if name == atom!("-") && (is_prefix!(desc.spec) || is_negate!(desc.spec)) =>
+ if name == atom!("-")
+ && (is_prefix!(desc.spec) || is_negate!(desc.spec)) =>
{
self.stack.pop();
self.terms.pop();
}
// on success, returns the parsed term and the number of lines read.
- pub fn read_term(&mut self, op_dir: &CompositeOpDir, tokens: Tokens) -> Result<Term, ParserError> {
+ pub fn read_term(
+ &mut self,
+ op_dir: &CompositeOpDir,
+ tokens: Tokens,
+ ) -> Result<Term, ParserError> {
self.tokens = match tokens {
Tokens::Default => read_tokens(&mut self.lexer)?,
Tokens::Provided(tokens) => tokens,
type SubtermDeque = VecDeque<(usize, usize)>;
-pub(crate) fn devour_whitespace<'a, R: CharRead>(parser: &mut Parser<'a, R>) -> Result<bool, ParserError> {
+pub(crate) fn devour_whitespace<'a, R: CharRead>(
+ parser: &mut Parser<'a, R>,
+) -> Result<bool, ParserError> {
match parser.lexer.scan_for_layout() {
- Err(e) if e.is_unexpected_eof() => {
- Ok(true)
- }
+ Err(e) if e.is_unexpected_eof() => Ok(true),
Err(e) => Err(e),
- Ok(_) => {
- Ok(false)
- }
+ Ok(_) => Ok(false),
}
}
CompilationError::from(err)
}
-
impl MachineState {
pub(crate) fn read(
&mut self,
parser.add_lines_read(prior_num_lines_read);
- let term = parser.read_term(&op_dir, Tokens::Default)
+ let term = parser
+ .read_term(&op_dir, Tokens::Default)
.map_err(|err| error_after_read_term(err, prior_num_lines_read, &parser))?; // CompilationError::from
(term, parser.lines_read() - prior_num_lines_read)
#[cfg(feature = "repl")]
#[inline]
pub fn new(pending_input: &str, add_history: bool) -> Self {
- let config = Config::builder()
- .check_cursor_position(true)
- .build();
+ let config = Config::builder().check_cursor_position(true).build();
let helper = Helper::new();
}
#[cfg(not(feature = "repl"))]
- pub fn set_atoms_for_completion(&mut self, atoms: *const IndexSet<Atom>) {
- }
+ pub fn set_atoms_for_completion(&mut self, atoms: *const IndexSet<Atom>) {}
#[inline]
pub fn reset(&mut self) {
unsafe {
if PROMPT {
- self.rl.add_history_entry(self.pending_input.get_ref().get_ref()).unwrap();
+ self.rl
+ .add_history_entry(self.pending_input.get_ref().get_ref())
+ .unwrap();
self.save_history();
PROMPT = false;
}
}
#[cfg(not(feature = "repl"))]
- fn save_history(&mut self) {
- }
+ fn save_history(&mut self) {}
#[inline]
pub(crate) fn peek_byte(&mut self) -> std::io::Result<u8> {
self.call_readline()?;
self.pending_input.read(buf)
}
- result => result
+ result => result,
}
}
}
Some(Ok(c)) => {
return Some(Ok(c));
}
- _ => {
- match self.call_readline() {
- Err(e) => {
- return Some(Err(e));
- }
- _ => {
- set_prompt(false);
- }
+ _ => match self.call_readline() {
+ Err(e) => {
+ return Some(Err(e));
}
- }
+ _ => {
+ set_prompt(false);
+ }
+ },
}
}
}
match term {
&TermRef::Cons(..) => list_loc_as_cell!(h),
&TermRef::AnonVar(_) | &TermRef::Var(..) => heap_loc_as_cell!(h),
- &TermRef::CompleteString(_, _, ref src) =>
+ &TermRef::CompleteString(_, _, ref src) => {
if src.as_str().is_empty() {
empty_list_as_cell!()
} else if self.heap[h].get_tag() == HeapCellValueTag::CStr {
heap_loc_as_cell!(h)
} else {
pstr_loc_as_cell!(h)
- },
+ }
+ }
&TermRef::PartialString(..) => pstr_loc_as_cell!(h),
&TermRef::Literal(_, _, literal) => HeapCellValue::from(*literal),
- &TermRef::Clause(_,_,_,subterms) if subterms.len() == 0 => heap_loc_as_cell!(h),
+ &TermRef::Clause(_, _, _, subterms) if subterms.len() == 0 => heap_loc_as_cell!(h),
&TermRef::Clause(..) => str_loc_as_cell!(h),
}
}
}
&TermRef::AnonVar(_) => {
if let Some((arity, site_h)) = self.queue.pop_front() {
- self.var_dict.insert(VarKey::AnonVar(h), heap_loc_as_cell!(site_h));
+ self.var_dict
+ .insert(VarKey::AnonVar(h), heap_loc_as_cell!(site_h));
if arity > 1 {
self.queue.push_front((arity - 1, site_h + 1));
use indexmap::IndexSet;
-use rustyline::completion::{Completer, Candidate};
+use rustyline::completion::{Candidate, Completer};
+use rustyline::highlight::{Highlighter, MatchingBracketHighlighter};
use rustyline::hint::Hinter;
use rustyline::validate::Validator;
-use rustyline::highlight::{MatchingBracketHighlighter, Highlighter};
-use rustyline::{Helper as RlHelper, Result, Context};
+use rustyline::{Context, Helper as RlHelper, Result};
use crate::atom_table::{Atom, STATIC_ATOMS_MAP};
}
if i == pos {
- break
+ break;
}
}
impl Candidate for StrPtr {
fn display(&self) -> &str {
- unsafe {
- self.0.as_ref().unwrap()
- }
+ unsafe { self.0.as_ref().unwrap() }
}
fn replacement(&self) -> &str {
- unsafe {
- self.0.as_ref().unwrap()
- }
+ unsafe { self.0.as_ref().unwrap() }
}
}
impl Completer for Helper {
type Candidate = StrPtr;
- fn complete(&self, line: &str, pos: usize, _ctx: &Context<'_>) -> Result<(usize, Vec<Self::Candidate>)> {
+ fn complete(
+ &self,
+ line: &str,
+ pos: usize,
+ _ctx: &Context<'_>,
+ ) -> Result<(usize, Vec<Self::Candidate>)> {
let start_of_prefix = get_prefix(line, pos);
if let Some(idx) = start_of_prefix {
let sub_str = line.get(idx..pos).unwrap();
Ok((idx, unsafe {
- let mut matching = (*self.atoms).iter()
+ let mut matching = (*self.atoms)
+ .iter()
.chain(STATIC_ATOMS_MAP.values())
.filter(|a| a.as_str().starts_with(sub_str))
.map(|s| StrPtr(s.as_str()))
PStrOffset = 0b001111,
// constants.
Cons = 0b0,
- F64 = 0b010001,
+ F64 = 0b010001,
Fixnum = 0b010011,
Char = 0b010101,
Atom = 0b010111,
PStrOffset = 0b001111,
// constants.
Cons = 0b0,
- F64 = 0b010001,
+ F64 = 0b010001,
Fixnum = 0b010011,
Char = 0b010101,
Atom = 0b010111,
TrailedHeapVar = 0b101111,
TrailedStackVar = 0b101011,
TrailedAttrVar = 0b100001,
- TrailedAttrVarListLink = 0b100011,
- TrailedAttachedValue = 0b100101,
- TrailedBlackboardEntry = 0b100111,
+ TrailedAttrVarListLink = 0b100011,
+ TrailedAttachedValue = 0b100101,
+ TrailedBlackboardEntry = 0b100111,
TrailedBlackboardOffset = 0b110011,
}
.with_tag(tag)
}
- #[cfg(target_pointer_width="32")]
+ #[cfg(target_pointer_width = "32")]
#[inline(always)]
pub fn as_ptr(self) -> *mut u8 {
let bytes = self.into_bytes();
unsafe { mem::transmute(raw_ptr_bytes) }
}
- #[cfg(target_pointer_width="64")]
+ #[cfg(target_pointer_width = "64")]
#[inline(always)]
pub fn as_ptr(self) -> *mut u8 {
self.ptr() as *mut _
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub struct Ref {
val: B56,
- #[allow(unused)] m: bool,
- #[allow(unused)] f: bool,
+ #[allow(unused)]
+ m: bool,
+ #[allow(unused)]
+ f: bool,
tag: RefTag,
}
impl Ord for Ref {
fn cmp(&self, rhs: &Ref) -> Ordering {
match self.get_tag() {
- RefTag::HeapCell | RefTag::AttrVar => {
- match rhs.get_tag() {
- RefTag::StackCell => Ordering::Less,
- _ => self.get_value().cmp(&rhs.get_value()),
- }
- }
- RefTag::StackCell => {
- match rhs.get_tag() {
- RefTag::StackCell =>
- self.get_value().cmp(&rhs.get_value()),
- _ =>
- Ordering::Greater,
- }
- }
+ RefTag::HeapCell | RefTag::AttrVar => match rhs.get_tag() {
+ RefTag::StackCell => Ordering::Less,
+ _ => self.get_value().cmp(&rhs.get_value()),
+ },
+ RefTag::StackCell => match rhs.get_tag() {
+ RefTag::StackCell => self.get_value().cmp(&rhs.get_value()),
+ _ => Ordering::Greater,
+ },
}
}
}
TrailedHeapVar = 0b101111,
TrailedStackVar = 0b101011,
TrailedAttrVar = 0b100001,
- TrailedAttrVarListLink = 0b100011,
- TrailedAttachedValue = 0b100101,
- TrailedBlackboardEntry = 0b100111,
+ TrailedAttrVarListLink = 0b100011,
+ TrailedAttachedValue = 0b100101,
+ TrailedBlackboardEntry = 0b100111,
TrailedBlackboardOffset = 0b110011,
}
#[repr(u64)]
pub(crate) struct TrailEntry {
val: B56,
- #[allow(unused)] f: bool,
- #[allow(unused)] m: bool,
- #[allow(unused)] tag: TrailEntryTag,
+ #[allow(unused)]
+ f: bool,
+ #[allow(unused)]
+ m: bool,
+ #[allow(unused)]
+ tag: TrailEntryTag,
}
impl TrailEntry {
#[inline(always)]
pub(crate) fn get_tag(self) -> TrailEntryTag {
match self.tag_or_err() {
- Ok(tag) => tag,
- Err(_) => TrailEntryTag::TrailedAttachedValue,
- }
+ Ok(tag) => tag,
+ Err(_) => TrailEntryTag::TrailedAttachedValue,
+ }
}
#[inline]
impl fmt::Debug for HeapCellValue {
fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result {
match self.get_tag() {
- HeapCellValueTag::F64 => {
- f.debug_struct("HeapCellValue")
- .field("tag", &HeapCellValueTag::F64)
- .field("offset", &self.get_value())
- .field("m", &self.m())
- .field("f", &self.f())
- .finish()
- }
+ HeapCellValueTag::F64 => f
+ .debug_struct("HeapCellValue")
+ .field("tag", &HeapCellValueTag::F64)
+ .field("offset", &self.get_value())
+ .field("m", &self.m())
+ .field("f", &self.f())
+ .finish(),
HeapCellValueTag::Cons => {
let cons_ptr = ConsPtr::from_bytes(self.into_bytes());
.finish()
}
HeapCellValueTag::Atom => {
- let (name, arity) = cell_as_atom_cell!(self)
- .get_name_and_arity();
+ let (name, arity) = cell_as_atom_cell!(self).get_name_and_arity();
f.debug_struct("HeapCellValue")
.field("tag", &HeapCellValueTag::Atom)
.finish()
}
HeapCellValueTag::PStr => {
- let (name, _) = cell_as_atom_cell!(self)
- .get_name_and_arity();
+ let (name, _) = cell_as_atom_cell!(self).get_name_and_arity();
f.debug_struct("HeapCellValue")
.field("tag", &HeapCellValueTag::PStr)
.field("f", &self.f())
.finish()
}
- tag => {
- f.debug_struct("HeapCellValue")
- .field("tag", &tag)
- .field("value", &self.get_value())
- .field("m", &self.get_mark_bit())
- .field("f", &self.get_forwarding_bit())
- .finish()
- }
+ tag => f
+ .debug_struct("HeapCellValue")
+ .field("tag", &tag)
+ .field("value", &self.get_value())
+ .field("m", &self.get_mark_bit())
+ .field("f", &self.get_forwarding_bit())
+ .finish(),
}
}
}
impl From<F64Ptr> for HeapCellValue {
#[inline]
fn from(f64_ptr: F64Ptr) -> HeapCellValue {
- HeapCellValue::build_with(
- HeapCellValueTag::F64,
- f64_ptr.as_offset().to_u64(),
- )
+ HeapCellValue::build_with(HeapCellValueTag::F64, f64_ptr.as_offset().to_u64())
}
}
#[inline]
pub fn is_ref(self) -> bool {
match self.get_tag() {
- HeapCellValueTag::Str | HeapCellValueTag::Lis | HeapCellValueTag::Var |
- HeapCellValueTag::StackVar | HeapCellValueTag::AttrVar | HeapCellValueTag::PStrLoc |
- HeapCellValueTag::PStrOffset => true,
+ HeapCellValueTag::Str
+ | HeapCellValueTag::Lis
+ | HeapCellValueTag::Var
+ | HeapCellValueTag::StackVar
+ | HeapCellValueTag::AttrVar
+ | HeapCellValueTag::PStrLoc
+ | HeapCellValueTag::PStrOffset => true,
_ => false,
}
}
#[inline]
pub fn is_constant(self) -> bool {
match self.get_tag() {
- HeapCellValueTag::Cons | HeapCellValueTag::F64 | HeapCellValueTag::Fixnum |
- HeapCellValueTag::Char | HeapCellValueTag::CStr => {
- true
- }
- HeapCellValueTag::Atom => {
- cell_as_atom_cell!(self).get_arity() == 0
- }
- _ => {
- false
- }
+ HeapCellValueTag::Cons
+ | HeapCellValueTag::F64
+ | HeapCellValueTag::Fixnum
+ | HeapCellValueTag::Char
+ | HeapCellValueTag::CStr => true,
+ HeapCellValueTag::Atom => cell_as_atom_cell!(self).get_arity() == 0,
+ _ => false,
}
}
HeapCellValueTag::Str => {
cell_as_atom_cell!(heap[self.get_value() as usize]).get_arity() > 0
}
- HeapCellValueTag::Lis |
- HeapCellValueTag::CStr |
- HeapCellValueTag::PStr |
- HeapCellValueTag::PStrLoc |
- HeapCellValueTag::PStrOffset => {
- true
- }
- HeapCellValueTag::Atom => {
- cell_as_atom_cell!(self).get_arity() > 0
- }
- _ => { false }
+ HeapCellValueTag::Lis
+ | HeapCellValueTag::CStr
+ | HeapCellValueTag::PStr
+ | HeapCellValueTag::PStrLoc
+ | HeapCellValueTag::PStrOffset => true,
+ HeapCellValueTag::Atom => cell_as_atom_cell!(self).get_arity() > 0,
+ _ => false,
}
}
#[inline]
pub fn to_pstr(self) -> Option<PartialString> {
match self.tag() {
- HeapCellValueTag::PStr => {
- Some(PartialString::from(Atom::from(self.val() << 3)))
- }
+ HeapCellValueTag::PStr => Some(PartialString::from(Atom::from(self.val() << 3))),
_ => None,
}
}
}
}
- #[cfg(target_pointer_width="32")]
+ #[cfg(target_pointer_width = "32")]
#[inline]
pub fn from_raw_ptr_bytes(ptr_bytes: [u8; 4]) -> Self {
- HeapCellValue::from_bytes([ptr_bytes[0], ptr_bytes[1], ptr_bytes[2], ptr_bytes[3], 0, 0, 0, 0])
- }
- #[cfg(target_pointer_width="64")]
+ HeapCellValue::from_bytes([
+ ptr_bytes[0],
+ ptr_bytes[1],
+ ptr_bytes[2],
+ ptr_bytes[3],
+ 0,
+ 0,
+ 0,
+ 0,
+ ])
+ }
+ #[cfg(target_pointer_width = "64")]
#[inline]
pub fn from_raw_ptr_bytes(ptr_bytes: [u8; 8]) -> Self {
HeapCellValue::from_bytes(ptr_bytes)
}
#[inline]
- #[cfg(target_pointer_width="32")]
+ #[cfg(target_pointer_width = "32")]
pub fn to_raw_ptr_bytes(self) -> [u8; 4] {
let bytes = self.into_bytes();
[bytes[0], bytes[1], bytes[2], bytes[3]]
}
#[inline]
- #[cfg(target_pointer_width="64")]
+ #[cfg(target_pointer_width = "64")]
pub fn to_raw_ptr_bytes(self) -> [u8; 8] {
self.into_bytes()
}
#[inline]
pub fn to_untyped_arena_ptr(self) -> Option<UntypedArenaPtr> {
match self.get_tag() {
- HeapCellValueTag::Cons => Some(UntypedArenaPtr::from_bytes(self.to_untyped_arena_ptr_bytes())),
+ HeapCellValueTag::Cons => Some(UntypedArenaPtr::from_bytes(
+ self.to_untyped_arena_ptr_bytes(),
+ )),
_ => None,
}
}
pub fn get_forwarding_bit(self) -> bool {
match self.get_tag() {
HeapCellValueTag::Cons => ConsPtr::from_bytes(self.into_bytes()).f(),
- _ => self.f()
+ _ => self.f(),
}
}
#[inline(always)]
pub fn get_mark_bit(self) -> bool {
match self.get_tag() {
- HeapCellValueTag::Cons => {
- ConsPtr::from_bytes(self.into_bytes()).m()
- }
+ HeapCellValueTag::Cons => ConsPtr::from_bytes(self.into_bytes()).m(),
_ => self.m(),
}
}
Some(TermOrderCategory::Variable)
}
HeapCellValueTag::Char => Some(TermOrderCategory::Atom),
- HeapCellValueTag::Atom => {
- Some(if cell_as_atom_cell!(self).get_arity() > 0 {
- TermOrderCategory::Compound
- } else {
- TermOrderCategory::Atom
- })
- }
- HeapCellValueTag::Lis | HeapCellValueTag::PStrLoc |
- HeapCellValueTag::CStr => {
+ HeapCellValueTag::Atom => Some(if cell_as_atom_cell!(self).get_arity() > 0 {
+ TermOrderCategory::Compound
+ } else {
+ TermOrderCategory::Atom
+ }),
+ HeapCellValueTag::Lis | HeapCellValueTag::PStrLoc | HeapCellValueTag::CStr => {
Some(TermOrderCategory::Compound)
}
HeapCellValueTag::Str => {
Some(TermOrderCategory::Compound)
}
}
- _ => {
- None
- }
+ _ => None,
},
}
}
#[repr(u64)]
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub struct UntypedArenaPtr {
- #[allow(unused)] ptr: B61,
+ #[allow(unused)]
+ ptr: B61,
m: bool,
- #[allow(unused)] padding: B2,
+ #[allow(unused)]
+ padding: B2,
}
impl UntypedArenaPtr {
#[inline(always)]
pub fn build_with(ptr: usize) -> Self {
- UntypedArenaPtr::new()
- .with_ptr(ptr as u64)
+ UntypedArenaPtr::new().with_ptr(ptr as u64)
}
}
self.set_m(m);
}
- #[cfg(target_pointer_width="32")]
+ #[cfg(target_pointer_width = "32")]
#[inline]
pub fn get_ptr(self) -> *const u8 {
let bytes = self.into_bytes();
unsafe { mem::transmute(raw_ptr_bytes) }
}
- #[cfg(target_pointer_width="64")]
+ #[cfg(target_pointer_width = "64")]
#[inline]
pub fn get_ptr(self) -> *const u8 {
- self.ptr() as *const u8
+ self.ptr() as *const u8
}
#[inline]
fn add(self, rhs: usize) -> Self::Output {
match self.get_tag() {
- tag @ HeapCellValueTag::Str |
- tag @ HeapCellValueTag::Lis |
- tag @ HeapCellValueTag::PStrOffset |
- tag @ HeapCellValueTag::PStrLoc |
- tag @ HeapCellValueTag::Var |
- tag @ HeapCellValueTag::AttrVar => {
+ tag @ HeapCellValueTag::Str
+ | tag @ HeapCellValueTag::Lis
+ | tag @ HeapCellValueTag::PStrOffset
+ | tag @ HeapCellValueTag::PStrLoc
+ | tag @ HeapCellValueTag::Var
+ | tag @ HeapCellValueTag::AttrVar => {
HeapCellValue::build_with(tag, (self.get_value() as usize + rhs) as u64)
}
- _ => {
- self
- }
+ _ => self,
}
}
}
fn sub(self, rhs: usize) -> Self::Output {
match self.get_tag() {
- tag @ HeapCellValueTag::Str |
- tag @ HeapCellValueTag::Lis |
- tag @ HeapCellValueTag::PStrOffset |
- tag @ HeapCellValueTag::PStrLoc |
- tag @ HeapCellValueTag::Var |
- tag @ HeapCellValueTag::AttrVar => {
+ tag @ HeapCellValueTag::Str
+ | tag @ HeapCellValueTag::Lis
+ | tag @ HeapCellValueTag::PStrOffset
+ | tag @ HeapCellValueTag::PStrLoc
+ | tag @ HeapCellValueTag::Var
+ | tag @ HeapCellValueTag::AttrVar => {
HeapCellValue::build_with(tag, (self.get_value() as usize - rhs) as u64)
}
- _ => {
- self
- }
+ _ => self,
}
}
}
fn sub(self, rhs: i64) -> Self::Output {
if rhs < 0 {
match self.get_tag() {
- tag @ HeapCellValueTag::Str |
- tag @ HeapCellValueTag::Lis |
- tag @ HeapCellValueTag::PStrOffset |
- tag @ HeapCellValueTag::PStrLoc |
- tag @ HeapCellValueTag::Var |
- tag @ HeapCellValueTag::AttrVar => {
+ tag @ HeapCellValueTag::Str
+ | tag @ HeapCellValueTag::Lis
+ | tag @ HeapCellValueTag::PStrOffset
+ | tag @ HeapCellValueTag::PStrLoc
+ | tag @ HeapCellValueTag::Var
+ | tag @ HeapCellValueTag::AttrVar => {
HeapCellValue::build_with(tag, self.get_value() + rhs.abs() as u64)
}
- _ => {
- self
- }
+ _ => self,
}
} else {
self.sub(rhs as usize)
}
}
}
-
#[derive(Debug, Clone, Copy)]
pub enum PermVarAllocation {
- Done { shallow_safety: VarSafetyStatus,
- deep_safety: VarSafetyStatus },
+ Done {
+ shallow_safety: VarSafetyStatus,
+ deep_safety: VarSafetyStatus,
+ },
Pending,
}
#[derive(Debug, Clone)]
pub enum VarAlloc {
- Temp { term_loc: GenContext,
- temp_reg: usize,
- temp_var_data: TempVarData,
- safety: VarSafetyStatus,
- to_perm_var_num: Option<usize> },
+ Temp {
+ term_loc: GenContext,
+ temp_reg: usize,
+ temp_var_data: TempVarData,
+ safety: VarSafetyStatus,
+ to_perm_var_num: Option<usize>,
+ },
Perm(usize, PermVarAllocation), // stack offset, allocation info
}
pub(crate) fn set_register(&mut self, reg_num: usize) {
match self {
VarAlloc::Perm(ref mut p, _) => *p = reg_num,
- VarAlloc::Temp { ref mut temp_reg, .. } => *temp_reg = reg_num,
+ VarAlloc::Temp {
+ ref mut temp_reg, ..
+ } => *temp_reg = reg_num,
};
}
}
// Compute the conflict set of u.
// 1.
- let mut use_sets: IndexMap<usize, IndexSet<(GenContext, usize), FxBuildHasher>> = IndexMap::new();
+ let mut use_sets: IndexMap<usize, IndexSet<(GenContext, usize), FxBuildHasher>> =
+ IndexMap::new();
for (var_gen_index, record) in self.0.iter_mut().enumerate() {
match &mut record.allocation {
use_sets.insert(var_gen_index, use_set);
}
- _ => {
- }
+ _ => {}
}
}
if let GenContext::Last(cn_u) = term_loc {
for (var_gen_index, record) in self.0.iter_mut().enumerate() {
match &mut record.allocation {
- VarAlloc::Temp { term_loc, temp_var_data, .. } => {
+ VarAlloc::Temp {
+ term_loc,
+ temp_var_data,
+ ..
+ } => {
if cn_u == term_loc.chunk_num() && u != var_gen_index {
if !temp_var_data.uses_reg(reg) {
temp_var_data.no_use_set.insert(reg);
}
// 3.
- if let VarAlloc::Temp{ temp_var_data, .. } = &mut self[u].allocation {
+ if let VarAlloc::Temp { temp_var_data, .. } = &mut self[u].allocation {
temp_var_data.use_set = use_set;
temp_var_data.populate_conflict_set();
}
#[serial]
#[test]
fn iso_conformity_tests() {
- load_module_test(
- "tests-pl/iso-conformity-tests.pl",
- "All tests passed",
- );
+ load_module_test("tests-pl/iso-conformity-tests.pl", "All tests passed");
}