forked from SWI-Prolog/swipl-devel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpl-arith.c
More file actions
5380 lines (4519 loc) · 121 KB
/
Copy pathpl-arith.c
File metadata and controls
5380 lines (4519 loc) · 121 KB
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
/* Part of SWI-Prolog
Author: Jan Wielemaker
E-mail: J.Wielemaker@vu.nl
WWW: http://www.swi-prolog.org
Copyright (c) 1985-2025, University of Amsterdam
VU University Amsterdam
CWI, Amsterdam
SWI-Prolog Solutions b.v.
All rights reserved.
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.
*/
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The arithmetic module defines a small set of logical integer predicates
as well as the evaluation of arbitrary arithmetic expressions.
Arithmetic can be interpreted or compiled (see -O flag). Interpreted
arithmetic is supported by the built-in predicates is/2, >/2, etc.
These functions call valueExpression() to evaluate a Prolog term holding
an arithmetic expression.
For compiled arithmetic, the compiler generates WAM codes that execute a
stack machine. This module maintains an array of arithmetic functions.
These functions are addressed by the WAM instructions using their index
in this array.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#ifdef __MINGW32__
#include <winsock2.h>
#include <windows.h>
#include <wincrypt.h>
#endif
/*#define O_DEBUG 1*/
#include "pl-incl.h"
#include "os/pl-utf8.h"
#include "pl-arith.h"
#include "pl-fli.h"
#include "pl-funct.h"
#include "pl-prims.h"
#include "pl-gc.h"
#include "pl-read.h"
#include "os/pl-prologflag.h"
#include <math.h>
#include <limits.h>
#ifdef HAVE_FLOAT_H
#include <float.h>
#ifdef _MSC_VER
#ifndef isnan
#define isnan(x) _isnan(x)
#endif
#define copysign(x,y) _copysign(x,y)
#endif
#endif
#ifdef HAVE_IEEEFP_H
#include <ieeefp.h>
#endif
#include <fenv.h>
#define O_BIGNUM_PRECHECK_ALLOCATIONS 1
#ifndef DBL_MAX
#define DBL_MAX 1.7976931348623157e+308
#endif
#ifndef DBL_MIN
#define DBL_MIN 2.2250738585072014e-308
#endif
#ifndef DBL_EPSILON
#define DBL_EPSILON 0.00000000000000022204
#endif
#undef LD
#define LD LOCAL_LD
#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif
#ifndef M_E
#define M_E (2.7182818284590452354)
#endif
static double const_nan;
static double const_inf;
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
On some machines, notably FreeBSD upto version 3.x, floating point
operations raise signals rather then leaving an error condition and this
behaviour can be changed to be IEEE754 using fpsetmask() and friends.
Here we test whether this interface is present and set it up
accordingly.
With many thanks to NIDE Naoyuki for the clear explanation of the
problem.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#if defined(HAVE_FLOATINGPOINT_H) && defined(HAVE_FPSETMASK) && defined(HAVE_FPRESETSTICKY)
#define O_INHIBIT_FP_SIGNALS
#include <floatingpoint.h>
#ifndef FP_X_DZ
#define FP_X_DZ 0
#endif
#ifndef FP_X_INV
#define FP_X_INV 0
#endif
#ifndef FP_X_OFL
#define FP_X_OFL 0
#endif
#endif
typedef bool (*ArithF0)(Number r);
typedef bool (*ArithF1)(Number n, Number r);
typedef bool (*ArithF2)(Number n1, Number n2, Number r);
typedef bool (*ArithF3)(Number n1, Number n2, Number n3, Number r);
#if USE_LD_MACROS
#define set_roundtoward(p, old) LDFUNC(set_roundtoward, p, old)
#endif /*USE_LD_MACROS*/
#define LDFUNC_DECLARATIONS
static bool ar_minus(Number n1, Number n2, Number r);
static bool mul64(int64_t x, int64_t y, int64_t *r);
static bool notLessThanZero(const char *f, int a, Number n);
static bool mustBePositive(const char *f, int a, Number n);
static bool set_roundtoward(Word p, Number old);
#undef LDFUNC_DECLARATIONS
/********************************
* LOGICAL INTEGER FUNCTIONS *
*********************************/
static inline void
clearInteger(Number n)
{
#ifdef O_BIGNUM
if ( n->type == V_MPZ && !MPZ_ON_STACK(n->value.mpz) )
mpz_clear(n->value.mpz);
#endif
}
typedef struct between_state
{ number low;
number high;
int hinf;
} between_state;
static
PRED_IMPL("between", 3, between, PL_FA_NONDETERMINISTIC)
{ PRED_LD
between_state *state;
term_t low = A1;
term_t high = A2;
term_t n = A3;
int rc = true;
switch( CTX_CNTRL )
{ case FRG_FIRST_CALL:
{ number l, h, i;
int hinf = false;
if ( !PL_get_number(low, &l) || !intNumber(&l) )
return PL_error(NULL, 0, NULL, ERR_TYPE, ATOM_integer, low);
if ( !PL_get_number(high, &h) || !intNumber(&h) )
{ if ( PL_is_inf(high) )
{ h.type = V_INTEGER; /* make clearInteger() safe */
hinf = true;
} else
{ return PL_error(NULL, 0, NULL, ERR_TYPE, ATOM_integer, high);
}
}
/* between(+,+,+) */
if ( PL_get_number(n, &i) && intNumber(&i) )
{ int rc;
if ( hinf )
{ rc = cmpNumbers(&i, &l) >= 0;
} else
{ rc = cmpNumbers(&i, &l) >= 0 && cmpNumbers(&i, &h) <= 0;
}
clearInteger(&l);
clearInteger(&i);
if ( !hinf )
clearInteger(&h);
return rc;
}
/* between(+,+,-) */
if ( !PL_is_variable(n) )
return PL_error(NULL, 0, NULL, ERR_TYPE, ATOM_integer, n);
if ( hinf == false && cmpNumbers(&h, &l) < 0 )
{ clearInteger(&l);
clearInteger(&h);
fail;
}
if ( !PL_unify(n, low) )
fail;
if ( hinf == false && cmpNumbers(&l, &h) == 0 )
{ clearInteger(&l);
clearInteger(&h);
succeed;
}
state = allocForeignState(sizeof(*state));
cpNumber(&state->low, &l);
cpNumber(&state->high, &h);
state->hinf = hinf;
clearInteger(&l);
clearInteger(&h);
ForeignRedoPtr(state);
/*NOTREACHED*/
}
case FRG_REDO:
{ state = CTX_PTR;
if ( !ar_add_si(&state->low, 1) ||
!PL_unify_number(n, &state->low) )
{ rc = false;
goto cleanup;
}
if ( !state->hinf )
{ if ( likely(state->high.type == V_INTEGER &&
state->low.type == V_INTEGER) )
{ if ( state->low.value.i == state->high.value.i )
goto cleanup;
} else if ( cmpNumbers(&state->low, &state->high) == CMPEX_EQUAL )
goto cleanup;
}
ForeignRedoPtr(state);
/*NOTREACHED*/
}
case FRG_CUTTED:
{ state = CTX_PTR;
cleanup:
clearInteger(&state->low);
clearInteger(&state->high);
freeForeignState(state, sizeof(*state));
/*FALLTHROUGH*/
}
default:;
return rc;
}
}
static
PRED_IMPL("succ", 2, succ, 0)
{ PRED_LD
Word p1, p2;
number i1, i2, one;
int rc;
p1 = valTermRef(A1); deRef(p1);
one.type = V_INTEGER;
one.value.i = 1;
if ( isInteger(*p1) )
{ if ( isTaggedInt(*p1) )
{ sword v = valInt(*p1);
if ( v >= 0 && ++v >= 0 )
return PL_unify_int64(A2, v);
}
get_integer(*p1, &i1);
if ( ar_sign_i(&i1) < 0 )
return PL_error(NULL, 0, NULL, ERR_DOMAIN,
ATOM_not_less_than_zero, A1);
rc = ( pl_ar_add(&i1, &one, &i2) &&
PL_unify_number(A2, &i2)
);
} else if ( !canBind(*p1) )
return PL_error(NULL, 0, NULL, ERR_TYPE, ATOM_integer, A1);
p2 = valTermRef(A2); deRef(p2);
if ( isTaggedInt(*p2) )
{ sword v = valInt(*p2);
if ( v > 0 )
return PL_unify_int64(A1, v-1);
if ( v == 0 )
return false;
}
if ( isInteger(*p2) )
{ get_integer(*p2, &i2);
switch( ar_sign_i(&i2) )
{ case 1:
rc = ( ar_minus(&i2, &one, &i1) &&
PL_unify_number(A1, &i1)
);
break;
case 0:
fail;
case -1:
default:
return PL_error(NULL, 0, NULL, ERR_DOMAIN,
ATOM_not_less_than_zero, A2);
}
} else if ( !canBind(*p2) )
{ return PL_error(NULL, 0, NULL, ERR_TYPE, ATOM_integer, A2);
} else
return PL_error(NULL, 0, NULL, ERR_INSTANTIATION);
clearInteger(&i1);
clearInteger(&i2);
clearInteger(&one);
return rc;
}
#define var_or_integer(t, n, which, mask) LDFUNC(var_or_integer, t, n, which, mask)
static int
var_or_integer(DECL_LD term_t t, number *n, int which, int *mask)
{ Word p = valTermRef(t);
deRef(p);
if ( isInteger(*p) )
{ get_integer(*p, n);
*mask |= which;
succeed;
}
if ( canBind(*p) )
succeed;
return PL_error(NULL, 0, NULL, ERR_TYPE, ATOM_integer, t);
}
static
PRED_IMPL("plus", 3, plus, 0)
{ GET_LD
number m, n, o;
int mask = 0;
int rc;
if ( !var_or_integer(A1, &m, 0x1, &mask) ||
!var_or_integer(A2, &n, 0x2, &mask) ||
!var_or_integer(A3, &o, 0x4, &mask) )
fail;
switch(mask)
{ case 0x7: /* +, +, + */
case 0x3: /* +, +, - */
pl_ar_add(&m, &n, &o);
rc = PL_unify_number(A3, &o);
break;
case 0x5: /* +, -, + */
ar_minus(&o, &m, &n);
rc = PL_unify_number(A2, &n);
break;
case 0x6: /* -, +, + */
ar_minus(&o, &n, &m);
rc = PL_unify_number(A1, &m);
break;
default:
return PL_error(NULL, 0, NULL, ERR_INSTANTIATION);
}
clearInteger(&m);
clearInteger(&n);
clearInteger(&o);
return rc;
}
/********************************
* LOGICAL NUMBER FUNCTION *
*********************************/
static
PRED_IMPL("bounded_number", 3, bounded_number, 0)
{ PRED_LD
number n, lo, hi;
int rc;
if ( PL_get_number(A3, &n) )
{ switch(n.type)
{
#ifdef O_BIGNUM
case V_MPZ:
#endif
case V_INTEGER:
{ cpNumber(&lo, &n);
cpNumber(&hi, &n);
ar_add_si(&lo, -1);
ar_add_si(&hi, 1);
break;
}
#if O_BIGNUM
case V_MPQ:
promoteToFloatNumber(&n);
/*FALLTHROUGH*/
#endif
case V_FLOAT:
{ if ( isfinite(n.value.f) )
{ lo.type = V_FLOAT;
lo.value.f = nexttoward(n.value.f,-INFINITY);
hi.type = V_FLOAT;
hi.value.f = nexttoward(n.value.f, INFINITY);
} else
{ clearNumber(&n);
return false;
}
break;
}
}
rc = ( ((PL_get_number(A1, &lo)) ? (cmpNumbers(&lo, &n) == -1)
: PL_unify_number(A1, &lo)) &&
((PL_get_number(A2, &hi)) ? (cmpNumbers(&n, &hi) == -1)
: PL_unify_number(A2, &hi))
);
} else
{ rc = PL_error(NULL, 0, NULL, ERR_TYPE, ATOM_number, A1);
}
clearNumber(&n);
clearNumber(&lo);
clearNumber(&hi);
return rc;
}
/*******************************
* BIGNUM FUNCTIONS *
*******************************/
#ifdef O_BIGNUM
#define get_mpz(t, n) LDFUNC(get_mpz, t, n)
static int
get_mpz(DECL_LD term_t t, Number n)
{ Word p = valTermRef(t);
deRef(p);
if ( isInteger(*p) )
{ get_integer(*p, n);
promoteToMPZNumber(n);
return true;
}
return PL_type_error("integer", t);
}
/**
* divmod(+Dividend, +Divisor, -Quotient, -Remainder)
*
* Defined as
*
* - Quotient is div(Dividend, Divisor)
* - Remainder is mod(Dividend, Divisor)
*/
static
PRED_IMPL("divmod", 4, divmod, 0)
{ PRED_LD
number N = {V_INTEGER}, D = {V_INTEGER};
int rc = false;
if ( get_mpz(A1, &N) &&
get_mpz(A2, &D) )
{ if ( mpz_sgn(D.value.mpz) != 0 )
{ number Q = {V_MPZ}, R = {V_MPZ};
mpz_init(R.value.mpz);
mpz_init(Q.value.mpz);
mpz_fdiv_qr(Q.value.mpz, R.value.mpz, N.value.mpz, D.value.mpz);
rc = ( PL_unify_number(A3, &Q) &&
PL_unify_number(A4, &R)
);
clearNumber(&R);
clearNumber(&Q);
} else
{ rc = PL_error("divmod", 2, NULL, ERR_DIV_BY_ZERO);
}
}
clearNumber(&N);
clearNumber(&D);
return rc;
}
/**
* nth_integer_root_and_remainder(+N, +I, -Root, -Remainder)
*/
static
PRED_IMPL("nth_integer_root_and_remainder", 4,
nth_integer_root_and_remainder, 0)
{ PRED_LD
number N = {V_INTEGER};
long I;
int rc = false;
if ( PL_get_long_ex(A1, &I) &&
get_mpz(A2, &N) )
{ if ( I >= 1 )
{ number root = {V_MPZ};
number rem = {V_MPZ};
if ( mpz_sgn(N.value.mpz) < 0 &&
I % 2 == 0 )
{ rc = PL_error(NULL, 0, NULL, ERR_AR_UNDEF);
goto out;
}
mpz_init(root.value.mpz);
mpz_init(rem.value.mpz);
mpz_rootrem(root.value.mpz, rem.value.mpz,
N.value.mpz, (unsigned long)I);
rc = ( PL_unify_number(A3, &root) &&
PL_unify_number(A4, &rem)
);
clearNumber(&root);
clearNumber(&rem);
} else
{ rc = PL_domain_error("not_less_than_one", A1);
}
}
out:
clearNumber(&N);
return rc;
}
static
PRED_IMPL("rational", 3, rational, 0)
{ PRED_LD
Word p = valTermRef(A1);
deRef(p);
if ( isRational(*p) )
{ if ( isMPQNum(*p) )
{ number n, num, den;
int rc;
get_rational(*p, &n);
assert(n.type == V_MPQ);
num.type = V_MPZ;
den.type = V_MPZ;
mpz_init(num.value.mpz);
mpz_init(den.value.mpz);
mpz_set(num.value.mpz, mpq_numref(n.value.mpq));
mpz_set(den.value.mpz, mpq_denref(n.value.mpq));
rc = ( PL_unify_number(A2, &num) &&
PL_unify_number(A3, &den) );
clearNumber(&num);
clearNumber(&den);
return rc;
} else
{ return ( PL_unify(A1, A2) &&
PL_unify_integer(A3, 1) );
}
}
return false;
}
#endif /*O_BIGNUM*/
static
PRED_IMPL("float_parts", 4, float_parts, 0)
{ PRED_LD
double d;
if ( PL_get_float_ex(A1, &d) )
{ double m;
int e;
m = frexp(d, &e);
return ( PL_unify_float(A2, m) &&
PL_unify_integer(A3, 2) &&
PL_unify_integer(A4, e) );
}
return false;
}
/********************************
* COMPARISON *
*********************************/
/* implements <, =<, >, >=, =:= and =\=
*/
int
ar_compare(Number n1, Number n2, int what)
{ int diff = cmpNumbers(n1, n2); /* nan compares CMP_NOTEQ */
switch(what)
{ case LT: return diff == CMP_LESS;
case GT: return diff == CMP_GREATER;
case LE: return (diff == CMP_LESS) || (diff == CMP_EQUAL);
case GE: return (diff == CMP_GREATER) || (diff == CMP_EQUAL);
case NE: return diff != CMP_EQUAL;
case EQ: return diff == CMP_EQUAL;
default:
assert(0);
return false;
}
}
#define compareNumbers(n1, n2, what) LDFUNC(compareNumbers, n1, n2, what)
static foreign_t
compareNumbers(DECL_LD term_t n1, term_t n2, int what)
{ AR_CTX
number left, right;
int rc;
AR_BEGIN();
if ( valueExpression(n1, &left) &&
valueExpression(n2, &right) )
{ rc = ar_compare(&left, &right, what);
clearNumber(&left);
clearNumber(&right);
AR_END();
} else
{ AR_CLEANUP();
rc = false;
}
return rc;
}
static
PRED_IMPL("<", 2, lt, PL_FA_ISO)
{ PRED_LD
return compareNumbers(A1, A2, LT);
}
static
PRED_IMPL(">", 2, gt, PL_FA_ISO)
{ PRED_LD
return compareNumbers(A1, A2, GT);
}
static
PRED_IMPL("=<", 2, leq, PL_FA_ISO)
{ PRED_LD
return compareNumbers(A1, A2, LE);
}
static
PRED_IMPL(">=", 2, geq, PL_FA_ISO)
{ PRED_LD
return compareNumbers(A1, A2, GE);
}
static
PRED_IMPL("=\\=", 2, neq, PL_FA_ISO)
{ PRED_LD
return compareNumbers(A1, A2, NE);
}
static
PRED_IMPL("=:=", 2, eq, PL_FA_ISO)
{ PRED_LD
return compareNumbers(A1, A2, EQ);
}
/* compare Real number function: treats any numeric value as point on real number line
and compares two values using `cmpReals` function returning -1, 0, or 1. Comparing
any value with `nan` will either return `nan` or generate an error depending on global
flag `float_undefined`.
*/
static bool
ar_cmpr(Number n1, Number n2, Number r)
{ r->type = V_INTEGER;
r->value.i = cmpReals(n1, n2);
if ( r->value.i == CMP_NOTEQ ) // non-number
{ GET_LD
if ( LD->arith.f.flags & FLT_UNDEFINED ) // check float_undefined flag
{ r->type = V_FLOAT; // return NaN
r->value.f = const_nan;
} else
return PL_error(NULL, 0, NULL, ERR_AR_UNDEF); // error
}
return true;
}
/*******************************
* ARITHMETIC STACK *
*******************************/
Number
growArithStack(DECL_LD)
{ Number n;
if ( LD->arith.stack.top == LD->arith.stack.max )
{ size_t size;
if ( LD->arith.stack.base )
{ size = (size_t)(LD->arith.stack.max - LD->arith.stack.base);
LD->arith.stack.base = PL_realloc(LD->arith.stack.base,
size*sizeof(number)*2);
LD->arith.stack.top = LD->arith.stack.base+size;
size *= 2;
} else
{ size = 16;
LD->arith.stack.base = PL_malloc(size*sizeof(number));
LD->arith.stack.top = LD->arith.stack.base;
}
LD->arith.stack.max = LD->arith.stack.base+size;
}
n = LD->arith.stack.top;
LD->arith.stack.top++;
return n;
}
void
freeArithLocalData(PL_local_data_t *ld)
{ if ( ld->arith.stack.base )
PL_free(ld->arith.stack.base);
#ifdef O_BIGNUM
if ( ld->arith.random.initialised )
{ DEBUG(0, { GET_LD
assert(ld == LD);
});
WITH_LD(ld)
AR_PERSISTENT(gmp_randclear(ld->arith.random.state));
ld->arith.random.initialised = false;
}
#endif
}
/********************************
* FUNCTIONS *
*********************************/
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
isCurrentArithFunction(functor_t f)
Find existing arithmetic function definition for f.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static inline ArithF
isCurrentArithFunction(functor_t f)
{ size_t index = indexFunctor(f);
if ( index < GD->arith.functions_allocated )
{ return GD->arith.functions[index];
}
return NULL;
}
bool
check_float(Number n)
{ PL_error_code code = ERR_NO_ERROR;
switch(fpclassify(n->value.f))
{ case FP_NAN:
code = ERR_AR_UNDEF;
break;
case FP_SUBNORMAL:
code = ERR_AR_UNDERFLOW;
break;
case FP_INFINITE:
code = ERR_AR_OVERFLOW;
break;
}
if ( code != ERR_NO_ERROR )
{ GET_LD
switch(code)
{ case ERR_AR_OVERFLOW:
if ( LD->arith.f.flags & FLT_OVERFLOW )
return true;
break;
case ERR_AR_UNDERFLOW:
if ( LD->arith.f.flags & FLT_UNDERFLOW )
return true;
break;
case ERR_AR_UNDEF:
n->value.f = const_nan;
if ( LD->arith.f.flags & FLT_UNDEFINED )
return true;
break;
default:
assert(0);
}
return PL_error(NULL, 0, NULL, code);
}
return true;
}
static int
check_zero_div(int sign_n, Number r, char *func, int arity)
{ GET_LD
if ( sign_n == 0 )
{ if ( LD->arith.f.flags & FLT_UNDEFINED )
{ r->type = V_FLOAT;
r->value.f = const_nan;
return true;
}
} else if ( LD->arith.f.flags & FLT_ZERO_DIV )
{ r->type = V_FLOAT;
r->value.f = copysign(const_inf,sign_n);
return true;
}
return PL_error(func, arity, NULL, ERR_DIV_BY_ZERO);
}
#ifdef O_BIGNUM
static bool
check_mpq(Number r)
{ GET_LD
size_t sz;
if ( (sz=LD->arith.rat.max_rational_size) != (size_t)-1 )
{ int szn = MPZ_LIMB_SIZE(mpq_numref(r->value.mpq));
int szd = MPZ_LIMB_SIZE(mpq_denref(r->value.mpq));
if ( szn < 0 ) szn = -szn;
if ( szd < 0 ) szd = -szd;
if ( ( szn + szd ) * sizeof(mp_limb_t) > sz )
{ atom_t action = LD->arith.rat.max_rational_size_action;
if ( action == ATOM_float )
promoteToFloatNumber(r);
else if ( action == ATOM_error )
return PL_error(NULL, 0, "requires more than max_rational_size bytes",
ERR_AR_TRIPWIRE, ATOM_max_rational_size, r);
else
assert(0);
}
}
return true;
}
#endif
/*******************************
* EVALULATE *
*******************************/
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
valueExpression() and evalExpression evaluate an `evaluable term'.
valueExpression() is provides a shorthand for plain variables that are
typically integers
This new implementation avoids using the C-stack to be able to process
more deeply nested terms and to be able to recover in the unlikely case
that terms are still too deeply nested.
If it finds a term, it starts processing at the last argument, working back
to the start. If it finds the functor itself, it evaluates the pushed
arguments. Using this technique we push as few as possible arguments on
terms that are nested on the left (as in (1+2)+3, while we only push a
single pointer for each recursion level in the evaluable term.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static bool
pushForMark(segstack *stack, Word p, bool wr)
{ word w = ptr2word(p)|wr;
return pushSegStack(stack, w, word);
}
static void
popForMark(segstack *stack, Word *pp, bool *wr)
{ word w = 0;
popSegStack(stack, &w, word);
*wr = w & (word)0x1;
*pp = word2ptr(Word, (w & ~(word)0x1));
}
bool
evalExpression(DECL_LD term_t expr, number *result)
{ segstack term_stack;
segstack arg_stack;
word term_buf[16];
number arg_buf[16];
number *n = result;
number n_tmp;
bool walk_ref = false;
Word p;
Word start;
bool known_acyclic = false;
int pushed = 0;
functor_t functor;
bool signalled;
retry:
signalled = false;
p = valTermRef(expr);
deRef(p);
start = p;
for(;;)
{ switch(tag(*p))
{ case TAG_INTEGER:
get_rational(*p, n);
break;
case TAG_FLOAT:
n->value.f = valFloat(*p);
n->type = V_FLOAT;
break;
case TAG_VAR:
PL_error(NULL, 0, NULL, ERR_INSTANTIATION);
goto error;
case TAG_REFERENCE:
{ if ( !pushForMark(&term_stack, p, walk_ref) )
{ PL_no_memory();
goto error;
}
walk_ref = true;
deRef(p);
continue;
}
case TAG_ATOM:
{ ArithF0 f;
functor = lookupFunctorDef(word2atom(*p), 0);
arity0:
if ( (f = (ArithF0)isCurrentArithFunction(functor)) )
{ if ( (*f)(n) != true )
goto error;
} else
{ if ( isTextAtom(*p) )
{ PL_error(NULL, 0, NULL, ERR_NOT_EVALUABLE, functor);
} else
{ PL_error(NULL, 0, NULL, ERR_TYPE,
ATOM_evaluable, pushWordAsTermRef(p));
popTermRef();
}
goto error;
}
break;
}
case TAG_STRING:
if ( getCharExpression(p, n) != true )
goto error;
break;
case TAG_COMPOUND:
{ Functor term = valueTerm(*p);
size_t arity = arityFunctor(term->definition);
if ( term->definition == FUNCTOR_dot2 )