gobject-ast 0.1.2

AST representation of GObject C code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
use std::path::PathBuf;

use gobject_ast::{
    Parser,
    model::{
        Expression, ForInit, Parameter, Project, Statement, TopLevelItem, TypeDefItem,
        TypedefTarget,
    },
};

fn parse_fixture(name: &str) -> Project {
    let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join(name);

    let mut parser = Parser::new().unwrap();
    parser.parse_file(&fixture_path).unwrap()
}

#[test]
fn test_parse_call_expressions() {
    let project = parse_fixture("call_expressions.c");

    let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("call_expressions.c");

    let file = project
        .get_file(&fixture_path)
        .expect("File should be parsed");

    let func = file
        .iter_function_definitions()
        .next()
        .expect("Should find a function");
    assert_eq!(func.name, "test_function");

    // Check we have statements parsed
    assert!(
        !func.body_statements.is_empty(),
        "Should have parsed body statements"
    );

    // Count call expressions
    let mut call_count = 0;
    for stmt in &func.body_statements {
        if let Statement::Expression(expr) = stmt
            && matches!(expr.as_ref(), Expression::Call(_))
        {
            call_count += 1;
        }
    }

    // We should find at least the function calls (not counting the variable
    // declaration)
    assert!(
        call_count >= 2,
        "Should find at least 2 call expressions (g_task_set_source_tag, g_object_unref), found {}",
        call_count
    );
}

#[test]
fn test_parse_assignments() {
    let project = parse_fixture("assignments.c");

    let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("assignments.c");

    let file = project
        .get_file(&fixture_path)
        .expect("File should be parsed");
    let func = file
        .iter_function_definitions()
        .next()
        .expect("Should find a function");

    // Count assignments
    let mut assignment_count = 0;
    for stmt in &func.body_statements {
        if let Statement::Expression(expr) = stmt
            && matches!(expr.as_ref(), Expression::Assignment(_))
        {
            assignment_count += 1;
        }
    }

    assert!(
        assignment_count >= 1,
        "Should find at least 1 assignment expression, found {}",
        assignment_count
    );
}

#[test]
fn test_parse_return_statement() {
    let project = parse_fixture("return_statement.c");

    let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("return_statement.c");

    let file = project
        .get_file(&fixture_path)
        .expect("File should be parsed");
    let func = file
        .iter_function_definitions()
        .next()
        .expect("Should find a function");

    // Should have a return statement
    assert!(!func.body_statements.is_empty(), "Should have statements");

    let has_return = func
        .body_statements
        .iter()
        .any(|stmt| matches!(stmt, Statement::Return(_)));

    assert!(has_return, "Should find return statement");
}

#[test]
fn test_parse_goto_statement() {
    let project = parse_fixture("goto_statement.c");

    let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("goto_statement.c");

    let file = project
        .get_file(&fixture_path)
        .expect("File should be parsed");

    let func = file
        .iter_function_definitions()
        .next()
        .expect("Should find a function");

    let has_goto = func.body_statements.iter().any(|s| {
        let mut found = false;
        s.walk(&mut |stmt| {
            if matches!(stmt, Statement::Goto(_)) {
                found = true;
            }
        });
        found
    });

    assert!(has_goto, "Should find goto statement");
}

#[test]
fn test_anonymous_union_field_types_collected() {
    let project = parse_fixture("anonymous_union.h");

    let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("anonymous_union.h");

    let file = project
        .get_file(&fixture_path)
        .expect("File should be parsed");

    let xdp_rule = file.iter_all_items().find_map(|item| match item {
        TopLevelItem::TypeDefinition(td @ TypeDefItem::Typedef { name, .. })
            if name == "XdpUsbRule" =>
        {
            Some(td)
        }
        _ => None,
    });

    let TypeDefItem::Typedef { struct_fields, .. } =
        xdp_rule.expect("XdpUsbRule typedef not found")
    else {
        panic!("XdpUsbRule should be a Typedef");
    };

    assert_eq!(
        struct_fields.len(),
        2,
        "XdpUsbRule should have 2 top-level fields"
    );

    let rule_type = &struct_fields[0];
    assert_eq!(rule_type.field_name.as_deref(), Some("rule_type"));
    assert_eq!(rule_type.field_type.base_type, "int");
    assert!(rule_type.inner_fields.is_empty());

    // The anonymous union `union { ... } d` is stored as field `d` with
    // inner_fields.
    let union_d = &struct_fields[1];
    assert_eq!(union_d.field_name.as_deref(), Some("d"));
    assert!(
        union_d.field_type.base_type.is_empty(),
        "anonymous union has no base type"
    );

    let inner: Vec<(&str, &str)> = union_d
        .inner_fields
        .iter()
        .map(|f| {
            (
                f.field_name.as_deref().unwrap_or(""),
                f.field_type.base_type.as_str(),
            )
        })
        .collect();
    assert_eq!(
        inner,
        vec![
            ("device_class", "int"),
            ("product", "UsbProduct"),
            ("vendor", "UsbVendor")
        ],
        "anonymous union inner fields mismatch"
    );
}

#[test]
fn test_statement_order() {
    let project = parse_fixture("statement_order.c");

    let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("statement_order.c");

    let file = project
        .get_file(&fixture_path)
        .expect("File should be parsed");
    let func = file
        .iter_function_definitions()
        .next()
        .expect("Should find a function");

    // Verify order: should have declaration/call first, then call
    assert!(
        func.body_statements.len() >= 2,
        "Should have at least 2 statements, found {}",
        func.body_statements.len()
    );

    // Second statement should be a call to g_bytes_unref
    let mut found_pattern = false;
    for i in 0..func.body_statements.len() - 1 {
        if let Statement::Expression(expr) = &func.body_statements[i + 1]
            && let Expression::Call(call2) = expr.as_ref()
            && call2.is_function("g_bytes_unref")
        {
            found_pattern = true;
        }
    }

    assert!(
        found_pattern,
        "Should find consecutive g_bytes_get_data and g_bytes_unref calls in order"
    );
}

#[test]
fn test_bitfield_struct_parsing() {
    let project = parse_fixture("bitfield_struct.h");

    let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("bitfield_struct.h");

    let file = project
        .get_file(&fixture_path)
        .expect("File should be parsed");

    let typedef = file
        .iter_all_items()
        .find_map(|item| match item {
            TopLevelItem::TypeDefinition(td @ TypeDefItem::Typedef { name, .. })
                if name == "MyBitStruct" =>
            {
                Some(td)
            }
            _ => None,
        })
        .expect("MyBitStruct typedef not found");

    let TypeDefItem::Typedef { struct_fields, .. } = typedef else {
        panic!("expected Typedef");
    };

    assert_eq!(struct_fields.len(), 4, "expected 4 fields");

    let flags = &struct_fields[0];
    assert_eq!(flags.field_name.as_deref(), Some("flags"));
    assert_eq!(flags.bit_width, Some(1));

    let count = &struct_fields[1];
    assert_eq!(count.field_name.as_deref(), Some("count"));
    assert_eq!(count.bit_width, Some(4));

    let padding = &struct_fields[2];
    assert_eq!(padding.field_name.as_deref(), Some("padding"));
    assert_eq!(padding.bit_width, Some(27));

    let normal = &struct_fields[3];
    assert_eq!(normal.field_name.as_deref(), Some("normal_field"));
    assert_eq!(normal.bit_width, None);
}

#[test]
fn test_callback_typedef_parsing() {
    let project = parse_fixture("typedef_callback.h");

    let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fixtures")
        .join("typedef_callback.h");

    let file = project
        .get_file(&fixture_path)
        .expect("File should be parsed");

    let typedefs: Vec<&TypeDefItem> = file
        .iter_all_items()
        .filter_map(|item| match item {
            TopLevelItem::TypeDefinition(td) => Some(td),
            _ => None,
        })
        .collect();

    // Plain type alias: `typedef struct _MyObject MyObject`
    let plain = typedefs
        .iter()
        .find(|td| matches!(td, TypeDefItem::Typedef { name, .. } if name == "MyObject"))
        .expect("MyObject typedef not found");
    let TypeDefItem::Typedef { target, .. } = plain else {
        panic!("expected Typedef");
    };
    assert!(
        matches!(target, TypedefTarget::Type(_)),
        "MyObject should be a plain type alias"
    );
    let TypedefTarget::Type(ti) = target else {
        unreachable!()
    };
    assert_eq!(ti.base_type, "_MyObject");
    assert!(ti.is_struct);

    // `typedef void (*MyCallback)(MyObject *obj, gpointer user_data)`
    let cb = typedefs
        .iter()
        .find(|td| matches!(td, TypeDefItem::Typedef { name, .. } if name == "MyCallback"))
        .expect("MyCallback typedef not found");
    let TypeDefItem::Typedef { target, .. } = cb else {
        panic!("expected Typedef");
    };
    let TypedefTarget::Callback {
        return_type,
        parameters,
    } = target
    else {
        panic!(
            "MyCallback should be TypedefTarget::Callback, got {:?}",
            target
        );
    };
    assert_eq!(return_type.base_type, "void");
    assert_eq!(return_type.pointer_depth, 0);
    assert_eq!(parameters.len(), 2);
    let Parameter::Regular { type_info: p0, .. } = &parameters[0] else {
        panic!("expected Regular")
    };
    let Parameter::Regular { type_info: p1, .. } = &parameters[1] else {
        panic!("expected Regular")
    };
    assert_eq!(p0.base_type, "MyObject");
    assert_eq!(p1.base_type, "gpointer");

    // `typedef gboolean (*MyPredicate)(const gchar *name, guint index)`
    let pred = typedefs
        .iter()
        .find(|td| matches!(td, TypeDefItem::Typedef { name, .. } if name == "MyPredicate"))
        .expect("MyPredicate typedef not found");
    let TypeDefItem::Typedef { target, .. } = pred else {
        panic!("expected Typedef");
    };
    let TypedefTarget::Callback {
        return_type,
        parameters,
    } = target
    else {
        panic!("MyPredicate should be TypedefTarget::Callback");
    };
    assert_eq!(return_type.base_type, "gboolean");
    assert_eq!(parameters.len(), 2);

    // `typedef const gchar *(*MyGetNameFunc)(MyObject *obj)`
    let getter = typedefs
        .iter()
        .find(|td| matches!(td, TypeDefItem::Typedef { name, .. } if name == "MyGetNameFunc"))
        .expect("MyGetNameFunc typedef not found");
    let TypeDefItem::Typedef { target, .. } = getter else {
        panic!("expected Typedef");
    };
    let TypedefTarget::Callback {
        return_type,
        parameters,
    } = target
    else {
        panic!("MyGetNameFunc should be TypedefTarget::Callback");
    };
    assert_eq!(return_type.base_type, "gchar");
    assert_eq!(return_type.pointer_depth, 1);
    assert!(return_type.is_const);
    assert_eq!(parameters.len(), 1);
    let Parameter::Regular { type_info: p0, .. } = &parameters[0] else {
        panic!("expected Regular")
    };
    assert_eq!(p0.base_type, "MyObject");
}

#[test]
fn test_variadic_parameter_parsing() {
    let project = parse_fixture("variadic_func.h");
    let file = project.files.values().next().expect("No files parsed");

    let decls: Vec<_> = file.iter_function_declarations().collect();
    assert_eq!(decls.len(), 3);

    // foo(int n, ...) — 2 params: Regular + Variadic
    let foo = decls
        .iter()
        .find(|d| d.name == "foo")
        .expect("foo not found");
    assert_eq!(foo.parameters.len(), 2);
    assert!(matches!(foo.parameters[0], Parameter::Regular { .. }));
    assert!(matches!(foo.parameters[1], Parameter::Variadic));

    // bar(const gchar *format, ...) — 2 params: Regular + Variadic
    let bar = decls
        .iter()
        .find(|d| d.name == "bar")
        .expect("bar not found");
    assert_eq!(bar.parameters.len(), 2);
    assert!(matches!(bar.parameters[0], Parameter::Regular { .. }));
    assert!(matches!(bar.parameters[1], Parameter::Variadic));

    // baz(void) — not variadic
    let baz = decls
        .iter()
        .find(|d| d.name == "baz")
        .expect("baz not found");
    assert!(
        baz.parameters
            .iter()
            .all(|p| !matches!(p, Parameter::Variadic))
    );
}

#[test]
fn test_for_statement_init_variants() {
    let project = parse_fixture("for_init.c");
    let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/for_init.c");
    let file = project.get_file(&fixture_path).expect("file not parsed");

    let func = file
        .iter_function_definitions()
        .next()
        .expect("no function");

    let for_stmts: Vec<_> = func
        .body_statements
        .iter()
        .filter_map(|s| {
            if let Statement::For(f) = s {
                Some(f)
            } else {
                None
            }
        })
        .collect();

    assert_eq!(for_stmts.len(), 4, "expected 4 for loops");

    // expression initializer: `for (i = 0; ...)`
    assert!(
        matches!(&for_stmts[0].initializer, Some(ForInit::Expr(_))),
        "first loop should have Expr initializer"
    );

    // C99 int declaration: `for (int j = 0; ...)`
    let Some(ForInit::Decl(decl)) = &for_stmts[1].initializer else {
        panic!("second loop should have Decl initializer");
    };
    assert_eq!(decl.name, "j");
    assert_eq!(decl.type_info.base_type, "int");

    // pointer declaration: `for (GList *l = list; ...)`
    let Some(ForInit::Decl(decl)) = &for_stmts[2].initializer else {
        panic!("third loop should have Decl initializer");
    };
    assert_eq!(decl.name, "l");
    assert_eq!(decl.type_info.base_type, "GList");

    // no initializer: `for (; i < 20; ...)`
    assert!(
        for_stmts[3].initializer.is_none(),
        "fourth loop should have no initializer"
    );
}