Merge branch 'master' into library-use-case

# Conflicts:
#	Cargo.toml
#	src/machine/mock_wam.rs
#	src/machine/mod.rs
This commit is contained in:
Nicolas Luck
2023-08-30 18:12:26 +02:00
27 changed files with 927 additions and 594 deletions

View File

@@ -16,12 +16,13 @@ jobs:
strategy: strategy:
matrix: matrix:
include: include:
- { os: windows-latest, rust-version: stable, shell: 'msys2 {0}' } - { os: windows-latest, rust-version: stable, shell: 'msys2 {0}', target: 'x86_64-pc-windows-gnu'}
- { os: macos-11, rust-version: stable, shell: bash } - { os: macos-11, rust-version: stable, shell: bash, target: 'x86_64-apple-darwin' }
- { os: ubuntu-20.04, rust-version: stable, shell: bash, extra: true } - { os: ubuntu-20.04, rust-version: stable, shell: bash, extra: true, target: 'x86_64-unknown-linux-gnu' }
- { os: ubuntu-20.04, rust-version: 1.65, shell: bash } - { os: ubuntu-20.04, rust-version: stable, shell: bash, target: 'i686-unknown-linux-gnu' }
- { os: ubuntu-20.04, rust-version: beta, shell: bash } - { os: ubuntu-20.04, rust-version: 1.65, shell: bash, target: 'x86_64-unknown-linux-gnu'}
- { os: ubuntu-20.04, rust-version: nightly, shell: bash } - { os: ubuntu-20.04, rust-version: beta, shell: bash, target: 'x86_64-unknown-linux-gnu'}
- { os: ubuntu-20.04, rust-version: nightly, shell: bash, target: 'x86_64-unknown-linux-gnu'}
defaults: defaults:
run: run:
shell: ${{ matrix.shell }} shell: ${{ matrix.shell }}
@@ -32,7 +33,11 @@ jobs:
id: toolchain id: toolchain
with: with:
toolchain: ${{ matrix.rust-version }} toolchain: ${{ matrix.rust-version }}
targets: ${{ matrix.target }}
components: clippy, rustfmt components: clippy, rustfmt
- name: Install i686 dependencies
if: "contains(matrix.target,'i686')"
run: sudo dpkg --add-architecture i386 && sudo apt-get update && sudo apt-get install libssl-dev:i386 gcc-multilib clang -y && echo "CC=clang" >> $GITHUB_ENV && echo "PKG_CONFIG_SYSROOT_DIR=/" >> $GITHUB_ENV
- uses: msys2/setup-msys2@v2 - uses: msys2/setup-msys2@v2
if: contains(matrix.os,'windows') if: contains(matrix.os,'windows')
with: with:
@@ -48,14 +53,14 @@ jobs:
~/.cargo/registry/cache/ ~/.cargo/registry/cache/
~/.cargo/git/db/ ~/.cargo/git/db/
target/ target/
key: ${{ matrix.os }}_rustc-${{ steps.toolchain.outputs.cachekey }}_cargo-${{ hashFiles('**/Cargo.lock') }} key: ${{ matrix.os }}_${{ matrix.target }}_rustc-${{ steps.toolchain.outputs.cachekey }}_cargo-${{ hashFiles('**/Cargo.lock') }}
# Build and test. # Build and test.
- name: Build library - name: Build library
run: cargo rustc --verbose --lib -- -D warnings run: cargo rustc --target ${{ matrix.target }} --verbose --lib -- -D warnings
- name: Test - name: Test
if: "!matrix.extra" if: "!matrix.extra"
run: cargo test --all --verbose run: cargo test --target ${{ matrix.target }} --all --verbose
# Extra steps only run once to avoid duplication, when matrix.extra is true # Extra steps only run once to avoid duplication, when matrix.extra is true
- name: Test and report - name: Test and report
@@ -90,14 +95,14 @@ jobs:
- name: Build release binary - name: Build release binary
if: contains(matrix.rust-version,'stable') if: contains(matrix.rust-version,'stable')
run: | run: |
cargo rustc --verbose --bin scryer-prolog --release -- -D warnings cargo rustc --target ${{ matrix.target }} --verbose --bin scryer-prolog --release -- -D warnings
echo "$PWD/target/release" >> $GITHUB_PATH echo "$PWD/target/release" >> $GITHUB_PATH
- name: Publish release binary artifact - name: Publish release binary artifact
if: contains(matrix.rust-version,'stable') if: contains(matrix.rust-version,'stable')
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v3
with: with:
path: target/release/scryer-prolog* path: target/${{ matrix.target }}/release/scryer-prolog*
name: scryer-prolog_${{ matrix.os }} name: scryer-prolog_${{ matrix.os }}_${{ matrix.target }}
logtalk-test: logtalk-test:
runs-on: ubuntu-20.04 runs-on: ubuntu-20.04
@@ -106,7 +111,7 @@ jobs:
# Download prebuilt ubuntu binary from build-test job, setup logtalk # Download prebuilt ubuntu binary from build-test job, setup logtalk
- uses: actions/download-artifact@v3 - uses: actions/download-artifact@v3
with: with:
name: scryer-prolog_ubuntu-20.04 name: scryer-prolog_ubuntu-20.04_x86_64-unknown-linux-gnu
- run: | - run: |
chmod +x scryer-prolog chmod +x scryer-prolog
echo "$PWD" >> "$GITHUB_PATH" echo "$PWD" >> "$GITHUB_PATH"
@@ -154,9 +159,9 @@ jobs:
- uses: actions/download-artifact@v3 - uses: actions/download-artifact@v3
- name: Zip binaries for release - name: Zip binaries for release
run: | run: |
zip scryer-prolog_macos-11.zip ./scryer-prolog_macos-11/scryer-prolog zip scryer-prolog_macos-11.zip ./scryer-prolog_macos-11_x86_64-apple-darwin/scryer-prolog
zip scryer-prolog_ubuntu-20.04.zip ./scryer-prolog_ubuntu-20.04/scryer-prolog zip scryer-prolog_ubuntu-20.04.zip ./scryer-prolog_ubuntu-20.04_x86_64-unknown-linux-gnu/scryer-prolog
zip scryer-prolog_windows-latest.zip ./scryer-prolog_windows-latest/scryer-prolog.exe zip scryer-prolog_windows-latest.zip ./scryer-prolog_windows-latest_x86_64-pc-windows-gnu/scryer-prolog.exe
- name: Release - name: Release
uses: softprops/action-gh-release@v1 uses: softprops/action-gh-release@v1
with: with:

