macroonz-compiler 0.1.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
//! The tables this home states rather than computes, and the contracts its kind and its refusal stand under.
//!
//! Each table is total, so a row admitted later stops the compiler in every one of them until somebody says what that row's answer is.

use super::spell::{
    CANDIDATE_BINDING, CARRIED_BINDING, CHOSEN_BINDING, COLLECTED_BINDING, ELECTED_BINDING,
    INTO_BINDING, LENGTH_BINDING, MATERIAL_BINDING, NESTED_BINDING, PRESENT_BINDING,
    REMAINING_BINDING, WIDTH_BINDING,
};
use super::{
    AssemblyPosture, CodecContent, CodecDirection, CodecError, CodecIssue, CodecMemberShape,
    CodecPlacement, CodecProjection, CodecTypePath, DECODE_ROAD, DecodeRefusal, ENCODE_ROAD,
    MemberContract, ROSTER_CONSTANT, SLOT_ROAD,
};
use crate::bounded::{Bounded, Capping};
use crate::diagnostic::{
    CODEC_DECLARATION_FAMILY, Family, LineBody, Observed, Phase, REPAIR_LIMIT, RefusalClass,
    Refused, Repair,
};
use crate::identity::{OwnerIdentity, encode_bytes, encode_length};
use crate::kind::{CanonicalContent, Kind, NoQuestions, SoleRole};
use core::fmt;

impl CanonicalContent for CodecContent {
    fn encode_content_into(&self, into: &mut Vec<u8>) {
        encode_path(self.shape.owner(), into);
        encode_bytes(self.shape.refusal().as_bytes(), into);
        let assembly = self.shape.assembly();
        encode_bytes(assembly.road().as_bytes(), into);
        match assembly.posture() {
            AssemblyPosture::Total => into.push(0),
            AssemblyPosture::Checked { refusal } => {
                into.push(1);
                encode_path(refusal, into);
            }
        }
        encode_length(self.shape.count(), into);
        for member in self.shape.members() {
            let mut encoded = Vec::new();
            encode_bytes(member.spelling().as_bytes(), &mut encoded);
            encode_path(member.held_as(), &mut encoded);
            encode_bytes(member.shape().name().as_bytes(), &mut encoded);
            encode_bytes(member.cardinality().name().as_bytes(), &mut encoded);
            encode_bytes(&encoded, into);
        }
        encode_bytes(self.direction.name().as_bytes(), into);
        match &self.placement {
            CodecPlacement::AtDeclarationSite => into.push(0),
            CodecPlacement::PublishedModule { spelling } => {
                into.push(1);
                encode_bytes(spelling.spelling().as_bytes(), into);
            }
        }
        encode_owner(self.schema.as_ref(), into);
        encode_owner(self.byte_role.as_ref(), into);
        encode_length(self.assumptions.len(), into);
        for assumption in self.assumptions.as_slice() {
            encode_bytes(&assumption.citation_bytes(), into);
        }
    }
}

fn encode_path(path: &CodecTypePath, into: &mut Vec<u8>) {
    encode_bytes(path.rooting().name().as_bytes(), into);
    encode_length(path.count(), into);
    for segment in path.segments() {
        encode_bytes(segment.as_bytes(), into);
    }
}

fn encode_owner(owner: Option<&OwnerIdentity>, into: &mut Vec<u8>) {
    match owner {
        None => into.push(0),
        Some(identity) => {
            into.push(1);
            encode_bytes(&identity.citation_bytes(), into);
        }
    }
}

impl Kind for CodecProjection {
    const NAME: &'static str = "codec-projection";

    type Content = CodecContent;
    type Role = SoleRole;
    type Question = NoQuestions;
}

impl CodecDirection {
    /// Whether this direction covers the road that writes canonical bytes.
    #[must_use]
    pub const fn writes(self) -> bool {
        match self {
            Self::Encode | Self::RoundTrip => true,
            Self::Decode => false,
        }
    }

    /// Whether this direction covers the road that reads them back.
    ///
    /// # Nonclaims
    ///
    /// A direction that does not cover it delivers no reader, and that is a stated posture rather than a rendering that fell short: "a codec that refuses on decode is the validator" says exactly as much about the codec that has no decode road.
    #[must_use]
    pub const fn reads(self) -> bool {
        match self {
            Self::Decode | Self::RoundTrip => true,
            Self::Encode => false,
        }
    }
}

