Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce Accessor Component Macros #56

Merged
merged 19 commits into from
Jan 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ jobs:
- uses: actions/checkout@v4
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
toolchain: nightly
override: true
components: rustfmt
- uses: actions-rs/cargo@v1
with:
command: fmt
Expand Down
7 changes: 2 additions & 5 deletions .rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
max_width = 100
reorder_imports = true

# nightly only

# group_imports = "StdExternalCrate"
# imports_granularity = "Module"
group_imports = "StdExternalCrate"
imports_granularity = "Module"
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

## v0.3.0 (pre-release)

- Introduce Accessor Component Macros - [#56](https://github.com/contextgeneric/cgp/pull/55)
- Introduce `#[cgp_getter]` attribute macro that extends `#[cgp_component]` and implement
`UseFields` and `UseField` for accessor traits.
- Introduce `#[cgp_auto_getter]` attribute macro for deriving accessor traits with
blanket implementations that use `HasField` directly.

- Introduce `cgp_type!` macro for defining simple abstract CGP types - [#55](https://github.com/contextgeneric/cgp/pull/55)
- Use `cgp_type!` to derive `HasErrorType` and `HasRuntimeType`.

Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,25 @@ pub struct ComponentNameSpec {
pub component_params: Punctuated<Ident, Comma>,
}

static VALID_KEYS: [&str; 3] = ["context", "provider", "name"];

impl Parse for ComponentSpec {
fn parse(input: ParseStream) -> syn::Result<Self> {
let Entries { entries } = input.parse()?;

for key in entries.keys() {
if !VALID_KEYS.iter().any(|valid| valid == key) {
return Err(syn::Error::new(
Span::call_site(),
format!(
r#"invalid key in component spec: {key}. the following keys are valid: "context", "provider", "name"."#
),
));
}
}

let context_type: Ident = {
let raw_context_type = entries.get(&Ident::new("context", Span::call_site()));
let raw_context_type = entries.get("context");

if let Some(context_type) = raw_context_type {
syn::parse2(context_type.to_token_stream())?
Expand All @@ -37,14 +50,14 @@ impl Parse for ComponentSpec {

let provider_name: Ident = {
let raw_provider_name = entries
.get(&Ident::new("provider", Span::call_site()))
.get("provider")
.ok_or_else(|| Error::new(input.span(), "expect provider name to be given"))?;

syn::parse2(raw_provider_name.to_token_stream())?
};

let (component_name, component_params) = {
let raw_component_name = entries.get(&Ident::new("name", Span::call_site()));
let raw_component_name = entries.get("name");

if let Some(raw_component_name) = raw_component_name {
let ComponentNameSpec {
Expand Down
34 changes: 20 additions & 14 deletions crates/cgp-component-macro-lib/src/derive_component/derive.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use proc_macro2::TokenStream;
use quote::ToTokens;
use quote::quote;
use syn::ItemTrait;

use crate::derive_component::component_name::derive_component_name_struct;
Expand All @@ -8,34 +8,40 @@ use crate::derive_component::consumer_impl::derive_consumer_impl;
use crate::derive_component::provider_impl::derive_provider_impl;
use crate::derive_component::provider_trait::derive_provider_trait;

pub fn derive_component(attr: TokenStream, item: TokenStream) -> TokenStream {
let spec: ComponentSpec = syn::parse2(attr).unwrap();
pub fn derive_component(attr: TokenStream, item: TokenStream) -> syn::Result<TokenStream> {
let spec: ComponentSpec = syn::parse2(attr)?;
let consumer_trait: ItemTrait = syn::parse2(item)?;

let consumer_trait: ItemTrait = syn::parse2(item).unwrap();
derive_component_with_ast(&spec, &consumer_trait)
}

pub fn derive_component_with_ast(
spec: &ComponentSpec,
consumer_trait: &ItemTrait,
) -> syn::Result<TokenStream> {
let provider_name = &spec.provider_name;
let context_type = &spec.context_type;

let component_struct =
derive_component_name_struct(&spec.component_name, &spec.component_params);

let provider_trait =
derive_provider_trait(&consumer_trait, provider_name, context_type).unwrap();
let provider_trait = derive_provider_trait(consumer_trait, provider_name, context_type)?;

let consumer_impl = derive_consumer_impl(&consumer_trait, provider_name, context_type);
let consumer_impl = derive_consumer_impl(consumer_trait, provider_name, context_type);

let provider_impl = derive_provider_impl(
&provider_trait,
&spec.component_name,
&spec.component_params,
);

let mut output = consumer_trait.to_token_stream();

output.extend(component_struct.to_token_stream());
output.extend(provider_trait.to_token_stream());
output.extend(consumer_impl.to_token_stream());
output.extend(provider_impl.to_token_stream());
let derived = quote! {
#consumer_trait
#component_struct
#provider_trait
#consumer_impl
#provider_impl
};

output
Ok(derived)
}
10 changes: 7 additions & 3 deletions crates/cgp-component-macro-lib/src/derive_component/entry.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};

use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
Expand All @@ -21,15 +22,18 @@ impl Parse for Entry {
}

pub struct Entries {
pub entries: BTreeMap<Ident, Type>,
pub entries: BTreeMap<String, Type>,
}

impl Parse for Entries {
fn parse(input: ParseStream) -> syn::Result<Self> {
let entry_list: Punctuated<Entry, Comma> = Punctuated::parse_terminated(input)?;

let entries =
BTreeMap::from_iter(entry_list.into_iter().map(|entry| (entry.key, entry.value)));
let entries = BTreeMap::from_iter(
entry_list
.into_iter()
.map(|entry| (entry.key.to_string(), entry.value)),
);

Ok(Entries { entries })
}
Expand Down
57 changes: 57 additions & 0 deletions crates/cgp-component-macro-lib/src/getter_component/blanket.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use alloc::string::ToString;

use proc_macro2::TokenStream;
use quote::quote;
use syn::{parse_quote, Ident, ItemImpl, ItemTrait};

use crate::getter_component::getter_field::GetterField;
use crate::getter_component::symbol::symbol_from_string;

pub fn derive_blanket_impl(
context_type: &Ident,
consumer_trait: &ItemTrait,
fields: &[GetterField],
) -> ItemImpl {
let consumer_name = &consumer_trait.ident;

let mut constraints = consumer_trait.supertraits.clone();

let mut methods: TokenStream = TokenStream::new();

for field in fields {
let field_name = &field.field_name;
let provider_type = &field.provider_type;
let field_symbol = symbol_from_string(&field.field_name.to_string());

if field.field_mut.is_none() {
constraints.push(parse_quote! {
HasField< #field_symbol, Value = #provider_type >
});

methods.extend(quote! {
fn #field_name( &self ) -> & #provider_type {
self.get_field( ::core::marker::PhantomData::< #field_symbol > )
}
});
} else {
constraints.push(parse_quote! {
HasFieldMut< #field_symbol, Value = #provider_type >
});

methods.extend(quote! {
fn #field_name( &mut self ) -> &mut #provider_type {
self.get_field_mut( ::core::marker::PhantomData::< #field_symbol > )
}
});
}
}

parse_quote! {
impl< #context_type > #consumer_name for #context_type
where
#context_type: #constraints
{
#methods
}
}
}
66 changes: 66 additions & 0 deletions crates/cgp-component-macro-lib/src/getter_component/derive.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::{Error, Ident, ItemTrait};

use crate::derive_component::component_spec::ComponentSpec;
use crate::derive_component::derive::derive_component_with_ast;
use crate::getter_component::blanket::derive_blanket_impl;
use crate::getter_component::getter_field::GetterField;
use crate::getter_component::parse::parse_getter_fields;
use crate::getter_component::use_field::derive_use_field_impl;
use crate::getter_component::use_fields::derive_use_fields_impl;
use crate::getter_component::with_provider::derive_with_provider_impl;

pub fn derive_getter_component(attr: TokenStream, body: TokenStream) -> syn::Result<TokenStream> {
let spec: ComponentSpec = syn::parse2(attr)?;
let consumer_trait: ItemTrait = syn::parse2(body)?;

let derived_component = derive_component_with_ast(&spec, &consumer_trait)?;

let fields = parse_getter_fields(&spec.context_type, &consumer_trait)?;

let use_fields_impl = derive_use_fields_impl(&spec, &consumer_trait, &fields);

let m_field: Option<[GetterField; 1]> = fields.try_into().ok();

let mut derived = quote! {
#derived_component

#use_fields_impl
};

if let Some([field]) = m_field {
let use_field_impl = derive_use_field_impl(&spec, &consumer_trait, &field);
let use_provider_impl = derive_with_provider_impl(&spec, &consumer_trait, &field);

derived.extend(use_field_impl);
derived.extend(use_provider_impl);
}

Ok(derived)
}

pub fn derive_auto_getter_component(
attr: TokenStream,
body: TokenStream,
) -> syn::Result<TokenStream> {
if !attr.is_empty() {
return Err(Error::new(
Span::call_site(),
"#[derive_auto_getter] does not accept any attribute argument",
));
}

let consumer_trait: ItemTrait = syn::parse2(body)?;

let context_type = Ident::new("Context", Span::call_site());

let fields = parse_getter_fields(&context_type, &consumer_trait)?;

let blanket_impl = derive_blanket_impl(&context_type, &consumer_trait, &fields);

Ok(quote! {
#consumer_trait
#blanket_impl
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use syn::token::Mut;
use syn::{Ident, Type};

pub struct GetterField {
pub field_name: Ident,
pub field_type: Type,
pub provider_type: Type,
pub field_mut: Option<Mut>,
}
8 changes: 8 additions & 0 deletions crates/cgp-component-macro-lib/src/getter_component/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
pub mod blanket;
pub mod derive;
pub mod getter_field;
pub mod parse;
pub mod symbol;
pub mod use_field;
pub mod use_fields;
pub mod with_provider;
Loading
Loading