sqc 0.4.84

Software Code Quality - CERT C compliance checker
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
//! Textual expansion of function-like C macros — Phase 2 of the macro-expansion
//! plan (`docs/design/macro-expansion.md`).
//!
//! sqc has no preprocessor, so function-like macro *invocations* are opaque to
//! dataflow. This module collects function-like macro *definitions* from the
//! parsed source (the prescan pre-pass crosses headers, so vendored/project
//! macros are visible) and expands an invocation on demand via token-aware
//! parameter substitution plus recursive rescanning (C11 6.10.3). Wiring the
//! expanded text into the CFG/dataflow is increment 2b; this module is the
//! engine + the collector, independently unit-tested.
//!
//! Out of scope (intentionally left unexpanded — safe, same as today):
//!   * macros using `#` (stringize) or `##` (token paste) — need real cpp
//!     semantics and are rare (<1% in the surveyed codebases);
//!   * variadic macros (`...` / `__VA_ARGS__`);
//!   * object-like macros — handled separately by `const_eval`.
//
// Increment 2a delivered the collector + engine. Increment 2b wired
// `collect_function_macros` into the prescan pre-pass / `ProjectContext` (so
// definitions are cached and available cross-file). The expander
// (`expand_invocation`) is consumed by the dataflow rules:
//   * 2c-ii — `macro_output_param_indices` feeds EXP33-C's read-checker and the
//     init-state transfer to recognize macro output arguments (`CF_DATA_SAVE`);
//   * 2c-iii — `macro_nulls_param_indices` feeds MEM30-C to recognize "safe
//     free" macros that free AND null their argument (`Curl_safefree`).

use std::collections::{HashMap, HashSet};
use tree_sitter::Node;

/// A collected function-like macro definition.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct FunctionMacro {
    /// Parameter names in order, e.g. `["x", "y"]`.
    pub params: Vec<String>,
    /// Raw replacement-list text, e.g. `(((x) < (y)) ? (x) : (y))`.
    pub body: String,
}

/// Maximum recursive-rescan depth (defense against pathological input; real
/// macro nesting is shallow).
const MAX_EXPAND_DEPTH: usize = 32;

fn is_ident_start(c: char) -> bool {
    c.is_ascii_alphabetic() || c == '_'
}
fn is_ident_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '_'
}

/// Collect function-like macro definitions from a parsed translation unit.
/// Skips macros that use `#`/`##` or are variadic (left unexpanded downstream).
///
/// Two passes: (1) a precise AST pass over `preproc_function_def` nodes; (2) a
/// textual error-correcting pass over the raw source that recovers definitions
/// tree-sitter buried in `ERROR` recovery regions (e.g. curl's `curl_setup.h`,
/// 1480 lines of nested `#if`, where `#define curlx_free(ptr) …` is misparsed
/// as `ERROR(#define) + call_expression` and never emitted as a
/// `preproc_function_def`). The AST pass is authoritative; the textual pass only
/// fills names the AST missed (`or_insert`), so clean files are unaffected.
pub fn collect_function_macros(root: &Node, source: &str) -> HashMap<String, FunctionMacro> {
    let mut out = HashMap::new();
    collect_rec(root, source, &mut out);
    for (name, m) in collect_function_macros_textual(source) {
        out.entry(name).or_insert(m);
    }
    out
}

/// Secondary, error-correcting collector: scans raw source line-by-line for
/// function-like `#define NAME(params) body` directives. Because the C
/// preprocessor is line-oriented, this is immune to however tree-sitter mangles
/// the surrounding C in error-recovery regions. Applies the same exclusions as
/// the AST pass (`#`/`##`, variadic) so the expander sees a consistent set.
pub fn collect_function_macros_textual(source: &str) -> HashMap<String, FunctionMacro> {
    let lines: Vec<&str> = source.lines().collect();
    let mut out = HashMap::new();
    let mut i = 0;
    while i < lines.len() {
        let (logical, next) = join_continuation(&lines, i);
        i = next;
        if let Some((name, m)) = parse_define_line(&logical) {
            // First definition wins (mirrors the AST pass): redefinitions across
            // platform `#ifdef` branches are ambiguous, so keep the first.
            out.entry(name).or_insert(m);
        }
    }
    out
}