impl DecodeRefusal {
    /// Whether this arm names the member the read was standing at.
    ///
    /// The two that do not are facts about the whole material and about the assembly, and a member seat on either would name a member no read was standing at.
    #[must_use]
    pub const fn carries_member(self) -> bool {
        match self {
            Self::Truncated
            | Self::LengthPastRemaining
            | Self::LengthPastAddressableWidth
            | Self::CountPastDeclaredWidth
            | Self::TextNotUtf8
            | Self::MemberNotAdmitted
            | Self::SlotNotAdmitted
            | Self::NestedMemberRefused
            | Self::PresenceNotAdmitted => true,
            Self::TrailingBytes | Self::NotAssembled => false,
        }
    }

    /// The sentence this arm is rendered with, for whoever reads the refusal in their own crate.
    #[must_use]
    pub const fn sentence(self) -> &'static str {
        match self {
            Self::Truncated => "The material ended inside this member.",
            Self::LengthPastRemaining => {
                "This member's declared length runs past the material that remains."
            }
            Self::LengthPastAddressableWidth => {
                "This member's declared length does not fit an addressable width."
            }
            Self::CountPastDeclaredWidth => {
                "This member's declared count does not fit the width the member is held at."
            }
            Self::TextNotUtf8 => "This member's framed bytes are not UTF-8.",
            Self::MemberNotAdmitted => "The member's own type refused what was read for it.",
            Self::SlotNotAdmitted => {
                "The slot read for this member names no arm of the roster it was declared over."
            }
            Self::NestedMemberRefused => {
                "The nested codec this member carries refused the framed material."
            }
            Self::PresenceNotAdmitted => {
                "This member's presence byte is neither of the two the encode road writes."
            }
            Self::TrailingBytes => {
                "Material remains after the last declared member. A canonical encoding is the \
                 whole of what a value writes, so a longer input is not this value with something \
                 after it."
            }
            Self::NotAssembled => {
                "Every member was read, and the road that assembles them refused. The refusal is \
                 the owner's own, carried exactly."
            }
        }
    }
}

/// The complete bill, one row per wire shape, in the roster's own order.
///
/// Five rows because the roster is five: a row added here without an arm beside it, or an arm without a row, is a length disagreement the declaration itself carries.
///
/// The closed-choice row is this compiler's own contract on a caller's roster — a complete roster constant and a position road answering one byte — and not an inheritance from any stamp that happens to emit one.
pub const MEMBER_CONTRACT: [MemberContract; 5] = [
    COUNT_CONTRACT.bill,
    BYTES_CONTRACT.bill,
    TEXT_CONTRACT.bill,
    CLOSED_CHOICE_CONTRACT.bill,
    NESTED_CONTRACT.bill,
];

/// The write operation one contract row selects.
#[derive(Clone, Copy)]
pub(super) enum WriteRoad {
    /// Widen one count and write its big-endian bytes.
    Count,
    /// Borrow bytes through the declared trait road and frame them.
    Bytes,
    /// Borrow text through the declared trait road and frame its UTF-8 bytes.
    Text,
    /// Write the declared slot of one closed-choice arm.
    ClosedChoice,
    /// Call and frame one nested codec.
    Nested,
}

/// The read operation one contract row selects.
#[derive(Clone, Copy)]
pub(super) enum ReadRoad {
    /// Read and narrow one count.
    Count,
    /// Read framed bytes and ask the member type to admit them.
    Bytes,
    /// Read framed UTF-8 text and ask the member type to admit it.
    Text,
    /// Elect one arm from the owner's complete roster.
    ClosedChoice,
    /// Ask one nested codec to read its framed material.
    Nested,
}

/// One authoritative contract row, with its public bill and the two internal operations that consume it.
#[derive(Clone, Copy)]
pub(super) struct RenderingContract {
    /// The public statement of the member roads.
    pub(super) bill: MemberContract,
    /// The generated write operation.
    pub(super) write: WriteRoad,
    /// The generated read operation.
    pub(super) read: ReadRoad,
}

const COUNT_CONTRACT: RenderingContract = RenderingContract {
    bill: MemberContract {
        shape: CodecMemberShape::Count,
        encode_road: "u64::from",
        decode_road: "<T as ::core::convert::TryFrom<u64>>::try_from",
    },
    write: WriteRoad::Count,
    read: ReadRoad::Count,
};

const BYTES_CONTRACT: RenderingContract = RenderingContract {
    bill: 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",
    },
    write: WriteRoad::Bytes,
    read: ReadRoad::Bytes,
};

const TEXT_CONTRACT: RenderingContract = RenderingContract {
    bill: 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",
    },
    write: WriteRoad::Text,
    read: ReadRoad::Text,
};