570
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "scryer-prolog" name = "scryer-prolog"
version = "0.9.1" version = "0.9.2"
authors = ["Mark Thom <markjordanthom@gmail.com>"] authors = ["Mark Thom <markjordanthom@gmail.com>"]
edition = "2021" edition = "2021"
description = "A modern Prolog implementation written mostly in Rust." description = "A modern Prolog implementation written mostly in Rust."
@@ -14,6 +14,12 @@ rust-version = "1.63"
[features] [features]
multi_thread = [] multi_thread = []
default = ["ffi", "repl", "hostname", "tls", "http"]
ffi = ["dep:libffi"]
repl = ["dep:crossterm", "dep:ctrlc", "dep:rustyline"]
hostname = ["dep:hostname"]
tls = ["dep:native-tls"]
http = ["dep:hyper", "dep:reqwest"]
[build-dependencies] [build-dependencies]
indexmap = "1.0.2" indexmap = "1.0.2"
@@ -30,50 +36,59 @@ walkdir = "2"
bit-set = "0.5.3" bit-set = "0.5.3"
bitvec = "1" bitvec = "1"
cpu-time = "1.0.0" cpu-time = "1.0.0"
crossterm = "0.20.0"
dirs-next = "2.0.0" dirs-next = "2.0.0"
divrem = "0.1.0" divrem = "0.1.0"
fxhash = "0.2.1" fxhash = "0.2.1"
git-version = "0.3.4" git-version = "0.3.4"
hostname = "0.3.1"
indexmap = "1.0.2" indexmap = "1.0.2"
lazy_static = "1.4.0" lazy_static = "1.4.0"
lexical = "5.2.2" lexical = "5.2.2"
libc = "0.2.62" libc = "0.2.62"
modular-bitfield = "0.11.2" modular-bitfield = "0.11.2"
ctrlc = "3.2.2"
ordered-float = "2.6.0" ordered-float = "2.6.0"
phf = { version = "0.9", features = ["macros"] } phf = { version = "0.9", features = ["macros"] }
ref_thread_local = "0.0.0" ref_thread_local = "0.0.0"
rustyline = "12.0.0"
ring = "0.16.13"
ripemd160 = "0.8.0" ripemd160 = "0.8.0"
sha3 = "0.8.2" sha3 = "0.8.2"
blake2 = "0.8.1" blake2 = "0.8.1"
crrl = "0.2.0" crrl = "0.6.0"
native-tls = "0.2.4"
chrono = "0.4.11" chrono = "0.4.11"
select = "0.6.0" select = "0.6.0"
roxmltree = "0.11.0" roxmltree = "0.11.0"
base64 = "0.12.3" base64 = "0.12.3"
smallvec = "1.8.0" smallvec = "1.8.0"
sodiumoxide = "0.2.6"
static_assertions = "1.1.0" static_assertions = "1.1.0"
ryu = "1.0.9" ryu = "1.0.9"
hyper = { version = "1.0.0-rc.4", features = ["full"] }
hyper-util = { git = "https://github.com/hyperium/hyper-util.git" }
tokio = { version = "1.28.2", features = ["full"] }
futures = "0.3" futures = "0.3"
regex = "1.9.1" regex = "1.9.1"
libloading = "0.7" libloading = "0.7"
derive_deref = "1.1.1" derive_deref = "1.1.1"
http-body-util = "0.1.0-rc.2" http-body-util = "0.1.0-rc.2"
bytes = "1" bytes = "1"
reqwest = { version = "0.11.18", features = ["blocking"] } dashu = { git = "https://github.com/coasys/dashu.git", version = "0.3.1" }
dashu = { git = "https://github.com/coasys/dashu.git" }
libffi = { git = "https://github.com/coasys/libffi-rs.git", branch = "windows-space" }
rand = "0.8.5" rand = "0.8.5"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
libffi = { git = "https://github.com/coasys/libffi-rs.git", branch = "windows-space", optional = true, version = "3.2.0" }
hostname = { version = "0.3.1", optional = true }
crossterm = { version = "0.20.0", optional = true }
ctrlc = { version = "3.2.2", optional = true }
rustyline = { version = "12.0.0", optional = true }
native-tls = { version = "0.2.4", optional = true }
hyper = { version = "=1.0.0-rc.3", features = ["full"], optional = true }
reqwest = { version = "0.11.18", features = ["blocking"], optional = true }
tokio = { version = "1.28.2", features = ["full"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
getrandom = { version = "0.2.10", features = ["js"] }
tokio = { version = "1.28.2", features = ["sync", "macros", "io-util", "rt", "time"] }
[target.'cfg(target_os = "wasi")'.dependencies]
ring-wasi = { version = "0.16.25" }
[target.'cfg(not(target_os = "wasi"))'.dependencies]
ring = { version = "0.16.13" }
[dev-dependencies] [dev-dependencies]
assert_cmd = "1.0.3" assert_cmd = "1.0.3"
predicates-core = "1.0.2" predicates-core = "1.0.2"

View File

@@ -99,6 +99,8 @@ enum BuiltInClauseType {
Ground, Ground,
#[strum_discriminants(strum(props(Arity = "2", Name = "is")))] #[strum_discriminants(strum(props(Arity = "2", Name = "is")))]
Is(RegType, ArithmeticTerm), Is(RegType, ArithmeticTerm),
#[strum_discriminants(strum(props(Arity = "1", Name = "$get_number")))]
GetNumber(ArithmeticTerm),
#[strum_discriminants(strum(props(Arity = "2", Name = "keysort")))] #[strum_discriminants(strum(props(Arity = "2", Name = "keysort")))]
KeySort, KeySort,
#[strum_discriminants(strum(props(Arity = "2", Name = "sort")))] #[strum_discriminants(strum(props(Arity = "2", Name = "sort")))]
@@ -1553,7 +1555,8 @@ fn generate_instruction_preface() -> TokenStream {
&Instruction::CallFunctor | &Instruction::CallFunctor |
&Instruction::CallGround | &Instruction::CallGround |
&Instruction::CallKeySort | &Instruction::CallKeySort |
&Instruction::CallSort => { &Instruction::CallSort |
&Instruction::CallGetNumber(_) => {
let (name, arity) = self.to_name_and_arity(); let (name, arity) = self.to_name_and_arity();
functor!(atom!("call"), [atom(name), fixnum(arity)]) functor!(atom!("call"), [atom(name), fixnum(arity)])
} }
@@ -1578,7 +1581,8 @@ fn generate_instruction_preface() -> TokenStream {
&Instruction::ExecuteGround | &Instruction::ExecuteGround |
&Instruction::ExecuteIs(..) | &Instruction::ExecuteIs(..) |
&Instruction::ExecuteKeySort | &Instruction::ExecuteKeySort |
&Instruction::ExecuteSort => { &Instruction::ExecuteSort |
&Instruction::ExecuteGetNumber(_) => {
let (name, arity) = self.to_name_and_arity(); let (name, arity) = self.to_name_and_arity();
functor!(atom!("execute"), [atom(name), fixnum(arity)]) functor!(atom!("execute"), [atom(name), fixnum(arity)])
} }
@@ -1603,7 +1607,8 @@ fn generate_instruction_preface() -> TokenStream {
&Instruction::DefaultCallGround | &Instruction::DefaultCallGround |
&Instruction::DefaultCallIs(..) | &Instruction::DefaultCallIs(..) |
&Instruction::DefaultCallKeySort | &Instruction::DefaultCallKeySort |
&Instruction::DefaultCallSort => { &Instruction::DefaultCallSort |
&Instruction::DefaultCallGetNumber(_) => {
let (name, arity) = self.to_name_and_arity(); let (name, arity) = self.to_name_and_arity();
functor!(atom!("call_default"), [atom(name), fixnum(arity)]) functor!(atom!("call_default"), [atom(name), fixnum(arity)])
} }
@@ -1628,7 +1633,8 @@ fn generate_instruction_preface() -> TokenStream {
&Instruction::DefaultExecuteGround | &Instruction::DefaultExecuteGround |
&Instruction::DefaultExecuteIs(..) | &Instruction::DefaultExecuteIs(..) |
&Instruction::DefaultExecuteKeySort | &Instruction::DefaultExecuteKeySort |
&Instruction::DefaultExecuteSort => { &Instruction::DefaultExecuteSort |
&Instruction::DefaultExecuteGetNumber(_) => {
let (name, arity) = self.to_name_and_arity(); let (name, arity) = self.to_name_and_arity();
functor!(atom!("execute_default"), [atom(name), fixnum(arity)]) functor!(atom!("execute_default"), [atom(name), fixnum(arity)])
} }

View File

@@ -150,7 +150,7 @@ pub fn index_static_strings(instruction_rs_path: &std::path::Path) -> TokenStrea
Err(_) => {} Err(_) => {}
} }
let indices = (0..visitor.static_strs.len()).map(|i| i << 3); let indices = (0..visitor.static_strs.len()).map(|i| (i << 3) as u64);
let indices_iter = indices.clone(); let indices_iter = indices.clone();
let static_strs_len = visitor.static_strs.len(); let static_strs_len = visitor.static_strs.len();

View File

@@ -1,3 +1,4 @@
#[cfg(feature = "http")]
use crate::http::{HttpListener, HttpResponse}; use crate::http::{HttpListener, HttpResponse};
use crate::machine::loader::LiveLoadState; use crate::machine::loader::LiveLoadState;
use crate::machine::machine_indices::*; use crate::machine::machine_indices::*;
@@ -306,12 +307,16 @@ pub trait ArenaAllocated: Sized {
fn copy_to_arena(self, dst: *mut Self) -> Self::PtrToAllocated; fn copy_to_arena(self, dst: *mut Self) -> Self::PtrToAllocated;
fn header_offset_from_payload() -> usize { fn header_offset_from_payload() -> usize {
mem::size_of::<*const ArenaHeader>() mem::size_of::<ArenaHeader>()
} }
unsafe fn alloc(arena: &mut Arena, value: Self) -> Self::PtrToAllocated { unsafe fn alloc(arena: &mut Arena, value: Self) -> Self::PtrToAllocated {
let size = value.size() + mem::size_of::<AllocSlab>(); let size = value.size() + mem::size_of::<AllocSlab>();
#[cfg(target_pointer_width="32")]
let align = mem::align_of::<AllocSlab>() * 2;
#[cfg(target_pointer_width="64")]
let align = mem::align_of::<AllocSlab>(); let align = mem::align_of::<AllocSlab>();
let layout = alloc::Layout::from_size_align_unchecked(size, align); let layout = alloc::Layout::from_size_align_unchecked(size, align);
@@ -566,6 +571,7 @@ impl ArenaAllocated for TcpListener {
} }
} }
#[cfg(feature = "http")]
impl ArenaAllocated for HttpListener { impl ArenaAllocated for HttpListener {
type PtrToAllocated = TypedArenaPtr<HttpListener>; type PtrToAllocated = TypedArenaPtr<HttpListener>;
@@ -588,6 +594,7 @@ impl ArenaAllocated for HttpListener {
} }
} }
#[cfg(feature = "http")]
impl ArenaAllocated for HttpResponse { impl ArenaAllocated for HttpResponse {
type PtrToAllocated = TypedArenaPtr<HttpResponse>; type PtrToAllocated = TypedArenaPtr<HttpResponse>;
@@ -653,9 +660,12 @@ impl ArenaAllocated for IndexPtr {
} }
} }
#[repr(C)]
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
struct AllocSlab { struct AllocSlab {
next: *mut AllocSlab, next: *mut AllocSlab,
#[cfg(target_pointer_width="32")]
_padding: u32,
header: ArenaHeader, header: ArenaHeader,
} }
@@ -695,12 +705,15 @@ unsafe fn drop_slab_in_place(value: &mut AllocSlab) {
ptr::drop_in_place(value.payload_offset::<StreamLayout<CharReader<NamedTcpStream>>>()); ptr::drop_in_place(value.payload_offset::<StreamLayout<CharReader<NamedTcpStream>>>());
} }
ArenaHeaderTag::NamedTlsStream => { ArenaHeaderTag::NamedTlsStream => {
#[cfg(feature = "tls")]
ptr::drop_in_place(value.payload_offset::<StreamLayout<CharReader<NamedTlsStream>>>()); ptr::drop_in_place(value.payload_offset::<StreamLayout<CharReader<NamedTlsStream>>>());
} }
ArenaHeaderTag::HttpReadStream => { ArenaHeaderTag::HttpReadStream => {
#[cfg(feature = "http")]
ptr::drop_in_place(value.payload_offset::<StreamLayout<CharReader<HttpReadStream>>>()); 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 => { ArenaHeaderTag::ReadlineStream => {
@@ -724,9 +737,11 @@ unsafe fn drop_slab_in_place(value: &mut AllocSlab) {
ptr::drop_in_place(value.payload_offset::<TcpListener>()); ptr::drop_in_place(value.payload_offset::<TcpListener>());
} }
ArenaHeaderTag::HttpListener => { ArenaHeaderTag::HttpListener => {
#[cfg(feature = "http")]
ptr::drop_in_place(value.payload_offset::<HttpListener>()); ptr::drop_in_place(value.payload_offset::<HttpListener>());
} }
ArenaHeaderTag::HttpResponse => { ArenaHeaderTag::HttpResponse => {
#[cfg(feature = "http")]
ptr::drop_in_place(value.payload_offset::<HttpResponse>()); ptr::drop_in_place(value.payload_offset::<HttpResponse>());
} }
ArenaHeaderTag::StandardOutputStream => { ArenaHeaderTag::StandardOutputStream => {
@@ -819,6 +834,12 @@ mod tests {
#[test] #[test]
fn heap_cell_value_const_cast() { fn heap_cell_value_const_cast() {
let mut wam = MockWAM::new(); let mut wam = MockWAM::new();
#[cfg(target_pointer_width="32")]
let const_value = HeapCellValue::from(ConsPtr::build_with(
0x0000_0431 as *const _,
ConsPtrMaskTag::Cons,
));
#[cfg(target_pointer_width="64")]
let const_value = HeapCellValue::from(ConsPtr::build_with( let const_value = HeapCellValue::from(ConsPtr::build_with(
0x0000_5555_ff00_0431 as *const _, 0x0000_5555_ff00_0431 as *const _,
ConsPtrMaskTag::Cons, ConsPtrMaskTag::Cons,
@@ -826,7 +847,7 @@ mod tests {
match const_value.to_untyped_arena_ptr() { match const_value.to_untyped_arena_ptr() {
Some(arena_ptr) => { Some(arena_ptr) => {
assert_eq!(arena_ptr.into_bytes(), const_value.into_bytes()); assert_eq!(arena_ptr.into_bytes(), const_value.to_untyped_arena_ptr_bytes());
} }
None => { None => {
assert!(false); assert!(false);
@@ -839,7 +860,7 @@ mod tests {
match stream_cell.to_untyped_arena_ptr() { match stream_cell.to_untyped_arena_ptr() {
Some(arena_ptr) => { Some(arena_ptr) => {
assert_eq!(arena_ptr.into_bytes(), stream_cell.into_bytes()); assert_eq!(arena_ptr.into_bytes(), stream_cell.to_untyped_arena_ptr_bytes());
} }
None => { None => {
assert!(false); assert!(false);
@@ -1093,7 +1114,7 @@ mod tests {
read_heap_cell!(cell, read_heap_cell!(cell,
(HeapCellValueTag::Atom, (el, _arity)) => { (HeapCellValueTag::Atom, (el, _arity)) => {
assert_eq!(el.flat_index() as usize, empty_list_as_cell!().get_value()); assert_eq!(el.flat_index(), empty_list_as_cell!().get_value());
assert_eq!(el.as_str(), "[]"); assert_eq!(el.as_str(), "[]");
} }
_ => { unreachable!() } _ => { unreachable!() }

View File

@@ -16,7 +16,7 @@ use modular_bitfield::prelude::*;
#[derive(Copy, Clone, Debug, PartialEq, Eq)] #[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Atom { pub struct Atom {
pub index: usize, pub index: u64,
} }
const_assert!(mem::size_of::<Atom>() == 8); const_assert!(mem::size_of::<Atom>() == 8);
@@ -156,7 +156,7 @@ impl Atom {
#[inline(always)] #[inline(always)]
pub fn is_static(self) -> bool { pub fn is_static(self) -> bool {
self.index < STRINGS.len() << 3 (self.index as usize) < STRINGS.len() << 3
} }
#[inline(always)] #[inline(always)]
@@ -164,19 +164,19 @@ impl Atom {
if self.is_static() { if self.is_static() {
ptr::null() ptr::null()
} else { } else {
(get_atom_tbl_buf_base() as usize + self.index - (STRINGS.len() << 3)) as *const u8 (get_atom_tbl_buf_base() as usize + (self.index as usize) - (STRINGS.len() << 3)) as *const u8
} }
} }
#[inline(always)] #[inline(always)]
pub fn from(index: usize) -> Self { pub fn from(index: u64) -> Self {
Self { index } Self { index }
} }
#[inline(always)] #[inline(always)]
pub fn len(self) -> usize { pub fn len(self) -> usize {
if self.is_static() { if self.is_static() {
STRINGS[self.index >> 3].len() STRINGS[(self.index >> 3) as usize].len()
} else { } else {
unsafe { ptr::read(self.as_ptr() as *const AtomHeader).len() as _ } unsafe { ptr::read(self.as_ptr() as *const AtomHeader).len() as _ }
} }
@@ -208,7 +208,7 @@ impl Atom {
let ptr = self.as_ptr(); let ptr = self.as_ptr();
if ptr.is_null() { if ptr.is_null() {
return STRINGS[self.index >> 3]; return STRINGS[(self.index >> 3) as usize];
} }
let header = ptr::read::<AtomHeader>(ptr as *const _); let header = ptr::read::<AtomHeader>(ptr as *const _);
@@ -339,7 +339,7 @@ impl AtomTable {
write_to_ptr(string, len_ptr); write_to_ptr(string, len_ptr);
let atom = Atom { let atom = Atom {
index: (STRINGS.len() << 3) + len_ptr as usize - ptr_base, index: ((STRINGS.len() << 3) + len_ptr as usize - ptr_base) as u64,
}; };
self.table.insert(atom); self.table.insert(atom);
@@ -386,7 +386,7 @@ impl AtomCell {
#[inline] #[inline]
pub fn get_name(self) -> Atom { pub fn get_name(self) -> Atom {
Atom::from(self.get_index() << 3) Atom::from((self.get_index() as u64) << 3)
} }
#[inline] #[inline]
@@ -396,6 +396,6 @@ impl AtomCell {
#[inline] #[inline]
pub fn get_name_and_arity(self) -> (Atom, usize) { pub fn get_name_and_arity(self) -> (Atom, usize) {
(Atom::from(self.get_index() << 3), self.get_arity()) (Atom::from((self.get_index() as u64) << 3), self.get_arity())
} }
} }

View File

@@ -3,10 +3,18 @@ fn main() -> std::process::ExitCode {
use scryer_prolog::*; use scryer_prolog::*;
use scryer_prolog::atom_table::Atom; use scryer_prolog::atom_table::Atom;
#[cfg(feature = "repl")]
ctrlc::set_handler(move || { ctrlc::set_handler(move || {
scryer_prolog::machine::INTERRUPT.store(true, Ordering::Relaxed); scryer_prolog::machine::INTERRUPT.store(true, Ordering::Relaxed);
}).unwrap(); }).unwrap();
#[cfg(target_os = "wasi")]
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
#[cfg(not(target_os = "wasi"))]
let runtime = tokio::runtime::Builder::new_multi_thread() let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all() .enable_all()
.build() .build()

View File

@@ -804,17 +804,44 @@ impl<'b> CodeGenerator<'b> {
&Term::Var(ref vr, ref name) => { &Term::Var(ref vr, ref name) => {
let var_num = name.to_var_num().unwrap(); let var_num = name.to_var_num().unwrap();
self.marker.mark_var::<QueryInstruction>( if self.marker.var_data.records[var_num].num_occurrences > 1 {
var_num, self.marker.mark_var::<QueryInstruction>(
Level::Shallow, var_num,
vr, Level::Shallow,
term_loc, vr,
code, term_loc,
); code,
);
self.marker.mark_safe_var_unconditionally(var_num); self.marker.mark_safe_var_unconditionally(var_num);
compile_expr!(self, &terms[1], term_loc, code)
} else {
if let Term::Var(ref vr, ref var) = &terms[1] {
let var_num = var.to_var_num().unwrap();
compile_expr!(self, &terms[1], term_loc, code) // if var is an anonymous variable, insert
// is/2 call so that an instantiation error is
// thrown when the predicate is run.
if self.marker.var_data.records[var_num].num_occurrences > 1 {
self.marker.mark_var::<QueryInstruction>(
var_num,
Level::Shallow,
vr,
term_loc,
code,
);
self.marker.mark_safe_var_unconditionally(var_num);
let at = ArithmeticTerm::Reg(vr.get().norm());
self.add_call(code, instr!("$get_number", at), call_policy);
return Ok(());
}
}
compile_expr!(self, &terms[1], term_loc, code)
}
} }
&Term::Literal(_, c @ Literal::Integer(_) | &Term::Literal(_, c @ Literal::Integer(_) |
c @ Literal::Float(_) | c @ Literal::Float(_) |

View File

@@ -17,11 +17,13 @@ mod allocator;
mod arithmetic; mod arithmetic;
pub mod codegen; pub mod codegen;
mod debray_allocator; mod debray_allocator;
#[cfg(feature = "ffi")]
mod ffi; mod ffi;
mod variable_records; mod variable_records;
mod forms; mod forms;
mod heap_iter; mod heap_iter;
pub mod heap_print; pub mod heap_print;
#[cfg(feature = "http")]
mod http; mod http;
mod indexing; mod indexing;
#[macro_use] #[macro_use]
@@ -32,6 +34,7 @@ mod iterators;
pub mod machine; pub mod machine;
mod raw_block; mod raw_block;
pub mod read; pub mod read;
#[cfg(feature = "repl")]
mod repl_helper; mod repl_helper;
mod targets; mod targets;
pub mod types; pub mod types;

View File

@@ -119,7 +119,7 @@
:- use_module(library(iso_ext)). :- use_module(library(iso_ext)).
:- use_module(library(dcgs)). :- use_module(library(dcgs)).
:- use_module(library(terms)). :- use_module(library(terms)).
:- use_module(library(error), [domain_error/3, type_error/3]). :- use_module(library(error), [domain_error/3, type_error/3, can_be/2]).
:- use_module(library(si)). :- use_module(library(si)).
:- use_module(library(freeze)). :- use_module(library(freeze)).
:- use_module(library(arithmetic)). :- use_module(library(arithmetic)).
@@ -838,12 +838,12 @@ Using suitable labeling strategies, we can easily find solutions with
``` ```
?- n_queens(80, Qs), labeling([ff], Qs). ?- n_queens(80, Qs), labeling([ff], Qs).
Qs = [1,3,5,44,42,4,50,7,68,57,76,61,6,39,30,40,8,54,36,41,...] Qs = [1,3,5,44,42,4,50,7,68,57,76,61,6,39,30,40,8,54,36,41|...]
; ... . ; ... .
?- time((n_queens(90, Qs), labeling([ff], Qs))). ?- time((n_queens(90, Qs), labeling([ff], Qs))).
% CPU time: 31.351s % CPU time: 2.382s
Qs = [1,3,5,50,42,4,49,7,59,48,46,63,6,55,47,64,8,70,58,67,...] Qs = [1,3,5,50,42,4,49,7,59,48,46,63,6,55,47,64,8,70,58,67|...]
; ... . ; ... .
``` ```
@@ -1745,11 +1745,7 @@ clpz_in(V, D) :-
drep_to_domain(D, Dom), drep_to_domain(D, Dom),
domain(V, Dom). domain(V, Dom).
fd_variable(V) :- fd_variable(V) :- can_be(integer, V).
( var(V) -> true
; integer(V) -> true
; type_error(integer, V)
).
%% ins(+Vars, +Domain) %% ins(+Vars, +Domain)
% %
@@ -2219,14 +2215,14 @@ all_different(Ls) :-
fd_must_be_list(Ls, all_different(Ls)-1), fd_must_be_list(Ls, all_different(Ls)-1),
maplist(fd_variable, Ls), maplist(fd_variable, Ls),
Orig = original_goal(_, all_different(Ls)), Orig = original_goal(_, all_different(Ls)),
all_different(Ls, [], Orig), new_queue(Q0),
do_queue. phrase((all_different(Ls, [], Orig),do_queue), [Q0], _).
all_different([], _, _). all_different([], _, _) --> [].
all_different([X|Right], Left, Orig) :- all_different([X|Right], Left, Orig) -->
( var(X) -> ( { var(X) } ->
make_propagator(pdifferent(Left,Right,X,Orig), Prop), { make_propagator(pdifferent(Left,Right,X,Orig), Prop) },
init_propagator(X, Prop), init_propagator_([X], Prop),
trigger_prop(Prop) trigger_prop(Prop)
; exclude_fire(Left, Right, X) ; exclude_fire(Left, Right, X)
), ),
@@ -2250,7 +2246,8 @@ all_distinct(Ls) :-
maplist(fd_variable, Ls), maplist(fd_variable, Ls),
make_propagator(pdistinct(Ls), Prop), make_propagator(pdistinct(Ls), Prop),
new_queue(Q0), new_queue(Q0),
phrase((distinct_attach(Ls, Prop, []),trigger_prop(Prop),do_queue), [Q0], _). phrase((distinct_attach(Ls, Prop, []),trigger_prop(Prop),do_queue), [Q0], _),
variables_same_queue(Ls).
%% nvalue(?N, +Vars). %% nvalue(?N, +Vars).
% %
@@ -2639,22 +2636,28 @@ parse_goals([G|Gs]) --> parse_goal(G), parse_goals(Gs).
parse_goal(g(Goal)) --> [Goal]. parse_goal(g(Goal)) --> [Goal].
parse_goal(p(Prop)) --> parse_goal(p(Prop)) -->
[make_propagator(Prop, P)],
{ term_variables(Prop, Vs) }, { term_variables(Prop, Vs) },
parse_init(Vs, P), [make_propagator(Prop, P),
[trigger_once(P)]. new_queue(Q0),
phrase(init_propagator_(Vs, P), [Q0], [Q]),
variables_same_queue(Vs),
trigger_once_(P, Q)].
parse_init([], _) --> []. /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
parse_init([V|Vs], P) --> [init_propagator(V, P)], parse_init(Vs, P). ?- use_module(library(lists)),
use_module(library(format)),
%?- set_prolog_flag(answer_write_options, [portray(true)]), clpz:parse_clpz_clauses(Clauses),
% clpz:parse_clpz_clauses(Clauses), maplist(portray_clause, Clauses). maplist(portray_clause, Clauses).
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
trigger_once(Prop) :- trigger_once(Prop) :-
new_queue(Q), new_queue(Q),
trigger_once_(Prop, Q).
trigger_once_(Prop, Q) :-
phrase((trigger_prop(Prop),do_queue), [Q], _). phrase((trigger_prop(Prop),do_queue), [Q], _).
neq(A, B) :- propagator_init_trigger(pneq(A, B)). neq(A, B) :- propagator_init_trigger(pneq(A, B)).
@@ -2666,19 +2669,41 @@ propagator_init_trigger(P) -->
propagator_init_trigger(Vs, P) --> propagator_init_trigger(Vs, P) -->
[p(Prop)], [p(Prop)],
{ make_propagator(P, Prop), { make_propagator(P, Prop),
maplist(prop_init(Prop), Vs), new_queue(Q0),
phrase(init_propagator_(Vs, Prop), [Q0], [Q]),
variables_same_queue(Vs), variables_same_queue(Vs),
trigger_once(Prop) }. trigger_once_(Prop, Q) }.
variables_same_queue(Vs0) :- variables_same_queue(Vs0) :-
include(var, Vs0, Vs), include(var, Vs0, Vs),
new_queue(Q), ( Vs == [] -> true
maplist(variable_queue, Vs, Qs), ; maplist(variable_queue, Vs, Qs0),
phrase((collect_goal(Qs), sort(Qs0, [Q|Qs]),
collect_fast(Qs), Q =.. [_|Args],
collect_slow(Qs)), [Q], [Q]), append_queues_(Qs, Args, [append,append,append,ignore]),
maplist(clear_queue, Qs), maplist(clear_queue, Qs),
maplist(=(Q), Qs). maplist(=(Q), Qs)
).
append_queues_([], _, _).
append_queues_([Q|Qs], Args0, Is) :-
Q =.. [_|Args],
maplist(append_queue, Is, Args0, Args),
append_queues_(Qs, Args, Is).
append_queue(ignore, _, _).
append_queue(append, Q0, Q) :-
( get_atts(Q0, queue(Ls0,Ls)) ->
( get_atts(Q, queue(Ms0,Ms)) ->
Ls = Ms0,
put_atts(Q0, queue(Ls0,Ms))
; true
)
; ( get_atts(Q, queue(Ms0,Ms)) ->
put_atts(Q0, queue(Ms0,Ms))
; true
)
).
clear_queue(queue(Goals,Fast,Slow,Aux)) :- clear_queue(queue(Goals,Fast,Slow,Aux)) :-
put_atts(Goals, -queue(_,_)), put_atts(Goals, -queue(_,_)),
@@ -2686,22 +2711,6 @@ clear_queue(queue(Goals,Fast,Slow,Aux)) :-
put_atts(Slow, -queue(_,_)), put_atts(Slow, -queue(_,_)),
put_atts(Aux, -disabled). put_atts(Aux, -disabled).
collect_goal(Qs) --> collect_arg(Qs, 1).
collect_fast(Qs) --> collect_arg(Qs, 2).
collect_slow(Qs) --> collect_arg(Qs, 3).
collect_arg([], _) --> [].
collect_arg([Q|Qs], Which) -->
collect_all_(Q, Which),
collect_arg(Qs, Which).
collect_all_(Q, Which) -->
( { queue_get_arg_(Q, Which, Element) } ->
insert_queue(Element, Which),
collect_all_(Q, Which)
; []
).
variable_queue(Var, Q) :- variable_queue(Var, Q) :-
get_attr(Var, clpz, Attr), get_attr(Var, clpz, Attr),
Attr = clpz_attr(_Left,_Right,_Spread,_Dom,_Ps,Q). Attr = clpz_attr(_Left,_Right,_Spread,_Dom,_Ps,Q).
@@ -2813,7 +2822,7 @@ matches([
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
m(var(X) #\= integer(Y)) => [g(neq_num(X, Y))], m(var(X) #\= integer(Y)) => [g(neq_num(X, Y))],
m(var(X) #\= var(Y)) => [g(neq(X,Y))], m(var(X) #\= var(Y)) => [p(pneq(X,Y))],
m(var(X) #\= var(Y) + var(Z)) => [p(x_neq_y_plus_z(X, Y, Z))], m(var(X) #\= var(Y) + var(Z)) => [p(x_neq_y_plus_z(X, Y, Z))],
m(var(X) #\= var(Y) - var(Z)) => [p(x_neq_y_plus_z(Y, X, Z))], m(var(X) #\= var(Y) - var(Z)) => [p(x_neq_y_plus_z(Y, X, Z))],
m(var(X) #\= var(Y)*var(Z)) => [p(ptimes(Y,Z,P)), g(neq(X,P))], m(var(X) #\= var(Y)*var(Z)) => [p(ptimes(Y,Z,P)), g(neq(X,P))],
@@ -2898,10 +2907,12 @@ match_goal(r(X,Y), F) --> { G =.. [F,X,Y] }, [G].
match_goal(d(X,Y), _) --> [parse_clpz(X, Y)]. match_goal(d(X,Y), _) --> [parse_clpz(X, Y)].
match_goal(g(Goal), _) --> [Goal]. match_goal(g(Goal), _) --> [Goal].
match_goal(p(Prop), _) --> match_goal(p(Prop), _) -->
[make_propagator(Prop, P)],
{ term_variables(Prop, Vs) }, { term_variables(Prop, Vs) },
parse_init(Vs, P), [make_propagator(Prop, P),
[trigger_once(P)]. new_queue(Q0),
phrase(init_propagator_(Vs, P), [Q0], [Q]),
variables_same_queue(Vs),
trigger_once_(P, Q)].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -3753,8 +3764,10 @@ kill_reified_tuples([B|Bs], Ps, All) -->
relation_tuple_b_prop(Relation, Tuple, B, p(Prop)) :- relation_tuple_b_prop(Relation, Tuple, B, p(Prop)) :-
put_attr(R, clpz_relation, Relation), put_attr(R, clpz_relation, Relation),
make_propagator(reified_tuple_in(Tuple, R, B), Prop), make_propagator(reified_tuple_in(Tuple, R, B), Prop),
tuple_freeze_(Tuple, Prop), new_queue(Q0),
init_propagator(B, Prop). phrase((tuple_freeze_(Tuple, Prop),
init_propagator_([B], Prop),
do_queue), [Q0], _).
tuples_in_conjunction(Tuples, Relation, Conj) :- tuples_in_conjunction(Tuples, Relation, Conj) :-
@@ -3960,7 +3973,7 @@ insert_queue(Element, Which) -->
Tail0 = [Element|Tail] Tail0 = [Element|Tail]
; Head = [Element|Tail] ; Head = [Element|Tail]
), ),
put_atts(Arg, +queue(Head,Tail)) }. put_atts(Arg, queue(Head,Tail)) }.
domain_spread(Dom, Spread) :- domain_spread(Dom, Spread) :-
@@ -4192,9 +4205,9 @@ ignore(Goal) :- ( Goal -> true ; true ).
print_queue --> print_queue -->
state(queue(Goal,Fast,Slow,_)), state(queue(Goal,Fast,Slow,_)),
{ ignore(get_atts(Goal, +queue(GHs,_))), { ignore(get_atts(Goal, queue(GHs,_))),
ignore(get_atts(Fast, +queue(FHs,_))), ignore(get_atts(Fast, queue(FHs,_))),
ignore(get_atts(Slow, +queue(SHs,_))), ignore(get_atts(Slow, queue(SHs,_))),
format("Current queue:~n goal: ~q~n fast: ~q~n slow: ~q~n~n", [GHs,FHs,SHs]) }. format("Current queue:~n goal: ~q~n fast: ~q~n slow: ~q~n~n", [GHs,FHs,SHs]) }.
@@ -4209,18 +4222,27 @@ queue_get_arg(Which, Element) -->
queue_get_arg_(Queue, Which, Element) :- queue_get_arg_(Queue, Which, Element) :-
arg(Which, Queue, Arg), arg(Which, Queue, Arg),
get_atts(Arg, +queue([Element|Elements],Tail)), get_atts(Arg, queue([Element|Elements],Tail)),
( var(Elements) -> ( var(Elements) ->
put_atts(Arg, -queue(_,_)) put_atts(Arg, -queue(_,_))
; put_atts(Arg, +queue(Elements,Tail)) ; put_atts(Arg, queue(Elements,Tail))
). ).
queue_enabled --> state(queue(_,_,_,Aux)), { \+ get_atts(Aux, disabled) }. queue_enabled --> state(queue(_,_,_,Aux)), { \+ get_atts(Aux, disabled) }.
disable_queue --> state(queue(_,_,_,Aux)), { put_atts(Aux, +disabled) }. disable_queue --> state(queue(_,_,_,Aux)), { put_atts(Aux, disabled) }.
enable_queue --> state(queue(_,_,_,Aux)), { put_atts(Aux, -disabled) }. enable_queue --> state(queue(_,_,_,Aux)), { put_atts(Aux, -disabled) }.
portray_propagator(propagator(P,_), F) :- functor(P, F, _). portray_propagator(propagator(P,_), F) :- functor(P, F, _).
init_propagator_([], _) --> [].
init_propagator_([V|Vs], Prop) -->
( { fd_get(V, Dom, Ps0) } ->
{ insert_propagator(Prop, Ps0, Ps) },
fd_put(V, Dom, Ps)
; []
),
init_propagator_(Vs, Prop).
init_propagator(Var, Prop) :- init_propagator(Var, Prop) :-
( fd_get(Var, Dom, Ps0) -> ( fd_get(Var, Dom, Ps0) ->
insert_propagator(Prop, Ps0, Ps), insert_propagator(Prop, Ps0, Ps),
@@ -4343,17 +4365,22 @@ tuples_in(Tuples, Relation) :-
must_be(list(list), Tuples), must_be(list(list), Tuples),
maplist(maplist(fd_variable), Tuples), maplist(maplist(fd_variable), Tuples),
must_be(list(list(integer)), Relation), must_be(list(list(integer)), Relation),
maplist(relation_tuple(Relation), Tuples). new_queue(Q0),
phrase(tuples_relation(Tuples, Relation), [Q0], [Q]),
append(Tuples, Vs),
variables_same_queue(Vs),
phrase(do_queue, [Q], _).
relation_tuple(Relation, Tuple) :- tuples_relation([], _) --> [].
relation_unifiable(Relation, Tuple, Us, _, _), tuples_relation([Tuple|Tuples], Relation) -->
( ground(Tuple) -> memberchk(Tuple, Relation) { relation_unifiable(Relation, Tuple, Us, _, _) },
; new_queue(Q), ( ground(Tuple) -> { memberchk(Tuple, Relation) }
phrase((tuple_domain(Tuple, Us),do_queue), [Q], _), ; tuple_domain(Tuple, Us),
( Tuple = [_,_|_] -> tuple_freeze(Tuple, Us) ( Tuple = [_,_|_] -> tuple_freeze(Tuple, Us)
; true ; []
) )
). ),
tuples_relation(Tuples, Relation).
list_first_rest([L|Ls], L, Ls). list_first_rest([L|Ls], L, Ls).
@@ -4371,19 +4398,19 @@ tuple_domain([T|Ts], Relation0) -->
), ),
tuple_domain(Ts, Relation1). tuple_domain(Ts, Relation1).
tuple_freeze(Tuple, Relation) :- tuple_freeze(Tuple, Relation) -->
( ground(Tuple) -> memberchk(Tuple, Relation) ( ground(Tuple) -> { memberchk(Tuple, Relation) }
; put_attr(R, clpz_relation, Relation), ; { put_attr(R, clpz_relation, Relation),
make_propagator(rel_tuple(R, Tuple), Prop), make_propagator(rel_tuple(R, Tuple), Prop) },
tuple_freeze_(Tuple, Prop) tuple_freeze_(Tuple, Prop)
). ).
tuple_freeze_([], _). tuple_freeze_([], _) --> [].
tuple_freeze_([T|Ts], Prop) :- tuple_freeze_([T|Ts], Prop) -->
( var(T) -> ( var(T) ->
init_propagator(T, Prop), init_propagator_([T], Prop),
trigger_prop(Prop) trigger_prop(Prop)
; true ; []
), ),
tuple_freeze_(Ts, Prop). tuple_freeze_(Ts, Prop).
@@ -5993,9 +6020,9 @@ max_factor(L1, U1, L2, U2, Max) :-
distinct_attach([], _, _) --> []. distinct_attach([], _, _) --> [].
distinct_attach([X|Xs], Prop, Right) --> distinct_attach([X|Xs], Prop, Right) -->
( var(X) -> ( var(X) ->
{ init_propagator(X, Prop), init_propagator_([X], Prop),
make_propagator(pexclude(Xs,Right,X), P1), { make_propagator(pexclude(Xs,Right,X), P1) },
init_propagator(X, P1) }, init_propagator_([X], P1),
trigger_prop(P1) trigger_prop(P1)
; exclude_fire(Xs, Right, X) ; exclude_fire(Xs, Right, X)
), ),
@@ -7488,9 +7515,15 @@ zcompare(Order, A, B) :-
propagator_init_trigger([A,B], pzcompare(Order, A, B)) propagator_init_trigger([A,B], pzcompare(Order, A, B))
). ).
zcompare_(=, A, B) :- #A #= #B. zcompare_(O, A, B) :-
zcompare_(<, A, B) :- #A #< #B. ( member(O, "<=>") -> true
zcompare_(>, A, B) :- #A #> #B. ; domain_error(order, O, zcompare/3)
),
zcompare__(O, A, B).
zcompare__(=, A, B) :- #A #= #B.
zcompare__(<, A, B) :- #A #< #B.
zcompare__(>, A, B) :- #A #> #B.
%% chain(+Relation, +Zs) %% chain(+Relation, +Zs)
% %

View File

@@ -711,6 +711,8 @@ curve25519_scalar_mult(Scalar, Point, Result) :-
must_be_bytes(ScalarBytes, curve25519_scalar_mult/3), must_be_bytes(ScalarBytes, curve25519_scalar_mult/3),
length(ScalarBytes, 32) length(ScalarBytes, 32)
), ),
must_be(chars, Point),
length(Point, 32),
maplist(char_code, Point, PointBytes), maplist(char_code, Point, PointBytes),
'$curve25519_scalar_mult'(ScalarBytes, PointBytes, Result). '$curve25519_scalar_mult'(ScalarBytes, PointBytes, Result).

View File

@@ -526,7 +526,7 @@ var_name(V, Name=V, Num0, Num) :-
Num is Num0 + 1. Num is Num0 + 1.
literal(Lit, VNs) --> literal(Lit, VNs) -->
{ write_term_to_chars(Lit, [quoted(true),variable_names(VNs)], Ls) }, { write_term_to_chars(Lit, [quoted(true),variable_names(VNs),double_quotes(true)], Ls) },
seq(Ls). seq(Ls).
portray_(Var, VNs) --> { var(Var) }, !, literal(Var, VNs). portray_(Var, VNs) --> { var(Var) }, !, literal(Var, VNs).

View File

@@ -14,6 +14,7 @@ but they're not part of the ISO Prolog standard at the moment.
partial_string/3, partial_string/3,
partial_string_tail/2, partial_string_tail/2,
setup_call_cleanup/3, setup_call_cleanup/3,
succ/2,
call_nth/2, call_nth/2,
countall/2, countall/2,
copy_term_nat/2, copy_term_nat/2,
@@ -112,6 +113,23 @@ bb_get(Key, Value) :-
). ).
%% succ(?I, ?S).
%
% True iff S is the successor of the non-negative integer I.
% At least one of the arguments must be instantiated.
succ(I, S) :-
can_be(not_less_than_zero, I),
can_be(not_less_than_zero, S),
( integer(S) ->
S > 0,
I is S-1
; integer(I) ->
S is I+1
; instantiation_error(succ/2)
).
% setup_call_cleanup. % setup_call_cleanup.
:- meta_predicate(call_cleanup(0, 0)). :- meta_predicate(call_cleanup(0, 0)).

View File

@@ -95,7 +95,8 @@
op(200, fy, @) op(200, fy, @)
]). ]).
:- use_module(library(lists),[member/2,memberchk/2]). :- use_module(library(lists),[member/2,memberchk/2,reverse/2]).
:- use_module(library(charsio)).
:- use_module(library(error)). :- use_module(library(error)).
:- use_module(library(dcgs)). :- use_module(library(dcgs)).
:- use_module(library(si)). :- use_module(library(si)).
@@ -636,5 +637,27 @@ text_of_1([C|Cs]) --> seq([C|Cs]).
xsd_number_chars(Number, Chars) :- xsd_number_chars(Number, Chars) :-
number_chars(Number, Chars). number_chars(Number, Chars).
normalize_space(Text0, Text) :- normalize_space(Cs0, Cs) :-
Text0 = Text. % no conversion for the moment. must_be(chars, Cs0),
no_leading_whitespace(Cs0, Cs1),
reverse(Cs1, Cs2),
no_leading_whitespace(Cs2, Cs3),
reverse(Cs3, Cs4),
single_intermediate_space(Cs4, Cs).
no_leading_whitespace([], []).
no_leading_whitespace([C0|Cs0], Cs) :-
( char_type(C0, whitespace) ->
no_leading_whitespace(Cs0, Cs)
; Cs = [C0|Cs0]
).
single_intermediate_space([], []).
single_intermediate_space([C0|Cs0], [C|Cs]) :-
( char_type(C0, whitespace) ->
no_leading_whitespace(Cs0, Cs1),
C = ' ',
single_intermediate_space(Cs1, Cs)
; C = C0,
single_intermediate_space(Cs0, Cs)
).

View File

@@ -187,8 +187,8 @@ impl<T: CopierTarget> CopyTermState<T> {
fn copy_attr_var_list(&mut self, mut list_addr: HeapCellValue) { fn copy_attr_var_list(&mut self, mut list_addr: HeapCellValue) {
while let HeapCellValueTag::Lis = list_addr.get_tag() { while let HeapCellValueTag::Lis = list_addr.get_tag() {
let threshold = self.target.threshold(); let threshold = self.target.threshold();
let heap_loc = list_addr.get_value(); let heap_loc = list_addr.get_value() as usize;
let str_loc = self.target[heap_loc].get_value(); 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+2));
self.target.push(heap_loc_as_cell!(threshold+1)); self.target.push(heap_loc_as_cell!(threshold+1));

View File

@@ -27,7 +27,7 @@ pub struct BranchNumber {
impl Default for BranchNumber { impl Default for BranchNumber {
fn default() -> Self { fn default() -> Self {
Self { Self {
branch_num: Rational::from(1usize << 63), branch_num: Rational::from(1u64 << 63),
delta: Rational::from(1), delta: Rational::from(1),
} }
} }

View File

@@ -1497,6 +1497,14 @@ impl Machine {
try_or_throw!(self.machine_st, self.machine_st.is(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); 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 => { &Instruction::CallAcyclicTerm => {
let addr = self.machine_st.registers[1]; let addr = self.machine_st.registers[1];
@@ -1965,6 +1973,34 @@ impl Machine {
self.machine_st.p = self.machine_st.cp; 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) => { &Instruction::CallN(arity) => {
let pred = self.machine_st.registers[1]; let pred = self.machine_st.registers[1];
@@ -4242,58 +4278,72 @@ impl Machine {
step_or_fail!(self, self.machine_st.p = self.machine_st.cp); step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
} }
&Instruction::CallHttpOpen => { &Instruction::CallHttpOpen => {
#[cfg(feature = "http")]
try_or_throw!(self.machine_st, self.http_open()); try_or_throw!(self.machine_st, self.http_open());
step_or_fail!(self, self.machine_st.p += 1); step_or_fail!(self, self.machine_st.p += 1);
} }
&Instruction::ExecuteHttpOpen => { &Instruction::ExecuteHttpOpen => {
#[cfg(feature = "http")]
try_or_throw!(self.machine_st, self.http_open()); try_or_throw!(self.machine_st, self.http_open());
step_or_fail!(self, self.machine_st.p = self.machine_st.cp); step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
} }
&Instruction::CallHttpListen => { &Instruction::CallHttpListen => {
#[cfg(feature = "http")]
try_or_throw!(self.machine_st, self.http_listen()); try_or_throw!(self.machine_st, self.http_listen());
step_or_fail!(self, self.machine_st.p += 1); step_or_fail!(self, self.machine_st.p += 1);
} }
&Instruction::ExecuteHttpListen => { &Instruction::ExecuteHttpListen => {
#[cfg(feature = "http")]
try_or_throw!(self.machine_st, self.http_listen()); try_or_throw!(self.machine_st, self.http_listen());
step_or_fail!(self, self.machine_st.p = self.machine_st.cp); step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
} }
&Instruction::CallHttpAccept => { &Instruction::CallHttpAccept => {
#[cfg(feature = "http")]
try_or_throw!(self.machine_st, self.http_accept()); try_or_throw!(self.machine_st, self.http_accept());
step_or_fail!(self, self.machine_st.p += 1); step_or_fail!(self, self.machine_st.p += 1);
} }
&Instruction::ExecuteHttpAccept => { &Instruction::ExecuteHttpAccept => {
#[cfg(feature = "http")]
try_or_throw!(self.machine_st, self.http_accept()); try_or_throw!(self.machine_st, self.http_accept());
step_or_fail!(self, self.machine_st.p = self.machine_st.cp); step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
} }
&Instruction::CallHttpAnswer => { &Instruction::CallHttpAnswer => {
#[cfg(feature = "http")]
try_or_throw!(self.machine_st, self.http_answer()); try_or_throw!(self.machine_st, self.http_answer());
step_or_fail!(self, self.machine_st.p += 1); step_or_fail!(self, self.machine_st.p += 1);
} }
&Instruction::ExecuteHttpAnswer => { &Instruction::ExecuteHttpAnswer => {
#[cfg(feature = "http")]
try_or_throw!(self.machine_st, self.http_answer()); try_or_throw!(self.machine_st, self.http_answer());
step_or_fail!(self, self.machine_st.p = self.machine_st.cp); step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
} }
&Instruction::CallLoadForeignLib => { &Instruction::CallLoadForeignLib => {
#[cfg(feature = "ffi")]
try_or_throw!(self.machine_st, self.load_foreign_lib()); try_or_throw!(self.machine_st, self.load_foreign_lib());
step_or_fail!(self, self.machine_st.p += 1); step_or_fail!(self, self.machine_st.p += 1);
} }
&Instruction::ExecuteLoadForeignLib => { &Instruction::ExecuteLoadForeignLib => {
#[cfg(feature = "ffi")]
try_or_throw!(self.machine_st, self.load_foreign_lib()); try_or_throw!(self.machine_st, self.load_foreign_lib());
step_or_fail!(self, self.machine_st.p = self.machine_st.cp); step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
} }
&Instruction::CallForeignCall => { &Instruction::CallForeignCall => {
#[cfg(feature = "ffi")]
try_or_throw!(self.machine_st, self.foreign_call()); try_or_throw!(self.machine_st, self.foreign_call());
step_or_fail!(self, self.machine_st.p += 1); step_or_fail!(self, self.machine_st.p += 1);
} }
&Instruction::ExecuteForeignCall => { &Instruction::ExecuteForeignCall => {
#[cfg(feature = "ffi")]
try_or_throw!(self.machine_st, self.foreign_call()); try_or_throw!(self.machine_st, self.foreign_call());
step_or_fail!(self, self.machine_st.p = self.machine_st.cp); step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
} }
&Instruction::CallDefineForeignStruct => { &Instruction::CallDefineForeignStruct => {
#[cfg(feature = "ffi")]
try_or_throw!(self.machine_st, self.define_foreign_struct()); try_or_throw!(self.machine_st, self.define_foreign_struct());
step_or_fail!(self, self.machine_st.p += 1); step_or_fail!(self, self.machine_st.p += 1);
} }
&Instruction::ExecuteDefineForeignStruct => { &Instruction::ExecuteDefineForeignStruct => {
#[cfg(feature = "ffi")]
try_or_throw!(self.machine_st, self.define_foreign_struct()); try_or_throw!(self.machine_st, self.define_foreign_struct());
step_or_fail!(self, self.machine_st.p = self.machine_st.cp); step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
} }
@@ -4462,18 +4512,22 @@ impl Machine {
self.machine_st.p = self.machine_st.cp; self.machine_st.p = self.machine_st.cp;
} }
&Instruction::CallTLSAcceptClient => { &Instruction::CallTLSAcceptClient => {
#[cfg(feature = "tls")]
try_or_throw!(self.machine_st, self.tls_accept_client()); try_or_throw!(self.machine_st, self.tls_accept_client());
step_or_fail!(self, self.machine_st.p += 1); step_or_fail!(self, self.machine_st.p += 1);
} }
&Instruction::ExecuteTLSAcceptClient => { &Instruction::ExecuteTLSAcceptClient => {
#[cfg(feature = "tls")]
try_or_throw!(self.machine_st, self.tls_accept_client()); try_or_throw!(self.machine_st, self.tls_accept_client());
step_or_fail!(self, self.machine_st.p = self.machine_st.cp); step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
} }
&Instruction::CallTLSClientConnect => { &Instruction::CallTLSClientConnect => {
#[cfg(feature = "tls")]
try_or_throw!(self.machine_st, self.tls_client_connect()); try_or_throw!(self.machine_st, self.tls_client_connect());
step_or_fail!(self, self.machine_st.p += 1); step_or_fail!(self, self.machine_st.p += 1);
} }
&Instruction::ExecuteTLSClientConnect => { &Instruction::ExecuteTLSClientConnect => {
#[cfg(feature = "tls")]
try_or_throw!(self.machine_st, self.tls_client_connect()); try_or_throw!(self.machine_st, self.tls_client_connect());
step_or_fail!(self, self.machine_st.p = self.machine_st.cp); step_or_fail!(self, self.machine_st.p = self.machine_st.cp);
} }

View File

@@ -68,7 +68,7 @@ pub(crate) struct StacklessPreOrderHeapIter<'a, UMP: UnmarkPolicy> {
orig_heap_len: usize, orig_heap_len: usize,
start: usize, start: usize,
current: usize, current: usize,
next: usize, next: u64,
_marker: PhantomData<UMP>, _marker: PhantomData<UMP>,
} }
@@ -153,14 +153,14 @@ impl<'a, UMP: UnmarkPolicy> StacklessPreOrderHeapIter<'a, UMP> {
} }
fn forward_var(&mut self) -> Option<HeapCellValue> { fn forward_var(&mut self) -> Option<HeapCellValue> {
if self.heap[self.next].get_forwarding_bit() { if self.heap[self.next as usize].get_forwarding_bit() {
return self.backward_and_return(); return self.backward_and_return();
} }
let temp = self.heap[self.next].get_value(); let temp = self.heap[self.next as usize].get_value();
self.heap[self.next].set_value(self.current); self.heap[self.next as usize].set_value(self.current as u64);
self.current = self.next; self.current = self.next as usize;
self.next = temp; self.next = temp;
None None
@@ -175,23 +175,23 @@ impl<'a, UMP: UnmarkPolicy> StacklessPreOrderHeapIter<'a, UMP> {
HeapCellValueTag::AttrVar => { 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].get_mark_bit() { if self.heap[self.next as usize].get_mark_bit() {
return Some(attr_var_as_cell!(self.current)); return Some(attr_var_as_cell!(self.current));
} }
} }
HeapCellValueTag::Var => { 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].get_mark_bit() { if self.heap[self.next as usize].get_mark_bit() {
return Some(heap_loc_as_cell!(self.current)); return Some(heap_loc_as_cell!(self.current));
} }
} }
HeapCellValueTag::Str => { HeapCellValueTag::Str => {
if self.heap[self.next + 1].get_forwarding_bit() { if self.heap[self.next as usize + 1].get_forwarding_bit() {
return self.backward_and_return(); return self.backward_and_return();
} }
let h = self.next; let h = self.next as usize;
let cell = self.heap[h]; let cell = self.heap[h];
let arity = cell_as_atom_cell!(self.heap[h]).get_arity(); let arity = cell_as_atom_cell!(self.heap[h]).get_arity();
@@ -203,13 +203,13 @@ impl<'a, UMP: UnmarkPolicy> StacklessPreOrderHeapIter<'a, UMP> {
let last_cell_loc = h + arity; let last_cell_loc = h + arity;
self.next = self.heap[last_cell_loc].get_value(); self.next = self.heap[last_cell_loc].get_value();
self.heap[last_cell_loc].set_value(self.current); self.heap[last_cell_loc].set_value(self.current as u64);
self.current = last_cell_loc; self.current = last_cell_loc;
return Some(cell); return Some(cell);
} }
HeapCellValueTag::Lis => { HeapCellValueTag::Lis => {
let last_cell_loc = self.next + 1; let last_cell_loc = self.next as usize + 1;
if self.heap[last_cell_loc].get_forwarding_bit() { if self.heap[last_cell_loc].get_forwarding_bit() {
return self.backward_and_return(); return self.backward_and_return();
@@ -218,13 +218,13 @@ impl<'a, UMP: UnmarkPolicy> StacklessPreOrderHeapIter<'a, UMP> {
self.heap[last_cell_loc].set_forwarding_bit(true); self.heap[last_cell_loc].set_forwarding_bit(true);
self.next = self.heap[last_cell_loc].get_value(); self.next = self.heap[last_cell_loc].get_value();
self.heap[last_cell_loc].set_value(self.current); self.heap[last_cell_loc].set_value(self.current as u64);
self.current = last_cell_loc; self.current = last_cell_loc;
return Some(list_loc_as_cell!(last_cell_loc - 1)); return Some(list_loc_as_cell!(last_cell_loc - 1));
} }
HeapCellValueTag::PStrLoc => { HeapCellValueTag::PStrLoc => {
let h = self.next; let h = self.next as usize;
let cell = self.heap[h]; let cell = self.heap[h];
if self.heap[h+1].get_forwarding_bit() { if self.heap[h+1].get_forwarding_bit() {
@@ -236,13 +236,13 @@ impl<'a, UMP: UnmarkPolicy> StacklessPreOrderHeapIter<'a, UMP> {
self.heap[last_cell_loc].set_forwarding_bit(true); self.heap[last_cell_loc].set_forwarding_bit(true);
self.next = self.heap[last_cell_loc].get_value(); self.next = self.heap[last_cell_loc].get_value();
self.heap[last_cell_loc].set_value(self.current); self.heap[last_cell_loc].set_value(self.current as u64);
self.current = last_cell_loc; self.current = last_cell_loc;
} else { } else {
debug_assert!(self.heap[h].get_tag() == HeapCellValueTag::PStrOffset); debug_assert!(self.heap[h].get_tag() == HeapCellValueTag::PStrOffset);
self.next = self.heap[h].get_value(); self.next = self.heap[h].get_value();
self.heap[h].set_value(self.current); self.heap[h].set_value(self.current as u64);
self.current = h; self.current = h;
if self.heap[h].get_mark_bit() { if self.heap[h].get_mark_bit() {
@@ -253,7 +253,7 @@ impl<'a, UMP: UnmarkPolicy> StacklessPreOrderHeapIter<'a, UMP> {
return Some(cell); return Some(cell);
} }
HeapCellValueTag::PStrOffset => { HeapCellValueTag::PStrOffset => {
let h = self.next; let h = self.next as usize;
let cell = self.heap[h]; let cell = self.heap[h];
// mark the Fixnum offset. // mark the Fixnum offset.
@@ -269,20 +269,20 @@ impl<'a, UMP: UnmarkPolicy> StacklessPreOrderHeapIter<'a, UMP> {
self.heap[last_cell_loc].set_forwarding_bit(true); self.heap[last_cell_loc].set_forwarding_bit(true);
self.next = self.heap[last_cell_loc].get_value(); self.next = self.heap[last_cell_loc].get_value();
self.heap[last_cell_loc].set_value(self.current); self.heap[last_cell_loc].set_value(self.current as u64);
self.current = last_cell_loc; self.current = last_cell_loc;
} else { } else {
debug_assert!(self.heap[h].get_tag() == HeapCellValueTag::CStr); debug_assert!(self.heap[h].get_tag() == HeapCellValueTag::CStr);
self.next = self.heap[h].get_value(); self.next = self.heap[h].get_value();
self.heap[h].set_value(self.current); self.heap[h].set_value(self.current as u64);
self.current = h; self.current = h;
} }
return Some(cell); return Some(cell);
} }
tag @ HeapCellValueTag::Atom => { tag @ HeapCellValueTag::Atom => {
let cell = HeapCellValue::build_with(tag, self.next as u64); let cell = HeapCellValue::build_with(tag, self.next);
let arity = AtomCell::from_bytes(cell.into_bytes()).get_arity(); let arity = AtomCell::from_bytes(cell.into_bytes()).get_arity();
if arity == 0 { if arity == 0 {
@@ -315,8 +315,8 @@ impl<'a, UMP: UnmarkPolicy> StacklessPreOrderHeapIter<'a, UMP> {
UMP::unmark(self.heap, self.current); UMP::unmark(self.heap, self.current);
self.heap[self.current].set_value(self.next); self.heap[self.current].set_value(self.next);
self.next = self.current; self.next = self.current as u64;
self.current = temp; self.current = temp as usize;
} }
self.heap[self.current].set_forwarding_bit(false); self.heap[self.current].set_forwarding_bit(false);

View File

@@ -2,6 +2,7 @@ use crate::arena::*;
use crate::atom_table::*; use crate::atom_table::*;
use crate::parser::ast::*; use crate::parser::ast::*;
#[cfg(feature = "ffi")]
use crate::ffi::FFIError; use crate::ffi::FFIError;
use crate::forms::*; use crate::forms::*;
use crate::machine::heap::*; use crate::machine::heap::*;
@@ -538,6 +539,7 @@ impl MachineState {
} }
} }
#[cfg(feature = "ffi")]
pub(super) fn ffi_error(&mut self, err: FFIError) -> MachineError { pub(super) fn ffi_error(&mut self, err: FFIError) -> MachineError {
let error_atom = match err { let error_atom = match err {
FFIError::ValueCast => atom!("value_cast"), FFIError::ValueCast => atom!("value_cast"),

View File

@@ -143,6 +143,10 @@ impl IndexPtr {
#[derive(Debug, Clone, Copy, Ord, Hash, PartialOrd, Eq, PartialEq)] #[derive(Debug, Clone, Copy, Ord, Hash, PartialOrd, Eq, PartialEq)]
pub struct CodeIndex(TypedArenaPtr<IndexPtr>); pub struct CodeIndex(TypedArenaPtr<IndexPtr>);
#[cfg(target_pointer_width="32")]
const_assert!(std::mem::align_of::<CodeIndex>() == 4);
#[cfg(target_pointer_width="64")]
const_assert!(std::mem::align_of::<CodeIndex>() == 8); const_assert!(std::mem::align_of::<CodeIndex>() == 8);
impl Deref for CodeIndex { impl Deref for CodeIndex {
@@ -164,7 +168,7 @@ impl DerefMut for CodeIndex {
impl From<CodeIndex> for UntypedArenaPtr { impl From<CodeIndex> for UntypedArenaPtr {
#[inline(always)] #[inline(always)]
fn from(ptr: CodeIndex) -> UntypedArenaPtr { fn from(ptr: CodeIndex) -> UntypedArenaPtr {
unsafe { std::mem::transmute(ptr.0.as_ptr()) } UntypedArenaPtr::build_with(ptr.0.as_ptr() as usize)
} }
} }

View File

@@ -31,6 +31,7 @@ use crate::arena::*;
use crate::arithmetic::*; use crate::arithmetic::*;
use crate::atom_table::*; use crate::atom_table::*;
use crate::forms::*; use crate::forms::*;
#[cfg(feature = "ffi")]
use crate::ffi::ForeignFunctionTable; use crate::ffi::ForeignFunctionTable;
use crate::instructions::*; use crate::instructions::*;
use crate::machine::args::*; use crate::machine::args::*;
@@ -73,6 +74,7 @@ pub struct Machine {
pub(super) user_output: Stream, pub(super) user_output: Stream,
pub(super) user_error: Stream, pub(super) user_error: Stream,
pub(super) load_contexts: Vec<LoadContext>, pub(super) load_contexts: Vec<LoadContext>,
#[cfg(feature = "ffi")]
pub(super) foreign_function_table: ForeignFunctionTable, pub(super) foreign_function_table: ForeignFunctionTable,
} }
@@ -452,6 +454,7 @@ impl Machine {
user_output, user_output,
user_error, user_error,
load_contexts: vec![], load_contexts: vec![],
#[cfg(feature = "ffi")]
foreign_function_table: Default::default(), foreign_function_table: Default::default(),
}; };
@@ -1253,7 +1256,7 @@ impl Machine {
} }
} }
TrailEntryTag::TrailedBlackboardEntry => { TrailEntryTag::TrailedBlackboardEntry => {
let key = Atom::from(h); let key = Atom::from(h as u64);
match self.indices.global_variables.get_mut(&key) { match self.indices.global_variables.get_mut(&key) {
Some((_, ref mut loc)) => *loc = None, Some((_, ref mut loc)) => *loc = None,
@@ -1261,7 +1264,7 @@ impl Machine {
} }
} }
TrailEntryTag::TrailedBlackboardOffset => { TrailEntryTag::TrailedBlackboardOffset => {
let key = Atom::from(h); let key = Atom::from(h as u64);
let value_cell = HeapCellValue::from(u64::from(self.machine_st.trail[i + 1])); let value_cell = HeapCellValue::from(u64::from(self.machine_st.trail[i + 1]));
match self.indices.global_variables.get_mut(&key) { match self.indices.global_variables.get_mut(&key) {

View File

@@ -9,6 +9,7 @@ use crate::machine::machine_errors::*;
use crate::machine::machine_indices::*; use crate::machine::machine_indices::*;
use crate::machine::machine_state::*; use crate::machine::machine_state::*;
use crate::types::*; use crate::types::*;
#[cfg(feature = "http")]
use crate::http::HttpResponse; use crate::http::HttpResponse;
pub use modular_bitfield::prelude::*; pub use modular_bitfield::prelude::*;
@@ -26,6 +27,7 @@ use std::net::{TcpStream, Shutdown};
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use std::ptr; use std::ptr;
#[cfg(feature = "tls")]
use native_tls::TlsStream; use native_tls::TlsStream;
#[derive(Debug, BitfieldSpecifier, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, BitfieldSpecifier, Clone, Copy, PartialEq, Eq, Hash)]
@@ -232,12 +234,14 @@ impl Write for NamedTcpStream {
} }
} }
#[cfg(feature = "tls")]
#[derive(Debug)] #[derive(Debug)]
pub struct NamedTlsStream { pub struct NamedTlsStream {
address: Atom, address: Atom,
tls_stream: TlsStream<Stream>, tls_stream: TlsStream<Stream>,
} }
#[cfg(feature = "tls")]
impl Read for NamedTlsStream { impl Read for NamedTlsStream {
#[inline] #[inline]
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
@@ -245,6 +249,7 @@ impl Read for NamedTlsStream {
} }
} }
#[cfg(feature = "tls")]
impl Write for NamedTlsStream { impl Write for NamedTlsStream {
#[inline] #[inline]
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
@@ -257,17 +262,20 @@ impl Write for NamedTlsStream {
} }
} }
#[cfg(feature = "http")]
pub struct HttpReadStream { pub struct HttpReadStream {
url: Atom, url: Atom,
body_reader: Box<dyn BufRead>, body_reader: Box<dyn BufRead>,
} }
#[cfg(feature = "http")]
impl Debug for HttpReadStream { impl Debug for HttpReadStream {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Http Read Stream [{}]", self.url.as_str()) write!(f, "Http Read Stream [{}]", self.url.as_str())
} }
} }
#[cfg(feature = "http")]
impl Read for HttpReadStream { impl Read for HttpReadStream {
#[inline] #[inline]
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
@@ -275,6 +283,7 @@ impl Read for HttpReadStream {
} }
} }
#[cfg(feature = "http")]
pub struct HttpWriteStream { pub struct HttpWriteStream {
status_code: u16, status_code: u16,
headers: hyper::HeaderMap, headers: hyper::HeaderMap,
@@ -282,12 +291,14 @@ pub struct HttpWriteStream {
buffer: Vec<u8>, buffer: Vec<u8>,
} }
#[cfg(feature = "http")]
impl Debug for HttpWriteStream { impl Debug for HttpWriteStream {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Http Write Stream") write!(f, "Http Write Stream")
} }
} }
#[cfg(feature = "http")]
impl Write for HttpWriteStream { impl Write for HttpWriteStream {
#[inline] #[inline]
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
@@ -361,7 +372,7 @@ impl StreamOptions {
#[inline] #[inline]
pub fn get_alias(self) -> Option<Atom> { pub fn get_alias(self) -> Option<Atom> {
if self.has_alias() { if self.has_alias() {
Some(Atom::from((self.alias() << 3) as usize)) Some(Atom::from((self.alias() as u64) << 3))
} else { } else {
None None
} }
@@ -453,8 +464,11 @@ arena_allocated_impl_for_stream!(CharReader<ByteStream>, ByteStream);
arena_allocated_impl_for_stream!(CharReader<InputFileStream>, InputFileStream); arena_allocated_impl_for_stream!(CharReader<InputFileStream>, InputFileStream);
arena_allocated_impl_for_stream!(OutputFileStream, OutputFileStream); arena_allocated_impl_for_stream!(OutputFileStream, OutputFileStream);
arena_allocated_impl_for_stream!(CharReader<NamedTcpStream>, NamedTcpStream); arena_allocated_impl_for_stream!(CharReader<NamedTcpStream>, NamedTcpStream);
#[cfg(feature = "tls")]
arena_allocated_impl_for_stream!(CharReader<NamedTlsStream>, NamedTlsStream); arena_allocated_impl_for_stream!(CharReader<NamedTlsStream>, NamedTlsStream);
#[cfg(feature = "http")]
arena_allocated_impl_for_stream!(CharReader<HttpReadStream>, HttpReadStream); arena_allocated_impl_for_stream!(CharReader<HttpReadStream>, HttpReadStream);
#[cfg(feature = "http")]
arena_allocated_impl_for_stream!(CharReader<HttpWriteStream>, HttpWriteStream); arena_allocated_impl_for_stream!(CharReader<HttpWriteStream>, HttpWriteStream);
arena_allocated_impl_for_stream!(ReadlineStream, ReadlineStream); arena_allocated_impl_for_stream!(ReadlineStream, ReadlineStream);
arena_allocated_impl_for_stream!(StaticStringStream, StaticStringStream); arena_allocated_impl_for_stream!(StaticStringStream, StaticStringStream);
@@ -468,8 +482,11 @@ pub enum Stream {
OutputFile(TypedArenaPtr<StreamLayout<OutputFileStream>>), OutputFile(TypedArenaPtr<StreamLayout<OutputFileStream>>),
StaticString(TypedArenaPtr<StreamLayout<StaticStringStream>>), StaticString(TypedArenaPtr<StreamLayout<StaticStringStream>>),
NamedTcp(TypedArenaPtr<StreamLayout<CharReader<NamedTcpStream>>>), NamedTcp(TypedArenaPtr<StreamLayout<CharReader<NamedTcpStream>>>),
#[cfg(feature = "tls")]
NamedTls(TypedArenaPtr<StreamLayout<CharReader<NamedTlsStream>>>), NamedTls(TypedArenaPtr<StreamLayout<CharReader<NamedTlsStream>>>),
#[cfg(feature = "http")]
HttpRead(TypedArenaPtr<StreamLayout<CharReader<HttpReadStream>>>), HttpRead(TypedArenaPtr<StreamLayout<CharReader<HttpReadStream>>>),
#[cfg(feature = "http")]
HttpWrite(TypedArenaPtr<StreamLayout<CharReader<HttpWriteStream>>>), HttpWrite(TypedArenaPtr<StreamLayout<CharReader<HttpWriteStream>>>),
Null(StreamOptions), Null(StreamOptions),
Readline(TypedArenaPtr<StreamLayout<ReadlineStream>>), Readline(TypedArenaPtr<StreamLayout<ReadlineStream>>),
@@ -524,8 +541,11 @@ impl Stream {
Stream::OutputFile(TypedArenaPtr::new(ptr as *mut _)) Stream::OutputFile(TypedArenaPtr::new(ptr as *mut _))
} }
ArenaHeaderTag::NamedTcpStream => Stream::NamedTcp(TypedArenaPtr::new(ptr as *mut _)), ArenaHeaderTag::NamedTcpStream => Stream::NamedTcp(TypedArenaPtr::new(ptr as *mut _)),
#[cfg(feature = "tls")]
ArenaHeaderTag::NamedTlsStream => Stream::NamedTls(TypedArenaPtr::new(ptr as *mut _)), ArenaHeaderTag::NamedTlsStream => Stream::NamedTls(TypedArenaPtr::new(ptr as *mut _)),
#[cfg(feature = "http")]
ArenaHeaderTag::HttpReadStream => Stream::HttpRead(TypedArenaPtr::new(ptr as *mut _)), 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::ReadlineStream => Stream::Readline(TypedArenaPtr::new(ptr as *mut _)),
ArenaHeaderTag::StaticStringStream => { ArenaHeaderTag::StaticStringStream => {
@@ -578,8 +598,11 @@ impl Stream {
Stream::OutputFile(ptr) => ptr.header_ptr(), Stream::OutputFile(ptr) => ptr.header_ptr(),
Stream::StaticString(ptr) => ptr.header_ptr(), Stream::StaticString(ptr) => ptr.header_ptr(),
Stream::NamedTcp(ptr) => ptr.header_ptr(), Stream::NamedTcp(ptr) => ptr.header_ptr(),
#[cfg(feature = "tls")]
Stream::NamedTls(ptr) => ptr.header_ptr(), Stream::NamedTls(ptr) => ptr.header_ptr(),
#[cfg(feature = "http")]
Stream::HttpRead(ptr) => ptr.header_ptr(), 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::Null(_) => ptr::null(),
Stream::Readline(ptr) => ptr.header_ptr(), Stream::Readline(ptr) => ptr.header_ptr(),
@@ -595,9 +618,12 @@ impl Stream {
Stream::OutputFile(ref ptr) => &ptr.options, Stream::OutputFile(ref ptr) => &ptr.options,
Stream::StaticString(ref ptr) => &ptr.options, Stream::StaticString(ref ptr) => &ptr.options,
Stream::NamedTcp(ref ptr) => &ptr.options, Stream::NamedTcp(ref ptr) => &ptr.options,
#[cfg(feature = "tls")]
Stream::NamedTls(ref ptr) => &ptr.options, Stream::NamedTls(ref ptr) => &ptr.options,
#[cfg(feature = "http")]
Stream::HttpRead(ref ptr) => &ptr.options, Stream::HttpRead(ref ptr) => &ptr.options,
Stream::HttpWrite(ref ptr) => &ptr.options, #[cfg(feature = "http")]
Stream::HttpWrite(ref ptr) => &ptr.options,
Stream::Null(ref options) => options, Stream::Null(ref options) => options,
Stream::Readline(ref ptr) => &ptr.options, Stream::Readline(ref ptr) => &ptr.options,
Stream::StandardOutput(ref ptr) => &ptr.options, Stream::StandardOutput(ref ptr) => &ptr.options,
@@ -612,8 +638,11 @@ impl Stream {
Stream::OutputFile(ref mut ptr) => &mut ptr.options, Stream::OutputFile(ref mut ptr) => &mut ptr.options,
Stream::StaticString(ref mut ptr) => &mut ptr.options, Stream::StaticString(ref mut ptr) => &mut ptr.options,
Stream::NamedTcp(ref mut ptr) => &mut ptr.options, Stream::NamedTcp(ref mut ptr) => &mut ptr.options,
#[cfg(feature = "tls")]
Stream::NamedTls(ref mut ptr) => &mut ptr.options, Stream::NamedTls(ref mut ptr) => &mut ptr.options,
#[cfg(feature = "http")]
Stream::HttpRead(ref mut ptr) => &mut ptr.options, Stream::HttpRead(ref mut ptr) => &mut ptr.options,
#[cfg(feature = "http")]
Stream::HttpWrite(ref mut ptr) => &mut ptr.options, Stream::HttpWrite(ref mut ptr) => &mut ptr.options,
Stream::Null(ref mut options) => options, Stream::Null(ref mut options) => options,
Stream::Readline(ref mut ptr) => &mut ptr.options, Stream::Readline(ref mut ptr) => &mut ptr.options,
@@ -630,8 +659,11 @@ impl Stream {
Stream::OutputFile(ptr) => ptr.lines_read += incr_num_lines_read, Stream::OutputFile(ptr) => ptr.lines_read += incr_num_lines_read,
Stream::StaticString(ptr) => ptr.lines_read += incr_num_lines_read, Stream::StaticString(ptr) => ptr.lines_read += incr_num_lines_read,
Stream::NamedTcp(ptr) => ptr.lines_read += incr_num_lines_read, Stream::NamedTcp(ptr) => ptr.lines_read += incr_num_lines_read,
#[cfg(feature = "tls")]
Stream::NamedTls(ptr) => ptr.lines_read += incr_num_lines_read, Stream::NamedTls(ptr) => ptr.lines_read += incr_num_lines_read,
#[cfg(feature = "http")]
Stream::HttpRead(ptr) => ptr.lines_read += incr_num_lines_read, Stream::HttpRead(ptr) => ptr.lines_read += incr_num_lines_read,
#[cfg(feature = "http")]
Stream::HttpWrite(_) => {} Stream::HttpWrite(_) => {}
Stream::Null(_) => {} Stream::Null(_) => {}
Stream::Readline(ptr) => ptr.lines_read += incr_num_lines_read, Stream::Readline(ptr) => ptr.lines_read += incr_num_lines_read,
@@ -648,8 +680,11 @@ impl Stream {
Stream::OutputFile(ptr) => ptr.lines_read = value, Stream::OutputFile(ptr) => ptr.lines_read = value,
Stream::StaticString(ptr) => ptr.lines_read = value, Stream::StaticString(ptr) => ptr.lines_read = value,
Stream::NamedTcp(ptr) => ptr.lines_read = value, Stream::NamedTcp(ptr) => ptr.lines_read = value,
#[cfg(feature = "tls")]
Stream::NamedTls(ptr) => ptr.lines_read = value, Stream::NamedTls(ptr) => ptr.lines_read = value,
#[cfg(feature = "http")]
Stream::HttpRead(ptr) => ptr.lines_read = value, Stream::HttpRead(ptr) => ptr.lines_read = value,
#[cfg(feature = "http")]
Stream::HttpWrite(_) => {} Stream::HttpWrite(_) => {}
Stream::Null(_) => {} Stream::Null(_) => {}
Stream::Readline(ptr) => ptr.lines_read = value, Stream::Readline(ptr) => ptr.lines_read = value,
@@ -666,8 +701,11 @@ impl Stream {
Stream::OutputFile(ptr) => ptr.lines_read, Stream::OutputFile(ptr) => ptr.lines_read,
Stream::StaticString(ptr) => ptr.lines_read, Stream::StaticString(ptr) => ptr.lines_read,
Stream::NamedTcp(ptr) => ptr.lines_read, Stream::NamedTcp(ptr) => ptr.lines_read,
#[cfg(feature = "tls")]
Stream::NamedTls(ptr) => ptr.lines_read, Stream::NamedTls(ptr) => ptr.lines_read,
#[cfg(feature = "http")]
Stream::HttpRead(ptr) => ptr.lines_read, Stream::HttpRead(ptr) => ptr.lines_read,
#[cfg(feature = "http")]
Stream::HttpWrite(_) => 0, Stream::HttpWrite(_) => 0,
Stream::Null(_) => 0, Stream::Null(_) => 0,
Stream::Readline(ptr) => ptr.lines_read, Stream::Readline(ptr) => ptr.lines_read,
@@ -682,15 +720,21 @@ impl CharRead for Stream {
match self { match self {
Stream::InputFile(file) => (*file).peek_char(), Stream::InputFile(file) => (*file).peek_char(),
Stream::NamedTcp(tcp_stream) => (*tcp_stream).peek_char(), Stream::NamedTcp(tcp_stream) => (*tcp_stream).peek_char(),
#[cfg(feature = "tls")]
Stream::NamedTls(tls_stream) => (*tls_stream).peek_char(), Stream::NamedTls(tls_stream) => (*tls_stream).peek_char(),
#[cfg(feature = "http")]
Stream::HttpRead(http_stream) => (*http_stream).peek_char(), Stream::HttpRead(http_stream) => (*http_stream).peek_char(),
Stream::Readline(rl_stream) => (*rl_stream).peek_char(), Stream::Readline(rl_stream) => (*rl_stream).peek_char(),
Stream::StaticString(src) => (*src).peek_char(), Stream::StaticString(src) => (*src).peek_char(),
Stream::Byte(cursor) => (*cursor).peek_char(), Stream::Byte(cursor) => (*cursor).peek_char(),
#[cfg(feature = "http")]
Stream::HttpWrite(_) => Some(Err(std::io::Error::new(
ErrorKind::PermissionDenied,
StreamError::ReadFromOutputStream,
))),
Stream::OutputFile(_) | Stream::OutputFile(_) |
Stream::StandardError(_) | Stream::StandardError(_) |
Stream::StandardOutput(_) | Stream::StandardOutput(_) |
Stream::HttpWrite(_) |
Stream::Null(_) => Some(Err(std::io::Error::new( Stream::Null(_) => Some(Err(std::io::Error::new(
ErrorKind::PermissionDenied, ErrorKind::PermissionDenied,
StreamError::ReadFromOutputStream, StreamError::ReadFromOutputStream,
@@ -702,15 +746,21 @@ impl CharRead for Stream {
match self { match self {
Stream::InputFile(file) => (*file).read_char(), Stream::InputFile(file) => (*file).read_char(),
Stream::NamedTcp(tcp_stream) => (*tcp_stream).read_char(), Stream::NamedTcp(tcp_stream) => (*tcp_stream).read_char(),
#[cfg(feature = "tls")]
Stream::NamedTls(tls_stream) => (*tls_stream).read_char(), Stream::NamedTls(tls_stream) => (*tls_stream).read_char(),
#[cfg(feature = "http")]
Stream::HttpRead(http_stream) => (*http_stream).read_char(), Stream::HttpRead(http_stream) => (*http_stream).read_char(),
Stream::Readline(rl_stream) => (*rl_stream).read_char(), Stream::Readline(rl_stream) => (*rl_stream).read_char(),
Stream::StaticString(src) => (*src).read_char(), Stream::StaticString(src) => (*src).read_char(),
Stream::Byte(cursor) => (*cursor).read_char(), Stream::Byte(cursor) => (*cursor).read_char(),
#[cfg(feature = "http")]
Stream::HttpWrite(_) => Some(Err(std::io::Error::new(
ErrorKind::PermissionDenied,
StreamError::ReadFromOutputStream,
))),
Stream::OutputFile(_) | Stream::OutputFile(_) |
Stream::StandardError(_) | Stream::StandardError(_) |
Stream::StandardOutput(_) | Stream::StandardOutput(_) |
Stream::HttpWrite(_) |
Stream::Null(_) => Some(Err(std::io::Error::new( Stream::Null(_) => Some(Err(std::io::Error::new(
ErrorKind::PermissionDenied, ErrorKind::PermissionDenied,
StreamError::ReadFromOutputStream, StreamError::ReadFromOutputStream,
@@ -722,15 +772,18 @@ impl CharRead for Stream {
match self { match self {
Stream::InputFile(file) => file.put_back_char(c), Stream::InputFile(file) => file.put_back_char(c),
Stream::NamedTcp(tcp_stream) => tcp_stream.put_back_char(c), Stream::NamedTcp(tcp_stream) => tcp_stream.put_back_char(c),
#[cfg(feature = "tls")]
Stream::NamedTls(tls_stream) => tls_stream.put_back_char(c), Stream::NamedTls(tls_stream) => tls_stream.put_back_char(c),
#[cfg(feature = "http")]
Stream::HttpRead(http_stream) => http_stream.put_back_char(c), Stream::HttpRead(http_stream) => http_stream.put_back_char(c),
Stream::Readline(rl_stream) => rl_stream.put_back_char(c), Stream::Readline(rl_stream) => rl_stream.put_back_char(c),
Stream::StaticString(src) => src.put_back_char(c), Stream::StaticString(src) => src.put_back_char(c),
Stream::Byte(cursor) => cursor.put_back_char(c), Stream::Byte(cursor) => cursor.put_back_char(c),
#[cfg(feature = "http")]
Stream::HttpWrite(_) => {}
Stream::OutputFile(_) | Stream::OutputFile(_) |
Stream::StandardError(_) | Stream::StandardError(_) |
Stream::StandardOutput(_) | Stream::StandardOutput(_) |
Stream::HttpWrite(_) |
Stream::Null(_) => {} Stream::Null(_) => {}
} }
} }
@@ -739,15 +792,18 @@ impl CharRead for Stream {
match self { match self {
Stream::InputFile(ref mut file) => file.consume(nread), Stream::InputFile(ref mut file) => file.consume(nread),
Stream::NamedTcp(ref mut tcp_stream) => tcp_stream.consume(nread), Stream::NamedTcp(ref mut tcp_stream) => tcp_stream.consume(nread),
#[cfg(feature = "tls")]
Stream::NamedTls(ref mut tls_stream) => tls_stream.consume(nread), Stream::NamedTls(ref mut tls_stream) => tls_stream.consume(nread),
#[cfg(feature = "http")]
Stream::HttpRead(ref mut http_stream) => http_stream.consume(nread), Stream::HttpRead(ref mut http_stream) => http_stream.consume(nread),
Stream::Readline(ref mut rl_stream) => rl_stream.consume(nread), Stream::Readline(ref mut rl_stream) => rl_stream.consume(nread),
Stream::StaticString(ref mut src) => src.consume(nread), Stream::StaticString(ref mut src) => src.consume(nread),
Stream::Byte(ref mut cursor) => cursor.consume(nread), Stream::Byte(ref mut cursor) => cursor.consume(nread),
#[cfg(feature = "http")]
Stream::HttpWrite(_) => {}
Stream::OutputFile(_) | Stream::OutputFile(_) |
Stream::StandardError(_) | Stream::StandardError(_) |
Stream::StandardOutput(_) | Stream::StandardOutput(_) |
Stream::HttpWrite(_) |
Stream::Null(_) => {} Stream::Null(_) => {}
} }
} }
@@ -759,15 +815,21 @@ impl Read for Stream {
let bytes_read = match self { let bytes_read = match self {
Stream::InputFile(file) => (*file).read(buf), Stream::InputFile(file) => (*file).read(buf),
Stream::NamedTcp(tcp_stream) => (*tcp_stream).read(buf), Stream::NamedTcp(tcp_stream) => (*tcp_stream).read(buf),
#[cfg(feature = "tls")]
Stream::NamedTls(tls_stream) => (*tls_stream).read(buf), Stream::NamedTls(tls_stream) => (*tls_stream).read(buf),
#[cfg(feature = "http")]
Stream::HttpRead(http_stream) => (*http_stream).read(buf), Stream::HttpRead(http_stream) => (*http_stream).read(buf),
Stream::Readline(rl_stream) => (*rl_stream).read(buf), Stream::Readline(rl_stream) => (*rl_stream).read(buf),
Stream::StaticString(src) => (*src).read(buf), Stream::StaticString(src) => (*src).read(buf),
Stream::Byte(cursor) => (*cursor).read(buf), Stream::Byte(cursor) => (*cursor).read(buf),
#[cfg(feature = "http")]
Stream::HttpWrite(_) => Err(std::io::Error::new(
ErrorKind::PermissionDenied,
StreamError::ReadFromOutputStream,
)),
Stream::OutputFile(_) Stream::OutputFile(_)
| Stream::StandardError(_) | Stream::StandardError(_)
| Stream::StandardOutput(_) | Stream::StandardOutput(_)
| Stream::HttpWrite(_)
| Stream::Null(_) => Err(std::io::Error::new( | Stream::Null(_) => Err(std::io::Error::new(
ErrorKind::PermissionDenied, ErrorKind::PermissionDenied,
StreamError::ReadFromOutputStream, StreamError::ReadFromOutputStream,
@@ -783,12 +845,18 @@ impl Write for Stream {
match self { match self {
Stream::OutputFile(ref mut file) => file.write(buf), Stream::OutputFile(ref mut file) => file.write(buf),
Stream::NamedTcp(ref mut tcp_stream) => tcp_stream.get_mut().write(buf), Stream::NamedTcp(ref mut tcp_stream) => tcp_stream.get_mut().write(buf),
#[cfg(feature = "tls")]
Stream::NamedTls(ref mut tls_stream) => tls_stream.get_mut().write(buf), Stream::NamedTls(ref mut tls_stream) => tls_stream.get_mut().write(buf),
Stream::Byte(ref mut cursor) => cursor.get_mut().write(buf), Stream::Byte(ref mut cursor) => cursor.get_mut().write(buf),
Stream::StandardOutput(stream) => stream.write(buf), Stream::StandardOutput(stream) => stream.write(buf),
Stream::StandardError(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),
Stream::HttpRead(_) | #[cfg(feature = "http")]
Stream::HttpRead(_) => Err(std::io::Error::new(
ErrorKind::PermissionDenied,
StreamError::WriteToInputStream,
)),
Stream::StaticString(_) | Stream::StaticString(_) |
Stream::Readline(_) | Stream::Readline(_) |
Stream::InputFile(..) | Stream::InputFile(..) |
@@ -803,12 +871,18 @@ impl Write for Stream {
match self { match self {
Stream::OutputFile(ref mut file) => file.stream.flush(), Stream::OutputFile(ref mut file) => file.stream.flush(),
Stream::NamedTcp(ref mut tcp_stream) => tcp_stream.stream.get_mut().flush(), Stream::NamedTcp(ref mut tcp_stream) => tcp_stream.stream.get_mut().flush(),
#[cfg(feature = "tls")]
Stream::NamedTls(ref mut tls_stream) => tls_stream.stream.get_mut().flush(), Stream::NamedTls(ref mut tls_stream) => tls_stream.stream.get_mut().flush(),
Stream::Byte(ref mut cursor) => cursor.stream.get_mut().flush(), Stream::Byte(ref mut cursor) => cursor.stream.get_mut().flush(),
Stream::StandardError(stream) => stream.stream.flush(), Stream::StandardError(stream) => stream.stream.flush(),
Stream::StandardOutput(stream) => stream.stream.flush(), Stream::StandardOutput(stream) => stream.stream.flush(),
#[cfg(feature = "http")]
Stream::HttpWrite(ref mut stream) => stream.stream.get_mut().flush(), Stream::HttpWrite(ref mut stream) => stream.stream.get_mut().flush(),
Stream::HttpRead(_) | #[cfg(feature = "http")]
Stream::HttpRead(_) => Err(std::io::Error::new(
ErrorKind::PermissionDenied,
StreamError::FlushToInputStream,
)),
Stream::StaticString(_) | Stream::StaticString(_) |
Stream::Readline(_) | Stream::Readline(_) |
Stream::InputFile(_) | Stream::InputFile(_) |
@@ -913,7 +987,12 @@ impl Stream {
Stream::InputFile(file_stream) => { Stream::InputFile(file_stream) => {
file_stream.position() file_stream.position()
} }
Stream::NamedTcp(..) | Stream::NamedTls(..) | Stream::Readline(..) => { #[cfg(feature = "tls")]
Stream::NamedTls(..) => {
Some(0)
}
Stream::NamedTcp(..)
| Stream::Readline(..) => {
Some(0) Some(0)
} }
_ => None, _ => None,
@@ -951,8 +1030,11 @@ impl Stream {
Stream::OutputFile(stream) => stream.past_end_of_stream, Stream::OutputFile(stream) => stream.past_end_of_stream,
Stream::StaticString(stream) => stream.past_end_of_stream, Stream::StaticString(stream) => stream.past_end_of_stream,
Stream::NamedTcp(stream) => stream.past_end_of_stream, Stream::NamedTcp(stream) => stream.past_end_of_stream,
#[cfg(feature = "tls")]
Stream::NamedTls(stream) => stream.past_end_of_stream, Stream::NamedTls(stream) => stream.past_end_of_stream,
#[cfg(feature = "http")]
Stream::HttpRead(stream) => stream.past_end_of_stream, Stream::HttpRead(stream) => stream.past_end_of_stream,
#[cfg(feature = "http")]
Stream::HttpWrite(stream) => stream.past_end_of_stream, Stream::HttpWrite(stream) => stream.past_end_of_stream,
Stream::Null(_) => false, Stream::Null(_) => false,
Stream::Readline(stream) => stream.past_end_of_stream, Stream::Readline(stream) => stream.past_end_of_stream,
@@ -974,8 +1056,11 @@ impl Stream {
Stream::OutputFile(stream) => stream.past_end_of_stream = value, Stream::OutputFile(stream) => stream.past_end_of_stream = value,
Stream::StaticString(stream) => stream.past_end_of_stream = value, Stream::StaticString(stream) => stream.past_end_of_stream = value,
Stream::NamedTcp(stream) => stream.past_end_of_stream = value, Stream::NamedTcp(stream) => stream.past_end_of_stream = value,
#[cfg(feature = "tls")]
Stream::NamedTls(stream) => stream.past_end_of_stream = value, Stream::NamedTls(stream) => stream.past_end_of_stream = value,
#[cfg(feature = "http")]
Stream::HttpRead(stream) => stream.past_end_of_stream = value, Stream::HttpRead(stream) => stream.past_end_of_stream = value,
#[cfg(feature = "http")]
Stream::HttpWrite(stream) => stream.past_end_of_stream = value, Stream::HttpWrite(stream) => stream.past_end_of_stream = value,
Stream::Null(_) => {} Stream::Null(_) => {}
Stream::Readline(stream) => stream.past_end_of_stream = value, Stream::Readline(stream) => stream.past_end_of_stream = value,
@@ -1054,6 +1139,7 @@ impl Stream {
Stream::InputFile(file) => Some(file.stream.get_ref().file_name), Stream::InputFile(file) => Some(file.stream.get_ref().file_name),
Stream::OutputFile(file) => Some(file.stream.file_name), Stream::OutputFile(file) => Some(file.stream.file_name),
Stream::NamedTcp(tcp) => Some(tcp.stream.get_ref().address), Stream::NamedTcp(tcp) => Some(tcp.stream.get_ref().address),
#[cfg(feature = "tls")]
Stream::NamedTls(tls) => Some(tls.stream.get_ref().address), Stream::NamedTls(tls) => Some(tls.stream.get_ref().address),
_ => None, _ => None,
} }
@@ -1062,14 +1148,19 @@ impl Stream {
#[inline] #[inline]
pub(crate) fn mode(&self) -> Atom { pub(crate) fn mode(&self) -> Atom {
match self { match self {
#[cfg(feature = "http")]
Stream::HttpRead(_) => atom!("read"),
#[cfg(feature = "tls")]
Stream::NamedTls(..) => atom!("read_append"),
Stream::Byte(_) Stream::Byte(_)
| Stream::Readline(_) | Stream::Readline(_)
| Stream::StaticString(_) | Stream::StaticString(_)
| Stream::HttpRead(_)
| Stream::InputFile(..) => atom!("read"), | Stream::InputFile(..) => atom!("read"),
Stream::NamedTcp(..) | Stream::NamedTls(..) => atom!("read_append"), Stream::NamedTcp(..) => atom!("read_append"),
Stream::OutputFile(file) if file.is_append => atom!("append"), Stream::OutputFile(file) if file.is_append => atom!("append"),
Stream::OutputFile(_) | Stream::StandardError(_) | Stream::StandardOutput(_) | Stream::HttpWrite(_) => atom!("write"), #[cfg(feature = "http")]
Stream::HttpWrite(_) => atom!("write"),
Stream::OutputFile(_) | Stream::StandardError(_) | Stream::StandardOutput(_) => atom!("write"),
Stream::Null(_) => atom!(""), Stream::Null(_) => atom!(""),
} }
} }
@@ -1108,6 +1199,7 @@ impl Stream {
)) ))
} }
#[cfg(feature = "tls")]
#[inline] #[inline]
pub(crate) fn from_tls_stream( pub(crate) fn from_tls_stream(
address: Atom, address: Atom,
@@ -1123,6 +1215,7 @@ impl Stream {
)) ))
} }
#[cfg(feature = "http")]
#[inline] #[inline]
pub(crate) fn from_http_stream( pub(crate) fn from_http_stream(
url: Atom, url: Atom,
@@ -1138,6 +1231,7 @@ impl Stream {
)) ))
} }
#[cfg(feature = "http")]
#[inline] #[inline]
pub(crate) fn from_http_sender( pub(crate) fn from_http_sender(
response: TypedArenaPtr<HttpResponse>, response: TypedArenaPtr<HttpResponse>,
@@ -1189,9 +1283,11 @@ impl Stream {
Stream::NamedTcp(ref mut tcp_stream) => { Stream::NamedTcp(ref mut tcp_stream) => {
tcp_stream.inner_mut().tcp_stream.shutdown(Shutdown::Both) tcp_stream.inner_mut().tcp_stream.shutdown(Shutdown::Both)
}, },
#[cfg(feature = "tls")]
Stream::NamedTls(ref mut tls_stream) => { Stream::NamedTls(ref mut tls_stream) => {
tls_stream.inner_mut().tls_stream.shutdown() tls_stream.inner_mut().tls_stream.shutdown()
} }
#[cfg(feature = "http")]
Stream::HttpRead(ref mut http_stream) => { Stream::HttpRead(ref mut http_stream) => {
unsafe { unsafe {
http_stream.set_tag(ArenaHeaderTag::Dropped); http_stream.set_tag(ArenaHeaderTag::Dropped);
@@ -1200,7 +1296,8 @@ impl Stream {
Ok(()) Ok(())
} }
Stream::HttpWrite(ref mut http_stream) => { #[cfg(feature = "http")]
Stream::HttpWrite(ref mut http_stream) => {
unsafe { unsafe {
http_stream.set_tag(ArenaHeaderTag::Dropped); http_stream.set_tag(ArenaHeaderTag::Dropped);
std::ptr::drop_in_place(&mut http_stream.inner_mut().buffer as *mut _); std::ptr::drop_in_place(&mut http_stream.inner_mut().buffer as *mut _);
@@ -1242,9 +1339,11 @@ impl Stream {
#[inline] #[inline]
pub(crate) fn is_input_stream(&self) -> bool { pub(crate) fn is_input_stream(&self) -> bool {
match self { match self {
#[cfg(feature = "tls")]
Stream::NamedTls(..) => true,
#[cfg(feature = "http")]
Stream::HttpRead(..) => true,
Stream::NamedTcp(..) Stream::NamedTcp(..)
| Stream::NamedTls(..)
| Stream::HttpRead(..)
| Stream::Byte(_) | Stream::Byte(_)
| Stream::Readline(_) | Stream::Readline(_)
| Stream::StaticString(_) | Stream::StaticString(_)
@@ -1256,11 +1355,13 @@ impl Stream {
#[inline] #[inline]
pub(crate) fn is_output_stream(&self) -> bool { pub(crate) fn is_output_stream(&self) -> bool {
match self { match self {
#[cfg(feature = "tls")]
Stream::NamedTls(..) => true,
#[cfg(feature = "http")]
Stream::HttpWrite(..) => true,
Stream::StandardError(_) Stream::StandardError(_)
| Stream::StandardOutput(_) | Stream::StandardOutput(_)
| Stream::NamedTcp(..) | Stream::NamedTcp(..)
| Stream::NamedTls(..)
| Stream::HttpWrite(..)
| Stream::Byte(_) | Stream::Byte(_)
| Stream::OutputFile(..) => true, | Stream::OutputFile(..) => true,
_ => false, _ => false,

View File

@@ -7,9 +7,11 @@ use lazy_static::lazy_static;
use crate::arena::*; use crate::arena::*;
use crate::atom_table::*; use crate::atom_table::*;
use crate::forms::*; use crate::forms::*;
#[cfg(feature = "ffi")]
use crate::ffi::*; use crate::ffi::*;
use crate::heap_iter::*; use crate::heap_iter::*;
use crate::heap_print::*; use crate::heap_print::*;
#[cfg(feature = "http")]
use crate::http::{HttpService, HttpListener, HttpResponse}; use crate::http::{HttpService, HttpListener, HttpResponse};
use crate::instructions::*; use crate::instructions::*;
use crate::machine; use crate::machine;
@@ -44,6 +46,7 @@ use std::cmp::Ordering;
use std::collections::BTreeSet; use std::collections::BTreeSet;
use std::convert::TryFrom; use std::convert::TryFrom;
use std::env; use std::env;
#[cfg(feature = "ffi")]
use std::ffi::CString; use std::ffi::CString;
use std::fs; use std::fs;
use std::hash::{BuildHasher, BuildHasherDefault}; use std::hash::{BuildHasher, BuildHasherDefault};
@@ -57,10 +60,13 @@ use std::process;
use std::str::FromStr; use std::str::FromStr;
use chrono::{offset::Local, DateTime}; use chrono::{offset::Local, DateTime};
#[cfg(not(target_os = "wasi"))]
use cpu_time::ProcessTime; use cpu_time::ProcessTime;
use std::time::{Duration, SystemTime}; use std::time::{Duration, SystemTime};
#[cfg(feature = "repl")]
use crossterm::event::{read, Event, KeyCode, KeyEvent, KeyModifiers}; use crossterm::event::{read, Event, KeyCode, KeyEvent, KeyModifiers};
#[cfg(feature = "repl")]
use crossterm::terminal::{disable_raw_mode, enable_raw_mode}; use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use blake2::{Blake2b, Blake2s}; use blake2::{Blake2b, Blake2s};
@@ -72,24 +78,28 @@ use ring::{
use ripemd160::{Digest, Ripemd160}; use ripemd160::{Digest, Ripemd160};
use sha3::{Sha3_224, Sha3_256, Sha3_384, Sha3_512}; use sha3::{Sha3_224, Sha3_256, Sha3_384, Sha3_512};
use crrl::secp256k1; use crrl::{secp256k1, x25519};
use sodiumoxide::crypto::scalarmult::curve25519::*;
#[cfg(feature = "tls")]
use native_tls::{TlsConnector,TlsAcceptor,Identity}; use native_tls::{TlsConnector,TlsAcceptor,Identity};
use base64; use base64;
use roxmltree; use roxmltree;
use select; use select;
#[cfg(feature = "http")]
use hyper::server::conn::http1; use hyper::server::conn::http1;
#[cfg(feature = "http")]
use hyper::header::{HeaderValue, HeaderName}; use hyper::header::{HeaderValue, HeaderName};
#[cfg(feature = "http")]
use hyper::{HeaderMap, Method}; use hyper::{HeaderMap, Method};
use http_body_util::BodyExt; use http_body_util::BodyExt;
use bytes::Buf; use bytes::Buf;
#[cfg(feature = "http")]
use reqwest::Url; use reqwest::Url;
use hyper_util::rt::TokioIo; use hyper_util::rt::TokioIo;
#[cfg(feature = "repl")]
pub(crate) fn get_key() -> KeyEvent { pub(crate) fn get_key() -> KeyEvent {
let key; let key;
enable_raw_mode().expect("failed to enable raw mode"); enable_raw_mode().expect("failed to enable raw mode");
@@ -744,7 +754,7 @@ impl MachineState {
}; };
if let Some(max_steps) = max_steps_n { if let Some(max_steps) = max_steps_n {
if max_steps.abs() as usize <= 1 << 63 { if max_steps.abs() as u64 <= 1 << 63 {
if max_steps >= 0 { if max_steps >= 0 {
max_old = max_steps; max_old = max_steps;
} else { } else {
@@ -979,7 +989,7 @@ impl MachineState {
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 chunk = self.store(self.deref(chunk));
let s = chunk.get_value(); let s = chunk.get_value() as usize;
let arity = cell_as_atom_cell!(self.heap[s]).get_arity(); let arity = cell_as_atom_cell!(self.heap[s]).get_arity();
let num_cells = arity - 1; let num_cells = arity - 1;
@@ -1160,7 +1170,7 @@ impl Machine {
let attr_var = self.deref_register(1); let attr_var = self.deref_register(1);
if let HeapCellValueTag::AttrVar = attr_var.get_tag() { if let HeapCellValueTag::AttrVar = attr_var.get_tag() {
let attr_var_loc = attr_var.get_value(); 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.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)));
} }
@@ -1346,7 +1356,7 @@ impl Machine {
} else { } else {
if is_internal_call { if is_internal_call {
debug_assert_eq!(goal.get_tag(), HeapCellValueTag::Str); debug_assert_eq!(goal.get_tag(), HeapCellValueTag::Str);
goal = self.machine_st.heap[goal.get_value()+1]; goal = self.machine_st.heap[goal.get_value() as usize+1];
(module_name, goal) = self.machine_st.strip_module(goal, module_name); (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) {
@@ -1576,7 +1586,7 @@ impl Machine {
); );
if HeapCellValueTag::Str == qualified_goal.get_tag() { if HeapCellValueTag::Str == qualified_goal.get_tag() {
let s = qualified_goal.get_value(); let s = qualified_goal.get_value() as usize;
let (name, arity) = cell_as_atom_cell!(self.machine_st.heap[s]) let (name, arity) = cell_as_atom_cell!(self.machine_st.heap[s])
.get_name_and_arity(); .get_name_and_arity();
@@ -1767,6 +1777,7 @@ impl Machine {
#[inline(always)] #[inline(always)]
pub(crate) fn current_hostname(&mut self) { pub(crate) fn current_hostname(&mut self) {
#[cfg(feature = "hostname")]
match hostname::get().ok() { match hostname::get().ok() {
Some(host) => match host.to_str() { Some(host) => match host.to_str() {
Some(host) => { Some(host) => {
@@ -3682,6 +3693,7 @@ impl Machine {
Ok(()) Ok(())
} }
#[cfg(feature = "repl")]
#[inline(always)] #[inline(always)]
pub(crate) fn get_single_char(&mut self) -> CallResult { pub(crate) fn get_single_char(&mut self) -> CallResult {
let ctrl_c = KeyEvent { let ctrl_c = KeyEvent {
@@ -3705,7 +3717,28 @@ impl Machine {
KeyCode::Char(c) => c, KeyCode::Char(c) => c,
_ => unreachable!(), _ => unreachable!(),
}; };
let a1 = self.deref_register(1);
self.machine_st.unify_char(
c,
a1,
);
Ok(())
}
#[cfg(not(feature = "repl"))]
#[inline(always)]
pub(crate) fn get_single_char(&mut self) -> CallResult {
let mut buffer = [0; 1];
// is there a better way?
if std::io::stdin().read(&mut buffer).is_err() {
let stub = functor_stub(atom!("get_single_char"), 1);
let err = self.machine_st.interrupt_error();
let err = self.machine_st.error_form(err, stub);
return Err(err);
}
let c = buffer[0] as char;
let a1 = self.deref_register(1); let a1 = self.deref_register(1);
self.machine_st.unify_char( self.machine_st.unify_char(
c, c,
@@ -4161,6 +4194,7 @@ impl Machine {
self.machine_st.fail = result; self.machine_st.fail = result;
} }
#[cfg(not(target_os = "wasi"))]
#[inline(always)] #[inline(always)]
pub(crate) fn cpu_now(&mut self) { pub(crate) fn cpu_now(&mut self) {
let secs = ProcessTime::now().as_duration().as_secs_f64(); let secs = ProcessTime::now().as_duration().as_secs_f64();
@@ -4169,6 +4203,12 @@ impl Machine {
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")]
#[inline(always)]
pub(crate) fn cpu_now(&mut self) {
// TODO
}
#[inline(always)] #[inline(always)]
pub(crate) fn det_length_rundown(&mut self) -> CallResult { pub(crate) fn det_length_rundown(&mut self) -> CallResult {
let stub_gen = || functor_stub(atom!("length"), 2); let stub_gen = || functor_stub(atom!("length"), 2);
@@ -4201,6 +4241,7 @@ impl Machine {
Ok(()) Ok(())
} }
#[cfg(feature = "http")]
#[inline(always)] #[inline(always)]
pub(crate) fn http_open(&mut self) -> CallResult { pub(crate) fn http_open(&mut self) -> CallResult {
let address_sink = self.deref_register(1); let address_sink = self.deref_register(1);
@@ -4319,6 +4360,7 @@ impl Machine {
Ok(()) Ok(())
} }
#[cfg(feature = "http")]
#[inline(always)] #[inline(always)]
pub(crate) fn http_listen(&mut self) -> CallResult { pub(crate) fn http_listen(&mut self) -> CallResult {
let address_sink = self.deref_register(1); let address_sink = self.deref_register(1);
@@ -4371,6 +4413,7 @@ impl Machine {
Ok(()) Ok(())
} }
#[cfg(feature = "http")]
#[inline(always)] #[inline(always)]
pub(crate) fn http_accept(&mut self) -> CallResult { pub(crate) fn http_accept(&mut self) -> CallResult {
let culprit = self.deref_register(1); let culprit = self.deref_register(1);
@@ -4455,6 +4498,7 @@ impl Machine {
Ok(()) Ok(())
} }
#[cfg(feature = "http")]
#[inline(always)] #[inline(always)]
pub(crate) fn http_answer(&mut self) -> CallResult { pub(crate) fn http_answer(&mut self) -> CallResult {
let culprit = self.deref_register(1); let culprit = self.deref_register(1);
@@ -4521,6 +4565,7 @@ impl Machine {
Ok(()) Ok(())
} }
#[cfg(feature = "ffi")]
#[inline(always)] #[inline(always)]
pub(crate) fn load_foreign_lib(&mut self) -> CallResult { pub(crate) fn load_foreign_lib(&mut self) -> CallResult {
let library_name = self.deref_register(1); let library_name = self.deref_register(1);
@@ -4567,6 +4612,7 @@ impl Machine {
Ok(()) Ok(())
} }
#[cfg(feature = "ffi")]
#[inline(always)] #[inline(always)]
pub(crate) fn foreign_call(&mut self) -> CallResult { pub(crate) fn foreign_call(&mut self) -> CallResult {
let function_name = self.deref_register(1); let function_name = self.deref_register(1);
@@ -4642,6 +4688,7 @@ impl Machine {
Ok(()) Ok(())
} }
#[cfg(feature = "ffi")]
fn build_struct(&mut self, name: &str, mut args: Vec<Value>) -> HeapCellValue { fn build_struct(&mut self, name: &str, mut args: Vec<Value>) -> HeapCellValue {
args.insert(0, Value::CString(CString::new(name).unwrap())); args.insert(0, Value::CString(CString::new(name).unwrap()));
let cells: Vec<_> = args.into_iter() let cells: Vec<_> = args.into_iter()
@@ -4662,6 +4709,7 @@ impl Machine {
) )
} }
#[cfg(feature = "ffi")]
#[inline(always)] #[inline(always)]
pub(crate) fn define_foreign_struct(&mut self) -> CallResult { pub(crate) fn define_foreign_struct(&mut self) -> CallResult {
let struct_name = self.deref_register(1); let struct_name = self.deref_register(1);
@@ -4854,7 +4902,7 @@ impl Machine {
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]; let list_head = self.machine_st.heap[match_site];
if list_head.get_value() == match_site { if list_head.get_value() as usize == match_site {
// at the end of the list, no match found in this case. // at the end of the list, no match found in this case.
self.machine_st.fail = true; self.machine_st.fail = true;
} else { } else {
@@ -4927,7 +4975,7 @@ impl Machine {
prev_tail prev_tail
} else { } else {
if self.machine_st.heap[match_site + 1].is_var() { if self.machine_st.heap[match_site + 1].is_var() {
let h = attr_var.get_value(); let h = attr_var.get_value() as usize;
self.machine_st.heap[h] = heap_loc_as_cell!(h); self.machine_st.heap[h] = heap_loc_as_cell!(h);
self.machine_st.trail(TrailRef::Ref(Ref::attr_var(h))); self.machine_st.trail(TrailRef::Ref(Ref::attr_var(h)));
@@ -5002,13 +5050,13 @@ impl Machine {
} }
MatchSite::Match(match_site) => { MatchSite::Match(match_site) => {
let l = self.machine_st.heap[match_site].get_value(); let l = self.machine_st.heap[match_site].get_value();
self.machine_st.heap[match_site].set_value(h); self.machine_st.heap[match_site].set_value(h as u64);
(match_site, l) (match_site, l)
} }
}; };
self.machine_st.trail(TrailRef::AttrVarListLink(match_site, l)); self.machine_st.trail(TrailRef::AttrVarListLink(match_site, l as usize));
} }
None => { None => {
// the list is empty. // the list is empty.
@@ -5038,7 +5086,7 @@ impl Machine {
let mut prev_tail = None; let mut prev_tail = None;
while let HeapCellValueTag::Lis = attrs_list.get_tag() { while let HeapCellValueTag::Lis = attrs_list.get_tag() {
let mut list_head = self.machine_st.heap[attrs_list.get_value()]; let mut list_head = self.machine_st.heap[attrs_list.get_value() as usize];
loop { loop {
read_heap_cell!(list_head, read_heap_cell!(list_head,
@@ -5058,7 +5106,7 @@ impl Machine {
if module == module_loc && name == t_name && arity == t_arity { if module == module_loc && name == t_name && arity == t_arity {
return Some(AttrListMatch { return Some(AttrListMatch {
match_site: MatchSite::Match(attrs_list.get_value()), match_site: MatchSite::Match(attrs_list.get_value() as usize),
prev_tail, prev_tail,
}); });
} }
@@ -5071,7 +5119,7 @@ impl Machine {
); );
} }
let tail_loc = attrs_list.get_value() + 1; let tail_loc = attrs_list.get_value() as usize + 1;
prev_tail = Some(tail_loc); prev_tail = Some(tail_loc);
// do the work of self.store(self.deref(...)) but inline it // do the work of self.store(self.deref(...)) but inline it
@@ -5416,7 +5464,7 @@ impl Machine {
let value = self.deref_register(2); let value = self.deref_register(2);
debug_assert_eq!(HeapCellValueTag::AttrVar, var.get_tag()); debug_assert_eq!(HeapCellValueTag::AttrVar, var.get_tag());
self.machine_st.heap[var.get_value()] = value; self.machine_st.heap[var.get_value() as usize] = value;
} }
#[inline(always)] #[inline(always)]
@@ -6241,6 +6289,7 @@ impl Machine {
Ok(()) Ok(())
} }
#[cfg(feature = "tls")]
#[inline(always)] #[inline(always)]
pub(crate) fn tls_client_connect(&mut self) -> CallResult { 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]) {
@@ -6278,6 +6327,7 @@ impl Machine {
} }
} }
#[cfg(feature = "tls")]
#[inline(always)] #[inline(always)]
pub(crate) fn tls_accept_client(&mut self) -> CallResult { pub(crate) fn tls_accept_client(&mut self) -> CallResult {
let pkcs12 = self.string_encoding_bytes(self.machine_st.registers[1], atom!("octet")); let pkcs12 = self.string_encoding_bytes(self.machine_st.registers[1], atom!("octet"));
@@ -7304,13 +7354,11 @@ impl Machine {
pub(crate) fn curve25519_scalar_mult(&mut self) { pub(crate) fn curve25519_scalar_mult(&mut self) {
let stub1_gen = || functor_stub(atom!("curve25519_scalar_mult"), 3); 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 scalar = Scalar(<[u8; 32]>::try_from(&scalar_bytes[..]).unwrap());
let stub2_gen = || functor_stub(atom!("curve25519_scalar_mult"), 3); 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 point = GroupElement(<[u8; 32]>::try_from(&point_bytes[..]).unwrap());
let result = scalarmult(&scalar, &point).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[..]); let string = self.u8s_to_string(&result[..]);

View File

@@ -73,9 +73,9 @@ macro_rules! cell_as_string {
macro_rules! cell_as_atom { macro_rules! cell_as_atom {
($cell:expr) => {{ ($cell:expr) => {{
let cell = AtomCell::from_bytes($cell.into_bytes()); let cell = AtomCell::from_bytes($cell.into_bytes());
let name = cell.get_index() << 3; let name = (cell.get_index() as u64) << 3;
Atom::from(name as usize) Atom::from(name)
}}; }};
} }
@@ -87,14 +87,14 @@ macro_rules! cell_as_atom_cell {
macro_rules! cell_as_f64_ptr { macro_rules! cell_as_f64_ptr {
($cell:expr) => {{ ($cell:expr) => {{
let offset = $cell.get_value(); let offset = $cell.get_value() as usize;
F64Ptr::from_offset(offset) F64Ptr::from_offset(offset)
}}; }};
} }
macro_rules! cell_as_untyped_arena_ptr { macro_rules! cell_as_untyped_arena_ptr {
($cell:expr) => { ($cell:expr) => {
UntypedArenaPtr::from(u64::from($cell) as *const ArenaHeader) UntypedArenaPtr::from_bytes($cell.to_untyped_arena_ptr_bytes())
}; };
} }
@@ -173,7 +173,14 @@ macro_rules! attr_var_loc_as_cell {
macro_rules! typed_arena_ptr_as_cell { macro_rules! typed_arena_ptr_as_cell {
($ptr:expr) => { ($ptr:expr) => {
untyped_arena_ptr_as_cell!($ptr.header_ptr()) raw_ptr_as_cell!($ptr.header_ptr())
};
}
macro_rules! raw_ptr_as_cell {
($ptr:expr) => {
// Cell is 64-bit, but raw ptr is 32-bit in 32-bit systems
HeapCellValue::from_raw_ptr_bytes(unsafe { std::mem::transmute($ptr) })
}; };
} }
@@ -217,7 +224,7 @@ macro_rules! string_as_pstr_cell {
macro_rules! stream_as_cell { macro_rules! stream_as_cell {
($ptr:expr) => { ($ptr:expr) => {
untyped_arena_ptr_as_cell!($ptr.as_ptr()) raw_ptr_as_cell!($ptr.as_ptr())
}; };
} }
@@ -250,13 +257,15 @@ macro_rules! match_untyped_arena_ptr_pat_body {
#[allow(unused_braces)] #[allow(unused_braces)]
$code $code
}}; }};
($cell:ident, OssifiedOpDir, $n:ident, $code:expr) => {{ ($ptr:ident, OssifiedOpDir, $n:ident, $code:expr) => {{
let $n = cell_as_ossified_op_dir!($cell); let payload_ptr = unsafe { std::mem::transmute::<_, *mut OssifiedOpDir>($ptr.payload_offset()) };
let $n = TypedArenaPtr::new(payload_ptr);
#[allow(unused_braces)] #[allow(unused_braces)]
$code $code
}}; }};
($cell:ident, LiveLoadState, $n:ident, $code:expr) => {{ ($ptr:ident, LiveLoadState, $n:ident, $code:expr) => {{
let $n = cell_as_load_state_payload!($cell); let payload_ptr = unsafe { std::mem::transmute::<_, *mut LiveLoadState>($ptr.payload_offset()) };
let $n = TypedArenaPtr::new(payload_ptr);
#[allow(unused_braces)] #[allow(unused_braces)]
$code $code
}}; }};

View File

@@ -10,14 +10,19 @@ use crate::machine::machine_indices::*;
use crate::machine::machine_state::MachineState; use crate::machine::machine_state::MachineState;
use crate::machine::streams::*; use crate::machine::streams::*;
use crate::parser::char_reader::*; use crate::parser::char_reader::*;
#[cfg(feature = "repl")]
use crate::repl_helper::Helper; use crate::repl_helper::Helper;
use crate::types::*; use crate::types::*;
use fxhash::FxBuildHasher; use fxhash::FxBuildHasher;
use indexmap::IndexSet; use indexmap::IndexSet;
#[cfg(feature = "repl")]
use rustyline::error::ReadlineError; use rustyline::error::ReadlineError;
#[cfg(feature = "repl")]
use rustyline::history::DefaultHistory; use rustyline::history::DefaultHistory;
#[cfg(feature = "repl")]
use rustyline::{Config, Editor}; use rustyline::{Config, Editor};
use std::collections::VecDeque; use std::collections::VecDeque;
@@ -102,12 +107,14 @@ fn get_prompt() -> &'static str {
#[derive(Debug)] #[derive(Debug)]
pub struct ReadlineStream { pub struct ReadlineStream {
#[cfg(feature = "repl")]
rl: Editor<Helper, DefaultHistory>, rl: Editor<Helper, DefaultHistory>,
pending_input: CharReader<Cursor<String>>, pending_input: CharReader<Cursor<String>>,
add_history: bool, add_history: bool,
} }
impl ReadlineStream { impl ReadlineStream {
#[cfg(feature = "repl")]
#[inline] #[inline]
pub fn new(pending_input: &str, add_history: bool) -> Self { pub fn new(pending_input: &str, add_history: bool) -> Self {
let config = Config::builder() let config = Config::builder()
@@ -133,11 +140,25 @@ impl ReadlineStream {
} }
} }
#[cfg(not(feature = "repl"))]
#[inline]
pub fn new(pending_input: &str, add_history: bool) -> Self {
ReadlineStream {
pending_input: CharReader::new(Cursor::new(pending_input.to_owned())),
add_history: add_history,
}
}
#[cfg(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>) {
let helper = self.rl.helper_mut().unwrap(); let helper = self.rl.helper_mut().unwrap();
helper.atoms = atoms; helper.atoms = atoms;
} }
#[cfg(not(feature = "repl"))]
pub fn set_atoms_for_completion(&mut self, atoms: *const IndexSet<Atom>) {
}
#[inline] #[inline]
pub fn reset(&mut self) { pub fn reset(&mut self) {
self.pending_input.reset_buffer(); self.pending_input.reset_buffer();
@@ -148,6 +169,7 @@ impl ReadlineStream {
pending_input.set_position(0); pending_input.set_position(0);
} }
#[cfg(feature = "repl")]
fn call_readline(&mut self) -> std::io::Result<usize> { fn call_readline(&mut self) -> std::io::Result<usize> {
match self.rl.readline(get_prompt()) { match self.rl.readline(get_prompt()) {
Ok(text) => { Ok(text) => {
@@ -175,6 +197,12 @@ impl ReadlineStream {
} }
} }
#[cfg(not(feature = "repl"))]
fn call_readline(&mut self) -> std::io::Result<usize> {
Ok(0)
}
#[cfg(feature = "repl")]
fn save_history(&mut self) { fn save_history(&mut self) {
if !self.add_history { if !self.add_history {
return; return;
@@ -191,6 +219,10 @@ impl ReadlineStream {
} }
} }
#[cfg(not(feature = "repl"))]
fn save_history(&mut self) {
}
#[inline] #[inline]
pub(crate) fn peek_byte(&mut self) -> std::io::Result<u8> { pub(crate) fn peek_byte(&mut self) -> std::io::Result<u8> {
let bytes = self.pending_input.refresh_buffer()?; let bytes = self.pending_input.refresh_buffer()?;

View File

@@ -88,6 +88,15 @@ impl ConsPtr {
.with_tag(tag) .with_tag(tag)
} }
#[cfg(target_pointer_width="32")]
#[inline(always)]
pub fn as_ptr(self) -> *mut u8 {
let bytes = self.into_bytes();
let raw_ptr_bytes = [bytes[1], bytes[2], bytes[3], bytes[4]];
unsafe { mem::transmute(raw_ptr_bytes) }
}
#[cfg(target_pointer_width="64")]
#[inline(always)] #[inline(always)]
pub fn as_ptr(self) -> *mut u8 { pub fn as_ptr(self) -> *mut u8 {
self.ptr() as *mut _ self.ptr() as *mut _
@@ -444,7 +453,7 @@ impl HeapCellValue {
pub fn is_compound(self, heap: &[HeapCellValue]) -> bool { pub fn is_compound(self, heap: &[HeapCellValue]) -> bool {
match self.get_tag() { match self.get_tag() {
HeapCellValueTag::Str => { HeapCellValueTag::Str => {
cell_as_atom_cell!(heap[self.get_value()]).get_arity() > 0 cell_as_atom_cell!(heap[self.get_value() as usize]).get_arity() > 0
} }
HeapCellValueTag::Lis | HeapCellValueTag::Lis |
HeapCellValueTag::CStr | HeapCellValueTag::CStr |
@@ -491,13 +500,13 @@ impl HeapCellValue {
} }
#[inline] #[inline]
pub fn get_value(self) -> usize { pub fn get_value(self) -> u64 {
self.val() as usize self.val() as u64
} }
#[inline] #[inline]
pub fn set_value(&mut self, val: usize) { pub fn set_value(&mut self, val: u64) {
self.set_val(val as u64); self.set_val(val);
} }
#[inline] #[inline]
@@ -513,7 +522,7 @@ impl HeapCellValue {
#[inline] #[inline]
pub fn to_atom(self) -> Option<Atom> { pub fn to_atom(self) -> Option<Atom> {
match self.tag() { match self.tag() {
HeapCellValueTag::Atom => Some(Atom::from((self.val() << 3) as usize)), HeapCellValueTag::Atom => Some(Atom::from(self.val() << 3)),
_ => None, _ => None,
} }
} }
@@ -522,7 +531,7 @@ impl HeapCellValue {
pub fn to_pstr(self) -> Option<PartialString> { pub fn to_pstr(self) -> Option<PartialString> {
match self.tag() { match self.tag() {
HeapCellValueTag::PStr => { HeapCellValueTag::PStr => {
Some(PartialString::from(Atom::from((self.val() as usize) << 3))) Some(PartialString::from(Atom::from(self.val() << 3)))
} }
_ => None, _ => None,
} }
@@ -536,10 +545,39 @@ impl HeapCellValue {
} }
} }
#[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")]
#[inline]
pub fn from_raw_ptr_bytes(ptr_bytes: [u8; 8]) -> Self {
HeapCellValue::from_bytes(ptr_bytes)
}
#[inline]
#[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")]
pub fn to_raw_ptr_bytes(self) -> [u8; 8] {
self.into_bytes()
}
#[inline]
pub fn to_untyped_arena_ptr_bytes(self) -> [u8; 8] {
self.into_bytes()
}
#[inline] #[inline]
pub fn to_untyped_arena_ptr(self) -> Option<UntypedArenaPtr> { pub fn to_untyped_arena_ptr(self) -> Option<UntypedArenaPtr> {
match self.tag() { match self.get_tag() {
HeapCellValueTag::Cons => Some(UntypedArenaPtr::from_bytes(self.into_bytes())), HeapCellValueTag::Cons => Some(UntypedArenaPtr::from_bytes(self.to_untyped_arena_ptr_bytes())),
_ => None, _ => None,
} }
} }
@@ -607,7 +645,7 @@ impl HeapCellValue {
Some(TermOrderCategory::Compound) Some(TermOrderCategory::Compound)
} }
HeapCellValueTag::Str => { HeapCellValueTag::Str => {
let value = heap[self.get_value()]; let value = heap[self.get_value() as usize];
let arity = cell_as_atom_cell!(value).get_arity(); let arity = cell_as_atom_cell!(value).get_arity();
if arity == 0 { if arity == 0 {
@@ -642,31 +680,39 @@ const_assert!(mem::size_of::<HeapCellValue>() == 8);
#[repr(u64)] #[repr(u64)]
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub struct UntypedArenaPtr { pub struct UntypedArenaPtr {
ptr: B61, #[allow(unused)] ptr: B61,
m: bool, 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)
}
}
const_assert!(mem::size_of::<UntypedArenaPtr>() == 8); const_assert!(mem::size_of::<UntypedArenaPtr>() == 8);
impl From<*const ArenaHeader> for UntypedArenaPtr { impl From<*const ArenaHeader> for UntypedArenaPtr {
#[inline] #[inline]
fn from(ptr: *const ArenaHeader) -> UntypedArenaPtr { fn from(ptr: *const ArenaHeader) -> UntypedArenaPtr {
unsafe { mem::transmute(ptr) } UntypedArenaPtr::build_with(ptr as usize)
} }
} }
impl From<*const IndexPtr> for UntypedArenaPtr { impl From<*const IndexPtr> for UntypedArenaPtr {
#[inline] #[inline]
fn from(ptr: *const IndexPtr) -> UntypedArenaPtr { fn from(ptr: *const IndexPtr) -> UntypedArenaPtr {
unsafe { mem::transmute(ptr) } UntypedArenaPtr::build_with(ptr as usize)
} }
} }
impl From<UntypedArenaPtr> for *const ArenaHeader { impl From<UntypedArenaPtr> for *const ArenaHeader {
#[inline] #[inline]
fn from(ptr: UntypedArenaPtr) -> *const ArenaHeader { fn from(ptr: UntypedArenaPtr) -> *const ArenaHeader {
unsafe { mem::transmute(ptr) } ptr.get_ptr() as *const ArenaHeader
} }
} }
@@ -676,15 +722,24 @@ impl UntypedArenaPtr {
self.set_m(m); self.set_m(m);
} }
#[cfg(target_pointer_width="32")]
#[inline] #[inline]
pub fn get_ptr(self) -> *const u8 { pub fn get_ptr(self) -> *const u8 {
self.ptr() as *const u8 let bytes = self.into_bytes();
let raw_ptr_bytes = [bytes[0], bytes[1], bytes[2], bytes[3]];
unsafe { mem::transmute(raw_ptr_bytes) }
}
#[cfg(target_pointer_width="64")]
#[inline]
pub fn get_ptr(self) -> *const u8 {
self.ptr() as *const u8
} }
#[inline] #[inline]
pub fn get_tag(self) -> ArenaHeaderTag { pub fn get_tag(self) -> ArenaHeaderTag {
unsafe { unsafe {
let header = *(self.ptr() as *const ArenaHeader); let header = *(self.get_ptr() as *const ArenaHeader);
header.get_tag() header.get_tag()
} }
} }
@@ -714,7 +769,7 @@ impl Add<usize> for HeapCellValue {
tag @ HeapCellValueTag::PStrLoc | tag @ HeapCellValueTag::PStrLoc |
tag @ HeapCellValueTag::Var | tag @ HeapCellValueTag::Var |
tag @ HeapCellValueTag::AttrVar => { tag @ HeapCellValueTag::AttrVar => {
HeapCellValue::build_with(tag, (self.get_value() + rhs) as u64) HeapCellValue::build_with(tag, (self.get_value() as usize + rhs) as u64)
} }
_ => { _ => {
self self
@@ -734,7 +789,7 @@ impl Sub<usize> for HeapCellValue {
tag @ HeapCellValueTag::PStrLoc | tag @ HeapCellValueTag::PStrLoc |
tag @ HeapCellValueTag::Var | tag @ HeapCellValueTag::Var |
tag @ HeapCellValueTag::AttrVar => { tag @ HeapCellValueTag::AttrVar => {
HeapCellValue::build_with(tag, (self.get_value() - rhs) as u64) HeapCellValue::build_with(tag, (self.get_value() as usize - rhs) as u64)
} }
_ => { _ => {
self self
@@ -762,7 +817,7 @@ impl Sub<i64> for HeapCellValue {
tag @ HeapCellValueTag::PStrLoc | tag @ HeapCellValueTag::PStrLoc |
tag @ HeapCellValueTag::Var | tag @ HeapCellValueTag::Var |
tag @ HeapCellValueTag::AttrVar => { tag @ HeapCellValueTag::AttrVar => {
HeapCellValue::build_with(tag, (self.get_value() + rhs.abs() as usize) as u64) HeapCellValue::build_with(tag, self.get_value() + rhs.abs() as u64)
} }
_ => { _ => {
self self