steep-kit 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +18 -0
  3. data/LICENSE.md +21 -0
  4. data/README.md +396 -0
  5. data/exe/steep-kit +12 -0
  6. data/lib/steep_kit/alias_skip.rb +41 -0
  7. data/lib/steep_kit/check.rb +62 -0
  8. data/lib/steep_kit/cli.rb +110 -0
  9. data/lib/steep_kit/config.rb +139 -0
  10. data/lib/steep_kit/constant_literal_inference.rb +33 -0
  11. data/lib/steep_kit/constant_table.rb +152 -0
  12. data/lib/steep_kit/conventions.rb +175 -0
  13. data/lib/steep_kit/dynamic_superclasses.rb +26 -0
  14. data/lib/steep_kit/error.rb +9 -0
  15. data/lib/steep_kit/fast.rb +113 -0
  16. data/lib/steep_kit/generate.rb +55 -0
  17. data/lib/steep_kit/lint_constant_access.rb +181 -0
  18. data/lib/steep_kit/lint_inline.rb +177 -0
  19. data/lib/steep_kit/literal_inference.rb +143 -0
  20. data/lib/steep_kit/mixin_inference/installer.rb +153 -0
  21. data/lib/steep_kit/mixin_inference.rb +149 -0
  22. data/lib/steep_kit/output_plan.rb +181 -0
  23. data/lib/steep_kit/passes.rb +282 -0
  24. data/lib/steep_kit/patch_guard.rb +18 -0
  25. data/lib/steep_kit/paths.rb +17 -0
  26. data/lib/steep_kit/project.rb +44 -0
  27. data/lib/steep_kit/project_types.rb +72 -0
  28. data/lib/steep_kit/rbs_builder.rb +141 -0
  29. data/lib/steep_kit/rbs_collection.rb +61 -0
  30. data/lib/steep_kit/rbs_rails_postprocess.rb +98 -0
  31. data/lib/steep_kit/rbs_rails_regen.rb +39 -0
  32. data/lib/steep_kit/rbs_rails_scratch.rb +169 -0
  33. data/lib/steep_kit/rbs_rails_tasks.rb +20 -0
  34. data/lib/steep_kit/runtime.rb +344 -0
  35. data/lib/steep_kit/settings.rb +96 -0
  36. data/lib/steep_kit/signature_index.rb +116 -0
  37. data/lib/steep_kit/signature_kinds.rb +68 -0
  38. data/lib/steep_kit/signature_merger.rb +149 -0
  39. data/lib/steep_kit/signature_only.rb +33 -0
  40. data/lib/steep_kit/source_analysis.rb +227 -0
  41. data/lib/steep_kit/source_cache.rb +92 -0
  42. data/lib/steep_kit/source_files.rb +66 -0
  43. data/lib/steep_kit/source_set.rb +62 -0
  44. data/lib/steep_kit/steep.rb +35 -0
  45. data/lib/steep_kit/type_name_resolver.rb +47 -0
  46. data/lib/steep_kit/value_classes.rb +89 -0
  47. data/lib/steep_kit/version.rb +3 -0
  48. data/lib/steep_kit/watch.rb +64 -0
  49. data/lib/steep_kit/workspace_graph.rb +90 -0
  50. data/lib/steep_kit.rb +31 -0
  51. metadata +137 -0
@@ -0,0 +1,98 @@
1
+ require 'rbs'
2
+ require_relative 'config'
3
+ require_relative 'error'
4
+
5
+ module SteepKit
6
+ # Post-processes one ActiveRecord model's rbs_rails signature before writing:
7
+ # - rewrites custom `attribute` types whose type object responds to `#rbs_type`
8
+ # - wraps PostgreSQL array columns in `::Array[...]`
9
+ # - annotates nilable attribute/association readers with `%a{pure}` so Steep
10
+ # narrows `if record.attr` (opt-outable via `rbs_rails.pure_nilable_readers`)
11
+ #
12
+ # Framework-agnostic ActiveRecord helper; works in Rails, Hanami, or standalone AR.
13
+ class RbsRailsPostprocess
14
+ PURE = '%a{pure}'.freeze
15
+ NILABLE_READER = /\A(\s*)def (\w+): \(\) -> .+\?$/
16
+
17
+ Result = Data.define(:rbs, :rewritten, :annotated)
18
+
19
+ def initialize(model, postgres_arrays: nil, custom_type_rbs_type: nil, pure_nilable_readers: nil)
20
+ defaults = Config.rbs_rails_settings
21
+ @model = model
22
+ @postgres_arrays = postgres_arrays.nil? ? defaults.postgres_arrays : postgres_arrays
23
+ @custom_type_rbs_type = custom_type_rbs_type.nil? ? defaults.custom_type_rbs_type : custom_type_rbs_type
24
+ @pure_nilable_readers = pure_nilable_readers.nil? ? defaults.pure_nilable_readers : pure_nilable_readers
25
+ end
26
+
27
+ def call(rbs)
28
+ lines = rbs.lines
29
+ rewritten = rewrite_overrides(lines)
30
+ output = @pure_nilable_readers ? annotate_pure(lines) : lines
31
+
32
+ Result.new(rbs: output.join, rewritten:, annotated: output.size - lines.size)
33
+ end
34
+
35
+ private
36
+
37
+ # An explicit #rbs_type wins over array wrapping.
38
+ def overrides
39
+ (@postgres_arrays ? array_overrides : {}).merge(@custom_type_rbs_type ? attribute_overrides : {})
40
+ end
41
+
42
+ def attribute_overrides
43
+ @model.attribute_types.filter_map { |name, type| [name, type.rbs_type] if type.respond_to?(:rbs_type) }.to_h
44
+ end
45
+
46
+ def array_overrides
47
+ @model.columns_hash.filter_map { |name, column| [name, :array] if column.respond_to?(:array) && column.array }.to_h
48
+ end
49
+
50
+ def rewrite_overrides(lines)
51
+ count = 0
52
+ overrides.each do |name, override|
53
+ accessor = /\A(?<indent>\s*)def (?<name>#{Regexp.escape(name)}=?): (?<type>.+)$/
54
+ lines.map! do |line|
55
+ match = accessor.match(line) or next line
56
+
57
+ rewritten = "#{match[:indent]}def #{match[:name]}: #{override_method_type(match[:type], override)}\n"
58
+ count += 1 if rewritten != line
59
+ rewritten
60
+ end
61
+ end
62
+ count
63
+ end
64
+
65
+ def override_method_type(source, override)
66
+ method_type = RBS::Parser.parse_method_type(source)
67
+ column_type = method_type.type.return_type
68
+ replacement = override_type(column_type, override) or return source
69
+
70
+ method_type.update(type: method_type.type.map_type { |type| type == column_type ? replacement : type }).to_s
71
+ rescue RBS::ParsingError => e
72
+ raise Error, "#{@model.name} accessor `#{source}` is not a method type: #{e.message.lines.first&.strip}"
73
+ end
74
+
75
+ def override_type(column_type, override)
76
+ optional = column_type.is_a?(RBS::Types::Optional)
77
+ base = optional ? column_type.type : column_type
78
+ replacement =
79
+ if override == :array
80
+ return if base.is_a?(RBS::Types::Bases::Any) || (base.is_a?(RBS::Types::ClassInstance) && base.name.to_s == '::Array')
81
+
82
+ RBS::Types::ClassInstance.new(name: RBS::TypeName.parse('::Array'), args: [base], location: nil)
83
+ else
84
+ RBS::Parser.parse_type(override)
85
+ end
86
+ optional ? RBS::Types::Optional.new(type: replacement, location: nil) : replacement
87
+ end
88
+
89
+ def annotate_pure(lines)
90
+ writers = lines.filter_map { |line| line[/\bdef (\w+)=: /, 1] }.to_set
91
+ lines.each_with_object([]) do |line, output|
92
+ match = NILABLE_READER.match(line)
93
+ output << "#{match[1]}#{PURE}\n" if match && writers.include?(match[2]) && output.last&.strip != PURE
94
+ output << line
95
+ end
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,39 @@
1
+ require 'pathname'
2
+ require_relative 'error'
3
+
4
+ module SteepKit
5
+ # `steep-kit rbs-rails [Model ...]`: regenerates sig/rbs_rails deterministically
6
+ # from the committed schema via `bin/rails rbs_rails:regen`.
7
+ class RbsRailsRegen
8
+ TASK = 'rbs_rails:regen'.freeze
9
+ ONLY_ENV = 'RBS_RAILS_ONLY'.freeze
10
+
11
+ class Shell
12
+ def run(env, *command, chdir:)
13
+ system(env, *command, chdir:) or raise Error, "#{command.join(' ')} failed"
14
+ end
15
+ end
16
+
17
+ def self.only_models(env)
18
+ names = env[ONLY_ENV].to_s.split(',').map(&:strip).reject(&:empty?)
19
+ names.empty? ? nil : names
20
+ end
21
+
22
+ def self.only_env(names)
23
+ { ONLY_ENV => (names.empty? ? nil : names.join(',')) }
24
+ end
25
+
26
+ def initialize(root:, models: [], shell: Shell.new)
27
+ @root = Pathname(root)
28
+ @models = models.map(&:strip)
29
+ @shell = shell
30
+ end
31
+
32
+ def call
33
+ raise Error, "bin/rails not found under #{@root}; run from the Rails application root" unless @root.join('bin/rails').executable?
34
+ raise Error, 'model names must not be blank' if @models.any?(&:empty?)
35
+
36
+ @shell.run(self.class.only_env(@models), 'bin/rails', TASK, chdir: @root.to_s)
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,169 @@
1
+ require 'pathname'
2
+ require_relative 'config'
3
+ require_relative 'error'
4
+ require_relative 'paths'
5
+ require_relative 'rbs_rails_postprocess'
6
+
7
+ module SteepKit
8
+ # The Rails side of `steep-kit rbs-rails`: loads the committed schema
9
+ # (`db/schema.rb` or `db/structure.sql`) into a purged scratch database,
10
+ # generates model and path helper signatures via rbs_rails, and runs
11
+ # RbsRailsPostprocess over each model signature before writing.
12
+ class RbsRailsScratch
13
+ CONFIG_FILES = %w[.rbs_rails.rb config/rbs_rails.rb].freeze
14
+ GENERATED_HEADER = '# resolve-type-names: false'.freeze
15
+
16
+ class Generator
17
+ def initialize(root)
18
+ @root = root
19
+ end
20
+
21
+ def configuration
22
+ @configuration ||= begin
23
+ require 'rbs_rails'
24
+ require 'rbs_rails/cli'
25
+ config_file = CONFIG_FILES.map { |name| @root.join(name) }.find(&:file?)
26
+ load(config_file.to_s) if config_file
27
+ RbsRails::CLI::Configuration.instance
28
+ end
29
+ end
30
+
31
+ def signature_root = Pathname(configuration.signature_root_dir)
32
+ def ignored?(klass) = configuration.ignored_model?(klass)
33
+ def generatable?(klass) = RbsRails::ActiveRecord.generatable?(klass)
34
+ def model_rbs(klass) = RbsRails::ActiveRecord.class_to_rbs(klass)
35
+ def path_helpers_rbs = RbsRails::PathHelpers.generate
36
+
37
+ def write(path, content)
38
+ path.dirname.mkpath
39
+ RbsRails::Util::FileWriter.new(path).write(content)
40
+ end
41
+ end
42
+
43
+ Runtime = Data.define(:application, :base, :database_tasks, :hash_config, :schema_format) do
44
+ def initialize(application:, base:, database_tasks:, hash_config:, schema_format: :ruby)
45
+ super
46
+ end
47
+
48
+ def self.current
49
+ format = defined?(::ActiveRecord) && ::ActiveRecord.respond_to?(:schema_format) ? ::ActiveRecord.schema_format : :ruby
50
+ new(
51
+ application: Rails.application,
52
+ base: ActiveRecord::Base,
53
+ database_tasks: ActiveRecord::Tasks::DatabaseTasks,
54
+ hash_config: ActiveRecord::DatabaseConfigurations::HashConfig,
55
+ schema_format: format
56
+ )
57
+ end
58
+ end
59
+
60
+ def initialize(root:, only: nil, stdout: $stdout, runtime: Runtime.current, **options)
61
+ @root = Pathname(root).expand_path
62
+ @only = only
63
+ @stdout = stdout
64
+ @runtime = runtime
65
+ @generator = options.fetch(:generator) { Generator.new(@root) }
66
+ @settings = options.fetch(:settings) { Config.rbs_rails_settings }
67
+ end
68
+
69
+ def call
70
+ @stdout.puts("rbs-rails: limiting to #{@only.join(', ')}") if @only
71
+ load_schema
72
+ signatures = generated_models.to_h { |klass| [signature_path(klass), signature(klass)] }
73
+ outputs = signatures.transform_values(&:rbs).merge(@generator.signature_root.join('path_helpers.rbs') => @generator.path_helpers_rbs)
74
+ outputs.each { |path, rbs| @generator.write(path, rbs) }
75
+ report(signatures.values)
76
+ remove_stale(outputs.keys) unless @only
77
+ end
78
+
79
+ private
80
+
81
+ def primary_config
82
+ @primary_config ||= @runtime.base.connection_db_config
83
+ end
84
+
85
+ def scratch_config
86
+ @scratch_config ||= begin
87
+ original = primary_config
88
+ suffix = @settings.scratch_suffix
89
+ hash = original.configuration_hash.except(:url).merge(database: "#{original.database}#{suffix}")
90
+ @runtime.hash_config.new(original.env_name, "#{original.name}#{suffix}", hash)
91
+ end
92
+ end
93
+
94
+ def load_schema
95
+ config = scratch_config
96
+ format = @runtime.schema_format
97
+ file = @runtime.database_tasks.schema_dump_path(primary_config, format) or raise Error, 'the primary database has no schema file'
98
+ @stdout.puts("rbs-rails: loading #{file} into #{config.database}")
99
+ tasks = @runtime.database_tasks
100
+ tasks.purge(config)
101
+ tasks.with_temporary_connection(config) { tasks.load_schema(config, format, file) }
102
+ @runtime.base.establish_connection(config)
103
+ end
104
+
105
+ def generated_models
106
+ @runtime.application.eager_load!
107
+ models = @runtime.base.descendants.select { |klass| candidate?(klass) }
108
+ check_names!(models)
109
+ check_tables!(models)
110
+ raise Error, 'found no model to generate; check config/rbs_rails.rb' if models.empty?
111
+
112
+ models
113
+ end
114
+
115
+ def candidate?(klass)
116
+ name = klass.name or return false
117
+ return false if @only && !@only.include?(name)
118
+ return false if @generator.ignored?(klass)
119
+
120
+ !klass.abstract_class?
121
+ end
122
+
123
+ def check_names!(models)
124
+ unknown = @only.to_a - models.map(&:name)
125
+ raise Error, "no model to generate named #{unknown.join(', ')} (unknown, abstract, or ignored by config/rbs_rails.rb)" if unknown.any?
126
+ end
127
+
128
+ def check_tables!(models)
129
+ missing = models.reject { |klass| table?(klass) }.map(&:name).sort
130
+ raise Error, "no table for #{missing.join(', ')}: run the pending migrations or ignore the model in config/rbs_rails.rb" if missing.any?
131
+ end
132
+
133
+ def table?(klass)
134
+ @generator.generatable?(klass)
135
+ rescue StandardError => e
136
+ raise Error, "cannot read the table of #{klass.name}: #{e.message.lines.first&.strip}"
137
+ end
138
+
139
+ def signature(klass)
140
+ RbsRailsPostprocess.new(
141
+ klass,
142
+ postgres_arrays: @settings.postgres_arrays,
143
+ custom_type_rbs_type: @settings.custom_type_rbs_type,
144
+ pure_nilable_readers: @settings.pure_nilable_readers
145
+ ).call(@generator.model_rbs(klass))
146
+ end
147
+
148
+ def signature_path(klass)
149
+ source, = Object.const_source_location(klass.name)
150
+ relative = source && Paths.relative_within(Pathname(source), @root)
151
+ @generator.signature_root.join(relative ? Pathname(relative).sub_ext('.rbs') : "app/models/#{klass.name.underscore}.rbs")
152
+ end
153
+
154
+ def report(results)
155
+ @stdout.puts("rbs_rails_postprocess: rewrote #{results.sum(&:rewritten)} accessor line(s), annotated #{results.sum(&:annotated)} reader(s)")
156
+ end
157
+
158
+ def remove_stale(written)
159
+ kept = written.map(&:expand_path)
160
+ stale = @generator.signature_root.glob('**/*.rbs').select { |file| !kept.include?(file.expand_path) && generated?(file) }
161
+ stale.each(&:delete)
162
+ @stdout.puts("rbs-rails: removed #{stale.size} stale signature(s)")
163
+ end
164
+
165
+ def generated?(file)
166
+ file.open(encoding: 'UTF-8', &:gets)&.chomp == GENERATED_HEADER
167
+ end
168
+ end
169
+ end
@@ -0,0 +1,20 @@
1
+ require 'rake'
2
+ require_relative 'config'
3
+ require_relative 'rbs_rails_regen'
4
+ require_relative 'rbs_rails_scratch'
5
+
6
+ # Rake glue for a consuming Rails app: `require 'steep_kit/rbs_rails_tasks'`
7
+ # inside a LoadError rescue where production bundles exclude the typecheck group.
8
+ namespace :rbs_rails do
9
+ # rbs_rails records `enum` calls through a hook installed before models load.
10
+ task :install_hooks do
11
+ require 'rbs_rails/active_record/enum'
12
+ end
13
+
14
+ desc 'Regenerate sig/rbs_rails from the schema through a scratch database'
15
+ task regen: %i[install_hooks environment] do
16
+ config = SteepKit::Config.locate(root: Rails.root) ? SteepKit::Config.load(root: Rails.root) : nil
17
+ settings = config ? config.rbs_rails : SteepKit::Settings::RbsRails.default
18
+ SteepKit::RbsRailsScratch.new(root: Rails.root, only: SteepKit::RbsRailsRegen.only_models(ENV), settings:).call
19
+ end
20
+ end
@@ -0,0 +1,344 @@
1
+ require 'json'
2
+ require 'optparse'
3
+ require 'pathname'
4
+ require 'rbs'
5
+ require 'rbs/cli'
6
+ require 'rbs/test'
7
+ require 'shellwords'
8
+ require_relative 'config'
9
+ require_relative 'source_files'
10
+ require_relative 'steep'
11
+
12
+ module SteepKit
13
+ # Runtime RBS verification harness built on RBS::Test::Tester.
14
+ #
15
+ # Loads inline RBS from configured signature_paths alongside classic `sig/`
16
+ # trees, applies generic RBS::Test fixes (prepended method ownership,
17
+ # ruby2_keywords discrimination, setter return semantics), optionally adapts
18
+ # ActiveSupport::TimeWithZone and ActiveRecord relations when loaded, and
19
+ # explains nested record/array/hash mismatches or logs them as JSONL.
20
+ module Runtime
21
+ DEFAULT_UNCHECKED_CLASSES = %w[
22
+ ::RSpec::Mocks::Double
23
+ ::RSpec::Mocks::InstanceVerifyingDouble
24
+ ::RSpec::Mocks::ObjectVerifyingDouble
25
+ ::RSpec::Mocks::ClassVerifyingDouble
26
+ ].freeze
27
+
28
+ module OwnMethodChain
29
+ def setup_alias_method_chain(klass, target, random:)
30
+ own = klass.instance_method(target)
31
+ own = own.super_method until own.nil? || own.owner == klass
32
+ return super if own.nil? || klass.instance_method(target).owner == klass
33
+
34
+ with_method, without_method = alias_names(target, random)
35
+ klass.define_method(without_method, own)
36
+ klass.alias_method(target, with_method)
37
+ klass.send(own_visibility(klass, without_method), target)
38
+ end
39
+
40
+ private
41
+
42
+ def own_visibility(klass, name)
43
+ return :private if klass.private_method_defined?(name)
44
+ return :protected if klass.protected_method_defined?(name)
45
+
46
+ :public
47
+ end
48
+ end
49
+
50
+ module KeywordFlag
51
+ def keyword?(value)
52
+ super && ::Hash.ruby2_keywords_hash?(value)
53
+ end
54
+ end
55
+
56
+ # Accepts ActiveSupport::TimeWithZone as `::Time` and ActiveRecord relation
57
+ # subclasses/proxies covariantly when those libraries are loaded.
58
+ module FrameworkConventions
59
+ RELATION_NAMES = %i[
60
+ ActiveRecord_Relation
61
+ ActiveRecord_AssociationRelation
62
+ ActiveRecord_Associations_CollectionProxy
63
+ ].freeze
64
+
65
+ def value(val, type)
66
+ super || (type.is_a?(RBS::Types::ClassInstance) && (zone_time?(val, type.name) || relation?(val, type.name)))
67
+ end
68
+
69
+ private
70
+
71
+ def zone_time?(val, name)
72
+ defined?(::ActiveSupport::TimeWithZone) && name.to_s == '::Time' && RBS::Test::IS_AP.bind_call(val, ::ActiveSupport::TimeWithZone)
73
+ end
74
+
75
+ def relation?(val, name)
76
+ return false unless defined?(::ActiveRecord::Relation) && RELATION_NAMES.include?(name.name)
77
+
78
+ model = get_class(name.namespace.to_type_name)
79
+ model.is_a?(::Class) && relation_kinds(name.name).any? { |kind| RBS::Test::IS_AP.bind_call(val, kind) } && val.klass <= model
80
+ end
81
+
82
+ def relation_kinds(relation_name)
83
+ return [::ActiveRecord::Relation] if relation_name == :ActiveRecord_Relation
84
+
85
+ [::ActiveRecord::AssociationRelation, ::ActiveRecord::Associations::CollectionProxy]
86
+ end
87
+ end
88
+
89
+ module WriterReturn
90
+ WRITER = /\A[[:alpha:]_]\w*=\z/
91
+
92
+ def return(method_name, *, return_error:, **)
93
+ super unless return_error == RBS::Test::Errors::ReturnTypeError && WRITER.match?(method_name)
94
+ end
95
+ end
96
+
97
+ class Explainer
98
+ def explain(check, error, trace)
99
+ case error
100
+ when RBS::Test::Errors::ArgumentTypeError, RBS::Test::Errors::BlockArgumentTypeError
101
+ mismatch(check, error.value, error.param.type, error.param.name&.to_s || 'argument')
102
+ when RBS::Test::Errors::ReturnTypeError, RBS::Test::Errors::BlockReturnTypeError
103
+ mismatch(check, error.value, error.type, 'return')
104
+ else
105
+ arguments = trace.method_call.arguments.map { |argument| describe(argument) }.join(', ')
106
+ "#{demodulize(error.class.name)}: given (#{arguments})"
107
+ end
108
+ end
109
+
110
+ def describe(value)
111
+ klass = RBS::Test::CLASS.bind_call(value)
112
+ case value
113
+ when ::Hash then "#{klass}{#{value.keys.first(6).map(&:inspect).join(', ')}}"
114
+ when ::Numeric, ::String, ::Symbol, nil, true, false then "#{klass} #{value.inspect[0, 40]}"
115
+ else klass.to_s
116
+ end
117
+ end
118
+
119
+ def demodulize(name)
120
+ name.to_s.split('::').last
121
+ end
122
+
123
+ private
124
+
125
+ def mismatch(check, value, type, path)
126
+ type = check.builder.expand_alias2(type.name.absolute!, type.args) while type.is_a?(RBS::Types::Alias)
127
+ refused = parts(value, type, path)&.find { |part, part_type, _| !check.value(part, part_type) }
128
+ refused ? mismatch(check, *refused) : "#{path}: expected `#{type}`, given #{describe(value)}"
129
+ end
130
+
131
+ def parts(value, type, path)
132
+ case type
133
+ when RBS::Types::Optional then [[value, type.type, path]] unless value.nil?
134
+ when RBS::Types::Record then record_parts(value, type, path)
135
+ when RBS::Types::Tuple then tuple_parts(value, type, path)
136
+ when RBS::Types::ClassInstance then collection_parts(value, type, path)
137
+ end
138
+ end
139
+
140
+ def record_parts(value, type, path)
141
+ return unless RBS::Test::IS_AP.bind_call(value, ::Hash)
142
+
143
+ type.fields.map { |key, field| [value[key], field, "#{path}[#{key.inspect}]"] }
144
+ end
145
+
146
+ def tuple_parts(value, type, path)
147
+ return unless RBS::Test::IS_AP.bind_call(value, ::Array)
148
+
149
+ type.types.each_with_index.map { |item, index| [value[index], item, "#{path}[#{index}]"] }
150
+ end
151
+
152
+ def collection_parts(value, type, path)
153
+ key_type, value_type = type.args
154
+ return unless key_type
155
+ return array_parts(value, key_type, path) if type.name.to_s == '::Array' && RBS::Test::IS_AP.bind_call(value, ::Array)
156
+ return unless type.name.to_s == '::Hash' && RBS::Test::IS_AP.bind_call(value, ::Hash) && value_type
157
+
158
+ value.flat_map { |key, item| [[key, key_type, "#{path} key"], [item, value_type, "#{path}[#{label(key)}]"]] }
159
+ end
160
+
161
+ def array_parts(value, element_type, path)
162
+ value.each_with_index.map { |item, index| [item, element_type, "#{path}[#{index}]"] }
163
+ end
164
+
165
+ def label(key)
166
+ key.is_a?(::String) || key.is_a?(::Symbol) || key.is_a?(::Integer) ? key.inspect : "<#{key.class}>"
167
+ end
168
+ end
169
+
170
+ module Recorder
171
+ def call(receiver, trace)
172
+ super
173
+ rescue RBS::Test::Tester::TypeError => e
174
+ details = e.errors.map { |error| Runtime.explainer.explain(check, error, trace) }
175
+ raise e.exception("#{e.message} (#{details.join('; ')})") unless Runtime.report?
176
+
177
+ Runtime.record(e.errors.zip(details), self_class, trace, caller_locations)
178
+ end
179
+ end
180
+
181
+ class Session
182
+ def initialize(root:, **options)
183
+ @root = Pathname(root).expand_path
184
+ assign_target_options(options)
185
+ assign_runtime_options(options)
186
+ end
187
+
188
+ def report?
189
+ @mode == 'report'
190
+ end
191
+
192
+ def install
193
+ raise Error, 'RBS_TEST_TARGET (or target:) must be set for SteepKit::Runtime' if @target.nil? || @target.empty?
194
+
195
+ RBS.logger_level = @loglevel
196
+ tester = RBS::Test::Tester.new(env: environment)
197
+ targets(tester.env).each { |klass| install_on(tester, klass) }
198
+ @stderr.puts("steep-kit runtime: checking #{tester.targets.size} modules")
199
+ tester
200
+ end
201
+
202
+ def record(violations, self_class, trace, locations)
203
+ frames = filtered_frames(locations)
204
+ Pathname(@log_path).dirname.mkpath
205
+ File.open(@log_path, 'a') do |file|
206
+ violations.each { |violation, detail| file.puts(JSON.generate(entry(violation, detail, self_class, trace, frames))) }
207
+ end
208
+ end
209
+
210
+ private
211
+
212
+ def assign_target_options(options)
213
+ @target = options.fetch(:target) { ENV.fetch('RBS_TEST_TARGET', nil) }
214
+ @skip = options.fetch(:skip) { ENV.fetch('RBS_TEST_SKIP', '') }.to_s
215
+ @libraries = Array(options[:libraries])
216
+ @signature_dirs = options[:signature_dirs]
217
+ @unchecked_classes = Array(options.fetch(:unchecked_classes, DEFAULT_UNCHECKED_CLASSES))
218
+ end
219
+
220
+ def assign_runtime_options(options)
221
+ @mode = options.fetch(:mode) { ENV.fetch('RBS_RUNTIME', nil) }
222
+ @log_path = options[:log_path] || ENV.fetch('RBS_RUNTIME_LOG', @root.join('tmp/rbs_runtime.jsonl').to_s)
223
+ @sample_size = options.fetch(:sample_size, 100)
224
+ @opt = options.fetch(:opt) { ENV.fetch('RBS_TEST_OPT', nil) }
225
+ @loglevel = options.fetch(:loglevel) { ENV.fetch('RBS_TEST_LOGLEVEL', 'warn') }
226
+ @stderr = options.fetch(:stderr, $stderr)
227
+ end
228
+
229
+ def install_on(tester, klass)
230
+ tester.install!(klass, sample_size: @sample_size, unchecked_classes: @unchecked_classes)
231
+ rescue RBS::BaseError, NameError => e
232
+ @stderr.puts("steep-kit runtime: #{klass} not checked: #{e.class}: #{e.message.lines.first}")
233
+ end
234
+
235
+ def environment
236
+ config = load_config
237
+ options = RBS::CLI::LibraryOptions.new
238
+ OptionParser.new { |parser| options.setup_library_options(parser) }.parse!(library_argv(config))
239
+
240
+ env = RBS::Environment.from_loader(options.loader)
241
+ add_inline_sources(env, config) if config
242
+ env.resolve_type_names
243
+ end
244
+
245
+ def load_config
246
+ return unless Config.locate(root: @root)
247
+
248
+ Config.load(root: @root)
249
+ end
250
+
251
+ def library_argv(config)
252
+ return Shellwords.shellsplit(@opt) if @opt
253
+
254
+ dirs = (@signature_dirs || discovered_signature_dirs(config)).flat_map { |dir| ['-I', dir.to_s] }
255
+ libs = @libraries.flat_map { |library| ['-r', library.to_s] }
256
+ dirs + libs
257
+ end
258
+
259
+ def discovered_signature_dirs(config)
260
+ sig_root = @root.join('sig')
261
+ dirs = sig_root.directory? ? sig_root.children.select(&:directory?).sort : []
262
+ projected = config && @root.join(config.projected_root)
263
+ dirs << projected if projected&.directory? && !dirs.include?(projected)
264
+ dirs.map(&:to_s)
265
+ end
266
+
267
+ def add_inline_sources(env, config)
268
+ SourceFiles.new(root: config.root).analyses(config.signature_paths).each do |analysis|
269
+ env.add_source(analysis.rbs_source)
270
+ end
271
+ end
272
+
273
+ def targets(env)
274
+ named = ObjectSpace.each_object(Module).map { |mod| [Module.instance_method(:name).bind_call(mod), mod] }
275
+ targeted = named.select { |name, _| name && target?(name) && env.module_name?(RBS::TypeName.parse("::#{name}")) }
276
+ targeted.sort_by(&:first).map(&:last)
277
+ end
278
+
279
+ def target?(name)
280
+ matches?(@target, name) && !matches?(@skip, name)
281
+ end
282
+
283
+ def matches?(list, name)
284
+ list.split(',').map(&:strip).any? do |filter|
285
+ next false if filter.empty?
286
+
287
+ filter.end_with?('*') ? name.start_with?(filter.chomp('*')) || name == filter.chomp('::*') : name == filter
288
+ end
289
+ end
290
+
291
+ def filtered_frames(locations)
292
+ locations.map(&:to_s).grep(%r{/(app|lib|spec|test)/}).grep_v(%r{/gems/|steep_kit/runtime})
293
+ end
294
+
295
+ def entry(violation, detail, self_class, trace, frames)
296
+ {
297
+ error: Runtime.explainer.demodulize(violation.class.name),
298
+ klass: self_class.to_s,
299
+ method: trace.method_name,
300
+ detail:,
301
+ message: RBS::Test::Errors.to_string(violation),
302
+ example: (::RSpec.current_example&.id if defined?(::RSpec) && ::RSpec.respond_to?(:current_example)),
303
+ frames: frames.first(4)
304
+ }
305
+ end
306
+ end
307
+
308
+ class << self
309
+ attr_reader :session
310
+
311
+ def explainer
312
+ @explainer ||= Explainer.new
313
+ end
314
+
315
+ def install_patches!
316
+ prepend_once(RBS::Test::Hook.singleton_class, OwnMethodChain)
317
+ prepend_once(RBS::Test::TypeCheck, KeywordFlag)
318
+ prepend_once(RBS::Test::TypeCheck, FrameworkConventions)
319
+ prepend_once(RBS::Test::TypeCheck, WriterReturn)
320
+ prepend_once(RBS::Test::Tester::MethodCallTester, Recorder)
321
+ end
322
+
323
+ def install(**)
324
+ install_patches!
325
+ @session = Session.new(**)
326
+ @session.install
327
+ end
328
+
329
+ def report?
330
+ @session&.report? || false
331
+ end
332
+
333
+ def record(...)
334
+ @session&.record(...)
335
+ end
336
+
337
+ private
338
+
339
+ def prepend_once(target, mod)
340
+ target.prepend(mod) unless target.ancestors.include?(mod)
341
+ end
342
+ end
343
+ end
344
+ end