-
Notifications
You must be signed in to change notification settings - Fork 0
/
wak.c
4890 lines (4451 loc) · 145 KB
/
wak.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
// wak.c -- "monolithic" (one-file) awk implementation
// Copyright 2024 Ray Gardner
// License: 0BSD
// vi: tabstop=2 softtabstop=2 shiftwidth=2
#ifndef FOR_TOYBOX
#ifndef __STDC_WANT_LIB_EXT2__
#define __STDC_WANT_LIB_EXT2__ 1 // for getline(), getdelim()
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <stdarg.h>
#include <ctype.h>
#include <math.h>
#include <time.h>
#include <locale.h>
#include <wchar.h>
#include <wctype.h>
#include <errno.h>
#include <assert.h>
// for isatty():
#include <unistd.h>
// for getopt_long():
#include <getopt.h>
#include <regex.h>
#if defined(__unix__) || defined(linux)
#include <langinfo.h>
#endif
extern char **environ; // needed outside toybox with gcc ?
// __USE_MINGW_ANSI_STDIO will have MinGW use its own printf format system?
// Because "The vc6.0 msvcrt.dll that MinGW-w64 targets doesn't implement
// support for the ANSI standard format specifiers."
// https://www.msys2.org/wiki/Porting/
#if !(defined(__unix__) || defined(linux))
# define __USE_MINGW_ANSI_STDIO 1
#endif
#endif // FOR_TOYBOX
#ifdef __GNUC__
#define ATTR_FALLTHROUGH_INTENDED __attribute__ ((fallthrough))
#else
#define ATTR_FALLTHROUGH_INTENDED
#endif
#ifndef FOR_TOYBOX
#define maxof(a,b) ((a)>(b)?(a):(b))
#ifndef REG_STARTEND
#define REG_STARTEND 0
#endif
struct arg_list {
struct arg_list *next;
char *arg;
};
#endif // FOR_TOYBOX
////////////////////
//// declarations
////////////////////
#define PBUFSIZE 512 // For num_to_zstring()
#ifndef FOR_TOYBOX
struct scanner_state {
char *p;
char *progstring;
struct arg_list *prog_args;
char *filename;
char *line;
size_t line_size;
ssize_t line_len;
int line_num;
int ch;
FILE *fp;
// state includes latest token seen
int tok;
int tokbuiltin;
int toktype;
char *tokstr;
// int maxtok;
// int toklen;
size_t maxtok;
size_t toklen;
// int symtab_entry;
double numval;
int error; // Set if lexical error.
};
struct compiler_globals {
int in_print_stmt;
int paren_level;
int in_function_body;
int funcnum;
int nparms;
int compile_error_count;
int first_begin;
int last_begin;
int first_end;
int last_end;
int first_recrule; // recrule means "record rule"
int last_recrule;
int break_dest;
int continue_dest;
int stack_offset_to_fix; // fixup stack if return in for(e in a)
int range_pattern_num;
int rule_type; // tkbegin, tkend, or 0
};
// zvalue: the main awk value type
// Can be number or string or both, or else map (array) or regex
struct zvalue {
unsigned flags;
double num;
union { // anonymous union not in C99; not going to fix it now.
struct zstring *vst;
struct zmap *map;
regex_t *rx;
};
};
struct runtime_globals {
struct zvalue cur_arg;
FILE *fp; // current data file
int narg; // cmdline arg index
int nfiles; // num of cmdline data file args processed
int eof; // all cmdline files (incl. stdin) read
char *recptr;
struct zstring *zspr; // Global to receive sprintf() string value
};
// zlist: expanding sequential list
struct zlist {
char *base, *limit, *avail;
size_t size;
};
struct zfile {
struct zfile *next;
char *fn;
FILE *fp;
char mode; // w, a, or r
char file_or_pipe; // 1 if file, 0 if pipe
char is_tty, is_std_file;
char eof;
int ro, lim, buflen;
char *buf;
};
// Global data
struct global_data {
struct scanner_state *scs;
char *tokstr;
// For checking end of prev statement for termination and if '/' can come next
int prevtok;
struct zlist globals_table; // global symbol table
struct zlist locals_table; // local symbol table
struct zlist func_def_table; // function symbol table
struct zlist literals;
struct zlist fields;
struct zlist zcode;
struct zlist stack;
char *progname;
struct compiler_globals cgl;
int spec_var_limit; // used in compile.c and run.c
int zcode_last; // used in only in compile.c
struct zvalue *stackp; // ptr to top of runtime stack
struct runtime_globals rgl;
char *pbuf; // Used for number formatting in num_to_zstring()
regex_t rx_default, rx_last; // Default and last used FS regex
#define FS_MAX 64
char fs_last[FS_MAX];
char one_char_fs[4];
int nf_internal; // should match NF
char range_sw[64]; // FIXME TODO quick and dirty set of range switches
int file_cnt, std_file_cnt;
struct zfile *zfiles, *cfile, *zstdout;
regex_t rx_printf_fmt;
#define RS_MAX 64
char rs_last[RS_MAX];
regex_t rx_rs_default, rx_rs_last;
};
#endif // FOR_TOYBOX
enum toktypes {
// EOF (use -1 from stdio.h)
ERROR = 2, NEWLINE, VAR, NUMBER, STRING, REGEX, USERFUNC, BUILTIN, TOKEN,
KEYWORD
};
// Must align with lbp_table[]
enum tokens {
tkunusedtoken, tkeof, tkerr, tknl,
tkvar, tknumber, tkstring, tkregex, tkfunc, tkbuiltin,
// static char *ops = " ; , [ ] ( ) { } $ ++ -- ^ ! * / % + - "
// "< <= != == > >= ~ !~ && || ? : ^= %= *= /= += -= = >> | ";
tksemi, tkcomma, tklbracket, tkrbracket, tklparen, tkrparen, tklbrace,
tkrbrace, tkfield, tkincr, tkdecr, tkpow, tknot, tkmul, tkdiv, tkmod,
tkplus, tkminus,
tkcat, // !!! Fake operator for concatenation (just adjacent string exprs)
tklt, tkle, tkne, tkeq, tkgt, tkge, tkmatchop, tknotmatch, tkand, tkor,
tkternif, tkternelse, tkpowasgn, tkmodasgn, tkmulasgn, tkdivasgn,
tkaddasgn, tksubasgn, tkasgn, tkappend, tkpipe,
// static char *keywords = " in BEGIN END if else "
// "while for do break continue exit function "
// "return next nextfile delete print printf getline ";
tkin, tkbegin, tkend, tkif, tkelse,
tkwhile, tkfor, tkdo, tkbreak, tkcontinue, tkexit, tkfunction,
tkreturn, tknext, tknextfile, tkdelete, tkprint, tkprintf, tkgetline,
// static char *builtins = " atan2 cos sin exp "
// "log sqrt int rand srand length "
// "tolower toupper system fflush "
// "and or xor lshift rshift ";
tkatan2, tkcos, tksin, tkexp, tklog, tksqrt, tkint, tkrand, tksrand,
tklength, tktolower, tktoupper, tksystem, tkfflush,
tkband, tkbor, tkbxor, tklshift, tkrshift,
// static char *specialfuncs = " close index match split "
// "sub gsub sprintf substr ";
tkclose, tkindex, tkmatch, tksplit,
tksub, tkgsub, tksprintf, tksubstr, tklasttk
};
enum opcodes {
opunusedop = tklasttk,
opvarref, opmapref, opfldref, oppush, opdrop, opdrop_n, opnotnot,
oppreincr, oppredecr, oppostincr, oppostdecr, opnegate, opjump, opjumptrue,
opjumpfalse, opprepcall, opmap, opmapiternext, opmapdelete, opmatchrec,
opquit, opprintrec, oprange1, oprange2, oprange3, oplastop
};
// Special variables (POSIX). Must align with char *spec_vars[]
enum spec_var_names { ARGC=1, ARGV, CONVFMT, ENVIRON, FILENAME, FNR, FS, NF,
NR, OFMT, OFS, ORS, RLENGTH, RS, RSTART, SUBSEP };
struct symtab_slot { // global symbol table entry
unsigned flags;
char *name;
};
// zstring: flexible string type.
// Capacity must be > size because we insert a NUL byte.
struct zstring {
int refcnt;
unsigned size;
unsigned capacity;
char str[]; // C99 flexible array member
};
// Flag bits for zvalue and symbol tables
#define ZF_MAYBEMAP (1u << 1)
#define ZF_MAP (1u << 2)
#define ZF_SCALAR (1u << 3)
#define ZF_NUM (1u << 4)
#define ZF_RX (1u << 5)
#define ZF_STR (1u << 6)
#define ZF_NUMSTR (1u << 7) // "numeric string" per posix
#define ZF_REF (1u << 9) // for lvalues
#define ZF_MAPREF (1u << 10) // for lvalues
#define ZF_FIELDREF (1u << 11) // for lvalues
#define ZF_EMPTY_RX (1u << 12)
#define ZF_ANYMAP (ZF_MAP | ZF_MAYBEMAP)
// Macro to help facilitate possible future change in zvalue layout.
#define ZVINIT(flags, num, ptr) {(flags), (double)(num), {(ptr)}}
#define IS_STR(zvalp) ((zvalp)->flags & ZF_STR)
#define IS_RX(zvalp) ((zvalp)->flags & ZF_RX)
#define IS_NUM(zvalp) ((zvalp)->flags & ZF_NUM)
#define IS_MAP(zvalp) ((zvalp)->flags & ZF_MAP)
#define IS_EMPTY_RX(zvalp) ((zvalp)->flags & ZF_EMPTY_RX)
#define GLOBAL ((struct symtab_slot *)TT.globals_table.base)
#define LOCAL ((struct symtab_slot *)TT.locals_table.base)
#define FUNC_DEF ((struct functab_slot *)TT.func_def_table.base)
#define LITERAL ((struct zvalue *)TT.literals.base)
#define STACK ((struct zvalue *)TT.stack.base)
#define FIELD ((struct zvalue *)TT.fields.base)
#define ZCODE ((int *)TT.zcode.base)
#define FUNC_DEFINED (1u)
#define FUNC_CALLED (2u)
#define MIN_STACK_LEFT 1024
struct functab_slot { // function symbol table entry
unsigned flags;
char *name;
struct zlist function_locals;
int zcode_addr;
};
// Elements of the hash table (key/value pairs)
struct zmap_slot {
int hash; // store hash key to speed hash table expansion
struct zstring *key;
struct zvalue val;
};
#define ZMSLOTINIT(hash, key, val) {hash, key, val}
// zmap: Mapping data type for arrays; a hash table. Values in hash are either
// 0 (unused), -1 (marked deleted), or one plus the number of the zmap slot
// containing a key/value pair. The zlist slot entries are numbered from 0 to
// count-1, so need to add one to distinguish from unused. The probe sequence
// is borrowed from Python dict, using the "perturb" idea to mix in upper bits
// of the original hash value.
struct zmap {
unsigned mask; // tablesize - 1; tablesize is 2 ** n
int *hash; // (mask + 1) elements
int limit; // 80% of table size ((mask+1)*8/10)
int count; // number of occupied slots in hash
int deleted; // number of deleted slots
struct zlist slot; // expanding list of zmap_slot elements
};
#define MAPSLOT ((struct zmap_slot *)(m->slot).base)
#define FFATAL(format, ...) zzerr("$" format, __VA_ARGS__)
#define FATAL(...) zzerr("$%s\n", __VA_ARGS__)
#define XERR(format, ...) zzerr(format, __VA_ARGS__)
#define NO_EXIT_STATUS (9999987) // value unlikely to appear in exit stmt
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
ssize_t getdelim(char ** restrict lineptr, size_t * restrict n, int delimiter, FILE *stream);
#ifndef FOR_TOYBOX
// Common (global) data
static struct global_data TT;
struct optflags {
char FLAG_b;
};
static struct optflags optflags;
#define FLAG(x) (optflags.FLAG_##x)
#endif // FOR_TOYBOX
////////////////////
//// lib
////////////////////
static void xfree(void *p)
{
free(p);
}
#ifndef FOR_TOYBOX
// awk_exit() to correspond to a wrapper for toybox
static void awk_exit(int status)
{
exit(status);
}
static void error_exit(char *format, ...)
{
va_list args;
fprintf(stderr, "FATAL: ");
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
putc('\n', stderr);
fflush(stderr);
awk_exit(2);
}
// Compile a regular expression into a regex_t
static void xregcomp(regex_t *preg, char *regex, int cflags)
{
// Copied from Rob Landley's toybox
// Copyright 2006 Rob Landley <[email protected]>
// License: 0BSD
int rc;
char libbuf[256]; // Added by rdg
// BSD regex implementations don't support the empty regex (which isn't
// allowed in the POSIX grammar), but glibc does. Fake it for BSD.
if (!*regex) {
regex = "()";
cflags |= REG_EXTENDED;
}
if ((rc = regcomp(preg, regex, cflags))) {
regerror(rc, preg, libbuf, sizeof(libbuf));
error_exit("bad regex '%s': %s", regex, libbuf);
}
}
// Do regex matching with len argument to handle embedded NUL bytes in string
static int regexec0(regex_t *preg, char *string, long len, int nmatch,
regmatch_t *pmatch, int eflags)
{
// Copied from Rob Landley's toybox
// Copyright 2006 Rob Landley <[email protected]>
// License: 0BSD
regmatch_t backup;
if (!nmatch) pmatch = &backup;
pmatch->rm_so = 0;
pmatch->rm_eo = len;
return regexec(preg, string, nmatch, pmatch, eflags|REG_STARTEND);
}
// Convert wc to utf8, returning bytes written. Does not null terminate.
static int wctoutf8(char *s, unsigned wc)
{
// Copied from Rob Landley's toybox
// Copyright 2006 Rob Landley <[email protected]>
// License: 0BSD
int len = (wc>0x7ff)+(wc>0xffff), i;
if (wc<128) {
*s = wc;
return 1;
} else {
i = len;
do {
s[1+i] = 0x80+(wc&0x3f);
wc >>= 6;
} while (i--);
*s = (((signed char) 0x80) >> (len+1)) | wc;
}
return 2+len;
}
// Convert utf8 sequence to a unicode wide character
// returns bytes consumed, or -1 if err, or -2 if need more data.
static int utf8towc(unsigned *wc, char *str, unsigned len)
{
// Copied from Rob Landley's toybox
// Copyright 2006 Rob Landley <[email protected]>
// License: 0BSD
unsigned result, mask, first;
char *s, c;
// fast path ASCII
if (len && *str<128) return !!(*wc = *str);
result = first = *(s = str++);
if (result<0xc2 || result>0xf4) return -1;
for (mask = 6; (first&0xc0)==0xc0; mask += 5, first <<= 1) {
if (!--len) return -2;
if (((c = *(str++))&0xc0) != 0x80) return -1;
result = (result<<6)|(c&0x3f);
}
result &= (1<<mask)-1;
c = str-s;
// Avoid overlong encodings
if (result<(unsigned []){0x80,0x800,0x10000}[c-2]) return -1;
// Limit unicode so it can't encode anything UTF-16 can't.
if (result>0x10ffff || (result>=0xd800 && result<=0xdfff)) return -1;
*wc = result;
return str-s;
}
static void *xmalloc(size_t size)
{
void *p = malloc(size);
if (!p) error_exit("xmalloc(%d)", size);
return p;
}
static void *xrealloc(void *p, size_t size)
{
p = realloc(p, size);
if (!p) error_exit("xrealloc(%d)", size);
return p;
}
static void *xzalloc(size_t size)
{
void *p = calloc(1, size);
if (!p) error_exit("xzalloc(%d)", size);
return p;
}
static char *xstrdup(char *s)
{
size_t n = strlen(s) + 1;
char *p = xmalloc(n);
memmove(p, s, n);
return p;
}
#endif // FOR_TOYBOX
static int hexval(int c)
{
// Assumes c is valid hex digit
return isdigit(c) ? c - '0' : (c | 040) - 'a' + 10;
}
////////////////////
//// common defs
////////////////////
#ifndef FOR_TOYBOX
// Global data
static struct global_data TT;
static struct optflags optflags;
#endif // FOR_TOYBOX
// These (ops, keywords, builtins) must align with enum tokens
static char *ops = " ; , [ ] ( ) { } $ ++ -- ^ ! * / % + - .. "
"< <= != == > >= ~ !~ && || ? : ^= %= *= /= += -= = >> | ";
static char *keywords = " in BEGIN END if else "
"while for do break continue exit function "
"return next nextfile delete print printf getline ";
static char *builtins = " atan2 cos sin exp log "
"sqrt int rand srand length "
"tolower toupper system fflush "
"and or xor lshift rshift "
"close index match split "
"sub gsub sprintf substr ";
static void zzerr(char *format, ...)
{
va_list args;
int fatal_sw = 0;
fprintf(stderr, "%s: ", TT.progname);
if (format[0] == '$') {
fprintf(stderr, "FATAL: ");
format++;
fatal_sw = 1;
}
fprintf(stderr, "file %s line %d: ", TT.scs->filename, TT.scs->line_num);
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
if (format[strlen(format)-1] != '\n') fputc('\n', stderr); // TEMP FIXME !!!
fflush(stderr);
if (fatal_sw) awk_exit(2);
// Don't bump error count for warnings
else if (!strstr(format, "arning")) TT.cgl.compile_error_count++;
}
static void get_token_text(char *op, int tk)
{
// This MUST ? be changed if ops string or tk... assignments change!
memmove(op, ops + 3 * (tk - tksemi) + 1, 2);
op[ op[1] == ' ' ? 1 : 2 ] = 0;
}
////////////////////
/// UTF-8
////////////////////
// Return number of bytes in 'cnt' utf8 codepoints
static int bytesinutf8(char *str, size_t len, size_t cnt)
{
if (FLAG(b)) return cnt;
unsigned wch;
char *lim = str + len, *s0 = str;
while (cnt-- && str < lim) {
int r = utf8towc(&wch, str, lim - str);
str += r > 0 ? r : 1;
}
return str - s0;
}
// Return number of utf8 codepoints in str
static int utf8cnt(char *str, size_t len)
{
unsigned wch;
int cnt = 0;
char *lim;
if (!len || FLAG(b)) return len;
for (lim = str + len; str < lim; cnt++) {
int r = utf8towc(&wch, str, lim - str);
str += r > 0 ? r : 1;
}
return cnt;
}
////////////////////
//// zlist
////////////////////
static struct zlist *zlist_initx(struct zlist *p, size_t size, size_t count)
{
p->base = p->avail = xzalloc(count * size);
p->limit = p->base + size * count;
p->size = size;
return p;
}
static struct zlist *zlist_init(struct zlist *p, size_t size)
{
#define SLIST_MAX_INIT_BYTES 128
return zlist_initx(p, size, SLIST_MAX_INIT_BYTES / size);
}
// This is called from zlist_append() and add_stack() in run
static void zlist_expand(struct zlist *p)
{
size_t offset = p->avail - p->base;
size_t cap = p->limit - p->base;
size_t newcap = maxof(cap + p->size, ((cap / p->size) * 3 / 2) * p->size);
if (newcap <= cap) error_exit("mem req error");
char *base = xrealloc(p->base, newcap);
p->base = base;
p->limit = base + newcap;
p->avail = base + offset;
}
static size_t zlist_append(struct zlist *p, void *obj)
{
// Insert obj (p->size bytes) at end of list, expand as needed.
// Return scaled offset to newly inserted obj; i.e. the
// "slot number" 0, 1, 2,...
void *objtemp = 0;
if (p->avail > p->limit - p->size) {
objtemp = xmalloc(p->size); // Copy obj in case it is in
memmove(objtemp, obj, p->size); // the area realloc might free!
obj = objtemp;
zlist_expand(p);
}
memmove(p->avail, obj, p->size);
if (objtemp) xfree(objtemp);
p->avail += p->size;
return (p->avail - p->base - p->size) / p->size; // offset of updated slot
}
static int zlist_len(struct zlist *p)
{
return (p->avail - p->base) / p->size;
}
////////////////////
//// zstring
////////////////////
static void zstring_release(struct zstring **s)
{
if (*s && (**s).refcnt-- == 0) xfree(*s); //free_zstring(s);
*s = 0;
}
static void zstring_incr_refcnt(struct zstring *s)
{
if (s) s->refcnt++;
}
// !! Use only if 'to' is NULL or its refcnt is 0.
static struct zstring *zstring_modify(struct zstring *to, size_t at, char *s, size_t n)
{
size_t cap = at + n + 1;
if (!to || to->capacity < cap) {
to = xrealloc(to, sizeof(*to) + cap);
to->capacity = cap;
to->refcnt = 0;
}
memcpy(to->str + at, s, n);
to->size = at + n;
to->str[to->size] = '\0';
return to;
}
// The 'to' pointer may move by realloc, so return (maybe updated) pointer.
// If refcnt is nonzero then there is another pointer to this zstring,
// so copy this one and release it. If refcnt is zero we can mutate this.
static struct zstring *zstring_update(struct zstring *to, size_t at, char *s, size_t n)
{
if (to && to->refcnt) {
struct zstring *to_before = to;
to = zstring_modify(0, 0, to->str, to->size);
zstring_release(&to_before);
}
return zstring_modify(to, at, s, n);
}
static struct zstring *zstring_copy(struct zstring *to, struct zstring *from)
{
return zstring_update(to, 0, from->str, from->size);
}
static struct zstring *zstring_extend(struct zstring *to, struct zstring *from)
{
return zstring_update(to, to->size, from->str, from->size);
}
static struct zstring *new_zstring(char *s, size_t size)
{
return zstring_modify(0, 0, s, size);
}
////////////////////
//// zvalue
////////////////////
static struct zvalue uninit_zvalue = ZVINIT(0, 0.0, 0);
// This will be reassigned in init_globals() with an empty string.
// It's a special value used for "uninitialized" field vars
// referenced past $NF. See push_field().
static struct zvalue uninit_string_zvalue = ZVINIT(0, 0.0, 0);
static struct zvalue new_str_val(char *s)
{
// Only if no nul inside string!
struct zvalue v = ZVINIT(ZF_STR, 0.0, new_zstring(s, strlen(s)));
return v;
}
static void zvalue_release_zstring(struct zvalue *v)
{
if (v && ! (v->flags & (ZF_ANYMAP | ZF_RX))) zstring_release(&v->vst);
}
// push_val() is used for initializing globals (see init_compiler())
// but mostly used in runtime
// WARNING: push_val may change location of v, so do NOT depend on it after!
// Note the incr refcnt used to be after the zlist_append, but that caused a
// heap-use-after-free error when the zlist_append relocated the zvalue being
// pushed, invalidating the v pointer.
static void push_val(struct zvalue *v)
{
if (IS_STR(v) && v->vst) v->vst->refcnt++; // inlined zstring_incr_refcnt()
*++TT.stackp = *v;
}
static void zvalue_copy(struct zvalue *to, struct zvalue *from)
{
if (IS_RX(from)) *to = *from;
else {
zvalue_release_zstring(to);
*to = *from;
zstring_incr_refcnt(to->vst);
}
}
static void zvalue_dup_zstring(struct zvalue *v)
{
struct zstring *z = new_zstring(v->vst->str, v->vst->size);
zstring_release(&v->vst);
v->vst = z;
}
////////////////////
//// zmap (array) implementation
////////////////////
static int zstring_match(struct zstring *a, struct zstring *b)
{
return a->size == b->size && memcmp(a->str, b->str, a->size) == 0;
}
static int zstring_hash(struct zstring *s)
{ // djb2 -- small, fast, good enough for this
unsigned h = 5381;
char *p = s->str, *lim = p + s->size;
while (p < lim)
h = (h << 5) + h + *p++;
return h;
}
enum { PSHIFT = 5 }; // "perturb" shift -- see find_mapslot() below
static struct zmap_slot *find_mapslot(struct zmap *m, struct zstring *key, int *hash, int *probe)
{
struct zmap_slot *x = 0;
unsigned perturb = *hash = zstring_hash(key);
*probe = *hash & m->mask;
int n, first_deleted = -1;
while ((n = m->hash[*probe])) {
if (n > 0) {
x = &MAPSLOT[n-1];
if (*hash == x->hash && zstring_match(key, x->key)) {
return x;
}
} else if (first_deleted < 0) first_deleted = *probe;
// Based on technique in Python dict implementation. Comment there
// (https://github.com/python/cpython/blob/3.10/Objects/dictobject.c)
// says
//
// j = ((5*j) + 1) mod 2**i
// For any initial j in range(2**i), repeating that 2**i times generates
// each int in range(2**i) exactly once (see any text on random-number
// generation for proof).
//
// The addition of 'perturb' greatly improves the probe sequence. See
// the Python dict implementation for more details.
*probe = (*probe * 5 + 1 + (perturb >>= PSHIFT)) & m->mask;
}
if (first_deleted >= 0) *probe = first_deleted;
return 0;
}
static struct zvalue *zmap_find(struct zmap *m, struct zstring *key)
{
int hash, probe;
struct zmap_slot *x = find_mapslot(m, key, &hash, &probe);
return x ? &x->val : 0;
}
static void zmap_init(struct zmap *m)
{
enum {INIT_SIZE = 8};
m->mask = INIT_SIZE - 1;
m->hash = xzalloc(INIT_SIZE * sizeof(*m->hash));
m->limit = INIT_SIZE * 8 / 10;
m->count = 0;
m->deleted = 0;
zlist_init(&m->slot, sizeof(struct zmap_slot));
}
static void zvalue_map_init(struct zvalue *v)
{
struct zmap *m = xmalloc(sizeof(*m));
zmap_init(m);
v->map = m;
v->flags |= ZF_MAP;
}
static void zmap_delete_map_incl_slotdata(struct zmap *m)
{
for (struct zmap_slot *p = &MAPSLOT[0]; p < &MAPSLOT[zlist_len(&m->slot)]; p++) {
if (p->key) zstring_release(&p->key);
if (p->val.vst) zstring_release(&p->val.vst);
}
xfree(m->slot.base);
xfree(m->hash);
}
static void zmap_delete_map(struct zmap *m)
{
zmap_delete_map_incl_slotdata(m);
zmap_init(m);
}
static void zmap_rehash(struct zmap *m)
{
// New table is twice the size of old.
int size = m->mask + 1;
unsigned mask = 2 * size - 1;
int *h = xzalloc(2 * size * sizeof(*m->hash));
// Step through the old hash table, set up location in new table.
for (int i = 0; i < size; i++) {
int n = m->hash[i];
if (n > 0) {
int hash = MAPSLOT[n-1].hash;
unsigned perturb = hash;
int p = hash & mask;
while (h[p]) {
p = (p * 5 + 1 + (perturb >>= PSHIFT)) & mask;
}
h[p] = n;
}
}
m->mask = mask;
xfree(m->hash);
m->hash = h;
m->limit = 2 * size * 8 / 10;
}
static struct zmap_slot *zmap_find_or_insert_key(struct zmap *m, struct zstring *key)
{
int hash, probe;
struct zmap_slot *x = find_mapslot(m, key, &hash, &probe);
if (x) return x;
// not found; insert it.
if (m->count == m->limit) {
zmap_rehash(m); // rehash if getting too full.
// rerun find_mapslot to get new probe index
x = find_mapslot(m, key, &hash, &probe);
}
// Assign key to new slot entry and bump refcnt.
struct zmap_slot zs = ZMSLOTINIT(hash, key, (struct zvalue)ZVINIT(0, 0.0, 0));
zstring_incr_refcnt(key);
int n = zlist_append(&m->slot, &zs);
m->count++;
m->hash[probe] = n + 1;
return &MAPSLOT[n];
}
static void zmap_delete(struct zmap *m, struct zstring *key)
{
int hash, probe;
struct zmap_slot *x = find_mapslot(m, key, &hash, &probe);
if (!x) return;
zstring_release(&MAPSLOT[m->hash[probe] - 1].key);
m->hash[probe] = -1;
m->deleted++;
}
////////////////////
//// scan (lexical analyzer)
////////////////////
// TODO:
// IS line_num getting incr correctly? Newline counts as start of line!?
// Handle nuls in file better.
// Open files "rb" and handle CRs in program.
// Roll gch() into get_char() ?
// Deal with signed char (at EOF? elsewhere?)
//
// 2023-01-11: Allow nul bytes inside strings? regexes?
static void progfile_open(void)
{
TT.scs->filename = TT.scs->prog_args->arg;
TT.scs->prog_args = TT.scs->prog_args->next;
TT.scs->fp = stdin;
if (strcmp(TT.scs->filename, "-")) TT.scs->fp = fopen(TT.scs->filename, "r");
if (!TT.scs->fp) error_exit("Can't open %s", TT.scs->filename);
TT.scs->line_num = 0;
}
static int get_char(void)
{
static char *nl = "\n";
// On first entry, TT.scs->p points to progstring if any, or null string.
for (;;) {
int c = *(TT.scs->p)++;
if (c) {
return c;
}
if (TT.scs->progstring) { // Fake newline at end of progstring.
if (TT.scs->progstring == nl) return EOF;
TT.scs->p = TT.scs->progstring = nl;
continue;
}
// Here if getting from progfile(s).
if (TT.scs->line == nl) return EOF;
if (!TT.scs->fp) {
progfile_open();
}
// Save last char to allow faking final newline.
int lastchar = (TT.scs->p)[-2];
TT.scs->line_len = getline(&TT.scs->line, &TT.scs->line_size, TT.scs->fp);
if (TT.scs->line_len > 0) {
TT.scs->line_num++;
TT.scs->p = TT.scs->line;
continue;
}
// EOF
// FIXME TODO or check for error? feof() vs. ferror()
fclose(TT.scs->fp);
TT.scs->fp = 0;
TT.scs->p = &(" "[2]); // Quiet clang warning on " " + 2;
if (!TT.scs->prog_args) {
xfree(TT.scs->line);
if (lastchar == '\n') return EOF;
// Fake final newline
TT.scs->line = TT.scs->p = nl;
}
}
}
static void append_this_char(int c)
{
if (TT.scs->toklen == TT.scs->maxtok - 1) {
TT.scs->maxtok *= 2;
TT.scs->tokstr = xrealloc(TT.scs->tokstr, TT.scs->maxtok);
}
TT.scs->tokstr[TT.scs->toklen++] = c;
TT.scs->tokstr[TT.scs->toklen] = 0;
}
static void gch(void)
{
// FIXME probably not right place to skip CRs.
do {
TT.scs->ch = get_char();
} while (TT.scs->ch == '\r');
}
static void append_char(void)
{
append_this_char(TT.scs->ch);
gch();
}
static int find_keyword_or_builtin(char *table,
int first_tok_in_table)
{
char s[16] = " ", *p;
// keywords and builtin functions are spaced 10 apart for strstr() lookup,
// so must be less than that long.
if (TT.scs->toklen >= 10) return 0;
strcat(s, TT.scs->tokstr);
strcat(s, " ");
p = strstr(table, s);
if (!p) return 0;
return first_tok_in_table + (p - table) / 10;