macroonz-compiler 0.2.0

Deterministic Rust code generation for procedural macros: plan, render, close, explain, and bind one sealed expansion from declared input.
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
//! Codec claims observed from outside: the public bill, canonical preimages, and generated Rust compiled and executed through the pinned toolchain.

use crate::support::observe_rustc;
use macroonz_compiler::codec::{
    AssemblyPosture, Cardinality, CodecAssembly, CodecContent, CodecDirection, CodecIssue,
    CodecMember, CodecMemberShape, CodecPlacement, CodecShape, CodecTypePath, MEMBER_CONTRACT,
    MemberContract, ModuleSpelling, PathRooting, codec_surface,
};
use macroonz_compiler::{Bounded, CanonicalContent, encode_bytes};

fn in_scope(spelling: &str) -> Result<CodecTypePath, String> {
    CodecTypePath::spelled(PathRooting::InScope, vec![spelling.to_owned()])
        .map_err(|refusal| refusal.to_string())
}

fn declared_member(
    spelling: &str,
    held_as: &str,
    shape: CodecMemberShape,
    cardinality: Cardinality,
) -> Result<CodecMember, String> {
    CodecMember::declared(spelling, in_scope(held_as)?, shape, cardinality)
        .map_err(|refusal| refusal.to_string())
}

fn codec_content(direction: CodecDirection) -> Result<CodecContent, String> {
    let assembly = CodecAssembly::stated(
        "assembled",
        AssemblyPosture::Checked {
            refusal: in_scope("AssemblyRefusal")?,
        },
    )
    .map_err(|refusal| refusal.to_string())?;
    let members = vec![
        declared_member(
            "count",
            "u16",
            CodecMemberShape::Count,
            Cardinality::Required,
        )?,
        declared_member(
            "payload",
            "EvenBytes",
            CodecMemberShape::Bytes,
            Cardinality::Required,
        )?,
        declared_member(
            "label",
            "String",
            CodecMemberShape::Text,
            Cardinality::Optional,
        )?,
        declared_member(
            "modes",
            "Choice",
            CodecMemberShape::ClosedChoice,
            Cardinality::Repeated,
        )?,
        declared_member(
            "child",
            "Nested",
            CodecMemberShape::Nested,
            Cardinality::Required,
        )?,
    ];
    let shape = CodecShape::declared(in_scope("Demo")?, "DemoRefusal", assembly, members)
        .map_err(|refusal| refusal.to_string())?;
    Ok(CodecContent {
        shape,
        direction,
        placement: CodecPlacement::AtDeclarationSite,
        schema: None,
        byte_role: None,
        assumptions: Bounded::empty(),
    })
}

fn independent_path(rooting: &str, segments: &[&str], into: &mut Vec<u8>) {
    encode_bytes(rooting.as_bytes(), into);
    let count = u64::try_from(segments.len()).unwrap_or(u64::MAX);
    into.extend_from_slice(&count.to_be_bytes());
    for segment in segments {
        encode_bytes(segment.as_bytes(), into);
    }
}

fn independent_member(
    spelling: &str,
    held_as: &str,
    shape: &str,
    cardinality: &str,
    into: &mut Vec<u8>,
) {
    let mut member = Vec::new();
    encode_bytes(spelling.as_bytes(), &mut member);
    independent_path("in-scope", &[held_as], &mut member);
    encode_bytes(shape.as_bytes(), &mut member);
    encode_bytes(cardinality.as_bytes(), &mut member);
    encode_bytes(&member, into);
}

fn independent_content_bytes() -> Vec<u8> {
    let mut bytes = Vec::new();
    independent_path("in-scope", &["Demo"], &mut bytes);
    encode_bytes(b"DemoRefusal", &mut bytes);
    encode_bytes(b"assembled", &mut bytes);
    bytes.push(1);
    independent_path("in-scope", &["AssemblyRefusal"], &mut bytes);
    bytes.extend_from_slice(&5_u64.to_be_bytes());
    independent_member("count", "u16", "count", "required", &mut bytes);
    independent_member("payload", "EvenBytes", "bytes", "required", &mut bytes);
    independent_member("label", "String", "text", "optional", &mut bytes);
    independent_member("modes", "Choice", "closed-choice", "repeated", &mut bytes);
    independent_member("child", "Nested", "nested", "required", &mut bytes);
    encode_bytes(b"round-trip", &mut bytes);
    bytes.push(0);
    bytes.push(0);
    bytes.push(0);
    bytes.extend_from_slice(&0_u64.to_be_bytes());
    bytes
}

