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

Improved generation of methods for traits implemented for objects #1051

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

PuffyWithEyes
Copy link

@PuffyWithEyes PuffyWithEyes commented Jan 29, 2025

Development challenges arise when working with traits because if I want to ensure that my struct implements all possible methods from a trait, I encounter the problem described in the following code snippets:

pub trait DummyTrait {
    extern "C" fn dummy_method(self);
}

#[repr(C)]
struct DummyStruct {
    a: isize,
}

impl DummyTrait for DummyStruct {
    #[no_mangle]
    extern "C" fn dummy_method(mut self) {
        self.a = 1;
    }   
}

#[repr(C)]
struct DummyOtherStruct {
    b: isize,
}

impl DummyTrait for DummyOtherStruct {
    #[no_mangle]
    extern "C" fn dummy_method(mut self) {
        self.b = 1;
    }
}
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>

typedef struct MyStruct {
  intptr_t a;
} DummyStruct;

typedef struct OtherStruct {
  intptr_t b;
} DummyOtherStruct;

void dummy_method(struct DummyStruct self);

void dummy_method(struct DummyOtherStruct self);

As we can see, we have two functions with the same name. Currently, this limitation can be worked around with somewhat inconvenient solutions, which is why I would like to propose my own solution that generates functions with more distinct names. An example of the generated code after applying my changes:

#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>

typedef struct MyStruct {
  intptr_t a;
} DummyStruct;

typedef struct OtherStruct {
  intptr_t b;
} DummyOtherStruct;

void dummy_method_DummyTraits_DummyStruct(struct DummyStruct self);

void dummy_method_DummyTraits_DummyOtherStruct(struct DummyOtherStruct self);

This code will compile. I have also created a separate branch named traits-method-gen-feature, where this functionality can be used as a feature.

P.S.: Apologies for any mistakes, as this is my first fork.

Copy link
Author

@PuffyWithEyes PuffyWithEyes left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Although my solution also does not look so beautiful, maybe this can be done more beautifully...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant