buildlang 1.15.0

BuildLang (buildc): an effects-oriented compiler with a verified C path, shader output, experimental backends, opt-in linear types, and re-checkable accountability + scientific-runtime receipts
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
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
// ===============================================================================
// BUILDLANG CODEGEN - GENERATED C VERIFIER
// ===============================================================================
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2022-2026 Zain Dana Harper.
// ===============================================================================

//! A check over the generated C text: every function the user section calls must
//! be declared somewhere in the output or come from the C standard library.
//!
//! The lowerer falls back to a bare C call when it does not recognise a method or
//! function (`v.iter()` becomes `iter(v)`). Without this pass the program passes
//! `buildc check` and then fails inside the C compiler with an "implicit
//! declaration" error about generated code. With it, `check` and `build` reject the
//! program with the BuildLang name of the call and a fix hint.
//!
//! The scan is a small C tokenizer, not a C parser. A name counts as declared when
//! it appears as `<type> name(` (a definition or prototype) or `#define name(`. A
//! name counts as called when it appears as `name(` after the end-of-runtime marker
//! in any other position.

use std::collections::BTreeSet;

/// Marker the C backend writes after the embedded runtime.
const RUNTIME_END_MARKER: &str = "End BuildLang Runtime";

/// C keywords and operators that look like calls (`sizeof(x)`, `if (x)`).
const C_KEYWORDS: &[&str] = &[
    "if",
    "else",
    "while",
    "for",
    "do",
    "switch",
    "case",
    "return",
    "sizeof",
    "goto",
    "break",
    "continue",
    "default",
    "typedef",
    "struct",
    "union",
    "enum",
    "static",
    "const",
    "volatile",
    "extern",
    "inline",
    "register",
    "restrict",
    "_Alignof",
    "_Static_assert",
    "_Generic",
    "alignof",
    "__attribute__",
    "__declspec",
    "defined",
];

/// Functions and function-like macros from the C headers the runtime includes.
const C_STDLIB: &[&str] = &[
    // stdio
    "printf",
    "fprintf",
    "sprintf",
    "snprintf",
    "vprintf",
    "vfprintf",
    "vsnprintf",
    "puts",
    "fputs",
    "fputc",
    "putchar",
    "fflush",
    "fopen",
    "fclose",
    "fread",
    "fwrite",
    "fgets",
    "getchar",
    "fgetc",
    "fseek",
    "ftell",
    "rewind",
    "perror",
    "remove",
    "rename",
    "setvbuf",
    "fileno",
    "_fileno",
    "_setmode",
    "scanf",
    "sscanf",
    "fscanf",
    // stdlib
    "malloc",
    "calloc",
    "realloc",
    "free",
    "exit",
    "abort",
    "atexit",
    "atoi",
    "atol",
    "atoll",
    "atof",
    "strtol",
    "strtoll",
    "strtoul",
    "strtoull",
    "strtod",
    "strtof",
    "qsort",
    "bsearch",
    "rand",
    "srand",
    "getenv",
    "system",
    "labs",
    "llabs",
    "div",
    // string
    "memcpy",
    "memmove",
    "memset",
    "memcmp",
    "memchr",
    "strlen",
    "strcmp",
    "strncmp",
    "strcpy",
    "strncpy",
    "strcat",
    "strncat",
    "strchr",
    "strrchr",
    "strstr",
    "strdup",
    "strtok",
    "strerror",
    // math
    "sqrt",
    "sqrtf",
    "pow",
    "powf",
    "exp",
    "expf",
    "exp2",
    "log",
    "logf",
    "log2",
    "log10",
    "sin",
    "sinf",
    "cos",
    "cosf",
    "tan",
    "tanf",
    "asin",
    "acos",
    "atan",
    "atan2",
    "sinh",
    "cosh",
    "tanh",
    "floor",
    "floorf",
    "ceil",
    "ceilf",
    "round",
    "roundf",
    "trunc",
    "truncf",
    "fabs",
    "fabsf",
    "fmod",
    "fmodf",
    "fmin",
    "fma",
    "fmax",
    "fminf",
    "fmaxf",
    "cbrt",
    "hypot",
    "isnan",
    "isinf",
    "isfinite",
    "copysign",
    "abs",
    "nextafter",
    "ldexp",
    "frexp",
    "modf",
    // setjmp, assert, stdarg, time, ctype
    "setjmp",
    "longjmp",
    "assert",
    "va_start",
    "va_end",
    "va_arg",
    "va_copy",
    "time",
    "clock",
    "isdigit",
    "isalpha",
    "isspace",
    "isalnum",
    "isupper",
    "islower",
    "toupper",
    "tolower",
    // windows and posix headers the runtime includes
    "Sleep",
    "GetTickCount64",
    "QueryPerformanceCounter",
    "QueryPerformanceFrequency",
    "WSAStartup",
    "WSACleanup",
    "socket",
    "connect",
    "send",
    "recv",
    "closesocket",
    "close",
    "getaddrinfo",
    "freeaddrinfo",
    "htons",
    "inet_pton",
    "usleep",
    "opendir",
    "readdir",
    "closedir",
    "stat",
    "_stat",
    "mkdir",
    "_mkdir",
    "isatty",
    "_isatty",
    "write",
    "read",
    // Thread pool for par_for / par_map (M5): Win32 and POSIX threads
    "CreateThread",
    "CloseHandle",
    "GetSystemInfo",
    "InitializeCriticalSection",
    "InitializeConditionVariable",
    "EnterCriticalSection",
    "LeaveCriticalSection",
    "SleepConditionVariableCS",
    "WakeAllConditionVariable",
    "pthread_create",
    "pthread_detach",
    "pthread_mutex_lock",
    "pthread_mutex_unlock",
    "pthread_cond_wait",
    "pthread_cond_broadcast",
    "sysconf",
];

