Debian Codegraph @

pycparser223/tests/test_c_parser.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 import os, sys
4 import io
5 import unittest
6
7 sys.path[0:0] = ['.', '..']
8
9 from pycparser import c_parser
10 from pycparser.c_ast import *
11 from pycparser.c_parser import ParseError
12
13 _c_parser = c_parser.CParser(
14 lex_optimize=False,
15 yacc_debug=True,
16 yacc_optimize=False,
17 yacctab='yacctab')
18
19
20 def expand_decl(decl):
21 """ Converts the declaration into a nested list.
22 """
23 typ = type(decl)
24
25 if typ == TypeDecl:
26 return ['TypeDecl', expand_decl(decl.type)]
27 elif typ == IdentifierType:
28 return ['IdentifierType', decl.names]
29 elif typ == ID:
30 return ['ID', decl.name]
31 elif typ in [Struct, Union]:
32 decls = [expand_decl(d) for d in decl.decls or []]
33 return [typ.__name__, decl.name, decls]
34 elif typ == Enum:
35 if decl.values is None:
36 values = None
37 else:
38 assert isinstance(decl.values, EnumeratorList)
39 values = [enum.name for enum in decl.values.enumerators]
40 return ['Enum', decl.name, values]
41 elif typ == Alignas:
42 return ['Alignas', expand_init(decl.alignment)]
43 elif typ == StaticAssert:
44 if decl.message:
45 return ['StaticAssert', decl.cond.value, decl.message.value]
46 else:
47 return ['StaticAssert', decl.cond.value]
48 else:
49 nested = expand_decl(decl.type)
50
51 if typ == Decl:
52 r = ['Decl']
53 if decl.quals:
54 r.append(decl.quals)
55 if decl.align:
56 r.append(expand_decl(decl.align[0]))
57 r.extend([decl.name, nested])
58 return r
59 elif typ == Typename: # for function parameters
60 if decl.quals:
61 return ['Typename', decl.quals, nested]
62 else:
63 return ['Typename', nested]
64 elif typ == ArrayDecl:
65 dimval = decl.dim.value if decl.dim else ''
66 return ['ArrayDecl', dimval, decl.dim_quals, nested]
67 elif typ == PtrDecl:
68 if decl.quals:
69 return ['PtrDecl', decl.quals, nested]
70 else:
71 return ['PtrDecl', nested]
72 elif typ == Typedef:
73 return ['Typedef', decl.name, nested]
74 elif typ == FuncDecl:
75 if decl.args:
76 params = [expand_decl(param) for param in decl.args.params]
77 else:
78 params = []
79 return ['FuncDecl', params, nested]
80
81
82 def expand_init(init):
83 """ Converts an initialization into a nested list
84 """
85 typ = type(init)
86
87 if typ == NamedInitializer:
88 des = [expand_init(dp) for dp in init.name]
89 return (des, expand_init(init.expr))
90 elif typ in (InitList, ExprList):
91 return [expand_init(expr) for expr in init.exprs]
92 elif typ == Constant:
93 return ['Constant', init.type, init.value]
94 elif typ == ID:
95 return ['ID', init.name]
96 elif typ == Decl:
97 return ['Decl', init.name]
98 elif typ == UnaryOp:
99 return ['UnaryOp', init.op, expand_decl(init.expr)]
100 elif typ == BinaryOp:
101 return ['BinaryOp', expand_init(init.left), init.op, expand_init(init.right)]
102 elif typ == Compound:
103 blocks = []
104 if init.block_items:
105 blocks = [expand_init(i) for i in init.block_items]
106 return ['Compound', blocks]
107 elif typ == Typename:
108 return expand_decl(init)
109 else:
110 # Fallback to type name
111 return [typ.__name__]
112
113
114 class TestCParser_base(unittest.TestCase):
115 def parse(self, txt, filename=''):
116 return self.cparser.parse(txt, filename)
117
118 def setUp(self):
119 self.cparser = _c_parser
120
121 def assert_coord(self, node, line, column=None, file=None):
122 self.assertEqual(node.coord.line, line)
123 if column is not None:
124 self.assertEqual(node.coord.column, column)
125 if file:
126 self.assertEqual(node.coord.file, file)
127
128
129
130 class TestCParser_fundamentals(TestCParser_base):
131 def get_decl(self, txt, index=0):
132 """ Given a source and an index returns the expanded
133 declaration at that index.
134
135 FileAST holds a list of 'external declarations'.
136 index is the offset of the desired declaration in that
137 list.
138 """
139 t = self.parse(txt).ext[index]
140 return expand_decl(t)
141
142 def get_decl_init(self, txt, index=0):
143 """ Returns the expanded initializer of the declaration
144 at index.
145 """
146 t = self.parse(txt).ext[index]
147 return expand_init(t.init)
148
149 def test_FileAST(self):
150 t = self.parse('int a; char c;')
151 self.assertIsInstance(t, FileAST)
152 self.assertEqual(len(t.ext), 2)
153
154 # empty file
155 t2 = self.parse('')
156 self.assertIsInstance(t2, FileAST)
157 self.assertEqual(len(t2.ext), 0)
158
159 def test_empty_toplevel_decl(self):
160 code = 'int foo;;'
161 t = self.parse(code)
162 self.assertIsInstance(t, FileAST)
163 self.assertEqual(len(t.ext), 1)
164 self.assertEqual(self.get_decl(code),
165 ['Decl', 'foo',
166 ['TypeDecl', ['IdentifierType', ['int']]]])
167
168 def test_initial_semi(self):
169 t = self.parse(';')
170 self.assertEqual(len(t.ext), 0)
171 t = self.parse(';int foo;')
172 self.assertEqual(len(t.ext), 1)
173 self.assertEqual(expand_decl(t.ext[0]),
174 ['Decl', 'foo',
175 ['TypeDecl', ['IdentifierType', ['int']]]])
176
177 def test_coords(self):
178 """ Tests the "coordinates" of parsed elements - file
179 name, line and column numbers, with modification
180 inserted by #line directives.
181 """
182 self.assert_coord(self.parse('int a;').ext[0], 1, 5)
183
184 t1 = """
185 int a;
186 int b;\n\n
187 int c;
188 """
189 f1 = self.parse(t1, filename='test.c')
190 self.assert_coord(f1.ext[0], 2, 13, 'test.c')
191 self.assert_coord(f1.ext[1], 3, 13, 'test.c')
192 self.assert_coord(f1.ext[2], 6, 13, 'test.c')
193
194 t1_1 = '''
195 int main() {
196 k = p;
197 printf("%d", b);
198 return 0;
199 }'''
200 f1_1 = self.parse(t1_1, filename='test.c')
201 self.assert_coord(f1_1.ext[0].body.block_items[0], 3, 13, 'test.c')
202 self.assert_coord(f1_1.ext[0].body.block_items[1], 4, 13, 'test.c')
203
204 t1_2 = '''
205 int main () {
206 int p = (int) k;
207 }'''
208 f1_2 = self.parse(t1_2, filename='test.c')
209 # make sure that the Cast has a coord (issue 23)
210 self.assert_coord(f1_2.ext[0].body.block_items[0].init, 3, 21, file='test.c')
211
212 t2 = """
213 #line 99
214 int c;
215 """
216 self.assert_coord(self.parse(t2).ext[0], 99, 13)
217
218 t3 = """
219 int dsf;
220 char p;
221 #line 3000 "in.h"
222 char d;
223 """
224 f3 = self.parse(t3, filename='test.c')
225 self.assert_coord(f3.ext[0], 2, 13, 'test.c')
226 self.assert_coord(f3.ext[1], 3, 14, 'test.c')
227 self.assert_coord(f3.ext[2], 3000, 14, 'in.h')
228
229 t4 = """
230 #line 20 "restore.h"
231 int maydler(char);
232
233 #line 30 "includes/daween.ph"
234 long j, k;
235
236 #line 50000
237 char* ro;
238 """
239 f4 = self.parse(t4, filename='myb.c')
240 self.assert_coord(f4.ext[0], 20, 13, 'restore.h')
241 self.assert_coord(f4.ext[1], 30, 14, 'includes/daween.ph')
242 self.assert_coord(f4.ext[2], 30, 17, 'includes/daween.ph')
243 self.assert_coord(f4.ext[3], 50000, 13, 'includes/daween.ph')
244
245 t5 = """
246 int
247 #line 99
248 c;
249 """
250 self.assert_coord(self.parse(t5).ext[0], 99, 9)
251
252 # coord for ellipsis
253 t6 = """
254 int foo(int j,
255 ...) {
256 }"""
257 f6 = self.parse(t6, filename='z.c')
258 self.assert_coord(self.parse(t6).ext[0].decl.type.args.params[1], 3, 17)
259
260 def test_forloop_coord(self):
261 t = '''\
262 void foo() {
263 for(int z=0; z<4;
264 z++){}
265 }
266 '''
267 s = self.parse(t, filename='f.c')
268 forloop = s.ext[0].body.block_items[0]
269 self.assert_coord(forloop.init, 2, 13, 'f.c')
270 self.assert_coord(forloop.cond, 2, 26, 'f.c')
271 self.assert_coord(forloop.next, 3, 17, 'f.c')
272
273 def test_simple_decls(self):
274 self.assertEqual(self.get_decl('int a;'),
275 ['Decl', 'a', ['TypeDecl', ['IdentifierType', ['int']]]])
276
277 self.assertEqual(self.get_decl('unsigned int a;'),
278 ['Decl', 'a', ['TypeDecl', ['IdentifierType', ['unsigned', 'int']]]])
279
280 self.assertEqual(self.get_decl('_Bool a;'),
281 ['Decl', 'a', ['TypeDecl', ['IdentifierType', ['_Bool']]]])
282
283 self.assertEqual(self.get_decl('float _Complex fcc;'),
284 ['Decl', 'fcc', ['TypeDecl', ['IdentifierType', ['float', '_Complex']]]])
285
286 self.assertEqual(self.get_decl('char* string;'),
287 ['Decl', 'string',
288 ['PtrDecl', ['TypeDecl', ['IdentifierType', ['char']]]]])
289
290 self.assertEqual(self.get_decl('long ar[15];'),
291 ['Decl', 'ar',
292 ['ArrayDecl', '15', [],
293 ['TypeDecl', ['IdentifierType', ['long']]]]])
294
295 self.assertEqual(self.get_decl('long long ar[15];'),
296 ['Decl', 'ar',
297 ['ArrayDecl', '15', [],
298 ['TypeDecl', ['IdentifierType', ['long', 'long']]]]])
299
300 self.assertEqual(self.get_decl('unsigned ar[];'),
301 ['Decl', 'ar',
302 ['ArrayDecl', '', [],
303 ['TypeDecl', ['IdentifierType', ['unsigned']]]]])
304
305 self.assertEqual(self.get_decl('int strlen(char* s);'),
306 ['Decl', 'strlen',
307 ['FuncDecl',
308 [['Decl', 's',
309 ['PtrDecl',
310 ['TypeDecl', ['IdentifierType', ['char']]]]]],
311 ['TypeDecl', ['IdentifierType', ['int']]]]])
312
313 self.assertEqual(self.get_decl('int strcmp(char* s1, char* s2);'),
314 ['Decl', 'strcmp',
315 ['FuncDecl',
316 [ ['Decl', 's1',
317 ['PtrDecl', ['TypeDecl', ['IdentifierType', ['char']]]]],
318 ['Decl', 's2',
319 ['PtrDecl', ['TypeDecl', ['IdentifierType', ['char']]]]]
320 ],
321 ['TypeDecl', ['IdentifierType', ['int']]]]])
322
323 # function return values and parameters may not have type information
324 self.assertEqual(self.get_decl('extern foobar(foo, bar);'),
325 ['Decl', 'foobar',
326 ['FuncDecl',
327 [ ['ID', 'foo'],
328 ['ID', 'bar']
329 ],
330 ['TypeDecl', ['IdentifierType', ['int']]]]])
331
332 def test_int128(self):
333 self.assertEqual(self.get_decl('__int128 a;'),
334 ['Decl', 'a', ['TypeDecl', ['IdentifierType', ['__int128']]]])
335
336
337 def test_nested_decls(self): # the fun begins
338 self.assertEqual(self.get_decl('char** ar2D;'),
339 ['Decl', 'ar2D',
340 ['PtrDecl', ['PtrDecl',
341 ['TypeDecl', ['IdentifierType', ['char']]]]]])
342
343 self.assertEqual(self.get_decl('int (*a)[1][2];'),
344 ['Decl', 'a',
345 ['PtrDecl',
346 ['ArrayDecl', '1', [],
347 ['ArrayDecl', '2', [],
348 ['TypeDecl', ['IdentifierType', ['int']]]]]]])
349
350 self.assertEqual(self.get_decl('int *a[1][2];'),
351 ['Decl', 'a',
352 ['ArrayDecl', '1', [],
353 ['ArrayDecl', '2', [],
354 ['PtrDecl', ['TypeDecl', ['IdentifierType', ['int']]]]]]])
355
356 self.assertEqual(self.get_decl('char* const* p;'),
357 ['Decl', 'p',
358 ['PtrDecl', ['PtrDecl', ['const'],
359 ['TypeDecl', ['IdentifierType', ['char']]]]]])
360
361 self.assertEqual(self.get_decl('const char* const* p;'),
362 ['Decl', ['const'], 'p',
363 ['PtrDecl', ['PtrDecl', ['const'],
364 ['TypeDecl', ['IdentifierType', ['char']]]]]])
365
366 self.assertEqual(self.get_decl('char* * const p;'),
367 ['Decl', 'p',
368 ['PtrDecl', ['const'], ['PtrDecl',
369 ['TypeDecl', ['IdentifierType', ['char']]]]]])
370
371 self.assertEqual(self.get_decl('char ***ar3D[40];'),
372 ['Decl', 'ar3D',
373 ['ArrayDecl', '40', [],
374 ['PtrDecl', ['PtrDecl', ['PtrDecl',
375 ['TypeDecl', ['IdentifierType', ['char']]]]]]]])
376
377 self.assertEqual(self.get_decl('char (***ar3D)[40];'),
378 ['Decl', 'ar3D',
379 ['PtrDecl', ['PtrDecl', ['PtrDecl',
380 ['ArrayDecl', '40', [], ['TypeDecl', ['IdentifierType', ['char']]]]]]]])
381
382 self.assertEqual(self.get_decl('int (*const*const x)(char, int);'),
383 ['Decl',
384 'x',
385 ['PtrDecl',
386 ['const'],
387 ['PtrDecl',
388 ['const'],
389 ['FuncDecl',
390 [['Typename', ['TypeDecl', ['IdentifierType', ['char']]]],
391 ['Typename', ['TypeDecl', ['IdentifierType', ['int']]]]],
392 ['TypeDecl', ['IdentifierType', ['int']]]]]]])
393
394 self.assertEqual(self.get_decl('int (*x[4])(char, int);'),
395 ['Decl', 'x',
396 ['ArrayDecl', '4', [],
397 ['PtrDecl',
398 ['FuncDecl',
399 [ ['Typename', ['TypeDecl', ['IdentifierType', ['char']]]],
400 ['Typename', ['TypeDecl', ['IdentifierType', ['int']]]]],
401 ['TypeDecl', ['IdentifierType', ['int']]]]]]])
402
403 self.assertEqual(self.get_decl('char *(*(**foo [][8])())[];'),
404 ['Decl', 'foo',
405 ['ArrayDecl', '', [],
406 ['ArrayDecl', '8', [],
407 ['PtrDecl', ['PtrDecl',
408 ['FuncDecl',
409 [],
410 ['PtrDecl',
411 ['ArrayDecl', '', [],
412 ['PtrDecl',
413 ['TypeDecl',
414 ['IdentifierType', ['char']]]]]]]]]]]])
415
416 # explore named and unnamed function pointer parameters,
417 # with and without qualifiers
418
419 # unnamed w/o quals
420 self.assertEqual(self.get_decl('int (*k)(int);'),
421 ['Decl', 'k',
422 ['PtrDecl',
423 ['FuncDecl',
424 [['Typename', ['TypeDecl', ['IdentifierType', ['int']]]]],
425 ['TypeDecl', ['IdentifierType', ['int']]]]]])
426
427 # unnamed w/ quals
428 self.assertEqual(self.get_decl('int (*k)(const int);'),
429 ['Decl', 'k',
430 ['PtrDecl',
431 ['FuncDecl',
432 [['Typename', ['const'], ['TypeDecl', ['IdentifierType', ['int']]]]],
433 ['TypeDecl', ['IdentifierType', ['int']]]]]])
434
435 # named w/o quals
436 self.assertEqual(self.get_decl('int (*k)(int q);'),
437 ['Decl', 'k',
438 ['PtrDecl',
439 ['FuncDecl',
440 [['Decl', 'q', ['TypeDecl', ['IdentifierType', ['int']]]]],
441 ['TypeDecl', ['IdentifierType', ['int']]]]]])
442
443 # named w/ quals
444 self.assertEqual(self.get_decl('int (*k)(const volatile int q);'),
445 ['Decl', 'k',
446 ['PtrDecl',
447 ['FuncDecl',
448 [['Decl', ['const', 'volatile'], 'q',
449 ['TypeDecl', ['IdentifierType', ['int']]]]],
450 ['TypeDecl', ['IdentifierType', ['int']]]]]])
451
452 self.assertEqual(self.get_decl('int (*k)(_Atomic volatile int q);'),
453 ['Decl', 'k',
454 ['PtrDecl',
455 ['FuncDecl',
456 [['Decl', ['_Atomic', 'volatile'], 'q',
457 ['TypeDecl', ['IdentifierType', ['int']]]]],
458 ['TypeDecl', ['IdentifierType', ['int']]]]]])
459
460 self.assertEqual(self.get_decl('int (*k)(const volatile int* q);'),
461 ['Decl', 'k',
462 ['PtrDecl',
463 ['FuncDecl',
464 [['Decl', ['const', 'volatile'], 'q',
465 ['PtrDecl', ['TypeDecl', ['IdentifierType', ['int']]]]]],
466 ['TypeDecl', ['IdentifierType', ['int']]]]]])
467
468 # restrict qualifier
469 self.assertEqual(self.get_decl('int (*k)(restrict int* q);'),
470 ['Decl', 'k',
471 ['PtrDecl',
472 ['FuncDecl',
473 [['Decl', ['restrict'], 'q',
474 ['PtrDecl',
475 ['TypeDecl', ['IdentifierType', ['int']]]]]],
476 ['TypeDecl', ['IdentifierType', ['int']]]]]])
477
478 def test_func_decls_with_array_dim_qualifiers(self):
479 # named function parameter
480 self.assertEqual(self.get_decl('int zz(int p[static 10]);'),
481 ['Decl', 'zz',
482 ['FuncDecl',
483 [['Decl', 'p', ['ArrayDecl', '10', ['static'],
484 ['TypeDecl', ['IdentifierType', ['int']]]]]],
485 ['TypeDecl', ['IdentifierType', ['int']]]]])
486 # anonymous function parameter
487 self.assertEqual(self.get_decl('int zz(int [static 10]);'),
488 ['Decl', 'zz',
489 ['FuncDecl',
490 [['Typename',
491 ['ArrayDecl', '10', ['static'],
492 ['TypeDecl', ['IdentifierType', ['int']]]]]],
493 ['TypeDecl', ['IdentifierType', ['int']]]]])
494 self.assertEqual(self.get_decl('int zz(int [static const restrict 10]);'),
495 ['Decl', 'zz',
496 ['FuncDecl',
497 [['Typename',
498 ['ArrayDecl', '10', ['static', 'const', 'restrict'],
499 ['TypeDecl', ['IdentifierType', ['int']]]]]],
500 ['TypeDecl', ['IdentifierType', ['int']]]]])
501
502 self.assertEqual(self.get_decl('int zz(int p[const 10]);'),
503 ['Decl', 'zz',
504 ['FuncDecl',
505 [['Decl', 'p', ['ArrayDecl', '10', ['const'],
506 ['TypeDecl', ['IdentifierType', ['int']]]]]],
507 ['TypeDecl', ['IdentifierType', ['int']]]]])
508
509 self.assertEqual(self.get_decl('int zz(int p[restrict][5]);'),
510 ['Decl', 'zz',
511 ['FuncDecl',
512 [['Decl', 'p', ['ArrayDecl', '', ['restrict'],
513 ['ArrayDecl', '5', [],
514 ['TypeDecl', ['IdentifierType', ['int']]]]]]],
515 ['TypeDecl', ['IdentifierType', ['int']]]]])
516
517 self.assertEqual(self.get_decl('int zz(int p[const restrict static 10][5]);'),
518 ['Decl', 'zz',
519 ['FuncDecl',
520 [['Decl', 'p', ['ArrayDecl', '10', ['const', 'restrict', 'static'],
521 ['ArrayDecl', '5', [],
522 ['TypeDecl', ['IdentifierType', ['int']]]]]]],
523 ['TypeDecl', ['IdentifierType', ['int']]]]])
524
525 # unnamed function parameter
526 self.assertEqual(self.get_decl('int zz(int [const 10]);'),
527 ['Decl', 'zz',
528 ['FuncDecl',
529 [['Typename', ['ArrayDecl', '10', ['const'],
530 ['TypeDecl', ['IdentifierType', ['int']]]]]],
531 ['TypeDecl', ['IdentifierType', ['int']]]]])
532
533 self.assertEqual(self.get_decl('int zz(int [restrict][5]);'),
534 ['Decl', 'zz',
535 ['FuncDecl',
536 [['Typename', ['ArrayDecl', '', ['restrict'],
537 ['ArrayDecl', '5', [],
538 ['TypeDecl', ['IdentifierType', ['int']]]]]]],
539 ['TypeDecl', ['IdentifierType', ['int']]]]])
540
541 self.assertEqual(self.get_decl('int zz(int [const restrict volatile 10][5]);'),
542 ['Decl', 'zz',
543 ['FuncDecl',
544 [['Typename', ['ArrayDecl', '10', ['const', 'restrict', 'volatile'],
545 ['ArrayDecl', '5', [],
546 ['TypeDecl', ['IdentifierType', ['int']]]]]]],
547 ['TypeDecl', ['IdentifierType', ['int']]]]])
548
549 def test_qualifiers_storage_specifiers(self):
550 def assert_qs(txt, index, quals, storage):
551 d = self.parse(txt).ext[index]
552 self.assertEqual(d.quals, quals)
553 self.assertEqual(d.storage, storage)
554
555 assert_qs("extern int p;", 0, [], ['extern'])
556 assert_qs("_Thread_local int p;", 0, [], ['_Thread_local'])
557 assert_qs("const long p = 6;", 0, ['const'], [])
558 assert_qs("_Atomic int p;", 0, ['_Atomic'], [])
559 assert_qs("_Atomic restrict int* p;", 0, ['_Atomic', 'restrict'], [])
560
561 d1 = "static const int p, q, r;"
562 for i in range(3):
563 assert_qs(d1, i, ['const'], ['static'])
564
565 d2 = "static char * const p;"
566 assert_qs(d2, 0, [], ['static'])
567 pdecl = self.parse(d2).ext[0].type
568 self.assertIsInstance(pdecl, PtrDecl)
569 self.assertEqual(pdecl.quals, ['const'])
570
571 def test_atomic_specifier(self):
572 self.assertEqual(self.get_decl('_Atomic(int) ai;'),
573 ['Decl', ['_Atomic'],
574 'ai',
575 ['TypeDecl', ['IdentifierType', ['int']]]])
576
577 self.assertEqual(self.get_decl('_Atomic(int*) ai;'),
578 ['Decl',
579 'ai',
580 ['PtrDecl', ['_Atomic'], ['TypeDecl', ['IdentifierType', ['int']]]]])
581
582 self.assertEqual(self.get_decl('_Atomic(_Atomic(int)*) aai;'),
583 ['Decl', ['_Atomic'],
584 'aai',
585 ['PtrDecl', ['_Atomic'], ['TypeDecl', ['IdentifierType', ['int']]]]])
586
587 # Multiple declarations with _Atomic(...)
588 s = '_Atomic(int) foo, bar;'
589 self.assertEqual(self.get_decl(s, 0),
590 ['Decl', ['_Atomic'],
591 'foo',
592 ['TypeDecl', ['IdentifierType', ['int']]]])
593 self.assertEqual(self.get_decl(s, 1),
594 ['Decl', ['_Atomic'],
595 'bar',
596 ['TypeDecl', ['IdentifierType', ['int']]]])
597
598 # typedefs with _Atomic specifiers.
599 s = 'typedef _Atomic(int) atomic_int;'
600 self.assertEqual(self.get_decl(s, 0),
601 ['Typedef', 'atomic_int', ['TypeDecl', ['IdentifierType', ['int']]]])
602
603 s = 'typedef _Atomic(_Atomic(_Atomic(int (*)(void)) *) *) t;'
604 self.assertEqual(self.get_decl(s, 0),
605 ['Typedef', 't',
606 ['PtrDecl', ['_Atomic'],
607 ['PtrDecl', ['_Atomic'],
608 ['PtrDecl', ['_Atomic'],
609 ['FuncDecl', [['Typename', ['TypeDecl', ['IdentifierType', ['void']]]]],
610 ['TypeDecl', ['IdentifierType', ['int']]]]]]]])
611
612 def test_sizeof(self):
613 e = """
614 void foo()
615 {
616 int a = sizeof k;
617 int b = sizeof(int);
618 int c = sizeof(int**);;
619
620 char* p = "just to make sure this parses w/o error...";
621 int d = sizeof(int());
622 }
623 """
624 compound = self.parse(e).ext[0].body
625
626 s1 = compound.block_items[0].init
627 self.assertIsInstance(s1, UnaryOp)
628 self.assertEqual(s1.op, 'sizeof')
629 self.assertIsInstance(s1.expr, ID)
630 self.assertEqual(s1.expr.name, 'k')
631
632 s2 = compound.block_items[1].init
633 self.assertEqual(expand_decl(s2.expr),
634 ['Typename', ['TypeDecl', ['IdentifierType', ['int']]]])
635
636 s3 = compound.block_items[2].init
637 self.assertEqual(expand_decl(s3.expr),
638 ['Typename',
639 ['PtrDecl',
640 ['PtrDecl',
641 ['TypeDecl',
642 ['IdentifierType', ['int']]]]]])
643
644 def test_alignof(self):
645 r = self.parse('int a = _Alignof(int);')
646 self.assertEqual(expand_decl(r.ext[0]), ['Decl', 'a', ['TypeDecl', ['IdentifierType', ['int']]]])
647 self.assertEqual(expand_init(r.ext[0].init), ['UnaryOp', '_Alignof',
648 ['Typename', ['TypeDecl', ['IdentifierType', ['int']]]]])
649
650 self.assertEqual(expand_decl(self.parse('_Alignas(_Alignof(int)) char a;').ext[0]),
651 ['Decl', ['Alignas',
652 ['UnaryOp', '_Alignof', ['Typename', ['TypeDecl', ['IdentifierType', ['int']]]]]],
653 'a', ['TypeDecl', ['IdentifierType', ['char']]]])
654
655 self.assertEqual(expand_decl(self.parse('_Alignas(4) char a;').ext[0]),
656 ['Decl', ['Alignas',
657 ['Constant', 'int', '4']],
658 'a', ['TypeDecl', ['IdentifierType', ['char']]]])
659
660 self.assertEqual(expand_decl(self.parse('_Alignas(int) char a;').ext[0]),
661 ['Decl', ['Alignas',
662 ['Typename', ['TypeDecl', ['IdentifierType', ['int']]]]],
663 'a', ['TypeDecl', ['IdentifierType', ['char']]]])
664
665 def test_offsetof(self):
666 def expand_ref(n):
667 if isinstance(n, StructRef):
668 return ['StructRef', expand_ref(n.name), expand_ref(n.field)]
669 elif isinstance(n, ArrayRef):
670 return ['ArrayRef', expand_ref(n.name), expand_ref(n.subscript)]
671 elif isinstance(n, ID):
672 return ['ID', n.name]
673 elif isinstance(n, Constant):
674 return ['Constant', n.type, n.value]
675 else:
676 raise TypeError("Unexpected type " + n.__class__.__name__)
677
678 e = """
679 void foo() {
680 int a = offsetof(struct S, p);
681 a.b = offsetof(struct sockaddr, sp) + strlen(bar);
682 int a = offsetof(struct S, p.q.r);
683 int a = offsetof(struct S, p[5].q[4][5]);
684 }
685 """
686 compound = self.parse(e).ext[0].body
687 s1 = compound.block_items[0].init
688 self.assertIsInstance(s1, FuncCall)
689 self.assertIsInstance(s1.name, ID)
690 self.assertEqual(s1.name.name, 'offsetof')
691 self.assertIsInstance(s1.args.exprs[0], Typename)
692 self.assertIsInstance(s1.args.exprs[1], ID)
693 s3 = compound.block_items[2].init
694 self.assertIsInstance(s3.args.exprs[1], StructRef)
695 self.assertEqual(expand_ref(s3.args.exprs[1]),
696 ['StructRef',
697 ['StructRef', ['ID', 'p'], ['ID', 'q']],
698 ['ID', 'r']])
699 s4 = compound.block_items[3].init
700 self.assertIsInstance(s4.args.exprs[1], ArrayRef)
701 self.assertEqual(expand_ref(s4.args.exprs[1]),
702 ['ArrayRef',
703 ['ArrayRef',
704 ['StructRef',
705 ['ArrayRef', ['ID', 'p'], ['Constant', 'int', '5']],
706 ['ID', 'q']],
707 ['Constant', 'int', '4']],
708 ['Constant', 'int', '5']])
709
710 def test_compound_statement(self):
711 e = """
712 void foo() {
713 }
714 """
715 compound = self.parse(e).ext[0].body
716 self.assertIsInstance(compound, Compound)
717 self.assert_coord(compound, 2)
718
719 # The C99 compound literal feature
720 #
721 def test_compound_literals(self):
722 ps1 = self.parse(r'''
723 void foo() {
724 p = (long long){k};
725 tc = (struct jk){.a = {1, 2}, .b[0] = t};
726 }''')
727
728 compound = ps1.ext[0].body.block_items[0].rvalue
729 self.assertEqual(expand_decl(compound.type),
730 ['Typename', ['TypeDecl', ['IdentifierType', ['long', 'long']]]])
731 self.assertEqual(expand_init(compound.init),
732 [['ID', 'k']])
733
734 compound = ps1.ext[0].body.block_items[1].rvalue
735 self.assertEqual(expand_decl(compound.type),
736 ['Typename', ['TypeDecl', ['Struct', 'jk', []]]])
737 self.assertEqual(expand_init(compound.init),
738 [
739 ([['ID', 'a']], [['Constant', 'int', '1'], ['Constant', 'int', '2']]),
740 ([['ID', 'b'], ['Constant', 'int', '0']], ['ID', 't'])])
741
742 def test_parenthesized_compounds(self):
743 e = self.parse(r'''
744 void foo() {
745 int a;
746 ({});
747 ({ 1; });
748 ({ 1; 2; });
749 int b = ({ 1; });
750 int c, d = ({ int x = 1; x + 2; });
751 a = ({ int x = 1; 2 * x; });
752 }''')
753 body = e.ext[0].body.block_items
754
755 self.assertIsInstance(body[1], Compound)
756 self.assertEqual(body[1].block_items, None)
757
758 self.assertIsInstance(body[2], Compound)
759 self.assertEqual(len(body[2].block_items), 1)
760 self.assertIsInstance(body[2].block_items[0], Constant)
761
762 self.assertIsInstance(body[3], Compound)
763 self.assertEqual(len(body[3].block_items), 2)
764 self.assertIsInstance(body[3].block_items[0], Constant)
765 self.assertIsInstance(body[3].block_items[1], Constant)
766
767 self.assertIsInstance(body[4], Decl)
768 self.assertEqual(expand_init(body[4].init),
769 ['Compound', [['Constant', 'int', '1']]])
770
771 self.assertIsInstance(body[5], Decl)
772 self.assertEqual(body[5].init, None)
773
774 self.assertIsInstance(body[6], Decl)
775 self.assertEqual(expand_init(body[6].init),
776 ['Compound', [['Decl', 'x'], ['BinaryOp', ['ID', 'x'], '+', ['Constant', 'int', '2']]]])
777
778 self.assertIsInstance(body[7], Assignment)
779 self.assertIsInstance(body[7].rvalue, Compound)
780 self.assertEqual(expand_init(body[7].rvalue),
781 ['Compound', [['Decl', 'x'], ['BinaryOp', ['Constant', 'int', '2'], '*', ['ID', 'x']]]])
782
783 def test_enums(self):
784 e1 = "enum mycolor op;"
785 e1_type = self.parse(e1).ext[0].type.type
786
787 self.assertIsInstance(e1_type, Enum)
788 self.assertEqual(e1_type.name, 'mycolor')
789 self.assertEqual(e1_type.values, None)
790
791 e2 = "enum mysize {large=20, small, medium} shoes;"
792 e2_type = self.parse(e2).ext[0].type.type
793
794 self.assertIsInstance(e2_type, Enum)
795 self.assertEqual(e2_type.name, 'mysize')
796
797 e2_elist = e2_type.values
798 self.assertIsInstance(e2_elist, EnumeratorList)
799
800 for e2_eval in e2_elist.enumerators:
801 self.assertIsInstance(e2_eval, Enumerator)
802
803 self.assertEqual(e2_elist.enumerators[0].name, 'large')
804 self.assertEqual(e2_elist.enumerators[0].value.value, '20')
805 self.assertEqual(e2_elist.enumerators[2].name, 'medium')
806 self.assertEqual(e2_elist.enumerators[2].value, None)
807
808 # enum with trailing comma (C99 feature)
809 e3 = """
810 enum
811 {
812 red,
813 blue,
814 green,
815 } color;
816 """
817
818 e3_type = self.parse(e3).ext[0].type.type
819 self.assertIsInstance(e3_type, Enum)
820 e3_elist = e3_type.values
821 self.assertIsInstance(e3_elist, EnumeratorList)
822
823 for e3_eval in e3_elist.enumerators:
824 self.assertIsInstance(e3_eval, Enumerator)
825
826 self.assertEqual(e3_elist.enumerators[0].name, 'red')
827 self.assertEqual(e3_elist.enumerators[0].value, None)
828 self.assertEqual(e3_elist.enumerators[1].name, 'blue')
829 self.assertEqual(e3_elist.enumerators[2].name, 'green')
830
831 def test_typedef(self):
832 # without typedef, error
833 s1 = """
834 node k;
835 """
836 self.assertRaises(ParseError, self.parse, s1)
837
838 # now with typedef, works
839 s2 = """
840 typedef void* node;
841 node k;
842 """
843 ps2 = self.parse(s2)
844 self.assertEqual(expand_decl(ps2.ext[0]),
845 ['Typedef', 'node',
846 ['PtrDecl',
847 ['TypeDecl', ['IdentifierType', ['void']]]]])
848
849 self.assertEqual(expand_decl(ps2.ext[1]),
850 ['Decl', 'k',
851 ['TypeDecl', ['IdentifierType', ['node']]]])
852
853 s3 = """
854 typedef int T;
855 typedef T *pT;
856
857 pT aa, bb;
858 """
859 ps3 = self.parse(s3)
860 self.assertEqual(expand_decl(ps3.ext[3]),
861 ['Decl', 'bb',
862 ['TypeDecl', ['IdentifierType', ['pT']]]])
863
864 s4 = '''
865 typedef char* __builtin_va_list;
866 typedef __builtin_va_list __gnuc_va_list;
867 '''
868 ps4 = self.parse(s4)
869 self.assertEqual(expand_decl(ps4.ext[1]),
870 ['Typedef', '__gnuc_va_list',
871 ['TypeDecl',
872 ['IdentifierType', ['__builtin_va_list']]]])
873
874 s5 = '''typedef struct tagHash Hash;'''
875 ps5 = self.parse(s5)
876 self.assertEqual(expand_decl(ps5.ext[0]),
877 ['Typedef', 'Hash', ['TypeDecl', ['Struct', 'tagHash', []]]])
878
879 s6 = '''typedef int (* const * const T)(void);'''
880 ps6 = self.parse(s6)
881 self.assertEqual(expand_decl(ps6.ext[0]),
882 ['Typedef',
883 'T',
884 ['PtrDecl',
885 ['const'],
886 ['PtrDecl',
887 ['const'],
888 ['FuncDecl',
889 [['Typename', ['TypeDecl', ['IdentifierType', ['void']]]]],
890 ['TypeDecl', ['IdentifierType', ['int']]]]]]])
891
892 def test_struct_union(self):
893 s1 = """
894 struct {
895 int id;
896 char* name;
897 } joe;
898 """
899
900 self.assertEqual(expand_decl(self.parse(s1).ext[0]),
901 ['Decl', 'joe',
902 ['TypeDecl', ['Struct', None,
903 [ ['Decl', 'id',
904 ['TypeDecl',
905 ['IdentifierType', ['int']]]],
906 ['Decl', 'name',
907 ['PtrDecl',
908 ['TypeDecl',
909 ['IdentifierType', ['char']]]]]]]]])
910
911 s2 = """
912 struct node p;
913 """
914 self.assertEqual(expand_decl(self.parse(s2).ext[0]),
915 ['Decl', 'p',
916 ['TypeDecl', ['Struct', 'node', []]]])
917
918 s21 = """
919 union pri ra;
920 """
921 self.assertEqual(expand_decl(self.parse(s21).ext[0]),
922 ['Decl', 'ra',
923 ['TypeDecl', ['Union', 'pri', []]]])
924
925 s3 = """
926 struct node* p;
927 """
928 self.assertEqual(expand_decl(self.parse(s3).ext[0]),
929 ['Decl', 'p',
930 ['PtrDecl',
931 ['TypeDecl', ['Struct', 'node', []]]]])
932
933 s4 = """
934 struct node;
935 """
936 self.assertEqual(expand_decl(self.parse(s4).ext[0]),
937 ['Decl', None,
938 ['Struct', 'node', []]])
939
940 s5 = """
941 union
942 {
943 struct
944 {
945 int type;
946 } n;
947
948 struct
949 {
950 int type;
951 int intnode;
952 } ni;
953 } u;
954 """
955 self.assertEqual(expand_decl(self.parse(s5).ext[0]),
956 ['Decl', 'u',
957 ['TypeDecl',
958 ['Union', None,
959 [['Decl', 'n',
960 ['TypeDecl',
961 ['Struct', None,
962 [['Decl', 'type',
963 ['TypeDecl', ['IdentifierType', ['int']]]]]]]],
964 ['Decl', 'ni',
965 ['TypeDecl',
966 ['Struct', None,
967 [['Decl', 'type',
968 ['TypeDecl', ['IdentifierType', ['int']]]],
969 ['Decl', 'intnode',
970 ['TypeDecl', ['IdentifierType', ['int']]]]]]]]]]]])
971
972 s6 = """
973 typedef struct foo_tag
974 {
975 void* data;
976 } foo, *pfoo;
977 """
978 s6_ast = self.parse(s6)
979
980 self.assertEqual(expand_decl(s6_ast.ext[0]),
981 ['Typedef', 'foo',
982 ['TypeDecl',
983 ['Struct', 'foo_tag',
984 [['Decl', 'data',
985 ['PtrDecl', ['TypeDecl', ['IdentifierType', ['void']]]]]]]]])
986
987 self.assertEqual(expand_decl(s6_ast.ext[1]),
988 ['Typedef', 'pfoo',
989 ['PtrDecl',
990 ['TypeDecl',
991 ['Struct', 'foo_tag',
992 [['Decl', 'data',
993 ['PtrDecl', ['TypeDecl', ['IdentifierType', ['void']]]]]]]]]])
994
995 s7 = r"""
996 struct _on_exit_args {
997 void * _fnargs[32];
998 void * _dso_handle[32];
999
1000 long _fntypes;
1001 #line 77 "D:\eli\cpp_stuff\libc_include/sys/reent.h"
1002
1003 long _is_cxa;
1004 };
1005 """
1006
1007 s7_ast = self.parse(s7, filename='test.c')
1008 self.assert_coord(s7_ast.ext[0].type.decls[2], 6, 22, 'test.c')
1009 self.assert_coord(s7_ast.ext[0].type.decls[3], 78, 22,
1010 r'D:\eli\cpp_stuff\libc_include/sys/reent.h')
1011
1012 s8 = """
1013 typedef enum tagReturnCode {SUCCESS, FAIL} ReturnCode;
1014
1015 typedef struct tagEntry
1016 {
1017 char* key;
1018 char* value;
1019 } Entry;
1020
1021
1022 typedef struct tagNode
1023 {
1024 Entry* entry;
1025
1026 struct tagNode* next;
1027 } Node;
1028
1029 typedef struct tagHash
1030 {
1031 unsigned int table_size;
1032
1033 Node** heads;
1034
1035 } Hash;
1036 """
1037 s8_ast = self.parse(s8)
1038 self.assertEqual(expand_decl(s8_ast.ext[3]),
1039 ['Typedef', 'Hash',
1040 ['TypeDecl', ['Struct', 'tagHash',
1041 [['Decl', 'table_size',
1042 ['TypeDecl', ['IdentifierType', ['unsigned', 'int']]]],
1043 ['Decl', 'heads',
1044 ['PtrDecl', ['PtrDecl', ['TypeDecl', ['IdentifierType', ['Node']]]]]]]]]])
1045
1046 def test_struct_enum(self):
1047 s1 = """
1048 struct Foo {
1049 enum Bar { A = 1 };
1050 };
1051 """
1052 self.assertEqual(expand_decl(self.parse(s1).ext[0]),
1053 ['Decl', None,
1054 ['Struct', 'Foo',
1055 [['Decl', None,
1056 ['Enum', 'Bar', ['A']]]]]])
1057 s2 = """
1058 struct Foo {
1059 enum Bar { A = 1, B, C } bar;
1060 enum Baz { D = A } baz;
1061 } foo;
1062 """
1063 self.assertEqual(expand_decl(self.parse(s2).ext[0]),
1064 ['Decl', 'foo',
1065 ['TypeDecl', ['Struct', 'Foo',
1066 [['Decl', 'bar',
1067 ['TypeDecl', ['Enum', 'Bar', ['A', 'B', 'C']]]],
1068 ['Decl', 'baz',
1069 ['TypeDecl', ['Enum', 'Baz', ['D']]]]]]]])
1070
1071 def test_struct_with_extra_semis_inside(self):
1072 s1 = """
1073 struct {
1074 int a;;
1075 } foo;
1076 """
1077 s1_ast = self.parse(s1)
1078 self.assertEqual(expand_decl(s1_ast.ext[0]),
1079 ['Decl', 'foo',
1080 ['TypeDecl', ['Struct', None,
1081 [['Decl', 'a',
1082 ['TypeDecl', ['IdentifierType', ['int']]]]]]]])
1083
1084 s2 = """
1085 struct {
1086 int a;;;;
1087 float b, c;
1088 ;;
1089 char d;
1090 } foo;
1091 """
1092 s2_ast = self.parse(s2)
1093 self.assertEqual(expand_decl(s2_ast.ext[0]),
1094 ['Decl', 'foo',
1095 ['TypeDecl', ['Struct', None,
1096 [['Decl', 'a', ['TypeDecl', ['IdentifierType', ['int']]]],
1097 ['Decl', 'b', ['TypeDecl', ['IdentifierType', ['float']]]],
1098 ['Decl', 'c', ['TypeDecl', ['IdentifierType', ['float']]]],
1099 ['Decl', 'd',
1100 ['TypeDecl', ['IdentifierType', ['char']]]]]]]])
1101
1102 def test_struct_with_initial_semi(self):
1103 s1 = """
1104 struct {
1105 ;int a;
1106 } foo;
1107 """
1108 s1_ast = self.parse(s1)
1109 self.assertEqual(expand_decl(s1_ast.ext[0]),
1110 ['Decl', 'foo',
1111 ['TypeDecl', ['Struct', None,
1112 [['Decl', 'a',
1113 ['TypeDecl', ['IdentifierType', ['int']]]]]]]])
1114
1115 def test_anonymous_struct_union(self):
1116 s1 = """
1117 union
1118 {
1119 union
1120 {
1121 int i;
1122 long l;
1123 };
1124
1125 struct
1126 {
1127 int type;
1128 int intnode;
1129 };
1130 } u;
1131 """
1132
1133 self.assertEqual(expand_decl(self.parse(s1).ext[0]),
1134 ['Decl', 'u',
1135 ['TypeDecl',
1136 ['Union', None,
1137 [['Decl', None,
1138 ['Union', None,
1139 [['Decl', 'i',
1140 ['TypeDecl',
1141 ['IdentifierType', ['int']]]],
1142 ['Decl', 'l',
1143 ['TypeDecl',
1144 ['IdentifierType', ['long']]]]]]],
1145 ['Decl', None,
1146 ['Struct', None,
1147 [['Decl', 'type',
1148 ['TypeDecl',
1149 ['IdentifierType', ['int']]]],
1150 ['Decl', 'intnode',
1151 ['TypeDecl',
1152 ['IdentifierType', ['int']]]]]]]]]]])
1153
1154 s2 = """
1155 struct
1156 {
1157 int i;
1158 union
1159 {
1160 int id;
1161 char* name;
1162 };
1163 float f;
1164 } joe;
1165 """
1166
1167 self.assertEqual(expand_decl(self.parse(s2).ext[0]),
1168 ['Decl', 'joe',
1169 ['TypeDecl',
1170 ['Struct', None,
1171 [['Decl', 'i',
1172 ['TypeDecl',
1173 ['IdentifierType', ['int']]]],
1174 ['Decl', None,
1175 ['Union', None,
1176 [['Decl', 'id',
1177 ['TypeDecl',
1178 ['IdentifierType', ['int']]]],
1179 ['Decl', 'name',
1180 ['PtrDecl',
1181 ['TypeDecl',
1182 ['IdentifierType', ['char']]]]]]]],
1183 ['Decl', 'f',
1184 ['TypeDecl',
1185 ['IdentifierType', ['float']]]]]]]])
1186
1187 # ISO/IEC 9899:201x Committee Draft 2010-11-16, N1539
1188 # section 6.7.2.1, par. 19, example 1
1189 s3 = """
1190 struct v {
1191 union {
1192 struct { int i, j; };
1193 struct { long k, l; } w;
1194 };
1195 int m;
1196 } v1;
1197 """
1198
1199 self.assertEqual(expand_decl(self.parse(s3).ext[0]),
1200 ['Decl', 'v1',
1201 ['TypeDecl',
1202 ['Struct', 'v',
1203 [['Decl', None,
1204 ['Union', None,
1205 [['Decl', None,
1206 ['Struct', None,
1207 [['Decl', 'i',
1208 ['TypeDecl',
1209 ['IdentifierType', ['int']]]],
1210 ['Decl', 'j',
1211 ['TypeDecl',
1212 ['IdentifierType', ['int']]]]]]],
1213 ['Decl', 'w',
1214 ['TypeDecl',
1215 ['Struct', None,
1216 [['Decl', 'k',
1217 ['TypeDecl',
1218 ['IdentifierType', ['long']]]],
1219 ['Decl', 'l',
1220 ['TypeDecl',
1221 ['IdentifierType', ['long']]]]]]]]]]],
1222 ['Decl', 'm',
1223 ['TypeDecl',
1224 ['IdentifierType', ['int']]]]]]]])
1225
1226 s4 = """
1227 struct v {
1228 int i;
1229 float;
1230 } v2;"""
1231 # just make sure this doesn't raise ParseError
1232 self.parse(s4)
1233
1234 def test_struct_members_namespace(self):
1235 """ Tests that structure/union member names reside in a separate
1236 namespace and can be named after existing types.
1237 """
1238 s1 = """
1239 typedef int Name;
1240 typedef Name NameArray[10];
1241
1242 struct {
1243 Name Name;
1244 Name NameArray[3];
1245 } sye;
1246
1247 void main(void)
1248 {
1249 sye.Name = 1;
1250 }
1251 """
1252
1253 s1_ast = self.parse(s1)
1254 self.assertEqual(expand_decl(s1_ast.ext[2]),
1255 ['Decl', 'sye',
1256 ['TypeDecl', ['Struct', None,
1257 [ ['Decl', 'Name',
1258 ['TypeDecl',
1259 ['IdentifierType', ['Name']]]],
1260 ['Decl', 'NameArray',
1261 ['ArrayDecl', '3', [],
1262 ['TypeDecl', ['IdentifierType', ['Name']]]]]]]]])
1263 self.assertEqual(s1_ast.ext[3].body.block_items[0].lvalue.field.name, 'Name')
1264
1265 def test_struct_bitfields(self):
1266 # a struct with two bitfields, one unnamed
1267 s1 = """
1268 struct {
1269 int k:6;
1270 int :2;
1271 } joe;
1272 """
1273
1274 parsed_struct = self.parse(s1).ext[0]
1275
1276 # We can see here the name of the decl for the unnamed bitfield is
1277 # None, but expand_decl doesn't show bitfield widths
1278 # ...
1279 self.assertEqual(expand_decl(parsed_struct),
1280 ['Decl', 'joe',
1281 ['TypeDecl', ['Struct', None,
1282 [ ['Decl', 'k',
1283 ['TypeDecl',
1284 ['IdentifierType', ['int']]]],
1285 ['Decl', None,
1286 ['TypeDecl',
1287 ['IdentifierType', ['int']]]]]]]])
1288
1289 # ...
1290 # so we test them manually
1291 self.assertEqual(parsed_struct.type.type.decls[0].bitsize.value, '6')
1292 self.assertEqual(parsed_struct.type.type.decls[1].bitsize.value, '2')
1293
1294 def test_struct_empty(self):
1295 """
1296 Tests that parsing an empty struct works.
1297
1298 Empty structs do NOT follow C99 (See 6.2.5-20 of the C99 standard).
1299 This is nevertheless supported by some compilers (clang, gcc),
1300 especially when using FORTIFY code.
1301 Some compilers (visual) will fail to compile with an error.
1302 """
1303 # an empty struct. This is NOT C99 compliant
1304 s1 = """
1305 struct foo { };
1306 """
1307
1308 parsed_struct = self.parse(s1).ext[0]
1309 self.assertEqual(expand_decl(parsed_struct),
1310 ['Decl', None, ['Struct', 'foo', []]])
1311
1312 s2 = """struct { } foo;"""
1313 parsed_struct = self.parse(s2).ext[0]
1314 self.assertEqual(expand_decl(parsed_struct),
1315 ['Decl', 'foo', ['TypeDecl', ['Struct', None, []]]])
1316
1317 s3 = """union { } foo;"""
1318 parsed_struct = self.parse(s3).ext[0]
1319 self.assertEqual(expand_decl(parsed_struct),
1320 ['Decl', 'foo', ['TypeDecl', ['Union', None, []]]])
1321
1322 def test_tags_namespace(self):
1323 """ Tests that the tags of structs/unions/enums reside in a separate namespace and
1324 can be named after existing types.
1325 """
1326 s1 = """
1327 typedef int tagEntry;
1328
1329 struct tagEntry
1330 {
1331 char* key;
1332 char* value;
1333 } Entry;
1334 """
1335
1336 s1_ast = self.parse(s1)
1337 self.assertEqual(expand_decl(s1_ast.ext[1]),
1338 ['Decl', 'Entry',
1339 ['TypeDecl', ['Struct', 'tagEntry',
1340 [['Decl', 'key',
1341 ['PtrDecl', ['TypeDecl', ['IdentifierType', ['char']]]]],
1342 ['Decl', 'value',
1343 ['PtrDecl', ['TypeDecl', ['IdentifierType', ['char']]]]]]]]])
1344
1345 s2 = """
1346 struct tagEntry;
1347
1348 typedef struct tagEntry tagEntry;
1349
1350 struct tagEntry
1351 {
1352 char* key;
1353 char* value;
1354 } Entry;
1355 """
1356
1357 s2_ast = self.parse(s2)
1358 self.assertEqual(expand_decl(s2_ast.ext[2]),
1359 ['Decl', 'Entry',
1360 ['TypeDecl', ['Struct', 'tagEntry',
1361 [['Decl', 'key',
1362 ['PtrDecl', ['TypeDecl', ['IdentifierType', ['char']]]]],
1363 ['Decl', 'value',
1364 ['PtrDecl', ['TypeDecl', ['IdentifierType', ['char']]]]]]]]])
1365
1366 s3 = """
1367 typedef int mytag;
1368
1369 enum mytag {ABC, CDE};
1370 enum mytag joe;
1371 """
1372
1373 s3_type = self.parse(s3).ext[1].type
1374
1375 self.assertIsInstance(s3_type, Enum)
1376 self.assertEqual(s3_type.name, 'mytag')
1377
1378 def test_multi_decls(self):
1379 d1 = 'int a, b;'
1380
1381 self.assertEqual(self.get_decl(d1, 0),
1382 ['Decl', 'a', ['TypeDecl', ['IdentifierType', ['int']]]])
1383 self.assertEqual(self.get_decl(d1, 1),
1384 ['Decl', 'b', ['TypeDecl', ['IdentifierType', ['int']]]])
1385
1386 d2 = 'char* p, notp, ar[4];'
1387 self.assertEqual(self.get_decl(d2, 0),
1388 ['Decl', 'p',
1389 ['PtrDecl',
1390 ['TypeDecl', ['IdentifierType', ['char']]]]])
1391 self.assertEqual(self.get_decl(d2, 1),
1392 ['Decl', 'notp', ['TypeDecl', ['IdentifierType', ['char']]]])
1393 self.assertEqual(self.get_decl(d2, 2),
1394 ['Decl', 'ar',
1395 ['ArrayDecl', '4', [],
1396 ['TypeDecl', ['IdentifierType', ['char']]]]])
1397
1398 def test_invalid_multiple_types_error(self):
1399 bad = [
1400 'int enum {ab, cd} fubr;',
1401 'enum kid char brbr;']
1402
1403 for b in bad:
1404 self.assertRaises(ParseError, self.parse, b)
1405
1406 def test_invalid_typedef_storage_qual_error(self):
1407 """ Tests that using typedef as a storage qualifier is correctly flagged
1408 as an error.
1409 """
1410 bad = 'typedef const int foo(int a) { return 0; }'
1411 self.assertRaises(ParseError, self.parse, bad)
1412
1413 def test_duplicate_typedef(self):
1414 """ Tests that redeclarations of existing types are parsed correctly.
1415 This is non-standard, but allowed by many compilers.
1416 """
1417 d1 = '''
1418 typedef int numbertype;
1419 typedef int numbertype;
1420 '''
1421
1422 self.assertEqual(self.get_decl(d1, 0),
1423 ['Typedef', 'numbertype',
1424 ['TypeDecl', ['IdentifierType', ['int']]]])
1425 self.assertEqual(self.get_decl(d1, 1),
1426 ['Typedef', 'numbertype',
1427 ['TypeDecl', ['IdentifierType', ['int']]]])
1428
1429 d2 = '''
1430 typedef int (*funcptr)(int x);
1431 typedef int (*funcptr)(int x);
1432 '''
1433 self.assertEqual(self.get_decl(d2, 0),
1434 ['Typedef', 'funcptr',
1435 ['PtrDecl', ['FuncDecl',
1436 [['Decl', 'x', ['TypeDecl', ['IdentifierType', ['int']]]]],
1437 ['TypeDecl', ['IdentifierType', ['int']]]]]])
1438 self.assertEqual(self.get_decl(d2, 1),
1439 ['Typedef', 'funcptr',
1440 ['PtrDecl', ['FuncDecl',
1441 [['Decl', 'x', ['TypeDecl', ['IdentifierType', ['int']]]]],
1442 ['TypeDecl', ['IdentifierType', ['int']]]]]])
1443
1444 d3 = '''
1445 typedef int numberarray[5];
1446 typedef int numberarray[5];
1447 '''
1448 self.assertEqual(self.get_decl(d3, 0),
1449 ['Typedef', 'numberarray',
1450 ['ArrayDecl', '5', [],
1451 ['TypeDecl', ['IdentifierType', ['int']]]]])
1452 self.assertEqual(self.get_decl(d3, 1),
1453 ['Typedef', 'numberarray',
1454 ['ArrayDecl', '5', [],
1455 ['TypeDecl', ['IdentifierType', ['int']]]]])
1456
1457 def test_decl_inits(self):
1458 d1 = 'int a = 16;'
1459 #~ self.parse(d1).show()
1460 self.assertEqual(self.get_decl(d1),
1461 ['Decl', 'a', ['TypeDecl', ['IdentifierType', ['int']]]])
1462 self.assertEqual(self.get_decl_init(d1),
1463 ['Constant', 'int', '16'])
1464
1465 d1_1 = 'float f = 0xEF.56p1;'
1466 self.assertEqual(self.get_decl_init(d1_1),
1467 ['Constant', 'double', '0xEF.56p1'])
1468
1469 d1_2 = 'int bitmask = 0b1001010;'
1470 self.assertEqual(self.get_decl_init(d1_2),
1471 ['Constant', 'int', '0b1001010'])
1472
1473 d2 = 'long ar[] = {7, 8, 9};'
1474 self.assertEqual(self.get_decl(d2),
1475 ['Decl', 'ar',
1476 ['ArrayDecl', '', [],
1477 ['TypeDecl', ['IdentifierType', ['long']]]]])
1478 self.assertEqual(self.get_decl_init(d2),
1479 [ ['Constant', 'int', '7'],
1480 ['Constant', 'int', '8'],
1481 ['Constant', 'int', '9']])
1482
1483 d21 = 'long ar[4] = {};'
1484 self.assertEqual(self.get_decl_init(d21), [])
1485
1486 d3 = 'char p = j;'
1487 self.assertEqual(self.get_decl(d3),
1488 ['Decl', 'p', ['TypeDecl', ['IdentifierType', ['char']]]])
1489 self.assertEqual(self.get_decl_init(d3),
1490 ['ID', 'j'])
1491
1492 d4 = "char x = 'c', *p = {0, 1, 2, {4, 5}, 6};"
1493 self.assertEqual(self.get_decl(d4, 0),
1494 ['Decl', 'x', ['TypeDecl', ['IdentifierType', ['char']]]])
1495 self.assertEqual(self.get_decl_init(d4, 0),
1496 ['Constant', 'char', "'c'"])
1497 self.assertEqual(self.get_decl(d4, 1),
1498 ['Decl', 'p',
1499 ['PtrDecl',
1500 ['TypeDecl', ['IdentifierType', ['char']]]]])
1501
1502 self.assertEqual(self.get_decl_init(d4, 1),
1503 [ ['Constant', 'int', '0'],
1504 ['Constant', 'int', '1'],
1505 ['Constant', 'int', '2'],
1506 [['Constant', 'int', '4'],
1507 ['Constant', 'int', '5']],
1508 ['Constant', 'int', '6']])
1509
1510 d5 = 'float d = 1.0;'
1511 self.assertEqual(self.get_decl_init(d5),
1512 ['Constant', 'double', '1.0'])
1513
1514 d51 = 'float ld = 1.0l;'
1515 self.assertEqual(self.get_decl_init(d51),
1516 ['Constant', 'long double', '1.0l'])
1517
1518 d52 = 'float ld = 1.0L;'
1519 self.assertEqual(self.get_decl_init(d52),
1520 ['Constant', 'long double', '1.0L'])
1521
1522 d53 = 'float ld = 1.0f;'
1523 self.assertEqual(self.get_decl_init(d53),
1524 ['Constant', 'float', '1.0f'])
1525
1526 d54 = 'float ld = 1.0F;'
1527 self.assertEqual(self.get_decl_init(d54),
1528 ['Constant', 'float', '1.0F'])
1529
1530 d55 = 'float ld = 0xDE.38p0;'
1531 self.assertEqual(self.get_decl_init(d55),
1532 ['Constant', 'double', '0xDE.38p0'])
1533
1534 d56 = 'float ld = 0xDE.38p0f;'
1535 self.assertEqual(self.get_decl_init(d56),
1536 ['Constant', 'float', '0xDE.38p0f'])
1537
1538 d57 = 'float ld = 0xDE.38p0F;'
1539 self.assertEqual(self.get_decl_init(d57),
1540 ['Constant', 'float', '0xDE.38p0F'])
1541
1542 d58 = 'float ld = 0xDE.38p0l;'
1543 self.assertEqual(self.get_decl_init(d58),
1544 ['Constant', 'long double', '0xDE.38p0l'])
1545
1546 d59 = 'float ld = 0xDE.38p0L;'
1547 self.assertEqual(self.get_decl_init(d59),
1548 ['Constant', 'long double', '0xDE.38p0L'])
1549
1550 d6 = 'int i = 1;'
1551 self.assertEqual(self.get_decl_init(d6),
1552 ['Constant', 'int', '1'])
1553
1554 d61 = 'long int li = 1l;'
1555 self.assertEqual(self.get_decl_init(d61),
1556 ['Constant', 'long int', '1l'])
1557
1558 d62 = 'unsigned int ui = 1u;'
1559 self.assertEqual(self.get_decl_init(d62),
1560 ['Constant', 'unsigned int', '1u'])
1561
1562 d63 = 'unsigned long long int ulli = 1LLU;'
1563 self.assertEqual(self.get_decl_init(d63),
1564 ['Constant', 'unsigned long long int', '1LLU'])
1565
1566 def test_decl_named_inits(self):
1567 d1 = 'int a = {.k = 16};'
1568 self.assertEqual(self.get_decl_init(d1),
1569 [( [['ID', 'k']],
1570 ['Constant', 'int', '16'])])
1571
1572 d2 = 'int a = { [0].a = {1}, [1].a[0] = 2 };'
1573 self.assertEqual(self.get_decl_init(d2),
1574 [
1575 ([['Constant', 'int', '0'], ['ID', 'a']],
1576 [['Constant', 'int', '1']]),
1577 ([['Constant', 'int', '1'], ['ID', 'a'], ['Constant', 'int', '0']],
1578 ['Constant', 'int', '2'])])
1579
1580 d3 = 'int a = { .a = 1, .c = 3, 4, .b = 5};'
1581 self.assertEqual(self.get_decl_init(d3),
1582 [
1583 ([['ID', 'a']], ['Constant', 'int', '1']),
1584 ([['ID', 'c']], ['Constant', 'int', '3']),
1585 ['Constant', 'int', '4'],
1586 ([['ID', 'b']], ['Constant', 'int', '5'])])
1587
1588 def test_function_definitions(self):
1589 def parse_fdef(str):
1590 return self.parse(str).ext[0]
1591
1592 def fdef_decl(fdef):
1593 return expand_decl(fdef.decl)
1594
1595 f1 = parse_fdef('''
1596 int factorial(int p)
1597 {
1598 return 3;
1599 }
1600 ''')
1601
1602 self.assertEqual(fdef_decl(f1),
1603 ['Decl', 'factorial',
1604 ['FuncDecl',
1605 [['Decl', 'p', ['TypeDecl', ['IdentifierType', ['int']]]]],
1606 ['TypeDecl', ['IdentifierType', ['int']]]]])
1607
1608 self.assertEqual(type(f1.body.block_items[0]), Return)
1609
1610 f2 = parse_fdef('''
1611 char* zzz(int p, char* c)
1612 {
1613 int a;
1614 char b;
1615
1616 a = b + 2;
1617 return 3;
1618 }
1619 ''')
1620
1621 self.assertEqual(fdef_decl(f2),
1622 ['Decl', 'zzz',
1623 ['FuncDecl',
1624 [ ['Decl', 'p', ['TypeDecl', ['IdentifierType', ['int']]]],
1625 ['Decl', 'c', ['PtrDecl',
1626 ['TypeDecl', ['IdentifierType', ['char']]]]]],
1627 ['PtrDecl', ['TypeDecl', ['IdentifierType', ['char']]]]]])
1628
1629 self.assertEqual(list(map(type, f2.body.block_items)),
1630 [Decl, Decl, Assignment, Return])
1631
1632 f3 = parse_fdef('''
1633 char* zzz(p, c)
1634 long p, *c;
1635 {
1636 int a;
1637 char b;
1638
1639 a = b + 2;
1640 return 3;
1641 }
1642 ''')
1643
1644 self.assertEqual(fdef_decl(f3),
1645 ['Decl', 'zzz',
1646 ['FuncDecl',
1647 [ ['ID', 'p'],
1648 ['ID', 'c']],
1649 ['PtrDecl', ['TypeDecl', ['IdentifierType', ['char']]]]]])
1650
1651 self.assertEqual(list(map(type, f3.body.block_items)),
1652 [Decl, Decl, Assignment, Return])
1653
1654 self.assertEqual(expand_decl(f3.param_decls[0]),
1655 ['Decl', 'p', ['TypeDecl', ['IdentifierType', ['long']]]])
1656 self.assertEqual(expand_decl(f3.param_decls[1]),
1657 ['Decl', 'c', ['PtrDecl', ['TypeDecl', ['IdentifierType', ['long']]]]])
1658
1659 # function return values and parameters may not have type information
1660 f4 = parse_fdef('''
1661 que(p)
1662 {
1663 return 3;
1664 }
1665 ''')
1666
1667 self.assertEqual(fdef_decl(f4),
1668 ['Decl', 'que',
1669 ['FuncDecl',
1670 [['ID', 'p']],
1671 ['TypeDecl', ['IdentifierType', ['int']]]]])
1672
1673 def test_static_assert(self):
1674 f1 = self.parse('''
1675 _Static_assert(1, "123");
1676 int factorial(int p)
1677 {
1678 _Static_assert(2, "456");
1679 _Static_assert(3);
1680 }
1681 ''')
1682
1683 self.assertEqual(expand_decl(f1.ext[0]), ['StaticAssert', '1', '"123"'])
1684 self.assertEqual(expand_decl(f1.ext[1].body.block_items[0]), ['StaticAssert', '2', '"456"'])
1685 self.assertEqual(expand_decl(f1.ext[1].body.block_items[2]), ['StaticAssert', '3'])
1686
1687 def test_unified_string_literals(self):
1688 # simple string, for reference
1689 d1 = self.get_decl_init('char* s = "hello";')
1690 self.assertEqual(d1, ['Constant', 'string', '"hello"'])
1691
1692 d2 = self.get_decl_init('char* s = "hello" " world";')
1693 self.assertEqual(d2, ['Constant', 'string', '"hello world"'])
1694
1695 # the test case from issue 6
1696 d3 = self.parse(r'''
1697 int main() {
1698 fprintf(stderr,
1699 "Wrong Params?\n"
1700 "Usage:\n"
1701 "%s <binary_file_path>\n",
1702 argv[0]
1703 );
1704 }
1705 ''')
1706
1707 self.assertEqual(
1708 d3.ext[0].body.block_items[0].args.exprs[1].value,
1709 r'"Wrong Params?\nUsage:\n%s <binary_file_path>\n"')
1710
1711 d4 = self.get_decl_init('char* s = "" "foobar";')
1712 self.assertEqual(d4, ['Constant', 'string', '"foobar"'])
1713
1714 d5 = self.get_decl_init(r'char* s = "foo\"" "bar";')
1715 self.assertEqual(d5, ['Constant', 'string', r'"foo\"bar"'])
1716
1717 # This is not correct based on the the C spec, but testing it here to
1718 # see the behavior in action. Will have to fix this
1719 # for https://github.com/eliben/pycparser/issues/392
1720 #
1721 # The spec says in section 6.4.5 that "escape sequences are converted
1722 # into single members of the execution character set just prior to
1723 # adjacent string literal concatenation".
1724 d6 = self.get_decl_init(r'char* s = "\1" "23";')
1725 self.assertEqual(d6, ['Constant', 'string', r'"\123"'])
1726
1727 def test_unified_wstring_literals(self):
1728 d1 = self.get_decl_init('char* s = L"hello" L"world";')
1729 self.assertEqual(d1, ['Constant', 'string', 'L"helloworld"'])
1730
1731 d2 = self.get_decl_init('char* s = L"hello " L"world" L" and I";')
1732 self.assertEqual(d2, ['Constant', 'string', 'L"hello world and I"'])
1733
1734 def test_inline_specifier(self):
1735 ps2 = self.parse('static inline void inlinefoo(void);')
1736 self.assertEqual(ps2.ext[0].funcspec, ['inline'])
1737
1738 def test_noreturn_specifier(self):
1739 ps2 = self.parse('static _Noreturn void noreturnfoo(void);')
1740 self.assertEqual(ps2.ext[0].funcspec, ['_Noreturn'])
1741
1742 # variable length array
1743 def test_vla(self):
1744 ps2 = self.parse(r'''
1745 int main() {
1746 int size;
1747 int var[size = 5];
1748
1749 int var2[*];
1750 }
1751 ''')
1752 self.assertIsInstance(ps2.ext[0].body.block_items[1].type.dim, Assignment)
1753 self.assertIsInstance(ps2.ext[0].body.block_items[2].type.dim, ID)
1754
1755 def test_pragma(self):
1756 s1 = r'''
1757 #pragma bar
1758 void main() {
1759 #pragma foo
1760 for(;;) {}
1761 #pragma baz
1762 {
1763 int i = 0;
1764 }
1765 #pragma
1766 }
1767 struct s {
1768 #pragma baz
1769 } s;
1770 _Pragma("other \"string\"")
1771 '''
1772 s1_ast = self.parse(s1)
1773 self.assertIsInstance(s1_ast.ext[0], Pragma)
1774 self.assertEqual(s1_ast.ext[0].string, 'bar')
1775 self.assertEqual(s1_ast.ext[0].coord.line, 2)
1776
1777 self.assertIsInstance(s1_ast.ext[1].body.block_items[0], Pragma)
1778 self.assertEqual(s1_ast.ext[1].body.block_items[0].string, 'foo')
1779 self.assertEqual(s1_ast.ext[1].body.block_items[0].coord.line, 4)
1780
1781 self.assertIsInstance(s1_ast.ext[1].body.block_items[2], Pragma)
1782 self.assertEqual(s1_ast.ext[1].body.block_items[2].string, 'baz')
1783 self.assertEqual(s1_ast.ext[1].body.block_items[2].coord.line, 6)
1784
1785 self.assertIsInstance(s1_ast.ext[1].body.block_items[4], Pragma)
1786 self.assertEqual(s1_ast.ext[1].body.block_items[4].string, '')
1787 self.assertEqual(s1_ast.ext[1].body.block_items[4].coord.line, 10)
1788
1789 self.assertIsInstance(s1_ast.ext[2].type.type.decls[0], Pragma)
1790 self.assertEqual(s1_ast.ext[2].type.type.decls[0].string, 'baz')
1791 self.assertEqual(s1_ast.ext[2].type.type.decls[0].coord.line, 13)
1792
1793 self.assertIsInstance(s1_ast.ext[3], Pragma)
1794 self.assertEqual(s1_ast.ext[3].string.value, r'"other \"string\""')
1795 self.assertEqual(s1_ast.ext[3].coord.line, 15)
1796
1797 def test_pragmacomp_or_statement(self):
1798 s1 = r'''
1799 void main() {
1800 int sum = 0;
1801 for (int i; i < 3; i++)
1802 #pragma omp critical
1803 sum += 1;
1804
1805 while(sum < 10)
1806 #pragma omp critical
1807 sum += 1;
1808
1809 mylabel:
1810 #pragma foo
1811 sum += 10;
1812
1813 if (sum > 10)
1814 #pragma bar
1815 #pragma baz
1816 sum = 10;
1817
1818 switch (sum)
1819 case 10:
1820 #pragma foo
1821 sum = 20;
1822 }
1823 '''
1824 s1_ast = self.parse(s1)
1825 self.assertIsInstance(s1_ast.ext[0].body.block_items[1], For)
1826 self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt, Compound)
1827 self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[0], Pragma)
1828 self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[1], Assignment)
1829 self.assertIsInstance(s1_ast.ext[0].body.block_items[2], While)
1830 self.assertIsInstance(s1_ast.ext[0].body.block_items[2].stmt, Compound)
1831 self.assertIsInstance(s1_ast.ext[0].body.block_items[2].stmt.block_items[0], Pragma)
1832 self.assertIsInstance(s1_ast.ext[0].body.block_items[2].stmt.block_items[1], Assignment)
1833 self.assertIsInstance(s1_ast.ext[0].body.block_items[3], Label)
1834 self.assertIsInstance(s1_ast.ext[0].body.block_items[3].stmt, Compound)
1835 self.assertIsInstance(s1_ast.ext[0].body.block_items[3].stmt.block_items[0], Pragma)
1836 self.assertIsInstance(s1_ast.ext[0].body.block_items[3].stmt.block_items[1], Assignment)
1837 self.assertIsInstance(s1_ast.ext[0].body.block_items[4], If)
1838 self.assertIsInstance(s1_ast.ext[0].body.block_items[4].iftrue, Compound)
1839 self.assertIsInstance(s1_ast.ext[0].body.block_items[4].iftrue.block_items[0], Pragma)
1840 self.assertIsInstance(s1_ast.ext[0].body.block_items[4].iftrue.block_items[1], Pragma)
1841 self.assertIsInstance(s1_ast.ext[0].body.block_items[4].iftrue.block_items[2], Assignment)
1842 self.assertIsInstance(s1_ast.ext[0].body.block_items[5], Switch)
1843 self.assertIsInstance(s1_ast.ext[0].body.block_items[5].stmt.stmts[0], Compound)
1844 self.assertIsInstance(s1_ast.ext[0].body.block_items[5].stmt.stmts[0].block_items[0],
1845 Pragma)
1846 self.assertIsInstance(s1_ast.ext[0].body.block_items[5].stmt.stmts[0].block_items[1],
1847 Assignment)
1848
1849
1850 class TestCParser_whole_code(TestCParser_base):
1851 """ Testing of parsing whole chunks of code.
1852
1853 Since I don't want to rely on the structure of ASTs too
1854 much, most of these tests are implemented with visitors.
1855 """
1856 # A simple helper visitor that lists the values of all the
1857 # Constant nodes it sees.
1858 #
1859 class ConstantVisitor(NodeVisitor):
1860 def __init__(self):
1861 self.values = []
1862
1863 def visit_Constant(self, node):
1864 self.values.append(node.value)
1865
1866 # This visitor counts the amount of references to the ID
1867 # with the name provided to it in the constructor.
1868 #
1869 class IDNameCounter(NodeVisitor):
1870 def __init__(self, name):
1871 self.name = name
1872 self.nrefs = 0
1873
1874 def visit_ID(self, node):
1875 if node.name == self.name:
1876 self.nrefs += 1
1877
1878 # Counts the amount of nodes of a given class
1879 #
1880 class NodeKlassCounter(NodeVisitor):
1881 def __init__(self, node_klass):
1882 self.klass = node_klass
1883 self.n = 0
1884
1885 def generic_visit(self, node):
1886 if node.__class__ == self.klass:
1887 self.n += 1
1888
1889 NodeVisitor.generic_visit(self, node)
1890
1891 def assert_all_Constants(self, code, constants):
1892 """ Asserts that the list of all Constant values (by
1893 'preorder' appearance) in the chunk of code is as
1894 given.
1895 """
1896 if isinstance(code, str):
1897 parsed = self.parse(code)
1898 else:
1899 parsed = code
1900
1901 cv = self.ConstantVisitor()
1902 cv.visit(parsed)
1903 self.assertEqual(cv.values, constants)
1904
1905 def assert_num_ID_refs(self, code, name, num):
1906 """ Asserts the number of references to the ID with
1907 the given name.
1908 """
1909 if isinstance(code, str):
1910 parsed = self.parse(code)
1911 else:
1912 parsed = code
1913
1914 iv = self.IDNameCounter(name)
1915 iv.visit(parsed)
1916 self.assertEqual(iv.nrefs, num)
1917
1918 def assert_num_klass_nodes(self, code, klass, num):
1919 """ Asserts the amount of klass nodes in the code.
1920 """
1921 if isinstance(code, str):
1922 parsed = self.parse(code)
1923 else:
1924 parsed = code
1925
1926 cv = self.NodeKlassCounter(klass)
1927 cv.visit(parsed)
1928 self.assertEqual(cv.n, num)
1929
1930 def test_expressions(self):
1931 e1 = '''int k = (r + 10.0) >> 6 + 8 << (3 & 0x14);'''
1932 self.assert_all_Constants(e1, ['10.0', '6', '8', '3', '0x14'])
1933
1934 e2 = r'''char n = '\n', *prefix = "st_";'''
1935 self.assert_all_Constants(e2, [r"'\n'", '"st_"'])
1936
1937 s1 = r'''int main() {
1938 int i = 5, j = 6, k = 1;
1939 if ((i=j && k == 1) || k > j)
1940 printf("Hello, world\n");
1941 return 0;
1942 }'''
1943 ps1 = self.parse(s1)
1944 self.assert_all_Constants(ps1,
1945 ['5', '6', '1', '1', '"Hello, world\\n"', '0'])
1946 self.assert_num_ID_refs(ps1, 'i', 1)
1947 self.assert_num_ID_refs(ps1, 'j', 2)
1948
1949
1950 def test_statements(self):
1951 s1 = r'''
1952 void foo(){
1953 if (sp == 1)
1954 if (optind >= argc ||
1955 argv[optind][0] != '-' || argv[optind][1] == '\0')
1956 return -1;
1957 else if (strcmp(argv[optind], "--") == 0) {
1958 optind++;
1959 return -1;
1960 }
1961 }
1962 '''
1963
1964 self.assert_all_Constants(s1,
1965 ['1', '0', r"'-'", '1', r"'\0'", '1', r'"--"', '0', '1'])
1966
1967 ps1 = self.parse(s1)
1968 self.assert_num_ID_refs(ps1, 'argv', 3)
1969 self.assert_num_ID_refs(ps1, 'optind', 5)
1970
1971 self.assert_num_klass_nodes(ps1, If, 3)
1972 self.assert_num_klass_nodes(ps1, Return, 2)
1973 self.assert_num_klass_nodes(ps1, FuncCall, 1) # strcmp
1974 self.assert_num_klass_nodes(ps1, BinaryOp, 7)
1975
1976 # In the following code, Hash and Node were defined as
1977 # int to pacify the parser that sees they're used as
1978 # types
1979 #
1980 s2 = r'''
1981 typedef int Hash, Node;
1982
1983 void HashDestroy(Hash* hash)
1984 {
1985 unsigned int i;
1986
1987 if (hash == NULL)
1988 return;
1989
1990 for (i = 0; i < hash->table_size; ++i)
1991 {
1992 Node* temp = hash->heads[i];
1993
1994 while (temp != NULL)
1995 {
1996 Node* temp2 = temp;
1997
1998 free(temp->entry->key);
1999 free(temp->entry->value);
2000 free(temp->entry);
2001
2002 temp = temp->next;
2003
2004 free(temp2);
2005 }
2006 }
2007
2008 free(hash->heads);
2009 hash->heads = NULL;
2010
2011 free(hash);
2012 }
2013 '''
2014
2015 ps2 = self.parse(s2)
2016 self.assert_num_klass_nodes(ps2, FuncCall, 6)
2017 self.assert_num_klass_nodes(ps2, FuncDef, 1)
2018 self.assert_num_klass_nodes(ps2, For, 1)
2019 self.assert_num_klass_nodes(ps2, While, 1)
2020 self.assert_num_klass_nodes(ps2, StructRef, 10)
2021
2022 # declarations don't count
2023 self.assert_num_ID_refs(ps2, 'hash', 6)
2024 self.assert_num_ID_refs(ps2, 'i', 4)
2025
2026 s3 = r'''
2027 void x(void) {
2028 int a, b;
2029 if (a < b)
2030 do {
2031 a = 0;
2032 } while (0);
2033 else if (a == b) {
2034 a = 1;
2035 }
2036 }
2037 '''
2038
2039 ps3 = self.parse(s3)
2040 self.assert_num_klass_nodes(ps3, DoWhile, 1)
2041 self.assert_num_ID_refs(ps3, 'a', 4)
2042 self.assert_all_Constants(ps3, ['0', '0', '1'])
2043
2044 def test_empty_statements(self):
2045 s1 = r'''
2046 void foo(void){
2047 ;
2048 return;;
2049
2050 ;
2051 }
2052 '''
2053 ps1 = self.parse(s1)
2054 self.assert_num_klass_nodes(ps1, EmptyStatement, 3)
2055 self.assert_num_klass_nodes(ps1, Return, 1)
2056 self.assert_coord(ps1.ext[0].body.block_items[0], 3)
2057 self.assert_coord(ps1.ext[0].body.block_items[1], 4)
2058 self.assert_coord(ps1.ext[0].body.block_items[2], 4)
2059 self.assert_coord(ps1.ext[0].body.block_items[3], 6)
2060
2061 def test_switch_statement(self):
2062 def assert_case_node(node, const_value):
2063 self.assertIsInstance(node, Case)
2064 self.assertIsInstance(node.expr, Constant)
2065 self.assertEqual(node.expr.value, const_value)
2066
2067 def assert_default_node(node):
2068 self.assertIsInstance(node, Default)
2069
2070 s1 = r'''
2071 int foo(void) {
2072 switch (myvar) {
2073 case 10:
2074 k = 10;
2075 p = k + 1;
2076 return 10;
2077 case 20:
2078 case 30:
2079 return 20;
2080 default:
2081 break;
2082 }
2083 return 0;
2084 }
2085 '''
2086 ps1 = self.parse(s1)
2087 switch = ps1.ext[0].body.block_items[0]
2088
2089 block = switch.stmt.block_items
2090 self.assertEqual(len(block), 4)
2091 assert_case_node(block[0], '10')
2092 self.assertEqual(len(block[0].stmts), 3)
2093 assert_case_node(block[1], '20')
2094 self.assertEqual(len(block[1].stmts), 0)
2095 assert_case_node(block[2], '30')
2096 self.assertEqual(len(block[2].stmts), 1)
2097 assert_default_node(block[3])
2098
2099 s2 = r'''
2100 int foo(void) {
2101 switch (myvar) {
2102 default:
2103 joe = moe;
2104 return 10;
2105 case 10:
2106 case 20:
2107 case 30:
2108 case 40:
2109 break;
2110 }
2111 return 0;
2112 }
2113 '''
2114 ps2 = self.parse(s2)
2115 switch = ps2.ext[0].body.block_items[0]
2116
2117 block = switch.stmt.block_items
2118 self.assertEqual(len(block), 5)
2119 assert_default_node(block[0])
2120 self.assertEqual(len(block[0].stmts), 2)
2121 assert_case_node(block[1], '10')
2122 self.assertEqual(len(block[1].stmts), 0)
2123 assert_case_node(block[2], '20')
2124 self.assertEqual(len(block[1].stmts), 0)
2125 assert_case_node(block[3], '30')
2126 self.assertEqual(len(block[1].stmts), 0)
2127 assert_case_node(block[4], '40')
2128 self.assertEqual(len(block[4].stmts), 1)
2129
2130 s3 = r'''
2131 int foo(void) {
2132 switch (myvar) {
2133 }
2134 return 0;
2135 }
2136 '''
2137 ps3 = self.parse(s3)
2138 switch = ps3.ext[0].body.block_items[0]
2139
2140 self.assertEqual(switch.stmt.block_items, [])
2141
2142 def test_for_statement(self):
2143 s2 = r'''
2144 void x(void)
2145 {
2146 int i;
2147 for (i = 0; i < 5; ++i) {
2148 x = 50;
2149 }
2150 }
2151 '''
2152 ps2 = self.parse(s2)
2153 self.assert_num_klass_nodes(ps2, For, 1)
2154 # here there are 3 refs to 'i' since the declaration doesn't count as
2155 # a ref in the visitor
2156 #
2157 self.assert_num_ID_refs(ps2, 'i', 3)
2158
2159 s3 = r'''
2160 void x(void)
2161 {
2162 for (int i = 0; i < 5; ++i) {
2163 x = 50;
2164 }
2165 }
2166 '''
2167 ps3 = self.parse(s3)
2168 self.assert_num_klass_nodes(ps3, For, 1)
2169 # here there are 2 refs to 'i' since the declaration doesn't count as
2170 # a ref in the visitor
2171 #
2172 self.assert_num_ID_refs(ps3, 'i', 2)
2173
2174 s4 = r'''
2175 void x(void) {
2176 for (int i = 0;;)
2177 i;
2178 }
2179 '''
2180 ps4 = self.parse(s4)
2181 self.assert_num_ID_refs(ps4, 'i', 1)
2182
2183 def _open_c_file(self, name):
2184 """ Find a c file by name, taking into account the current dir can be
2185 in a couple of typical places
2186 """
2187 testdir = os.path.dirname(__file__)
2188 name = os.path.join(testdir, 'c_files', name)
2189 assert os.path.exists(name)
2190 return io.open(name)
2191
2192 def test_whole_file(self):
2193 # See how pycparser handles a whole, real C file.
2194 #
2195 with self._open_c_file('memmgr_with_h.c') as f:
2196 code = f.read()
2197 p = self.parse(code)
2198
2199 self.assert_num_klass_nodes(p, FuncDef, 5)
2200
2201 # each FuncDef also has a FuncDecl. 4 declarations
2202 # + 5 definitions, overall 9
2203 self.assert_num_klass_nodes(p, FuncDecl, 9)
2204
2205 self.assert_num_klass_nodes(p, Typedef, 4)
2206
2207 self.assertEqual(p.ext[4].coord.line, 88)
2208 self.assertEqual(p.ext[4].coord.file, "./memmgr.h")
2209
2210 self.assertEqual(p.ext[6].coord.line, 10)
2211 self.assertEqual(p.ext[6].coord.file, "memmgr.c")
2212
2213 def test_whole_file_with_stdio(self):
2214 # Parse a whole file with stdio.h included by cpp
2215 #
2216 with self._open_c_file('cppd_with_stdio_h.c') as f:
2217 code = f.read()
2218 p = self.parse(code)
2219
2220 self.assertIsInstance(p.ext[0], Typedef)
2221 self.assertEqual(p.ext[0].coord.line, 213)
2222 self.assertEqual(p.ext[0].coord.file, r"D:\eli\cpp_stuff\libc_include/stddef.h")
2223
2224 self.assertIsInstance(p.ext[-1], FuncDef)
2225 self.assertEqual(p.ext[-1].coord.line, 15)
2226 self.assertEqual(p.ext[-1].coord.file, "example_c_file.c")
2227
2228 self.assertIsInstance(p.ext[-8], Typedef)
2229 self.assertIsInstance(p.ext[-8].type, TypeDecl)
2230 self.assertEqual(p.ext[-8].name, 'cookie_io_functions_t')
2231
2232
2233 class TestCParser_typenames(TestCParser_base):
2234 """ Test issues related to the typedef-name problem.
2235 """
2236 def test_innerscope_typedef(self):
2237 # should fail since TT is not a type in bar
2238 s1 = r'''
2239 void foo() {
2240 typedef char TT;
2241 TT x;
2242 }
2243 void bar() {
2244 TT y;
2245 }
2246 '''
2247 self.assertRaises(ParseError, self.parse, s1)
2248
2249 # should succeed since TT is not a type in bar
2250 s2 = r'''
2251 void foo() {
2252 typedef char TT;
2253 TT x;
2254 }
2255 void bar() {
2256 unsigned TT;
2257 }
2258 '''
2259 self.assertIsInstance(self.parse(s2), FileAST)
2260
2261 def test_ambiguous_parameters(self):
2262 # From ISO/IEC 9899:TC2, 6.7.5.3.11:
2263 # "If, in a parameter declaration, an identifier can be treated either
2264 # as a typedef name or as a parameter name, it shall be taken as a
2265 # typedef name."
2266
2267 # foo takes an int named aa
2268 # bar takes a function taking a TT
2269 s1 = r'''
2270 typedef char TT;
2271 int foo(int (aa));
2272 int bar(int (TT));
2273 '''
2274 s1_ast = self.parse(s1)
2275 self.assertEqual(expand_decl(s1_ast.ext[1].type.args.params[0]),
2276 ['Decl', 'aa', ['TypeDecl', ['IdentifierType', ['int']]]])
2277 self.assertEqual(expand_decl(s1_ast.ext[2].type.args.params[0]),
2278 ['Typename', ['FuncDecl',
2279 [['Typename', ['TypeDecl', ['IdentifierType', ['TT']]]]],
2280 ['TypeDecl', ['IdentifierType', ['int']]]]])
2281
2282 # foo takes a function taking a char
2283 # bar takes a function taking a function taking a char
2284 s2 = r'''
2285 typedef char TT;
2286 int foo(int (aa (char)));
2287 int bar(int (TT (char)));
2288 '''
2289 s2_ast = self.parse(s2)
2290 self.assertEqual(expand_decl(s2_ast.ext[1].type.args.params[0]),
2291 ['Decl', 'aa', ['FuncDecl',
2292 [['Typename', ['TypeDecl', ['IdentifierType', ['char']]]]],
2293 ['TypeDecl', ['IdentifierType', ['int']]]]])
2294 self.assertEqual(expand_decl(s2_ast.ext[2].type.args.params[0]),
2295 ['Typename', ['FuncDecl',
2296 [['Typename', ['FuncDecl',
2297 [['Typename', ['TypeDecl', ['IdentifierType', ['char']]]]],
2298 ['TypeDecl', ['IdentifierType', ['TT']]]]]],
2299 ['TypeDecl', ['IdentifierType', ['int']]]]])
2300
2301
2302 # foo takes an int array named aa
2303 # bar takes a function taking a TT array
2304 s3 = r'''
2305 typedef char TT;
2306 int foo(int (aa[]));
2307 int bar(int (TT[]));
2308 '''
2309 s3_ast = self.parse(s3)
2310 self.assertEqual(expand_decl(s3_ast.ext[1].type.args.params[0]),
2311 ['Decl', 'aa', ['ArrayDecl', '', [], ['TypeDecl', ['IdentifierType', ['int']]]]])
2312 self.assertEqual(expand_decl(s3_ast.ext[2].type.args.params[0]),
2313 ['Typename', ['FuncDecl',
2314 [['Typename', ['ArrayDecl', '', [], ['TypeDecl', ['IdentifierType', ['TT']]]]]],
2315 ['TypeDecl', ['IdentifierType', ['int']]]]])
2316
2317 def test_innerscope_reuse_typedef_name(self):
2318 # identifiers can be reused in inner scopes; the original should be
2319 # restored at the end of the block
2320 s1 = r'''
2321 typedef char TT;
2322 void foo(void) {
2323 unsigned TT;
2324 TT = 10;
2325 }
2326 TT x = 5;
2327 '''
2328 s1_ast = self.parse(s1)
2329 self.assertEqual(expand_decl(s1_ast.ext[1].body.block_items[0]),
2330 ['Decl', 'TT', ['TypeDecl', ['IdentifierType', ['unsigned']]]])
2331 self.assertEqual(expand_decl(s1_ast.ext[2]),
2332 ['Decl', 'x', ['TypeDecl', ['IdentifierType', ['TT']]]])
2333
2334 # this should be recognized even with an initializer
2335 s2 = r'''
2336 typedef char TT;
2337 void foo(void) {
2338 unsigned TT = 10;
2339 }
2340 '''
2341 s2_ast = self.parse(s2)
2342 self.assertEqual(expand_decl(s2_ast.ext[1].body.block_items[0]),
2343 ['Decl', 'TT', ['TypeDecl', ['IdentifierType', ['unsigned']]]])
2344
2345 # before the second local variable, TT is a type; after, it's a
2346 # variable
2347 s3 = r'''
2348 typedef char TT;
2349 void foo(void) {
2350 TT tt = sizeof(TT);
2351 unsigned TT = 10;
2352 }
2353 '''
2354 s3_ast = self.parse(s3)
2355 self.assertEqual(expand_decl(s3_ast.ext[1].body.block_items[0]),
2356 ['Decl', 'tt', ['TypeDecl', ['IdentifierType', ['TT']]]])
2357 self.assertEqual(expand_decl(s3_ast.ext[1].body.block_items[1]),
2358 ['Decl', 'TT', ['TypeDecl', ['IdentifierType', ['unsigned']]]])
2359
2360 # a variable and its type can even share the same name
2361 s4 = r'''
2362 typedef char TT;
2363 void foo(void) {
2364 TT TT = sizeof(TT);
2365 unsigned uu = TT * 2;
2366 }
2367 '''
2368 s4_ast = self.parse(s4)
2369 self.assertEqual(expand_decl(s4_ast.ext[1].body.block_items[0]),
2370 ['Decl', 'TT', ['TypeDecl', ['IdentifierType', ['TT']]]])
2371 self.assertEqual(expand_decl(s4_ast.ext[1].body.block_items[1]),
2372 ['Decl', 'uu', ['TypeDecl', ['IdentifierType', ['unsigned']]]])
2373
2374 # ensure an error is raised if a type, redeclared as a variable, is
2375 # used as a type
2376 s5 = r'''
2377 typedef char TT;
2378 void foo(void) {
2379 unsigned TT = 10;
2380 TT erroneous = 20;
2381 }
2382 '''
2383 self.assertRaises(ParseError, self.parse, s5)
2384
2385 # reusing a type name should work with multiple declarators
2386 s6 = r'''
2387 typedef char TT;
2388 void foo(void) {
2389 unsigned TT, uu;
2390 }
2391 '''
2392 s6_ast = self.parse(s6)
2393 items = s6_ast.ext[1].body.block_items
2394 self.assertEqual(expand_decl(items[0]),
2395 ['Decl', 'TT', ['TypeDecl', ['IdentifierType', ['unsigned']]]])
2396 self.assertEqual(expand_decl(items[1]),
2397 ['Decl', 'uu', ['TypeDecl', ['IdentifierType', ['unsigned']]]])
2398
2399 # reusing a type name should work after a pointer
2400 s7 = r'''
2401 typedef char TT;
2402 void foo(void) {
2403 unsigned * TT;
2404 }
2405 '''
2406 s7_ast = self.parse(s7)
2407 items = s7_ast.ext[1].body.block_items
2408 self.assertEqual(expand_decl(items[0]),
2409 ['Decl', 'TT', ['PtrDecl', ['TypeDecl', ['IdentifierType', ['unsigned']]]]])
2410
2411 # redefine a name in the middle of a multi-declarator declaration
2412 s8 = r'''
2413 typedef char TT;
2414 void foo(void) {
2415 int tt = sizeof(TT), TT, uu = sizeof(TT);
2416 int uu = sizeof(tt);
2417 }
2418 '''
2419 s8_ast = self.parse(s8)
2420 items = s8_ast.ext[1].body.block_items
2421 self.assertEqual(expand_decl(items[0]),
2422 ['Decl', 'tt', ['TypeDecl', ['IdentifierType', ['int']]]])
2423 self.assertEqual(expand_decl(items[1]),
2424 ['Decl', 'TT', ['TypeDecl', ['IdentifierType', ['int']]]])
2425 self.assertEqual(expand_decl(items[2]),
2426 ['Decl', 'uu', ['TypeDecl', ['IdentifierType', ['int']]]])
2427
2428 # Don't test this until we have support for it
2429 # self.assertEqual(expand_init(items[0].init),
2430 # ['UnaryOp', 'sizeof', ['Typename', ['TypeDecl', ['IdentifierType', ['TT']]]]])
2431 # self.assertEqual(expand_init(items[2].init),
2432 # ['UnaryOp', 'sizeof', ['ID', 'TT']])
2433
2434 def test_parameter_reuse_typedef_name(self):
2435 # identifiers can be reused as parameter names; parameter name scope
2436 # begins and ends with the function body; it's important that TT is
2437 # used immediately before the LBRACE or after the RBRACE, to test
2438 # a corner case
2439 s1 = r'''
2440 typedef char TT;
2441 void foo(unsigned TT, TT bar) {
2442 TT = 10;
2443 }
2444 TT x = 5;
2445 '''
2446 s1_ast = self.parse(s1)
2447 self.assertEqual(expand_decl(s1_ast.ext[1].decl),
2448 ['Decl', 'foo',
2449 ['FuncDecl',
2450 [ ['Decl', 'TT', ['TypeDecl', ['IdentifierType', ['unsigned']]]],
2451 ['Decl', 'bar', ['TypeDecl', ['IdentifierType', ['TT']]]]],
2452 ['TypeDecl', ['IdentifierType', ['void']]]]])
2453
2454 # the scope of a parameter name in a function declaration ends at the
2455 # end of the declaration...so it is effectively never used; it's
2456 # important that TT is used immediately after the declaration, to
2457 # test a corner case
2458 s2 = r'''
2459 typedef char TT;
2460 void foo(unsigned TT, TT bar);
2461 TT x = 5;
2462 '''
2463 s2_ast = self.parse(s2)
2464 self.assertEqual(expand_decl(s2_ast.ext[1]),
2465 ['Decl', 'foo',
2466 ['FuncDecl',
2467 [ ['Decl', 'TT', ['TypeDecl', ['IdentifierType', ['unsigned']]]],
2468 ['Decl', 'bar', ['TypeDecl', ['IdentifierType', ['TT']]]]],
2469 ['TypeDecl', ['IdentifierType', ['void']]]]])
2470
2471 # ensure an error is raised if a type, redeclared as a parameter, is
2472 # used as a type
2473 s3 = r'''
2474 typedef char TT;
2475 void foo(unsigned TT, TT bar) {
2476 TT erroneous = 20;
2477 }
2478 '''
2479 self.assertRaises(ParseError, self.parse, s3)
2480
2481 def test_nested_function_decls(self):
2482 # parameter names of nested function declarations must not escape into
2483 # the top-level function _definition's_ scope; the following must
2484 # succeed because TT is still a typedef inside foo's body
2485 s1 = r'''
2486 typedef char TT;
2487 void foo(unsigned bar(int TT)) {
2488 TT x = 10;
2489 }
2490 '''
2491 self.assertIsInstance(self.parse(s1), FileAST)
2492
2493 def test_samescope_reuse_name(self):
2494 # a typedef name cannot be reused as an object name in the same scope
2495 s1 = r'''
2496 typedef char TT;
2497 char TT = 5;
2498 '''
2499 self.assertRaises(ParseError, self.parse, s1)
2500
2501 # ...and vice-versa
2502 s2 = r'''
2503 char TT = 5;
2504 typedef char TT;
2505 '''
2506 self.assertRaises(ParseError, self.parse, s2)
2507
2508 def test_label_empty_statement(self):
2509 # Labels with empty statements and no semicolon should be parsed correctly
2510 s1 = r'''
2511 int main() {
2512 int i = 0;
2513 label0: i++;
2514 label1:
2515 }
2516 '''
2517 s1_ast : FileAST = self.parse(s1)
2518 self.assertIsInstance(s1_ast.ext[0].body.block_items[1], Label)
2519 self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt, UnaryOp)
2520 self.assertIsInstance(s1_ast.ext[0].body.block_items[2], Label)
2521 self.assertIsInstance(s1_ast.ext[0].body.block_items[2].stmt, EmptyStatement)
2522
2523 def test_case_empty_statement(self):
2524 # Labels with empty statements and no semicolon should be parsed correctly
2525 s1 = r'''
2526 int main() {
2527 int i = 0;
2528 switch (i) {
2529 case 0:
2530 i = 1;
2531 case 1:
2532 }
2533 return i;
2534 }
2535 '''
2536 s2 = r'''
2537 int main() {
2538 int i = 0;
2539 switch (i) {
2540 case 0:
2541 i = 1;
2542 default:
2543 }
2544 return i;
2545 }
2546 '''
2547 s1_ast : FileAST = self.parse(s1)
2548 s2_ast : FileAST = self.parse(s2)
2549 self.assertIsInstance(s1_ast.ext[0].body.block_items[1], Switch)
2550 self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt, Compound)
2551 self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[0], Case)
2552 self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[0].stmts[0], Assignment)
2553 self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[1], Case)
2554 self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[1].stmts[0], EmptyStatement)
2555 self.assertIsInstance(s2_ast.ext[0].body.block_items[1].stmt.block_items[1].stmts[0], EmptyStatement)
2556
2557 if __name__ == '__main__':
2558 #~ suite = unittest.TestLoader().loadTestsFromNames(
2559 #~ ['test_c_parser.TestCParser_fundamentals.test_typedef'])
2560
2561 #~ unittest.TextTestRunner(verbosity=2).run(suite)
2562 unittest.main()