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
//! Rendering the builder module one network declaration compresses.
//!
//! The module holds one generated fault enum, `topology()`, and one function per declared schedule — exactly what an author would have written by hand against the harness's network home, with every refusal traveling as itself.

use super::{DisciplineRow, FaultRow, LinkRow, NetworkDeclaration, ScheduleRow};
use crate::bounded::Overflow;
use crate::descriptor::DirectBinding;
use crate::descriptor::emitting::{
    absolute_path, derive_attribute, direct_path, doc_attribute, fallible_return, from_impl,
};
use crate::token::{GeneratedDelimiter, GeneratedToken};

/// The names the generated module writes beside the authored ones, which no schedule may take.
///
/// One seat for both halves: the emission below spells these constants, and the capture refuses an authored schedule that spells one of them — so the roster cannot drift from the items it reserves.
pub(super) const RESERVED: [&str; 2] = [TOPOLOGY_ROAD, FAULT_ENUM];

/// The generated topology function's name.
const TOPOLOGY_ROAD: &str = "topology";

/// The generated fault enum's name.
const FAULT_ENUM: &str = "Fault";

/// The fault enum's arms: the arm, the refusal it carries, and its stated doc.
const FAULT_ARMS: [(&str, [&str; 2], &str); 4] = [
    (
        "Name",
        ["descriptor", "NameRefusal"],
        "A declared name was refused by the name vocabulary.",
    ),
    (
        "Topology",
        ["network", "TopologyRefusal"],
        "The declared topology was refused by its own guard.",
    ),
    (
        "Span",
        ["network", "TickSpanRefusal"],
        "A declared delay span was refused by its own guard.",
    ),
    (
        "Schedule",
        ["network", "NetworkScheduleRefusal"],
        "A declared schedule was refused by its own guard.",
    ),
];

/// The declaration-site tokens one network payload renders to.
///
/// # Errors
///
/// Returns [`Overflow`] where a composed group carries more tokens than the declared magnitude admits.
pub fn rendered(declaration: &NetworkDeclaration) -> Result<Vec<GeneratedToken>, Overflow> {
    let mut tokens = Vec::new();
    doc_attribute(
        "The generated network builders: the declared topology, and one function per declared schedule.",
        &mut tokens,
    )?;
    tokens.push(GeneratedToken::word("pub"));
    tokens.push(GeneratedToken::word("mod"));
    tokens.push(GeneratedToken::word(declaration.module()));
    let mut body = Vec::new();
    fault_enum(declaration.harness(), &mut body)?;
    topology_fn(declaration, &mut body)?;
    for schedule in declaration.schedules() {
        schedule_fn(declaration, schedule, &mut body)?;
    }
    tokens.push(GeneratedToken::group(GeneratedDelimiter::Brace, body)?);
    Ok(tokens)
}

/// The generated fault enum and its `From` impls.
fn fault_enum(harness: &DirectBinding, into: &mut Vec<GeneratedToken>) -> Result<(), Overflow> {
    doc_attribute(
        "Everything a generated builder can refuse, carried as itself.",
        into,
    )?;
    derive_attribute(&["Debug", "Clone", "PartialEq", "Eq"], into)?;
    into.push(GeneratedToken::word("pub"));
    into.push(GeneratedToken::word("enum"));
    into.push(GeneratedToken::word(FAULT_ENUM));
    let mut arms = Vec::new();
    for (arm, path, doc) in &FAULT_ARMS {
        doc_attribute(doc, &mut arms)?;
        arms.push(GeneratedToken::word(arm));
        let mut carried = Vec::new();
        direct_path(harness, path, &mut carried);
        arms.push(GeneratedToken::group(
            GeneratedDelimiter::Parenthesis,
            carried,
        )?);
        arms.push(GeneratedToken::alone(','));
    }
    into.push(GeneratedToken::group(GeneratedDelimiter::Brace, arms)?);
    for (arm, path, _doc) in &FAULT_ARMS {
        from_impl(harness_path(harness, path), FAULT_ENUM, arm, into)?;
    }
    Ok(())
}

/// One `<harness>::network::NodeRef::declared(<harness>::descriptor::NamespacedName::named("<ns>", "<node>")?)` expression.
fn node_expr(
    harness: &DirectBinding,
    namespace: &str,
    node: &str,
    into: &mut Vec<GeneratedToken>,
) -> Result<(), Overflow> {
    direct_path(harness, &["network", "NodeRef", "declared"], into);
    let mut inner = Vec::new();
    direct_path(
        harness,
        &["descriptor", "NamespacedName", "named"],
        &mut inner,
    );
    inner.push(GeneratedToken::group(
        GeneratedDelimiter::Parenthesis,
        vec![
            GeneratedToken::text(namespace),
            GeneratedToken::alone(','),
            GeneratedToken::text(node),
        ],
    )?);
    inner.push(GeneratedToken::alone('?'));
    into.push(GeneratedToken::group(
        GeneratedDelimiter::Parenthesis,
        inner,
    )?);
    Ok(())
}