#[derive(Debug, Clone, PartialEq, Eq)]
enum Tok<'a> {
    Ident(&'a str),
    Punct(char),
    Directive(&'a str),
}

/// Tokenize C text into identifiers, punctuation and preprocessor directive names,
/// skipping comments, string literals and character literals.
fn tokenize(src: &str) -> Vec<Tok<'_>> {
    let bytes = src.as_bytes();
    let mut out = Vec::new();
    let mut i = 0;
    let mut line_start = true;
    while i < bytes.len() {
        let c = bytes[i];
        if c == b'\n' {
            line_start = true;
            i += 1;
            continue;
        }
        if c.is_ascii_whitespace() {
            i += 1;
            continue;
        }
        if c == b'/' && bytes.get(i + 1) == Some(&b'/') {
            while i < bytes.len() && bytes[i] != b'\n' {
                i += 1;
            }
            continue;
        }
        if c == b'/' && bytes.get(i + 1) == Some(&b'*') {
            i += 2;
            while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
                i += 1;
            }
            i += 2;
            continue;
        }
        if c == b'"' || c == b'\'' {
            let quote = c;
            i += 1;
            while i < bytes.len() && bytes[i] != quote {
                if bytes[i] == b'\\' {
                    i += 1;
                }
                i += 1;
            }
            i += 1;
            line_start = false;
            continue;
        }
        if c == b'#' && line_start {
            let mut j = i + 1;
            while j < bytes.len() && (bytes[j] == b' ' || bytes[j] == b'\t') {
                j += 1;
            }
            let start = j;
            while j < bytes.len() && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'_') {
                j += 1;
            }
            out.push(Tok::Directive(&src[start..j]));
            i = j;
            line_start = false;
            continue;
        }
        line_start = false;
        if c.is_ascii_alphabetic() || c == b'_' {
            let start = i;
            while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
                i += 1;
            }
            out.push(Tok::Ident(&src[start..i]));
            continue;
        }
        if c.is_ascii_digit() {
            while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'.') {
                i += 1;
            }
            continue;
        }
        out.push(Tok::Punct(c as char));
        i += 1;
    }
    out
}

