diff --git a/pdl-compiler/src/analyzer.rs b/pdl-compiler/src/analyzer.rs index cd446997..e1aa37e5 100644 --- a/pdl-compiler/src/analyzer.rs +++ b/pdl-compiler/src/analyzer.rs @@ -220,11 +220,7 @@ impl Diagnostics { } fn err_or(self, value: T) -> Result { - if self.is_empty() { - Ok(value) - } else { - Err(self) - } + if self.is_empty() { Ok(value) } else { Err(self) } } pub fn emit( @@ -268,11 +264,7 @@ impl<'d> Scope<'d> { } // Return failure if any diagnostic is raised. - if diagnostics.is_empty() { - Ok(scope) - } else { - Err(diagnostics) - } + if diagnostics.is_empty() { Ok(scope) } else { Err(diagnostics) } } /// Iterate over the child declarations of the selected declaration. @@ -447,11 +439,7 @@ impl Schema { } _ => false, }); - if has_payload_size { - Size::Dynamic - } else { - Size::Unknown - } + if has_payload_size { Size::Dynamic } else { Size::Unknown } } FieldDesc::Typedef { type_id, .. } | FieldDesc::FixedEnum { enum_id: type_id, .. } @@ -478,11 +466,7 @@ impl Schema { } _ => false, }); - if has_array_size { - Size::Dynamic - } else { - Size::Unknown - } + if has_array_size { Size::Dynamic } else { Size::Unknown } } FieldDesc::Array { .. } => unreachable!(), }; @@ -576,11 +560,7 @@ fn bit_width(value: usize) -> usize { /// Return the maximum value for a scalar value. fn scalar_max(width: usize) -> usize { - if width >= usize::BITS as usize { - usize::MAX - } else { - (1 << width) - 1 - } + if width >= usize::BITS as usize { usize::MAX } else { (1 << width) - 1 } } /// Check declaration identifiers. @@ -1650,7 +1630,7 @@ fn check_optional_fields(file: &File) -> Result<(), Diagnostics> { )), ]) .with_notes(vec![ - "note: expected scalar field identifier".to_owned() + "note: expected scalar field identifier".to_owned(), ]), ), Some(Field { loc, .. }) => diagnostics.push( @@ -3410,8 +3390,8 @@ mod test { ); } - use analyzer::Size; use Size::*; + use analyzer::Size; #[derive(Debug, PartialEq, Eq)] struct Annotations { diff --git a/pdl-compiler/src/backends/common/alignment.rs b/pdl-compiler/src/backends/common/alignment.rs index 4143aa02..d77ab5c9 100644 --- a/pdl-compiler/src/backends/common/alignment.rs +++ b/pdl-compiler/src/backends/common/alignment.rs @@ -94,7 +94,10 @@ impl ByteAligner { self.staged_fields.push(Field { offset: self.staged_width, symbol, width }); self.staged_width += width; if self.staged_width > Self::MAX_CHUNK_WIDTH { - panic!("total field width grew beyond max chunk width of {} before aligning to a byte boundary", Self::MAX_CHUNK_WIDTH) + panic!( + "total field width grew beyond max chunk width of {} before aligning to a byte boundary", + Self::MAX_CHUNK_WIDTH + ) } self.try_commit_staged_chunk(); } diff --git a/pdl-compiler/src/backends/java/codegen/enum.rs b/pdl-compiler/src/backends/java/codegen/enum.rs index 1fb887d0..f43acee9 100644 --- a/pdl-compiler/src/backends/java/codegen/enum.rs +++ b/pdl-compiler/src/backends/java/codegen/enum.rs @@ -14,14 +14,14 @@ use std::iter; -use genco::{lang::Java, quote, tokens::quoted, Tokens}; +use genco::{Tokens, lang::Java, quote, tokens::quoted}; use heck::ToUpperCamelCase; use crate::{ ast::{Tag, TagOther, TagRange, TagValue}, backends::java::{ - codegen::expr::{cast_symbol, literal, ExprTree}, Integral, + codegen::expr::{ExprTree, cast_symbol, literal}, }, }; diff --git a/pdl-compiler/src/backends/java/codegen/expr.rs b/pdl-compiler/src/backends/java/codegen/expr.rs index 8bf3630a..33514f97 100644 --- a/pdl-compiler/src/backends/java/codegen/expr.rs +++ b/pdl-compiler/src/backends/java/codegen/expr.rs @@ -14,7 +14,7 @@ use std::{cell::RefCell, cmp::max}; -use genco::{lang::Java, quote, quote_in, tokens::FormatInto, Tokens}; +use genco::{Tokens, lang::Java, quote, quote_in, tokens::FormatInto}; use crate::backends::java::Integral; @@ -140,11 +140,7 @@ impl ExprTree { } pub fn sub(&self, lhs: ExprId, rhs: ExprId) -> ExprId { - if self.is_literal(rhs, 0) { - lhs - } else { - self.op(lhs, BinOp::Sub, rhs) - } + if self.is_literal(rhs, 0) { lhs } else { self.op(lhs, BinOp::Sub, rhs) } } pub fn mul(&self, lhs: ExprId, rhs: ExprId) -> ExprId { @@ -158,11 +154,7 @@ impl ExprTree { } pub fn div(&self, lhs: ExprId, rhs: ExprId) -> ExprId { - if self.is_literal(rhs, 1) { - lhs - } else { - self.op(lhs, BinOp::Divide, rhs) - } + if self.is_literal(rhs, 1) { lhs } else { self.op(lhs, BinOp::Divide, rhs) } } pub fn lshift(&self, lhs: ExprId, rhs: ExprId) -> ExprId { diff --git a/pdl-compiler/src/backends/java/codegen/mod.rs b/pdl-compiler/src/backends/java/codegen/mod.rs index 0a00d36d..63697225 100644 --- a/pdl-compiler/src/backends/java/codegen/mod.rs +++ b/pdl-compiler/src/backends/java/codegen/mod.rs @@ -14,11 +14,10 @@ use core::panic; use genco::{ - self, - prelude::{java, Java}, + self, Tokens, + prelude::{Java, java}, quote, quote_in, tokens::FormatInto, - Tokens, }; use std::collections::HashMap; @@ -41,12 +40,12 @@ pub mod expr; mod packet; use crate::backends::java::{ - codegen::expr::{cast_symbol, ExprId, ExprTree}, - inheritance::{ClassHeirarchy, Constraint}, Context, Field, WidthField, + codegen::expr::{ExprId, ExprTree, cast_symbol}, + inheritance::{ClassHeirarchy, Constraint}, }; -use super::{import, Chunk, Class, EndiannessValue, Integral, JavaFile, PacketDef}; +use super::{Chunk, Class, EndiannessValue, Integral, JavaFile, PacketDef, import}; impl JavaFile<&Context> for Class { fn generate(self, context: &Context) -> Tokens { @@ -274,7 +273,9 @@ impl Field { Integral::fitting(width), ), _ => { - panic!("Bitfields ending in 'size' or 'count' are not supported. Use _size_ or _count_ instead.") + panic!( + "Bitfields ending in 'size' or 'count' are not supported. Use _size_ or _count_ instead." + ) } } } else if let Field::Integral { width: 1, .. } = self { diff --git a/pdl-compiler/src/backends/java/codegen/packet.rs b/pdl-compiler/src/backends/java/codegen/packet.rs index 3ea5d7d6..8d783c24 100644 --- a/pdl-compiler/src/backends/java/codegen/packet.rs +++ b/pdl-compiler/src/backends/java/codegen/packet.rs @@ -14,7 +14,7 @@ use std::collections::{BTreeMap, HashMap}; -use genco::{self, prelude::Java, quote, tokens::quoted, Tokens}; +use genco::{self, Tokens, prelude::Java, quote, tokens::quoted}; use heck::{self, ToLowerCamelCase, ToUpperCamelCase}; use crate::{ @@ -22,14 +22,14 @@ use crate::{ backends::{ common::alignment::Alignment, java::{ + Context, Field, WidthField, codegen::expr::ExprId, inheritance::{ClassHeirarchy, Constraint, InheritanceNode}, - Context, Field, WidthField, }, }, }; -use super::{expr::ExprTree, import, Chunk, Integral, PacketDef}; +use super::{Chunk, Integral, PacketDef, expr::ExprTree, import}; pub fn gen_packet(name: &String, def: &PacketDef, ctx: &Context) -> Tokens { let endianness = ctx.endianness; diff --git a/pdl-compiler/src/backends/java/inheritance.rs b/pdl-compiler/src/backends/java/inheritance.rs index 761a9119..725607ae 100644 --- a/pdl-compiler/src/backends/java/inheritance.rs +++ b/pdl-compiler/src/backends/java/inheritance.rs @@ -34,11 +34,7 @@ pub struct InheritanceNode { impl InheritanceNode { pub fn field_width(&self) -> Option { - if self.dyn_fields.is_empty() { - Some(self.static_field_width) - } else { - None - } + if self.dyn_fields.is_empty() { Some(self.static_field_width) } else { None } } } diff --git a/pdl-compiler/src/backends/java/mod.rs b/pdl-compiler/src/backends/java/mod.rs index 053ceef3..3b69d22c 100644 --- a/pdl-compiler/src/backends/java/mod.rs +++ b/pdl-compiler/src/backends/java/mod.rs @@ -13,10 +13,9 @@ // limitations under the License. use genco::{ - self, - prelude::{java, Java}, + self, Tokens, + prelude::{Java, java}, tokens::FormatInto, - Tokens, }; use heck::{self, ToLowerCamelCase, ToUpperCamelCase}; use std::{ diff --git a/pdl-compiler/src/backends/java/preamble.rs b/pdl-compiler/src/backends/java/preamble.rs index 78e87f31..561374ed 100644 --- a/pdl-compiler/src/backends/java/preamble.rs +++ b/pdl-compiler/src/backends/java/preamble.rs @@ -12,11 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -use genco::{lang::Java, quote, Tokens}; +use genco::{Tokens, lang::Java, quote}; use crate::{ ast::EndiannessValue, - backends::java::{codegen::expr::ExprTree, import, Integral, JavaFile}, + backends::java::{Integral, JavaFile, codegen::expr::ExprTree, import}, }; pub struct Utils; diff --git a/pdl-compiler/src/backends/java/test.rs b/pdl-compiler/src/backends/java/test.rs index 7533db96..bf451090 100644 --- a/pdl-compiler/src/backends/java/test.rs +++ b/pdl-compiler/src/backends/java/test.rs @@ -13,11 +13,11 @@ // limitations under the License. use genco::{ + Tokens, lang::Java, prelude::{java, quote_fn}, quote, - tokens::{quoted, FormatInto}, - Tokens, + tokens::{FormatInto, quoted}, }; use heck::ToUpperCamelCase; use serde_json::{Map, Value}; @@ -29,7 +29,7 @@ use std::{ str, }; -use super::{import, Class, Integral, JavaFile}; +use super::{Class, Integral, JavaFile, import}; use crate::{ ast::{self, Decl, DeclDesc, Field, FieldDesc}, backends::{ diff --git a/pdl-compiler/src/backends/rust/decoder.rs b/pdl-compiler/src/backends/rust/decoder.rs index 42e4d34b..1938018c 100644 --- a/pdl-compiler/src/backends/rust/decoder.rs +++ b/pdl-compiler/src/backends/rust/decoder.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::backends::rust::{mask_bits, types, ToIdent, ToUpperCamelCase}; +use crate::backends::rust::{ToIdent, ToUpperCamelCase, mask_bits, types}; use crate::{analyzer, ast}; use quote::{format_ident, quote}; diff --git a/pdl-compiler/src/backends/rust/encoder.rs b/pdl-compiler/src/backends/rust/encoder.rs index d7f5c783..4e7b21a3 100644 --- a/pdl-compiler/src/backends/rust/encoder.rs +++ b/pdl-compiler/src/backends/rust/encoder.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::backends::rust::{mask_bits, types, ToIdent, ToUpperCamelCase}; +use crate::backends::rust::{ToIdent, ToUpperCamelCase, mask_bits, types}; use crate::{analyzer, ast}; use quote::{format_ident, quote}; diff --git a/pdl-compiler/src/backends/rust/mod.rs b/pdl-compiler/src/backends/rust/mod.rs index 6e67175c..9df40b56 100644 --- a/pdl-compiler/src/backends/rust/mod.rs +++ b/pdl-compiler/src/backends/rust/mod.rs @@ -351,7 +351,7 @@ fn generate_specialize_impl( case.id.clone(), ) { Some(id) if id != case.id => { - return Err(format!("{} and {} cannot be disambiguated", id, case.id)) + return Err(format!("{} and {} cannot be disambiguated", id, case.id)); } _ => (), } @@ -997,11 +997,7 @@ fn generate_enum_decl(id: &str, tags: &[ast::Tag], width: usize) -> proc_macro2: ranges.first().unwrap().0 == 0 && ranges.last().unwrap().1 == max && ranges.windows(2).all(|window| { - if let [left, right] = window { - left.1 == right.0 - 1 - } else { - false - } + if let [left, right] = window { left.1 == right.0 - 1 } else { false } }) } @@ -1012,11 +1008,7 @@ fn generate_enum_decl(id: &str, tags: &[ast::Tag], width: usize) -> proc_macro2: // Return the maximum value for the scalar type. fn scalar_max(width: usize) -> usize { - if width >= usize::BITS as usize { - usize::MAX - } else { - (1 << width) - 1 - } + if width >= usize::BITS as usize { usize::MAX } else { (1 << width) - 1 } } // Format an enum tag identifier to rust upper caml case. diff --git a/pdl-compiler/src/backends/rust/types.rs b/pdl-compiler/src/backends/rust/types.rs index 5c30d106..1d678e71 100644 --- a/pdl-compiler/src/backends/rust/types.rs +++ b/pdl-compiler/src/backends/rust/types.rs @@ -92,11 +92,7 @@ pub fn rust_type(field: &ast::Field) -> proc_macro2::TokenStream { /// Suffix for `Buf::get_*` and `BufMut::put_*` methods when reading a /// value with the given `width`. fn endianness_suffix(endianness: ast::EndiannessValue, width: usize) -> &'static str { - if width > 8 && endianness == ast::EndiannessValue::LittleEndian { - "_le" - } else { - "" - } + if width > 8 && endianness == ast::EndiannessValue::LittleEndian { "_le" } else { "" } } /// Parse an unsigned integer with the given `width`. diff --git a/pdl-compiler/src/main.rs b/pdl-compiler/src/main.rs index 6c2a329a..968b5313 100644 --- a/pdl-compiler/src/main.rs +++ b/pdl-compiler/src/main.rs @@ -37,7 +37,9 @@ impl std::str::FromStr for OutputFormat { "python" => Ok(Self::Python), "rust" => Ok(Self::Rust), "java" => Ok(Self::Java), - "rust_legacy" => Err("'rust_legacy' is now deprecated. Use 'rust' format instead.".to_string()), + "rust_legacy" => { + Err("'rust_legacy' is now deprecated. Use 'rust' format instead.".to_string()) + } _ => Err(format!( "could not parse {input:?}, valid option are 'json', 'python', 'rust'." )), @@ -74,6 +76,12 @@ struct Opt { /// exclude declarations from the generated output. exclude_declaration: Vec, + #[argh(option)] + /// select declarations to include in the generated output. + /// If both include and exclude declarations are specified then the include declaration + /// list is used. + include_declaration: Vec, + #[argh(option)] /// custom_field import paths. /// For the rust backend, declares a list of qualified paths like "module::CustomField". @@ -93,13 +101,25 @@ struct Opt { } /// Remove declarations listed in the input filter. -fn filter_declarations(file: ast::File, exclude_declarations: &[String]) -> ast::File { +fn filter_declarations( + file: ast::File, + exclude_declarations: &[String], + include_declarations: &[String], +) -> ast::File { ast::File { declarations: file .declarations .into_iter() .filter(|decl| { - decl.id().map(|id| !exclude_declarations.contains(&id.to_owned())).unwrap_or(true) + decl.id() + .map(|id| { + if include_declarations.is_empty() { + !exclude_declarations.contains(&id.to_owned()) + } else { + include_declarations.contains(&id.to_owned()) + } + }) + .unwrap_or(true) }) .collect(), ..file @@ -110,7 +130,8 @@ fn generate_backend(opt: &Opt, input_file: &str) -> Result<(), String> { let mut sources = ast::SourceDatabase::new(); match parser::parse_file(&mut sources, input_file) { Ok(file) => { - let file = filter_declarations(file, &opt.exclude_declaration); + let file = + filter_declarations(file, &opt.exclude_declaration, &opt.include_declaration); let analyzed_file = match analyzer::analyze(&file) { Ok(file) => file, Err(diagnostics) => { diff --git a/pdl-compiler/src/parser.rs b/pdl-compiler/src/parser.rs index 463353b9..441e3f71 100644 --- a/pdl-compiler/src/parser.rs +++ b/pdl-compiler/src/parser.rs @@ -488,7 +488,7 @@ fn parse_field(node: Node<'_>, context: &Context) -> Result Rule::integer, Rule::size_modifier, n.as_rule() - )) + )); } None => (None, None), }; @@ -718,15 +718,17 @@ mod test { // Validate that the parser rejects inputs where whitespaces // are not applied between alphabetical keywords and identifiers. let mut db = ast::SourceDatabase::new(); - assert!(parse_inline( - &mut db, - "test", - r#" + assert!( + parse_inline( + &mut db, + "test", + r#" little_endian_packetsstructx{foo:8} "# - .to_owned() - ) - .is_err()); + .to_owned() + ) + .is_err() + ); let result = parse_inline( &mut db, diff --git a/pdl-runtime/src/lib.rs b/pdl-runtime/src/lib.rs index 4dd98e46..c2b8cdce 100644 --- a/pdl-runtime/src/lib.rs +++ b/pdl-runtime/src/lib.rs @@ -56,7 +56,9 @@ pub enum DecodeError { /// Type of serialization errors. #[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)] pub enum EncodeError { - #[error("the size of {packet}::{field} ({size}) is outside the range of valid values 0..{maximum_size}")] + #[error( + "the size of {packet}::{field} ({size}) is outside the range of valid values 0..{maximum_size}" + )] SizeOverflow { packet: &'static str, field: &'static str, size: usize, maximum_size: usize }, #[error( "the count of {packet}::{field} ({count}) is outside the range of valid values 0..{maximum_count}" @@ -100,11 +102,7 @@ pub trait Packet: Sized { /// Returns an error if unparsed bytes remain at the end of the input slice. fn decode_full(buf: &[u8]) -> Result { let (packet, remaining) = Self::decode(buf)?; - if remaining.is_empty() { - Ok(packet) - } else { - Err(DecodeError::TrailingBytes) - } + if remaining.is_empty() { Ok(packet) } else { Err(DecodeError::TrailingBytes) } } /// Return the length of the encoded packet.