-
Notifications
You must be signed in to change notification settings - Fork 11
/
metta_loader.pl
executable file
·3695 lines (3504 loc) · 152 KB
/
metta_loader.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Project: MeTTaLog - A MeTTa to Prolog Transpiler/Interpreter
* Description: This file is part of the source code for a transpiler designed to convert
* MeTTa language programs into Prolog, utilizing the SWI-Prolog compiler for
* optimizing and transforming function/logic programs. It handles different
* logical constructs and performs conversions between functions and predicates.
*
* Author: Douglas R. Miles
* Contact: [email protected] / [email protected]
* License: LGPL
* Repository: https://github.com/trueagi-io/metta-wam
* https://github.com/logicmoo/hyperon-wam
* Created Date: 8/23/2023
* Last Modified: $LastChangedDate$ # You will replace this with Git automation
*
* Usage: This file is a part of the transpiler that transforms MeTTa programs into Prolog. For details
* on how to contribute or use this project, please refer to the repository README or the project documentation.
*
* Contribution: Contributions are welcome! For contributing guidelines, please check the CONTRIBUTING.md
* file in the repository.
*
* Notes:
* - Ensure you have SWI-Prolog installed and properly configured to use this transpiler.
* - This project is under active development, and we welcome feedback and contributions.
*
* Acknowledgments: Special thanks to all contributors and the open source community for their support and contributions.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
%*********************************************************************************************
% PROGRAM FUNCTION: handles loading, parsing, and processing MeTTa files, including functions
% for reading s-expressions, managing file buffers, and converting between different data representations.
%*********************************************************************************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% IMPORTANT: DO NOT DELETE COMMENTED-OUT CODE AS IT MAY BE UN-COMMENTED AND USED
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Ensure that the `metta_interp` library is loaded,
% That loads all the predicates called from this file
:- ensure_loaded(metta_interp).
%! when_tracing(+Goal) is det.
%
% Executes the given Goal if tracing is currently enabled.
%
% This predicate checks if tracing is enabled. If tracing is active, it
% temporarily disables tracing to execute the Goal, ensuring that the Goal
% runs without generating trace output. If tracing is not active, the predicate
% simply succeeds without executing the Goal.
%
% @arg Goal The Prolog goal to be executed conditionally based on the tracing status.
%
% @example
% % Assume tracing is active and we want to run a goal without trace output.
% ?- trace, when_tracing(writeln('This runs without trace output')).
% % Trace is turned off temporarily, executes the goal, then restores tracing.
%
when_tracing(Goal) :-
% Check if tracing is active
tracing,
% Cut to prevent further execution if tracing is not active
!,
% Temporarily disable tracing, run the Goal without tracing output
notrace(Goal),
% Cut to avoid backtracking into the next clause
!.
% If tracing is not active, do nothing and succeed without executing Goal.
when_tracing(_).
% The 'multifile' predicate allows other files to add clauses
:- multifile(user:asserted_metta_pred/2).
% The 'dynamic' predicate allows the predicate to be added, removed, or modified during execution
:- dynamic(user:asserted_metta_pred/2).
%! exists_virtually(+Library) is det.
%
% Declares the virtual existence of a specified library.
%
% @arg Library The name of the library that is considered to exist virtually.
%
exists_virtually(corelib).
exists_virtually(stdlib).
%! path_chars(+A, -C) is det.
%
% Maps the symbolic characters of `A` to `C`.
%
% This predicate relates a symbolic representation in `A` to its character form
% in `C`. It delegates this functionality to `symbol_chars/2`, which should
% perform the actual conversion.
%
% @arg A The symbolic representation to be converted.
% @arg C The resulting list of characters.
%
path_chars(A, C) :- symbol_chars(A, C).
%! with_wild_path(+Fnicate, +Dir) is det.
%
% Sets up a wild card path environment in the given directory `Dir`.
%
% This predicate sets up the current directory with wild card processing by
% referring to `Fnicate` and the directory `Dir`. It retrieves the current
% working directory `PWD` and then invokes `wwp/2` with `Fnicate` and `Dir` as
% arguments. `wwp/2` is assumed to handle the wild card path processing.
%
% @arg Fnicate A function or object associated with wild path setup.
% @arg Dir The directory where the wild path setup is to be applied.
%
% @example
% % Apply wild path setup for a specific directory.
% ?- with_wild_path(my_fnicate, '/home/user/docs').
%
with_wild_path(Fnicate, Dir) :-
% Retrieve the current working directory.
working_directory(PWD, PWD),
% Apply the wild path setup.
wwp(Fnicate, Dir).
%! inner_compound(+Compound, -Outer, -Inner) is det.
%
% Traverses the innermost compound term, producing `Inner` as the deepest nested term.
%
% This predicate recursively navigates the structure of a compound term `Compound`
% until reaching an atomic term. It constructs `Outer` by maintaining the
% structure around `Inner`. If `Inner` is not compound, it is returned directly.
%
% @arg Compound The compound term to traverse.
% @arg Outer The structure containing `Inner`.
% @arg Inner The innermost atomic or non-compound term.
%
% @example
% % Decompose nested compound structures.
% ?- inner_compound(f(g(h, i)), Outer, Inner).
% Outer = f(g(Midder)),
% Inner = h.
%
inner_compound(Inner, '.', Inner) :-
% If Inner is not compound, return it as Inner.
\+ compound(Inner), !.
inner_compound(Cmpd, Outter, Inner) :-
% Decompose Cmpd into functor F and arguments [X|Args]
compound_name_arguments(Cmpd, F, [X|Args]),
% Recompose Outer with the functor F and [Midder|Args] as arguments
compound_name_arguments(Outter, F, [Midder|Args]),
% Recursively find the innermost term.
inner_compound(X, Midder, Inner).
%! afn(+A, -B) is det.
%
% Resolves the absolute file name for `A`, yielding `B` as the resolved path.
%
% This predicate quietly resolves the absolute file name of `A`, unifying the
% result with `B`.
%
% @arg A The file name or path to resolve.
% @arg B The resolved absolute path.
%
% @example
% % Resolve the absolute path of a relative file name.
% ?- afn('file.txt', AbsPath).
% AbsPath = '/home/user/file.txt'.
%
afn(A, B) :- quietly(absolute_file_name(A, B)).
%! afn(+A, -B, +Options) is det.
%
% Resolves the absolute file name for `A` with specific options, unifying with `B`.
%
% This variant of `afn/2` allows additional options for file name resolution,
% which are passed to `absolute_file_name/3`.
%
% @arg A The file name or path to resolve.
% @arg B The resolved absolute path.
% @arg Options The options list for customizing the resolution.
%
% @example
% % Resolve a file path with specific options.
% ?- afn('file.txt', AbsPath, [access(read)]).
% AbsPath = '/home/user/file.txt'.
%
afn(A, B, C) :- quietly(absolute_file_name(A, B, C)).
%! wwp(+Fnicate, +Path) is det.
%
% Processes a file or directory path with a given predicate `Fnicate`.
%
% The `wwp/2` predicate is a versatile file and directory handler that operates
% on paths of various types, including files, directories, symbolic paths, and
% compound terms. It allows processing of virtual paths, lists of paths, and
% compound structures. The predicate applies the function `Fnicate` on each
% processed file or directory found.
%
% @arg Fnicate The predicate to apply to each processed path or file.
% @arg Path The file, directory, symbolic path, or compound structure to process.
%
% @example
% % Apply a function to each file in a directory or file list.
% ?- wwp(my_process_fnicate, '/path/to/directory').
%
wwp(Fnicate,Dir):-
extreme_debug(fbug(wwp(Fnicate,Dir))),
fail.
wwp(_Fnicate, []) :-
% If the path is an empty list, succeed without further processing.
!.
wwp(_Fnicate, Virtual) :-
% If the path exists virtually, succeed immediately.
exists_virtually(Virtual), !.
wwp(Fnicate, Virtual) :-
% If the path is unbound, throw an error to handle uninitialized input.
var(Virtual), !, throw(var_wwp(Fnicate, Virtual)).
wwp(Fnicate, Dir) :-
% If running on Scryer Prolog and the path is a symbol, convert it to a character list
% and reapply wwp on the resulting list.
is_scryer, symbol(Dir), !, must_det_ll((path_chars(Dir, Chars), wwp(Fnicate, Chars))).
wwp(Fnicate, Chars) :-
% If the path is a character list or code list, convert it to a file name and reapply wwp.
is_list(Chars), catch(name(File, Chars), _, fail), Chars \== File, !, wwp(Fnicate, File).
wwp(Fnicate, File) :-
% If the path is a list of files, apply wwp to each element in the list.
is_list(File), !, must_det_ll((maplist(wwp(Fnicate), File))).
wwp(Fnicate, Cmpd) :-
% If the path is a compound term, find the innermost term and process it within the outer structure.
compound(Cmpd), inner_compound(Cmpd, Outter, Inner), !,
% Find absolute path of the outer compound and apply wwp with Inner inside that directory.
afn(Outter, Dir, [solutions(all), access(read), file_errors(fail)]),
with_cwd(Dir, wwp(Fnicate, Inner)), !.
wwp(Fnicate, Chars) :-
% If running on SWI-Prolog, convert character list to an atom and process it.
\+ is_scryer, \+ symbol(Chars), !, must_det_ll((name(Atom, Chars), wwp(Fnicate, Atom))).
wwp(Fnicate, File) :-
% If the path exists as a file, directly apply Fnicate to it.
exists_file(File), !, must_det_ll((call(Fnicate, File))).
wwp(Fnicate, ColonS) :-
% Handle symbolic paths containing ':' separators, treating them as modular paths.
fail, symbolic(ColonS), symbol_contains(ColonS, ':'), !,
% Split the symbolic path into top-level directory and the remaining path.
symbolic_list_concat([Top|Rest], ':', ColonS),
symbolic_list_concat(Rest, ':', FileNext),
% Log if tracing and attempt to find the directory.
when_tracing(listing(is_metta_module_path)),
find_top_dirs(Top, Dir),
(
% If FileNext is empty, apply wwp only on Dir, otherwise process within the directory.
(fail, symbol_length(FileNext, 0))
-> wwp(Fnicate, Dir)
; (exists_directory(Dir)
-> with_cwd(Dir, wwp(Fnicate, FileNext))
; fail)
),
!.
wwp(Fnicate, ColonS) :-
% If path contains ':' separator, split it for directory processing.
symbolic(ColonS), symbol_contains(ColonS, ':'), !,
symbolic_list_concat([Top|Rest], ':', ColonS),
symbolic_list_concat(Rest, ':', FileNext), !,
when_tracing(listing(is_metta_module_path)),
must_det_ll((call((
quietly(find_top_dirs(Top, Dir)),
% If Dir exists, process the remaining path within Dir.
exists_directory(Dir),
with_cwd(Dir, wwp(Fnicate, FileNext)))))), !.
wwp(Fnicate, File) :-
% If the path contains '*', expand it to match multiple files.
symbol_contains(File, '*'),
expand_file_name(File, List),
maplist(wwp(Fnicate), List), !.
wwp(Fnicate, Dir) :-
% If Dir is a directory, check for `__init__.py` file and process if it exists.
exists_directory(Dir),
quietly(afn_from('__init__.py', PyFile, [access(read), file_errors(fail), relative_to(Dir)])),
wwp(Fnicate, PyFile).
wwp(Fnicate, File) :-
% If File doesn’t exist as file or directory, search for it with predefined extensions.
\+ exists_directory(File), \+ exists_file(File),
extension_search_order(Ext),
symbolic_list_concat([File|Ext], MeTTafile),
exists_file(MeTTafile),
call(Fnicate, MeTTafile).
wwp(Fnicate, File) :-
% For files containing '..', search with alternative extensions and process if found.
\+ exists_directory(File), \+ exists_file(File), symbol_contains(File, '..'),
extension_search_order(Ext),
symbolic_list_concat([File|Ext], MeTTafile0),
afn_from(MeTTafile0, MeTTafile, [access(read), file_errors(fail)]),
exists_file(MeTTafile),
call(Fnicate, MeTTafile).
wwp(Fnicate, File) :-
% If File is a directory, process all files matching '*.*sv' in that directory.
exists_directory(File),
directory_file_path(File, '*.*sv', Wildcard),
expand_file_name(Wildcard, List), !,
maplist(Fnicate, List).
wwp(Fnicate, Dir) :-
% If Dir is a directory, retrieve all files within and apply Fnicate to each.
exists_directory(Dir), !,
must_det_ll((directory_files(Dir, Files),
maplist(directory_file_path(Dir, Files), Paths),
maplist(path_chars, Paths, CharPaths),
maplist(wwp(Fnicate), CharPaths))), !.
wwp(Fnicate, File) :-
% Fallback case: directly apply Fnicate on the file.
must_det_ll((call(Fnicate, File))).
%! extension_search_order(-ExtensionList) is det.
%
% Defines the order in which file extensions are searched.
%
% Specifies the order of file extensions to use when searching for files.
%
% @arg ExtensionList A list of file extensions in the preferred search order.
%
% @example
% % Retrieve the preferred search order for extensions.
% ?- extension_search_order(Order).
% Order = ['.metta'] ;
% Order = ['.py'] ;
% Order = [''].
%
extension_search_order(['.metta']).
extension_search_order(['.py']).
extension_search_order(['']).
:- if(\+ current_predicate(load_metta_file/2)).
%! load_metta_file(+Self, +Filemask) is det.
%
% Loads a `.metta` file or other supported files based on the file mask.
%
% Attempts to load the specified `Filemask`. If the `Filemask` has a `.metta`
% extension, `load_metta/2` is used. Otherwise, `load_flybase/1` is called.
%
% @arg Self The calling module or context.
% @arg Filemask The file name or pattern to load.
%
% @example
% % Load a file with .metta extension.
% ?- load_metta_file(module, 'example.metta').
%
load_metta_file(Self, Filemask) :-
symbol_concat(_, '.metta', Filemask), !,
% Load the file if it has a .metta extension
load_metta(Self, Filemask).
load_metta_file(_Slf, Filemask) :-
% Otherwise, use the flybase loader for the file mask
load_flybase(Filemask).
:- endif.
%! afn_from(+RelFilename, -Filename) is det.
%
% Resolves the absolute filename from a relative filename.
%
% Finds the absolute path for `RelFilename`, applying defaults as needed.
%
% @arg RelFilename The relative filename to resolve.
% @arg Filename The resulting absolute filename.
%
% @example
% % Resolve absolute path of a relative file name.
% ?- afn_from('docs/example.txt', Path).
%
afn_from(RelFilename, Filename) :-
afn_from(RelFilename, Filename, []).
%! afn_from(+RelFilename, -Filename, +Opts) is det.
%
% Resolves an absolute filename from a relative filename with options.
%
% Supports an option `relative_to/1` to specify a base directory.
%
% @arg RelFilename The relative filename to resolve.
% @arg Filename The resulting absolute filename.
% @arg Opts A list of options for the resolution process.
%
% @example
% % Resolve relative to a specified directory.
% ?- afn_from('docs/example.txt', Path, [relative_to('/home/user')]).
%
afn_from(RelFilename, Filename, Opts) :-
select(relative_to(RelFrom), Opts, NewOpts),
afn_from(RelFrom, RelFromNew, NewOpts),
% Resolve Filename relative to RelFromNew directory
quietly(afn(RelFilename, Filename, [relative_to(RelFromNew) | NewOpts])).
afn_from(RelFilename, Filename, Opts) :-
is_metta_module_path(ModPath),
% Attempt to resolve Filename with ModPath as reference
quietly(afn(RelFilename, Filename, [relative_to(ModPath) | Opts])).
%! register_module(+Dir) is det.
%
% Registers the current module within a directory.
%
% Registers `Dir` with the current module space.
%
% @arg Dir The directory to register.
%
% @example
% % Register a module in a specific directory.
% ?- register_module('/path/to/module').
%
register_module(Dir) :-
current_self(Space),
% Register the module under the current Space
register_module(Space, Dir).
%! register_module(+Space, +Path) is det.
%
% Registers a module in the specified path.
%
% Registers `Space` in `Path`, calculating `Dir` and `ModuleName` from the path.
%
% @arg Space The module space to register.
% @arg Path The directory or file path of the module.
%
% @example
% % Register a specific module space and path.
% ?- register_module(space, '/path/to/module').
%
register_module(Space, Path) :-
% Register the top-level path within the Space
register_module(Space, '%top%', Path),
file_directory_name(Path, Dir),
file_base_name(Path, ModuleName),
% Register the specific ModuleName in the derived Dir
register_module(Space, ModuleName, Dir).
%! register_module(+Space, +ModuleName, +Dir) is det.
%
% Registers a module by name within a space and directory.
%
% Registers `ModuleName` under `Space` in the specified `Dir`.
%
% @arg Space The module space.
% @arg ModuleName The name of the module to register.
% @arg Dir The directory of the module.
%
% @example
% % Register a module by name in a directory.
% ?- register_module(space, 'mod_name', '/path/to/module').
%
register_module(Space, ModuleName, Dir) :-
space_name(Space, SpaceName),
% Find the absolute path of Dir before asserting
absolute_dir(Dir, AbsDir),
asserta(is_metta_module_path(SpaceName, ModuleName, AbsDir)).
%! find_top_dirs(+Top, -Dir) is det.
%
% Finds the top-level directory for a given identifier.
%
% @arg Top The top-level identifier.
% @arg Dir The directory corresponding to the identifier.
%
% @example
% % Find the directory for a top-level identifier.
% ?- find_top_dirs('top_id', Dir).
%
find_top_dirs(Top, Dir) :-
current_self(Self),
space_name(Self, SpaceName),
% Use the space name to locate the directory
find_top_dirs(SpaceName, Top, Dir).
%! find_top_dirs(+SpaceName, +Top, -Dir) is det.
%
% Finds or asserts the directory associated with `Top` within a `SpaceName`.
%
% @arg SpaceName The name of the space.
% @arg Top The top-level identifier.
% @arg Dir The corresponding directory.
%
% @example
% % Find or assert directory in a specific space.
% ?- find_top_dirs('space', 'top_id', Dir).
%
find_top_dirs(SpaceName, Top, Abs) :-
% Try to locate the absolute path for Top in SpaceName
is_metta_module_path(SpaceName, Top, Abs).
find_top_dirs(SpaceName,Top,Dir):-
% Search within the top level of SpaceName's root
is_metta_module_path(SpaceName,'%top%',Root),absolute_dir(Top,Root,Dir).
find_top_dirs(SpaceName,Top,Dir):-
% If not found, derive the parent directory
working_directory(PWD,PWD),
parent_dir_of(PWD,Top,Dir), assert(is_metta_module_path(SpaceName,Top,Dir)).
%! parent_dir_of(+PWD, +Top, -Dir) is det.
%
% Finds the parent directory matching `Top`.
%
% @arg PWD The current working directory.
% @arg Top The top-level directory identifier.
% @arg Dir The matching parent directory.
%
% @example
% % Find the parent directory containing the identifier `Top`.
% ?- parent_dir_of('/current/dir', 'top', Dir).
%
parent_dir_of(PWD, Top, Dir) :-
directory_file_path(Parent, TTop, PWD),
% Check if the current top matches
(TTop == Top -> Dir = PWD ; parent_dir_of(Parent, Top, Dir)).
%! space_name(+Space, -SpaceName) is det.
%
% Retrieves the name associated with a space.
%
% Resolves `SpaceName` from `Space` using symbolic representations or existing names.
%
% @arg Space The initial space identifier.
% @arg SpaceName The resolved name for the space.
%
% @example
% % Find the name of a space.
% ?- space_name('space_identifier', Name).
%
space_name(Space, SpaceName) :-
symbol(Space), !,
% If Space is symbolic, use it directly as SpaceName
SpaceName = Space, !.
space_name(Space, SpaceName) :-
% Check if an existing space name matches
is_space_name(SpaceName), same_space(SpaceName, Space), !.
space_name(Space, SpaceName) :-
% Retrieve or create a space-symbol if needed
'get-atoms'(Space, ['space-symbol', SpaceName]), !.
%! same_space(+Space1, +Space2) is nondet.
%
% Checks if `Space1` and `Space2` represent the same space.
%
% Uses symbolic equality or evaluation to determine if the spaces match.
%
% @arg Space1 The first space to compare.
% @arg Space2 The second space to compare.
%
% @example
% % Check if two spaces are the same.
% ?- same_space('space1', 'space2').
%
same_space(Space1, Space2) :-
% Direct equality check for spaces
Space1 = Space2.
same_space(SpaceName1, Space2) :-
% Evaluate symbolic name and compare
symbol(SpaceName1),
eval(SpaceName1, Space1),
!,
same_space(Space2, Space1).
%! absolute_dir(+Dir, -AbsDir) is det.
%
% Resolves the absolute path of a directory.
%
% Converts `Dir` to an absolute directory path.
%
% @arg Dir The directory to resolve.
% @arg AbsDir The absolute path of the directory.
%
% @example
% % Resolve the absolute path of a directory.
% ?- absolute_dir('my_dir', AbsPath).
%
absolute_dir(Dir, AbsDir) :-
% Generate the absolute path with access and error options
afn(Dir, AbsDir, [access(read), file_errors(fail), file_type(directory)]).
%! absolute_dir(+Dir, +From, -AbsDir) is det.
%
% Resolves the absolute path of a directory relative to a base directory.
%
% Finds `AbsDir` from `Dir` with reference to `From`.
%
% @arg Dir The target directory to resolve.
% @arg From The base directory.
% @arg AbsDir The resulting absolute directory path.
%
% @example
% % Find absolute path of `Dir` relative to a base directory `From`.
% ?- absolute_dir('my_dir', '/base/dir', AbsPath).
%
absolute_dir(Dir, From, AbsDir) :-
% Specify From as the base for the absolute path resolution
afn(Dir, AbsDir, [relative_to(From), access(read), file_errors(fail), file_type(directory)]), !.
:- dynamic(is_metta_module_path/3).
:- dynamic(is_metta_module_path/1).
%! is_metta_module_path(-Path) is det.
%
% Represents paths associated with Metta modules.
%
% Declares a fact to indicate a path is part of a Metta module.
%
% @arg Path The module path.
%
% @example
% % Assert or check if a path is a metta module path.
% ?- is_metta_module_path(Path).
%
is_metta_module_path('.').
%! when_circular(+Key, :Goal, +Item, :DoThis) is nondet.
%
% Executes a goal while preventing circular dependencies by tracking processed items.
% If the current item (e.g., a file or goal) is already in the list of currently processed
% items (tracked by Key), it executes the provided DoThis action and fails. Otherwise, it
% proceeds with the goal, ensuring that the item is properly tracked. The item is automatically
% removed from the tracking list after execution, using `setup_call_cleanup/3` for cleanup.
%
% @arg Key The name of the non-backtrackable global variable to track circular dependencies.
% @arg Goal The goal to execute if no circular dependencies are detected.
% @arg Item The item being processed (e.g., a file name or goal).
% @arg DoThis The action to take when a circular dependency is detected (e.g., throwing an error).
%
when_circular(Key, Goal, Item, DoThis) :-
% Retrieve the current list of items being processed from the global variable (if it exists).
(nb_current(Key, CurrentItems) -> true; CurrentItems = []),
% Check if the current item is already in the list of processed items, indicating a circular dependency.
( member(Item, CurrentItems)
-> % If a circular dependency is detected, execute the DoThis action (e.g., throw an error).
call(DoThis)
; % Otherwise, proceed with setup_call_cleanup to track and cleanup the processing list.
setup_call_cleanup(
% Setup: Add the current item to the list of processed items.
nb_setval(Key, [Item | CurrentItems]),
% Call the main goal to be executed.
call(Goal),
% Cleanup: Remove the current item from the processed list after the goal completes.
(nb_current(Key, UpdatedItems),
select(Item, UpdatedItems, RemainingItems),
nb_setval(Key, RemainingItems))
)
).
%! without_circular_error(:Goal, +Error) is det.
%
% Executes a goal while avoiding circular dependencies. If a circular dependency
% is detected, an error is thrown.
%
% This predicate provides a safety check when executing a goal, ensuring that if
% the goal leads to a circular dependency, the specified error will be thrown instead
% of entering an infinite loop or recursion.
%
% @arg Goal The goal to execute if no circular dependencies are detected.
% @arg Error The error term to throw in case of circular dependency.
%
% @example
% % Attempt to execute a goal that might have circular dependencies.
% ?- without_circular_error(my_goal, circular_dependency_detected).
% % If `my_goal` involves a circular dependency, an error will be raised.
%
without_circular_error(Goal, Error) :-
% Use when_circular/4 to check for circular dependencies and throw an error when detected.
when_circular('$circular_goals', Goal, Goal, throw(error(Error, _))).
%! load_metta(+Filename) is det.
%
% Loads a MeTTa file with the specified filename in the current context.
%
% This predicate loads a MeTTa file specified by the Filename parameter into the
% current context, here represented by `&self`. It is assumed that the loaded file
% contains constructs or expressions in the MeTTa language, which this program
% interprets or transpiles into Prolog.
%
% @arg Filename The name of the MeTTa file to load, specified as an atom or string.
%
% @example
% % Load a MeTTa language file named "example.metta".
% ?- load_metta('example.metta').
%
load_metta(Filename):-
% Call load_metta with the context `&self` and the provided Filename.
load_metta('&self', Filename).
%! load_metta(+Self, +Filename) is det.
%
% Loads a Metta file and handles circular dependencies.
% The predicate checks if the Filename is already in the list of currently
% loaded files (to avoid circular loads). If it is, an error is thrown.
% If not, it adds the Filename to the list, proceeds with the load, and
% finally removes the Filename after the load is complete.
%
% @arg Self The current module or context performing the load.
% @arg Filename The name of the file to be loaded.
%
% @throws An error if the file is already in the list of currently loaded files.
%
load_metta(_Self, Filename):-
% Special case: if the Filename is '--repl', start the REPL instead of loading a file.
Filename == '--repl', !, repl.
load_metta(Self, Filename):-
% Call without_circular_error/2 to prevent circular dependencies when loading files.
without_circular_error(load_metta1(Self, Filename),
missing_exception(load_metta(Self, Filename))).
%! load_metta1(+Self, +Filename) is det.
%
% Helper predicate that performs the actual MeTTa file loading process.
%
% This predicate checks if the `Filename` is a valid symbol and if the file exists.
% If either condition fails, it attempts to handle the `Filename` as a wildcard path,
% which could match multiple files. Once a valid file is identified, it loads the file
% in the specified context and tracks its loading status.
%
% @arg Self The module or context performing the load.
% @arg Filename The name or path of the file to load, potentially including wildcards.
%
% @example
% % Attempt to load a file named "example.metta".
% ?- load_metta1('&self', 'example.metta').
%
load_metta1(Self, Filename):-
% Check if the Filename is not a valid symbol or does not exist as a file.
(\+ symbol(Filename); \+ exists_file(Filename)),!,
% Use with_wild_path to handle wildcard paths and load the file if matched.
with_wild_path(load_metta(Self), Filename), !,
% Call loonit_report for logging or tracking purposes.
loonit_report.
load_metta1(Self, RelFilename):-
% Ensure that RelFilename is valid and exists as a file.
must_det_ll((symbol(RelFilename), % @TODO: Check if it can also be a string.
exists_file(RelFilename),!,
% Convert the relative filename to an absolute filename.
afn_from(RelFilename, Filename),
% Use a local flag for garbage collection and track file loading.
locally(set_prolog_flag(gc, true),
track_load_into_file(Filename,
% Include the file in the current context/module.
include_metta(Self, RelFilename))))).
%! import_metta(+Self, +Filename) is det.
%
% Imports a Metta file and handles circular dependencies.
% The predicate checks if the Filename is already in the list of currently
% imported files (to avoid circular imports). If it is, an error is thrown.
% If not, it adds the Filename to the list, proceeds with the import, and
% finally removes the Filename after the import is complete.
%
% @arg Self The current module or context performing the import.
% @arg Filename The name of the file to be imported.
%
% @throws An error if the file is already in the list of currently imported files.
%
import_metta(Self, Filename):-
% Define the goal for importing the Metta file.
About = import_metta1(Self, Filename),
% Use when_circular/4 to handle circular dependencies during imports.
when_circular('$circular_goals', About, About, complain_if_missing(Filename, About)).
%! complain_if_missing(+Filename, +About) is det.
%
% Reports an error if a specified file is either missing or involved in a circular dependency.
%
% This predicate checks if the `Filename` exists. If it does not, it writes an error message
% indicating that the file is missing. If the file exists but a circular dependency is detected,
% it writes a circular dependency error message.
%
% @arg Filename The name of the file being checked for existence and circular dependency.
% @arg About A term describing the context or operation related to the file (e.g., which
% part of the program or module requires this file).
%
% @example
% % Attempt to load a file and report if it is missing or circular.
% ?- complain_if_missing('example.metta', load_metta).
%
complain_if_missing(Filename, About):-
% If the file does not exist, print a missing exception message.
\+ exists_file(Filename), !, write_src_nl(missing_exception(About)).
complain_if_missing(_, About):-
% If a circular dependency is found, print a circular exception message.
write_src_nl(circular_exception(About)).
%! import_metta1(+Self, +Module) is det.
%
% Imports a MeTTa file or module into the current Prolog context.
% This predicate performs the actual import process for a MeTTa file or module, extending
% the current Prolog environment with MeTTa constructs or, in some cases, Python modules.
%
% @arg Self The identifier for the current Prolog context or module performing the import.
% @arg Module The name of the MeTTa file or Python module to import, either as a file path
% or a module name.
%
% @example
% % Import a MeTTa file named "example.metta" within the `&self` context.
% ?- import_metta1('&self', 'example.metta').
%
% % Import a Python module named "example_py_module" into the Prolog environment.
% ?- import_metta1('&self', 'example_py_module').
%
import_metta1(Self, Module):-
% If the Module is a valid Python module, extend the current Prolog context with Python.
current_predicate(py_is_module/1), py_is_module(Module),!,
must_det_ll(self_extend_py(Self, Module)),!.
import_metta1(Self, Filename):-
% If Filename is not a valid symbol or file does not exist, use wildcards for import.
(\+ symbol(Filename); \+ exists_file(Filename)),!,
must_det_ll(with_wild_path(import_metta(Self), Filename)),!.
import_metta1(Self, RelFilename):-
% Ensure that RelFilename is a symbol and exists as a file.
must_det_ll((
symbol(RelFilename),
exists_file(RelFilename),
% Convert the relative filename to an absolute path.
absolute_file_name(RelFilename, Filename),
% Extract the directory path from the filename.
directory_file_path(Directory, _, Filename),
% Register the file in Prolog as being part of the MeTTa context.
pfcAdd_Now(metta_file(Self, Filename, Directory)),
% Suspend Prolog answers during the inclusion of the MeTTa file.
locally(nb_setval(suspend_answers, true),
% Include the file and load its content into the specified directory.
include_metta_directory_file(Self, Directory, Filename)))).
% Ensure Metta persistency and parsing functionalities are loaded.
:- ensure_loaded(metta_persists).
:- ensure_loaded(metta_parser).
%! include_metta(+Self, +Filename) is det.
%
% Includes a Metta file and handles circular dependencies.
% The predicate checks if the Filename is already in the list of currently
% included files (to avoid circular includes). If it is, an error is thrown.
% If not, it adds the Filename to the list, proceeds with the include, and
% finally removes the Filename after the include is complete.
%
% @arg Self The current module or context performing the include.
% @arg Filename The name of the file to be included.
%
% @throws An error if the file is already in the list of currently included files.
%
include_metta(Self, Filename):-
% Use without_circular_error/2 to handle circular dependencies for including files.
without_circular_error(include_metta1(Self, Filename),
missing_exception(include_metta(Self, Filename))).
%! include_metta1(+Self, +Filename) is det.
%
% Helper predicate that performs the actual inclusion of a MeTTa file.
%
% This predicate checks if `Filename` is a valid symbol and if the file exists.
% If not, it handles the filename as a wildcard path for potential matching files.
% Once validated, it converts `RelFilename` to an absolute path, generates a
% temporary file if needed, extracts the directory path, and registers the file
% in the Prolog knowledge base as part of the current context.
%
% @arg Self The module or context in which the file is being included.
% @arg Filename The name or path of the file to include.
%
% @example
% % Include a valid file "example.metta" into the current knowledge base context.
% ?- include_metta1('&self', 'example.metta').
%
include_metta1(Self, Filename):-
% If Filename is not a valid symbol or file does not exist, handle wildcards for includes.
(\+ symbol(Filename); \+ exists_file(Filename)),!,
must_det_ll(with_wild_path(include_metta(Self), Filename)),!.
include_metta1(Self, RelFilename):-
% Ensure RelFilename is a valid symbol and exists as a file.
must_det_ll((
symbol(RelFilename),
exists_file(RelFilename),!,
% Convert the relative filename to an absolute path.
afn_from(RelFilename, Filename),
% Generate a temporary file if necessary, based on the absolute filename.
gen_tmp_file(false, Filename),
% Extract the directory path from the filename.
directory_file_path(Directory, _, Filename),
% Register the file in Prolog knowledge base as part of the MeTTa context.
pfcAdd_Now(metta_file(Self, Filename, Directory)),
% Mark the file as loaded into the current knowledge base.
pfcAdd_Now(user:loaded_into_kb(Self, Filename)),
% Include the file's directory content into the current module context.
include_metta_directory_file(Self, Directory, Filename))),
% Register the file status in the knowledge base and optionally list it.
pfcAdd_Now(user:loaded_into_kb(Self, Filename)),
nop(listing(user:loaded_into_kb/2)).
%! count_lines_up_to(+TwoK, +Filename, -Count) is det.
%
% Counts lines in a file up to a specified limit.
% This predicate opens the specified file `Filename`, counts lines up to the
% specified limit `TwoK`, and then closes the file. If the file has fewer than
% `TwoK` lines, the total line count is returned.
%
% @arg TwoK The maximum number of lines to count.
% @arg Filename The name of the file whose lines are being counted.
% @arg Count The resulting line count, which will be either the total number of
% lines in the file or `TwoK`, whichever is smaller.
%
% @example
% % Count up to 2000 lines in "example.txt".
% ?- count_lines_up_to(2000, 'example.txt', Count).
%
count_lines_up_to(TwoK, Filename, Count) :-
open(Filename, read, Stream, [encoding(utf8)]),
count_lines_in_stream(TwoK, Stream, 0, Count),
close(Stream).
%! count_lines_in_stream(+TwoK, +Stream, +CurrentCount, -FinalCount) is det.
%
% Counts lines from an open stream up to a specified limit.
% This helper predicate recursively reads lines from `Stream` and increments the
% count until it reaches `TwoK` or the end of the file. `FinalCount` is unified
% with the line count reached.
%
% @arg TwoK The maximum number of lines to count.
% @arg Stream The open file stream to read from.
% @arg CurrentCount The current line count, used for recursion.
% @arg FinalCount The resulting line count, limited by `TwoK` or end of file.
%
count_lines_in_stream(TwoK, Stream, CurrentCount, FinalCount) :-
( CurrentCount >= TwoK
-> FinalCount = TwoK
; read_line_to_codes(Stream, Codes),
( Codes == end_of_file
-> FinalCount = CurrentCount
; NewCount is CurrentCount + 1,
count_lines_in_stream(TwoK, Stream, NewCount, FinalCount)
)
).
%! include_metta_directory_file_prebuilt(+Self, +Directory, +Filename) is nondet.
%
% Loads a prebuilt `.qlf` or `.datalog` file if it is available and up-to-date.
%
% This predicate checks if there is an existing precompiled `.qlf` or `.datalog` file
% associated with a `.metta` file (`Filename`). If the `.qlf` or `.datalog` file exists
% and is more recent than the `.metta` file, it is loaded to avoid recompiling. The `.qlf`
% and `.datalog` files must be newer than the `.metta` file and meet additional conditions
% before they are loaded.
%
% @arg Self The context or module into which the file is being loaded.
% @arg Directory The directory containing the file.
% @arg Filename The name of the original `.metta` file.
%
include_metta_directory_file_prebuilt(Self, _Directory, Filename):-
% Attempt to load a prebuilt `.qlf` file if it is newer than the `.metta` file.
symbol_concat(_, '.metta', Filename),
symbol_concat(Filename, '.qlf', QlfFile),
exists_file(QlfFile),
time_file(Filename, MettaTime),
time_file(QlfFile, QLFTime),
\+ always_rebuild_temp,
QLFTime > MettaTime,!, % Ensure QLF file is newer than the METTA file
pfcAdd_Now(user:loaded_into_kb(Self, Filename)),
ensure_loaded(QlfFile),!.
include_metta_directory_file_prebuilt(Self, _Directory, Filename):-
% Attempt to load a `.datalog` file if it is newer, large enough, and `just_load_datalog` is true.
just_load_datalog,
symbol_concat(_, '.metta', Filename),
symbol_concat(Filename, '.datalog', DatalogFile),
exists_file(DatalogFile),
time_file(Filename, MettaTime),
time_file(DatalogFile, DatalogTime),
DatalogTime > MettaTime,
\+ always_rebuild_temp, !,
size_file(Filename, MettaSize),
size_file(DatalogFile, DatalogSize),
% Ensure the Datalog file is at least 25% the size of the METTA file.
DatalogSize >= 0.25 * MettaSize,
% always rebuild
delete_file(DatalogFile), fail,
!, % Cut to prevent backtracking
pfcAdd_Now(user:loaded_into_kb(Self, Filename)),
ensure_loaded(DatalogFile), !.
include_metta_directory_file_prebuilt(Self, _Directory, Filename):-
% Convert a `.datalog` file to `.qlf` if the size requirement is met and load it.
symbol_concat(_, '.metta', Filename),
symbol_concat(Filename, '.datalog', DatalogFile),
exists_file(DatalogFile),!,
size_file(Filename, MettaSize),
size_file(DatalogFile, DatalogSize),