-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathconvert.c
2618 lines (2371 loc) · 93.8 KB
/
convert.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
/*
* C99-to-MSVC-compatible-C89 syntax converter
* Copyright (c) 2012 Ronald S. Bultje <[email protected]>
* Copyright (c) 2012 Derek Buitenhuis <[email protected]>
* Copyright (c) 2012 Martin Storsjo <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <assert.h>
#include <stdio.h>
#include <clang-c/Index.h>
#include <string.h>
#include <stdlib.h>
#include <inttypes.h>
#ifdef _MSC_VER
#define strtoll _strtoi64
#endif
/*
* The basic idea of the token parser is to "stack" ordered tokens
* (i.e. ordering is done by libclang) in such a way that we can
* re-arrange them on the fly before printing it back out to an
* output file.
*
* Example:
*
* x = (AVRational) { y, z };
* becomes
* { AVRational temp = { y, z }; x = temp; }
*
* x = function((AVRational) { y, z });
* becomes
* { AVRational temp = { y, z }; x = function(temp); }
*
* return function((AVRational) { y, z });
* becomes
* { AVRational temp = { y, z }; return function(temp); }
*
* int var = ((int[2]) { 1, 2 })[1];
* becomes
* int var; { int temp[2] = { 1, 2 }; var = temp[1]; { [..] } }
*
* Note in the above, that the [..] indeed means the whole rest
* of the statements in the same context needs to be within the
* brackets, otherwise the resulting code could contain mixed
* variable declarations and statements, which c89 does not allow.
*
* Like for compound literals, c89 does not support designated
* initializers, thus we attempt to replace them. The basic idea
* is to parse the layout of structs and enums, and then to parse
* expressions like:
* {
* [index1] = val1,
* [index2] = val2,
* }
* or
* {
* .member1 = val1,
* .member2 = val2,
* }
* and convert these to ordered struct/array initializers without
* designation, i.e.:
* {
* val1,
* val2,
* }
* Note that in cases where the indexes or members are not ordered,
* i.e. their order in the struct (for members) is different from
* the order of initialization in the expression, or their numeric
* values are not linearly ascending in the same way as they are
* presented in the expression, then we have to reorder the expressions
* and, in some cases, insert gap fillers. For example,
* {
* [index3] = val3,
* [index1] = val1,
* }
* becomes
* {
* val1, 0,
* val3,
* }
* (assuming index1 is the first value and index3 is the third value
* in an enum, and in between these two is a value index2 which is
* not used in this designated initializer expression. If the values
* themselves are structs, we use {} instead of 0 as a gap filler.
*/
typedef struct {
char *type;
unsigned struct_decl_idx;
char *name;
unsigned n_ptrs; // 0 if not a pointer
unsigned array_depth; // 0 if no array
CXCursor cursor;
} StructMember;
typedef struct {
StructMember *entries;
unsigned n_entries;
unsigned n_allocated_entries;
char *name;
CXCursor cursor;
int is_union;
} StructDeclaration;
static StructDeclaration *structs = NULL;
static unsigned n_structs = 0;
static unsigned n_allocated_structs = 0;
typedef struct {
char *name;
int value;
CXCursor cursor;
} EnumMember;
typedef struct {
EnumMember *entries;
unsigned n_entries;
unsigned n_allocated_entries;
char *name;
CXCursor cursor;
} EnumDeclaration;
static EnumDeclaration *enums = NULL;
static unsigned n_enums = 0;
static unsigned n_allocated_enums = 0;
/* FIXME we're not taking pointers or array sizes into account here,
* in large part because Libav doesn't use those in combination with
* typedefs. */
typedef struct {
char *proxy;
char *name;
unsigned struct_decl_idx;
unsigned enum_decl_idx;
CXCursor cursor;
} TypedefDeclaration;
static TypedefDeclaration *typedefs = NULL;
static unsigned n_typedefs = 0;
static unsigned n_allocated_typedefs = 0;
enum StructArrayType {
TYPE_IRRELEVANT = 0,
TYPE_STRUCT = 1,
TYPE_ARRAY = 2,
};
typedef struct {
unsigned index;
struct {
unsigned start, end;
} value_offset, expression_offset;
} StructArrayItem;
typedef struct {
enum StructArrayType type;
unsigned struct_decl_idx;
unsigned array_depth;
StructArrayItem *entries;
unsigned level;
unsigned n_entries;
unsigned n_allocated_entries;
struct {
unsigned start, end;
} value_offset;
int convert_to_assignment;
char *name;
} StructArrayList;
static StructArrayList *struct_array_lists = NULL;
static unsigned n_struct_array_lists = 0;
static unsigned n_allocated_struct_array_lists = 0;
typedef struct {
int end;
int n_scopes;
} EndScope;
static EndScope *end_scopes = NULL;
static unsigned n_end_scopes = 0;
static unsigned n_allocated_end_scopes = 0;
static FILE *out;
static CXTranslationUnit TU;
#define DEBUG 0
#define dprintf(...) \
if (DEBUG) \
printf(__VA_ARGS__)
static unsigned find_token_index(CXToken *tokens, unsigned n_tokens,
const char *str)
{
unsigned n;
for (n = n_tokens - 1; n != (unsigned) -1; n--) {
CXString tstr = clang_getTokenSpelling(TU, tokens[n]);
const char *cstr = clang_getCString(tstr);
int res = strcmp(str, cstr);
clang_disposeString(tstr);
if (!res)
return n;
}
fprintf(stderr, "Could not find token %s in set\n", str);
exit(1);
}
static char *concat_name(CXToken *tokens, unsigned int from, unsigned to)
{
unsigned int cnt = 0, n;
char *str;
for (n = from; n <= to; n++) {
CXString tstr = clang_getTokenSpelling(TU, tokens[n]);
const char *cstr = clang_getCString(tstr);
cnt += strlen(cstr) + 1;
clang_disposeString(tstr);
}
str = (char *) malloc(cnt);
if (!str) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
for (cnt = 0, n = from; n <= to; n++) {
CXString tstr = clang_getTokenSpelling(TU, tokens[n]);
const char *cstr = clang_getCString(tstr);
int len = strlen(cstr);
memcpy(&str[cnt], cstr, len);
if (n == to) {
str[cnt + len] = 0;
} else {
str[cnt + len] = ' ';
}
cnt += len + 1;
clang_disposeString(tstr);
}
return str;
}
static void register_struct(const char *str, CXCursor cursor,
TypedefDeclaration *decl_ptr, int is_union);
static void register_enum(const char *str, CXCursor cursor,
TypedefDeclaration *decl_ptr);
static unsigned find_struct_decl_idx_for_type_name(const char *name);
static enum CXChildVisitResult find_anon_struct(CXCursor cursor,
CXCursor parent,
CXClientData client_data)
{
CXString cstr = clang_getCursorSpelling(cursor);
const char *str = clang_getCString(cstr);
switch (cursor.kind) {
case CXCursor_StructDecl:
register_struct(str, cursor, client_data, 0);
break;
case CXCursor_UnionDecl:
register_struct(str, cursor, client_data, 1);
break;
case CXCursor_EnumDecl:
register_enum(str, cursor, client_data);
break;
case CXCursor_TypeRef: {
TypedefDeclaration *td = client_data;
td->struct_decl_idx = find_struct_decl_idx_for_type_name(str);
break;
}
default:
break;
}
clang_disposeString(cstr);
return CXChildVisit_Continue;
}
static enum CXChildVisitResult fill_struct_members(CXCursor cursor,
CXCursor parent,
CXClientData client_data)
{
unsigned decl_idx = (unsigned) client_data;
StructDeclaration *decl = &structs[decl_idx];
CXString cstr = clang_getCursorSpelling(cursor);
const char *str = clang_getCString(cstr);
switch (cursor.kind) {
case CXCursor_FieldDecl: {
unsigned n = decl->n_entries, idx, m;
CXToken *tokens = 0;
unsigned int n_tokens = 0;
CXSourceRange range = clang_getCursorExtent(cursor);
TypedefDeclaration td;
// padding bitfields
if (!strcmp(str, "")) {
clang_disposeString(cstr);
return CXChildVisit_Continue;
}
clang_tokenize(TU, range, &tokens, &n_tokens);
if (decl->n_entries == decl->n_allocated_entries) {
unsigned num = decl->n_allocated_entries + 16;
void *mem = realloc(decl->entries,
sizeof(*decl->entries) * num);
if (!mem) {
fprintf(stderr,
"Ran out of memory while declaring field %s in %s\n",
str, decl->name);
exit(1);
}
decl->entries = (StructMember *) mem;
decl->n_allocated_entries = num;
}
decl->entries[n].name = strdup(str);
decl->entries[n].cursor = cursor;
decl->n_entries++;
idx = find_token_index(tokens, n_tokens, str);
decl->entries[n].n_ptrs = 0;
decl->entries[n].array_depth = 0;
for (m = idx + 1; m < n_tokens; m++) {
CXString tstr = clang_getTokenSpelling(TU, tokens[m]);
const char *cstr = clang_getCString(tstr);
int res = strcmp(cstr, ";") && strcmp(cstr, ",");
if (!strcmp(cstr, "["))
decl->entries[n].array_depth++;
clang_disposeString(tstr);
if (!res)
break;
}
for (;;) {
unsigned im1 = idx - 1 - decl->entries[n].n_ptrs;
CXString tstr = clang_getTokenSpelling(TU, tokens[im1]);
const char *cstr = clang_getCString(tstr);
int res = strcmp(cstr, "*");
clang_disposeString(tstr);
if (!res) {
decl->entries[n].n_ptrs++;
} else {
break;
}
}
do {
unsigned im1 = idx - 1 - decl->entries[n].n_ptrs;
CXString tstr = clang_getTokenSpelling(TU, tokens[im1]);
const char *cstr = clang_getCString(tstr);
if (!strcmp(cstr, ",")) {
decl->entries[n].type = strdup(decl->entries[n - 1].type);
} else {
decl->entries[n].type = concat_name(tokens, 0, im1);
}
clang_disposeString(tstr);
} while (0);
memset(&td, 0, sizeof(td));
td.struct_decl_idx = (unsigned) -1;
clang_visitChildren(cursor, find_anon_struct, &td);
decl->entries[n].struct_decl_idx = td.struct_decl_idx;
// FIXME it's not hard to find the struct name (either because
// tokens[idx-2-n_ptrs] == 'struct', or because tokens[idx-1-n_ptrs]
// is a typedef for the struct name), and then we can use
// find_struct_decl() to find the StructDeclaration belonging to
// that type.
clang_disposeTokens(TU, tokens, n_tokens);
break;
}
case CXCursor_StructDecl:
register_struct(str, cursor, NULL, 0);
break;
case CXCursor_UnionDecl:
register_struct(str, cursor, NULL, 1);
break;
case CXCursor_EnumDecl:
register_enum(str, cursor, NULL);
break;
default:
break;
}
clang_disposeString(cstr);
return CXChildVisit_Continue;
}
static void register_struct(const char *str, CXCursor cursor,
TypedefDeclaration *decl_ptr, int is_union)
{
unsigned n;
StructDeclaration *decl;
for (n = 0; n < n_structs; n++) {
if ((str[0] != 0 && !strcmp(structs[n].name, str)) ||
!memcmp(&cursor, &structs[n].cursor, sizeof(cursor))) {
/* already exists */
if (decl_ptr)
decl_ptr->struct_decl_idx = n;
if (structs[n].n_entries == 0) {
// Fill in structs that were defined (empty) earlier, i.e.
// 'struct AVFilterPad;', followed by the full declaration
// 'struct AVFilterPad { ... };'
clang_visitChildren(cursor, fill_struct_members, (void *) n);
}
return;
}
}
if (n_structs == n_allocated_structs) {
unsigned num = n_allocated_structs + 16;
void *mem = realloc(structs, sizeof(*structs) * num);
if (!mem) {
fprintf(stderr, "Out of memory while registering struct %s\n", str);
exit(1);
}
structs = (StructDeclaration *) mem;
n_allocated_structs = num;
}
if (decl_ptr)
decl_ptr->struct_decl_idx = n_structs;
decl = &structs[n_structs++];
decl->name = strdup(str);
decl->cursor = cursor;
decl->n_entries = 0;
decl->n_allocated_entries = 0;
decl->entries = NULL;
decl->is_union = is_union;
clang_visitChildren(cursor, fill_struct_members, (void *) (n_structs - 1));
}
static int arithmetic_expression(int val1, const char *expr, int val2)
{
assert(expr[1] == 0 || expr[2] == 0);
if (expr[1] == 0) {
switch (expr[0]) {
case '^': return val1 ^ val2;
case '|': return val1 | val2;
case '&': return val1 & val2;
case '+': return val1 + val2;
case '-': return val1 - val2;
case '*': return val1 * val2;
case '/': return val1 / val2;
case '%': return val1 % val2;
default:
fprintf(stderr, "Arithmetic expression '%c' not handled\n",
expr[0]);
exit(1);
}
} else {
#define TWOCHARCODE(a, b) ((a << 8) | b)
#define TWOCHARTAG(expr) (TWOCHARCODE(expr[0], expr[1]))
switch (TWOCHARTAG(expr)) {
case TWOCHARCODE('<', '='): return val1 <= val2;
case TWOCHARCODE('>', '='): return val1 >= val2;
case TWOCHARCODE('!', '='): return val1 != val2;
case TWOCHARCODE('=', '='): return val1 == val2;
case TWOCHARCODE('<', '<'): return val1 << val2;
case TWOCHARCODE('>', '>'): return val1 >> val2;
default:
fprintf(stderr, "Arithmetic expression '%s' not handled\n",
expr);
exit(1);
}
}
fprintf(stderr, "Unknown arithmetic expression %s\n", expr);
exit(1);
}
static int find_enum_value(const char *str)
{
unsigned n, m;
for (n = 0; n < n_enums; n++) {
for (m = 0; m < enums[n].n_entries; m++) {
if (!strcmp(enums[n].entries[m].name, str))
return enums[n].entries[m].value;
}
}
fprintf(stderr, "Unknown enum value %s\n", str);
exit(1);
}
typedef struct FillEnumMemberCache {
int n[3];
char *op;
} FillEnumMemberCache;
static enum CXChildVisitResult fill_enum_value(CXCursor cursor,
CXCursor parent,
CXClientData client_data)
{
FillEnumMemberCache *cache = (FillEnumMemberCache *) client_data;
CXToken *tokens = 0;
unsigned int n_tokens = 0;
CXSourceRange range = clang_getCursorExtent(cursor);
clang_tokenize(TU, range, &tokens, &n_tokens);
if (parent.kind == CXCursor_BinaryOperator && cache->n[0] == 0) {
CXString str = clang_getTokenSpelling(TU, tokens[n_tokens - 1]);
cache->op = strdup(clang_getCString(str));
clang_disposeString(str);
}
switch (cursor.kind) {
case CXCursor_UnaryOperator: {
CXString tsp = clang_getTokenSpelling(TU, tokens[0]);
const char *str = clang_getCString(tsp);
clang_visitChildren(cursor, fill_enum_value, client_data);
assert(str[1] == 0 && (str[0] == '+' || str[0] == '-' || str[0] == '~'));
assert(cache->n[0] == 1);
if (str[0] == '-') {
cache->n[1] = -cache->n[1];
} else if (str[0] == '~') {
cache->n[1] = ~cache->n[1];
}
clang_disposeString(tsp);
break;
}
case CXCursor_BinaryOperator: {
FillEnumMemberCache cache2;
memset(&cache2, 0, sizeof(cache2));
assert(n_tokens >= 4);
clang_visitChildren(cursor, fill_enum_value, &cache2);
assert(cache2.n[0] == 2);
assert(cache2.op != NULL);
cache->n[++cache->n[0]] = arithmetic_expression(cache2.n[1],
cache2.op,
cache2.n[2]);
free(cache2.op);
break;
}
case CXCursor_IntegerLiteral: {
CXString tsp;
const char *str;
char *end;
assert(n_tokens == 2);
tsp = clang_getTokenSpelling(TU, tokens[0]);
str = clang_getCString(tsp);
cache->n[++cache->n[0]] = strtol(str, &end, 0);
assert(end - str == strlen(str) ||
(end - str == strlen(str) - 1 && // str may have a suffix like 'U' that strtol doesn't consume
(*end == 'U' || *end == 'u')));
clang_disposeString(tsp);
break;
}
case CXCursor_DeclRefExpr: {
CXString tsp;
assert(n_tokens == 2);
tsp = clang_getTokenSpelling(TU, tokens[0]);
cache->n[++cache->n[0]] = find_enum_value(clang_getCString(tsp));
clang_disposeString(tsp);
break;
}
case CXCursor_CharacterLiteral: {
CXString spelling;
const char *str;
assert(n_tokens == 2);
spelling = clang_getTokenSpelling(TU, tokens[0]);
str = clang_getCString(spelling);
assert(strlen(str) == 3 && str[0] == '\'' && str[2] == '\'');
cache->n[++cache->n[0]] = str[1];
clang_disposeString(spelling);
break;
}
case CXCursor_ParenExpr:
clang_visitChildren(cursor, fill_enum_value, client_data);
break;
default:
break;
}
clang_disposeTokens(TU, tokens, n_tokens);
return CXChildVisit_Continue;
}
static enum CXChildVisitResult fill_enum_members(CXCursor cursor,
CXCursor parent,
CXClientData client_data)
{
EnumDeclaration *decl = (EnumDeclaration *) client_data;
if (cursor.kind == CXCursor_EnumConstantDecl) {
CXString cstr = clang_getCursorSpelling(cursor);
const char *str = clang_getCString(cstr);
unsigned n = decl->n_entries;
FillEnumMemberCache cache;
memset(&cache, 0, sizeof(cache));
if (decl->n_entries == decl->n_allocated_entries) {
unsigned num = decl->n_allocated_entries + 16;
void *mem = realloc(decl->entries,
sizeof(*decl->entries) * num);
if (!mem) {
fprintf(stderr,
"Ran out of memory while declaring field %s in %s\n",
str, decl->name);
exit(1);
}
decl->entries = (EnumMember *) mem;
decl->n_allocated_entries = num;
}
decl->entries[n].name = strdup(str);
decl->entries[n].cursor = cursor;
clang_visitChildren(cursor, fill_enum_value, &cache);
assert(cache.n[0] <= 1);
if (cache.n[0] == 1) {
decl->entries[n].value = cache.n[1];
} else if (n == 0) {
decl->entries[n].value = 0;
} else {
decl->entries[n].value = decl->entries[n - 1].value + 1;
}
decl->n_entries++;
clang_disposeString(cstr);
}
return CXChildVisit_Continue;
}
static void register_enum(const char *str, CXCursor cursor,
TypedefDeclaration *decl_ptr)
{
unsigned n;
EnumDeclaration *decl;
for (n = 0; n < n_enums; n++) {
if ((str[0] != 0 && !strcmp(enums[n].name, str)) ||
!memcmp(&cursor, &enums[n].cursor, sizeof(cursor))) {
/* already exists */
if (decl_ptr)
decl_ptr->enum_decl_idx = n;
return;
}
}
if (n_enums == n_allocated_enums) {
unsigned num = n_allocated_enums + 16;
void *mem = realloc(enums, sizeof(*enums) * num);
if (!mem) {
fprintf(stderr, "Out of memory while registering enum %s\n", str);
exit(1);
}
enums = (EnumDeclaration *) mem;
n_allocated_enums = num;
}
if (decl_ptr)
decl_ptr->enum_decl_idx = n_enums;
decl = &enums[n_enums++];
decl->name = strdup(str);
decl->cursor = cursor;
decl->n_entries = 0;
decl->n_allocated_entries = 0;
decl->entries = NULL;
clang_visitChildren(cursor, fill_enum_members, decl);
}
static void register_typedef(const char *name,
CXToken *tokens, unsigned n_tokens,
TypedefDeclaration *decl, CXCursor cursor)
{
unsigned n;
if (n_typedefs == n_allocated_typedefs) {
unsigned num = n_allocated_typedefs + 16;
void *mem = realloc(typedefs, sizeof(*typedefs) * num);
if (!mem) {
fprintf(stderr, "Ran out of memory while declaring typedef %s\n",
name);
exit(1);
}
n_allocated_typedefs = num;
typedefs = (TypedefDeclaration *) mem;
}
n = n_typedefs++;
typedefs[n].name = strdup(name);
if (decl->struct_decl_idx != (unsigned) -1) {
typedefs[n].struct_decl_idx = decl->struct_decl_idx;
typedefs[n].proxy = NULL;
typedefs[n].enum_decl_idx = (unsigned) -1;
} else if (decl->enum_decl_idx != (unsigned) -1) {
typedefs[n].enum_decl_idx = decl->enum_decl_idx;
typedefs[n].struct_decl_idx = (unsigned) -1;
typedefs[n].proxy = NULL;
} else {
typedefs[n].enum_decl_idx = (unsigned) -1;
typedefs[n].struct_decl_idx = (unsigned) -1;
typedefs[n].proxy = concat_name(tokens, 1, n_tokens - 3);
}
memcpy(&typedefs[n].cursor, &cursor, sizeof(cursor));
}
static unsigned get_token_offset(CXToken token)
{
CXSourceLocation l = clang_getTokenLocation(TU, token);
CXFile file;
unsigned line, col, off;
clang_getSpellingLocation(l, &file, &line, &col, &off);
return off;
}
static unsigned find_struct_decl_idx_by_name(const char *name)
{
unsigned n;
for (n = 0; n < n_structs; n++) {
if (!strcmp(name, structs[n].name))
return n;
}
return (unsigned) -1;
}
static void resolve_proxy(TypedefDeclaration *decl)
{
if (decl->struct_decl_idx != (unsigned) -1 ||
decl->enum_decl_idx != (unsigned) -1)
return;
decl->struct_decl_idx = find_struct_decl_idx_for_type_name(decl->proxy);
// we could theoretically also resolve the enum, but we wouldn't use
// that information, so let's just not
}
static TypedefDeclaration *find_typedef_decl_by_name(const char *name)
{
unsigned n;
for (n = 0; n < n_typedefs; n++) {
if (!strcmp(name, typedefs[n].name)) {
resolve_proxy(&typedefs[n]);
return &typedefs[n];
}
}
return NULL;
}
// FIXME this function has some duplicate functionality compared to
// fill_struct_members() further up.
static unsigned find_struct_decl_idx(const char *var, CXToken *tokens,
unsigned n_tokens, unsigned *depth)
{
/*
* In the list of tokens that make up a sequence like:
* 'static const struct str_type name = { val }',
* A) find the token that contains 'var', get the type (token before that)
* B) check the tokens before that one to see if type is a struct
* C) if not, check if the type is a typedef and go back to (B)
* D) if type is a struct, return that type's StructDeclaration;
* if type is not a struct and not a typedef, return NULL.
*/
unsigned n, var_tok_idx;
*depth = 0;
for (n = 0; n < n_tokens; n++) {
CXString spelling = clang_getTokenSpelling(TU, tokens[n]);
int res = strcmp(clang_getCString(spelling), var);
clang_disposeString(spelling);
if (!res)
break;
}
if (n == n_tokens)
return (unsigned) -1;
var_tok_idx = n;
for (n = var_tok_idx + 1; n < n_tokens; n++) {
CXString spelling = clang_getTokenSpelling(TU, tokens[n]);
int res = strcmp(clang_getCString(spelling), "=");
if (!strcmp(clang_getCString(spelling), "["))
(*depth)++;
clang_disposeString(spelling);
if (!res)
break;
}
// is it a struct?
if (var_tok_idx > 1) {
CXString spelling;
int res;
spelling = clang_getTokenSpelling(TU, tokens[var_tok_idx - 2]);
res = strcmp(clang_getCString(spelling), "struct");
clang_disposeString(spelling);
if (!res) {
unsigned str_decl;
spelling = clang_getTokenSpelling(TU, tokens[var_tok_idx - 1]);
str_decl = find_struct_decl_idx_by_name(clang_getCString(spelling));
clang_disposeString(spelling);
return str_decl;
}
}
// is it a typedef?
if (var_tok_idx > 0) {
CXString spelling;
TypedefDeclaration *td_decl;
spelling = clang_getTokenSpelling(TU, tokens[var_tok_idx - 1]);
td_decl = find_typedef_decl_by_name(clang_getCString(spelling));
clang_disposeString(spelling);
if (td_decl && td_decl->struct_decl_idx != (unsigned) -1)
return td_decl->struct_decl_idx;
}
return (unsigned) -1;
}
static unsigned find_member_index_in_struct(StructDeclaration *str_decl,
const char *member)
{
unsigned n;
for (n = 0; n < str_decl->n_entries; n++) {
if (!strcmp(str_decl->entries[n].name, member))
return n;
}
return -1;
}
static unsigned find_struct_decl_idx_for_type_name(const char *name)
{
if (!strncmp(name, "const ", 6))
name += 6;
if (!strncmp(name, "struct ", 7)) {
return find_struct_decl_idx_by_name(name + 7);
} else if (!strncmp(name, "union ", 6)) {
return find_struct_decl_idx_by_name(name + 6);
} else {
TypedefDeclaration *decl = find_typedef_decl_by_name(name);
return decl ? decl->struct_decl_idx : (unsigned) -1;
}
}
/*
* Structure to keep track of compound literals that we eventually want
* to replace with something else.
*/
enum CLType {
TYPE_UNKNOWN = 0,
TYPE_OMIT_CAST, // AVRational x = (AVRational) { y, z }
// -> AVRational x = { y, z }
TYPE_TEMP_ASSIGN, // AVRational x; [..] x = (AVRational) { y, z }
// -> [..] { AVRational tmp = { y, z }; x = tmp; }
// can also be used for return
TYPE_CONST_DECL, // anything with a const that can be statically
// declared, e.g. x = ((const int[]){ y, z })[0] ->
// static const int tmp[] = { y, z } [..] x = tmp[0]
TYPE_NEW_CONTEXT, // func(); int x; [..] -> func(); { int x; [..] }
TYPE_LOOP_CONTEXT, // for(int i = 0; ... -> { int i = 0; for (; ... }
};
typedef struct {
enum CLType type;
struct {
unsigned start, end; // to get the values
} value_token, cast_token, context;
unsigned cast_token_array_start;
unsigned struct_decl_idx; // struct type
union {
struct {
char *tmp_var_name; // temporary variable name for the constant
// data, assigned in the first stage (var
// declaration), and used in the second stage
// (replacement of the CL with the var ref)
} t_c_d;
} data;
} CompoundLiteralList;
static CompoundLiteralList *comp_literal_lists = NULL;
static unsigned n_comp_literal_lists = 0;
static unsigned n_allocated_comp_literal_lists = 0;
/*
* Helper struct for traversing the tree. This allows us to keep state
* beyond the current and parent node.
*/
typedef struct CursorRecursion CursorRecursion;
struct CursorRecursion {
enum CXCursorKind kind;
CursorRecursion *parent;
unsigned child_cntr;
unsigned allow_var_decls;
CXToken *tokens;
unsigned n_tokens;
union {
void *opaque;
unsigned sal_idx; // InitListExpr and UnexposedExpr
// after an InitListExpr
struct {
unsigned struct_decl_idx;
unsigned array_depth;
} var_decl_data; // VarDecl
TypedefDeclaration *td_decl; // TypedefDecl
unsigned cl_idx; // CompoundLiteralExpr
} data;
int is_function;
int end_scopes;
};
static unsigned find_encompassing_struct_decl(unsigned start, unsigned end,
StructArrayList **ptr,
CursorRecursion *rec,
unsigned *depth)
{
/*
* In previously registered arrays/structs, find one with a start-end
* that fully contains the given start/end function arguments. If found,
* return that array/struct's type. If not found, return NULL.
*/
unsigned n;
*depth = 0;
*ptr = NULL;
for (n = n_struct_array_lists - 1; n != (unsigned) -1; n--) {
if (start >= struct_array_lists[n].value_offset.start &&
end <= struct_array_lists[n].value_offset.end &&
!(start == struct_array_lists[n].value_offset.start &&
end == struct_array_lists[n].value_offset.end)) {
if (struct_array_lists[n].type == TYPE_ARRAY) {
/* { <- parent
* [..] = { .. }, <- us
* } */
assert((rec->parent->kind == CXCursor_UnexposedExpr &&
rec->parent->parent->kind == CXCursor_InitListExpr) ||
rec->parent->kind == CXCursor_InitListExpr);
*ptr = &struct_array_lists[n];
assert(struct_array_lists[n].array_depth > 0);
*depth = struct_array_lists[n].array_depth - 1;
return struct_array_lists[n].struct_decl_idx;
} else if (struct_array_lists[n].type == TYPE_STRUCT) {
/* { <- parent
* .member = { .. }, <- us
* } */
unsigned m;
StructArrayList *l = *ptr = &struct_array_lists[n];
assert((rec->parent->kind == CXCursor_UnexposedExpr &&
rec->parent->parent->kind == CXCursor_InitListExpr) ||
rec->parent->kind == CXCursor_InitListExpr);
assert(l->array_depth == 0);
for (m = 0; m <= l->n_entries; m++) {
if (start >= l->entries[m].expression_offset.start &&
end <= l->entries[m].expression_offset.end) {
unsigned s_idx = l->struct_decl_idx;
unsigned m_idx = l->entries[m].index;
*depth = structs[s_idx].entries[m_idx].array_depth;
return structs[s_idx].entries[m_idx].struct_decl_idx;
}
}
// Can this ever trigger?
return (unsigned) -1;
} else if (rec->parent->kind == CXCursor_InitListExpr) {
/* { <- parent
* { .. }, <- us (so now the question is: array or struct?)
* } */
StructArrayList *l = *ptr = &struct_array_lists[n];
unsigned s_idx = l->struct_decl_idx;
unsigned m_idx = rec->parent->child_cntr - 1;