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