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