Skip to content

Commit 2349640

Browse files
refactor: use more ideomatic practices
1 parent 903b959 commit 2349640

13 files changed

Lines changed: 74 additions & 59 deletions

File tree

codama-attributes/src/attributes.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,9 @@ impl<'a> Attributes<'a> {
1818
let inners = ast.unfeatured_all();
1919
if inners.len() <= 1 {
2020
// Not a multi-attr cfg_attr - use standard parsing
21-
let unfeatured = ast.unfeatured();
22-
let effective = unfeatured.unwrap_or_else(|| (*ast).clone());
21+
// Fall back to the attribute itself when it is not a
22+
// `cfg_attr` (the only case that needs an owned clone).
23+
let effective = ast.unfeatured().unwrap_or_else(|| ast.clone());
2324
vec![(ast, effective)]
2425
} else {
2526
// Multi-attr cfg_attr - expand each inner attribute

codama-errors/src/combine_errors.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ macro_rules! combine_errors {
6666
(Ok(value1), Ok(value2)) => Ok((value1, value2)),
6767
(Err(err1), Err(err2)) => {
6868
let mut combined = err1;
69-
codama_errors::CombineErrors::combine(&mut combined, err2);
69+
$crate::CombineErrors::combine(&mut combined, err2);
7070
Err(combined)
7171
}
7272
(Err(err), _) => Err(err),
@@ -76,11 +76,11 @@ macro_rules! combine_errors {
7676

7777
// 3 results.
7878
($first:expr, $second:expr, $third:expr $(,)?) => {{
79-
match ($first, combine_errors!($second, $third)) {
79+
match ($first, $crate::combine_errors!($second, $third)) {
8080
(Ok(value1), Ok((value2, value3))) => Ok((value1, value2, value3)),
8181
(Err(err1), Err(err2)) => {
8282
let mut combined = err1;
83-
codama_errors::CombineErrors::combine(&mut combined, err2);
83+
$crate::CombineErrors::combine(&mut combined, err2);
8484
Err(combined)
8585
}
8686
(Err(err), _) => Err(err),

codama-errors/src/errors.rs

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,14 +46,10 @@ pub enum CodamaError {
4646
pub type CodamaResult<T> = Result<T, CodamaError>;
4747

4848
impl CodamaError {
49-
pub fn to_compile_error(&self) -> TokenStream {
49+
pub fn into_compile_error(self) -> TokenStream {
5050
match self {
5151
CodamaError::Compilation(error) => error.to_compile_error(),
5252
_ => TokenStream::new(),
5353
}
5454
}
55-
56-
pub fn into_compile_error(self) -> TokenStream {
57-
self.to_compile_error()
58-
}
5955
}

codama-korok-visitors/src/combine_types_visitor.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ pub struct CombineTypesVisitor {
1515
pub r#override: bool,
1616
pub get_enum_variant:
1717
fn(korok: &EnumVariantKorok, parent: &str) -> Option<CodamaResult<EnumVariantTypeNode>>,
18-
pub get_nammed_field:
18+
pub get_named_field:
1919
fn(korok: &FieldKorok, parent: &str) -> Option<CodamaResult<StructFieldTypeNode>>,
2020
pub get_unnammed_field:
2121
fn(korok: &FieldKorok, parent: &str, index: usize) -> Option<CodamaResult<TypeNode>>,
@@ -27,7 +27,7 @@ impl Default for CombineTypesVisitor {
2727
Self {
2828
r#override: false,
2929
get_enum_variant: |x, _| Self::get_default_enum_variant(x),
30-
get_nammed_field: |x, _| Self::get_default_named_field(x),
30+
get_named_field: |x, _| Self::get_default_named_field(x),
3131
get_unnammed_field: |x, _, _| Self::get_default_unnamed_field(x),
3232
parent_enum: String::new(),
3333
}
@@ -41,7 +41,7 @@ impl CombineTypesVisitor {
4141
pub fn strict() -> Self {
4242
Self {
4343
get_enum_variant: Self::get_strict_enum_variant,
44-
get_nammed_field: Self::get_strict_named_field,
44+
get_named_field: Self::get_strict_named_field,
4545
get_unnammed_field: Self::get_strict_unnamed_field,
4646
..Self::default()
4747
}
@@ -124,7 +124,7 @@ impl CombineTypesVisitor {
124124
) -> CodamaResult<Vec<StructFieldTypeNode>> {
125125
let fields = fields
126126
.iter()
127-
.filter_map(|field| (self.get_nammed_field)(field, parent))
127+
.filter_map(|field| (self.get_named_field)(field, parent))
128128
.collect_and_combine_errors()?;
129129

130130
let (before, after): (Vec<_>, Vec<_>) = attributes
@@ -173,9 +173,9 @@ impl KorokVisitor for CombineTypesVisitor {
173173
StructTypeNode::new(fields).into()
174174
}
175175
syn::Fields::Unnamed(_) => {
176-
let items = self.parse_unnamed_fields(&korok.fields, &parent)?;
176+
let mut items = self.parse_unnamed_fields(&korok.fields, &parent)?;
177177
if items.len() == 1 {
178-
items.first().unwrap().clone()
178+
items.remove(0)
179179
} else {
180180
TupleTypeNode::new(items).into()
181181
}

codama-korok-visitors/src/set_instructions_visitors.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ impl Default for SetInstructionsVisitor {
2525
Self {
2626
combine_types: CombineTypesVisitor {
2727
// Skip fields with the `account` codama directive.
28-
get_nammed_field: |korok, parent| {
28+
get_named_field: |korok, parent| {
2929
if korok.attributes.has_codama_attribute("account") {
3030
return None;
3131
}

codama-nodes/derive/src/nestable_type_node.rs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,18 @@ pub fn expand_derive_nestable_type_node(input: &syn::DeriveInput) -> CodamaResul
1717
input.as_struct()?;
1818
let item_name = &input.ident;
1919

20-
// The item name ident without the last 8 characters (for "TypeNode" or "LinkNode").
21-
let variant_name = item_name.to_string();
22-
let variant_name = syn::Ident::new(&variant_name[..variant_name.len() - 8], item_name.span());
20+
// The item name without its `TypeNode`/`LinkNode` suffix names the `TypeNode` variant.
21+
let item_name_string = item_name.to_string();
22+
let variant_name = item_name_string
23+
.strip_suffix("TypeNode")
24+
.or_else(|| item_name_string.strip_suffix("LinkNode"))
25+
.ok_or_else(|| {
26+
syn::Error::new(
27+
item_name.span(),
28+
"expected a name ending in `TypeNode` or `LinkNode`",
29+
)
30+
})?;
31+
let variant_name = syn::Ident::new(variant_name, item_name.span());
2332

2433
Ok(quote! {
2534
impl crate::TypeNodeTrait for #item_name<TypeNode> {

codama-nodes/derive/src/node_union.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ pub fn expand_derive_node_union(input: &syn::DeriveInput) -> CodamaResult<TokenS
113113
let value = serde_json::Value::deserialize(deserializer)?;
114114
let kind = value["kind"].as_str().ok_or_else(|| serde::de::Error::custom("missing kind"))?;
115115
let to_serde_error = |e: serde_json::Error| -> D::Error {
116-
serde::de::Error::custom(format!("failed to deserialize AmountTypeNode: {}", e))
116+
serde::de::Error::custom(format!("failed to deserialize {}: {}", stringify!(#item_name), e))
117117
};
118118
match kind {
119119
#(#deserialize_patterns)*

codama-nodes/derive/src/type_node.rs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,18 @@ pub fn expand_derive_type_node(input: &syn::DeriveInput) -> CodamaResult<TokenSt
1818
let item_name = &input.ident;
1919
let (pre_generics, post_generics) = &input.generics.block_wrappers();
2020

21-
// The item name ident without the last 8 characters (for "TypeNode" or "LinkNode").
22-
let variant_name = item_name.to_string();
23-
let variant_name = syn::Ident::new(&variant_name[..variant_name.len() - 8], item_name.span());
21+
// The item name without its `TypeNode`/`LinkNode` suffix names the `TypeNode` variant.
22+
let item_name_string = item_name.to_string();
23+
let variant_name = item_name_string
24+
.strip_suffix("TypeNode")
25+
.or_else(|| item_name_string.strip_suffix("LinkNode"))
26+
.ok_or_else(|| {
27+
syn::Error::new(
28+
item_name.span(),
29+
"expected a name ending in `TypeNode` or `LinkNode`",
30+
)
31+
})?;
32+
let variant_name = syn::Ident::new(variant_name, item_name.span());
2433

2534
Ok(quote! {
2635
impl #pre_generics crate::TypeNodeTrait for #item_name #post_generics{

codama-plugin-core/src/plugin.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ impl<'a> DirectiveResolver for CompositeDirectiveResolver<'a> {
8989
pub type ResolvePluginsResult<'a> = Box<dyn Fn(&mut dyn KorokVisitable) -> CodamaResult<()> + 'a>;
9090

9191
/// Combine all plugins into a single function that runs them in sequence.
92+
#[must_use = "the returned function must be called on a visitable to run the plugins"]
9293
pub fn resolve_plugins<'a>(plugins: &'a [Box<dyn KorokPlugin + 'a>]) -> ResolvePluginsResult<'a> {
9394
Box::new(move |visitable: &mut dyn KorokVisitable| {
9495
// Phase 0: Resolve all resolvable directives.

codama-visitors-core/src/bottom_up_transformer.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -113,12 +113,12 @@ impl BottomUpTransformer {
113113

114114
/// Applies every rule whose selector matches the current path, in order.
115115
fn run_rules(&mut self, mut node: Node) -> Node {
116-
// Clone the path so the rule closures (which borrow `&mut self.rules`)
117-
// can also read it without a borrow conflict.
118-
let path = self.path.clone();
119-
for rule in self.rules.iter_mut() {
120-
if rule.selector.matches(&path) {
121-
node = (rule.transform)(node, &path);
116+
// Disjoint field borrows let the rule closures read the path while
117+
// `rules` is borrowed mutably -- no need to clone the path per node.
118+
let Self { rules, path, .. } = self;
119+
for rule in rules.iter_mut() {
120+
if rule.selector.matches(path) {
121+
node = (rule.transform)(node, path);
122122
}
123123
}
124124
node

0 commit comments

Comments
 (0)