alef 0.62.8

Opinionated polyglot binding generator for Rust libraries
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
use crate::snippets::error::Result;
use crate::snippets::scratch::ScratchDir;
use crate::snippets::session::ValidationSession;
use crate::snippets::types::{Language, Snippet, SnippetStatus, ValidationLevel};
use crate::snippets::validators::{BatchValidation, SnippetValidator, run_command};
use std::io::Write;
use tempfile::NamedTempFile;

pub struct CValidator;

const NO_C_COMPILER: &str = "no C compiler on PATH";
const BATCH_FILE_PREFIX: &str = "snippet_batch_";
const BATCH_FAILED_WITHOUT_DIAGNOSTIC: &str = "the C compiler failed without a snippet-specific diagnostic";

/// The substring that separates a diagnostic the compiler rejects the translation unit over from
/// one it merely reports. Every snippet is compiled with the same flags the per-snippet path uses,
/// so a warning that leaves that path passing must leave the batch passing too — attributing a
/// line to a snippet is not the same as failing it. `fatal error:` ends with this marker as well. ~keep
const ERROR_DIAGNOSTIC_MARKER: &str = "error:";

fn compiler() -> Option<String> {
    for candidate in ["cc", "clang", "gcc"] {
        if which::which(candidate).is_ok() {
            return Some(candidate.to_string());
        }
    }
    None
}

impl CValidator {
    /// One compiler start for the whole batch instead of one per snippet. `-fsyntax-only` accepts
    /// many sources and type-checks each as its own translation unit, so the `main` every snippet
    /// declares never collides — nothing is linked, which is exactly why the levels that do link
    /// decline in `validate_batch_in_session`. ~keep
    fn validate_batch_with_context(
        snippets: &[&Snippet],
        level: ValidationLevel,
        timeout_secs: u64,
        session: Option<&ValidationSession>,
    ) -> Result<BatchValidation> {
        let Some(cc) = compiler() else {
            return Ok(vec![
                (SnippetStatus::Unavailable, Some(NO_C_COMPILER.into()));
                snippets.len()
            ]);
        };
        let dir = match session {
            Some(session) => session.scratch_dir()?,
            None => ScratchDir::isolated()?,
        };
        let mut file_names = Vec::with_capacity(snippets.len());
        let mut paths = Vec::with_capacity(snippets.len());
        for (index, snippet) in snippets.iter().enumerate() {
            let file_name = format!("{BATCH_FILE_PREFIX}{index}.c");
            let path = dir.path().join(&file_name);
            std::fs::write(&path, snippet.code.as_bytes())?;
            file_names.push(file_name);
            paths.push(path);
        }
        let mut command = std::process::Command::new(cc);
        command.arg("-fsyntax-only");
        if level == ValidationLevel::TypeCheck {
            command.args(["-Wall", "-Werror"]);
        }
        if let Some(session) = session {
            apply_session_includes(&mut command, session);
        }
        command.args(&paths);
        if let Some(session) = session {
            session.apply(&mut command);
        }
        let (success, output) = run_command(&mut command, timeout_secs)?;
        Ok(Self::batch_results(&file_names, success, &output))
    }

    /// Attributes compiler output back to the snippet that owns it. Every diagnostic opens with
    /// its own source path (`snippet_batch_2.c:4:9: error: …`), and the caret/source lines that
    /// follow carry no path at all, so a pathless line stays with the file last named. ~keep
    fn batch_results(file_names: &[String], success: bool, output: &str) -> BatchValidation {
        let mut diagnostics = vec![Vec::new(); file_names.len()];
        let mut rejected = vec![false; file_names.len()];
        let mut unmatched = Vec::new();
        let mut current = None;
        for line in output.lines() {
            if line.trim().is_empty() {
                continue;
            }
            match Self::file_owner(file_names, line).or(current) {
                Some(index) => {
                    current = Some(index);
                    diagnostics[index].push(line.to_string());
                    rejected[index] |= line.contains(ERROR_DIAGNOSTIC_MARKER);
                }
                None => unmatched.push(line.to_string()),
            }
        }
        let attributed = rejected.iter().any(|value| *value);
        let fallback = (!success && !attributed).then(|| {
            if unmatched.is_empty() {
                BATCH_FAILED_WITHOUT_DIAGNOSTIC.to_string()
            } else {
                unmatched.join("\n")
            }
        });
        rejected
            .into_iter()
            .zip(diagnostics)
            .map(|(rejected, messages)| match (rejected, &fallback) {
                (true, _) => (SnippetStatus::Fail, Some(messages.join("\n"))),
                (false, Some(message)) => (SnippetStatus::Fail, Some(message.clone())),
                (false, None) => (SnippetStatus::Pass, None),
            })
            .collect()
    }

    fn file_owner(file_names: &[String], line: &str) -> Option<usize> {
        file_names
            .iter()
            .position(|file_name| line.contains(file_name.as_str()))
    }
}

impl SnippetValidator for CValidator {
    fn language(&self) -> Language {
        Language::C
    }

    fn is_available(&self) -> bool {
        compiler().is_some()
    }

    fn validate(
        &self,
        snippet: &Snippet,
        level: ValidationLevel,
        timeout_secs: u64,
    ) -> Result<(SnippetStatus, Option<String>)> {
        let Some(cc) = compiler() else {
            return Ok((SnippetStatus::Unavailable, Some(NO_C_COMPILER.into())));
        };

        let mut source = NamedTempFile::with_suffix(".c")?;
        source.write_all(snippet.code.as_bytes())?;
        source.flush()?;
        let source_path = source.path().to_string_lossy().to_string();

        let mut command = std::process::Command::new(&cc);
        match level {
            ValidationLevel::Syntax => {
                command.args(["-fsyntax-only", &source_path]);
            }
            ValidationLevel::TypeCheck => {
                command.args(["-fsyntax-only", "-Wall", "-Werror", &source_path]);
            }
            ValidationLevel::Compile | ValidationLevel::Run => {
                // The compiled binary lives inside a guarded scratch directory rather than being
                // removed by hand at each `return`: the two `run_command` calls below both exit
                // through `?`, and neither of the old `remove_file` calls was reachable from
                // there, so a spawn failure or a timeout leaked an executable every time. ~keep
                let scratch = ScratchDir::isolated()?;
                let out_path = scratch.path().join("snippet-output").to_string_lossy().to_string();
                command.args(["-o", &out_path, &source_path]);
                let (success, output) = run_command(&mut command, timeout_secs)?;
                if !success {
                    return Ok((SnippetStatus::Fail, Some(output)));
                }
                if matches!(level, ValidationLevel::Run) {
                    let mut run = std::process::Command::new(&out_path);
                    let (ran_ok, run_output) = run_command(&mut run, timeout_secs)?;
                    return Ok(if ran_ok {
                        (SnippetStatus::Pass, None)
                    } else {
                        (SnippetStatus::Fail, Some(run_output))
                    });
                }
                return Ok((SnippetStatus::Pass, None));
            }
        }

        let (success, output) = run_command(&mut command, timeout_secs)?;
        if success {
            Ok((SnippetStatus::Pass, None))
        } else {
            Ok((SnippetStatus::Fail, Some(output)))
        }
    }

    fn max_level(&self) -> ValidationLevel {
        ValidationLevel::Run
    }

    fn validate_in_session(
        &self,
        snippet: &Snippet,
        level: ValidationLevel,
        timeout_secs: u64,
        session: Option<&ValidationSession>,
    ) -> Result<(SnippetStatus, Option<String>)> {
        let Some(session) = session else {
            return self.validate(snippet, level, timeout_secs);
        };
        let Some(cc) = compiler() else {
            return Ok((SnippetStatus::Unavailable, Some(NO_C_COMPILER.into())));
        };
        let scratch_dir = session.scratch_dir()?;
        let mut source = tempfile::Builder::new().suffix(".c").tempfile_in(scratch_dir.path())?;
        source.write_all(snippet.code.as_bytes())?;
        source.flush()?;
        let output = scratch_dir.path().join(".alef-snippet-output");
        let mut command = std::process::Command::new(cc);
        apply_session_includes(&mut command, session);
        if level == ValidationLevel::Syntax {
            command.arg("-fsyntax-only");
        }
        if level == ValidationLevel::TypeCheck {
            command.args(["-fsyntax-only", "-Wall", "-Werror"]);
        }
        if level == ValidationLevel::Compile {
            command.arg("-c").arg("-o").arg(&output);
        } else if level == ValidationLevel::Run {
            command.arg("-o").arg(&output);
        }
        command.arg(source.path());
        session.apply(&mut command);
        let (success, message) = run_command(&mut command, timeout_secs)?;
        if !success {
            return Ok((SnippetStatus::Fail, Some(message)));
        }
        if level != ValidationLevel::Run {
            let _ = std::fs::remove_file(&output);
            return Ok((SnippetStatus::Pass, None));
        }
        let mut run = std::process::Command::new(&output);
        session.apply(&mut run);
        let (success, message) = run_command(&mut run, timeout_secs)?;
        let _ = std::fs::remove_file(&output);
        Ok(if success {
            (SnippetStatus::Pass, None)
        } else {
            (SnippetStatus::Fail, Some(message))
        })
    }

    /// Batching covers only the levels that reach for `-fsyntax-only`. `Compile` and `Run` each
    /// produce their own artifact from their own `main`, so one invocation cannot serve N of them;
    /// they fall back to one process per snippet. ~keep
    fn validate_batch_in_session(
        &self,
        snippets: &[&Snippet],
        level: ValidationLevel,
        timeout_secs: u64,
        session: Option<&ValidationSession>,
    ) -> Option<Result<BatchValidation>> {
        matches!(level, ValidationLevel::Syntax | ValidationLevel::TypeCheck)
            .then(|| Self::validate_batch_with_context(snippets, level, timeout_secs, session))
    }

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

    fn is_dependency_error(&self, output: &str) -> bool {
        output.contains("file not found")
            || output.contains("No such file or directory")
            || output.contains("undeclared identifier")
            || output.contains("implicit declaration")
            || output.contains("unknown type name")
    }
}

fn apply_include_paths(command: &mut std::process::Command, include_paths: &[std::path::PathBuf]) {
    for include_path in include_paths {
        command.arg("-I").arg(include_path);
    }
}

