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
//! Reading one authored network declaration out of a typed token tree.
//!
//! # The authored grammar
//!
//! ```text
//! <helper>! {
//!     harness = <dependency path>,
//!     module = <ident>,
//!     namespace = "<owner>",
//!     nodes = [<ident>, ...],
//!     link <ident> = <node> to <node>,
//!     schedule <ident> = [<fault phrase>, ...],
//! }
//! ```
//!
//! Clause order is free and is read by key; roster order is meaning and is preserved.
//! The reading walks the clauses in passes — the names first, then the links against the nodes, then the schedules against the links — so every clause may stand wherever its author put it.

use super::render::RESERVED;
use super::{
    DisciplineRow, FaultRow, LinkRow, NetworkCaptureError, NetworkDeclaration, ScheduleRow,
};
use crate::descriptor::DirectBinding;
use crate::descriptor::clause::{
    assigned_identifier, assigned_text, binding_once, comma_groups, fill_once, opening, value_of,
};
use crate::descriptor::{CaptureCause, Grammar};
use crate::token::{
    CapturedDelimiter, CapturedInput, CapturedTokenTree, SpanHandle, rendered_identifier,
    rust_keyword,
};

/// Read one network payload out of the declaration's body.
///
/// # Errors
///
/// Returns [`NetworkCaptureError`] where the tokens do not say a network declaration — an absent or unreadable binding, an unreadable clause, an undeclared key, a doubled name, a separator separating nothing, a link drawn to an undeclared node, a phrase on an undrawn link, a phrase this grammar cannot read, a number past its seat's width, a name the language or the generated module already owns — each at the token it was established at, and an absent required clause at the declaration's opening.
pub fn declared(
    body: &CapturedInput,
    grammar: Grammar,
) -> Result<NetworkDeclaration, NetworkCaptureError> {
    let groups = comma_groups(grammar, body.trees(), refused)?;
    let world = world_of(grammar, &groups)?;
    let mut schedules: Vec<ScheduleRow> = Vec::new();
    for group in &groups {
        if head_word(group) == Some("schedule") {
            let schedule = schedule_of(grammar, group, &world)?;
            if schedules.iter().any(|held| held.name() == schedule.name()) {
                return Err(refused(
                    grammar,
                    CaptureCause::ChoiceDoubled,
                    opening(group),
                ));
            }
            schedules.push(schedule);
        }
    }
    Ok(NetworkDeclaration::read(
        world.harness,
        world.module,
        world.namespace,
        world.nodes,
        world.links,
        schedules,
    ))
}

/// One established grammar refusal at one token.
const fn refused(grammar: Grammar, cause: CaptureCause, at: SpanHandle) -> NetworkCaptureError {
    NetworkCaptureError::grammar_refused(grammar, cause, at)
}

/// The declaration's world: everything a schedule is read against.
struct World {
    /// The physical path to the harness vocabulary this projection targets.
    harness: DirectBinding,
    /// The module the builders land in.
    module: String,
    /// The namespace every declared name is owned under.
    namespace: String,
    /// The node spellings, in authored order.
    nodes: Vec<String>,
    /// The links, in authored order.
    links: Vec<LinkRow>,
}

/// The word one group opens with, where it opens with one.
fn head_word<'trees>(group: &[&'trees CapturedTokenTree]) -> Option<&'trees str> {
    group.first().and_then(|tree| tree.word())
}

/// Read the world out of every non-schedule clause, refusing what these passes can already judge.
fn world_of(
    grammar: Grammar,
    groups: &[Vec<&CapturedTokenTree>],
) -> Result<World, NetworkCaptureError> {
    let mut module: Option<String> = None;
    let mut namespace: Option<String> = None;
    let mut nodes: Option<Vec<String>> = None;
    let mut harness: Option<DirectBinding> = None;
    for group in groups {
        match head_word(group) {
            Some("harness") => binding_once(
                grammar,
                group,
                &mut harness,
                refused,
                NetworkCaptureError::binding_refused,
            )?,
            Some("module") => {
                fill_once(grammar, group, &mut module, assigned_identifier, refused)?;
            }
            Some("namespace") => {
                fill_once(grammar, group, &mut namespace, assigned_text, refused)?;
            }
            Some("nodes") => read_nodes(grammar, group, &mut nodes)?,
            Some("link" | "schedule") => {}
            Some(_) => {
                return Err(refused(
                    grammar,
                    CaptureCause::ClauseUndeclared,
                    opening(group),
                ));
            }
            None => return Err(refused(grammar, CaptureCause::ClauseUnread, opening(group))),
        }
    }
    let Some(nodes) = nodes else {
        return Err(refused(
            grammar,
            CaptureCause::ClauseAbsent,
            SpanHandle::at(0),
        ));
    };
    let Some(harness) = harness else {
        return Err(refused(
            grammar,
            CaptureCause::ClauseAbsent,
            SpanHandle::at(0),
        ));
    };
    let mut links: Vec<LinkRow> = Vec::new();
    for group in groups {
        if head_word(group) == Some("link") {
            let link = link_of(grammar, group, &nodes)?;
            if links.iter().any(|held| held.name() == link.name()) {
                return Err(refused(
                    grammar,
                    CaptureCause::ChoiceDoubled,
                    opening(group),
                ));
            }
            links.push(link);
        }
    }
    let Some(module) = module else {
        return Err(refused(
            grammar,
            CaptureCause::ClauseAbsent,
            SpanHandle::at(0),
        ));
    };
    let Some(namespace) = namespace else {
        return Err(refused(
            grammar,
            CaptureCause::ClauseAbsent,
            SpanHandle::at(0),
        ));
    };
    if links.is_empty() {
        return Err(refused(
            grammar,
            CaptureCause::ClauseAbsent,
            SpanHandle::at(0),
        ));
    }
    Ok(World {
        harness,
        module,
        namespace,
        nodes,
        links,
    })
}

/// Read the node roster, refusing a repeated spelling at its own token.
///
/// An authored `nodes = []` refuses at its own bracket as choosing nothing, so an empty first statement never stands to vanish under a second — and a doubled clause refuses at its own opening, marked by the seat a lawful first clause filled.
/// The commas are grammar rather than noise: two names with no separator between them are one phrase this roster does not read, refused at the second name.
fn read_nodes(
    grammar: Grammar,
    group: &[&CapturedTokenTree],
    nodes: &mut Option<Vec<String>>,
) -> Result<(), NetworkCaptureError> {
    if nodes.is_some() {
        return Err(refused(
            grammar,
            CaptureCause::ClauseDoubled,
            opening(group),
        ));
    }
    let [roster] = value_of(group) else {
        return Err(refused(grammar, CaptureCause::RosterUnread, opening(group)));
    };
    let Some((CapturedDelimiter::Bracket, members)) = roster.group() else {
        return Err(refused(grammar, CaptureCause::RosterUnread, roster.span()));
    };
    let mut declared: Vec<String> = Vec::new();
    let mut separated = true;
    for member in members {
        if separated {
            let Some(word) = member.word() else {
                return Err(refused(grammar, CaptureCause::ChoiceUnread, member.span()));
            };
            if declared.iter().any(|held| held == word) {
                return Err(refused(grammar, CaptureCause::ChoiceDoubled, member.span()));
            }
            declared.push(word.to_owned());
            separated = false;
        } else {
            if member.punct() != Some(',') {
                return Err(refused(grammar, CaptureCause::ChoiceUnread, member.span()));
            }
            separated = true;
        }
    }
    if declared.is_empty() {
        return Err(refused(grammar, CaptureCause::NothingChosen, roster.span()));
    }
    *nodes = Some(declared);
    Ok(())
}

/// Read one `link <name> = <from> to <to>` clause against the declared nodes.
fn link_of(
    grammar: Grammar,
    group: &[&CapturedTokenTree],
    nodes: &[String],
) -> Result<LinkRow, NetworkCaptureError> {
    let [_link, name_tree, assigned_by, from_tree, to_word, to_tree] = group else {
        return Err(refused(grammar, CaptureCause::ClauseUnread, opening(group)));
    };
    if assigned_by.punct() != Some('=') || to_word.word() != Some("to") {
        return Err(refused(grammar, CaptureCause::ClauseUnread, opening(group)));
    }
    let (Some(name), Some(from), Some(to)) = (name_tree.word(), from_tree.word(), to_tree.word())
    else {
        return Err(refused(grammar, CaptureCause::ClauseUnread, opening(group)));
    };
    if !nodes.iter().any(|held| held == from) {
        return Err(refused(
            grammar,
            CaptureCause::EndpointUnknown,
            from_tree.span(),
        ));
    }
    if !nodes.iter().any(|held| held == to) {
        return Err(refused(
            grammar,
            CaptureCause::EndpointUnknown,
            to_tree.span(),
        ));
    }
    Ok(LinkRow::drawn(
        name.to_owned(),
        from.to_owned(),
        to.to_owned(),
    ))
}

