gobject-linter 0.1.2

A fast tree-sitter-based linter for 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
use gobject_ast::model::{AssignmentOp, Expression, FileModel, FunctionDefItem, Statement};

use crate::{
    ast_context::AstContext,
    config::{Config, Style},
    rules::{Fix, Rule, Violation},
};

pub struct UseGStealPointer;

impl Rule for UseGStealPointer {
    fn name(&self) -> &'static str {
        "use_g_steal_pointer"
    }

    fn description(&self) -> &'static str {
        "Use g_steal_pointer() instead of manually copying a pointer and setting it to NULL"
    }

    fn category(&self) -> crate::rules::Category {
        crate::rules::Category::Style
    }

    fn fixable(&self) -> bool {
        true
    }

    fn check_func_impl(
        &self,
        _ast_context: &AstContext,
        config: &Config,
        func: &FunctionDefItem,
        file: &FileModel,
        violations: &mut Vec<Violation>,
    ) {
        self.check_statements(&func.body_statements, file, &config.style, violations);
    }
}

impl UseGStealPointer {
    fn check_statements(
        &self,
        statements: &[Statement],
        file: &FileModel,
        style: &Style,
        violations: &mut Vec<Violation>,
    ) {
        let mut i = 0;
        while i < statements.len() {
            if self.try_if_else_steal(&statements[i], file, style, violations) {
                i += 1;
                continue;
            }
            if self.try_if_no_else_steal(&statements[i], file, style, violations) {
                i += 1;
                continue;
            }
            if i + 2 < statements.len()
                && self.try_declare_null_return(
                    &statements[i],
                    &statements[i + 1],
                    &statements[i + 2],
                    file,
                    style,
                    violations,
                )
            {
                i += 3;
                continue;
            }
            if i + 1 < statements.len()
                && self.try_assign_null(&statements[i], &statements[i + 1], file, style, violations)
            {
                i += 2;
                continue;
            }
            statements[i].for_each_child_block(|body| {
                self.check_statements(body, file, style, violations);
            });
            i += 1;
        }
    }

    /// Matches: `T *tmp = ptr_expr; ptr_expr = NULL; return tmp;`
    fn try_declare_null_return(
        &self,
        s1: &Statement,
        s2: &Statement,
        s3: &Statement,
        file: &FileModel,
        style: &Style,
        violations: &mut Vec<Violation>,
    ) -> bool {
        // s1: T *tmp = ptr_expr
        let Statement::Declaration(decl) = s1 else {
            return false;
        };

        let Some(init_expr) = &decl.initializer else {
            return false;
        };

        // Skip NULL initializers
        if init_expr.is_null() {
            return false;
        }

        // Get the variable name from the initializer
        let Some(ptr_expr) = init_expr.extract_variable_name() else {
            return false;
        };

        // Skip dereferences
        if ptr_expr.starts_with('*') {
            return false;
        }

        let tmp_name = &decl.name;

        // s2: ptr_expr = NULL
        if !s2.is_null_assignment_to(ptr_expr) {
            return false;
        }

        // s3: return tmp
        let Statement::Return(ret) = s3 else {
            return false;
        };

        if let Some(Expression::Identifier(id)) = &ret.value {
            if id.name != *tmp_name {
                return false;
            }
        } else {
            return false;
        }

        let steal = style.format_addr_call("g_steal_pointer", ptr_expr, &[]);
        let replacement = format!("return {steal};");
        let message =
            format!("Use {replacement} instead of copying {ptr_expr} and setting it to NULL");

        let fixes = vec![
            Fix::delete_line(s1.location()),
            Fix::delete_line(s2.location()),
            Fix::new(
                s3.location().start_byte,
                s3.location().end_byte,
                replacement,
            ),
        ];

        violations.push(self.violation_with_fixes_at(&file.path, s1.location(), message, fixes));
        true
    }

