-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpre.c
More file actions
1823 lines (1638 loc) · 62.5 KB
/
pre.c
File metadata and controls
1823 lines (1638 loc) · 62.5 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
#include <time.h>
#include "global.c"
#include "lexer.c"
#ifdef __SSE2__
#include <immintrin.h>
#endif
typedef enum {
MACRO_NOT_SPECIAL = 0,
MACRO_defined,
MACRO_FILE,
MACRO_LINE,
MACRO_DATE,
MACRO_TIME,
MACRO_COUNTER,
MACRO_INCLUDE_LEVEL,
MACRO_BASE_FILE,
MACRO_FILE_NAME,
MACRO_TIMESTAMP,
MACRO_has_include,
MACRO_has_include_next,
MACRO_COUNT
} SpecialMacro;
typedef struct {
char * key;
Token * replace_list;
char ** arg_list;
FileInfo * file;
size_t file_offset;
int32_t arg_count;
SpecialMacro special;
bool is_defined;
bool func_like;
bool variadic;
bool forced;
} Define;
typedef struct {
int * macro_index_stack;
Token * list;
TokenIndex * tidx;
char * last_macro_name;
bool in_expression;
} ExpandContext;
typedef struct {
Token * result_list;
FileInfo * current_file;
Define * defines;
const char ** include_paths;
MemArena * arena;
NameSet * dependency_set;
ExprContext * expr_ctx;
ExpandContext expand_ctx;
char * expansion_site;
LocationContext loc;
const Config * cfg;
NoticeState * notice_stack;
NoticeState notice;
const char * base_file;
int counter;
int include_level;
int sys_header_first;
int sys_header_last;
bool is_sys_header;
bool minimal_parse;
bool preprocess_only;
} PreContext;
typedef struct {
PreContext * ctx;
FileInfo * chunk_file;
int32_t begin_chunk;
NoticeState notice;
} PasteState;
#define BOLD_RED "\e[1;31m"
#define BOLD_YELLOW "\e[1;33m"
#define CYAN "\e[0;36m"
#define WHITE "\e[0;37m"
#define BOLD_WHITE "\e[1;37m"
static void
strput_code_segment(char ** p_s, char * segment_start, char * segment_end, char * highlight_start, char * highlight_end, const char * highlight_color) {
strputf(p_s, "\n%.*s", (int)(highlight_start - segment_start), segment_start);
strputf(p_s, "%s%.*s" WHITE, highlight_color, (int)(highlight_end - highlight_start), highlight_start);
strputf(p_s, "%.*s\n", (int)(segment_end - highlight_end), highlight_end);
for (int i=0; i < highlight_start - segment_start; i++) {
if (segment_start[i] == '\t') {
arrput(*p_s, '\t');
} else {
arrput(*p_s, ' ');
}
}
for (int i=0; i < highlight_end - highlight_start; i++) arrput(*p_s, '~');
strputf(p_s, "\n");
}
static int
count_newlines_unaligned(char * start, int count) {
int result = 0;
char * s = start;
while (s < start + count) {
if (*s == '\n') result += 1;
s++;
}
return result;
}
static int
count_newlines_in_range(char * start, char * end, char ** o_last_line) {
#ifdef __SSE2__
char * s = start;
int result = 1;
int count_to_aligned = (16 - ((uintptr_t)s & 15)) & 15;
_assume(end > s);
result += count_newlines_unaligned(s, MIN(count_to_aligned, end - s));
if (s < end) {
while (s+16 < end) {
const __m128i newlines = _mm_set1_epi8('\n');
const __m128i mask = _mm_set1_epi8(1);
__m128i line = _mm_load_si128((void *)s);
__m128i cmp = _mm_cmpeq_epi8(line, newlines);
cmp = _mm_and_si128(cmp, mask);
__m128i vsum = _mm_sad_epu8(cmp, _mm_setzero_si128());
int isum = _mm_cvtsi128_si32(vsum) + _mm_extract_epi16(vsum, 4);
result += isum;
s += 16;
}
_assume(end - s >= 0);
result += count_newlines_unaligned(s, end - s);
}
#else
int result = 1 + count_newlines_unaligned(start, end - start);
#endif
while (end >= start && *--end != '\n');
end++;
*o_last_line = end;
return result;
}
FileInfo *
get_location_info(LocationContext * lctx, int32_t tk_index, NoticeState * o_notice) {
int loc_index = -1;
int max = (lctx->count)? lctx->count : arrlen(lctx->list);
for (int i=lctx->index; i < max; i++) {
FileLoc loc = lctx->list[i];
if (tk_index < loc.offset) {
lctx->index = i;
loc_index = i-1;
break;
} else {
lctx->notice = loc.notice;
if (loc.file) lctx->file = loc.file;
switch(loc.mode) {
case LOC_NONE:
break;
case LOC_FILE:
case LOC_MACRO:
arrput(lctx->stack, i);
break;
case LOC_POP:
assert(arrlen(lctx->stack) > 0);
(void)arrpop(lctx->stack);
int last_stack = lctx->stack[arrlen(lctx->stack) - 1];
lctx->file = lctx->list[last_stack].file;
break;
}
}
}
if (loc_index < 0) return NULL;
char * file_buffer = lctx->file->buffer;
if (!file_buffer) {
fprintf(stderr, "Internal error: failed to find file for error report.");
exit(-1);
}
if (o_notice) *o_notice = lctx->notice;
return lctx->file;
}
static FileInfo *
find_origin(LocationContext * lctx, FileInfo * current, char * ptr) {
int i = arrlen(lctx->file_buffers);
if (i == 0) return NULL;
FileInfo * file = (current)? current : lctx->file_buffers[--i];
while (1) {
if (ptr >= file->buffer && ptr < (file->buffer + file->buffer_size)) {
return file;
}
if (--i >= 0) {
file = lctx->file_buffers[i];
} else {
break;
}
}
return NULL;
}
static void
message_internal(char * start_of_line, const char * filename, int line, char * hl_start, char * hl_end, const char * message, int message_type) {
char * end_of_line = strchr(hl_end, '\n');
if (!end_of_line) {
end_of_line = hl_end;
}
char * s = NULL;
const char * message_type_string = (message_type == 1)? "Warning" : "Error";
const char * color = (message_type == 1)? BOLD_YELLOW : BOLD_RED;
strputf(&s, "%s%s" WHITE " (" CYAN "%s:" BOLD_WHITE "%i" WHITE "): %s\n", color, message_type_string, filename, line, message);
strput_code_segment(&s, start_of_line, end_of_line, hl_start, hl_end, color);
fputs(s, stderr);
//db_break();
arrfree(s);
}
void
parse_msg_internal(LocationContext * lctx, int32_t tk_index, char * message, int message_type) {
Token tk = lctx->tk_list[tk_index];
char * start_of_line = NULL;
FileInfo * file = get_location_info(lctx, tk_index, NULL);
int line_num = count_newlines_in_range(file->buffer, tk.start, &start_of_line);
char * filename = file->filename;
assert(start_of_line != NULL);
char * hl_start = tk.start;
char * hl_end = hl_start + tk.length;
message_internal(start_of_line, filename, line_num, hl_start, hl_end, message, message_type);
for (int i=arrlen(lctx->stack) - 1; i >= 0; i--) {
FileLoc l = lctx->list[lctx->stack[i]];
if (l.mode == LOC_FILE) {
fprintf(stderr, "In file: '%s'\n", l.file->filename);
} else if (l.mode == LOC_MACRO) {
hl_start = l.file->buffer + l.file_offset;
hl_end = hl_start + strlen(l.macro_name);
line_num = count_newlines_in_range(l.file->buffer, hl_start, &start_of_line);
message_internal(start_of_line, filename, line_num, hl_start, hl_end, "In expansion", message_type);
}
}
}
static void
preprocess_message_internal(LocationContext * lctx, const Token * tk, char * message, int msg_type) {
FileInfo * file = find_origin(lctx, lctx->file, tk->start);
int line_num = 0;
char * start_of_line = tk->start;
char * filename = "__GENERATED__";
if (file) {
line_num = count_newlines_in_range(file->buffer, tk->start, &start_of_line);
filename = file->filename;
}
message_internal(start_of_line, filename, line_num, tk->start, tk->start + tk->length, message, msg_type);
}
#define preprocess_error(tk, message) preprocess_message_internal(&ctx->loc, tk, message, 0)
#define preprocess_warning(tk, message) preprocess_message_internal(&ctx->loc, tk, message, 1)
void
location_note(LocationContext * lctx, IntroLocation location, const char * msg) {
FileInfo * file = NULL;
for (int i=0; i < lctx->count; i++) {
FileInfo * f = lctx->file_buffers[i];
if (0==strcmp(f->filename, location.path)) {
file = f;
break;
}
}
if (file == NULL) {
fprintf(stderr, "Could not find location for note.\n");
return;
}
char * s = file->buffer + location.offset;
char * start_of_line;
int line = count_newlines_in_range(file->buffer, s, &start_of_line);
Token tk = pre_next_token(&s);
message_internal(start_of_line, location.path, line, tk.start, tk.start + tk.length, msg, 1);
}
void
strput_tokens(char ** p_str, Token * list) {
for (int i=0; i < arrlen(list); i++) {
Token tk = list[i];
if (tk.preceding_space) {
arrput(*p_str, ' ');
}
char * dst = arraddnptr(*p_str, tk.length);
memcpy(dst, tk.start, tk.length);
}
arrsetcap(*p_str, arrlen(*p_str) + 1);
(*p_str)[arrlen(*p_str)] = 0;
}
static Token
create_stringized(PreContext * ctx, Token * list) {
char * buf = NULL;
arrput(buf, '"');
for (int i=0; i < arrlen(list); i++) {
Token tk = list[i];
if (tk.preceding_space && i > 0) {
arrput(buf, ' ');
}
if (tk.type == TK_STRING) {
for (char * s = tk.start; s < tk.start + tk.length; s++) {
if (*s == '"' || *s == '\\') {
arrput(buf, '\\');
}
arrput(buf, *s);
}
continue;
}
strputf(&buf, "%.*s", tk.length, tk.start);
}
strputf(&buf, "\"");
char * str = copy_and_terminate(ctx->arena, buf, arrlen(buf));
Token result = {
.start = str,
.length = arrlen(buf),
.type = TK_STRING,
};
arrfree(buf);
return result;
}
static void
ignore_section(PasteState * state, int32_t begin_ignored, int32_t end_ignored) {
PreContext * ctx = state->ctx;
if (state->begin_chunk != -1) {
ptrdiff_t signed_file_offset = state->chunk_file->tk_list[state->begin_chunk].start - state->chunk_file->buffer;
_assume(signed_file_offset >= 0);
FileLoc loc = {
.offset = arrlen(ctx->result_list),
.file_offset = (size_t)signed_file_offset,
.notice = state->notice,
};
FileLoc * plast = &arrlast(ctx->loc.list);
if ((loc.offset == plast->offset) && (plast->mode == LOC_NONE)) {
*plast = loc;
} else {
arrput(ctx->loc.list, loc);
}
// paste chunk
int len_chunk = begin_ignored - state->begin_chunk;
if (len_chunk > 0) {
if (!state->ctx->preprocess_only) {
for (int i=0; i < len_chunk; i++) {
Token tk = state->chunk_file->tk_list[state->begin_chunk + i];
if (tk.type != TK_NEWLINE && tk.type != TK_COMMENT) {
arrput(ctx->result_list, tk);
}
}
} else {
Token last_tk = {0};
for (int i=0; i < len_chunk; i++) {
Token tk = state->chunk_file->tk_list[state->begin_chunk + i];
if (tk.type != TK_COMMENT) {
if (tk.type == TK_IDENTIFIER && last_tk.type == TK_IDENTIFIER) {
tk.preceding_space = true;
}
arrput(ctx->result_list, tk);
last_tk = tk;
}
}
}
}
}
state->begin_chunk = end_ignored;
state->chunk_file = ctx->current_file;
state->notice = ctx->notice;
}
void
tk_cat(Token ** p_list, const Token * ext, bool space) {
Token * dest = arraddnptr(*p_list, arrlen(ext));
for (int i=0; i < arrlen(ext); i++) {
dest[i] = ext[i];
}
dest[0].preceding_space = space;
}
typedef struct {
Token tk;
char * name;
bool exists;
bool is_quote;
bool is_next;
bool test_only;
} IncludeFile;
bool
pre_get_include_path(PreContext * ctx, const char * file_dir, IncludeFile inc_file, char * o_path) {
int start_search_index = 0;
if (inc_file.is_next) {
for (int i=0; i < arrlen(ctx->include_paths); i++) {
const char * include_path = ctx->include_paths[i];
if (0==strcmp(file_dir, include_path)) {
start_search_index = i + 1;
break;
}
}
} else {
if (inc_file.is_quote) {
path_join(o_path, file_dir, inc_file.name);
if (access(o_path, F_OK) == 0) {
ctx->is_sys_header = false;
return true;
}
}
}
for (int i = start_search_index; i < arrlen(ctx->include_paths); i++) {
const char * include_path = ctx->include_paths[i];
path_join(o_path, include_path, inc_file.name);
if (access(o_path, F_OK) == 0) {
if (!inc_file.test_only) {
ctx->is_sys_header = (i >= ctx->sys_header_first && i <= ctx->sys_header_last);
}
return true;
}
}
return false;
}
static bool macro_scan(PreContext * ctx, int macro_tk_index);
static Token
internal_macro_next_token(PreContext * ctx, int * o_index) {
++(*o_index);
if (*o_index < arrlen(ctx->expand_ctx.list)) {
return ctx->expand_ctx.list[*o_index];
} else {
Token tk;
if (!ctx->expand_ctx.tidx) {
tk = (Token){.type = TK_END};
arrput(ctx->expand_ctx.list, tk);
return tk;
}
do {
tk = next_token(ctx->expand_ctx.tidx);
} while (tk.type == TK_COMMENT || tk.type == TK_NEWLINE);
arrput(ctx->expand_ctx.list, tk);
return tk;
}
}
typedef struct {
Token ** unexpanded_list;
Token ** expanded_list;
int count_tokens;
bool complete;
} MacroArgs;
MacroArgs
get_macro_arguments(PreContext * ctx, int macro_tk_index) {
MacroArgs result = {0};
int i = macro_tk_index;
int32_t prev_index = 0;
if (ctx->expand_ctx.tidx) prev_index = ctx->expand_ctx.tidx->index;
int prev_len_list = arrlen(ctx->expand_ctx.list);
Token l_paren = internal_macro_next_token(ctx, &i);
if (l_paren.type == TK_END || *l_paren.start != '(') {
arrsetlen(ctx->expand_ctx.list, prev_len_list);
if (ctx->expand_ctx.tidx) ctx->expand_ctx.tidx->index = prev_index;
return result;
}
int paren_level = 1;
int count_tokens = 1;
Token ** arg_list = NULL;
Token * arg_tks = NULL;
while (1) {
Token tk = internal_macro_next_token(ctx, &i);
if (tk.type == TK_END) {
preprocess_error(&l_paren, "No closing ')'.");
exit(1);
}
count_tokens += 1;
if (paren_level == 1 && tk.type == TK_COMMA) {
arrput(arg_list, arg_tks);
arg_tks = NULL;
continue;
}
if (tk.type == TK_L_PARENTHESIS) {
paren_level += 1;
} else if (tk.type == TK_R_PARENTHESIS) {
paren_level -= 1;
if (paren_level == 0) {
arrput(arg_list, arg_tks);
break;
}
}
arrput(arg_tks, tk);
}
arg_tks = NULL;
Token ** unexpanded_list = NULL;
arrsetcap(unexpanded_list, arrlen(arg_list));
for (int arg_i=0; arg_i < arrlen(arg_list); arg_i++) {
Token * tks = NULL;
if (arrlen(arg_list[arg_i]) > 0) {
arraddnptr(tks, arrlen(arg_list[arg_i]));
memcpy(tks, arg_list[arg_i], arrlen(arg_list[arg_i]) * sizeof(*arg_list[arg_i]));
}
arrput(unexpanded_list, tks);
}
ExpandContext prev_ctx = ctx->expand_ctx;
for (int arg_i=0; arg_i < arrlen(arg_list); arg_i++) {
for (int tk_i=0; tk_i < arrlen(arg_list[arg_i]); tk_i++) {
if (arg_list[arg_i][tk_i].type == TK_IDENTIFIER) {
ctx->expand_ctx = (ExpandContext){
.macro_index_stack = ctx->expand_ctx.macro_index_stack,
.list = arg_list[arg_i],
.tidx = ctx->expand_ctx.tidx,
};
macro_scan(ctx, tk_i);
arg_list[arg_i] = ctx->expand_ctx.list;
}
}
}
prev_ctx.macro_index_stack = ctx->expand_ctx.macro_index_stack;
ctx->expand_ctx = prev_ctx;
result.unexpanded_list = unexpanded_list;
result.expanded_list = arg_list;
result.count_tokens = count_tokens;
result.complete = true;
return result;
}
static void
free_macro_arguments(MacroArgs margs) {
for (int i=0; i < arrlen(margs.unexpanded_list); i++) {
arrfree(margs.unexpanded_list[i]);
}
arrfree(margs.unexpanded_list);
for (int i=0; i < arrlen(margs.expanded_list); i++) {
arrfree(margs.expanded_list[i]);
}
arrfree(margs.expanded_list);
}
static bool // true if token was expanded
macro_scan(PreContext * ctx, int macro_tk_index) {
Token * macro_tk = &ctx->expand_ctx.list[macro_tk_index];
char temp [1024];
TERMINATE(temp, macro_tk->start, macro_tk->length);
ptrdiff_t macro_index = shgeti(ctx->defines, temp);
if (macro_index < 0) {
return false;
}
Define * macro = &ctx->defines[macro_index];
if (!macro->is_defined) return false;
if (macro->special != MACRO_NOT_SPECIAL) {
char * buf = NULL;
int token_type = TK_STRING;
switch(macro->special) {
case MACRO_NOT_SPECIAL: _assume(0);
case MACRO_defined: {
if (!ctx->expand_ctx.in_expression) {
return false;
}
bool preceding_space = macro_tk->preceding_space;
int index = macro_tk_index;
Token tk = internal_macro_next_token(ctx, &index);
bool is_paren = false;
if (tk.type == TK_L_PARENTHESIS) {
is_paren = true;
tk = internal_macro_next_token(ctx, &index);
}
if (tk.type != TK_IDENTIFIER) {
preprocess_error(&tk, "Expected identifier.");
exit(1);
}
TERMINATE(temp, tk.start, tk.length);
Define def = shgets(ctx->defines, temp);
char * replace = (def.is_defined)? "1" : "0";
if (is_paren) {
tk = internal_macro_next_token(ctx, &index);
if (tk.type != TK_R_PARENTHESIS) {
preprocess_error(&tk, "Expected ')'.");
exit(1);
}
}
Token replace_tk = (Token){
.start = replace,
.length = 1,
.type = TK_NUMBER,
.preceding_space = preceding_space,
};
arrdeln(ctx->expand_ctx.list, macro_tk_index, index - macro_tk_index);
ctx->expand_ctx.list[macro_tk_index] = replace_tk;
return true;
}break;
case MACRO_FILE: {
strputf(&buf, "\"%s\"", ctx->current_file->filename);
}break;
case MACRO_LINE: {
const FileInfo * current_file = find_origin(&ctx->loc, ctx->loc.file, ctx->expansion_site);
int line_num = 0;
if (current_file) {
char * start_of_line_;
line_num = count_newlines_in_range(current_file->buffer, ctx->expansion_site, &start_of_line_);
}
strputf(&buf, "%i", line_num);
token_type = TK_NUMBER;
}break;
case MACRO_DATE: {
char static_buf [12];
time_t time_value;
struct tm * date;
time(&time_value);
date = localtime(&time_value);
strftime(static_buf, sizeof(static_buf), "%b %d %Y", date);
strputf(&buf, "\"%s\"", static_buf);
}break;
case MACRO_TIME: {
char static_buf [9];
time_t time_value;
struct tm * date;
time(&time_value);
date = localtime(&time_value);
strftime(static_buf, sizeof(static_buf), "%H:%M:%S", date);
strputf(&buf, "\"%s\"", static_buf);
}break;
case MACRO_COUNTER: {
strputf(&buf, "%i", ctx->counter++);
token_type = TK_IDENTIFIER;
}break;
case MACRO_INCLUDE_LEVEL: {
strputf(&buf, "%i", ctx->include_level);
token_type = TK_IDENTIFIER;
}break;
case MACRO_BASE_FILE: {
strputf(&buf, "\"%s\"", ctx->base_file);
}break;
case MACRO_FILE_NAME: {
char static_buf_ [1024];
char * filename = NULL;
path_dir(static_buf_, ctx->current_file->filename, &filename);
strputf(&buf, "\"%s\"", filename);
}break;
case MACRO_TIMESTAMP: {
char static_buf [256];
struct tm * date;
date = localtime(&ctx->current_file->mtime);
strftime(static_buf, sizeof(static_buf), "%a %b %d %H:%M:%S %Y", date);
strputf(&buf, "\"%s\"", static_buf);
}break;
case MACRO_COUNT: {
preprocess_warning(macro_tk, "sus");
return false;
}break;
case MACRO_has_include_next:
case MACRO_has_include: {
if (!ctx->expand_ctx.in_expression) {
return false;
}
IncludeFile inc_file = {0};
inc_file.is_next = (macro->special == MACRO_has_include_next);
inc_file.test_only = true;
bool preceding_space = macro_tk->preceding_space;
int index = macro_tk_index;
Token tk = internal_macro_next_token(ctx, &index);
bool is_paren = false;
if (tk.type == TK_L_PARENTHESIS) {
is_paren = true;
tk = internal_macro_next_token(ctx, &index);
}
const char * start;
const char * end;
if (tk.type == TK_STRING) {
start = tk.start + 1;
end = tk.start + tk.length - 1;
inc_file.is_quote = true;
} else if (tk.type == TK_L_ANGLE) {
start = tk.start + 1;
Token opening = tk;
while (1) {
tk = internal_macro_next_token(ctx, &index);
if (tk.type == TK_R_ANGLE) {
break;
}
if (tk.type == TK_END) {
preprocess_error(&opening, "No closing '>'.");
exit(1);
}
}
end = tk.start;
} else {
preprocess_error(&tk, "Expected include file.");
exit(1);
}
char inc_filename [1024];
char file_dir [1024];
char _static_buf [1024];
char * _filename;
TERMINATE(inc_filename, start, end - start);
inc_file.name = inc_filename;
path_dir(file_dir, ctx->current_file->filename, &_filename);
bool found_file = pre_get_include_path(ctx, file_dir, inc_file, _static_buf);
char * replace = (found_file)? "1" : "0";
if (is_paren) {
tk = internal_macro_next_token(ctx, &index);
if (tk.type != TK_R_PARENTHESIS) {
preprocess_error(&tk, "Expected ')'.");
exit(1);
}
}
Token replace_tk = (Token){
.start = replace,
.length = 1,
.type = TK_NUMBER,
.preceding_space = preceding_space,
};
arrdeln(ctx->expand_ctx.list, macro_tk_index, index - macro_tk_index);
ctx->expand_ctx.list[macro_tk_index] = replace_tk;
return true;
}break;
}
Token replace_tk = {
.start = copy_and_terminate(ctx->arena, buf, arrlen(buf)),
.length = arrlen(buf),
.type = token_type,
.preceding_space = macro_tk->preceding_space,
};
arrfree(buf);
ctx->expand_ctx.list[macro_tk_index] = replace_tk;
return true;
}
for (int i=0; i < arrlen(ctx->expand_ctx.macro_index_stack); i++) {
if (macro_index == ctx->expand_ctx.macro_index_stack[i]) {
macro_tk->type = TK_DISABLED;
return false;
}
}
Token * replace_list = NULL;
bool free_replace_list = false;
int count_arg_tokens = 0;
bool preceding_space = (macro_tk_index == 0)? false : macro_tk->preceding_space;
macro_tk = NULL; // following code will make this invalid
if (macro->func_like) {
Token * list = NULL;
MacroArgs margs = get_macro_arguments(ctx, macro_tk_index);
if (!margs.complete) {
return false;
}
count_arg_tokens = margs.count_tokens;
Token ltk = {.start = ""};
for (int tk_i=0; tk_i < arrlen(macro->replace_list); tk_i++) {
Token tk = macro->replace_list[tk_i];
bool replaced = false;
if (tk.type == TK_IDENTIFIER) {
if (macro->variadic && tk_equal(&tk, "__VA_ARGS__")) {
for (int arg_i=macro->arg_count; arg_i < arrlen(margs.expanded_list); arg_i++) {
tk_cat(&list, margs.expanded_list[arg_i], tk.preceding_space);
static const Token comma = {.start = ",", .length = 1};
if (arg_i != arrlen(margs.expanded_list) - 1) arrput(list, comma);
}
replaced = true;
}
for (int param_i=0; param_i < macro->arg_count; param_i++) {
if (tk_equal(&tk, macro->arg_list[param_i])) {
if (ltk.type == TK_HASH) {
Token stringized = create_stringized(ctx, margs.unexpanded_list[param_i]);
stringized.preceding_space = ltk.preceding_space;
arrput(list, stringized);
} else {
bool part_of_concat = ltk.type == TK_D_HASH || (tk_i+1 < arrlen(macro->replace_list) && macro->replace_list[tk_i+1].type == TK_D_HASH);
if (margs.unexpanded_list[param_i]) {
if (part_of_concat) {
tk_cat(&list, margs.unexpanded_list[param_i], tk.preceding_space);
} else {
tk_cat(&list, margs.expanded_list[param_i], tk.preceding_space);
}
} else {
if (part_of_concat) {
arrput(list, (Token){.type = TK_PLACEHOLDER});
}
}
}
replaced = true;
break;
}
}
}
if (!replaced && !(tk.type == TK_HASH)) {
arrput(list, tk);
}
ltk = tk;
}
replace_list = list;
free_replace_list = true;
free_macro_arguments(margs);
} else {
replace_list = macro->replace_list;
}
// ## concat
for (int i=0; i < arrlen(replace_list); i++) {
Token tk = replace_list[i];
if (tk.type == TK_D_HASH) {
if (!(i > 0 && i+1 < arrlen(replace_list))) {
preprocess_error(&tk, "Invalid concat operator.");
exit(1);
}
Token result = {0};
Token last_tk = replace_list[i-1];
Token next_tk = replace_list[i+1];
if (last_tk.type == TK_PLACEHOLDER && next_tk.type == TK_PLACEHOLDER) {
result.type = TK_PLACEHOLDER;
} else {
char * buf = NULL;
if (last_tk.type != TK_PLACEHOLDER) {
strputf(&buf, "%.*s", last_tk.length, last_tk.start);
}
if (next_tk.type != TK_PLACEHOLDER) {
strputf(&buf, "%.*s", next_tk.length, next_tk.start);
}
result.start = copy_and_terminate(ctx->arena, buf, arrlen(buf));
result.length = arrlen(buf);
result.preceding_space = last_tk.preceding_space;
char * s = result.start;
Token result_eval_tk = pre_next_token(&s);
result.type = result_eval_tk.type;
arrfree(buf);
}
i--;
arrdeln(replace_list, i, MIN(2, arrlen(replace_list) - i));
replace_list[i] = result;
}
}
// insert list
int diff = arrlen(replace_list) - count_arg_tokens - 1;
if (diff > 0) {
arrinsn(ctx->expand_ctx.list, macro_tk_index, diff);
} else {
arrdeln(ctx->expand_ctx.list, macro_tk_index, -diff);
}
for (int i=0; i < arrlen(replace_list); i++) {
ctx->expand_ctx.list[macro_tk_index + i] = replace_list[i];
}
// rescan
int back_offset = macro_tk_index + arrlen(replace_list) - arrlen(ctx->expand_ctx.list);
arrpush(ctx->expand_ctx.macro_index_stack, macro_index);
for (int i=macro_tk_index; i < arrlen(ctx->expand_ctx.list) + back_offset; i++) {
if (ctx->expand_ctx.list[i].type == TK_IDENTIFIER) {
if (macro_scan(ctx, i)) {
i--;
}
}
}
(void)arrpop(ctx->expand_ctx.macro_index_stack);
ctx->expand_ctx.list[macro_tk_index].preceding_space = preceding_space;
ctx->expand_ctx.last_macro_name = macro->key;
if (free_replace_list) arrfree(replace_list);
return true;
}
Token *
expand_line(PreContext * ctx, TokenIndex * tidx, bool is_include) {
Token * ptks = NULL;
arrsetcap(ptks, 16);
ExpandContext prev_ctx = ctx->expand_ctx;
while (1) {
Token ptk = next_token(tidx);
int32_t prev_index = tidx->index - 1;
if (ptk.type == TK_NEWLINE) {
tidx->index = prev_index;
ptk.type = TK_END;
ptk.start -= 1; // highlight last character in errors
arrput(ptks, ptk);
break;
} else if (ptk.type == TK_COMMENT) {
continue;
} else if (is_include && ptk.type == TK_L_ANGLE) {
int32_t closing = find_closing((TokenIndex){.list = tidx->list, .index = prev_index});
if (!closing) {
preprocess_error(&ptk, "No closing '>'.");
exit(1);
}
tidx->index = closing;
ptk.length = tidx->list[tidx->index].start - ptk.start;
ptk.type = TK_STRING;
arrput(ptks, ptk);
} else {
int index = arrlen(ptks);
arrput(ptks, ptk);
if (ptk.type == TK_IDENTIFIER) {
ctx->expand_ctx = (ExpandContext){
.macro_index_stack = NULL,
.list = ptks,
.in_expression = !is_include,
.tidx = tidx,
};
macro_scan(ctx, index);
ptks = ctx->expand_ctx.list;
}
}
}
ctx->expand_ctx = prev_ctx;
return ptks;
}
bool
parse_expression(PreContext * ctx, TokenIndex * tidx) {
Token * tks = expand_line(ctx, tidx, false);
TokenIndex etidx = {.list = tks, .index = 0};
ExprNode * tree = build_expression_tree2(ctx->expr_ctx, &etidx);
if (!tree) {
preprocess_error(&etidx.list[etidx.index - 1], "Problem token.");
exit(1);
}
uint8_t * bytecode = build_expression_procedure2(ctx->expr_ctx, tree, NULL);
intmax_t result = intro_run_bytecode(bytecode, NULL).si;
arrfree(bytecode);
reset_arena(ctx->expr_ctx->arena);
arrfree(tks);
return !!result;
}
static void
pre_skip(PreContext * ctx, TokenIndex * tidx, bool elif_ok) {
int depth = 1;
while (1) {
Token tk = next_token(tidx);
if (tk.length == 1 && tk.start[0] == '#') {
tk = next_token(tidx);
if (tk.type == TK_IDENTIFIER) {
if (tk_equal(&tk, "if")
|| tk_equal(&tk, "ifdef")
|| tk_equal(&tk, "ifndef"))
{
depth++;
} else if (tk_equal(&tk, "endif")) {
depth--;
} else if (tk_equal(&tk, "else")) {
if (elif_ok && depth == 1) {
depth = 0;
}
} else if (tk_equal(&tk, "elif")) {
if (elif_ok && depth == 1) {