alef 0.67.2

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
use serde::{Deserialize, Serialize};
use std::fmt;
use std::path::PathBuf;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Language {
    Bash,
    C,
    Csharp,
    Dart,
    Docker,
    Elixir,
    Go,
    Java,
    Json,
    Kotlin,
    Mermaid,
    Php,
    PowerShell,
    Python,
    R,
    Ruby,
    Rust,
    Swift,
    Text,
    Toml,
    TypeScript,
    Xml,
    Yaml,
    Zig,
    Unknown,
}

impl Language {
    #[must_use]
    pub fn from_fence_tag(tag: &str) -> Self {
        match tag.trim().to_lowercase().as_str() {
            "bash" | "sh" | "shell" | "zsh" | "console" => Self::Bash,
            "c" => Self::C,
            "csharp" | "c#" | "cs" => Self::Csharp,
            "dart" => Self::Dart,
            "docker" | "dockerfile" => Self::Docker,
            "elixir" | "ex" | "exs" => Self::Elixir,
            "go" | "golang" => Self::Go,
            "java" => Self::Java,
            "json" => Self::Json,
            "kotlin" | "kt" | "kts" => Self::Kotlin,
            "mermaid" => Self::Mermaid,
            "php" => Self::Php,
            "powershell" | "ps" | "ps1" | "pwsh" => Self::PowerShell,
            "python" | "py" | "python3" => Self::Python,
            "r" | "rscript" => Self::R,
            "ruby" | "rb" => Self::Ruby,
            "rust" | "rs" => Self::Rust,
            "swift" => Self::Swift,
            "text" | "txt" | "plain" => Self::Text,
            "toml" => Self::Toml,
            "typescript" | "ts" | "javascript" | "js" => Self::TypeScript,
            "xml" => Self::Xml,
            "yaml" | "yml" => Self::Yaml,
            "zig" => Self::Zig,
            _ => Self::Unknown,
        }
    }

    #[must_use]
    pub fn from_session_target(target: &str) -> Self {
        match Self::normalize_session_target(target).as_str() {
            "node" | "wasm" => Self::TypeScript,
            "kotlin_android" => Self::Kotlin,
            "core" | "rust_core" => Self::Rust,
            "c_ffi" | "ffi" => Self::C,
            other => Self::from_fence_tag(other),
        }
    }

    #[must_use]
    pub fn normalize_session_target(target: &str) -> String {
        target.trim().to_lowercase().replace('-', "_")
    }

    #[must_use]
    pub fn from_extension(ext: &str) -> Self {
        match ext.to_lowercase().as_str() {
            "sh" | "bash" => Self::Bash,
            "c" | "h" => Self::C,
            "cs" => Self::Csharp,
            "dart" => Self::Dart,
            "dockerfile" => Self::Docker,
            "ex" | "exs" => Self::Elixir,
            "go" => Self::Go,
            "java" => Self::Java,
            "json" => Self::Json,
            "kt" | "kts" => Self::Kotlin,
            "php" => Self::Php,
            "py" => Self::Python,
            "r" => Self::R,
            "rb" => Self::Ruby,
            "rs" => Self::Rust,
            "swift" => Self::Swift,
            "toml" => Self::Toml,
            "ts" | "js" | "mts" | "mjs" => Self::TypeScript,
            "zig" => Self::Zig,
            _ => Self::Unknown,
        }
    }

    #[must_use]
    pub fn from_dir_name(name: &str) -> Self {
        match name.to_lowercase().as_str() {
            "bash" | "shell" => Self::Bash,
            "c" => Self::C,
            "csharp" | "c-sharp" | "dotnet" => Self::Csharp,
            "dart" => Self::Dart,
            "docker" => Self::Docker,
            "elixir" => Self::Elixir,
            "go" | "golang" => Self::Go,
            "java" => Self::Java,
            "json" => Self::Json,
            "kotlin" | "kotlin_android" | "kotlin-android" => Self::Kotlin,
            "php" => Self::Php,
            "python" => Self::Python,
            "r" => Self::R,
            "ruby" => Self::Ruby,
            "rust" => Self::Rust,
            "swift" => Self::Swift,
            "toml" => Self::Toml,
            "typescript" | "wasm" | "node" => Self::TypeScript,
            "zig" => Self::Zig,
            _ => Self::Unknown,
        }
    }
}

