repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/compatibility_patches.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/compatibility_patches.rb | # frozen_string_literal: true
# typed: ignore
# Work around an interaction bug with sorbet-runtime and rspec-mocks,
# which occurs when using message expectations (*_any_instance_of,
# expect, allow) and and_call_original.
#
# When a sig is defined, sorbet-runtime will replace the sigged method
# with a wrapper that, upon first invocation, re-wraps the method with a faster
# implementation.
#
# When expect_any_instance_of is used, rspec stores a reference to the first wrapper,
# to be restored later.
#
# The first wrapper is invoked as part of the test and sorbet-runtime replaces
# the method definition with the second wrapper.
#
# But when mocks are cleaned up, rspec restores back to the first wrapper.
# Upon subsequent invocations, the first wrapper is called, and sorbet-runtime
# throws a runtime error, since this is an unexpected state.
#
# We work around this by forcing re-wrapping before rspec stores a reference
# to the method.
if defined? ::RSpec::Mocks
module T
module CompatibilityPatches
module RSpecCompatibility
module RecorderExtensions
def observe!(method_name)
if @klass.method_defined?(method_name.to_sym)
method = @klass.instance_method(method_name.to_sym)
T::Private::Methods.maybe_run_sig_block_for_method(method)
end
super(method_name)
end
end
::RSpec::Mocks::AnyInstance::Recorder.prepend(RecorderExtensions) if defined?(::RSpec::Mocks::AnyInstance::Recorder)
module MethodDoubleExtensions
def initialize(object, method_name, proxy)
if ::Kernel.instance_method(:respond_to?).bind(object).call(method_name, true) # rubocop:disable Performance/BindCall
method = ::RSpec::Support.method_handle_for(object, method_name)
T::Private::Methods.maybe_run_sig_block_for_method(method)
end
super(object, method_name, proxy)
end
end
::RSpec::Mocks::MethodDouble.prepend(MethodDoubleExtensions) if defined?(::RSpec::Mocks::MethodDouble)
end
end
end
end
# Work around for sorbet-runtime wrapped methods.
#
# When a sig is defined, sorbet-runtime will replace the sigged method
# with a wrapper. Those wrapper methods look like `foo(*args, &blk)`
# so that wrappers can handle and pass on all the arguments supplied.
#
# However, that creates a problem with runtime reflection on the methods,
# since when a sigged method is introspected, it will always return its
# `arity` as `-1`, its `parameters` as `[[:rest, :args], [:block, :blk]]`,
# and its `source_location` as `[<some_file_in_sorbet>, <some_line_number>]`.
#
# This might be a problem for some applications that rely on getting the
# correct information from these methods.
#
# This compatibility module, when prepended to the `Method` class, would fix
# the return values of `arity`, `parameters` and `source_location`.
#
# @example
# require 'sorbet-runtime'
# ::Method.prepend(T::CompatibilityPatches::MethodExtensions)
module T
module CompatibilityPatches
module MethodExtensions
def arity
arity = super
return arity if arity != -1 || self.is_a?(Proc)
sig = T::Private::Methods.signature_for_method(self)
sig ? sig.method.arity : arity
end
def source_location
sig = T::Private::Methods.signature_for_method(self)
sig ? sig.method.source_location : super
end
def parameters
sig = T::Private::Methods.signature_for_method(self)
sig ? sig.method.parameters : super
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/final.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/final.rb | # frozen_string_literal: true
# typed: false
module T::Private::Final
module NoInherit
def inherited(arg)
super(arg)
raise "#{self} was declared as final and cannot be inherited"
end
end
module NoIncludeExtend
def included(arg)
super(arg)
raise "#{self} was declared as final and cannot be included"
end
def extended(arg)
super(arg)
raise "#{self} was declared as final and cannot be extended"
end
end
def self.declare(mod)
if !mod.is_a?(Module)
raise "#{mod} is not a class or module and cannot be declared as final with `final!`"
end
if final_module?(mod)
raise "#{mod} was already declared as final and cannot be re-declared as final"
end
if T::AbstractUtils.abstract_module?(mod)
raise "#{mod} was already declared as abstract and cannot be declared as final"
end
if T::Private::Sealed.sealed_module?(mod)
raise "#{mod} was already declared as sealed and cannot be declared as final"
end
mod.extend(mod.is_a?(Class) ? NoInherit : NoIncludeExtend)
mark_as_final_module(mod)
mark_as_final_module(mod.singleton_class)
T::Private::Methods.install_hooks(mod)
end
def self.final_module?(mod)
mod.instance_variable_defined?(:@sorbet_final_module)
end
private_class_method def self.mark_as_final_module(mod)
mod.instance_variable_set(:@sorbet_final_module, true)
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/decl_state.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/decl_state.rb | # frozen_string_literal: true
# typed: true
class T::Private::DeclState
def self.current
Thread.current[:opus_types__decl_state] ||= self.new
end
def self.current=(other)
Thread.current[:opus_types__decl_state] = other
end
attr_accessor :active_declaration
attr_accessor :skip_on_method_added
def reset!
self.active_declaration = nil
end
def without_on_method_added
begin
# explicit 'self' is needed here
old_value = self.skip_on_method_added
self.skip_on_method_added = true
yield
ensure
self.skip_on_method_added = old_value
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/casts.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/casts.rb | # frozen_string_literal: true
# typed: false
module T::Private
module Casts
def self.cast(value, type, cast_method)
begin
coerced_type = T::Utils::Private.coerce_and_check_module_types(type, value, true)
return value unless coerced_type
error = coerced_type.error_message_for_obj(value)
return value unless error
caller_loc = T.must(caller_locations(2..2)).first
suffix = "Caller: #{T.must(caller_loc).path}:#{T.must(caller_loc).lineno}"
raise TypeError.new("#{cast_method}: #{error}\n#{suffix}")
rescue TypeError => e # raise into rescue to ensure e.backtrace is populated
T::Configuration.inline_type_error_handler(e, {kind: cast_method, value: value, type: type})
value
end
end
# there's a lot of shared logic with the above one, but factoring
# it out like this makes it easier to hopefully one day delete
# this one
def self.cast_recursive(value, type, cast_method)
begin
error = T::Utils.coerce(type).error_message_for_obj_recursive(value)
return value unless error
caller_loc = T.must(caller_locations(2..2)).first
suffix = "Caller: #{T.must(caller_loc).path}:#{T.must(caller_loc).lineno}"
raise TypeError.new("#{cast_method}: #{error}\n#{suffix}")
rescue TypeError => e # raise into rescue to ensure e.backtrace is populated
T::Configuration.inline_type_error_handler(e, {kind: cast_method, value: value, type: type})
value
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/caller_utils.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/caller_utils.rb | # frozen_string_literal: true
# typed: false
module T::Private::CallerUtils
if Thread.respond_to?(:each_caller_location) # RUBY_VERSION >= "3.2"
def self.find_caller
skipped_first = false
Thread.each_caller_location do |loc|
unless skipped_first
skipped_first = true
next
end
next if loc.path&.start_with?("<internal:")
return loc if yield(loc)
end
nil
end
else
def self.find_caller
caller_locations(2).find do |loc|
!loc.path&.start_with?("<internal:") && yield(loc)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/sealed.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/sealed.rb | # frozen_string_literal: true
# typed: false
module T::Private::Sealed
module NoInherit
def inherited(child)
super
caller_loc = T::Private::CallerUtils.find_caller { |loc| loc.base_label != 'inherited' }
T::Private::Sealed.validate_inheritance(caller_loc, self, child, 'inherited')
@sorbet_sealed_module_all_subclasses << child
end
def sealed_subclasses
@sorbet_sealed_module_all_subclasses_set ||= # rubocop:disable Naming/MemoizedInstanceVariableName
begin
require 'set'
Set.new(@sorbet_sealed_module_all_subclasses).freeze
end
end
end
module NoIncludeExtend
def included(child)
super
caller_loc = T::Private::CallerUtils.find_caller { |loc| loc.base_label != 'included' }
T::Private::Sealed.validate_inheritance(caller_loc, self, child, 'included')
@sorbet_sealed_module_all_subclasses << child
end
def extended(child)
super
caller_loc = T::Private::CallerUtils.find_caller { |loc| loc.base_label != 'extended' }
T::Private::Sealed.validate_inheritance(caller_loc, self, child, 'extended')
@sorbet_sealed_module_all_subclasses << child
end
def sealed_subclasses
# this will freeze the set so that you can never get into a
# state where you use the subclasses list and then something
# else will add to it
@sorbet_sealed_module_all_subclasses_set ||= # rubocop:disable Naming/MemoizedInstanceVariableName
begin
require 'set'
Set.new(@sorbet_sealed_module_all_subclasses).freeze
end
end
end
def self.declare(mod, decl_file)
if !mod.is_a?(Module)
raise "#{mod} is not a class or module and cannot be declared `sealed!`"
end
if sealed_module?(mod)
raise "#{mod} was already declared `sealed!` and cannot be re-declared `sealed!`"
end
if T::Private::Final.final_module?(mod)
raise "#{mod} was already declared `final!` and cannot be declared `sealed!`"
end
mod.extend(mod.is_a?(Class) ? NoInherit : NoIncludeExtend)
if !decl_file
raise "Couldn't determine declaration file for sealed class."
end
mod.instance_variable_set(:@sorbet_sealed_module_decl_file, decl_file)
mod.instance_variable_set(:@sorbet_sealed_module_all_subclasses, [])
end
def self.sealed_module?(mod)
mod.instance_variable_defined?(:@sorbet_sealed_module_decl_file)
end
def self.validate_inheritance(caller_loc, parent, child, verb)
this_file = caller_loc&.path
decl_file = parent.instance_variable_get(:@sorbet_sealed_module_decl_file)
if !this_file
raise "Could not use backtrace to determine file for #{verb} child #{child}"
end
if !decl_file
raise "#{parent} does not seem to be a sealed module (#{verb} by #{child})"
end
if !this_file.start_with?(decl_file)
whitelist = T::Configuration.sealed_violation_whitelist
if !whitelist.nil? && whitelist.any? { |pattern| this_file =~ pattern }
return
end
raise "#{parent} was declared sealed and can only be #{verb} in #{decl_file}, not #{this_file}"
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/retry.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/retry.rb | # frozen_string_literal: true
# typed: true
module T::Private::Retry
# A special singleton used for static analysis of exceptions.
module RETRY
freeze
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/class_utils.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/class_utils.rb | # frozen_string_literal: true
# typed: false
# Cut down version of Chalk::Tools::ClassUtils with only :replace_method functionality.
# Extracted to a separate namespace so the type system can be used standalone.
module T::Private::ClassUtils
class ReplacedMethod
def initialize(mod, old_method, new_method, overwritten, visibility)
if old_method.name != new_method.name
raise "Method names must match. old=#{old_method.name} new=#{new_method.name}"
end
@mod = mod
@old_method = old_method
@new_method = new_method
@overwritten = overwritten
@name = old_method.name
@visibility = visibility
@restored = false
end
def restore
# The check below would also catch this, but this makes the failure mode much clearer
if @restored
raise "Method '#{@name}' on '#{@mod}' was already restored"
end
if @mod.instance_method(@name) != @new_method
raise "Trying to restore #{@mod}##{@name} but the method has changed since the call to replace_method"
end
@restored = true
if @overwritten
# The original method was overwritten. Overwrite again to restore it.
T::Configuration.without_ruby_warnings do
@mod.send(:define_method, @old_method.name, @old_method)
end
else
# The original method was in an ancestor. Restore it by removing the overriding method.
@mod.send(:remove_method, @old_method.name)
end
# Restore the visibility. Note that we need to do this even when we call remove_method
# above, because the module may have set custom visibility for a method it inherited.
@mod.send(@visibility, @old_method.name)
nil
end
def bind(obj)
@old_method.bind(obj)
end
def to_s
@old_method.to_s
end
end
# `name` must be an instance method (for class methods, pass in mod.singleton_class)
private_class_method def self.visibility_method_name(mod, name)
if mod.public_method_defined?(name)
:public
elsif mod.protected_method_defined?(name)
:protected
elsif mod.private_method_defined?(name)
:private
else
mod.method(name) # Raises
end
end
def self.def_with_visibility(mod, name, visibility, method=nil, &block)
mod.module_exec do
# Start a visibility (public/protected/private) region, so that
# all of the method redefinitions happen with the right visibility
# from the beginning. This ensures that any other code that is
# triggered by `method_added`, sees the redefined method with the
# right visibility.
send(visibility)
if method
define_method(name, method)
else
define_method(name, &block)
end
if block && block.arity < 0 && respond_to?(:ruby2_keywords, true)
ruby2_keywords(name)
end
end
end
# Replaces a method, either by overwriting it (if it is defined directly on `mod`) or by
# overriding it (if it is defined by one of mod's ancestors). If `original_only` is
# false, returns a ReplacedMethod instance on which you can call `bind(...).call(...)`
# to call the original method, or `restore` to restore the original method (by
# overwriting or removing the override).
#
# If `original_only` is true, return the `UnboundMethod` representing the original method.
def self.replace_method(mod, name, original_only=false, &blk)
original_method = mod.instance_method(name)
original_visibility = visibility_method_name(mod, name)
original_owner = original_method.owner
mod.ancestors.each do |ancestor|
break if ancestor == mod
if ancestor == original_owner
# If we get here, that means the method we're trying to replace exists on a *prepended*
# mixin, which means in order to supersede it, we'd need to create a method on a new
# module that we'd prepend before `ancestor`. The problem with that approach is there'd
# be no way to remove that new module after prepending it, so we'd be left with these
# empty anonymous modules in the ancestor chain after calling `restore`.
#
# That's not necessarily a deal breaker, but for now, we're keeping it as unsupported.
raise "You're trying to replace `#{name}` on `#{mod}`, but that method exists in a " \
"prepended module (#{ancestor}), which we don't currently support."
end
end
overwritten = original_owner == mod
T::Configuration.without_ruby_warnings do
T::Private::DeclState.current.without_on_method_added do
def_with_visibility(mod, name, original_visibility, &blk)
end
end
if original_only
original_method
else
new_method = mod.instance_method(name)
ReplacedMethod.new(mod, original_method, new_method, overwritten, original_visibility)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/runtime_levels.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/runtime_levels.rb | # frozen_string_literal: true
# typed: true
# Used in `sig.checked(level)` to determine when runtime type checking
# is enabled on a method.
module T::Private::RuntimeLevels
LEVELS = [
# Validate every call in every environment
:always,
# Validate in tests, but not in production
:tests,
# Don't even validate in tests, b/c too expensive,
# or b/c we fully trust the static typing
:never,
].freeze
@check_tests = false
@wrapped_tests_with_validation = false
@has_read_default_checked_level = false
@default_checked_level = :always
def self.check_tests?
# Assume that this code path means that some `sig.checked(:tests)`
# has been wrapped (or not wrapped) already, which is a trapdoor
# for toggling `@check_tests`.
@wrapped_tests_with_validation = true
@check_tests
end
def self.enable_checking_in_tests
if !@check_tests && @wrapped_tests_with_validation
all_checked_tests_sigs = T::Private::Methods.all_checked_tests_sigs
locations = all_checked_tests_sigs.map { |sig| sig.method.source_location.join(':') }.join("\n- ")
raise "Toggle `:tests`-level runtime type checking earlier. " \
"There are already some methods wrapped with `sig.checked(:tests)`:\n" \
"- #{locations}"
end
_toggle_checking_tests(true)
end
def self.default_checked_level
@has_read_default_checked_level = true
@default_checked_level
end
def self.default_checked_level=(default_checked_level)
if @has_read_default_checked_level
raise "Set the default checked level earlier. There are already some methods whose sig blocks have evaluated which would not be affected by the new default."
end
if !LEVELS.include?(default_checked_level)
raise "Invalid `checked` level '#{default_checked_level}'. Use one of: #{LEVELS}."
end
@default_checked_level = default_checked_level
end
def self._toggle_checking_tests(checked)
@check_tests = checked
end
private_class_method def self.set_enable_checking_in_tests_from_environment
if ENV['SORBET_RUNTIME_ENABLE_CHECKING_IN_TESTS']
enable_checking_in_tests
end
end
set_enable_checking_in_tests_from_environment
private_class_method def self.set_default_checked_level_from_environment
level = ENV['SORBET_RUNTIME_DEFAULT_CHECKED_LEVEL']
if level
self.default_checked_level = level.to_sym
end
end
set_default_checked_level_from_environment
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/abstract/declare.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/abstract/declare.rb | # frozen_string_literal: true
# typed: true
module T::Private::Abstract::Declare
Abstract = T::Private::Abstract
AbstractUtils = T::AbstractUtils
def self.declare_abstract(mod, type:)
if AbstractUtils.abstract_module?(mod)
raise "#{mod} is already declared as abstract"
end
if T::Private::Final.final_module?(mod)
raise "#{mod} was already declared as final and cannot be declared as abstract"
end
Abstract::Data.set(mod, :can_have_abstract_methods, true)
Abstract::Data.set(mod.singleton_class, :can_have_abstract_methods, true)
Abstract::Data.set(mod, :abstract_type, type)
mod.extend(Abstract::Hooks)
if mod.is_a?(Class)
if type == :interface
# Since `interface!` is just `abstract!` with some extra validation, we could technically
# allow this, but it's unclear there are good use cases, and it might be confusing.
raise "Classes can't be interfaces. Use `abstract!` instead of `interface!`."
end
if Object.instance_method(:method).bind_call(mod, :new).owner == mod
raise "You must call `abstract!` *before* defining a `new` method"
end
# Don't need to silence warnings via without_ruby_warnings when calling
# define_method because of the guard above
mod.send(:define_singleton_method, :new) do |*args, &blk|
result = super(*args, &blk)
if result.instance_of?(mod)
raise "#{mod} is declared as abstract; it cannot be instantiated"
end
result
end
# Ruby doesn not emit "method redefined" warnings for aliased methods
# (more robust than undef_method that would create a small window in which the method doesn't exist)
mod.singleton_class.send(:alias_method, :new, :new)
if mod.singleton_class.respond_to?(:ruby2_keywords, true)
mod.singleton_class.send(:ruby2_keywords, :new)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/abstract/data.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/abstract/data.rb | # frozen_string_literal: true
# typed: true
# We need to associate data with abstract modules. We could add instance methods to them that
# access ivars, but those methods will unnecessarily pollute the module namespace, and they'd
# have access to other private state and methods that they don't actually need. We also need to
# associate data with arbitrary classes/modules that implement abstract mixins, where we don't
# control the interface at all. So, we access data via these `get` and `set` methods.
#
# Using instance_variable_get/set here is gross, but the alternative is to use a hash keyed on
# `mod`, and we can't trust that arbitrary modules can be added to those, because there are lurky
# modules that override the `hash` method with something completely broken.
module T::Private::Abstract::Data
def self.get(mod, key)
mod.instance_variable_get("@opus_abstract__#{key}")
end
def self.set(mod, key, value)
mod.instance_variable_set("@opus_abstract__#{key}", value)
end
def self.key?(mod, key)
mod.instance_variable_defined?("@opus_abstract__#{key}")
end
# Works like `setdefault` in Python. If key has already been set, return its value. If not,
# insert `key` with a value of `default` and return `default`.
def self.set_default(mod, key, default)
if self.key?(mod, key)
self.get(mod, key)
else
self.set(mod, key, default)
default
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/abstract/hooks.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/abstract/hooks.rb | # frozen_string_literal: true
# typed: true
module T::Private::Abstract::Hooks
# This will become the self.extend_object method on a module that extends Abstract::Hooks.
# It gets called when *that* module gets extended in another class/module (similar to the
# `extended` hook, but this gets calls before the ancestors of `other` get modified, which
# is important for our validation).
private def extend_object(other)
T::Private::Abstract::Data.set(self, :last_used_by, other)
super
end
# This will become the self.append_features method on a module that extends Abstract::Hooks.
# It gets called when *that* module gets included in another class/module (similar to the
# `included` hook, but this gets calls before the ancestors of `other` get modified, which
# is important for our validation).
private def append_features(other)
T::Private::Abstract::Data.set(self, :last_used_by, other)
super
end
# This will become the self.inherited method on a class that extends Abstract::Hooks.
# It gets called when *that* class gets inherited by another class.
private def inherited(other)
super
# `self` may not actually be abstract -- it could be a concrete class that inherited from an
# abstract class. We only need to check this in `inherited` because, for modules being included
# or extended, the concrete ones won't have these hooks at all. This is just an optimization.
return if !T::AbstractUtils.abstract_module?(self)
T::Private::Abstract::Data.set(self, :last_used_by, other)
end
# This will become the self.prepended method on a module that extends Abstract::Hooks.
# It will get called when *that* module gets prepended in another class/module.
private def prepended(other)
# Prepending abstract methods is weird. You'd only be able to override them via other prepended
# modules, or in subclasses. Punt until we have a use case.
Kernel.raise "Prepending abstract mixins is not currently supported."
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/abstract/validate.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/abstract/validate.rb | # frozen_string_literal: true
# typed: true
module T::Private::Abstract::Validate
Abstract = T::Private::Abstract
AbstractUtils = T::AbstractUtils
Methods = T::Private::Methods
SignatureValidation = T::Private::Methods::SignatureValidation
def self.validate_abstract_module(mod)
type = Abstract::Data.get(mod, :abstract_type)
validate_interface(mod) if type == :interface
end
# Validates a class/module with an abstract class/module as an ancestor. This must be called
# after all methods on `mod` have been defined.
def self.validate_subclass(mod)
can_have_abstract_methods = !T::Private::Abstract::Data.get(mod, :can_have_abstract_methods)
unimplemented_methods = []
T::AbstractUtils.declared_abstract_methods_for(mod).each do |abstract_method|
implementation_method = mod.instance_method(abstract_method.name)
if AbstractUtils.abstract_method?(implementation_method)
# Note that when we end up here, implementation_method might not be the same as
# abstract_method; the latter could've been overridden by another abstract method. In either
# case, if we have a concrete definition in an ancestor, that will end up as the effective
# implementation (see CallValidation.wrap_method_if_needed), so that's what we'll validate
# against.
implementation_method = T.unsafe(nil)
mod.ancestors.each do |ancestor|
if ancestor.instance_methods.include?(abstract_method.name)
method = ancestor.instance_method(abstract_method.name)
T::Private::Methods.maybe_run_sig_block_for_method(method)
if !T::AbstractUtils.abstract_method?(method)
implementation_method = method
break
end
end
end
if !implementation_method
# There's no implementation
if can_have_abstract_methods
unimplemented_methods << describe_method(abstract_method)
end
next # Nothing to validate
end
end
implementation_signature = Methods.signature_for_method(implementation_method)
# When a signature exists and the method is defined directly on `mod`, we skip the validation
# here, because it will have already been done when the method was defined (by
# T::Private::Methods._on_method_added).
next if implementation_signature&.owner == mod
# We validate the remaining cases here: (a) methods defined directly on `mod` without a
# signature and (b) methods from ancestors (note that these ancestors can come before or
# after the abstract module in the inheritance chain -- the former coming from
# walking `mod.ancestors` above).
abstract_signature = Methods.signature_for_method(abstract_method)
# We allow implementation methods to be defined without a signature.
# In that case, get its untyped signature.
implementation_signature ||= Methods::Signature.new_untyped(
method: implementation_method,
mode: Methods::Modes.override
)
SignatureValidation.validate_override_shape(implementation_signature, abstract_signature)
SignatureValidation.validate_override_types(implementation_signature, abstract_signature)
end
method_type = mod.singleton_class? ? "class" : "instance"
if !unimplemented_methods.empty?
raise "Missing implementation for abstract #{method_type} method(s) in #{mod}:\n" \
"#{unimplemented_methods.join("\n")}\n" \
"If #{mod} is meant to be an abstract class/module, you can call " \
"`abstract!` or `interface!`. Otherwise, you must implement the method(s)."
end
end
private_class_method def self.validate_interface_all_abstract(mod, method_names)
violations = method_names.map do |method_name|
method = mod.instance_method(method_name)
if !AbstractUtils.abstract_method?(method)
describe_method(method, show_owner: false)
end
end.compact
if !violations.empty?
raise "`#{mod}` is declared as an interface, but the following methods are not declared " \
"with `abstract`:\n#{violations.join("\n")}"
end
end
private_class_method def self.validate_interface(mod)
interface_methods = T::Utils.methods_excluding_object(mod)
validate_interface_all_abstract(mod, interface_methods)
validate_interface_all_public(mod, interface_methods)
end
private_class_method def self.validate_interface_all_public(mod, method_names)
violations = method_names.map do |method_name|
if !mod.public_method_defined?(method_name)
describe_method(mod.instance_method(method_name), show_owner: false)
end
end.compact
if !violations.empty?
raise "All methods on an interface must be public. If you intend to have non-public " \
"methods, declare your class/module using `abstract!` instead of `interface!`. " \
"The following methods on `#{mod}` are not public: \n#{violations.join("\n")}"
end
end
private_class_method def self.describe_method(method, show_owner: true)
loc = if method.source_location
method.source_location.join(':')
else
"<unknown location>"
end
owner = if show_owner
" declared in #{method.owner}"
else
""
end
" * `#{method.name}`#{owner} at #{loc}"
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/methods/signature_validation.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/methods/signature_validation.rb | # frozen_string_literal: true
# typed: true
module T::Private::Methods::SignatureValidation
Methods = T::Private::Methods
Modes = Methods::Modes
def self.validate(signature)
# Constructors in any language are always a bit weird: they're called in a
# static context, but their bodies are implemented by instance methods. So
# a mix of the rules that apply to instance methods and class methods
# apply.
#
# In languages like Java and Scala, static methods/companion object methods
# are never inherited. (In Java it almost looks like you can inherit them,
# because `Child.static_parent_method` works, but this method is simply
# resolved statically to `Parent.static_parent_method`). Even though most
# instance methods overrides have variance checking done, constructors are
# not treated like this, because static methods are never
# inherited/overridden, and the constructor can only ever be called
# indirectly by way of the static method. (Note: this is only a mental
# model--there's not actually a static method for the constructor in Java,
# there's an `invokespecial` JVM instruction that handles this).
#
# But Ruby is not like Java: singleton class methods in Ruby *are*
# inherited, unlike static methods in Java. In fact, this is similar to how
# JavaScript works. TypeScript simply then sidesteps the issue with
# structural typing: `typeof Parent` is not compatible with `typeof Child`
# if their constructors are different. (In a nominal type system, simply
# having Child descend from Parent should be the only factor in determining
# whether those types are compatible).
#
# Flow has nominal subtyping for classes. When overriding (static and
# instance) methods in a child class, the overrides must satisfy variance
# constraints. But it still carves out an exception for constructors,
# because then literally every class would have to have the same
# constructor. This is simply unsound. Hack does a similar thing--static
# method overrides are checked, but not constructors. Though what Hack
# *does* have is a way to opt into override checking for constructors with
# a special annotation.
#
# It turns out, Sorbet already has this special annotation: either
# `abstract` or `overridable`. At time of writing, *no* static override
# checking happens unless marked with these keywords (though at runtime, it
# always happens). Getting the static system to parity with the runtime by
# always checking overrides would be a great place to get to one day, but
# for now we can take advantage of it by only doing override checks for
# constructors if they've opted in.
#
# (When we get around to more widely checking overrides statically, we will
# need to build a matching special case for constructors statically.)
#
# Note that this breaks with tradition: normally, constructors are not
# allowed to be abstract. But that's kind of a side-effect of everything
# above: in Java/Scala, singleton class methods are never abstract because
# they're not inherited, and this extends to constructors. TypeScript
# simply rejects `new klass()` entirely if `klass` is
# `typeof AbstractClass`, requiring instead that you write
# `{ new(): AbstractClass }`. We may want to consider building some
# analogue to `T.class_of` in the future that works like this `{new():
# ...}` type.
if signature.method_name == :initialize && signature.method.owner.is_a?(Class) &&
signature.mode == Modes.standard
return
end
super_method = signature.method.super_method
if super_method && super_method.owner != signature.method.owner
Methods.maybe_run_sig_block_for_method(super_method)
super_signature = Methods.signature_for_method(super_method)
# If the super_method has any kwargs we can't build a
# Signature for it, so we'll just skip validation in that case.
if !super_signature && !super_method.parameters.select { |kind, _| kind == :rest || kind == :kwrest }.empty?
nil
else
# super_signature can be nil when we're overriding a method (perhaps a builtin) that didn't use
# one of the method signature helpers. Use an untyped signature so we can still validate
# everything but types.
#
# We treat these signatures as overridable, that way people can use `.override` with
# overrides of builtins. In the future we could try to distinguish when the method is a
# builtin and treat non-builtins as non-overridable (so you'd be forced to declare them with
# `.overridable`).
#
super_signature ||= Methods::Signature.new_untyped(method: super_method)
validate_override_mode(signature, super_signature)
validate_override_shape(signature, super_signature)
validate_override_types(signature, super_signature)
validate_override_visibility(signature, super_signature)
end
else
validate_non_override_mode(signature)
end
end
private_class_method def self.pretty_mode(signature)
if signature.mode == Modes.overridable_override
'.overridable.override'
else
".#{signature.mode}"
end
end
def self.validate_override_mode(signature, super_signature)
case signature.mode
when *Modes::OVERRIDE_MODES
# Peaceful
when Modes.abstract
# Either the parent method is abstract, or it's not.
#
# If it's abstract, we want to allow overriding abstract with abstract to
# possibly narrow the type or provide more specific documentation.
#
# If it's not, then marking this method `abstract` will silently be a no-op.
# That's bad and we probably want to report an error, but fixing that
# will have to be a separate fix (that bad behavior predates this current
# comment, introduced when we fixed the abstract/abstract case).
#
# Therefore:
# Peaceful (mostly)
when *Modes::NON_OVERRIDE_MODES
if super_signature.mode == Modes.standard
# Peaceful
elsif super_signature.mode == Modes.abstract
raise "You must use `.override` when overriding the abstract method `#{signature.method_name}`.\n" \
" Abstract definition: #{method_loc_str(super_signature.method)}\n" \
" Implementation definition: #{method_loc_str(signature.method)}\n"
elsif super_signature.mode != Modes.untyped
raise "You must use `.override` when overriding the existing method `#{signature.method_name}`.\n" \
" Parent definition: #{method_loc_str(super_signature.method)}\n" \
" Child definition: #{method_loc_str(signature.method)}\n"
end
else
raise "Unexpected mode: #{signature.mode}. Please report this bug at https://github.com/sorbet/sorbet/issues"
end
end
def self.validate_non_override_mode(signature)
case signature.mode
when Modes.override
if signature.method_name == :each && signature.method.owner < Enumerable
# Enumerable#each is the only method in Sorbet's RBI payload that defines an abstract method.
# Enumerable#each does not actually exist at runtime, but it is required to be implemented by
# any class which includes Enumerable. We want to declare Enumerable#each as abstract so that
# people can call it anything which implements the Enumerable interface, and so that it's a
# static error to forget to implement it.
#
# This is a one-off hack, and we should think carefully before adding more methods here.
nil
else
raise "You marked `#{signature.method_name}` as #{pretty_mode(signature)}, but that method doesn't already exist in this class/module to be overridden.\n" \
" Either check for typos and for missing includes or super classes to make the parent method shows up\n" \
" ... or remove #{pretty_mode(signature)} here: #{method_loc_str(signature.method)}\n"
end
when Modes.standard, *Modes::NON_OVERRIDE_MODES
# Peaceful
nil
else
raise "Unexpected mode: #{signature.mode}. Please report this bug at https://github.com/sorbet/sorbet/issues"
end
# Given a singleton class, we can check if it belongs to a
# module by looking at its superclass; given `module M`,
# `M.singleton_class.superclass == Module`, which is not true
# for any class.
owner = signature.method.owner
if (signature.mode == Modes.abstract || Modes::OVERRIDABLE_MODES.include?(signature.mode)) &&
owner.singleton_class? && owner.superclass == Module
raise "Defining an overridable class method (via #{pretty_mode(signature)}) " \
"on a module is not allowed. Class methods on " \
"modules do not get inherited and thus cannot be overridden."
end
end
def self.validate_override_shape(signature, super_signature)
return if signature.override_allow_incompatible == true
return if super_signature.mode == Modes.untyped
method_name = signature.method_name
mode_verb = super_signature.mode == Modes.abstract ? 'implements' : 'overrides'
if !signature.has_rest && signature.arg_count < super_signature.arg_count
raise "Your definition of `#{method_name}` must accept at least #{super_signature.arg_count} " \
"positional arguments to be compatible with the method it #{mode_verb}: " \
"#{base_override_loc_str(signature, super_signature)}"
end
if !signature.has_rest && super_signature.has_rest
raise "Your definition of `#{method_name}` must have `*#{super_signature.rest_name}` " \
"to be compatible with the method it #{mode_verb}: " \
"#{base_override_loc_str(signature, super_signature)}"
end
if signature.req_arg_count > super_signature.req_arg_count
raise "Your definition of `#{method_name}` must have no more than #{super_signature.req_arg_count} " \
"required argument(s) to be compatible with the method it #{mode_verb}: " \
"#{base_override_loc_str(signature, super_signature)}"
end
if !signature.has_keyrest
# O(nm), but n and m are tiny here
missing_kwargs = super_signature.kwarg_names - signature.kwarg_names
if !missing_kwargs.empty?
raise "Your definition of `#{method_name}` is missing these keyword arg(s): #{missing_kwargs} " \
"which are defined in the method it #{mode_verb}: " \
"#{base_override_loc_str(signature, super_signature)}"
end
end
if !signature.has_keyrest && super_signature.has_keyrest
raise "Your definition of `#{method_name}` must have `**#{super_signature.keyrest_name}` " \
"to be compatible with the method it #{mode_verb}: " \
"#{base_override_loc_str(signature, super_signature)}"
end
# O(nm), but n and m are tiny here
extra_req_kwargs = signature.req_kwarg_names - super_signature.req_kwarg_names
if !extra_req_kwargs.empty?
raise "Your definition of `#{method_name}` has extra required keyword arg(s) " \
"#{extra_req_kwargs} relative to the method it #{mode_verb}, making it incompatible: " \
"#{base_override_loc_str(signature, super_signature)}"
end
if super_signature.block_name && !signature.block_name
raise "Your definition of `#{method_name}` must accept a block parameter to be compatible " \
"with the method it #{mode_verb}: " \
"#{base_override_loc_str(signature, super_signature)}"
end
end
def self.validate_override_types(signature, super_signature)
return if signature.override_allow_incompatible == true
return if super_signature.mode == Modes.untyped
return unless [signature, super_signature].all? do |sig|
sig.check_level == :always || (sig.check_level == :tests && T::Private::RuntimeLevels.check_tests?)
end
mode_noun = super_signature.mode == Modes.abstract ? 'implementation' : 'override'
# arg types must be contravariant
super_signature.arg_types.zip(signature.arg_types).each_with_index do |((_super_name, super_type), (name, type)), index|
if !super_type.subtype_of?(type)
raise "Incompatible type for arg ##{index + 1} (`#{name}`) in signature for #{mode_noun} of method " \
"`#{signature.method_name}`:\n" \
"* Base: `#{super_type}` (in #{method_loc_str(super_signature.method)})\n" \
"* #{mode_noun.capitalize}: `#{type}` (in #{method_loc_str(signature.method)})\n" \
"(The types must be contravariant.)"
end
end
# kwarg types must be contravariant
super_signature.kwarg_types.each do |name, super_type|
type = signature.kwarg_types[name]
if !super_type.subtype_of?(type)
raise "Incompatible type for arg `#{name}` in signature for #{mode_noun} of method `#{signature.method_name}`:\n" \
"* Base: `#{super_type}` (in #{method_loc_str(super_signature.method)})\n" \
"* #{mode_noun.capitalize}: `#{type}` (in #{method_loc_str(signature.method)})\n" \
"(The types must be contravariant.)"
end
end
# return types must be covariant
super_signature_return_type = super_signature.return_type
if super_signature_return_type == T::Private::Types::Void::Private::INSTANCE
# Treat `.void` as `T.anything` (see corresponding comment in definition_valitor for more)
super_signature_return_type = T::Types::Anything::Private::INSTANCE
end
if !signature.return_type.subtype_of?(super_signature_return_type)
raise "Incompatible return type in signature for #{mode_noun} of method `#{signature.method_name}`:\n" \
"* Base: `#{super_signature.return_type}` (in #{method_loc_str(super_signature.method)})\n" \
"* #{mode_noun.capitalize}: `#{signature.return_type}` (in #{method_loc_str(signature.method)})\n" \
"(The types must be covariant.)"
end
end
ALLOW_INCOMPATIBLE_VISIBILITY = [:visibility, true].freeze
private_constant :ALLOW_INCOMPATIBLE_VISIBILITY
def self.validate_override_visibility(signature, super_signature)
return if super_signature.mode == Modes.untyped
# This departs from the behavior of other `validate_override_whatever` functions in that it
# only comes into effect when the child signature explicitly says the word `override`. This was
# done because the primary method for silencing these errors (`allow_incompatible: :visibility`)
# requires an `override` node to attach to. Once we have static override checking for implicitly
# overridden methods, we can remove this.
return unless Modes::OVERRIDE_MODES.include?(signature.mode)
return if ALLOW_INCOMPATIBLE_VISIBILITY.include?(signature.override_allow_incompatible)
method = signature.method
super_method = super_signature.method
mode_noun = super_signature.mode == Modes.abstract ? 'implementation' : 'override'
vis = method_visibility(method)
super_vis = method_visibility(super_method)
if visibility_strength(vis) > visibility_strength(super_vis)
raise "Incompatible visibility for #{mode_noun} of method #{method.name}\n" \
"* Base: #{super_vis} (in #{method_loc_str(super_method)})\n" \
"* #{mode_noun.capitalize}: #{vis} (in #{method_loc_str(method)})\n" \
"(The override must be at least as permissive as the supermethod)" \
end
end
private_class_method def self.method_visibility(method)
T::Private::Methods.visibility_method_name(method.owner, method.name)
end
# Higher = more restrictive.
METHOD_VISIBILITIES = %i[public protected private].freeze
private_constant :METHOD_VISIBILITIES
private_class_method def self.visibility_strength(vis)
METHOD_VISIBILITIES.find_index(vis)
end
private_class_method def self.base_override_loc_str(signature, super_signature)
mode_noun = super_signature.mode == Modes.abstract ? 'Implementation' : 'Override'
"\n * Base definition: in #{method_loc_str(super_signature.method)}" \
"\n * #{mode_noun}: in #{method_loc_str(signature.method)}"
end
private_class_method def self.method_loc_str(method)
loc = if method.source_location
method.source_location.join(':')
else
"<unknown location>"
end
"#{method.owner} at #{loc}"
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/methods/modes.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/methods/modes.rb | # frozen_string_literal: true
# typed: true
module T::Private::Methods::Modes
def self.standard
'standard'
end
def self.abstract
'abstract'
end
def self.overridable
'overridable'
end
def self.override
'override'
end
def self.overridable_override
'overridable_override'
end
def self.untyped
'untyped'
end
MODES = [self.standard, self.abstract, self.overridable, self.override, self.overridable_override, self.untyped].freeze
OVERRIDABLE_MODES = [self.override, self.overridable, self.overridable_override, self.untyped, self.abstract].freeze
OVERRIDE_MODES = [self.override, self.overridable_override].freeze
NON_OVERRIDE_MODES = MODES - OVERRIDE_MODES
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/methods/_methods.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/methods/_methods.rb | # frozen_string_literal: true
# typed: false
module T::Private::Methods
@installed_hooks = {}
if defined?(Concurrent::Hash)
@signatures_by_method = Concurrent::Hash.new
@sig_wrappers = Concurrent::Hash.new
else
@signatures_by_method = {}
@sig_wrappers = {}
end
@sigs_that_raised = {}
# stores method names that were declared final without regard for where.
# enables early rejection of names that we know can't induce final method violations.
@was_ever_final_names = {}.compare_by_identity
# maps from a module's object_id to the set of final methods declared in that module.
# we also overload entries slightly: if the value is nil, that means that the
# module has final methods somewhere along its ancestor chain, but does not itself
# have any final methods.
#
# we need the latter information to know whether we need to check along the ancestor
# chain for final method violations. we need the former information because we
# care about exactly where a final method is defined (e.g. including the same module
# twice is permitted). we could do this with two tables, but it seems slightly
# cleaner with a single table.
# Effectively T::Hash[Module, T.nilable(Set))]
@modules_with_final = Hash.new { |hash, key| hash[key] = nil }.compare_by_identity
# this stores the old [included, extended] hooks for Module and inherited hook for Class that we override when
# enabling final checks for when those hooks are called. the 'hooks' here don't have anything to do with the 'hooks'
# in installed_hooks.
@old_hooks = nil
ARG_NOT_PROVIDED = Object.new
PROC_TYPE = Object.new
DeclarationBlock = Struct.new(:mod, :loc, :blk, :final, :raw)
def self.declare_sig(mod, loc, arg, &blk)
T::Private::DeclState.current.active_declaration = _declare_sig_internal(mod, loc, arg, &blk)
nil
end
# See tests for how to use this. But you shouldn't be using this.
def self._declare_sig(mod, arg=nil, &blk)
_declare_sig_internal(mod, caller_locations(1, 1).first, arg, raw: true, &blk)
end
private_class_method def self._declare_sig_internal(mod, loc, arg, raw: false, &blk)
install_hooks(mod)
if T::Private::DeclState.current.active_declaration
T::Private::DeclState.current.reset!
raise "You called sig twice without declaring a method in between"
end
if !arg.nil? && arg != :final
raise "Invalid argument to `sig`: #{arg}"
end
DeclarationBlock.new(mod, loc, blk, arg == :final, raw)
end
def self._with_declared_signature(mod, declblock, &blk)
# If declblock is provided, this code is equivalent to the check in
# _declare_sig_internal, above.
# If declblock is not provided and we have an active declaration, we are
# obviously doing something wrong.
if T::Private::DeclState.current.active_declaration
T::Private::DeclState.current.reset!
raise "You called sig twice without declaring a method in between"
end
if declblock
T::Private::DeclState.current.active_declaration = declblock
end
mod.module_exec(&blk)
end
def self.start_proc
DeclBuilder.new(PROC_TYPE, false)
end
def self.finalize_proc(decl)
decl.finalized = true
if decl.mode != Modes.standard
raise "Procs cannot have override/abstract modifiers"
end
if decl.mod != PROC_TYPE
raise "You are passing a DeclBuilder as a type. Did you accidentally use `self` inside a `sig` block? Perhaps you wanted the `T.self_type` instead: https://sorbet.org/docs/self-type"
end
if decl.returns == ARG_NOT_PROVIDED
raise "Procs must specify a return type"
end
if decl.on_failure != ARG_NOT_PROVIDED
raise "Procs cannot use .on_failure"
end
if decl.params == ARG_NOT_PROVIDED
decl.params = {}
end
T::Types::Proc.new(decl.params, decl.returns)
end
# Fetch the directory name of the file that defines the `T::Private` constant and
# add a trailing slash to allow us to match it as a directory prefix.
SORBET_RUNTIME_LIB_PATH = File.dirname(T.const_source_location(:Private).first) + File::SEPARATOR
private_constant :SORBET_RUNTIME_LIB_PATH
# when target includes a module with instance methods source_method_names, ensure there is zero intersection between
# the final instance methods of target and source_method_names. so, for every m in source_method_names, check if there
# is already a method defined on one of target_ancestors with the same name that is final.
#
# we assume that source_method_names has already been filtered to only include method
# names that were declared final at one point.
def self._check_final_ancestors(target, target_ancestors, source_method_names, source)
source_ancestors = nil
# use reverse_each to check farther-up ancestors first, for better error messages.
target_ancestors.reverse_each do |ancestor|
final_methods = @modules_with_final.fetch(ancestor, nil)
# In this case, either ancestor didn't have any final methods anywhere in its
# ancestor chain, or ancestor did have final methods somewhere in its ancestor
# chain, but no final methods defined in ancestor itself. Either way, there
# are no final methods to check here, so we can move on to the next ancestor.
next unless final_methods
source_method_names.each do |method_name|
next unless final_methods.include?(method_name)
# If we get here, we are defining a method that some ancestor declared as
# final. however, we permit a final method to be defined multiple
# times if it is the same final method being defined each time.
if source
if !source_ancestors
source_ancestors = source.ancestors
# filter out things without actual final methods just to make sure that
# the below checks (which should be uncommon) go as quickly as possible.
source_ancestors.select! do |a|
@modules_with_final.fetch(a, nil)
end
end
# final-ness means that there should be no more than one index for which
# the below block returns true.
defining_ancestor_idx = source_ancestors.index do |a|
@modules_with_final.fetch(a).include?(method_name)
end
next if defining_ancestor_idx && source_ancestors[defining_ancestor_idx] == ancestor
end
definition_file, definition_line = T::Private::Methods.signature_for_method(ancestor.instance_method(method_name)).method.source_location
is_redefined = target == ancestor
caller_loc = T::Private::CallerUtils.find_caller { |loc| !loc.path.to_s.start_with?(SORBET_RUNTIME_LIB_PATH) }
extra_info = "\n"
if caller_loc
extra_info = (is_redefined ? "Redefined" : "Overridden") + " here: #{caller_loc.path}:#{caller_loc.lineno}\n"
end
error_message = "The method `#{method_name}` on #{ancestor} was declared as final and cannot be " +
(is_redefined ? "redefined" : "overridden in #{target}")
pretty_message = "#{error_message}\n" \
"Made final here: #{definition_file}:#{definition_line}\n" \
"#{extra_info}"
begin
raise pretty_message
rescue => e
# sig_validation_error_handler raises by default; on the off chance that
# it doesn't raise, we need to ensure that the rest of signature building
# sees a consistent state. This sig failed to validate, so we should get
# rid of it. If we don't do this, errors of the form "You called sig
# twice without declaring a method in between" will non-deterministically
# crop up in tests.
T::Private::DeclState.current.reset!
T::Configuration.sig_validation_error_handler(e, {})
end
end
end
end
def self.add_module_with_final_method(mod, method_name)
methods = @modules_with_final[mod]
if methods.nil?
methods = {}
@modules_with_final[mod] = methods
end
methods[method_name] = true
nil
end
def self.note_module_deals_with_final(mod)
# Side-effectfully initialize the value if it's not already there
@modules_with_final[mod]
@modules_with_final[mod.singleton_class]
end
# Only public because it needs to get called below inside the replace_method blocks below.
def self._on_method_added(hook_mod, mod, method_name)
if T::Private::DeclState.current.skip_on_method_added
return
end
current_declaration = T::Private::DeclState.current.active_declaration
if T::Private::Final.final_module?(mod) && (current_declaration.nil? || !current_declaration.final)
raise "#{mod} was declared as final but its method `#{method_name}` was not declared as final"
end
# Don't compute mod.ancestors if we don't need to bother checking final-ness.
if @was_ever_final_names.include?(method_name) && @modules_with_final.include?(mod)
_check_final_ancestors(mod, mod.ancestors, [method_name], nil)
# We need to fetch the active declaration again, as _check_final_ancestors
# may have reset it (see the comment in that method for details).
current_declaration = T::Private::DeclState.current.active_declaration
end
if current_declaration.nil?
return
end
T::Private::DeclState.current.reset!
if method_name == :method_added || method_name == :singleton_method_added
raise(
"Putting a `sig` on `#{method_name}` is not supported" \
" (sorbet-runtime uses this method internally to perform `sig` validation logic)"
)
end
original_method = mod.instance_method(method_name)
sig_block = lambda do
T::Private::Methods.run_sig(hook_mod, method_name, original_method, current_declaration)
end
# Always replace the original method with this wrapper,
# which is called only on the *first* invocation.
# This wrapper is very slow, so it will subsequently re-wrap with a much faster wrapper
# (or unwrap back to the original method).
key = method_owner_and_name_to_key(mod, method_name)
unless current_declaration.raw
T::Private::ClassUtils.replace_method(mod, method_name, true) do |*args, &blk|
method_sig = T::Private::Methods.maybe_run_sig_block_for_key(key)
method_sig ||= T::Private::Methods._handle_missing_method_signature(
self,
original_method,
__callee__,
)
# Should be the same logic as CallValidation.wrap_method_if_needed but we
# don't want that extra layer of indirection in the callstack
if method_sig.mode == T::Private::Methods::Modes.abstract
# We're in an interface method, keep going up the chain
if defined?(super)
super(*args, &blk)
else
raise NotImplementedError.new("The method `#{method_sig.method_name}` on #{mod} is declared as `abstract`. It does not have an implementation.")
end
# Note, this logic is duplicated (intentionally, for micro-perf) at `CallValidation.wrap_method_if_needed`,
# make sure to keep changes in sync.
elsif method_sig.check_level == :always || (method_sig.check_level == :tests && T::Private::RuntimeLevels.check_tests?)
CallValidation.validate_call(self, original_method, method_sig, args, blk)
else
original_method.bind_call(self, *args, &blk)
end
end
end
@sig_wrappers[key] = sig_block
if current_declaration.final
@was_ever_final_names[method_name] = true
# use hook_mod, not mod, because for example, we want class C to be marked as having final if we def C.foo as
# final. change this to mod to see some final_method tests fail.
note_module_deals_with_final(hook_mod)
add_module_with_final_method(mod, method_name)
end
end
def self._handle_missing_method_signature(receiver, original_method, callee)
method_sig = T::Private::Methods.signature_for_method(original_method)
if !method_sig
raise "`sig` not present for method `#{callee}` on #{receiver.inspect} but you're trying to run it anyways. " \
"This should only be executed if you used `alias_method` to grab a handle to a method after `sig`ing it, but that clearly isn't what you are doing. " \
"Maybe look to see if an exception was thrown in your `sig` lambda or somehow else your `sig` wasn't actually applied to the method."
end
if receiver.class <= original_method.owner
receiving_class = receiver.class
elsif receiver.singleton_class <= original_method.owner
receiving_class = receiver.singleton_class
elsif receiver.is_a?(Module) && receiver <= original_method.owner
receiving_class = receiver
else
raise "#{receiver} is not related to #{original_method} - how did we get here?"
end
# Check for a case where `alias` or `alias_method` was called for a
# method which had already had a `sig` applied. In that case, we want
# to avoid hitting this slow path again, by moving to a faster validator
# just like we did or will for the original method.
#
# If this isn't an `alias` or `alias_method` case, we're probably in the
# middle of some metaprogramming using a Method object, e.g. a pattern like
# `arr.map(&method(:foo))`. There's nothing really we can do to optimize
# that here.
receiving_method = receiving_class.instance_method(callee)
if receiving_method != original_method && receiving_method.original_name == original_method.name
aliasing_mod = receiving_method.owner
method_sig = method_sig.as_alias(callee)
unwrap_method(aliasing_mod, method_sig, original_method)
end
method_sig
end
# Executes the `sig` block, and converts the resulting Declaration
# to a Signature.
def self.run_sig(hook_mod, method_name, original_method, declaration_block)
current_declaration =
begin
run_builder(declaration_block)
rescue DeclBuilder::BuilderError => e
T::Configuration.sig_builder_error_handler(e, declaration_block.loc)
nil
end
declaration_block.loc = nil
signature =
if current_declaration
build_sig(hook_mod, method_name, original_method, current_declaration)
else
Signature.new_untyped(method: original_method)
end
unwrap_method(signature.method.owner, signature, original_method)
signature
end
def self.run_builder(declaration_block)
builder = DeclBuilder.new(declaration_block.mod, declaration_block.raw)
builder
.instance_exec(&declaration_block.blk)
.finalize!
.decl
end
def self.build_sig(hook_mod, method_name, original_method, current_declaration)
begin
# We allow `sig` in the current module's context (normal case) and
if hook_mod != current_declaration.mod &&
# inside `class << self`, and
hook_mod.singleton_class != current_declaration.mod &&
# on `self` at the top level of a file
current_declaration.mod != TOP_SELF
raise "A method (#{method_name}) is being added on a different class/module (#{hook_mod}) than the " \
"last call to `sig` (#{current_declaration.mod}). Make sure each call " \
"to `sig` is immediately followed by a method definition on the same " \
"class/module."
end
signature = Signature.new(
method: original_method,
method_name: method_name,
raw_arg_types: current_declaration.params,
raw_return_type: current_declaration.returns,
bind: current_declaration.bind,
mode: current_declaration.mode,
check_level: current_declaration.checked,
on_failure: current_declaration.on_failure,
override_allow_incompatible: current_declaration.override_allow_incompatible,
defined_raw: current_declaration.raw,
)
SignatureValidation.validate(signature)
signature
rescue => e
super_method = original_method&.super_method
super_signature = signature_for_method(super_method) if super_method
T::Configuration.sig_validation_error_handler(
e,
method: original_method,
declaration: current_declaration,
signature: signature,
super_signature: super_signature
)
Signature.new_untyped(method: original_method)
end
end
# Returns the signature for a method whose definition was preceded by `sig`.
#
# @param method [UnboundMethod]
# @return [T::Private::Methods::Signature]
def self.signature_for_method(method)
signature_for_key(method_to_key(method))
end
private_class_method def self.signature_for_key(key)
maybe_run_sig_block_for_key(key)
@signatures_by_method[key]
end
def self.unwrap_method(mod, signature, original_method)
maybe_wrapped_method = CallValidation.wrap_method_if_needed(mod, signature, original_method)
@signatures_by_method[method_to_key(maybe_wrapped_method)] = signature
end
def self.has_sig_block_for_method(method)
has_sig_block_for_key(method_to_key(method))
end
private_class_method def self.has_sig_block_for_key(key)
@sig_wrappers.key?(key)
end
def self.maybe_run_sig_block_for_method(method)
maybe_run_sig_block_for_key(method_to_key(method))
end
# Only public so that it can be accessed in the closure for _on_method_added
def self.maybe_run_sig_block_for_key(key)
run_sig_block_for_key(key) if has_sig_block_for_key(key)
end
def self.run_sig_block_for_method(method)
run_sig_block_for_key(method_to_key(method))
end
# use this directly if you don't want/need to box up the method into an object to pass to method_to_key.
private_class_method def self.method_owner_and_name_to_key(owner, name)
"#{owner.object_id}##{name}"
end
private_class_method def self.method_to_key(method)
# If a subclass Sub inherits a method `foo` from Base, then
# Sub.instance_method(:foo) != Base.instance_method(:foo) even though they resolve to the
# same method. Similarly, Foo.method(:bar) != Foo.singleton_class.instance_method(:bar).
# So, we always do the look up by the method on the owner (Base in this example).
method_owner_and_name_to_key(method.owner, method.name)
end
private_class_method def self.key_to_method(key)
id, name = key.split("#")
obj = ObjectSpace._id2ref(id.to_i)
obj.instance_method(name)
end
private_class_method def self.run_sig_block_for_key(key, force_type_init: false)
blk = @sig_wrappers[key]
if !blk
sig = @signatures_by_method[key]
if sig
# We already ran the sig block, perhaps in another thread.
return sig
else
raise "No `sig` wrapper for #{key_to_method(key)}"
end
end
begin
sig = blk.call
rescue
@sigs_that_raised[key] = true
raise
end
if @sigs_that_raised[key]
raise "A previous invocation of #{key_to_method(key)} raised, and the current one succeeded. Please don't do that."
end
@sig_wrappers.delete(key)
sig.force_type_init if force_type_init
sig
end
def self.run_all_sig_blocks(force_type_init: true)
loop do
break if @sig_wrappers.empty?
key, = @sig_wrappers.first
run_sig_block_for_key(key, force_type_init: force_type_init)
end
end
def self.all_checked_tests_sigs
@signatures_by_method.values.select { |sig| sig.check_level == :tests }
end
# the module target is adding the methods from the module source to itself. we need to check that for all instance
# methods M on source, M is not defined on any of target's ancestors.
def self._hook_impl(target, singleton_class, source)
# we do not need to call add_was_ever_final here, because we have already marked
# any such methods when source was originally defined.
if !@modules_with_final.include?(target)
if !@modules_with_final.include?(source)
return
end
note_module_deals_with_final(target)
install_hooks(target)
return
end
methods = source.instance_methods
methods.select! do |method_name|
@was_ever_final_names.include?(method_name)
end
if methods.empty?
return
end
target_ancestors = singleton_class ? target.singleton_class.ancestors : target.ancestors
_check_final_ancestors(target, target_ancestors, methods, source)
end
def self.set_final_checks_on_hooks(enable)
is_enabled = !@old_hooks.nil?
if enable == is_enabled
return
end
if is_enabled
# A cut-down version of T::Private::ClassUtils::ReplacedMethod#restore, because we
# should only be resetting final hooks during tests.
T::Configuration.without_ruby_warnings do
Module.define_method(:included, @old_hooks[0])
Module.define_method(:extended, @old_hooks[1])
Class.define_method(:inherited, @old_hooks[2])
end
@old_hooks = nil
else
old_included = T::Private::ClassUtils.replace_method(Module, :included, true) do |arg|
old_included.bind_call(self, arg)
::T::Private::Methods._hook_impl(arg, false, self)
end
old_extended = T::Private::ClassUtils.replace_method(Module, :extended, true) do |arg|
old_extended.bind_call(self, arg)
::T::Private::Methods._hook_impl(arg, true, self)
end
old_inherited = T::Private::ClassUtils.replace_method(Class, :inherited, true) do |arg|
old_inherited.bind_call(self, arg)
::T::Private::Methods._hook_impl(arg, false, self)
end
@old_hooks = [old_included, old_extended, old_inherited]
end
end
module MethodHooks
def method_added(name)
::T::Private::Methods._on_method_added(self, self, name)
super(name)
end
end
module SingletonMethodHooks
def singleton_method_added(name)
::T::Private::Methods._on_method_added(self, singleton_class, name)
super(name)
end
end
def self.install_hooks(mod)
return if @installed_hooks.include?(mod)
@installed_hooks[mod] = true
if mod == TOP_SELF
# self at the top-level of a file is weirdly special in Ruby
# The Ruby VM on startup creates an `Object.new` and stashes it.
# Unlike when we're using sig inside a module, `self` is actually a
# normal object, not an instance of Module.
#
# Thus we can't ask things like mod.singleton_class? (since that's
# defined only on Module, not on Object) and even if we could, the places
# where we need to install the hooks are special.
mod.extend(SingletonMethodHooks) # def self.foo; end (at top level)
Object.extend(MethodHooks) # def foo; end (at top level)
return
end
# See https://github.com/sorbet/sorbet/pull/3964 for an explanation of why this
# check (which theoretically should not be needed) is actually needed.
if !mod.is_a?(Module)
return
end
if mod.singleton_class?
mod.include(SingletonMethodHooks)
else
mod.extend(MethodHooks)
end
mod.extend(SingletonMethodHooks)
end
# `name` must be an instance method (for class methods, pass in mod.singleton_class)
def self.visibility_method_name(mod, name)
if mod.public_method_defined?(name)
:public
elsif mod.protected_method_defined?(name)
:protected
elsif mod.private_method_defined?(name)
:private
else
# Raises a NameError formatted like the Ruby VM would (the exact text formatting
# of these errors changed across Ruby VM versions, in ways that would sometimes
# cause tests to fail if they were dependent on hard coding errors).
mod.method(name)
end
end
end
# This has to be here, and can't be nested inside `T::Private::Methods`,
# because the value of `self` depends on lexical (nesting) scope, and we
# specifically need a reference to the file-level self, i.e. `main:Object`
T::Private::Methods::TOP_SELF = self
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/methods/call_validation_2_7.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/methods/call_validation_2_7.rb | # frozen_string_literal: true
# typed: false
# DO NOT EDIT. This file is autogenerated. To regenerate, run:
#
# bazel test //gems/sorbet-runtime:update_call_validation
module T::Private::Methods::CallValidation
def self.create_validator_method_fast(mod, original_method, method_sig, original_visibility)
if method_sig.return_type.is_a?(T::Private::Types::Void)
raise 'Should have used create_validator_procedure_fast'
end
# trampoline to reduce stack frame size
arg_types = method_sig.arg_types
case arg_types.length
when 0
create_validator_method_fast0(mod, original_method, method_sig, original_visibility, method_sig.return_type.raw_type)
when 1
create_validator_method_fast1(mod, original_method, method_sig, original_visibility, method_sig.return_type.raw_type,
arg_types[0][1].raw_type)
when 2
create_validator_method_fast2(mod, original_method, method_sig, original_visibility, method_sig.return_type.raw_type,
arg_types[0][1].raw_type,
arg_types[1][1].raw_type)
when 3
create_validator_method_fast3(mod, original_method, method_sig, original_visibility, method_sig.return_type.raw_type,
arg_types[0][1].raw_type,
arg_types[1][1].raw_type,
arg_types[2][1].raw_type)
when 4
create_validator_method_fast4(mod, original_method, method_sig, original_visibility, method_sig.return_type.raw_type,
arg_types[0][1].raw_type,
arg_types[1][1].raw_type,
arg_types[2][1].raw_type,
arg_types[3][1].raw_type)
else
raise 'should not happen'
end
end
def self.create_validator_method_fast0(mod, original_method, method_sig, original_visibility, return_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |&blk|
# This method is a manually sped-up version of more general code in `validate_call`
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
return_value = original_method.bind_call(self, &blk)
unless return_value.is_a?(return_type)
message = method_sig.return_type.error_message_for_obj(return_value)
if message
CallValidation.report_error(
method_sig,
message,
'Return value',
nil,
method_sig.return_type,
return_value,
caller_offset: -1
)
end
end
return_value
end
end
def self.create_validator_method_fast1(mod, original_method, method_sig, original_visibility, return_type, arg0_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |arg0, &blk|
# This method is a manually sped-up version of more general code in `validate_call`
unless arg0.is_a?(arg0_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[0][1].error_message_for_obj(arg0),
'Parameter',
method_sig.arg_types[0][0],
arg0_type,
arg0,
caller_offset: -1
)
end
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
return_value = original_method.bind_call(self, arg0, &blk)
unless return_value.is_a?(return_type)
message = method_sig.return_type.error_message_for_obj(return_value)
if message
CallValidation.report_error(
method_sig,
message,
'Return value',
nil,
method_sig.return_type,
return_value,
caller_offset: -1
)
end
end
return_value
end
end
def self.create_validator_method_fast2(mod, original_method, method_sig, original_visibility, return_type, arg0_type, arg1_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |arg0, arg1, &blk|
# This method is a manually sped-up version of more general code in `validate_call`
unless arg0.is_a?(arg0_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[0][1].error_message_for_obj(arg0),
'Parameter',
method_sig.arg_types[0][0],
arg0_type,
arg0,
caller_offset: -1
)
end
unless arg1.is_a?(arg1_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[1][1].error_message_for_obj(arg1),
'Parameter',
method_sig.arg_types[1][0],
arg1_type,
arg1,
caller_offset: -1
)
end
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
return_value = original_method.bind_call(self, arg0, arg1, &blk)
unless return_value.is_a?(return_type)
message = method_sig.return_type.error_message_for_obj(return_value)
if message
CallValidation.report_error(
method_sig,
message,
'Return value',
nil,
method_sig.return_type,
return_value,
caller_offset: -1
)
end
end
return_value
end
end
def self.create_validator_method_fast3(mod, original_method, method_sig, original_visibility, return_type, arg0_type, arg1_type, arg2_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |arg0, arg1, arg2, &blk|
# This method is a manually sped-up version of more general code in `validate_call`
unless arg0.is_a?(arg0_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[0][1].error_message_for_obj(arg0),
'Parameter',
method_sig.arg_types[0][0],
arg0_type,
arg0,
caller_offset: -1
)
end
unless arg1.is_a?(arg1_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[1][1].error_message_for_obj(arg1),
'Parameter',
method_sig.arg_types[1][0],
arg1_type,
arg1,
caller_offset: -1
)
end
unless arg2.is_a?(arg2_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[2][1].error_message_for_obj(arg2),
'Parameter',
method_sig.arg_types[2][0],
arg2_type,
arg2,
caller_offset: -1
)
end
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
return_value = original_method.bind_call(self, arg0, arg1, arg2, &blk)
unless return_value.is_a?(return_type)
message = method_sig.return_type.error_message_for_obj(return_value)
if message
CallValidation.report_error(
method_sig,
message,
'Return value',
nil,
method_sig.return_type,
return_value,
caller_offset: -1
)
end
end
return_value
end
end
def self.create_validator_method_fast4(mod, original_method, method_sig, original_visibility, return_type, arg0_type, arg1_type, arg2_type, arg3_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |arg0, arg1, arg2, arg3, &blk|
# This method is a manually sped-up version of more general code in `validate_call`
unless arg0.is_a?(arg0_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[0][1].error_message_for_obj(arg0),
'Parameter',
method_sig.arg_types[0][0],
arg0_type,
arg0,
caller_offset: -1
)
end
unless arg1.is_a?(arg1_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[1][1].error_message_for_obj(arg1),
'Parameter',
method_sig.arg_types[1][0],
arg1_type,
arg1,
caller_offset: -1
)
end
unless arg2.is_a?(arg2_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[2][1].error_message_for_obj(arg2),
'Parameter',
method_sig.arg_types[2][0],
arg2_type,
arg2,
caller_offset: -1
)
end
unless arg3.is_a?(arg3_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[3][1].error_message_for_obj(arg3),
'Parameter',
method_sig.arg_types[3][0],
arg3_type,
arg3,
caller_offset: -1
)
end
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
return_value = original_method.bind_call(self, arg0, arg1, arg2, arg3, &blk)
unless return_value.is_a?(return_type)
message = method_sig.return_type.error_message_for_obj(return_value)
if message
CallValidation.report_error(
method_sig,
message,
'Return value',
nil,
method_sig.return_type,
return_value,
caller_offset: -1
)
end
end
return_value
end
end
def self.create_validator_method_skip_return_fast(mod, original_method, method_sig, original_visibility)
# trampoline to reduce stack frame size
arg_types = method_sig.arg_types
case arg_types.length
when 0
create_validator_method_skip_return_fast0(mod, original_method, method_sig, original_visibility)
when 1
create_validator_method_skip_return_fast1(mod, original_method, method_sig, original_visibility,
arg_types[0][1].raw_type)
when 2
create_validator_method_skip_return_fast2(mod, original_method, method_sig, original_visibility,
arg_types[0][1].raw_type,
arg_types[1][1].raw_type)
when 3
create_validator_method_skip_return_fast3(mod, original_method, method_sig, original_visibility,
arg_types[0][1].raw_type,
arg_types[1][1].raw_type,
arg_types[2][1].raw_type)
when 4
create_validator_method_skip_return_fast4(mod, original_method, method_sig, original_visibility,
arg_types[0][1].raw_type,
arg_types[1][1].raw_type,
arg_types[2][1].raw_type,
arg_types[3][1].raw_type)
else
raise 'should not happen'
end
end
def self.create_validator_method_skip_return_fast0(mod, original_method, method_sig, original_visibility)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |&blk|
# This method is a manually sped-up version of more general code in `validate_call`
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
original_method.bind_call(self, &blk)
end
end
def self.create_validator_method_skip_return_fast1(mod, original_method, method_sig, original_visibility, arg0_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |arg0, &blk|
# This method is a manually sped-up version of more general code in `validate_call`
unless arg0.is_a?(arg0_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[0][1].error_message_for_obj(arg0),
'Parameter',
method_sig.arg_types[0][0],
arg0_type,
arg0,
caller_offset: -1
)
end
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
original_method.bind_call(self, arg0, &blk)
end
end
def self.create_validator_method_skip_return_fast2(mod, original_method, method_sig, original_visibility, arg0_type, arg1_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |arg0, arg1, &blk|
# This method is a manually sped-up version of more general code in `validate_call`
unless arg0.is_a?(arg0_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[0][1].error_message_for_obj(arg0),
'Parameter',
method_sig.arg_types[0][0],
arg0_type,
arg0,
caller_offset: -1
)
end
unless arg1.is_a?(arg1_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[1][1].error_message_for_obj(arg1),
'Parameter',
method_sig.arg_types[1][0],
arg1_type,
arg1,
caller_offset: -1
)
end
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
original_method.bind_call(self, arg0, arg1, &blk)
end
end
def self.create_validator_method_skip_return_fast3(mod, original_method, method_sig, original_visibility, arg0_type, arg1_type, arg2_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |arg0, arg1, arg2, &blk|
# This method is a manually sped-up version of more general code in `validate_call`
unless arg0.is_a?(arg0_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[0][1].error_message_for_obj(arg0),
'Parameter',
method_sig.arg_types[0][0],
arg0_type,
arg0,
caller_offset: -1
)
end
unless arg1.is_a?(arg1_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[1][1].error_message_for_obj(arg1),
'Parameter',
method_sig.arg_types[1][0],
arg1_type,
arg1,
caller_offset: -1
)
end
unless arg2.is_a?(arg2_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[2][1].error_message_for_obj(arg2),
'Parameter',
method_sig.arg_types[2][0],
arg2_type,
arg2,
caller_offset: -1
)
end
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
original_method.bind_call(self, arg0, arg1, arg2, &blk)
end
end
def self.create_validator_method_skip_return_fast4(mod, original_method, method_sig, original_visibility, arg0_type, arg1_type, arg2_type, arg3_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |arg0, arg1, arg2, arg3, &blk|
# This method is a manually sped-up version of more general code in `validate_call`
unless arg0.is_a?(arg0_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[0][1].error_message_for_obj(arg0),
'Parameter',
method_sig.arg_types[0][0],
arg0_type,
arg0,
caller_offset: -1
)
end
unless arg1.is_a?(arg1_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[1][1].error_message_for_obj(arg1),
'Parameter',
method_sig.arg_types[1][0],
arg1_type,
arg1,
caller_offset: -1
)
end
unless arg2.is_a?(arg2_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[2][1].error_message_for_obj(arg2),
'Parameter',
method_sig.arg_types[2][0],
arg2_type,
arg2,
caller_offset: -1
)
end
unless arg3.is_a?(arg3_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[3][1].error_message_for_obj(arg3),
'Parameter',
method_sig.arg_types[3][0],
arg3_type,
arg3,
caller_offset: -1
)
end
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
original_method.bind_call(self, arg0, arg1, arg2, arg3, &blk)
end
end
def self.create_validator_procedure_fast(mod, original_method, method_sig, original_visibility)
# trampoline to reduce stack frame size
arg_types = method_sig.arg_types
case arg_types.length
when 0
create_validator_procedure_fast0(mod, original_method, method_sig, original_visibility)
when 1
create_validator_procedure_fast1(mod, original_method, method_sig, original_visibility,
arg_types[0][1].raw_type)
when 2
create_validator_procedure_fast2(mod, original_method, method_sig, original_visibility,
arg_types[0][1].raw_type,
arg_types[1][1].raw_type)
when 3
create_validator_procedure_fast3(mod, original_method, method_sig, original_visibility,
arg_types[0][1].raw_type,
arg_types[1][1].raw_type,
arg_types[2][1].raw_type)
when 4
create_validator_procedure_fast4(mod, original_method, method_sig, original_visibility,
arg_types[0][1].raw_type,
arg_types[1][1].raw_type,
arg_types[2][1].raw_type,
arg_types[3][1].raw_type)
else
raise 'should not happen'
end
end
def self.create_validator_procedure_fast0(mod, original_method, method_sig, original_visibility)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |&blk|
# This method is a manually sped-up version of more general code in `validate_call`
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
original_method.bind_call(self, &blk)
T::Private::Types::Void::VOID
end
end
def self.create_validator_procedure_fast1(mod, original_method, method_sig, original_visibility, arg0_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |arg0, &blk|
# This method is a manually sped-up version of more general code in `validate_call`
unless arg0.is_a?(arg0_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[0][1].error_message_for_obj(arg0),
'Parameter',
method_sig.arg_types[0][0],
arg0_type,
arg0,
caller_offset: -1
)
end
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
original_method.bind_call(self, arg0, &blk)
T::Private::Types::Void::VOID
end
end
def self.create_validator_procedure_fast2(mod, original_method, method_sig, original_visibility, arg0_type, arg1_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |arg0, arg1, &blk|
# This method is a manually sped-up version of more general code in `validate_call`
unless arg0.is_a?(arg0_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[0][1].error_message_for_obj(arg0),
'Parameter',
method_sig.arg_types[0][0],
arg0_type,
arg0,
caller_offset: -1
)
end
unless arg1.is_a?(arg1_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[1][1].error_message_for_obj(arg1),
'Parameter',
method_sig.arg_types[1][0],
arg1_type,
arg1,
caller_offset: -1
)
end
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
original_method.bind_call(self, arg0, arg1, &blk)
T::Private::Types::Void::VOID
end
end
def self.create_validator_procedure_fast3(mod, original_method, method_sig, original_visibility, arg0_type, arg1_type, arg2_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |arg0, arg1, arg2, &blk|
# This method is a manually sped-up version of more general code in `validate_call`
unless arg0.is_a?(arg0_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[0][1].error_message_for_obj(arg0),
'Parameter',
method_sig.arg_types[0][0],
arg0_type,
arg0,
caller_offset: -1
)
end
unless arg1.is_a?(arg1_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[1][1].error_message_for_obj(arg1),
'Parameter',
method_sig.arg_types[1][0],
arg1_type,
arg1,
caller_offset: -1
)
end
unless arg2.is_a?(arg2_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[2][1].error_message_for_obj(arg2),
'Parameter',
method_sig.arg_types[2][0],
arg2_type,
arg2,
caller_offset: -1
)
end
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
original_method.bind_call(self, arg0, arg1, arg2, &blk)
T::Private::Types::Void::VOID
end
end
def self.create_validator_procedure_fast4(mod, original_method, method_sig, original_visibility, arg0_type, arg1_type, arg2_type, arg3_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |arg0, arg1, arg2, arg3, &blk|
# This method is a manually sped-up version of more general code in `validate_call`
unless arg0.is_a?(arg0_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[0][1].error_message_for_obj(arg0),
'Parameter',
method_sig.arg_types[0][0],
arg0_type,
arg0,
caller_offset: -1
)
end
unless arg1.is_a?(arg1_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[1][1].error_message_for_obj(arg1),
'Parameter',
method_sig.arg_types[1][0],
arg1_type,
arg1,
caller_offset: -1
)
end
unless arg2.is_a?(arg2_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[2][1].error_message_for_obj(arg2),
'Parameter',
method_sig.arg_types[2][0],
arg2_type,
arg2,
caller_offset: -1
)
end
unless arg3.is_a?(arg3_type)
CallValidation.report_error(
method_sig,
method_sig.arg_types[3][1].error_message_for_obj(arg3),
'Parameter',
method_sig.arg_types[3][0],
arg3_type,
arg3,
caller_offset: -1
)
end
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
original_method.bind_call(self, arg0, arg1, arg2, arg3, &blk)
T::Private::Types::Void::VOID
end
end
def self.create_validator_method_medium(mod, original_method, method_sig, original_visibility)
if method_sig.return_type.is_a?(T::Private::Types::Void)
raise 'Should have used create_validator_procedure_medium'
end
# trampoline to reduce stack frame size
arg_types = method_sig.arg_types
case arg_types.length
when 0
create_validator_method_medium0(mod, original_method, method_sig, original_visibility, method_sig.return_type)
when 1
create_validator_method_medium1(mod, original_method, method_sig, original_visibility, method_sig.return_type,
arg_types[0][1])
when 2
create_validator_method_medium2(mod, original_method, method_sig, original_visibility, method_sig.return_type,
arg_types[0][1],
arg_types[1][1])
when 3
create_validator_method_medium3(mod, original_method, method_sig, original_visibility, method_sig.return_type,
arg_types[0][1],
arg_types[1][1],
arg_types[2][1])
when 4
create_validator_method_medium4(mod, original_method, method_sig, original_visibility, method_sig.return_type,
arg_types[0][1],
arg_types[1][1],
arg_types[2][1],
arg_types[3][1])
else
raise 'should not happen'
end
end
def self.create_validator_method_medium0(mod, original_method, method_sig, original_visibility, return_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |&blk|
# This method is a manually sped-up version of more general code in `validate_call`
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
return_value = original_method.bind_call(self, &blk)
unless return_type.valid?(return_value)
message = method_sig.return_type.error_message_for_obj(return_value)
if message
CallValidation.report_error(
method_sig,
message,
'Return value',
nil,
method_sig.return_type,
return_value,
caller_offset: -1
)
end
end
return_value
end
end
def self.create_validator_method_medium1(mod, original_method, method_sig, original_visibility, return_type, arg0_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |arg0, &blk|
# This method is a manually sped-up version of more general code in `validate_call`
unless arg0_type.valid?(arg0)
CallValidation.report_error(
method_sig,
method_sig.arg_types[0][1].error_message_for_obj(arg0),
'Parameter',
method_sig.arg_types[0][0],
arg0_type,
arg0,
caller_offset: -1
)
end
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
return_value = original_method.bind_call(self, arg0, &blk)
unless return_type.valid?(return_value)
message = method_sig.return_type.error_message_for_obj(return_value)
if message
CallValidation.report_error(
method_sig,
message,
'Return value',
nil,
method_sig.return_type,
return_value,
caller_offset: -1
)
end
end
return_value
end
end
def self.create_validator_method_medium2(mod, original_method, method_sig, original_visibility, return_type, arg0_type, arg1_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |arg0, arg1, &blk|
# This method is a manually sped-up version of more general code in `validate_call`
unless arg0_type.valid?(arg0)
CallValidation.report_error(
method_sig,
method_sig.arg_types[0][1].error_message_for_obj(arg0),
'Parameter',
method_sig.arg_types[0][0],
arg0_type,
arg0,
caller_offset: -1
)
end
unless arg1_type.valid?(arg1)
CallValidation.report_error(
method_sig,
method_sig.arg_types[1][1].error_message_for_obj(arg1),
'Parameter',
method_sig.arg_types[1][0],
arg1_type,
arg1,
caller_offset: -1
)
end
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
return_value = original_method.bind_call(self, arg0, arg1, &blk)
unless return_type.valid?(return_value)
message = method_sig.return_type.error_message_for_obj(return_value)
if message
CallValidation.report_error(
method_sig,
message,
'Return value',
nil,
method_sig.return_type,
return_value,
caller_offset: -1
)
end
end
return_value
end
end
def self.create_validator_method_medium3(mod, original_method, method_sig, original_visibility, return_type, arg0_type, arg1_type, arg2_type)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |arg0, arg1, arg2, &blk|
# This method is a manually sped-up version of more general code in `validate_call`
unless arg0_type.valid?(arg0)
CallValidation.report_error(
method_sig,
method_sig.arg_types[0][1].error_message_for_obj(arg0),
'Parameter',
method_sig.arg_types[0][0],
arg0_type,
arg0,
caller_offset: -1
)
end
unless arg1_type.valid?(arg1)
CallValidation.report_error(
method_sig,
method_sig.arg_types[1][1].error_message_for_obj(arg1),
'Parameter',
method_sig.arg_types[1][0],
arg1_type,
arg1,
caller_offset: -1
)
end
unless arg2_type.valid?(arg2)
CallValidation.report_error(
method_sig,
method_sig.arg_types[2][1].error_message_for_obj(arg2),
'Parameter',
method_sig.arg_types[2][0],
arg2_type,
arg2,
caller_offset: -1
)
end
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
return_value = original_method.bind_call(self, arg0, arg1, arg2, &blk)
unless return_type.valid?(return_value)
message = method_sig.return_type.error_message_for_obj(return_value)
if message
CallValidation.report_error(
method_sig,
message,
'Return value',
nil,
method_sig.return_type,
return_value,
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | true |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/methods/signature.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/methods/signature.rb | # frozen_string_literal: true
# typed: true
class T::Private::Methods::Signature
attr_reader :method, :method_name, :arg_types, :kwarg_types, :block_type, :block_name,
:rest_type, :rest_name, :keyrest_type, :keyrest_name, :bind,
:return_type, :mode, :req_arg_count, :req_kwarg_names, :has_rest, :has_keyrest,
:check_level, :parameters, :on_failure, :override_allow_incompatible,
:defined_raw
UNNAMED_REQUIRED_PARAMETERS = [[:req]].freeze
def self.new_untyped(method:, mode: T::Private::Methods::Modes.untyped, parameters: method.parameters)
# Using `NotTyped` ensures we'll get an error if we ever try validation on these.
not_typed = T::Private::Types::NotTyped::INSTANCE
raw_return_type = not_typed
# Map missing parameter names to "argN" positionally
parameters = parameters.each_with_index.map do |(param_kind, param_name), index|
[param_kind, param_name || "arg#{index}"]
end
raw_arg_types = {}
parameters.each do |_, param_name|
raw_arg_types[param_name] = not_typed
end
self.new(
method: method,
method_name: method.name,
raw_arg_types: raw_arg_types,
raw_return_type: raw_return_type,
bind: nil,
mode: mode,
check_level: :never,
parameters: parameters,
on_failure: nil,
)
end
def initialize(method:, method_name:, raw_arg_types:, raw_return_type:, bind:, mode:, check_level:, on_failure:, parameters: method.parameters, override_allow_incompatible: false, defined_raw: false)
@method = method
@method_name = method_name
@block_type = nil
@block_name = nil
@rest_type = nil
@rest_name = nil
@keyrest_type = nil
@keyrest_name = nil
@return_type = T::Utils.coerce(raw_return_type)
@bind = bind ? T::Utils.coerce(bind) : bind
@mode = mode
@check_level = check_level
@has_rest = false
@has_keyrest = false
@parameters = parameters
@on_failure = on_failure
@override_allow_incompatible = override_allow_incompatible
@defined_raw = defined_raw
# Use T.untyped in lieu of T.nilable to try to avoid unnecessary allocations.
arg_types = T.let(nil, T.untyped)
kwarg_types = T.let(nil, T.untyped)
req_arg_count = 0
req_kwarg_names = T.let(nil, T.untyped)
# If sig params are declared but there is a single parameter with a missing name
# **and** the method ends with a "=", assume it is a writer method generated
# by attr_writer or attr_accessor
writer_method = !(raw_arg_types.size == 1 && raw_arg_types.key?(nil)) && parameters == UNNAMED_REQUIRED_PARAMETERS && method_name[-1] == "="
# For writer methods, map the single parameter to the method name without the "=" at the end
parameters = [[:req, method_name[0...-1].to_sym]] if writer_method
is_name_missing = parameters.any? { |_, name| !raw_arg_types.key?(name) }
if is_name_missing
param_names = parameters.map { |_, name| name }
missing_names = param_names - raw_arg_types.keys
raise "The declaration for `#{method.name}` is missing parameter(s): #{missing_names.join(', ')}"
elsif parameters.length != raw_arg_types.size
param_names = parameters.map { |_, name| name }
has_extra_names = parameters.count { |_, name| raw_arg_types.key?(name) } < raw_arg_types.size
if has_extra_names
extra_names = raw_arg_types.keys - param_names
raise "The declaration for `#{method.name}` has extra parameter(s): #{extra_names.join(', ')}"
end
end
if parameters.size != raw_arg_types.size
raise "The declaration for `#{method.name}` has arguments with duplicate names"
end
i = 0
raw_arg_types.each do |type_name, raw_type|
param_kind, param_name = parameters[i]
if type_name != param_name
hint = ""
# Ruby reorders params so that required keyword arguments
# always precede optional keyword arguments. We can't tell
# whether the culprit is the Ruby reordering or user error, so
# we error but include a note
if param_kind == :keyreq && parameters.any? { |k, _| k == :key }
hint = "\n\nNote: Any required keyword arguments must precede any optional keyword " \
"arguments. If your method declaration matches your `def`, try reordering any " \
"optional keyword parameters to the end of the method list."
end
raise "Parameter `#{type_name}` is declared out of order (declared as arg number " \
"#{i + 1}, defined in the method as arg number " \
"#{parameters.index { |_, name| name == type_name } + 1}).#{hint}\nMethod: #{method_desc}"
end
type = T::Utils.coerce(raw_type)
case param_kind
when :req
if (arg_types ? arg_types.length : 0) > req_arg_count
# Note that this is actually is supported by Ruby, but it would add complexity to
# support it here, and I'm happy to discourage its use anyway.
#
# If you are seeing this error and surprised by it, it's possible that you have
# overridden the method described in the error message. For example, Rails defines
# def self.update!(id = :all, attributes)
# on AR models. If you have also defined `self.update!` on an AR model you might
# see this error. The simplest resolution is to rename your method.
raise "Required params after optional params are not supported in method declarations. Method: #{method_desc}"
end
(arg_types ||= []) << [param_name, type]
req_arg_count += 1
when :opt
(arg_types ||= []) << [param_name, type]
when :key, :keyreq
(kwarg_types ||= {})[param_name] = type
if param_kind == :keyreq
(req_kwarg_names ||= []) << param_name
end
when :block
@block_name = param_name
@block_type = type
when :rest
@has_rest = true
@rest_name = param_name
@rest_type = type
when :keyrest
@has_keyrest = true
@keyrest_name = param_name
@keyrest_type = type
else
raise "Unexpected param_kind: `#{param_kind}`. Method: #{method_desc}"
end
i += 1
end
@arg_types = arg_types || EMPTY_LIST
@kwarg_types = kwarg_types || EMPTY_HASH
@req_arg_count = req_arg_count
@req_kwarg_names = req_kwarg_names || EMPTY_LIST
end
attr_writer :method_name
protected :method_name=
def as_alias(alias_name)
new_sig = clone
new_sig.method_name = alias_name
new_sig
end
def arg_count
@arg_types.length
end
def kwarg_names
@kwarg_types.keys
end
def owner
@method.owner
end
def dsl_method
"#{@mode}_method"
end
# @return [Hash] a mapping like `{arg_name: [val, type], ...}`, for only those args actually present.
def each_args_value_type(args)
# Manually split out args and kwargs based on ruby's behavior. Do not try to implement this by
# getting ruby to determine the kwargs for you (e.g., by defining this method to take *args and
# **kwargs). That won't work, because ruby's behavior for determining kwargs is dependent on the
# the other parameters in the method definition, and our method definition here doesn't (and
# can't) match the definition of the method we're validating. In addition, Ruby has a bug that
# causes forwarding **kwargs to do the wrong thing: see https://bugs.ruby-lang.org/issues/10708
# and https://bugs.ruby-lang.org/issues/11860.
args_length = args.length
if (args_length > @req_arg_count) && (!@kwarg_types.empty? || @has_keyrest) && args[-1].is_a?(Hash)
kwargs = args[-1]
args_length -= 1
else
kwargs = EMPTY_HASH
end
if !@has_rest && ((args_length < @req_arg_count) || (args_length > @arg_types.length))
expected_str = @req_arg_count.to_s
if @arg_types.length != @req_arg_count
expected_str += "..#{@arg_types.length}"
end
raise ArgumentError.new("wrong number of arguments (given #{args_length}, expected #{expected_str})")
end
begin
it = 0
# Process given pre-rest args. When there are no rest args,
# this is just the given number of args.
while it < args_length && it < @arg_types.length
yield @arg_types[it][0], args[it], @arg_types[it][1]
it += 1
end
if @has_rest
rest_count = args_length - @arg_types.length
rest_count = 0 if rest_count.negative?
rest_count.times do
yield @rest_name, args[it], @rest_type
it += 1
end
end
end
kwargs.each do |name, val|
type = @kwarg_types[name]
if !type && @has_keyrest
type = @keyrest_type
end
yield name, val, type if type
end
end
def method_desc
loc = if @method.source_location
@method.source_location.join(':')
else
"<unknown location>"
end
"#{@method} at #{loc}"
end
def force_type_init
@arg_types.each { |_, type| type.build_type }
@kwarg_types.each { |_, type| type.build_type }
@block_type&.build_type
@rest_type&.build_type
@keyrest_type&.build_type
@return_type.build_type
end
EMPTY_LIST = [].freeze
EMPTY_HASH = {}.freeze
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/methods/call_validation.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/methods/call_validation.rb | # frozen_string_literal: true
# typed: false
module T::Private::Methods::CallValidation
CallValidation = T::Private::Methods::CallValidation
Modes = T::Private::Methods::Modes
# Wraps a method with a layer of validation for the given type signature.
# This wrapper is meant to be fast, and is applied by a previous wrapper,
# which was placed by `_on_method_added`.
#
# @param method_sig [T::Private::Methods::Signature]
# @return [UnboundMethod] the new wrapper method (or the original one if we didn't wrap it)
def self.wrap_method_if_needed(mod, method_sig, original_method)
original_visibility = T::Private::Methods.visibility_method_name(mod, method_sig.method_name)
if method_sig.mode == T::Private::Methods::Modes.abstract
create_abstract_wrapper(mod, method_sig, original_method, original_visibility)
# Do nothing in this case; this method was not wrapped in _on_method_added.
elsif method_sig.defined_raw
# Note, this logic is duplicated (intentionally, for micro-perf) at `Methods._on_method_added`,
# make sure to keep changes in sync.
# This is a trapdoor point for each method:
# if a given method is wrapped, it stays wrapped; and if not, it's never wrapped.
# (Therefore, we need the `@wrapped_tests_with_validation` check in `T::RuntimeLevels`.)
elsif method_sig.check_level == :always || (method_sig.check_level == :tests && T::Private::RuntimeLevels.check_tests?)
create_validator_method(mod, original_method, method_sig, original_visibility)
else
T::Configuration.without_ruby_warnings do
# get all the shims out of the way and put back the original method
T::Private::DeclState.current.without_on_method_added do
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility, original_method)
end
end
end
# Return the newly created method (or the original one if we didn't replace it)
mod.instance_method(method_sig.method_name)
end
@is_allowed_to_have_fast_path = true
def self.is_allowed_to_have_fast_path
@is_allowed_to_have_fast_path
end
def self.disable_fast_path
@is_allowed_to_have_fast_path = false
end
def self.create_abstract_wrapper(mod, method_sig, original_method, original_visibility)
T::Configuration.without_ruby_warnings do
T::Private::DeclState.current.without_on_method_added do
mod.module_eval(<<~METHOD, __FILE__, __LINE__ + 1)
#{original_visibility}
def #{method_sig.method_name}(...)
# We allow abstract methods to be implemented by things further down the ancestor chain.
# So, if a super method exists, call it.
if defined?(super)
super
else
raise NotImplementedError.new(
"The method `#{method_sig.method_name}` on #{mod} is declared as `abstract`. It does not have an implementation."
)
end
end
METHOD
end
end
end
def self.create_validator_method(mod, original_method, method_sig, original_visibility)
has_fixed_arity = method_sig.kwarg_types.empty? && !method_sig.has_rest && !method_sig.has_keyrest &&
original_method.parameters.all? { |(kind, _name)| kind == :req || kind == :block }
can_skip_block_type = method_sig.block_type.nil? || method_sig.block_type.valid?(nil)
ok_for_fast_path = has_fixed_arity && can_skip_block_type && !method_sig.bind && method_sig.arg_types.length < 5 && is_allowed_to_have_fast_path
all_args_are_simple = ok_for_fast_path && method_sig.arg_types.all? { |_name, type| type.is_a?(T::Types::Simple) }
simple_method = all_args_are_simple && method_sig.return_type.is_a?(T::Types::Simple)
simple_procedure = all_args_are_simple && method_sig.return_type.is_a?(T::Private::Types::Void)
# All the types for which valid? unconditionally returns `true`
return_is_ignorable =
method_sig.return_type.equal?(T::Types::Untyped::Private::INSTANCE) ||
method_sig.return_type.equal?(T::Types::Anything::Private::INSTANCE) ||
method_sig.return_type.equal?(T::Types::AttachedClassType::Private::INSTANCE) ||
method_sig.return_type.equal?(T::Types::SelfType::Private::INSTANCE) ||
method_sig.return_type.is_a?(T::Types::TypeParameter) ||
method_sig.return_type.is_a?(T::Types::TypeVariable) ||
(method_sig.return_type.is_a?(T::Types::Simple) && method_sig.return_type.raw_type.equal?(BasicObject))
returns_anything_method = all_args_are_simple && return_is_ignorable
T::Configuration.without_ruby_warnings do
T::Private::DeclState.current.without_on_method_added do
if simple_method
create_validator_method_fast(mod, original_method, method_sig, original_visibility)
elsif returns_anything_method
create_validator_method_skip_return_fast(mod, original_method, method_sig, original_visibility)
elsif simple_procedure
create_validator_procedure_fast(mod, original_method, method_sig, original_visibility)
elsif ok_for_fast_path && method_sig.return_type.is_a?(T::Private::Types::Void)
create_validator_procedure_medium(mod, original_method, method_sig, original_visibility)
elsif ok_for_fast_path && return_is_ignorable
create_validator_method_skip_return_medium(mod, original_method, method_sig, original_visibility)
elsif ok_for_fast_path
create_validator_method_medium(mod, original_method, method_sig, original_visibility)
elsif can_skip_block_type
# The Ruby VM already validates that any block passed to a method
# must be either `nil` or a `Proc` object, so there's no need to also
# have sorbet-runtime check that.
create_validator_slow_skip_block_type(mod, original_method, method_sig, original_visibility)
else
create_validator_slow(mod, original_method, method_sig, original_visibility)
end
end
mod.send(original_visibility, method_sig.method_name)
end
end
def self.create_validator_slow_skip_block_type(mod, original_method, method_sig, original_visibility)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |*args, &blk|
CallValidation.validate_call_skip_block_type(self, original_method, method_sig, args, blk)
end
end
def self.validate_call_skip_block_type(instance, original_method, method_sig, args, blk)
# This method is called for every `sig`. It's critical to keep it fast and
# reduce number of allocations that happen here.
if method_sig.bind
message = method_sig.bind.error_message_for_obj(instance)
if message
CallValidation.report_error(
method_sig,
message,
'Bind',
nil,
method_sig.bind,
instance
)
end
end
# NOTE: We don't bother validating for missing or extra kwargs;
# the method call itself will take care of that.
method_sig.each_args_value_type(args) do |name, arg, type|
message = type.error_message_for_obj(arg)
if message
CallValidation.report_error(
method_sig,
message,
'Parameter',
name,
type,
arg,
caller_offset: 2
)
end
end
# The original method definition allows passing `nil` for the `&blk`
# argument, so we do not have to do any method_sig.block_type type checks
# of our own.
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
return_value = original_method.bind_call(instance, *args, &blk)
# The only type that is allowed to change the return value is `.void`.
# It ignores what you returned and changes it to be a private singleton.
if method_sig.return_type.is_a?(T::Private::Types::Void)
T::Private::Types::Void::VOID
else
message = method_sig.return_type.error_message_for_obj(return_value)
if message
CallValidation.report_error(
method_sig,
message,
'Return value',
nil,
method_sig.return_type,
return_value,
)
end
return_value
end
end
def self.create_validator_slow(mod, original_method, method_sig, original_visibility)
T::Private::ClassUtils.def_with_visibility(mod, method_sig.method_name, original_visibility) do |*args, &blk|
CallValidation.validate_call(self, original_method, method_sig, args, blk)
end
end
def self.validate_call(instance, original_method, method_sig, args, blk)
# This method is called for every `sig`. It's critical to keep it fast and
# reduce number of allocations that happen here.
if method_sig.bind
message = method_sig.bind.error_message_for_obj(instance)
if message
CallValidation.report_error(
method_sig,
message,
'Bind',
nil,
method_sig.bind,
instance
)
end
end
# NOTE: We don't bother validating for missing or extra kwargs;
# the method call itself will take care of that.
method_sig.each_args_value_type(args) do |name, arg, type|
message = type.error_message_for_obj(arg)
if message
CallValidation.report_error(
method_sig,
message,
'Parameter',
name,
type,
arg,
caller_offset: 2
)
end
end
# The Ruby VM already checks that `&blk` is either a `Proc` type or `nil`:
# https://github.com/ruby/ruby/blob/v2_7_6/vm_args.c#L1150-L1154
# And `T.proc` types don't (can't) do any runtime arg checking, so we can
# save work by simply checking that `blk` is non-nil (if the method allows
# `nil` for the block, it would not have used this validate_call path).
unless blk
# Have to use `&.` here, because it's technically a public API that
# people can _always_ call `validate_call` to validate any signature
# (i.e., the faster validators are merely optimizations).
# In practice, this only affects the first call to the method (before the
# optimized validators have a chance to replace the initial, slow
# wrapper).
message = method_sig.block_type&.error_message_for_obj(blk)
if message
CallValidation.report_error(
method_sig,
message,
'Block parameter',
method_sig.block_name,
method_sig.block_type,
blk
)
end
end
# The following line breaks are intentional to show nice pry message
# PRY note:
# this code is sig validation code.
# Please issue `finish` to step out of it
return_value = original_method.bind_call(instance, *args, &blk)
# The only type that is allowed to change the return value is `.void`.
# It ignores what you returned and changes it to be a private singleton.
if method_sig.return_type.is_a?(T::Private::Types::Void)
T::Private::Types::Void::VOID
else
message = method_sig.return_type.error_message_for_obj(return_value)
if message
CallValidation.report_error(
method_sig,
message,
'Return value',
nil,
method_sig.return_type,
return_value,
)
end
return_value
end
end
def self.report_error(method_sig, error_message, kind, name, type, value, caller_offset: 0)
caller_loc = T.must(caller_locations(3 + caller_offset, 1))[0]
method = method_sig.method
definition_file, definition_line = method.source_location
owner = method.owner
pretty_method_name =
if owner.singleton_class? && owner.respond_to?(:attached_object)
# attached_object is new in Ruby 3.2
"#{owner.attached_object}.#{method.name}"
else
"#{owner}##{method.name}"
end
pretty_message = "#{kind}#{name ? " '#{name}'" : ''}: #{error_message}\n" \
"Caller: #{caller_loc.path}:#{caller_loc.lineno}\n" \
"Definition: #{definition_file}:#{definition_line} (#{pretty_method_name})"
T::Configuration.call_validation_error_handler(
method_sig,
message: error_message,
pretty_message: pretty_message,
kind: kind,
name: name,
type: type,
value: value,
location: caller_loc
)
end
end
require_relative './call_validation_2_7'
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/methods/decl_builder.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/methods/decl_builder.rb | # frozen_string_literal: true
# typed: true
module T::Private::Methods
Declaration = Struct.new(:mod, :params, :returns, :bind, :mode, :checked, :finalized, :on_failure, :override_allow_incompatible, :type_parameters, :raw)
class DeclBuilder
attr_reader :decl
class BuilderError < StandardError; end
private def check_live!
if decl.finalized
raise BuilderError.new("You can't modify a signature declaration after it has been used.")
end
end
def initialize(mod, raw)
@decl = Declaration.new(
mod,
ARG_NOT_PROVIDED, # params
ARG_NOT_PROVIDED, # returns
ARG_NOT_PROVIDED, # bind
Modes.standard, # mode
ARG_NOT_PROVIDED, # checked
false, # finalized
ARG_NOT_PROVIDED, # on_failure
nil, # override_allow_incompatible
ARG_NOT_PROVIDED, # type_parameters
raw
)
end
def params(*unused_positional_params, **params)
check_live!
if !decl.params.equal?(ARG_NOT_PROVIDED)
raise BuilderError.new("You can't call .params twice")
end
if unused_positional_params.any?
some_or_only = params.any? ? "some" : "only"
raise BuilderError.new(<<~MSG)
'params' was called with #{some_or_only} positional arguments, but it needs to be called with keyword arguments.
The keyword arguments' keys must match the name and order of the method's parameters.
MSG
end
if params.empty?
raise BuilderError.new(<<~MSG)
'params' was called without any arguments, but it needs to be called with keyword arguments.
The keyword arguments' keys must match the name and order of the method's parameters.
Omit 'params' entirely for methods with no parameters.
MSG
end
decl.params = params
self
end
def returns(type)
check_live!
if decl.returns.is_a?(T::Private::Types::Void)
raise BuilderError.new("You can't call .returns after calling .void.")
end
if !decl.returns.equal?(ARG_NOT_PROVIDED)
raise BuilderError.new("You can't call .returns multiple times in a signature.")
end
decl.returns = type
self
end
def void
check_live!
if !decl.returns.equal?(ARG_NOT_PROVIDED)
raise BuilderError.new("You can't call .void after calling .returns.")
end
decl.returns = T::Private::Types::Void::Private::INSTANCE
self
end
def bind(type)
check_live!
if !decl.bind.equal?(ARG_NOT_PROVIDED)
raise BuilderError.new("You can't call .bind multiple times in a signature.")
end
decl.bind = type
self
end
def checked(level)
check_live!
if !decl.checked.equal?(ARG_NOT_PROVIDED)
raise BuilderError.new("You can't call .checked multiple times in a signature.")
end
if level == :never && !decl.on_failure.equal?(ARG_NOT_PROVIDED)
raise BuilderError.new("You can't use .checked(:#{level}) with .on_failure because .on_failure will have no effect.")
end
if !T::Private::RuntimeLevels::LEVELS.include?(level)
raise BuilderError.new("Invalid `checked` level '#{level}'. Use one of: #{T::Private::RuntimeLevels::LEVELS}.")
end
decl.checked = level
self
end
def on_failure(*args)
check_live!
if !decl.on_failure.equal?(ARG_NOT_PROVIDED)
raise BuilderError.new("You can't call .on_failure multiple times in a signature.")
end
if decl.checked == :never
raise BuilderError.new("You can't use .on_failure with .checked(:#{decl.checked}) because .on_failure will have no effect.")
end
decl.on_failure = args
self
end
def abstract
check_live!
case decl.mode
when Modes.standard
decl.mode = Modes.abstract
when Modes.abstract
raise BuilderError.new(".abstract cannot be repeated in a single signature")
else
raise BuilderError.new("`.abstract` cannot be combined with `.override` or `.overridable`.")
end
self
end
def final
check_live!
raise BuilderError.new("The syntax for declaring a method final is `sig(:final) {...}`, not `sig {final. ...}`")
end
def override(allow_incompatible: false)
check_live!
case decl.mode
when Modes.standard
decl.mode = Modes.override
case allow_incompatible
when true, false, :visibility
decl.override_allow_incompatible = allow_incompatible
else
raise BuilderError.new(".override(allow_incompatible: ...) only accepts `true`, `false`, or `:visibility`, got: #{allow_incompatible.inspect}")
end
when Modes.override, Modes.overridable_override
raise BuilderError.new(".override cannot be repeated in a single signature")
when Modes.overridable
decl.mode = Modes.overridable_override
else
raise BuilderError.new("`.override` cannot be combined with `.abstract`.")
end
self
end
def overridable
check_live!
case decl.mode
when Modes.abstract
raise BuilderError.new("`.overridable` cannot be combined with `.#{decl.mode}`")
when Modes.override
decl.mode = Modes.overridable_override
when Modes.standard
decl.mode = Modes.overridable
when Modes.overridable, Modes.overridable_override
raise BuilderError.new(".overridable cannot be repeated in a single signature")
end
self
end
# Declares valid type parameters which can be used with `T.type_parameter` in
# this `sig`.
#
# This is used for generic methods. Example usage:
#
# sig do
# type_parameters(:U)
# .params(blk: T.proc.params(arg0: Elem).returns(T.type_parameter(:U)))
# .returns(T::Array[T.type_parameter(:U)])
# end
# def map(&blk); end
def type_parameters(*names)
check_live!
names.each do |name|
raise BuilderError.new("not a symbol: #{name}") unless name.is_a?(Symbol)
end
if !decl.type_parameters.equal?(ARG_NOT_PROVIDED)
raise BuilderError.new("You can't call .type_parameters multiple times in a signature.")
end
decl.type_parameters = names
self
end
def finalize!
check_live!
if decl.returns.equal?(ARG_NOT_PROVIDED)
raise BuilderError.new("You must provide a return type; use the `.returns` or `.void` builder methods.")
end
if decl.bind.equal?(ARG_NOT_PROVIDED)
decl.bind = nil
end
if decl.checked.equal?(ARG_NOT_PROVIDED)
default_checked_level = T::Private::RuntimeLevels.default_checked_level
if default_checked_level == :never && !decl.on_failure.equal?(ARG_NOT_PROVIDED)
raise BuilderError.new("To use .on_failure you must additionally call .checked(:tests) or .checked(:always), otherwise, the .on_failure has no effect.")
end
decl.checked = default_checked_level
end
if decl.on_failure.equal?(ARG_NOT_PROVIDED)
decl.on_failure = nil
end
if decl.params.equal?(ARG_NOT_PROVIDED)
decl.params = FROZEN_HASH
end
if decl.type_parameters.equal?(ARG_NOT_PROVIDED)
decl.type_parameters = FROZEN_HASH
end
decl.finalized = true
self
end
FROZEN_HASH = {}.freeze
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/types/simple_pair_union.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/types/simple_pair_union.rb | # frozen_string_literal: true
# typed: true
# Specialization of Union for the common case of the union of two simple types.
#
# This covers e.g. T.nilable(SomeModule), T.any(Integer, Float), and T::Boolean.
class T::Private::Types::SimplePairUnion < T::Types::Union
class DuplicateType < RuntimeError; end
# @param type_a [T::Types::Simple]
# @param type_b [T::Types::Simple]
def initialize(type_a, type_b)
if type_a == type_b
raise DuplicateType.new("#{type_a} == #{type_b}")
end
@raw_a = type_a.raw_type
@raw_b = type_b.raw_type
end
# @override Union
def recursively_valid?(obj)
obj.is_a?(@raw_a) || obj.is_a?(@raw_b)
end
# @override Union
def valid?(obj)
obj.is_a?(@raw_a) || obj.is_a?(@raw_b)
end
# @override Union
def types
# We reconstruct the simple types rather than just storing them because
# (1) this is normally not a hot path and (2) we want to keep the instance
# variable count <= 3 so that we can fit in a 40 byte heap entry along
# with object headers.
@types ||= [
T::Types::Simple::Private::Pool.type_for_module(@raw_a),
T::Types::Simple::Private::Pool.type_for_module(@raw_b),
]
end
# overrides Union
def unwrap_nilable
a_nil = @raw_a.equal?(NilClass)
b_nil = @raw_b.equal?(NilClass)
if a_nil
return types[1]
end
if b_nil
return types[0]
end
nil
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/types/string_holder.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/types/string_holder.rb | # frozen_string_literal: true
# typed: true
# Holds a string. Useful for showing type aliases in error messages
class T::Private::Types::StringHolder < T::Types::Base
attr_reader :string
def initialize(string)
@string = string
end
def build_type
nil
end
# overrides Base
def name
string
end
# overrides Base
def valid?(obj)
false
end
# overrides Base
private def subtype_of_single?(other)
false
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/types/void.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/types/void.rb | # frozen_string_literal: true
# typed: true
# A marking class for when methods return void.
# Should never appear in types directly.
module T::Private::Types
class Void < T::Types::Base
ERROR_MESSAGE = "Validation is being done on an `Void`. Please report this bug at https://github.com/sorbet/sorbet/issues"
# The actual return value of `.void` methods.
#
# Uses `module VOID` because this gives it a readable name when someone
# examines it in Pry or with `#inspect` like:
#
# T::Private::Types::Void::VOID
#
module VOID
freeze
end
def build_type
nil
end
# overrides Base
def name
"<VOID>"
end
# overrides Base
def valid?(obj)
raise ERROR_MESSAGE
end
# overrides Base
private def subtype_of_single?(other)
raise ERROR_MESSAGE
end
module Private
INSTANCE = Void.new.freeze
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/types/not_typed.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/types/not_typed.rb | # frozen_string_literal: true
# typed: true
# A placeholder for when an untyped thing must provide a type.
# Raises an exception if it is ever used for validation.
class T::Private::Types::NotTyped < T::Types::Base
ERROR_MESSAGE = "Validation is being done on a `NotTyped`. Please report this bug at https://github.com/sorbet/sorbet/issues"
def build_type
nil
end
# overrides Base
def name
"<NOT-TYPED>"
end
# overrides Base
def valid?(obj)
raise ERROR_MESSAGE
end
# overrides Base
private def subtype_of_single?(other)
raise ERROR_MESSAGE
end
INSTANCE = ::T::Private::Types::NotTyped.new.freeze
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/types/type_alias.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/types/type_alias.rb | # frozen_string_literal: true
# typed: true
module T::Private::Types
# Wraps a proc for a type alias to defer its evaluation.
class TypeAlias < T::Types::Base
def initialize(callable)
@callable = callable
end
def build_type
nil
end
def aliased_type
@aliased_type ||= T::Utils.coerce(@callable.call)
end
# overrides Base
def name
aliased_type.name
end
# overrides Base
def recursively_valid?(obj)
aliased_type.recursively_valid?(obj)
end
# overrides Base
def valid?(obj)
aliased_type.valid?(obj)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/mixins/mixins.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/private/mixins/mixins.rb | # frozen_string_literal: true
# typed: true
module T::Private
module MixesInClassMethods
def included(other)
mods = Abstract::Data.get(self, :class_methods_mixins)
mods.each { |mod| other.extend(mod) }
super
end
end
module Mixins
def self.declare_mixes_in_class_methods(mixin, class_methods)
if mixin.is_a?(Class)
raise "Classes cannot be used as mixins, and so mixes_in_class_methods cannot be used on a Class."
end
if Abstract::Data.key?(mixin, :class_methods_mixins)
class_methods = Abstract::Data.get(mixin, :class_methods_mixins) + class_methods
end
mixin.singleton_class.include(MixesInClassMethods)
Abstract::Data.set(mixin, :class_methods_mixins, class_methods)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/type_parameter.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/type_parameter.rb | # frozen_string_literal: true
# typed: true
module T::Types
class TypeParameter < Base
module Private
@pool = {}
def self.cached_entry(name)
@pool[name]
end
def self.set_entry_for(name, type)
@pool[name] = type
end
end
def initialize(name)
raise ArgumentError.new("not a symbol: #{name}") unless name.is_a?(Symbol)
@name = name
end
def build_type
nil
end
def self.make(name)
cached = Private.cached_entry(name)
return cached if cached
Private.set_entry_for(name, new(name))
end
def valid?(obj)
true
end
def subtype_of_single?(type)
true
end
def name
"T.type_parameter(:#{@name})"
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_enumerator_lazy.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_enumerator_lazy.rb | # frozen_string_literal: true
# typed: true
module T::Types
class TypedEnumeratorLazy < TypedEnumerable
def underlying_class
Enumerator::Lazy
end
# overrides Base
def name
"T::Enumerator::Lazy[#{type.name}]"
end
# overrides Base
def recursively_valid?(obj)
obj.is_a?(Enumerator::Lazy) && super
end
# overrides Base
def valid?(obj)
obj.is_a?(Enumerator::Lazy)
end
def new(...)
Enumerator::Lazy.new(...)
end
class Untyped < TypedEnumeratorLazy
def initialize
super(T::Types::Untyped::Private::INSTANCE)
end
def valid?(obj)
obj.is_a?(Enumerator::Lazy)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/untyped.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/untyped.rb | # frozen_string_literal: true
# typed: true
module T::Types
# A dynamic type, which permits whatever
class Untyped < Base
def initialize; end
def build_type
nil
end
# overrides Base
def name
"T.untyped"
end
# overrides Base
def valid?(obj)
true
end
# overrides Base
private def subtype_of_single?(other)
true
end
module Private
INSTANCE = Untyped.new.freeze
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/proc.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/proc.rb | # frozen_string_literal: true
# typed: true
module T::Types
# Defines the type of a proc (a ruby callable). At runtime, only
# validates that the value is a `::Proc`.
#
# At present, we only support fixed-arity procs with no optional or
# keyword arguments.
class Proc < Base
def initialize(arg_types, returns)
@inner_arg_types = arg_types
@inner_returns = returns
end
def arg_types
@arg_types ||= @inner_arg_types.transform_values do |raw_type|
T::Utils.coerce(raw_type)
end
end
def returns
@returns ||= T::Utils.coerce(@inner_returns)
end
def build_type
arg_types
returns
nil
end
# overrides Base
def name
args = []
arg_types.each do |k, v|
args << "#{k}: #{v.name}"
end
"T.proc.params(#{args.join(', ')}).returns(#{returns})"
end
# overrides Base
def valid?(obj)
obj.is_a?(::Proc)
end
# overrides Base
private def subtype_of_single?(other)
case other
when self.class
if arg_types.size != other.arg_types.size
return false
end
arg_types.values.zip(other.arg_types.values).all? do |a, b|
!b.nil? && b.subtype_of?(a)
end && returns.subtype_of?(other.returns)
else
false
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_set.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_set.rb | # frozen_string_literal: true
# typed: true
module T::Types
class TypedSet < TypedEnumerable
def underlying_class
Set
end
# overrides Base
def name
"T::Set[#{type.name}]"
end
# overrides Base
def recursively_valid?(obj)
return false if Object.autoload?(:Set) # Set is meant to be autoloaded but not yet loaded, this value can't be a Set
return false unless Object.const_defined?(:Set) # Set is not loaded yet
obj.is_a?(Set) && super
end
# overrides Base
def valid?(obj)
return false if Object.autoload?(:Set) # Set is meant to be autoloaded but not yet loaded, this value can't be a Set
return false unless Object.const_defined?(:Set) # Set is not loaded yet
obj.is_a?(Set)
end
def new(...)
# Fine for this to blow up, because hopefully if they're trying to make a
# Set, they don't mind putting (or already have put) a `require 'set'` in
# their program directly.
Set.new(...)
end
class Untyped < TypedSet
def initialize
super(T::Types::Untyped::Private::INSTANCE)
end
def valid?(obj)
return false if Object.autoload?(:Set) # Set is meant to be autoloaded but not yet loaded, this value can't be a Set
return false unless Object.const_defined?(:Set) # Set is not loaded yet
obj.is_a?(Set)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/class_of.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/class_of.rb | # frozen_string_literal: true
# typed: true
module T::Types
# Validates that an object belongs to the specified class.
class ClassOf < Base
attr_reader :type
def initialize(type)
@type = type
end
def build_type
nil
end
# overrides Base
def name
"T.class_of(#{@type})"
end
# overrides Base
def valid?(obj)
obj.is_a?(@type.singleton_class)
end
# overrides Base
def subtype_of_single?(other)
case other
when ClassOf
@type.is_a?(other.type.singleton_class)
when Simple
@type.is_a?(other.raw_type)
when TypedClass, TypedModule
@type.is_a?(other.underlying_class)
else
false
end
end
# overrides Base
def describe_obj(obj)
obj.inspect
end
# So that `T.class_of(...)[...]` syntax is valid.
# Mirrors the definition of T::Generic#[] (generics are erased).
#
# We avoid simply writing `include T::Generic` because we don't want any of
# the other methods to appear (`T.class_of(A).type_member` doesn't make sense)
def [](*types)
self
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_hash.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_hash.rb | # frozen_string_literal: true
# typed: true
module T::Types
class TypedHash < TypedEnumerable
def underlying_class
Hash
end
def initialize(keys:, values:)
@inner_keys = keys
@inner_values = values
end
# Technically we don't need this, but it is a nice api
def keys
@keys ||= T::Utils.coerce(@inner_keys)
end
# Technically we don't need this, but it is a nice api
def values
@values ||= T::Utils.coerce(@inner_values)
end
def type
@type ||= T::Utils.coerce([keys, values])
end
# overrides Base
def name
"T::Hash[#{keys.name}, #{values.name}]"
end
# overrides Base
def recursively_valid?(obj)
obj.is_a?(Hash) && super
end
# overrides Base
def valid?(obj)
obj.is_a?(Hash)
end
def new(...)
Hash.new(...)
end
class Untyped < TypedHash
def initialize
super(keys: T.untyped, values: T.untyped)
end
def valid?(obj)
obj.is_a?(Hash)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/type_member.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/type_member.rb | # frozen_string_literal: true
# typed: strict
module T::Types
class TypeMember < TypeVariable
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_enumerable.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_enumerable.rb | # frozen_string_literal: true
# typed: true
module T::Types
# Note: All subclasses of Enumerable should add themselves to the
# `case` statement below in `describe_obj` in order to get better
# error messages.
class TypedEnumerable < Base
def initialize(type)
@inner_type = type
end
def type
@type ||= T::Utils.coerce(@inner_type)
end
def build_type
type
nil
end
def underlying_class
Enumerable
end
# overrides Base
def name
"T::Enumerable[#{type.name}]"
end
# overrides Base
def valid?(obj)
obj.is_a?(Enumerable)
end
# overrides Base
def recursively_valid?(obj)
return false unless obj.is_a?(Enumerable)
case obj
when Array
it = 0
while it < obj.count
return false unless type.recursively_valid?(obj[it])
it += 1
end
true
when Hash
type_ = self.type
return false unless type_.is_a?(FixedArray)
key_type, value_type = type_.types
return false if key_type.nil? || value_type.nil? || type_.types.size > 2
obj.each_pair do |key, val|
# Some objects (I'm looking at you Rack::Utils::HeaderHash) don't
# iterate over a [key, value] array, so we can't just use the type.recursively_valid?(v)
return false if !key_type.recursively_valid?(key) || !value_type.recursively_valid?(val)
end
true
when Enumerator::Lazy
# Enumerators can be unbounded: see `[:foo, :bar].cycle`
true
when Enumerator::Chain
# Enumerators can be unbounded: see `[:foo, :bar].cycle`
true
when Enumerator
# Enumerators can be unbounded: see `[:foo, :bar].cycle`
true
when Range
# A nil beginning or a nil end does not provide any type information. That is, nil in a range represents
# boundlessness, it does not express a type. For example `(nil...nil)` is not a T::Range[NilClass], its a range
# of unknown types (T::Range[T.untyped]).
# Similarly, `(nil...1)` is not a `T::Range[T.nilable(Integer)]`, it's a boundless range of Integer.
(obj.begin.nil? || type.recursively_valid?(obj.begin)) && (obj.end.nil? || type.recursively_valid?(obj.end))
when Set
obj.each do |item|
return false unless type.recursively_valid?(item)
end
true
else
# We don't check the enumerable since it isn't guaranteed to be
# rewindable (e.g. STDIN) and it may be expensive to enumerate
# (e.g. an enumerator that makes an HTTP request)"
true
end
end
# overrides Base
private def subtype_of_single?(other)
if other.class <= TypedEnumerable &&
underlying_class <= other.underlying_class
# Enumerables are covariant because they are read only
#
# Properly speaking, many Enumerable subtypes (e.g. Set)
# should be invariant because they are mutable and support
# both reading and writing. However, Sorbet treats *all*
# Enumerable subclasses as covariant for ease of adoption.
type.subtype_of?(other.type)
elsif other.class <= Simple
underlying_class <= other.raw_type
else
false
end
end
# overrides Base
def describe_obj(obj)
return super unless obj.is_a?(Enumerable)
type_from_instance(obj).name
end
private def type_from_instances(objs)
return objs.class unless objs.is_a?(Enumerable)
obtained_types = []
begin
objs.each do |x|
obtained_types << type_from_instance(x)
end
rescue
return T.untyped # all we can do is go with the types we have so far
end
if obtained_types.count > 1
# Multiple kinds of bad types showed up, we'll suggest a union
# type you might want.
Union.new(obtained_types)
elsif obtained_types.empty?
T.noreturn
else
# Everything was the same bad type, lets just show that
obtained_types.first
end
end
private def type_from_instance(obj)
if [true, false].include?(obj)
return T::Boolean
elsif !obj.is_a?(Enumerable)
return obj.class
end
case obj
when Array
T::Array[type_from_instances(obj)]
when Hash
inferred_key = type_from_instances(obj.keys)
inferred_val = type_from_instances(obj.values)
T::Hash[inferred_key, inferred_val]
when Range
# We can't get any information from `NilClass` in ranges (since nil is used to represent boundlessness).
typeable_objects = [obj.begin, obj.end].compact
if typeable_objects.empty?
T::Range[T.untyped]
else
T::Range[type_from_instances(typeable_objects)]
end
when Enumerator::Lazy
T::Enumerator::Lazy[type_from_instances(obj)]
when Enumerator::Chain
T::Enumerator::Chain[type_from_instances(obj)]
when Enumerator
T::Enumerator[type_from_instances(obj)]
when Set
T::Set[type_from_instances(obj)]
when IO
# Short circuit for anything IO-like (File, etc.). In these cases,
# enumerating the object is a destructive operation and might hang.
obj.class
else
# This is a specialized enumerable type, just return the class.
Object.instance_method(:class).bind_call(obj)
end
end
class Untyped < TypedEnumerable
def initialize
super(T::Types::Untyped::Private::INSTANCE)
end
def valid?(obj)
obj.is_a?(Enumerable)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/type_variable.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/type_variable.rb | # frozen_string_literal: true
# typed: true
module T::Types
# Since we do type erasure at runtime, this just validates the variance and
# provides some syntax for the static type checker
class TypeVariable < Base
attr_reader :variance
VALID_VARIANCES = %i[in out invariant].freeze
def initialize(variance)
case variance
when Hash then raise ArgumentError.new("Pass bounds using a block. Got: #{variance}")
when *VALID_VARIANCES then nil
else
raise TypeError.new("invalid variance #{variance}")
end
@variance = variance
end
def build_type
nil
end
def valid?(obj)
true
end
def subtype_of_single?(type)
true
end
def name
Untyped.new.name
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_class.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_class.rb | # frozen_string_literal: true
# typed: true
module T::Types
class TypedClass < T::Types::Base
def initialize(type)
@inner_type = type
end
def type
@type ||= T::Utils.coerce(@inner_type)
end
def build_type
type
nil
end
# overrides Base
def name
"T::Class[#{type.name}]"
end
def underlying_class
Class
end
# overrides Base
def valid?(obj)
Class.===(obj)
end
# overrides Base
private def subtype_of_single?(type)
case type
when TypedClass, TypedModule
# treat like generics are erased
true
when Simple
Class <= type.raw_type
else
false
end
end
module Private
module Pool
CACHE_FROZEN_OBJECTS =
begin
ObjectSpace::WeakMap.new[1] = 1
true # Ruby 2.7 and newer
rescue ArgumentError
false # Ruby 2.6 and older
end
@cache = ObjectSpace::WeakMap.new
def self.type_for_module(mod)
cached = @cache[mod]
return cached if cached
type = TypedClass.new(mod)
if CACHE_FROZEN_OBJECTS || (!mod.frozen? && !type.frozen?)
@cache[mod] = type
end
type
end
end
end
class Untyped < TypedClass
def initialize
super(T::Types::Untyped::Private::INSTANCE)
end
def freeze
build_type # force lazy initialization before freezing the object
super
end
module Private
INSTANCE = Untyped.new.freeze
end
end
class Anything < TypedClass
def initialize
super(T.anything)
end
def freeze
build_type # force lazy initialization before freezing the object
super
end
module Private
INSTANCE = Anything.new.freeze
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/fixed_array.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/fixed_array.rb | # frozen_string_literal: true
# https://jira.corp.stripe.com/browse/RUBYPLAT-1107
# typed: false
module T::Types
# Takes a list of types. Validates each item in an array using the type in the same position
# in the list.
class FixedArray < Base
def initialize(types)
@inner_types = types
end
def types
@types ||= @inner_types.map { |type| T::Utils.coerce(type) }
end
def build_type
types
nil
end
# overrides Base
def name
"[#{types.join(', ')}]"
end
# overrides Base
def recursively_valid?(obj)
if obj.is_a?(Array) && obj.length == types.length
i = 0
while i < types.length
if !types[i].recursively_valid?(obj[i])
return false
end
i += 1
end
true
else
false
end
end
# overrides Base
def valid?(obj)
if obj.is_a?(Array) && obj.length == types.length
i = 0
while i < types.length
if !types[i].valid?(obj[i])
return false
end
i += 1
end
true
else
false
end
end
# overrides Base
private def subtype_of_single?(other)
case other
when FixedArray
# Properly speaking, covariance here is unsound since arrays
# can be mutated, but sorbet implements covariant tuples for
# ease of adoption.
types.size == other.types.size && types.zip(other.types).all? do |t1, t2|
t1.subtype_of?(t2)
end
when TypedArray
# warning: covariant arrays
value1, value2, *values_rest = types
value_type = if !value2.nil?
T::Types::Union::Private::Pool.union_of_types(value1, value2, values_rest)
elsif value1.nil?
T.untyped
else
value1
end
T::Types::TypedArray.new(value_type).subtype_of?(other)
else
false
end
end
# This gives us better errors, e.g.:
# "Expected [String, Symbol], got [String, String]"
# instead of
# "Expected [String, Symbol], got Array".
#
# overrides Base
def describe_obj(obj)
if obj.is_a?(Array)
if obj.length == types.length
item_classes = obj.map(&:class).join(', ')
"type [#{item_classes}]"
else
"array of size #{obj.length}"
end
else
super
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/base.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/base.rb | # frozen_string_literal: true
# typed: true
module T::Types
class Base
def self.method_added(method_name)
super(method_name)
# What is now `subtype_of_single?` used to be named `subtype_of?`. Make sure people don't
# override the wrong thing.
#
# NB: Outside of T::Types, we would enforce this by using `sig` and not declaring the method
# as overridable, but doing so here would result in a dependency cycle.
if method_name == :subtype_of? && self != T::Types::Base
raise "`subtype_of?` should not be overridden. You probably want to override " \
"`subtype_of_single?` instead."
end
end
# this will be redefined in certain subclasses
def recursively_valid?(obj)
valid?(obj)
end
define_method(:valid?) do |_obj|
raise NotImplementedError
end
# @return [T::Boolean] This method must be implemented to return whether the subclass is a subtype
# of `type`. This should only be called by `subtype_of?`, which guarantees that `type` will be
# a "single" type, by which we mean it won't be a Union or an Intersection (c.f.
# `isSubTypeSingle` in sorbet).
private def subtype_of_single?(type)
raise NotImplementedError
end
# Force any lazy initialization that this type might need to do
# It's unusual to call this directly; you probably want to call it indirectly via `T::Utils.run_all_sig_blocks`.
define_method(:build_type) do
raise NotImplementedError
end
# Equality is based on name, so be sure the name reflects all relevant state when implementing.
define_method(:name) do
raise NotImplementedError
end
# Mirrors ruby_typer::core::Types::isSubType
# See https://git.corp.stripe.com/stripe-internal/ruby-typer/blob/9fc8ed998c04ac0b96592ae6bb3493b8a925c5c1/core/types/subtyping.cc#L912-L950
#
# This method cannot be overridden (see `method_added` above).
# Subclasses only need to implement `subtype_of_single?`).
def subtype_of?(t2)
t1 = self
if t2.is_a?(T::Private::Types::TypeAlias)
t2 = t2.aliased_type
end
if t2.is_a?(T::Types::Anything)
return true
end
if t1.is_a?(T::Private::Types::TypeAlias)
return t1.aliased_type.subtype_of?(t2)
end
if t1.is_a?(T::Types::TypeVariable) || t2.is_a?(T::Types::TypeVariable)
# Generics are erased at runtime. Let's treat them like `T.untyped` for
# the purpose of things like override checking.
return true
end
# pairs to cover: 1 (_, _)
# 2 (_, And)
# 3 (_, Or)
# 4 (And, _)
# 5 (And, And)
# 6 (And, Or)
# 7 (Or, _)
# 8 (Or, And)
# 9 (Or, Or)
# Note: order of cases here matters!
if t1.is_a?(T::Types::Union) # 7, 8, 9
# this will be incorrect if/when we have Type members
return t1.types.all? { |t1_member| t1_member.subtype_of?(t2) }
end
if t2.is_a?(T::Types::Intersection) # 2, 5
# this will be incorrect if/when we have Type members
return t2.types.all? { |t2_member| t1.subtype_of?(t2_member) }
end
if t2.is_a?(T::Types::Union)
if t1.is_a?(T::Types::Intersection) # 6
# dropping either of parts eagerly make subtype test be too strict.
# we have to try both cases, when we normally try only one
return t2.types.any? { |t2_member| t1.subtype_of?(t2_member) } ||
t1.types.any? { |t1_member| t1_member.subtype_of?(t2) }
end
return t2.types.any? { |t2_member| t1.subtype_of?(t2_member) } # 3
end
if t1.is_a?(T::Types::Intersection) # 4
# this will be incorrect if/when we have Type members
return t1.types.any? { |t1_member| t1_member.subtype_of?(t2) }
end
# 1; Start with some special cases
if t1.is_a?(T::Private::Types::Void)
return t2.is_a?(T::Private::Types::Void)
end
if t1.is_a?(T::Types::Untyped) || t2.is_a?(T::Types::Untyped)
return true
end
# Rest of (1)
subtype_of_single?(t2)
end
def to_s
name
end
def describe_obj(obj)
# Would be redundant to print class and value in these common cases.
case obj
when nil, true, false
return "type #{obj.class}"
end
# In rare cases, obj.inspect may fail, or be undefined, so rescue.
begin
# Default inspect behavior of, eg; `#<Object:0x0...>` is ugly; just print the hash instead, which is more concise/readable.
if obj.method(:inspect).owner == Kernel
"type #{obj.class} with hash #{obj.hash}"
elsif T::Configuration.include_value_in_type_errors?
"type #{obj.class} with value #{T::Utils.string_truncate_middle(obj.inspect, 30, 30)}"
else
"type #{obj.class}"
end
rescue StandardError, SystemStackError
"type #{obj.class} with unprintable value"
end
end
def error_message_for_obj(obj)
if valid?(obj)
nil
else
error_message(obj)
end
end
def error_message_for_obj_recursive(obj)
if recursively_valid?(obj)
nil
else
error_message(obj)
end
end
private def error_message(obj)
"Expected type #{self.name}, got #{describe_obj(obj)}"
end
def validate!(obj)
err = error_message_for_obj(obj)
raise TypeError.new(err) if err
end
### Equality methods (necessary for deduping types with `uniq`)
def hash
name.hash
end
# Type equivalence, defined by serializing the type to a string (with
# `#name`) and comparing the resulting strings for equality.
def ==(other)
case other
when T::Types::Base
other.name == self.name
else
false
end
end
alias_method :eql?, :==
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_enumerator_chain.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_enumerator_chain.rb | # frozen_string_literal: true
# typed: true
module T::Types
class TypedEnumeratorChain < TypedEnumerable
def underlying_class
Enumerator::Chain
end
# overrides Base
def name
"T::Enumerator::Chain[#{type.name}]"
end
# overrides Base
def recursively_valid?(obj)
obj.is_a?(Enumerator::Chain) && super
end
# overrides Base
def valid?(obj)
obj.is_a?(Enumerator::Chain)
end
def new(...)
Enumerator::Chain.new(...)
end
class Untyped < TypedEnumeratorChain
def initialize
super(T::Types::Untyped::Private::INSTANCE)
end
def valid?(obj)
obj.is_a?(Enumerator::Chain)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/fixed_hash.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/fixed_hash.rb | # frozen_string_literal: true
# typed: true
module T::Types
# Takes a hash of types. Validates each item in a hash using the type in the same position
# in the list.
class FixedHash < Base
def initialize(types)
@inner_types = types
end
def types
@types ||= @inner_types.transform_values { |v| T::Utils.coerce(v) }
end
def build_type
types
nil
end
# overrides Base
def name
serialize_hash(types)
end
# overrides Base
def recursively_valid?(obj)
return false unless obj.is_a?(Hash)
return false if types.any? { |key, type| !type.recursively_valid?(obj[key]) }
return false if obj.any? { |key, _| !types[key] }
true
end
# overrides Base
def valid?(obj)
return false unless obj.is_a?(Hash)
return false if types.any? { |key, type| !type.valid?(obj[key]) }
return false if obj.any? { |key, _| !types[key] }
true
end
# overrides Base
private def subtype_of_single?(other)
case other
when FixedHash
# Using `subtype_of?` here instead of == would be unsound
types == other.types
when TypedHash
# warning: covariant hashes
key1, key2, *keys_rest = types.keys.map { |key| T::Utils.coerce(key.class) }
key_type = if !key2.nil?
T::Types::Union::Private::Pool.union_of_types(key1, key2, keys_rest)
elsif key1.nil?
T.untyped
else
key1
end
value1, value2, *values_rest = types.values
value_type = if !value2.nil?
T::Types::Union::Private::Pool.union_of_types(value1, value2, values_rest)
elsif value1.nil?
T.untyped
else
value1
end
T::Types::TypedHash.new(keys: key_type, values: value_type).subtype_of?(other)
else
false
end
end
# This gives us better errors, e.g.:
# `Expected {a: String}, got {a: TrueClass}`
# instead of
# `Expected {a: String}, got Hash`.
#
# overrides Base
def describe_obj(obj)
if obj.is_a?(Hash)
"type #{serialize_hash(obj.transform_values(&:class))}"
else
super
end
end
private
def serialize_hash(hash)
entries = hash.map do |(k, v)|
if Symbol === k && ":#{k}" == k.inspect
"#{k}: #{v}"
else
"#{k.inspect} => #{v}"
end
end
"{#{entries.join(', ')}}"
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/noreturn.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/noreturn.rb | # frozen_string_literal: true
# typed: true
module T::Types
# The bottom type
class NoReturn < Base
def initialize; end
def build_type
nil
end
# overrides Base
def name
"T.noreturn"
end
# overrides Base
def valid?(obj)
false
end
# overrides Base
private def subtype_of_single?(other)
true
end
module Private
INSTANCE = NoReturn.new.freeze
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/union.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/union.rb | # frozen_string_literal: true
# typed: true
module T::Types
# Takes a list of types. Validates that an object matches at least one of the types.
class Union < Base
# Don't use Union.new directly, use `Private::Pool.union_of_types`
# inside sorbet-runtime and `T.any` elsewhere.
def initialize(types)
@inner_types = types
end
def types
@types ||= @inner_types.flat_map do |type|
type = T::Utils.coerce(type)
if type.is_a?(Union)
# Simplify nested unions (mostly so `name` returns a nicer value)
type.types
else
type
end
end.uniq
end
def build_type
types
nil
end
# overrides Base
def name
# Use the attr_reader here so we can override it in SimplePairUnion
type_shortcuts(types)
end
private def type_shortcuts(types)
if types.size == 1
# We shouldn't generally get here but it's possible if initializing the type
# evades Sorbet's static check and we end up on the slow path, or if someone
# is using the T:Types::Union constructor directly (the latter possibility
# is why we don't just move the `uniq` into `Private::Pool.union_of_types`).
return types[0].name
end
nilable = T::Utils.coerce(NilClass)
trueclass = T::Utils.coerce(TrueClass)
falseclass = T::Utils.coerce(FalseClass)
if types.any? { |t| t == nilable }
remaining_types = types.reject { |t| t == nilable }
"T.nilable(#{type_shortcuts(remaining_types)})"
elsif types.any? { |t| t == trueclass } && types.any? { |t| t == falseclass }
remaining_types = types.reject { |t| t == trueclass || t == falseclass }
type_shortcuts([T::Private::Types::StringHolder.new("T::Boolean")] + remaining_types)
else
names = types.map(&:name).compact.sort
"T.any(#{names.join(', ')})"
end
end
# overrides Base
def recursively_valid?(obj)
types.any? { |type| type.recursively_valid?(obj) }
end
# overrides Base
def valid?(obj)
types.any? { |type| type.valid?(obj) }
end
# overrides Base
private def subtype_of_single?(other)
raise "This should never be reached if you're going through `subtype_of?` (and you should be)"
end
def unwrap_nilable
non_nil_types = types.reject { |t| t == T::Utils::Nilable::NIL_TYPE }
return nil if types.length == non_nil_types.length
case non_nil_types.length
when 0 then nil
when 1 then non_nil_types.first
else
T::Types::Union::Private::Pool.union_of_types(non_nil_types[0], non_nil_types[1], non_nil_types[2..-1])
end
end
module Private
module Pool
EMPTY_ARRAY = [].freeze
private_constant :EMPTY_ARRAY
# Try to use `to_nilable` on a type to get memoization, or failing that
# try to at least use SimplePairUnion to get faster init and typechecking.
#
# We aren't guaranteed to detect a simple `T.nilable(<Module>)` type here
# in cases where there are duplicate types, nested unions, etc.
#
# That's ok, because returning is SimplePairUnion an optimization which
# isn't necessary for correctness.
#
# @param type_a [T::Types::Base]
# @param type_b [T::Types::Base]
# @param types [Array] optional array of additional T::Types::Base instances
def self.union_of_types(type_a, type_b, types=EMPTY_ARRAY)
if !types.empty?
# Slow path
return Union.new([type_a, type_b] + types)
elsif !type_a.is_a?(T::Types::Simple) || !type_b.is_a?(T::Types::Simple)
# Slow path
return Union.new([type_a, type_b])
end
begin
if type_b == T::Utils::Nilable::NIL_TYPE
type_a.to_nilable
elsif type_a == T::Utils::Nilable::NIL_TYPE
type_b.to_nilable
else
T::Private::Types::SimplePairUnion.new(type_a, type_b)
end
rescue T::Private::Types::SimplePairUnion::DuplicateType
# Slow path
#
# This shouldn't normally be possible due to static checks,
# but we can get here if we're constructing a type dynamically.
#
# Relying on the duplicate check in the constructor has the
# advantage that we avoid it when we hit the memoized case
# of `to_nilable`.
type_a
end
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/simple.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/simple.rb | # frozen_string_literal: true
# typed: true
module T::Types
# Validates that an object belongs to the specified class.
class Simple < Base
NAME_METHOD = Module.instance_method(:name)
private_constant(:NAME_METHOD)
attr_reader :raw_type
def initialize(raw_type)
@raw_type = raw_type
end
def build_type
nil
end
# overrides Base
def name
# Memoize to mitigate pathological performance with anonymous modules (https://bugs.ruby-lang.org/issues/11119)
#
# `name` isn't normally a hot path for types, but it is used in initializing a T::Types::Union,
# and so in `T.nilable`, and so in runtime constructions like `x = T.let(nil, T.nilable(Integer))`.
#
# Care more about back compat than we do about performance here.
# Once 2.6 is well in the rear view mirror, we can replace this.
# rubocop:disable Performance/BindCall
@name ||= (NAME_METHOD.bind(@raw_type).call || @raw_type.name).freeze
# rubocop:enable Performance/BindCall
end
# overrides Base
def valid?(obj)
obj.is_a?(@raw_type)
end
# overrides Base
private def subtype_of_single?(other)
case other
when Simple
@raw_type <= other.raw_type
when TypedClass, TypedModule
# This case is a bit odd--we would have liked to solve this like we do
# for `T::Array` et al., but don't for backwards compatibility.
# See `type_for_module` below.
@raw_type <= other.underlying_class
else
false
end
end
# overrides Base
private def error_message(obj)
error_message = super(obj)
actual_name = obj.class.name
return error_message unless name == actual_name
<<~MSG.strip
#{error_message}
The expected type and received object type have the same name but refer to different constants.
Expected type is #{name} with object id #{@raw_type.__id__}, but received type is #{actual_name} with object id #{obj.class.__id__}.
There might be a constant reloading problem in your application.
MSG
end
def to_nilable
@nilable ||= T::Private::Types::SimplePairUnion.new(
self,
T::Utils::Nilable::NIL_TYPE,
)
end
module Private
module Pool
CACHE_FROZEN_OBJECTS = begin
ObjectSpace::WeakMap.new[1] = 1
true # Ruby 2.7 and newer
rescue ArgumentError # Ruby 2.6 and older
false
end
@cache = ObjectSpace::WeakMap.new
def self.type_for_module(mod)
cached = @cache[mod]
return cached if cached
type = if mod == ::Array
T::Array[T.untyped]
elsif mod == ::Hash
T::Hash[T.untyped, T.untyped]
elsif mod == ::Enumerable
T::Enumerable[T.untyped]
elsif mod == ::Enumerator
T::Enumerator[T.untyped]
elsif mod == ::Range
T::Range[T.untyped]
elsif !Object.autoload?(:Set) && Object.const_defined?(:Set) && mod == ::Set
T::Set[T.untyped]
else
# ideally we would have a case mapping from ::Class -> T::Class and
# ::Module -> T::Module here but for backwards compatibility we
# don't have that, and instead have a special case in subtype_of_single?
Simple.new(mod)
end
# Unfortunately, we still need to check if the module is frozen,
# since on 2.6 and older WeakMap adds a finalizer to the key that is added
# to the map, so that it can clear the map entry when the key is
# garbage collected.
# For a frozen object, though, adding a finalizer is not a valid
# operation, so this still raises if `mod` is frozen.
if CACHE_FROZEN_OBJECTS || (!mod.frozen? && !type.frozen?)
@cache[mod] = type
end
type
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/enum.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/enum.rb | # frozen_string_literal: true
# typed: true
module T::Types
# validates that the provided value is within a given set/enum
class Enum < Base
extend T::Sig
attr_reader :values
def initialize(values)
case values
when Hash
@values = values
else
require "set" unless defined?(Set)
@values = values.to_set
end
end
def build_type
nil
end
# overrides Base
def valid?(obj)
@values.member?(obj)
end
# overrides Base
private def subtype_of_single?(other)
case other
when Enum
(@values - other.values).empty?
else
false
end
end
# overrides Base
def name
@name ||= "T.deprecated_enum([#{@values.map(&:inspect).sort.join(', ')}])"
end
# overrides Base
def describe_obj(obj)
obj.inspect
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/type_template.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/type_template.rb | # frozen_string_literal: true
# typed: strict
module T::Types
class TypeTemplate < TypeVariable
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_enumerator.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_enumerator.rb | # frozen_string_literal: true
# typed: true
module T::Types
class TypedEnumerator < TypedEnumerable
def underlying_class
Enumerator
end
# overrides Base
def name
"T::Enumerator[#{type.name}]"
end
# overrides Base
def recursively_valid?(obj)
obj.is_a?(Enumerator) && super
end
# overrides Base
def valid?(obj)
obj.is_a?(Enumerator)
end
def new(...)
Enumerator.new(...)
end
class Untyped < TypedEnumerator
def initialize
super(T::Types::Untyped::Private::INSTANCE)
end
def valid?(obj)
obj.is_a?(Enumerator)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/anything.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/anything.rb | # frozen_string_literal: true
# typed: true
module T::Types
# The top type
class Anything < Base
def initialize; end
def build_type
nil
end
# overrides Base
def name
"T.anything"
end
# overrides Base
def valid?(obj)
true
end
# overrides Base
private def subtype_of_single?(other)
case other
when T::Types::Anything then true
else false
end
end
module Private
INSTANCE = Anything.new.freeze
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/self_type.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/self_type.rb | # frozen_string_literal: true
# typed: true
module T::Types
# Modeling self-types properly at runtime would require additional tracking,
# so at runtime we permit all values and rely on the static checker.
class SelfType < Base
def initialize(); end
def build_type
nil
end
# overrides Base
def name
"T.self_type"
end
# overrides Base
def valid?(obj)
true
end
# overrides Base
private def subtype_of_single?(other)
case other
when SelfType
true
else
false
end
end
module Private
INSTANCE = SelfType.new.freeze
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_module.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_module.rb | # frozen_string_literal: true
# typed: true
module T::Types
class TypedModule < T::Types::Base
def initialize(type)
@inner_type = type
end
def type
@type ||= T::Utils.coerce(@inner_type)
end
def build_type
type
nil
end
# overrides Base
def name
"T::Module[#{type.name}]"
end
def underlying_class
Module
end
# overrides Base
def valid?(obj)
Module.===(obj)
end
# overrides Base
private def subtype_of_single?(type)
case type
when TypedModule
# treat like generics are erased
true
when Simple
Module <= type.raw_type
else
false
end
end
module Private
module Pool
CACHE_FROZEN_OBJECTS =
begin
ObjectSpace::WeakMap.new[1] = 1
true # Ruby 2.7 and newer
rescue ArgumentError
false # Ruby 2.6 and older
end
@cache = ObjectSpace::WeakMap.new
def self.type_for_module(mod)
cached = @cache[mod]
return cached if cached
type = TypedModule.new(mod)
if CACHE_FROZEN_OBJECTS || (!mod.frozen? && !type.frozen?)
@cache[mod] = type
end
type
end
end
end
class Untyped < TypedModule
def initialize
super(T::Types::Untyped::Private::INSTANCE)
end
def freeze
build_type # force lazy initialization before freezing the object
super
end
module Private
INSTANCE = Untyped.new.freeze
end
end
class Anything < TypedModule
def initialize
super(T.anything)
end
def freeze
build_type # force lazy initialization before freezing the object
super
end
module Private
INSTANCE = Anything.new.freeze
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/attached_class.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/attached_class.rb | # frozen_string_literal: true
# typed: true
module T::Types
# Modeling AttachedClass properly at runtime would require additional
# tracking, so at runtime we permit all values and rely on the static checker.
# As AttachedClass is modeled statically as a type member on every singleton
# class, this is consistent with the runtime behavior for all type members.
class AttachedClassType < Base
def initialize(); end
def build_type
nil
end
# overrides Base
def name
"T.attached_class"
end
# overrides Base
def valid?(obj)
true
end
# overrides Base
private def subtype_of_single?(other)
case other
when AttachedClassType
true
else
false
end
end
module Private
INSTANCE = AttachedClassType.new.freeze
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/t_enum.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/t_enum.rb | # frozen_string_literal: true
# typed: true
module T::Types
# Validates that an object is equal to another T::Enum singleton value.
class TEnum < Base
attr_reader :val
def initialize(val)
@val = val
end
def build_type
nil
end
# overrides Base
def name
# Strips the #<...> off, just leaving the ...
# Reasoning: the user will have written something like
# T.any(MyEnum::A, MyEnum::B)
# in the type, so we should print what they wrote in errors, not:
# T.any(#<MyEnum::A>, #<MyEnum::B>)
@val.inspect[2..-2]
end
# overrides Base
def valid?(obj)
@val == obj
end
# overrides Base
private def subtype_of_single?(other)
case other
when TEnum
@val == other.val
when Simple
other.raw_type.===(@val)
else
false
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_array.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_array.rb | # frozen_string_literal: true
# typed: true
module T::Types
class TypedArray < TypedEnumerable
# overrides Base
def name
"T::Array[#{type.name}]"
end
def underlying_class
Array
end
# overrides Base
def recursively_valid?(obj)
obj.is_a?(Array) && super
end
# overrides Base
def valid?(obj)
obj.is_a?(Array)
end
def new(...)
Array.new(...)
end
module Private
module Pool
CACHE_FROZEN_OBJECTS = begin
ObjectSpace::WeakMap.new[1] = 1
true # Ruby 2.7 and newer
rescue ArgumentError # Ruby 2.6 and older
false
end
@cache = ObjectSpace::WeakMap.new
def self.type_for_module(mod)
cached = @cache[mod]
return cached if cached
type = TypedArray.new(mod)
if CACHE_FROZEN_OBJECTS || (!mod.frozen? && !type.frozen?)
@cache[mod] = type
end
type
end
end
end
class Untyped < TypedArray
def initialize
super(T::Types::Untyped::Private::INSTANCE)
end
def valid?(obj)
obj.is_a?(Array)
end
def freeze
build_type # force lazy initialization before freezing the object
super
end
module Private
INSTANCE = Untyped.new.freeze
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/intersection.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/intersection.rb | # frozen_string_literal: true
# typed: true
module T::Types
# Takes a list of types. Validates that an object matches all of the types.
class Intersection < Base
def initialize(types)
@inner_types = types
end
def types
@types ||= @inner_types.flat_map do |type|
type = T::Utils.resolve_alias(type)
if type.is_a?(Intersection)
# Simplify nested intersections (mostly so `name` returns a nicer value)
type.types
else
T::Utils.coerce(type)
end
end.uniq
end
def build_type
types
nil
end
# overrides Base
def name
"T.all(#{types.map(&:name).compact.sort.join(', ')})"
end
# overrides Base
def recursively_valid?(obj)
types.all? { |type| type.recursively_valid?(obj) }
end
# overrides Base
def valid?(obj)
types.all? { |type| type.valid?(obj) }
end
# overrides Base
private def subtype_of_single?(other)
raise "This should never be reached if you're going through `subtype_of?` (and you should be)"
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_range.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/types/typed_range.rb | # frozen_string_literal: true
# typed: true
module T::Types
class TypedRange < TypedEnumerable
def underlying_class
Range
end
# overrides Base
def name
"T::Range[#{type.name}]"
end
# overrides Base
def recursively_valid?(obj)
obj.is_a?(Range) && super
end
# overrides Base
def valid?(obj)
obj.is_a?(Range)
end
def new(...)
Range.new(...)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/serializable.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/serializable.rb | # frozen_string_literal: true
# typed: false
module T::Props::Serializable
include T::Props::Plugin
# Required because we have special handling for `optional: false`
include T::Props::Optional
# Required because we have special handling for extra_props
include T::Props::PrettyPrintable
# Serializes this object to a hash, suitable for conversion to
# JSON/BSON.
#
# @param strict [T::Boolean] (true) If false, do not raise an
# exception if this object has mandatory props with missing
# values.
# @return [Hash] A serialization of this object.
def serialize(strict=true)
begin
h = __t_props_generated_serialize(strict)
rescue => e
msg = self.class.decorator.message_with_generated_source_context(
e,
:__t_props_generated_serialize,
:generate_serialize_source
)
if msg
begin
raise e.class.new(msg)
rescue ArgumentError
raise TypeError.new(msg)
end
else
raise
end
end
h.merge!(@_extra_props) if defined?(@_extra_props)
h
end
private def __t_props_generated_serialize(strict)
# No-op; will be overridden if there are any props.
#
# To see the definition for class `Foo`, run `Foo.decorator.send(:generate_serialize_source)`
{}
end
# Populates the property values on this object with the values
# from a hash. In general, prefer to use {.from_hash} to construct
# a new instance, instead of loading into an existing instance.
#
# @param hash [Hash<String, Object>] The hash to take property
# values from.
# @param strict [T::Boolean] (false) If true, raise an exception if
# the hash contains keys that do not correspond to any known
# props on this instance.
# @return [void]
def deserialize(hash, strict=false)
begin
hash_keys_matching_props = __t_props_generated_deserialize(hash)
rescue => e
msg = self.class.decorator.message_with_generated_source_context(
e,
:__t_props_generated_deserialize,
:generate_deserialize_source
)
if msg
begin
raise e.class.new(msg)
rescue ArgumentError
raise TypeError.new(msg)
end
else
raise
end
end
if hash.size > hash_keys_matching_props
serialized_forms = self.class.decorator.prop_by_serialized_forms
extra = hash.reject { |k, _| serialized_forms.key?(k) }
# `extra` could still be empty here if the input matches a `dont_store` prop;
# historically, we just ignore those
if !extra.empty?
if strict
raise "Unknown properties for #{self.class.name}: #{extra.keys.inspect}"
else
@_extra_props = extra
end
end
end
end
private def __t_props_generated_deserialize(hash)
# No-op; will be overridden if there are any props.
#
# To see the definition for class `Foo`, run `Foo.decorator.send(:generate_deserialize_source)`
0
end
# with() will clone the old object to the new object and merge the specified props to the new object.
def with(changed_props)
with_existing_hash(changed_props, existing_hash: self.serialize)
end
private def recursive_stringify_keys(obj)
if obj.is_a?(Hash)
new_obj = obj.class.new
obj.each do |k, v|
new_obj[k.to_s] = recursive_stringify_keys(v)
end
elsif obj.is_a?(Array)
new_obj = obj.map { |v| recursive_stringify_keys(v) }
else
new_obj = obj
end
new_obj
end
private def with_existing_hash(changed_props, existing_hash:)
serialized = existing_hash
new_val = self.class.from_hash(serialized.merge(recursive_stringify_keys(changed_props)))
old_extra = self.instance_variable_get(:@_extra_props)
new_extra = new_val.instance_variable_get(:@_extra_props)
if old_extra != new_extra
difference =
if old_extra
new_extra.reject { |k, v| old_extra[k] == v }
else
new_extra
end
raise ArgumentError.new("Unexpected arguments: input(#{changed_props}), unexpected(#{difference})")
end
new_val
end
# Asserts if this property is missing during strict serialize
private def required_prop_missing_from_serialize(prop)
if @_required_props_missing_from_deserialize&.include?(prop)
# If the prop was already missing during deserialization, that means the application
# code already had to deal with a nil value, which means we wouldn't be accomplishing
# much by raising here (other than causing an unnecessary breakage).
T::Configuration.log_info_handler(
"chalk-odm: missing required property in serialize",
prop: prop, class: self.class.name, id: self.class.decorator.get_id(self)
)
else
raise TypeError.new("#{self.class.name}.#{prop} not set for non-optional prop")
end
end
# Marks this property as missing during deserialize
private def required_prop_missing_from_deserialize(prop)
@_required_props_missing_from_deserialize ||= Set[]
@_required_props_missing_from_deserialize << prop
nil
end
private def raise_deserialization_error(prop_name, value, orig_error)
T::Configuration.soft_assert_handler(
'Deserialization error (probably unexpected stored type)',
storytime: {
klass: self.class,
prop: prop_name,
value: value,
error: orig_error.message,
notify: 'djudd'
}
)
end
end
##############################################
# NB: This must stay in the same file where T::Props::Serializable is defined due to
# T::Props::Decorator#apply_plugin; see https://git.corp.stripe.com/stripe-internal/pay-server/blob/fc7f15593b49875f2d0499ffecfd19798bac05b3/chalk/odm/lib/chalk-odm/document_decorator.rb#L716-L717
module T::Props::Serializable::DecoratorMethods
include T::Props::HasLazilySpecializedMethods::DecoratorMethods
# Heads up!
#
# There are already too many ad-hoc options on the prop DSL.
#
# We have already done a lot of work to remove unnecessary and confusing
# options. If you're considering adding a new rule key, please come chat with
# the Sorbet team first, as we'd really like to learn more about how to best
# solve the problem you're encountering.
VALID_RULE_KEYS = {dont_store: true, name: true, raise_on_nil_write: true}.freeze
private_constant :VALID_RULE_KEYS
def valid_rule_key?(key)
super || VALID_RULE_KEYS[key]
end
def required_props
@class.props.select { |_, v| T::Props::Utils.required_prop?(v) }.keys
end
def prop_dont_store?(prop)
prop_rules(prop)[:dont_store]
end
def prop_by_serialized_forms
@class.prop_by_serialized_forms
end
def from_hash(hash, strict=false)
raise ArgumentError.new("#{hash.inspect} provided to from_hash") if !(hash && hash.is_a?(Hash))
i = @class.allocate
i.deserialize(hash, strict)
i
end
def prop_serialized_form(prop)
prop_rules(prop)[:serialized_form]
end
def serialized_form_prop(serialized_form)
prop_by_serialized_forms[serialized_form.to_s] || raise("No such serialized form: #{serialized_form.inspect}")
end
def add_prop_definition(prop, rules)
serialized_form = rules.fetch(:name, prop.to_s)
rules[:serialized_form] = serialized_form
res = super
prop_by_serialized_forms[serialized_form] = prop
if T::Configuration.use_vm_prop_serde?
enqueue_lazy_vm_method_definition!(:__t_props_generated_serialize) { generate_serialize2 }
enqueue_lazy_vm_method_definition!(:__t_props_generated_deserialize) { generate_deserialize2 }
else
enqueue_lazy_method_definition!(:__t_props_generated_serialize) { generate_serialize_source }
enqueue_lazy_method_definition!(:__t_props_generated_deserialize) { generate_deserialize_source }
end
res
end
private def generate_serialize_source
T::Props::Private::SerializerGenerator.generate(props)
end
private def generate_deserialize_source
T::Props::Private::DeserializerGenerator.generate(
props,
props_with_defaults || {},
)
end
private def generate_serialize2
T::Props::Private::SerializerGenerator.generate2(decorated_class, props)
end
private def generate_deserialize2
T::Props::Private::DeserializerGenerator.generate2(
decorated_class,
props,
props_with_defaults || {},
)
end
def message_with_generated_source_context(error, generated_method, generate_source_method)
generated_method = generated_method.to_s
if error.backtrace_locations
line_loc = error.backtrace_locations.find { |l| l.base_label == generated_method }
return unless line_loc
line_num = line_loc.lineno
else
label = if RUBY_VERSION >= "3.4"
# in 'ClassName#__t_props_generated_serialize'"
"##{generated_method}'"
else
# in `__t_props_generated_serialize'"
"in `#{generated_method}'"
end
line_label = error.backtrace.find { |l| l.end_with?(label) }
return unless line_label
line_num = if line_label.start_with?("(eval)")
# (eval):13:in ...
line_label.split(':')[1]&.to_i
else
# (eval at /Users/jez/stripe/sorbet/gems/sorbet-runtime/lib/types/props/has_lazily_specialized_methods.rb:65):13:in ...
line_label.split(':')[2]&.to_i
end
end
return unless line_num
source_lines = self.send(generate_source_method).split("\n")
previous_blank = source_lines[0...line_num].rindex(&:empty?) || 0
next_blank = line_num + (source_lines[line_num..-1]&.find_index(&:empty?) || 0)
context = " #{source_lines[(previous_blank + 1)...next_blank].join("\n ")}"
<<~MSG
Error in #{decorated_class.name}##{generated_method}: #{error.message}
at line #{line_num - previous_blank - 1} in:
#{context}
MSG
end
def raise_nil_deserialize_error(hkey)
msg = "Tried to deserialize a required prop from a nil value. It's "\
"possible that a nil value exists in the database, so you should "\
"provide a `default: or factory:` for this prop (see go/optional "\
"for more details). If this is already the case, you probably "\
"omitted a required prop from the `fields:` option when doing a "\
"partial load."
storytime = {prop: hkey, klass: decorated_class.name}
# Notify the model owner if it exists, and always notify the API owner.
begin
if T::Configuration.class_owner_finder && (owner = T::Configuration.class_owner_finder.call(decorated_class))
T::Configuration.hard_assert_handler(
msg,
storytime: storytime,
project: owner
)
end
ensure
T::Configuration.hard_assert_handler(msg, storytime: storytime)
end
end
def prop_validate_definition!(name, cls, rules, type)
result = super
if (rules_name = rules[:name])
unless rules_name.is_a?(String)
raise ArgumentError.new("Invalid name in prop #{@class.name}.#{name}: #{rules_name.inspect}")
end
validate_prop_name(rules_name)
end
if !rules[:raise_on_nil_write].nil? && rules[:raise_on_nil_write] != true
raise ArgumentError.new("The value of `raise_on_nil_write` if specified must be `true` (given: #{rules[:raise_on_nil_write]}).")
end
result
end
def get_id(instance)
prop = prop_by_serialized_forms['_id']
if prop
get(instance, prop)
else
nil
end
end
EMPTY_EXTRA_PROPS = {}.freeze
private_constant :EMPTY_EXTRA_PROPS
def extra_props(instance)
instance.instance_variable_get(:@_extra_props) || EMPTY_EXTRA_PROPS
end
# adds to the default result of T::Props::PrettyPrintable
def pretty_print_extra(instance, pp)
# This is to maintain backwards compatibility with Stripe's codebase, where only the single line (through `inspect`)
# version is expected to add anything extra
return if !pp.is_a?(PP::SingleLine)
if (extra_props = extra_props(instance)) && !extra_props.empty?
pp.breakable
pp.text("@_extra_props=")
pp.group(1, "<", ">") do
extra_props.each_with_index do |(prop, value), i|
pp.breakable unless i.zero?
pp.text("#{prop}=")
value.pretty_print(pp)
end
end
end
end
end
##############################################
# NB: This must stay in the same file where T::Props::Serializable is defined due to
# T::Props::Decorator#apply_plugin; see https://git.corp.stripe.com/stripe-internal/pay-server/blob/fc7f15593b49875f2d0499ffecfd19798bac05b3/chalk/odm/lib/chalk-odm/document_decorator.rb#L716-L717
module T::Props::Serializable::ClassMethods
def prop_by_serialized_forms
@prop_by_serialized_forms ||= {}
end
# Allocate a new instance and call {#deserialize} to load a new
# object from a hash.
# @return [Serializable]
def from_hash(hash, strict=false)
self.decorator.from_hash(hash, strict)
end
# Equivalent to {.from_hash} with `strict` set to true.
# @return [Serializable]
def from_hash!(hash)
self.decorator.from_hash(hash, true)
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/errors.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/errors.rb | # frozen_string_literal: true
# typed: strict
module T::Props
class Error < StandardError; end
class InvalidValueError < Error; end
class ImmutableProp < Error; end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/weak_constructor.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/weak_constructor.rb | # frozen_string_literal: true
# typed: false
module T::Props::WeakConstructor
include T::Props::Optional
extend T::Sig
# checked(:never) - O(runtime object construction)
sig { params(hash: T::Hash[Symbol, T.untyped]).void.checked(:never) }
def initialize(hash={})
decorator = self.class.decorator
hash_keys_matching_props = decorator.construct_props_with_defaults(self, hash) +
decorator.construct_props_without_defaults(self, hash)
if hash_keys_matching_props < hash.size
raise ArgumentError.new("#{self.class}: Unrecognized properties: #{(hash.keys - decorator.props.keys).join(', ')}")
end
end
end
module T::Props::WeakConstructor::DecoratorMethods
extend T::Sig
# Set values for all props that have no defaults. Ignore any not present.
#
# @return [Integer] A count of props that we successfully initialized (which
# we'll use to check for any unrecognized input.)
#
# checked(:never) - O(runtime object construction)
sig { params(instance: T::Props::WeakConstructor, hash: T::Hash[Symbol, T.untyped]).returns(Integer).checked(:never) }
def construct_props_without_defaults(instance, hash)
# Use `each_pair` rather than `count` because, as of Ruby 2.6, the latter delegates to Enumerator
# and therefore allocates for each entry.
result = 0
props_without_defaults&.each_pair do |p, setter_proc|
if hash.key?(p)
instance.instance_exec(hash[p], &setter_proc)
result += 1
end
end
result
end
# Set values for all props that have defaults. Use the default if and only if
# the prop key isn't in the input.
#
# @return [Integer] A count of props that we successfully initialized (which
# we'll use to check for any unrecognized input.)
#
# checked(:never) - O(runtime object construction)
sig { params(instance: T::Props::WeakConstructor, hash: T::Hash[Symbol, T.untyped]).returns(Integer).checked(:never) }
def construct_props_with_defaults(instance, hash)
# Use `each_pair` rather than `count` because, as of Ruby 2.6, the latter delegates to Enumerator
# and therefore allocates for each entry.
result = 0
props_with_defaults&.each_pair do |p, default_struct|
if hash.key?(p)
instance.instance_exec(hash[p], &default_struct.setter_proc)
result += 1
else
default_struct.set_default(instance)
end
end
result
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/optional.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/optional.rb | # frozen_string_literal: true
# typed: false
module T::Props::Optional
include T::Props::Plugin
end
##############################################
# NB: This must stay in the same file where T::Props::Optional is defined due to
# T::Props::Decorator#apply_plugin; see https://git.corp.stripe.com/stripe-internal/pay-server/blob/fc7f15593b49875f2d0499ffecfd19798bac05b3/chalk/odm/lib/chalk-odm/document_decorator.rb#L716-L717
module T::Props::Optional::DecoratorMethods
extend T::Sig
# Heads up!
#
# There are already too many ad-hoc options on the prop DSL.
#
# We have already done a lot of work to remove unnecessary and confusing
# options. If you're considering adding a new rule key, please come chat with
# the Sorbet team first, as we'd really like to learn more about how to best
# solve the problem you're encountering.
VALID_RULE_KEYS = {
default: true,
factory: true,
}.freeze
private_constant :VALID_RULE_KEYS
DEFAULT_SETTER_RULE_KEY = :_t_props_private_apply_default
private_constant :DEFAULT_SETTER_RULE_KEY
def valid_rule_key?(key)
super || VALID_RULE_KEYS[key]
end
def prop_optional?(prop)
prop_rules(prop)[:fully_optional]
end
def compute_derived_rules(rules)
rules[:fully_optional] = !T::Props::Utils.need_nil_write_check?(rules)
rules[:need_nil_read_check] = T::Props::Utils.need_nil_read_check?(rules)
end
# checked(:never) - O(runtime object construction)
sig { returns(T::Hash[Symbol, T::Props::Private::ApplyDefault]).checked(:never) }
attr_reader :props_with_defaults
# checked(:never) - O(runtime object construction)
sig { returns(T::Hash[Symbol, T::Props::Private::SetterFactory::SetterProc]).checked(:never) }
attr_reader :props_without_defaults
def add_prop_definition(prop, rules)
compute_derived_rules(rules)
default_setter = T::Props::Private::ApplyDefault.for(decorated_class, rules)
if default_setter
@props_with_defaults ||= {}
@props_with_defaults[prop] = default_setter
props_without_defaults&.delete(prop) # Handle potential override
rules[DEFAULT_SETTER_RULE_KEY] = default_setter
else
@props_without_defaults ||= {}
@props_without_defaults[prop] = rules.fetch(:setter_proc)
props_with_defaults&.delete(prop) # Handle potential override
end
super
end
def prop_validate_definition!(name, cls, rules, type)
result = super
if rules.key?(:default) && rules.key?(:factory)
raise ArgumentError.new("Setting both :default and :factory is invalid. See: go/chalk-docs")
end
result
end
def has_default?(rules)
rules.include?(DEFAULT_SETTER_RULE_KEY)
end
def get_default(rules, instance_class)
rules[DEFAULT_SETTER_RULE_KEY]&.default
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/utils.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/utils.rb | # frozen_string_literal: true
# typed: true
module T::Props::Utils
# Deep copy an object. The object must consist of Ruby primitive
# types and Hashes and Arrays.
def self.deep_clone_object(what, freeze: false)
result = case what
when true
true
when false
false
when Symbol, NilClass, Numeric
what
when Array
what.map { |v| deep_clone_object(v, freeze: freeze) }
when Hash
h = what.class.new
what.each do |k, v|
k.freeze if freeze
h[k] = deep_clone_object(v, freeze: freeze)
end
h
when Regexp
what.dup
when T::Enum
what
else
what.clone
end
freeze ? result.freeze : result
end
# The prop_rules indicate whether we should check for reading a nil value for the prop/field.
# This is mostly for the compatibility check that we allow existing documents carry some nil prop/field.
def self.need_nil_read_check?(prop_rules)
# . :on_load allows nil read, but we need to check for the read for future writes
prop_rules[:optional] == :on_load || prop_rules[:raise_on_nil_write]
end
# The prop_rules indicate whether we should check for writing a nil value for the prop/field.
def self.need_nil_write_check?(prop_rules)
need_nil_read_check?(prop_rules) || T::Props::Utils.required_prop?(prop_rules)
end
def self.required_prop?(prop_rules)
# Clients should never reference :_tnilable as the implementation can change.
!prop_rules[:_tnilable]
end
def self.optional_prop?(prop_rules)
# Clients should never reference :_tnilable as the implementation can change.
!!prop_rules[:_tnilable]
end
def self.merge_serialized_optional_rule(prop_rules)
{'_tnilable' => true}.merge(prop_rules.merge('_tnilable' => true))
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/type_validation.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/type_validation.rb | # frozen_string_literal: true
# typed: false
module T::Props::TypeValidation
include T::Props::Plugin
BANNED_TYPES = [Object, BasicObject, Kernel].freeze
class UnderspecifiedType < ArgumentError; end
module DecoratorMethods
extend T::Sig
sig { params(key: Symbol).returns(T::Boolean).checked(:never) }
def valid_rule_key?(key)
super || key == :DEPRECATED_underspecified_type
end
# checked(:never) - Rules hash is expensive to check
sig do
params(
name: T.any(Symbol, String),
_cls: T::Module[T.anything],
rules: T::Hash[Symbol, T.untyped],
type: T.any(T::Types::Base, T::Module[T.anything])
)
.void
.checked(:never)
end
def prop_validate_definition!(name, _cls, rules, type)
super
if !rules[:DEPRECATED_underspecified_type]
validate_type(type, name)
elsif rules[:DEPRECATED_underspecified_type] && find_invalid_subtype(type).nil?
raise ArgumentError.new("DEPRECATED_underspecified_type set unnecessarily for #{@class.name}.#{name} - #{type} is a valid type")
end
end
sig do
params(
type: T::Types::Base,
field_name: T.any(Symbol, String),
)
.void
.checked(:never)
end
private def validate_type(type, field_name)
if (invalid_subtype = find_invalid_subtype(type))
raise UnderspecifiedType.new(type_error_message(invalid_subtype, field_name, type))
end
end
# Returns an invalid type, if any, found in the given top-level type.
# This might be the type itself, if it is e.g. "Object", or might be
# a subtype like the type of the values of a typed hash.
#
# If the type is fully valid, returns nil.
#
# checked(:never) - called potentially many times recursively
sig { params(type: T::Types::Base).returns(T.nilable(T::Types::Base)).checked(:never) }
private def find_invalid_subtype(type)
case type
when T::Types::TypedEnumerable
find_invalid_subtype(type.type)
when T::Types::FixedHash
type.types.values.map { |subtype| find_invalid_subtype(subtype) }.compact.first
when T::Types::Union, T::Types::FixedArray
# `T.any` is valid if all of the members are valid
type.types.map { |subtype| find_invalid_subtype(subtype) }.compact.first
when T::Types::Intersection
# `T.all` is valid if at least one of the members is valid
invalid = type.types.map { |subtype| find_invalid_subtype(subtype) }.compact
if invalid.length == type.types.length
invalid.first
else
nil
end
when T::Types::Enum, T::Types::ClassOf
nil
when T::Private::Types::TypeAlias
find_invalid_subtype(type.aliased_type)
when T::Types::Simple
# TODO Could we manage to define a whitelist, consisting of something
# like primitives, subdocs, DataInterfaces, and collections/enums/unions
# thereof?
if BANNED_TYPES.include?(type.raw_type)
type
else
nil
end
else
type
end
end
sig do
params(
type: T::Types::Base,
field_name: T.any(Symbol, String),
orig_type: T::Types::Base,
)
.returns(String)
end
private def type_error_message(type, field_name, orig_type)
msg_prefix = "#{@class.name}.#{field_name}: #{orig_type} is invalid in prop definition"
if type == orig_type
"#{msg_prefix}. Please choose a more specific type (T.untyped and ~equivalents like Object are banned)."
else
"#{msg_prefix}. Please choose a subtype more specific than #{type} (T.untyped and ~equivalents like Object are banned)."
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/constructor.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/constructor.rb | # frozen_string_literal: true
# typed: false
module T::Props::Constructor
include T::Props::WeakConstructor
end
module T::Props::Constructor::DecoratorMethods
extend T::Sig
# Set values for all props that have no defaults. Override what `WeakConstructor`
# does in order to raise errors on nils instead of ignoring them.
#
# @return [Integer] A count of props that we successfully initialized (which
# we'll use to check for any unrecognized input.)
#
# checked(:never) - O(runtime object construction)
sig { params(instance: T::Props::Constructor, hash: T::Hash[Symbol, T.untyped]).returns(Integer).checked(:never) }
def construct_props_without_defaults(instance, hash)
# Use `each_pair` rather than `count` because, as of Ruby 2.6, the latter delegates to Enumerator
# and therefore allocates for each entry.
result = 0
props_without_defaults&.each_pair do |p, setter_proc|
begin
val = hash[p]
instance.instance_exec(val, &setter_proc)
if val || hash.key?(p)
result += 1
end
rescue TypeError, T::Props::InvalidValueError
if !hash.key?(p)
raise ArgumentError.new("Missing required prop `#{p}` for class `#{instance.class.name}`")
else
raise
end
end
end
result
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/pretty_printable.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/pretty_printable.rb | # frozen_string_literal: true
# typed: true
require 'pp'
module T::Props::PrettyPrintable
include T::Props::Plugin
# Override the PP gem with something that's similar, but gives us a hook to do redaction and customization
def pretty_print(pp)
klass = T.unsafe(T.cast(self, Object).class).decorator
multiline = pp.is_a?(PP)
pp.group(1, "<#{klass.inspect_class_with_decoration(self)}", ">") do
klass.all_props.sort.each do |prop|
pp.breakable
rules = klass.prop_rules(prop)
val = klass.get(self, prop, rules)
pp.text("#{prop}=")
if (custom_inspect = rules[:inspect])
inspected = if T::Utils.arity(custom_inspect) == 1
custom_inspect.call(val)
else
custom_inspect.call(val, {multiline: multiline})
end
pp.text(inspected.nil? ? "nil" : inspected)
elsif (sensitivity = rules[:sensitivity]) && !sensitivity.empty? && !val.nil?
pp.text("<REDACTED #{sensitivity.join(', ')}>")
else
val.pretty_print(pp)
end
end
klass.pretty_print_extra(self, pp)
end
end
# Return a string representation of this object and all of its props in a single line
def inspect
string = +""
PP.singleline_pp(self, string)
string
end
# Return a pretty string representation of this object and all of its props
def pretty_inspect
string = +""
PP.pp(self, string)
string
end
module DecoratorMethods
extend T::Sig
sig { params(key: Symbol).returns(T::Boolean).checked(:never) }
def valid_rule_key?(key)
super || key == :inspect
end
# Overridable method to specify how the first part of a `pretty_print`d object's class should look like
# NOTE: This is just to support Stripe's `PrettyPrintableModel` case, and not recommended to be overridden
sig { params(instance: T::Props::PrettyPrintable).returns(String).checked(:never) }
def inspect_class_with_decoration(instance)
T.unsafe(instance).class.to_s
end
# Overridable method to add anything that is not a prop
# NOTE: This is to support cases like Serializable's `@_extra_props`, and Stripe's `PrettyPrintableModel#@_deleted`
sig { params(instance: T::Props::PrettyPrintable, pp: T.any(PrettyPrint, PP::SingleLine)).void.checked(:never) }
def pretty_print_extra(instance, pp); end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/plugin.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/plugin.rb | # frozen_string_literal: true
# typed: false
module T::Props::Plugin
include T::Props
extend T::Helpers
module ClassMethods
def included(child)
super
child.plugin(self)
end
end
mixes_in_class_methods(ClassMethods)
module Private
# These need to be non-instance methods so we can use them without prematurely creating the
# child decorator in `model_inherited` (see comments there for details).
#
# The dynamic constant access below forces this file to be `typed: false`
def self.apply_class_methods(plugin, target)
if plugin.const_defined?('ClassMethods')
# FIXME: This will break preloading, selective test execution, etc if `mod::ClassMethods`
# is ever defined in a separate file from `mod`.
target.extend(plugin::ClassMethods)
end
end
def self.apply_decorator_methods(plugin, target)
if plugin.const_defined?('DecoratorMethods')
# FIXME: This will break preloading, selective test execution, etc if `mod::DecoratorMethods`
# is ever defined in a separate file from `mod`.
target.extend(plugin::DecoratorMethods)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/has_lazily_specialized_methods.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/has_lazily_specialized_methods.rb | # frozen_string_literal: true
# typed: false
module T::Props
# Helper for generating methods that replace themselves with a specialized
# version on first use. The main use case is when we want to generate a
# method using the full set of props on a class; we can't do that during
# prop definition because we have no way of knowing whether we are defining
# the last prop.
#
# See go/M8yrvzX2 (Stripe-internal) for discussion of security considerations.
# In outline, while `class_eval` is a bit scary, we believe that as long as
# all inputs are defined in version control (and this is enforced by calling
# `disable_lazy_evaluation!` appropriately), risk isn't significantly higher
# than with build-time codegen.
module HasLazilySpecializedMethods
extend T::Sig
class SourceEvaluationDisabled < RuntimeError
def initialize
super("Evaluation of lazily-defined methods is disabled")
end
end
# Disable any future evaluation of lazily-defined methods.
#
# This is intended to be called after startup but before interacting with
# the outside world, to limit attack surface for our `class_eval` use.
#
# Note it does _not_ prevent explicit calls to `eagerly_define_lazy_methods!`
# from working.
sig { void }
def self.disable_lazy_evaluation!
@lazy_evaluation_disabled ||= true
end
sig { returns(T::Boolean) }
def self.lazy_evaluation_enabled?
!@lazy_evaluation_disabled
end
module DecoratorMethods
extend T::Sig
sig { returns(T::Hash[Symbol, T.proc.returns(String)]).checked(:never) }
private def lazily_defined_methods
@lazily_defined_methods ||= {}
end
sig { returns(T::Hash[Symbol, T.untyped]).checked(:never) }
private def lazily_defined_vm_methods
@lazily_defined_vm_methods ||= {}
end
sig { params(name: Symbol).void }
private def eval_lazily_defined_method!(name)
if !HasLazilySpecializedMethods.lazy_evaluation_enabled?
raise SourceEvaluationDisabled.new
end
source = lazily_defined_methods.fetch(name).call
cls = decorated_class
T::Configuration.without_ruby_warnings do
cls.class_eval(source.to_s)
end
cls.send(:private, name)
end
sig { params(name: Symbol).void }
private def eval_lazily_defined_vm_method!(name)
if !HasLazilySpecializedMethods.lazy_evaluation_enabled?
raise SourceEvaluationDisabled.new
end
lazily_defined_vm_methods.fetch(name).call
cls = decorated_class
cls.send(:private, name)
end
sig { params(name: Symbol, blk: T.proc.returns(String)).void }
private def enqueue_lazy_method_definition!(name, &blk)
lazily_defined_methods[name] = blk
cls = decorated_class
if cls.method_defined?(name) || cls.private_method_defined?(name)
# Ruby does not emit "method redefined" warnings for aliased methods
# (more robust than undef_method that would create a small window in which the method doesn't exist)
cls.send(:alias_method, name, name)
end
cls.send(:define_method, name) do |*args|
self.class.decorator.send(:eval_lazily_defined_method!, name)
send(name, *args)
end
if cls.respond_to?(:ruby2_keywords, true)
cls.send(:ruby2_keywords, name)
end
cls.send(:private, name)
end
sig { params(name: Symbol, blk: T.untyped).void }
private def enqueue_lazy_vm_method_definition!(name, &blk)
lazily_defined_vm_methods[name] = blk
cls = decorated_class
cls.send(:define_method, name) do |*args|
self.class.decorator.send(:eval_lazily_defined_vm_method!, name)
send(name, *args)
end
if cls.respond_to?(:ruby2_keywords, true)
cls.send(:ruby2_keywords, name)
end
cls.send(:private, name)
end
sig { void }
def eagerly_define_lazy_methods!
return if lazily_defined_methods.empty?
# rubocop:disable Style/StringConcatenation
source = "# frozen_string_literal: true\n" + lazily_defined_methods.values.map(&:call).map(&:to_s).join("\n\n")
# rubocop:enable Style/StringConcatenation
cls = decorated_class
cls.class_eval(source)
lazily_defined_methods.each_key { |name| cls.send(:private, name) }
lazily_defined_methods.clear
end
sig { void }
def eagerly_define_lazy_vm_methods!
return if lazily_defined_vm_methods.empty?
lazily_defined_vm_methods.values.map(&:call)
cls = decorated_class
lazily_defined_vm_methods.each_key { |name| cls.send(:private, name) }
lazily_defined_vm_methods.clear
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/_props.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/_props.rb | # frozen_string_literal: true
# typed: true
# A mixin for defining typed properties (attributes).
# To get serialization methods (to/from JSON-style hashes), add T::Props::Serializable.
# To get a constructor based on these properties, inherit from T::Struct.
module T::Props
extend T::Helpers
#####
# CAUTION: This mixin is used in hundreds of classes; we want to keep its surface area as narrow
# as possible and avoid polluting (and possibly conflicting with) the classes that use it.
#
# It currently has *zero* instance methods; let's try to keep it that way.
# For ClassMethods (below), try to add things to T::Props::Decorator instead unless you are sure
# it needs to be exposed here.
#####
module ClassMethods
extend T::Sig
extend T::Helpers
def props
decorator.props
end
def plugins
@plugins ||= []
end
def decorator_class
Decorator
end
def decorator
@decorator ||= decorator_class.new(self)
end
def reload_decorator!
@decorator = decorator_class.new(self)
end
# Define a new property. See {file:README.md} for some concrete
# examples.
#
# Defining a property defines a method with the same name as the
# property, that returns the current value, and a `prop=` method
# to set its value. Properties will be inherited by subclasses of
# a document class.
#
# @param name [Symbol] The name of this property
# @param cls [Class,T::Types::Base] The type of this
# property. If the type is itself a `Document` subclass, this
# property will be recursively serialized/deserialized.
# @param rules [Hash] Options to control this property's behavior.
# @option rules [T::Boolean,Symbol] :optional If `true`, this property
# is never required to be set before an instance is serialized.
# If `:on_load` (default), when this property is missing or nil, a
# new model cannot be saved, and an existing model can only be
# saved if the property was already missing when it was loaded.
# If `false`, when the property is missing/nil after deserialization, it
# will be set to the default value (as defined by the `default` or
# `factory` option) or will raise if they are not present.
# Deprecated: For `Model`s, if `:optional` is set to the special value
# `:existing`, the property can be saved as nil even if it was
# deserialized with a non-nil value. (Deprecated because there should
# never be a need for this behavior; the new behavior of non-optional
# properties should be sufficient.)
# @option rules [Array] :enum An array of legal values; The
# property is required to take on one of those values.
# @option rules [T::Boolean] :dont_store If true, this property will
# not be saved on the hash resulting from
# {T::Props::Serializable#serialize}
# @option rules [Object] :ifunset A value to be returned if this
# property is requested but has never been set (is set to
# `nil`). It is applied at property-access time, and never saved
# back onto the object or into the database.
#
# ``:ifunset`` is considered **DEPRECATED** and should not be used
# in new code, in favor of just setting a default value.
# @option rules [Model, Symbol, Proc] :foreign A model class that this
# property is a reference to. Passing `:foreign` will define a
# `:"#{name}_"` method, that will load and return the
# corresponding foreign model.
#
# A symbol can be passed to avoid load-order dependencies; It
# will be lazily resolved relative to the enclosing module of the
# defining class.
#
# A callable (proc or method) can be passed to dynamically specify the
# foreign model. This will be passed the object instance so that other
# properties of the object can be used to determine the relevant model
# class. It should return a string/symbol class name or the foreign model
# class directly.
#
# @option rules [Object] :default A default value that will be set
# by `#initialize` if none is provided in the initialization
# hash. This will not affect objects loaded by {.from_hash}.
# @option rules [Proc] :factory A `Proc` that will be called to
# generate an initial value for this prop on `#initialize`, if
# none is provided.
# @option rules [T::Boolean] :immutable If true, this prop cannot be
# modified after an instance is created or loaded from a hash.
# @option rules [T::Boolean] :override It is an error to redeclare a
# `prop` that has already been declared (including on a
# superclass), unless `:override` is set to `true`.
# @option rules [Symbol, Array] :redaction A redaction directive that may
# be passed to Chalk::Tools::RedactionUtils.redact_with_directive to
# sanitize this parameter for display. Will define a
# `:"#{name}_redacted"` method, which will return the value in sanitized
# form.
#
# @return [void]
sig { params(name: Symbol, cls: T.untyped, rules: T.untyped).void }
def prop(name, cls, **rules)
cls = T::Utils.coerce(cls) if !cls.is_a?(Module)
decorator.prop_defined(name, cls, rules)
end
# Validates the value of the specified prop. This method allows the caller to
# validate a value for a prop without having to set the data on the instance.
# Throws if invalid.
#
# @param prop [Symbol]
# @param val [Object]
# @return [void]
def validate_prop_value(prop, val)
decorator.validate_prop_value(prop, val)
end
# Needs to be documented
def plugin(mod)
decorator.plugin(mod)
end
# Shorthand helper to define a `prop` with `immutable => true`
sig { params(name: Symbol, cls: T.untyped, rules: T.untyped).void }
def const(name, cls, **rules)
if rules.key?(:immutable)
Kernel.raise ArgumentError.new("Cannot pass 'immutable' argument when using 'const' keyword to define a prop")
end
rules[:immutable] = true
self.prop(name, cls, **rules)
end
def included(child)
decorator.model_inherited(child)
super
end
def prepended(child)
decorator.model_inherited(child)
super
end
def extended(child)
decorator.model_inherited(child.singleton_class)
super
end
def inherited(child)
decorator.model_inherited(child)
super
end
end
mixes_in_class_methods(ClassMethods)
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/decorator.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/decorator.rb | # frozen_string_literal: true
# typed: strict
# NB: This is not actually a decorator. It's just named that way for consistency
# with DocumentDecorator and ModelDecorator (which both seem to have been written
# with an incorrect understanding of the decorator pattern). These "decorators"
# should really just be static methods on private modules (we'd also want/need to
# replace decorator overrides in plugins with class methods that expose the necessary
# functionality).
class T::Props::Decorator
extend T::Sig
Rules = T.type_alias { T::Hash[Symbol, T.untyped] }
DecoratedInstance = T.type_alias { Object } # Would be T::Props, but that produces circular reference errors in some circumstances
PropType = T.type_alias { T::Types::Base }
PropTypeOrClass = T.type_alias { T.any(PropType, T::Module[T.anything]) }
OverrideRules = T.type_alias { T::Hash[Symbol, {allow_incompatible: T::Boolean}] }
DecoratedClassType = T.type_alias { T.all(T::Module[T.anything], T::Props::ClassMethods) }
private_constant :DecoratedClassType
class NoRulesError < StandardError; end
EMPTY_PROPS = T.let({}.freeze, T::Hash[Symbol, Rules], checked: false)
private_constant :EMPTY_PROPS
OVERRIDE_TRUE = T.let({
reader: {allow_incompatible: false}.freeze,
writer: {allow_incompatible: false}.freeze,
}.freeze, OverrideRules)
OVERRIDE_READER = T.let({
reader: {allow_incompatible: false}.freeze,
}.freeze, OverrideRules)
OVERRIDE_WRITER = T.let({
writer: {allow_incompatible: false}.freeze,
}.freeze, OverrideRules)
OVERRIDE_EMPTY = T.let({}.freeze, OverrideRules)
sig { params(klass: T.untyped).void.checked(:never) }
def initialize(klass)
@class = T.let(klass, DecoratedClassType)
@class.plugins.each do |mod|
T::Props::Plugin::Private.apply_decorator_methods(mod, self)
end
@props = T.let(EMPTY_PROPS, T::Hash[Symbol, Rules], checked: false)
end
# checked(:never) - O(prop accesses)
sig { returns(T::Hash[Symbol, Rules]).checked(:never) }
attr_reader :props
sig { returns(T::Array[Symbol]) }
def all_props
props.keys
end
# checked(:never) - O(prop accesses)
sig { params(prop: T.any(Symbol, String)).returns(Rules).checked(:never) }
def prop_rules(prop)
props[prop.to_sym] || raise("No such prop: #{prop.inspect}")
end
# checked(:never) - Rules hash is expensive to check
sig { params(name: Symbol, rules: Rules).void.checked(:never) }
def add_prop_definition(name, rules)
override = rules.delete(:override)
if props.include?(name) && !override
raise ArgumentError.new("Attempted to redefine prop #{name.inspect} on class #{@class} that's already defined without specifying :override => true: #{prop_rules(name)}")
end
@props = @props.merge(name => rules.freeze).freeze
end
# Heads up!
#
# There are already too many ad-hoc options on the prop DSL.
#
# We have already done a lot of work to remove unnecessary and confusing
# options. If you're considering adding a new rule key, please come chat with
# the Sorbet team first, as we'd really like to learn more about how to best
# solve the problem you're encountering.
VALID_RULE_KEYS = T.let(%i[
enum
foreign
ifunset
immutable
override
redaction
sensitivity
without_accessors
clobber_existing_method!
extra
setter_validate
_tnilable
].to_h { |k| [k, true] }.freeze, T::Hash[Symbol, T::Boolean], checked: false)
private_constant :VALID_RULE_KEYS
sig { params(key: Symbol).returns(T::Boolean).checked(:never) }
def valid_rule_key?(key)
!!VALID_RULE_KEYS[key]
end
# checked(:never) - O(prop accesses)
sig { returns(DecoratedClassType).checked(:never) }
def decorated_class
@class
end
# Accessors
# Use this to validate that a value will validate for a given prop. Useful for knowing whether a value can be set on a model without setting it.
#
# checked(:never) - potentially O(prop accesses) depending on usage pattern
sig { params(prop: Symbol, val: T.untyped).void.checked(:never) }
def validate_prop_value(prop, val)
prop_rules(prop).fetch(:value_validate_proc).call(val)
end
# For performance, don't use named params here.
# Passing in rules here is purely a performance optimization.
# Unlike the other methods that take rules, this one calls prop_rules for
# the default, which raises if the prop doesn't exist (this maintains
# preexisting behavior).
#
# Note this path is NOT used by generated setters on instances,
# which are defined using `setter_proc` directly.
#
# checked(:never) - O(prop accesses)
sig do
params(
instance: DecoratedInstance,
prop: Symbol,
val: T.untyped,
rules: Rules
)
.void
.checked(:never)
end
def prop_set(instance, prop, val, rules=prop_rules(prop))
instance.instance_exec(val, &rules.fetch(:setter_proc))
end
alias_method :set, :prop_set
# Only Models have any custom get logic but we need to call this on
# non-Models since we don't know at code gen time what we have.
sig do
params(
instance: DecoratedInstance,
prop: Symbol,
value: T.untyped
)
.returns(T.untyped)
.checked(:never)
end
def prop_get_logic(instance, prop, value)
value
end
# For performance, don't use named params here.
# Passing in rules here is purely a performance optimization.
#
# Note this path is NOT used by generated getters on instances,
# unless `ifunset` is used on the prop, or `prop_get` is overridden.
#
# checked(:never) - O(prop accesses)
sig do
params(
instance: DecoratedInstance,
prop: T.any(String, Symbol),
rules: Rules
)
.returns(T.untyped)
.checked(:never)
end
def prop_get(instance, prop, rules=prop_rules(prop))
# `instance_variable_get` will return nil if the variable doesn't exist
# which is what we want to have happen for the logic below.
val = instance.instance_variable_get(rules[:accessor_key])
if !val.nil?
val
elsif (d = rules[:ifunset])
T::Props::Utils.deep_clone_object(d)
else
nil
end
end
sig do
params(
instance: DecoratedInstance,
prop: T.any(String, Symbol),
rules: Rules
)
.returns(T.untyped)
.checked(:never)
end
def prop_get_if_set(instance, prop, rules=prop_rules(prop))
# `instance_variable_get` will return nil if the variable doesn't exist
# which is what we want to have happen for the return value here.
instance.instance_variable_get(rules[:accessor_key])
end
alias_method :get, :prop_get_if_set # Alias for backwards compatibility
# checked(:never) - O(prop accesses)
sig do
params(
instance: DecoratedInstance,
prop: Symbol,
foreign_class: T::Module[T.anything],
rules: Rules,
opts: T::Hash[Symbol, T.untyped],
)
.returns(T.untyped)
.checked(:never)
end
def foreign_prop_get(instance, prop, foreign_class, rules=prop_rules(prop), opts={})
return if !(value = prop_get(instance, prop, rules))
T.unsafe(foreign_class).load(value, {}, opts)
end
# TODO: we should really be checking all the methods on `cls`, not just Object
BANNED_METHOD_NAMES = T.let(Object.instance_methods.each_with_object({}) { |x, acc| acc[x] = true }.freeze, T::Hash[Symbol, TrueClass], checked: false)
# checked(:never) - Rules hash is expensive to check
sig do
params(
name: Symbol,
cls: T::Module[T.anything],
rules: Rules,
type: PropTypeOrClass
)
.void
.checked(:never)
end
def prop_validate_definition!(name, cls, rules, type)
validate_prop_name(name)
if rules.key?(:pii)
raise ArgumentError.new("The 'pii:' option for props has been renamed " \
"to 'sensitivity:' (in prop #{@class.name}.#{name})")
end
if rules.keys.any? { |k| !valid_rule_key?(k) }
invalid_keys = rules.keys.reject { |k| valid_rule_key?(k) }
suffix = invalid_keys.size == 1 ? "" : "s"
raise ArgumentError.new("Invalid prop arg#{suffix} supplied in #{self}: #{invalid_keys.inspect}")
end
if !rules[:clobber_existing_method!] && !rules[:without_accessors] && BANNED_METHOD_NAMES.include?(name.to_sym)
raise ArgumentError.new(
"#{name} can't be used as a prop in #{@class} because a method with " \
"that name already exists (defined by #{@class.instance_method(name).owner} " \
"at #{@class.instance_method(name).source_location || '<unknown>'}). " \
"(If using this name is unavoidable, try `without_accessors: true`.)"
)
end
extra = rules[:extra]
if !extra.nil? && !extra.is_a?(Hash)
raise ArgumentError.new("Extra metadata must be a Hash in prop #{@class.name}.#{name}")
end
nil
end
SAFE_NAME = T.let(/\A[A-Za-z_][A-Za-z0-9_-]*\z/, Regexp, checked: false)
# Should be exactly the same as `SAFE_NAME`, but with a leading `@`.
SAFE_ACCESSOR_KEY_NAME = T.let(/\A@[A-Za-z_][A-Za-z0-9_-]*\z/, Regexp, checked: false)
# Used to validate both prop names and serialized forms
sig { params(name: T.any(Symbol, String)).void.checked(:never) }
private def validate_prop_name(name)
if !name.match?(SAFE_NAME)
raise ArgumentError.new("Invalid prop name in #{@class.name}: #{name}")
end
end
# This converts the type from a T::Type to a regular old ruby class.
sig { params(type: T::Types::Base).returns(T::Module[T.anything]).checked(:never) }
private def convert_type_to_class(type)
case type
when T::Types::TypedArray, T::Types::FixedArray
Array
when T::Types::TypedHash, T::Types::FixedHash
Hash
when T::Types::TypedSet
Set
when T::Types::Union
# The below unwraps our T.nilable types for T::Props if we can.
# This lets us do things like specify: const T.nilable(String), foreign: Opus::DB::Model::Merchant
non_nil_type = T::Utils.unwrap_nilable(type)
if non_nil_type
convert_type_to_class(non_nil_type)
else
Object
end
when T::Types::Simple
type.raw_type
else
# This isn't allowed unless whitelisted_for_underspecification is
# true, due to the check in prop_validate_definition
Object
end
end
# Returns `true` when the type of the prop is nilable, or the field is typed
# as `T.untyped`, a `:default` is present in the rules hash, and its value is
# `nil`. The latter case is a workaround for explicitly not supporting the use
# of `T.nilable(T.untyped)`.
#
# checked(:never) - Rules hash is expensive to check
sig do
params(
cls: PropTypeOrClass,
rules: Rules,
)
.returns(T.anything)
.checked(:never)
end
private def prop_nilable?(cls, rules)
# NB: `prop` and `const` do not `T::Utils::coerce the type of the prop if it is a `Module`,
# hence the bare `NilClass` check.
T::Utils::Nilable.is_union_with_nilclass(cls) || ((cls == T.untyped || cls == NilClass) && rules.key?(:default) && rules[:default].nil?)
end
sig(:final) { params(name: Symbol).returns(T::Boolean).checked(:never) }
private def method_defined_on_ancestor?(name)
(@class.method_defined?(name) || @class.private_method_defined?(name)) &&
# Unfortunately, older versions of ruby don't allow the second parameter on
# `private_method_defined?`.
!@class.method_defined?(name, false) && !@class.private_method_defined?(name, false)
end
sig(:final) { params(name: Symbol, rules: Rules).void.checked(:never) }
private def validate_overrides(name, rules)
override = elaborate_override(name, rules[:override])
return if rules[:without_accessors]
if override[:reader] && !method_defined_on_ancestor?(name) && !props.include?(name)
raise ArgumentError.new("You marked the getter for prop #{name.inspect} as `override`, but the method `#{name}` doesn't exist to be overridden.")
end
# Properly, we should also check whether `props[name]` is immutable, but the old code didn't either.
if !rules[:immutable] && override[:writer] && !method_defined_on_ancestor?("#{name}=".to_sym) && !props.include?(name)
raise ArgumentError.new("You marked the setter for prop #{name.inspect} as `override`, but the method `#{name}=` doesn't exist to be overridden.")
end
end
# checked(:never) - Rules hash is expensive to check
sig do
params(
name: T.any(Symbol, String),
cls: PropTypeOrClass,
rules: Rules,
)
.void
.checked(:never)
end
def prop_defined(name, cls, rules={})
cls = T::Utils.resolve_alias(cls)
if prop_nilable?(cls, rules)
# :_tnilable is introduced internally for performance purpose so that clients do not need to call
# T::Utils::Nilable.is_tnilable(cls) again.
# It is strictly internal: clients should always use T::Props::Utils.required_prop?() or
# T::Props::Utils.optional_prop?() for checking whether a field is required or optional.
rules[:_tnilable] = true
end
name = name.to_sym
type = cls
if !cls.is_a?(Module)
cls = convert_type_to_class(cls)
end
type_object = smart_coerce(type, enum: rules[:enum])
prop_validate_definition!(name, cls, rules, type_object)
# Retrieve the possible underlying object with T.nilable.
type = T::Utils::Nilable.get_underlying_type(type)
rules_sensitivity = rules[:sensitivity]
sensitivity_and_pii = {sensitivity: rules_sensitivity}
if !rules_sensitivity.nil?
normalize = T::Configuration.normalize_sensitivity_and_pii_handler
if normalize
sensitivity_and_pii = normalize.call(sensitivity_and_pii)
# We check for Class so this is only applied on concrete
# documents/models; We allow mixins containing props to not
# specify their PII nature, as long as every class into which they
# are ultimately included does.
#
if sensitivity_and_pii[:pii] && @class.is_a?(Class) && !T.unsafe(@class).contains_pii?
raise ArgumentError.new(
"Cannot define pii prop `#{@class}##{name}` because `#{@class}` is `contains_no_pii`"
)
end
end
end
rules[:type] = type
rules[:type_object] = type_object
rules[:accessor_key] = "@#{name}".to_sym
rules[:sensitivity] = sensitivity_and_pii[:sensitivity]
rules[:pii] = sensitivity_and_pii[:pii]
rules[:extra] = rules[:extra]&.freeze
# extra arbitrary metadata attached by the code defining this property
# for backcompat (the `:array` key is deprecated but because the name is
# so generic it's really hard to be sure it's not being relied on anymore)
if type.is_a?(T::Types::TypedArray)
inner = T::Utils::Nilable.get_underlying_type(type.type)
if inner.is_a?(Module)
rules[:array] = inner
end
end
setter_proc, value_validate_proc = T::Props::Private::SetterFactory.build_setter_proc(@class, name, rules)
setter_proc.freeze
value_validate_proc.freeze
rules[:setter_proc] = setter_proc
rules[:value_validate_proc] = value_validate_proc
validate_overrides(name, rules)
add_prop_definition(name, rules)
# NB: using `without_accessors` doesn't make much sense unless you also define some other way to
# get at the property (e.g., Chalk::ODM::Document exposes `get` and `set`).
define_getter_and_setter(name, rules) unless rules[:without_accessors]
handle_foreign_option(name, cls, rules, rules[:foreign]) if rules[:foreign]
handle_redaction_option(name, rules[:redaction]) if rules[:redaction]
end
# checked(:never) - Rules hash is expensive to check
sig { params(name: Symbol, rules: Rules).void.checked(:never) }
private def define_getter_and_setter(name, rules)
T::Configuration.without_ruby_warnings do
if !rules[:immutable]
if method(:prop_set).owner != T::Props::Decorator
d = @class.decorator
@class.send(:define_method, "#{name}=") do |val|
d.prop_set(self, name, val, rules)
end
else
# Fast path (~4x faster as of Ruby 2.6)
@class.send(:define_method, "#{name}=", &rules.fetch(:setter_proc))
end
end
if method(:prop_get).owner != T::Props::Decorator || rules.key?(:ifunset)
d = @class.decorator
@class.send(:define_method, name) do
d.prop_get(self, name, rules)
end
else
# Fast path (~30x faster as of Ruby 2.6)
@class.send(:attr_reader, name) # send is used because `attr_reader` is private in 2.4
end
end
end
sig do
params(type: PropTypeOrClass, enum: T.untyped)
.returns(T::Types::Base)
.checked(:never)
end
private def smart_coerce(type, enum:)
# Backwards compatibility for pre-T::Types style
type = T::Utils.coerce(type)
if enum.nil?
type
else
nonnil_type = T::Utils.unwrap_nilable(type)
if nonnil_type
T.unsafe(T.nilable(T.all(T.unsafe(nonnil_type), T.deprecated_enum(enum))))
else
T.unsafe(T.all(T.unsafe(type), T.deprecated_enum(enum)))
end
end
end
# Create `#{prop_name}_redacted` method
sig do
params(
prop_name: Symbol,
redaction: T.untyped,
)
.void
.checked(:never)
end
private def handle_redaction_option(prop_name, redaction)
redacted_method = "#{prop_name}_redacted"
@class.send(:define_method, redacted_method) do
value = self.public_send(prop_name)
handler = T::Configuration.redaction_handler
if !handler
raise "Using `redaction:` on a prop requires specifying `T::Configuration.redaction_handler`"
end
handler.call(value, redaction)
end
end
sig do
params(
option_sym: Symbol,
foreign: T.untyped,
valid_type_msg: String,
)
.void
.checked(:never)
end
private def validate_foreign_option(option_sym, foreign, valid_type_msg:)
if foreign.is_a?(Symbol) || foreign.is_a?(String)
raise ArgumentError.new(
"Using a symbol/string for `#{option_sym}` is no longer supported. Instead, use a Proc " \
"that returns the class, e.g., foreign: -> {Foo}"
)
end
if !foreign.is_a?(Proc) && !foreign.is_a?(Array) && !foreign.respond_to?(:load)
raise ArgumentError.new("The `#{option_sym}` option must be #{valid_type_msg}")
end
end
# checked(:never) - Rules hash is expensive to check
sig do
params(
prop_name: T.any(String, Symbol),
rules: Rules,
foreign: T.untyped,
)
.void
.checked(:never)
end
private def define_foreign_method(prop_name, rules, foreign)
fk_method = "#{prop_name}_"
# n.b. there's no clear reason *not* to allow additional options
# here, but we're baking in `allow_direct_mutation` since we
# *haven't* allowed additional options in the past and want to
# default to keeping this interface narrow.
foreign = T.let(foreign, T.untyped, checked: false)
@class.send(:define_method, fk_method) do |allow_direct_mutation: nil|
if foreign.is_a?(Proc)
resolved_foreign = foreign.call
if !resolved_foreign.respond_to?(:load)
raise ArgumentError.new(
"The `foreign` proc for `#{prop_name}` must return a model class. " \
"Got `#{resolved_foreign.inspect}` instead."
)
end
# `foreign` is part of the closure state, so this will persist to future invocations
# of the method, optimizing it so this only runs on the first invocation.
foreign = resolved_foreign
end
opts = if allow_direct_mutation.nil?
{}
else
{allow_direct_mutation: allow_direct_mutation}
end
T.unsafe(self.class).decorator.foreign_prop_get(self, prop_name, foreign, rules, opts)
end
force_fk_method = "#{fk_method}!"
@class.send(:define_method, force_fk_method) do |allow_direct_mutation: nil|
loaded_foreign = send(fk_method, allow_direct_mutation: allow_direct_mutation)
if !loaded_foreign
T::Configuration.hard_assert_handler(
'Failed to load foreign model',
storytime: {method: force_fk_method, class: self.class}
)
end
loaded_foreign
end
end
# checked(:never) - Rules hash is expensive to check
sig do
params(
prop_name: Symbol,
prop_cls: T::Module[T.anything],
rules: Rules,
foreign: T.untyped,
)
.void
.checked(:never)
end
private def handle_foreign_option(prop_name, prop_cls, rules, foreign)
validate_foreign_option(
:foreign, foreign, valid_type_msg: "a model class or a Proc that returns one"
)
if prop_cls != String
raise ArgumentError.new("`foreign` can only be used with a prop type of String")
end
if foreign.is_a?(Array)
# We don't support arrays with `foreign` because it's hard to both preserve ordering and
# keep them from being lurky performance hits by issuing a bunch of un-batched DB queries.
# We could potentially address that by porting over something like AmbiguousIDLoader.
raise ArgumentError.new(
"Using an array for `foreign` is no longer supported. Instead, please use a union type of " \
"token types for the prop type, e.g., T.any(Opus::Autogen::Tokens::FooModelToken, Opus::Autogen::Tokens::BarModelToken)"
)
end
unless foreign.is_a?(Proc)
T::Configuration.soft_assert_handler(<<~MESSAGE, storytime: {prop: prop_name, value: foreign}, notify: 'jerry')
Please use a Proc that returns a model class instead of the model class itself as the argument to `foreign`. In other words:
instead of `prop :foo, String, foreign: FooModel`
use `prop :foo, String, foreign: -> {FooModel}`
MESSAGE
end
define_foreign_method(prop_name, rules, foreign)
end
# TODO: rename this to props_inherited
#
# This gets called when a module or class that extends T::Props gets included, extended,
# prepended, or inherited.
sig { params(child: T::Module[T.anything]).void.checked(:never) }
def model_inherited(child)
child.extend(T::Props::ClassMethods)
child = T.cast(child, DecoratedClassType)
child.plugins.concat(decorated_class.plugins)
decorated_class.plugins.each do |mod|
# NB: apply_class_methods must not be an instance method on the decorator itself,
# otherwise we'd have to call child.decorator here, which would create the decorator
# before any `decorator_class` override has a chance to take effect (see the comment below).
T::Props::Plugin::Private.apply_class_methods(mod, child)
end
props.each do |name, rules|
copied_rules = rules.dup
# NB: Calling `child.decorator` here is a time bomb that's going to give someone a really bad
# time. Any class that defines props and also overrides the `decorator_class` method is going
# to reach this line before its override take effect, turning it into a no-op.
child.decorator.add_prop_definition(name, copied_rules)
# It's a bit tricky to support `prop_get` hooks added by plugins without
# sacrificing the `attr_reader` fast path or clobbering customized getters
# defined manually on a child.
#
# To make this work, we _do_ clobber getters defined on the child, but only if:
# (a) it's needed in order to support a `prop_get` hook, and
# (b) it's safe because the getter was defined by this file.
#
unless rules[:without_accessors]
if clobber_getter?(child, name)
child.send(:define_method, name) do
T.unsafe(self.class).decorator.prop_get(self, name, rules)
end
end
if !rules[:immutable] && clobber_setter?(child, name)
child.send(:define_method, "#{name}=") do |val|
T.unsafe(self.class).decorator.prop_set(self, name, val, rules)
end
end
end
end
end
sig(:final) do
params(key: Symbol, d: T.untyped, out: T::Hash[Symbol, {allow_incompatible: T::Boolean}])
.void
.checked(:never)
end
private def elaborate_override_entry(key, d, out)
# It's written this way so that `{reader: false}` will omit the entry for `reader` in the
# result entirely
case d[key]
when TrueClass
out[key] = {allow_incompatible: false}
when Hash
out[key] = {allow_incompatible: !!d[key][:allow_incompatible]}
end
end
sig(:final) do
params(name: Symbol, d: T.untyped)
.returns(T::Hash[Symbol, {allow_incompatible: T::Boolean}])
.checked(:never)
end
private def elaborate_override(name, d)
return OVERRIDE_TRUE if d == true
return OVERRIDE_READER if d == :reader
return OVERRIDE_WRITER if d == :writer
return OVERRIDE_EMPTY if d == false || d.nil?
unless d.is_a?(Hash)
raise ArgumentError.new("`override` only accepts `true`, `:reader`, `:writer`, or a Hash in prop #{@class.name}.#{name} (got #{d.class})")
end
# cwong: should we check for bad keys? `sig { override(not_real: true) }` on a normal function
# errors statically but not at runtime.
# XX cwong: this means {reader: false, allow_incompatible: true} will become {allow_incompatible: true},
# is that fine?
unless (allow_incompatible = d[:allow_incompatible]).nil?
return {reader: {allow_incompatible: !!allow_incompatible},
writer: {allow_incompatible: !!allow_incompatible}}.to_h
end
result = {}
elaborate_override_entry(:reader, d, result)
elaborate_override_entry(:writer, d, result)
result
end
sig { params(child: DecoratedClassType, prop: Symbol).returns(T::Boolean).checked(:never) }
private def clobber_getter?(child, prop)
!!(child.decorator.method(:prop_get).owner != method(:prop_get).owner &&
child.instance_method(prop).source_location&.first == __FILE__)
end
sig { params(child: DecoratedClassType, prop: Symbol).returns(T::Boolean).checked(:never) }
private def clobber_setter?(child, prop)
!!(child.decorator.method(:prop_set).owner != method(:prop_set).owner &&
child.instance_method("#{prop}=").source_location&.first == __FILE__)
end
sig { params(mod: T::Module[T.anything]).void.checked(:never) }
def plugin(mod)
decorated_class.plugins << mod
T::Props::Plugin::Private.apply_class_methods(mod, decorated_class)
T::Props::Plugin::Private.apply_decorator_methods(mod, self)
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/custom_type.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/custom_type.rb | # frozen_string_literal: true
# typed: strict
module T::Props
module CustomType
extend T::Sig
extend T::Helpers
abstract!
include Kernel # for `is_a?`
# Alias for backwards compatibility
sig(:final) do
params(
value: BasicObject,
)
.returns(T::Boolean)
.checked(:never)
end
def instance?(value)
self.===(value)
end
# Alias for backwards compatibility
sig(:final) do
params(
value: BasicObject,
)
.returns(T::Boolean)
.checked(:never)
end
def valid?(value)
instance?(value)
end
# Given an instance of this type, serialize that into a scalar type
# supported by T::Props.
#
# @param [Object] instance
# @return An instance of one of T::Configuration.scalar_types
sig { abstract.params(instance: T.untyped).returns(T.untyped).checked(:never) }
def serialize(instance); end
# Given the serialized form of your type, this returns an instance
# of that custom type representing that value.
#
# @param scalar One of T::Configuration.scalar_types
# @return Object
sig { abstract.params(scalar: T.untyped).returns(T.untyped).checked(:never) }
def deserialize(scalar); end
sig { override.params(_base: T::Module[T.anything]).void }
def self.included(_base)
super
raise 'Please use "extend", not "include" to attach this module'
end
sig(:final) { params(val: T.untyped).returns(T::Boolean).checked(:never) }
def self.scalar_type?(val)
# We don't need to check for val's included modules in
# T::Configuration.scalar_types, because T::Configuration.scalar_types
# are all classes.
klass = val.class
until klass.nil?
return true if T::Configuration.scalar_types.include?(klass.to_s)
klass = klass.superclass
end
false
end
# We allow custom types to serialize to Arrays, so that we can
# implement set-like fields that store a unique-array, but forbid
# hashes; Custom hash types should be implemented via an emebdded
# T::Struct (or a subclass like Chalk::ODM::Document) or via T.
sig(:final) { params(val: Object).returns(T::Boolean).checked(:never) }
def self.valid_serialization?(val)
case val
when Array
val.each do |v|
return false unless scalar_type?(v)
end
true
else
scalar_type?(val)
end
end
sig(:final) do
params(instance: Object)
.returns(T.untyped)
.checked(:never)
end
def self.checked_serialize(instance)
val = T.cast(instance.class, T::Props::CustomType).serialize(instance)
unless valid_serialization?(val)
msg = "#{instance.class} did not serialize to a valid scalar type. It became a: #{val.class}"
if val.is_a?(Hash)
msg += "\nIf you want to store a structured Hash, consider using a T::Struct as your type."
end
raise TypeError.new(msg)
end
val
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/generated_code_validation.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/generated_code_validation.rb | # frozen_string_literal: true
# typed: true
module T::Props
# Helper to validate generated code, to mitigate security concerns around
# `class_eval`. Not called by default; the expectation is this will be used
# in a test iterating over all T::Props::Serializable subclasses.
#
# We validate the exact expected structure of the generated methods as far
# as we can, and then where cloning produces an arbitrarily nested structure,
# we just validate a lack of side effects.
module GeneratedCodeValidation
extend Private::Parse
class ValidationError < RuntimeError; end
def self.validate_deserialize(source)
parsed = parse(source)
# def %<name>(hash)
# ...
# end
assert_equal(:def, parsed.type)
name, args, body = parsed.children
assert_equal(:__t_props_generated_deserialize, name)
assert_equal(s(:args, s(:arg, :hash)), args)
assert_equal(:begin, body.type)
init, *prop_clauses, ret = body.children
# found = %<prop_count>
# ...
# found
assert_equal(:lvasgn, init.type)
init_name, init_val = init.children
assert_equal(:found, init_name)
assert_equal(:int, init_val.type)
assert_equal(s(:lvar, :found), ret)
prop_clauses.each_with_index do |clause, i|
if i.even?
validate_deserialize_hash_read(clause)
else
validate_deserialize_ivar_set(clause)
end
end
end
def self.validate_serialize(source)
parsed = parse(source)
# def %<name>(strict)
# ...
# end
assert_equal(:def, parsed.type)
name, args, body = parsed.children
assert_equal(:__t_props_generated_serialize, name)
assert_equal(s(:args, s(:arg, :strict)), args)
assert_equal(:begin, body.type)
init, *prop_clauses, ret = body.children
# h = {}
# ...
# h
assert_equal(s(:lvasgn, :h, s(:hash)), init)
assert_equal(s(:lvar, :h), ret)
prop_clauses.each do |clause|
validate_serialize_clause(clause)
end
end
private_class_method def self.validate_serialize_clause(clause)
assert_equal(:if, clause.type)
condition, if_body, else_body = clause.children
# if @%<accessor_key>.nil?
assert_equal(:send, condition.type)
receiver, method = condition.children
assert_equal(:ivar, receiver.type)
assert_equal(:nil?, method)
unless if_body.nil?
# required_prop_missing_from_serialize(%<prop>) if strict
assert_equal(:if, if_body.type)
if_strict_condition, if_strict_body, if_strict_else = if_body.children
assert_equal(s(:lvar, :strict), if_strict_condition)
assert_equal(:send, if_strict_body.type)
on_strict_receiver, on_strict_method, on_strict_arg = if_strict_body.children
assert_equal(nil, on_strict_receiver)
assert_equal(:required_prop_missing_from_serialize, on_strict_method)
assert_equal(:sym, on_strict_arg.type)
assert_equal(nil, if_strict_else)
end
# h[%<serialized_form>] = ...
assert_equal(:send, else_body.type)
receiver, method, h_key, h_val = else_body.children
assert_equal(s(:lvar, :h), receiver)
assert_equal(:[]=, method)
assert_equal(:str, h_key.type)
validate_lack_of_side_effects(h_val, whitelisted_methods_for_serialize)
end
private_class_method def self.validate_deserialize_hash_read(clause)
# val = hash[%<serialized_form>s]
assert_equal(:lvasgn, clause.type)
name, val = clause.children
assert_equal(:val, name)
assert_equal(:send, val.type)
receiver, method, arg = val.children
assert_equal(s(:lvar, :hash), receiver)
assert_equal(:[], method)
assert_equal(:str, arg.type)
end
private_class_method def self.validate_deserialize_ivar_set(clause)
# %<accessor_key>s = if val.nil?
# found -= 1 unless hash.key?(%<serialized_form>s)
# %<nil_handler>s
# else
# %<serialized_val>s
# end
assert_equal(:ivasgn, clause.type)
ivar_name, deser_val = clause.children
unless ivar_name.is_a?(Symbol)
raise ValidationError.new("Unexpected ivar: #{ivar_name}")
end
assert_equal(:if, deser_val.type)
condition, if_body, else_body = deser_val.children
assert_equal(s(:send, s(:lvar, :val), :nil?), condition)
assert_equal(:begin, if_body.type)
update_found, handle_nil = if_body.children
assert_equal(:if, update_found.type)
found_condition, found_if_body, found_else_body = update_found.children
assert_equal(:send, found_condition.type)
receiver, method, arg = found_condition.children
assert_equal(s(:lvar, :hash), receiver)
assert_equal(:key?, method)
assert_equal(:str, arg.type)
assert_equal(nil, found_if_body)
assert_equal(s(:op_asgn, s(:lvasgn, :found), :-, s(:int, 1)), found_else_body)
validate_deserialize_handle_nil(handle_nil)
if else_body.type == :kwbegin
rescue_expression, = else_body.children
assert_equal(:rescue, rescue_expression.type)
try, rescue_body = rescue_expression.children
validate_lack_of_side_effects(try, whitelisted_methods_for_deserialize)
assert_equal(:resbody, rescue_body.type)
exceptions, assignment, handler = rescue_body.children
assert_equal(:array, exceptions.type)
exceptions.children.each { |c| assert_equal(:const, c.type) }
assert_equal(:lvasgn, assignment.type)
assert_equal([:e], assignment.children)
deserialization_error, val_return = handler.children
assert_equal(:send, deserialization_error.type)
receiver, method, *args = deserialization_error.children
assert_equal(nil, receiver)
assert_equal(:raise_deserialization_error, method)
args.each { |a| validate_lack_of_side_effects(a, whitelisted_methods_for_deserialize) }
validate_lack_of_side_effects(val_return, whitelisted_methods_for_deserialize)
else
validate_lack_of_side_effects(else_body, whitelisted_methods_for_deserialize)
end
end
private_class_method def self.validate_deserialize_handle_nil(node)
case node.type
when :hash, :array, :str, :sym, :int, :float, :true, :false, :nil, :const # rubocop:disable Lint/BooleanSymbol
# Primitives and constants are safe
when :send
receiver, method, arg = node.children
if receiver.nil?
# required_prop_missing_from_deserialize(%<prop>)
assert_equal(:required_prop_missing_from_deserialize, method)
assert_equal(:sym, arg.type)
elsif receiver == self_class_decorator
# self.class.decorator.raise_nil_deserialize_error(%<serialized_form>)
assert_equal(:raise_nil_deserialize_error, method)
assert_equal(:str, arg.type)
elsif method == :default
# self.class.decorator.props_with_defaults.fetch(%<prop>).default
assert_equal(:send, receiver.type)
inner_receiver, inner_method, inner_arg = receiver.children
assert_equal(
s(:send, self_class_decorator, :props_with_defaults),
inner_receiver,
)
assert_equal(:fetch, inner_method)
assert_equal(:sym, inner_arg.type)
else
raise ValidationError.new("Unexpected receiver in nil handler: #{node.inspect}")
end
else
raise ValidationError.new("Unexpected nil handler: #{node.inspect}")
end
end
private_class_method def self.self_class_decorator
@self_class_decorator ||= s(:send, s(:send, s(:self), :class), :decorator).freeze
end
private_class_method def self.validate_lack_of_side_effects(node, whitelisted_methods_by_receiver_type)
case node.type
when :const
# This is ok, because we'll have validated what method has been called
# if applicable
when :hash, :array, :str, :sym, :int, :float, :true, :false, :nil, :self # rubocop:disable Lint/BooleanSymbol
# Primitives & self are ok
when :lvar, :arg, :ivar
# Reading local & instance variables & arguments is ok
unless node.children.all? { |c| c.is_a?(Symbol) }
raise ValidationError.new("Unexpected child for #{node.type}: #{node.inspect}")
end
when :args, :mlhs, :block, :begin, :if
# Blocks etc are read-only if their contents are read-only
node.children.each { |c| validate_lack_of_side_effects(c, whitelisted_methods_by_receiver_type) if c }
when :send
# Sends are riskier so check a whitelist
receiver, method, *args = node.children
if receiver
if receiver.type == :send
key = receiver
else
key = receiver.type
validate_lack_of_side_effects(receiver, whitelisted_methods_by_receiver_type)
end
if !whitelisted_methods_by_receiver_type[key]&.include?(method)
raise ValidationError.new("Unexpected method #{method} called on #{receiver.inspect}")
end
end
args.each do |arg|
validate_lack_of_side_effects(arg, whitelisted_methods_by_receiver_type)
end
else
raise ValidationError.new("Unexpected node type #{node.type}: #{node.inspect}")
end
end
private_class_method def self.assert_equal(expected, actual)
if expected != actual
raise ValidationError.new("Expected #{expected}, got #{actual}")
end
end
# Method calls generated by SerdeTransform
private_class_method def self.whitelisted_methods_for_serialize
@whitelisted_methods_for_serialize ||= {
lvar: %i{dup map transform_values transform_keys each_with_object nil? []= serialize},
ivar: %i[dup map transform_values transform_keys each_with_object serialize],
const: %i[checked_serialize deep_clone_object],
}
end
# Method calls generated by SerdeTransform
private_class_method def self.whitelisted_methods_for_deserialize
@whitelisted_methods_for_deserialize ||= {
lvar: %i{dup map transform_values transform_keys each_with_object nil? []= to_f},
const: %i[deserialize from_hash deep_clone_object],
}
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/private/deserializer_generator.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/private/deserializer_generator.rb | # frozen_string_literal: true
# typed: strict
module T::Props
module Private
# Generates a specialized `deserialize` implementation for a subclass of
# T::Props::Serializable.
#
# The basic idea is that we analyze the props and for each prop, generate
# the simplest possible logic as a block of Ruby source, so that we don't
# pay the cost of supporting types like T:::Hash[CustomType, SubstructType]
# when deserializing a simple Integer. Then we join those together,
# with a little shared logic to be able to detect when we get input keys
# that don't match any prop.
module DeserializerGenerator
extend T::Sig
CAN_USE_SYMBOL_NAME = T.let(RUBY_VERSION >= "3.3.0", T::Boolean)
# Generate a method that takes a T::Hash[String, T.untyped] representing
# serialized props, sets instance variables for each prop found in the
# input, and returns the count of we props set (which we can use to check
# for unexpected input keys with minimal effect on the fast path).
sig do
params(
props: T::Hash[Symbol, T::Hash[Symbol, T.untyped]],
defaults: T::Hash[Symbol, T::Props::Private::ApplyDefault],
)
.returns(String)
.checked(:never)
end
def self.generate(props, defaults)
parts = props.filter_map do |prop, rules|
next if rules[:dont_store]
# All of these strings should already be validated (directly or
# indirectly) in `validate_prop_name`, so we don't bother with a nice
# error message, but we double check here to prevent a refactoring
# from introducing a security vulnerability.
raise unless T::Props::Decorator::SAFE_NAME.match?(CAN_USE_SYMBOL_NAME ? prop.name : prop.to_s)
hash_key = rules.fetch(:serialized_form)
raise unless T::Props::Decorator::SAFE_NAME.match?(hash_key)
key = rules.fetch(:accessor_key)
ivar_name = CAN_USE_SYMBOL_NAME ? key.name : key.to_s
raise unless ivar_name.start_with?('@') && T::Props::Decorator::SAFE_ACCESSOR_KEY_NAME.match?(ivar_name)
transformation = SerdeTransform.generate(
T::Utils::Nilable.get_underlying_type_object(rules.fetch(:type_object)),
SerdeTransform::Mode::DESERIALIZE,
'val'
)
transformed_val = if transformation
# Rescuing exactly NoMethodError is intended as a temporary hack
# to preserve the semantics from before codegen. More generally
# we are inconsistent about typechecking on deser and need to decide
# our strategy here.
<<~RUBY
begin
#{transformation}
rescue NoMethodError => e
raise_deserialization_error(
#{prop.inspect},
val,
e,
)
val
end
RUBY
else
'val'
end
nil_handler = generate_nil_handler(
prop: prop,
serialized_form: hash_key,
default: defaults[prop],
nilable_type: T::Props::Utils.optional_prop?(rules),
raise_on_nil_write: !!rules[:raise_on_nil_write],
)
<<~RUBY
val = hash[#{hash_key.inspect}]
#{ivar_name} = if val.nil?
found -= 1 unless hash.key?(#{hash_key.inspect})
#{nil_handler}
else
#{transformed_val}
end
RUBY
end
<<~RUBY
def __t_props_generated_deserialize(hash)
found = #{parts.size}
#{parts.join("\n\n")}
found
end
RUBY
end
# This is very similar to what we do in ApplyDefault, but has a few
# key differences that mean we don't just re-use the code:
#
# 1. Where the logic in construction is that we generate a default
# if & only if the prop key isn't present in the input, here we'll
# generate a default even to override an explicit nil, but only
# if the prop is actually required.
# 2. Since we're generating raw Ruby source, we can remove a layer
# of indirection for marginally better performance; this seems worth
# it for the common cases of literals and empty arrays/hashes.
# 3. We need to care about the distinction between `raise_on_nil_write`
# and actually non-nilable, where new-instance construction doesn't.
#
# So we fall back to ApplyDefault only when one of the cases just
# mentioned doesn't apply.
sig do
params(
prop: Symbol,
serialized_form: String,
default: T.nilable(ApplyDefault),
nilable_type: T::Boolean,
raise_on_nil_write: T::Boolean,
)
.returns(String)
.checked(:never)
end
private_class_method def self.generate_nil_handler(
prop:,
serialized_form:,
default:,
nilable_type:,
raise_on_nil_write:
)
if !nilable_type
case default
when NilClass
"self.class.decorator.raise_nil_deserialize_error(#{serialized_form.inspect})"
when ApplyPrimitiveDefault
literal = default.default
case literal
# `Float` is intentionally left out here because `.inspect` does not produce the correct code
# representation for non-finite values like `Float::INFINITY` and `Float::NAN` and it's not totally
# clear that it won't cause issues with floating point precision.
when String, Integer, Symbol, TrueClass, FalseClass, NilClass
literal.inspect
else
"self.class.decorator.props_with_defaults.fetch(#{prop.inspect}).default"
end
when ApplyEmptyArrayDefault
'[]'
when ApplyEmptyHashDefault
'{}'
else
"self.class.decorator.props_with_defaults.fetch(#{prop.inspect}).default"
end
elsif raise_on_nil_write
"required_prop_missing_from_deserialize(#{prop.inspect})"
else
'nil'
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/private/serializer_generator.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/private/serializer_generator.rb | # frozen_string_literal: true
# typed: strict
module T::Props
module Private
# Generates a specialized `serialize` implementation for a subclass of
# T::Props::Serializable.
#
# The basic idea is that we analyze the props and for each prop, generate
# the simplest possible logic as a block of Ruby source, so that we don't
# pay the cost of supporting types like T:::Hash[CustomType, SubstructType]
# when serializing a simple Integer. Then we join those together,
# with a little shared logic to be able to detect when we get input keys
# that don't match any prop.
module SerializerGenerator
extend T::Sig
CAN_USE_SYMBOL_NAME = T.let(RUBY_VERSION >= "3.3.0", T::Boolean)
sig do
params(
props: T::Hash[Symbol, T::Hash[Symbol, T.untyped]],
)
.returns(String)
.checked(:never)
end
def self.generate(props)
parts = props.filter_map do |prop, rules|
next if rules[:dont_store]
# All of these strings should already be validated (directly or
# indirectly) in `validate_prop_name`, so we don't bother with a nice
# error message, but we double check here to prevent a refactoring
# from introducing a security vulnerability.
raise unless T::Props::Decorator::SAFE_NAME.match?(CAN_USE_SYMBOL_NAME ? prop.name : prop.to_s)
hash_key = rules.fetch(:serialized_form)
raise unless T::Props::Decorator::SAFE_NAME.match?(hash_key)
key = rules.fetch(:accessor_key)
ivar_name = CAN_USE_SYMBOL_NAME ? key.name : key.to_s
raise unless ivar_name.start_with?('@') && T::Props::Decorator::SAFE_ACCESSOR_KEY_NAME.match?(ivar_name)
transformed_val = SerdeTransform.generate(
T::Utils::Nilable.get_underlying_type_object(rules.fetch(:type_object)),
SerdeTransform::Mode::SERIALIZE,
ivar_name
) || ivar_name
nil_asserter =
if rules[:fully_optional]
''
else
"required_prop_missing_from_serialize(#{prop.inspect}) if strict"
end
# Don't serialize values that are nil to save space (both the
# nil value itself and the field name in the serialized BSON
# document)
<<~RUBY
if #{ivar_name}.nil?
#{nil_asserter}
else
h[#{hash_key.inspect}] = #{transformed_val}
end
RUBY
end
<<~RUBY
def __t_props_generated_serialize(strict)
h = {}
#{parts.join("\n\n")}
h
end
RUBY
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/private/setter_factory.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/private/setter_factory.rb | # frozen_string_literal: true
# typed: strict
module T::Props
module Private
module SetterFactory
extend T::Sig
SetterProc = T.type_alias { T.proc.params(val: T.untyped).void }
ValueValidationProc = T.type_alias { T.proc.params(val: T.untyped).void }
ValidateProc = T.type_alias { T.proc.params(prop: Symbol, value: T.untyped).void }
sig do
params(
klass: T.all(T::Module[T.anything], T::Props::ClassMethods),
prop: Symbol,
rules: T::Hash[Symbol, T.untyped]
)
.returns([SetterProc, ValueValidationProc])
.checked(:never)
end
def self.build_setter_proc(klass, prop, rules)
# Our nil check works differently than a simple T.nilable for various
# reasons (including the `raise_on_nil_write` setting and the existence
# of defaults & factories), so unwrap any T.nilable and do a check
# manually.
non_nil_type = T::Utils::Nilable.get_underlying_type_object(rules.fetch(:type_object))
accessor_key = rules.fetch(:accessor_key)
validate = rules[:setter_validate]
# It seems like a bug that this affects the behavior of setters, but
# some existing code relies on this behavior
has_explicit_nil_default = rules.key?(:default) && rules.fetch(:default).nil?
# Use separate methods in order to ensure that we only close over necessary
# variables
if !T::Props::Utils.need_nil_write_check?(rules) || has_explicit_nil_default
if validate.nil? && non_nil_type.is_a?(T::Types::Simple)
simple_nilable_proc(prop, accessor_key, non_nil_type.raw_type, klass)
else
nilable_proc(prop, accessor_key, non_nil_type, klass, validate)
end
else
if validate.nil? && non_nil_type.is_a?(T::Types::Simple)
simple_non_nil_proc(prop, accessor_key, non_nil_type.raw_type, klass)
else
non_nil_proc(prop, accessor_key, non_nil_type, klass, validate)
end
end
end
sig do
params(
prop: Symbol,
accessor_key: Symbol,
non_nil_type: T::Module[T.anything],
klass: T.all(T::Module[T.anything], T::Props::ClassMethods),
)
.returns([SetterProc, ValueValidationProc])
end
private_class_method def self.simple_non_nil_proc(prop, accessor_key, non_nil_type, klass)
[
proc do |val|
unless val.is_a?(non_nil_type)
T::Props::Private::SetterFactory.raise_pretty_error(
klass,
prop,
T::Utils.coerce(non_nil_type),
val,
)
end
instance_variable_set(accessor_key, val)
end,
proc do |val|
unless val.is_a?(non_nil_type)
T::Props::Private::SetterFactory.raise_pretty_error(
klass,
prop,
T::Utils.coerce(non_nil_type),
val,
)
end
end,
]
end
sig do
params(
prop: Symbol,
accessor_key: Symbol,
non_nil_type: T::Types::Base,
klass: T.all(T::Module[T.anything], T::Props::ClassMethods),
validate: T.nilable(ValidateProc)
)
.returns([SetterProc, ValueValidationProc])
end
private_class_method def self.non_nil_proc(prop, accessor_key, non_nil_type, klass, validate)
[
proc do |val|
# this use of recursively_valid? is intentional: unlike for
# methods, we want to make sure data at the 'edge'
# (e.g. models that go into databases or structs serialized
# from disk) are correct, so we use more thorough runtime
# checks there
if non_nil_type.recursively_valid?(val)
validate&.call(prop, val)
else
T::Props::Private::SetterFactory.raise_pretty_error(
klass,
prop,
non_nil_type,
val,
)
end
instance_variable_set(accessor_key, val)
end,
proc do |val|
# this use of recursively_valid? is intentional: unlike for
# methods, we want to make sure data at the 'edge'
# (e.g. models that go into databases or structs serialized
# from disk) are correct, so we use more thorough runtime
# checks there
if non_nil_type.recursively_valid?(val)
validate&.call(prop, val)
else
T::Props::Private::SetterFactory.raise_pretty_error(
klass,
prop,
non_nil_type,
val,
)
end
end,
]
end
sig do
params(
prop: Symbol,
accessor_key: Symbol,
non_nil_type: T::Module[T.anything],
klass: T.all(T::Module[T.anything], T::Props::ClassMethods),
)
.returns([SetterProc, ValueValidationProc])
end
private_class_method def self.simple_nilable_proc(prop, accessor_key, non_nil_type, klass)
[
proc do |val|
unless val.nil? || val.is_a?(non_nil_type)
T::Props::Private::SetterFactory.raise_pretty_error(
klass,
prop,
T::Utils.coerce(non_nil_type),
val,
)
end
instance_variable_set(accessor_key, val)
end,
proc do |val|
unless val.nil? || val.is_a?(non_nil_type)
T::Props::Private::SetterFactory.raise_pretty_error(
klass,
prop,
T::Utils.coerce(non_nil_type),
val,
)
end
end,
]
end
sig do
params(
prop: Symbol,
accessor_key: Symbol,
non_nil_type: T::Types::Base,
klass: T.all(T::Module[T.anything], T::Props::ClassMethods),
validate: T.nilable(ValidateProc),
)
.returns([SetterProc, ValueValidationProc])
end
private_class_method def self.nilable_proc(prop, accessor_key, non_nil_type, klass, validate)
[
proc do |val|
if val.nil?
instance_variable_set(accessor_key, nil)
# this use of recursively_valid? is intentional: unlike for
# methods, we want to make sure data at the 'edge'
# (e.g. models that go into databases or structs serialized
# from disk) are correct, so we use more thorough runtime
# checks there
elsif non_nil_type.recursively_valid?(val)
validate&.call(prop, val)
instance_variable_set(accessor_key, val)
else
T::Props::Private::SetterFactory.raise_pretty_error(
klass,
prop,
non_nil_type,
val,
)
instance_variable_set(accessor_key, val)
end
end,
proc do |val|
if val.nil?
# this use of recursively_valid? is intentional: unlike for
# methods, we want to make sure data at the 'edge'
# (e.g. models that go into databases or structs serialized
# from disk) are correct, so we use more thorough runtime
# checks there
elsif non_nil_type.recursively_valid?(val)
validate&.call(prop, val)
else
T::Props::Private::SetterFactory.raise_pretty_error(
klass,
prop,
non_nil_type,
val,
)
end
end,
]
end
sig do
params(
klass: T.all(T::Module[T.anything], T::Props::ClassMethods),
prop: Symbol,
type: T.any(T::Types::Base, T::Module[T.anything]),
val: T.untyped,
)
.void
end
def self.raise_pretty_error(klass, prop, type, val)
base_message = "Can't set #{klass.name}.#{prop} to #{val.inspect} (instance of #{val.class}) - need a #{type}"
pretty_message = "Parameter '#{prop}': #{base_message}\n"
caller_loc = caller_locations.find { |l| !l.to_s.include?('sorbet-runtime/lib/types/props') }
if caller_loc
pretty_message += "Caller: #{caller_loc.path}:#{caller_loc.lineno}\n"
end
T::Configuration.call_validation_error_handler(
nil,
message: base_message,
pretty_message: pretty_message,
kind: 'Parameter',
name: prop,
type: type,
value: val,
location: caller_loc,
)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/private/parser.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/private/parser.rb | # frozen_string_literal: true
# typed: false
module T::Props
module Private
module Parse
def parse(source)
@current_ruby ||= require_parser(:CurrentRuby)
@current_ruby.parse(source)
end
def s(type, *children)
@node ||= require_parser(:AST, :Node)
@node.new(type, children)
end
private def require_parser(*constants)
# This is an optional dependency for sorbet-runtime in general,
# but is required here
require 'parser/current'
# Hack to work around the static checker thinking the constant is
# undefined
cls = Kernel.const_get(:Parser, true)
while (const = constants.shift)
cls = cls.const_get(const, false)
end
cls
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/private/apply_default.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/private/apply_default.rb | # frozen_string_literal: true
# typed: strict
module T::Props
module Private
class ApplyDefault
extend T::Sig
extend T::Helpers
abstract!
# checked(:never) - O(object construction x prop count)
sig { returns(SetterFactory::SetterProc).checked(:never) }
attr_reader :setter_proc
# checked(:never) - We do this with `T.let` instead
sig { params(accessor_key: Symbol, setter_proc: SetterFactory::SetterProc).void.checked(:never) }
def initialize(accessor_key, setter_proc)
@accessor_key = T.let(accessor_key, Symbol)
@setter_proc = T.let(setter_proc, SetterFactory::SetterProc)
end
# checked(:never) - O(object construction x prop count)
sig { abstract.returns(T.untyped).checked(:never) }
def default; end
# checked(:never) - O(object construction x prop count)
sig { abstract.params(instance: T.all(T::Props::Optional, Object)).void.checked(:never) }
def set_default(instance); end
NO_CLONE_TYPES = T.let([TrueClass, FalseClass, NilClass, Symbol, Numeric, T::Enum].freeze, T::Array[T::Module[T.anything]])
# checked(:never) - Rules hash is expensive to check
sig { params(cls: T::Module[T.anything], rules: T::Hash[Symbol, T.untyped]).returns(T.nilable(ApplyDefault)).checked(:never) }
def self.for(cls, rules)
accessor_key = rules.fetch(:accessor_key)
setter = rules.fetch(:setter_proc)
if rules.key?(:factory)
ApplyDefaultFactory.new(cls, rules.fetch(:factory), accessor_key, setter)
elsif rules.key?(:default)
default = rules.fetch(:default)
case default
when *NO_CLONE_TYPES
return ApplyPrimitiveDefault.new(default, accessor_key, setter)
when String
if default.frozen?
return ApplyPrimitiveDefault.new(default, accessor_key, setter)
end
when Array
if default.empty? && default.class == Array
return ApplyEmptyArrayDefault.new(accessor_key, setter)
end
when Hash
if default.empty? && default.default.nil? && T.unsafe(default).default_proc.nil? && default.class == Hash
return ApplyEmptyHashDefault.new(accessor_key, setter)
end
end
ApplyComplexDefault.new(default, accessor_key, setter)
else
nil
end
end
end
class ApplyFixedDefault < ApplyDefault
abstract!
# checked(:never) - We do this with `T.let` instead
sig { params(default: BasicObject, accessor_key: Symbol, setter_proc: SetterFactory::SetterProc).void.checked(:never) }
def initialize(default, accessor_key, setter_proc)
# FIXME: Ideally we'd check here that the default is actually a valid
# value for this field, but existing code relies on the fact that we don't.
#
# :(
#
# setter_proc.call(default)
@default = T.let(default, BasicObject)
super(accessor_key, setter_proc)
end
# checked(:never) - O(object construction x prop count)
sig { override.params(instance: T.all(T::Props::Optional, Object)).void.checked(:never) }
def set_default(instance)
instance.instance_variable_set(@accessor_key, default)
end
end
class ApplyPrimitiveDefault < ApplyFixedDefault
# checked(:never) - O(object construction x prop count)
sig { override.returns(T.untyped).checked(:never) }
attr_reader :default
end
class ApplyComplexDefault < ApplyFixedDefault
# checked(:never) - O(object construction x prop count)
sig { override.returns(T.untyped).checked(:never) }
def default
T::Props::Utils.deep_clone_object(@default)
end
end
# Special case since it's so common, and a literal `[]` is meaningfully
# faster than falling back to ApplyComplexDefault or even calling
# `some_empty_array.dup`
class ApplyEmptyArrayDefault < ApplyDefault
# checked(:never) - O(object construction x prop count)
sig { override.params(instance: T.all(T::Props::Optional, Object)).void.checked(:never) }
def set_default(instance)
instance.instance_variable_set(@accessor_key, [])
end
# checked(:never) - O(object construction x prop count)
sig { override.returns(T::Array[T.untyped]).checked(:never) }
def default
[]
end
end
# Special case since it's so common, and a literal `{}` is meaningfully
# faster than falling back to ApplyComplexDefault or even calling
# `some_empty_hash.dup`
class ApplyEmptyHashDefault < ApplyDefault
# checked(:never) - O(object construction x prop count)
sig { override.params(instance: T.all(T::Props::Optional, Object)).void.checked(:never) }
def set_default(instance)
instance.instance_variable_set(@accessor_key, {})
end
# checked(:never) - O(object construction x prop count)
sig { override.returns(T::Hash[T.untyped, T.untyped]).checked(:never) }
def default
{}
end
end
class ApplyDefaultFactory < ApplyDefault
# checked(:never) - We do this with `T.let` instead
sig do
params(
cls: T::Module[T.anything],
factory: T.any(Proc, Method),
accessor_key: Symbol,
setter_proc: SetterFactory::SetterProc,
)
.void
.checked(:never)
end
def initialize(cls, factory, accessor_key, setter_proc)
@class = T.let(cls, T::Module[T.anything])
@factory = T.let(factory, T.any(Proc, Method))
super(accessor_key, setter_proc)
end
# checked(:never) - O(object construction x prop count)
sig { override.params(instance: T.all(T::Props::Optional, Object)).void.checked(:never) }
def set_default(instance)
# Use the actual setter to validate the factory returns a legitimate
# value every time
instance.instance_exec(default, &@setter_proc)
end
# checked(:never) - O(object construction x prop count)
sig { override.returns(T.untyped).checked(:never) }
def default
@class.class_exec(&@factory)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/private/serde_transform.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/props/private/serde_transform.rb | # frozen_string_literal: true
# typed: strict
module T::Props
module Private
module SerdeTransform
extend T::Sig
class Serialize; end
private_constant :Serialize
class Deserialize; end
private_constant :Deserialize
ModeType = T.type_alias { T.any(Serialize, Deserialize) }
private_constant :ModeType
module Mode
SERIALIZE = T.let(Serialize.new.freeze, Serialize)
DESERIALIZE = T.let(Deserialize.new.freeze, Deserialize)
end
NO_TRANSFORM_TYPES = T.let(
[TrueClass, FalseClass, NilClass, Symbol, String].freeze,
T::Array[T::Module[T.anything]],
)
private_constant :NO_TRANSFORM_TYPES
sig do
params(
type: T::Types::Base,
mode: ModeType,
varname: String,
)
.returns(T.nilable(String))
.checked(:never)
end
def self.generate(type, mode, varname)
case type
when T::Types::TypedArray
inner = generate(type.type, mode, 'v')
if inner.nil?
"#{varname}.dup"
else
"#{varname}.map {|v| #{inner}}"
end
when T::Types::TypedSet
inner = generate(type.type, mode, 'v')
if inner.nil?
"#{varname}.dup"
else
"Set.new(#{varname}) {|v| #{inner}}"
end
when T::Types::TypedHash
keys = generate(type.keys, mode, 'k')
values = generate(type.values, mode, 'v')
if keys && values
"#{varname}.each_with_object({}) {|(k,v),h| h[#{keys}] = #{values}}"
elsif keys
"#{varname}.transform_keys {|k| #{keys}}"
elsif values
"#{varname}.transform_values {|v| #{values}}"
else
"#{varname}.dup"
end
when T::Types::Simple
raw = type.raw_type
if NO_TRANSFORM_TYPES.any? { |cls| raw <= cls }
nil
elsif raw <= Float
case mode
when Deserialize then "#{varname}.to_f"
when Serialize then nil
else T.absurd(mode)
end
elsif raw <= Numeric
nil
elsif raw < T::Props::Serializable
handle_serializable_subtype(varname, raw, mode)
elsif raw.singleton_class < T::Props::CustomType
handle_custom_type(varname, T.unsafe(raw), mode)
elsif T::Configuration.scalar_types.include?(raw.name)
# It's a bit of a hack that this is separate from NO_TRANSFORM_TYPES
# and doesn't check inheritance (like `T::Props::CustomType.scalar_type?`
# does), but it covers the main use case (pay-server's custom `Boolean`
# module) without either requiring `T::Configuration.scalar_types` to
# accept modules instead of strings (which produces load-order issues
# and subtle behavior changes) or eating the performance cost of doing
# an inheritance check by manually crawling a class hierarchy and doing
# string comparisons.
nil
else
"T::Props::Utils.deep_clone_object(#{varname})"
end
when T::Types::Union
non_nil_type = T::Utils.unwrap_nilable(type)
if non_nil_type
inner = generate(non_nil_type, mode, varname)
if inner.nil?
nil
else
"#{varname}.nil? ? nil : #{inner}"
end
elsif type.types.all? { |t| generate(t, mode, varname).nil? }
# Handle, e.g., T::Boolean
nil
else
# We currently deep_clone_object if the type was T.any(Integer, Float).
# When we get better support for union types (maybe this specific
# union type, because it would be a replacement for
# Chalk::ODM::DeprecatedNumemric), we could opt to special case
# this union to have no specific serde transform (the only reason
# why Float has a special case is because round tripping through
# JSON might normalize Floats to Integers)
"T::Props::Utils.deep_clone_object(#{varname})"
end
when T::Types::Intersection
dynamic_fallback = "T::Props::Utils.deep_clone_object(#{varname})"
# Transformations for any members of the intersection type where we
# know what we need to do and did not have to fall back to the
# dynamic deep clone method.
#
# NB: This deliberately does include `nil`, which means we know we
# don't need to do any transforming.
inner_known = type.types
.map { |t| generate(t, mode, varname) }
.reject { |t| t == dynamic_fallback }
.uniq
if inner_known.size != 1
# If there were no cases where we could tell what we need to do,
# e.g. if this is `T.all(SomethingWeird, WhoKnows)`, just use the
# dynamic fallback.
#
# If there were multiple cases and they weren't consistent, e.g.
# if this is `T.all(String, T::Array[Integer])`, the type is probably
# bogus/uninhabited, but use the dynamic fallback because we still
# don't have a better option, and this isn't the place to raise that
# error.
dynamic_fallback
else
# This is probably something like `T.all(String, SomeMarker)` or
# `T.all(SomeEnum, T.deprecated_enum(SomeEnum::FOO))` and we should
# treat it like String or SomeEnum even if we don't know what to do
# with the rest of the type.
inner_known.first
end
when T::Types::Enum
generate(T::Utils.lift_enum(type), mode, varname)
else
"T::Props::Utils.deep_clone_object(#{varname})"
end
end
sig { params(varname: String, type: T::Module[T.anything], mode: ModeType).returns(String).checked(:never) }
private_class_method def self.handle_serializable_subtype(varname, type, mode)
case mode
when Serialize
"#{varname}.serialize(strict)"
when Deserialize
type_name = T.must(module_name(type))
"#{type_name}.from_hash(#{varname})"
else
T.absurd(mode)
end
end
sig { params(varname: String, type: T::Module[T.anything], mode: ModeType).returns(String).checked(:never) }
private_class_method def self.handle_custom_type(varname, type, mode)
case mode
when Serialize
"T::Props::CustomType.checked_serialize(#{varname})"
when Deserialize
type_name = T.must(module_name(type))
"#{type_name}.deserialize(#{varname})"
else
T.absurd(mode)
end
end
sig { params(type: T::Module[T.anything]).returns(T.nilable(String)).checked(:never) }
private_class_method def self.module_name(type)
T::Configuration.module_name_mangler.call(type)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/public_suffix-7.0.0/lib/public_suffix.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/public_suffix-7.0.0/lib/public_suffix.rb | # frozen_string_literal: true
# = Public Suffix
#
# Domain name parser based on the Public Suffix List.
#
# Copyright (c) 2009-2025 Simone Carletti <weppos@weppos.net>
require_relative "public_suffix/domain"
require_relative "public_suffix/version"
require_relative "public_suffix/errors"
require_relative "public_suffix/rule"
require_relative "public_suffix/list"
# PublicSuffix is a Ruby domain name parser based on the Public Suffix List.
#
# The [Public Suffix List](https://publicsuffix.org) is a cross-vendor initiative
# to provide an accurate list of domain name suffixes.
#
# The Public Suffix List is an initiative of the Mozilla Project,
# but is maintained as a community resource. It is available for use in any software,
# but was originally created to meet the needs of browser manufacturers.
module PublicSuffix
DOT = "."
BANG = "!"
STAR = "*"
# Parses +name+ and returns the {PublicSuffix::Domain} instance.
#
# @example Parse a valid domain
# PublicSuffix.parse("google.com")
# # => #<PublicSuffix::Domain:0x007fec2e51e588 @sld="google", @tld="com", @trd=nil>
#
# @example Parse a valid subdomain
# PublicSuffix.parse("www.google.com")
# # => #<PublicSuffix::Domain:0x007fec276d4cf8 @sld="google", @tld="com", @trd="www">
#
# @example Parse a fully qualified domain
# PublicSuffix.parse("google.com.")
# # => #<PublicSuffix::Domain:0x007fec257caf38 @sld="google", @tld="com", @trd=nil>
#
# @example Parse a fully qualified domain (subdomain)
# PublicSuffix.parse("www.google.com.")
# # => #<PublicSuffix::Domain:0x007fec27b6bca8 @sld="google", @tld="com", @trd="www">
#
# @example Parse an invalid (unlisted) domain
# PublicSuffix.parse("x.yz")
# # => #<PublicSuffix::Domain:0x007fec2f49bec0 @sld="x", @tld="yz", @trd=nil>
#
# @example Parse an invalid (unlisted) domain with strict checking (without applying the default * rule)
# PublicSuffix.parse("x.yz", default_rule: nil)
# # => PublicSuffix::DomainInvalid: `x.yz` is not a valid domain
#
# @example Parse an URL (not supported, only domains)
# PublicSuffix.parse("http://www.google.com")
# # => PublicSuffix::DomainInvalid: http://www.google.com is not expected to contain a scheme
#
#
# @param name [#to_s] The domain name or fully qualified domain name to parse.
# @param list [PublicSuffix::List] The rule list to search, defaults to the default {PublicSuffix::List}
# @param ignore_private [Boolean]
# @return [PublicSuffix::Domain]
#
# @raise [PublicSuffix::DomainInvalid] If domain is not a valid domain.
# @raise [PublicSuffix::DomainNotAllowed] If a rule for +domain+ is found, but the rule doesn't allow +domain+.
def self.parse(name, list: List.default, default_rule: list.default_rule, ignore_private: false)
what = normalize(name)
raise what if what.is_a?(DomainInvalid)
rule = list.find(what, default: default_rule, ignore_private: ignore_private)
# rubocop:disable Style/IfUnlessModifier
if rule.nil?
raise DomainInvalid, "`#{what}` is not a valid domain"
end
if rule.decompose(what).last.nil?
raise DomainNotAllowed, "`#{what}` is not allowed according to Registry policy"
end
# rubocop:enable Style/IfUnlessModifier
decompose(what, rule)
end
# Checks whether +domain+ is assigned and allowed, without actually parsing it.
#
# This method doesn't care whether domain is a domain or subdomain.
# The validation is performed using the default {PublicSuffix::List}.
#
# @example Validate a valid domain
# PublicSuffix.valid?("example.com")
# # => true
#
# @example Validate a valid subdomain
# PublicSuffix.valid?("www.example.com")
# # => true
#
# @example Validate a not-listed domain
# PublicSuffix.valid?("example.tldnotlisted")
# # => true
#
# @example Validate a not-listed domain with strict checking (without applying the default * rule)
# PublicSuffix.valid?("example.tldnotlisted")
# # => true
# PublicSuffix.valid?("example.tldnotlisted", default_rule: nil)
# # => false
#
# @example Validate a fully qualified domain
# PublicSuffix.valid?("google.com.")
# # => true
# PublicSuffix.valid?("www.google.com.")
# # => true
#
# @example Check an URL (which is not a valid domain)
# PublicSuffix.valid?("http://www.example.com")
# # => false
#
#
# @param name [#to_s] The domain name or fully qualified domain name to validate.
# @param ignore_private [Boolean]
# @return [Boolean]
def self.valid?(name, list: List.default, default_rule: list.default_rule, ignore_private: false)
what = normalize(name)
return false if what.is_a?(DomainInvalid)
rule = list.find(what, default: default_rule, ignore_private: ignore_private)
!rule.nil? && !rule.decompose(what).last.nil?
end
# Attempt to parse the name and returns the domain, if valid.
#
# This method doesn't raise. Instead, it returns nil if the domain is not valid for whatever reason.
#
# @param name [#to_s] The domain name or fully qualified domain name to parse.
# @param list [PublicSuffix::List] The rule list to search, defaults to the default {PublicSuffix::List}
# @param ignore_private [Boolean]
# @return [String]
def self.domain(name, **options)
parse(name, **options).domain
rescue PublicSuffix::Error
nil
end
# private
def self.decompose(name, rule)
left, right = rule.decompose(name)
parts = left.split(DOT)
# If we have 0 parts left, there is just a tld and no domain or subdomain
# If we have 1 part left, there is just a tld, domain and not subdomain
# If we have 2 parts left, the last part is the domain, the other parts (combined) are the subdomain
tld = right
sld = parts.empty? ? nil : parts.pop
trd = parts.empty? ? nil : parts.join(DOT)
Domain.new(tld, sld, trd)
end
# Pretend we know how to deal with user input.
def self.normalize(name)
name = name.to_s.dup
name.strip!
name.chomp!(DOT)
name.downcase!
return DomainInvalid.new("Name is blank") if name.empty?
return DomainInvalid.new("Name starts with a dot") if name.start_with?(DOT)
return DomainInvalid.new(format("%s is not expected to contain a scheme", name)) if name.include?("://")
name
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/public_suffix-7.0.0/lib/public_suffix/version.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/public_suffix-7.0.0/lib/public_suffix/version.rb | # frozen_string_literal: true
# = Public Suffix
#
# Domain name parser based on the Public Suffix List.
#
# Copyright (c) 2009-2025 Simone Carletti <weppos@weppos.net>
module PublicSuffix
# @return [String] the current library version
VERSION = "7.0.0"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/public_suffix-7.0.0/lib/public_suffix/errors.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/public_suffix-7.0.0/lib/public_suffix/errors.rb | # frozen_string_literal: true
# = Public Suffix
#
# Domain name parser based on the Public Suffix List.
#
# Copyright (c) 2009-2025 Simone Carletti <weppos@weppos.net>
module PublicSuffix
class Error < StandardError
end
# Raised when trying to parse an invalid name.
# A name is considered invalid when no rule is found in the definition list.
#
# @example
#
# PublicSuffix.parse("nic.test")
# # => PublicSuffix::DomainInvalid
#
# PublicSuffix.parse("http://www.nic.it")
# # => PublicSuffix::DomainInvalid
#
class DomainInvalid < Error
end
# Raised when trying to parse a name that matches a suffix.
#
# @example
#
# PublicSuffix.parse("nic.do")
# # => PublicSuffix::DomainNotAllowed
#
# PublicSuffix.parse("www.nic.do")
# # => PublicSuffix::Domain
#
class DomainNotAllowed < DomainInvalid
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/public_suffix-7.0.0/lib/public_suffix/domain.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/public_suffix-7.0.0/lib/public_suffix/domain.rb | # frozen_string_literal: true
# = Public Suffix
#
# Domain name parser based on the Public Suffix List.
#
# Copyright (c) 2009-2025 Simone Carletti <weppos@weppos.net>
module PublicSuffix
# Domain represents a domain name, composed by a TLD, SLD and TRD.
class Domain
# Splits a string into the labels, that is the dot-separated parts.
#
# The input is not validated, but it is assumed to be a valid domain name.
#
# @example
#
# name_to_labels('example.com')
# # => ['example', 'com']
#
# name_to_labels('example.co.uk')
# # => ['example', 'co', 'uk']
#
# @param name [String, #to_s] The domain name to split.
# @return [Array<String>]
def self.name_to_labels(name)
name.to_s.split(DOT)
end
attr_reader :tld, :sld, :trd
# Creates and returns a new {PublicSuffix::Domain} instance.
#
# @overload initialize(tld)
# Initializes with a +tld+.
# @param [String] tld The TLD (extension)
# @overload initialize(tld, sld)
# Initializes with a +tld+ and +sld+.
# @param [String] tld The TLD (extension)
# @param [String] sld The TRD (domain)
# @overload initialize(tld, sld, trd)
# Initializes with a +tld+, +sld+ and +trd+.
# @param [String] tld The TLD (extension)
# @param [String] sld The SLD (domain)
# @param [String] trd The TRD (subdomain)
#
# @yield [self] Yields on self.
# @yieldparam [PublicSuffix::Domain] self The newly creates instance
#
# @example Initialize with a TLD
# PublicSuffix::Domain.new("com")
# # => #<PublicSuffix::Domain @tld="com">
#
# @example Initialize with a TLD and SLD
# PublicSuffix::Domain.new("com", "example")
# # => #<PublicSuffix::Domain @tld="com", @trd=nil>
#
# @example Initialize with a TLD, SLD and TRD
# PublicSuffix::Domain.new("com", "example", "wwww")
# # => #<PublicSuffix::Domain @tld="com", @trd=nil, @sld="example">
#
def initialize(*args)
@tld, @sld, @trd = args
yield(self) if block_given?
end
# Returns a string representation of this object.
#
# @return [String]
def to_s
name
end
# Returns an array containing the domain parts.
#
# @return [Array<String, nil>]
#
# @example
#
# PublicSuffix::Domain.new("google.com").to_a
# # => [nil, "google", "com"]
#
# PublicSuffix::Domain.new("www.google.com").to_a
# # => [nil, "google", "com"]
#
def to_a
[@trd, @sld, @tld]
end
# Returns the full domain name.
#
# @return [String]
#
# @example Gets the domain name of a domain
# PublicSuffix::Domain.new("com", "google").name
# # => "google.com"
#
# @example Gets the domain name of a subdomain
# PublicSuffix::Domain.new("com", "google", "www").name
# # => "www.google.com"
#
def name
[@trd, @sld, @tld].compact.join(DOT)
end
# Returns a domain-like representation of this object
# if the object is a {#domain?}, <tt>nil</tt> otherwise.
#
# PublicSuffix::Domain.new("com").domain
# # => nil
#
# PublicSuffix::Domain.new("com", "google").domain
# # => "google.com"
#
# PublicSuffix::Domain.new("com", "google", "www").domain
# # => "www.google.com"
#
# This method doesn't validate the input. It handles the domain
# as a valid domain name and simply applies the necessary transformations.
#
# This method returns a FQD, not just the domain part.
# To get the domain part, use <tt>#sld</tt> (aka second level domain).
#
# PublicSuffix::Domain.new("com", "google", "www").domain
# # => "google.com"
#
# PublicSuffix::Domain.new("com", "google", "www").sld
# # => "google"
#
# @see #domain?
# @see #subdomain
#
# @return [String]
def domain
[@sld, @tld].join(DOT) if domain?
end
# Returns a subdomain-like representation of this object
# if the object is a {#subdomain?}, <tt>nil</tt> otherwise.
#
# PublicSuffix::Domain.new("com").subdomain
# # => nil
#
# PublicSuffix::Domain.new("com", "google").subdomain
# # => nil
#
# PublicSuffix::Domain.new("com", "google", "www").subdomain
# # => "www.google.com"
#
# This method doesn't validate the input. It handles the domain
# as a valid domain name and simply applies the necessary transformations.
#
# This method returns a FQD, not just the subdomain part.
# To get the subdomain part, use <tt>#trd</tt> (aka third level domain).
#
# PublicSuffix::Domain.new("com", "google", "www").subdomain
# # => "www.google.com"
#
# PublicSuffix::Domain.new("com", "google", "www").trd
# # => "www"
#
# @see #subdomain?
# @see #domain
#
# @return [String]
def subdomain
[@trd, @sld, @tld].join(DOT) if subdomain?
end
# Checks whether <tt>self</tt> looks like a domain.
#
# This method doesn't actually validate the domain.
# It only checks whether the instance contains
# a value for the {#tld} and {#sld} attributes.
#
# @example
#
# PublicSuffix::Domain.new("com").domain?
# # => false
#
# PublicSuffix::Domain.new("com", "google").domain?
# # => true
#
# PublicSuffix::Domain.new("com", "google", "www").domain?
# # => true
#
# # This is an invalid domain, but returns true
# # because this method doesn't validate the content.
# PublicSuffix::Domain.new("com", nil).domain?
# # => true
#
# @see #subdomain?
#
# @return [Boolean]
def domain?
!(@tld.nil? || @sld.nil?)
end
# Checks whether <tt>self</tt> looks like a subdomain.
#
# This method doesn't actually validate the subdomain.
# It only checks whether the instance contains
# a value for the {#tld}, {#sld} and {#trd} attributes.
# If you also want to validate the domain,
# use {#valid_subdomain?} instead.
#
# @example
#
# PublicSuffix::Domain.new("com").subdomain?
# # => false
#
# PublicSuffix::Domain.new("com", "google").subdomain?
# # => false
#
# PublicSuffix::Domain.new("com", "google", "www").subdomain?
# # => true
#
# # This is an invalid domain, but returns true
# # because this method doesn't validate the content.
# PublicSuffix::Domain.new("com", "example", nil).subdomain?
# # => true
#
# @see #domain?
#
# @return [Boolean]
def subdomain?
!(@tld.nil? || @sld.nil? || @trd.nil?)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/public_suffix-7.0.0/lib/public_suffix/list.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/public_suffix-7.0.0/lib/public_suffix/list.rb | # frozen_string_literal: true
# = Public Suffix
#
# Domain name parser based on the Public Suffix List.
#
# Copyright (c) 2009-2025 Simone Carletti <weppos@weppos.net>
module PublicSuffix
# A {PublicSuffix::List} is a collection of one
# or more {PublicSuffix::Rule}.
#
# Given a {PublicSuffix::List},
# you can add or remove {PublicSuffix::Rule},
# iterate all items in the list or search for the first rule
# which matches a specific domain name.
#
# # Create a new list
# list = PublicSuffix::List.new
#
# # Push two rules to the list
# list << PublicSuffix::Rule.factory("it")
# list << PublicSuffix::Rule.factory("com")
#
# # Get the size of the list
# list.size
# # => 2
#
# # Search for the rule matching given domain
# list.find("example.com")
# # => #<PublicSuffix::Rule::Normal>
# list.find("example.org")
# # => nil
#
# You can create as many {PublicSuffix::List} you want.
# The {PublicSuffix::List.default} rule list is used
# to tokenize and validate a domain.
#
class List
DEFAULT_LIST_PATH = File.expand_path("../../data/list.txt", __dir__)
# Gets the default rule list.
#
# Initializes a new {PublicSuffix::List} parsing the content
# of {PublicSuffix::List.default_list_content}, if required.
#
# @return [PublicSuffix::List]
def self.default(**options)
@default ||= parse(File.read(DEFAULT_LIST_PATH), **options)
end
# Sets the default rule list to +value+.
#
# @param value [PublicSuffix::List] the new list
# @return [PublicSuffix::List]
def self.default=(value)
@default = value
end
# Parse given +input+ treating the content as Public Suffix List.
#
# See http://publicsuffix.org/format/ for more details about input format.
#
# @param input [#each_line] the list to parse
# @param private_domains [Boolean] whether to ignore the private domains section
# @return [PublicSuffix::List]
def self.parse(input, private_domains: true)
comment_token = "//"
private_token = "===BEGIN PRIVATE DOMAINS==="
section = nil # 1 == ICANN, 2 == PRIVATE
new do |list|
input.each_line do |line|
line.strip!
case # rubocop:disable Style/EmptyCaseCondition
# skip blank lines
when line.empty?
next
# include private domains or stop scanner
when line.include?(private_token)
break if !private_domains
section = 2
# skip comments
when line.start_with?(comment_token) # rubocop:disable Lint/DuplicateBranch
next
else
list.add(Rule.factory(line, private: section == 2))
end
end
end
end
# Initializes an empty {PublicSuffix::List}.
#
# @yield [self] Yields on self.
# @yieldparam [PublicSuffix::List] self The newly created instance.
def initialize
@rules = {}
yield(self) if block_given?
end
# Checks whether two lists are equal.
#
# List <tt>one</tt> is equal to <tt>two</tt>, if <tt>two</tt> is an instance of
# {PublicSuffix::List} and each +PublicSuffix::Rule::*+
# in list <tt>one</tt> is available in list <tt>two</tt>, in the same order.
#
# @param other [PublicSuffix::List] the List to compare
# @return [Boolean]
def ==(other)
return false unless other.is_a?(List)
equal?(other) || @rules == other.rules
end
alias eql? ==
# Iterates each rule in the list.
def each(&block)
Enumerator.new do |y|
@rules.each do |key, node|
y << entry_to_rule(node, key)
end
end.each(&block)
end
# Adds the given object to the list and optionally refreshes the rule index.
#
# @param rule [PublicSuffix::Rule::*] the rule to add to the list
# @return [self]
def add(rule)
@rules[rule.value] = rule_to_entry(rule)
self
end
alias << add
# Gets the number of rules in the list.
#
# @return [Integer]
def size
@rules.size
end
# Checks whether the list is empty.
#
# @return [Boolean]
def empty?
@rules.empty?
end
# Removes all rules.
#
# @return [self]
def clear
@rules.clear
self
end
# Finds and returns the rule corresponding to the longest public suffix for the hostname.
#
# @param name [#to_s] the hostname
# @param default [PublicSuffix::Rule::*] the default rule to return in case no rule matches
# @return [PublicSuffix::Rule::*]
def find(name, default: default_rule, **options)
rule = select(name, **options).inject do |l, r|
return r if r.instance_of?(Rule::Exception)
l.length > r.length ? l : r
end
rule || default
end
# Selects all the rules matching given hostame.
#
# If `ignore_private` is set to true, the algorithm will skip the rules that are flagged as
# private domain. Note that the rules will still be part of the loop.
# If you frequently need to access lists ignoring the private domains,
# you should create a list that doesn't include these domains setting the
# `private_domains: false` option when calling {.parse}.
#
# Note that this method is currently private, as you should not rely on it. Instead,
# the public interface is {#find}. The current internal algorithm allows to return all
# matching rules, but different data structures may not be able to do it, and instead would
# return only the match. For this reason, you should rely on {#find}.
#
# @param name [#to_s] the hostname
# @param ignore_private [Boolean]
# @return [Array<PublicSuffix::Rule::*>]
def select(name, ignore_private: false)
name = name.to_s
parts = name.split(DOT).reverse!
index = 0
query = parts[index]
rules = []
loop do
match = @rules[query]
rules << entry_to_rule(match, query) if !match.nil? && (ignore_private == false || match.private == false)
index += 1
break if index >= parts.size
query = parts[index] + DOT + query
end
rules
end
private :select
# Gets the default rule.
#
# @see PublicSuffix::Rule.default_rule
#
# @return [PublicSuffix::Rule::*]
def default_rule
PublicSuffix::Rule.default
end
protected
attr_reader :rules
private
def entry_to_rule(entry, value)
entry.type.new(value: value, length: entry.length, private: entry.private)
end
def rule_to_entry(rule)
Rule::Entry.new(rule.class, rule.length, rule.private)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/public_suffix-7.0.0/lib/public_suffix/rule.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/public_suffix-7.0.0/lib/public_suffix/rule.rb | # frozen_string_literal: true
# = Public Suffix
#
# Domain name parser based on the Public Suffix List.
#
# Copyright (c) 2009-2025 Simone Carletti <weppos@weppos.net>
module PublicSuffix
# A Rule is a special object which holds a single definition
# of the Public Suffix List.
#
# There are 3 types of rules, each one represented by a specific
# subclass within the +PublicSuffix::Rule+ namespace.
#
# To create a new Rule, use the {PublicSuffix::Rule#factory} method.
#
# PublicSuffix::Rule.factory("ar")
# # => #<PublicSuffix::Rule::Normal>
#
module Rule
# @api internal
Entry = Struct.new(:type, :length, :private) # rubocop:disable Lint/StructNewOverride
# = Abstract rule class
#
# This represent the base class for a Rule definition
# in the {Public Suffix List}[https://publicsuffix.org].
#
# This is intended to be an Abstract class
# and you shouldn't create a direct instance. The only purpose
# of this class is to expose a common interface
# for all the available subclasses.
#
# * {PublicSuffix::Rule::Normal}
# * {PublicSuffix::Rule::Exception}
# * {PublicSuffix::Rule::Wildcard}
#
# ## Properties
#
# A rule is composed by 4 properties:
#
# value - A normalized version of the rule name.
# The normalization process depends on rule tpe.
#
# Here's an example
#
# PublicSuffix::Rule.factory("*.google.com")
# #<PublicSuffix::Rule::Wildcard:0x1015c14b0
# @value="google.com"
# >
#
# ## Rule Creation
#
# The best way to create a new rule is passing the rule name
# to the <tt>PublicSuffix::Rule.factory</tt> method.
#
# PublicSuffix::Rule.factory("com")
# # => PublicSuffix::Rule::Normal
#
# PublicSuffix::Rule.factory("*.com")
# # => PublicSuffix::Rule::Wildcard
#
# This method will detect the rule type and create an instance
# from the proper rule class.
#
# ## Rule Usage
#
# A rule describes the composition of a domain name and explains how to tokenize
# the name into tld, sld and trd.
#
# To use a rule, you first need to be sure the name you want to tokenize
# can be handled by the current rule.
# You can use the <tt>#match?</tt> method.
#
# rule = PublicSuffix::Rule.factory("com")
#
# rule.match?("google.com")
# # => true
#
# rule.match?("google.com")
# # => false
#
# Rule order is significant. A name can match more than one rule.
# See the {Public Suffix Documentation}[http://publicsuffix.org/format/]
# to learn more about rule priority.
#
# When you have the right rule, you can use it to tokenize the domain name.
#
# rule = PublicSuffix::Rule.factory("com")
#
# rule.decompose("google.com")
# # => ["google", "com"]
#
# rule.decompose("www.google.com")
# # => ["www.google", "com"]
#
# @abstract
#
class Base
# @return [String] the rule definition
attr_reader :value
# @return [String] the length of the rule
attr_reader :length
# @return [Boolean] true if the rule is a private domain
attr_reader :private
# Initializes a new rule from the content.
#
# @param content [String] the content of the rule
# @param private [Boolean]
def self.build(content, private: false)
new(value: content, private: private)
end
# Initializes a new rule.
#
# @param value [String]
# @param private [Boolean]
def initialize(value:, length: nil, private: false)
@value = value.to_s
@length = length || (@value.count(DOT) + 1)
@private = private
end
# Checks whether this rule is equal to <tt>other</tt>.
#
# @param other [PublicSuffix::Rule::*] The rule to compare
# @return [Boolean] true if this rule and other are instances of the same class
# and has the same value, false otherwise.
def ==(other)
equal?(other) || (self.class == other.class && value == other.value)
end
alias eql? ==
# Checks if this rule matches +name+.
#
# A domain name is said to match a rule if and only if
# all of the following conditions are met:
#
# - When the domain and rule are split into corresponding labels,
# that the domain contains as many or more labels than the rule.
# - Beginning with the right-most labels of both the domain and the rule,
# and continuing for all labels in the rule, one finds that for every pair,
# either they are identical, or that the label from the rule is "*".
#
# @see https://publicsuffix.org/list/
#
# @example
# PublicSuffix::Rule.factory("com").match?("example.com")
# # => true
# PublicSuffix::Rule.factory("com").match?("example.net")
# # => false
#
# @param name [String] the domain name to check
# @return [Boolean]
def match?(name)
# NOTE: it works because of the assumption there are no
# rules like foo.*.com. If the assumption is incorrect,
# we need to properly walk the input and skip parts according
# to wildcard component.
diff = name.chomp(value)
diff.empty? || diff.end_with?(DOT)
end
# @abstract
def parts
raise NotImplementedError
end
# @abstract
# @param domain [#to_s] The domain name to decompose
# @return [Array<String, nil>]
def decompose(*)
raise NotImplementedError
end
end
# Normal represents a standard rule (e.g. com).
class Normal < Base
# Gets the original rule definition.
#
# @return [String] The rule definition.
def rule
value
end
# Decomposes the domain name according to rule properties.
#
# @param domain [#to_s] The domain name to decompose
# @return [Array<String>] The array with [trd + sld, tld].
def decompose(domain)
suffix = parts.join('\.')
matches = domain.to_s.match(/^(.*)\.(#{suffix})$/)
matches ? matches[1..2] : [nil, nil]
end
# dot-split rule value and returns all rule parts
# in the order they appear in the value.
#
# @return [Array<String>]
def parts
@value.split(DOT)
end
end
# Wildcard represents a wildcard rule (e.g. *.co.uk).
class Wildcard < Base
# Initializes a new rule from the content.
#
# @param content [String] the content of the rule
# @param private [Boolean]
def self.build(content, private: false)
new(value: content.to_s[2..], private: private)
end
# Initializes a new rule.
#
# @param value [String]
# @param length [Integer]
# @param private [Boolean]
def initialize(value:, length: nil, private: false)
super
length or @length += 1 # * counts as 1
end
# Gets the original rule definition.
#
# @return [String] The rule definition.
def rule
value == "" ? STAR : STAR + DOT + value
end
# Decomposes the domain name according to rule properties.
#
# @param domain [#to_s] The domain name to decompose
# @return [Array<String>] The array with [trd + sld, tld].
def decompose(domain)
suffix = ([".*?"] + parts).join('\.')
matches = domain.to_s.match(/^(.*)\.(#{suffix})$/)
matches ? matches[1..2] : [nil, nil]
end
# dot-split rule value and returns all rule parts
# in the order they appear in the value.
#
# @return [Array<String>]
def parts
@value.split(DOT)
end
end
# Exception represents an exception rule (e.g. !parliament.uk).
class Exception < Base
# Initializes a new rule from the content.
#
# @param content [#to_s] the content of the rule
# @param private [Boolean]
def self.build(content, private: false)
new(value: content.to_s[1..], private: private)
end
# Gets the original rule definition.
#
# @return [String] The rule definition.
def rule
BANG + value
end
# Decomposes the domain name according to rule properties.
#
# @param domain [#to_s] The domain name to decompose
# @return [Array<String>] The array with [trd + sld, tld].
def decompose(domain)
suffix = parts.join('\.')
matches = domain.to_s.match(/^(.*)\.(#{suffix})$/)
matches ? matches[1..2] : [nil, nil]
end
# dot-split rule value and returns all rule parts
# in the order they appear in the value.
# The leftmost label is not considered a label.
#
# See http://publicsuffix.org/format/:
# If the prevailing rule is a exception rule,
# modify it by removing the leftmost label.
#
# @return [Array<String>]
def parts
@value.split(DOT)[1..]
end
end
# Takes the +name+ of the rule, detects the specific rule class
# and creates a new instance of that class.
# The +name+ becomes the rule +value+.
#
# @example Creates a Normal rule
# PublicSuffix::Rule.factory("ar")
# # => #<PublicSuffix::Rule::Normal>
#
# @example Creates a Wildcard rule
# PublicSuffix::Rule.factory("*.ar")
# # => #<PublicSuffix::Rule::Wildcard>
#
# @example Creates an Exception rule
# PublicSuffix::Rule.factory("!congresodelalengua3.ar")
# # => #<PublicSuffix::Rule::Exception>
#
# @param content [#to_s] the content of the rule
# @return [PublicSuffix::Rule::*] A rule instance.
def self.factory(content, private: false)
case content.to_s[0, 1]
when STAR
Wildcard
when BANG
Exception
else
Normal
end.build(content, private: private)
end
# The default rule to use if no rule match.
#
# The default rule is "*". From https://publicsuffix.org/list/:
#
# > If no rules match, the prevailing rule is "*".
#
# @return [PublicSuffix::Rule::Wildcard] The default rule.
def self.default
factory(STAR)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata.rb | # BinData -- Binary data manipulator.
# Copyright (c) 2007 - 2025 Dion Mendel.
require 'bindata/version'
require 'bindata/array'
require 'bindata/bits'
require 'bindata/buffer'
require 'bindata/choice'
require 'bindata/count_bytes_remaining'
require 'bindata/delayed_io'
require 'bindata/float'
require 'bindata/int'
require 'bindata/primitive'
require 'bindata/record'
require 'bindata/rest'
require 'bindata/section'
require 'bindata/skip'
require 'bindata/string'
require 'bindata/stringz'
require 'bindata/struct'
require 'bindata/trace'
require 'bindata/uint8_array'
require 'bindata/virtual'
require 'bindata/alignment'
require 'bindata/warnings'
# = BinData
#
# A declarative way to read and write structured binary data.
#
# A full reference manual is available online at
# https://github.com/dmendel/bindata/wiki
#
# == License
#
# BinData is released under the same license as Ruby.
#
# Copyright (c) 2007 - 2025 Dion Mendel.
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/io.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/io.rb | require 'stringio'
module BinData
# A wrapper around an IO object. The wrapper provides a consistent
# interface for BinData objects to use when accessing the IO.
module IO
# Creates a StringIO around +str+.
def self.create_string_io(str = "")
bin_str = str.dup.force_encoding(Encoding::BINARY)
StringIO.new(bin_str).tap(&:binmode)
end
# Create a new IO Read wrapper around +io+. +io+ must provide #read,
# #pos if reading the current stream position and #seek if setting the
# current stream position. If +io+ is a string it will be automatically
# wrapped in an StringIO object.
#
# The IO can handle bitstreams in either big or little endian format.
#
# M byte1 L M byte2 L
# S 76543210 S S fedcba98 S
# B B B B
#
# In big endian format:
# readbits(6), readbits(5) #=> [765432, 10fed]
#
# In little endian format:
# readbits(6), readbits(5) #=> [543210, a9876]
#
class Read
def initialize(io)
if self.class === io
raise ArgumentError, "io must not be a #{self.class}"
end
# wrap strings in a StringIO
if io.respond_to?(:to_str)
io = BinData::IO.create_string_io(io.to_str)
end
@io = RawIO.new(io)
# bits when reading
@rnbits = 0
@rval = 0
@rendian = nil
end
# Allow transforming data in the input stream.
# See +BinData::Buffer+ as an example.
#
# +io+ must be an instance of +Transform+.
#
# yields +self+ and +io+ to the given block
def transform(io)
reset_read_bits
saved = @io
@io = io.prepend_to_chain(@io)
yield(self, io)
io.after_read_transform
ensure
@io = saved
end
# The number of bytes remaining in the io steam.
def num_bytes_remaining
@io.num_bytes_remaining
end
# Seek +n+ bytes from the current position in the io stream.
def skipbytes(n)
reset_read_bits
@io.skip(n)
end
# Seek to an absolute offset within the io stream.
def seek_to_abs_offset(n)
reset_read_bits
@io.seek_abs(n)
end
# Reads exactly +n+ bytes from +io+.
#
# If the data read is nil an EOFError is raised.
#
# If the data read is too short an IOError is raised.
def readbytes(n)
reset_read_bits
read(n)
end
# Reads all remaining bytes from the stream.
def read_all_bytes
reset_read_bits
read
end
# Reads exactly +nbits+ bits from the stream. +endian+ specifies whether
# the bits are stored in +:big+ or +:little+ endian format.
def readbits(nbits, endian)
if @rendian != endian
# don't mix bits of differing endian
reset_read_bits
@rendian = endian
end
if endian == :big
read_big_endian_bits(nbits)
else
read_little_endian_bits(nbits)
end
end
# Discards any read bits so the stream becomes aligned at the
# next byte boundary.
def reset_read_bits
@rnbits = 0
@rval = 0
end
#---------------
private
def read(n = nil)
str = @io.read(n)
if n
raise EOFError, "End of file reached" if str.nil?
raise IOError, "data truncated" if str.size < n
end
str
end
def read_big_endian_bits(nbits)
while @rnbits < nbits
accumulate_big_endian_bits
end
val = (@rval >> (@rnbits - nbits)) & mask(nbits)
@rnbits -= nbits
@rval &= mask(@rnbits)
val
end
def accumulate_big_endian_bits
byte = read(1).unpack1('C') & 0xff
@rval = (@rval << 8) | byte
@rnbits += 8
end
def read_little_endian_bits(nbits)
while @rnbits < nbits
accumulate_little_endian_bits
end
val = @rval & mask(nbits)
@rnbits -= nbits
@rval >>= nbits
val
end
def accumulate_little_endian_bits
byte = read(1).unpack1('C') & 0xff
@rval = @rval | (byte << @rnbits)
@rnbits += 8
end
def mask(nbits)
(1 << nbits) - 1
end
end
# Create a new IO Write wrapper around +io+. +io+ must provide #write.
# If +io+ is a string it will be automatically wrapped in an StringIO
# object.
#
# The IO can handle bitstreams in either big or little endian format.
#
# See IO::Read for more information.
class Write
def initialize(io)
if self.class === io
raise ArgumentError, "io must not be a #{self.class}"
end
# wrap strings in a StringIO
if io.respond_to?(:to_str)
io = BinData::IO.create_string_io(io.to_str)
end
@io = RawIO.new(io)
@wnbits = 0
@wval = 0
@wendian = nil
end
# Allow transforming data in the output stream.
# See +BinData::Buffer+ as an example.
#
# +io+ must be an instance of +Transform+.
#
# yields +self+ and +io+ to the given block
def transform(io)
flushbits
saved = @io
@io = io.prepend_to_chain(@io)
yield(self, io)
io.after_write_transform
ensure
@io = saved
end
# Seek to an absolute offset within the io stream.
def seek_to_abs_offset(n)
raise IOError, "stream is unseekable" unless @io.seekable?
flushbits
@io.seek_abs(n)
end
# Writes the given string of bytes to the io stream.
def writebytes(str)
flushbits
write(str)
end
# Writes +nbits+ bits from +val+ to the stream. +endian+ specifies whether
# the bits are to be stored in +:big+ or +:little+ endian format.
def writebits(val, nbits, endian)
if @wendian != endian
# don't mix bits of differing endian
flushbits
@wendian = endian
end
clamped_val = val & mask(nbits)
if endian == :big
write_big_endian_bits(clamped_val, nbits)
else
write_little_endian_bits(clamped_val, nbits)
end
end
# To be called after all +writebits+ have been applied.
def flushbits
raise "Internal state error nbits = #{@wnbits}" if @wnbits >= 8
if @wnbits > 0
writebits(0, 8 - @wnbits, @wendian)
end
end
alias flush flushbits
#---------------
private
def write(data)
@io.write(data)
end
def write_big_endian_bits(val, nbits)
while nbits > 0
bits_req = 8 - @wnbits
if nbits >= bits_req
msb_bits = (val >> (nbits - bits_req)) & mask(bits_req)
nbits -= bits_req
val &= mask(nbits)
@wval = (@wval << bits_req) | msb_bits
write(@wval.chr)
@wval = 0
@wnbits = 0
else
@wval = (@wval << nbits) | val
@wnbits += nbits
nbits = 0
end
end
end
def write_little_endian_bits(val, nbits)
while nbits > 0
bits_req = 8 - @wnbits
if nbits >= bits_req
lsb_bits = val & mask(bits_req)
nbits -= bits_req
val >>= bits_req
@wval = @wval | (lsb_bits << @wnbits)
write(@wval.chr)
@wval = 0
@wnbits = 0
else
@wval = @wval | (val << @wnbits)
@wnbits += nbits
nbits = 0
end
end
end
def mask(nbits)
(1 << nbits) - 1
end
end
# API used to access the raw data stream.
class RawIO
def initialize(io)
@io = io
@pos = 0
if is_seekable?(io)
@initial_pos = io.pos
else
singleton_class.prepend(UnSeekableIO)
end
end
def is_seekable?(io)
io.pos
rescue NoMethodError, Errno::ESPIPE, Errno::EPIPE, Errno::EINVAL
nil
end
def seekable?
true
end
def num_bytes_remaining
start_mark = @io.pos
@io.seek(0, ::IO::SEEK_END)
end_mark = @io.pos
@io.seek(start_mark, ::IO::SEEK_SET)
end_mark - start_mark
end
def offset
@pos
end
def skip(n)
raise IOError, "can not skip backwards" if n.negative?
@io.seek(n, ::IO::SEEK_CUR)
@pos += n
end
def seek_abs(n)
@io.seek(n + @initial_pos, ::IO::SEEK_SET)
@pos = n
end
def read(n)
@io.read(n).tap { |data| @pos += (data&.size || 0) }
end
def write(data)
@io.write(data)
end
end
# An IO stream may be transformed before processing.
# e.g. encoding, compression, buffered.
#
# Multiple transforms can be chained together.
#
# To create a new transform layer, subclass +Transform+.
# Override the public methods +#read+ and +#write+ at a minimum.
# Additionally the hook, +#before_transform+, +#after_read_transform+
# and +#after_write_transform+ are available as well.
#
# IMPORTANT! If your transform changes the size of the underlying
# data stream (e.g. compression), then call
# +::transform_changes_stream_length!+ in your subclass.
class Transform
class << self
# Indicates that this transform changes the length of the
# underlying data. e.g. performs compression or error correction
def transform_changes_stream_length!
prepend(UnSeekableIO)
end
end
def initialize
@chain_io = nil
end
# Initialises this transform.
#
# Called before any IO operations.
def before_transform; end
# Flushes the input stream.
#
# Called after the final read operation.
def after_read_transform; end
# Flushes the output stream.
#
# Called after the final write operation.
def after_write_transform; end
# Prepends this transform to the given +chain+.
#
# Returns self (the new head of chain).
def prepend_to_chain(chain)
@chain_io = chain
before_transform
self
end
# Is the IO seekable?
def seekable?
@chain_io.seekable?
end
# How many bytes are available for reading?
def num_bytes_remaining
chain_num_bytes_remaining
end
# The current offset within the stream.
def offset
chain_offset
end
# Skips forward +n+ bytes in the input stream.
def skip(n)
chain_skip(n)
end
# Seeks to the given absolute position.
def seek_abs(n)
chain_seek_abs(n)
end
# Reads +n+ bytes from the stream.
def read(n)
chain_read(n)
end
# Writes +data+ to the stream.
def write(data)
chain_write(data)
end
#-------------
private
def create_empty_binary_string
String.new.force_encoding(Encoding::BINARY)
end
def chain_seekable?
@chain_io.seekable?
end
def chain_num_bytes_remaining
@chain_io.num_bytes_remaining
end
def chain_offset
@chain_io.offset
end
def chain_skip(n)
@chain_io.skip(n)
end
def chain_seek_abs(n)
@chain_io.seek_abs(n)
end
def chain_read(n)
@chain_io.read(n)
end
def chain_write(data)
@chain_io.write(data)
end
end
# A module to be prepended to +RawIO+ or +Transform+ when the data
# stream is not seekable. This is either due to underlying stream
# being unseekable or the transform changes the number of bytes.
module UnSeekableIO
def seekable?
false
end
def num_bytes_remaining
raise IOError, "stream is unseekable"
end
def skip(n)
raise IOError, "can not skip backwards" if n.negative?
# skip over data in 8k blocks
while n > 0
bytes_to_read = [n, 8192].min
read(bytes_to_read)
n -= bytes_to_read
end
end
def seek_abs(n)
skip(n - offset)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/record.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/record.rb | require 'bindata/dsl'
require 'bindata/struct'
module BinData
# A Record is a declarative wrapper around Struct.
#
# See +Struct+ for more info.
class Record < BinData::Struct
extend DSLMixin
unregister_self
dsl_parser :struct
arg_processor :record
end
class RecordArgProcessor < StructArgProcessor
include MultiFieldArgSeparator
def sanitize_parameters!(obj_class, params)
super(obj_class, params.merge!(obj_class.dsl_params))
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/int.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/int.rb | require 'thread'
require 'bindata/base_primitive'
module BinData
# Defines a number of classes that contain an integer. The integer
# is defined by endian, signedness and number of bytes.
module Int # :nodoc: all
@@mutex = Mutex.new
class << self
def define_class(name, nbits, endian, signed)
@@mutex.synchronize do
unless BinData.const_defined?(name)
new_class = Class.new(BinData::BasePrimitive)
Int.define_methods(new_class, nbits, endian.to_sym, signed.to_sym)
RegisteredClasses.register(name, new_class)
BinData.const_set(name, new_class)
end
end
BinData.const_get(name)
end
def define_methods(int_class, nbits, endian, signed)
raise "nbits must be divisible by 8" unless (nbits % 8).zero?
int_class.module_eval <<-END
def assign(val)
#{create_clamp_code(nbits, signed)}
super(val)
end
def do_num_bytes
#{nbits / 8}
end
#---------------
private
def sensible_default
0
end
def value_to_binary_string(val)
#{create_clamp_code(nbits, signed)}
#{create_to_binary_s_code(nbits, endian, signed)}
end
def read_and_return_value(io)
#{create_read_code(nbits, endian, signed)}
end
END
end
#-------------
private
def create_clamp_code(nbits, signed)
if signed == :signed
max = "(1 << (#{nbits} - 1)) - 1"
min = "-((#{max}) + 1)"
else
max = "(1 << #{nbits}) - 1"
min = "0"
end
"val = val.clamp(#{min}, #{max})"
end
def create_read_code(nbits, endian, signed)
read_str = create_raw_read_code(nbits, endian, signed)
if need_signed_conversion_code?(nbits, signed)
"val = #{read_str} ; #{create_uint2int_code(nbits)}"
else
read_str
end
end
def create_raw_read_code(nbits, endian, signed)
# special case 8bit integers for speed
if nbits == 8
"io.readbytes(1).ord"
else
unpack_str = create_read_unpack_code(nbits, endian, signed)
assemble_str = create_read_assemble_code(nbits, endian)
"(#{unpack_str} ; #{assemble_str})"
end
end
def create_read_unpack_code(nbits, endian, signed)
nbytes = nbits / 8
pack_directive = pack_directive(nbits, endian, signed)
"ints = io.readbytes(#{nbytes}).unpack('#{pack_directive}')"
end
def create_read_assemble_code(nbits, endian)
nwords = nbits / bits_per_word(nbits)
idx = (0...nwords).to_a
idx.reverse! if endian == :big
parts = (0...nwords).collect do |i|
"(ints.at(#{idx[i]}) << #{bits_per_word(nbits) * i})"
end
parts[0] = parts[0].sub(/ << 0\b/, "") # Remove " << 0" for optimisation
parts.join(" + ")
end
def create_to_binary_s_code(nbits, endian, signed)
# special case 8bit integers for speed
return "(val & 0xff).chr" if nbits == 8
pack_directive = pack_directive(nbits, endian, signed)
words = val_as_packed_words(nbits, endian)
pack_str = "[#{words}].pack('#{pack_directive}')"
if need_signed_conversion_code?(nbits, signed)
"#{create_int2uint_code(nbits)} ; #{pack_str}"
else
pack_str
end
end
def val_as_packed_words(nbits, endian)
nwords = nbits / bits_per_word(nbits)
mask = (1 << bits_per_word(nbits)) - 1
vals = (0...nwords).collect { |i| "val >> #{bits_per_word(nbits) * i}" }
vals[0] = vals[0].sub(/ >> 0\b/, "") # Remove " >> 0" for optimisation
vals.reverse! if (endian == :big)
vals = vals.collect { |val| "#{val} & #{mask}" } # TODO: "& mask" is needed to work around jruby bug. Remove this line when fixed.
vals.join(',')
end
def create_int2uint_code(nbits)
"val &= #{(1 << nbits) - 1}"
end
def create_uint2int_code(nbits)
"(val >= #{1 << (nbits - 1)}) ? val - #{1 << nbits} : val"
end
def bits_per_word(nbits)
(nbits % 64).zero? ? 64 :
(nbits % 32).zero? ? 32 :
(nbits % 16).zero? ? 16 :
8
end
def pack_directive(nbits, endian, signed)
nwords = nbits / bits_per_word(nbits)
directives = { 8 => 'C', 16 => 'S', 32 => 'L', 64 => 'Q' }
d = directives[bits_per_word(nbits)]
d += ((endian == :big) ? '>' : '<') unless d == 'C'
if signed == :signed && directives.key?(nbits)
(d * nwords).downcase
else
d * nwords
end
end
def need_signed_conversion_code?(nbits, signed)
signed == :signed && ![64, 32, 16].include?(nbits)
end
end
end
# Unsigned 1 byte integer.
class Uint8 < BinData::BasePrimitive
Int.define_methods(self, 8, :little, :unsigned)
end
# Signed 1 byte integer.
class Int8 < BinData::BasePrimitive
Int.define_methods(self, 8, :little, :signed)
end
# Create classes on demand
module IntFactory
def const_missing(name)
mappings = {
/^Uint(\d+)be$/ => [:big, :unsigned],
/^Uint(\d+)le$/ => [:little, :unsigned],
/^Int(\d+)be$/ => [:big, :signed],
/^Int(\d+)le$/ => [:little, :signed]
}
mappings.each_pair do |regex, args|
if regex =~ name.to_s
nbits = $1.to_i
if nbits > 0 && (nbits % 8).zero?
return Int.define_class(name, nbits, *args)
end
end
end
super
end
end
BinData.extend IntFactory
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/version.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/version.rb | module BinData
VERSION = '2.5.1'
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/struct.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/struct.rb | require 'bindata/base'
require 'bindata/delayed_io'
module BinData
class Base
optional_parameter :onlyif, :byte_align # Used by Struct
end
# A Struct is an ordered collection of named data objects.
#
# require 'bindata'
#
# class Tuple < BinData::Record
# int8 :x
# int8 :y
# int8 :z
# end
#
# obj = BinData::Struct.new(hide: :a,
# fields: [ [:int32le, :a],
# [:int16le, :b],
# [:tuple, :s] ])
# obj.field_names =># [:b, :s]
#
#
# == Parameters
#
# Parameters may be provided at initialisation to control the behaviour of
# an object. These params are:
#
# <tt>:fields</tt>:: An array specifying the fields for this struct.
# Each element of the array is of the form [type, name,
# params]. Type is a symbol representing a registered
# type. Name is the name of this field. Params is an
# optional hash of parameters to pass to this field
# when instantiating it. If name is "" or nil, then
# that field is anonymous and behaves as a hidden field.
# <tt>:hide</tt>:: A list of the names of fields that are to be hidden
# from the outside world. Hidden fields don't appear
# in #snapshot or #field_names but are still accessible
# by name.
# <tt>:endian</tt>:: Either :little or :big. This specifies the default
# endian of any numerics in this struct, or in any
# nested data objects.
# <tt>:search_prefix</tt>:: Allows abbreviated type names. If a type is
# unrecognised, then each prefix is applied until
# a match is found.
#
# == Field Parameters
#
# Fields may have have extra parameters as listed below:
#
# [<tt>:onlyif</tt>] Used to indicate a data object is optional.
# if +false+, this object will not be included in any
# calls to #read, #write, #num_bytes or #snapshot.
# [<tt>:byte_align</tt>] This field's rel_offset must be a multiple of
# <tt>:byte_align</tt>.
class Struct < BinData::Base
arg_processor :struct
mandatory_parameter :fields
optional_parameters :endian, :search_prefix, :hide
# These reserved words may not be used as field names
RESERVED =
Hash[*
(Hash.instance_methods +
%w[alias and begin break case class def defined do else elsif
end ensure false for if in module next nil not or redo
rescue retry return self super then true undef unless until
when while yield] +
%w[array element index value] +
%w[type initial_length read_until] +
%w[fields endian search_prefix hide onlyif byte_align] +
%w[choices selection copy_on_change] +
%w[read_abs_offset struct_params])
.collect(&:to_sym)
.uniq.collect { |key| [key, true] }
.flatten
]
def initialize_shared_instance
fields = get_parameter(:fields)
@field_names = fields.field_names.freeze
extend ByteAlignPlugin if fields.any_field_has_parameter?(:byte_align)
define_field_accessors
super
end
def initialize_instance
@field_objs = []
end
def clear # :nodoc:
@field_objs.each { |f| f.nil? || f.clear }
end
def clear? # :nodoc:
@field_objs.all? { |f| f.nil? || f.clear? }
end
def assign(val)
clear
assign_fields(val)
end
def snapshot
snapshot = Snapshot.new
field_names.each do |name|
obj = find_obj_for_name(name)
snapshot[name] = obj.snapshot if include_obj?(obj)
end
snapshot
end
# Returns a list of the names of all fields accessible through this
# object. +include_hidden+ specifies whether to include hidden names
# in the listing.
def field_names(include_hidden = false)
if include_hidden
@field_names.compact
else
hidden = get_parameter(:hide) || []
@field_names.compact - hidden
end
end
def debug_name_of(child) # :nodoc:
field_name = @field_names[find_index_of(child)]
"#{debug_name}.#{field_name}"
end
def offset_of(child) # :nodoc:
instantiate_all_objs
sum = sum_num_bytes_below_index(find_index_of(child))
child.bit_aligned? ? sum.floor : sum.ceil
end
def do_read(io) # :nodoc:
instantiate_all_objs
@field_objs.each { |f| f.do_read(io) if include_obj_for_io?(f) }
end
def do_write(io) # :nodoc:
instantiate_all_objs
@field_objs.each { |f| f.do_write(io) if include_obj_for_io?(f) }
end
def do_num_bytes # :nodoc:
instantiate_all_objs
sum_num_bytes_for_all_fields
end
def [](key)
find_obj_for_name(key)
end
def []=(key, value)
find_obj_for_name(key)&.assign(value)
end
def key?(key)
@field_names.index(base_field_name(key))
end
# Calls the given block for each field_name-field_obj pair.
#
# Does not include anonymous or hidden fields unless
# +include_all+ is true.
def each_pair(include_all = false)
instantiate_all_objs
pairs = @field_names.zip(@field_objs).select do |name, _obj|
name || include_all
end
if block_given?
pairs.each { |el| yield(el) }
else
pairs.each
end
end
#---------------
private
def define_field_accessors
get_parameter(:fields).each_with_index do |field, i|
name = field.name_as_sym
define_field_accessors_for(name, i) if name
end
end
def define_field_accessors_for(name, index)
define_singleton_method(name) do
instantiate_obj_at(index) if @field_objs[index].nil?
@field_objs[index]
end
define_singleton_method("#{name}=") do |*vals|
instantiate_obj_at(index) if @field_objs[index].nil?
@field_objs[index].assign(*vals)
end
define_singleton_method("#{name}?") do
instantiate_obj_at(index) if @field_objs[index].nil?
include_obj?(@field_objs[index])
end
end
def find_index_of(obj)
@field_objs.index { |el| el.equal?(obj) }
end
def find_obj_for_name(name)
index = @field_names.index(base_field_name(name))
if index
instantiate_obj_at(index)
@field_objs[index]
end
end
def base_field_name(name)
name.to_s.sub(/(=|\?)\z/, "").to_sym
end
def instantiate_all_objs
@field_names.each_index { |i| instantiate_obj_at(i) }
end
def instantiate_obj_at(index)
if @field_objs[index].nil?
field = get_parameter(:fields)[index]
@field_objs[index] = field.instantiate(nil, self)
end
end
def assign_fields(val)
src = as_stringified_hash(val)
@field_names.compact.each do |name|
obj = find_obj_for_name(name)
if obj && src.key?(name)
obj.assign(src[name])
end
end
end
def as_stringified_hash(val)
if BinData::Struct === val
val
elsif val.nil?
{}
else
hash = Snapshot.new
val.each_pair { |k, v| hash[k] = v }
hash
end
end
def sum_num_bytes_for_all_fields
sum_num_bytes_below_index(@field_objs.length)
end
def sum_num_bytes_below_index(index)
(0...index).inject(0) do |sum, i|
obj = @field_objs[i]
if include_obj?(obj)
nbytes = obj.do_num_bytes
(nbytes.is_a?(Integer) ? sum.ceil : sum) + nbytes
else
sum
end
end
end
def include_obj_for_io?(obj)
# Used by #do_read and #do_write, to ensure the stream is passed to
# DelayedIO objects for delayed processing.
include_obj?(obj) || DelayedIO === obj
end
def include_obj?(obj)
!obj.has_parameter?(:onlyif) || obj.eval_parameter(:onlyif)
end
# A hash that can be accessed via attributes.
class Snapshot < ::Hash # :nodoc:
def []=(key, value)
super unless value.nil?
end
def respond_to_missing?(symbol, include_all = false)
key?(symbol) || super
end
def method_missing(symbol, *args)
key?(symbol) ? self[symbol] : super
end
end
# Align fields to a multiple of :byte_align
module ByteAlignPlugin
def do_read(io)
offset = 0
instantiate_all_objs
@field_objs.each do |f|
next unless include_obj?(f)
if align_obj?(f)
nbytes = bytes_to_align(f, offset.ceil)
offset = offset.ceil + nbytes
io.readbytes(nbytes)
end
f.do_read(io)
nbytes = f.do_num_bytes
offset = (nbytes.is_a?(Integer) ? offset.ceil : offset) + nbytes
end
end
def do_write(io)
offset = 0
instantiate_all_objs
@field_objs.each do |f|
next unless include_obj?(f)
if align_obj?(f)
nbytes = bytes_to_align(f, offset.ceil)
offset = offset.ceil + nbytes
io.writebytes("\x00" * nbytes)
end
f.do_write(io)
nbytes = f.do_num_bytes
offset = (nbytes.is_a?(Integer) ? offset.ceil : offset) + nbytes
end
end
def sum_num_bytes_below_index(index)
sum = 0
@field_objs.each_with_index do |obj, i|
next unless include_obj?(obj)
if align_obj?(obj)
sum = sum.ceil + bytes_to_align(obj, sum.ceil)
end
break if i >= index
nbytes = obj.do_num_bytes
sum = (nbytes.is_a?(Integer) ? sum.ceil : sum) + nbytes
end
sum
end
def bytes_to_align(obj, rel_offset)
align = obj.eval_parameter(:byte_align)
(align - (rel_offset % align)) % align
end
def align_obj?(obj)
obj.has_parameter?(:byte_align)
end
end
end
class StructArgProcessor < BaseArgProcessor
def sanitize_parameters!(obj_class, params)
sanitize_endian(params)
sanitize_search_prefix(params)
sanitize_fields(obj_class, params)
sanitize_hide(params)
end
#-------------
private
def sanitize_endian(params)
params.sanitize_endian(:endian)
end
def sanitize_search_prefix(params)
params.sanitize(:search_prefix) do |sprefix|
search_prefix = Array(sprefix).collect do |prefix|
prefix.to_s.chomp("_")
end
search_prefix - [""]
end
end
def sanitize_fields(obj_class, params)
params.sanitize_fields(:fields) do |fields, sanitized_fields|
fields.each do |ftype, fname, fparams|
sanitized_fields.add_field(ftype, fname, fparams)
end
field_names = sanitized_field_names(sanitized_fields)
ensure_field_names_are_valid(obj_class, field_names)
end
end
def sanitize_hide(params)
params.sanitize(:hide) do |hidden|
field_names = sanitized_field_names(params[:fields])
hfield_names = hidden_field_names(hidden)
hfield_names & field_names
end
end
def sanitized_field_names(sanitized_fields)
sanitized_fields.field_names.compact
end
def hidden_field_names(hidden)
(hidden || []).collect(&:to_sym)
end
def ensure_field_names_are_valid(obj_class, field_names)
reserved_names = BinData::Struct::RESERVED
field_names.each do |name|
if obj_class.method_defined?(name)
raise NameError.new("Rename field '#{name}' in #{obj_class}, " \
"as it shadows an existing method.", name)
end
if reserved_names.include?(name)
raise NameError.new("Rename field '#{name}' in #{obj_class}, " \
"as it is a reserved name.", name)
end
if field_names.count(name) != 1
raise NameError.new("field '#{name}' in #{obj_class}, " \
"is defined multiple times.", name)
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/bits.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/bits.rb | require 'thread'
require 'bindata/base_primitive'
module BinData
# Defines a number of classes that contain a bit based integer.
# The integer is defined by endian and number of bits.
module BitField # :nodoc: all
@@mutex = Mutex.new
class << self
def define_class(name, nbits, endian, signed = :unsigned)
@@mutex.synchronize do
unless BinData.const_defined?(name)
new_class = Class.new(BinData::BasePrimitive)
BitField.define_methods(new_class, nbits, endian.to_sym, signed.to_sym)
RegisteredClasses.register(name, new_class)
BinData.const_set(name, new_class)
end
end
BinData.const_get(name)
end
def define_methods(bit_class, nbits, endian, signed)
bit_class.module_eval <<-END
#{create_params_code(nbits)}
def assign(val)
#{create_nbits_code(nbits)}
#{create_clamp_code(nbits, signed)}
super(val)
end
def do_write(io)
#{create_nbits_code(nbits)}
val = _value
#{create_int2uint_code(nbits, signed)}
io.writebits(val, #{nbits}, :#{endian})
end
def do_num_bytes
#{create_nbits_code(nbits)}
#{create_do_num_bytes_code(nbits)}
end
def bit_aligned?
true
end
#---------------
private
def read_and_return_value(io)
#{create_nbits_code(nbits)}
val = io.readbits(#{nbits}, :#{endian})
#{create_uint2int_code(nbits, signed)}
val
end
def sensible_default
0
end
END
end
def create_params_code(nbits)
if nbits == :nbits
"mandatory_parameter :nbits"
else
""
end
end
def create_nbits_code(nbits)
if nbits == :nbits
"nbits = eval_parameter(:nbits)"
else
""
end
end
def create_do_num_bytes_code(nbits)
if nbits == :nbits
"nbits / 8.0"
else
nbits / 8.0
end
end
def create_clamp_code(nbits, signed)
if nbits == :nbits
create_dynamic_clamp_code(signed)
else
create_fixed_clamp_code(nbits, signed)
end
end
def create_dynamic_clamp_code(signed)
if signed == :signed
max = "(1 << (nbits - 1)) - 1"
min = "-((#{max}) + 1)"
else
max = "(1 << nbits) - 1"
min = "0"
end
"val = val.clamp(#{min}, #{max})"
end
def create_fixed_clamp_code(nbits, signed)
if nbits == 1 && signed == :signed
raise "signed bitfield must have more than one bit"
end
if signed == :signed
max = "(1 << (#{nbits} - 1)) - 1"
min = "-((#{max}) + 1)"
else
min = "0"
max = "(1 << #{nbits}) - 1"
end
clamp = "(val = val.clamp(#{min}, #{max}))"
if nbits == 1
# allow single bits to be used as booleans
clamp = "(val == true) ? 1 : (not val) ? 0 : #{clamp}"
end
"val = #{clamp}"
end
def create_int2uint_code(nbits, signed)
if signed != :signed
""
elsif nbits == :nbits
"val &= (1 << nbits) - 1"
else
"val &= #{(1 << nbits) - 1}"
end
end
def create_uint2int_code(nbits, signed)
if signed != :signed
""
elsif nbits == :nbits
"val -= (1 << nbits) if (val >= (1 << (nbits - 1)))"
else
"val -= #{1 << nbits} if (val >= #{1 << (nbits - 1)})"
end
end
end
end
# Create classes for dynamic bitfields
{
'Bit' => :big,
'BitLe' => :little,
'Sbit' => [:big, :signed],
'SbitLe' => [:little, :signed]
}.each_pair { |name, args| BitField.define_class(name, :nbits, *args) }
# Create classes on demand
module BitFieldFactory
def const_missing(name)
mappings = {
/^Bit(\d+)$/ => :big,
/^Bit(\d+)le$/ => :little,
/^Sbit(\d+)$/ => [:big, :signed],
/^Sbit(\d+)le$/ => [:little, :signed]
}
mappings.each_pair do |regex, args|
if regex =~ name.to_s
nbits = $1.to_i
return BitField.define_class(name, nbits, *args)
end
end
super(name)
end
end
BinData.extend BitFieldFactory
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/count_bytes_remaining.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/count_bytes_remaining.rb | require 'bindata/base_primitive'
module BinData
# Counts the number of bytes remaining in the input stream from the current
# position to the end of the stream. This only makes sense for seekable
# streams.
#
# require 'bindata'
#
# class A < BinData::Record
# count_bytes_remaining :bytes_remaining
# string :all_data, read_length: :bytes_remaining
# end
#
# obj = A.read("abcdefghij")
# obj.all_data #=> "abcdefghij"
#
class CountBytesRemaining < BinData::BasePrimitive
#---------------
private
def value_to_binary_string(val)
""
end
def read_and_return_value(io)
io.num_bytes_remaining
end
def sensible_default
0
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/section.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/section.rb | require 'bindata/base'
require 'bindata/dsl'
module BinData
# A Section is a layer on top of a stream that transforms the underlying
# data. This allows BinData to process a stream that has multiple
# encodings. e.g. Some data data is compressed or encrypted.
#
# require 'bindata'
#
# class XorTransform < BinData::IO::Transform
# def initialize(xor)
# super()
# @xor = xor
# end
#
# def read(n)
# chain_read(n).bytes.map { |byte| (byte ^ @xor).chr }.join
# end
#
# def write(data)
# chain_write(data.bytes.map { |byte| (byte ^ @xor).chr }.join)
# end
# end
#
# obj = BinData::Section.new(transform: -> { XorTransform.new(0xff) },
# type: [:string, read_length: 5])
#
# obj.read("\x97\x9A\x93\x93\x90") #=> "hello"
#
#
# == Parameters
#
# Parameters may be provided at initialisation to control the behaviour of
# an object. These params are:
#
# <tt>:transform</tt>:: A callable that returns a new BinData::IO::Transform.
# <tt>:type</tt>:: The single type inside the buffer. Use a struct if
# multiple fields are required.
class Section < BinData::Base
extend DSLMixin
dsl_parser :section
arg_processor :section
mandatory_parameters :transform, :type
def initialize_instance
@type = get_parameter(:type).instantiate(nil, self)
end
def clear?
@type.clear?
end
def assign(val)
@type.assign(val)
end
def snapshot
@type.snapshot
end
def respond_to_missing?(symbol, include_all = false) # :nodoc:
@type.respond_to?(symbol, include_all) || super
end
def method_missing(symbol, *args, &block) # :nodoc:
@type.__send__(symbol, *args, &block)
end
def do_read(io) # :nodoc:
io.transform(eval_parameter(:transform)) do |transformed_io, _raw_io|
@type.do_read(transformed_io)
end
end
def do_write(io) # :nodoc:
io.transform(eval_parameter(:transform)) do |transformed_io, _raw_io|
@type.do_write(transformed_io)
end
end
def do_num_bytes # :nodoc:
to_binary_s.size
end
end
class SectionArgProcessor < BaseArgProcessor
include MultiFieldArgSeparator
def sanitize_parameters!(obj_class, params)
params.merge!(obj_class.dsl_params)
params.sanitize_object_prototype(:type)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/array.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/array.rb | require 'bindata/base'
require 'bindata/dsl'
module BinData
# An Array is a list of data objects of the same type.
#
# require 'bindata'
#
# data = "\x03\x04\x05\x06\x07\x08\x09"
#
# obj = BinData::Array.new(type: :int8, initial_length: 6)
# obj.read(data) #=> [3, 4, 5, 6, 7, 8]
#
# obj = BinData::Array.new(type: :int8,
# read_until: -> { index == 1 })
# obj.read(data) #=> [3, 4]
#
# obj = BinData::Array.new(type: :int8,
# read_until: -> { element >= 6 })
# obj.read(data) #=> [3, 4, 5, 6]
#
# obj = BinData::Array.new(type: :int8,
# read_until: -> { array[index] + array[index - 1] == 13 })
# obj.read(data) #=> [3, 4, 5, 6, 7]
#
# obj = BinData::Array.new(type: :int8, read_until: :eof)
# obj.read(data) #=> [3, 4, 5, 6, 7, 8, 9]
#
# == Parameters
#
# Parameters may be provided at initialisation to control the behaviour of
# an object. These params are:
#
# <tt>:type</tt>:: The symbol representing the data type of the
# array elements. If the type is to have params
# passed to it, then it should be provided as
# <tt>[type_symbol, hash_params]</tt>.
# <tt>:initial_length</tt>:: The initial length of the array.
# <tt>:read_until</tt>:: While reading, elements are read until this
# condition is true. This is typically used to
# read an array until a sentinel value is found.
# The variables +index+, +element+ and +array+
# are made available to any lambda assigned to
# this parameter. If the value of this parameter
# is the symbol :eof, then the array will read
# as much data from the stream as possible.
#
# Each data object in an array has the variable +index+ made available
# to any lambda evaluated as a parameter of that data object.
class Array < BinData::Base
extend DSLMixin
include Enumerable
dsl_parser :array
arg_processor :array
mandatory_parameter :type
optional_parameters :initial_length, :read_until
mutually_exclusive_parameters :initial_length, :read_until
def initialize_shared_instance
@element_prototype = get_parameter(:type)
if get_parameter(:read_until) == :eof
extend ReadUntilEOFPlugin
elsif has_parameter?(:read_until)
extend ReadUntilPlugin
elsif has_parameter?(:initial_length)
extend InitialLengthPlugin
end
super
end
def initialize_instance
@elements = nil
end
def clear?
@elements.nil? || elements.all?(&:clear?)
end
def assign(array)
return if self.equal?(array) # prevent self assignment
raise ArgumentError, "can't set a nil value for #{debug_name}" if array.nil?
@elements = []
concat(array)
end
def snapshot
elements.collect(&:snapshot)
end
def find_index(obj)
elements.index(obj)
end
alias index find_index
# Returns the first index of +obj+ in self.
#
# Uses equal? for the comparator.
def find_index_of(obj)
elements.index { |el| el.equal?(obj) }
end
def push(*args)
insert(-1, *args)
self
end
alias << push
def unshift(*args)
insert(0, *args)
self
end
def concat(array)
insert(-1, *array.to_ary)
self
end
def insert(index, *objs)
extend_array(index - 1)
abs_index = (index >= 0) ? index : index + 1 + length
# insert elements before...
new_elements = objs.map { new_element }
elements.insert(index, *new_elements)
# ...assigning values
objs.each_with_index do |obj, i|
self[abs_index + i] = obj
end
self
end
# Returns the element at +index+.
def [](arg1, arg2 = nil)
if arg1.respond_to?(:to_int) && arg2.nil?
slice_index(arg1.to_int)
elsif arg1.respond_to?(:to_int) && arg2.respond_to?(:to_int)
slice_start_length(arg1.to_int, arg2.to_int)
elsif arg1.is_a?(Range) && arg2.nil?
slice_range(arg1)
else
raise TypeError, "can't convert #{arg1} into Integer" unless arg1.respond_to?(:to_int)
raise TypeError, "can't convert #{arg2} into Integer" unless arg2.respond_to?(:to_int)
end
end
alias slice []
def slice_index(index)
extend_array(index)
at(index)
end
def slice_start_length(start, length)
elements[start, length]
end
def slice_range(range)
elements[range]
end
private :slice_index, :slice_start_length, :slice_range
# Returns the element at +index+. Unlike +slice+, if +index+ is out
# of range the array will not be automatically extended.
def at(index)
elements[index]
end
# Sets the element at +index+.
def []=(index, value)
extend_array(index)
elements[index].assign(value)
end
# Returns the first element, or the first +n+ elements, of the array.
# If the array is empty, the first form returns nil, and the second
# form returns an empty array.
def first(n = nil)
if n.nil? && empty?
# explicitly return nil as arrays grow automatically
nil
elsif n.nil?
self[0]
else
self[0, n]
end
end
# Returns the last element, or the last +n+ elements, of the array.
# If the array is empty, the first form returns nil, and the second
# form returns an empty array.
def last(n = nil)
if n.nil?
self[-1]
else
n = length if n > length
self[-n, n]
end
end
def length
elements.length
end
alias size length
def empty?
length.zero?
end
# Allow this object to be used in array context.
def to_ary
collect { |el| el }
end
def each
elements.each { |el| yield el }
end
def debug_name_of(child) # :nodoc:
index = find_index_of(child)
"#{debug_name}[#{index}]"
end
def offset_of(child) # :nodoc:
index = find_index_of(child)
sum = sum_num_bytes_below_index(index)
child.bit_aligned? ? sum.floor : sum.ceil
end
def do_write(io) # :nodoc:
elements.each { |el| el.do_write(io) }
end
def do_num_bytes # :nodoc:
sum_num_bytes_for_all_elements
end
#---------------
private
def extend_array(max_index)
max_length = max_index + 1
while elements.length < max_length
append_new_element
end
end
def elements
@elements ||= []
end
def append_new_element
element = new_element
elements << element
element
end
def new_element
@element_prototype.instantiate(nil, self)
end
def sum_num_bytes_for_all_elements
sum_num_bytes_below_index(length)
end
def sum_num_bytes_below_index(index)
(0...index).inject(0) do |sum, i|
nbytes = elements[i].do_num_bytes
if nbytes.is_a?(Integer)
sum.ceil + nbytes
else
sum + nbytes
end
end
end
# Logic for the :read_until parameter
module ReadUntilPlugin
def do_read(io)
loop do
element = append_new_element
element.do_read(io)
variables = { index: self.length - 1, element: self.last, array: self }
break if eval_parameter(:read_until, variables)
end
end
end
# Logic for the read_until: :eof parameter
module ReadUntilEOFPlugin
def do_read(io)
loop do
element = append_new_element
begin
element.do_read(io)
rescue EOFError, IOError
elements.pop
break
end
end
end
end
# Logic for the :initial_length parameter
module InitialLengthPlugin
def do_read(io)
elements.each { |el| el.do_read(io) }
end
def elements
if @elements.nil?
@elements = []
eval_parameter(:initial_length).times do
@elements << new_element
end
end
@elements
end
end
end
class ArrayArgProcessor < BaseArgProcessor
def sanitize_parameters!(obj_class, params) # :nodoc:
# ensure one of :initial_length and :read_until exists
unless params.has_at_least_one_of?(:initial_length, :read_until)
params[:initial_length] = 0
end
params.warn_replacement_parameter(:length, :initial_length)
params.warn_replacement_parameter(:read_length, :initial_length)
params.must_be_integer(:initial_length)
params.merge!(obj_class.dsl_params)
params.sanitize_object_prototype(:type)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/rest.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/rest.rb | require 'bindata/base_primitive'
module BinData
# Rest will consume the input stream from the current position to the end of
# the stream. This will mainly be useful for debugging and developing.
#
# require 'bindata'
#
# class A < BinData::Record
# string :a, read_length: 5
# rest :rest
# end
#
# obj = A.read("abcdefghij")
# obj.a #=> "abcde"
# obj.rest #=" "fghij"
#
class Rest < BinData::BasePrimitive
#---------------
private
def value_to_binary_string(val)
val
end
def read_and_return_value(io)
io.read_all_bytes
end
def sensible_default
""
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/delayed_io.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/delayed_io.rb | require 'bindata/base'
require 'bindata/dsl'
module BinData
# BinData declarations are evaluated in a single pass.
# However, some binary formats require multi pass processing. A common
# reason is seeking backwards in the input stream.
#
# DelayedIO supports multi pass processing. It works by ignoring the normal
# #read or #write calls. The user must explicitly call the #read_now! or
# #write_now! methods to process an additional pass. This additional pass
# must specify the abs_offset of the I/O operation.
#
# require 'bindata'
#
# obj = BinData::DelayedIO.new(read_abs_offset: 3, type: :uint16be)
# obj.read("\x00\x00\x00\x11\x12")
# obj #=> 0
#
# obj.read_now!
# obj #=> 0x1112
#
# - OR -
#
# obj.read("\x00\x00\x00\x11\x12") { obj.read_now! } #=> 0x1122
#
# obj.to_binary_s { obj.write_now! } #=> "\x00\x00\x00\x11\x12"
#
# You can use the +auto_call_delayed_io+ keyword to cause #read and #write to
# automatically perform the extra passes.
#
# class ReversePascalString < BinData::Record
# auto_call_delayed_io
#
# delayed_io :str, read_abs_offset: 0 do
# string read_length: :len
# end
# count_bytes_remaining :total_size
# skip to_abs_offset: -> { total_size - 1 }
# uint8 :len, value: -> { str.length }
# end
#
# s = ReversePascalString.read("hello\x05")
# s.to_binary_s #=> "hello\x05"
#
#
# == Parameters
#
# Parameters may be provided at initialisation to control the behaviour of
# an object. These params are:
#
# <tt>:read_abs_offset</tt>:: The abs_offset to start reading at.
# <tt>:type</tt>:: The single type inside the delayed io. Use
# a struct if multiple fields are required.
class DelayedIO < BinData::Base
extend DSLMixin
dsl_parser :delayed_io
arg_processor :delayed_io
mandatory_parameters :read_abs_offset, :type
def initialize_instance
@type = get_parameter(:type).instantiate(nil, self)
@abs_offset = nil
@read_io = nil
@write_io = nil
end
def clear?
@type.clear?
end
def assign(val)
@type.assign(val)
end
def snapshot
@type.snapshot
end
def num_bytes
@type.num_bytes
end
def respond_to_missing?(symbol, include_all = false) # :nodoc:
@type.respond_to?(symbol, include_all) || super
end
def method_missing(symbol, *args, &block) # :nodoc:
@type.__send__(symbol, *args, &block)
end
def abs_offset
@abs_offset || eval_parameter(:read_abs_offset)
end
# Sets the +abs_offset+ to use when writing this object.
def abs_offset=(offset)
@abs_offset = offset
end
def rel_offset
abs_offset
end
def do_read(io) # :nodoc:
@read_io = io
end
def do_write(io) # :nodoc:
@write_io = io
end
def do_num_bytes # :nodoc:
0
end
def include_obj?
!has_parameter?(:onlyif) || eval_parameter(:onlyif)
end
# DelayedIO objects aren't read when #read is called.
# The reading is delayed until this method is called.
def read_now!
return unless include_obj?
raise IOError, "read from where?" unless @read_io
@read_io.seek_to_abs_offset(abs_offset)
start_read do
@type.do_read(@read_io)
end
end
# DelayedIO objects aren't written when #write is called.
# The writing is delayed until this method is called.
def write_now!
return unless include_obj?
raise IOError, "write to where?" unless @write_io
@write_io.seek_to_abs_offset(abs_offset)
@type.do_write(@write_io)
end
end
class DelayedIoArgProcessor < BaseArgProcessor
include MultiFieldArgSeparator
def sanitize_parameters!(obj_class, params)
params.merge!(obj_class.dsl_params)
params.must_be_integer(:read_abs_offset)
params.sanitize_object_prototype(:type)
end
end
class Base
# Add +auto_call_delayed_io+ keyword to BinData::Base.
class << self
# The +auto_call_delayed_io+ keyword sets a data object tree to perform
# multi pass I/O automatically.
def auto_call_delayed_io
include AutoCallDelayedIO
return if DelayedIO.method_defined? :initialize_instance_without_record_io
DelayedIO.send(:alias_method, :initialize_instance_without_record_io, :initialize_instance)
DelayedIO.send(:define_method, :initialize_instance) do
if @parent && !defined? @delayed_io_recorded
@delayed_io_recorded = true
list = top_level_get(:delayed_ios)
list << self if list
end
initialize_instance_without_record_io
end
end
end
module AutoCallDelayedIO
def initialize_shared_instance
top_level_set(:delayed_ios, [])
super
end
def read(io)
super(io) { top_level_get(:delayed_ios).each(&:read_now!) }
end
def write(io, *_)
super(io) { top_level_get(:delayed_ios).each(&:write_now!) }
end
def num_bytes
to_binary_s.size
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/float.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/float.rb | require 'bindata/base_primitive'
module BinData
# Defines a number of classes that contain a floating point number.
# The float is defined by precision and endian.
module FloatingPoint # :nodoc: all
class << self
PRECISION = {
single: 4,
double: 8,
}
PACK_CODE = {
[:single, :little] => 'e',
[:single, :big] => 'g',
[:double, :little] => 'E',
[:double, :big] => 'G'
}
def define_methods(float_class, precision, endian)
float_class.module_eval <<-END
def do_num_bytes
#{create_num_bytes_code(precision)}
end
#---------------
private
def sensible_default
0.0
end
def value_to_binary_string(val)
#{create_to_binary_s_code(precision, endian)}
end
def read_and_return_value(io)
#{create_read_code(precision, endian)}
end
END
end
def create_num_bytes_code(precision)
PRECISION[precision]
end
def create_read_code(precision, endian)
nbytes = PRECISION[precision]
unpack = PACK_CODE[[precision, endian]]
"io.readbytes(#{nbytes}).unpack1('#{unpack}')"
end
def create_to_binary_s_code(precision, endian)
pack = PACK_CODE[[precision, endian]]
"[val].pack('#{pack}')"
end
end
end
# Single precision floating point number in little endian format
class FloatLe < BinData::BasePrimitive
FloatingPoint.define_methods(self, :single, :little)
end
# Single precision floating point number in big endian format
class FloatBe < BinData::BasePrimitive
FloatingPoint.define_methods(self, :single, :big)
end
# Double precision floating point number in little endian format
class DoubleLe < BinData::BasePrimitive
FloatingPoint.define_methods(self, :double, :little)
end
# Double precision floating point number in big endian format
class DoubleBe < BinData::BasePrimitive
FloatingPoint.define_methods(self, :double, :big)
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/registry.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/registry.rb | module BinData
# Raised when #lookup fails.
class UnRegisteredTypeError < StandardError; end
# This registry contains a register of name -> class mappings.
#
# Numerics (integers and floating point numbers) have an endian property as
# part of their name (e.g. int32be, float_le).
#
# Classes can be looked up based on their full name or an abbreviated +name+
# with +hints+.
#
# There are two hints supported, :endian and :search_prefix.
#
# #lookup("int32", { endian: :big }) will return Int32Be.
#
# #lookup("my_type", { search_prefix: :ns }) will return NsMyType.
#
# Names are stored in under_score_style, not camelCase.
class Registry
def initialize
@registry = {}
end
def register(name, class_to_register)
return if name.nil? || class_to_register.nil?
formatted_name = underscore_name(name)
warn_if_name_is_already_registered(formatted_name, class_to_register)
@registry[formatted_name] = class_to_register
end
def unregister(name)
@registry.delete(underscore_name(name))
end
def lookup(name, hints = {})
search_names(name, hints).each do |search|
register_dynamic_class(search)
if @registry.has_key?(search)
return @registry[search]
end
end
# give the user a hint if the endian keyword is missing
search_names(name, hints.merge(endian: :big)).each do |search|
register_dynamic_class(search)
if @registry.has_key?(search)
raise(UnRegisteredTypeError, "#{name}, do you need to specify endian?")
end
end
raise(UnRegisteredTypeError, name)
end
# Convert CamelCase +name+ to underscore style.
def underscore_name(name)
name
.to_s
.sub(/.*::/, "")
.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
.gsub(/([a-z\d])([A-Z])/, '\1_\2')
.tr('-', '_')
.downcase
end
#---------------
private
def search_names(name, hints)
base = underscore_name(name)
searches = []
search_prefix = [""] + Array(hints[:search_prefix])
search_prefix.each do |prefix|
nwp = name_with_prefix(base, prefix)
nwe = name_with_endian(nwp, hints[:endian])
searches << nwp
searches << nwe if nwe
end
searches
end
def name_with_prefix(name, prefix)
prefix = prefix.to_s.chomp('_')
if prefix == ""
name
else
"#{prefix}_#{name}"
end
end
def name_with_endian(name, endian)
return nil if endian.nil?
suffix = (endian == :little) ? 'le' : 'be'
if /^u?int\d+$/.match?(name)
name + suffix
else
name + '_' + suffix
end
end
def register_dynamic_class(name)
if /^u?int\d+(le|be)$/.match?(name) || /^s?bit\d+(le)?$/.match?(name)
class_name = name.gsub(/(?:^|_)(.)/) { $1.upcase }
begin
# call const_get for side effect of creating class
BinData.const_get(class_name)
rescue NameError
end
end
end
def warn_if_name_is_already_registered(name, class_to_register)
prev_class = @registry[name]
if prev_class && prev_class != class_to_register
Kernel.warn "warning: replacing registered class #{prev_class} " \
"with #{class_to_register}"
end
end
end
# A singleton registry of all registered classes.
RegisteredClasses = Registry.new
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/warnings.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/warnings.rb | module BinData
class Base
# Don't override initialize. If you are defining a new kind of datatype
# (list, array, choice etc) then put your initialization code in
# #initialize_instance. BinData objects might be initialized as prototypes
# and your initialization code may not be called.
#
# If you're subclassing BinData::Record, you are definitely doing the wrong
# thing. Read the documentation on how to use BinData.
# http://github.com/dmendel/bindata/wiki/Records
alias_method :initialize_without_warning, :initialize
def initialize_with_warning(*args)
owner = method(:initialize).owner
if owner != BinData::Base
msg = "Don't override #initialize on #{owner}."
if %w[BinData::Base BinData::BasePrimitive].include? self.class.superclass.name
msg += "\nrename #initialize to #initialize_instance."
end
fail msg
end
initialize_without_warning(*args)
end
alias initialize initialize_with_warning
def initialize_instance(*args)
unless args.empty?
fail "#{caller[0]} remove the call to super in #initialize_instance"
end
end
end
class Struct
# has_key? is deprecated
alias has_key? key?
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/uint8_array.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/uint8_array.rb | require 'bindata/base_primitive'
module BinData
# Uint8Array is a specialised type of array that only contains
# bytes (Uint8). It is a faster and more memory efficient version
# of `BinData::Array.new(:type => :uint8)`.
#
# require 'bindata'
#
# obj = BinData::Uint8Array.new(initial_length: 5)
# obj.read("abcdefg") #=> [97, 98, 99, 100, 101]
# obj[2] #=> 99
# obj.collect { |x| x.chr }.join #=> "abcde"
#
# == Parameters
#
# Parameters may be provided at initialisation to control the behaviour of
# an object. These params are:
#
# <tt>:initial_length</tt>:: The initial length of the array.
# <tt>:read_until</tt>:: May only have a value of `:eof`. This parameter
# instructs the array to read as much data from
# the stream as possible.
class Uint8Array < BinData::BasePrimitive
optional_parameters :initial_length, :read_until
mutually_exclusive_parameters :initial_length, :read_until
arg_processor :uint8_array
#---------------
private
def value_to_binary_string(val)
val.pack("C*")
end
def read_and_return_value(io)
if has_parameter?(:initial_length)
data = io.readbytes(eval_parameter(:initial_length))
else
data = io.read_all_bytes
end
data.unpack("C*")
end
def sensible_default
[]
end
end
class Uint8ArrayArgProcessor < BaseArgProcessor
def sanitize_parameters!(obj_class, params) # :nodoc:
# ensure one of :initial_length and :read_until exists
unless params.has_at_least_one_of?(:initial_length, :read_until)
params[:initial_length] = 0
end
msg = "Parameter :read_until must have a value of :eof"
params.sanitize(:read_until) { |val| raise ArgumentError, msg unless val == :eof }
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/lazy.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/lazy.rb | module BinData
# A LazyEvaluator is bound to a data object. The evaluator will evaluate
# lambdas in the context of this data object. These lambdas
# are those that are passed to data objects as parameters, e.g.:
#
# BinData::String.new(value: -> { %w(a test message).join(" ") })
#
# As a shortcut, :foo is the equivalent of lambda { foo }.
#
# When evaluating lambdas, unknown methods are resolved in the context of the
# parent of the bound data object. Resolution is attempted firstly as keys
# in #parameters, and secondly as methods in this parent. This
# resolution propagates up the chain of parent data objects.
#
# An evaluation will recurse until it returns a result that is not
# a lambda or a symbol.
#
# This resolution process makes the lambda easier to read as we just write
# <tt>field</tt> instead of <tt>obj.field</tt>.
class LazyEvaluator
# Creates a new evaluator. All lazy evaluation is performed in the
# context of +obj+.
def initialize(obj)
@obj = obj
end
def lazy_eval(val, overrides = nil)
@overrides = overrides if overrides
if val.is_a? Symbol
__send__(val)
elsif callable?(val)
instance_exec(&val)
else
val
end
end
# Returns a LazyEvaluator for the parent of this data object.
def parent
if @obj.parent
@obj.parent.lazy_evaluator
else
nil
end
end
# Returns the index of this data object inside it's nearest container
# array.
def index
return @overrides[:index] if defined?(@overrides) && @overrides.key?(:index)
child = @obj
parent = @obj.parent
while parent
if parent.respond_to?(:find_index_of)
return parent.find_index_of(child)
end
child = parent
parent = parent.parent
end
raise NoMethodError, "no index found"
end
def method_missing(symbol, *args)
return @overrides[symbol] if defined?(@overrides) && @overrides.key?(symbol)
if @obj.parent
eval_symbol_in_parent_context(symbol, args)
else
super
end
end
#---------------
private
def eval_symbol_in_parent_context(symbol, args)
result = resolve_symbol_in_parent_context(symbol, args)
recursively_eval(result, args)
end
def resolve_symbol_in_parent_context(symbol, args)
obj_parent = @obj.parent
if obj_parent.has_parameter?(symbol)
obj_parent.get_parameter(symbol)
elsif obj_parent.safe_respond_to?(symbol, true)
obj_parent.__send__(symbol, *args)
else
symbol
end
end
def recursively_eval(val, args)
if val.is_a?(Symbol)
parent.__send__(val, *args)
elsif callable?(val)
parent.instance_exec(&val)
else
val
end
end
def callable?(obj)
Proc === obj || Method === obj || UnboundMethod === obj
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/alignment.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/alignment.rb | require 'bindata/base_primitive'
module BinData
# Resets the stream alignment to the next byte. This is
# only useful when using bit-based primitives.
#
# class MyRec < BinData::Record
# bit4 :a
# resume_byte_alignment
# bit4 :b
# end
#
# MyRec.read("\x12\x34") #=> {"a" => 1, "b" => 3}
#
class ResumeByteAlignment < BinData::Base
def clear?; true; end
def assign(val); end
def snapshot; nil; end
def do_num_bytes; 0; end
def do_read(io)
io.readbytes(0)
end
def do_write(io)
io.writebytes("")
end
end
# A monkey patch to force byte-aligned primitives to
# become bit-aligned. This allows them to be used at
# non byte based boundaries.
#
# class BitString < BinData::String
# bit_aligned
# end
#
# class MyRecord < BinData::Record
# bit4 :preamble
# bit_string :str, length: 2
# end
#
module BitAligned
class BitAlignedIO
def initialize(io)
@io = io
end
def binary_string(str)
str.to_s.dup.force_encoding(Encoding::BINARY)
end
def readbytes(n)
n.times.inject(binary_string("")) do |bytes, _|
bytes + @io.readbits(8, :big).chr
end
end
def writebytes(str)
str.each_byte { |v| @io.writebits(v, 8, :big) }
end
end
def bit_aligned?
true
end
def do_read(io)
super(BitAlignedIO.new(io))
end
def do_num_bytes
super.to_f
end
def do_write(io)
super(BitAlignedIO.new(io))
end
end
def BasePrimitive.bit_aligned
include BitAligned
end
def Primitive.bit_aligned
fail "'bit_aligned' is not supported for BinData::Primitives"
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/dsl.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/bindata-2.5.1/lib/bindata/dsl.rb | module BinData
# Extracts args for Records and Buffers.
#
# Foo.new(bar: "baz) is ambiguous as to whether :bar is a value or parameter.
#
# BaseArgExtractor always assumes :bar is parameter. This extractor correctly
# identifies it as value or parameter.
module MultiFieldArgSeparator
def separate_args(obj_class, obj_args)
value, parameters, parent = super(obj_class, obj_args)
if parameters_is_value?(obj_class, value, parameters)
value = parameters
parameters = {}
end
[value, parameters, parent]
end
def parameters_is_value?(obj_class, value, parameters)
if value.nil? && !parameters.empty?
field_names_in_parameters?(obj_class, parameters)
else
false
end
end
def field_names_in_parameters?(obj_class, parameters)
field_names = obj_class.fields.field_names
param_keys = parameters.keys
!(field_names & param_keys).empty?
end
end
# BinData classes that are part of the DSL must be extended by this.
module DSLMixin
def dsl_parser(parser_type = nil)
@dsl_parser ||= begin
parser_type ||= superclass.dsl_parser.parser_type
DSLParser.new(self, parser_type)
end
end
def method_missing(symbol, *args, &block) # :nodoc:
dsl_parser.__send__(symbol, *args, &block)
end
# Assert object is not an array or string.
def to_ary; nil; end
def to_str; nil; end
# A DSLParser parses and accumulates field definitions of the form
#
# type name, params
#
# where:
# * +type+ is the under_scored name of a registered type
# * +name+ is the (possible optional) name of the field
# * +params+ is a hash containing any parameters
#
class DSLParser
def initialize(the_class, parser_type)
raise "unknown parser type #{parser_type}" unless parser_abilities[parser_type]
@the_class = the_class
@parser_type = parser_type
@validator = DSLFieldValidator.new(the_class, self)
@endian = nil
end
attr_reader :parser_type
def endian(endian = nil)
if endian
set_endian(endian)
elsif @endian.nil?
set_endian(parent_attribute(:endian))
end
@endian
end
def search_prefix(*args)
@search_prefix ||= parent_attribute(:search_prefix, []).dup
prefix = args.collect(&:to_sym).compact
unless prefix.empty?
if fields?
dsl_raise SyntaxError, "search_prefix must be called before defining fields"
end
@search_prefix = prefix.concat(@search_prefix)
end
@search_prefix
end
def hide(*args)
if option?(:hidden_fields)
@hide ||= parent_attribute(:hide, []).dup
hidden = args.collect(&:to_sym).compact
@hide.concat(hidden)
@hide
end
end
def fields
@fields ||= SanitizedFields.new(hints, parent_fields)
end
def dsl_params
abilities = parser_abilities[@parser_type]
send(abilities.at(0), abilities.at(1))
end
def method_missing(*args, &block)
ensure_hints
parse_and_append_field(*args, &block)
end
#-------------
private
def parser_abilities
@abilities ||= {
struct: [:to_struct_params, :struct, [:multiple_fields, :optional_fieldnames, :hidden_fields]],
array: [:to_object_params, :type, [:multiple_fields, :optional_fieldnames]],
buffer: [:to_object_params, :type, [:multiple_fields, :optional_fieldnames, :hidden_fields]],
choice: [:to_choice_params, :choices, [:multiple_fields, :all_or_none_fieldnames, :fieldnames_are_values]],
delayed_io: [:to_object_params, :type, [:multiple_fields, :optional_fieldnames, :hidden_fields]],
primitive: [:to_struct_params, :struct, [:multiple_fields, :optional_fieldnames]],
section: [:to_object_params, :type, [:multiple_fields, :optional_fieldnames]],
skip: [:to_object_params, :until_valid, [:multiple_fields, :optional_fieldnames]]
}
end
def option?(opt)
parser_abilities[@parser_type].at(2).include?(opt)
end
def ensure_hints
endian
search_prefix
end
def hints
{ endian: endian, search_prefix: search_prefix }
end
def set_endian(endian)
if endian
if fields?
dsl_raise SyntaxError, "endian must be called before defining fields"
end
if !valid_endian?(endian)
dsl_raise ArgumentError, "unknown value for endian '#{endian}'"
end
if endian == :big_and_little
DSLBigAndLittleEndianHandler.handle(@the_class)
end
@endian = endian
end
end
def valid_endian?(endian)
[:big, :little, :big_and_little].include?(endian)
end
def parent_fields
parent_attribute(:fields)
end
def fields?
defined?(@fields) && !@fields.empty?
end
def parse_and_append_field(*args, &block)
parser = DSLFieldParser.new(hints, *args, &block)
begin
@validator.validate_field(parser.name)
append_field(parser.type, parser.name, parser.params)
rescue Exception => e
dsl_raise e.class, e.message
end
end
def append_field(type, name, params)
fields.add_field(type, name, params)
rescue BinData::UnRegisteredTypeError => e
raise TypeError, "unknown type '#{e.message}'"
end
def parent_attribute(attr, default = nil)
parent = @the_class.superclass
parser = parent.respond_to?(:dsl_parser) ? parent.dsl_parser : nil
if parser&.respond_to?(attr)
parser.send(attr)
else
default
end
end
def dsl_raise(exception, msg)
backtrace = caller
backtrace.shift while %r{bindata/dsl.rb}.match?(backtrace.first)
raise exception, "#{msg} in #{@the_class}", backtrace
end
def to_object_params(key)
case fields.length
when 0
{}
when 1
{ key => fields[0].prototype }
else
{ key => [:struct, to_struct_params] }
end
end
def to_choice_params(key)
if fields.empty?
{}
elsif fields.all_field_names_blank?
{ key => fields.collect(&:prototype) }
else
choices = {}
fields.each { |f| choices[f.name] = f.prototype }
{ key => choices }
end
end
def to_struct_params(*_)
result = { fields: fields }
if !endian.nil?
result[:endian] = endian
end
if !search_prefix.empty?
result[:search_prefix] = search_prefix
end
if option?(:hidden_fields) && !hide.empty?
result[:hide] = hide
end
result
end
end
# Handles the :big_and_little endian option.
# This option creates two subclasses, each handling
# :big or :little endian.
class DSLBigAndLittleEndianHandler
class << self
def handle(bnl_class)
make_class_abstract(bnl_class)
create_subclasses_with_endian(bnl_class)
override_new_in_class(bnl_class)
delegate_field_creation(bnl_class)
fixup_subclass_hierarchy(bnl_class)
end
def make_class_abstract(bnl_class)
bnl_class.send(:unregister_self)
end
def create_subclasses_with_endian(bnl_class)
instance_eval "class ::#{bnl_class}Be < ::#{bnl_class}; endian :big; end"
instance_eval "class ::#{bnl_class}Le < ::#{bnl_class}; endian :little; end"
end
def override_new_in_class(bnl_class)
endian_classes = {
big: class_with_endian(bnl_class, :big),
little: class_with_endian(bnl_class, :little)
}
bnl_class.define_singleton_method(:new) do |*args|
if self == bnl_class
_, options, _ = arg_processor.separate_args(self, args)
delegate = endian_classes[options[:endian]]
return delegate.new(*args) if delegate
end
super(*args)
end
end
def delegate_field_creation(bnl_class)
endian_classes = {
big: class_with_endian(bnl_class, :big),
little: class_with_endian(bnl_class, :little)
}
parser = bnl_class.dsl_parser
parser.define_singleton_method(:parse_and_append_field) do |*args, &block|
endian_classes[:big].send(*args, &block)
endian_classes[:little].send(*args, &block)
end
end
def fixup_subclass_hierarchy(bnl_class)
parent = bnl_class.superclass
return if obj_attribute(parent, :endian) != :big_and_little
be_subclass = class_with_endian(bnl_class, :big)
be_parent = class_with_endian(parent, :big)
be_fields = obj_attribute(be_parent, :fields)
le_subclass = class_with_endian(bnl_class, :little)
le_parent = class_with_endian(parent, :little)
le_fields = obj_attribute(le_parent, :fields)
be_subclass.dsl_parser.define_singleton_method(:parent_fields) do
be_fields
end
le_subclass.dsl_parser.define_singleton_method(:parent_fields) do
le_fields
end
end
def class_with_endian(class_name, endian)
hints = {
endian: endian,
search_prefix: class_name.dsl_parser.search_prefix
}
RegisteredClasses.lookup(class_name, hints)
end
def obj_attribute(obj, attr)
obj.dsl_parser.send(attr)
end
end
end
# Extracts the details from a field declaration.
class DSLFieldParser
def initialize(hints, symbol, *args, &block)
@hints = hints
@type = symbol
@name = name_from_field_declaration(args)
@params = params_from_field_declaration(args, &block)
end
attr_reader :type, :name, :params
def name_from_field_declaration(args)
name, _ = args
if name == "" || name.is_a?(Hash)
nil
else
name
end
end
def params_from_field_declaration(args, &block)
params = params_from_args(args)
if block_given?
params.merge(params_from_block(&block))
else
params
end
end
def params_from_args(args)
name, params = args
params = name if name.is_a?(Hash)
params || {}
end
def params_from_block(&block)
bindata_classes = {
array: BinData::Array,
buffer: BinData::Buffer,
choice: BinData::Choice,
delayed_io: BinData::DelayedIO,
section: BinData::Section,
skip: BinData::Skip,
struct: BinData::Struct
}
if bindata_classes.include?(@type)
parser = DSLParser.new(bindata_classes[@type], @type)
parser.endian(@hints[:endian])
parser.search_prefix(*@hints[:search_prefix])
parser.instance_eval(&block)
parser.dsl_params
else
{}
end
end
end
# Validates a field defined in a DSLMixin.
class DSLFieldValidator
def initialize(the_class, parser)
@the_class = the_class
@dsl_parser = parser
end
def validate_field(name)
if must_not_have_a_name_failed?(name)
raise SyntaxError, "field must not have a name"
end
if all_or_none_names_failed?(name)
raise SyntaxError, "fields must either all have names, or none must have names"
end
if must_have_a_name_failed?(name)
raise SyntaxError, "field must have a name"
end
ensure_valid_name(name)
end
def ensure_valid_name(name)
if name && !option?(:fieldnames_are_values)
if malformed_name?(name)
raise SyntaxError, "field '#{name}' is an illegal fieldname"
end
if duplicate_name?(name)
raise SyntaxError, "duplicate field '#{name}'"
end
if name_shadows_method?(name)
raise SyntaxError, "field '#{name}' shadows an existing method"
end
if name_is_reserved?(name)
raise SyntaxError, "field '#{name}' is a reserved name"
end
end
end
def must_not_have_a_name_failed?(name)
option?(:no_fieldnames) && !name.nil?
end
def must_have_a_name_failed?(name)
option?(:mandatory_fieldnames) && name.nil?
end
def all_or_none_names_failed?(name)
if option?(:all_or_none_fieldnames) && !fields.empty?
all_names_blank = fields.all_field_names_blank?
no_names_blank = fields.no_field_names_blank?
(!name.nil? && all_names_blank) || (name.nil? && no_names_blank)
else
false
end
end
def malformed_name?(name)
!/^[a-z_]\w*$/.match?(name.to_s)
end
def duplicate_name?(name)
fields.field_name?(name)
end
def name_shadows_method?(name)
@the_class.method_defined?(name)
end
def name_is_reserved?(name)
BinData::Struct::RESERVED.include?(name.to_sym)
end
def fields
@dsl_parser.fields
end
def option?(opt)
@dsl_parser.send(:option?, opt)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.