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

Non Int32 Enum.from_value issue #10301

Closed
carlhoerberg opened this issue Jan 26, 2021 · 2 comments · Fixed by #10303
Closed

Non Int32 Enum.from_value issue #10301

carlhoerberg opened this issue Jan 26, 2021 · 2 comments · Fixed by #10303
Labels
kind:bug A bug in the code. Does not apply to documentation, specs, etc. kind:regression Something that used to correctly work but no longer works topic:stdlib

Comments

@carlhoerberg
Copy link
Contributor

 ✗ crystal -v
Crystal 0.36.0 [1e6f96aef] (2021-01-26)

LLVM: 10.0.0
Default target: x86_64-unknown-linux-gnu
@[Flags]
enum F : UInt8
  A
end
F.from_value 1u8
$ crystal run f.cr
Showing last frame. Use --error-trace for full trace.

There was a problem expanding macro 'macro_139997757591040'

Code in /usr/share/crystal/src/enum.cr:357:5

 357 | {% if @type.annotation(Flags) %}
       ^
Called macro defined in /usr/share/crystal/src/enum.cr:357:5

 357 | {% if @type.annotation(Flags) %}

Which expanded to:

 > 2 | all_mask = F::All.value
 > 3 | return if all_mask & value != value
 > 4 | return new(value.to_i)
              ^--
Error: no overload matches 'F.new' with type Int32

Overloads are:
 - F.new(value : ::UInt8)
@asterite
Copy link
Member

asterite commented Jan 26, 2021

Regression introduced by #10145

@carlhoerberg
Copy link
Contributor Author

Workaround suggested by @bcardiff:

struct Enum
  def self.from_value?(value : Int) : self?
    {% if @type.annotation(Flags) %}
      all_mask = {{@type}}::All.value
      return if all_mask & value != value
      return new(value)
    {% else %}
      {% for member in @type.constants %}
        return new({{@type.constant(member)}}) if {{@type.constant(member)}} == value
      {% end %}
    {% end %}
    nil
  end
end

@straight-shoota straight-shoota added kind:bug A bug in the code. Does not apply to documentation, specs, etc. topic:stdlib labels Jan 26, 2021
@asterite asterite added the kind:regression Something that used to correctly work but no longer works label Jan 26, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind:bug A bug in the code. Does not apply to documentation, specs, etc. kind:regression Something that used to correctly work but no longer works topic:stdlib
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants