Skip to content

Conversation

jnastarot
Copy link
Contributor

The callback mechanism provides greater flexibility than regexps.
It allows you to easily customize the reference return policy especially in cases where pointer or reference return types require special handling.

I have many setters that return a reference to themselves, and I want to handle them as reference_internal. Using regular expressions would make it difficult to distinguish between functions that start with set and return a reference, and others that don't.

I think it would be better to replace the regular expressions in the options with callbacks allowing for much more complex rules

I know i can do this using comments in code, but this process is bad if the project has more than 100 classes with their own methods.

CurrentClass& setValue(uint32_t value) {
    _value = value;
    return *this;
}
uint32_t getValue() const {
    return _value;
}
SomeObject& getObjects() {
    return _objects;
}
def refrenceDetector(func):
    if not func.return_value_policy:
        if isinstance(func.cpp_element().parent, CppPublicProtectedPrivate):
            if hasattr(func.cpp_element(), "return_type") and (
                    '&' in func.cpp_element().return_type.modifiers or 
                    '*' in func.cpp_element().return_type.modifiers):
                func.return_value_policy = "reference_internal"
def my_litgen_options() -> litgen.LitgenOptions: 
    options = litgen.LitgenOptions()
    ...
    options.fn_return_force_policy_reference__callback = refrenceDetector
    return options 

@pthom
Copy link
Owner

pthom commented Nov 30, 2024

Hello, many thanks for your proposition!!

I agree that a callback mechanism is better. Could you post a sample usage with your modification?

If sufficiently short it could be added to the unit tests.

@jnastarot
Copy link
Contributor Author

Added test and fixed build issue 37336e7

@pthom pthom changed the title Callback mechanism instead of regex Callback mechanism instead of regex for return type Dec 2, 2024
@pthom pthom changed the title Callback mechanism instead of regex for return type Callback mechanism instead of regex for rv_policy Dec 2, 2024
@pthom
Copy link
Owner

pthom commented Dec 2, 2024

Thank you, the example is very clear!!
I merged your PR in eae5946

I did some modifications in eae5946, especially by using typing.TYPE_CHECKING to import AdaptedFunction only when running the type checks.

@pthom pthom closed this Dec 2, 2024
@pthom pthom changed the title Callback mechanism instead of regex for rv_policy Callback mechanism instead of regex for rv_policy (merged) Dec 2, 2024
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.

2 participants