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

[ENH] Discriminated stack unions #3990

Open
Tracked by #3992
mrakgr opened this issue Jan 29, 2021 · 2 comments
Open
Tracked by #3992

[ENH] Discriminated stack unions #3990

mrakgr opened this issue Jan 29, 2021 · 2 comments

Comments

@mrakgr
Copy link

mrakgr commented Jan 29, 2021

This particular feature even F# got recently.

inl main() =
    inl ~x : option i32 = None
    match x with
    | Some: x => x
    | None => 0
cdef class US0:
    cdef readonly unsigned long tag
cdef class US0_0(US0): # none
    def __init__(self): self.tag = 0
cdef class US0_1(US0): # some_
    cdef readonly signed long v0
    def __init__(self, signed long v0): self.tag = 1; self.v0 = v0
cpdef signed long main():
    cdef US0 v0
    cdef signed long v1
    v0 = US0_0()
    if v0.tag == 0: # none
        return 0
    elif v0.tag == 1: # some_
        v1 = (<US0_1>v0).v0
        return v1

Right now there is no difference between how stack (non-recursive) and heap (recursive) unions are compiled in the Cython backend. I had no choice, but to do a heap implementation for both of them.

Cython's cdef unions are not the right tool for the job. Not only do they not support Python objects, even if they did, the memory management system would not be able to handle them. So unless I want to mess with memory management and pointer myself in the backend, I have no choice but to leave the implementation as it is for the time being.

The result of that is that option types will have to go through the heap and be less efficient as a result.

But overall this issue is not as high priority as stack tuples.

@mrakgr mrakgr mentioned this issue Jan 29, 2021
4 tasks
@da-woods
Copy link
Contributor

If you're just looking for to support "value or None" then it works (by default) with extension types. https://cython.readthedocs.io/en/latest/src/userguide/extension_types.html#extension-types-and-none.

@mrakgr
Copy link
Author

mrakgr commented Jan 30, 2021

I suppose the option type could be optimized for extension types and objects to just check whether they are None instead of wrapping them with the union wrapper. But this is not particularly important for me.

Much like with stack tuples, the main benefit of stack unions would be that they avoid the heap allocation of heap unions. That fact that the tag field would take some extra space on the stack is trivial in comparison.

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

No branches or pull requests

2 participants