const CLOSED_CHOICE_CONTRACT: RenderingContract = RenderingContract {
    bill: MemberContract {
        shape: CodecMemberShape::ClosedChoice,
        encode_road: SLOT_ROAD,
        decode_road: ROSTER_CONSTANT,
    },
    write: WriteRoad::ClosedChoice,
    read: ReadRoad::ClosedChoice,
};

const NESTED_CONTRACT: RenderingContract = RenderingContract {
    bill: MemberContract {
        shape: CodecMemberShape::Nested,
        encode_road: ENCODE_ROAD,
        decode_road: DECODE_ROAD,
    },
    write: WriteRoad::Nested,
    read: ReadRoad::Nested,
};

/// The authoritative row one member shape selects.
///
/// Both the public bill and generated operations read this seat, so adding or reassigning a shape cannot leave an independently selected renderer behind it.
pub(super) const fn rendering_contract(shape: CodecMemberShape) -> RenderingContract {
    match shape {
        CodecMemberShape::Count => COUNT_CONTRACT,
        CodecMemberShape::Bytes => BYTES_CONTRACT,
        CodecMemberShape::Text => TEXT_CONTRACT,
        CodecMemberShape::ClosedChoice => CLOSED_CHOICE_CONTRACT,
        CodecMemberShape::Nested => NESTED_CONTRACT,
    }
}

/// The locals the rendered decode road declares for itself.
///
/// # Authority
///
/// **A member whose spelling is one of these is refused rather than renamed.**
/// The decode road binds one local per member under the member's OWN spelling, which is what makes the rendered road readable and what lets the assembly call name its arguments the way the owner named its members.
/// A member colliding with one of these would shadow the rendering's own binding, and the road would go on reading a value nobody meant — a defect that compiles.
///
/// Renaming the rendering's locals to something nobody would write is not the repair: an unreadable rendered road is a road nobody can audit, and the collision would still exist for whatever names were chosen instead.
pub const RESERVED_BINDINGS: [&str; 12] = [
    MATERIAL_BINDING,
    REMAINING_BINDING,
    INTO_BINDING,
    NESTED_BINDING,
    COLLECTED_BINDING,
    CANDIDATE_BINDING,
    CHOSEN_BINDING,
    ELECTED_BINDING,
    PRESENT_BINDING,
    CARRIED_BINDING,
    LENGTH_BINDING,
    WIDTH_BINDING,
];

impl CodecIssue {
    /// This row's position in the declared roster, written ahead of the issue's own material.
    ///
    /// Appended and never renumbered: the byte stands inside every identity derived over a refusal that names it.
    #[must_use]
    pub const fn slot(&self) -> u8 {
        match self {
            Self::PathSegmentsAbsent => 0,
            Self::SegmentNotAnIdentifier { .. } => 1,
            Self::PathSegmentsUnbounded { .. } => 2,
            Self::MemberSpellingAbsent => 3,
            Self::MemberSpellingNotAnIdentifier { .. } => 4,
            Self::MemberSpellingDoubled { .. } => 5,
            Self::MemberShadowsBinding { .. } => 6,
            Self::AssemblyRoadAbsent => 7,
            Self::AssemblyRoadNotAnIdentifier { .. } => 8,
            Self::RefusalSpellingNotAnIdentifier { .. } => 9,
            Self::ModuleSpellingNotAnIdentifier { .. } => 10,
            Self::MembersAbsent => 11,
            Self::MembersUnbounded { .. } => 12,
        }
    }

    /// How what this issue observed differs from the contract that was expected.
    #[must_use]
    pub const fn observed(&self) -> Observed {
        match self {
            Self::PathSegmentsAbsent
            | Self::MemberSpellingAbsent
            | Self::AssemblyRoadAbsent
            | Self::MembersAbsent => Observed::SeatAbsent,
            Self::PathSegmentsUnbounded { .. } | Self::MembersUnbounded { .. } => {
                Observed::BoundExceeded
            }
            Self::SegmentNotAnIdentifier { .. }
            | Self::MemberSpellingNotAnIdentifier { .. }
            | Self::MemberSpellingDoubled { .. }
            | Self::MemberShadowsBinding { .. }
            | Self::AssemblyRoadNotAnIdentifier { .. }
            | Self::RefusalSpellingNotAnIdentifier { .. }
            | Self::ModuleSpellingNotAnIdentifier { .. } => Observed::ContractDisagreement,
        }
    }

    /// Which class of refusal a summary line opens with where this issue is the first established.
    #[must_use]
    pub const fn class(&self) -> RefusalClass {
        match self {
            Self::PathSegmentsUnbounded { .. } | Self::MembersUnbounded { .. } => {
                RefusalClass::MagnitudeNotHeld
            }
            Self::PathSegmentsAbsent
            | Self::SegmentNotAnIdentifier { .. }
            | Self::MemberSpellingAbsent
            | Self::MemberSpellingNotAnIdentifier { .. }
            | Self::MemberSpellingDoubled { .. }
            | Self::MemberShadowsBinding { .. }
            | Self::AssemblyRoadAbsent
            | Self::AssemblyRoadNotAnIdentifier { .. }
            | Self::RefusalSpellingNotAnIdentifier { .. }
            | Self::ModuleSpellingNotAnIdentifier { .. }
            | Self::MembersAbsent => RefusalClass::DeclarationNotRead,
        }
    }
}

impl fmt::Display for CodecIssue {
    fn fmt(&self, into: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::PathSegmentsAbsent => into.write_str("a rendered type path names no segment"),
            Self::SegmentNotAnIdentifier { segment } => {
                write!(into, "the path segment {segment} is not one Rust identifier")
            }
            Self::PathSegmentsUnbounded { bound, observed } => write!(
                into,
                "a rendered type path names {observed} segments where {bound} are declared"
            ),
            Self::MemberSpellingAbsent => into.write_str("a codec member states no spelling"),
            Self::MemberSpellingNotAnIdentifier { spelling } => {
                write!(into, "the member spelling {spelling} is not one Rust identifier")
            }
            Self::MemberSpellingDoubled { spelling } => write!(
                into,
                "two members of one shape are both spelled {spelling}, so the decode road would bind one local twice"
            ),
            Self::MemberShadowsBinding { spelling, binding } => write!(
                into,
                "the member {spelling} is spelled like {binding}, which the decode road binds for itself"
            ),
            Self::AssemblyRoadAbsent => into.write_str("a codec assembly road states no spelling"),
            Self::AssemblyRoadNotAnIdentifier { spelling } => {
                write!(into, "the assembly road {spelling} is not one Rust identifier")
            }
            Self::RefusalSpellingNotAnIdentifier { spelling } => write!(
                into,
                "the rendered decode refusal {spelling} is not one Rust identifier"
            ),
            Self::ModuleSpellingNotAnIdentifier { spelling } => write!(
                into,
                "the published module {spelling} is not one Rust identifier"
            ),
            Self::MembersAbsent => into.write_str(
                "a codec shape declares no member, so its decode road could refuse for one reason and admit every other input",
            ),
            Self::MembersUnbounded { bound, observed } => write!(
                into,
                "a codec shape declares {observed} members where {bound} are declared"
            ),
        }
    }
}

impl fmt::Display for CodecError {
    fn fmt(&self, into: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(into, "{}", self.first_issue())?;
        let further = self.issues().count().saturating_sub(1);
        if further > 0 {
            write!(into, ", and {further} further issues")?;
        }
        if let Capping::Truncated { omitted } = self.capping() {
            write!(into, ", {omitted} of them not carried")?;
        }
        Ok(())
    }
}

impl core::error::Error for CodecError {}

impl Refused for CodecError {
    const PHASE: Phase = Phase::Capture;
    const FAMILY: Family = CODEC_DECLARATION_FAMILY;

    fn class(&self) -> RefusalClass {
        self.first_issue().class()
    }

    fn first(&self) -> String {
        self.first_issue().to_string()
    }

    fn observed(&self) -> Observed {
        self.first_issue().observed()
    }

    fn body(&self) -> LineBody {
        let further = self.issues().count().saturating_sub(1);
        let capping = self.capping();
        if further == 0 && capping == Capping::Complete {
            LineBody::SingleCause
        } else {
            LineBody::Body { further, capping }
        }
    }

    /// The issues established beyond the primary cause; the primary is the summary's own subject, never a member of its related set.
    fn related(&self) -> Vec<Vec<u8>> {
        self.issues()
            .iter()
            .skip(1)
            .map(CodecIssue::canonical_bytes)
            .collect()
    }

    /// This home declares no repair of its own.
    ///
    /// Every issue is about what the caller's own declaration states, so the repair is that declaration; a sentence composed here would be this compiler citing a fact nobody declared.
    fn repairs(&self) -> Bounded<Repair, REPAIR_LIMIT> {
        Bounded::empty()
    }
}