Debian Codegraph @

tests/test_c_parser.py

raw
1 #!/usr/bin/env python
2
3 import os
4 import io
5 import unittest
6 from pycparser import c_parser
7 from pycparser.c_ast import *
8
9 ParseError = c_parser.ParseError
10
11 _c_parser = c_parser.CParser()
12
13
14 def expand_decl(decl):
15 """Converts the declaration into a nested list."""
16 typ = type(decl)
17
18 if typ == TypeDecl:
19 return ["TypeDecl", expand_decl(decl.type)]
20 elif typ == IdentifierType:
21 return ["IdentifierType", decl.names]
22 elif typ == ID:
23 return ["ID", decl.name]
24 elif typ in [Struct, Union]:
25 decls = [expand_decl(d) for d in decl.decls or []]
26 return [typ.__name__, decl.name, decls]
27 elif typ == Enum:
28 if decl.values is None:
29 values = None
30 else:
31 assert isinstance(decl.values, EnumeratorList)
32 values = [enum.name for enum in decl.values.enumerators]
33 return ["Enum", decl.name, values]
34 elif typ == Alignas:
35 return ["Alignas", expand_init(decl.alignment)]
36 elif typ == StaticAssert:
37 if decl.message:
38 return ["StaticAssert", decl.cond.value, decl.message.value]
39 else:
40 return ["StaticAssert", decl.cond.value]
41 else:
42 nested = expand_decl(decl.type)
43
44 if typ == Decl:
45 r = ["Decl"]
46 if decl.quals:
47 r.append(decl.quals)
48 if decl.align:
49 r.append(expand_decl(decl.align[0]))
50 r.extend([decl.name, nested])
51 return r
52 elif typ == Typename: # for function parameters
53 if decl.quals:
54 return ["Typename", decl.quals, nested]
55 else:
56 return ["Typename", nested]
57 elif typ == ArrayDecl:
58 dimval = decl.dim.value if decl.dim else ""
59 return ["ArrayDecl", dimval, decl.dim_quals, nested]
60 elif typ == PtrDecl:
61 if decl.quals:
62 return ["PtrDecl", decl.quals, nested]
63 else:
64 return ["PtrDecl", nested]
65 elif typ == Typedef:
66 return ["Typedef", decl.name, nested]
67 elif typ == FuncDecl:
68 if decl.args:
69 params = [expand_decl(param) for param in decl.args.params]
70 else:
71 params = []
72 return ["FuncDecl", params, nested]
73
74
75 def expand_init(init):
76 """Converts an initialization into a nested list"""
77 typ = type(init)
78
79 if typ == NamedInitializer:
80 des = [expand_init(dp) for dp in init.name]
81 return (des, expand_init(init.expr))
82 elif typ in (InitList, ExprList):
83 return [expand_init(expr) for expr in init.exprs]
84 elif typ == Constant:
85 return ["Constant", init.type, init.value]
86 elif typ == ID:
87 return ["ID", init.name]
88 elif typ == Decl:
89 return ["Decl", init.name]
90 elif typ == UnaryOp:
91 return ["UnaryOp", init.op, expand_decl(init.expr)]
92 elif typ == BinaryOp:
93 return ["BinaryOp", expand_init(init.left), init.op, expand_init(init.right)]
94 elif typ == Compound:
95 blocks = []
96 if init.block_items:
97 blocks = [expand_init(i) for i in init.block_items]
98 return ["Compound", blocks]
99 elif typ == Typename:
100 return expand_decl(init)
101 else:
102 # Fallback to type name
103 return [typ.__name__]
104
105
106 class TestCParser_base(unittest.TestCase):
107 def parse(self, txt, filename=""):
108 return self.cparser.parse(txt, filename)
109
110 def setUp(self):
111 self.cparser = _c_parser
112
113 def assert_coord(self, node, line, column=None, file=None):
114 self.assertEqual(node.coord.line, line)
115 if column is not None:
116 self.assertEqual(node.coord.column, column)
117 if file:
118 self.assertEqual(node.coord.file, file)
119
120
121 class TestCParser_fundamentals(TestCParser_base):
122 def get_decl(self, txt, index=0):
123 """Given a source and an index returns the expanded
124 declaration at that index.
125
126 FileAST holds a list of 'external declarations'.
127 index is the offset of the desired declaration in that
128 list.
129 """
130 t = self.parse(txt).ext[index]
131 return expand_decl(t)
132
133 def get_decl_init(self, txt, index=0):
134 """Returns the expanded initializer of the declaration
135 at index.
136 """
137 t = self.parse(txt).ext[index]
138 return expand_init(t.init)
139
140 def test_FileAST(self):
141 t = self.parse("int a; char c;")
142 self.assertIsInstance(t, FileAST)
143 self.assertEqual(len(t.ext), 2)
144
145 # empty file
146 t2 = self.parse("")
147 self.assertIsInstance(t2, FileAST)
148 self.assertEqual(len(t2.ext), 0)
149
150 def test_empty_toplevel_decl(self):
151 code = "int foo;;"
152 t = self.parse(code)
153 self.assertIsInstance(t, FileAST)
154 self.assertEqual(len(t.ext), 1)
155 self.assertEqual(
156 self.get_decl(code),
157 ["Decl", "foo", ["TypeDecl", ["IdentifierType", ["int"]]]],
158 )
159
160 def test_initial_semi(self):
161 t = self.parse(";")
162 self.assertEqual(len(t.ext), 0)
163 t = self.parse(";int foo;")
164 self.assertEqual(len(t.ext), 1)
165 self.assertEqual(
166 expand_decl(t.ext[0]),
167 ["Decl", "foo", ["TypeDecl", ["IdentifierType", ["int"]]]],
168 )
169
170 def test_coords(self):
171 """Tests the "coordinates" of parsed elements - file
172 name, line and column numbers, with modification
173 inserted by #line directives.
174 """
175 self.assert_coord(self.parse("int a;").ext[0], 1, 5)
176
177 t1 = """
178 int a;
179 int b;\n\n
180 int c;
181 """
182 f1 = self.parse(t1, filename="test.c")
183 self.assert_coord(f1.ext[0], 2, 13, "test.c")
184 self.assert_coord(f1.ext[1], 3, 13, "test.c")
185 self.assert_coord(f1.ext[2], 6, 13, "test.c")
186
187 t1_1 = """
188 int main() {
189 k = p;
190 printf("%d", b);
191 return 0;
192 }"""
193 f1_1 = self.parse(t1_1, filename="test.c")
194 self.assert_coord(f1_1.ext[0].body.block_items[0], 3, 13, "test.c")
195 self.assert_coord(f1_1.ext[0].body.block_items[1], 4, 13, "test.c")
196
197 t1_2 = """
198 int main () {
199 int p = (int) k;
200 }"""
201 f1_2 = self.parse(t1_2, filename="test.c")
202 # make sure that the Cast has a coord (issue 23)
203 self.assert_coord(f1_2.ext[0].body.block_items[0].init, 3, 21, file="test.c")
204
205 t2 = """
206 #line 99
207 int c;
208 """
209 self.assert_coord(self.parse(t2).ext[0], 99, 13)
210
211 t3 = """
212 int dsf;
213 char p;
214 #line 3000 "in.h"
215 char d;
216 """
217 f3 = self.parse(t3, filename="test.c")
218 self.assert_coord(f3.ext[0], 2, 13, "test.c")
219 self.assert_coord(f3.ext[1], 3, 14, "test.c")
220 self.assert_coord(f3.ext[2], 3000, 14, "in.h")
221
222 t4 = """
223 #line 20 "restore.h"
224 int maydler(char);
225
226 #line 30 "includes/daween.ph"
227 long j, k;
228
229 #line 50000
230 char* ro;
231 """
232 f4 = self.parse(t4, filename="myb.c")
233 self.assert_coord(f4.ext[0], 20, 13, "restore.h")
234 self.assert_coord(f4.ext[1], 30, 14, "includes/daween.ph")
235 self.assert_coord(f4.ext[2], 30, 17, "includes/daween.ph")
236 self.assert_coord(f4.ext[3], 50000, 13, "includes/daween.ph")
237
238 t5 = """
239 int
240 #line 99
241 c;
242 """
243 self.assert_coord(self.parse(t5).ext[0], 99, 9)
244
245 # coord for ellipsis
246 t6 = """
247 int foo(int j,
248 ...) {
249 }"""
250 self.assert_coord(self.parse(t6).ext[0].decl.type.args.params[1], 3, 17)
251
252 def test_forloop_coord(self):
253 t = """\
254 void foo() {
255 for(int z=0; z<4;
256 z++){}
257 }
258 """
259 s = self.parse(t, filename="f.c")
260 forloop = s.ext[0].body.block_items[0]
261 self.assert_coord(forloop.init, 2, 13, "f.c")
262 self.assert_coord(forloop.cond, 2, 26, "f.c")
263 self.assert_coord(forloop.next, 3, 17, "f.c")
264
265 def test_simple_decls(self):
266 self.assertEqual(
267 self.get_decl("int a;"),
268 ["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]],
269 )
270
271 self.assertEqual(
272 self.get_decl("unsigned int a;"),
273 ["Decl", "a", ["TypeDecl", ["IdentifierType", ["unsigned", "int"]]]],
274 )
275
276 self.assertEqual(
277 self.get_decl("_Bool a;"),
278 ["Decl", "a", ["TypeDecl", ["IdentifierType", ["_Bool"]]]],
279 )
280
281 self.assertEqual(
282 self.get_decl("float _Complex fcc;"),
283 ["Decl", "fcc", ["TypeDecl", ["IdentifierType", ["float", "_Complex"]]]],
284 )
285
286 self.assertEqual(
287 self.get_decl("char* string;"),
288 ["Decl", "string", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]],
289 )
290
291 self.assertEqual(
292 self.get_decl("long ar[15];"),
293 [
294 "Decl",
295 "ar",
296 ["ArrayDecl", "15", [], ["TypeDecl", ["IdentifierType", ["long"]]]],
297 ],
298 )
299
300 self.assertEqual(
301 self.get_decl("long long ar[15];"),
302 [
303 "Decl",
304 "ar",
305 [
306 "ArrayDecl",
307 "15",
308 [],
309 ["TypeDecl", ["IdentifierType", ["long", "long"]]],
310 ],
311 ],
312 )
313
314 self.assertEqual(
315 self.get_decl("unsigned ar[];"),
316 [
317 "Decl",
318 "ar",
319 ["ArrayDecl", "", [], ["TypeDecl", ["IdentifierType", ["unsigned"]]]],
320 ],
321 )
322
323 self.assertEqual(
324 self.get_decl("int strlen(char* s);"),
325 [
326 "Decl",
327 "strlen",
328 [
329 "FuncDecl",
330 [
331 [
332 "Decl",
333 "s",
334 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]],
335 ]
336 ],
337 ["TypeDecl", ["IdentifierType", ["int"]]],
338 ],
339 ],
340 )
341
342 self.assertEqual(
343 self.get_decl("int strcmp(char* s1, char* s2);"),
344 [
345 "Decl",
346 "strcmp",
347 [
348 "FuncDecl",
349 [
350 [
351 "Decl",
352 "s1",
353 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]],
354 ],
355 [
356 "Decl",
357 "s2",
358 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]],
359 ],
360 ],
361 ["TypeDecl", ["IdentifierType", ["int"]]],
362 ],
363 ],
364 )
365
366 # function return values and parameters may not have type information
367 self.assertEqual(
368 self.get_decl("extern foobar(foo, bar);"),
369 [
370 "Decl",
371 "foobar",
372 [
373 "FuncDecl",
374 [["ID", "foo"], ["ID", "bar"]],
375 ["TypeDecl", ["IdentifierType", ["int"]]],
376 ],
377 ],
378 )
379
380 def test_int128(self):
381 self.assertEqual(
382 self.get_decl("__int128 a;"),
383 ["Decl", "a", ["TypeDecl", ["IdentifierType", ["__int128"]]]],
384 )
385
386 def test_nested_decls(self): # the fun begins
387 self.assertEqual(
388 self.get_decl("char** ar2D;"),
389 [
390 "Decl",
391 "ar2D",
392 ["PtrDecl", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]],
393 ],
394 )
395
396 self.assertEqual(
397 self.get_decl("int (*a)[1][2];"),
398 [
399 "Decl",
400 "a",
401 [
402 "PtrDecl",
403 [
404 "ArrayDecl",
405 "1",
406 [],
407 [
408 "ArrayDecl",
409 "2",
410 [],
411 ["TypeDecl", ["IdentifierType", ["int"]]],
412 ],
413 ],
414 ],
415 ],
416 )
417
418 self.assertEqual(
419 self.get_decl("int *a[1][2];"),
420 [
421 "Decl",
422 "a",
423 [
424 "ArrayDecl",
425 "1",
426 [],
427 [
428 "ArrayDecl",
429 "2",
430 [],
431 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["int"]]]],
432 ],
433 ],
434 ],
435 )
436
437 self.assertEqual(
438 self.get_decl("char* const* p;"),
439 [
440 "Decl",
441 "p",
442 [
443 "PtrDecl",
444 ["PtrDecl", ["const"], ["TypeDecl", ["IdentifierType", ["char"]]]],
445 ],
446 ],
447 )
448
449 self.assertEqual(
450 self.get_decl("const char* const* p;"),
451 [
452 "Decl",
453 ["const"],
454 "p",
455 [
456 "PtrDecl",
457 ["PtrDecl", ["const"], ["TypeDecl", ["IdentifierType", ["char"]]]],
458 ],
459 ],
460 )
461
462 self.assertEqual(
463 self.get_decl("char* * const p;"),
464 [
465 "Decl",
466 "p",
467 [
468 "PtrDecl",
469 ["const"],
470 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]],
471 ],
472 ],
473 )
474
475 self.assertEqual(
476 self.get_decl("char ***ar3D[40];"),
477 [
478 "Decl",
479 "ar3D",
480 [
481 "ArrayDecl",
482 "40",
483 [],
484 [
485 "PtrDecl",
486 [
487 "PtrDecl",
488 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]],
489 ],
490 ],
491 ],
492 ],
493 )
494
495 self.assertEqual(
496 self.get_decl("char (***ar3D)[40];"),
497 [
498 "Decl",
499 "ar3D",
500 [
501 "PtrDecl",
502 [
503 "PtrDecl",
504 [
505 "PtrDecl",
506 [
507 "ArrayDecl",
508 "40",
509 [],
510 ["TypeDecl", ["IdentifierType", ["char"]]],
511 ],
512 ],
513 ],
514 ],
515 ],
516 )
517
518 self.assertEqual(
519 self.get_decl("int (*const*const x)(char, int);"),
520 [
521 "Decl",
522 "x",
523 [
524 "PtrDecl",
525 ["const"],
526 [
527 "PtrDecl",
528 ["const"],
529 [
530 "FuncDecl",
531 [
532 [
533 "Typename",
534 ["TypeDecl", ["IdentifierType", ["char"]]],
535 ],
536 ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]],
537 ],
538 ["TypeDecl", ["IdentifierType", ["int"]]],
539 ],
540 ],
541 ],
542 ],
543 )
544
545 self.assertEqual(
546 self.get_decl("int (*x[4])(char, int);"),
547 [
548 "Decl",
549 "x",
550 [
551 "ArrayDecl",
552 "4",
553 [],
554 [
555 "PtrDecl",
556 [
557 "FuncDecl",
558 [
559 [
560 "Typename",
561 ["TypeDecl", ["IdentifierType", ["char"]]],
562 ],
563 ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]],
564 ],
565 ["TypeDecl", ["IdentifierType", ["int"]]],
566 ],
567 ],
568 ],
569 ],
570 )
571
572 self.assertEqual(
573 self.get_decl("char *(*(**foo [][8])())[];"),
574 [
575 "Decl",
576 "foo",
577 [
578 "ArrayDecl",
579 "",
580 [],
581 [
582 "ArrayDecl",
583 "8",
584 [],
585 [
586 "PtrDecl",
587 [
588 "PtrDecl",
589 [
590 "FuncDecl",
591 [],
592 [
593 "PtrDecl",
594 [
595 "ArrayDecl",
596 "",
597 [],
598 [
599 "PtrDecl",
600 [
601 "TypeDecl",
602 ["IdentifierType", ["char"]],
603 ],
604 ],
605 ],
606 ],
607 ],
608 ],
609 ],
610 ],
611 ],
612 ],
613 )
614
615 # explore named and unnamed function pointer parameters,
616 # with and without qualifiers
617
618 # unnamed w/o quals
619 self.assertEqual(
620 self.get_decl("int (*k)(int);"),
621 [
622 "Decl",
623 "k",
624 [
625 "PtrDecl",
626 [
627 "FuncDecl",
628 [["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]]],
629 ["TypeDecl", ["IdentifierType", ["int"]]],
630 ],
631 ],
632 ],
633 )
634
635 # unnamed w/ quals
636 self.assertEqual(
637 self.get_decl("int (*k)(const int);"),
638 [
639 "Decl",
640 "k",
641 [
642 "PtrDecl",
643 [
644 "FuncDecl",
645 [
646 [
647 "Typename",
648 ["const"],
649 ["TypeDecl", ["IdentifierType", ["int"]]],
650 ]
651 ],
652 ["TypeDecl", ["IdentifierType", ["int"]]],
653 ],
654 ],
655 ],
656 )
657
658 # named w/o quals
659 self.assertEqual(
660 self.get_decl("int (*k)(int q);"),
661 [
662 "Decl",
663 "k",
664 [
665 "PtrDecl",
666 [
667 "FuncDecl",
668 [["Decl", "q", ["TypeDecl", ["IdentifierType", ["int"]]]]],
669 ["TypeDecl", ["IdentifierType", ["int"]]],
670 ],
671 ],
672 ],
673 )
674
675 # named w/ quals
676 self.assertEqual(
677 self.get_decl("int (*k)(const volatile int q);"),
678 [
679 "Decl",
680 "k",
681 [
682 "PtrDecl",
683 [
684 "FuncDecl",
685 [
686 [
687 "Decl",
688 ["const", "volatile"],
689 "q",
690 ["TypeDecl", ["IdentifierType", ["int"]]],
691 ]
692 ],
693 ["TypeDecl", ["IdentifierType", ["int"]]],
694 ],
695 ],
696 ],
697 )
698
699 self.assertEqual(
700 self.get_decl("int (*k)(_Atomic volatile int q);"),
701 [
702 "Decl",
703 "k",
704 [
705 "PtrDecl",
706 [
707 "FuncDecl",
708 [
709 [
710 "Decl",
711 ["_Atomic", "volatile"],
712 "q",
713 ["TypeDecl", ["IdentifierType", ["int"]]],
714 ]
715 ],
716 ["TypeDecl", ["IdentifierType", ["int"]]],
717 ],
718 ],
719 ],
720 )
721
722 self.assertEqual(
723 self.get_decl("int (*k)(const volatile int* q);"),
724 [
725 "Decl",
726 "k",
727 [
728 "PtrDecl",
729 [
730 "FuncDecl",
731 [
732 [
733 "Decl",
734 ["const", "volatile"],
735 "q",
736 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["int"]]]],
737 ]
738 ],
739 ["TypeDecl", ["IdentifierType", ["int"]]],
740 ],
741 ],
742 ],
743 )
744
745 # restrict qualifier
746 self.assertEqual(
747 self.get_decl("int (*k)(restrict int* q);"),
748 [
749 "Decl",
750 "k",
751 [
752 "PtrDecl",
753 [
754 "FuncDecl",
755 [
756 [
757 "Decl",
758 ["restrict"],
759 "q",
760 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["int"]]]],
761 ]
762 ],
763 ["TypeDecl", ["IdentifierType", ["int"]]],
764 ],
765 ],
766 ],
767 )
768
769 def test_func_decls_with_array_dim_qualifiers(self):
770 # named function parameter
771 self.assertEqual(
772 self.get_decl("int zz(int p[static 10]);"),
773 [
774 "Decl",
775 "zz",
776 [
777 "FuncDecl",
778 [
779 [
780 "Decl",
781 "p",
782 [
783 "ArrayDecl",
784 "10",
785 ["static"],
786 ["TypeDecl", ["IdentifierType", ["int"]]],
787 ],
788 ]
789 ],
790 ["TypeDecl", ["IdentifierType", ["int"]]],
791 ],
792 ],
793 )
794 # anonymous function parameter
795 self.assertEqual(
796 self.get_decl("int zz(int [static 10]);"),
797 [
798 "Decl",
799 "zz",
800 [
801 "FuncDecl",
802 [
803 [
804 "Typename",
805 [
806 "ArrayDecl",
807 "10",
808 ["static"],
809 ["TypeDecl", ["IdentifierType", ["int"]]],
810 ],
811 ]
812 ],
813 ["TypeDecl", ["IdentifierType", ["int"]]],
814 ],
815 ],
816 )
817 self.assertEqual(
818 self.get_decl("int zz(int [static const restrict 10]);"),
819 [
820 "Decl",
821 "zz",
822 [
823 "FuncDecl",
824 [
825 [
826 "Typename",
827 [
828 "ArrayDecl",
829 "10",
830 ["static", "const", "restrict"],
831 ["TypeDecl", ["IdentifierType", ["int"]]],
832 ],
833 ]
834 ],
835 ["TypeDecl", ["IdentifierType", ["int"]]],
836 ],
837 ],
838 )
839
840 self.assertEqual(
841 self.get_decl("int zz(int p[const 10]);"),
842 [
843 "Decl",
844 "zz",
845 [
846 "FuncDecl",
847 [
848 [
849 "Decl",
850 "p",
851 [
852 "ArrayDecl",
853 "10",
854 ["const"],
855 ["TypeDecl", ["IdentifierType", ["int"]]],
856 ],
857 ]
858 ],
859 ["TypeDecl", ["IdentifierType", ["int"]]],
860 ],
861 ],
862 )
863
864 self.assertEqual(
865 self.get_decl("int zz(int p[restrict][5]);"),
866 [
867 "Decl",
868 "zz",
869 [
870 "FuncDecl",
871 [
872 [
873 "Decl",
874 "p",
875 [
876 "ArrayDecl",
877 "",
878 ["restrict"],
879 [
880 "ArrayDecl",
881 "5",
882 [],
883 ["TypeDecl", ["IdentifierType", ["int"]]],
884 ],
885 ],
886 ]
887 ],
888 ["TypeDecl", ["IdentifierType", ["int"]]],
889 ],
890 ],
891 )
892
893 self.assertEqual(
894 self.get_decl("int zz(int p[const restrict static 10][5]);"),
895 [
896 "Decl",
897 "zz",
898 [
899 "FuncDecl",
900 [
901 [
902 "Decl",
903 "p",
904 [
905 "ArrayDecl",
906 "10",
907 ["const", "restrict", "static"],
908 [
909 "ArrayDecl",
910 "5",
911 [],
912 ["TypeDecl", ["IdentifierType", ["int"]]],
913 ],
914 ],
915 ]
916 ],
917 ["TypeDecl", ["IdentifierType", ["int"]]],
918 ],
919 ],
920 )
921
922 # unnamed function parameter
923 self.assertEqual(
924 self.get_decl("int zz(int [const 10]);"),
925 [
926 "Decl",
927 "zz",
928 [
929 "FuncDecl",
930 [
931 [
932 "Typename",
933 [
934 "ArrayDecl",
935 "10",
936 ["const"],
937 ["TypeDecl", ["IdentifierType", ["int"]]],
938 ],
939 ]
940 ],
941 ["TypeDecl", ["IdentifierType", ["int"]]],
942 ],
943 ],
944 )
945
946 self.assertEqual(
947 self.get_decl("int zz(int [restrict][5]);"),
948 [
949 "Decl",
950 "zz",
951 [
952 "FuncDecl",
953 [
954 [
955 "Typename",
956 [
957 "ArrayDecl",
958 "",
959 ["restrict"],
960 [
961 "ArrayDecl",
962 "5",
963 [],
964 ["TypeDecl", ["IdentifierType", ["int"]]],
965 ],
966 ],
967 ]
968 ],
969 ["TypeDecl", ["IdentifierType", ["int"]]],
970 ],
971 ],
972 )
973
974 self.assertEqual(
975 self.get_decl("int zz(int [const restrict volatile 10][5]);"),
976 [
977 "Decl",
978 "zz",
979 [
980 "FuncDecl",
981 [
982 [
983 "Typename",
984 [
985 "ArrayDecl",
986 "10",
987 ["const", "restrict", "volatile"],
988 [
989 "ArrayDecl",
990 "5",
991 [],
992 ["TypeDecl", ["IdentifierType", ["int"]]],
993 ],
994 ],
995 ]
996 ],
997 ["TypeDecl", ["IdentifierType", ["int"]]],
998 ],
999 ],
1000 )
1001
1002 def test_qualifiers_storage_specifiers(self):
1003 def assert_qs(txt, index, quals, storage):
1004 d = self.parse(txt).ext[index]
1005 self.assertEqual(d.quals, quals)
1006 self.assertEqual(d.storage, storage)
1007
1008 assert_qs("extern int p;", 0, [], ["extern"])
1009 assert_qs("_Thread_local int p;", 0, [], ["_Thread_local"])
1010 assert_qs("const long p = 6;", 0, ["const"], [])
1011 assert_qs("_Atomic int p;", 0, ["_Atomic"], [])
1012 assert_qs("_Atomic restrict int* p;", 0, ["_Atomic", "restrict"], [])
1013
1014 d1 = "static const int p, q, r;"
1015 for i in range(3):
1016 assert_qs(d1, i, ["const"], ["static"])
1017
1018 d2 = "static char * const p;"
1019 assert_qs(d2, 0, [], ["static"])
1020 pdecl = self.parse(d2).ext[0].type
1021 self.assertIsInstance(pdecl, PtrDecl)
1022 self.assertEqual(pdecl.quals, ["const"])
1023
1024 def test_atomic_specifier(self):
1025 self.assertEqual(
1026 self.get_decl("_Atomic(int) ai;"),
1027 ["Decl", ["_Atomic"], "ai", ["TypeDecl", ["IdentifierType", ["int"]]]],
1028 )
1029
1030 self.assertEqual(
1031 self.get_decl("_Atomic(int*) ai;"),
1032 [
1033 "Decl",
1034 "ai",
1035 ["PtrDecl", ["_Atomic"], ["TypeDecl", ["IdentifierType", ["int"]]]],
1036 ],
1037 )
1038
1039 self.assertEqual(
1040 self.get_decl("_Atomic(_Atomic(int)*) aai;"),
1041 [
1042 "Decl",
1043 ["_Atomic"],
1044 "aai",
1045 ["PtrDecl", ["_Atomic"], ["TypeDecl", ["IdentifierType", ["int"]]]],
1046 ],
1047 )
1048
1049 # Multiple declarations with _Atomic(...)
1050 s = "_Atomic(int) foo, bar;"
1051 self.assertEqual(
1052 self.get_decl(s, 0),
1053 ["Decl", ["_Atomic"], "foo", ["TypeDecl", ["IdentifierType", ["int"]]]],
1054 )
1055 self.assertEqual(
1056 self.get_decl(s, 1),
1057 ["Decl", ["_Atomic"], "bar", ["TypeDecl", ["IdentifierType", ["int"]]]],
1058 )
1059
1060 # typedefs with _Atomic specifiers.
1061 s = "typedef _Atomic(int) atomic_int;"
1062 self.assertEqual(
1063 self.get_decl(s, 0),
1064 ["Typedef", "atomic_int", ["TypeDecl", ["IdentifierType", ["int"]]]],
1065 )
1066
1067 s = "typedef _Atomic(_Atomic(_Atomic(int (*)(void)) *) *) t;"
1068 self.assertEqual(
1069 self.get_decl(s, 0),
1070 [
1071 "Typedef",
1072 "t",
1073 [
1074 "PtrDecl",
1075 ["_Atomic"],
1076 [
1077 "PtrDecl",
1078 ["_Atomic"],
1079 [
1080 "PtrDecl",
1081 ["_Atomic"],
1082 [
1083 "FuncDecl",
1084 [
1085 [
1086 "Typename",
1087 ["TypeDecl", ["IdentifierType", ["void"]]],
1088 ]
1089 ],
1090 ["TypeDecl", ["IdentifierType", ["int"]]],
1091 ],
1092 ],
1093 ],
1094 ],
1095 ],
1096 )
1097
1098 def test_sizeof(self):
1099 e = """
1100 void foo()
1101 {
1102 int a = sizeof k;
1103 int b = sizeof(int);
1104 int c = sizeof(int**);;
1105
1106 char* p = "just to make sure this parses w/o error...";
1107 int d = sizeof(int());
1108 }
1109 """
1110 compound = self.parse(e).ext[0].body
1111
1112 s1 = compound.block_items[0].init
1113 self.assertIsInstance(s1, UnaryOp)
1114 self.assertEqual(s1.op, "sizeof")
1115 self.assertIsInstance(s1.expr, ID)
1116 self.assertEqual(s1.expr.name, "k")
1117
1118 s2 = compound.block_items[1].init
1119 self.assertEqual(
1120 expand_decl(s2.expr),
1121 ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]],
1122 )
1123
1124 s3 = compound.block_items[2].init
1125 self.assertEqual(
1126 expand_decl(s3.expr),
1127 [
1128 "Typename",
1129 ["PtrDecl", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["int"]]]]],
1130 ],
1131 )
1132
1133 def test_alignof(self):
1134 r = self.parse("int a = _Alignof(int);")
1135 self.assertEqual(
1136 expand_decl(r.ext[0]),
1137 ["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]],
1138 )
1139 self.assertEqual(
1140 expand_init(r.ext[0].init),
1141 [
1142 "UnaryOp",
1143 "_Alignof",
1144 ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]],
1145 ],
1146 )
1147
1148 self.assertEqual(
1149 expand_decl(self.parse("_Alignas(_Alignof(int)) char a;").ext[0]),
1150 [
1151 "Decl",
1152 [
1153 "Alignas",
1154 [
1155 "UnaryOp",
1156 "_Alignof",
1157 ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]],
1158 ],
1159 ],
1160 "a",
1161 ["TypeDecl", ["IdentifierType", ["char"]]],
1162 ],
1163 )
1164
1165 self.assertEqual(
1166 expand_decl(self.parse("_Alignas(4) char a;").ext[0]),
1167 [
1168 "Decl",
1169 ["Alignas", ["Constant", "int", "4"]],
1170 "a",
1171 ["TypeDecl", ["IdentifierType", ["char"]]],
1172 ],
1173 )
1174
1175 self.assertEqual(
1176 expand_decl(self.parse("_Alignas(int) char a;").ext[0]),
1177 [
1178 "Decl",
1179 ["Alignas", ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]]],
1180 "a",
1181 ["TypeDecl", ["IdentifierType", ["char"]]],
1182 ],
1183 )
1184
1185 def test_alignas_with_typedef_in_struct(self):
1186 # Issue #472
1187 s = """
1188 typedef int test_int;
1189 typedef struct {
1190 _Alignas(int) test_int a1;
1191 } test_struct;
1192 """
1193 ast = self.parse(s)
1194 field = ast.ext[1].type.type.decls[0]
1195 self.assertEqual(field.name, "a1")
1196 self.assertTrue(hasattr(field, "align") and field.align is not None)
1197 self.assertEqual(
1198 expand_decl(field),
1199 [
1200 "Decl",
1201 ["Alignas", ["Typename", ["TypeDecl", ["IdentifierType", ["int"]]]]],
1202 "a1",
1203 ["TypeDecl", ["IdentifierType", ["test_int"]]],
1204 ],
1205 )
1206
1207 def test_offsetof(self):
1208 def expand_ref(n):
1209 if isinstance(n, StructRef):
1210 return ["StructRef", expand_ref(n.name), expand_ref(n.field)]
1211 elif isinstance(n, ArrayRef):
1212 return ["ArrayRef", expand_ref(n.name), expand_ref(n.subscript)]
1213 elif isinstance(n, ID):
1214 return ["ID", n.name]
1215 elif isinstance(n, Constant):
1216 return ["Constant", n.type, n.value]
1217 else:
1218 raise TypeError("Unexpected type " + n.__class__.__name__)
1219
1220 e = """
1221 void foo() {
1222 int a = offsetof(struct S, p);
1223 a.b = offsetof(struct sockaddr, sp) + strlen(bar);
1224 int a = offsetof(struct S, p.q.r);
1225 int a = offsetof(struct S, p[5].q[4][5]);
1226 }
1227 """
1228 compound = self.parse(e).ext[0].body
1229 s1 = compound.block_items[0].init
1230 self.assertIsInstance(s1, FuncCall)
1231 self.assertIsInstance(s1.name, ID)
1232 self.assertEqual(s1.name.name, "offsetof")
1233 self.assertIsInstance(s1.args.exprs[0], Typename)
1234 self.assertIsInstance(s1.args.exprs[1], ID)
1235 s3 = compound.block_items[2].init
1236 self.assertIsInstance(s3.args.exprs[1], StructRef)
1237 self.assertEqual(
1238 expand_ref(s3.args.exprs[1]),
1239 ["StructRef", ["StructRef", ["ID", "p"], ["ID", "q"]], ["ID", "r"]],
1240 )
1241 s4 = compound.block_items[3].init
1242 self.assertIsInstance(s4.args.exprs[1], ArrayRef)
1243 self.assertEqual(
1244 expand_ref(s4.args.exprs[1]),
1245 [
1246 "ArrayRef",
1247 [
1248 "ArrayRef",
1249 [
1250 "StructRef",
1251 ["ArrayRef", ["ID", "p"], ["Constant", "int", "5"]],
1252 ["ID", "q"],
1253 ],
1254 ["Constant", "int", "4"],
1255 ],
1256 ["Constant", "int", "5"],
1257 ],
1258 )
1259
1260 def test_compound_statement(self):
1261 e = """
1262 void foo() {
1263 }
1264 """
1265 compound = self.parse(e).ext[0].body
1266 self.assertIsInstance(compound, Compound)
1267 self.assert_coord(compound, 2)
1268
1269 # The C99 compound literal feature
1270 #
1271 def test_compound_literals(self):
1272 ps1 = self.parse(r"""
1273 void foo() {
1274 p = (long long){k};
1275 tc = (struct jk){.a = {1, 2}, .b[0] = t};
1276 }""")
1277
1278 compound = ps1.ext[0].body.block_items[0].rvalue
1279 self.assertEqual(
1280 expand_decl(compound.type),
1281 ["Typename", ["TypeDecl", ["IdentifierType", ["long", "long"]]]],
1282 )
1283 self.assertEqual(expand_init(compound.init), [["ID", "k"]])
1284
1285 compound = ps1.ext[0].body.block_items[1].rvalue
1286 self.assertEqual(
1287 expand_decl(compound.type), ["Typename", ["TypeDecl", ["Struct", "jk", []]]]
1288 )
1289 self.assertEqual(
1290 expand_init(compound.init),
1291 [
1292 ([["ID", "a"]], [["Constant", "int", "1"], ["Constant", "int", "2"]]),
1293 ([["ID", "b"], ["Constant", "int", "0"]], ["ID", "t"]),
1294 ],
1295 )
1296
1297 def test_parenthesized_compounds(self):
1298 e = self.parse(r"""
1299 void foo() {
1300 int a;
1301 ({});
1302 ({ 1; });
1303 ({ 1; 2; });
1304 int b = ({ 1; });
1305 int c, d = ({ int x = 1; x + 2; });
1306 a = ({ int x = 1; 2 * x; });
1307 }""")
1308 body = e.ext[0].body.block_items
1309
1310 self.assertIsInstance(body[1], Compound)
1311 self.assertEqual(body[1].block_items, None)
1312
1313 self.assertIsInstance(body[2], Compound)
1314 self.assertEqual(len(body[2].block_items), 1)
1315 self.assertIsInstance(body[2].block_items[0], Constant)
1316
1317 self.assertIsInstance(body[3], Compound)
1318 self.assertEqual(len(body[3].block_items), 2)
1319 self.assertIsInstance(body[3].block_items[0], Constant)
1320 self.assertIsInstance(body[3].block_items[1], Constant)
1321
1322 self.assertIsInstance(body[4], Decl)
1323 self.assertEqual(
1324 expand_init(body[4].init), ["Compound", [["Constant", "int", "1"]]]
1325 )
1326
1327 self.assertIsInstance(body[5], Decl)
1328 self.assertEqual(body[5].init, None)
1329
1330 self.assertIsInstance(body[6], Decl)
1331 self.assertEqual(
1332 expand_init(body[6].init),
1333 [
1334 "Compound",
1335 [
1336 ["Decl", "x"],
1337 ["BinaryOp", ["ID", "x"], "+", ["Constant", "int", "2"]],
1338 ],
1339 ],
1340 )
1341
1342 self.assertIsInstance(body[7], Assignment)
1343 self.assertIsInstance(body[7].rvalue, Compound)
1344 self.assertEqual(
1345 expand_init(body[7].rvalue),
1346 [
1347 "Compound",
1348 [
1349 ["Decl", "x"],
1350 ["BinaryOp", ["Constant", "int", "2"], "*", ["ID", "x"]],
1351 ],
1352 ],
1353 )
1354
1355 def test_enums(self):
1356 e1 = "enum mycolor op;"
1357 e1_type = self.parse(e1).ext[0].type.type
1358
1359 self.assertIsInstance(e1_type, Enum)
1360 self.assertEqual(e1_type.name, "mycolor")
1361 self.assertEqual(e1_type.values, None)
1362
1363 e2 = "enum mysize {large=20, small, medium} shoes;"
1364 e2_type = self.parse(e2).ext[0].type.type
1365
1366 self.assertIsInstance(e2_type, Enum)
1367 self.assertEqual(e2_type.name, "mysize")
1368
1369 e2_elist = e2_type.values
1370 self.assertIsInstance(e2_elist, EnumeratorList)
1371
1372 for e2_eval in e2_elist.enumerators:
1373 self.assertIsInstance(e2_eval, Enumerator)
1374
1375 self.assertEqual(e2_elist.enumerators[0].name, "large")
1376 self.assertEqual(e2_elist.enumerators[0].value.value, "20")
1377 self.assertEqual(e2_elist.enumerators[2].name, "medium")
1378 self.assertEqual(e2_elist.enumerators[2].value, None)
1379
1380 # enum with trailing comma (C99 feature)
1381 e3 = """
1382 enum
1383 {
1384 red,
1385 blue,
1386 green,
1387 } color;
1388 """
1389
1390 e3_type = self.parse(e3).ext[0].type.type
1391 self.assertIsInstance(e3_type, Enum)
1392 e3_elist = e3_type.values
1393 self.assertIsInstance(e3_elist, EnumeratorList)
1394
1395 for e3_eval in e3_elist.enumerators:
1396 self.assertIsInstance(e3_eval, Enumerator)
1397
1398 self.assertEqual(e3_elist.enumerators[0].name, "red")
1399 self.assertEqual(e3_elist.enumerators[0].value, None)
1400 self.assertEqual(e3_elist.enumerators[1].name, "blue")
1401 self.assertEqual(e3_elist.enumerators[2].name, "green")
1402
1403 def test_typedef(self):
1404 # without typedef, error
1405 s1 = """
1406 node k;
1407 """
1408 self.assertRaises(ParseError, self.parse, s1)
1409
1410 # now with typedef, works
1411 s2 = """
1412 typedef void* node;
1413 node k;
1414 """
1415 ps2 = self.parse(s2)
1416 self.assertEqual(
1417 expand_decl(ps2.ext[0]),
1418 [
1419 "Typedef",
1420 "node",
1421 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["void"]]]],
1422 ],
1423 )
1424
1425 self.assertEqual(
1426 expand_decl(ps2.ext[1]),
1427 ["Decl", "k", ["TypeDecl", ["IdentifierType", ["node"]]]],
1428 )
1429
1430 s3 = """
1431 typedef int T;
1432 typedef T *pT;
1433
1434 pT aa, bb;
1435 """
1436 ps3 = self.parse(s3)
1437 self.assertEqual(
1438 expand_decl(ps3.ext[3]),
1439 ["Decl", "bb", ["TypeDecl", ["IdentifierType", ["pT"]]]],
1440 )
1441
1442 s4 = """
1443 typedef char* __builtin_va_list;
1444 typedef __builtin_va_list __gnuc_va_list;
1445 """
1446 ps4 = self.parse(s4)
1447 self.assertEqual(
1448 expand_decl(ps4.ext[1]),
1449 [
1450 "Typedef",
1451 "__gnuc_va_list",
1452 ["TypeDecl", ["IdentifierType", ["__builtin_va_list"]]],
1453 ],
1454 )
1455
1456 s5 = """typedef struct tagHash Hash;"""
1457 ps5 = self.parse(s5)
1458 self.assertEqual(
1459 expand_decl(ps5.ext[0]),
1460 ["Typedef", "Hash", ["TypeDecl", ["Struct", "tagHash", []]]],
1461 )
1462
1463 s6 = """typedef int (* const * const T)(void);"""
1464 ps6 = self.parse(s6)
1465 self.assertEqual(
1466 expand_decl(ps6.ext[0]),
1467 [
1468 "Typedef",
1469 "T",
1470 [
1471 "PtrDecl",
1472 ["const"],
1473 [
1474 "PtrDecl",
1475 ["const"],
1476 [
1477 "FuncDecl",
1478 [["Typename", ["TypeDecl", ["IdentifierType", ["void"]]]]],
1479 ["TypeDecl", ["IdentifierType", ["int"]]],
1480 ],
1481 ],
1482 ],
1483 ],
1484 )
1485
1486 def test_struct_union(self):
1487 s1 = """
1488 struct {
1489 int id;
1490 char* name;
1491 } joe;
1492 """
1493
1494 self.assertEqual(
1495 expand_decl(self.parse(s1).ext[0]),
1496 [
1497 "Decl",
1498 "joe",
1499 [
1500 "TypeDecl",
1501 [
1502 "Struct",
1503 None,
1504 [
1505 ["Decl", "id", ["TypeDecl", ["IdentifierType", ["int"]]]],
1506 [
1507 "Decl",
1508 "name",
1509 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]],
1510 ],
1511 ],
1512 ],
1513 ],
1514 ],
1515 )
1516
1517 s2 = """
1518 struct node p;
1519 """
1520 self.assertEqual(
1521 expand_decl(self.parse(s2).ext[0]),
1522 ["Decl", "p", ["TypeDecl", ["Struct", "node", []]]],
1523 )
1524
1525 s21 = """
1526 union pri ra;
1527 """
1528 self.assertEqual(
1529 expand_decl(self.parse(s21).ext[0]),
1530 ["Decl", "ra", ["TypeDecl", ["Union", "pri", []]]],
1531 )
1532
1533 s3 = """
1534 struct node* p;
1535 """
1536 self.assertEqual(
1537 expand_decl(self.parse(s3).ext[0]),
1538 ["Decl", "p", ["PtrDecl", ["TypeDecl", ["Struct", "node", []]]]],
1539 )
1540
1541 s4 = """
1542 struct node;
1543 """
1544 self.assertEqual(
1545 expand_decl(self.parse(s4).ext[0]), ["Decl", None, ["Struct", "node", []]]
1546 )
1547
1548 s5 = """
1549 union
1550 {
1551 struct
1552 {
1553 int type;
1554 } n;
1555
1556 struct
1557 {
1558 int type;
1559 int intnode;
1560 } ni;
1561 } u;
1562 """
1563 self.assertEqual(
1564 expand_decl(self.parse(s5).ext[0]),
1565 [
1566 "Decl",
1567 "u",
1568 [
1569 "TypeDecl",
1570 [
1571 "Union",
1572 None,
1573 [
1574 [
1575 "Decl",
1576 "n",
1577 [
1578 "TypeDecl",
1579 [
1580 "Struct",
1581 None,
1582 [
1583 [
1584 "Decl",
1585 "type",
1586 [
1587 "TypeDecl",
1588 ["IdentifierType", ["int"]],
1589 ],
1590 ]
1591 ],
1592 ],
1593 ],
1594 ],
1595 [
1596 "Decl",
1597 "ni",
1598 [
1599 "TypeDecl",
1600 [
1601 "Struct",
1602 None,
1603 [
1604 [
1605 "Decl",
1606 "type",
1607 [
1608 "TypeDecl",
1609 ["IdentifierType", ["int"]],
1610 ],
1611 ],
1612 [
1613 "Decl",
1614 "intnode",
1615 [
1616 "TypeDecl",
1617 ["IdentifierType", ["int"]],
1618 ],
1619 ],
1620 ],
1621 ],
1622 ],
1623 ],
1624 ],
1625 ],
1626 ],
1627 ],
1628 )
1629
1630 s6 = """
1631 typedef struct foo_tag
1632 {
1633 void* data;
1634 } foo, *pfoo;
1635 """
1636 s6_ast = self.parse(s6)
1637
1638 self.assertEqual(
1639 expand_decl(s6_ast.ext[0]),
1640 [
1641 "Typedef",
1642 "foo",
1643 [
1644 "TypeDecl",
1645 [
1646 "Struct",
1647 "foo_tag",
1648 [
1649 [
1650 "Decl",
1651 "data",
1652 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["void"]]]],
1653 ]
1654 ],
1655 ],
1656 ],
1657 ],
1658 )
1659
1660 self.assertEqual(
1661 expand_decl(s6_ast.ext[1]),
1662 [
1663 "Typedef",
1664 "pfoo",
1665 [
1666 "PtrDecl",
1667 [
1668 "TypeDecl",
1669 [
1670 "Struct",
1671 "foo_tag",
1672 [
1673 [
1674 "Decl",
1675 "data",
1676 [
1677 "PtrDecl",
1678 ["TypeDecl", ["IdentifierType", ["void"]]],
1679 ],
1680 ]
1681 ],
1682 ],
1683 ],
1684 ],
1685 ],
1686 )
1687
1688 s7 = r"""
1689 struct _on_exit_args {
1690 void * _fnargs[32];
1691 void * _dso_handle[32];
1692
1693 long _fntypes;
1694 #line 77 "D:\eli\cpp_stuff\libc_include/sys/reent.h"
1695
1696 long _is_cxa;
1697 };
1698 """
1699
1700 s7_ast = self.parse(s7, filename="test.c")
1701 self.assert_coord(s7_ast.ext[0].type.decls[2], 6, 22, "test.c")
1702 self.assert_coord(
1703 s7_ast.ext[0].type.decls[3],
1704 78,
1705 22,
1706 r"D:\eli\cpp_stuff\libc_include/sys/reent.h",
1707 )
1708
1709 s8 = """
1710 typedef enum tagReturnCode {SUCCESS, FAIL} ReturnCode;
1711
1712 typedef struct tagEntry
1713 {
1714 char* key;
1715 char* value;
1716 } Entry;
1717
1718
1719 typedef struct tagNode
1720 {
1721 Entry* entry;
1722
1723 struct tagNode* next;
1724 } Node;
1725
1726 typedef struct tagHash
1727 {
1728 unsigned int table_size;
1729
1730 Node** heads;
1731
1732 } Hash;
1733 """
1734 s8_ast = self.parse(s8)
1735 self.assertEqual(
1736 expand_decl(s8_ast.ext[3]),
1737 [
1738 "Typedef",
1739 "Hash",
1740 [
1741 "TypeDecl",
1742 [
1743 "Struct",
1744 "tagHash",
1745 [
1746 [
1747 "Decl",
1748 "table_size",
1749 ["TypeDecl", ["IdentifierType", ["unsigned", "int"]]],
1750 ],
1751 [
1752 "Decl",
1753 "heads",
1754 [
1755 "PtrDecl",
1756 [
1757 "PtrDecl",
1758 ["TypeDecl", ["IdentifierType", ["Node"]]],
1759 ],
1760 ],
1761 ],
1762 ],
1763 ],
1764 ],
1765 ],
1766 )
1767
1768 def test_struct_enum(self):
1769 s1 = """
1770 struct Foo {
1771 enum Bar { A = 1 };
1772 };
1773 """
1774 self.assertEqual(
1775 expand_decl(self.parse(s1).ext[0]),
1776 ["Decl", None, ["Struct", "Foo", [["Decl", None, ["Enum", "Bar", ["A"]]]]]],
1777 )
1778 s2 = """
1779 struct Foo {
1780 enum Bar { A = 1, B, C } bar;
1781 enum Baz { D = A } baz;
1782 } foo;
1783 """
1784 self.assertEqual(
1785 expand_decl(self.parse(s2).ext[0]),
1786 [
1787 "Decl",
1788 "foo",
1789 [
1790 "TypeDecl",
1791 [
1792 "Struct",
1793 "Foo",
1794 [
1795 [
1796 "Decl",
1797 "bar",
1798 ["TypeDecl", ["Enum", "Bar", ["A", "B", "C"]]],
1799 ],
1800 ["Decl", "baz", ["TypeDecl", ["Enum", "Baz", ["D"]]]],
1801 ],
1802 ],
1803 ],
1804 ],
1805 )
1806
1807 def test_struct_with_extra_semis_inside(self):
1808 s1 = """
1809 struct {
1810 int a;;
1811 } foo;
1812 """
1813 s1_ast = self.parse(s1)
1814 self.assertEqual(
1815 expand_decl(s1_ast.ext[0]),
1816 [
1817 "Decl",
1818 "foo",
1819 [
1820 "TypeDecl",
1821 [
1822 "Struct",
1823 None,
1824 [["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]]],
1825 ],
1826 ],
1827 ],
1828 )
1829
1830 s2 = """
1831 struct {
1832 int a;;;;
1833 float b, c;
1834 ;;
1835 char d;
1836 } foo;
1837 """
1838 s2_ast = self.parse(s2)
1839 self.assertEqual(
1840 expand_decl(s2_ast.ext[0]),
1841 [
1842 "Decl",
1843 "foo",
1844 [
1845 "TypeDecl",
1846 [
1847 "Struct",
1848 None,
1849 [
1850 ["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]],
1851 ["Decl", "b", ["TypeDecl", ["IdentifierType", ["float"]]]],
1852 ["Decl", "c", ["TypeDecl", ["IdentifierType", ["float"]]]],
1853 ["Decl", "d", ["TypeDecl", ["IdentifierType", ["char"]]]],
1854 ],
1855 ],
1856 ],
1857 ],
1858 )
1859
1860 def test_struct_with_initial_semi(self):
1861 s1 = """
1862 struct {
1863 ;int a;
1864 } foo;
1865 """
1866 s1_ast = self.parse(s1)
1867 self.assertEqual(
1868 expand_decl(s1_ast.ext[0]),
1869 [
1870 "Decl",
1871 "foo",
1872 [
1873 "TypeDecl",
1874 [
1875 "Struct",
1876 None,
1877 [["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]]],
1878 ],
1879 ],
1880 ],
1881 )
1882
1883 def test_anonymous_struct_union(self):
1884 s1 = """
1885 union
1886 {
1887 union
1888 {
1889 int i;
1890 long l;
1891 };
1892
1893 struct
1894 {
1895 int type;
1896 int intnode;
1897 };
1898 } u;
1899 """
1900
1901 self.assertEqual(
1902 expand_decl(self.parse(s1).ext[0]),
1903 [
1904 "Decl",
1905 "u",
1906 [
1907 "TypeDecl",
1908 [
1909 "Union",
1910 None,
1911 [
1912 [
1913 "Decl",
1914 None,
1915 [
1916 "Union",
1917 None,
1918 [
1919 [
1920 "Decl",
1921 "i",
1922 ["TypeDecl", ["IdentifierType", ["int"]]],
1923 ],
1924 [
1925 "Decl",
1926 "l",
1927 ["TypeDecl", ["IdentifierType", ["long"]]],
1928 ],
1929 ],
1930 ],
1931 ],
1932 [
1933 "Decl",
1934 None,
1935 [
1936 "Struct",
1937 None,
1938 [
1939 [
1940 "Decl",
1941 "type",
1942 ["TypeDecl", ["IdentifierType", ["int"]]],
1943 ],
1944 [
1945 "Decl",
1946 "intnode",
1947 ["TypeDecl", ["IdentifierType", ["int"]]],
1948 ],
1949 ],
1950 ],
1951 ],
1952 ],
1953 ],
1954 ],
1955 ],
1956 )
1957
1958 s2 = """
1959 struct
1960 {
1961 int i;
1962 union
1963 {
1964 int id;
1965 char* name;
1966 };
1967 float f;
1968 } joe;
1969 """
1970
1971 self.assertEqual(
1972 expand_decl(self.parse(s2).ext[0]),
1973 [
1974 "Decl",
1975 "joe",
1976 [
1977 "TypeDecl",
1978 [
1979 "Struct",
1980 None,
1981 [
1982 ["Decl", "i", ["TypeDecl", ["IdentifierType", ["int"]]]],
1983 [
1984 "Decl",
1985 None,
1986 [
1987 "Union",
1988 None,
1989 [
1990 [
1991 "Decl",
1992 "id",
1993 ["TypeDecl", ["IdentifierType", ["int"]]],
1994 ],
1995 [
1996 "Decl",
1997 "name",
1998 [
1999 "PtrDecl",
2000 [
2001 "TypeDecl",
2002 ["IdentifierType", ["char"]],
2003 ],
2004 ],
2005 ],
2006 ],
2007 ],
2008 ],
2009 ["Decl", "f", ["TypeDecl", ["IdentifierType", ["float"]]]],
2010 ],
2011 ],
2012 ],
2013 ],
2014 )
2015
2016 # ISO/IEC 9899:201x Committee Draft 2010-11-16, N1539
2017 # section 6.7.2.1, par. 19, example 1
2018 s3 = """
2019 struct v {
2020 union {
2021 struct { int i, j; };
2022 struct { long k, l; } w;
2023 };
2024 int m;
2025 } v1;
2026 """
2027
2028 self.assertEqual(
2029 expand_decl(self.parse(s3).ext[0]),
2030 [
2031 "Decl",
2032 "v1",
2033 [
2034 "TypeDecl",
2035 [
2036 "Struct",
2037 "v",
2038 [
2039 [
2040 "Decl",
2041 None,
2042 [
2043 "Union",
2044 None,
2045 [
2046 [
2047 "Decl",
2048 None,
2049 [
2050 "Struct",
2051 None,
2052 [
2053 [
2054 "Decl",
2055 "i",
2056 [
2057 "TypeDecl",
2058 ["IdentifierType", ["int"]],
2059 ],
2060 ],
2061 [
2062 "Decl",
2063 "j",
2064 [
2065 "TypeDecl",
2066 ["IdentifierType", ["int"]],
2067 ],
2068 ],
2069 ],
2070 ],
2071 ],
2072 [
2073 "Decl",
2074 "w",
2075 [
2076 "TypeDecl",
2077 [
2078 "Struct",
2079 None,
2080 [
2081 [
2082 "Decl",
2083 "k",
2084 [
2085 "TypeDecl",
2086 [
2087 "IdentifierType",
2088 ["long"],
2089 ],
2090 ],
2091 ],
2092 [
2093 "Decl",
2094 "l",
2095 [
2096 "TypeDecl",
2097 [
2098 "IdentifierType",
2099 ["long"],
2100 ],
2101 ],
2102 ],
2103 ],
2104 ],
2105 ],
2106 ],
2107 ],
2108 ],
2109 ],
2110 ["Decl", "m", ["TypeDecl", ["IdentifierType", ["int"]]]],
2111 ],
2112 ],
2113 ],
2114 ],
2115 )
2116
2117 s4 = """
2118 struct v {
2119 int i;
2120 float;
2121 } v2;"""
2122 # just make sure this doesn't raise ParseError
2123 self.parse(s4)
2124
2125 def test_struct_members_namespace(self):
2126 """Tests that structure/union member names reside in a separate
2127 namespace and can be named after existing types.
2128 """
2129 s1 = """
2130 typedef int Name;
2131 typedef Name NameArray[10];
2132
2133 struct {
2134 Name Name;
2135 Name NameArray[3];
2136 } sye;
2137
2138 void main(void)
2139 {
2140 sye.Name = 1;
2141 }
2142 """
2143
2144 s1_ast = self.parse(s1)
2145 self.assertEqual(
2146 expand_decl(s1_ast.ext[2]),
2147 [
2148 "Decl",
2149 "sye",
2150 [
2151 "TypeDecl",
2152 [
2153 "Struct",
2154 None,
2155 [
2156 [
2157 "Decl",
2158 "Name",
2159 ["TypeDecl", ["IdentifierType", ["Name"]]],
2160 ],
2161 [
2162 "Decl",
2163 "NameArray",
2164 [
2165 "ArrayDecl",
2166 "3",
2167 [],
2168 ["TypeDecl", ["IdentifierType", ["Name"]]],
2169 ],
2170 ],
2171 ],
2172 ],
2173 ],
2174 ],
2175 )
2176 self.assertEqual(s1_ast.ext[3].body.block_items[0].lvalue.field.name, "Name")
2177
2178 def test_struct_bitfields(self):
2179 # a struct with two bitfields, one unnamed
2180 s1 = """
2181 struct {
2182 int k:6;
2183 int :2;
2184 } joe;
2185 """
2186
2187 parsed_struct = self.parse(s1).ext[0]
2188
2189 # We can see here the name of the decl for the unnamed bitfield is
2190 # None, but expand_decl doesn't show bitfield widths
2191 # ...
2192 self.assertEqual(
2193 expand_decl(parsed_struct),
2194 [
2195 "Decl",
2196 "joe",
2197 [
2198 "TypeDecl",
2199 [
2200 "Struct",
2201 None,
2202 [
2203 ["Decl", "k", ["TypeDecl", ["IdentifierType", ["int"]]]],
2204 ["Decl", None, ["TypeDecl", ["IdentifierType", ["int"]]]],
2205 ],
2206 ],
2207 ],
2208 ],
2209 )
2210
2211 # ...
2212 # so we test them manually
2213 self.assertEqual(parsed_struct.type.type.decls[0].bitsize.value, "6")
2214 self.assertEqual(parsed_struct.type.type.decls[1].bitsize.value, "2")
2215
2216 def test_struct_empty(self):
2217 """
2218 Tests that parsing an empty struct works.
2219
2220 Empty structs do NOT follow C99 (See 6.2.5-20 of the C99 standard).
2221 This is nevertheless supported by some compilers (clang, gcc),
2222 especially when using FORTIFY code.
2223 Some compilers (visual) will fail to compile with an error.
2224 """
2225 # an empty struct. This is NOT C99 compliant
2226 s1 = """
2227 struct foo { };
2228 """
2229
2230 parsed_struct = self.parse(s1).ext[0]
2231 self.assertEqual(
2232 expand_decl(parsed_struct), ["Decl", None, ["Struct", "foo", []]]
2233 )
2234
2235 s2 = """struct { } foo;"""
2236 parsed_struct = self.parse(s2).ext[0]
2237 self.assertEqual(
2238 expand_decl(parsed_struct),
2239 ["Decl", "foo", ["TypeDecl", ["Struct", None, []]]],
2240 )
2241
2242 s3 = """union { } foo;"""
2243 parsed_struct = self.parse(s3).ext[0]
2244 self.assertEqual(
2245 expand_decl(parsed_struct),
2246 ["Decl", "foo", ["TypeDecl", ["Union", None, []]]],
2247 )
2248
2249 def test_tags_namespace(self):
2250 """Tests that the tags of structs/unions/enums reside in a separate namespace and
2251 can be named after existing types.
2252 """
2253 s1 = """
2254 typedef int tagEntry;
2255
2256 struct tagEntry
2257 {
2258 char* key;
2259 char* value;
2260 } Entry;
2261 """
2262
2263 s1_ast = self.parse(s1)
2264 self.assertEqual(
2265 expand_decl(s1_ast.ext[1]),
2266 [
2267 "Decl",
2268 "Entry",
2269 [
2270 "TypeDecl",
2271 [
2272 "Struct",
2273 "tagEntry",
2274 [
2275 [
2276 "Decl",
2277 "key",
2278 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]],
2279 ],
2280 [
2281 "Decl",
2282 "value",
2283 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]],
2284 ],
2285 ],
2286 ],
2287 ],
2288 ],
2289 )
2290
2291 s2 = """
2292 struct tagEntry;
2293
2294 typedef struct tagEntry tagEntry;
2295
2296 struct tagEntry
2297 {
2298 char* key;
2299 char* value;
2300 } Entry;
2301 """
2302
2303 s2_ast = self.parse(s2)
2304 self.assertEqual(
2305 expand_decl(s2_ast.ext[2]),
2306 [
2307 "Decl",
2308 "Entry",
2309 [
2310 "TypeDecl",
2311 [
2312 "Struct",
2313 "tagEntry",
2314 [
2315 [
2316 "Decl",
2317 "key",
2318 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]],
2319 ],
2320 [
2321 "Decl",
2322 "value",
2323 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]],
2324 ],
2325 ],
2326 ],
2327 ],
2328 ],
2329 )
2330
2331 s3 = """
2332 typedef int mytag;
2333
2334 enum mytag {ABC, CDE};
2335 enum mytag joe;
2336 """
2337
2338 s3_type = self.parse(s3).ext[1].type
2339
2340 self.assertIsInstance(s3_type, Enum)
2341 self.assertEqual(s3_type.name, "mytag")
2342
2343 def test_multi_decls(self):
2344 d1 = "int a, b;"
2345
2346 self.assertEqual(
2347 self.get_decl(d1, 0),
2348 ["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]],
2349 )
2350 self.assertEqual(
2351 self.get_decl(d1, 1),
2352 ["Decl", "b", ["TypeDecl", ["IdentifierType", ["int"]]]],
2353 )
2354
2355 d2 = "char* p, notp, ar[4];"
2356 self.assertEqual(
2357 self.get_decl(d2, 0),
2358 ["Decl", "p", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]],
2359 )
2360 self.assertEqual(
2361 self.get_decl(d2, 1),
2362 ["Decl", "notp", ["TypeDecl", ["IdentifierType", ["char"]]]],
2363 )
2364 self.assertEqual(
2365 self.get_decl(d2, 2),
2366 [
2367 "Decl",
2368 "ar",
2369 ["ArrayDecl", "4", [], ["TypeDecl", ["IdentifierType", ["char"]]]],
2370 ],
2371 )
2372
2373 def test_invalid_multiple_types_error(self):
2374 bad = ["int enum {ab, cd} fubr;", "enum kid char brbr;"]
2375
2376 for b in bad:
2377 self.assertRaises(ParseError, self.parse, b)
2378
2379 def test_invalid_typedef_storage_qual_error(self):
2380 """Tests that using typedef as a storage qualifier is correctly flagged
2381 as an error.
2382 """
2383 bad = "typedef const int foo(int a) { return 0; }"
2384 self.assertRaises(ParseError, self.parse, bad)
2385
2386 def test_duplicate_typedef(self):
2387 """Tests that redeclarations of existing types are parsed correctly.
2388 This is non-standard, but allowed by many compilers.
2389 """
2390 d1 = """
2391 typedef int numbertype;
2392 typedef int numbertype;
2393 """
2394
2395 self.assertEqual(
2396 self.get_decl(d1, 0),
2397 ["Typedef", "numbertype", ["TypeDecl", ["IdentifierType", ["int"]]]],
2398 )
2399 self.assertEqual(
2400 self.get_decl(d1, 1),
2401 ["Typedef", "numbertype", ["TypeDecl", ["IdentifierType", ["int"]]]],
2402 )
2403
2404 d2 = """
2405 typedef int (*funcptr)(int x);
2406 typedef int (*funcptr)(int x);
2407 """
2408 self.assertEqual(
2409 self.get_decl(d2, 0),
2410 [
2411 "Typedef",
2412 "funcptr",
2413 [
2414 "PtrDecl",
2415 [
2416 "FuncDecl",
2417 [["Decl", "x", ["TypeDecl", ["IdentifierType", ["int"]]]]],
2418 ["TypeDecl", ["IdentifierType", ["int"]]],
2419 ],
2420 ],
2421 ],
2422 )
2423 self.assertEqual(
2424 self.get_decl(d2, 1),
2425 [
2426 "Typedef",
2427 "funcptr",
2428 [
2429 "PtrDecl",
2430 [
2431 "FuncDecl",
2432 [["Decl", "x", ["TypeDecl", ["IdentifierType", ["int"]]]]],
2433 ["TypeDecl", ["IdentifierType", ["int"]]],
2434 ],
2435 ],
2436 ],
2437 )
2438
2439 d3 = """
2440 typedef int numberarray[5];
2441 typedef int numberarray[5];
2442 """
2443 self.assertEqual(
2444 self.get_decl(d3, 0),
2445 [
2446 "Typedef",
2447 "numberarray",
2448 ["ArrayDecl", "5", [], ["TypeDecl", ["IdentifierType", ["int"]]]],
2449 ],
2450 )
2451 self.assertEqual(
2452 self.get_decl(d3, 1),
2453 [
2454 "Typedef",
2455 "numberarray",
2456 ["ArrayDecl", "5", [], ["TypeDecl", ["IdentifierType", ["int"]]]],
2457 ],
2458 )
2459
2460 def test_decl_inits(self):
2461 d1 = "int a = 16;"
2462 # ~ self.parse(d1).show()
2463 self.assertEqual(
2464 self.get_decl(d1), ["Decl", "a", ["TypeDecl", ["IdentifierType", ["int"]]]]
2465 )
2466 self.assertEqual(self.get_decl_init(d1), ["Constant", "int", "16"])
2467
2468 d1_1 = "float f = 0xEF.56p1;"
2469 self.assertEqual(self.get_decl_init(d1_1), ["Constant", "double", "0xEF.56p1"])
2470
2471 d1_2 = "int bitmask = 0b1001010;"
2472 self.assertEqual(self.get_decl_init(d1_2), ["Constant", "int", "0b1001010"])
2473
2474 d2 = "long ar[] = {7, 8, 9};"
2475 self.assertEqual(
2476 self.get_decl(d2),
2477 [
2478 "Decl",
2479 "ar",
2480 ["ArrayDecl", "", [], ["TypeDecl", ["IdentifierType", ["long"]]]],
2481 ],
2482 )
2483 self.assertEqual(
2484 self.get_decl_init(d2),
2485 [
2486 ["Constant", "int", "7"],
2487 ["Constant", "int", "8"],
2488 ["Constant", "int", "9"],
2489 ],
2490 )
2491
2492 d21 = "long ar[4] = {};"
2493 self.assertEqual(self.get_decl_init(d21), [])
2494
2495 d3 = "char p = j;"
2496 self.assertEqual(
2497 self.get_decl(d3), ["Decl", "p", ["TypeDecl", ["IdentifierType", ["char"]]]]
2498 )
2499 self.assertEqual(self.get_decl_init(d3), ["ID", "j"])
2500
2501 d4 = "char x = 'c', *p = {0, 1, 2, {4, 5}, 6};"
2502 self.assertEqual(
2503 self.get_decl(d4, 0),
2504 ["Decl", "x", ["TypeDecl", ["IdentifierType", ["char"]]]],
2505 )
2506 self.assertEqual(self.get_decl_init(d4, 0), ["Constant", "char", "'c'"])
2507 self.assertEqual(
2508 self.get_decl(d4, 1),
2509 ["Decl", "p", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]]],
2510 )
2511
2512 self.assertEqual(
2513 self.get_decl_init(d4, 1),
2514 [
2515 ["Constant", "int", "0"],
2516 ["Constant", "int", "1"],
2517 ["Constant", "int", "2"],
2518 [["Constant", "int", "4"], ["Constant", "int", "5"]],
2519 ["Constant", "int", "6"],
2520 ],
2521 )
2522
2523 d5 = "float d = 1.0;"
2524 self.assertEqual(self.get_decl_init(d5), ["Constant", "double", "1.0"])
2525
2526 d51 = "float ld = 1.0l;"
2527 self.assertEqual(self.get_decl_init(d51), ["Constant", "long double", "1.0l"])
2528
2529 d52 = "float ld = 1.0L;"
2530 self.assertEqual(self.get_decl_init(d52), ["Constant", "long double", "1.0L"])
2531
2532 d53 = "float ld = 1.0f;"
2533 self.assertEqual(self.get_decl_init(d53), ["Constant", "float", "1.0f"])
2534
2535 d54 = "float ld = 1.0F;"
2536 self.assertEqual(self.get_decl_init(d54), ["Constant", "float", "1.0F"])
2537
2538 d55 = "float ld = 0xDE.38p0;"
2539 self.assertEqual(self.get_decl_init(d55), ["Constant", "double", "0xDE.38p0"])
2540
2541 d56 = "float ld = 0xDE.38p0f;"
2542 self.assertEqual(self.get_decl_init(d56), ["Constant", "float", "0xDE.38p0f"])
2543
2544 d57 = "float ld = 0xDE.38p0F;"
2545 self.assertEqual(self.get_decl_init(d57), ["Constant", "float", "0xDE.38p0F"])
2546
2547 d58 = "float ld = 0xDE.38p0l;"
2548 self.assertEqual(
2549 self.get_decl_init(d58), ["Constant", "long double", "0xDE.38p0l"]
2550 )
2551
2552 d59 = "float ld = 0xDE.38p0L;"
2553 self.assertEqual(
2554 self.get_decl_init(d59), ["Constant", "long double", "0xDE.38p0L"]
2555 )
2556
2557 d6 = "int i = 1;"
2558 self.assertEqual(self.get_decl_init(d6), ["Constant", "int", "1"])
2559
2560 d61 = "long int li = 1l;"
2561 self.assertEqual(self.get_decl_init(d61), ["Constant", "long int", "1l"])
2562
2563 d62 = "unsigned int ui = 1u;"
2564 self.assertEqual(self.get_decl_init(d62), ["Constant", "unsigned int", "1u"])
2565
2566 d63 = "unsigned long long int ulli = 1LLU;"
2567 self.assertEqual(
2568 self.get_decl_init(d63), ["Constant", "unsigned long long int", "1LLU"]
2569 )
2570
2571 def test_decl_named_inits(self):
2572 d1 = "int a = {.k = 16};"
2573 self.assertEqual(
2574 self.get_decl_init(d1), [([["ID", "k"]], ["Constant", "int", "16"])]
2575 )
2576
2577 d2 = "int a = { [0].a = {1}, [1].a[0] = 2 };"
2578 self.assertEqual(
2579 self.get_decl_init(d2),
2580 [
2581 ([["Constant", "int", "0"], ["ID", "a"]], [["Constant", "int", "1"]]),
2582 (
2583 [["Constant", "int", "1"], ["ID", "a"], ["Constant", "int", "0"]],
2584 ["Constant", "int", "2"],
2585 ),
2586 ],
2587 )
2588
2589 d3 = "int a = { .a = 1, .c = 3, 4, .b = 5};"
2590 self.assertEqual(
2591 self.get_decl_init(d3),
2592 [
2593 ([["ID", "a"]], ["Constant", "int", "1"]),
2594 ([["ID", "c"]], ["Constant", "int", "3"]),
2595 ["Constant", "int", "4"],
2596 ([["ID", "b"]], ["Constant", "int", "5"]),
2597 ],
2598 )
2599
2600 def test_function_definitions(self):
2601 def parse_fdef(str):
2602 return self.parse(str).ext[0]
2603
2604 def fdef_decl(fdef):
2605 return expand_decl(fdef.decl)
2606
2607 f1 = parse_fdef("""
2608 int factorial(int p)
2609 {
2610 return 3;
2611 }
2612 """)
2613
2614 self.assertEqual(
2615 fdef_decl(f1),
2616 [
2617 "Decl",
2618 "factorial",
2619 [
2620 "FuncDecl",
2621 [["Decl", "p", ["TypeDecl", ["IdentifierType", ["int"]]]]],
2622 ["TypeDecl", ["IdentifierType", ["int"]]],
2623 ],
2624 ],
2625 )
2626
2627 self.assertEqual(type(f1.body.block_items[0]), Return)
2628
2629 f2 = parse_fdef("""
2630 char* zzz(int p, char* c)
2631 {
2632 int a;
2633 char b;
2634
2635 a = b + 2;
2636 return 3;
2637 }
2638 """)
2639
2640 self.assertEqual(
2641 fdef_decl(f2),
2642 [
2643 "Decl",
2644 "zzz",
2645 [
2646 "FuncDecl",
2647 [
2648 ["Decl", "p", ["TypeDecl", ["IdentifierType", ["int"]]]],
2649 [
2650 "Decl",
2651 "c",
2652 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]],
2653 ],
2654 ],
2655 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]],
2656 ],
2657 ],
2658 )
2659
2660 self.assertEqual(
2661 list(map(type, f2.body.block_items)), [Decl, Decl, Assignment, Return]
2662 )
2663
2664 f3 = parse_fdef("""
2665 char* zzz(p, c)
2666 long p, *c;
2667 {
2668 int a;
2669 char b;
2670
2671 a = b + 2;
2672 return 3;
2673 }
2674 """)
2675
2676 self.assertEqual(
2677 fdef_decl(f3),
2678 [
2679 "Decl",
2680 "zzz",
2681 [
2682 "FuncDecl",
2683 [["ID", "p"], ["ID", "c"]],
2684 ["PtrDecl", ["TypeDecl", ["IdentifierType", ["char"]]]],
2685 ],
2686 ],
2687 )
2688
2689 self.assertEqual(
2690 list(map(type, f3.body.block_items)), [Decl, Decl, Assignment, Return]
2691 )
2692
2693 self.assertEqual(
2694 expand_decl(f3.param_decls[0]),
2695 ["Decl", "p", ["TypeDecl", ["IdentifierType", ["long"]]]],
2696 )
2697 self.assertEqual(
2698 expand_decl(f3.param_decls[1]),
2699 ["Decl", "c", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["long"]]]]],
2700 )
2701
2702 # function return values and parameters may not have type information
2703 f4 = parse_fdef("""
2704 que(p)
2705 {
2706 return 3;
2707 }
2708 """)
2709
2710 self.assertEqual(
2711 fdef_decl(f4),
2712 [
2713 "Decl",
2714 "que",
2715 ["FuncDecl", [["ID", "p"]], ["TypeDecl", ["IdentifierType", ["int"]]]],
2716 ],
2717 )
2718
2719 def test_static_assert(self):
2720 f1 = self.parse("""
2721 _Static_assert(1, "123");
2722 int factorial(int p)
2723 {
2724 _Static_assert(2, "456");
2725 _Static_assert(3);
2726 }
2727 """)
2728
2729 self.assertEqual(expand_decl(f1.ext[0]), ["StaticAssert", "1", '"123"'])
2730 self.assertEqual(
2731 expand_decl(f1.ext[1].body.block_items[0]), ["StaticAssert", "2", '"456"']
2732 )
2733 self.assertEqual(
2734 expand_decl(f1.ext[1].body.block_items[2]), ["StaticAssert", "3"]
2735 )
2736
2737 def test_unified_string_literals(self):
2738 # simple string, for reference
2739 d1 = self.get_decl_init('char* s = "hello";')
2740 self.assertEqual(d1, ["Constant", "string", '"hello"'])
2741
2742 d2 = self.get_decl_init('char* s = "hello" " world";')
2743 self.assertEqual(d2, ["Constant", "string", '"hello world"'])
2744
2745 # the test case from issue 6
2746 d3 = self.parse(r"""
2747 int main() {
2748 fprintf(stderr,
2749 "Wrong Params?\n"
2750 "Usage:\n"
2751 "%s <binary_file_path>\n",
2752 argv[0]
2753 );
2754 }
2755 """)
2756
2757 self.assertEqual(
2758 d3.ext[0].body.block_items[0].args.exprs[1].value,
2759 r'"Wrong Params?\nUsage:\n%s <binary_file_path>\n"',
2760 )
2761
2762 d4 = self.get_decl_init('char* s = "" "foobar";')
2763 self.assertEqual(d4, ["Constant", "string", '"foobar"'])
2764
2765 d5 = self.get_decl_init(r'char* s = "foo\"" "bar";')
2766 self.assertEqual(d5, ["Constant", "string", r'"foo\"bar"'])
2767
2768 # This is not correct based on the the C spec, but testing it here to
2769 # see the behavior in action. Will have to fix this
2770 # for https://github.com/eliben/pycparser/issues/392
2771 #
2772 # The spec says in section 6.4.5 that "escape sequences are converted
2773 # into single members of the execution character set just prior to
2774 # adjacent string literal concatenation".
2775 d6 = self.get_decl_init(r'char* s = "\1" "23";')
2776 self.assertEqual(d6, ["Constant", "string", r'"\123"'])
2777
2778 def test_unified_wstring_literals(self):
2779 d1 = self.get_decl_init('char* s = L"hello" L"world";')
2780 self.assertEqual(d1, ["Constant", "string", 'L"helloworld"'])
2781
2782 d2 = self.get_decl_init('char* s = L"hello " L"world" L" and I";')
2783 self.assertEqual(d2, ["Constant", "string", 'L"hello world and I"'])
2784
2785 def test_inline_specifier(self):
2786 ps2 = self.parse("static inline void inlinefoo(void);")
2787 self.assertEqual(ps2.ext[0].funcspec, ["inline"])
2788
2789 def test_noreturn_specifier(self):
2790 ps2 = self.parse("static _Noreturn void noreturnfoo(void);")
2791 self.assertEqual(ps2.ext[0].funcspec, ["_Noreturn"])
2792
2793 # variable length array
2794 def test_vla(self):
2795 ps2 = self.parse(r"""
2796 int main() {
2797 int size;
2798 int var[size = 5];
2799
2800 int var2[*];
2801 }
2802 """)
2803 self.assertIsInstance(ps2.ext[0].body.block_items[1].type.dim, Assignment)
2804 self.assertIsInstance(ps2.ext[0].body.block_items[2].type.dim, ID)
2805
2806 def test_pragma(self):
2807 s1 = r"""
2808 #pragma bar
2809 void main() {
2810 #pragma foo
2811 for(;;) {}
2812 #pragma baz
2813 {
2814 int i = 0;
2815 }
2816 #pragma
2817 }
2818 struct s {
2819 #pragma baz
2820 } s;
2821 _Pragma("other \"string\"")
2822 """
2823 s1_ast = self.parse(s1)
2824 self.assertIsInstance(s1_ast.ext[0], Pragma)
2825 self.assertEqual(s1_ast.ext[0].string, "bar")
2826 self.assertEqual(s1_ast.ext[0].coord.line, 2)
2827
2828 self.assertIsInstance(s1_ast.ext[1].body.block_items[0], Pragma)
2829 self.assertEqual(s1_ast.ext[1].body.block_items[0].string, "foo")
2830 self.assertEqual(s1_ast.ext[1].body.block_items[0].coord.line, 4)
2831
2832 self.assertIsInstance(s1_ast.ext[1].body.block_items[2], Pragma)
2833 self.assertEqual(s1_ast.ext[1].body.block_items[2].string, "baz")
2834 self.assertEqual(s1_ast.ext[1].body.block_items[2].coord.line, 6)
2835
2836 self.assertIsInstance(s1_ast.ext[1].body.block_items[4], Pragma)
2837 self.assertEqual(s1_ast.ext[1].body.block_items[4].string, "")
2838 self.assertEqual(s1_ast.ext[1].body.block_items[4].coord.line, 10)
2839
2840 self.assertIsInstance(s1_ast.ext[2].type.type.decls[0], Pragma)
2841 self.assertEqual(s1_ast.ext[2].type.type.decls[0].string, "baz")
2842 self.assertEqual(s1_ast.ext[2].type.type.decls[0].coord.line, 13)
2843
2844 self.assertIsInstance(s1_ast.ext[3], Pragma)
2845 self.assertEqual(s1_ast.ext[3].string.value, r'"other \"string\""')
2846 self.assertEqual(s1_ast.ext[3].coord.line, 15)
2847
2848 def test_pragmacomp_or_statement(self):
2849 s1 = r"""
2850 void main() {
2851 int sum = 0;
2852 for (int i; i < 3; i++)
2853 #pragma omp critical
2854 sum += 1;
2855
2856 while(sum < 10)
2857 #pragma omp critical
2858 sum += 1;
2859
2860 mylabel:
2861 #pragma foo
2862 sum += 10;
2863
2864 if (sum > 10)
2865 #pragma bar
2866 #pragma baz
2867 sum = 10;
2868
2869 switch (sum)
2870 case 10:
2871 #pragma foo
2872 sum = 20;
2873 }
2874 """
2875 s1_ast = self.parse(s1)
2876 self.assertIsInstance(s1_ast.ext[0].body.block_items[1], For)
2877 self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt, Compound)
2878 self.assertIsInstance(
2879 s1_ast.ext[0].body.block_items[1].stmt.block_items[0], Pragma
2880 )
2881 self.assertIsInstance(
2882 s1_ast.ext[0].body.block_items[1].stmt.block_items[1], Assignment
2883 )
2884 self.assertIsInstance(s1_ast.ext[0].body.block_items[2], While)
2885 self.assertIsInstance(s1_ast.ext[0].body.block_items[2].stmt, Compound)
2886 self.assertIsInstance(
2887 s1_ast.ext[0].body.block_items[2].stmt.block_items[0], Pragma
2888 )
2889 self.assertIsInstance(
2890 s1_ast.ext[0].body.block_items[2].stmt.block_items[1], Assignment
2891 )
2892 self.assertIsInstance(s1_ast.ext[0].body.block_items[3], Label)
2893 self.assertIsInstance(s1_ast.ext[0].body.block_items[3].stmt, Compound)
2894 self.assertIsInstance(
2895 s1_ast.ext[0].body.block_items[3].stmt.block_items[0], Pragma
2896 )
2897 self.assertIsInstance(
2898 s1_ast.ext[0].body.block_items[3].stmt.block_items[1], Assignment
2899 )
2900 self.assertIsInstance(s1_ast.ext[0].body.block_items[4], If)
2901 self.assertIsInstance(s1_ast.ext[0].body.block_items[4].iftrue, Compound)
2902 self.assertIsInstance(
2903 s1_ast.ext[0].body.block_items[4].iftrue.block_items[0], Pragma
2904 )
2905 self.assertIsInstance(
2906 s1_ast.ext[0].body.block_items[4].iftrue.block_items[1], Pragma
2907 )
2908 self.assertIsInstance(
2909 s1_ast.ext[0].body.block_items[4].iftrue.block_items[2], Assignment
2910 )
2911 self.assertIsInstance(s1_ast.ext[0].body.block_items[5], Switch)
2912 self.assertIsInstance(s1_ast.ext[0].body.block_items[5].stmt.stmts[0], Compound)
2913 self.assertIsInstance(
2914 s1_ast.ext[0].body.block_items[5].stmt.stmts[0].block_items[0], Pragma
2915 )
2916 self.assertIsInstance(
2917 s1_ast.ext[0].body.block_items[5].stmt.stmts[0].block_items[1], Assignment
2918 )
2919
2920
2921 class TestCParser_whole_code(TestCParser_base):
2922 """Testing of parsing whole chunks of code.
2923
2924 Since I don't want to rely on the structure of ASTs too
2925 much, most of these tests are implemented with visitors.
2926 """
2927
2928 # A simple helper visitor that lists the values of all the
2929 # Constant nodes it sees.
2930 #
2931 class ConstantVisitor(NodeVisitor):
2932 def __init__(self):
2933 self.values = []
2934
2935 def visit_Constant(self, node):
2936 self.values.append(node.value)
2937
2938 # This visitor counts the amount of references to the ID
2939 # with the name provided to it in the constructor.
2940 #
2941 class IDNameCounter(NodeVisitor):
2942 def __init__(self, name):
2943 self.name = name
2944 self.nrefs = 0
2945
2946 def visit_ID(self, node):
2947 if node.name == self.name:
2948 self.nrefs += 1
2949
2950 # Counts the amount of nodes of a given class
2951 #
2952 class NodeKlassCounter(NodeVisitor):
2953 def __init__(self, node_klass):
2954 self.klass = node_klass
2955 self.n = 0
2956
2957 def generic_visit(self, node):
2958 if node.__class__ == self.klass:
2959 self.n += 1
2960
2961 NodeVisitor.generic_visit(self, node)
2962
2963 def assert_all_Constants(self, code, constants):
2964 """Asserts that the list of all Constant values (by
2965 'preorder' appearance) in the chunk of code is as
2966 given.
2967 """
2968 if isinstance(code, str):
2969 parsed = self.parse(code)
2970 else:
2971 parsed = code
2972
2973 cv = self.ConstantVisitor()
2974 cv.visit(parsed)
2975 self.assertEqual(cv.values, constants)
2976
2977 def assert_num_ID_refs(self, code, name, num):
2978 """Asserts the number of references to the ID with
2979 the given name.
2980 """
2981 if isinstance(code, str):
2982 parsed = self.parse(code)
2983 else:
2984 parsed = code
2985
2986 iv = self.IDNameCounter(name)
2987 iv.visit(parsed)
2988 self.assertEqual(iv.nrefs, num)
2989
2990 def assert_num_klass_nodes(self, code, klass, num):
2991 """Asserts the amount of klass nodes in the code."""
2992 if isinstance(code, str):
2993 parsed = self.parse(code)
2994 else:
2995 parsed = code
2996
2997 cv = self.NodeKlassCounter(klass)
2998 cv.visit(parsed)
2999 self.assertEqual(cv.n, num)
3000
3001 def test_expressions(self):
3002 e1 = """int k = (r + 10.0) >> 6 + 8 << (3 & 0x14);"""
3003 self.assert_all_Constants(e1, ["10.0", "6", "8", "3", "0x14"])
3004
3005 e2 = r"""char n = '\n', *prefix = "st_";"""
3006 self.assert_all_Constants(e2, [r"'\n'", '"st_"'])
3007
3008 s1 = r"""int main() {
3009 int i = 5, j = 6, k = 1;
3010 if ((i=j && k == 1) || k > j)
3011 printf("Hello, world\n");
3012 return 0;
3013 }"""
3014 ps1 = self.parse(s1)
3015 self.assert_all_Constants(ps1, ["5", "6", "1", "1", '"Hello, world\\n"', "0"])
3016 self.assert_num_ID_refs(ps1, "i", 1)
3017 self.assert_num_ID_refs(ps1, "j", 2)
3018
3019 def test_statements(self):
3020 s1 = r"""
3021 void foo(){
3022 if (sp == 1)
3023 if (optind >= argc ||
3024 argv[optind][0] != '-' || argv[optind][1] == '\0')
3025 return -1;
3026 else if (strcmp(argv[optind], "--") == 0) {
3027 optind++;
3028 return -1;
3029 }
3030 }
3031 """
3032
3033 self.assert_all_Constants(
3034 s1, ["1", "0", r"'-'", "1", r"'\0'", "1", r'"--"', "0", "1"]
3035 )
3036
3037 ps1 = self.parse(s1)
3038 self.assert_num_ID_refs(ps1, "argv", 3)
3039 self.assert_num_ID_refs(ps1, "optind", 5)
3040
3041 self.assert_num_klass_nodes(ps1, If, 3)
3042 self.assert_num_klass_nodes(ps1, Return, 2)
3043 self.assert_num_klass_nodes(ps1, FuncCall, 1) # strcmp
3044 self.assert_num_klass_nodes(ps1, BinaryOp, 7)
3045
3046 # In the following code, Hash and Node were defined as
3047 # int to pacify the parser that sees they're used as
3048 # types
3049 #
3050 s2 = r"""
3051 typedef int Hash, Node;
3052
3053 void HashDestroy(Hash* hash)
3054 {
3055 unsigned int i;
3056
3057 if (hash == NULL)
3058 return;
3059
3060 for (i = 0; i < hash->table_size; ++i)
3061 {
3062 Node* temp = hash->heads[i];
3063
3064 while (temp != NULL)
3065 {
3066 Node* temp2 = temp;
3067
3068 free(temp->entry->key);
3069 free(temp->entry->value);
3070 free(temp->entry);
3071
3072 temp = temp->next;
3073
3074 free(temp2);
3075 }
3076 }
3077
3078 free(hash->heads);
3079 hash->heads = NULL;
3080
3081 free(hash);
3082 }
3083 """
3084
3085 ps2 = self.parse(s2)
3086 self.assert_num_klass_nodes(ps2, FuncCall, 6)
3087 self.assert_num_klass_nodes(ps2, FuncDef, 1)
3088 self.assert_num_klass_nodes(ps2, For, 1)
3089 self.assert_num_klass_nodes(ps2, While, 1)
3090 self.assert_num_klass_nodes(ps2, StructRef, 10)
3091
3092 # declarations don't count
3093 self.assert_num_ID_refs(ps2, "hash", 6)
3094 self.assert_num_ID_refs(ps2, "i", 4)
3095
3096 s3 = r"""
3097 void x(void) {
3098 int a, b;
3099 if (a < b)
3100 do {
3101 a = 0;
3102 } while (0);
3103 else if (a == b) {
3104 a = 1;
3105 }
3106 }
3107 """
3108
3109 ps3 = self.parse(s3)
3110 self.assert_num_klass_nodes(ps3, DoWhile, 1)
3111 self.assert_num_ID_refs(ps3, "a", 4)
3112 self.assert_all_Constants(ps3, ["0", "0", "1"])
3113
3114 def test_empty_statements(self):
3115 s1 = r"""
3116 void foo(void){
3117 ;
3118 return;;
3119
3120 ;
3121 }
3122 """
3123 ps1 = self.parse(s1)
3124 self.assert_num_klass_nodes(ps1, EmptyStatement, 3)
3125 self.assert_num_klass_nodes(ps1, Return, 1)
3126 self.assert_coord(ps1.ext[0].body.block_items[0], 3)
3127 self.assert_coord(ps1.ext[0].body.block_items[1], 4)
3128 self.assert_coord(ps1.ext[0].body.block_items[2], 4)
3129 self.assert_coord(ps1.ext[0].body.block_items[3], 6)
3130
3131 def test_switch_statement(self):
3132 def assert_case_node(node, const_value):
3133 self.assertIsInstance(node, Case)
3134 self.assertIsInstance(node.expr, Constant)
3135 self.assertEqual(node.expr.value, const_value)
3136
3137 def assert_default_node(node):
3138 self.assertIsInstance(node, Default)
3139
3140 s1 = r"""
3141 int foo(void) {
3142 switch (myvar) {
3143 case 10:
3144 k = 10;
3145 p = k + 1;
3146 return 10;
3147 case 20:
3148 case 30:
3149 return 20;
3150 default:
3151 break;
3152 }
3153 return 0;
3154 }
3155 """
3156 ps1 = self.parse(s1)
3157 switch = ps1.ext[0].body.block_items[0]
3158
3159 block = switch.stmt.block_items
3160 self.assertEqual(len(block), 4)
3161 assert_case_node(block[0], "10")
3162 self.assertEqual(len(block[0].stmts), 3)
3163 assert_case_node(block[1], "20")
3164 self.assertEqual(len(block[1].stmts), 0)
3165 assert_case_node(block[2], "30")
3166 self.assertEqual(len(block[2].stmts), 1)
3167 assert_default_node(block[3])
3168
3169 s2 = r"""
3170 int foo(void) {
3171 switch (myvar) {
3172 default:
3173 joe = moe;
3174 return 10;
3175 case 10:
3176 case 20:
3177 case 30:
3178 case 40:
3179 break;
3180 }
3181 return 0;
3182 }
3183 """
3184 ps2 = self.parse(s2)
3185 switch = ps2.ext[0].body.block_items[0]
3186
3187 block = switch.stmt.block_items
3188 self.assertEqual(len(block), 5)
3189 assert_default_node(block[0])
3190 self.assertEqual(len(block[0].stmts), 2)
3191 assert_case_node(block[1], "10")
3192 self.assertEqual(len(block[1].stmts), 0)
3193 assert_case_node(block[2], "20")
3194 self.assertEqual(len(block[1].stmts), 0)
3195 assert_case_node(block[3], "30")
3196 self.assertEqual(len(block[1].stmts), 0)
3197 assert_case_node(block[4], "40")
3198 self.assertEqual(len(block[4].stmts), 1)
3199
3200 s3 = r"""
3201 int foo(void) {
3202 switch (myvar) {
3203 }
3204 return 0;
3205 }
3206 """
3207 ps3 = self.parse(s3)
3208 switch = ps3.ext[0].body.block_items[0]
3209
3210 self.assertEqual(switch.stmt.block_items, [])
3211
3212 def test_for_statement(self):
3213 s2 = r"""
3214 void x(void)
3215 {
3216 int i;
3217 for (i = 0; i < 5; ++i) {
3218 x = 50;
3219 }
3220 }
3221 """
3222 ps2 = self.parse(s2)
3223 self.assert_num_klass_nodes(ps2, For, 1)
3224 # here there are 3 refs to 'i' since the declaration doesn't count as
3225 # a ref in the visitor
3226 #
3227 self.assert_num_ID_refs(ps2, "i", 3)
3228
3229 s3 = r"""
3230 void x(void)
3231 {
3232 for (int i = 0; i < 5; ++i) {
3233 x = 50;
3234 }
3235 }
3236 """
3237 ps3 = self.parse(s3)
3238 self.assert_num_klass_nodes(ps3, For, 1)
3239 # here there are 2 refs to 'i' since the declaration doesn't count as
3240 # a ref in the visitor
3241 #
3242 self.assert_num_ID_refs(ps3, "i", 2)
3243
3244 s4 = r"""
3245 void x(void) {
3246 for (int i = 0;;)
3247 i;
3248 }
3249 """
3250 ps4 = self.parse(s4)
3251 self.assert_num_ID_refs(ps4, "i", 1)
3252
3253 def _open_c_file(self, name):
3254 """Find a c file by name, taking into account the current dir can be
3255 in a couple of typical places
3256 """
3257 testdir = os.path.dirname(__file__)
3258 name = os.path.join(testdir, "c_files", name)
3259 assert os.path.exists(name)
3260 return io.open(name)
3261
3262 def test_whole_file(self):
3263 # See how pycparser handles a whole, real C file.
3264 #
3265 with self._open_c_file("memmgr_with_h.c") as f:
3266 code = f.read()
3267 p = self.parse(code)
3268
3269 self.assert_num_klass_nodes(p, FuncDef, 5)
3270
3271 # each FuncDef also has a FuncDecl. 4 declarations
3272 # + 5 definitions, overall 9
3273 self.assert_num_klass_nodes(p, FuncDecl, 9)
3274
3275 self.assert_num_klass_nodes(p, Typedef, 4)
3276
3277 self.assertEqual(p.ext[4].coord.line, 88)
3278 self.assertEqual(p.ext[4].coord.file, "./memmgr.h")
3279
3280 self.assertEqual(p.ext[6].coord.line, 10)
3281 self.assertEqual(p.ext[6].coord.file, "memmgr.c")
3282
3283 def test_whole_file_with_stdio(self):
3284 # Parse a whole file with stdio.h included by cpp
3285 #
3286 with self._open_c_file("cppd_with_stdio_h.c") as f:
3287 code = f.read()
3288 p = self.parse(code)
3289
3290 self.assertIsInstance(p.ext[0], Typedef)
3291 self.assertEqual(p.ext[0].coord.line, 213)
3292 self.assertEqual(p.ext[0].coord.file, r"D:\eli\cpp_stuff\libc_include/stddef.h")
3293
3294 self.assertIsInstance(p.ext[-1], FuncDef)
3295 self.assertEqual(p.ext[-1].coord.line, 15)
3296 self.assertEqual(p.ext[-1].coord.file, "example_c_file.c")
3297
3298 self.assertIsInstance(p.ext[-8], Typedef)
3299 self.assertIsInstance(p.ext[-8].type, TypeDecl)
3300 self.assertEqual(p.ext[-8].name, "cookie_io_functions_t")
3301
3302
3303 class TestCParser_typenames(TestCParser_base):
3304 """Test issues related to the typedef-name problem."""
3305
3306 def test_innerscope_typedef(self):
3307 # should fail since TT is not a type in bar
3308 s1 = r"""
3309 void foo() {
3310 typedef char TT;
3311 TT x;
3312 }
3313 void bar() {
3314 TT y;
3315 }
3316 """
3317 self.assertRaises(ParseError, self.parse, s1)
3318
3319 # should succeed since TT is not a type in bar
3320 s2 = r"""
3321 void foo() {
3322 typedef char TT;
3323 TT x;
3324 }
3325 void bar() {
3326 unsigned TT;
3327 }
3328 """
3329 self.assertIsInstance(self.parse(s2), FileAST)
3330
3331 def test_ambiguous_parameters(self):
3332 # From ISO/IEC 9899:TC2, 6.7.5.3.11:
3333 # "If, in a parameter declaration, an identifier can be treated either
3334 # as a typedef name or as a parameter name, it shall be taken as a
3335 # typedef name."
3336
3337 # foo takes an int named aa
3338 # bar takes a function taking a TT
3339 s1 = r"""
3340 typedef char TT;
3341 int foo(int (aa));
3342 int bar(int (TT));
3343 """
3344 s1_ast = self.parse(s1)
3345 self.assertEqual(
3346 expand_decl(s1_ast.ext[1].type.args.params[0]),
3347 ["Decl", "aa", ["TypeDecl", ["IdentifierType", ["int"]]]],
3348 )
3349 self.assertEqual(
3350 expand_decl(s1_ast.ext[2].type.args.params[0]),
3351 [
3352 "Typename",
3353 [
3354 "FuncDecl",
3355 [["Typename", ["TypeDecl", ["IdentifierType", ["TT"]]]]],
3356 ["TypeDecl", ["IdentifierType", ["int"]]],
3357 ],
3358 ],
3359 )
3360
3361 # foo takes a function taking a char
3362 # bar takes a function taking a function taking a char
3363 s2 = r"""
3364 typedef char TT;
3365 int foo(int (aa (char)));
3366 int bar(int (TT (char)));
3367 """
3368 s2_ast = self.parse(s2)
3369 self.assertEqual(
3370 expand_decl(s2_ast.ext[1].type.args.params[0]),
3371 [
3372 "Decl",
3373 "aa",
3374 [
3375 "FuncDecl",
3376 [["Typename", ["TypeDecl", ["IdentifierType", ["char"]]]]],
3377 ["TypeDecl", ["IdentifierType", ["int"]]],
3378 ],
3379 ],
3380 )
3381 self.assertEqual(
3382 expand_decl(s2_ast.ext[2].type.args.params[0]),
3383 [
3384 "Typename",
3385 [
3386 "FuncDecl",
3387 [
3388 [
3389 "Typename",
3390 [
3391 "FuncDecl",
3392 [
3393 [
3394 "Typename",
3395 ["TypeDecl", ["IdentifierType", ["char"]]],
3396 ]
3397 ],
3398 ["TypeDecl", ["IdentifierType", ["TT"]]],
3399 ],
3400 ]
3401 ],
3402 ["TypeDecl", ["IdentifierType", ["int"]]],
3403 ],
3404 ],
3405 )
3406
3407 # foo takes an int array named aa
3408 # bar takes a function taking a TT array
3409 s3 = r"""
3410 typedef char TT;
3411 int foo(int (aa[]));
3412 int bar(int (TT[]));
3413 """
3414 s3_ast = self.parse(s3)
3415 self.assertEqual(
3416 expand_decl(s3_ast.ext[1].type.args.params[0]),
3417 [
3418 "Decl",
3419 "aa",
3420 ["ArrayDecl", "", [], ["TypeDecl", ["IdentifierType", ["int"]]]],
3421 ],
3422 )
3423 self.assertEqual(
3424 expand_decl(s3_ast.ext[2].type.args.params[0]),
3425 [
3426 "Typename",
3427 [
3428 "FuncDecl",
3429 [
3430 [
3431 "Typename",
3432 [
3433 "ArrayDecl",
3434 "",
3435 [],
3436 ["TypeDecl", ["IdentifierType", ["TT"]]],
3437 ],
3438 ]
3439 ],
3440 ["TypeDecl", ["IdentifierType", ["int"]]],
3441 ],
3442 ],
3443 )
3444
3445 def test_innerscope_reuse_typedef_name(self):
3446 # identifiers can be reused in inner scopes; the original should be
3447 # restored at the end of the block
3448 s1 = r"""
3449 typedef char TT;
3450 void foo(void) {
3451 unsigned TT;
3452 TT = 10;
3453 }
3454 TT x = 5;
3455 """
3456 s1_ast = self.parse(s1)
3457 self.assertEqual(
3458 expand_decl(s1_ast.ext[1].body.block_items[0]),
3459 ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]],
3460 )
3461 self.assertEqual(
3462 expand_decl(s1_ast.ext[2]),
3463 ["Decl", "x", ["TypeDecl", ["IdentifierType", ["TT"]]]],
3464 )
3465
3466 # this should be recognized even with an initializer
3467 s2 = r"""
3468 typedef char TT;
3469 void foo(void) {
3470 unsigned TT = 10;
3471 }
3472 """
3473 s2_ast = self.parse(s2)
3474 self.assertEqual(
3475 expand_decl(s2_ast.ext[1].body.block_items[0]),
3476 ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]],
3477 )
3478
3479 # before the second local variable, TT is a type; after, it's a
3480 # variable
3481 s3 = r"""
3482 typedef char TT;
3483 void foo(void) {
3484 TT tt = sizeof(TT);
3485 unsigned TT = 10;
3486 }
3487 """
3488 s3_ast = self.parse(s3)
3489 self.assertEqual(
3490 expand_decl(s3_ast.ext[1].body.block_items[0]),
3491 ["Decl", "tt", ["TypeDecl", ["IdentifierType", ["TT"]]]],
3492 )
3493 self.assertEqual(
3494 expand_decl(s3_ast.ext[1].body.block_items[1]),
3495 ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]],
3496 )
3497
3498 # a variable and its type can even share the same name
3499 s4 = r"""
3500 typedef char TT;
3501 void foo(void) {
3502 TT TT = sizeof(TT);
3503 unsigned uu = TT * 2;
3504 }
3505 """
3506 s4_ast = self.parse(s4)
3507 self.assertEqual(
3508 expand_decl(s4_ast.ext[1].body.block_items[0]),
3509 ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["TT"]]]],
3510 )
3511 self.assertEqual(
3512 expand_decl(s4_ast.ext[1].body.block_items[1]),
3513 ["Decl", "uu", ["TypeDecl", ["IdentifierType", ["unsigned"]]]],
3514 )
3515
3516 # ensure an error is raised if a type, redeclared as a variable, is
3517 # used as a type
3518 s5 = r"""
3519 typedef char TT;
3520 void foo(void) {
3521 unsigned TT = 10;
3522 TT erroneous = 20;
3523 }
3524 """
3525 self.assertRaises(ParseError, self.parse, s5)
3526
3527 # reusing a type name should work with multiple declarators
3528 s6 = r"""
3529 typedef char TT;
3530 void foo(void) {
3531 unsigned TT, uu;
3532 }
3533 """
3534 s6_ast = self.parse(s6)
3535 items = s6_ast.ext[1].body.block_items
3536 self.assertEqual(
3537 expand_decl(items[0]),
3538 ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]],
3539 )
3540 self.assertEqual(
3541 expand_decl(items[1]),
3542 ["Decl", "uu", ["TypeDecl", ["IdentifierType", ["unsigned"]]]],
3543 )
3544
3545 # reusing a type name should work after a pointer
3546 s7 = r"""
3547 typedef char TT;
3548 void foo(void) {
3549 unsigned * TT;
3550 }
3551 """
3552 s7_ast = self.parse(s7)
3553 items = s7_ast.ext[1].body.block_items
3554 self.assertEqual(
3555 expand_decl(items[0]),
3556 ["Decl", "TT", ["PtrDecl", ["TypeDecl", ["IdentifierType", ["unsigned"]]]]],
3557 )
3558
3559 # redefine a name in the middle of a multi-declarator declaration
3560 s8 = r"""
3561 typedef char TT;
3562 void foo(void) {
3563 int tt = sizeof(TT), TT, uu = sizeof(TT);
3564 int uu = sizeof(tt);
3565 }
3566 """
3567 s8_ast = self.parse(s8)
3568 items = s8_ast.ext[1].body.block_items
3569 self.assertEqual(
3570 expand_decl(items[0]),
3571 ["Decl", "tt", ["TypeDecl", ["IdentifierType", ["int"]]]],
3572 )
3573 self.assertEqual(
3574 expand_decl(items[1]),
3575 ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["int"]]]],
3576 )
3577 self.assertEqual(
3578 expand_decl(items[2]),
3579 ["Decl", "uu", ["TypeDecl", ["IdentifierType", ["int"]]]],
3580 )
3581
3582 # Don't test this until we have support for it
3583 # self.assertEqual(expand_init(items[0].init),
3584 # ['UnaryOp', 'sizeof', ['Typename', ['TypeDecl', ['IdentifierType', ['TT']]]]])
3585 # self.assertEqual(expand_init(items[2].init),
3586 # ['UnaryOp', 'sizeof', ['ID', 'TT']])
3587
3588 def test_parameter_reuse_typedef_name(self):
3589 # identifiers can be reused as parameter names; parameter name scope
3590 # begins and ends with the function body; it's important that TT is
3591 # used immediately before the LBRACE or after the RBRACE, to test
3592 # a corner case
3593 s1 = r"""
3594 typedef char TT;
3595 void foo(unsigned TT, TT bar) {
3596 TT = 10;
3597 }
3598 TT x = 5;
3599 """
3600 s1_ast = self.parse(s1)
3601 self.assertEqual(
3602 expand_decl(s1_ast.ext[1].decl),
3603 [
3604 "Decl",
3605 "foo",
3606 [
3607 "FuncDecl",
3608 [
3609 ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]],
3610 ["Decl", "bar", ["TypeDecl", ["IdentifierType", ["TT"]]]],
3611 ],
3612 ["TypeDecl", ["IdentifierType", ["void"]]],
3613 ],
3614 ],
3615 )
3616
3617 # the scope of a parameter name in a function declaration ends at the
3618 # end of the declaration...so it is effectively never used; it's
3619 # important that TT is used immediately after the declaration, to
3620 # test a corner case
3621 s2 = r"""
3622 typedef char TT;
3623 void foo(unsigned TT, TT bar);
3624 TT x = 5;
3625 """
3626 s2_ast = self.parse(s2)
3627 self.assertEqual(
3628 expand_decl(s2_ast.ext[1]),
3629 [
3630 "Decl",
3631 "foo",
3632 [
3633 "FuncDecl",
3634 [
3635 ["Decl", "TT", ["TypeDecl", ["IdentifierType", ["unsigned"]]]],
3636 ["Decl", "bar", ["TypeDecl", ["IdentifierType", ["TT"]]]],
3637 ],
3638 ["TypeDecl", ["IdentifierType", ["void"]]],
3639 ],
3640 ],
3641 )
3642
3643 # ensure an error is raised if a type, redeclared as a parameter, is
3644 # used as a type
3645 s3 = r"""
3646 typedef char TT;
3647 void foo(unsigned TT, TT bar) {
3648 TT erroneous = 20;
3649 }
3650 """
3651 self.assertRaises(ParseError, self.parse, s3)
3652
3653 def test_nested_function_decls(self):
3654 # parameter names of nested function declarations must not escape into
3655 # the top-level function _definition's_ scope; the following must
3656 # succeed because TT is still a typedef inside foo's body
3657 s1 = r"""
3658 typedef char TT;
3659 void foo(unsigned bar(int TT)) {
3660 TT x = 10;
3661 }
3662 """
3663 self.assertIsInstance(self.parse(s1), FileAST)
3664
3665 def test_samescope_reuse_name(self):
3666 # a typedef name cannot be reused as an object name in the same scope
3667 s1 = r"""
3668 typedef char TT;
3669 char TT = 5;
3670 """
3671 self.assertRaises(ParseError, self.parse, s1)
3672
3673 # ...and vice-versa
3674 s2 = r"""
3675 char TT = 5;
3676 typedef char TT;
3677 """
3678 self.assertRaises(ParseError, self.parse, s2)
3679
3680 def test_label_empty_statement(self):
3681 # Labels with empty statements and no semicolon should be parsed correctly
3682 s1 = r"""
3683 int main() {
3684 int i = 0;
3685 label0: i++;
3686 label1:
3687 }
3688 """
3689 s1_ast: FileAST = self.parse(s1)
3690 self.assertIsInstance(s1_ast.ext[0].body.block_items[1], Label)
3691 self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt, UnaryOp)
3692 self.assertIsInstance(s1_ast.ext[0].body.block_items[2], Label)
3693 self.assertIsInstance(s1_ast.ext[0].body.block_items[2].stmt, EmptyStatement)
3694
3695 def test_case_empty_statement(self):
3696 # Labels with empty statements and no semicolon should be parsed correctly
3697 s1 = r"""
3698 int main() {
3699 int i = 0;
3700 switch (i) {
3701 case 0:
3702 i = 1;
3703 case 1:
3704 }
3705 return i;
3706 }
3707 """
3708 s2 = r"""
3709 int main() {
3710 int i = 0;
3711 switch (i) {
3712 case 0:
3713 i = 1;
3714 default:
3715 }
3716 return i;
3717 }
3718 """
3719 s1_ast: FileAST = self.parse(s1)
3720 s2_ast: FileAST = self.parse(s2)
3721 self.assertIsInstance(s1_ast.ext[0].body.block_items[1], Switch)
3722 self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt, Compound)
3723 self.assertIsInstance(
3724 s1_ast.ext[0].body.block_items[1].stmt.block_items[0], Case
3725 )
3726 self.assertIsInstance(
3727 s1_ast.ext[0].body.block_items[1].stmt.block_items[0].stmts[0], Assignment
3728 )
3729 self.assertIsInstance(
3730 s1_ast.ext[0].body.block_items[1].stmt.block_items[1], Case
3731 )
3732 self.assertIsInstance(
3733 s1_ast.ext[0].body.block_items[1].stmt.block_items[1].stmts[0],
3734 EmptyStatement,
3735 )
3736 self.assertIsInstance(
3737 s2_ast.ext[0].body.block_items[1].stmt.block_items[1].stmts[0],
3738 EmptyStatement,
3739 )
3740
3741
3742 if __name__ == "__main__":
3743 # ~ suite = unittest.TestLoader().loadTestsFromNames(
3744 # ~ ['test_c_parser.TestCParser_fundamentals.test_typedef'])
3745
3746 # ~ unittest.TextTestRunner(verbosity=2).run(suite)
3747 unittest.main()