impl fmt::Display for Language {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Bash => write!(f, "bash"),
            Self::C => write!(f, "c"),
            Self::Csharp => write!(f, "csharp"),
            Self::Dart => write!(f, "dart"),
            Self::Docker => write!(f, "docker"),
            Self::Elixir => write!(f, "elixir"),
            Self::Go => write!(f, "go"),
            Self::Java => write!(f, "java"),
            Self::Json => write!(f, "json"),
            Self::Kotlin => write!(f, "kotlin"),
            Self::Mermaid => write!(f, "mermaid"),
            Self::Php => write!(f, "php"),
            Self::PowerShell => write!(f, "powershell"),
            Self::Python => write!(f, "python"),
            Self::R => write!(f, "r"),
            Self::Ruby => write!(f, "ruby"),
            Self::Rust => write!(f, "rust"),
            Self::Swift => write!(f, "swift"),
            Self::Text => write!(f, "text"),
            Self::Toml => write!(f, "toml"),
            Self::TypeScript => write!(f, "typescript"),
            Self::Xml => write!(f, "xml"),
            Self::Yaml => write!(f, "yaml"),
            Self::Zig => write!(f, "zig"),
            Self::Unknown => write!(f, "unknown"),
        }
    }
}

impl std::str::FromStr for Language {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let language = Self::from_fence_tag(s);
        if language == Self::Unknown {
            Err(format!("unknown language: {s}"))
        } else {
            Ok(language)
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ValidationLevel {
    Syntax,
    Compile,
    /// Static type-checking without executing the code (e.g. `mypy` for Python, `tsc` for
    /// TypeScript). Deeper than `Compile` for dynamically-typed languages whose compile step is
    /// only a bytecode/syntax pass; equivalent to `Compile` for languages whose compiler already
    /// type-checks. Ordered between `Compile` and `Run` so it is the strongest static guarantee
    /// short of execution. ~keep
    TypeCheck,
    Run,
}

impl fmt::Display for ValidationLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Syntax => write!(f, "syntax"),
            Self::Compile => write!(f, "compile"),
            Self::TypeCheck => write!(f, "typecheck"),
            Self::Run => write!(f, "run"),
        }
    }
}

