Skip to content

Conversation

yykamei
Copy link

@yykamei yykamei commented Jun 11, 2025

Validate that all flag values are Integers when defining flags to prevent runtime errors caused by non-Integer values in bit operations.

Motivation for the changes

The primary motivation for this change is to prevent potential runtime errors.

For instance, when a class inheriting from Literal::Flags8 was defined as follows:

class Example < Literal::Flags8
  define(a: nil, b: true)
end

I got an error with the following. This is because nil was expanded to an empty String, leading to a syntax error.

/Users/yykamei/literal/lib/literal/flags.rb:34:in 'Module#class_eval': 
/Users/yykamei/literal/lib/literal/flags.rb:38: syntax errors found (SyntaxError)
36 | 
	37 | def b?
	> 38 |  @value & (2 ** ) > 0
	|                 ^ unexpected ')', assuming it is closing the parent parentheses
	|                 ^ unexpected ')'; expected an expression after the operator
	|                      ^ expected an `end` to close the `def` statement
	39 | end
...

In another case, the following class was defined and then initialized with Example.new(a: true).

class Example < Literal::Flags8
  define(a: 0.1, b: 1)
end

This resulted in a TypeError.

/Users/yykamei/literal/lib/literal/flags.rb:67:in 'Integer#|': 2.2973967099940698 can't be 
coerced into Integer (TypeError)

value | (bit ? 2 ** flags.fetch(key) : 0)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
from /Users/yykamei/literal/lib/literal/flags.rb:67:in 'block in Literal::Flags.cal
culate_from_hash'
from /Users/yykamei/literal/lib/literal/flags.rb:66:in 'Hash#each'
from /Users/yykamei/literal/lib/literal/flags.rb:66:in 'Enumerable#reduce'
from /Users/yykamei/literal/lib/literal/flags.rb:66:in 'Literal::Flags.calculate_fr
om_hash'
from /Users/yykamei/literal/lib/literal/flags.rb:8:in 'Literal::Flags#initialize'
...

Based on these two examples, it is evident that the Literal::Flags.define method should only accept integer values for its flags. For this reason, I have proposed the changes to enforce this validation.

Validate that all flag values are Integers when defining flags to
prevent runtime errors caused by non-Integer values in bit operations.
@yykamei
Copy link
Author

yykamei commented Jun 11, 2025

Oh, I should address this error.

NameError: uninitialized constant Literal::Types::InterfaceType

@joeldrapper
Copy link
Collaborator

It's not you. It's JRuby. We're waiting for them to fix.

@yykamei
Copy link
Author

yykamei commented Jun 11, 2025

Thanks!

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