/// Claim: the public five-row bill and the operations emitted for all five shapes remain one observable contract.
///
/// Population: every `CodecMemberShape` row in one round-trip surface.
/// Hostile control: the expected bill is independently restated at the public boundary, so a changed road or row order disagrees before generated compilation can mask it.
/// Evidence ceiling: this establishes the public bill and emitted callable spellings, while the compiled specimen below establishes that the calls type-check and execute for one representative owner.
#[test]
fn every_member_contract_row_reaches_the_generated_surface() -> Result<(), String> {
    let expected = [
        MemberContract {
            shape: CodecMemberShape::Count,
            encode_road: "u64::from",
            decode_road: "<T as ::core::convert::TryFrom<u64>>::try_from",
        },
        MemberContract {
            shape: CodecMemberShape::Bytes,
            encode_road: "<T as ::core::convert::AsRef<[u8]>>::as_ref",
            decode_road: "<T as ::core::convert::TryFrom<::std::vec::Vec<u8>>>::try_from",
        },
        MemberContract {
            shape: CodecMemberShape::Text,
            encode_road: "<T as ::core::convert::AsRef<str>>::as_ref",
            decode_road: "<T as ::core::convert::TryFrom<::std::string::String>>::try_from",
        },
        MemberContract {
            shape: CodecMemberShape::ClosedChoice,
            encode_road: "slot",
            decode_road: "ALL",
        },
        MemberContract {
            shape: CodecMemberShape::Nested,
            encode_road: "encode_canonical",
            decode_road: "decode_canonical",
        },
    ];
    assert_eq!(MEMBER_CONTRACT, expected);

    let surface = codec_surface(&codec_content(CodecDirection::RoundTrip)?)
        .map_err(|refusal| refusal.to_string())?
        .inspected();
    for contract in MEMBER_CONTRACT {
        let encode = contract
            .encode_road
            .rsplit("::")
            .next()
            .unwrap_or(contract.encode_road);
        let decode = contract
            .decode_road
            .rsplit("::")
            .next()
            .unwrap_or(contract.decode_road);
        assert!(surface.contains(encode), "the surface omits {encode}");
        assert!(surface.contains(decode), "the surface omits {decode}");
    }
    Ok(())
}

/// Claim: the codec content preimage is complete and stable at the public canonical-content boundary.
///
/// Population: one content value carrying all five wire shapes, all three cardinalities, checked assembly, and both roads.
/// Reversal: changing only the direction changes the preimage.
/// Denominator: every field of `CodecContent`, its shape, its assembly, and every member row is re-encoded from its public values.
/// Evidence ceiling: this fixes the preimage bytes for this representative content and does not claim collision resistance or every possible owner identity and assumption roster.
#[test]
fn codec_content_bytes_match_an_independent_preimage() -> Result<(), String> {
    let content = codec_content(CodecDirection::RoundTrip)?;
    let mut actual = Vec::new();
    content.encode_content_into(&mut actual);
    assert_eq!(actual, independent_content_bytes());

    let mut encode_only = Vec::new();
    codec_content(CodecDirection::Encode)?.encode_content_into(&mut encode_only);
    assert_ne!(actual, encode_only);
    Ok(())
}

fn issue_material(spelling: &str) -> Vec<u8> {
    let mut material = Vec::new();
    encode_bytes(spelling.as_bytes(), &mut material);
    material
}

fn issue_bytes(slot: u8, material: &[u8]) -> Vec<u8> {
    let mut bytes = vec![slot];
    encode_bytes(material, &mut bytes);
    bytes
}

fn require_compiled_specimen(source: &str) -> Result<(), String> {
    let output = observe_rustc("codec", source, &[])?;
    if output.status.success() {
        Ok(())
    } else {
        Err(String::from_utf8_lossy(&output.stderr).into_owned())
    }
}

