-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinca3.c
1860 lines (1696 loc) · 60.4 KB
/
inca3.c
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
#include<limits.h>
#include<math.h>
#include<stdint.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<termios.h>
#include<unistd.h>
/* Basic types */
typedef unsigned char C;
typedef intptr_t I;
typedef uintptr_t U;
typedef double D;
typedef struct a{I t, r, n, k, d[1];}*A; /* The abstract array header */
#define AT(a) ((a)->t) /* Type (takes values from enum type) */
#define AR(a) ((a)->r) /* Rank (size of Dims) */
#define AN(a) ((a)->n) /* Number of values in ravel */
#define AK(a) ((a)->k) /* Offset of ravel */
#define AD(a) ((a)->d) /* Dims */
#define AV(a) ((I*)(((C*)(a))+AK(a))) /* Values in ravelled order */
enum type { NLL, INT, BOX, SYMB, CHAR, NUM, DBL, MRK, VRB, NTYPES };
#define TYPEPAIR(a,b) ((a)*NTYPES+(b))
/* "singleton" objects */
struct a nullob = { NLL };
A null = &nullob;
struct a markob = { MRK };
A mark = &markob;
I infinite; /* result for function arguments not in function domain */
A newsymb(C *s,I n,I state); /* symbol constructor */
struct st *findsymb(struct st *st, char **s, int mode); /* symbol lookup */
/* Idioms */
#define P printf
#define R return
#define V1(f) A f(A w, A self) /* monadic verb signature */
#define V2(f) A f(A a, A w, A self) /* dyadic verb signature */
#define DO(n,x) {I i=0,_n=(n);for(;i<_n;++i){x;}}
#define DO2(n,x) {I j=0,_o=(n);for(;j<_o;++j){x;}}
#define DO3(n,x) {I k=0,_p=(n);for(;k<_p;++k){x;}}
/* Special ascii control-code macros
MODE1() defines the internal "base" representation for non-ascii APL symbols,
which just sets the top bit.
*/
#define ESC(x) "\x1b" #x
#define ESCCHR '\x1b'
#define CTL(x) (x-64)
#define EOT 004
#define DEL 127
#define MODE1(x) (x|1<<7)
#define MODE2(x) (x-32)
#include "ialf3.h" /* define character translation table alphatab[] */
/* convert input character to internal representation */
int inputtobase (int c, int mode){ int i;
for (i=0;i<(sizeof alphatab/sizeof*alphatab);i++)
if (c==*alphatab[i].input && mode==alphatab[i].ext)
return alphatab[i].base;
return mode? MODE1(c): c;
//return c | mode << 7;
}
/* convert internal representation to output representation */
char *basetooutput (int c){ int i;
for (i=0;i<(sizeof alphatab/sizeof*alphatab);i++)
if (c==alphatab[i].base)
return alphatab[i].output;
return "";
}
struct termios tm; /* terminal settings struct to save default settings */
/* setup special terminal mode for line editor:
turn off canonical mode for char-at-a-time processing
select vt220 G2 and G3 character sets for display of extra glyphs
*/
void specialtty(){
tcgetattr(0,&tm);
/*https://web.archive.org/web/20060117034503/\
http://www.cs.utk.edu/~shuford/terminal/xterm_codes_news.txt*/
//fputs("\x1B""*0\n",stdout);
#if 0
//experiment with line-drawing chars
fputs(ESC(*0),stdout);
fputs(ESC(n)
"lqqqqqk\n"
"x"
ESC(o)"a box"ESC(n)
"x\n"
"mqqqqqj\n"
ESC(o)"\n", stdout);
#endif
#if 0
//show the various alternate charsets available in xterm vt220 mode
fputs("\x1B*0\x1Bn",stdout); DO('~'-' ',P("%c",' '+i))P("\x1Bo\n");
//these 2 are not interesting:
//fputs("\x1B*1\x1Bn",stdout); DO('~'-' ',P("%c",' '+i))P("\x1Bo\n");
//fputs("\x1B*2\x1Bn",stdout); DO('~'-' ',P("%c",' '+i))P("\x1Bo\n");
fputs("\x1B*A\x1Bn",stdout); DO('~'-' ',P("%c",' '+i))P("\x1Bo\n");
fputs("\x1B*B\x1Bn",stdout); DO('~'-' ',P("%c",' '+i))P("\x1Bo\n");
#endif
#if 0
//show special char and line-drawing set as keyboard layout
fputs(ESC(*0)ESC(n),stdout);
fputs( "~!@#$%^&*()_+" "\n" "`1234567890-=" "\n"
"QWERTYUIOP{}|" "\n" "qwertyuiop[]\\" "\n"
"ASDFGHJKL:\"" "\n" "asdfghjkl;'" "\n"
"ZXCVBNM<>?" "\n" "zxcvbnm,./" "\n" , stdout);
fputs(ESC(o),stdout);
#endif
/* Select vt220 character sets */
fputs(ESC()")B",stdout); //set G1 charset to B : usascii
fputs(ESC(*0),stdout); //set G2 charset to 0 : special char and line drawing set ESC(n)
fputs(ESC(+A),stdout); //set G3 charset to A : "uk" accented and special chars ESC(o)
fputc(CTL('N'),stdout); //select G1 charset ESC(n):select G2 ESC(o):select G3
#if 1
{ /* print ALT-keyboard layout */
int i,j;
char *keys[] = {
"~!@#$%^&*()_+",
"`1234567890-=",
"QWERTYUIOP{}|",
"qwertyuiop[]\\",
"ASDFGHJKL:\"",
"asdfghjkl;'",
"ZXCVBNM<>?",
"zxcvbnm,./"
};
for (i=0;i<(sizeof keys/sizeof*keys);i++){
int n = strlen(keys[i]);
for (j=0;j<n;j++) /* V- mode=1 */
fputs(basetooutput(inputtobase(keys[i][j],1)),stdout);
fputc('\n',stdout);
}
}
#endif
/*
Set special terminal mode.
* No echo. (we'll control what you see)
* No echo of newline. (we'll control what you say)
* Ignore XON/XOFF semantics. (so ctrl-s and ctrl-q are available)
*/
{ struct termios tt=tm; //man termios
//cfmakeraw(&tt);
tt.c_iflag &= ~(IGNBRK | /*BRKINT |*/
PARMRK | ISTRIP | /*INLCR | IGNCR | ICRNL |*/ IXON);
/*tt.c_oflag &= ~OPOST;*/
tt.c_lflag &= ~(ECHO | /*ECHONL |*/ ICANON /*| ISIG | IEXTEN*/);
tt.c_cflag &= ~(CSIZE | PARENB);
tt.c_cflag |= CS8;
tcsetattr(0,TCSANOW,&tt); }
}
/* restore saved default terminal settings */
void restoretty(){ tcsetattr(0,TCSANOW,&tm); }
/* read expression from terminal into buffer
(re)allocate buffer as necessary
process backspaces
process mode changes and alt key.
pass characters through the translation table,
storing the "base" form, echoing the "output" form.
*/
C * getln(C *prompt, C **s, int *len){
int mode = 0;
int tmpmode = 0;
C *p;
if (prompt) fputs(prompt,stdout);
if (!*s) *s = malloc(*len=256);
p = *s;
while(1){
int c;
if (p-*s>*len){
C *t = realloc(*s,*len*=2);
if (t) *s=t;
else { *len/=2; R NULL; }
}
c = fgetc(stdin);
switch(c){
case EOF:
case EOT: if (p==*s) goto err;
break;
case ESCCHR:
c = fgetc(stdin);
switch(c){
default:
tmpmode = 1;
goto storechar;
break;
#if 0
/*
TODO: learn how the arrow keys can be distinguished from alt-[
*/
case '[':
c = fgetc(stdin);
switch(c){
default:
*p++ = MODE1('[');
fputs(basetooutput(MODE1('[')),stdout);
ungetc(c,stdin);
break;
case 'Z':
c = '\v'; //convert shift-TAB to vertical tab
*p++ = c; // save base in string
fputs(basetooutput(c),stdout); // echo output form
break;
}
break;
#endif
}
break;
case '\n':
fputc('\n',stdout);
*p++ = c;
goto breakwhile;
case CTL('N'): mode = !mode; tmpmode = 0; break;
case CTL('U'):
while(p>*s){
fputs("\b \b",stdout);
--p;
}
tmpmode = 0;
break;
case '\b':
case DEL:
fputs("\b \b",stdout);
if (p!=*s) --p;
break;
default:
storechar:
c = inputtobase(c,mode|tmpmode); // convert to internal "base" form
*p++ = c; // save base in string
tmpmode = 0;
fputs(basetooutput(c),stdout); // echo output form
break;
}
}
breakwhile:
*p++ = 0;
err:
return p==*s?NULL:*s;
}
/* allocate integer array */
I *ma(I n){R(I*)calloc(n,sizeof(I));}
/* move integers */
void mv(I*d,I*s,I n){DO(n,d[i]=s[i]);}
/* table rank, product of dimensions d[0..r-1] */
I tr(I r,I*d){I z=1;DO(r,z=z*d[i]);R z;}
/* generate (allocate and initialize) new abstract array
of type t */
A ga(I t,I r,I*d){I n;A z=(A)ma(sizeof*z+r+(n=tr(r,d)));
AT(z)=t;AR(z)=r;AN(z)=n;AK(z)=sizeof*z+(-1+AR(z))*sizeof(I);
mv(AD(z),d,r);R z;}
/* integer scalar */
A i0(I i){A z=ga(INT,0,0);*AV(z)=i;R z;}
/* integer vector */
A i1(I n,I*v){A z=ga(INT,1,&n);mv(AV(z),v,n);R z;}
/* integer-encoded numbers in the NUM type */
enum {
IMM_BIT = 16,
IMM_MASK = (1<<IMM_BIT)-1,
IMM_SIGN = 1<<(IMM_BIT-1),
BANK_BIT = sizeof(I)*CHAR_BIT - IMM_BIT,
//BANK_MASK = ((1<<BANK_BIT)-1) << IMM_BIT,
};
#define BANK_MASK (((1<<BANK_BIT)-1) << IMM_BIT)
#define encodenum(bnk,idx) ((bnk<<IMM_BIT)|idx)
A bank; /* the top-level number bank */
#define BANK_INIT (bank=ga(BOX,1,(I[]){1<<BANK_BIT})), \
(AV(bank)[0]=0)
A fixnum; /* current full-width integer allocation block */
#define FIXNUM_INIT (fixnum=(A) (AV(bank)[ ++AV(bank)[0] ]=(I)ga(INT,1,(I[]){1<<IMM_BIT}))), \
(AV(fixnum)[0]=0)
A flonum; /* current floating point number allocation block */
#define FLONUM_INIT (flonum=(A) (AV(bank)[ ++AV(bank)[0] ]=(I)ga(DBL,1,(I[]){1<<IMM_BIT}))), \
(((D*)AV(flonum))[0]=0.0)
/* search full-width integer in bank[FIXNUM]
allocate if not found
return encoded (bank,index) */
I fix(I i){
int j,n;
for(j=0,n=AV(fixnum)[0];++j<=n;)
if (AV(fixnum)[j]==i)
R encodenum(1,j);
//TODO: check for full table
// allocate new fixnum table in bank,
// update global fixnum pointer
// use a cursor variable here instead of constant 1
AV(fixnum)[j]=i;
++AV(fixnum)[0];
R encodenum(1,j);
}
/* search floating number in bank[FLONUM]
allocate if not found
return encoded(bank,index) */
I flo(D d){
int j,n;
for(j=0,n=(I)(((D*)AV(flonum))[0]);++j<=n;)
if (((D*)AV(flonum))[j]==d)
R encodenum(2,j);
//TODO: check for full table as in fix()
((D*)AV(flonum))[j]=d;
++((D*)AV(flonum))[0];
R encodenum(2,j);
}
/* "number"-encoded integer */
I num(I i){
if ((i)&(BANK_MASK|IMM_SIGN)) {
if (((i)&(BANK_MASK|IMM_SIGN))==(BANK_MASK|IMM_SIGN)) {
R i&IMM_MASK; //small negative number
}
else
R fix(i);
} else
R i;
}
/* number scalar */
A num0(I i){ A z=i0(num(i)); AT(z)=NUM; R z; }
/* "raw" number scalar. don't overcook. */
A num0r(I i){ A z=i0(i); AT(z)=NUM; R z;}
/* floating number scalar */
A num0f(D d){ A z=i0(flo(d)); AT(z)=NUM; R z; }
/* convert immediate num to full-width integer */
I numimm(I n){ R n&IMM_SIGN?n|BANK_MASK:n; }
/* fetch full-width integer from bank */
I numint(I n){
if ((n&BANK_MASK)==0) R numimm(n);
R AV((A)(AV(bank)[((unsigned)n&BANK_MASK)>>IMM_BIT]))[n&IMM_MASK];
}
/* fetch floating-point number from bank */
D numdbl(I n){
R ((D*)AV((A)(AV(bank)[((unsigned)n&BANK_MASK)>>IMM_BIT])))[n&IMM_MASK];
}
/* Multiprecision Integers
MPIs are a subtype of NUM (as are FIX FLO and IMM).
They are allocated in the mpint bank which is a BOX array.
Each element (the mpi data) is an INT array.
Numbers are stored in a sign-magnitude representation.
The top bit of the first int is the sign bit.
The base must therefore be <= 2^31.
The implementation can use either power-of-2 or power-of-10 bases.
Until a general radix-conversion is written for the output,
the base 10000 is used so the output routine can take shortcuts.
*/
#define MPI_SIGN_BIT (1U<<31)
#ifdef MPI_POWER_OF_2
# define MPI_BITS 31
# define MPI_BASE (1U<<MPI_BITS)
#else
# define MPI_BASE 10000
#endif
#define MPI_MAX (MPI_BASE-1)
#define MPI_SIGN(x) (!!(AV(x)[0]&MPI_SIGN_BIT))
#define SET_MPI_SIGN(x) (AV(x)[0]|=MPI_SIGN_BIT)
#define CLEAR_MPI_SIGN(x) (AV(x)[0]&=~MPI_SIGN_BIT) /*(AV(x)[0]&=MPI_MAX)*/
A mpint;
I mpzero;
#define MPINT_INIT (mpint=(A) (AV(bank)[ ++AV(bank)[0] ]=(I)ga(BOX,1,(I[]){1<<IMM_BIT}))), \
(AV(mpint)[0]=0), \
(mpzero=mpi(0))
/* construct new multiprecision int of length n.
return encoded bank:index.
TODO: check for full table as in fix()
*/
I newmpint(I n){
I j = ++AV(mpint)[0];
AV(mpint)[j]=(I)ga(INT,1,(I[]){n});
R encodenum(3,j);
}
/* yield the array representation of mpi designated n */
A numbox(I n){
R (A)AV((A)(AV(bank)[((unsigned)n&BANK_MASK)>>IMM_BIT]))[n&IMM_MASK];
}
/* allocate a larger array, left-padded with 0, containing the same value as x,
assumed unsigned.
note: does not allocate a slot in the mpint bank.
*/
A promote(A x,I n){
A z=ga(INT,1,(I[]){n});
DO(n-AN(x),AV(z)[i]=0)
DO(AN(x),AV(z)[i+(n-AN(x))]=AV(x)[i])
R z;
}
/*
construct a multiprecision int with (signed) value u.
return encoded bank:index.
*/
I mpi(U u){
I sign = !!(u&MPI_SIGN_BIT);
if (sign) u=(~u)+1; //unsigned 2's-comp negate
#ifdef MPI_POWER_OF_2
I r=newmpint(2);
A z=numbox(r);
AV(z)[0]=u>>MPI_BITS;
AV(z)[1]=u&MPI_MAX;
#else
I n=u?ceil(ceil(log10((D)u))/floor(log10((D)MPI_MAX))):1;
if(!n)n=1;
I r=newmpint(n);
A z=numbox(r);
I t;
DO(n, AV(z)[(AN(z)-1)-i]=u%MPI_BASE; u/=MPI_BASE)
//AV(z)[0]=i/MPI_BASE;
//AV(z)[1]=i%MPI_BASE;
#endif
if (sign) SET_MPI_SIGN(z);
R r;
}
I mpi_lt_mag(A a, A w){ // is a smaller than w?
if(AN(a)<AN(w)) R 1;
if(AN(a)>AN(w)) R 0;
#ifdef MPI_POWER_OF_2
DO(AN(w),if((AV(a)[i]&MPI_MAX)>(AV(w)[i]&MPI_MAX))R 0)
#else
DO(AN(w),if((AV(a)[i]&~MPI_SIGN_BIT)>(AV(w)[i]&~MPI_SIGN_BIT))R 0)
#endif
R 1;
}
/* perform math function op on mpi x and mpi y, yielding new mpi result.
allocates a new mpi value in the mpint bank.
*/
I mpop(I x,C op,I y){
A a,w,z;
I r;
I b=MPI_BASE;
a=numbox(x);
w=numbox(y);
I n=AN(a);
switch(op){ // handle sizes
case '+': case '-':
if (n<AN(w)){ a=promote(a,AN(w)); n=AN(w); }
if (n>AN(w)){ w=promote(w,n); }
}
I signa=MPI_SIGN(a); // save and remove signs from data representation
CLEAR_MPI_SIGN(a);
I signw=MPI_SIGN(w);
CLEAR_MPI_SIGN(w);
I signz=signa;
switch(op){ // handle signs
case '+':
if (signa!=signw){
op='-';
if (mpi_lt_mag(a,w)){
A t=w;w=a;a=t;
I tsign=signw;signw=signa;signa=tsign;
signz=signa;
}
}
break;
case '-':
if (signa!=signw){
signz=!signw;
op='+';
} else if (mpi_lt_mag(a,w)){
A t=w;w=a;a=t;
I tsign=signw;signw=signa;signa=tsign;
signz=!signz;
}
break;
case '*':
case '/':
signz=signa!=signw;
break;
}
switch(op){ // unsigned multiprecision arithmetic
case '+':
r=newmpint(n+1);
z=numbox(r);
{
int j=n,k=0;
while(j){
U t= (U)AV(a)[j-1] + (U)AV(w)[j-1] + (U)k;
#ifdef MPI_POWER_OF_2
AV(z)[j]= t&MPI_MAX;
k= !!(t&MPI_BASE);
#else
AV(z)[j]= t%MPI_BASE;
k= t/MPI_BASE;
#endif
--j;
}
if (k) AV(z)[0]=k;
else {
AK(z)+=sizeof(I); //don't keep adding zeros on the left
--AN(z);
--AD(z)[0];
}
}
break;
case '-':
r=newmpint(n);
z=numbox(r);
{
int j=n,k=0;
while(j){
U t= ((U)AV(a)[j-1] - (U)AV(w)[j-1]) - (U)k;
#ifdef MPI_POWER_OF_2
AV(z)[j-1]= t&MPI_MAX;
k= !!(t&MPI_BASE);
#else
AV(z)[j-1]= t%MPI_BASE;
k= t/MPI_BASE;
#endif
--j;
}
}
break;
case '*':
r=newmpint(n+AN(w)); /* m+n*/
z=numbox(r);
DO(AN(z),AV(z)[i]=0)
{
I j=n; /* m ==AN(a) */
while(j){
if (AV(w)[j-1]==0){ AV(z)[j-1]=0; } else {
U i=AN(w), /* n */
k=0;
while (i>0){
uint64_t t = AV(a)[i-1] * AV(w)[j-1] + AV(z)[(i+j)-1] + k;
#ifdef MPI_POWER_OF_2
AV(z)[(i+j)-1]= t&MPI_MAX;
k= t>>MPI_BITS;
#else
AV(z)[(i+j)-1]= t%MPI_BASE;
k= t/MPI_BASE;
#endif
--i;
}
}
--j;
}
}
break;
case '/':
{
I allzero=1;
DO(AN(a),if((AV(a)[i]&~MPI_SIGN_BIT)==0)continue;allzero=0;)
if (allzero)
R 0;
allzero=1;
DO(AN(w),if((AV(w)[i]&~MPI_SIGN_BIT)==0)continue;allzero=0;)
if (allzero)
R infinite;
}
break;
}
if (signa) SET_MPI_SIGN(a); // restore signs to the data representation
if (signw) SET_MPI_SIGN(w);
if (signz) SET_MPI_SIGN(z);
R r;
}
/* verb function declarations */
V1(copy);
V1(iota); V2(find);
V2(match);
V1(id); V2(plus);
V1(neg); V2(minus); V2(plusminus);
V2(times);
V2(quotient);
V1(size); V2(from);
V1(sha); V2(rsh);
V1(box);
V2(cat);
V2(boxcat);
V1(reduce);
/*
The verb table. The VERBNAME symbolically indexes a
single functional symbol which has an associated
ALPHATAB name and associated functions for monadic
(single right argument) or dyadic (left and right args) uses.
Verbs are recognized by the wd() function by being non-whitespace
non-alphanumeric and then refined by verb() called by newsymb().
The verb's A representation is a small integer which indexes
this table or an array of type VRB whose value is a (possibly
modified) copy of the verb record.
*/
/* VERBNAME ALPHA_NAME vm vd f g k m n id */
#define VERBTAB(_) \
_( ZEROFUNC, 0, 0, 0, 0, 0, 0, 0, 0, 0 ) \
_( PLUS, ALPHA_PLUS, id, plus, 0, 0, 0, 0, 0, 0 ) \
_( MINUS, ALPHA_MINUS, neg, minus, 0, 0, 0, 0, 0, 0 ) \
_( TIMES, ALPHA_TIMES, 0, times, 0, 0, 0, 0, 0, 1 ) \
_( DIVIDE, ALPHA_COLONBAR, 0, quotient, 0, 0, 0, 0, 0, 1 ) \
_( PLUSMINUS, ALPHA_PLUSMINUS, neg, plusminus, 0, 0, 0, 0, 0, 0 ) \
_( RBRACE, ALPHA_RBRACE, size, from, 0, 0, 0, 0, 0, 0 ) \
_( IOTA, ALPHA_IOTA, iota, find, 0, 0, 0, 0, 0, 0 ) \
_( BOXF, ALPHA_LANG, box, 0, 0, 0, 0, 0, 0, 0 ) \
_( RHO, ALPHA_RHO, sha, rsh, 0, 0, 0, 0, 0, 0 ) \
_( COMMA, ALPHA_COMMA, 0, cat, 0, 0, 0, 0, 0, 0 ) \
_( SEMICOLON, ALPHA_SEMICOLON, box, boxcat, 0, 0, 0, 0, 0, 0 ) \
_( SLASH, 0, 0, 0, 0, 0, 0, 0, 0, 0 ) \
_( NULLFUNC, 0, 0, 0, 0, 0, 0, 0, 0, 0 )
struct v { I c; A (*vm)(); A (*vd)(); I f,g,k,m,n; I id; };
typedef struct v *V; //dynamic verb type
#define VERBTAB_NAME(a, ...) a ,
enum { VERBTAB(VERBTAB_NAME) }; //generate verb symbols
#define VERBTAB_ENT(a, ...) { __VA_ARGS__ },
struct v vt[] = { VERBTAB(VERBTAB_ENT) }; //generate verb table array
/* adverb function declarations */
V1(withl);
V1(withr);
V1(on1);
V2(on2);
V2(amp);
V2(rank);
V1(areduce);
/*
The adverb table uses the same struct as a verb but is
separated to better distinguish the two classes of object.
The adverb's A representation is a small integer, biased by
the range of verb codes, which indexes this table. (Adverbs it
seems do not exist as dynamic entities, since the application
of an adverb produces a derived *verb*; thus there is no such
thing as a derived adverb (as defined in J and APL87).)
*/
/* ADVNAME ALPHA_NAME vm vd f g k m n id) */
#define ADVTAB(_) \
_(ZEROOP=NULLFUNC+1, 0, 0, 0, 0, 0, 0, 0, 0, 0) \
_(WITH, ALPHA_AMPERSAND, 0, amp, 0, 0, 0, 0, 0, 0) \
_(RANK, ALPHA_TWODOTS, 0, rank, 0, 0, 0, 0, 0, 0) \
_(ASLASH, ALPHA_SLASH, areduce, 0, 0, 0, 0, 0, 0, 0) \
_(NULLOP, 0)
#define ADVTAB_NAME(a, ...) a ,
enum { ADVTAB(ADVTAB_NAME) };
struct v ot[] = { ADVTAB(VERBTAB_ENT) }; //generate adverb table array
/* produce a new derived verb with specified fields. must have A z;
declared and available for scratch. */
#define DERIV(...) \
((z=ga(VRB,1,(I[]){sizeof(struct v)/sizeof(int)})), \
(*((V)AV(z))=(struct v){__VA_ARGS__}), \
z)
/* adverb/conjunction macros */
I qv(); /* declare the verb predicate */
enum { ANOUN = 1, AVERB, N_A,
NN=ANOUN*N_A+ANOUN,
NV=ANOUN*N_A+AVERB,
VN=AVERB*N_A+ANOUN,
VV=AVERB*N_A+AVERB,
};
#define VERBNOUN(x) \
(qv(x)?AVERB:ANOUN)
#define CONJCASE(a,w) \
(VERBNOUN(a)*N_A+VERBNOUN(w))
/* load verb data from code in x.
save new derived verb in x. */
#define LOADV(x) \
abs((I)x)<(sizeof vt/sizeof*vt)? \
(x=DERIV(vt[(I)x].c, vt[(I)x].vm, vt[(I)x].vd, vt[(I)x].f, vt[(I)x].g, \
vt[(I)x].k, vt[(I)x].m, vt[(I)x].n, vt[(I)x].id)) \
:x
/* & conjunction */
V2(amp){
A z;
switch(CONJCASE(a,w)){
case NN: R 0;
case NV: R DERIV(ALPHA_AMPERSAND, withl, NULL, (I)a, (I)w, 0, 0, 0, 0);
case VN: R DERIV(ALPHA_AMPERSAND, withr, NULL, (I)a, (I)w, 0, 0, 0, 0);
case VV: R DERIV(ALPHA_AMPERSAND, on1, on2, (I)a, (I)w, 0, 0, 0, 0);
}
}
/* rank conjunction */
V2(rank){
A z;
switch(CONJCASE(a,w)){
case NN: R 0;
case NV: R 0;
case VN: LOADV(a);
switch(AN(w)){
case 0: R 0;
case 1: R DERIV(((V)AV(a))->c, ((V)AV(a))->vm, ((V)AV(a))->vd, 0, 0,
numint(*AV(w)), numint(*AV(w)), numint(*AV(w)), ((V)AV(a))->id);
case 2: R DERIV(((V)AV(a))->c, ((V)AV(a))->vm, ((V)AV(a))->vd, 0, 0,
numint(AV(w)[1]), numint(AV(w)[0]), numint(AV(w)[1]), ((V)AV(a))->id);
case 3: R DERIV(((V)AV(a))->c, ((V)AV(a))->vm, ((V)AV(a))->vd, 0, 0,
numint(AV(w)[0]), numint(AV(w)[1]), numint(AV(w)[2]), ((V)AV(a))->id);
default: R 0;
}
case VV: LOADV(a);
LOADV(w);
R DERIV(((V)AV(a))->c, ((V)AV(a))->vm, ((V)AV(a))->vd, 0, 0,
((V)AV(w))->k, ((V)AV(w))->m, ((V)AV(w))->n, ((V)AV(a))->id);
}
}
/* reduce adverb */
V1(areduce){
A z;
R DERIV(ALPHA_SLASH, reduce, NULL, (I)w, 0, 0, 0, 0, 0);
}
/* Verb macros */
/* create v pointer to access verb properties
if self is zero, load base verb from verb table
*/
#define LOADVSELF(base) \
V v=self? \
(I)self>0&&(I)self<(sizeof vt/sizeof*vt)? \
vt+(I)self \
:(V)AV(self) \
:vt+base;
/* fill-in array f with rk elements of ar's shape vector */
#define LOADFRAME(f,ar,rk) \
/*P("rk=%d\n",rk);*/ \
if (AR(ar)-(rk)>=0) { \
/*f = ga(0,AR(ar)?AR(ar)==1?0:1:0,(I[]){AR(ar)-(rk)?AR(ar)-(rk):1});*/ \
/*mv(AV(f),AR(ar)-(rk)?AD(ar):(I[]){0},AR(ar)-(rk)?AR(ar)-(rk):1);*/ \
AR(f)=AR(ar)-(rk)>0?1:0; \
AN(f)=AD(f)[0]=AR(ar)-(rk); \
AK(f)=((C*)AD(ar))-((C*)f); /*make "indirect" array of ar's frame shape*/ \
} \
/*P("AR(f)=%d\n", AR(f));*/
/* load the left frame */
#define LFRAME(rk) \
/*A lf = 0;*/ \
A lf = &(struct a){.t=INT,.n=0,.r=0}; \
if ((rk)<0) { LOADFRAME(lf,a,AR(a)+(rk)) } \
else { LOADFRAME(lf,a,rk) }
/* load the right frame */
#define RFRAME(rk) \
/*A rf = 0;*/ \
A rf = &(struct a){.t=INT,.n=0,.r=0}; \
if ((rk)<0) { LOADFRAME(rf,w,AR(w)+(rk)) } \
else { LOADFRAME(rf,w,rk) }
/* fill-in array c with rk elements from the tail of ar's shape vector */
#define LOADCELL(c,ar,rk) \
if ((rk)>0 && (rk)<AR(ar)) { \
AR(c)=(rk)>0?1:0; \
AN(c)=AD(c)[0]=rk; \
AK(c)=((C*)(AD(ar)+AR(ar)-(rk)))-((C*)c); /* indirect array of ar's cell shape */ \
}
/* load the left cell */
#define LCELL(rk) \
A lc = &(struct a){.t=INT,.n=0,.r=0}; \
if ((rk)<0) { LOADCELL(lc,a,AR(a)+(rk)) } \
else { LOADCELL(lc,a,rk) }
/* load the right cell */
#define RCELL(rk) \
A rc = &(struct a){.t=INT,.n=0,.r=0}; \
if ((rk)<0) { LOADCELL(rc,w,AR(w)+(rk)) } \
else { LOADCELL(rc,w,rk) }
/* reshape arguments to make frames agree */
#define FRAME_AGREE \
/*P("frame agree\n");*/ \
if (!*AV(match(lf,rf,0))) { /* Frame Agreement */ \
/*P("no match\n");*/ \
if (AN(lf)==0) /* Scalar extension on left frame */ \
{ \
/*P("reshape_a\n");*/ \
/*pr(rf); pr(lc);*/ \
if (AN(lc)>0) \
a=rsh(cat(rf,lc,0),a,0); \
else \
a=rsh(rf,a,0); \
/*pr(a);*/ \
} else \
if (AN(rf)==0) /* Scalar extension on right frame */ \
{ \
/*P("reshape_w\n");*/ \
/*pr(lf); pr(rc);*/ \
if (AN(rc)>0) \
w=rsh(cat(lf,rc,0),w,0); \
else \
w=rsh(lf,w,0); \
/*pr(w);*/ \
} \
}
/* header size */
#define HSZ(rc) ((AR(rc)?AR(rc):0)+sizeof(struct a))
/*
create an box array of frame dimensions,
each element of which is an indirect array
accessing a cell-sized slice of the argument array.
*/
#define BOX_CELLS(base,csz,lf,lc,a,ba,bam) \
csz=tr(AN(lc),AV(lc)); /* cell size */ \
A ba=ga(BOX,AN(lf),AV(lf)); /* boxed a */ \
A bam=(A)ma(HSZ(lc)*tr(AN(lf),AV(lf))); /* boxed a memory (for array headers) */ \
DO(AN(ba), \
AV(ba)[i]=(I)(((I*)bam)+HSZ(lc)*i); /* set pointer to header in box array */ \
AT((A)(((I*)bam)+HSZ(lc)*i))=AT(a); /* type of header is type of a */ \
AN((A)(((I*)bam)+HSZ(lc)*i))=csz; /* num elements is cell size */ \
AR((A)(((I*)bam)+HSZ(lc)*i))=AN(lc); /* rank is length of cell shape */ \
mv(AD((A)(((I*)bam)+HSZ(lc)*i)),AV(lc),AN(lc)); /* dims are cell data */ \
AK((A)(((I*)bam)+HSZ(lc)*i))= /* array data is (ptr to) */ \
((C*)(AV(w)+csz*i))-((C*)(((I*)bam)+HSZ(lc)*i)); /* slice of a */ \
/*pr(AV(ba)[i]);*/ \
) \
/*
unpack and expand the boxed results from the recursive call to the verb
*/
#define ASSEMBLE_RESULTS(ba,bam) \
/*P("assemble results\n");*/ \
A ms = ga(INT,1,(I[]){0}); \
DO(AN(bz), /* find max shape */ \
if ( (AR((A)(AV(bz)[i]))>AN(ms)) \
|| (tr(AR((A)(AV(bz)[i])),AD((A)(AV(bz)[i]))) > tr(AR(ms),AD(ms))) \
) \
{ \
free(ms); \
ms = ga(INT,1,&AR((A)(AV(bz)[i]))); \
mv(AV(ms),AD((A)(AV(bz)[i])),AR((A)(AV(bz)[i]))); \
} \
) \
/*pr(ms);*/ \
DO(AN(bz), /* pad to max shape */ \
if ( (AR((A)(AV(bz)[i]))<AN(ms)) \
|| (tr(AR((A)(AV(bz)[i])),AD((A)(AV(bz)[i])))<tr(AN(ms),AV(ms))) \
) \
{ \
AV(bz)[i]=(I)rsh(ms,(A)AV(bz)[i],0); \
} \
) \
rf=cat(rf,ms,0); \
/*pr(rf);*/ \
A z=ga(AT(w),AN(rf),AV(rf)); \
A zslice=ga(AT(w),1,&AN(ms)); \
AR(zslice)=AN(ms); \
mv(AD(zslice),AV(ms),AN(ms)); \
AK(zslice)=((C*)AV(z))-((C*)zslice); \
AN(zslice)=tr(AR(zslice),AD(zslice)); \
DO(AN(bz), \
mv(AV(zslice),AV((A)AV(bz)[i]),AN(zslice)); \
/*pr(zslice);*/ \
AK(zslice)+=AN(zslice)*sizeof(I); \
) \
free(ms); free(zslice); free(ba); free(bam); R z; \
/*
monadic verb behavior for handling non-base cells
*/
#define CELL_HANDLE1(base) \
if (self&& (vt[base].k != v->k)) { \
/* requested cell is not base cell */ \
I csz; \
BOX_CELLS(base,csz,rf,rc,w,bw,bwm) \
A bz=v->vm(bw,base); \
ASSEMBLE_RESULTS(bw,bwm) \
}
/*
dyadic verb behavior for handling non-base cells
*/
#define CELL_HANDLE2(base) \
/*P("cell handle\n");*/ \
if (self&& (vt[base].m != v->m && vt[base].n != v->n)) { \
/*P(" requested cells are not base cells\n");*/ \
I csz; \
BOX_CELLS(base,csz,lf,lc,a,ba,bam) \
BOX_CELLS(base,csz,rf,rc,w,bw,bwm) \
A bz=v->vd(ba,bw,base); \
/*pr(bz);*/ \
free(ba); free(bam); \
ASSEMBLE_RESULTS(bw,bwm) \
} else if (self&& vt[base].m != v->m) { \
/*P(" left cell is not base cell\n");*/ \
I csz; \
BOX_CELLS(base,csz,lf,lc,a,ba,bam) \
A bz=v->vd(ba,w,base); /* call self recursively with base ranks */ \
/*pr(bz);*/ \
/* assemble results */ \
ASSEMBLE_RESULTS(ba,bam) \
} else if (self&& vt[base].n != v->n) { \
/*P(" right cell is not base cell\n");*/ \
I csz; \
BOX_CELLS(base,csz,rf,rc,w,bw,bwm) \
A bz=v->vd(a,bw,base); /* call self recursively with base ranks */ \
/*pr(bz);*/ \
ASSEMBLE_RESULTS(bw,bwm) \
}
/*
monadic behavior for handling a boxed argument:
call verb recursively upon each element
*/
#define BOX_HANDLE1(base) \
if (AT(w)==BOX) { \
A z=ga(BOX,AN(rf),AV(rf)); \
DO(AN(z), \
AV(z)[i]=(I)v->vm(AV(w)[i],base); \
) \
R z; \
}
/*
dyadic behavior for handling boxed arguments:
call verb recursively upon boxed elements or slices
*/
#define BOX_HANDLE2(base) \
if (AT(a)==BOX&&AT(w)==BOX){ \
/*P("BOXaw\n");*/ \
A z=ga(BOX,AN(lf),AV(lf)); \
DO(AN(z), \
AV(z)[i]=(I)v->vd(AV(a)[i],AV(w)[i],base); \
) \
R z; \
} else if (AT(a)==BOX) { \
/*P("BOXa\n");*/ \
A wslice=ga(AT(w),1,&AN(rc)); \
AR(wslice)=AN(rc); \
mv(AD(wslice),AV(rc),AN(rc)); \
AK(wslice)=((C*)AV(w))-((C*)wslice); \
AN(wslice)=tr(AR(wslice),AD(wslice)); \
A z=ga(BOX,AN(lf),AV(lf)); \
DO(AN(z), \
AV(z)[i]=(I)v->vd(AV(a)[i],wslice,base); \
AK(wslice)+=AN(wslice)*sizeof(I); \
) \
free(wslice); \
R z; \
} else if (AT(w)==BOX) { \
/*P("BOXw\n");*/ \
A aslice=ga(AT(a),1,&AN(lc)); \
AR(aslice)=AN(lc); \
mv(AD(aslice),AV(lc),AN(lc)); \
AK(aslice)=((C*)AV(a))-((C*)aslice); \
AN(aslice)=tr(AR(aslice),AD(aslice)); \
A z=ga(BOX,AN(rf),AV(rf)); \
DO(AN(z), \
/*P("slice=%d %d %d %d\n", AR(aslice), *AD(aslice), AN(aslice), AK(aslice));*/ \
/*pr(aslice);*/ \