/// Read one `schedule <name> = [<phrases>]` clause against the drawn links.
fn schedule_of(
    grammar: Grammar,
    group: &[&CapturedTokenTree],
    world: &World,
) -> Result<ScheduleRow, NetworkCaptureError> {
    let [_schedule, name_tree, assigned_by, roster] = group else {
        return Err(refused(grammar, CaptureCause::ClauseUnread, opening(group)));
    };
    let Some(name) = name_tree.word() else {
        return Err(refused(
            grammar,
            CaptureCause::ClauseUnread,
            name_tree.span(),
        ));
    };
    if !rendered_identifier(name) {
        return Err(refused(
            grammar,
            CaptureCause::ClauseUnread,
            name_tree.span(),
        ));
    }
    if rust_keyword(name) || RESERVED.contains(&name) {
        return Err(refused(
            grammar,
            CaptureCause::NameReserved,
            name_tree.span(),
        ));
    }
    if assigned_by.punct() != Some('=') {
        return Err(refused(grammar, CaptureCause::ClauseUnread, opening(group)));
    }
    let Some((CapturedDelimiter::Bracket, members)) = roster.group() else {
        return Err(refused(grammar, CaptureCause::RosterUnread, roster.span()));
    };
    let mut disciplines: Vec<DisciplineRow> = Vec::new();
    for phrase in &comma_groups(grammar, members, refused)? {
        let (link, fault) = phrase_of(grammar, phrase, world)?;
        match disciplines
            .iter_mut()
            .find(|held| held.link().name() == link.name())
        {
            Some(discipline) => discipline.push(fault),
            None => disciplines.push(DisciplineRow::gathered(link, vec![fault])),
        }
    }
    Ok(ScheduleRow::declared(name.to_owned(), disciplines))
}

/// Read one fault phrase against the drawn links, handing back the resolved link beside the fault.
fn phrase_of(
    grammar: Grammar,
    phrase: &[&CapturedTokenTree],
    world: &World,
) -> Result<(LinkRow, FaultRow), NetworkCaptureError> {
    let (link_tree, fault) = match phrase {
        [verb, link, at_word, at]
            if verb.word() == Some("drop") && at_word.word() == Some("at") =>
        {
            (
                link,
                FaultRow::Drop {
                    at: ordinal_of(grammar, at)?,
                },
            )
        }
        [verb, link, at_word, at]
            if verb.word() == Some("duplicate") && at_word.word() == Some("at") =>
        {
            (
                link,
                FaultRow::Duplicate {
                    at: ordinal_of(grammar, at)?,
                },
            )
        }
        [verb, link, at_word, at, by_word, by]
            if verb.word() == Some("delay")
                && at_word.word() == Some("at")
                && by_word.word() == Some("by") =>
        {
            (
                link,
                FaultRow::Delay {
                    at: ordinal_of(grammar, at)?,
                    by: ordinal_of(grammar, by)?,
                },
            )
        }
        [verb, link, from_word, from, until_word, until]
            if verb.word() == Some("partition")
                && from_word.word() == Some("from")
                && until_word.word() == Some("until") =>
        {
            (
                link,
                FaultRow::Partition {
                    from: number_of(grammar, from)?,
                    until: number_of(grammar, until)?,
                },
            )
        }
        _unread => {
            return Err(refused(
                grammar,
                CaptureCause::PhraseUnread,
                opening(phrase),
            ));
        }
    };
    let Some(link) = link_tree.word() else {
        return Err(refused(
            grammar,
            CaptureCause::PhraseUnread,
            link_tree.span(),
        ));
    };
    world
        .links
        .iter()
        .find(|held| held.name() == link)
        .cloned()
        .map(|resolved| (resolved, fault))
        .ok_or_else(|| refused(grammar, CaptureCause::EndpointUnknown, link_tree.span()))
}

/// The one unsigned number a tick seat states, at the tick's sixty-four-bit width.
fn number_of(grammar: Grammar, tree: &CapturedTokenTree) -> Result<u64, NetworkCaptureError> {
    let digits = tree
        .number()
        .ok_or_else(|| refused(grammar, CaptureCause::PhraseUnread, tree.span()))?;
    digits
        .parse::<u64>()
        .map_err(|_beyond| refused(grammar, CaptureCause::NumberBeyondSeat, tree.span()))
}

/// The one unsigned number an ordinal or span seat states, at those seats' thirty-two-bit width.
///
/// Parsed at exactly the seat's width so a number past it refuses HERE, at the authored token: generated code cannot outsource the range to rustc, whose overflowing-literal diagnostic is suppressed inside a foreign macro expansion and whose out-of-range literal wraps silently.
fn ordinal_of(grammar: Grammar, tree: &CapturedTokenTree) -> Result<u32, NetworkCaptureError> {
    let digits = tree
        .number()
        .ok_or_else(|| refused(grammar, CaptureCause::PhraseUnread, tree.span()))?;
    digits
        .parse::<u32>()
        .map_err(|_beyond| refused(grammar, CaptureCause::NumberBeyondSeat, tree.span()))
}