/// Claim: every diagnostic issue row commits to its stable slot and complete typed payload.
///
/// Population: all 13 `CodecIssue` rows.
/// Hostile controls: two spelling-bearing rows carrying the same spelling remain separated by their slots, and changing one spelling changes its bytes.
/// Denominator: the expected bytes use the public frame and no codec issue encoder.
/// Evidence ceiling: this establishes codec issue material, not the diagnostic home's later family and subject derivation.
#[test]
fn every_codec_issue_matches_its_independent_bytes() {
    let mut shadowed = issue_material("material");
    encode_bytes(b"material", &mut shadowed);
    let mut path_bound = Vec::new();
    path_bound.extend_from_slice(&8_u64.to_be_bytes());
    path_bound.extend_from_slice(&9_u64.to_be_bytes());
    let mut member_bound = Vec::new();
    member_bound.extend_from_slice(&64_u64.to_be_bytes());
    member_bound.extend_from_slice(&65_u64.to_be_bytes());
    let cases = vec![
        (CodecIssue::PathSegmentsAbsent, issue_bytes(0, &[])),
        (
            CodecIssue::SegmentNotAnIdentifier {
                segment: "bad!".to_owned(),
            },
            issue_bytes(1, &issue_material("bad!")),
        ),
        (
            CodecIssue::PathSegmentsUnbounded {
                bound: 8,
                observed: 9,
            },
            issue_bytes(2, &path_bound),
        ),
        (CodecIssue::MemberSpellingAbsent, issue_bytes(3, &[])),
        (
            CodecIssue::MemberSpellingNotAnIdentifier {
                spelling: "bad!".to_owned(),
            },
            issue_bytes(4, &issue_material("bad!")),
        ),
        (
            CodecIssue::MemberSpellingDoubled {
                spelling: "same".to_owned(),
            },
            issue_bytes(5, &issue_material("same")),
        ),
        (
            CodecIssue::MemberShadowsBinding {
                spelling: "material".to_owned(),
                binding: "material",
            },
            issue_bytes(6, &shadowed),
        ),
        (CodecIssue::AssemblyRoadAbsent, issue_bytes(7, &[])),
        (
            CodecIssue::AssemblyRoadNotAnIdentifier {
                spelling: "bad!".to_owned(),
            },
            issue_bytes(8, &issue_material("bad!")),
        ),
        (
            CodecIssue::RefusalSpellingNotAnIdentifier {
                spelling: "bad!".to_owned(),
            },
            issue_bytes(9, &issue_material("bad!")),
        ),
        (
            CodecIssue::ModuleSpellingNotAnIdentifier {
                spelling: "bad!".to_owned(),
            },
            issue_bytes(10, &issue_material("bad!")),
        ),
        (CodecIssue::MembersAbsent, issue_bytes(11, &[])),
        (
            CodecIssue::MembersUnbounded {
                bound: 64,
                observed: 65,
            },
            issue_bytes(12, &member_bound),
        ),
    ];
    for (issue, expected) in cases {
        assert_eq!(issue.canonical_bytes(), expected);
    }

    let same = CodecIssue::MemberSpellingDoubled {
        spelling: "same".to_owned(),
    };
    let another_row = CodecIssue::AssemblyRoadNotAnIdentifier {
        spelling: "same".to_owned(),
    };
    let another_spelling = CodecIssue::MemberSpellingDoubled {
        spelling: "other".to_owned(),
    };
    assert_ne!(same.canonical_bytes(), another_row.canonical_bytes());
    assert_ne!(same.canonical_bytes(), another_spelling.canonical_bytes());
}

/// The three typed rootings render the language's own qualifiers — the caller's crate, the landing module, and its parent — never the extern prelude.
#[test]
fn a_codec_path_renders_under_its_typed_rooting() -> Result<(), String> {
    let owner = CodecTypePath::spelled(PathRooting::CrateAbsolute, vec!["Demo".to_owned()])
        .map_err(|refusal| refusal.to_string())?;
    let held = CodecTypePath::spelled(PathRooting::ParentScoped, vec!["Held".to_owned()])
        .map_err(|refusal| refusal.to_string())?;
    let near = CodecTypePath::spelled(PathRooting::SelfScoped, vec!["Near".to_owned()])
        .map_err(|refusal| refusal.to_string())?;
    let members = vec![
        CodecMember::declared(
            "held",
            held,
            CodecMemberShape::Nested,
            Cardinality::Required,
        )
        .map_err(|refusal| refusal.to_string())?,
        CodecMember::declared(
            "near",
            near,
            CodecMemberShape::Nested,
            Cardinality::Required,
        )
        .map_err(|refusal| refusal.to_string())?,
    ];
    let assembly = CodecAssembly::stated("assembled", AssemblyPosture::Total)
        .map_err(|refusal| refusal.to_string())?;
    let shape = CodecShape::declared(owner, "DemoRefusal", assembly, members)
        .map_err(|refusal| refusal.to_string())?;
    let content = CodecContent {
        shape,
        direction: CodecDirection::RoundTrip,
        placement: CodecPlacement::AtDeclarationSite,
        schema: None,
        byte_role: None,
        assumptions: Bounded::empty(),
    };
    let text = codec_surface(&content)
        .map_err(|refusal| refusal.to_string())?
        .inspected();
    for spelled in ["crate :: Demo", "super :: Held", "self :: Near"] {
        assert!(
            text.contains(spelled),
            "the surface does not spell {spelled}"
        );
    }
    assert!(!text.contains(":: crate"), "the extern prelude leaked in");
    Ok(())
}