/// Join a backslash-continued logical line starting at `start`. Returns the
/// spliced text (continuation backslashes removed, joined with a space) and the
/// index of the next unconsumed physical line.
fn join_continuation(lines: &[&str], start: usize) -> (String, usize) {
    let mut buf = String::new();
    let mut i = start;
    while i < lines.len() {
        let line = lines[i];
        let te = line.trim_end();
        if let Some(stripped) = te.strip_suffix('\\') {
            buf.push_str(stripped);
            buf.push(' ');
            i += 1;
        } else {
            buf.push_str(line);
            i += 1;
            break;
        }
    }
    (buf, i)
}

/// Parse one logical line as a function-like `#define`. Returns `None` for
/// non-directives, object-like macros, variadic macros, and macros using
/// `#`/`##`.
fn parse_define_line(line: &str) -> Option<(String, FunctionMacro)> {
    let s = line.trim_start();
    let s = s.strip_prefix('#')?;
    let s = s.trim_start().strip_prefix("define")?;
    // `define` must be a whole token (followed by whitespace), not a prefix
    // like `defined` or `definex`.
    if !s.starts_with(|c: char| c.is_whitespace()) {
        return None;
    }
    let s = s.trim_start();

    // Macro name.
    let chars: Vec<char> = s.chars().collect();
    if chars.is_empty() || !is_ident_start(chars[0]) {
        return None;
    }
    let mut k = 0;
    while k < chars.len() && is_ident_char(chars[k]) {
        k += 1;
    }
    let name: String = chars[..k].iter().collect();

    // Function-like requires '(' *immediately* after the name (no whitespace);
    // `#define NAME (x)` is object-like with body `(x)`.
    if k >= chars.len() || chars[k] != '(' {
        return None;
    }

    // Parse parameter list up to the matching ')'.
    let (params, body_start) = parse_param_list(&chars, k)?;
    let body_raw: String = chars[body_start..].iter().collect();
    let body = strip_comments(&body_raw).trim().to_string();

    if body_uses_paste_or_stringize(&body) {
        return None;
    }
    Some((name, FunctionMacro { params, body }))
}

/// Parse `(p1, p2, …)` starting at `open` (an index of `'('`). Returns the
/// parameter names and the index just past the closing `')'`. Bails on variadic
/// (`...`) macros (`None`).
fn parse_param_list(chars: &[char], open: usize) -> Option<(Vec<String>, usize)> {
    debug_assert_eq!(chars[open], '(');
    let mut params = Vec::new();
    let mut cur = String::new();
    let mut i = open + 1;
    let mut depth = 1i32;
    while i < chars.len() {
        match chars[i] {
            '(' => {
                depth += 1;
                cur.push('(');
            }
            ')' => {
                depth -= 1;
                if depth == 0 {
                    let t = cur.trim();
                    if !t.is_empty() {
                        params.push(t.to_string());
                    }
                    // Variadic param → unsupported.
                    if params.iter().any(|p| p.contains("...")) {
                        return None;
                    }
                    return Some((params, i + 1));
                }
                cur.push(')');
            }
            ',' if depth == 1 => {
                params.push(cur.trim().to_string());
                cur.clear();
            }
            c => cur.push(c),
        }
        i += 1;
    }
    None // unbalanced
}

/// Remove `/* … */` and `// …` comments from a macro replacement list, so the
/// textual body matches what the AST pass's `preproc_arg` yields.
fn strip_comments(s: &str) -> String {
    let chars: Vec<char> = s.chars().collect();
    let mut out = String::with_capacity(s.len());
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
            i += 2;
            while i + 1 < chars.len() && !(chars[i] == '*' && chars[i + 1] == '/') {
                i += 1;
            }
            i += 2;
            out.push(' ');
        } else if chars[i] == '/' && i + 1 < chars.len() && chars[i + 1] == '/' {
            break;
        } else {
            out.push(chars[i]);
            i += 1;
        }
    }
    out
}

fn collect_rec(node: &Node, source: &str, out: &mut HashMap<String, FunctionMacro>) {
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            match child.kind() {
                "preproc_function_def" => {
                    if let Some((name, m)) = parse_function_def(&child, source) {
                        // First definition wins; redefinitions (e.g. platform
                        // #ifdef branches) are ambiguous, so keep the first.
                        out.entry(name).or_insert(m);
                    }
                }
                kind if kind.starts_with("preproc_") => collect_rec(&child, source, out),
                _ => {}
            }
        }
    }
}