impl std::str::FromStr for ValidationLevel {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "syntax" => Ok(Self::Syntax),
            "compile" => Ok(Self::Compile),
            "typecheck" | "type-check" => Ok(Self::TypeCheck),
            "run" => Ok(Self::Run),
            _ => Err(format!("unknown validation level: {s}")),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SnippetAnnotationKind {
    Skip,
    CompileOnly,
    SyntaxOnly,
    TypeCheckOnly,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SnippetAnnotation {
    pub kind: SnippetAnnotationKind,
    pub reason: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct SnippetMetadata {
    pub id: Option<String>,
    pub language: Option<Language>,
    pub target: Option<String>,
    pub title: Option<String>,
    pub level: Option<ValidationLevel>,
    pub skip: bool,
    pub reason: Option<String>,
    pub tags: Vec<String>,
    pub requires: Vec<String>,
    pub side_effect: Option<SideEffectClass>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SideEffectClass {
    #[serde(alias = "none", alias = "local")]
    Safe,
    Network,
    Process,
    Install,
    Server,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SnippetStatus {
    Pass,
    Downgraded,
    Fail,
    Skip,
    Error,
    Unavailable,
}

impl fmt::Display for SnippetStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Pass => write!(f, "pass"),
            Self::Downgraded => write!(f, "downgraded"),
            Self::Fail => write!(f, "fail"),
            Self::Skip => write!(f, "skip"),
            Self::Error => write!(f, "error"),
            Self::Unavailable => write!(f, "unavailable"),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Snippet {
    pub id: Option<String>,
    pub path: PathBuf,
    pub language: Language,
    pub title: Option<String>,
    pub code: String,
    pub start_line: usize,
    pub block_index: usize,
    pub annotation: Option<SnippetAnnotation>,
    pub metadata: SnippetMetadata,
    pub source_origin: SourceOrigin,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SourceOrigin {
    pub path: PathBuf,
    pub line: usize,
    pub block_index: usize,
}

/// Why a result's effective level fell below the requested level, or why a `Pass` needed a
/// caveat at all. Distinct from `SnippetStatus`: a `capability_capped` `Pass` and a `Downgraded`
/// result can share a reason (`ValidatorCapability`), and two `Downgraded` results can differ
/// (`Annotation` vs `Environment`) — attribution needs the reason, not just the status, to tell a
/// consumer what to actually do about it. ~keep
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DowngradeReason {
    /// A front-matter `level:` contract was requested and fully satisfied — reported for
    /// attribution even though the status is `Pass`, not a violation. ~keep
    Declared,
    /// A `<!-- snippet:*-only -->` suppression annotation lowered the ceiling below what was
    /// requested; the author's choice, so it still fails strict. ~keep
    Annotation,
    /// The validator can never reach the requested level for this language (`max_level`, or a
    /// structural `achievable_level` gap) — unsatisfiable in any environment.
    ValidatorCapability,
    /// This run's environment could not back the requested level, but a different environment
    /// could (e.g. a real type-checker binary happens to be missing).
    Environment,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationResult {
    pub snippet: Snippet,
    pub status: SnippetStatus,
    pub level: ValidationLevel,
    pub requested_level: ValidationLevel,
    pub effective_level: ValidationLevel,
    pub message: Option<String>,
    pub duration_ms: u64,
    /// True when the snippet passed below the requested level solely because its validator
    /// declares a lower `max_level`. That ceiling is a capability statement, not a quality
    /// signal, so strict mode must not treat it as a failure — otherwise requesting a level
    /// any validator caps below is structurally unsatisfiable. Downgrades from any other
    /// cause leave this false and still fail strict. ~keep
    #[serde(default)]
    pub capability_capped: bool,
    /// Populated whenever the effective level differs from the requested level for a reason
    /// worth naming — `None` for an ordinary, unqualified `Pass`, and equally for `Fail`, `Skip`,
    /// `Error`, or `Unavailable`, none of which have a reason in this taxonomy at all. `None` is
    /// deliberately a real "not applicable" here rather than a degraded default: the only writer
    /// that ever sets this to `Some` is `runner::finalize_result` (via `classify_result`), which
    /// is exhaustive over every path that produces `Downgraded` or a `capability_capped` `Pass`
    /// — see the `debug_assert!` there. ~keep
    #[serde(default)]
    pub downgrade_reason: Option<DowngradeReason>,
    /// True when this `Unavailable` result started as a validator `Fail` at `Compile`,
    /// `TypeCheck`, or `Run` whose message the validator's own `is_dependency_error` recognized
    /// as a missing import/package/symbol rather than a defect in the snippet. That shape is
    /// what a toolchain reports when the environment never built the artifact the snippet links
    /// or imports against — before this field existed, indistinguishable from a genuinely broken
    /// snippet, because both landed in `Fail`. `false` for every other result, including an
    /// ordinary toolchain-missing `Unavailable`, so it names one specific cause rather than
    /// standing in for the whole status. Set only by `runner::finalize_result`. ~keep
    #[serde(default)]
    pub unresolved_dependency: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunSummary {
    pub schema_version: u32,
    pub total: usize,
    pub passed: usize,
    pub downgraded: usize,
    pub failed: usize,
    pub skipped: usize,
    pub errors: usize,
    pub unavailable: usize,
    /// Passing snippets whose level was limited by their validator's declared ceiling.
    /// Reported so a strict run can say what it accepted rather than hiding it. ~keep
    #[serde(default)]
    pub capability_capped: usize,
    /// Passing snippets whose level was limited by their own front-matter `level:` contract
    /// (`DowngradeReason::Declared`) rather than by the validator's capability. Tracked
    /// separately from `capability_capped` for the same reason that one is tracked at all: a
    /// consumer who configured `docs.snippets.validation_level = "run"` and sees every result
    /// pass has no way to learn that some of them never actually ran, only typechecked, because a
    /// snippet's own declared `level:` clamped it first — that includes every fixture snippet
    /// `alef e2e generate` emits, which stamps `level: typecheck` unconditionally. ~keep
    #[serde(default)]
    pub declared_capped: usize,
    /// Subset of `unavailable`: results reclassified from `Fail` to `Unavailable` because their
    /// message was dependency-shaped at a level above `Syntax` — see
    /// `ValidationResult::unresolved_dependency`. Never counted in `failed`, `errors`, or any
    /// other bucket; always `<= unavailable`. Reported separately from a plain toolchain-missing
    /// `Unavailable` because the remediation differs: install a toolchain vs. run `alef build`. ~keep
    #[serde(default)]
    pub unresolved_dependency: usize,
    pub results: Vec<ValidationResult>,
}

impl RunSummary {
    #[must_use]
    pub fn from_results(results: Vec<ValidationResult>) -> Self {
        let mut summary = Self {
            schema_version: 1,
            total: results.len(),
            passed: 0,
            downgraded: 0,
            failed: 0,
            skipped: 0,
            errors: 0,
            unavailable: 0,
            capability_capped: 0,
            declared_capped: 0,
            unresolved_dependency: 0,
            results,
        };

        for result in &summary.results {
            if result.capability_capped {
                summary.capability_capped += 1;
            }
            if result.downgrade_reason == Some(DowngradeReason::Declared) {
                summary.declared_capped += 1;
            }
            if result.unresolved_dependency {
                summary.unresolved_dependency += 1;
            }
            match result.status {
                SnippetStatus::Pass => summary.passed += 1,
                SnippetStatus::Downgraded => summary.downgraded += 1,
                SnippetStatus::Fail => summary.failed += 1,
                SnippetStatus::Skip => summary.skipped += 1,
                SnippetStatus::Error => summary.errors += 1,
                SnippetStatus::Unavailable => summary.unavailable += 1,
            }
        }

        summary
    }

    #[must_use]
    pub const fn has_failures(&self) -> bool {
        self.failed > 0 || self.errors > 0
    }
}

#[cfg(test)]
mod tests {
    use super::{
        Language, RunSummary, SideEffectClass, Snippet, SnippetAnnotationKind, SnippetMetadata, SnippetStatus,
        SourceOrigin, ValidationLevel, ValidationResult,
    };

    fn result(status: SnippetStatus, unresolved_dependency: bool) -> ValidationResult {
        ValidationResult {
            snippet: Snippet {
                id: None,
                path: "example.md".into(),
                language: Language::Go,
                title: None,
                code: "package main".into(),
                start_line: 1,
                block_index: 0,
                annotation: None,
                metadata: SnippetMetadata::default(),
                source_origin: SourceOrigin {
                    path: "example.md".into(),
                    line: 1,
                    block_index: 0,
                },
            },
            status,
            level: ValidationLevel::Compile,
            requested_level: ValidationLevel::Compile,
            effective_level: ValidationLevel::Compile,
            message: None,
            duration_ms: 0,
            capability_capped: false,
            downgrade_reason: None,
            unresolved_dependency,
        }
    }

    /// The reconciliation the fix promises: `unresolved_dependency` is always a subset of
    /// `unavailable`, never overlaps `failed`/`errors`, and every top-level bucket still sums to
    /// `total` — so a reader never has to trust the count, only add it up. ~keep
    #[test]
    fn unresolved_dependency_is_a_reconcilable_subset_of_unavailable() {
        let summary = RunSummary::from_results(vec![
            result(SnippetStatus::Unavailable, true),
            result(SnippetStatus::Unavailable, false),
            result(SnippetStatus::Fail, false),
            result(SnippetStatus::Pass, false),
        ]);

        assert_eq!(summary.total, 4);
        assert_eq!(summary.unavailable, 2);
        assert_eq!(summary.unresolved_dependency, 1);
        assert!(summary.unresolved_dependency <= summary.unavailable);
        assert_eq!(summary.failed, 1);
        assert_eq!(summary.passed, 1);
        assert_eq!(
            summary.total,
            summary.passed
                + summary.downgraded
                + summary.failed
                + summary.skipped
                + summary.errors
                + summary.unavailable
        );
        assert!(summary.has_failures());
    }

    #[test]
    fn validation_level_parses_typecheck_aliases() {
        assert_eq!("typecheck".parse::<ValidationLevel>(), Ok(ValidationLevel::TypeCheck));
        assert_eq!("type-check".parse::<ValidationLevel>(), Ok(ValidationLevel::TypeCheck));
        assert_eq!("TypeCheck".parse::<ValidationLevel>(), Ok(ValidationLevel::TypeCheck));
        assert_eq!(ValidationLevel::TypeCheck.to_string(), "typecheck");
    }

    #[test]
    fn typecheck_orders_between_compile_and_run() {
        assert!(ValidationLevel::Compile < ValidationLevel::TypeCheck);
        assert!(ValidationLevel::TypeCheck < ValidationLevel::Run);
    }

    #[test]
    fn typecheck_only_annotation_kind_is_distinct() {
        assert_ne!(SnippetAnnotationKind::TypeCheckOnly, SnippetAnnotationKind::CompileOnly);
    }

    #[test]
    fn side_effects_round_trip_and_accept_legacy_safe_aliases() {
        for class in [
            SideEffectClass::Safe,
            SideEffectClass::Network,
            SideEffectClass::Process,
            SideEffectClass::Install,
            SideEffectClass::Server,
        ] {
            let encoded = serde_json::to_string(&class).unwrap();
            assert_eq!(serde_json::from_str::<SideEffectClass>(&encoded).unwrap(), class);
        }
        assert_eq!(
            serde_json::from_str::<SideEffectClass>(r#""none""#).unwrap(),
            SideEffectClass::Safe
        );
        assert_eq!(
            serde_json::from_str::<SideEffectClass>(r#""local""#).unwrap(),
            SideEffectClass::Safe
        );
        assert!(serde_json::from_str::<SideEffectClass>(r#""external_mutation""#).is_err());
    }
}