Skip to content

Commit

Permalink
output_language
Browse files Browse the repository at this point in the history
  • Loading branch information
TeamSPoon committed Dec 1, 2024
1 parent 4890e60 commit 9fb8a9b
Show file tree
Hide file tree
Showing 9 changed files with 274 additions and 130 deletions.
4 changes: 2 additions & 2 deletions hyperon-wam.vpj
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@
Name="Other Files"
Filters=""></Folder>
</CustomFolders>
<List Name="RTE">
</List>
<Files AutoFolders="DirectoryView">
<Folder Name="t:/">
<Folder Name="root">
Expand Down Expand Up @@ -279,6 +281,4 @@
Recurse="1"
Excludes=".git/;*.metta.html;*.bak;build/;.*/;*~*/"/>
</Files>
<List Name="RTE">
</List>
</Project>
52 changes: 45 additions & 7 deletions src/canary/metta_compiler.pl
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@
% ?- compile_for_exec(RetResult, is(pi+pi), Converted).

compile_for_exec(Res,I,O):-
%ignore(Res='$VAR'('RetResult')),
%ignore(Res='$VAR'('RetResult')),`
compile_for_exec0(Res,I,O),!.

compile_for_exec0(Res,I,eval_args(I,Res)):- is_ftVar(I),!.
Expand Down Expand Up @@ -180,10 +180,25 @@
%(var(HResult) -> (Result = HResult, HHead = Head) ;
% funct_with_result_is_nth_of_pred(HeadIs,AsFunction, Result, _Nth, Head)),
ast_to_prolog_aux([FnName/LenArgsPlus1],[assign,HResult,[call(FnName)|Args]],HeadC),
format("~w",[NextBody]),
ast_to_prolog([FnName/LenArgsPlus1],NextBody,NextBodyC)

output_language( ast, ((
\+ \+ (( no_conflict_numbervars(HeadC + NextBody),
%write_src_wi([=,HeadC,NextBody]),
print_tree_nl([=,HeadC,NextBody]),
true))))),


ast_to_prolog([FnName/LenArgsPlus1],NextBody,NextBodyC),
output_language(prolog, (print_pl_source(Converted))),
true
)).


no_conflict_numbervars(Term):-
findall(N,(sub_term(E,Term),compound(E), '$VAR'(N)=E, integer(N)),NL),!,
max_list([-1|NL],Max),Start is Max + 1,!,
numbervars(Term,Start,_,[attvar(skip),singletons(true)]).

%compile_for_assert(HeadIs, AsBodyFn, Converted) :-
% format("compile_for_assert: ~w ~w\n",[HeadIs, AsBodyFn]),
% HeadIs=[FnName|Args],
Expand Down Expand Up @@ -426,14 +441,18 @@
findall(Atom1, (between(1, Am1, I1), Atom1='$VAR'(I1)), AtomList1),
B=..[u_assign,[F|AtomList1],'$VAR'(A)],
(enable_interpreter_calls -> G=true;G=fail),
create_and_consult_temp_file(Space,Fp/A,[H:-(format("######### warning: using stub for:~w\n",[F]),G,B)]))).
create_and_consult_temp_file(Space,Fp/A,[H:-(format("; % ######### warning: using stub for:~w\n",[F]),G,B)]))).

% Predicate to create a temporary file and write the tabled predicate
create_and_consult_temp_file(Space,F/A, PredClauses) :-
must_det_ll((
% Generate a unique temporary memory buffer
tmp_file_stream(text, TempFileName, TempFileStream),
% Write the tabled predicate to the temporary file
format(TempFileStream, ':- multifile((~q)/~w).~n', [metta_compiled_predicate, 3]),
format(TempFileStream, ':- dynamic((~q)/~w).~n', [metta_compiled_predicate, 3]),
format(TempFileStream, '~N~q.~n',[metta_compiled_predicate(Space,F,A)]),

format(TempFileStream, ':- multifile((~q)/~w).~n', [F, A]),
format(TempFileStream, ':- dynamic((~q)/~w).~n', [F, A]),
%if_t( \+ option_value('tabling',false),
Expand All @@ -444,16 +463,26 @@
% Consult the temporary file
% abolish(F/A),
/*'&self':*/
% sformat(CAT,'cat ~w',[TempFileName]), shell(CAT),
consult(TempFileName),

listing(F/A),
% listing(F/A),
% Delete the temporary file after consulting
%delete_file(TempFileName),
asserta(metta_compiled_predicate(Space,F,A)),
current_predicate(F/A),
listing(metta_compiled_predicate/3),
%listing(metta_compiled_predicate/3),
true)).


write_to_streams(StreamList, Format, Args) :-
% Write to each stream in the list
forall(member(Stream, StreamList),
format(Stream, Format, Args)),
% Write to stdout
format(user_output, Format, Args),
flush_output(user_output). % Ensure output is displayed immediately


%metta_compiled_predicate(_,F,A):- metta_compiled_predicate(F,A).

% Helper predicate to write a clause to the file
Expand Down Expand Up @@ -523,6 +552,15 @@
atom(Fn),
compile_flow_control(HeadIs,RetResult,Convert, Converted),!.

f2p(HeadIs,RetResult, Convert, Converted) :- HeadIs\=@=Convert,
Convert=[Fn|_], \+ atom(Fn),
Args = Convert,
maplist(f2p(HeadIs),NewArgs, Args, NewCodes),
append(NewCodes,CombinedNewCode),
Code=[assign,RetResult,list(NewArgs)],
append(CombinedNewCode,[Code],Converted).


f2p(HeadIs,RetResult, Convert, Converted) :- HeadIs\=@=Convert,
Convert=[Fn|Args],
atom(Fn),!,
Expand Down
3 changes: 3 additions & 0 deletions src/canary/metta_compiler_lib.pl
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,6 @@

mc__assertEqualToResult(A, B, C) :- u_assign([assertEqualToResult, A, B], C).



mc__empty(_):-!,fail.

This comment has been minimized.

Copy link
@TeamSPoon

TeamSPoon Dec 2, 2024

Author Collaborator

The cut here is ore for doc purposes :)

63 changes: 63 additions & 0 deletions src/canary/metta_debug.pl
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,69 @@
is_showing(Flag) :- is_verbose(Flag), !.
is_showing(Flag) :- fast_option_value(Flag, 'show'), !.


log_file_type(X):- nonvar(X),!,log_file_type(Is),!,Is=X.
log_file_type(metta):- fast_option_value(compile, full),!.
log_file_type(prolog):- fast_option_value(compile, save),!.
log_file_type(markdown):- fast_option_value(format, markdown),!.
log_file_type(metta):- fast_option_value(compile, false),!.
log_file_type(prolog).


into_blocktype(InfoType,Goal):- !,
enter_markdown(InfoType),!,
Goal.
%setup_call_cleanup(format('~N```~w~n',[InfoType]),Goal, format('~N```~n',[])).

into_blocktype(InfoType,Goal):- log_file_type(markdown), !,
setup_call_cleanup(format('~N```~w~n',[InfoType]),Goal, format('~N```~n',[])).

into_blocktype(InfoType,Goal):- log_file_type(prolog), !,
setup_call_cleanup(format('~N```~w~n',[InfoType]),Goal, format('~N```~n',[])).

into_blocktype(InfoType,Goal):- log_file_type(prolog), !,
setup_call_cleanup(format('~N/*~n```~w~n*/~n',[InfoType]),Goal, format('~N/*~n```~n*/~n',[])).

