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

[BUG] Mojo should block mutating __getitem__ -> ref ... call on alias #3281

Closed
soraros opened this issue Jul 22, 2024 · 3 comments
Closed

[BUG] Mojo should block mutating __getitem__ -> ref ... call on alias #3281

soraros opened this issue Jul 22, 2024 · 3 comments
Labels
bug Something isn't working mojo-repo Tag all issues with this label

Comments

@soraros
Copy link
Contributor

soraros commented Jul 22, 2024

Bug description

As title.

Steps to reproduce

@value
struct S:
    var data: Int

    @always_inline
    fn __getitem__(ref [_]self) -> ref [__lifetime_of(self)] Int:
        return self.data

fn main():
    alias foo = S(0)
    foo[] = 10
    print(foo[])  # prints 0

System information

Mojo 2024.7.2205 (9b0e6242)
@soraros soraros added bug Something isn't working mojo-repo Tag all issues with this label labels Jul 22, 2024
@lattner
Copy link
Collaborator

lattner commented Jul 29, 2024

I don't think this is a desirable fix for this problem. Python allows all sorts of weird getitem/setitem things, and Mojo doesn't want to impose "taste" (or even "common sense" :-) ) on library authors.

The issue here is that referring to the alias value "materializes" it into a local, so the code is like:

fn main():
    alias foo = S(0)
    var tmp1 = foo
    tmp1[] = 10
    var tmp2 = foo
    print(tmp2[])  # prints 0

The behavior is a bit surprising but stacks out from how other parts of the language works.

@soraros soraros changed the title [BUG] Mojo should block mutating __getitem__ -> ref ... call [BUG] Mojo should block mutating __getitem__ -> ref ... call on alias Jul 29, 2024
@soraros
Copy link
Contributor Author

soraros commented Jul 29, 2024

@lattner But the following code doesn't compile:

@value
struct S:
    var data: Int

    fn __setitem__(inout self, value: Int):
        self.data = value

fn main():
    alias foo = S(0)  # error: invalid call to '__setitem__': invalid use of mutating method on rvalue of type 'S'
    foo[] = 10
    print(foo[])  # prints 0

@soraros
Copy link
Contributor Author

soraros commented Sep 24, 2024

Fixed on mojo 2024.9.2405 (094f5635).

@soraros soraros closed this as completed Sep 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working mojo-repo Tag all issues with this label
Projects
None yet
Development

No branches or pull requests

2 participants