-
Notifications
You must be signed in to change notification settings - Fork 29
/
packcc.c
5690 lines (5479 loc) · 213 KB
/
packcc.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
/*
* PackCC: a packrat parser generator for C.
*
* Copyright (c) 2014, 2019-2024 Arihiro Yoshida. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* The algorithm is based on the paper "Packrat Parsers Can Support Left Recursion"
* authored by A. Warth, J. R. Douglass, and T. Millstein.
*
* The specification is determined by referring to peg/leg developed by Ian Piumarta.
*/
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#endif
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#ifndef _MSC_VER
#if defined __GNUC__ && defined _WIN32 /* MinGW */
#ifndef PCC_USE_SYSTEM_STRNLEN
#define strnlen(str, maxlen) strnlen_(str, maxlen)
static size_t strnlen_(const char *str, size_t maxlen) {
size_t i;
for (i = 0; i < maxlen && str[i]; i++);
return i;
}
#endif /* !PCC_USE_SYSTEM_STRNLEN */
#endif /* defined __GNUC__ && defined _WIN32 */
#endif /* !_MSC_VER */
#ifdef _MSC_VER
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#define unlink _unlink
#else
#include <unistd.h> /* for unlink() */
#endif
#ifdef _WIN32 /* Windows including MSVC and MinGW */
#include <io.h> /* _get_osfhandle() */
/* NOTE: The header "fileapi.h" causes a compiler error due to an illegal anonymous union. */
#define DECLSPEC_IMPORT __declspec(dllimport)
#define WINAPI __stdcall
#define S_OK 0
#define CSIDL_PROFILE 0x0028
#define CSIDL_COMMON_APPDATA 0x0023
#define SHGFP_TYPE_DEFAULT 1
#define MAX_PATH 260
typedef int BOOL;
typedef unsigned long DWORD;
typedef char *LPSTR;
typedef long HRESULT;
typedef void *HANDLE;
typedef void *HWND;
typedef struct _FILETIME {
DWORD dwLowDateTime;
DWORD dwHighDateTime;
} FILETIME;
typedef struct _BY_HANDLE_FILE_INFORMATION {
DWORD dwFileAttributes;
FILETIME ftCreationTime;
FILETIME ftLastAccessTime;
FILETIME ftLastWriteTime;
DWORD dwVolumeSerialNumber;
DWORD nFileSizeHigh;
DWORD nFileSizeLow;
DWORD nNumberOfLinks;
DWORD nFileIndexHigh;
DWORD nFileIndexLow;
} BY_HANDLE_FILE_INFORMATION, *LPBY_HANDLE_FILE_INFORMATION;
DECLSPEC_IMPORT BOOL WINAPI GetFileInformationByHandle(HANDLE hFile, LPBY_HANDLE_FILE_INFORMATION lpFileInformation);
DECLSPEC_IMPORT HRESULT WINAPI SHGetFolderPathA(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPSTR pszPath);
#else /* !_WIN32 */
#include <sys/stat.h> /* for fstat() */
#endif
#if !defined __has_attribute || defined _MSC_VER
#define __attribute__(x)
#endif
#undef TRUE /* to avoid macro definition conflicts with the system header file of IBM AIX */
#undef FALSE
#ifdef _MSC_VER
#define IMPORT_DIR_SYSTEM "packcc/import" /* should be a relative path */
#else
#define IMPORT_DIR_SYSTEM "/usr/share/packcc/import" /* should be an absolute path */
#endif
#define IMPORT_DIR_USER ".packcc/import"
#ifdef _WIN32 /* Windows including MSVC and MinGW (MinGW automatically converts paths to those in Windows style) */
#define PATH_SEP ';'
#else
#define PATH_SEP ':'
#endif
#define ENVVAR_IMPORT_PATH "PCC_IMPORT_PATH"
#define WEBSITE "https://github.com/arithy/packcc"
#define VERSION "2.0.3"
#ifndef BUFFER_MIN_SIZE
#define BUFFER_MIN_SIZE 256
#endif
#ifndef ARRAY_MIN_SIZE
#define ARRAY_MIN_SIZE 2
#endif
#define VOID_VALUE (~(size_t)0)
#ifdef _WIN64 /* 64-bit Windows including MSVC and MinGW-w64 */
#define FMT_LU "%llu"
typedef unsigned long long ulong_t;
/* NOTE: "%llu" and "long long" are not C89-compliant, but we cannot help using them to deal with a 64-bit integer value in 64-bit Windows. */
#else
#define FMT_LU "%lu"
typedef unsigned long ulong_t;
#endif
/* FMT_LU and ulong_t are used to print size_t values safely (ex. printf(FMT_LU "\n", (ulong_t)value);) */
/* NOTE: Neither "%zu" nor <inttypes.h> is used since PackCC complies with the C89 standard as much as possible. */
typedef enum bool_tag {
FALSE = 0,
TRUE
} bool_t;
#ifdef _WIN32 /* Windows including MSVC and MinGW */
typedef BY_HANDLE_FILE_INFORMATION file_id_t;
#else
typedef struct stat file_id_t;
#endif
typedef struct file_id_array_tag {
file_id_t *buf;
size_t max;
size_t len;
} file_id_array_t;
typedef struct file_pos_tag {
char *path; /* the file path name */
size_t line; /* the line number (0-based); VOID_VALUE if not available */
size_t col; /* the column number (0-based); VOID_VALUE if not available */
} file_pos_t;
typedef struct stream_tag {
FILE *file; /* the file stream; just a reference */
const char *path; /* the file path name */
size_t line; /* the current line number (0-based); line counting is disabled if VOID_VALUE */
} stream_t;
typedef struct char_array_tag {
char *buf;
size_t max;
size_t len;
} char_array_t;
typedef struct string_array_tag {
char **buf;
size_t max;
size_t len;
} string_array_t;
typedef struct code_block_tag {
char *text;
size_t len;
file_pos_t fpos;
} code_block_t;
typedef struct code_block_array_tag {
code_block_t *buf;
size_t max;
size_t len;
} code_block_array_t;
typedef enum node_type_tag {
NODE_RULE = 0,
NODE_REFERENCE,
NODE_STRING,
NODE_CHARCLASS,
NODE_QUANTITY,
NODE_PREDICATE,
NODE_SEQUENCE,
NODE_ALTERNATE,
NODE_CAPTURE,
NODE_EXPAND,
NODE_ACTION,
NODE_ERROR
} node_type_t;
typedef struct node_tag node_t;
typedef struct node_array_tag {
node_t **buf;
size_t max;
size_t len;
} node_array_t;
typedef struct node_const_array_tag {
const node_t **buf;
size_t max;
size_t len;
} node_const_array_t;
typedef struct node_hash_table_tag {
const node_t **buf;
size_t max;
size_t mod;
} node_hash_table_t;
typedef struct node_rule_tag {
char *name;
node_t *expr;
int ref; /* mutable under make_rulehash(), link_references(), and unreference_rules_from_unused_rule() */
bool_t used; /* mutable under mark_rules_if_used() */
node_const_array_t vars;
node_const_array_t capts;
node_const_array_t codes;
file_pos_t fpos;
} node_rule_t;
typedef struct node_reference_tag {
char *var; /* NULL if no variable name */
size_t index;
char *name;
const node_t *rule;
file_pos_t fpos;
} node_reference_t;
typedef struct node_string_tag {
char *value;
} node_string_t;
typedef struct node_charclass_tag {
char *value; /* NULL means any character */
} node_charclass_t;
typedef struct node_quantity_tag {
int min;
int max;
node_t *expr;
} node_quantity_t;
typedef struct node_predicate_tag {
bool_t neg;
node_t *expr;
} node_predicate_t;
typedef struct node_sequence_tag {
node_array_t nodes;
} node_sequence_t;
typedef struct node_alternate_tag {
node_array_t nodes;
} node_alternate_t;
typedef struct node_capture_tag {
node_t *expr;
size_t index;
} node_capture_t;
typedef struct node_expand_tag {
size_t index;
file_pos_t fpos;
} node_expand_t;
typedef struct node_action_tag {
code_block_t code;
size_t index;
node_const_array_t vars;
node_const_array_t capts;
} node_action_t;
typedef struct node_error_tag {
node_t *expr;
code_block_t code;
size_t index;
node_const_array_t vars;
node_const_array_t capts;
} node_error_t;
typedef union node_data_tag {
node_rule_t rule;
node_reference_t reference;
node_string_t string;
node_charclass_t charclass;
node_quantity_t quantity;
node_predicate_t predicate;
node_sequence_t sequence;
node_alternate_t alternate;
node_capture_t capture;
node_expand_t expand;
node_action_t action;
node_error_t error;
} node_data_t;
struct node_tag {
node_type_t type;
node_data_t data;
};
typedef struct options_tag {
bool_t ascii; /* UTF-8 support is disabled if true */
bool_t lines; /* #line directives are output if true */
bool_t debug; /* debug information is output if true */
} options_t;
typedef enum code_flag_tag {
CODE_FLAG__NONE = 0,
CODE_FLAG__UTF8_CHARCLASS_USED = 1
} code_flag_t;
typedef struct input_state_tag input_state_t;
struct input_state_tag {
char *path; /* the path name of the PEG file being parsed; "<stdin>" if stdin */
FILE *file; /* the input file stream of the PEG file */
bool_t ascii; /* UTF-8 support is disabled if true */
code_flag_t flags; /* the bitwise flags to control code generation; updated during PEG parsing */
size_t errnum; /* the current number of PEG parsing errors */
size_t linenum; /* the current line number (0-based) */
size_t charnum; /* the number of characters in the current line that are already flushed (0-based, UTF-8 support if not disabled) */
size_t linepos; /* the beginning position in the PEG file of the current line */
size_t bufpos; /* the position in the PEG file of the first character currently buffered */
size_t bufcur; /* the current parsing position in the character buffer */
char_array_t buffer; /* the character buffer */
input_state_t *parent; /* the input state of the parent PEG file that imports the input; just a reference */
};
typedef struct context_tag {
char *spath; /* the path name of the C source file being generated */
char *hpath; /* the path name of the C header file being generated */
char *hid; /* the macro name for the include guard of the C header file */
char *vtype; /* the type name of the data output by the parsing API function (NULL means the default) */
char *atype; /* the type name of the user-defined data passed to the parser creation API function (NULL means the default) */
char *prefix; /* the prefix of the API function names (NULL means the default) */
const string_array_t *dirs; /* the path names of directories to search for import files */
options_t opts; /* the options */
code_flag_t flags; /* the bitwise flags to control code generation; updated during PEG parsing */
size_t errnum; /* the current number of PEG parsing errors */
input_state_t *input; /* the current input state */
file_id_array_t done; /* the unique identifiers of the PEG file already parsed or being parsed */
node_array_t rules; /* the PEG rules */
node_hash_table_t rulehash; /* the hash table to accelerate access of desired PEG rules */
code_block_array_t esource; /* the code blocks from %earlysource and %earlycommon directives to be added into the generated source file */
code_block_array_t eheader; /* the code blocks from %earlyheader and %earlycommon directives to be added into the generated header file */
code_block_array_t source; /* the code blocks from %source and %common directives to be added into the generated source file */
code_block_array_t header; /* the code blocks from %header and %common directives to be added into the generated header file */
code_block_array_t fsource; /* the code fragments after %% directive to be added into the generated source file */
} context_t;
typedef struct generate_tag {
stream_t *stream;
const node_t *rule;
int label;
bool_t ascii;
} generate_t;
typedef enum string_flag_tag {
STRING_FLAG__NONE = 0,
STRING_FLAG__NOTEMPTY = 1,
STRING_FLAG__NOTVOID = 2,
STRING_FLAG__IDENTIFIER = 4
} string_flag_t;
typedef enum code_reach_tag {
CODE_REACH__BOTH = 0,
CODE_REACH__ALWAYS_SUCCEED = 1,
CODE_REACH__ALWAYS_FAIL = -1
} code_reach_t;
static const char *g_cmdname = "packcc"; /* replaced later with actual one */
__attribute__((format(printf, 1, 2)))
static int print_error(const char *format, ...) {
int n;
va_list a;
va_start(a, format);
n = fprintf(stderr, "%s: ", g_cmdname);
if (n >= 0) {
const int k = vfprintf(stderr, format, a);
if (k < 0) n = k; else n += k;
}
va_end(a);
return n;
}
static FILE *fopen_rb_e(const char *path) {
FILE *const f = fopen(path, "rb");
if (f == NULL) {
print_error("Cannot open file to read: %s\n", path);
exit(2);
}
return f;
}
static FILE *fopen_wt_e(const char *path) {
FILE *const f = fopen(path, "wt");
if (f == NULL) {
print_error("Cannot open file to write: %s\n", path);
exit(2);
}
return f;
}
static int fclose_e(FILE *file, const char *path) {
const int r = fclose(file);
if (r == EOF) {
print_error("File closing error: %s\n", path);
exit(2);
}
return r;
}
static int fgetc_e(FILE *file, const char *path) {
const int c = fgetc(file);
if (c == EOF && ferror(file)) {
print_error("File read error: %s\n", path);
exit(2);
}
return c;
}
static void *malloc_e(size_t size) {
void *const p = malloc(size);
if (p == NULL) {
print_error("Out of memory\n");
exit(3);
}
return p;
}
static void *realloc_e(void *ptr, size_t size) {
void *const p = realloc(ptr, size);
if (p == NULL) {
print_error("Out of memory\n");
exit(3);
}
return p;
}
static char *strdup_e(const char *str) {
const size_t m = strlen(str);
char *const s = (char *)malloc_e(m + 1);
memcpy(s, str, m);
s[m] = '\0';
return s;
}
static char *strndup_e(const char *str, size_t len) {
const size_t m = strnlen(str, len);
char *const s = (char *)malloc_e(m + 1);
memcpy(s, str, m);
s[m] = '\0';
return s;
}
static size_t string_to_size_t(const char *str) {
#define N (~(size_t)0 / 10)
#define M (~(size_t)0 - 10 * N)
size_t n = 0, i, k;
for (i = 0; str[i]; i++) {
const char c = str[i];
if (c < '0' || c > '9') return VOID_VALUE;
k = (size_t)(c - '0');
if (n >= N && k > M) return VOID_VALUE; /* overflow */
n = k + 10 * n;
}
return n;
#undef N
#undef M
}
static size_t find_first_trailing_space(const char *str, size_t start, size_t end, size_t *next) {
size_t j = start, i;
for (i = start; i < end; i++) {
switch (str[i]) {
case ' ':
case '\v':
case '\f':
case '\t':
continue;
case '\n':
if (next) *next = i + 1;
return j;
case '\r':
if (i + 1 < end && str[i + 1] == '\n') i++;
if (next) *next = i + 1;
return j;
default:
j = i + 1;
}
}
if (next) *next = end;
return j;
}
static size_t count_indent_spaces(const char *str, size_t start, size_t end, size_t *next) {
size_t n = 0, i;
for (i = start; i < end; i++) {
switch (str[i]) {
case ' ':
case '\v':
case '\f':
n++;
break;
case '\t':
n = (n + 8) & ~7;
break;
default:
if (next) *next = i;
return n;
}
}
if (next) *next = end;
return n;
}
static bool_t is_filled_string(const char *str) {
size_t i;
for (i = 0; str[i]; i++) {
if (
str[i] != ' ' &&
str[i] != '\v' &&
str[i] != '\f' &&
str[i] != '\t' &&
str[i] != '\n' &&
str[i] != '\r'
) return TRUE;
}
return FALSE;
}
static bool_t is_identifier_string(const char *str) {
size_t i;
if (!(
(str[0] >= 'a' && str[0] <= 'z') ||
(str[0] >= 'A' && str[0] <= 'Z') ||
str[0] == '_'
)) return FALSE;
for (i = 1; str[i]; i++) {
if (!(
(str[i] >= 'a' && str[i] <= 'z') ||
(str[i] >= 'A' && str[i] <= 'Z') ||
(str[i] >= '0' && str[i] <= '9') ||
str[i] == '_'
)) return FALSE;
}
return TRUE;
}
static bool_t is_pointer_type(const char *str) {
const size_t n = strlen(str);
return (n > 0 && str[n - 1] == '*') ? TRUE : FALSE;
}
static bool_t is_valid_utf8_string(const char *str) {
int k = 0, n = 0, u = 0;
size_t i;
for (i = 0; str[i]; i++) {
const int c = (int)(unsigned char)str[i];
switch (k) {
case 0:
if (c >= 0x80) {
if ((c & 0xe0) == 0xc0) {
u = c & 0x1f;
n = k = 1;
}
else if ((c & 0xf0) == 0xe0) {
u = c & 0x0f;
n = k = 2;
}
else if ((c & 0xf8) == 0xf0) {
u = c & 0x07;
n = k = 3;
}
else {
return FALSE;
}
}
break;
case 1:
case 2:
case 3:
if ((c & 0xc0) == 0x80) {
u <<= 6;
u |= c & 0x3f;
k--;
if (k == 0) {
switch (n) {
case 1:
if (u < 0x80) return FALSE;
break;
case 2:
if (u < 0x800) return FALSE;
break;
case 3:
if (u < 0x10000 || u > 0x10ffff) return FALSE;
break;
default:
assert(((void)"unexpected control flow", 0));
return FALSE; /* never reached */
}
u = 0;
n = 0;
}
}
else {
return FALSE;
}
break;
default:
assert(((void)"unexpected control flow", 0));
return FALSE; /* never reached */
}
}
return (k == 0) ? TRUE : FALSE;
}
static size_t utf8_to_utf32(const char *seq, int *out) { /* without checking UTF-8 validity */
const int c = (int)(unsigned char)seq[0];
const size_t n =
(c == 0) ? 0 : (c < 0x80) ? 1 :
((c & 0xe0) == 0xc0) ? 2 :
((c & 0xf0) == 0xe0) ? 3 :
((c & 0xf8) == 0xf0) ? 4 : 1;
int u = 0;
switch (n) {
case 0:
case 1:
u = c;
break;
case 2:
u = ((c & 0x1f) << 6) |
((int)(unsigned char)seq[1] & 0x3f);
break;
case 3:
u = ((c & 0x0f) << 12) |
(((int)(unsigned char)seq[1] & 0x3f) << 6) |
(seq[1] ? ((int)(unsigned char)seq[2] & 0x3f) : 0);
break;
default:
u = ((c & 0x07) << 18) |
(((int)(unsigned char)seq[1] & 0x3f) << 12) |
(seq[1] ? (((int)(unsigned char)seq[2] & 0x3f) << 6) : 0) |
(seq[2] ? ((int)(unsigned char)seq[3] & 0x3f) : 0);
}
if (out) *out = u;
return n;
}
static bool_t unescape_string(char *str, bool_t cls) { /* cls: TRUE if used for character class matching */
bool_t b = TRUE;
size_t i, j;
for (j = 0, i = 0; str[i]; i++) {
if (str[i] == '\\') {
i++;
switch (str[i]) {
case '\0': str[j++] = '\\'; str[j] = '\0'; return FALSE;
case '\'': str[j++] = '\''; break;
case '\"': str[j++] = '\"'; break;
case '0': str[j++] = '\x00'; break;
case 'a': str[j++] = '\x07'; break;
case 'b': str[j++] = '\x08'; break;
case 'f': str[j++] = '\x0c'; break;
case 'n': str[j++] = '\x0a'; break;
case 'r': str[j++] = '\x0d'; break;
case 't': str[j++] = '\x09'; break;
case 'v': str[j++] = '\x0b'; break;
case 'x':
{
char s = 0, c;
size_t k;
for (k = 0; k < 2; k++) {
char d;
c = str[i + k + 1];
d = (c >= '0' && c <= '9') ? c - '0' :
(c >= 'a' && c <= 'f') ? c - 'a' + 10 :
(c >= 'A' && c <= 'F') ? c - 'A' + 10 : -1;
if (d < 0) break;
s = (s << 4) | d;
}
if (k < 2) {
const size_t l = i + k;
str[j++] = '\\'; str[j++] = 'x';
while (i <= l) str[j++] = str[++i];
if (c == '\0') return FALSE;
b = FALSE;
continue;
}
str[j++] = s;
i += 2;
}
break;
case 'u':
{
int s = 0, t = 0;
char c;
size_t k;
for (k = 0; k < 4; k++) {
char d;
c = str[i + k + 1];
d = (c >= '0' && c <= '9') ? c - '0' :
(c >= 'a' && c <= 'f') ? c - 'a' + 10 :
(c >= 'A' && c <= 'F') ? c - 'A' + 10 : -1;
if (d < 0) break;
s = (s << 4) | d;
}
if (k < 4 || (s & 0xfc00) == 0xdc00) { /* invalid character or invalid surrogate code point */
const size_t l = i + k;
str[j++] = '\\'; str[j++] = 'u';
while (i <= l) str[j++] = str[++i];
if (c == '\0') return FALSE;
b = FALSE;
continue;
}
if ((s & 0xfc00) == 0xd800) { /* surrogate pair */
for (k = 4; k < 10; k++) {
c = str[i + k + 1];
if (k == 4) {
if (c != '\\') break;
}
else if (k == 5) {
if (c != 'u') break;
}
else {
const char d =
(c >= '0' && c <= '9') ? c - '0' :
(c >= 'a' && c <= 'f') ? c - 'a' + 10 :
(c >= 'A' && c <= 'F') ? c - 'A' + 10 : -1;
if (d < 0) break;
t = (t << 4) | d;
}
}
if (k < 10 || (t & 0xfc00) != 0xdc00) { /* invalid character or invalid surrogate code point */
const size_t l = i + 4; /* NOTE: Not i + k to redo with recovery. */
str[j++] = '\\'; str[j++] = 'u';
while (i <= l) str[j++] = str[++i];
b = FALSE;
continue;
}
}
{
const int u = t ? ((((s & 0x03ff) + 0x0040) << 10) | (t & 0x03ff)) : s;
if (u < 0x0080) {
str[j++] = (char)u;
}
else if (u < 0x0800) {
str[j++] = (char)(0xc0 | (u >> 6));
str[j++] = (char)(0x80 | (u & 0x3f));
}
else if (u < 0x010000) {
str[j++] = (char)(0xe0 | (u >> 12));
str[j++] = (char)(0x80 | ((u >> 6) & 0x3f));
str[j++] = (char)(0x80 | (u & 0x3f));
}
else if (u < 0x110000) {
str[j++] = (char)(0xf0 | (u >> 18));
str[j++] = (char)(0x80 | ((u >> 12) & 0x3f));
str[j++] = (char)(0x80 | ((u >> 6) & 0x3f));
str[j++] = (char)(0x80 | (u & 0x3f));
}
else { /* never reached theoretically; in case */
const size_t l = i + 10;
str[j++] = '\\'; str[j++] = 'u';
while (i <= l) str[j++] = str[++i];
b = FALSE;
continue;
}
}
i += t ? 10 : 4;
}
break;
case '\n': break;
case '\r': if (str[i + 1] == '\n') i++; break;
case '\\':
if (cls) str[j++] = '\\'; /* left for character class matching (ex. considering [\^\]\\]) */
str[j++] = '\\';
break;
default: str[j++] = '\\'; str[j++] = str[i];
}
}
else {
str[j++] = str[i];
}
}
str[j] = '\0';
return b;
}
static const char *escape_character(char ch, char (*buf)[5]) {
switch (ch) {
case '\x00': strncpy(*buf, "\\0", 5); break;
case '\x07': strncpy(*buf, "\\a", 5); break;
case '\x08': strncpy(*buf, "\\b", 5); break;
case '\x0c': strncpy(*buf, "\\f", 5); break;
case '\x0a': strncpy(*buf, "\\n", 5); break;
case '\x0d': strncpy(*buf, "\\r", 5); break;
case '\x09': strncpy(*buf, "\\t", 5); break;
case '\x0b': strncpy(*buf, "\\v", 5); break;
case '\\': strncpy(*buf, "\\\\", 5); break;
case '\'': strncpy(*buf, "\\\'", 5); break;
case '\"': strncpy(*buf, "\\\"", 5); break;
default:
if (ch >= '\x20' && ch < '\x7f')
snprintf(*buf, 5, "%c", ch);
else
snprintf(*buf, 5, "\\x%02x", (int)(unsigned char)ch);
}
(*buf)[4] = '\0';
return *buf;
}
static void remove_leading_blanks(char *str) {
size_t i, j;
for (i = 0; str[i]; i++) {
if (
str[i] != ' ' &&
str[i] != '\v' &&
str[i] != '\f' &&
str[i] != '\t' &&
str[i] != '\n' &&
str[i] != '\r'
) break;
}
for (j = 0; str[i]; i++) {
str[j++] = str[i];
}
str[j] = '\0';
}
static void remove_trailing_blanks(char *str) {
size_t i, j;
for (j = 0, i = 0; str[i]; i++) {
if (
str[i] != ' ' &&
str[i] != '\v' &&
str[i] != '\f' &&
str[i] != '\t' &&
str[i] != '\n' &&
str[i] != '\r'
) j = i + 1;
}
str[j] = '\0';
}
static size_t find_trailing_blanks(const char *str) {
size_t i, j;
for (j = 0, i = 0; str[i]; i++) {
if (
str[i] != ' ' &&
str[i] != '\v' &&
str[i] != '\f' &&
str[i] != '\t' &&
str[i] != '\n' &&
str[i] != '\r'
) j = i + 1;
}
return j;
}
static size_t count_characters(const char *str, size_t start, size_t end) {
/* UTF-8 multibyte character support but without checking UTF-8 validity */
size_t n = 0, i = start;
while (i < end) {
const int c = (int)(unsigned char)str[i];
if (c == 0) break;
n++;
i += (c < 0x80) ? 1 : ((c & 0xe0) == 0xc0) ? 2 : ((c & 0xf0) == 0xe0) ? 3 : ((c & 0xf8) == 0xf0) ? 4 : /* invalid code */ 1;
}
return n;
}
static void make_header_identifier(char *str) {
size_t i;
for (i = 0; str[i]; i++) {
str[i] =
((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= '0' && str[i] <= '9')) ? str[i] :
(str[i] >= 'a' && str[i] <= 'z') ? str[i] - 'a' + 'A' : '_';
}
}
static void file_pos__init(file_pos_t *pos) {
pos->path = NULL;
pos->line = VOID_VALUE;
pos->col = VOID_VALUE;
}
static void file_pos__set(file_pos_t *pos, const char *path, size_t line, size_t col) {
free(pos->path);
pos->path = path ? strdup_e(path) : NULL;
pos->line = line;
pos->col = col;
}
static void file_pos__term(file_pos_t *pos) {
free(pos->path);
}
static void file_id__get(FILE *file, const char *path, file_id_t *id) {
#ifdef _WIN32 /* Windows including MSVC and MinGW */
if (GetFileInformationByHandle((HANDLE)_get_osfhandle(_fileno(file)), id) == 0) {
print_error("Cannot get file information: %s\n", path);
exit(2);
}
#else
if (fstat(fileno(file), id) != 0) {
print_error("Cannot get file information: %s\n", path);
exit(2);
}
#endif
}
static bool_t file_id__equals(const file_id_t *id0, const file_id_t *id1) {
#ifdef _WIN32 /* Windows including MSVC and MinGW */
return (
id0->dwVolumeSerialNumber == id1->dwVolumeSerialNumber &&
id0->nFileIndexHigh == id1->nFileIndexHigh &&
id0->nFileIndexLow == id1->nFileIndexLow
) ? TRUE : FALSE;
#else
return (id0->st_dev == id1->st_dev && id0->st_ino == id1->st_ino) ? TRUE : FALSE;
#endif
}
static stream_t stream__wrap(FILE *file, const char *path, size_t line) {
stream_t s;
s.file = file;
s.path = path;
s.line = line;
return s;
}
static int stream__putc(stream_t *stream, int c) {
const int r = fputc(c, stream->file);
if (r == EOF) {
print_error("File write error: %s\n", stream->path);
exit(2);
}
if (stream->line != VOID_VALUE) {
if (c == '\n') stream->line++;
}
return r;
}
static int stream__puts(stream_t *stream, const char *s) {
const int r = fputs(s, stream->file);
if (r == EOF) {
print_error("File write error: %s\n", stream->path);
exit(2);
}
if (stream->line != VOID_VALUE) {
size_t i = 0;
for (i = 0; s[i]; i++) {
if (s[i] == '\n') stream->line++;
}
}
return r;
}
__attribute__((format(printf, 2, 3)))
static int stream__printf(stream_t *stream, const char *format, ...) {
if (stream->line != VOID_VALUE) {
#define M 1024
char s[M], *p = NULL;
int n = 0;
size_t l = 0;
{
va_list a;
va_start(a, format);