fn parse_function_def(node: &Node, source: &str) -> Option<(String, FunctionMacro)> {
    let name = node
        .child_by_field_name("name")?
        .utf8_text(source.as_bytes())
        .ok()?
        .to_string();

    let params_node = node.child_by_field_name("parameters")?;
    let mut params = Vec::new();
    for i in 0..params_node.child_count() {
        if let Some(p) = params_node.child(i) {
            match p.kind() {
                "identifier" => params.push(p.utf8_text(source.as_bytes()).ok()?.to_string()),
                // variadic param: bail (unsupported)
                "..." => return None,
                _ => {}
            }
        }
    }

    let body = node
        .child_by_field_name("value")
        .and_then(|v| v.utf8_text(source.as_bytes()).ok())
        .unwrap_or("")
        .trim()
        .to_string();

    // Skip stringize / token-paste — require real preprocessor semantics.
    if body_uses_paste_or_stringize(&body) {
        return None;
    }

    Some((name, FunctionMacro { params, body }))
}

/// Detect `#`/`##` operators in a replacement list, ignoring occurrences inside
/// string/char literals.
fn body_uses_paste_or_stringize(body: &str) -> bool {
    let bytes: Vec<char> = body.chars().collect();
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            '"' | '\'' => {
                let quote = bytes[i];
                i += 1;
                while i < bytes.len() && bytes[i] != quote {
                    if bytes[i] == '\\' {
                        i += 1;
                    }
                    i += 1;
                }
                i += 1;
            }
            '#' => return true,
            _ => i += 1,
        }
    }
    false
}

/// Expand a single function-like macro invocation `name(args...)` using `table`,
/// recursively rescanning the result. Returns `None` if `name` is not a known
/// function-like macro or the argument count does not match the parameters.
pub fn expand_invocation(
    table: &HashMap<String, FunctionMacro>,
    name: &str,
    args: &[String],
) -> Option<String> {
    let mut active = HashSet::new();
    expand_named(table, name, args, &mut active, 0)
}

fn expand_named(
    table: &HashMap<String, FunctionMacro>,
    name: &str,
    args: &[String],
    active: &mut HashSet<String>,
    depth: usize,
) -> Option<String> {
    if depth >= MAX_EXPAND_DEPTH || active.contains(name) {
        return None;
    }
    let m = table.get(name)?;
    if m.params.len() != args.len() {
        return None; // arity mismatch — do not expand
    }
    let mut map = HashMap::new();
    for (p, a) in m.params.iter().zip(args.iter()) {
        map.insert(p.clone(), a.clone());
    }
    let substituted = substitute_params(&m.body, &map);
    active.insert(name.to_string());
    let rescanned = rescan(table, &substituted, active, depth + 1);
    active.remove(name);
    Some(rescanned)
}

/// Replace whole-identifier occurrences of parameter names in `body` with their
/// argument text. Skips identifiers inside string/char literals.
fn substitute_params(body: &str, map: &HashMap<String, String>) -> String {
    let chars: Vec<char> = body.chars().collect();
    let mut out = String::with_capacity(body.len());
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if c == '"' || c == '\'' {
            let quote = c;
            out.push(c);
            i += 1;
            while i < chars.len() {
                out.push(chars[i]);
                if chars[i] == '\\' && i + 1 < chars.len() {
                    out.push(chars[i + 1]);
                    i += 2;
                    continue;
                }
                if chars[i] == quote {
                    i += 1;
                    break;
                }
                i += 1;
            }
        } else if is_ident_start(c) {
            let start = i;
            while i < chars.len() && is_ident_char(chars[i]) {
                i += 1;
            }
            let ident: String = chars[start..i].iter().collect();
            if let Some(repl) = map.get(&ident) {
                out.push_str(repl);
            } else {
                out.push_str(&ident);
            }
        } else {
            out.push(c);
            i += 1;
        }
    }
    out
}

