1mod committed;
8mod graph;
9mod verbatim;
10
11use std::fmt::Write as _;
12
13use proc_macro2::TokenStream;
14use quote::quote;
15
16pub use committed::{Change, Committed, Drift, Drifted};
17
18use crate::walk::{emit_choice, emit_dispatch, emit_enum, emit_layout, emit_message};
19use crate::{Derive, Error, Invalid, Item, Root, Spelling};
20
21#[derive(Debug, Clone)]
23#[non_exhaustive]
24pub struct Module {
25 pub doc: Vec<String>,
39 pub uses: Vec<String>,
41 pub derives: Vec<Derive>,
45 pub items: Vec<Item>,
47 pub root: Root,
49}
50
51impl Module {
52 #[must_use]
54 pub fn new(items: Vec<Item>) -> Self {
55 Self {
56 doc: Vec::new(),
57 uses: Vec::new(),
58 derives: Vec::new(),
59 items,
60 root: Root::new(syn::parse_quote!(::layline), Spelling::Bare),
61 }
62 }
63
64 #[must_use]
66 pub fn with_root(self, root: Root) -> Self {
67 Self { root, ..self }
68 }
69
70 #[must_use]
72 pub fn with_doc(self, doc: Vec<String>) -> Self {
73 Self { doc, ..self }
74 }
75
76 #[must_use]
78 pub fn with_uses(self, uses: Vec<String>) -> Self {
79 Self { uses, ..self }
80 }
81
82 #[must_use]
84 pub fn with_derives(self, derives: Vec<Derive>) -> Self {
85 Self { derives, ..self }
86 }
87}
88
89#[derive(Debug, Clone, PartialEq, Eq)]
91#[non_exhaustive]
92pub struct Generated {
93 pub source: String,
95 pub audit: String,
99}
100
101pub fn generate(module: &Module) -> Result<Generated, Error> {
124 let mut audit = String::new();
125 let source = emit_source(module, &mut audit)?;
126 Ok(Generated { source, audit })
127}
128
129fn emit_source(module: &Module, audit: &mut String) -> Result<String, Error> {
130 let root = &module.root;
131 let mut tokens = TokenStream::new();
132
133 for u in &module.uses {
135 syn::parse_str::<syn::ItemUse>(&format!("use {u};")).map_err(|_| {
136 Error::Invalid(
137 String::from("uses"),
138 Invalid::Other(format!(
139 "`{u}` is not a valid `use` path. \
140 Write one path per entry, such as `crate::wire::Head`"
141 )),
142 )
143 })?;
144 }
145
146 if module.items.iter().any(|i| matches!(i, Item::Message(_) | Item::Choice(_))) {
147 tokens.extend(quote! {
148 #[allow(unused_imports)]
150 pub use #root::ParseError;
151 });
152 }
153 let allocates = |i: &Item| match i {
154 Item::Message(_) | Item::Choice(_) => true,
155 Item::Dispatch(d) => d.other_body.is_none(),
156 _ => false,
157 };
158 if module.items.iter().any(allocates) {
159 tokens.extend(quote! {
160 #[allow(unused_imports)]
161 use #root::__private::{Box, String, Vec};
162 });
163 }
164
165 graph::recursion(module)?;
166 let cycles = graph::open_end_cycles(module)?;
167 let cyclic = |name: &str| {
168 cycles.iter().find(|(n, _)| n == name).map_or(&[][..], |(_, members)| members.as_slice())
169 };
170
171 let derives = &module.derives;
172 for item in &module.items {
173 tokens.extend(match item {
174 Item::Enum(e) => emit_enum(e, derives, root)?,
175 Item::Layout(l) => {
176 let code = emit_layout(l, derives, root)?;
177 audit.push_str(&crate::audit::layout(l));
178 code
179 }
180 Item::Dispatch(d) => emit_dispatch(d, derives, root)?,
181 Item::Choice(c) => {
182 let (code, arms) = emit_choice(c, derives, root, cyclic(&c.name))?;
183 audit.push_str(&crate::audit::choice(&c.name, &arms));
184 code
185 }
186 Item::Message(m) => {
187 graph::terminal_switches(module, m)?;
188 let (code, rows) = emit_message(m, derives, root, cyclic(&m.name))?;
189 audit.push_str(&crate::audit::message(&m.name, &m.needs, &rows));
190 code
191 }
192 Item::Verbatim(verbatim) => {
193 verbatim::refuse_codec(verbatim)?;
194 verbatim.clone()
195 }
196 });
197 }
198
199 let body = crate::source::render(tokens)?;
200
201 let mut out = String::new();
202 let _ = writeln!(out, "// @generated by layline-codegen — do not edit.");
203 for line in &module.doc {
204 let _ = writeln!(out, "//! {line}");
205 }
206 let _ = writeln!(out);
207 for u in &module.uses {
208 let _ = writeln!(out, "use {u};");
209 }
210 if !module.uses.is_empty() {
211 let _ = writeln!(out);
212 }
213 out.push_str(&body);
214 Ok(out)
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220 use crate::walk::message_parts;
221 use crate::{
222 Arm, By, ChoiceDef, Collection, Count, CoverTo, Coverage, Discriminant, Endian, Field,
223 Kind, MessageDef, Presence, Scalar, Segment,
224 };
225
226 fn emit_module(module: &Module) -> Result<String, Error> {
227 generate(module).map(|g| g.source)
228 }
229
230 #[test]
231 fn a_switch_may_discriminate_on_body_length() {
232 let module = Module {
233 items: vec![
234 Item::Choice(ChoiceDef {
235 name: "VelocityForm".into(),
236 endian: Endian::Le,
237 arms: vec![
238 Arm::new(
239 16,
240 "F32",
241 vec![Segment::Block(vec![
242 Field::new("velocity", Kind::array(Scalar::F32, 3)),
243 Field::new("sigma", Kind::Scalar(Scalar::F32)),
244 ])],
245 ),
246 Arm::new(
247 24,
248 "F64",
249 vec![Segment::Block(vec![Field::new(
250 "velocity",
251 Kind::array(Scalar::F64, 3),
252 )])],
253 ),
254 ],
255 other: None,
256 other_bytes: None,
257 doc: None,
258 derives: Vec::new(),
259 }),
260 Item::Message(MessageDef {
261 name: "VelocityReport".into(),
262 endian: Endian::Le,
263 bits: None,
264 needs: Vec::new(),
265 segments: vec![Segment::Switch {
266 stated: None,
267 name: "form".into(),
268 on: Discriminant::BodyLength,
269 choice: "VelocityForm".into(),
270 window: None,
271 doc: None,
272 }],
273 doc: None,
274 derives: Vec::new(),
275 lifetime: None,
276 }),
277 ],
278 ..Module::new(Vec::new())
279 };
280 let out = emit_module(&module).expect("specification emits");
281 assert!(
282 out.contains("((__body.len() - __at) as i64)"),
283 "the discriminant is the body the switch can see:\n{out}"
284 );
285 assert!(out.contains("<VelocityForm as ::layline::Choice>::decode_with_nested"), "{out}");
286 assert!(out.contains("fn decode_with_nested("), "{out}");
287 assert!(out.contains(r#"field: "VelocityForm""#), "{out}");
288 }
289
290 #[test]
291 fn a_checksum_may_live_inside_one_arm_of_a_choice() {
292 let module = Module {
293 items: vec![Item::Choice(ChoiceDef {
294 name: "Body".into(),
295 endian: Endian::Le,
296 arms: vec![
297 Arm::new(
298 0,
299 "Bare",
300 vec![Segment::Block(vec![Field::new("seq", Kind::Scalar(Scalar::U(16)))])],
301 ),
302 Arm::new(
303 1,
304 "Checked",
305 vec![
306 Segment::Block(vec![Field::new("seq", Kind::Scalar(Scalar::U(16)))]),
307 Segment::Checksum {
308 stated: None,
309 name: "crc".into(),
310 repr: Scalar::U(16),
311 algorithm: "::wire::Crc16Ccitt".into(),
312 over: Coverage::whole(),
313 doc: None,
314 },
315 ],
316 ),
317 Arm::new(
318 2,
319 "Excised",
320 vec![
321 Segment::Checksum {
322 stated: None,
323 name: "sum".into(),
324 repr: Scalar::U(16),
325 algorithm: "::wire::Sum16NegLe".into(),
326 over: Coverage::whole().to(CoverTo::After("tail".into())),
327 doc: None,
328 },
329 Segment::Repeat {
330 stated: None,
331 collection: Collection::Vec,
332 name: "tail".into(),
333 doc: None,
334 element: Kind::Scalar(Scalar::U(8)),
335 count: Count::Fill { cap: None },
336 at: None,
337 },
338 ],
339 ),
340 ],
341 other: None,
342 other_bytes: None,
343 doc: None,
344 derives: Vec::new(),
345 })],
346 ..Module::new(Vec::new())
347 };
348 let out = emit_module(&module).expect("specification emits");
349 assert!(out.contains("__BodyCk0"), "the arm gets its own one-field layout:\n{out}");
350 assert!(
351 out.contains("&out.written()[__base..]") && out.contains(".get(0..__ck_to)"),
352 "the arm's range starts at the arm's own first byte:\n{out}"
353 );
354 assert!(out.contains("ParseError::Checksum"), "{out}");
355
356 assert!(
357 out.contains("Checksum>::init()") && out.contains("Checksum>::finish("),
358 "an excludes_self range is the fold:\n{out}"
359 );
360 assert!(out.contains("__BodyCk1 { sum: 0 }"), "the reserved bytes:\n{out}");
361 assert!(
362 out.contains("out.written_mut()[__out_sum..__out_sum + 2]"),
363 "…stamped once the range has landed:\n{out}"
364 );
365 assert!(
366 out.contains("const COVERED: &'static [::layline::table::ArmCover<'static>]"),
367 "the checksum column, per arm:\n{out}"
368 );
369 let covered: Vec<&str> =
370 out.split("ArmCover::new(").skip(1).filter_map(|s| s.split('"').nth(1)).collect();
371 assert_eq!(covered, ["Checked", "Excised"], "an arm with no checksum has no row:\n{out}");
372 assert!(out.contains(" true,\n"), "the hole is its own bytes:\n{out}");
373 }
374
375 #[test]
376 fn a_checksum_refuses_a_range_it_cannot_resolve() {
377 let msg = |over: Coverage| MessageDef {
378 name: "Packet".into(),
379 endian: Endian::Le,
380 bits: None,
381 needs: Vec::new(),
382 segments: vec![
383 Segment::Block(vec![Field::new("magic", Kind::Scalar(Scalar::U(16)))]),
384 Segment::Checksum {
385 stated: None,
386 name: "crc".into(),
387 repr: Scalar::U(16),
388 algorithm: "::wire::Crc16Ccitt".into(),
389 over,
390 doc: None,
391 },
392 ],
393 doc: None,
394 derives: Vec::new(),
395 lifetime: None,
396 };
397 assert!(matches!(
398 message_parts(&msg(Coverage::from_field("nope")), &[], &Root::default()),
399 Err(Error::Invalid(..)),
400 ));
401 assert!(message_parts(&msg(Coverage::from_field("magic")), &[], &Root::default()).is_ok());
402 assert!(message_parts(&msg(Coverage::whole()), &[], &Root::default()).is_ok());
403 }
404
405 #[test]
406 fn a_checksum_field_may_not_also_be_a_count() {
407 let out = message_parts(
408 &MessageDef {
409 name: "Packet".into(),
410 endian: Endian::Le,
411 bits: None,
412 needs: Vec::new(),
413 segments: vec![
414 Segment::Checksum {
415 stated: None,
416 name: "crc".into(),
417 repr: Scalar::U(16),
418 algorithm: "::wire::Crc16Ccitt".into(),
419 over: Coverage::whole(),
420 doc: None,
421 },
422 Segment::Repeat {
423 stated: None,
424 collection: Collection::Vec,
425 name: "items".into(),
426 element: Kind::Scalar(Scalar::U(8)),
427 count: Count::Field { by: By::field("crc"), cap: None },
428 at: None,
429 doc: None,
430 },
431 ],
432 doc: None,
433 derives: Vec::new(),
434 lifetime: None,
435 },
436 &[],
437 &Root::default(),
438 );
439 let Err(err) = out else {
440 panic!("a doubly-derived field must be refused");
441 };
442 let why = err.to_string();
443 assert!(why.contains("crc"), "{why}");
444 }
445
446 #[test]
447 fn a_bool_presence_flag_governs_exactly_one_field() {
448 let opt = |name: &str, kind| Segment::Opt {
449 when: Presence::Flag { field: "head.on".into() },
450 field: Field::new(name, kind),
451 };
452 let msg = |extra: Segment| MessageDef {
453 name: "Packet".into(),
454 endian: Endian::Le,
455 bits: None,
456 needs: Vec::new(),
457 segments: vec![
458 Segment::Block(vec![Field::new(
459 "head",
460 Kind::Nested { ty: "Head".into(), bytes: 1 },
461 )]),
462 opt("a", Kind::Scalar(Scalar::U(8))),
463 extra,
464 ],
465 doc: None,
466 derives: Vec::new(),
467 lifetime: None,
468 };
469
470 let out = message_parts(&msg(opt("b", Kind::Scalar(Scalar::U(8)))), &[], &Root::default());
471 let Err(Error::Refused(why)) = out else {
472 panic!("two presence writes over one `bool` must be refused");
473 };
474 assert!(why.contains("is the whole of `a`'s presence flag"), "{why}");
475
476 let out = message_parts(
477 &msg(Segment::Repeat {
478 stated: None,
479 collection: Collection::Vec,
480 name: "items".into(),
481 element: Kind::Scalar(Scalar::U(8)),
482 count: Count::Field { by: By::field("head.on"), cap: None },
483 at: None,
484 doc: None,
485 }),
486 &[],
487 &Root::default(),
488 );
489 assert!(matches!(out, Err(Error::Refused(_))), "a count over a presence flag");
490 }
491
492 #[test]
493 fn a_field_may_not_follow_an_open_ended_switch() {
494 let module = Module {
495 items: vec![
496 Item::Choice(ChoiceDef {
497 name: "Body".into(),
498 endian: Endian::Le,
499 arms: vec![Arm::new(
500 0,
501 "Ping",
502 vec![Segment::Block(vec![Field::new("seq", Kind::Scalar(Scalar::U(16)))])],
503 )],
504 other: Some("Unknown".into()),
505 other_bytes: None,
506 doc: None,
507 derives: Vec::new(),
508 }),
509 Item::Message(MessageDef {
510 name: "Packet".into(),
511 endian: Endian::Le,
512 bits: None,
513 needs: Vec::new(),
514 segments: vec![
515 Segment::Block(vec![Field::new("kind", Kind::Scalar(Scalar::U(8)))]),
516 Segment::Switch {
517 stated: None,
518 name: "body".into(),
519 on: Discriminant::Field("kind".into()),
520 choice: "Body".into(),
521 window: None,
522 doc: None,
523 },
524 Segment::Block(vec![Field::new("trailer", Kind::Scalar(Scalar::U(8)))]),
525 ],
526 doc: None,
527 derives: Vec::new(),
528 lifetime: None,
529 }),
530 ],
531 ..Module::new(Vec::new())
532 };
533 assert!(matches!(emit_module(&module), Err(Error::Invalid(_, Invalid::AfterOpenEnd(_)))));
534 }
535}