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
mod break_stmt;
mod compound_stmt;
mod continue_stmt;
mod for_stmt;
mod goto_stmt;
mod if_stmt;
mod labeled_stmt;
mod return_stmt;
mod switch_stmt;
mod variable_decl;
mod while_stmt;

pub use break_stmt::BreakStatement;
pub use compound_stmt::CompoundStatement;
pub use continue_stmt::ContinueStatement;
pub use for_stmt::{ForInit, ForStatement};
pub use goto_stmt::GotoStatement;
pub use if_stmt::IfStatement;
pub use labeled_stmt::LabeledStatement;
pub use return_stmt::ReturnStatement;
use serde::Serialize;
pub use switch_stmt::{CaseLabel, SwitchCase, SwitchStatement};
pub use variable_decl::VariableDecl;
pub use while_stmt::{DoWhileStatement, WhileStatement};

use crate::model::{
    Assignment, CallExpression, Comment, Expression, PreprocessorDirective, SourceLocation,
};

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Statement {
    Declaration(Box<VariableDecl>),
    Expression(Box<Expression>),
    If(IfStatement),
    Return(ReturnStatement),
    Goto(GotoStatement),
    Labeled(LabeledStatement),
    Compound(CompoundStatement),
    Switch(SwitchStatement),
    For(Box<ForStatement>),
    While(WhileStatement),
    DoWhile(DoWhileStatement),
    Break(BreakStatement),
    Continue(ContinueStatement),
    Preprocessor(PreprocessorDirective),
    Comment(Comment),
}

