Ruby: enum.to_i
implementation is buggy due to string replacement
#1125
Labels
enum.to_i
implementation is buggy due to string replacement
#1125
When stumbling upon this line of code in KSC, I got suspicious because I'm generally convinced is that any kind of string manipulation on translated expressions (i.e. whenever you don't treat the translated expressions as opaque strings) is naive, flawed and can cause hard-to-detect bugs:
RubyTranslator.scala:67
It turns out that this use of
String.replace()
does indeed cause an observable bug. See reproduction code below. For comparison, I wrote two .ksy specs that are very similar, one where the bug isn't triggered (enum_nested_no_bug.ksy
) and one where the bug is triggered (enum_nested_bug.ksy
):I also added a debug print in KSC to make it easy to see how the bug happens (this is at
RubyTranslator.scala:67
):You can already see the problem - the valid reference to the "enum inverse map" would be
ABC::I__ABC
, but the compiler ended up withI__ABC::I__ABC
because of the naive string substitution. This is reflected in the generated code:It's not hard to imagine that the
enum_nested_no_bug.rb
file works, whereasenum_nested_bug.rb
doesn't:This bug well demonstrates that string manipulation on translated expressions should be avoided as much as possible, as it almost always has unintended consequences (this is because it's inherently the wrong tool for the task).
Git blames kaitai-io/kaitai_struct_compiler#159 authored by @ams-tschoening and merged by @GreyCat. I'm not mentioning this because I want to be mean, but I wanted to let you know about this pitfall so we can avoid it in the future. Everyone makes mistakes, but I think this kind can be easily avoided if you know what to look out for.
The text was updated successfully, but these errors were encountered: