diff --git a/README.md b/README.md index 66f5cb82..d421bfa0 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ programming, which is itself written in a high-level language. Produce an implementation of the Warren Abstract Machine in Rust, done according to the progression of languages in [Warren's Abstract Machine: A Tutorial -Reconstruction](http://wambook.sourceforge.net/wambook.pdf). +Reconstruction](https://github.com/mthom/scryer-prolog/blob/master/wambook/wambook.pdf). Phase 1 has been completed in that Scryer Prolog implements in some form all of the WAM book, including lists, cuts, Debray allocation, first diff --git a/build/instructions_template.rs b/build/instructions_template.rs index bc1ca703..e4904352 100644 --- a/build/instructions_template.rs +++ b/build/instructions_template.rs @@ -262,6 +262,8 @@ enum SystemClauseType { DeleteFile, #[strum_discriminants(strum(props(Arity = "2", Name = "$rename_file")))] RenameFile, + #[strum_discriminants(strum(props(Arity = "2", Name = "$file_copy")))] + FileCopy, #[strum_discriminants(strum(props(Arity = "2", Name = "$working_directory")))] WorkingDirectory, #[strum_discriminants(strum(props(Arity = "1", Name = "$delete_directory")))] @@ -296,8 +298,6 @@ enum SystemClauseType { GetCode, #[strum_discriminants(strum(props(Arity = "1", Name = "$get_single_char")))] GetSingleChar, - #[strum_discriminants(strum(props(Arity = "0", Name = "$reset_attr_var_state")))] - ResetAttrVarState, #[strum_discriminants(strum(props(Arity = "2", Name = "$truncate_if_no_lh_growth_diff")))] TruncateIfNoLiftedHeapGrowthDiff, #[strum_discriminants(strum(props(Arity = "1", Name = "$truncate_if_no_lh_growth")))] @@ -412,8 +412,6 @@ enum SystemClauseType { GetCurrentBlock, #[strum_discriminants(strum(props(Arity = "1", Name = "$get_cp")))] GetCutPoint, - #[strum_discriminants(strum(props(Arity = "1", Name = "$get_staggered_cp")))] - GetStaggeredCutPoint, #[strum_discriminants(strum(props(Arity = "1", Name = "$get_double_quotes")))] GetDoubleQuotes, #[strum_discriminants(strum(props(Arity = "1", Name = "$install_new_block")))] @@ -726,9 +724,9 @@ enum InstructionTemplate { Allocate(usize), // num_frames. #[strum_discriminants(strum(props(Arity = "0", Name = "deallocate")))] Deallocate, - #[strum_discriminants(strum(props(Arity = "3", Name = "jmp_by_call")))] + #[strum_discriminants(strum(props(Arity = "arity", Name = "jmp_by_call")))] JmpByCall(usize, usize), // arity, relative offset. - #[strum_discriminants(strum(props(Arity = "3", Name = "jmp_by_execute")))] + #[strum_discriminants(strum(props(Arity = "arity", Name = "jmp_by_execute")))] JmpByExecute(usize, usize), // arity, relative offset. #[strum_discriminants(strum(props(Arity = "1", Name = "rev_jmp_by")))] RevJmpBy(usize), @@ -1611,6 +1609,7 @@ fn generate_instruction_preface() -> TokenStream { &Instruction::CallMakeDirectoryPath(_) | &Instruction::CallDeleteFile(_) | &Instruction::CallRenameFile(_) | + &Instruction::CallFileCopy(_) | &Instruction::CallWorkingDirectory(_) | &Instruction::CallDeleteDirectory(_) | &Instruction::CallPathCanonical(_) | @@ -1630,7 +1629,6 @@ fn generate_instruction_preface() -> TokenStream { &Instruction::CallGetNChars(_) | &Instruction::CallGetCode(_) | &Instruction::CallGetSingleChar(_) | - &Instruction::CallResetAttrVarState(_) | &Instruction::CallTruncateIfNoLiftedHeapGrowthDiff(_) | &Instruction::CallTruncateIfNoLiftedHeapGrowth(_) | &Instruction::CallGetAttributedVariableList(_) | @@ -1688,7 +1686,6 @@ fn generate_instruction_preface() -> TokenStream { &Instruction::CallGetBall(_) | &Instruction::CallGetCurrentBlock(_) | &Instruction::CallGetCutPoint(_) | - &Instruction::CallGetStaggeredCutPoint(_) | &Instruction::CallGetDoubleQuotes(_) | &Instruction::CallInstallNewBlock(_) | &Instruction::CallMaybe(_) | @@ -1825,6 +1822,7 @@ fn generate_instruction_preface() -> TokenStream { &Instruction::ExecuteMakeDirectoryPath(_) | &Instruction::ExecuteDeleteFile(_) | &Instruction::ExecuteRenameFile(_) | + &Instruction::ExecuteFileCopy(_) | &Instruction::ExecuteWorkingDirectory(_) | &Instruction::ExecuteDeleteDirectory(_) | &Instruction::ExecutePathCanonical(_) | @@ -1844,7 +1842,6 @@ fn generate_instruction_preface() -> TokenStream { &Instruction::ExecuteGetNChars(_) | &Instruction::ExecuteGetCode(_) | &Instruction::ExecuteGetSingleChar(_) | - &Instruction::ExecuteResetAttrVarState(_) | &Instruction::ExecuteTruncateIfNoLiftedHeapGrowthDiff(_) | &Instruction::ExecuteTruncateIfNoLiftedHeapGrowth(_) | &Instruction::ExecuteGetAttributedVariableList(_) | @@ -1902,7 +1899,6 @@ fn generate_instruction_preface() -> TokenStream { &Instruction::ExecuteGetBall(_) | &Instruction::ExecuteGetCurrentBlock(_) | &Instruction::ExecuteGetCutPoint(_) | - &Instruction::ExecuteGetStaggeredCutPoint(_) | &Instruction::ExecuteGetDoubleQuotes(_) | &Instruction::ExecuteInstallNewBlock(_) | &Instruction::ExecuteMaybe(_) | diff --git a/src/lib/arithmetic.pl b/src/lib/arithmetic.pl index ee719a18..e557c90b 100644 --- a/src/lib/arithmetic.pl +++ b/src/lib/arithmetic.pl @@ -1,4 +1,4 @@ -:- module(arithmetic, [expmod/4, lsb/2, msb/2, number_to_rational/2, +:- module(arithmetic, [expmod/4, lcm/3, lsb/2, msb/2, number_to_rational/2, number_to_rational/3, popcount/2, rational_numerator_denominator/3]). @@ -28,6 +28,22 @@ expmod_(Base0, Expo0, Mod, C, R) :- Base is (Base0 * Base0) mod Mod, expmod_(Base, Expo, Mod, C, R). +%% lcm(+A, +B, -Lcm) is det. +% +% Calculates the Least common multiple for A and B: the smallest positive integer +% that is divisible by both A and B. +% +% A and B need to be integers. +lcm(A, B, X) :- + builtins:must_be_number(A, lcm/2), + builtins:must_be_number(B, lcm/2), + ( \+ integer(A) -> type_error(integer, A, lcm/2) + ; \+ integer(B) -> type_error(integer, B, lcm/2) + ; (A = 0, B = 0) -> X = 0 + ; builtins:can_be_number(X, lcm/2), + X is abs(B) // gcd(A,B) * abs(A) + ). + lsb(X, N) :- builtins:must_be_number(X, lsb/2), ( \+ integer(X) -> type_error(integer, X, lsb/2) diff --git a/src/lib/builtins.pl b/src/lib/builtins.pl index 89270f6f..aef9b32b 100644 --- a/src/lib/builtins.pl +++ b/src/lib/builtins.pl @@ -256,9 +256,8 @@ G1 -> G2 :- control_entry_point((G1 -> G2)). :- non_counted_backtracking staggered_if_then/2. staggered_if_then(G1, G2) :- - '$get_staggered_cp'(B), call(G1), - '$set_cp'(B), + !, call(G2). %% ;(G1, G2) @@ -269,7 +268,14 @@ G1 ; G2 :- control_entry_point((G1 ; G2)). :- non_counted_backtracking staggered_sc/2. -staggered_sc(G, _) :- call(G). +staggered_sc(G, _) :- + ( nonvar(G), + G = '$call'(builtins:staggered_if_then(G1, G2)) -> + call(G1), + !, + call(G2) + ; call(G) + ). staggered_sc(_, G) :- call(G). %% !. @@ -288,6 +294,7 @@ set_cp(B) :- '$set_cp'(B). % Conjuction (and) ','(G1, G2) :- control_entry_point((G1, G2)). + :- non_counted_backtracking control_entry_point/1. control_entry_point(G) :- @@ -311,47 +318,15 @@ cont_list_goal([Cont], Cont) :- !. cont_list_goal(Conts, '$call'(builtins:dispatch_call_list(Conts))). -:- non_counted_backtracking module_qualified_cut/1. - -module_qualified_cut(Gs) :- - ( functor(Gs, call, 1) -> - arg(1, Gs, G1) - ; Gs = G1 - ), - functor(G1, (:), 2), - arg(2, G1, G2), - G2 == !. - - :- non_counted_backtracking dispatch_prep/3. dispatch_prep(Gs, B, [Cont|Conts]) :- ( callable(Gs) -> - ( functor(Gs, ',', 2) -> - arg(1, Gs, G1), - arg(2, Gs, G2), - dispatch_prep(G1, B, IConts1), - cont_list_goal(IConts1, Cont), - dispatch_prep(G2, B, Conts) - ; functor(Gs, ';', 2) -> - arg(1, Gs, G1), - arg(2, Gs, G2), - dispatch_prep(G1, B, IConts0), - dispatch_prep(G2, B, IConts1), - cont_list_goal(IConts0, Cont0), - cont_list_goal(IConts1, Cont1), - Cont = '$call'(builtins:staggered_sc(Cont0, Cont1)), - Conts = [] - ; functor(Gs, ->, 2) -> - arg(1, Gs, G1), - arg(2, Gs, G2), - dispatch_prep(G1, B, IConts1), - dispatch_prep(G2, B, IConts2), - cont_list_goal(IConts1, Cont1), - cont_list_goal(IConts2, Cont2), - Cont = '$call'(builtins:staggered_if_then(Cont1, Cont2)), - Conts = [] - ; ( Gs == ! ; module_qualified_cut(Gs) ) -> + strip_module(Gs, M, Gs0), + ( nonvar(Gs0), + dispatch_prep_(Gs0, B, [Cont|Conts]) -> + true + ; Gs0 == ! -> Cont = '$call'(builtins:set_cp(B)), Conts = [] ; Cont = Gs, @@ -364,6 +339,28 @@ dispatch_prep(Gs, B, [Cont|Conts]) :- ). +:- non_counted_backtracking dispatch_prep_/3. + +dispatch_prep_((G1, G2), B, [Cont|Conts]) :- + dispatch_prep(G1, B, IConts1), + cont_list_goal(IConts1, Cont), + dispatch_prep(G2, B, Conts). +dispatch_prep_((G1 ; G2), B, [Cont|Conts]) :- + dispatch_prep(G1, B, IConts0), + dispatch_prep(G2, B, IConts1), + cont_list_goal(IConts0, Cont0), + cont_list_goal(IConts1, Cont1), + Cont = '$call'(builtins:staggered_sc(Cont0, Cont1)), + Conts = []. +dispatch_prep_((G1 -> G2), B, [Cont|Conts]) :- + dispatch_prep(G1, B, IConts1), + dispatch_prep(G2, B, IConts2), + cont_list_goal(IConts1, Cont1), + cont_list_goal(IConts2, Cont2), + Cont = '$call'(builtins:staggered_if_then(Cont1, Cont2)), + Conts = []. + + :- non_counted_backtracking dispatch_call_list/1. dispatch_call_list([]). @@ -960,11 +957,10 @@ findall_with_existential(Template, Goal, PairedSolutions, Witnesses0, Witnesses) % Bag = [1,2]. bagof(Template, Goal, Solution) :- error:can_be(list, Solution), - term_variables(Template, TemplateVars0), - term_variables(Goal, GoalVars0), - sort(TemplateVars0, TemplateVars), - sort(GoalVars0, GoalVars), - set_difference(GoalVars, TemplateVars, Witnesses0), + term_variables(Template, TemplateVars), + term_variables(Goal, GoalVars), + term_variables(TemplateVars+GoalVars, TGVs), + lists:append(TemplateVars, Witnesses0, TGVs), findall_with_existential(Template, Goal, PairedSolutions0, Witnesses0, Witnesses), keysort(PairedSolutions0, PairedSolutions), group_by_variants(PairedSolutions, GroupedSolutions), @@ -997,11 +993,10 @@ iterate_variants_and_sort([_|GroupSolutions], Ws, Solution) :- % Set = [1, 2]. setof(Template, Goal, Solution) :- error:can_be(list, Solution), - term_variables(Template, TemplateVars0), - term_variables(Goal, GoalVars0), - sort(TemplateVars0, TemplateVars), - sort(GoalVars0, GoalVars), - set_difference(GoalVars, TemplateVars, Witnesses0), + term_variables(Template, TemplateVars), + term_variables(Goal, GoalVars), + term_variables(TemplateVars+GoalVars, TGVs), + lists:append(TemplateVars, Witnesses0, TGVs), findall_with_existential(Template, Goal, PairedSolutions0, Witnesses0, Witnesses), keysort(PairedSolutions0, PairedSolutions), group_by_variants(PairedSolutions, GroupedSolutions), diff --git a/src/lib/files.pl b/src/lib/files.pl index ef73e851..e920b5bd 100644 --- a/src/lib/files.pl +++ b/src/lib/files.pl @@ -1,3 +1,22 @@ +/** Predicates for reasoning about files and directories. + +In this library, directories and files are represented as +*lists of characters*. This is an ideal representation: + +* Lists of characters can be conveniently reasoned about with DCGs + and built-in Prolog predicates from library(lists). This alone + is already a very compelling argument to use them. +* Other Scryer libraries such as library(http/http_open) also already + use lists of characters to represent paths. +* File names are mostly ephemeral, so it is good for efficiency + that they can quickly allocated transiently on the heap, leaving the + atom table mostly unaffected. Indexing is almost never needed + for file names. If needed, it should be added to the engine. +* The previous point is also good for security, since the system + leaves little trace of which files were even accessed. +* Scryer Prolog represents lists of characters extremely compactly. +*/ + /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Written 2020, 2022 by Markus Triska (triska@metalevel.at) Part of Scryer Prolog. @@ -51,8 +70,9 @@ file_exists/1, directory_exists/1, delete_file/1, - rename_file/2, - delete_directory/1, + rename_file/2, + file_copy/2, + delete_directory/1, make_directory/1, make_directory_path/1, working_directory/2, @@ -67,41 +87,82 @@ :- use_module(library(charsio)). :- use_module(library(dcgs)). +%% directory_files(+Directory, -Files). +% +% Returns the list of files *and* directories available at a specific +% directory in the current system. + directory_files(Directory, Files) :- must_be(chars, Directory), can_be(list, Files), '$directory_files'(Directory, Files). +%% file_size(+File, -Size). +% +% Returns the size (in bytes) of a file. The file must exist. + file_size(File, Size) :- file_must_exist(File, file_size/2), can_be(integer, Size), '$file_size'(File, Size). +%% file_exists(+File). +% +% Succeeds if File is a file that exists in the current system. file_exists(File) :- must_be(chars, File), '$file_exists'(File). +%% directory_exists(+Directory). +% +% Succeeds if Directory is a directory that exists in the current system. directory_exists(Directory) :- must_be(chars, Directory), '$directory_exists'(Directory). +%% make_directory(+Directory). +% +% Succeeds if it creates a new directory named Directory in the current system. +% If you want to create a nested directory, use make\_directory\_path/1. make_directory(Directory) :- must_be(chars, Directory), '$make_directory'(Directory). +%% make_directory_path(+Directory). +% +% Similar to make\_directory/1 but recursively creates directories if they're missing. +% Equivalent to mkdir -p in Unix. make_directory_path(Directory) :- must_be(chars, Directory), '$make_directory_path'(Directory). +%% delete_file(+File). +% +% Succeeds if deletes File from the current system. delete_file(File) :- file_must_exist(File, delete_file/1), '$delete_file'(File). +%% rename_file(+File, +Renamed). +% +% Succeeds if File is renamed to Renamed rename_file(File, Renamed) :- file_must_exist(File, rename_file/2), must_be(chars, Renamed), '$rename_file'(File, Renamed). +%% file_copy(+File, +Copied). +% +% Succeeds if File is copied to Copied +file_copy(File, Copied) :- + file_must_exist(File, file_copy/2), + must_be(chars, Copied), + '$file_copy'(File, Copied). + +%% delete_directory(+Directory). +% +% Succeeds if Directory is deleted from the current system. +% Directory must be empty. delete_directory(Directory) :- directory_must_exist(Directory, delete_directory/1), must_be(chars, Directory), @@ -117,31 +178,31 @@ directory_must_exist(Directory, Context) :- ; throw(error(existence_error(directory, Directory), Context)) ). -/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Dir0 is the current working directory, and the working directory - is changed to Dir. +%% workind_directory(Dir0, Dir). +% +% Dir0 is the current working directory, and the working directory +% is changed to Dir. - Use working_directory(Ds, Ds) to determine the current working directory, - and leave it as is. -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ +% Use `working\_directory(Ds, Ds)` to determine the current working directory, +% and leave it as is. working_directory(Dir0, Dir) :- can_be(list, Dir0), can_be(list, Dir), '$working_directory'(Dir0, Dir). -/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - True iff Cs is the canonical, absolute path of Ps. - - All intermediate components are normalized, and all symbolic links - are resolved. - - The predicate fails in the following situations, though not - necessarily *only* in these cases: - - 1. Ps is a path that does not exist. - 2. A non-final component in Ps is not a directory. -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ +%% path_canonical(Ps, Cs). +% +% True iff Cs is the canonical, absolute path of Ps. +% +% All intermediate components are normalized, and all symbolic links +% are resolved. +% +% The predicate fails in the following situations, though not +% necessarily *only* in these cases: +% +% 1. Ps is a path that does not exist. +% 2. A non-final component in Ps is not a directory. path_canonical(Ps, Cs) :- must_be(chars, Ps), @@ -155,12 +216,27 @@ path_canonical(Ps, Cs) :- For two time stamps A and B, if A precedes B, then A @< B holds. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ +%% file_modification_time(+File, -T). +% +% For a file File that must exist, it returns a time stamp T with the modification time +% +% T is a time stamp compatible with library(time). file_modification_time(File, T) :- file_time_(File, modification, T). +%% file_access_time(+File, -T). +% +% For a file File that must exist, it returns a time stamp T with the access time +% +% T is a time stamp compatible with library(time). file_access_time(File, T) :- file_time_(File, access, T). +%% file_creation_time(+File, -T). +% +% For a file File that must exist, it returns a time stamp T with the creation time +% +% T is a time stamp compatible with library(time). file_creation_time(File, T) :- file_time_(File, creation, T). @@ -170,29 +246,27 @@ file_time_(File, Which, T) :- read_from_chars(T0, T). -/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - path_segments(Ps, Segments): True iff Segments are the segments of Ps. - - Segments is the list of components of the path Ps that are - separated by the platform-specific directory separator. Each - segment is a list of characters. - - At least one of the arguments must be instantiated. - - Examples: - - ?- path_segments("/hello/there", Segments). - Segments = [[],"hello","there"]. - - ?- path_segments(Path, ["hello","there"]). - Path = "hello/there". - - - To obtain the platform-specific directory separator, you can use: - - ?- path_segments(Separator, ["",""]). - Separator = "/". -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ +%% path_segments(Ps, Segments). +% +% True iff Segments are the segments of Ps. +% +% Segments is the list of components of the path Ps that are +% separated by the platform-specific directory separator. Each +% segment is a list of characters. +% +% At least one of the arguments must be instantiated. +% +% Examples: +% +% ?- path_segments("/hello/there", Segments). +% Segments = [[],"hello","there"]. +% ?- path_segments(Path, ["hello","there"]). +% Path = "hello/there". +% +% To obtain the platform-specific directory separator, you can use: +% +% ?- path_segments(Separator, ["",""]). +% Separator = "/". path_segments(Path, Segments) :- '$directory_separator'(Sep), diff --git a/src/lib/http/http_open.pl b/src/lib/http/http_open.pl index 1c89b5a5..7d0503c2 100644 --- a/src/lib/http/http_open.pl +++ b/src/lib/http/http_open.pl @@ -1,34 +1,37 @@ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Written 2022 by Adrián Arroyo Calle (adrian.arroyocalle@gmail.com) Part of Scryer Prolog. +*/ - http_open(+Address, -Stream, +Options) - ====================================== +/** Make HTTP requests. - Yields Stream to read the body of an HTTP reply from Address. - Address is a list of characters, and includes the method. Both HTTP - and HTTPS are supported. - - Options supported: - - * method(+Method): Sets the HTTP method of the call. Method can be get (default), head, delete, post, put or patch. - * data(+Data): Data to be sent in the request. Useful for POST, PUT and PATCH operations. - * size(-Size): Unifies with the value of the Content-Length header - * request_headers(+RequestHeaders): Headers to be used in the request - * headers(-ListHeaders): Unifies with a list with all headers returned in the response - * status_code(-Code): Unifies with the status code of the request (200, 201, 404, ...) - - Example: - - ?- http_open("https://github.com/mthom/scryer-prolog", S, []). - %@ S = '$stream'(0x7fcfc9e00f00). - -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ +This library contains the predicate http\_open/3 which allows you to perform HTTP(S) calls. +Useful for making API calls, or parsing websites. It uses Hyper underneath. +*/ :- module(http_open, [http_open/3]). :- use_module(library(lists)). +%% http_open(+Address, -Stream, +Options). +% +% Yields Stream to read the body of an HTTP reply from Address. +% Address is a list of characters, and includes the method. Both HTTP +% and HTTPS are supported. +% +% Options supported: +% +% * `method(+Method)`: Sets the HTTP method of the call. Method can be `get` (default), `head`, `delete`, `post`, `put` or `patch`. +% * `data(+Data)`: Data to be sent in the request. Useful for POST, PUT and PATCH operations. +% * `size(-Size)`: Unifies with the value of the Content-Length header +% * `request_headers(+RequestHeaders)`: Headers to be used in the request +% * `headers(-ListHeaders)`: Unifies with a list with all headers returned in the response +% * `status_code(-Code)`: Unifies with the status code of the request (200, 201, 404, ...) +% +% Example: +% +% ?- http_open("https://www.example.com", S, []), get_n_chars(S, N, HTML). +% S = '$stream'(0x7fb548001be8), N = 1256, HTML = "\n true; Method = get), @@ -65,4 +68,4 @@ parse_http_options_(request_headers(Headers), request_headers(Headers)) :- parse_http_options_(size(Size), size(Size)). parse_http_options_(status_code(Code), status_code(Code)). -parse_http_options_(headers(Headers), headers(Headers)). \ No newline at end of file +parse_http_options_(headers(Headers), headers(Headers)). diff --git a/src/lib/iso_ext.pl b/src/lib/iso_ext.pl index 26b4713c..2ae3bf84 100644 --- a/src/lib/iso_ext.pl +++ b/src/lib/iso_ext.pl @@ -1,3 +1,9 @@ +/** Useful general predicates that are not ISO standard yet + +Predicates available here are similar to the ones defined in builtin.pl, +but they're not part of the ISO Prolog standard at the moment. +*/ + :- module(iso_ext, [bb_b_put/2, bb_get/2, bb_put/2, @@ -22,25 +28,70 @@ :- meta_predicate(forall(0, 0)). +%% forall(Generate, Test). +% +% For all bindings possible by Generate, Test must be true. +% +% In this example, it checks that all numbers are even: +% +% ?- Ns = [2,4,6], forall(member(N, Ns), 0 is N mod 2). +% Ns = [2,4,6]. forall(Generate, Test) :- \+ (Generate, \+ Test). -%% (non-)backtrackable global variables. +% (non-)backtrackable global variables. +%% bb_put(+Key, +Value). +% +% Sets a global variable named Key (must be an atom) with value Value. +% The global variable isn't backtrackable. Check bb\_b\_put/2 for the +% backtrackable version. +% +% ?- bb_put(city, "Valladolid"). +% true. +% ?- bb_get(city, X). +% X = "Valladolid". +% In this example one can understand the difference between bb\_put/2 and +% bb\_b\_put/2: +% +% ?- bb_put(city, "Valladolid"), (bb_put(city, "Salamanca"), false);(bb_get(city, X)). +% X = "Salamanca". +% ?- bb_put(city, "Valladolid"), (bb_b_put(city, "Salamanca"), false);(bb_get(city, X)). +% X = "Valladolid". bb_put(Key, Value) :- ( atom(Key) -> '$store_global_var'(Key, Value) ; type_error(atom, Key, bb_put/2) ). -%% backtrackable global variables. +% backtrackable global variables. +%% bb_b_put(+Key, +Value). +% +% Sets a global variable named Key (must be an atom) with value Value. +% The global variable is backtrackable. Check bb\_put/2 for the +% non-backtrackable version. +% +% ?- bb_b_put(city, "Valladolid"). +% true. +% ?- bb_get(city, X). +% X = "Valladolid". +% In this example one can understand the difference between bb\_put/2 and +% bb\_b\_put/2: +% +% ?- bb_put(city, "Valladolid"), (bb_put(city, "Salamanca"), false);(bb_get(city, X)). +% X = "Salamanca". +% ?- bb_put(city, "Valladolid"), (bb_b_put(city, "Salamanca"), false);(bb_get(city, X)). +% X = "Valladolid". bb_b_put(Key, Value) :- ( atom(Key) -> '$store_backtrackable_global_var'(Key, Value) ; type_error(atom, Key, bb_b_put/2) ). +%% bb_get(+Key, -Value). +% +% Gets the value Value of a global variable named Key (must be an atom) bb_get(Key, Value) :- ( atom(Key) -> '$fetch_global_var'(Key, Value) @@ -52,12 +103,23 @@ bb_get(Key, Value) :- :- meta_predicate(call_cleanup(0, 0)). +%% call_cleanup(Goal, Cleanup). +% +% Executes Goal and then, either on success or failure, executes Cleanup. +% The success or failure of Cleanup is ignored and choice points created inside are destroyed. call_cleanup(G, C) :- setup_call_cleanup(true, G, C). :- meta_predicate(setup_call_cleanup(0, 0, 0)). :- non_counted_backtracking setup_call_cleanup/3. +%% setup_call_cleanup(Setup, Goal, Cleanup). +% +% If Setup succeeds, Cleanup will be called after the execution of Goal. Goal itself can succeed or not. +% +% In this example, we use the predicate to always close an open file: +% +% ?- setup_call_cleanup(open(File, read, Stream), do_something_with_stream(Stream), close(Stream)). setup_call_cleanup(S, G, C) :- '$get_b_value'(B), '$call_with_inference_counting'(call(S)), @@ -144,6 +206,9 @@ handle_ile(B, _, _) :- :- non_counted_backtracking call_with_inference_limit/3. +%% call_with_inference_limit(Goal, Limit, Result). +% +% Similar to `call(Goal)` but it limits the number of inferences for each solution of Goal. call_with_inference_limit(G, L, R) :- ( integer(L) -> ( L < 0 -> @@ -186,6 +251,10 @@ call_with_inference_limit(_, _, R, Bb, B) :- ), handle_ile(B, Ball, R). +%% partial_string(String, L, L0) +% +% Explicitly construct a partial string "manually". It can be used as an optimized append/3. +% It's not recommended to use this predicate in application code. partial_string(String, L, L0) :- ( String == [] -> L = L0 @@ -195,9 +264,17 @@ partial_string(String, L, L0) :- '$create_partial_string'(Atom, L, L0) ). +%% partial_string(+String) +% +% Succeeds if String is a _partial string_. A partial string is a string composed of several smaller +% strings, even just one. That means all strings in Scryer are partial strings. partial_string(String) :- '$is_partial_string'(String). +%% partial_string_tail(+String, -Tail). +% +% Unifies Tail with the last section of the partial string. +% It's not recommended to use this predicate in application code. partial_string_tail(String, Tail) :- ( partial_string(String) -> '$partial_string_tail'(String, Tail) @@ -209,6 +286,9 @@ partial_string_tail(String, Tail) :- :- meta_predicate(call_nth(0, ?)). +%% call_nth(Goal, N). +% +% Succeeds when Goal succeeded for the Nth time (there are at least N solutions) call_nth(Goal, N) :- can_be(integer, N), ( integer(N) -> @@ -247,16 +327,24 @@ call_nth_nesting(C, ID) :- bb_put(i_call_nth_counter, C). +%% copy_term_nat(Source, Dest) +% +% Similar to copy\_term/2 but without attribute variables copy_term_nat(Source, Dest) :- '$copy_term_without_attr_vars'(Source, Dest). - +%% asserta(Module, Rule_Fact). +% +% Similar to asserta/1 but allows specifying a Module asserta(Module, (Head :- Body)) :- !, '$asserta'(Module, Head, Body). asserta(Module, Fact) :- '$asserta'(Module, Fact, true). +%% assertz(Module, Rule_Fact). +% +% Similar to assertz/1 but allows specifying a Module assertz(Module, (Head :- Body)) :- !, '$assertz'(Module, Head, Body). diff --git a/src/lib/lists.pl b/src/lib/lists.pl index 4eb204b1..15d9afa0 100644 --- a/src/lib/lists.pl +++ b/src/lib/lists.pl @@ -1,3 +1,7 @@ +/** +List manipulation predicates +*/ + :- module(lists, [member/2, select/3, append/2, append/3, foldl/4, foldl/5, memberchk/2, reverse/2, length/2, maplist/2, maplist/3, maplist/4, maplist/5, maplist/6, @@ -57,6 +61,18 @@ resource_error(Resource, Context) :- throw(error(resource_error(Resource), Context)). +%% length(?Xs, ?N). +% +% Relates a list to its length (number of items). It can be used to count the elements of a current list or +% to create a list full of free variables with N length. +% +% ?- length([a,b,c], 3). +% true. +% ?- length([a,b,c], N). +% N = 3. +% ?- length(Xs, 3). +% Xs = [_A, _B, _C]. + length(Xs0, N) :- '$skip_max_list'(M, N, Xs0,Xs), !, @@ -95,28 +111,61 @@ length_addendum([_|Xs], N, M) :- M1 is M + 1, length_addendum(Xs, N, M1). - +%% member(?X, ?Xs). +% +% Succeeds when X unifies with an item of the list Xs, which can be at any position. +% +% ?- member(X, "hello world"). +% X = h +% ; ... . +% member(X, [X|_]). member(X, [_|Xs]) :- member(X, Xs). - +%% select(X, Xs0, Xs1). +% +% Succeeds when the list Xs1 is the list Xs0 without the item X +% +% ?- select(c, "abcd", X). +% X = "abd". +% select(X, [X|Xs], Xs). select(X, [Y|Xs], [Y|Ys]) :- select(X, Xs, Ys). - +%% append(+XsXs, ?Xs). +% +% Concatenates a list of lists +% +% ?- append([[1, 2], [3]], Xs). +% Xs = [1, 2, 3]. +% append([], []). append([L0|Ls0], Ls) :- append(L0, Rest, Ls), append(Ls0, Rest). - +%% append(Xs0, Xs1, Xs). +% +% List Xs is the concatenation of Xs0 and Xs1 +% +% ?- append([1,2,3], [4,5,6], Xs). +% Xs = [1, 2, 3, 4, 5, 6]. +% append([], R, R). append([X|L], R, [X|S]) :- append(L, R, S). - +%% memberchk(?X, +Xs). +% +% This predicate is similar to member/2, but it only provides a single answer memberchk(X, Xs) :- member(X, Xs), !. - +%% reverse(?Xs, ?Ys). +% +% Xs is the Ys list in reverse order +% +% ?- reverse([1,2,3], [3,2,1]). +% true. +% reverse(Xs, Ys) :- ( nonvar(Xs) -> reverse(Xs, Ys, [], Xs) ; reverse(Ys, Xs, [], Ys) @@ -126,62 +175,111 @@ reverse([], [], YsRev, YsRev). reverse([_|Xs], [Y1|Ys], YsPreludeRev, Xss) :- reverse(Xs, Ys, [Y1|YsPreludeRev], Xss). +%% maplist(+Predicate, ?Xs0). +% +% This is a metapredicate that applies predicate to each element of the list Xs0 +% +% ?- maplist(write, [1,2,3]). +% 123 true. +% maplist(_, []). maplist(Cont1, [E1|E1s]) :- call(Cont1, E1), maplist(Cont1, E1s). +%% maplist(+Predicate, ?Xs0, ?Xs1). +% +% This is a metapredicate that applies predicate to each element of the lists Xs0 and Xs1. +% +% ?- maplist(length, ["hello", "prolog", "marseille"], Xs1). +% Xs1 = [5,6,9]. +% maplist(_, [], []). maplist(Cont2, [E1|E1s], [E2|E2s]) :- call(Cont2, E1, E2), maplist(Cont2, E1s, E2s). +%% maplist(+Predicate, ?Xs0, ?Xs1, ?Xs2). +% +% This is a metapredicate that applies predicate to each element of the lists Xs0, Xs1 and Xs2. maplist(_, [], [], []). maplist(Cont3, [E1|E1s], [E2|E2s], [E3|E3s]) :- call(Cont3, E1, E2, E3), maplist(Cont3, E1s, E2s, E3s). +%% maplist(+Predicate, ?Xs0, ?Xs1, ?Xs2, ?Xs3). +% +% This is a metapredicate that applies predicate to each element of the lists Xs0, Xs1, Xs2 and Xs3. maplist(_, [], [], [], []). maplist(Cont, [E1|E1s], [E2|E2s], [E3|E3s], [E4|E4s]) :- call(Cont, E1, E2, E3, E4), maplist(Cont, E1s, E2s, E3s, E4s). - +%% maplist(+Predicate, ?Xs0, ?Xs1, ?Xs2, ?Xs3, ?Xs4). +% +% This is a metapredicate that applies predicate to each element of the lists Xs0, Xs1, Xs2, Xs3 and Xs4. maplist(_, [], [], [], [], []). maplist(Cont, [E1|E1s], [E2|E2s], [E3|E3s], [E4|E4s], [E5|E5s]) :- call(Cont, E1, E2, E3, E4, E5), maplist(Cont, E1s, E2s, E3s, E4s, E5s). - +%% maplist(+Predicate, ?Xs0, ?Xs1, ?Xs2, ?Xs3, ?Xs4, ?Xs5). +% +% This is a metapredicate that applies predicate to each element of the lists Xs0, Xs1, Xs2, Xs3, Xs4 and Xs5. maplist(_, [], [], [], [], [], []). maplist(Cont, [E1|E1s], [E2|E2s], [E3|E3s], [E4|E4s], [E5|E5s], [E6|E6s]) :- call(Cont, E1, E2, E3, E4, E5, E6), maplist(Cont, E1s, E2s, E3s, E4s, E5s, E6s). - +%% maplist(+Predicate, ?Xs0, ?Xs1, ?Xs2, ?Xs3, ?Xs4, ?Xs5, ?Xs6). +% +% This is a metapredicate that applies predicate to each element of the lists Xs0, Xs1, Xs2, Xs3, Xs4, Xs5 and Xs6. maplist(_, [], [], [], [], [], [], []). maplist(Cont, [E1|E1s], [E2|E2s], [E3|E3s], [E4|E4s], [E5|E5s], [E6|E6s], [E7|E7s]) :- call(Cont, E1, E2, E3, E4, E5, E6, E7), maplist(Cont, E1s, E2s, E3s, E4s, E5s, E6s, E7s). - +%% maplist(+Predicate, ?Xs0, ?Xs1, ?Xs2, ?Xs3, ?Xs4, ?Xs5, ?Xs6, ?Xs7). +% +% This is a metapredicate that applies predicate to each element of the lists Xs0, Xs1, Xs2, Xs3, Xs4, Xs5, Xs6 and Xs7. maplist(_, [], [], [], [], [], [], [], []). maplist(Cont, [E1|E1s], [E2|E2s], [E3|E3s], [E4|E4s], [E5|E5s], [E6|E6s], [E7|E7s], [E8|E8s]) :- call(Cont, E1, E2, E3, E4, E5, E6, E7, E8), maplist(Cont, E1s, E2s, E3s, E4s, E5s, E6s, E7s, E8s). - +%% sum_list(+Xs, -Sum). +% +% Takes a lists of numbers and unifies Sum with the result of summing all the elements of the list. +% +% ?- sum_list([2,2,2], 6). +% true. sum_list(Ls, S) :- foldl(lists:sum_, Ls, 0, S). sum_(L, S0, S) :- S is S0 + L. - +%% same_length(?Xs, ?Ys). +% +% Succeeds if Xs and Ys are lists of the same length same_length([], []). same_length([_|As], [_|Bs]) :- same_length(As, Bs). +%% foldl(+Predicate, ?Ls, +A0, ?A). +% +% foldl, sometimes called reduce, is a metapredicate that takes a predicate, a list of items +% and a starting value, and outputs a single value. The predicate _Predicate_ must be able to take the current +% element of the list, the previous value of the computation and the next value of the computation. +% +% For example, if we define sum_ as: +% +% sum_(L, S0, S) :- S is S0 + L. +% +% Then we can define sum\_list/2 as the following: +% +% sum_list(Ls, S) :- foldl(sum_, Ls, 0, S). +% foldl(Goal_3, Ls, A0, A) :- foldl_(Ls, Goal_3, A0, A). @@ -191,7 +289,9 @@ foldl_([L|Ls], G_3, A0, A) :- call(G_3, L, A0, A1), foldl_(Ls, G_3, A1, A). - +%% foldl(+Predicate, ?Ls0, ?Ls1, +A0, ?A). +% +% Same as foldl/4 but with an extra list foldl(Goal_4, Xs, Ys, A0, A) :- foldl_(Xs, Ys, Goal_4, A0, A). @@ -201,6 +301,13 @@ foldl_([X|Xs], [Y|Ys], G_4, A0, A) :- call(G_4, X, Y, A0, A1), foldl_(Xs, Ys, G_4, A1, A). +%% transpose(?Ls, ?Ts). +% +% If Ls is a list of lists, Ts contains the transposition +% +% ?- transpose([[1,1],[2,2]], Ts). +% Ts = [[1,2],[1,2]]. +% transpose(Ls, Ts) :- lists_transpose(Ls, Ts). @@ -214,7 +321,13 @@ transpose_(_, Fs, Lists0, Lists) :- list_first_rest([L|Ls], L, Ls). - +%% list_to_set(+Ls0, -Set). +% +% Takes a list Ls0 and returns a list Set that doesn't contain any repeated element +% +% ?- list_to_set([2,3,4,4,1,2], Set). +% Set = [2,3,4,1]. +% list_to_set(Ls0, Ls) :- maplist(lists:with_var, Ls0, LVs0), keysort(LVs0, LVs), @@ -242,7 +355,12 @@ unify_same(E-V, Prev-Var, E-V) :- ; true ). - +%% nth0(?N, ?Ls, ?E). +% +% Succeeds if in the N position of the list Ls, we found the element E. The elements start counting from zero. +% +% ?- nth0(2, [1,2,3,4], 3). +% true. nth0(N, Es0, E) :- nonvar(N), '$skip_max_list'(Skip, N, Es0,Es1), @@ -277,6 +395,12 @@ nth0_el(N0,N, _,E, [E0|Es0]) :- N1 is N0+1, nth0_el(N1,N, E0,E, Es0). +%% nth1(?N, ?Ls, ?E). +% +% Succeeds if in the N position of the list Ls, we found the element E. The elements start counting from one. +% +% ?- nth1(2, [1,2,3,4], 2). +% true. nth1(N, Es0, E) :- N \== 0, nth0(N, [_|Es0], E), @@ -291,6 +415,12 @@ skipn(N0, Es0,Es, Xs0,Xs) :- skipn(N1, Es1,Es, Xs1,Xs). skipn(0, Es,Es, Xs,Xs). +%% nth0(?N, ?Ls, ?E, ?Rs). +% +% Succeeds if in the N position of the list Ls, we found the element E and the rest of the list is Rs. The elements start counting from zero. +% +% ?- nth0(2, [1,2,3,4], 3, [1,2,4]). +% true. nth0(N, Es0, E, Es) :- integer(N), N >= 0, @@ -315,45 +445,54 @@ nth0_elx(N0,N, E0,E, [E1|Es0], [E0|Es]) :- % p.p.8.5 +%% nth1(?N, ?Ls, ?E, ?Rs). +% +% Succeeds if in the N position of the list Ls, we found the element E and the rest of the list is Rs. The elements start counting from one. +% +% ?- nth1(2, [1,2,3,4], 2, [1,3,4]). +% true. nth1(N, Es0, E, Es) :- N \== 0, nth0(N, [_|Es0], E, [_|Es]), N \== 0. - +%% list_max(+Xs, -Max). +% +% Takes a list Xs and unifies with the maximum value of the list list_max([N|Ns], Max) :- foldl(lists:list_max_, Ns, N, Max). list_max_(N, Max0, Max) :- Max is max(N, Max0). +%% list_min(+Xs, -Min). +% +% Takes a list Xs and unifies with the minimum value of the list list_min([N|Ns], Min) :- foldl(lists:list_min_, Ns, N, Min). list_min_(N, Min0, Min) :- Min is min(N, Min0). -%! permutation(?Xs, ?Ys) is nondet. +%% permutation(?Xs, ?Ys) is nondet. % -% True when Xs is a permutation of Ys. This can solve for Ys given -% Xs or Xs given Ys, or even enumerate Xs and Ys together. The -% predicate permutation/2 is primarily intended to generate -% permutations. Note that a list of length N has N! permutations, -% and unbounded permutation generation becomes prohibitively -% expensive, even for rather short lists (10! = 3,628,800). +% True when Xs is a permutation of Ys. This can solve for Ys given +% Xs or Xs given Ys, or even enumerate Xs and Ys together. The +% predicate permutation/2 is primarily intended to generate +% permutations. Note that a list of length N has N! permutations, +% and unbounded permutation generation becomes prohibitively +% expensive, even for rather short lists (10! = 3,628,800). % -% The example below illustrates that Xs and Ys being proper lists -% is not a sufficient condition to use the above replacement. +% The example below illustrates that Xs and Ys being proper lists +% is not a sufficient condition to use the above replacement. % -% == % ?- permutation([1,2], [X,Y]). -% X = 1, Y = 2 ; -% X = 2, Y = 1 ; -% false. -% == +% X = 1, Y = 2 +% ; X = 2, Y = 1 +% ; false. % -% @error type_error(list, Arg) if either argument is not a proper -% or partial list. +% Throws type\_error(list, Arg) if either argument is not a proper +% or partial list. permutation(Xs, Ys) :- '$skip_max_list'(Xlen, _, Xs, XTail), diff --git a/src/lib/ordsets.pl b/src/lib/ordsets.pl index b5886d38..fd17495b 100644 --- a/src/lib/ordsets.pl +++ b/src/lib/ordsets.pl @@ -54,20 +54,19 @@ :- use_module(library(lists)). -/** Ordered set manipulation +/** Ordered set manipulation + Ordered sets are lists with unique elements sorted to the standard order of terms (see sort/2). Exploiting ordering, many of the set operations can be expressed in order N rather than N^2 when dealing with unordered sets that may contain duplicates. The library(ordsets) is available in a number of Prolog implementations. Our predicates are designed to be -compatible with common practice in the Prolog community. The -implementation is incomplete and relies partly on library(oset), an -older ordered set library distributed with SWI-Prolog. New applications -are advised to use library(ordsets). +compatible with common practice in the Prolog community. Some of these predicates match directly to corresponding list operations. It is advised to use the versions from this library to make clear you are operating on ordered sets. An exception is member/2. See -ord_memberchk/2. +ord\_memberchk/2. + The ordsets library is based on the standard order of terms. This implies it can handle all Prolog terms, including variables. Note however, that the ordering is not stable if a term inside the set is @@ -80,13 +79,13 @@ fresh variable. In other cases one should cease using it as an ordset because the order it relies on may have been changed. */ -%! is_ordset(@Term) is semidet. +%% is_ordset(@Term) is semidet. % -% True if Term is an ordered set. All predicates in this library -% expect ordered sets as input arguments. Failing to fullfil this -% assumption results in undefined behaviour. Typically, ordered -% sets are created by predicates from this library, sort/2 or -% setof/3. +% True if Term is an ordered set. All predicates in this library +% expect ordered sets as input arguments. Failing to fullfil this +% assumption results in undefined behaviour. Typically, ordered +% sets are created by predicates from this library, sort/2 or +% setof/3. is_ordset(Term) :- '$skip_max_list'(_, _, Term, Tail), Tail == [], %% is_list(Term), @@ -102,37 +101,35 @@ is_ordset3([H2|T], H) :- is_ordset3(T, H2). -%! ord_empty(?List) is semidet. +%% ord_empty(?List) is semidet. % -% True when List is the empty ordered set. Simply unifies list -% with the empty list. Not part of Quintus. +% True when List is the empty ordered set. Simply unifies list +% with the empty list. Not part of Quintus. ord_empty([]). -%! ord_seteq(+Set1, +Set2) is semidet. +%% ord_seteq(+Set1, +Set2) is semidet. % -% True if Set1 and Set2 have the same elements. As both are -% canonical sorted lists, this is the same as ==/2. -% -% @compat sicstus +% True if Set1 and Set2 have the same elements. As both are +% canonical sorted lists, this is the same as ==/2. ord_seteq(Set1, Set2) :- Set1 == Set2. -%! list_to_ord_set(+List, -OrdSet) is det. +%% list_to_ord_set(+List, -OrdSet) is det. % -% Transform a list into an ordered set. This is the same as -% sorting the list. +% Transform a list into an ordered set. This is the same as +% sorting the list. list_to_ord_set(List, Set) :- sort(List, Set). -%! ord_intersect(+Set1, +Set2) is semidet. +%% ord_intersect(+Set1, +Set2) is semidet. % -% True if both ordered sets have a non-empty intersection. +% True if both ordered sets have a non-empty intersection. ord_intersect([H1|T1], L2) :- ord_intersect_(L2, H1, T1). @@ -148,31 +145,29 @@ ord_intersect__(>, H1, T1, _H2, T2) :- ord_intersect_(T2, H1, T1). -%! ord_disjoint(+Set1, +Set2) is semidet. +%% ord_disjoint(+Set1, +Set2) is semidet. % -% True if Set1 and Set2 have no common elements. This is the -% negation of ord_intersect/2. +% True if Set1 and Set2 have no common elements. This is the +% negation of ord\_intersect/2. ord_disjoint(Set1, Set2) :- \+ ord_intersect(Set1, Set2). -%! ord_intersect(+Set1, +Set2, -Intersection) +%% ord_intersect(+Set1, +Set2, -Intersection) % -% Intersection holds the common elements of Set1 and Set2. +% Intersection holds the common elements of Set1 and Set2. % -% @deprecated Use ord_intersection/3 +% This predicate is **deprecated**. Use ord\_intersection/3 ord_intersect(Set1, Set2, Intersection) :- oset_int(Set1, Set2, Intersection). -%! ord_intersection(+PowerSet, -Intersection) +%% ord_intersection(+PowerSet, -Intersection) % -% Intersection of a powerset. True when Intersection is an ordered -% set holding all elements common to all sets in PowerSet. -% -% @compat sicstus +% Intersection of a powerset. True when Intersection is an ordered +% set holding all elements common to all sets in PowerSet. ord_intersection(PowerSet, Intersection) :- key_by_length(PowerSet, Pairs), @@ -190,10 +185,10 @@ l_int([_-H|T], S0, S) :- l_int(T, S1, S). -%! ord_intersection(+Set1, +Set2, -Intersection) is det. +%% ord_intersection(+Set1, +Set2, -Intersection) is det. % -% Intersection holds the common elements of Set1 and Set2. Uses -% ord_disjoint/2 if Intersection is bound to `[]` on entry. +% Intersection holds the common elements of Set1 and Set2. Uses +% ord\_disjoint/2 if Intersection is bound to `[]` on entry. ord_intersection(Set1, Set2, Intersection) :- ( Intersection == [] @@ -202,13 +197,11 @@ ord_intersection(Set1, Set2, Intersection) :- ). -%! ord_intersection(+Set1, +Set2, ?Intersection, ?Difference) is det. +%% ord_intersection(+Set1, +Set2, ?Intersection, ?Difference) is det. % -% Intersection and difference between two ordered sets. -% Intersection is the intersection between Set1 and Set2, while -% Difference is defined by ord_subtract(Set2, Set1, Difference). -% -% @see ord_intersection/3 and ord_subtract/3. +% Intersection and difference between two ordered sets. +% Intersection is the intersection between Set1 and Set2, while +% Difference is defined by ord\_subtract(Set2, Set1, Difference). ord_intersection([], L, [], L) :- !. ord_intersection([_|_], [], [], []) :- !. @@ -224,35 +217,35 @@ ord_intersection2(>, H1, T1, H2, T2, Intersection, [H2|HDiff]) :- ord_intersection([H1|T1], T2, Intersection, HDiff). -%! ord_add_element(+Set1, +Element, ?Set2) is det. +%% ord_add_element(+Set1, +Element, ?Set2) is det. % -% Insert an element into the set. This is the same as -% ord_union(Set1, [Element], Set2). +% Insert an element into the set. This is the same as +% ord\_union(Set1, [Element], Set2). ord_add_element(Set1, Element, Set2) :- oset_addel(Set1, Element, Set2). -%! ord_del_element(+Set, +Element, -NewSet) is det. +%% ord_del_element(+Set, +Element, -NewSet) is det. % -% Delete an element from an ordered set. This is the same as -% ord_subtract(Set, [Element], NewSet). +% Delete an element from an ordered set. This is the same as +% ord\_subtract(Set, [Element], NewSet). ord_del_element(Set, Element, NewSet) :- oset_delel(Set, Element, NewSet). -%! ord_selectchk(+Item, ?Set1, ?Set2) is semidet. +%% ord_selectchk(+Item, ?Set1, ?Set2) is semidet. % -% Selectchk/3, specialised for ordered sets. Is true when -% select(Item, Set1, Set2) and Set1, Set2 are both sorted lists -% without duplicates. This implementation is only expected to work -% for Item ground and either Set1 or Set2 ground. The "chk" suffix -% is meant to remind you of memberchk/2, which also expects its -% first argument to be ground. ord_selectchk(X, S, T) => -% ord_memberchk(X, S) & \+ ord_memberchk(X, T). +% Selectchk/3, specialised for ordered sets. Is true when +% select(Item, Set1, Set2) and Set1, Set2 are both sorted lists +% without duplicates. This implementation is only expected to work +% for Item ground and either Set1 or Set2 ground. The "chk" suffix +% is meant to remind you of memberchk/2, which also expects its +% first argument to be ground. ord\_selectchk(X, S, T) => +% ord\_memberchk(X, S) & \\+ ord\_memberchk(X, T). % -% @author Richard O'Keefe +% Author: Richard O'Keefe ord_selectchk(Item, [X|Set1], [X|Set2]) :- X @< Item, @@ -266,19 +259,19 @@ ord_selectchk(Item, [Item|Set1], Set1) :- ). -%! ord_memberchk(+Element, +OrdSet) is semidet. +%% ord_memberchk(+Element, +OrdSet) is semidet. % -% True if Element is a member of OrdSet, compared using ==. Note -% that _enumerating_ elements of an ordered set can be done using -% member/2. +% True if Element is a member of OrdSet, compared using ==. Note +% that _enumerating_ elements of an ordered set can be done using +% member/2. % -% Some Prolog implementations also provide ord_member/2, with the -% same semantics as ord_memberchk/2. We believe that having a -% semidet ord_member/2 is unacceptably inconsistent with the *_chk -% convention. Portable code should use ord_memberchk/2 or -% member/2. +% Some Prolog implementations also provide ord\_member/2, with the +% same semantics as ord\_memberchk/2. We believe that having a +% semidet ord\_member/2 is unacceptably inconsistent with the \*\_chk +% convention. Portable code should use ord\_memberchk/2 or +% member/2. % -% @author Richard O'Keefe +% Author: Richard O'Keefe ord_memberchk(Item, [X1,X2,X3,X4|Xs]) :- !, @@ -303,9 +296,9 @@ ord_memberchk(Item, [X1]) :- Item == X1. -%! ord_subset(+Sub, +Super) is semidet. +%% ord_subset(+Sub, +Super) is semidet. % -% Is true if all elements of Sub are in Super +% Is true if all elements of Sub are in Super ord_subset([], _). ord_subset([H1|T1], [H2|T2]) :- @@ -319,22 +312,20 @@ ord_subset_(=, _, T1, T2) :- ord_subset(T1, T2). -%! ord_subtract(+InOSet, +NotInOSet, -Diff) is det. +%% ord_subtract(+InOSet, +NotInOSet, -Diff) is det. % -% Diff is the set holding all elements of InOSet that are not in -% NotInOSet. +% Diff is the set holding all elements of InOSet that are not in +% NotInOSet. ord_subtract(InOSet, NotInOSet, Diff) :- oset_diff(InOSet, NotInOSet, Diff). -%! ord_union(+SetOfSets, -Union) is det. +%% ord_union(+SetOfSets, -Union) is det. % -% True if Union is the union of all elements in the superset -% SetOfSets. Each member of SetOfSets must be an ordered set, the -% sets need not be ordered in any way. -% -% @author Copied from YAP, probably originally by Richard O'Keefe. +% True if Union is the union of all elements in the superset +% SetOfSets. Each member of SetOfSets must be an ordered set, the +% sets need not be ordered in any way. ord_union([], []). ord_union([Set|Sets], Union) :- @@ -355,18 +346,18 @@ ord_union_all(N, Sets0, Union, Sets) :- ). -%! ord_union(+Set1, +Set2, ?Union) is det. +%% ord_union(+Set1, +Set2, ?Union) is det. % -% Union is the union of Set1 and Set2 +% Union is the union of Set1 and Set2 ord_union(Set1, Set2, Union) :- oset_union(Set1, Set2, Union). -%! ord_union(+Set1, +Set2, -Union, -New) is det. +%% ord_union(+Set1, +Set2, -Union, -New) is det. % -% True iff ord_union(Set1, Set2, Union) and -% ord_subtract(Set2, Set1, New). +% True iff ord\_union(Set1, Set2, Union) and +% ord\_subtract(Set2, Set1, New). ord_union([], Set2, Set2, Set2). ord_union([H|T], Set2, Union, New) :- @@ -390,26 +381,22 @@ ord_union_2([H|T], H2, T2, Union, New) :- ord_union(Order, H, T, H2, T2, Union, New). -%! ord_symdiff(+Set1, +Set2, ?Difference) is det. +%% ord_symdiff(+Set1, +Set2, ?Difference) is det. % -% Is true when Difference is the symmetric difference of Set1 and -% Set2. I.e., Difference contains all elements that are not in the -% intersection of Set1 and Set2. The semantics is the same as the -% sequence below (but the actual implementation requires only a -% single scan). +% Is true when Difference is the symmetric difference of Set1 and +% Set2. I.e., Difference contains all elements that are not in the +% intersection of Set1 and Set2. The semantics is the same as the +% sequence below (but the actual implementation requires only a +% single scan). % -% == -% ord_union(Set1, Set2, Union), -% ord_intersection(Set1, Set2, Intersection), -% ord_subtract(Union, Intersection, Difference). -% == +% ord_union(Set1, Set2, Union), +% ord_intersection(Set1, Set2, Intersection), +% ord_subtract(Union, Intersection, Difference). % % For example: % -% == % ?- ord_symdiff([1,2], [2,3], X). % X = [1,3]. -% == ord_symdiff([], Set2, Set2). ord_symdiff([H1|T1], Set2, Difference) :- @@ -457,7 +444,7 @@ ord_symdiff(>, H1, T1, H2, Set2, [H2|Difference]) :- */ -/** Ordered set manipulation +/* Ordered set manipulation This library defines set operations on sets represented as ordered lists. diff --git a/src/lib/sockets.pl b/src/lib/sockets.pl index e2b1b723..541c3133 100644 --- a/src/lib/sockets.pl +++ b/src/lib/sockets.pl @@ -1,4 +1,9 @@ - +/** +Predicates for handling network sockets, both as a server and as a client. +As a server, you should open a socket an call socket\_server\_accept/4 to get a stream for each connection. +As a client, you should just open a socket and you will receive a stream. +In both cases, with a stream, you can use the usual predicates to read and write to the stream. +*/ :- module(sockets, [socket_client_open/3, socket_server_open/2, socket_server_accept/4, @@ -7,6 +12,18 @@ :- use_module(library(error)). +%% socket_client_open(+Addr, -Stream, +Options). +% +% Open a socket to a server, returning a stream. Addr must satisfy `Addr = Address:Port`. +% +% The following options are available: +% +% * alias(+Alias): Set an alias to the stream +% * eof_action(+Action): Defined what happens if the end of the stream is reached. Values: `error`, `eof_code` and `reset`. +% * reposition(+Boolean): Specifies whether repositioning is required for the stream. `false` is the default. +% * type(+Type): Type can be `text` or `binary`. Defines the type of the stream, if it's optimized for plain text +% or just binary +% socket_client_open(Addr, Stream, Options) :- ( var(Addr) -> throw(error(instantiation_error, socket_client_open/3)) @@ -27,7 +44,11 @@ socket_client_open(Addr, Stream, Options) :- socket_client_open/3), '$socket_client_open'(Address, Port, Stream, Alias, EOFAction, Reposition, Type). - +%% socket_server_open(+Addr, -ServerSocket). +% +% Open a server socket, returning a ServerSocket. Use that ServerSocket to accept incoming connections in +% socket\_server\_accept/4. Addr must satisfy `Addr = Address:Port`. Depending on the operating system +% configuration, some ports might be reserved for superusers. socket_server_open(Addr, ServerSocket) :- must_be(var, ServerSocket), ( ( integer(Addr) ; var(Addr) ) -> @@ -39,7 +60,19 @@ socket_server_open(Addr, ServerSocket) :- '$socket_server_open'(Address, Port, ServerSocket) ). - +%% socket_server_accept(+ServerSocket, -Client, -Stream, +Options). +% +% Given a ServerSocket and a list of Options, accepts a incoming connection, returning data from the Client and +% a Stream to read or write data. +% +% The following options are available: +% +% * alias(+Alias): Set an alias to the stream +% * eof_action(+Action): Defined what happens if the end of the stream is reached. Values: `error`, `eof_code` and `reset`. +% * reposition(+Boolean): Specifies whether repositioning is required for the stream. `false` is the default. +% * type(+Type): Type can be `text` or `binary`. Defines the type of the stream, if it's optimized for plain text +% or just binary +% socket_server_accept(ServerSocket, Client, Stream, Options) :- must_be(var, Client), must_be(var, Stream), @@ -48,10 +81,14 @@ socket_server_accept(ServerSocket, Client, Stream, Options) :- socket_server_accept/4), '$socket_server_accept'(ServerSocket, Client, Stream, Alias, EOFAction, Reposition, Type). - +%% socket_server_close(+ServerSocket). +% +% Stops listening on that ServerSocket. It's recommended to always close a ServerSocket once it's no longer needed socket_server_close(ServerSocket) :- '$socket_server_close'(ServerSocket). - +%% current_hostname(-HostName). +% +% Returns the current hostname of the computer in which Scryer Prolog is executing right now current_hostname(HostName) :- '$current_hostname'(HostName). diff --git a/src/machine/attributed_variables.pl b/src/machine/attributed_variables.pl index 8c656e31..c288511b 100644 --- a/src/machine/attributed_variables.pl +++ b/src/machine/attributed_variables.pl @@ -1,11 +1,9 @@ :- module('$atts', []). - driver(Vars, Values) :- iterate(Vars, Values, ListOfListsOfGoalLists), !, call_goals(ListOfListsOfGoalLists), - '$reset_attr_var_state', '$return_from_verify_attr'. iterate([Var|VarBindings], [Value|ValueBindings], [ListOfGoalLists | ListsCubed]) :- diff --git a/src/machine/attributed_variables.rs b/src/machine/attributed_variables.rs index f74d3981..2bab7451 100644 --- a/src/machine/attributed_variables.rs +++ b/src/machine/attributed_variables.rs @@ -33,8 +33,8 @@ impl AttrVarInitializer { } #[inline] - pub(super) fn reset(&mut self) { - self.attr_var_queue.clear(); + pub(super) fn reset(&mut self, len: usize) { + self.attr_var_queue.truncate(len); self.bindings.clear(); } } @@ -147,6 +147,16 @@ impl MachineState { let value = unmark_cell_bits!(value); + if h != iter.focus() { + let deref_value = heap_bound_store(iter.heap, heap_bound_deref(iter.heap, value)); + + if deref_value.is_compound(iter.heap) { + // a cyclic structure is bound to the attributed variable at h. + // it mustn't be included in seen_vars. + continue; + } + } + seen_vars.push(value); seen_set.insert(h); diff --git a/src/machine/dispatch.rs b/src/machine/dispatch.rs index ee57a83e..d3a6a9e1 100644 --- a/src/machine/dispatch.rs +++ b/src/machine/dispatch.rs @@ -3533,6 +3533,14 @@ impl Machine { self.rename_file(); step_or_fail!(self, self.machine_st.p = self.machine_st.cp); } + &Instruction::CallFileCopy(_) => { + self.file_copy(); + step_or_fail!(self, self.machine_st.p += 1); + } + &Instruction::ExecuteFileCopy(_) => { + self.file_copy(); + step_or_fail!(self, self.machine_st.p = self.machine_st.cp); + } &Instruction::CallWorkingDirectory(_) => { try_or_throw!(self.machine_st, self.working_directory()); step_or_fail!(self, self.machine_st.p += 1); @@ -3683,14 +3691,6 @@ impl Machine { try_or_throw!(self.machine_st, self.get_single_char()); step_or_fail!(self, self.machine_st.p = self.machine_st.cp); } - &Instruction::CallResetAttrVarState(_) => { - self.reset_attr_var_state(); - self.machine_st.p += 1; - } - &Instruction::ExecuteResetAttrVarState(_) => { - self.reset_attr_var_state(); - self.machine_st.p = self.machine_st.cp; - } &Instruction::CallTruncateIfNoLiftedHeapGrowthDiff(_) => { self.truncate_if_no_lifted_heap_growth_diff(); step_or_fail!(self, self.machine_st.p += 1); @@ -4152,14 +4152,6 @@ impl Machine { self.get_cut_point(); step_or_fail!(self, self.machine_st.p = self.machine_st.cp); } - &Instruction::CallGetStaggeredCutPoint(_) => { - self.get_staggered_cut_point(); - step_or_fail!(self, self.machine_st.p += 1); - } - &Instruction::ExecuteGetStaggeredCutPoint(_) => { - self.get_staggered_cut_point(); - step_or_fail!(self, self.machine_st.p = self.machine_st.cp); - } &Instruction::CallGetDoubleQuotes(_) => { self.get_double_quotes(); step_or_fail!(self, self.machine_st.p += 1); diff --git a/src/machine/machine_state.rs b/src/machine/machine_state.rs index 6aa51916..2db02c01 100644 --- a/src/machine/machine_state.rs +++ b/src/machine/machine_state.rs @@ -849,6 +849,7 @@ impl MachineState { or_frame.prelude.tr = self.tr; or_frame.prelude.h = self.heap.len(); or_frame.prelude.b0 = self.b0; + or_frame.prelude.attr_var_queue_len = self.attr_var_init.attr_var_queue.len(); self.b = b; @@ -876,6 +877,7 @@ impl MachineState { or_frame.prelude.tr = self.tr; or_frame.prelude.h = self.heap.len(); or_frame.prelude.b0 = self.b0; + or_frame.prelude.attr_var_queue_len = self.attr_var_init.attr_var_queue.len(); self.b = b; diff --git a/src/machine/mod.rs b/src/machine/mod.rs index 4cd1fce8..164471f4 100644 --- a/src/machine/mod.rs +++ b/src/machine/mod.rs @@ -570,10 +570,11 @@ impl Machine { let old_tr = or_frame.prelude.tr; let curr_tr = self.machine_st.tr; let target_h = or_frame.prelude.h; + let attr_var_queue_len = or_frame.prelude.attr_var_queue_len; self.machine_st.tr = or_frame.prelude.tr; + self.reset_attr_var_state(attr_var_queue_len); - self.reset_attr_var_state(); self.machine_st.hb = target_h; self.unwind_trail(old_tr, curr_tr); @@ -603,9 +604,10 @@ impl Machine { let old_tr = or_frame.prelude.tr; let curr_tr = self.machine_st.tr; let target_h = or_frame.prelude.h; + let attr_var_queue_len = or_frame.prelude.attr_var_queue_len; self.machine_st.tr = or_frame.prelude.tr; - self.reset_attr_var_state(); + self.reset_attr_var_state(attr_var_queue_len); self.machine_st.hb = target_h; self.machine_st.p = self.machine_st.p + offset; @@ -640,7 +642,7 @@ impl Machine { self.machine_st.tr = or_frame.prelude.tr; self.machine_st.b = or_frame.prelude.b; - self.reset_attr_var_state(); + self.reset_attr_var_state(or_frame.prelude.attr_var_queue_len); self.machine_st.hb = target_h; self.machine_st.p = self.machine_st.p + offset; @@ -676,7 +678,7 @@ impl Machine { self.machine_st.tr = or_frame.prelude.tr; self.machine_st.b = or_frame.prelude.b; - self.reset_attr_var_state(); + self.reset_attr_var_state(or_frame.prelude.attr_var_queue_len); self.machine_st.hb = target_h; self.machine_st.p += 1; diff --git a/src/machine/stack.rs b/src/machine/stack.rs index 388c3008..47a4fbf4 100644 --- a/src/machine/stack.rs +++ b/src/machine/stack.rs @@ -123,6 +123,7 @@ pub(crate) struct OrFramePrelude { pub(crate) tr: usize, pub(crate) h: usize, pub(crate) b0: usize, + pub(crate) attr_var_queue_len: usize, } #[derive(Debug)] diff --git a/src/machine/system_calls.rs b/src/machine/system_calls.rs index 87ab9e48..0e4b1e16 100644 --- a/src/machine/system_calls.rs +++ b/src/machine/system_calls.rs @@ -988,6 +988,11 @@ impl MachineState { } impl Machine { + #[inline(always)] + pub(crate) fn deref_register(&mut self, i: usize) -> HeapCellValue { + self.machine_st.store(self.machine_st.deref(self.machine_st.registers[i])) + } + #[inline(always)] pub(crate) fn call_inline( &mut self, @@ -995,7 +1000,7 @@ impl Machine { call_at_index: impl Fn(&mut Machine, Atom, usize, IndexPtr) -> CallResult, ) -> CallResult { let arity = arity - 1; - let goal = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let goal = self.deref_register(1); let load_registers = |machine_st: &mut MachineState, goal: HeapCellValue| -> Option { read_heap_cell!(goal, @@ -1060,8 +1065,8 @@ impl Machine { #[inline(always)] pub(crate) fn compile_inline_or_expanded_goal(&mut self) -> CallResult { - let goal = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); - let module_name = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[4])); + let goal = self.deref_register(1); + let module_name = self.deref_register(4); // supp_vars are the supplementary variables generated by // complete_partial_goal prior to goal_expansion. @@ -1364,7 +1369,7 @@ impl Machine { #[inline(always)] pub(crate) fn bind_from_register(&mut self) { - let reg = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let reg = self.deref_register(2); let n = match Number::try_from(reg) { Ok(Number::Fixnum(n)) => usize::try_from(n.get_num()).ok(), Ok(Number::Integer(n)) => n.to_usize(), @@ -1393,9 +1398,10 @@ impl Machine { Some(host) => { let hostname = self.machine_st.atom_tbl.build_with(host); + let a1 = self.deref_register(1); self.machine_st.unify_atom( hostname, - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])) + a1 ); return; @@ -1410,7 +1416,7 @@ impl Machine { #[inline(always)] pub(crate) fn current_input(&mut self) -> CallResult { - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let addr = self.deref_register(1); let stream = self.user_input; if let Some(var) = addr.as_var() { @@ -1445,7 +1451,7 @@ impl Machine { #[inline(always)] pub(crate) fn current_output(&mut self) -> CallResult { - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let addr = self.deref_register(1); let stream = self.user_output; if let Some(var) = addr.as_var() { @@ -1562,9 +1568,7 @@ impl Machine { #[inline(always)] pub(crate) fn file_time(&mut self) { if let Some(file) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) { - let which = cell_as_atom!(self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[2] - ))); + let which = cell_as_atom!(self.deref_register(2)); if let Ok(md) = fs::metadata(file.as_str()) { if let Ok(time) = match which { @@ -1649,6 +1653,19 @@ impl Machine { self.machine_st.fail = true; } + #[inline(always)] + pub(crate) fn file_copy(&mut self) { + if let Some(file) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) { + if let Some(copied) = self.machine_st.value_to_str_like(self.machine_st.registers[2]) { + if fs::copy(file.as_str(), copied.as_str()).is_ok() { + return; + } + } + } + + self.machine_st.fail = true; + } + #[inline(always)] pub(crate) fn delete_directory(&mut self) { if let Some(dir) = self.machine_st.value_to_str_like(self.machine_st.registers[1]) { @@ -1677,16 +1694,17 @@ impl Machine { let current_atom = self.machine_st.atom_tbl.build_with(¤t); + let a1 = self.deref_register(1); self.machine_st.unify_complete_string( current_atom, - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])), + a1 ); if self.machine_st.fail { return Ok(()); } - let target = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let target = self.deref_register(2); if let Some(next) = self.machine_st.value_to_str_like(target) { if env::set_current_dir(std::path::Path::new(next.as_str())).is_ok() { @@ -1717,9 +1735,10 @@ impl Machine { let canonical_atom = self.machine_st.atom_tbl.build_with(cs); + let a2 = self.deref_register(2); self.machine_st.unify_complete_string( canonical_atom, - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])), + a2 ); return Ok(()); @@ -1735,7 +1754,8 @@ impl Machine { #[inline(always)] pub(crate) fn atom_chars(&mut self) { - let a1 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let a1 = self.deref_register(1); + let a2 = self.deref_register(2); read_heap_cell!(a1, (HeapCellValueTag::Char) => { @@ -1753,7 +1773,7 @@ impl Machine { if arity == 0 { self.machine_st.unify_complete_string( name, - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])), + a2, ); } else { self.machine_st.fail = true; @@ -1763,14 +1783,14 @@ impl Machine { if arity == 0 { self.machine_st.unify_complete_string( name, - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])), + a2, ); } else { self.machine_st.fail = true; } } (HeapCellValueTag::Var | HeapCellValueTag::AttrVar | HeapCellValueTag::StackVar) => { - let a2 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let a2 = self.deref_register(2); if let Some(str_like) = self.machine_st.value_to_str_like(a2) { let atom_cell = match str_like { @@ -1800,7 +1820,7 @@ impl Machine { #[inline(always)] pub(crate) fn atom_codes(&mut self) -> CallResult { - let a1 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let a1 = self.deref_register(1); read_heap_cell!(a1, (HeapCellValueTag::Char, c) => { @@ -1861,7 +1881,7 @@ impl Machine { #[inline(always)] pub(crate) fn atom_length(&mut self) { - let a1 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let a1 = self.deref_register(1); let len: i64 = read_heap_cell!(a1, (HeapCellValueTag::Str, s) => { @@ -1891,16 +1911,17 @@ impl Machine { } ); + let a2 = self.deref_register(2); self.machine_st.unify_fixnum( Fixnum::build_with(len), - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])), + a2, ); } #[inline(always)] pub(crate) fn call_continuation(&mut self, last_call: bool) -> CallResult { let stub_gen = || functor_stub(atom!("call_continuation"), 1); - let a1 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let a1 = self.deref_register(1); match self.machine_st.try_from_list(a1, stub_gen) { Err(e) => Err(e), @@ -1925,7 +1946,7 @@ impl Machine { #[inline(always)] pub(crate) fn chars_to_number(&mut self) -> CallResult { let stub_gen = || functor_stub(atom!("number_chars"), 2); - let a1 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let a1 = self.deref_register(1); let atom_or_string = self.machine_st.value_to_str_like(a1).unwrap(); self.machine_st.parse_number_from_string( @@ -1938,7 +1959,7 @@ impl Machine { #[inline(always)] pub(crate) fn create_partial_string(&mut self) { let atom = cell_as_atom!( - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])) + self.deref_register(1) ); if atom == atom!("") { @@ -1961,7 +1982,7 @@ impl Machine { #[inline(always)] pub(crate) fn is_partial_string(&mut self) { - let value = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let value = self.deref_register(1); let h = self.machine_st.heap.len(); self.machine_st.heap.push(value); @@ -1978,7 +1999,8 @@ impl Machine { #[inline(always)] pub(crate) fn partial_string_tail(&mut self) { - let pstr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let pstr = self.deref_register(1); + let a2 = self.deref_register(2); read_heap_cell!(pstr, (HeapCellValueTag::PStrLoc, h) => { @@ -1987,20 +2009,20 @@ impl Machine { if HeapCellValueTag::CStr == self.machine_st.heap[h].get_tag() { self.machine_st.unify_atom( atom!("[]"), - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])) + a2 ); } else { unify_fn!( self.machine_st, heap_loc_as_cell!(h+1), - self.machine_st.registers[2] + a2 ); } } (HeapCellValueTag::CStr) => { self.machine_st.unify_atom( atom!("[]"), - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])) + a2 ); } (HeapCellValueTag::Lis, h) => { @@ -2043,18 +2065,20 @@ impl Machine { } } + let addr = self.deref_register(2); + if stream.at_end_of_stream() { stream.set_past_end_of_stream(true); self.machine_st.unify_fixnum( Fixnum::build_with(-1), - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])), + addr, ); return Ok(()); } - let addr = match self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])) { + match addr { addr if addr.is_var() => addr, addr => match Number::try_from(addr) { Ok(Number::Integer(n)) => { @@ -2136,20 +2160,20 @@ impl Machine { } } + let a2 = self.deref_register(2); + if stream.at_end_of_stream() { let end_of_file = atom!("end_of_file"); stream.set_past_end_of_stream(true); self.machine_st.unify_atom( end_of_file, - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])), + a2, ); return Ok(()); } - let a2 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); - let a2 = read_heap_cell!(a2, (HeapCellValueTag::Char) => { a2 @@ -2233,20 +2257,20 @@ impl Machine { } } + let a2 = self.deref_register(2); + if stream.at_end_of_stream() { let end_of_file = atom!("end_of_file"); stream.set_past_end_of_stream(true); self.machine_st.unify_atom( end_of_file, - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])), + a2, ); return Ok(()); } - let a2 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); - let addr = read_heap_cell!(a2, (HeapCellValueTag::Var | HeapCellValueTag::StackVar | HeapCellValueTag::AttrVar) => { a2 @@ -2319,10 +2343,8 @@ impl Machine { #[inline(always)] pub(crate) fn number_to_chars(&mut self) { - let n = self.machine_st.registers[1]; - let chs = self.machine_st.registers[2]; - - let n = self.machine_st.store(self.machine_st.deref(n)); + let n = self.deref_register(1); + let chs = self.deref_register(2); let string = match Number::try_from(n) { Ok(Number::Float(OrderedFloat(n))) => { @@ -2344,13 +2366,13 @@ impl Machine { let chars_atom = self.machine_st.atom_tbl.build_with(&string.trim()); self.machine_st.unify_complete_string( chars_atom, - self.machine_st.store(self.machine_st.deref(chs)), + chs, ); } #[inline(always)] pub(crate) fn number_to_codes(&mut self) { - let n = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let n = self.deref_register(1); let chs = self.machine_st.registers[2]; let string = match Number::try_from(n) { @@ -2406,7 +2428,8 @@ impl Machine { #[inline(always)] pub(crate) fn char_code(&mut self) -> CallResult { let stub_gen = || functor_stub(atom!("char_code"), 2); - let a1 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let a1 = self.deref_register(1); + let a2 = self.deref_register(2); let c = read_heap_cell!(a1, (HeapCellValueTag::Atom, (name, _arity)) => { @@ -2423,8 +2446,6 @@ impl Machine { c } _ => { - let a2 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); - match Number::try_from(a2) { Ok(Number::Integer(n)) => { let c = match n.to_u32().and_then(std::char::from_u32) { @@ -2462,7 +2483,7 @@ impl Machine { self.machine_st.unify_fixnum( Fixnum::build_with(c as i64), - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])), + a2, ); Ok(()) @@ -2470,8 +2491,8 @@ impl Machine { #[inline(always)] pub(crate) fn char_type(&mut self) { - let a1 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); - let a2 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let a1 = self.deref_register(1); + let a2 = self.deref_register(2); let c = read_heap_cell!(a1, (HeapCellValueTag::Char, c) => { @@ -2558,7 +2579,7 @@ impl Machine { #[inline(always)] pub(crate) fn check_cut_point(&mut self) { - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let addr = self.deref_register(1); let old_b = cell_as_fixnum!(addr).get_num() as usize; let prev_b = self.machine_st.stack.index_or_frame(self.machine_st.b).prelude.b; @@ -2576,7 +2597,7 @@ impl Machine { #[inline(always)] pub(crate) fn fetch_global_var(&mut self) { - let key = cell_as_atom!(self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1]))); + let key = cell_as_atom!(self.deref_register(1)); let addr = self.machine_st.registers[2]; match self.indices.global_variables.get_mut(&key) { @@ -2621,7 +2642,7 @@ impl Machine { )?; let stub_gen = || functor_stub(atom!("put_code"), 2); - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let addr = self.deref_register(2); if addr.is_var() { let err = self.machine_st.instantiation_error(); @@ -2671,7 +2692,7 @@ impl Machine { )?; let stub_gen = || functor_stub(atom!("put_char"), 2); - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let addr = self.deref_register(2); if addr.is_var() { let err = self.machine_st.instantiation_error(); @@ -2757,7 +2778,7 @@ impl Machine { )?; let stub_gen = || functor_stub(atom!("put_byte"), 2); - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let addr = self.deref_register(2); if addr.is_var() { let err = self.machine_st.instantiation_error(); @@ -2833,7 +2854,7 @@ impl Machine { } let stub_gen = || functor_stub(atom!("get_byte"), 2); - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let addr = self.deref_register(2); let addr = if addr.is_var() { addr @@ -2912,13 +2933,15 @@ impl Machine { } } + let addr = self.deref_register(2); + if stream.at_end_of_stream() { let end_of_file = atom!("end_of_file"); stream.set_past_end_of_stream(true); self.machine_st.unify_atom( end_of_file, - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])) + addr ); return Ok(()); @@ -2927,8 +2950,6 @@ impl Machine { let stub_gen = || functor_stub(atom!("get_char"), 2); let mut iter = self.machine_st.open_parsing_stream(stream, atom!("get_char"), 2)?; - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); - let addr = if addr.is_var() { addr } else { @@ -2983,7 +3004,7 @@ impl Machine { 3, )?; - let num = match Number::try_from(self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2]))) { + let num = match Number::try_from(self.deref_register(2)) { Ok(Number::Fixnum(n)) => usize::try_from(n.get_num()).unwrap(), Ok(Number::Integer(n)) => match n.to_usize() { Some(u) => u, @@ -3025,7 +3046,7 @@ impl Machine { } }; - let output = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[3])); + let output = self.deref_register(3); let atom = self.machine_st.atom_tbl.build_with(&string); self.machine_st.unify_complete_string(atom, output); @@ -3057,19 +3078,20 @@ impl Machine { } } + let addr = self.deref_register(2); + if stream.at_end_of_stream() { stream.set_past_end_of_stream(true); self.machine_st.unify_fixnum( Fixnum::build_with(-1), - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])), + addr, ); return Ok(()); } let stub_gen = || functor_stub(atom!("get_code"), 2); - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); let addr = if addr.is_var() { addr @@ -3155,9 +3177,7 @@ impl Machine { if let Some(first_stream) = first_stream { let stream = stream_as_cell!(first_stream); - let var = self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[1] - )).as_var().unwrap(); + let var = self.deref_register(1).as_var().unwrap(); self.machine_st.bind(var, stream); } else { @@ -3167,9 +3187,7 @@ impl Machine { #[inline(always)] pub(crate) fn next_stream(&mut self) { - let prev_stream = cell_as_stream!(self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[1] - ))); + let prev_stream = cell_as_stream!(self.deref_register(1)); let mut next_stream = None; let mut null_streams = BTreeSet::new(); @@ -3191,9 +3209,7 @@ impl Machine { self.indices.streams = self.indices.streams.sub(&null_streams); if let Some(next_stream) = next_stream { - let var = self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[2] - )).as_var().unwrap(); + let var = self.deref_register(2).as_var().unwrap(); let next_stream = stream_as_cell!(next_stream); self.machine_st.bind(var, next_stream); @@ -3252,9 +3268,10 @@ impl Machine { _ => unreachable!(), }; + let a1 = self.deref_register(1); self.machine_st.unify_char( c, - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])), + a1, ); Ok(()) @@ -3262,12 +3279,10 @@ impl Machine { #[inline(always)] pub(crate) fn head_is_dynamic(&mut self) { - let module_name = cell_as_atom!(self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[1]) - )); + let module_name = cell_as_atom!(self.deref_register(1)); let (name, arity) = read_heap_cell!( - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])), + self.deref_register(2), (HeapCellValueTag::Str, s) => { cell_as_atom_cell!(self.machine_st.heap[s]).get_name_and_arity() } @@ -3337,7 +3352,7 @@ impl Machine { #[inline(always)] pub(crate) fn copy_to_lifted_heap(&mut self) { let lh_offset = cell_as_fixnum!( - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])) + self.deref_register(1) ).get_num() as usize; let copy_target = self.machine_st.registers[2]; @@ -3352,79 +3367,12 @@ impl Machine { } } - #[inline(always)] - pub(crate) fn delete_attribute(&mut self) { - let ls0 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); - - if let HeapCellValueTag::Lis = ls0.get_tag() { - let l1 = ls0.get_value(); - let ls1 = self.machine_st.store(self.machine_st.deref(heap_loc_as_cell!(l1 + 1))); - - if let HeapCellValueTag::Lis = ls1.get_tag() { - let l2 = ls1.get_value(); - - let old_addr = self.machine_st.store(self.machine_st.deref(self.machine_st.heap[l1+1])); - let tail = self.machine_st.store(self.machine_st.deref(heap_loc_as_cell!(l2 + 1))); - - let tail = if tail.is_var() { - heap_loc_as_cell!(l1 + 1) - } else { - tail - }; - - let trail_ref = read_heap_cell!(old_addr, - (HeapCellValueTag::Var, h) => { - TrailRef::AttrVarHeapLink(h) - } - (HeapCellValueTag::Lis, l) => { - TrailRef::AttrVarListLink(l1 + 1, l) - } - _ => { - unreachable!() - } - ); - - self.machine_st.heap[l1 + 1] = tail; - self.machine_st.trail(trail_ref); - } - } - } - - #[inline(always)] - pub(crate) fn delete_head_attribute(&mut self) { - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); - - debug_assert_eq!(addr.get_tag(), HeapCellValueTag::AttrVar); - - let h = addr.get_value(); - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.heap[h + 1])); - - debug_assert_eq!(addr.get_tag(), HeapCellValueTag::Lis); - - let l = addr.get_value(); - let tail = self.machine_st.store(self.machine_st.deref(self.machine_st.heap[l + 1])); - - let tail = if tail.is_var() { - self.machine_st.heap[h] = heap_loc_as_cell!(h); - self.machine_st.trail(TrailRef::Ref(Ref::attr_var(h))); - - heap_loc_as_cell!(h + 1) - } else { - tail - }; - - self.machine_st.heap[h + 1] = tail; - self.machine_st.trail(TrailRef::AttrVarListLink(h + 1, l)); - } - #[inline(always)] pub(crate) fn dynamic_module_resolution( &mut self, narity: usize, ) -> Result<(Atom, PredicateKey), MachineStub> { - let module_name = self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[1] - )); + let module_name = self.deref_register(1); let module_name = read_heap_cell!(module_name, (HeapCellValueTag::Atom, (name, _arity)) => { @@ -3446,9 +3394,7 @@ impl Machine { } ); - let goal = self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[2] - )); + let goal = self.deref_register(2); let (name, arity, s) = self.machine_st.setup_call_n_init_goal_info(goal, narity)?; @@ -3475,22 +3421,9 @@ impl Machine { Ok((module_name, key)) } - #[inline(always)] - pub(crate) fn enqueue_attributed_var(&mut self) { - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); - - read_heap_cell!(addr, - (HeapCellValueTag::AttrVar, h) => { - self.machine_st.attr_var_init.attr_var_queue.push(h); - } - _ => { - } - ); - } - #[inline(always)] pub(crate) fn get_next_db_ref(&mut self) { - let a1 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let a1 = self.deref_register(1); if let Some(name_var) = a1.as_var() { let mut iter = self.indices.code_dir.iter(); @@ -3508,9 +3441,7 @@ impl Machine { self.machine_st.fail = true; } else if a1.get_tag() == HeapCellValueTag::Atom { let name = cell_as_atom!(a1); - let arity = cell_as_fixnum!(self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[2]) - )).get_num() as usize; + let arity = cell_as_fixnum!(self.deref_register(2)).get_num() as usize; match self.machine_st.get_next_db_ref(&self.indices, &DBRef::NamedPred(name, arity)) { Some(DBRef::NamedPred(name, arity)) => { @@ -3534,12 +3465,12 @@ impl Machine { #[inline(always)] pub(crate) fn get_next_op_db_ref(&mut self) { - let prec = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let prec = self.deref_register(1); if let Some(prec_var) = prec.as_var() { - let spec = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); - let op = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[3])); - let orig_op = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[7])); + let spec = self.deref_register(2); + let op = self.deref_register(3); + let orig_op = self.deref_register(7); let spec_num = if spec.get_tag() == HeapCellValueTag::Atom { (match cell_as_atom!(spec) { @@ -3666,9 +3597,7 @@ impl Machine { match ossified_op_dir.iter().next() { Some(((op_atom, _), (op_prec, op_spec))) => { - let ossified_op_dir_var = self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[4] - )).as_var().unwrap(); + let ossified_op_dir_var = self.deref_register(4).as_var().unwrap(); let spec_atom = match *op_spec { FX => atom!("fx"), @@ -3698,9 +3627,9 @@ impl Machine { } } } else { - let spec = cell_as_atom!(self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2]))); - let op_atom = cell_as_atom!(self.machine_st.store(self.machine_st.deref(self.machine_st.registers[3]))); - let ossified_op_dir_cell = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[4])); + let spec = cell_as_atom!(self.deref_register(2)); + let op_atom = cell_as_atom!(self.deref_register(3)); + let ossified_op_dir_cell = self.deref_register(4); if ossified_op_dir_cell.is_var() { self.machine_st.fail = true; @@ -3783,7 +3712,7 @@ impl Machine { #[inline(always)] pub(crate) fn det_length_rundown(&mut self) -> CallResult { let stub_gen = || functor_stub(atom!("length"), 2); - let len = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let len = self.deref_register(2); let n = match Number::try_from(len) { Ok(Number::Fixnum(n)) => n.get_num() as usize, @@ -3806,7 +3735,7 @@ impl Machine { (0 .. n).map(|i| heap_loc_as_cell!(h + 2 * i + 1)), ); - let tail = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let tail = self.deref_register(1); self.machine_st.bind(tail.as_var().unwrap(), heap_loc_as_cell!(h)); Ok(()) @@ -3814,8 +3743,8 @@ impl Machine { #[inline(always)] pub(crate) fn http_open(&mut self) -> CallResult { - let address_sink = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); - let method = read_heap_cell!(self.machine_st.store(self.machine_st.deref(self.machine_st.registers[3])), + let address_sink = self.deref_register(1); + let method = read_heap_cell!(self.deref_register(3), (HeapCellValueTag::Atom, (name, arity)) => { debug_assert_eq!(arity, 0); match name { @@ -3832,8 +3761,8 @@ impl Machine { unreachable!() } ); - let address_status = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[4])); - let address_data = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[5])); + let address_status = self.deref_register(4); + let address_data = self.deref_register(5); let mut bytes: Vec = Vec::new(); if let Some(string) = self.machine_st.value_to_str_like(address_data) { bytes = string.as_str().bytes().collect(); @@ -3915,7 +3844,7 @@ impl Machine { stream_as_cell!(stream) }); - let stream_addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let stream_addr = self.deref_register(2); self.machine_st.bind(stream_addr.as_var().unwrap(), stream); } else { @@ -3930,7 +3859,7 @@ impl Machine { #[inline(always)] pub(crate) fn http_listen(&mut self) -> CallResult { - let address_sink = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let address_sink = self.deref_register(1); if let Some(address_str) = self.machine_st.value_to_str_like(address_sink) { let address_string = address_str.as_str(); let addr: SocketAddr = match address_string.to_socket_addrs().ok().and_then(|mut s| s.next()) { @@ -3965,7 +3894,7 @@ impl Machine { }); let http_listener = HttpListener { incoming: rx }; let http_listener = arena_alloc!(http_listener, &mut self.machine_st.arena); - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let addr = self.deref_register(2); self.machine_st.bind(addr.as_var().unwrap(), typed_arena_ptr_as_cell!(http_listener)); } Ok(()) @@ -3973,12 +3902,12 @@ impl Machine { #[inline(always)] pub(crate) fn http_accept(&mut self) -> CallResult { - let culprit = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); - let method = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); - let path = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[3])); - let query = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[5])); - let stream_addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[6])); - let handle_addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[7])); + let culprit = self.deref_register(1); + let method = self.deref_register(2); + let path = self.deref_register(3); + let query = self.deref_register(5); + let stream_addr = self.deref_register(6); + let handle_addr = self.deref_register(7); read_heap_cell!(culprit, (HeapCellValueTag::Cons, cons_ptr) => { match_untyped_arena_ptr!(cons_ptr, @@ -4056,8 +3985,8 @@ impl Machine { #[inline(always)] pub(crate) fn http_answer(&mut self) -> CallResult { - let culprit = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); - let status_code = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let culprit = self.deref_register(1); + let status_code = self.deref_register(2); let status_code: u16 = match Number::try_from(status_code) { Ok(Number::Fixnum(n)) => n.get_num() as u16, Ok(Number::Integer(n)) => match n.to_u16() { @@ -4089,7 +4018,7 @@ impl Machine { }, Err(e) => return Err(e) }; - let stream_addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[4])); + let stream_addr = self.deref_register(4); read_heap_cell!(culprit, (HeapCellValueTag::Cons, cons_ptr) => { @@ -4139,7 +4068,7 @@ impl Machine { let stream_type = self.machine_st.registers[7]; let options = self.machine_st.to_stream_options(alias, eof_action, reposition, stream_type); - let src_sink = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let src_sink = self.deref_register(1); if let Some(file_spec) = self.machine_st.value_to_str_like(src_sink) { let file_spec = file_spec.as_atom(&mut self.machine_st.atom_tbl); @@ -4157,7 +4086,7 @@ impl Machine { self.indices.stream_aliases.insert(alias, stream); } - let stream_var = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[3])); + let stream_var = self.deref_register(3); self.machine_st.bind(stream_var.as_var().unwrap(), stream_as_cell!(stream)); } else { let err = self.machine_st.domain_error(DomainErrorType::SourceSink, src_sink); @@ -4171,11 +4100,8 @@ impl Machine { #[inline(always)] pub(crate) fn op_declaration(&mut self) -> CallResult { - let priority = self.machine_st.registers[1]; - let specifier = self.machine_st.registers[2]; - let op = self.machine_st.registers[3]; - - let priority = self.machine_st.store(self.machine_st.deref(priority)); + let priority = self.deref_register(1); + let specifier = cell_as_atom_cell!(self.deref_register(2)).get_name(); let priority = match Number::try_from(priority) { Ok(Number::Integer(n)) => n.to_u16().unwrap(), @@ -4185,10 +4111,7 @@ impl Machine { } }; - let specifier = cell_as_atom_cell!(self.machine_st.store(self.machine_st.deref(specifier))) - .get_name(); - - let op = read_heap_cell!(self.machine_st.store(self.machine_st.deref(op)), + let op = read_heap_cell!(self.deref_register(3), (HeapCellValueTag::Char, c) => { self.machine_st.atom_tbl.build_with(&c.to_string()) } @@ -4262,7 +4185,7 @@ impl Machine { #[inline(always)] pub(crate) fn get_attributed_variable_list(&mut self) { - let attr_var = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let attr_var = self.deref_register(1); let attr_var_list = read_heap_cell!(attr_var, (HeapCellValueTag::AttrVar, h) => { h + 1 @@ -4283,22 +4206,21 @@ impl Machine { } ); - let list_addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let list_addr = self.deref_register(2); self.machine_st.bind(Ref::heap_cell(attr_var_list), list_addr); } #[inline(always)] pub(crate) fn get_attr_var_queue_delimiter(&mut self) { - let addr = self.machine_st.registers[1]; + let addr = self.deref_register(1); let value = Fixnum::build_with(self.machine_st.attr_var_init.attr_var_queue.len() as i64); - self.machine_st.unify_fixnum(value, self.machine_st.store(self.machine_st.deref(addr))); + self.machine_st.unify_fixnum(value, addr); } #[inline(always)] pub(crate) fn get_attr_var_queue_beyond(&mut self) { - let addr = self.machine_st.registers[1]; - let addr = self.machine_st.store(self.machine_st.deref(addr)); + let addr = self.deref_register(1); let b = match Number::try_from(addr) { Ok(Number::Integer(n)) => n.to_usize(), @@ -4321,14 +4243,90 @@ impl Machine { } } + #[inline(always)] + pub(crate) fn enqueue_attributed_var(&mut self) { + let addr = self.deref_register(1); + + read_heap_cell!(addr, + (HeapCellValueTag::AttrVar, h) => { + self.machine_st.attr_var_init.attr_var_queue.push(h); + } + _ => { + } + ); + } + + #[inline(always)] + pub(crate) fn delete_attribute(&mut self) { + let ls0 = self.deref_register(1); + + if let HeapCellValueTag::Lis = ls0.get_tag() { + let l1 = ls0.get_value(); + let ls1 = self.machine_st.store(self.machine_st.deref(heap_loc_as_cell!(l1 + 1))); + + if let HeapCellValueTag::Lis = ls1.get_tag() { + let l2 = ls1.get_value(); + + let old_addr = self.machine_st.store(self.machine_st.deref(self.machine_st.heap[l1+1])); + let tail = self.machine_st.store(self.machine_st.deref(heap_loc_as_cell!(l2 + 1))); + + let tail = if tail.is_var() { + heap_loc_as_cell!(l1 + 1) + } else { + tail + }; + + let trail_ref = read_heap_cell!(old_addr, + (HeapCellValueTag::Var, h) => { + TrailRef::AttrVarHeapLink(h) + } + (HeapCellValueTag::Lis, l) => { + TrailRef::AttrVarListLink(l1 + 1, l) + } + _ => { + unreachable!() + } + ); + + self.machine_st.heap[l1 + 1] = tail; + self.machine_st.trail(trail_ref); + } + } + } + + #[inline(always)] + pub(crate) fn delete_head_attribute(&mut self) { + let addr = self.deref_register(1); + + debug_assert_eq!(addr.get_tag(), HeapCellValueTag::AttrVar); + + let h = addr.get_value(); + let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.heap[h + 1])); + + debug_assert_eq!(addr.get_tag(), HeapCellValueTag::Lis); + + let l = addr.get_value(); + let tail = self.machine_st.store(self.machine_st.deref(self.machine_st.heap[l + 1])); + + let tail = if tail.is_var() { + self.machine_st.heap[h] = heap_loc_as_cell!(h); + self.machine_st.trail(TrailRef::Ref(Ref::attr_var(h))); + + heap_loc_as_cell!(h + 1) + } else { + tail + }; + + self.machine_st.heap[h + 1] = tail; + self.machine_st.trail(TrailRef::AttrVarListLink(h + 1, l)); + } + #[inline(always)] pub(crate) fn get_continuation_chunk(&mut self) { - let e = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let e = self.deref_register(1); let e = cell_as_fixnum!(e).get_num() as usize; - let p_functor = self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[2] - )); + let p_functor = self.deref_register(2); let p = to_local_code_ptr(&self.machine_st.heap, p_functor).unwrap(); @@ -4421,7 +4419,7 @@ impl Machine { #[inline(always)] pub(crate) fn get_double_quotes(&mut self) { - let a1 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let a1 = self.deref_register(1); self.machine_st.unify_atom( match self.machine_st.flags.double_quotes { @@ -4457,7 +4455,7 @@ impl Machine { #[inline(always)] pub(crate) fn halt(&mut self) { - let code = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let code = self.deref_register(1); let code = match Number::try_from(code) { Ok(Number::Fixnum(n)) => i32::try_from(n.get_num()).unwrap(), @@ -4491,8 +4489,8 @@ impl Machine { #[inline(always)] pub(crate) fn install_inference_counter(&mut self) -> CallResult { // A1 = B, A2 = L - let a1 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); - let a2 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let a1 = self.deref_register(1); + let a2 = self.deref_register(2); let n = match Number::try_from(a2) { Ok(Number::Fixnum(bp)) => bp.get_num() as usize, @@ -4514,7 +4512,7 @@ impl Machine { self.machine_st.increment_call_count_fn = MachineState::increment_call_count; - let a3 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[3])); + let a3 = self.deref_register(3); self.machine_st.unify_big_int(count, a3); Ok(()) @@ -4522,24 +4520,18 @@ impl Machine { #[inline(always)] pub(crate) fn module_exists(&mut self) { - let module = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let module = self.deref_register(1); let module_name = cell_as_atom!(module); self.machine_st.fail = !self.indices.modules.contains_key(&module_name); } - pub(crate) fn predicate_defined(&self) -> bool { - let module_name = cell_as_atom!(self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[1] - ))); + pub(crate) fn predicate_defined(&mut self) -> bool { + let module_name = cell_as_atom!(self.deref_register(1)); + let name = cell_as_atom!(self.deref_register(2)); + let a3 = self.deref_register(3); - let name = cell_as_atom!(self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[2] - ))); - - let arity = match Number::try_from(self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[3] - ))) { + let arity = match Number::try_from(a3) { Ok(Number::Fixnum(n)) => n.get_num() as usize, Ok(Number::Integer(n)) => { if let Some(n) = n.to_usize() { @@ -4563,11 +4555,9 @@ impl Machine { #[inline(always)] pub(crate) fn no_such_predicate(&mut self) -> CallResult { - let module_name = cell_as_atom!(self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[1] - ))); + let module_name = cell_as_atom!(self.deref_register(1)); - let head = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let head = self.deref_register(2); self.machine_st.fail = read_heap_cell!(head, (HeapCellValueTag::Str, s) => { @@ -4623,8 +4613,8 @@ impl Machine { } #[inline(always)] pub(crate) fn redo_attr_var_binding(&mut self) { - let var = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); - let value = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let var = self.deref_register(1); + let value = self.deref_register(2); debug_assert_eq!(HeapCellValueTag::AttrVar, var.get_tag()); self.machine_st.heap[var.get_value()] = value; @@ -4646,16 +4636,14 @@ impl Machine { } #[inline(always)] - pub(crate) fn reset_attr_var_state(&mut self) { + pub(crate) fn reset_attr_var_state(&mut self, queue_len: usize) { self.restore_instr_at_verify_attr_interrupt(); - self.machine_st.attr_var_init.reset(); + self.machine_st.attr_var_init.reset(queue_len); } #[inline(always)] pub(crate) fn remove_call_policy_check(&mut self) { - let bp = cell_as_fixnum!(self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[1] - ))).get_num() as usize; + let bp = cell_as_fixnum!(self.deref_register(1)).get_num() as usize; if bp == self.machine_st.b && self.machine_st.cwil.is_empty() { self.machine_st.cwil.reset(); @@ -4665,19 +4653,21 @@ impl Machine { #[inline(always)] pub(crate) fn remove_inference_counter(&mut self) { - let a1 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let a1 = self.deref_register(1); let bp = cell_as_fixnum!(a1).get_num() as usize; let count = self.machine_st.cwil.remove_limit(bp).clone(); let count = arena_alloc!(count.clone(), &mut self.machine_st.arena); - let a2 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let a2 = self.deref_register(2); self.machine_st.unify_big_int(count, a2); } #[inline(always)] pub(crate) fn return_from_verify_attr(&mut self) { + self.restore_instr_at_verify_attr_interrupt(); + let e = self.machine_st.e; let frame_len = self.machine_st.stack.index_and_frame(e).prelude.univ_prelude.num_cells; @@ -4720,9 +4710,7 @@ impl Machine { #[inline(always)] pub(crate) fn set_input(&mut self) -> CallResult { - let addr = self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[1] - )); + let addr = self.deref_register(1); let stream = self.machine_st.get_stream_or_alias( addr, @@ -4750,7 +4738,7 @@ impl Machine { #[inline(always)] pub(crate) fn set_output(&mut self) -> CallResult { - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let addr = self.deref_register(1); let stream = self.machine_st.get_stream_or_alias( addr, &self.indices.stream_aliases, @@ -4792,8 +4780,8 @@ impl Machine { #[inline(always)] pub(crate) fn inference_level(&mut self) { - let a1 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); - let a2 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let a1 = self.deref_register(1); + let a2 = self.deref_register(2); let bp = cell_as_fixnum!(a2).get_num() as usize; let prev_b = self.machine_st.stack.index_or_frame(self.machine_st.b).prelude.b; @@ -4807,7 +4795,7 @@ impl Machine { #[inline(always)] pub(crate) fn clean_up_block(&mut self) { - let nb = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let nb = self.deref_register(1); let nb = cell_as_fixnum!(nb).get_num() as usize; let b = self.machine_st.b; @@ -4819,7 +4807,7 @@ impl Machine { #[inline(always)] pub(crate) fn get_ball(&mut self) { - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let addr = self.deref_register(1); let h = self.machine_st.heap.len(); if self.machine_st.ball.stub.len() > 0 { @@ -4877,65 +4865,9 @@ impl Machine { self.machine_st.unify_fixnum(n, self.machine_st.registers[1]); } - #[inline(always)] - pub(crate) fn get_staggered_cut_point(&mut self) { - use std::sync::Once; - - let b = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); - - static mut SEMICOLON_SECOND_BRANCH_LOC: usize = 0; - static LOC_INIT: Once = Once::new(); - - let semicolon_second_clause_p = unsafe { - LOC_INIT.call_once(|| { - if let Some(builtins) = self.indices.modules.get(&atom!("builtins")) { - match builtins.code_dir.get(&(atom!("staggered_sc"), 2)).map(|cell| cell.get()) { - Some(ip) if ip.tag() == IndexPtrTag::Index => { - let p = ip.p() as usize; - - match &self.code[p] { - &Instruction::TryMeElse(o) => { - SEMICOLON_SECOND_BRANCH_LOC = p + o; - } - _ => { - unreachable!(); - } - } - } - _ => { - unreachable!(); - } - } - } else { - unreachable!(); - } - }); - - SEMICOLON_SECOND_BRANCH_LOC - }; - - let staggered_b0 = if self.machine_st.b > 0 { - let or_frame = self.machine_st.stack.index_or_frame(self.machine_st.b); - - if or_frame.prelude.bp == semicolon_second_clause_p { - or_frame.prelude.b0 - } else { - self.machine_st.b0 - } - } else { - self.machine_st.b0 - }; - - let staggered_b0 = integer_as_cell!( - Number::arena_from(staggered_b0, &mut self.machine_st.arena) - ); - - self.machine_st.bind(b.as_var().unwrap(), staggered_b0); - } - #[inline(always)] pub(crate) fn next_ep(&mut self) { - let first_arg = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let first_arg = self.deref_register(1); let next_ep_atom = |machine_st: &mut MachineState, name, arity| { debug_assert_eq!(name, atom!("first")); @@ -5004,7 +4936,7 @@ impl Machine { #[inline(always)] pub(crate) fn points_to_continuation_reset_marker(&mut self) { - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let addr = self.deref_register(1); let p = match to_local_code_ptr(&self.machine_st.heap, addr) { Some(p) => p + 1, @@ -5021,7 +4953,7 @@ impl Machine { #[inline(always)] pub(crate) fn quoted_token(&mut self) { - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let addr = self.deref_register(1); read_heap_cell!(addr, (HeapCellValueTag::Fixnum, n) => { @@ -5102,9 +5034,7 @@ impl Machine { }; let result = heap_loc_as_cell!(term_write_result.heap_loc); - let var = self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[2] - )).as_var().unwrap(); + let var = self.deref_register(2).as_var().unwrap(); self.machine_st.bind(var, result); } else { @@ -5137,7 +5067,7 @@ impl Machine { #[inline(always)] pub(crate) fn set_seed(&mut self) { - let seed = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let seed = self.deref_register(1); let mut rand = RANDOM_STATE.borrow_mut(); match Number::try_from(seed) { @@ -5152,7 +5082,7 @@ impl Machine { #[inline(always)] pub(crate) fn sleep(&mut self) { - let time = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let time = self.deref_register(1); let time = match Number::try_from(time) { Ok(Number::Float(n)) => n.into_inner(), @@ -5171,8 +5101,8 @@ impl Machine { #[inline(always)] pub(crate) fn socket_client_open(&mut self) -> CallResult { - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); - let port = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let addr = self.deref_register(1); + let port = self.deref_register(2); let socket_atom = cell_as_atom!(addr); @@ -5259,7 +5189,7 @@ impl Machine { } }; - let stream_addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[3])); + let stream_addr = self.deref_register(3); self.machine_st.bind(stream_addr.as_var().unwrap(), stream); Ok(()) @@ -5267,7 +5197,7 @@ impl Machine { #[inline(always)] pub(crate) fn socket_server_open(&mut self) -> CallResult { - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let addr = self.deref_register(1); let socket_atom = cell_as_atom_cell!(addr).get_name(); let socket_atom = if socket_atom == atom!("[]") { @@ -5276,7 +5206,7 @@ impl Machine { socket_atom }; - let port = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let port = self.deref_register(2); let port = if port.is_var() { String::from("0") @@ -5319,7 +5249,7 @@ impl Machine { } }; - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[3])); + let addr = self.deref_register(3); self.machine_st.bind(addr.as_var().unwrap(), typed_arena_ptr_as_cell!(tcp_listener)); if had_zero_port { @@ -5352,7 +5282,7 @@ impl Machine { } } - let culprit = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let culprit = self.deref_register(1); read_heap_cell!(culprit, (HeapCellValueTag::Cons, cons_ptr) => { @@ -5379,12 +5309,8 @@ impl Machine { let tcp_stream = stream_as_cell!(tcp_stream); let client = atom_as_cell!(client); - let client_addr = self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[2], - )); - let stream_addr = self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[3], - )); + let client_addr = self.deref_register(2); + let stream_addr = self.deref_register(3); self.machine_st.bind(client_addr.as_var().unwrap(), client); self.machine_st.bind(stream_addr.as_var().unwrap(), tcp_stream); @@ -5433,7 +5359,7 @@ impl Machine { self.indices.streams.insert(stream); self.machine_st.heap.push(stream_as_cell!(stream)); - let stream_addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[3])); + let stream_addr = self.deref_register(3); self.machine_st.bind(stream_addr.as_var().unwrap(), stream_as_cell!(stream)); Ok(()) @@ -5483,7 +5409,7 @@ impl Machine { let stream = Stream::from_tls_stream(atom!("TLS"), stream, &mut self.machine_st.arena); self.indices.streams.insert(stream); - let stream_addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[4])); + let stream_addr = self.deref_register(4); self.machine_st.bind(stream_addr.as_var().unwrap(), stream_as_cell!(stream)); } else { unreachable!(); @@ -5494,7 +5420,7 @@ impl Machine { #[inline(always)] pub(crate) fn socket_server_close(&mut self) -> CallResult { - let culprit = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let culprit = self.deref_register(1); read_heap_cell!(culprit, (HeapCellValueTag::Cons, cons_ptr) => { @@ -5543,7 +5469,7 @@ impl Machine { return Err(self.machine_st.error_form(err, stub)); } - let position = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let position = self.deref_register(2); let position = match Number::try_from(position) { Ok(Number::Fixnum(n)) => n.get_num() as u64, @@ -5573,9 +5499,7 @@ impl Machine { 2, )?; - let atom = cell_as_atom!(self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[2] - ))); + let atom = cell_as_atom!(self.deref_register(2)); let property = match atom { atom!("file_name") => { @@ -5647,7 +5571,7 @@ impl Machine { #[inline(always)] pub(crate) fn store_global_var(&mut self) { - let key = cell_as_atom!(self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1]))); + let key = cell_as_atom!(self.deref_register(1)); let value = self.machine_st.registers[2]; let mut ball = Ball::new(); @@ -5665,8 +5589,8 @@ impl Machine { #[inline(always)] pub(crate) fn store_backtrackable_global_var(&mut self) { - let key = cell_as_atom!(self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1]))); - let new_value = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])); + let key = cell_as_atom!(self.deref_register(1)); + let new_value = self.deref_register(2); match self.indices.global_variables.get_mut(&key) { Some((_, ref mut loc)) => match loc { @@ -5691,9 +5615,10 @@ impl Machine { #[inline(always)] pub(crate) fn term_attributed_variables(&mut self) { if self.machine_st.registers[1].is_constant() { + let a2 = self.deref_register(2); self.machine_st.unify_atom( atom!("[]"), - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])), + a2, ); return; @@ -5709,13 +5634,11 @@ impl Machine { #[inline(always)] pub(crate) fn term_variables(&mut self) { - let a1 = self.machine_st.registers[1]; - let a2 = self.machine_st.registers[2]; - - let stored_v = self.machine_st.store(self.machine_st.deref(a1)); + let stored_v = self.deref_register(1); + let a2 = self.deref_register(2); if stored_v.is_constant() { - self.machine_st.unify_atom(atom!("[]"), self.machine_st.store(self.machine_st.deref(a2))); + self.machine_st.unify_atom(atom!("[]"), a2); return; } @@ -5734,7 +5657,7 @@ impl Machine { pub(crate) fn term_variables_under_max_depth(&mut self) { // Term, MaxDepth, VarList let max_depth = cell_as_fixnum!( - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[2])) + self.deref_register(2) ).get_num() as usize; self.machine_st.term_variables_under_max_depth( @@ -5746,7 +5669,7 @@ impl Machine { #[inline(always)] pub(crate) fn truncate_lifted_heap_to(&mut self) { - let a1 = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let a1 = self.deref_register(1); let lh_offset = cell_as_fixnum!(a1).get_num() as usize; self.machine_st.lifted_heap.truncate(lh_offset); @@ -5784,15 +5707,9 @@ impl Machine { #[inline(always)] pub(crate) fn wam_instructions(&mut self) -> CallResult { - let module_name = cell_as_atom!(self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[1]) - )); - - let name = self.machine_st.registers[2]; - let arity = self.machine_st.registers[3]; - - let name = cell_as_atom!(self.machine_st.store(self.machine_st.deref(name))); - let arity = self.machine_st.store(self.machine_st.deref(arity)); + let module_name = cell_as_atom!(self.deref_register(1)); + let name = cell_as_atom!(self.deref_register(2)); + let arity = self.deref_register(3); let arity = match Number::try_from(arity) { Ok(Number::Fixnum(n)) => n.get_num() as usize, @@ -5968,9 +5885,7 @@ impl Machine { &mut self.machine_st.atom_tbl, ); - let result_addr = self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[1] - )); + let result_addr = self.deref_register(1); if let Some(var) = result_addr.as_var() { self.machine_st.bind(var, chars); @@ -5988,9 +5903,10 @@ impl Machine { let buffer = git_version!(cargo_prefix = "cargo:", fallback = "unknown"); let buffer_atom = self.machine_st.atom_tbl.build_with(buffer); + let a1 = self.deref_register(1); self.machine_st.unify_complete_string( buffer_atom, - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])), + a1, ); } @@ -6016,10 +5932,10 @@ impl Machine { #[inline(always)] pub(crate) fn crypto_data_hash(&mut self) { - let encoding = cell_as_atom!(self.machine_st.registers[2]); + let encoding = cell_as_atom!(self.deref_register(2)); let bytes = self.string_encoding_bytes(self.machine_st.registers[1], encoding); - let algorithm = cell_as_atom!(self.machine_st.registers[4]); + let algorithm = cell_as_atom!(self.deref_register(4)); let ints_list = match algorithm { atom!("sha3_224") => { @@ -6156,7 +6072,7 @@ impl Machine { #[inline(always)] pub(crate) fn crypto_data_hkdf(&mut self) { - let encoding = cell_as_atom!(self.machine_st.registers[2]); + let encoding = cell_as_atom!(self.deref_register(2)); let data = self.string_encoding_bytes(self.machine_st.registers[1], encoding); let stub1_gen = || functor_stub(atom!("crypto_data_hkdf"), 4); @@ -6165,9 +6081,9 @@ impl Machine { let stub2_gen = || functor_stub(atom!("crypto_data_hkdf"), 4); let info = self.machine_st.integers_to_bytevec(self.machine_st.registers[4], stub2_gen); - let algorithm = cell_as_atom!(self.machine_st.registers[5]); + let algorithm = cell_as_atom!(self.deref_register(5)); - let length = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[6])); + let length = self.deref_register(6); let length = match Number::try_from(length) { Ok(Number::Fixnum(n)) => usize::try_from(n.get_num()).unwrap(), @@ -6229,7 +6145,7 @@ impl Machine { let stub2_gen = || functor_stub(atom!("crypto_password_hash"), 3); let salt = self.machine_st.integers_to_bytevec(self.machine_st.registers[2], stub2_gen); - let iterations = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[3])); + let iterations = self.deref_register(3); let iterations = match Number::try_from(iterations) { Ok(Number::Fixnum(n)) => u64::try_from(n.get_num()).unwrap(), @@ -6271,7 +6187,7 @@ impl Machine { #[inline(always)] pub(crate) fn crypto_data_encrypt(&mut self) { - let encoding = cell_as_atom!(self.machine_st.registers[3]); + let encoding = cell_as_atom!(self.deref_register(3)); let data = self.string_encoding_bytes(self.machine_st.registers[1], encoding); let aad = self.string_encoding_bytes(self.machine_st.registers[2], encoding); @@ -6318,7 +6234,7 @@ impl Machine { #[inline(always)] pub(crate) fn crypto_data_decrypt(&mut self) { let data = self.string_encoding_bytes(self.machine_st.registers[1], atom!("octet")); - let encoding = cell_as_atom!(self.machine_st.store(self.machine_st.deref(self.machine_st.registers[5]))); + let encoding = cell_as_atom!(self.deref_register(5)); let aad = self.string_encoding_bytes(self.machine_st.registers[2], encoding); let stub1_gen = || functor_stub(atom!("crypto_data_decrypt"), 7); @@ -6411,7 +6327,7 @@ impl Machine { #[inline(always)] pub(crate) fn ed25519_sign(&mut self) { let key = self.string_encoding_bytes(self.machine_st.registers[1], atom!("octet")); - let encoding = cell_as_atom!(self.machine_st.registers[3]); + let encoding = cell_as_atom!(self.deref_register(3)); let data = self.string_encoding_bytes(self.machine_st.registers[2], encoding); let key_pair = match signature::Ed25519KeyPair::from_pkcs8(&key) { @@ -6439,7 +6355,7 @@ impl Machine { #[inline(always)] pub(crate) fn ed25519_verify(&mut self) { let key = self.string_encoding_bytes(self.machine_st.registers[1], atom!("octet")); - let encoding = cell_as_atom!(self.machine_st.registers[3]); + let encoding = cell_as_atom!(self.deref_register(3)); let data = self.string_encoding_bytes(self.machine_st.registers[2], encoding); let stub_gen = || functor_stub(atom!("ed25519_verify"), 5); let signature = self.machine_st.integers_to_bytevec(self.machine_st.registers[4], stub_gen); @@ -6473,7 +6389,7 @@ impl Machine { #[inline(always)] pub(crate) fn first_non_octet(&mut self) { - let addr = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let addr = self.deref_register(1); if let Some(string) = self.machine_st.value_to_str_like(addr) { for c in string.as_str().chars() { @@ -6596,8 +6512,9 @@ impl Machine { } } + let a1 = self.deref_register(1); let command = self.machine_st.value_to_str_like( - self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])) + a1 ).unwrap(); match env::var("SHELL") { @@ -6627,8 +6544,8 @@ impl Machine { #[inline(always)] pub(crate) fn chars_base64(&mut self) -> CallResult { - let padding = cell_as_atom!(self.machine_st.registers[3]); - let charset = cell_as_atom!(self.machine_st.registers[4]); + let padding = cell_as_atom!(self.deref_register(3)); + let charset = cell_as_atom!(self.deref_register(4)); let config = if padding == atom!("true") { if charset == atom!("standard") { @@ -6644,7 +6561,7 @@ impl Machine { } }; - if self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])).is_var() { + if self.deref_register(1).is_var() { let b64 = self.machine_st.value_to_str_like(self.machine_st.registers[2]).unwrap(); let bytes = base64::decode_config(b64.as_str(), config); @@ -6676,9 +6593,7 @@ impl Machine { #[inline(always)] pub(crate) fn load_library_as_stream(&mut self) -> CallResult { - let library_name = cell_as_atom!(self.machine_st.store(self.machine_st.deref( - self.machine_st.registers[1] - ))); + let library_name = cell_as_atom!(self.deref_register(1)); use crate::machine::LIBRARIES; @@ -6792,7 +6707,7 @@ impl Machine { #[inline(always)] pub(crate) fn pop_count(&mut self) { - let number = self.machine_st.store(self.machine_st.deref(self.machine_st.registers[1])); + let number = self.deref_register(1); let pop_count = integer_as_cell!(match Number::try_from(number) { Ok(Number::Fixnum(n)) => { Number::Fixnum(Fixnum::build_with(n.get_num().count_ones() as i64)) diff --git a/wambook/wambook.pdf b/wambook/wambook.pdf new file mode 100644 index 00000000..e2646ffa Binary files /dev/null and b/wambook/wambook.pdf differ