Skip to content

Commit 27dd9d5

Browse files
committed
builtin module support plus local changes to precompiler
1 parent 6e553d8 commit 27dd9d5

File tree

8 files changed

+613
-467
lines changed

8 files changed

+613
-467
lines changed

.Attic/comp_werks2/metta_pfc_base.pl

Lines changed: 441 additions & 441 deletions
Large diffs are not rendered by default.
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
;; this is loaded as !(import &self fileio)
2+
3+
; This add ther type to the type system
4+
(: FileHandle Type)
5+
; the system level get-type is nondetermninistic therefore returns all willing participants
6+
(= (get-type $obj)
7+
(call-for! FileHandle ; call for returns the first argument
8+
(atomic $obj) ; stream might return an error if obj is not atomic
9+
(stream $obj))) ; if obj is a stream we are calling it a filehandle since prolog streams already support this api
10+
11+
(= (parse-mode $chars)
12+
(call-for! $mode
13+
(or
14+
(and (memberchk r $chars) (memberchk w $chars) (= $mode update))
15+
(and (memberchk a $chars) (= $mode append))
16+
(and (memberchk w $chars) (= $mode write))
17+
(and (memberchk r $chars) (= $mode read))
18+
(= $mode read))))
19+
20+
(= (handle-create-options $path $chars)
21+
(call-unit
22+
(if-then (and (memberchk n $chars) (exists_file $path))
23+
(throw (error (file_exists_error $path))))
24+
(if-then (and (memberchk c $chars) (not (exists_file $path)))
25+
(setup_call_cleanup (open $path write $s) (close $s) true))
26+
(if-then (and (memberchk t $chars) (exists_file $path))
27+
(setup_call_cleanup (open $path write $s) (close $s) true))))
28+
29+
(@doc file-open!
30+
(@desc "Function takes path to the file and open options (r, w, c, a, t) both in form of string, creates filehandle and
31+
returns it")
32+
(@params (
33+
(@param "Filepath (string atom)")
34+
(@param "Open options (string atom), r - read, w - write, c - create if file doesn't exist, a - append to file,
35+
t - truncate file")))
36+
(@return "Filehandle or error if combination of path and open options is wrong (e.g. file doesn't exist and no 'c'
37+
in options; or 'rc' option provided, since 'c' demands for 'w')"))
38+
(: file-open! (-> String String FileHandle))
39+
; tells the compiler to return only the first successful clause
40+
(iz file-open! Deterministic)
41+
(= (file-open! $fpath $opt)
42+
(call-for! $stream
43+
(string_chars $opt $chars)
44+
(any_to_atom $fpath $path)
45+
(= $mode (parse-mode $chars))
46+
(handle-create-options $path $chars)
47+
(open $path $mode $stream [ (type text) ])))
48+
(= (file-open-err! $path $opt)
49+
(call-for! $_err
50+
(format (string $msg)
51+
"Failed to open file with provided path=~w and options=~w"
52+
[$path $opt])
53+
(throw (error (file_open_error $msg)))))
54+
55+
(@doc file-read-to-string!
56+
(@desc "Function takes filehandle provided by file-open! reads its content from current cursor place till the end of
57+
file and returns content in form of string.")
58+
(@params (
59+
(@param "Filehandle")))
60+
(@return "File's content"))
61+
(: file-read-to-string! (-> FileHandle String))
62+
(= (file-read-to-string! $stream)
63+
(call-fn read_string $stream $_ ))
64+
65+
(@doc file-write!
66+
(@desc "Function takes filehandle provided by file-open!, content to be written (string atom) and puts content into
67+
file associated with filehandle")
68+
(@params (
69+
(@param "Filehandle")
70+
(@param "Content (string atom)")))
71+
(@return "Unit atom"))
72+
(: file-write! (-> FileHandle String Unit))
73+
(= (file-write! $stream $content)
74+
(call-unit
75+
(write $stream $content)
76+
(flush_output $stream)))
77+
78+
(@doc file-seek!
79+
(@desc "Function takes filehandle provided by file-open! and desired cursor position (number) and sets cursor to
80+
provided position")
81+
(@params (
82+
(@param "Filehandle")
83+
(@param "Desired cursor position (number)")))
84+
(@return "Unit atom"))
85+
(: file-seek! (-> FileHandle Number Unit))
86+
(= (file-seek! $stream $offset)
87+
(call-unit
88+
(seek $stream $offset bof $_)))
89+
90+
(@doc file-read-exact!
91+
(@desc "Function takes filehandle provided by file-open! and desired number of bytes to read (number), reads content
92+
of file from current cursor position (number of read bytes <= input number of bytes to read) and returns it in form of
93+
string")
94+
(@params (
95+
(@param "Filehandle")
96+
(@param "Number of bytes to read")))
97+
(@return "File's content"))
98+
(: file-read-exact! (-> FileHandle Number String))
99+
(= (file-read-exact! $stream $bytes)
100+
(call-for! $content ; runs this code returning the binding of $content
101+
(read_string $stream $bytes $content)))
102+
103+
(@doc file-get-size!
104+
(@desc "Function takes filehandle provided by file-open! and returns size of file")
105+
(@params (
106+
(@param "Filehandle")))
107+
(@return "Size of file"))
108+
(: file-get-size! (-> FileHandle Number))
109+
(= (file-get-size! $stream)
110+
(call-for! $size ; runs this code returning the binding of $size
111+
(stream_property $stream (file_name $file))
112+
(size_file $file $size)))
113+
114+
(@doc file-close!
115+
(@desc "Function takes filehandle provided by file-open! and closes it")
116+
(@params (
117+
(@param "Filehandle")))
118+
(@return "Unit atom"))
119+
(: file-close! (-> FileHandle Unit))
120+
(= (file-close! $stream)
121+
(call-unit
122+
(close $stream)))
123+
124+
; Load system libs (not required .. but more here for reference)
125+
;!(call-unit
126+
; (use_module (library apply))
127+
; (use_module (library filesex)))
128+
129+

prolog/metta_lang/corelib.metta

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
!(import! stdlib_mettalog.metta)
1+
!(import! &self stdlib_mettalog.metta)
2+

prolog/metta_lang/metta_compiler_lib.pl

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -492,7 +492,7 @@
492492
('mc__1_1_collapse'(A,AA),
493493
'mc__1_1_collapse'(B,BB)),
494494
equal_enough_for_test_renumbered_l(not_alpha_equ,AA,BB), C).
495-
495+
496496
:- initialization(setup_library_call(builtin, 'quote', [1], '@doc', '@doc', [x(noeval,eager,[])], x(noeval,eager,[])), program).
497497
'mc__1_1_quote'(A,['quote',AA]):- unify_with_occurs_check(A,AA).
498498
compile_flow_control(HeadIs,LazyVars,RetResult,RetResultN,LazyRetQuoted,Convert, QuotedCode1a, QuotedCode1N) :-
@@ -813,7 +813,7 @@
813813
OpAsBodyMid=@=OpAsBodyMidCopy,!.
814814

815815
metta_body_macro_stack(TD, HeadIs, Stack, OpAsBody, AsBodyFnOutReally):-
816-
TD == td,
816+
(TD == td1 ; TD == td2),
817817
once((copy_term(OpAsBody,OpAsBodyMidCopy),
818818
metta_body_macro_pass(TD, OpAsBody , AsBodyFnOut),
819819
OpAsBody=@=OpAsBodyMidCopy)),
@@ -828,15 +828,15 @@
828828
metta_body_macro_pass(bu,['if-equal',Var1,Var2|Rest], [if,['metta-equal',Var1,Var2]|Rest]).
829829
metta_body_macro_pass(bu,['if-decons-expr',Expr,Head,Tail|Rest],[if,['decons-ht',Expr,Head,Tail]|Rest]).
830830
metta_body_macro_pass(bu,['if-decons',Expr,Head,Tail|Rest],[if,['decons-ht',Expr,Head,Tail]|Rest]).
831-
metta_body_macro_pass(bu,['chain',[Ceval,Eval],Var|Rest], ['let',Var,Eval|Rest]):- Ceval == eval,!.
831+
metta_body_macro_pass(td1,['chain',[Ceval,Eval],Var|Rest], ['let',Var,Eval|Rest]):- Ceval == eval,!.
832832
metta_body_macro_pass(bu,['chain',Eval,Var|Rest], ['let',Var,Eval|Rest]).
833833

834834
metta_body_macro_pass(td1,[['py-dot'|Args]|Rest], ['py-dot-call',Args|Rest]).
835835
metta_body_macro_pass(td1,[['py-atom'|Args]|Rest], ['py-atom-call',Args|Rest]).
836836
%metta_body_macro_pass(bu,[eval,Next], Next).
837837

838838
% metta_body_macro_pass(td,[eval,Eval], Eval).
839-
metta_body_macro_pass(td1,['capture',Eval], Eval).
839+
%metta_body_macro_pass(td1,['capture',Eval], Eval).
840840

841841
metta_body_macro_pass(td2,['unique',Eval],
842842
['let',Var,['call-fn!','no_repeats_var'],

prolog/metta_lang/metta_eval.pl

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -945,6 +945,14 @@
945945
eval_args_once(Eq,RetType,Depth,Space,Eval,Result):-
946946
eval_10(Eq,RetType,Depth,Space,Eval,Result)*->true;(Eval=Result).
947947

948+
eval_20(Eq,RetType,Depth,Self,['call-unit!'|Program],Res):- !,
949+
eval_args(Eq,RetType,Depth,Self,['call-for!',[]|Program],Res).
950+
951+
eval_20(Eq,RetType,Depth,Self,['call-for!',Res|Program],Res):- !,
952+
must((s2ps(Depth,Self,Program,ProgramL),
953+
maplist(call_prog,ProgramL))).
954+
955+
call_prog(P):- catch_warn(P).
948956

949957
eval_20(Eq,RetType,Depth,Self,['capture',X],Res):- !,
950958
eval_args(Eq,RetType,Depth,Self,X, Res).
@@ -3972,7 +3980,8 @@
39723980

39733981
s2ps(S,P):- current_self(Self),s2ps(30,Self,S,P).
39743982

3975-
s2ps(_,_,_Self,S,P):- S=='Nil',!,P=[].
3983+
s2ps(_,_Self,S,P):- S=='Nil',!,P=[].
3984+
s2ps(_,_Self,S,P):- S==[],!,P=[].
39763985
s2ps(D,Self,S,P):- \+ is_list(S),!,as_prolog_x(D,Self,S, P).
39773986
s2ps(D,Self,[F|S],P):- atom(F),!,maplist(as_prolog_x(D,Self),S,SS),join_s2ps(F,SS,P).
39783987
s2ps(D,Self,[F|S],P):- is_list(F),!,maplist(as_prolog_x(D,Self),[F|S],SS),join_s2ps(call,SS,P).
@@ -4212,7 +4221,7 @@
42124221

42134222

42144223
% get a guarded definition
4215-
eval_30(Eq,RetType,Depth,Self,X,Y):- can_be_ok(get_defn_expansions_guarded,X),
4224+
eval_30(Eq,RetType,Depth,Self,X,Y):- fail, can_be_ok(get_defn_expansions_guarded,X),
42164225
quietly((if_trace(defn, (curried_arity(X,F,A),finfo(F,A,X))),
42174226
findall(guarded_defn(XX,ParamTypes,FRetType,B0),
42184227
get_defn_expansions_guarded(Eq,RetType,Depth,Self,ParamTypes,FRetType,X,XX,B0),XXB0L))),

prolog/metta_lang/metta_loader.pl

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,21 @@
325325
maplist(directory_file_path(Dir, Files), Paths),
326326
maplist(path_chars, Paths, CharPaths),
327327
maplist(wwp(Fnicate), CharPaths))), !.
328+
329+
wwp(Fnicate, FileNext) :-
330+
symbolic(FileNext), % \+ symbol_contains(FileNext, '/'),
331+
\+ exists_directory(FileNext), \+ exists_file(FileNext),
332+
current_self(Top),
333+
((call((
334+
quietly(find_top_dirs(Top, Dir)),
335+
% If Dir exists, process the remaining path within Dir.
336+
exists_directory(Dir),
337+
extension_search_order(Ext),
338+
symbolic_list_concat(['builtins-',FileNext|Ext], Search),
339+
absolute_file_name(Search,Found,[access(exist), file_errors(fail), relative_to(Dir)]),
340+
exists_file(Found),
341+
with_cwd(Dir, call(Fnicate, Search)))))), !.
342+
328343
wwp(Fnicate, File) :-
329344
% Fallback case: directly apply Fnicate on the file.
330345
must_det_ll((call(Fnicate, File))).
@@ -488,6 +503,10 @@
488503
space_name(Self, SpaceName),
489504
% Use the space name to locate the directory
490505
find_top_dirs(SpaceName, Top, Dir).
506+
find_top_dirs(_Top, Dir) :- metta_builtin_mods_dir(Dir).
507+
508+
metta_builtin_mods_dir(Dir):-
509+
metta_library_dir(Value), absolute_file_name('./builtin_mods/', Dir, [relative_to(Value)]).
491510

492511
%! find_top_dirs(+SpaceName, +Top, -Dir) is det.
493512
%

prolog/metta_lang/metta_python.pl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1915,6 +1915,7 @@
19151915

19161916
assumed_loaded(mettalog).
19171917
assumed_loaded(random).
1918+
assumed_loaded(corelib).
19181919

19191920
%! py_load_modfile(+Use) is det.
19201921
%

prolog/metta_lang/stdlib_mettalog.metta

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -205,12 +205,16 @@ For example:
205205
(@param "Atom to return if condition is True")
206206
(@param "Atom to return if condition is False (optional)")))
207207
(@return "Either the second or third argument depending on the condition"))
208-
(: MettaMorph-If (-> Bool Atom Atom Atom))
208+
209209
(: MettaMorph-If (-> Bool Atom Atom))
210210
(= (MettaMorph-If True $then) $then)
211+
; (= (MettaMorph-If False $then) (empty))
211212
(= (MettaMorph-If False $then) (let $n 0 (let $n 1 $n))) ; Placeholder for False condition
213+
214+
(: MettaMorph-If (-> Bool Atom Atom Atom))
212215
(= (MettaMorph-If $cond $then $else) (if $cond $then $else))
213216

217+
214218
;; Arity Assignments
215219

216220
(predicate-arity predicate-arity 2)
@@ -624,7 +628,7 @@ For example:
624628
(@return "Result of atom's evaluation"))
625629
(: function (-> Atom Atom))
626630

627-
(iz eval MinimalMeTTa)
631+
(iz eval MeTTa)
628632
(@doc eval
629633
(@desc "Evaluates input Atom, performs one step of the evaluation. Empty results (Empty, ()) are removed from the result set. If no results are produced for a non-grounded function, eval returns NotReducible.")
630634
(@params (
@@ -970,23 +974,6 @@ For example:
970974
(@return "Random float number from defined range"))
971975
(is-op-2 random-int random)
972976

973-
(@doc file-read
974-
(@desc "Function takes path to the file in form of string and reads file as string")
975-
(@params (
976-
(@param "Filepath (string atom)")))
977-
(@return "Content of file (string atom), error if no file exists"))
978-
(= (file-read $filepath)
979-
(call-fn file_read_content $filepath))
980-
981-
(@doc file-write
982-
(@desc "Function takes path to the file (string atom) and content to be written (string atom), creates file and puts content into it")
983-
(@params (
984-
(@param "Filepath (string atom)")
985-
(@param "Content (string atom)")))
986-
(@return "Unit atom if write successfull, error otherwise (if there is no such folder)"))
987-
(= (file-write $filepath $content)
988-
(call-fn file_write_content $filepath $content))
989-
990977
(iz collapse-bind MeTTa)
991978
(@doc collapse-bind
992979
(@desc "Evaluates the Atom (first argument) and returns an expression which contains all alternative evaluations in a form (Atom Bindings). Bindings are represented in a form of a grounded atom { <var> <- <binding>, ... }. See also the complement superpose-bind. Note that, like chain, collapse-bind only evaluates Minimal Metta expressions. Evaluation of non-Minimal MeTTa atoms can be controlled by wrapping in a call to eval (for one evaluation step) or metta (for full evaluation).")

0 commit comments

Comments
 (0)