Skip to content

Commit

Permalink
Protobuf DSL: generate namespaced enum constants on root
Browse files Browse the repository at this point in the history
The Protobuf DSL compiler was causing errors by generating un-namespaced
constants for enums. In certain cases, this could result in a constant
conflicting with a reserved Ruby word, such as "BEGIN." Instead,
we generate the constants with the correct namespace outside of the
class or module, ensuring that RBIs never contain code such as
"BEGIN = 3" which is invalid Ruby syntax.

Co-authored-by: Alexandre Terrasa <alexandre.terrasa@shopify.com>
  • Loading branch information
egiurleo and Morriar committed Nov 9, 2022
1 parent e35819f commit fe46892
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
13 changes: 12 additions & 1 deletion lib/tapioca/dsl/compilers/protobuf.rb
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,18 @@ def decorate
case descriptor
when Google::Protobuf::EnumDescriptor
descriptor.to_h.each do |sym, val|
klass.create_constant(sym.to_s, value: val.to_s)
# For each enum value, create a namespaced constant on the root rather than an un-namespaced
# constant within the class. This is because un-namespaced constants might conflict with reserved
# Ruby words, such as "BEGIN." By namespacing them, we avoid this problem.
#
# Invalid syntax:
# class Foo
# BEGIN = 3
# end
#
# Valid syntax:
# Foo::BEGIN = 3
root.create_constant("#{constant}::#{sym}", value: val.to_s)
end

klass.create_method(
Expand Down
8 changes: 4 additions & 4 deletions spec/tapioca/dsl/compilers/protobuf_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -193,11 +193,11 @@ def lookup(number); end
sig { params(symbol: Symbol).returns(T.nilable(Integer)) }
def resolve(symbol); end
end
FIXED_AMOUNT = 1
NULL = 0
PERCENTAGE = 2
end
Cart::VALUE_TYPE::FIXED_AMOUNT = 1
Cart::VALUE_TYPE::NULL = 0
Cart::VALUE_TYPE::PERCENTAGE = 2
RBI

assert_equal(expected_enum_rbi, rbi_for("Cart::VALUE_TYPE"))
Expand Down

0 comments on commit fe46892

Please sign in to comment.