const SPECIMEN_DECLARATIONS: &str = r"
#[derive(Debug, Clone, PartialEq, Eq)]
struct EvenBytes(Vec<u8>);

impl AsRef<[u8]> for EvenBytes {
    fn as_ref(&self) -> &[u8] { &self.0 }
}

impl TryFrom<Vec<u8>> for EvenBytes {
    type Error = ();

    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
        if bytes.first() == Some(&0xff) { Err(()) } else { Ok(Self(bytes)) }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Choice { First, Second }

impl Choice {
    const ALL: [Self; 2] = [Self::First, Self::Second];

    const fn slot(self) -> u8 {
        match self { Self::First => 0, Self::Second => 1 }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct Nested(u8);

#[derive(Debug, Clone, PartialEq, Eq)]
struct NestedRefusal;

impl Nested {
    fn encode_canonical(&self, into: &mut Vec<u8>) { into.push(self.0); }

    fn decode_canonical(material: &[u8]) -> Result<Self, NestedRefusal> {
        match material { [value] if *value != 0 => Ok(Self(*value)), _ => Err(NestedRefusal) }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssemblyRefusal;

#[derive(Debug, Clone, PartialEq, Eq)]
struct Demo {
    count: u16,
    payload: EvenBytes,
    label: Option<String>,
    modes: Vec<Choice>,
    child: Nested,
}

impl Demo {
    fn assembled(
        count: u16,
        payload: EvenBytes,
        label: Option<String>,
        modes: Vec<Choice>,
        child: Nested,
    ) -> Result<Self, AssemblyRefusal> {
        if count == 0 {
            Err(AssemblyRefusal)
        } else {
            Ok(Self { count, payload, label, modes, child })
        }
    }
}
";

const SPECIMEN_ASSERTIONS: &str = r#"
fn main() {
    let value = Demo {
        count: 513,
        payload: EvenBytes(vec![3, 4]),
        label: Some(String::from("hi")),
        modes: vec![Choice::First, Choice::Second],
        child: Nested(7),
    };
    let mut encoded = Vec::new();
    value.encode_canonical(&mut encoded);
    let expected = vec![
        0, 0, 0, 0, 0, 0, 2, 1,
        0, 0, 0, 0, 0, 0, 0, 2, 3, 4,
        1,
        0, 0, 0, 0, 0, 0, 0, 2, 104, 105,
        0, 0, 0, 0, 0, 0, 0, 2, 0, 1,
        0, 0, 0, 0, 0, 0, 0, 1, 7,
    ];
    assert_eq!(encoded, expected);
    assert_eq!(Demo::decode_canonical(&encoded), Ok(value.clone()));

    let mut trailing = encoded.clone();
    trailing.push(9);
    assert_eq!(Demo::decode_canonical(&trailing), Err(DemoRefusal::TrailingBytes));

    let mut bad_presence = encoded.clone();
    bad_presence[18] = 2;
    assert_eq!(
        Demo::decode_canonical(&bad_presence),
        Err(DemoRefusal::PresenceNotAdmitted { member: "label" }),
    );

    let mut bad_slot = encoded.clone();
    bad_slot[37] = 9;
    assert_eq!(
        Demo::decode_canonical(&bad_slot),
        Err(DemoRefusal::SlotNotAdmitted { member: "modes" }),
    );

    let mut bad_nested = encoded.clone();
    bad_nested[47] = 0;
    assert_eq!(
        Demo::decode_canonical(&bad_nested),
        Err(DemoRefusal::NestedMemberRefused { member: "child" }),
    );

    let mut refused_member = encoded.clone();
    refused_member[16] = 0xff;
    assert_eq!(
        Demo::decode_canonical(&refused_member),
        Err(DemoRefusal::MemberNotAdmitted { member: "payload" }),
    );

    let mut bad_text = encoded.clone();
    bad_text[27] = 0xff;
    assert_eq!(
        Demo::decode_canonical(&bad_text),
        Err(DemoRefusal::TextNotUtf8 { member: "label" }),
    );

    let mut wide_count = encoded.clone();
    wide_count[..8].copy_from_slice(&u64::MAX.to_be_bytes());
    assert_eq!(
        Demo::decode_canonical(&wide_count),
        Err(DemoRefusal::CountPastDeclaredWidth { member: "count" }),
    );

    let mut long_payload = encoded.clone();
    long_payload[8..16].copy_from_slice(&99_u64.to_be_bytes());
    assert_eq!(
        Demo::decode_canonical(&long_payload),
        Err(DemoRefusal::LengthPastRemaining { member: "payload" }),
    );

    assert_eq!(
        Demo::decode_canonical(&[0, 1, 2]),
        Err(DemoRefusal::Truncated { member: "count" }),
    );

    let refused = Demo {
        count: 0,
        payload: EvenBytes(vec![3, 4]),
        label: None,
        modes: Vec::new(),
        child: Nested(7),
    };
    let mut refused_bytes = Vec::new();
    refused.encode_canonical(&mut refused_bytes);
    assert_eq!(
        Demo::decode_canonical(&refused_bytes),
        Err(DemoRefusal::NotAssembled(AssemblyRefusal)),
    );
}
"#;

/// Claim: generated codec Rust for every wire shape and cardinality compiles and executes its public round-trip and refusal behavior.
///
/// Population: one checked-assembly surface covering five shapes, three cardinalities, and every generated refusal arm that can be reached by bounded hostile material.
/// Hostile controls: trailing, malformed presence, foreign slot, nested refusal, member refusal, invalid UTF-8, count overflow, overlong frame, truncation, and checked-assembly refusal.
/// Denominator: the generated source is compiled by Rust 1.98 and its standalone executable must pass every assertion.
/// Evidence ceiling: this is one representative type roster on the local Windows host, not arbitrary downstream types, Wasm, Linux, packaging, or performance.
#[test]
fn generated_codec_rust_compiles_executes_and_refuses_hostile_bytes() -> Result<(), String> {
    let surface = codec_surface(&codec_content(CodecDirection::RoundTrip)?)
        .map_err(|refusal| refusal.to_string())?
        .inspected();
    let mut source = String::from(SPECIMEN_DECLARATIONS);
    source.push_str(&surface);
    source.push_str(SPECIMEN_ASSERTIONS);
    require_compiled_specimen(&source)
}

/// Claim: published-module placement wraps the complete codec surface in one public module that imports its parent scope and remains executable.
///
/// Population: the same representative checked-assembly surface used by the generated-behavior crossing, moved from the declaration site into one named module.
/// Hostile control: the source assertions stand outside the generated module, so compilation or execution fails if the wrapper drops parent-scope access, module visibility, the generated refusal, or either codec road.
/// Denominator: the public `CodecPlacement::PublishedModule` route through `codec_surface` and Rust 1.98 compilation.
/// Evidence ceiling: this establishes one module spelling and one representative owner, not arbitrary surrounding imports or nested landing modules.
#[test]
fn published_module_placement_compiles_and_executes_from_its_parent_scope() -> Result<(), String> {
    let mut content = codec_content(CodecDirection::RoundTrip)?;
    content.placement = CodecPlacement::PublishedModule {
        spelling: ModuleSpelling::spelled("demo_codec").map_err(|refusal| refusal.to_string())?,
    };
    let surface = codec_surface(&content)
        .map_err(|refusal| refusal.to_string())?
        .inspected();
    for spelling in [
        "pub mod demo_codec",
        "use super :: *",
        "The canonical encode and decode roads",
        "pub enum DemoRefusal",
        "impl Demo",
    ] {
        assert!(surface.contains(spelling), "the wrapper omits {spelling}");
    }

    let mut source = String::from(SPECIMEN_DECLARATIONS);
    source.push_str(&surface);
    source.push_str("use demo_codec::DemoRefusal;");
    source.push_str(SPECIMEN_ASSERTIONS);
    require_compiled_specimen(&source)
}