output_language( InfoType, Goal ) :- log_file_type(Lang), !, % (Lang==prolog; Lang==metta),!,
((InfoType == Lang -> (must_det_ll((enter_markdown(Lang),leave_comment)),call(Goal)) ; (must_det_ll(enter_comment),into_blocktype(InfoType,Goal)))).

output_language( InfoType, Goal ) :- log_file_type(markdown), !, into_blocktype(InfoType,Goal).
output_language( comment, Goal ) :- log_file_type(markdown), !, call(Goal).
output_language( comment, Goal ) :- log_file_type(prolog), !, format('~N:- q.~n', [output_language( comment, Goal)]).
output_language( comment, Goal ) :- log_file_type(metta), !, in_cmt(Goal).


:- dynamic(inside_comment/0).
leave_comment:- inside_comment,!, format('~N*/~n~n'),retract(inside_comment).
leave_comment.
enter_comment:- inside_comment,!.
enter_comment:- format('~N~n/*~n'),assert(inside_comment).
:- enter_comment.

:- at_halt(leave_markdown(_)).
:- at_halt(leave_comment).


:- dynamic(inside_markdown/1).
leave_markdown(_):- \+ inside_markdown(_),!.
leave_markdown(Lang):- inside_markdown(Lang),!, format('~N```~n'),retract(inside_markdown(Lang)).
leave_markdown(_):- !. % inside_markdown(Other),!,leave_markdown(Other).
leave_markdown(_Lang):- !. %format('~N```~n'),!.
enter_markdown(Lang):- inside_markdown(Lang),!.
enter_markdown(Lang):- inside_markdown(Other),!,leave_markdown(Other),!,enter_markdown(Lang).
enter_markdown(Lang):- log_file_type(Us),Us=Lang,inside_comment,!,format('~N```~w~n',[Lang]),asserta(inside_markdown(Lang)),leave_comment.
enter_markdown(Lang):- format('~N```~w~n',[Lang]),asserta(inside_markdown(Lang)).


