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