Skip to content

Conversation

sabiwara
Copy link
Contributor

@sabiwara sabiwara commented Sep 8, 2024

Close #13814

Indeed as pointed out by José guards being able were a side effect of the shared implementation between match? and regular =.

The match? version would not be strictly equivalent, since there is no way to to reuse extracted variables after matches, but this is probably an OK limitation in practice.


@doc false
def __match__({:when, _, _} = left, _, _, _, _) do
raise ArgumentError, """
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm not sure what the best way to raise here would be.
Ideally this would be a CompileError.

BTW, I noticed that right now without assert we're getting:

error: undefined function when/2 (there is no such import)

But I think we can have a better error message in this case, given that when is a reserved word and can't be used as a function name?

raise ArgumentError, """
invalid pattern in assert/1: #{Macro.to_string(left)}
Use assert match?(... when ...) if you need to assert with a guard.
Copy link
Member

Choose a reason for hiding this comment

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

We could even print out the actual code they were trying to use, right? We have all the ASTs and stuff. Maybe

Use this if you need to assert with a guard:

    assert match?(actual_code)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I like it, but I can see how it could end up with a big suggestion if the pattern is a huge map for instance (and Macro.to_string/2 doesn't have a limit like inspect).
What do you think?

Copy link
Member

Choose a reason for hiding this comment

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

I’m not sure someone would assert on a huge map with a guard at the end, as in I’m not sure that's a common pattern. If that ends up happening, you could always format the code to make it fit nicely.

Copy link
Contributor Author

@sabiwara sabiwara Sep 8, 2024

Choose a reason for hiding this comment

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

SGTM! I went with 6cb2a91, WDYT?

Copy link
Member

@whatyouhide whatyouhide left a comment

Choose a reason for hiding this comment

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

Lovely!

@sabiwara sabiwara merged commit 5137c33 into elixir-lang:main Sep 9, 2024
9 checks passed
@sabiwara sabiwara deleted the assert-when branch September 9, 2024 08:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

assert macro allows for guards in match context

3 participants