-
Notifications
You must be signed in to change notification settings - Fork 125
/
builtins.pl
2261 lines (1970 loc) · 72.6 KB
/
builtins.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
:- module(builtins, [(=)/2, (\=)/2, (\+)/1, !/0, (',')/2, (->)/2,
(;)/2, (=..)/2, abolish/1, asserta/1, assertz/1,
at_end_of_stream/0, at_end_of_stream/1,
atom_chars/2, atom_codes/2, atom_concat/3,
atom_length/2, bagof/3, call/1, call/2, call/3,
call/4, call/5, call/6, call/7, call/8, call/9,
callable/1, catch/3, char_code/2, clause/2,
close/1, close/2, current_input/1,
current_output/1, current_op/3,
current_predicate/1, current_prolog_flag/2,
error/2, fail/0, false/0, findall/3, findall/4,
flush_output/0, flush_output/1, get_byte/1,
get_byte/2, get_char/1, get_char/2, get_code/1,
get_code/2, halt/0, halt/1, nl/0, nl/1,
number_chars/2, number_codes/2, once/1, op/3,
open/3, open/4, peek_byte/1, peek_byte/2,
peek_char/1, peek_char/2, peek_code/1,
peek_code/2, put_byte/1, put_byte/2, put_code/1,
put_code/2, put_char/1, put_char/2, read/1,
read/2, read_term/2, read_term/3, repeat/0,
retract/1, retractall/1, set_prolog_flag/2,
set_input/1, set_stream_position/2, set_output/1,
setof/3, stream_property/2, sub_atom/5,
subsumes_term/2, term_variables/2, throw/1,
true/0, unify_with_occurs_check/2, write/1,
write/2, write_canonical/1, write_canonical/2,
write_term/2, write_term/3, writeq/1, writeq/2]).
/** Builtin predicates
This library, unlike the rest, is loaded by default and it exposes the most fundamental and general
predicates of the Prolog system under the ISO standard. Basic operators, metaprogramming, exceptions,
internal settings and basic I/O are all here.
*/
% unify.
%% =(?X, ?Y)
%
% True if X and Y can be unified. This is the most basic operation of Prolog.
% Unification also happens when doing head matching in a rule.
X = X.
%% true.
%
% Always true.
true.
%% false.
%
% Always false.
false :- '$fail'.
% These are stub versions of call/{1-9} defined for bootstrapping.
% Once Scryer is bootstrapped, each is replaced with a version that
% uses expand_goal to pass the expanded goal along to '$call'.
%% call(Goal).
%
% Execute the Goal. Typically used when the Goal is not known at compile time.
call(_).
%% call(Goal, ExtraArg1).
%
% Execute the Goal with ExtraArg1 appended to the argument list. For example:
%
% ?- call(format("~s~n"), ["Alain Colmerauer"]).
% Alain Colmerauer
% true.
%
% Which is equivalent to: `format("~s~n", ["Alain Colmerauer"]).`
call(_, _).
%% call(Goal, ExtraArg1, ExtraArg2).
%
% Execute Goal with ExtraArg1 and ExtraArg2 appended to the argument list.
call(_, _, _).
%% call(Goal, ExtraArg1, ExtraArg2, ExtraArg3).
%
% Execute Goal with ExtraArg1, ExtraArg2 and ExtraArg3 appended to the argument list.
call(_, _, _, _).
%% call(Goal, ExtraArg1, ExtraArg2, ExtraArg3, ExtraArg4).
%
% Execute Goal with ExtraArg1, ExtraArg2, ExtraArg3 and ExtraArg4 appended to the argument list.
call(_, _, _, _, _).
%% call(Goal, ExtraArg1, ExtraArg2, ExtraArg3, ExtraArg4, ExtraArg5).
%
% Execute Goal with ExtraArg1, ExtraArg2, ExtraArg3, ExtraArg4 and ExtraArg5 appended to the argument list.
call(_, _, _, _, _, _).
%% call(Goal, ExtraArg1, ExtraArg2, ExtraArg3, ExtraArg4, ExtraArg5, ExtraArg6).
%
% Execute Goal with ExtraArg1, ExtraArg2, ExtraArg3, ExtraArg4, ExtraArg5 and ExtraArg6 appended
% to the argument list.
call(_, _, _, _, _, _, _).
%% call(Goal, ExtraArg1, ExtraArg2, ExtraArg3, ExtraArg4, ExtraArg5, ExtraArg6, ExtraArg7).
%
% Execute Goal with ExtraArg1, ExtraArg2, ExtraArg3, ExtraArg4, ExtraArg5, ExtraArg6 and ExtraArg7
% appended to the argument list.
call(_, _, _, _, _, _, _, _).
%% call(Goal, ExtraArg1, ExtraArg2, ExtraArg3, ExtraArg4, ExtraArg5, ExtraArg6, ExtraArg7, ExtraArg8).
%
% Execute Goal with ExtraArg1, ExtraArg2, ExtraArg3, ExtraArg4, ExtraArg5, ExtraArg6, ExtraArg7 and
% ExtraArg8, appended to the argument list.
call(_, _, _, _, _, _, _, _, _).
:- meta_predicate catch(0, ?, 0).
% flags.
%% current_prolog_flag(Flag, Value)
%
% True iff Flag is a flag supported by the processor, and Value is the value currently associated with it.
% A flag is a setting which value affects internal operation of the Prolog system. Some flags are read-only,
% while others can be set with `set_prolog_flag/2`.
%
% The flags that Scryer Prolog support are:
%
% * `max_arity`: The max arity a predicate can have in Prolog. On Scryer is set to 1023. Read only.
% * `bounded`: `true` if integer arithmethic is bounded between some min/max values. On Scryer is always set
% to `false` since it supports unbounded integer arithmethic. Read only.
% * `integer_rounding_function`: Describes the rounding donde by `//` and `rem` functions. On Scryer is
% always set to `toward_zero`. Read only
% * `double_quotes`: Determines how double quoted strings are red by Prolog. Scryer uses `chars` by default
% which is a list of one-character atoms. Other values are codes (list of integers representing characters),
% and atom which creates a whole atom for the string value. Read and write.
% * `max_integer`: Maximum integer supported by the system. As Scryer Prolog has unbounded integer arithmethic,
% checking the value of this flag fails. Read only.
% * `min_integer`: Minimum integer supported by the system. As Scryer Prolog has unbounded integer arithmethic,
% checking the value of this flag fails. Read only.
% * `occurs_check`: Returns if the occurs check is enabled. The occurs check prevents the creation cyclic terms.
% Historically the Prolog unification algorithm didn't do that check so changing the value modifies how Prolog
% operates in the low-level. Possible values are `false` (default), `true` (unification has this check
% enabled) and `error` which throws an exception when a cylic term is created. Read and write.
% * `unknown`: How undefined predicates are handled when called. Possible values are `error` (the default, an error is thrown),
% `fail` (the call silently fails) and `warn` (the call fails and a warning about the undefined predicate is printed).
% * `answer_write_options`: Additional write options used by the top level for writing answers.
%
current_prolog_flag(Flag, Value) :- Flag == max_arity, !, Value = 1023.
current_prolog_flag(max_arity, 1023).
current_prolog_flag(Flag, Value) :- Flag == bounded, !, Value = false.
current_prolog_flag(bounded, false).
current_prolog_flag(Flag, Value) :- Flag == integer_rounding_function, !, Value == toward_zero.
current_prolog_flag(integer_rounding_function, toward_zero).
current_prolog_flag(Flag, Value) :- Flag == double_quotes, !, '$get_double_quotes'(Value).
current_prolog_flag(double_quotes, Value) :- '$get_double_quotes'(Value).
current_prolog_flag(Flag, Value) :- Flag == unknown, !, '$get_unknown'(Value).
current_prolog_flag(unknown, Value) :- '$get_unknown'(Value).
current_prolog_flag(Flag, _) :- Flag == max_integer, !, '$fail'.
current_prolog_flag(Flag, _) :- Flag == min_integer, !, '$fail'.
current_prolog_flag(Flag, OccursCheckEnabled) :-
Flag == occurs_check,
!,
'$is_sto_enabled'(OccursCheckEnabled).
current_prolog_flag(occurs_check, OccursCheckEnabled) :-
'$is_sto_enabled'(OccursCheckEnabled).
current_prolog_flag(Flag, Value) :-
Flag == answer_write_options,
!,
answer_write_options(Value).
current_prolog_flag(answer_write_options, Value) :-
answer_write_options(Value).
current_prolog_flag(Flag, _) :-
atom(Flag),
throw(error(domain_error(prolog_flag, Flag), current_prolog_flag/2)). % 8.17.2.3 b
current_prolog_flag(Flag, _) :-
nonvar(Flag),
throw(error(type_error(atom, Flag), current_prolog_flag/2)). % 8.17.2.3 a
answer_write_options(Value) :-
( iso_ext:bb_get('$answer_write_options', Value) -> true
; Value = []
).
%% set_prolog_flag(Flag, Value).
%
% Sets the internal value of the flag. To see the list of flags supported by Scryer Prolog,
% check `current_prolog_flag/2`. The flags that are read only will fail if you try to change their values
set_prolog_flag(Flag, Value) :-
(var(Flag) ; var(Value)),
throw(error(instantiation_error, set_prolog_flag/2)). % 8.17.1.3 a, b
set_prolog_flag(bounded, false) :- !. % 7.11.1.1
set_prolog_flag(bounded, true) :- !, '$fail'. % 7.11.1.1
set_prolog_flag(bounded, Value) :-
throw(error(domain_error(flag_value, bounded + Value), set_prolog_flag/2)). % 8.17.1.3 e
set_prolog_flag(max_integer, Value) :- integer(Value), !, '$fail'. % 7.11.1.2
set_prolog_flag(max_integer, Value) :-
throw(error(domain_error(flag_value, max_integer + Value), set_prolog_flag/2)). % 8.17.1.3 e
set_prolog_flag(min_integer, Value) :- integer(Value), !, '$fail'. % 7.11.1.3
set_prolog_flag(min_integer, Value) :-
throw(error(domain_error(flag_value, min_integer + Value), set_prolog_flag/2)). % 8.17.1.3 e
set_prolog_flag(integer_rounding_function, down) :- !. % 7.11.1.4
set_prolog_flag(integer_rounding_function, Value) :-
throw(error(domain_error(flag_value, integer_rounding_function + Value),
set_prolog_flag/2)). % 8.17.1.3 e
set_prolog_flag(double_quotes, chars) :-
!, '$set_double_quotes'(chars). % 7.11.2.5, list of one-char atoms.
set_prolog_flag(double_quotes, atom) :-
!, '$set_double_quotes'(atom). % 7.11.2.5, list of char codes (UTF8).
set_prolog_flag(double_quotes, codes) :-
!, '$set_double_quotes'(codes).
set_prolog_flag(unknown, error) :-
!, '$set_unknown'(error).
set_prolog_flag(unknown, warning) :-
!, '$set_unknown'(warning).
set_prolog_flag(unknown, fail) :-
!, '$set_unknown'(fail).
set_prolog_flag(occurs_check, true) :-
!, '$set_sto_as_unify'.
set_prolog_flag(occurs_check, false) :-
!, '$set_nsto_as_unify'.
set_prolog_flag(occurs_check, error) :-
!, '$set_sto_with_error_as_unify'.
set_prolog_flag(double_quotes, Value) :-
flag_domain_error(double_quotes, Value).
set_prolog_flag(answer_write_options, Options) :-
!,
catch(catch(builtins:parse_write_options(Options, _, set_prolog_flag/2),
error(domain_error(_,_), _),
throw(error(type_error(_,_), _))), % convert domain error to type error ....
error(type_error(_,_), _), % ... to catch type and domain errors.
flag_domain_error(answer_write_options, Options)),
iso_ext:bb_put('$answer_write_options', Options).
set_prolog_flag(Flag, _) :-
atom(Flag),
throw(error(domain_error(prolog_flag, Flag), set_prolog_flag/2)). % 8.17.1.3 d
set_prolog_flag(Flag, _) :-
throw(error(type_error(atom, Flag), set_prolog_flag/2)). % 8.17.1.3 c
flag_domain_error(Flag, Value) :-
% domain error via 8.17.1.3 e: Value is inappropriate for Flag
throw(error(domain_error(flag_value, Flag + Value), set_prolog_flag/2)).
% control operators.
%% fail.
%
% A predicate that always fails. The more declarative `false/0` should be used instead.
fail :- '$fail'.
:- meta_predicate \+(0).
%% \+(Goal)
%
% True iff Goal fails
\+ G :- call(G), !, '$fail'.
\+ _.
%% \=(?X, ?Y)
%
% True iff X and Y can't be unified
X \= X :- !, '$fail'.
_ \= _.
:- meta_predicate once(0).
%% once(Goal)
%
% Execute Goal (like `call/1`) but exactly once, ignoring any kind of alternative solutions the original predicate
% could have generated.
once(G) :- call(G), !.
%% repeat.
%
% This predicate succeeds arbitrarily often, generating choice points with that.
repeat.
repeat :- repeat.
:- meta_predicate ','(0,0).
:- meta_predicate ;(0,0).
:- meta_predicate ->(0,0).
%% ->(G1, G2)
%
% If-then and if-then-else constructs
:- non_counted_backtracking (->)/2.
G1 -> G2 :- control_entry_point((G1 -> G2)).
:- non_counted_backtracking staggered_if_then/2.
staggered_if_then(G1, G2) :-
call(G1),
!,
call(G2).
%% ;(G1, G2)
%
% Disjunction (or)
:- non_counted_backtracking (;)/2.
G1 ; G2 :- control_entry_point((G1 ; G2)).
:- non_counted_backtracking staggered_sc/2.
staggered_sc(G, _) :-
( nonvar(G),
G = '$call'(builtins:staggered_if_then(G1, G2)) ->
call(G1),
!,
call(G2)
; call(G)
).
staggered_sc(_, G) :- call(G).
%% !.
%
% Cut operator. Discards the choicepoints created since entering the prediacate in which the operator appears.
% Using cut is not recommended as it introduces a non-declarative flow of programming and makes it more difficult
% to reason about the programs. Also restricts the ability to run the program with alternative execution strategies
!.
:- non_counted_backtracking get_cp/1.
get_cp(B) :- '$get_cp'(B).
:- non_counted_backtracking set_cp/1.
set_cp(B) :- '$set_cp'(B).
%% ,(G1, G2)
%
% Conjuction (and)
:- non_counted_backtracking (',')/2.
','(G1, G2) :- control_entry_point((G1, G2)).
:- non_counted_backtracking control_entry_point/1.
control_entry_point(G) :-
functor(G, Name, Arity),
'$get_cp'(B),
catch('$call'(builtins:dispatch_prep(G,B,Conts)),
dispatch_prep_error,
'$call'(builtins:throw(error(type_error(callable, G), Name/Arity)))),
dispatch_call_list(Conts).
:- non_counted_backtracking cont_list_to_goal/2.
cont_list_goal([Cont], Cont) :- !.
cont_list_goal(Conts, '$call'(builtins:dispatch_call_list(Conts))).
:- non_counted_backtracking dispatch_prep/3.
dispatch_prep(Gs, B, Conts) :-
( callable(Gs) ->
strip_module(Gs, M, Gs0),
( nonvar(Gs0),
dispatch_prep_(Gs0, B, Conts) ->
true
; Gs0 == ! ->
Conts = ['$call'(builtins:set_cp(B))]
; nonvar(Gs0),
\+ callable(Gs0) ->
throw(dispatch_prep_error)
; Conts = [Gs]
)
; var(Gs) ->
Conts = [Gs]
; throw(dispatch_prep_error)
).
:- 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, Conts) :-
( nonvar(G1) ->
( G1 = (G11 -> G12) ->
dispatch_prep(G11, B, IConts2),
dispatch_prep(G12, B, IConts3),
cont_list_goal(IConts2, Cont2),
cont_list_goal(IConts3, Cont3),
Cont0 = '$call'(builtins:staggered_if_then(Cont2, Cont3))
; dispatch_prep(G1, B, IConts0),
dispatch_prep(G2, B, IConts1),
cont_list_goal(IConts0, Cont0)
)
; dispatch_prep(G1, B1, IConts0),
cont_list_goal(IConts0, Cont0)
),
dispatch_prep(G2, B, IConts1),
cont_list_goal(IConts0, Cont0),
cont_list_goal(IConts1, Cont1),
Conts = ['$call'(builtins:staggered_sc(Cont0, Cont1))].
dispatch_prep_((G1 -> G2), B, Conts) :-
dispatch_prep(G1, B1, IConts1),
dispatch_prep(G2, B, IConts2),
cont_list_goal(IConts1, Cont1),
cont_list_goal(IConts2, Cont2),
Conts = ['$call'(builtins:get_cp(B1)),
'$call'(builtins:staggered_if_then(Cont1, Cont2))].
:- non_counted_backtracking dispatch_call_list/1.
dispatch_call_list([]).
dispatch_call_list([G1,G2,G3,G4,G5,G6,G7,G8|Gs]) :-
!,
'$call_with_inference_counting'(call(G1)),
'$call_with_inference_counting'(call(G2)),
'$call_with_inference_counting'(call(G3)),
'$call_with_inference_counting'(call(G4)),
'$call_with_inference_counting'(call(G5)),
'$call_with_inference_counting'(call(G6)),
'$call_with_inference_counting'(call(G7)),
'$call_with_inference_counting'(call(G8)),
dispatch_call_list(Gs).
dispatch_call_list([G1,G2,G3,G4,G5,G6,G7]) :-
!,
'$call_with_inference_counting'(call(G1)),
'$call_with_inference_counting'(call(G2)),
'$call_with_inference_counting'(call(G3)),
'$call_with_inference_counting'(call(G4)),
'$call_with_inference_counting'(call(G5)),
'$call_with_inference_counting'(call(G6)),
'$call_with_inference_counting'(call(G7)).
dispatch_call_list([G1,G2,G3,G4,G5,G6]) :-
!,
'$call_with_inference_counting'(call(G1)),
'$call_with_inference_counting'(call(G2)),
'$call_with_inference_counting'(call(G3)),
'$call_with_inference_counting'(call(G4)),
'$call_with_inference_counting'(call(G5)),
'$call_with_inference_counting'(call(G6)).
dispatch_call_list([G1,G2,G3,G4,G5]) :-
!,
'$call_with_inference_counting'(call(G1)),
'$call_with_inference_counting'(call(G2)),
'$call_with_inference_counting'(call(G3)),
'$call_with_inference_counting'(call(G4)),
'$call_with_inference_counting'(call(G5)).
dispatch_call_list([G1,G2,G3,G4]) :-
!,
'$call_with_inference_counting'(call(G1)),
'$call_with_inference_counting'(call(G2)),
'$call_with_inference_counting'(call(G3)),
'$call_with_inference_counting'(call(G4)).
dispatch_call_list([G1,G2,G3]) :-
!,
'$call_with_inference_counting'(call(G1)),
'$call_with_inference_counting'(call(G2)),
'$call_with_inference_counting'(call(G3)).
dispatch_call_list([G1,G2]) :-
!,
'$call_with_inference_counting'(call(G1)),
'$call_with_inference_counting'(call(G2)).
dispatch_call_list([G1]) :-
'$call_with_inference_counting'(call(G1)).
% univ.
:- non_counted_backtracking univ_errors/3.
univ_errors(Term, List, N) :-
'$skip_max_list'(N, _, List, R),
( var(R) ->
( var(Term),
throw(error(instantiation_error, (=..)/2)) % 8.5.3.3 a)
; true
)
; R \== [] ->
throw(error(type_error(list, List), (=..)/2)) % 8.5.3.3 b)
; List = [H|T] ->
( var(H),
var(Term), % R == [] => List is a proper list.
throw(error(instantiation_error, (=..)/2)) % 8.5.3.3 c)
; T \== [],
nonvar(H),
\+ atom(H),
throw(error(type_error(atom, H), (=..)/2)) % 8.5.3.3 d)
; compound(H),
T == [],
throw(error(type_error(atomic, H), (=..)/2)) % 8.5.3.3 e)
; var(Term),
current_prolog_flag(max_arity, M),
N - 1 > M,
throw(error(representation_error(max_arity), (=..)/2)) % 8.5.3.3 g)
; true
)
; var(Term) ->
throw(error(domain_error(non_empty_list, List), (=..)/2)) % 8.5.3.3 f)
; true
).
:- non_counted_backtracking (=..)/2.
%% =..(Term, List)
%
% Univ operator. True iff Term is a term whose functor is the head of the List, and the rest of arguments of Term
% are in tail of the List. Example:
%
% ?- f(a, X) =.. List.
% List = [f,a,X].
Term =.. List :-
univ_errors(Term, List, N),
univ_worker(Term, List, N).
:- non_counted_backtracking univ_worker/3.
univ_worker(Term, List, _) :-
atomic(Term),
!,
List = [Term].
univ_worker(Term, [Name|Args], N) :-
var(Term),
!,
Arity is N-1,
functor(Term, Name, Arity), % Term = {var}, Name = nonvar, Arity = 0.
get_args(Args, Term, 1, Arity).
univ_worker(Term, List, _) :-
functor(Term, Name, Arity),
get_args(Args, Term, 1, Arity),
List = [Name|Args].
:- non_counted_backtracking get_args/4.
get_args(Args, _, _, 0) :-
!,
Args = [].
get_args([Arg], Func, N, N) :-
!,
arg(N, Func, Arg).
get_args([Arg|Args], Func, I0, N) :-
arg(I0, Func, Arg),
I1 is I0 + 1,
get_args(Args, Func, I1, N).
:- meta_predicate parse_options_list(?, 2, ?, ?, ?).
parse_options_list(Options, Selector, DefaultPairs, OptionValues, Stub) :-
'$skip_max_list'(_, _, Options, Tail),
( Tail == [] ->
true
; var(Tail) ->
throw(error(instantiation_error, Stub)) % 8.11.5.3c)
; Tail \== [] ->
throw(error(type_error(list, Options), Stub)) % 8.11.5.3e)
),
( lists:maplist('$call'(nonvar), Options), % need '$call' because
% maplist isn't
% declared as a
% meta-predicate yet
catch(lists:maplist(Selector, Options, OptionPairs0),
error(E, _),
builtins:throw(error(E, Stub))) ->
lists:append(DefaultPairs, OptionPairs0, OptionPairs1),
keysort(OptionPairs1, OptionPairs),
select_rightmost_options(OptionPairs, OptionValues)
;
throw(error(instantiation_error, Stub)) % 8.11.5.3c)
).
parse_write_options(Options, OptionValues, Stub) :-
DefaultOptions = [double_quotes-false, ignore_ops-false, max_depth-0, numbervars-false,
quoted-false, variable_names-[]],
parse_options_list(Options, builtins:parse_write_options_, DefaultOptions, OptionValues, Stub).
parse_write_options_(double_quotes(DoubleQuotes), double_quotes-DoubleQuotes) :-
( var(DoubleQuotes) ->
throw(error(instantiation_error, _))
; lists:member(DoubleQuotes, [true, false]),
!
; throw(error(domain_error(write_option, double_quotes(DoubleQuotes)), _))
).
parse_write_options_(ignore_ops(IgnoreOps), ignore_ops-IgnoreOps) :-
( var(IgnoreOps) ->
throw(error(instantiation_error, _))
; lists:member(IgnoreOps, [true, false]),
!
; throw(error(domain_error(write_option, ignore_ops(IgnoreOps)), _))
).
parse_write_options_(quoted(Quoted), quoted-Quoted) :-
( var(Quoted) ->
throw(error(instantiation_error, _))
; lists:member(Quoted, [true, false]),
!
; throw(error(domain_error(write_option, quoted(Quoted)), _))
).
parse_write_options_(numbervars(NumberVars), numbervars-NumberVars) :-
( var(NumberVars) ->
throw(error(instantiation_error, _))
; lists:member(NumberVars, [true, false]),
!
; throw(error(domain_error(write_option, numbervars(NumberVars)), _))
).
parse_write_options_(variable_names(VNNames), variable_names-VNNames) :-
must_be_var_names_list(VNNames),
!.
parse_write_options_(max_depth(MaxDepth), max_depth-MaxDepth) :-
( var(MaxDepth) ->
throw(error(instantiation_error, _))
; integer(MaxDepth),
MaxDepth >= 0,
!
; throw(error(domain_error(write_option, max_depth(MaxDepth)), _))
).
parse_write_options_(E, _) :-
throw(error(domain_error(write_option, E), _)).
must_be_var_names_list(VarNames) :-
'$skip_max_list'(_, _, VarNames, Tail),
( Tail == [] ->
must_be_var_names_list_(VarNames, VarNames)
; var(Tail) ->
throw(error(instantiation_error, write_term/2))
; throw(error(domain_error(write_option, variable_names(VarNames)), write_term/2))
).
must_be_var_names_list_([], List).
must_be_var_names_list_([VarName | VarNames], List) :-
( nonvar(VarName) ->
( VarName = (Atom = _) ->
( atom(Atom) ->
must_be_var_names_list_(VarNames, List)
; var(Atom) ->
throw(error(instantiation_error, write_term/2))
; throw(error(domain_error(write_option, variable_names(List)), write_term/2))
)
; throw(error(domain_error(write_option, variable_names(List)), write_term/2))
)
; throw(error(instantiation_error, write_term/2))
).
%% write_term(+Term, +Options).
%
% Write Term to the current output stream according to some output syntax options.
% Options are specified in detail in `write_term/3`.
write_term(Term, Options) :-
current_output(Stream),
write_term(Stream, Term, Options).
%% write_term(+Stream, +Term, +Options).
%
% Write Term to the stream Stream according to some output syntax options. The options avaibale are:
%
% * `ignore_ops(+Boolean)` if `true`, the generic term representation is used everywhere. In `false`
% (default), operators do not use that generic term representation.
% * `max_depth(+N)` if the term is nested deeper than N, print the reminder as ellipses.
% If N = 0 (default), there's no limit.
% * `numbervars(+Boolean)` if true, replaces `$VAR(N)` variables with letters, in order. Default is false.
% * `quoted(+Boolean)` if true, strings and atoms that need quotes to be valid Prolog syntax, are quoted. Default is false.
% * `variable_names(+List)` assign names to variables in term. List should be a list of terms of format `Name=Var`.
% * `double_quotes(+Boolean)` if true, strings are printed in double quotes rather than with list notation. Default is false.
write_term(Stream, Term, Options) :-
parse_write_options(Options, [DoubleQuotes, IgnoreOps, MaxDepth, NumberVars, Quoted, VNNames], write_term/3),
'$write_term'(Stream, Term, IgnoreOps, NumberVars, Quoted, VNNames, MaxDepth, DoubleQuotes).
%% write(+Term).
%
% Write Term to the current output stream using a syntax similar to Prolog
write(Term) :-
current_output(Stream),
'$write_term'(Stream, Term, false, true, false, [], 0, false).
%% write(+Stream, +Term).
%
% Write Term to the stream Stream using a syntax similar to Prolog
write(Stream, Term) :-
'$write_term'(Stream, Term, false, true, false, [], 0, false).
%% write_canonical(+Term).
%
% Write Term to the current output stream using canonical Prolog syntax. Can be read back as Prolog terms.
write_canonical(Term) :-
current_output(Stream),
'$write_term'(Stream, Term, true, false, true, [], 0, false).
%% write_canonical(+Stream, +Term).
%
% Write Term to the stream Stream using canonical Prolog syntax. Can be read back as Prolog terms.
write_canonical(Stream, Term) :-
'$write_term'(Stream, Term, true, false, true, [], 0, false).
%% writeq(+Term).
%
% Write Term to the current output stream using a syntax similar to `write/1` but quoting the atoms that need to be
% quoted according to Prolog syntax.
writeq(Term) :-
current_output(Stream),
'$write_term'(Stream, Term, false, true, true, [], 0, false).
%% writeq(+Stream, +Term).
%
% Write Term to the stream Stream using a syntax similar to `write/1` but quoting the atoms that need to be
% quoted according to Prolog syntax.
writeq(Stream, Term) :-
'$write_term'(Stream, Term, false, true, true, [], 0, false).
select_rightmost_options([Option-Value | OptionPairs], OptionValues) :-
( pairs:same_key(Option, OptionPairs, OtherValues, _),
OtherValues == [] ->
OptionValues = [Value | OptionValues0],
select_rightmost_options(OptionPairs, OptionValues0)
;
select_rightmost_options(OptionPairs, OptionValues)
).
select_rightmost_options([], []).
parse_read_term_options(Options, OptionValues, Stub) :-
DefaultOptions = [singletons-_, variables-_, variable_names-_],
parse_options_list(Options, builtins:parse_read_term_options_, DefaultOptions, OptionValues, Stub).
parse_read_term_options_(singletons(Vars), singletons-Vars) :- !.
parse_read_term_options_(variables(Vars), variables-Vars) :- !.
parse_read_term_options_(variable_names(Vars), variable_names-Vars) :- !.
parse_read_term_options_(E,_) :-
throw(error(domain_error(read_option, E), _)).
%% read_term(+Stream, -Term, +Options).
%
% Read Term from the stream Stream. It supports several options:
% * `variables(-Vars)` unifies Vars with a list of variables in the term. Similar to do `term_variables/2` with the new term.
% * `variable_names(-Vars)` unifies Vars with a list `Name=Var` with Name describing the variable name and Var the variable itself that appears in Term.
% * `singletons` similar to `variable_names` but only reports variables occurring only once in Term.
read_term(Stream, Term, Options) :-
parse_read_term_options(Options, [Singletons, VariableNames, Variables], read_term/3),
'$read_term'(Stream, Term, Singletons, Variables, VariableNames).
%% read_term(-Term, +Options).
%
% Read Term from the current input stream. It supports several options described in more detail in `read_term/3`.
read_term(Term, Options) :-
current_input(Stream),
read_term(Stream, Term, Options).
%% read(-Term).
%
% Read Term from the current input stream with default options. **NOTE** This is not a general predicate
% to read input from a file or the user. Use other predicates like `phrase_from_file/2` for that.
read(Term) :-
current_input(Stream),
read_term(Stream, Term, []).
% read(Stream, Term).
read(Stream, Term) :-
read_term(Stream, Term, []).
% ensures List is either a variable or a list.
can_be_list(List, _) :-
var(List),
!.
can_be_list(List, _) :-
'$skip_max_list'(_, _, List, Tail),
( var(Tail) ->
true
; Tail == []
),
!.
can_be_list(List, PI) :-
throw(error(type_error(list, List), PI)).
% term_variables.
%% term_variables(+Term, -Vars).
%
% True iff given a Term, Vars is a list of all the unique variables that appear in Term. The variables are sorted depth-first
% and left-to-right.
%
% ?- term_variables(f(X, Y, X, g(Z)), Vars).
% Vars = [X, Y, Z].
term_variables(Term, Vars) :-
can_be_list(Vars, term_variables/2),
'$term_variables'(Term, Vars).
% exceptions.
:- non_counted_backtracking catch/3.
%% catch(Goal, Catcher, Recover).
%
% Calls Goal, but if it throws an exception that unifies with Catcher, Recover will be called instead
% and the program will be resumed. Example:
%
% ```
% ?- catch(number_chars(X, "not_a_number"), error(syntax_error(_), _), X = 0).
% X = 0.
% ```
catch(G,C,R) :-
'$get_current_block'(Bb),
catch(G,C,R,Bb).
:- meta_predicate catch(0, ?, 0, ?).
:- non_counted_backtracking catch/4.
catch(G,C,R,Bb) :-
'$install_new_block'(NBb),
call(G),
end_block(Bb, NBb).
catch(G,C,R,Bb) :-
'$reset_block'(Bb),
'$get_ball'(Ball),
'$push_ball_stack', % move ball to ball stack.
handle_ball(Ball, C, R).
:- non_counted_backtracking end_block/2.
end_block(Bb, NBb) :-
'$clean_up_block'(NBb),
'$reset_block'(Bb).
end_block(_Bb, NBb) :-
'$reset_block'(NBb),
'$fail'.
:- non_counted_backtracking handle_ball/3.
handle_ball(C, C, R) :-
!,
'$pop_ball_stack', % remove ball from ball stack.
call(R).
handle_ball(_, _, _) :-
'$pop_from_ball_stack', % restore ball from ball stack.
'$unwind_stack'.
:- non_counted_backtracking throw/1.
%% throw(+Exception).
%
% Raise the exception Exception. The system looks for the innermost `catch/3` for which Exception
% unifies with Catcher. Example:
%
% ```
% ?- throw(custom_error(42)).
% throw(custom_error(42)).
% ?- catch(throw(custom_error(42)), custom_error(_), true).
% true.
% ```
throw(Ball) :-
( var(Ball) ->
'$set_ball'(error(instantiation_error,throw/1))
; '$set_ball'(Ball)
),
'$unwind_stack'.
:- non_counted_backtracking '$iterate_find_all'/4.
'$iterate_find_all'(Template, Goal, _, LhOffset) :-
'$call_with_inference_counting'(call(Goal)),
'$copy_to_lh'(LhOffset, Template),
'$fail'.
'$iterate_find_all'(_, _, Solutions, LhOffset) :-
'$truncate_if_no_lh_growth'(LhOffset),
'$get_lh_from_offset'(LhOffset, Solutions).
truncate_lh_to(LhLength) :- '$truncate_lh_to'(LhLength).
:- meta_predicate findall(?, 0, ?).
:- non_counted_backtracking findall_cleanup/2.
findall_cleanup(LhLength, Error) :-
truncate_lh_to(LhLength),
throw(Error).
:- non_counted_backtracking findall/3.
%% findall(Template, Goal, Solutions).
%
% Unify Solutions with a list of all values that variables in Template can take in Goal.
% `findall/3` is equivalent to `bagof/3` with all free variables scoped to the Goal (`^` operator)
% except that `bagof/3` fails when no solutions are found and `findall/3` unifies with an empty list.
% Example:
%
% ```
% f(1,2).
% f(1,3).
% f(1,4).
% ?- findall(X-Y, f(X, Y), Solutions).
% Solutions = [1-2,1-3,1-4].
% ```
findall(Template, Goal, Solutions) :-
error:can_be(list, Solutions),
'$lh_length'(LhLength),
catch(builtins:'$iterate_find_all'(Template, Goal, Solutions, LhLength),
Error,
builtins:findall_cleanup(LhLength, Error)
).
:- non_counted_backtracking '$iterate_find_all_diff'/5.
'$iterate_find_all_diff'(Template, Goal, _, _, LhOffset) :-
'$call_with_inference_counting'(call(Goal)),
'$copy_to_lh'(LhOffset, Template),
'$fail'.
'$iterate_find_all_diff'(_, _, Solutions0, Solutions1, LhOffset) :-
'$truncate_if_no_lh_growth_diff'(LhOffset, Solutions1),
'$get_lh_from_offset_diff'(LhOffset, Solutions0, Solutions1).
:- meta_predicate findall(?, 0, ?, ?).
:- non_counted_backtracking findall/4.
%% findall(Template, Goal, Solutions0, Solutions1)
%
% Similar to `findall/3` but returns the solutions as the difference list Solutions0-Solutions1.
findall(Template, Goal, Solutions0, Solutions1) :-
error:can_be(list, Solutions0),
error:can_be(list, Solutions1),
'$lh_length'(LhLength),
catch(builtins:'$iterate_find_all_diff'(Template, Goal, Solutions0,
Solutions1, LhLength),
Error,
builtins:findall_cleanup(LhLength, Error)
).
:- non_counted_backtracking set_difference/3.
set_difference([X|Xs], [Y|Ys], Zs) :-
X == Y, !, set_difference(Xs, [Y|Ys], Zs).
set_difference([X|Xs], [Y|Ys], [X|Zs]) :-
X @< Y, !, set_difference(Xs, [Y|Ys], Zs).
set_difference([X|Xs], [Y|Ys], Zs) :-
X @> Y, !, set_difference([X|Xs], Ys, Zs).
set_difference([], _, []) :- !.
set_difference(Xs, [], Xs).
% variant/2 checks whether X is a variant of Y per the definition in
% 7.1.6.1 of the ISO standard.
:- non_counted_backtracking variant/4.
variant(X,Y,VPs,VPs0) :-
( var(X) ->
var(Y),
VPs = [X-Y|VPs0]
; var(Y) ->
false
; X =.. [FX | XArgs],
Y =.. [FX | YArgs],
lists:foldl('$call'(builtins:variant), XArgs, YArgs, VPs, VPs0)
).
:- non_counted_backtracking variant/2.
singleton([_]).
variant(X, Y) :-
variant(X,Y, VPs, []),
keysort(VPs, SVPs),
pairs:group_pairs_by_key(SVPs, SVPKs),
pairs:pairs_values(SVPKs, Vals),
lists:maplist('$call'(builtins:term_variables), Vals, Vs),
lists:maplist('$call'(builtins:singleton), Vs),
term_variables(Vs, YVars),
lists:length(SVPKs, N),
lists:length(YVars, N).
:- non_counted_backtracking group_by_variant/4.
group_by_variant([V2-S2 | Pairs], V1-S1, [S2 | Solutions], Pairs0) :-
variant(V1, V2),
!,
V1 = V2,
group_by_variant(Pairs, V2-S2, Solutions, Pairs0).
group_by_variant(Pairs, _, [], Pairs).
:- non_counted_backtracking group_by_variants/2.
group_by_variants([V-S|Pairs], [V-Solution|Solutions]) :-
group_by_variant([V-S|Pairs], V-S, Solution, Pairs0),