impl Statement {
    /// Recursively visit all nested statements. The closure receives a
    /// `&'s Statement` tied to `self`'s lifetime, so references extracted
    /// inside the closure can be stored in an outer `Vec<&'s T>`.
    pub fn walk<'s, F>(&'s self, f: &mut F)
    where
        F: FnMut(&'s Self),
    {
        f(self);
        match self {
            Self::If(if_stmt) => {
                for stmt in &if_stmt.then_body {
                    stmt.walk(f);
                }
                if let Some(else_body) = &if_stmt.else_body {
                    for stmt in else_body {
                        stmt.walk(f);
                    }
                }
            }
            Self::Compound(compound) => {
                for stmt in &compound.statements {
                    stmt.walk(f);
                }
            }
            Self::Labeled(labeled) => {
                labeled.statement.walk(f);
            }
            Self::Switch(switch) => {
                for case in &switch.cases {
                    for stmt in &case.body {
                        stmt.walk(f);
                    }
                }
            }
            Self::For(for_stmt) => {
                for stmt in &for_stmt.body {
                    stmt.walk(f);
                }
            }
            Self::While(while_stmt) => {
                for stmt in &while_stmt.body {
                    stmt.walk(f);
                }
            }
            Self::DoWhile(do_while) => {
                for stmt in &do_while.body {
                    stmt.walk(f);
                }
            }
            Self::Declaration(_)
            | Self::Expression(_)
            | Self::Return(_)
            | Self::Goto(_)
            | Self::Break(_)
            | Self::Continue(_)
            | Self::Preprocessor(_)
            | Self::Comment(_) => {}
        }
    }

    /// Call `f` with each immediate child block (a `&[Statement]` slice) of
    /// this statement. Covers all container variants exhaustively; leaf
    /// variants produce no calls. Use this instead of a manual `match` when
    /// you need to apply a slice-level operation (e.g. pair detection) to
    /// every nested body.
    pub fn for_each_child_block<F>(&self, mut f: F)
    where
        F: FnMut(&[Self]),
    {
        match self {
            Self::If(if_stmt) => {
                f(&if_stmt.then_body);
                if let Some(else_body) = &if_stmt.else_body {
                    f(else_body);
                }
            }
            Self::Compound(c) => f(&c.statements),
            Self::Labeled(l) => f(std::slice::from_ref(&l.statement)),
            Self::For(for_stmt) => f(&for_stmt.body),
            Self::While(w) => f(&w.body),
            Self::DoWhile(d) => f(&d.body),
            Self::Switch(sw) => {
                for case in &sw.cases {
                    f(&case.body);
                }
            }
            Self::Declaration(_)
            | Self::Expression(_)
            | Self::Return(_)
            | Self::Goto(_)
            | Self::Break(_)
            | Self::Continue(_)
            | Self::Preprocessor(_)
            | Self::Comment(_) => {}
        }
    }

    /// Visit all direct expressions contained in this statement
    /// (non-recursive). Includes conditions, initialisers, and all other
    /// expressions that are immediate children of this statement node.
    /// Zero-allocation alternative to collecting into a Vec.
    pub fn visit_expressions<'s>(&'s self, f: &mut impl FnMut(&'s Expression)) {
        match self {
            Self::Expression(expr_stmt) => f(expr_stmt),
            Self::Return(ret) => {
                if let Some(v) = &ret.value {
                    f(v);
                }
            }
            Self::Declaration(decl) => {
                if let Some(init) = &decl.initializer {
                    f(init);
                }
                if let Some(size) = &decl.array_size {
                    f(size);
                }
            }
            Self::If(if_stmt) => f(&if_stmt.condition),
            Self::Switch(switch) => {
                f(&switch.condition);
                for case in &switch.cases {
                    if let Some(label_expr) = &case.label.value {
                        f(label_expr);
                    }
                }
            }
            Self::For(for_stmt) => {
                match &for_stmt.initializer {
                    Some(ForInit::Expr(init)) => f(init),
                    Some(ForInit::Decl(decl)) => {
                        if let Some(init) = &decl.initializer {
                            f(init);
                        }
                    }
                    None => {}
                }
                if let Some(cond) = &for_stmt.condition {
                    f(cond);
                }
                if let Some(update) = &for_stmt.update {
                    f(update);
                }
            }
            Self::While(while_stmt) => f(&while_stmt.condition),
            Self::DoWhile(do_while) => f(&do_while.condition),
            Self::Goto(_)
            | Self::Labeled(_)
            | Self::Compound(_)
            | Self::Break(_)
            | Self::Continue(_)
            | Self::Preprocessor(_)
            | Self::Comment(_) => {}
        }
    }

    pub fn location(&self) -> &SourceLocation {
        match self {
            Self::Declaration(d) => &d.location,
            Self::Expression(e) => e.location(),
            Self::If(i) => &i.location,
            Self::Return(r) => &r.location,
            Self::Goto(g) => &g.location,
            Self::Labeled(l) => &l.location,
            Self::Compound(c) => &c.location,
            Self::Switch(s) => &s.location,
            Self::For(f) => &f.location,
            Self::While(w) => &w.location,
            Self::DoWhile(d) => &d.location,
            Self::Break(b) => &b.location,
            Self::Continue(c) => &c.location,
            Self::Preprocessor(p) => p.location(),
            Self::Comment(c) => &c.location,
        }
    }

    /// Recursively walk all expressions in this statement tree.
    /// Visits the direct expression of each statement (not sub-expressions —
    /// call `Expression::walk` on the result if you need nested expressions).
    pub fn walk_expressions<'s, F>(&'s self, f: &mut F)
    where
        F: FnMut(&'s Expression),
    {
        self.walk(&mut |s| {
            s.visit_expressions(f);
        });
    }

    /// Iterator over all switch statements in this statement tree (recursive)
    pub fn iter_switches<'s>(&'s self) -> impl Iterator<Item = &'s SwitchStatement> + 's {
        let mut results: Vec<&'s SwitchStatement> = Vec::new();
        self.walk(&mut |s| {
            if let Self::Switch(sw) = s {
                results.push(sw);
            }
        });
        results.into_iter()
    }

    /// Iterator over all if statements in this statement tree (recursive)
    pub fn iter_if_statements<'s>(&'s self) -> impl Iterator<Item = &'s IfStatement> + 's {
        let mut results: Vec<&'s IfStatement> = Vec::new();
        self.walk(&mut |s| {
            if let Self::If(if_stmt) = s {
                results.push(if_stmt);
            }
        });
        results.into_iter()
    }

    /// Iterator over all variable declarations in this statement tree
    /// (recursive)
    pub fn iter_declarations<'s>(&'s self) -> impl Iterator<Item = &'s VariableDecl> + 's {
        let mut results: Vec<&'s VariableDecl> = Vec::new();
        self.walk(&mut |s| {
            if let Self::Declaration(decl) = s {
                results.push(decl);
            }
            if let Self::For(for_stmt) = s
                && let Some(ForInit::Decl(decl)) = &for_stmt.initializer
            {
                results.push(decl);
            }
        });
        results.into_iter()
    }

    /// Iterator over all return statements in this statement tree (recursive)
    pub fn iter_returns<'s>(&'s self) -> impl Iterator<Item = &'s ReturnStatement> + 's {
        let mut results: Vec<&'s ReturnStatement> = Vec::new();
        self.walk(&mut |s| {
            if let Self::Return(ret) = s {
                results.push(ret);
            }
        });
        results.into_iter()
    }

    /// Iterator over all top-level assignment statements in this statement tree
    /// (recursive). Only yields assignments that are the entire expression
    /// statement, not assignments nested inside other expressions.
    pub fn iter_assignments<'s>(&'s self) -> impl Iterator<Item = &'s Assignment> + 's {
        let mut results: Vec<&'s Assignment> = Vec::new();
        self.walk(&mut |s| {
            if let Self::Expression(expr_stmt) = s
                && let Expression::Assignment(assign) = expr_stmt.as_ref()
            {
                results.push(assign);
            }
        });
        results.into_iter()
    }

    /// Iterator over all call expressions in this statement tree (recursive).
    /// Includes calls at all nesting levels within expressions (e.g. nested
    /// arguments).
    pub fn iter_calls<'s>(&'s self) -> impl Iterator<Item = &'s CallExpression> + 's {
        // Two-step: first collect top-level expressions (avoids nested-closure
        // invariance issue with &mut Vec), then walk each for nested calls.
        let mut exprs: Vec<&'s Expression> = Vec::new();
        self.walk_expressions(&mut |expr| exprs.push(expr));

        let mut results: Vec<&'s CallExpression> = Vec::new();
        for expr in exprs {
            expr.walk(&mut |e| {
                if let Expression::Call(call) = e {
                    results.push(call);
                }
            });
        }
        results.into_iter()
    }

    /// Extract the call expression if this is an expression statement with a
    /// call
    pub fn extract_call(&self) -> Option<&CallExpression> {
        if let Self::Expression(expr_stmt) = self
            && let Expression::Call(call) = expr_stmt.as_ref()
        {
            return Some(call);
        }
        None
    }

    /// Check if this statement assigns a value matching the predicate to the
    /// target variable
    pub fn is_assignment_to<F>(&self, target_var: &str, value_check: F) -> bool
    where
        F: Fn(&Expression) -> bool,
    {
        if let Self::Expression(expr_stmt) = self
            && let Expression::Assignment(assign) = expr_stmt.as_ref()
        {
            let lhs_text = assign.lhs.location().as_str().unwrap_or("");
            return lhs_text.trim() == target_var.trim() && value_check(&assign.rhs);
        }
        false
    }

    /// Extract the assignment expression if this is an assignment statement
    pub fn extract_assignment(&self) -> Option<&Assignment> {
        if let Self::Expression(expr_stmt) = self
            && let Expression::Assignment(assign) = expr_stmt.as_ref()
        {
            return Some(assign);
        }
        None
    }

    /// Check if this statement assigns NULL to the target variable
    pub fn is_null_assignment_to(&self, var_name: &str) -> bool {
        self.is_assignment_to(var_name, Expression::is_null)
    }

    fn non_comments(stmts: &[Self]) -> Vec<&Self> {
        stmts
            .iter()
            .filter(|s| !matches!(s, Self::Comment(_)))
            .collect()
    }

    /// Iterate over consecutive pairs of statements (skipping comments)
    pub fn for_each_pair<F>(statements: &[Self], mut f: F)
    where
        F: FnMut(&Self, &Self),
    {
        let nc = Self::non_comments(statements);
        for w in nc.windows(2) {
            f(w[0], w[1]);
        }
    }

    /// Iterate over consecutive triples of statements (skipping comments)
    pub fn for_each_triple<F>(statements: &[Self], mut f: F)
    where
        F: FnMut(&Self, &Self, &Self),
    {
        let nc = Self::non_comments(statements);
        for w in nc.windows(3) {
            f(w[0], w[1], w[2]);
        }
    }

    /// Recursively visit consecutive pairs of statements at every nesting level
    /// (if bodies, else bodies, compound blocks, loops, switch cases, labeled
    /// statements). Comments are skipped so they don't break pair detection.
    pub fn walk_pairs<F>(stmts: &[Self], f: &mut F)
    where
        F: FnMut(&Self, &Self),
    {
        let nc = Self::non_comments(stmts);
        for w in nc.windows(2) {
            f(w[0], w[1]);
        }
        for stmt in stmts {
            match stmt {
                Self::If(if_stmt) => {
                    Self::walk_pairs(&if_stmt.then_body, f);
                    if let Some(else_body) = &if_stmt.else_body {
                        Self::walk_pairs(else_body, f);
                    }
                }
                Self::Compound(c) => Self::walk_pairs(&c.statements, f),
                Self::Labeled(l) => Self::walk_pairs(std::slice::from_ref(&l.statement), f),
                Self::For(for_stmt) => Self::walk_pairs(&for_stmt.body, f),
                Self::While(w) => Self::walk_pairs(&w.body, f),
                Self::DoWhile(d) => Self::walk_pairs(&d.body, f),
                Self::Switch(sw) => {
                    for case in &sw.cases {
                        Self::walk_pairs(&case.body, f);
                    }
                }
                Self::Declaration(_)
                | Self::Expression(_)
                | Self::Return(_)
                | Self::Goto(_)
                | Self::Break(_)
                | Self::Continue(_)
                | Self::Preprocessor(_)
                | Self::Comment(_) => {}
            }
        }
    }

    /// Recursively visit consecutive triples of statements at every nesting
    /// level. Comments are skipped so they don't break triple detection.
    pub fn walk_triples<F>(stmts: &[Self], f: &mut F)
    where
        F: FnMut(&Self, &Self, &Self),
    {
        let nc = Self::non_comments(stmts);
        for w in nc.windows(3) {
            f(w[0], w[1], w[2]);
        }
        for stmt in stmts {
            match stmt {
                Self::If(if_stmt) => {
                    Self::walk_triples(&if_stmt.then_body, f);
                    if let Some(else_body) = &if_stmt.else_body {
                        Self::walk_triples(else_body, f);
                    }
                }
                Self::Compound(c) => Self::walk_triples(&c.statements, f),
                Self::Labeled(l) => Self::walk_triples(std::slice::from_ref(&l.statement), f),
                Self::For(for_stmt) => Self::walk_triples(&for_stmt.body, f),
                Self::While(w) => Self::walk_triples(&w.body, f),
                Self::DoWhile(d) => Self::walk_triples(&d.body, f),
                Self::Switch(sw) => {
                    for case in &sw.cases {
                        Self::walk_triples(&case.body, f);
                    }
                }
                Self::Declaration(_)
                | Self::Expression(_)
                | Self::Return(_)
                | Self::Goto(_)
                | Self::Break(_)
                | Self::Continue(_)
                | Self::Preprocessor(_)
                | Self::Comment(_) => {}
            }
        }
    }
}