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 }),
276 ],
277 ..Module::new(Vec::new())
278 };
279 let out = emit_module(&module).expect("specification emits");
280 assert!(
281 out.contains("((__body.len() - __at) as i64)"),
282 "the discriminant is the body the switch can see:\n{out}"
283 );
284 assert!(out.contains("<VelocityForm as ::layline::Choice>::decode_with_nested"), "{out}");
285 assert!(out.contains("fn decode_with_nested("), "{out}");
286 assert!(out.contains(r#"field: "VelocityForm""#), "{out}");
287 }
288
289 #[test]
290 fn a_checksum_may_live_inside_one_arm_of_a_choice() {
291 let module = Module {
292 items: vec![Item::Choice(ChoiceDef {
293 name: "Body".into(),
294 endian: Endian::Le,
295 arms: vec![
296 Arm::new(
297 0,
298 "Bare",
299 vec![Segment::Block(vec![Field::new("seq", Kind::Scalar(Scalar::U(16)))])],
300 ),
301 Arm::new(
302 1,
303 "Checked",
304 vec![
305 Segment::Block(vec![Field::new("seq", Kind::Scalar(Scalar::U(16)))]),
306 Segment::Checksum {
307 stated: None,
308 name: "crc".into(),
309 repr: Scalar::U(16),
310 algorithm: "::wire::Crc16Ccitt".into(),
311 over: Coverage::whole(),
312 doc: None,
313 },
314 ],
315 ),
316 Arm::new(
317 2,
318 "Excised",
319 vec![
320 Segment::Checksum {
321 stated: None,
322 name: "sum".into(),
323 repr: Scalar::U(16),
324 algorithm: "::wire::Sum16NegLe".into(),
325 over: Coverage::whole().to(CoverTo::After("tail".into())),
326 doc: None,
327 },
328 Segment::Repeat {
329 stated: None,
330 collection: Collection::Vec,
331 name: "tail".into(),
332 doc: None,
333 element: Kind::Scalar(Scalar::U(8)),
334 count: Count::Fill { cap: None },
335 at: None,
336 },
337 ],
338 ),
339 ],
340 other: None,
341 other_bytes: None,
342 doc: None,
343 derives: Vec::new(),
344 })],
345 ..Module::new(Vec::new())
346 };
347 let out = emit_module(&module).expect("specification emits");
348 assert!(out.contains("__BodyCk0"), "the arm gets its own one-field layout:\n{out}");
349 assert!(
350 out.contains("&out.written()[__base..]") && out.contains(".get(0..__ck_to)"),
351 "the arm's range starts at the arm's own first byte:\n{out}"
352 );
353 assert!(out.contains("ParseError::Checksum"), "{out}");
354
355 assert!(
356 out.contains("Checksum>::init()") && out.contains("Checksum>::finish("),
357 "an excludes_self range is the fold:\n{out}"
358 );
359 assert!(out.contains("__BodyCk1 { sum: 0 }"), "the reserved bytes:\n{out}");
360 assert!(
361 out.contains("out.written_mut()[__out_sum..__out_sum + 2]"),
362 "…stamped once the range has landed:\n{out}"
363 );
364 assert!(
365 out.contains("const COVERED: &'static [::layline::table::ArmCover<'static>]"),
366 "the checksum column, per arm:\n{out}"
367 );
368 let covered: Vec<&str> =
369 out.split("ArmCover::new(").skip(1).filter_map(|s| s.split('"').nth(1)).collect();
370 assert_eq!(covered, ["Checked", "Excised"], "an arm with no checksum has no row:\n{out}");
371 assert!(out.contains(" true,\n"), "the hole is its own bytes:\n{out}");
372 }
373
374 #[test]
375 fn a_checksum_refuses_a_range_it_cannot_resolve() {
376 let msg = |over: Coverage| MessageDef {
377 name: "Packet".into(),
378 endian: Endian::Le,
379 bits: None,
380 needs: Vec::new(),
381 segments: vec![
382 Segment::Block(vec![Field::new("magic", Kind::Scalar(Scalar::U(16)))]),
383 Segment::Checksum {
384 stated: None,
385 name: "crc".into(),
386 repr: Scalar::U(16),
387 algorithm: "::wire::Crc16Ccitt".into(),
388 over,
389 doc: None,
390 },
391 ],
392 doc: None,
393 derives: Vec::new(),
394 };
395 assert!(matches!(
396 message_parts(&msg(Coverage::from_field("nope")), &Root::default()),
397 Err(Error::Invalid(..)),
398 ));
399 assert!(message_parts(&msg(Coverage::from_field("magic")), &Root::default()).is_ok());
400 assert!(message_parts(&msg(Coverage::whole()), &Root::default()).is_ok());
401 }
402
403 #[test]
404 fn a_checksum_field_may_not_also_be_a_count() {
405 let out = message_parts(
406 &MessageDef {
407 name: "Packet".into(),
408 endian: Endian::Le,
409 bits: None,
410 needs: Vec::new(),
411 segments: vec![
412 Segment::Checksum {
413 stated: None,
414 name: "crc".into(),
415 repr: Scalar::U(16),
416 algorithm: "::wire::Crc16Ccitt".into(),
417 over: Coverage::whole(),
418 doc: None,
419 },
420 Segment::Repeat {
421 stated: None,
422 collection: Collection::Vec,
423 name: "items".into(),
424 element: Kind::Scalar(Scalar::U(8)),
425 count: Count::Field { by: By::field("crc"), cap: None },
426 at: None,
427 doc: None,
428 },
429 ],
430 doc: None,
431 derives: Vec::new(),
432 },
433 &Root::default(),
434 );
435 let Err(err) = out else {
436 panic!("a doubly-derived field must be refused");
437 };
438 let why = err.to_string();
439 assert!(why.contains("crc"), "{why}");
440 }
441
442 #[test]
443 fn a_bool_presence_flag_governs_exactly_one_field() {
444 let opt = |name: &str, kind| Segment::Opt {
445 when: Presence::Flag { field: "head.on".into() },
446 field: Field::new(name, kind),
447 };
448 let msg = |extra: Segment| MessageDef {
449 name: "Packet".into(),
450 endian: Endian::Le,
451 bits: None,
452 needs: Vec::new(),
453 segments: vec![
454 Segment::Block(vec![Field::new(
455 "head",
456 Kind::Nested { ty: "Head".into(), bytes: 1 },
457 )]),
458 opt("a", Kind::Scalar(Scalar::U(8))),
459 extra,
460 ],
461 doc: None,
462 derives: Vec::new(),
463 };
464
465 let out = message_parts(&msg(opt("b", Kind::Scalar(Scalar::U(8)))), &Root::default());
466 let Err(Error::Refused(why)) = out else {
467 panic!("two presence writes over one `bool` must be refused");
468 };
469 assert!(why.contains("is the whole of `a`'s presence flag"), "{why}");
470
471 let out = message_parts(
472 &msg(Segment::Repeat {
473 stated: None,
474 collection: Collection::Vec,
475 name: "items".into(),
476 element: Kind::Scalar(Scalar::U(8)),
477 count: Count::Field { by: By::field("head.on"), cap: None },
478 at: None,
479 doc: None,
480 }),
481 &Root::default(),
482 );
483 assert!(matches!(out, Err(Error::Refused(_))), "a count over a presence flag");
484 }
485
486 #[test]
487 fn a_field_may_not_follow_an_open_ended_switch() {
488 let module = Module {
489 items: vec![
490 Item::Choice(ChoiceDef {
491 name: "Body".into(),
492 endian: Endian::Le,
493 arms: vec![Arm::new(
494 0,
495 "Ping",
496 vec![Segment::Block(vec![Field::new("seq", Kind::Scalar(Scalar::U(16)))])],
497 )],
498 other: Some("Unknown".into()),
499 other_bytes: None,
500 doc: None,
501 derives: Vec::new(),
502 }),
503 Item::Message(MessageDef {
504 name: "Packet".into(),
505 endian: Endian::Le,
506 bits: None,
507 needs: Vec::new(),
508 segments: vec![
509 Segment::Block(vec![Field::new("kind", Kind::Scalar(Scalar::U(8)))]),
510 Segment::Switch {
511 stated: None,
512 name: "body".into(),
513 on: Discriminant::Field("kind".into()),
514 choice: "Body".into(),
515 window: None,
516 doc: None,
517 },
518 Segment::Block(vec![Field::new("trailer", Kind::Scalar(Scalar::U(8)))]),
519 ],
520 doc: None,
521 derives: Vec::new(),
522 }),
523 ],
524 ..Module::new(Vec::new())
525 };
526 assert!(matches!(emit_module(&module), Err(Error::Invalid(_, Invalid::AfterOpenEnd(_)))));
527 }
528}