pick_quote(String, '"'):- \+ string_contains(String,'"'),!.
pick_quote(String, '\''):- \+ string_contains(String,'\''),!.
pick_quote(String, '`'):- \+ string_contains(String,'`'),!.

banner_writeln(Msg):-
writeln('/*===='),
writeln(Msg),
writeln('====*/'),!.

%! if_show(+Flag, :Goal) is nondet.
%
% Conditionally execute a goal if showing is enabled for the given flag.
Expand Down
106 changes: 98 additions & 8 deletions src/canary/metta_interp.pl
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,9 @@
redo_call_cleanup(set_prolog_IO(user_input, Out,user_error), G,
set_prolog_IO(user_input,COut,user_error)).

not_compatio(G):- if_t(once(is_mettalog;is_testing),user_err(G)).
not_compatio(G):- nb_current(in_not_compatio, true),!,call(G).
not_compatio(G):- if_t(once(is_mettalog;is_testing; (\+ is_compatio )),
user_err( locally(nb_setval(in_not_compatio, true), G))).

extra_answer_padding(_).

Expand Down Expand Up @@ -1287,7 +1289,7 @@
assert_preds(Self,Load,Preds):-
expand_to_hb(Preds,H,_B),
functor(H,F,A), %trace,
if_t((show_transpiler),
if_t((false,show_transpiler),
color_g_mesg_ok('#005288',(
ignore((
% \+ predicate_property(H,defined),
Expand Down Expand Up @@ -1527,10 +1529,11 @@
metta_anew(Load,_Src,OBO):- silent_loading,!,metta_anew1(Load,OBO).
metta_anew(Load,Src,OBO):-
not_compat_io((
if_show(load,color_g_mesg('#ffa500', ((format('~N '), write_src(Src))))),
output_language( metta, (if_show(load, color_g_mesg('#ffa500', ((format('~N '), write_src(Src))))))),
% format('~N'),
if_verbose(load,color_g_mesg('#0f0f0f',(write(' ; Action: '),writeq(Load=OBO),nl))))),
metta_anew1(Load,OBO),not_compat_io((format('~N'))).
output_language( Load, (if_verbose(load,color_g_mesg('#4f4f0f', (( (write('; Action: '),writeq(Load=OBO),nl))))))),
true)),
metta_anew1(Load,OBO),not_compat_io((format('~N'))).

subst_vars_not_last(A,B):-
functor(A,_F,N),arg(N,A,E),
Expand Down Expand Up @@ -1574,7 +1577,7 @@
wots(S,write_src(exec(Exec))),
nb_setval(exec_src,Exec),
format('~N'),
ignore((notrace((color_g_mesg('#0D6328',writeln(S)))))).
output_language(metta,ignore((notrace((color_g_mesg('#0D6328',writeln(S))))))).

%!(let* (( ($a $b) (collapse (get-atoms &self)))) ((bind! &stdlib $a) (bind! &corelib $b)))

Expand Down Expand Up @@ -1777,7 +1780,7 @@
do_metta_exec(From,Self,TermV,FOut):-
Output = X,
%format("########################X0 ~w ~w ~w\n",[Self,TermV,FOut]),
(catch(((not_compatio(write_exec(TermV)),
(catch(((output_language(metta,write_exec(TermV)),
notrace(into_metta_callable(Self,TermV,Term,X,NamedVarsList,Was)),!,
%format("########################X1 ~w ~w ~w ~w\n",[Term,X,NamedVarsList,Output]),
user:interactively_do_metta_exec(From,Self,TermV,Term,X,NamedVarsList,Was,Output,FOut))),
Expand Down Expand Up @@ -1811,7 +1814,10 @@
subst_vars(Res+ExecGoal,Res+Term,NamedVarsList),
copy_term_g(NamedVarsList,Was),
term_variables(Term,Vars),
notrace((color_g_mesg('#114411',print_pl_source(answer(Res):-ExecGoal)))),


Call = do_metta_runtime(Res, ExecGoal),
output_language(prolog, notrace((color_g_mesg('#114411', print_pl_source(:- Call ))))),
%nl,writeq(Term),nl,
((\+ \+
((
Expand Down Expand Up @@ -1846,6 +1852,8 @@
current_self(SelfS),SelfS==Self,!,
do_metta(true,exec,Self,Form,_Out).
eval_H(Term,X):- catch_metta_return(eval_args(Term,X),X).

eval_H(StackMax,Self,Term,X):- fast_option_value(compile, save),!.
eval_H(StackMax,Self,Term,X):- catch_metta_return(eval_args('=',_,StackMax,Self,Term,X),X).
/*
eval_H(StackMax,Self,Term,X).
Expand Down Expand Up @@ -2231,6 +2239,9 @@
:- ensure_loaded(metta_python).
:- ensure_loaded(metta_corelib).
%:- ensure_loaded(metta_help).

:- enter_comment.

:- initialization(use_corelib_file).
:- initialization(use_metta_ontology).

Expand All @@ -2255,7 +2266,86 @@
%:- initialization(loon(program),program).
%:- initialization(loon(default)).

% Flush any pending output to ensure smooth runtime interactions
flush_metta_output :-
with_output_to(user_error, (write_answer_output, ttyflush)).

% Write out answers in hyperon-experimental format to user_error
metta_runtime_write_answers(List) :-
with_output_to(user_error, (write('['), write_answers_aux(List), write(']'))).

% Helper predicate to manage answer formatting to user_error
write_answers_aux([]) :- !.
write_answers_aux([H|T]) :-
with_output_to(user_error, (write_src_woi(H), (T == [] -> true ; write(', '), write_answers_aux(T)))).

% Dynamically describe the current file or an actively reading file, providing context for runtime sessions
file_desc(Message) :-
prolog_load_context(file, CurrentFile),
( stream_property(Stream, mode(read)),
stream_property(Stream, file_name(File)),
\+ at_end_of_stream(Stream),
File \= CurrentFile,
!,
sformat(Message, 'File(~w)', [File])
; sformat(Message, 'File(~w)', [CurrentFile])
).

:- dynamic(runtime_session/4).

% Begin a runtime session with detailed time recording, output to user_error
begin_metta_runtime :-
file_desc(Description),
current_times(WallStart, CPUStart),
asserta(runtime_session(start, WallStart, CPUStart, Description)),
with_output_to(user_error, format('~w started.~n', [Description])).

% End a runtime session, calculate and print elapsed times, output to user_error
end_metta_runtime :-
file_desc(Description),
( retract(runtime_session(start, WallStart, CPUStart, Description))
-> calculate_elapsed_time(WallStart, CPUStart, WallElapsedTime, CPUElapsedTime),
print_elapsed_time(WallElapsedTime, CPUElapsedTime, Description)
; with_output_to(user_error, format('Error: No runtime session start information found for "~w".~n', [Description]))
).

% Wall and CPU time
current_times(WallStart, CPUStart) :-
get_time(WallStart),
statistics(cputime, CPUStart).

% Calculate elapsed times
calculate_elapsed_time(WallStart, CPUStart, WallElapsedTime, CPUElapsedTime) :-
current_times(WallEnd, CPUEnd),
WallElapsedTime is WallEnd - WallStart,
CPUElapsedTime is CPUEnd - CPUStart.

% Print the elapsed wall and CPU time with a description, output to user_error
print_elapsed_time(WallElapsedTime, CPUElapsedTime, Description) :-
with_output_to(user_error,
format(' % Walltime: ~9f seconds, CPUtime: ~9f seconds for ~w~n',
[WallElapsedTime, CPUElapsedTime, Description])).

% Execute a Prolog query and handle output, performance logging, and time measurements to user_error
do_metta_runtime(_Var,_Call) :- fast_option_value(compile, save),!.
do_metta_runtime( Var, Call) :-
functor(Call, Func, _),
atom_concat('Testing ', Func, Description),
current_times(WallStart, CPUStart),
% Execute the query and collect results
with_output_to(user_error, findall(Var, Call, List)),
% Record stop time
calculate_elapsed_time(WallStart, CPUStart, WallElapsedTime, CPUElapsedTime),
% Show results
with_output_to(user_error, metta_runtime_write_answers(List)),
% Print elapsed time
print_elapsed_time(WallElapsedTime, CPUElapsedTime, Description),
flush_metta_output.



:- set_prolog_flag(metta_interp,ready).
%:- ensure_loaded(metta_runtime).
%:- set_prolog_flag(gc,false).

:- use_module(library(clpr)). % Import the CLP(R) library
Expand Down
Loading

0 comments on commit 9fb8a9b

Please sign in to comment.