/// One `<harness>::network::Link::between(<from>, <to>)` expression.
fn link_expr(
    harness: &DirectBinding,
    namespace: &str,
    link: &LinkRow,
    into: &mut Vec<GeneratedToken>,
) -> Result<(), Overflow> {
    direct_path(harness, &["network", "Link", "between"], into);
    let mut inner = Vec::new();
    node_expr(harness, namespace, link.from(), &mut inner)?;
    inner.push(GeneratedToken::alone(','));
    node_expr(harness, namespace, link.to(), &mut inner)?;
    into.push(GeneratedToken::group(
        GeneratedDelimiter::Parenthesis,
        inner,
    )?);
    Ok(())
}

/// One `::std::vec::Vec::from([<members>])` expression, or `::std::vec::Vec::new()` where nothing is listed.
fn vec_expr(
    members: Vec<Vec<GeneratedToken>>,
    into: &mut Vec<GeneratedToken>,
) -> Result<(), Overflow> {
    if members.is_empty() {
        absolute_path(&["std", "vec", "Vec", "new"], into);
        into.push(GeneratedToken::group(
            GeneratedDelimiter::Parenthesis,
            Vec::new(),
        )?);
        return Ok(());
    }
    absolute_path(&["std", "vec", "Vec", "from"], into);
    let mut listed = Vec::new();
    for (position, member) in members.into_iter().enumerate() {
        if position > 0 {
            listed.push(GeneratedToken::alone(','));
        }
        listed.extend(member);
    }
    into.push(GeneratedToken::group(
        GeneratedDelimiter::Parenthesis,
        vec![GeneratedToken::group(GeneratedDelimiter::Bracket, listed)?],
    )?);
    Ok(())
}

/// The generated `topology()` function.
fn topology_fn(
    declaration: &NetworkDeclaration,
    into: &mut Vec<GeneratedToken>,
) -> Result<(), Overflow> {
    doc_attribute("The declared topology.", into)?;
    into.push(GeneratedToken::word("pub"));
    into.push(GeneratedToken::word("fn"));
    into.push(GeneratedToken::word(TOPOLOGY_ROAD));
    into.push(GeneratedToken::group(
        GeneratedDelimiter::Parenthesis,
        Vec::new(),
    )?);
    let mut ok_seat = Vec::new();
    direct_path(
        declaration.harness(),
        &["network", "Topology"],
        &mut ok_seat,
    );
    fallible_return(ok_seat, FAULT_ENUM, into);
    let mut body = Vec::new();
    absolute_path(&["core", "result", "Result", "Ok"], &mut body);
    let mut inner = Vec::new();
    direct_path(
        declaration.harness(),
        &["network", "Topology", "declared"],
        &mut inner,
    );
    let mut nodes = Vec::new();
    for node in declaration.nodes() {
        let mut expression = Vec::new();
        node_expr(
            declaration.harness(),
            declaration.namespace(),
            node,
            &mut expression,
        )?;
        nodes.push(expression);
    }
    let mut links = Vec::new();
    for link in declaration.links() {
        let mut expression = Vec::new();
        link_expr(
            declaration.harness(),
            declaration.namespace(),
            link,
            &mut expression,
        )?;
        links.push(expression);
    }
    let mut seats = Vec::new();
    vec_expr(nodes, &mut seats)?;
    seats.push(GeneratedToken::alone(','));
    vec_expr(links, &mut seats)?;
    inner.push(GeneratedToken::group(
        GeneratedDelimiter::Parenthesis,
        seats,
    )?);
    inner.push(GeneratedToken::alone('?'));
    body.push(GeneratedToken::group(
        GeneratedDelimiter::Parenthesis,
        inner,
    )?);
    into.push(GeneratedToken::group(GeneratedDelimiter::Brace, body)?);
    Ok(())
}

/// One generated schedule function.
fn schedule_fn(
    declaration: &NetworkDeclaration,
    schedule: &ScheduleRow,
    into: &mut Vec<GeneratedToken>,
) -> Result<(), Overflow> {
    doc_attribute(
        &format!("The declared `{}` schedule.", schedule.name()),
        into,
    )?;
    into.push(GeneratedToken::word("pub"));
    into.push(GeneratedToken::word("fn"));
    into.push(GeneratedToken::word(schedule.name()));
    into.push(GeneratedToken::group(
        GeneratedDelimiter::Parenthesis,
        Vec::new(),
    )?);
    let mut ok_seat = Vec::new();
    direct_path(
        declaration.harness(),
        &["network", "NetworkSchedule"],
        &mut ok_seat,
    );
    fallible_return(ok_seat, FAULT_ENUM, into);
    let mut body = Vec::new();
    absolute_path(&["core", "result", "Result", "Ok"], &mut body);
    let mut inner = Vec::new();
    direct_path(
        declaration.harness(),
        &["network", "NetworkSchedule", "declared"],
        &mut inner,
    );
    let mut seats = Vec::new();
    direct_path(
        declaration.harness(),
        &["descriptor", "NamespacedName", "named"],
        &mut seats,
    );
    seats.push(GeneratedToken::group(
        GeneratedDelimiter::Parenthesis,
        vec![
            GeneratedToken::text(declaration.namespace()),
            GeneratedToken::alone(','),
            GeneratedToken::text(schedule.name()),
        ],
    )?);
    seats.push(GeneratedToken::alone('?'));
    seats.push(GeneratedToken::alone(','));
    let mut disciplines = Vec::new();
    for discipline in schedule.disciplines() {
        let mut expression = Vec::new();
        discipline_expr(
            declaration.harness(),
            declaration.namespace(),
            discipline,
            &mut expression,
        )?;
        disciplines.push(expression);
    }
    vec_expr(disciplines, &mut seats)?;
    inner.push(GeneratedToken::group(
        GeneratedDelimiter::Parenthesis,
        seats,
    )?);
    inner.push(GeneratedToken::alone('?'));
    body.push(GeneratedToken::group(
        GeneratedDelimiter::Parenthesis,
        inner,
    )?);
    into.push(GeneratedToken::group(GeneratedDelimiter::Brace, body)?);
    Ok(())
}

/// One `<harness>::network::LinkDiscipline::declared(<link>, <faults>)` expression.
fn discipline_expr(
    harness: &DirectBinding,
    namespace: &str,
    discipline: &DisciplineRow,
    into: &mut Vec<GeneratedToken>,
) -> Result<(), Overflow> {
    direct_path(harness, &["network", "LinkDiscipline", "declared"], into);
    let mut seats = Vec::new();
    link_expr(harness, namespace, discipline.link(), &mut seats)?;
    seats.push(GeneratedToken::alone(','));
    let mut faults = Vec::new();
    for fault in discipline.faults() {
        let mut expression = Vec::new();
        fault_expr(harness, fault, &mut expression)?;
        faults.push(expression);
    }
    vec_expr(faults, &mut seats)?;
    into.push(GeneratedToken::group(
        GeneratedDelimiter::Parenthesis,
        seats,
    )?);
    Ok(())
}

/// One `<harness>::network::LinkFault::…` expression.
fn fault_expr(
    harness: &DirectBinding,
    fault: &FaultRow,
    into: &mut Vec<GeneratedToken>,
) -> Result<(), Overflow> {
    match *fault {
        FaultRow::Drop { at } => positional_fault(harness, "DropAt", at, Vec::new(), into),
        FaultRow::Duplicate { at } => {
            positional_fault(harness, "DuplicateAt", at, Vec::new(), into)
        }
        FaultRow::Delay { at, by } => {
            let mut ticks = vec![
                GeneratedToken::alone(','),
                GeneratedToken::word("ticks"),
                GeneratedToken::alone(':'),
            ];
            direct_path(harness, &["network", "TickSpan", "declared"], &mut ticks);
            ticks.push(GeneratedToken::group(
                GeneratedDelimiter::Parenthesis,
                vec![GeneratedToken::number(u64::from(by))],
            )?);
            ticks.push(GeneratedToken::alone('?'));
            positional_fault(harness, "DelayAt", at, ticks, into)
        }
        FaultRow::Partition { from, until } => {
            direct_path(harness, &["network", "LinkFault", "Partition"], into);
            let mut fields = vec![GeneratedToken::word("opens"), GeneratedToken::alone(':')];
            tick_expr(harness, from, &mut fields)?;
            fields.push(GeneratedToken::alone(','));
            fields.push(GeneratedToken::word("heals"));
            fields.push(GeneratedToken::alone(':'));
            tick_expr(harness, until, &mut fields)?;
            into.push(GeneratedToken::group(GeneratedDelimiter::Brace, fields)?);
            Ok(())
        }
    }
}

/// One positional fault arm: `LinkFault::<arm> { position: SendOrdinal::at(<n>)<extra fields> }`.
fn positional_fault(
    harness: &DirectBinding,
    arm: &str,
    at: u32,
    extra_fields: Vec<GeneratedToken>,
    into: &mut Vec<GeneratedToken>,
) -> Result<(), Overflow> {
    direct_path(harness, &["network", "LinkFault", arm], into);
    let mut fields = vec![GeneratedToken::word("position"), GeneratedToken::alone(':')];
    direct_path(harness, &["network", "SendOrdinal", "at"], &mut fields);
    fields.push(GeneratedToken::group(
        GeneratedDelimiter::Parenthesis,
        vec![GeneratedToken::number(u64::from(at))],
    )?);
    fields.extend(extra_fields);
    into.push(GeneratedToken::group(GeneratedDelimiter::Brace, fields)?);
    Ok(())
}

/// One `<harness>::network::Tick::at(<n>)` expression.
fn tick_expr(
    harness: &DirectBinding,
    ordinal: u64,
    into: &mut Vec<GeneratedToken>,
) -> Result<(), Overflow> {
    direct_path(harness, &["network", "Tick", "at"], into);
    into.push(GeneratedToken::group(
        GeneratedDelimiter::Parenthesis,
        vec![GeneratedToken::number(ordinal)],
    )?);
    Ok(())
}

/// One owned generated path at the direct harness binding.
fn harness_path(harness: &DirectBinding, destination: &[&str]) -> Vec<GeneratedToken> {
    let mut tokens = Vec::new();
    direct_path(harness, destination, &mut tokens);
    tokens
}