/// Rescan expanded text, expanding any further function-like macro invocations.
fn rescan(
    table: &HashMap<String, FunctionMacro>,
    text: &str,
    active: &mut HashSet<String>,
    depth: usize,
) -> String {
    if depth >= MAX_EXPAND_DEPTH {
        return text.to_string();
    }
    let chars: Vec<char> = text.chars().collect();
    let mut out = String::with_capacity(text.len());
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if c == '"' || c == '\'' {
            let quote = c;
            out.push(c);
            i += 1;
            while i < chars.len() {
                out.push(chars[i]);
                if chars[i] == '\\' && i + 1 < chars.len() {
                    out.push(chars[i + 1]);
                    i += 2;
                    continue;
                }
                if chars[i] == quote {
                    i += 1;
                    break;
                }
                i += 1;
            }
        } else if is_ident_start(c) {
            let start = i;
            while i < chars.len() && is_ident_char(chars[i]) {
                i += 1;
            }
            let ident: String = chars[start..i].iter().collect();
            // Is this a function-like macro invocation? Look for a '(' after
            // optional whitespace.
            let mut j = i;
            while j < chars.len() && chars[j].is_whitespace() {
                j += 1;
            }
            if table.contains_key(&ident)
                && !active.contains(&ident)
                && j < chars.len()
                && chars[j] == '('
            {
                if let Some((args, end)) = parse_call_args(&chars, j) {
                    if let Some(expanded) = expand_named(table, &ident, &args, active, depth) {
                        out.push_str(&expanded);
                        i = end;
                        continue;
                    }
                }
            }
            out.push_str(&ident);
        } else {
            out.push(c);
            i += 1;
        }
    }
    out
}

/// Parse a parenthesized, comma-separated argument list starting at `open`
/// (which must index a `'('`). Returns the argument texts (trimmed) and the
/// index just past the closing `')'`. Respects nested parens/brackets/braces
/// and string/char literals.
fn parse_call_args(chars: &[char], open: usize) -> Option<(Vec<String>, usize)> {
    debug_assert_eq!(chars[open], '(');
    let mut args = Vec::new();
    let mut cur = String::new();
    let mut depth = 0i32;
    let mut i = open;
    while i < chars.len() {
        let c = chars[i];
        match c {
            '"' | '\'' => {
                let quote = c;
                cur.push(c);
                i += 1;
                while i < chars.len() {
                    cur.push(chars[i]);
                    if chars[i] == '\\' && i + 1 < chars.len() {
                        cur.push(chars[i + 1]);
                        i += 2;
                        continue;
                    }
                    if chars[i] == quote {
                        i += 1;
                        break;
                    }
                    i += 1;
                }
            }
            '(' | '[' | '{' => {
                depth += 1;
                if depth > 1 {
                    cur.push(c);
                }
                i += 1;
            }
            ')' | ']' | '}' => {
                depth -= 1;
                if depth == 0 {
                    // end of arg list
                    let trimmed = cur.trim();
                    // An empty `()` call has zero args, not one empty arg.
                    if !(args.is_empty() && trimmed.is_empty()) {
                        args.push(trimmed.to_string());
                    }
                    return Some((args, i + 1));
                }
                cur.push(c);
                i += 1;
            }
            ',' if depth == 1 => {
                args.push(cur.trim().to_string());
                cur.clear();
                i += 1;
            }
            _ => {
                cur.push(c);
                i += 1;
            }
        }
    }
    None // unbalanced
}

/// Parameter indices that a function-like macro *writes* — i.e. the macro body
/// assigns to the (whole) parameter, directly or after expanding nested macros
/// drawn from `table`. Such positions are macro **output arguments**: a
/// bare-identifier argument there is being written by the macro, not read, so it
/// is not a use of uninitialized memory and is initialized afterwards.
///
/// Example: curl's `CF_DATA_SAVE(save, cf, data)` expands to
/// `do { (save) = …; … } while(0)`, so index 0 (`save`) is an output. The other
/// args (`cf`, `data`) only appear as reads, so they are not outputs.
///
/// Detection is deliberately conservative — only *whole-object* assignment
/// (`(param) = …`) counts. Field/element/deref writes (`param->f = …`,
/// `param[i] = …`, `*param = …`) read `param` first and so are NOT outputs.
pub fn macro_output_param_indices(
    table: &HashMap<String, FunctionMacro>,
    name: &str,
) -> Vec<usize> {
    let m = match table.get(name) {
        Some(m) => m,
        None => return Vec::new(),
    };
    if m.params.is_empty() {
        return Vec::new();
    }
    // Substitute each parameter with a unique sentinel, then fully expand (so
    // nested macros from the same body — `CF_CTX_CALL_DATA`, `CURL_UNCONST` —
    // resolve and we see the real lvalue context of each parameter).
    let sentinels: Vec<String> = (0..m.params.len())
        .map(|i| format!("__SQC_MOUT_{i}__"))
        .collect();
    let expanded = match expand_invocation(table, name, &sentinels) {
        Some(e) => e,
        None => return Vec::new(),
    };
    let mut out = Vec::new();
    for (i, sent) in sentinels.iter().enumerate() {
        if is_whole_assignment_target(&expanded, sent) {
            out.push(i);
        }
    }
    out
}

/// Parameter indices that a function-like macro frees-and-nulls: the body
/// assigns the (whole) parameter the null pointer constant (`(param) = NULL`),
/// directly or after expanding nested macros from `table`. This is the
/// "safe free" idiom — curl `Curl_safefree(ptr)` expands to
/// `do { curlx_free(ptr); (ptr) = NULL; } while(0)`, so index 0 is reported.
///
/// MEM30-C already treats such macros as a free (the name contains `FREE`), but
/// cannot see the `= NULL`; consuming this list lets it clear the argument's
/// freed state — exactly as if the caller had written `free(p); p = NULL;` —
/// removing use-after-free / double-free false positives on safe-free wrappers.
/// (mosquitto `mosquitto_FREE`, `SAFE_FREE` share the idiom — engine, not
/// allowlist.)
pub fn macro_nulls_param_indices(table: &HashMap<String, FunctionMacro>, name: &str) -> Vec<usize> {
    let m = match table.get(name) {
        Some(m) => m,
        None => return Vec::new(),
    };
    if m.params.is_empty() {
        return Vec::new();
    }
    let sentinels: Vec<String> = (0..m.params.len())
        .map(|i| format!("__SQC_MNULL_{i}__"))
        .collect();
    let expanded = match expand_invocation(table, name, &sentinels) {
        Some(e) => e,
        None => return Vec::new(),
    };
    let mut out = Vec::new();
    for (i, sent) in sentinels.iter().enumerate() {
        if is_null_assignment_target(&expanded, sent) {
            out.push(i);
        }
    }
    out
}

/// True if the token starting at `start` (after skipping whitespace and an
/// optional opening paren of a cast we don't model) is the null pointer
/// constant `NULL` or `0`, terminated by a non-identifier/non-digit char.
fn rhs_is_null_constant(chars: &[char], start: usize) -> bool {
    let n = chars.len();
    let mut j = start;
    while j < n && chars[j].is_whitespace() {
        j += 1;
    }
    // `NULL`
    let null_kw = ['N', 'U', 'L', 'L'];
    if j + 4 <= n && chars[j..j + 4] == null_kw && (j + 4 >= n || !is_ident_char(chars[j + 4])) {
        return true;
    }
    // `0` (or `0L`, `0u`… ) — a bare zero literal, not `0x..`/`0.5`/`01`.
    if j < n && chars[j] == '0' {
        let after = if j + 1 < n { chars[j + 1] } else { ' ' };
        if !after.is_ascii_digit() && after != '.' && after != 'x' && after != 'X' {
            return true;
        }
    }
    false
}

/// True if identifier `ident` appears in `text` as the target of a whole-object
/// assignment: `ident =` or `(ident) =` (any number of wrapping parens),
/// excluding compound assignment (`+=`/`==`/…), field/element/deref writes, and
/// member/arrow access. See [`macro_output_param_indices`].
fn is_whole_assignment_target(text: &str, ident: &str) -> bool {
    find_assignment_targets(text, ident, |_| true)
}

/// True if `ident` appears in `text` as a whole-object assignment whose
/// right-hand side is the null pointer constant (`NULL` or `0`) — i.e.
/// `ident = NULL` / `(ident) = 0`. See [`macro_nulls_param_indices`].
fn is_null_assignment_target(text: &str, ident: &str) -> bool {
    let chars: Vec<char> = text.chars().collect();
    find_assignment_targets(text, ident, |rhs_start| {
        rhs_is_null_constant(&chars, rhs_start)
    })
}

