Return an optional method from MethodTable#[] `MethodTable#[]` was declared to return `Method`, as `Hash#[]` is, though it returns `nil` for a method the definition doesn't have. The table is not a `Hash`, so it has no reason to follow the convention, and the type let `TypeAssertions#method_defs` call `#defs` on `nil`. It is declared to return `Method?`. The callers that read a method without testing the result use `#fetch`, so `#method_defs` raises `KeyError` instead of `NoMethodError` for a method that is not defined. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
diff --git a/lib/rbs/cli.rb b/lib/rbs/cli.rb index 41efcb8..ec5359a 100644 --- a/lib/rbs/cli.rb +++ b/lib/rbs/cli.rb
@@ -384,7 +384,7 @@ end definition.methods.keys.sort.each do |name| - method = definition.methods[name] + method = definition.methods.fetch(name) if inherit || method.implemented_in == type_name stdout.puts "#{name} (#{method.accessibility})" end
diff --git a/lib/rbs/definition.rb b/lib/rbs/definition.rb index 8916dbc..a87df6c 100644 --- a/lib/rbs/definition.rb +++ b/lib/rbs/definition.rb
@@ -296,7 +296,7 @@ end def [](name) - lookup(name) || (_ = nil) + lookup(name) end def fetch(name, *default, &block)
diff --git a/lib/rbs/unit_test/type_assertions.rb b/lib/rbs/unit_test/type_assertions.rb index 2a07d01..e2a5dfb 100644 --- a/lib/rbs/unit_test/type_assertions.rb +++ b/lib/rbs/unit_test/type_assertions.rb
@@ -235,10 +235,10 @@ case type when Types::ClassInstance, Types::ClassSingleton if type.is_a?(Types::ClassSingleton) && type.args.empty? - definition.methods[method].defs + definition.methods.fetch(method).defs else subst = RBS::Substitution.build(definition.type_params, type.args) - definition.methods[method].defs.map do |type_def| + definition.methods.fetch(method).defs.map do |type_def| type_def.update( type: type_def.type.sub(subst) ) @@ -298,6 +298,7 @@ method_entry = definition.methods[method] assert method_entry, "Method `#{method}` not found in RBS definition" + method_entry or raise assert visibility == method_entry.accessibility, "Expected `#{method}` to be #{visibility}, but was #{method_entry.accessibility}" end
diff --git a/sig/definition.rbs b/sig/definition.rbs index 4ba18a4..5605fc7 100644 --- a/sig/definition.rbs +++ b/sig/definition.rbs
@@ -247,7 +247,7 @@ # # Returns `nil` if the method is not defined, like `Hash#[]` does. # - def []: (Symbol) -> Method + def []: (Symbol) -> Method? def fetch: (Symbol) -> Method | [T] (Symbol, T default) -> (Method | T)