Skip to content

Commit b37885d

Browse files
committed
refactor: make arg parsing code more readable
1 parent aef2e05 commit b37885d

File tree

1 file changed

+39
-35
lines changed

1 file changed

+39
-35
lines changed

test-context-macros/src/test_args.rs

Lines changed: 39 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -40,45 +40,49 @@ pub enum TestArg {
4040

4141
impl TestArg {
4242
pub fn parse_arg_with_expected_context(arg: FnArg, expected_context_type: &syn::Type) -> Self {
43-
// Check if the argument is the context argument
44-
if let syn::FnArg::Typed(pat_type) = &arg
45-
&& let syn::Pat::Ident(pat_ident) = &*pat_type.pat
46-
{
47-
let arg_type = &*pat_type.ty;
48-
// Check for mutable/immutable reference
49-
if let syn::Type::Reference(type_ref) = arg_type
50-
&& types_equal(&type_ref.elem, expected_context_type)
51-
{
52-
let mode = if type_ref.mutability.is_some() {
53-
ContextArgMode::MutableReference
54-
} else {
55-
ContextArgMode::Reference
56-
};
43+
let syn::FnArg::Typed(pat_type) = &arg else {
44+
return Self::Any(arg);
45+
};
46+
47+
let syn::Pat::Ident(pat_ident) = &*pat_type.pat else {
48+
return Self::Any(arg);
49+
};
5750

58-
TestArg::Context(ContextArg {
59-
name: pat_ident.ident.clone(),
60-
mode,
61-
})
62-
} else if types_equal(arg_type, expected_context_type) {
63-
// To determine mutability for an owned type, we check the identifier pattern.
64-
let mode = if pat_ident.mutability.is_some() {
65-
// This catches signatures like: `mut my_ctx: ContextType`
66-
ContextArgMode::OwnedMut
67-
} else {
68-
// This catches signatures like: `my_ctx: ContextType`
69-
ContextArgMode::Owned
70-
};
51+
let arg_type = &*pat_type.ty;
7152

72-
TestArg::Context(ContextArg {
73-
name: pat_ident.ident.clone(),
74-
mode,
75-
})
53+
// Check for mutable/immutable reference
54+
if let syn::Type::Reference(type_ref) = arg_type
55+
&& types_equal(&type_ref.elem, expected_context_type)
56+
{
57+
let mode = if type_ref.mutability.is_some() {
58+
ContextArgMode::MutableReference
7659
} else {
77-
TestArg::Any(arg)
78-
}
79-
} else {
80-
TestArg::Any(arg)
60+
ContextArgMode::Reference
61+
};
62+
63+
return TestArg::Context(ContextArg {
64+
name: pat_ident.ident.clone(),
65+
mode,
66+
});
8167
}
68+
69+
if !types_equal(arg_type, expected_context_type) {
70+
return TestArg::Any(arg);
71+
}
72+
73+
// To determine mutability for an owned type, we check the identifier pattern.
74+
let mode = if pat_ident.mutability.is_some() {
75+
// This catches signatures like: `mut my_ctx: ContextType`
76+
ContextArgMode::OwnedMut
77+
} else {
78+
// This catches signatures like: `my_ctx: ContextType`
79+
ContextArgMode::Owned
80+
};
81+
82+
TestArg::Context(ContextArg {
83+
name: pat_ident.ident.clone(),
84+
mode,
85+
})
8286
}
8387
}
8488

0 commit comments

Comments
 (0)