    /// Matches: `other_expr = ptr_expr; ptr_expr = NULL;`
    fn try_assign_null(
        &self,
        s1: &Statement,
        s2: &Statement,
        file: &FileModel,
        style: &Style,
        violations: &mut Vec<Violation>,
    ) -> bool {
        let Some((other_expr, ptr_expr)) = self.extract_assignment(s1) else {
            return false;
        };

        if ptr_expr.starts_with('*') {
            return false;
        }

        if !s2.is_null_assignment_to(ptr_expr) {
            return false;
        }

        let steal = style.format_addr_call("g_steal_pointer", ptr_expr, &[]);
        let replacement = format!("{other_expr} = {steal};");
        let message = format!("Use {steal} instead of copying and setting to NULL");

        // Use two separate fixes to preserve comments between statements
        let s2_end = s2.location().find_semicolon_end();
        let fixes = vec![
            // Delete the entire first line
            Fix::delete_line(s1.location()),
            // Replace the second statement
            Fix::new(s2.location().start_byte, s2_end, replacement),
        ];

        violations.push(self.violation_with_fixes_at(&file.path, s1.location(), message, fixes));
        true
    }

    /// Matches: if (expr) { dest = expr; expr = NULL; } else { dest = NULL; }
    fn try_if_else_steal(
        &self,
        stmt: &Statement,
        file: &FileModel,
        style: &Style,
        violations: &mut Vec<Violation>,
    ) -> bool {
        let Statement::If(if_stmt) = stmt else {
            return false;
        };

        // Must have else block
        let Some(else_body) = &if_stmt.else_body else {
            return false;
        };

        // Extract tested expression from condition
        let Some(expr_text) = if_stmt.extract_null_check_variable() else {
            return false;
        };

        // Skip dereference expressions
        if expr_text.starts_with('*') {
            return false;
        }

        // Then-block must have exactly 2 statements
        if if_stmt.then_body.len() != 2 {
            return false;
        }

        // then_body[0]: dest = expr
        let Some((dest_expr, rhs)) = self.extract_assignment(&if_stmt.then_body[0]) else {
            return false;
        };
        if rhs != expr_text {
            return false;
        }

        // then_body[1]: expr = NULL
        if !if_stmt.then_body[1].is_null_assignment_to(expr_text) {
            return false;
        }

        // Else-block must have exactly 1 statement: dest = NULL
        if else_body.len() != 1 {
            return false;
        }
        if !else_body[0].is_null_assignment_to(dest_expr) {
            return false;
        }

        let steal = style.format_addr_call("g_steal_pointer", expr_text, &[]);
        let replacement = format!("{dest_expr} = {steal};");
        let message = format!("Use {steal} instead of if/else copy-and-NULL pattern");
        let fix = Fix::new(
            if_stmt.location.start_byte,
            if_stmt.location.end_byte,
            replacement,
        );
        violations.push(self.violation_with_fix_at(&file.path, &if_stmt.location, message, fix));
        true
    }

    /// Matches if-without-else with steal pattern in body
    /// if (c) { dest = ptr; ptr = NULL; } or if (c) { T *tmp = ptr; ptr = NULL;
    /// return tmp; }
    fn try_if_no_else_steal(
        &self,
        stmt: &Statement,
        file: &FileModel,
        style: &Style,
        violations: &mut Vec<Violation>,
    ) -> bool {
        let Statement::If(if_stmt) = stmt else {
            return false;
        };

        // Must have no else
        if if_stmt.else_body.is_some() {
            return false;
        }

        // Try to extract condition expression
        let condition_expr = if_stmt.extract_null_check_variable();

        // Pattern 1: 2 statements - dest = ptr; ptr = NULL;
        if if_stmt.then_body.len() == 2 {
            let Some((dest_expr, ptr_expr)) = self.extract_assignment(&if_stmt.then_body[0]) else {
                return false;
            };

            // Skip dereference expressions
            if ptr_expr.starts_with('*') {
                return false;
            }

            if !if_stmt.then_body[1].is_null_assignment_to(ptr_expr) {
                return false;
            }

            let steal = style.format_addr_call("g_steal_pointer", ptr_expr, &[]);
            let replacement = format!("{dest_expr} = {steal};");
            let message = format!("Use {steal} instead of copying and setting to NULL");

            // If condition tests the same variable being stolen, remove entire if
            // Otherwise just replace the body
            let fix = if condition_expr == Some(ptr_expr) {
                Fix::new(
                    if_stmt.location.start_byte,
                    if_stmt.location.end_byte,
                    replacement,
                )
            } else if if_stmt.then_has_braces {
                let (open_brace, close_brace) =
                    if_stmt.then_body[0].location().find_braces_around();
                Fix::new(open_brace, close_brace, replacement)
            } else {
                let body_start = if_stmt.then_body[0].location().start_byte;
                let body_end = if_stmt.then_body[1].location().end_byte;
                Fix::new(body_start, body_end, replacement)
            };

            violations.push(self.violation_with_fix_at(
                &file.path,
                if_stmt.then_body[0].location(),
                message,
                fix,
            ));
            return true;
        }

        // Pattern 2: 3 statements - T *tmp = ptr; ptr = NULL; return tmp;
        if if_stmt.then_body.len() == 3 {
            let Statement::Declaration(decl) = &if_stmt.then_body[0] else {
                return false;
            };

            let Some(init_expr) = &decl.initializer else {
                return false;
            };

            // Skip NULL initializers
            if init_expr.is_null() {
                return false;
            }

            let Some(ptr_expr) = init_expr.extract_variable_name() else {
                return false;
            };

            // Skip dereference expressions
            if ptr_expr.starts_with('*') {
                return false;
            }

            let tmp_name = &decl.name;

            if !if_stmt.then_body[1].is_null_assignment_to(ptr_expr) {
                return false;
            }

            // Third statement must be return tmp
            let Statement::Return(ret) = &if_stmt.then_body[2] else {
                return false;
            };

            if let Some(Expression::Identifier(id)) = &ret.value {
                if id.name != *tmp_name {
                    return false;
                }
            } else {
                return false;
            }

            let steal = style.format_addr_call("g_steal_pointer", ptr_expr, &[]);
            let replacement = format!("return {steal};");
            let message =
                format!("Use {replacement} instead of copying {ptr_expr} and setting it to NULL");

            // If condition tests the same variable being stolen, remove entire if
            let fix = if condition_expr == Some(ptr_expr) {
                Fix::new(
                    if_stmt.location.start_byte,
                    if_stmt.location.end_byte,
                    replacement,
                )
            } else if if_stmt.then_has_braces {
                let (open_brace, close_brace) =
                    if_stmt.then_body[0].location().find_braces_around();
                Fix::new(open_brace, close_brace, replacement)
            } else {
                let body_start = if_stmt.then_body[0].location().start_byte;
                let body_end = if_stmt.then_body[2].location().end_byte;
                Fix::new(body_start, body_end, replacement)
            };

            violations.push(self.violation_with_fix_at(
                &file.path,
                if_stmt.then_body[0].location(),
                message,
                fix,
            ));
            return true;
        }

        false
    }

    /// Extract (lhs, rhs) from assignment statement
    fn extract_assignment<'a>(&self, stmt: &'a Statement) -> Option<(&'a str, &'a str)> {
        let Statement::Expression(expr_stmt) = stmt else {
            return None;
        };

        let Expression::Assignment(assign) = expr_stmt.as_ref() else {
            return None;
        };

        if assign.operator != AssignmentOp::Assign {
            return None;
        }

        // Get rhs as string - handle various expression types
        let rhs = match &*assign.rhs {
            Expression::Identifier(id) => id.name.as_str(),
            Expression::FieldAccess(f) => f.location.as_str().unwrap_or(""),
            Expression::Null(_) | Expression::Call(_) => {
                // For NULL or function calls like g_strdup(), we don't want to suggest
                // g_steal_pointer
                return None;
            }
            _ => {
                return None;
            }
        };

        let lhs = assign.lhs_as_text();
        if lhs.is_empty() {
            return None;
        }
        Some((lhs, rhs))
    }
}