fn is_keyword(name: &str) -> bool {
    C_KEYWORDS.contains(&name)
}

/// Names declared in `src` as functions, prototypes or function-like macros.
fn declared_names(toks: &[Tok<'_>]) -> BTreeSet<String> {
    let mut declared = BTreeSet::new();
    for (k, tok) in toks.iter().enumerate() {
        let Tok::Ident(name) = tok else { continue };
        if !matches!(toks.get(k + 1), Some(Tok::Punct('('))) {
            continue;
        }
        let prev = if k == 0 { None } else { toks.get(k - 1) };
        let is_decl = match prev {
            Some(Tok::Ident(p)) => !is_keyword(p) || matches!(*p, "struct" | "static" | "const"),
            Some(Tok::Punct('*')) => {
                // `void* name(` is a declaration; `x = *name(` is a call.
                matches!(toks.get(k.wrapping_sub(2)), Some(Tok::Ident(t)) if !is_keyword(t))
            }
            Some(Tok::Directive("define")) => true,
            _ => false,
        };
        if is_decl {
            declared.insert((*name).to_string());
        }
    }
    // Also count `#define NAME` object-like macros and typedef'd function pointers.
    for (k, tok) in toks.iter().enumerate() {
        if let Tok::Directive("define") = tok {
            if let Some(Tok::Ident(name)) = toks.get(k + 1) {
                declared.insert((*name).to_string());
            }
        }
    }
    declared
}

/// Prefixes of names a macro builds by token pasting (`bl_iadd_##SUFFIX(`). A
/// called name that starts with one of these is generated by a macro expansion.
fn pasted_prefixes(toks: &[Tok<'_>]) -> Vec<String> {
    let mut prefixes = Vec::new();
    for w in toks.windows(4) {
        if let [Tok::Ident(p), Tok::Punct('#'), Tok::Punct('#'), Tok::Ident(_)] = w {
            prefixes.push((*p).to_string());
        }
    }
    prefixes
}

/// Names called from the user section of the generated C.
fn called_names(toks: &[Tok<'_>]) -> BTreeSet<String> {
    let mut called = BTreeSet::new();
    for (k, tok) in toks.iter().enumerate() {
        let Tok::Ident(name) = tok else { continue };
        if is_keyword(name) || !matches!(toks.get(k + 1), Some(Tok::Punct('('))) {
            continue;
        }
        // `int32_t (*)(...)` and `T (*name)(...)` are function-pointer types.
        if matches!(toks.get(k + 2), Some(Tok::Punct('*'))) {
            continue;
        }
        let prev = if k == 0 { None } else { toks.get(k - 1) };
        let looks_like_decl = match prev {
            Some(Tok::Ident(p)) => !is_keyword(p),
            Some(Tok::Directive(_)) => true,
            Some(Tok::Punct('*')) => {
                matches!(toks.get(k.wrapping_sub(2)), Some(Tok::Ident(t)) if !is_keyword(t))
            }
            _ => false,
        };
        // A member call through a struct field (`v.fn(` or `p->fn(`) is a
        // function pointer, not a free function.
        let is_member = matches!(prev, Some(Tok::Punct('.')))
            || (matches!(prev, Some(Tok::Punct('>')))
                && matches!(toks.get(k.wrapping_sub(2)), Some(Tok::Punct('-'))));
        if !looks_like_decl && !is_member {
            called.insert((*name).to_string());
        }
    }
    called
}

/// Variables and parameters that hold function pointers are called like
/// functions. Collect names declared with a `(*name)` declarator, so a call
/// through them is not reported.
fn variable_names(toks: &[Tok<'_>]) -> BTreeSet<String> {
    let mut vars = BTreeSet::new();
    for (k, tok) in toks.iter().enumerate() {
        if let Tok::Ident(name) = tok {
            let next = toks.get(k + 1);
            // `(*name)` function pointer declarator. Plain variables (`size_t
            // len;`) are not counted: a call to their name is still undeclared.
            if matches!(
                k.checked_sub(1).and_then(|p| toks.get(p)),
                Some(Tok::Punct('*'))
            ) && matches!(
                k.checked_sub(2).and_then(|p| toks.get(p)),
                Some(Tok::Punct('('))
            ) && matches!(next, Some(Tok::Punct(')')))
            {
                vars.insert((*name).to_string());
            }
        }
    }
    vars
}

/// Return the names the user section of `c_source` calls without any declaration.
pub fn undeclared_calls(c_source: &str) -> Vec<String> {
    let user_start = c_source
        .find(RUNTIME_END_MARKER)
        .map(|pos| c_source[pos..].find('\n').map_or(pos, |nl| pos + nl))
        .unwrap_or(0);
    let all_toks = tokenize(c_source);
    let user_toks = tokenize(&c_source[user_start..]);
    let declared = declared_names(&all_toks);
    let vars = variable_names(&all_toks);
    let prefixes = pasted_prefixes(&all_toks);
    called_names(&user_toks)
        .into_iter()
        .filter(|n| {
            !declared.contains(n)
                && !vars.contains(n)
                && !C_STDLIB.contains(&n.as_str())
                && !prefixes.iter().any(|p| n.starts_with(p.as_str()))
        })
        .collect()
}

/// A fix hint for a call the C backend cannot compile, keyed by the BuildLang name.
pub fn hint_for(name: &str) -> String {
    match name {
        "iter" | "into_iter" | "iter_mut" => "iterators are not supported by the C backend yet; \
             loop with an index: `let mut i = 0; while i < v.len() { let x = v[i]; ... i += 1; }`"
            .to_string(),
        "parse" => "`parse` works on a string with its target type written: \
             `s.parse::<i32>()` gives a `Result<i32, str>`"
            .to_string(),
        "unwrap" | "expect" => format!(
            "`{name}` works on an `Option` or a `Result` whose type is known here; \
             annotate the value (`let r: Result<i32, str> = ...;`) or use `match`"
        ),
        "split" | "lines" | "split_whitespace" | "chars" | "trim" | "bytes" => format!(
            "`{name}` is not supported by the C backend yet; walk the string by index with \
             `s.len()` and `s[i]`"
        ),
        "sort" | "sort_by" | "reverse" | "dedup" => format!(
            "`{name}` is not supported on vectors by the C backend yet; write the loop \
             (for example an insertion sort over indices)"
        ),
        _ => format!(
            "no function or method named `{name}` exists for the C backend; check the \
             spelling, define it as a `fn`, or declare it in an `extern \"C\"` block"
        ),
    }
}

/// Whether `name` is bound as a variable in `source` (`let name`, `let mut name`,
/// or a `name:` parameter), which means a call to it goes through a function value.
pub fn is_bound_variable(source: &str, name: &str) -> bool {
    let word = |rest: &str| {
        rest.strip_prefix(name)
            .map(|after| !after.starts_with(|c: char| c.is_alphanumeric() || c == '_'))
            .unwrap_or(false)
    };
    source.match_indices("let ").any(|(i, _)| {
        let rest = source[i + 4..].trim_start();
        let rest = rest
            .strip_prefix("mut ")
            .map(str::trim_start)
            .unwrap_or(rest);
        word(rest)
    }) || source.match_indices(name).any(|(i, _)| {
        let before_ok = i == 0 || {
            let b = source.as_bytes()[i - 1];
            b == b'(' || b == b',' || b == b' '
        };
        before_ok
            && word(&source[i..])
            && source[i + name.len()..].trim_start().starts_with(':')
            && !source[i + name.len()..].trim_start().starts_with("::")
    })
}

/// Hint for a call through a variable that holds a function.
pub fn function_value_hint(name: &str) -> String {
    format!(
        "`{name}` holds a function value; calling a function stored in a variable, field or \
         collection is not supported by the C backend yet. Call the function by its own \
         name, or branch with `if`/`match` and call each function directly"
    )
}

/// Byte range of the first call to `name` in `source`, as a method (`.name(`) or a
/// plain call (`name(`), skipping `fn name(` definitions.
pub fn locate_call(source: &str, name: &str) -> Option<(u32, u32)> {
    let bytes = source.as_bytes();
    let mut from = 0;
    while let Some(rel) = source[from..].find(name) {
        let start = from + rel;
        let end = start + name.len();
        from = end;
        let before_ok = start == 0 || {
            let b = bytes[start - 1];
            !(b.is_ascii_alphanumeric() || b == b'_')
        };
        let after = source[end..].trim_start();
        let after_ok = after.starts_with('(') || after.starts_with("::<");
        let is_def = source[..start].trim_end().ends_with("fn");
        let in_comment = source[..start]
            .rfind('\n')
            .map_or(&source[..start], |nl| &source[nl..start])
            .contains("//");
        if before_ok && after_ok && !is_def && !in_comment {
            return Some((start as u32, end as u32));
        }
    }
    None
}

/// The first MIR temporary (`_N`) that a generated C function body reads
/// without declaring it, if any. `body` is the function's text from its
/// signature to its closing brace; temporaries named in the signature are
/// parameters. Otherwise a temporary counts as
/// declared when a line ends in `<type> _N;`, `<type> _N[...];`,
/// `<ret> (*_N)(...);` or starts with `<type> _N = ...;`.
pub fn undeclared_temporary(body: &str) -> Option<String> {
    let mut declared = BTreeSet::new();
    let (signature, body) = body.split_once('{').unwrap_or(("", body));
    for word in signature.split(|c: char| !(c == '_' || c.is_ascii_alphanumeric())) {
        if is_temp(word) {
            declared.insert(word.to_string());
        }
    }
    for line in body.lines() {
        let t = line.trim();
        if !t.ends_with(';') || t.starts_with("goto") || t.starts_with("return") {
            continue;
        }
        let lhs = match t.split_once('=') {
            Some((lhs, _)) => lhs,
            None => t.trim_end_matches(';'),
        };
        // A declaration has a type before the name: two or more words.
        let words: Vec<&str> = lhs
            .split(|c: char| c.is_whitespace() || c == '*' || c == '(' || c == ')' || c == '[')
            .filter(|w| !w.is_empty())
            .collect();
        if words.len() >= 2 {
            for w in &words[1..] {
                if is_temp(w) {
                    declared.insert((*w).to_string());
                    break;
                }
            }
        }
    }
    let bytes = body.as_bytes();
    let mut i = 0;
    let mut in_str = false;
    while i < bytes.len() {
        let c = bytes[i];
        if in_str {
            if c == b'\\' {
                i += 2;
                continue;
            }
            if c == b'"' {
                in_str = false;
            }
            i += 1;
            continue;
        }
        if c == b'"' {
            in_str = true;
            i += 1;
            continue;
        }
        if c == b'_' || c.is_ascii_alphabetic() {
            let start = i;
            while i < bytes.len() && (bytes[i] == b'_' || bytes[i].is_ascii_alphanumeric()) {
                i += 1;
            }
            let member = start > 0 && (bytes[start - 1] == b'.' || bytes[start - 1] == b'>');
            let word = &body[start..i];
            if !member && is_temp(word) && !declared.contains(word) {
                return Some(word.to_string());
            }
            continue;
        }
        if c.is_ascii_digit() {
            // Skip numeric literals such as `1e_` lookalikes and `0x_`.
            while i < bytes.len() && (bytes[i] == b'_' || bytes[i].is_ascii_alphanumeric()) {
                i += 1;
            }
            continue;
        }
        i += 1;
    }
    None
}

fn is_temp(word: &str) -> bool {
    word.len() > 1 && word.starts_with('_') && word[1..].bytes().all(|b| b.is_ascii_digit())
}

#[cfg(test)]
mod tests {
    #[test]
    fn undeclared_temporary_finds_a_read_of_a_missing_local() {
        let body = "static void f(int64_t _9) {\n    int64_t _1;\n    int64_t _2;\n\n    _1 = _9;\n    _2 = _6;\n    return;\n}\n";
        assert_eq!(super::undeclared_temporary(body).as_deref(), Some("_6"));
    }

    #[test]
    fn undeclared_temporary_accepts_declared_and_ignores_members_and_strings() {
        let body = "static void g(void) {\n    BuildString _3;\n    int8_t* _4;\n    int64_t _5[4];\n    int32_t (*_6)(int32_t);\n    int64_t _7 = n;\n\n    _4 = _3.ptr;\n    _5[0] = _7;\n    h._9 = 1;\n    p->_10 = 2;\n    printf(\"_11 %d\", _7);\n    _6 = f;\n}\n";
        assert_eq!(super::undeclared_temporary(body), None);
    }

    use super::*;

    #[test]
    fn reports_a_call_with_no_declaration() {
        let c = "static int helper(int x) { return x; }\n// End BuildLang Runtime\n\
                 int32_t main(void) { int32_t a = helper(1); _3 = iter(v); return 0; }";
        assert_eq!(undeclared_calls(c), vec!["iter".to_string()]);
    }

    #[test]
    fn accepts_runtime_stdlib_macros_and_function_pointers() {
        let c = "#define BL_CHECK(x) (x)\nstatic void* build_alloc(size_t n);\n\
                 // End BuildLang Runtime\nint32_t f(int32_t (*cb)(int32_t)) { return cb(1); }\n\
                 int32_t main(void) { printf(\"%d\", 1); void* p = build_alloc(4); \
                 if (BL_CHECK(1)) { return f(0); } return (int32_t)sqrt(4.0); }";
        assert!(undeclared_calls(c).is_empty(), "{:?}", undeclared_calls(c));
    }

    #[test]
    fn accepts_names_built_by_token_pasting() {
        let c = "#define DEF(S, T) static T bl_iadd_##S(T a, T b) { return a + b; }
                 DEF(i32, int32_t)
// End BuildLang Runtime
                 int32_t main(void) { return bl_iadd_i32(1, 2); }";
        assert!(undeclared_calls(c).is_empty(), "{:?}", undeclared_calls(c));
    }

    #[test]
    fn ignores_calls_inside_strings_and_comments() {
        let c = "// End BuildLang Runtime\nint32_t main(void) { /* iter(x) */ \
                 printf(\"parse(x)\"); return 0; }";
        assert!(undeclared_calls(c).is_empty());
    }

    #[test]
    fn a_plain_variable_does_not_hide_an_undeclared_call() {
        // `size_t len;` in a runtime struct must not make a call to `len` look
        // declared: only `(*name)` function-pointer declarators count.
        let c = "typedef struct { size_t len; } S;\n// End BuildLang Runtime\n\
                 int32_t main(void) { return len(x); }";
        assert_eq!(undeclared_calls(c), vec!["len".to_string()]);
    }

    #[test]
    fn detects_function_values_bound_with_let_or_as_parameters() {
        assert!(is_bound_variable("let loader = read_file;", "loader"));
        assert!(is_bound_variable("let mut f = g;", "f"));
        assert!(is_bound_variable("fn apply(cb: fn(i32) -> i32) {}", "cb"));
        assert!(!is_bound_variable("let loaders = x;", "loader"));
        assert!(!is_bound_variable("fn iter() {}", "iter"));
    }

    #[test]
    fn locates_method_calls_and_skips_definitions() {
        let src = "fn iter() {}\nfn main() { // v.iter()\n  for x in v.iter() {} }";
        let (start, _) = locate_call(src, "iter").unwrap();
        assert_eq!(&src[start as usize..start as usize + 4], "iter");
        assert!(src[..start as usize].ends_with("v."));
    }
}