fn apply_session_includes(command: &mut std::process::Command, session: &ValidationSession) {
    let include_directory = session
        .manifest
        .as_deref()
        .and_then(std::path::Path::parent)
        .unwrap_or(&session.working_directory);
    command.arg("-I").arg(include_directory);
    apply_include_paths(command, &session.include_paths);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::snippets::types::{Snippet, SnippetMetadata, SourceOrigin};
    use std::path::PathBuf;

    fn snippet(code: &str) -> Snippet {
        Snippet {
            id: None,
            path: PathBuf::from("test.c"),
            language: Language::C,
            title: None,
            code: code.to_string(),
            start_line: 1,
            block_index: 0,
            annotation: None,
            metadata: SnippetMetadata::default(),
            source_origin: SourceOrigin {
                path: PathBuf::from("test.c"),
                line: 1,
                block_index: 0,
            },
        }
    }

    const TOOLCHAIN_TEST_TIMEOUT_SECS: u64 = 120;

    #[test]
    fn batch_declines_the_levels_that_link_an_executable() {
        let only = snippet("int main(void) { return 0; }\n");

        for level in [ValidationLevel::Compile, ValidationLevel::Run] {
            let declined = CValidator.validate_batch_in_session(&[&only], level, 10, None);
            assert!(
                declined.is_none(),
                "{level:?} must fall back to one process per snippet"
            );
        }
    }

    #[test]
    fn batch_returns_one_result_per_snippet_in_input_order() {
        if compiler().is_none() {
            return;
        }
        let first = snippet("int first(void) { return 1; }\n");
        let second = snippet("int second(void) { return 2; }\n");
        let third = snippet("int third(void) { return 3; }\n");

        let results = CValidator::validate_batch_with_context(
            &[&first, &second, &third],
            ValidationLevel::Syntax,
            TOOLCHAIN_TEST_TIMEOUT_SECS,
            None,
        )
        .expect("batch validation runs");

        assert_eq!(
            results,
            vec![
                (SnippetStatus::Pass, None),
                (SnippetStatus::Pass, None),
                (SnippetStatus::Pass, None)
            ]
        );
    }

    #[test]
    fn batch_fails_only_the_broken_snippet_and_passes_its_neighbours() {
        if compiler().is_none() {
            return;
        }
        let first = snippet("int first(void) { return 1; }\n");
        let broken = snippet("int second(void) { @@@ }\n");
        let third = snippet("int third(void) { return 3; }\n");

        let results = CValidator::validate_batch_with_context(
            &[&first, &broken, &third],
            ValidationLevel::Syntax,
            TOOLCHAIN_TEST_TIMEOUT_SECS,
            None,
        )
        .expect("batch validation runs");

        assert_eq!(results.len(), 3);
        assert_eq!(results[0], (SnippetStatus::Pass, None), "{:?}", results[0]);
        assert_eq!(results[1].0, SnippetStatus::Fail);
        assert!(
            results[1]
                .1
                .as_deref()
                .is_some_and(|message| message.contains("error:")),
            "{:?}",
            results[1].1
        );
        assert_eq!(results[2], (SnippetStatus::Pass, None), "{:?}", results[2]);
    }

    /// The isolation the `-fsyntax-only` level buys: every snippet declares its own `main`, which
    /// would be a duplicate-symbol link failure the moment the batch linked them together — and a
    /// failure the per-snippet path never produces. ~keep
    #[test]
    fn batch_passes_two_snippets_that_each_declare_main() {
        if compiler().is_none() {
            return;
        }
        let first = snippet("int main(void) { return 0; }\n");
        let second = snippet("int main(void) { return 1; }\n");

        let results = CValidator::validate_batch_with_context(
            &[&first, &second],
            ValidationLevel::Syntax,
            TOOLCHAIN_TEST_TIMEOUT_SECS,
            None,
        )
        .expect("batch validation runs");

        assert_eq!(results, vec![(SnippetStatus::Pass, None), (SnippetStatus::Pass, None)]);
    }

    /// Attributing a compiler line to a snippet is not the same as failing it: `-fsyntax-only`
    /// without `-Werror` reports warnings and still exits 0, exactly as the per-snippet path does,
    /// so a warned-about snippet must keep passing. ~keep
    #[test]
    fn batch_does_not_fail_a_snippet_the_compiler_only_warns_about() {
        if compiler().is_none() {
            return;
        }
        let first = snippet("int first(void) { return 1; }\n");
        let warned = snippet("#warning batch fixture warning\nint second(void) { return 2; }\n");

        let results = CValidator::validate_batch_with_context(
            &[&first, &warned],
            ValidationLevel::Syntax,
            TOOLCHAIN_TEST_TIMEOUT_SECS,
            None,
        )
        .expect("batch validation runs");

        assert_eq!(results, vec![(SnippetStatus::Pass, None), (SnippetStatus::Pass, None)]);
    }

    /// A compiler that fails without naming any snippet must not let the batch pass: every snippet
    /// carries the real output instead. ~keep
    #[test]
    fn batch_results_fail_every_snippet_when_no_diagnostic_names_one() {
        let file_names = vec!["snippet_batch_0.c".to_string(), "snippet_batch_1.c".to_string()];

        let results = CValidator::batch_results(&file_names, false, "cc: error: unrecognized command-line option\n");

        assert_eq!(
            results,
            vec![
                (
                    SnippetStatus::Fail,
                    Some("cc: error: unrecognized command-line option".to_string())
                ),
                (
                    SnippetStatus::Fail,
                    Some("cc: error: unrecognized command-line option".to_string())
                ),
            ]
        );
    }

    #[test]
    fn syntax_ok() {
        let v = CValidator;
        if !v.is_available() {
            return;
        }
        let s = snippet("int main(void) { return 0; }\n");
        let (status, _) = v.validate(&s, ValidationLevel::Syntax, 30).unwrap();
        assert_eq!(status, SnippetStatus::Pass);
    }

    #[test]
    fn syntax_fail() {
        let v = CValidator;
        if !v.is_available() {
            return;
        }
        let s = snippet("int main(void) { @@@ }\n");
        let (status, _) = v.validate(&s, ValidationLevel::Syntax, 30).unwrap();
        assert_eq!(status, SnippetStatus::Fail);
    }

    fn scratch_shape_session(project: &std::path::Path, fingerprint: &str) -> ValidationSession {
        ValidationSession {
            language: Language::C,
            working_directory: project.to_path_buf(),
            manifest: None,
            fingerprint: fingerprint.into(),
            env: std::collections::BTreeMap::new(),
            include_paths: Vec::new(),
            rust_features: Vec::new(),
            rust_dependencies: std::collections::BTreeMap::new(),
        }
    }

    fn scratch_top_level_entries(project: &std::path::Path) -> Vec<std::ffi::OsString> {
        std::fs::read_dir(project)
            .expect("read project directory")
            .filter_map(|entry| entry.ok())
            .map(|entry| entry.file_name())
            .filter(|name| name != ".alef")
            .collect()
    }

    /// Regression: `validate_in_session` used to write its source file via a bare `tempfile_in`
    /// directly against `session.working_directory`, and its compiled output to a literal
    /// `session.working_directory.join(".alef-snippet-output")` — both loose in a tracked
    /// package source directory. Both must nest under the session's own `.alef/snippets/tmp`
    /// cache root instead. ~keep
    #[test]
    fn session_scratch_resolves_under_the_cache_root_not_the_working_directory() {
        if compiler().is_none() {
            return;
        }
        let project = tempfile::tempdir().expect("project directory");
        let session = scratch_shape_session(project.path(), "scratch-shape-fixture");
        let s = snippet("int main(void) { return 0; }\n");

        let (status, output) = CValidator
            .validate_in_session(&s, ValidationLevel::Compile, 30, Some(&session))
            .expect("validation runs");
        assert_eq!(status, SnippetStatus::Pass, "{output:?}");

        let leftovers = scratch_top_level_entries(project.path());
        assert!(
            leftovers.is_empty(),
            "no scratch entry may be left directly in the project directory: {leftovers:?}"
        );
    }

    /// Pins cleanup on the failure path specifically: a snippet that fails to compile must not
    /// leave its scratch source or output behind under the working directory any more than a
    /// passing one does.
    #[test]
    fn session_scratch_is_removed_after_a_run_that_fails() {
        if compiler().is_none() {
            return;
        }
        let project = tempfile::tempdir().expect("project directory");
        let session = scratch_shape_session(project.path(), "scratch-cleanup-fixture");
        let s = snippet("int main(void) { @@@ }\n");

        let (status, _) = CValidator
            .validate_in_session(&s, ValidationLevel::Compile, 30, Some(&session))
            .expect("validation runs");
        assert_eq!(status, SnippetStatus::Fail);

        let leftovers = scratch_top_level_entries(project.path());
        assert!(
            leftovers.is_empty(),
            "no scratch entry may be left directly in the project directory after a failing run: {leftovers:?}"
        );
        let scratch_root = project.path().join(".alef/snippets/tmp");
        let remaining = std::fs::read_dir(&scratch_root)
            .map(|entries| entries.filter_map(|entry| entry.ok()).count())
            .unwrap_or(0);
        assert_eq!(
            remaining, 0,
            "scratch left behind under the cache root after a failing snippet validation"
        );
    }

    #[test]
    fn session_include_paths_are_passed_to_c_compiler() {
        let mut command = std::process::Command::new("cc");
        apply_include_paths(
            &mut command,
            &[
                std::path::PathBuf::from("include"),
                std::path::PathBuf::from("vendor/include"),
            ],
        );

        assert_eq!(
            command.get_args().collect::<Vec<_>>(),
            ["-I", "include", "-I", "vendor/include"]
        );
    }
}