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

Features/enums2 #5

Merged
merged 3 commits into from
Mar 25, 2024
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
91 changes: 75 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,29 @@ let dto = PersonDto { id: 321, name: "Jack".into(), age: 23 };
let person: Person = dto.into();

assert_eq!(person.id, 321); assert_eq!(person.name, "Jack"); assert_eq!(person.age, 23);

// Starting from v0.4.2 o2o also supports enums:

enum Creature {
Person(Person),
Cat { nickname: String },
Dog(String),
Other
}

#[derive(o2o)]
#[from_owned(Creature)]
enum CreatureDto {
Person(#[map(~.into())] PersonDto),
Cat { nickname: String },
Dog(String),
Other
}

let creature = Creature::Cat { nickname: "Floppa".into() };
let dto: CreatureDto = creature.into();

if let CreatureDto::Cat { nickname } = dto { assert_eq!(nickname, "Floppa"); } else { assert!(false) }
```

And here's the code that `o2o` generates (from here on, generated code is produced by [rust-analyzer: Expand macro recursively](https://rust-analyzer.github.io/manual.html#expand-macro-recursively) command):
Expand All @@ -78,6 +101,17 @@ And here's the code that `o2o` generates (from here on, generated code is produc
}
}
}

impl std::convert::From<Creature> for CreatureDto {
fn from(value: Creature) -> CreatureDto {
match value {
Creature::Person(f0) => CreatureDto::Person(f0.into()),
Creature::Cat { nickname } => CreatureDto::Cat { nickname: nickname },
Creature::Dog(f0) => CreatureDto::Dog(f0),
Creature::Other => CreatureDto::Other,
}
}
}
```
</details>

Expand All @@ -87,7 +121,7 @@ And here's the code that `o2o` generates (from here on, generated code is produc
- [The (not so big) Problem](#the-not-so-big-problem)
- [Inline expressions](#inline-expressions)
- [Examples](#examples)
- [Different field name](#different-field-name)
- [Different member name](#different-member-name)
- [Different field type](#different-field-type)
- [Nested structs](#nested-structs)
- [Nested collection](#nested-collection)
Expand All @@ -107,8 +141,8 @@ And here's the code that `o2o` generates (from here on, generated code is produc
- [Additional o2o instruction available via `#[o2o(...)]` syntax](#additional-o2o-instruction-available-via-o2o-syntax)
- [Primitive type conversions](#primitive-type-conversions)
- [Repeat instructions](#repeat-instructions)
- [Contributions](#contributions)
- [License](#license)
- [Contributions](#contributions)
- [License](#license)

## Traits and `o2o` *trait instructions*

Expand Down Expand Up @@ -279,7 +313,7 @@ So finally, let's look at some examples.

## Examples

### Different field name
### Different member name

``` rust
use o2o::o2o;
Expand All @@ -289,14 +323,29 @@ struct Entity {
another_int: i16,
}

enum EntityEnum {
Entity(Entity),
SomethingElse { field: i32 }
}

#[derive(o2o)]
#[from_ref(Entity)]
#[ref_into_existing(Entity)]
#[map_ref(Entity)]
struct EntityDto {
some_int: i32,
#[map(another_int)]
different_int: i16,
}

#[derive(o2o)]
#[map_ref(EntityEnum)]
enum EntityEnumDto {
#[map(Entity)]
EntityDto(#[map(~.into())]EntityDto),
SomethingElse {
#[map(field, *~)]
f: i32
}
}
```
<details>
<summary>View generated code</summary>
Expand All @@ -316,6 +365,23 @@ struct EntityDto {
other.another_int = self.different_int;
}
}

impl std::convert::From<&EntityEnum> for EntityEnumDto {
fn from(value: &EntityEnum) -> EntityEnumDto {
match value {
EntityEnum::Entity(f0) => EntityEnumDto::EntityDto(f0.into()),
EntityEnum::SomethingElse { field } => EntityEnumDto::SomethingElse { f: *field },
}
}
}
impl std::convert::Into<EntityEnum> for &EntityEnumDto {
fn into(self) -> EntityEnum {
match self {
EntityEnumDto::EntityDto(f0) => EntityEnum::Entity(f0.into()),
EntityEnumDto::SomethingElse { f } => EntityEnum::SomethingElse { field: *f },
}
}
}
```
</details>

Expand Down Expand Up @@ -451,9 +517,6 @@ struct Child {
#[map_owned(Entity)]
struct EntityDto {
some_int: i32,
// Here field name as well as type are different, so we pass in field name and tilde inline expression.
// Also, it doesn't hurt to use member trait instruction #[map()],
// which is broader than trait instruction #[map_owned]
#[map(children, ~.iter().map(|p|p.into()).collect())]
children_vec: Vec<ChildDto>
}
Expand Down Expand Up @@ -554,7 +617,7 @@ enum ZodiacSign {}
```
</details>

In a reverse case, you need to use a struct level `#[ghost()]` instruction:
In a reverse case, you need to use a struct level `#[ghosts()]` instruction:
``` rust
use o2o::o2o;

Expand Down Expand Up @@ -771,16 +834,12 @@ impl Employee {
#[derive(o2o)]
#[map(Employee)]
#[ghosts(
// o2o supports closures with one input parameter.
// This parameter represents instance on the other side of the conversion.
first_name: {@.get_first_name()},
last_name: {@.get_last_name()}
)]
struct EmployeeDto {
#[map(id)]
employee_id: i32,
// '@.' is another flavor of 'inline expression'.
// @ also represents instance on the other side of the conversion.
#[ghost(@.get_full_name())]
full_name: String,

Expand Down Expand Up @@ -1518,11 +1577,11 @@ struct CarDto {
```
</details>

### Contributions
## Contributions

All issues, questions, pull requests are extremely welcome.

#### License
## License

<sup>
Licensed under either an <a href="LICENSE-APACHE">Apache License, Version
Expand Down
156 changes: 146 additions & 10 deletions o2o-impl/src/ast.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
use crate::attr::{self};
use crate::attr::{FieldAttrs, StructAttrs};
use crate::attr::{MemberAttrs, DataTypeAttrs};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{DataStruct, DeriveInput, Fields, Generics, Ident, Index, Member, Result};
use syn::token::Comma;
use syn::{Attribute, DataEnum, DataStruct, DeriveInput, Fields, Generics, Ident, Index, Member, Result};

pub(crate) struct Struct<'a> {
pub attrs: StructAttrs,
pub attrs: DataTypeAttrs,
pub ident: &'a Ident,
pub generics: &'a Generics,
pub fields: Vec<Field>,
pub named_fields: bool,
}

pub(crate) struct Field {
pub attrs: FieldAttrs,
pub idx: usize,
pub member: Member,
}

impl<'a> Struct<'a> {
pub fn from_syn(node: &'a DeriveInput, data: &'a DataStruct) -> Result<Self> {
let (attrs, bark) = attr::get_struct_attrs(&node.attrs)?;
Expand All @@ -31,6 +27,13 @@ impl<'a> Struct<'a> {
}
}

#[derive(Clone)]
pub(crate) struct Field {
pub attrs: MemberAttrs,
pub idx: usize,
pub member: Member,
}

impl<'a> Field {
fn multiple_from_syn(fields: &'a Fields, bark: bool) -> Result<Vec<Self>> {
let mut attrs_to_repeat = None;
Expand Down Expand Up @@ -62,7 +65,7 @@ impl<'a> Field {

fn from_syn(i: usize, node: &'a syn::Field, bark: bool) -> Result<Self> {
Ok(Field {
attrs: attr::get_field_attrs(node, bark)?,
attrs: attr::get_field_attrs(SynDataTypeMember::Field(node), bark)?,
idx: i,
member: node.ident.clone().map(Member::Named).unwrap_or_else(|| {
Member::Unnamed(Index {
Expand All @@ -73,3 +76,136 @@ impl<'a> Field {
})
}
}

pub(crate) struct Enum<'a> {
pub attrs: DataTypeAttrs,
pub ident: &'a Ident,
pub generics: &'a Generics,
pub variants: Vec<Variant>
}

impl<'a> Enum<'a> {
pub fn from_syn(node: &'a DeriveInput, data: &'a DataEnum) -> Result<Self> {
let (attrs, bark) = attr::get_struct_attrs(&node.attrs)?;
let variants = Variant::multiple_from_syn(&data.variants, bark)?;
Ok(Enum {
attrs,
ident: &node.ident,
generics: &node.generics,
variants
})
}
}

pub(crate) struct Variant {
pub attrs: MemberAttrs,
pub ident: Ident,
_idx: usize,
pub fields: Vec<Field>,
pub named_fields: bool,
}

impl<'a> Variant {
fn multiple_from_syn(variants: &'a Punctuated<syn::Variant, Comma>, bark: bool) -> Result<Vec<Self>> {
let mut attrs_to_repeat = None;

variants
.iter()
.enumerate()
.map(|(i, variant)| {
let mut field = Variant::from_syn(i, variant, bark)?;

if field.attrs.stop_repeat {
attrs_to_repeat = None;
}

if field.attrs.repeat.is_some() {
if attrs_to_repeat.is_some() && !field.attrs.stop_repeat {
panic!("Previous #[repeat] instruction must be terminated with #[stop_repeat]")
}

attrs_to_repeat = Some(field.attrs.clone());
} else if let Some(attrs_to_repeat) = &attrs_to_repeat {
field.attrs.merge(attrs_to_repeat.clone());
}

Ok(field)
})
.collect()
}

fn from_syn(i: usize, variant: &'a syn::Variant, bark: bool) -> Result<Self> {
let fields = Field::multiple_from_syn(&variant.fields, bark)?;
Ok(Variant {
attrs: attr::get_field_attrs(SynDataTypeMember::Variant(variant), bark)?,
ident: variant.ident.clone(),
_idx: i,
fields,
named_fields: matches!(&variant.fields, Fields::Named(_)),
})
}
}

pub(crate) enum DataType<'a> {
Struct(&'a Struct<'a>),
Enum(&'a Enum<'a>)
}

impl<'a> DataType<'a> {
pub fn get_ident(&'a self) -> &Ident {
match self {
DataType::Struct(s) => s.ident,
DataType::Enum(e) => e.ident
}
}

pub fn get_attrs(&'a self) -> &'a DataTypeAttrs {
match self {
DataType::Struct(s) => &s.attrs,
DataType::Enum(e) => &e.attrs
}
}

pub fn get_members(&'a self) -> Vec<DataTypeMember> {
match self {
DataType::Struct(s) => s.fields.iter().map(DataTypeMember::Field).collect(),
DataType::Enum(e) => e.variants.iter().map(DataTypeMember::Variant).collect()
}
}

pub fn get_generics(&'a self) -> &'a Generics {
match self {
DataType::Struct(s) => s.generics,
DataType::Enum(e) => e.generics
}
}
}

pub(crate) enum SynDataTypeMember<'a> {
Field(&'a syn::Field),
Variant(&'a syn::Variant)
}

impl<'a> SynDataTypeMember<'a> {
pub fn get_attrs(&'a self) -> &'a Vec<Attribute> {
match self {
SynDataTypeMember::Field(f) => &f.attrs,
SynDataTypeMember::Variant(v) => &v.attrs
}
}
}

#[derive(Clone, Copy)]
pub(crate) enum DataTypeMember<'a> {
Field(&'a Field),
Variant(&'a Variant)
}

impl<'a> DataTypeMember<'a> {
pub fn get_attrs(&'a self) -> &'a MemberAttrs {
match self {
DataTypeMember::Field(f) => &f.attrs,
DataTypeMember::Variant(v) => &v.attrs
}
}
}
Loading