/// Scan `text` for whole-object assignment targets named `ident` (handling
/// wrapping parens and excluding deref/field/compound/comparison forms — see
/// [`is_whole_assignment_target`]). For each candidate, call `rhs_ok` with the
/// char index just past the `=`; return true on the first that passes.
fn find_assignment_targets(text: &str, ident: &str, rhs_ok: impl Fn(usize) -> bool) -> bool {
    let chars: Vec<char> = text.chars().collect();
    let id: Vec<char> = ident.chars().collect();
    let (n, m) = (chars.len(), id.len());
    if m == 0 {
        return false;
    }
    let mut i = 0;
    while i + m <= n {
        if chars[i..i + m] == id[..] {
            // Whole-token match: boundaries must not be identifier chars.
            let prev_ok = i == 0 || !is_ident_char(chars[i - 1]);
            let next_ok = i + m >= n || !is_ident_char(chars[i + m]);
            // Look back past wrapping `(` and whitespace for the first
            // significant char. `*`/`.`/`->` there means a deref/field write
            // (`*(p) =`, `(*p) =`, `obj.ident`) which READS the identifier.
            let mut b = i;
            while b > 0 && (chars[b - 1].is_whitespace() || chars[b - 1] == '(') {
                b -= 1;
            }
            let prev_c = if b > 0 { chars[b - 1] } else { ' ' };
            let arrow = b >= 2 && chars[b - 1] == '>' && chars[b - 2] == '-';
            if prev_ok && next_ok && prev_c != '.' && prev_c != '*' && !arrow {
                // Skip whitespace and closing parens after the identifier.
                let mut j = i + m;
                while j < n && (chars[j].is_whitespace() || chars[j] == ')') {
                    j += 1;
                }
                // A single `=` (not `==`) immediately follows → assignment target.
                if j < n && chars[j] == '=' && (j + 1 >= n || chars[j + 1] != '=') && rhs_ok(j + 1)
                {
                    return true;
                }
            }
        }
        i += 1;
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::CParser;

    fn table(src: &str) -> HashMap<String, FunctionMacro> {
        let mut p = CParser::new().unwrap();
        let tree = p.parse_source(src).unwrap();
        collect_function_macros(&tree.root_node(), src)
    }

    #[test]
    fn collects_simple_function_macro() {
        let t = table("#define MIN(x,y) (((x) < (y)) ? (x) : (y))\n");
        let m = t.get("MIN").expect("MIN collected");
        assert_eq!(m.params, vec!["x", "y"]);
        assert!(m.body.contains("(x) < (y)"));
    }

    #[test]
    fn skips_stringize_and_paste() {
        let t = table("#define STR(x) #x\n#define CAT(a,b) a##b\n#define OK(a) ((a)+1)\n");
        assert!(!t.contains_key("STR"));
        assert!(!t.contains_key("CAT"));
        assert!(t.contains_key("OK"));
    }

    #[test]
    fn skips_variadic() {
        let t = table("#define LOG(fmt, ...) printf(fmt, __VA_ARGS__)\n");
        assert!(!t.contains_key("LOG"));
    }

    #[test]
    fn expands_simple() {
        let t = table("#define MIN(x,y) (((x) < (y)) ? (x) : (y))\n");
        let out = expand_invocation(&t, "MIN", &["a".into(), "b+1".into()]).unwrap();
        assert_eq!(out, "(((a) < (b+1)) ? (a) : (b+1))");
    }

    #[test]
    fn expands_deref_macro() {
        let t = table("#define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))\n");
        let out = expand_invocation(&t, "ORIGVFS", &["pFile".into()]).unwrap();
        assert_eq!(out, "((sqlite3_vfs*)((pFile)->pAppData))");
    }

    #[test]
    fn arity_mismatch_returns_none() {
        let t = table("#define MIN(x,y) ((x)<(y)?(x):(y))\n");
        assert!(expand_invocation(&t, "MIN", &["a".into()]).is_none());
    }

    #[test]
    fn does_not_substitute_inside_string() {
        let t = table("#define TAG(x) \"x is here\" x\n");
        // The "x" inside the string literal must not be replaced.
        let out = expand_invocation(&t, "TAG", &["v".into()]).unwrap();
        assert_eq!(out, "\"x is here\" v");
    }

    #[test]
    fn recursive_rescan_nested_macro() {
        let t = table("#define SQUARE(z) ((z)*(z))\n#define DIST(a) SQUARE(a)\n");
        let out = expand_invocation(&t, "DIST", &["n+1".into()]).unwrap();
        assert_eq!(out, "((n+1)*(n+1))");
    }

    #[test]
    fn self_reference_does_not_loop() {
        // `#define A(x) A(x)` must not infinitely recurse; the inner A is left
        // unexpanded once A is active.
        let t = table("#define A(x) A((x)+1)\n");
        let out = expand_invocation(&t, "A", &["v".into()]).unwrap();
        assert_eq!(out, "A((v)+1)");
    }

    #[test]
    fn nested_call_args_with_commas() {
        let t = table("#define ADD(a,b) ((a)+(b))\n#define ID(x) (x)\n");
        // ID(ADD(1,2)) — the comma is inside a nested call, one arg to ID.
        let out = expand_invocation(&t, "ID", &["ADD(1,2)".into()]).unwrap();
        assert_eq!(out, "(((1)+(2)))");
    }

    // ── Textual error-correcting collector ──────────────────────────────────

    #[test]
    fn textual_collects_function_like() {
        let t = collect_function_macros_textual(
            "#define curlx_free(ptr) curl_dbg_free(ptr, __LINE__, __FILE__)\n",
        );
        let m = t.get("curlx_free").expect("curlx_free collected");
        assert_eq!(m.params, vec!["ptr"]);
        assert_eq!(m.body, "curl_dbg_free(ptr, __LINE__, __FILE__)");
    }

    #[test]
    fn textual_skips_object_like() {
        // Space before '(' → object-like alias, not a function-like macro.
        let t = collect_function_macros_textual("#define curlx_free Curl_cfree\n");
        assert!(!t.contains_key("curlx_free"));
        let t2 = collect_function_macros_textual("#define PAREN (1 + 2)\n");
        assert!(!t2.contains_key("PAREN"));
    }

    #[test]
    fn textual_skips_variadic_and_paste() {
        let t = collect_function_macros_textual(
            "#define LOG(fmt, ...) printf(fmt, __VA_ARGS__)\n#define CAT(a,b) a##b\n",
        );
        assert!(!t.contains_key("LOG"));
        assert!(!t.contains_key("CAT"));
    }

    #[test]
    fn textual_joins_continuation() {
        let t = collect_function_macros_textual(
            "#define curlx_calloc(nbelem, size) \\\n  curl_dbg_calloc(nbelem, size, __LINE__, __FILE__)\n",
        );
        let m = t
            .get("curlx_calloc")
            .expect("collected across continuation");
        assert_eq!(m.params, vec!["nbelem", "size"]);
        assert!(m.body.contains("curl_dbg_calloc(nbelem, size"));
    }

    #[test]
    fn textual_strips_comments() {
        let t = collect_function_macros_textual("#define WRAP(x) real(x) /* trailing */\n");
        assert_eq!(t.get("WRAP").unwrap().body, "real(x)");
    }

    #[test]
    fn textual_indented_define_with_space_after_hash() {
        let t = collect_function_macros_textual("  #  define INDENT(x) ((x)+1)\n");
        assert!(t.contains_key("INDENT"));
    }

    #[test]
    fn does_not_match_defined_operator() {
        let t = collect_function_macros_textual("#if defined(FOO)\n#endif\n");
        assert!(t.is_empty());
    }

    // ── Macro output-parameter detection ────────────────────────────────────

    #[test]
    fn output_param_simple_assignment() {
        // The first parameter is assigned; the others are only read.
        let t = table("#define SAVE(out, a, b) do { (out) = (a) + (b); } while(0)\n");
        assert_eq!(macro_output_param_indices(&t, "SAVE"), vec![0]);
    }

    #[test]
    fn output_param_cf_data_save_shape() {
        // curl's CF_DATA_SAVE pattern (with the nested CF_CTX_CALL_DATA macro
        // resolving through the table). save (arg 0) is assigned; cf/data are read.
        let t = table(
            "#define CF_CTX_CALL_DATA(cf) ((cf)->ctx->call_data)\n\
             #define CF_DATA_SAVE(save, cf, data) do { (save) = CF_CTX_CALL_DATA(cf); CF_CTX_CALL_DATA(cf).data = (data); } while(0)\n",
        );
        assert_eq!(macro_output_param_indices(&t, "CF_DATA_SAVE"), vec![0]);
    }

    #[test]
    fn output_param_excludes_field_and_deref_writes() {
        // Field write (p->f =), element write (p[i] =), and deref write (*p =)
        // all READ the pointer first — they are not whole-object outputs.
        let t = table(
            "#define FW(p) do { (p)->f = 1; } while(0)\n\
             #define EW(p) do { (p)[0] = 1; } while(0)\n\
             #define DW(p) do { *(p) = 1; } while(0)\n",
        );
        assert!(macro_output_param_indices(&t, "FW").is_empty());
        assert!(macro_output_param_indices(&t, "EW").is_empty());
        assert!(macro_output_param_indices(&t, "DW").is_empty());
    }

    #[test]
    fn output_param_excludes_compound_and_comparison() {
        // `+=` reads first; `==` is a comparison, not an assignment.
        let t = table(
            "#define ADDEQ(x, y) do { (x) += (y); } while(0)\n\
             #define CMP(x, y) ((x) == (y))\n",
        );
        assert!(macro_output_param_indices(&t, "ADDEQ").is_empty());
        assert!(macro_output_param_indices(&t, "CMP").is_empty());
    }

    #[test]
    fn output_param_multiple_outputs() {
        let t = table("#define BOTH(a, b, c) do { a = 1; b = 2; (void)c; } while(0)\n");
        assert_eq!(macro_output_param_indices(&t, "BOTH"), vec![0, 1]);
    }

    #[test]
    fn output_param_unknown_macro_is_empty() {
        let t = table("#define X(a) (a)\n");
        assert!(macro_output_param_indices(&t, "NOPE").is_empty());
    }

    // ── Free-and-null (safe-free) macro detection ───────────────────────────

    #[test]
    fn nulls_param_curl_safefree_shape() {
        // curl Curl_safefree expands free(ptr) then (ptr)=NULL through the
        // nested curlx_free wrapper.
        let t = table(
            "#define curlx_free(p) free(p)\n\
             #define Curl_safefree(ptr) do { curlx_free(ptr); (ptr) = NULL; } while(0)\n",
        );
        assert_eq!(macro_nulls_param_indices(&t, "Curl_safefree"), vec![0]);
    }

    #[test]
    fn nulls_param_zero_literal() {
        let t = table("#define SAFE_FREE(x) do { free(x); (x) = 0; } while(0)\n");
        assert_eq!(macro_nulls_param_indices(&t, "SAFE_FREE"), vec![0]);
    }

    #[test]
    fn nulls_param_excludes_plain_free_no_null() {
        // A free wrapper that does NOT null its arg must not be reported.
        let t = table("#define just_free(p) free(p)\n");
        assert!(macro_nulls_param_indices(&t, "just_free").is_empty());
    }

    #[test]
    fn nulls_param_excludes_nonzero_and_field_assign() {
        // RHS is not the null constant; and a field write is not whole-object.
        let t = table(
            "#define SETONE(x) do { (x) = 1; } while(0)\n\
             #define CLEARF(p) do { (p)->next = NULL; } while(0)\n",
        );
        assert!(macro_nulls_param_indices(&t, "SETONE").is_empty());
        assert!(macro_nulls_param_indices(&t, "CLEARF").is_empty());
    }

    #[test]
    fn nulls_param_only_nulled_arg() {
        // Frees a, nulls b — only b is the nulled param.
        let t = table("#define FN(a, b) do { free(a); (b) = NULL; } while(0)\n");
        assert_eq!(macro_nulls_param_indices(&t, "FN"), vec![1]);
    }

    #[test]
    fn merge_recovers_macro_in_error_region() {
        // A torture-header shape: a malformed construct forces tree-sitter into
        // ERROR recovery, so the following `#define` is NOT emitted as a
        // preproc_function_def — only the textual pass recovers it.
        let src = "#define BROKEN(a) a +++ ++ +\n\
                   int f(void) { return 1 } }\n\
                   #define recovered_free(ptr) free(ptr)\n";
        let mut p = CParser::new().unwrap();
        let tree = p.parse_source(src).unwrap();
        let ast_only = {
            let mut out = HashMap::new();
            collect_rec(&tree.root_node(), src, &mut out);
            out
        };
        let merged = collect_function_macros(&tree.root_node(), src);
        // Whatever the AST pass managed, the merged set must contain the wrapper.
        assert!(
            merged.contains_key("recovered_free"),
            "textual pass should recover recovered_free; ast_only={:?}",
            ast_only.keys().collect::<Vec<_>>()
        );
        assert_eq!(merged["recovered_free"].body, "free(ptr)");
    }
}