erb_check 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.
@@ -0,0 +1,199 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "open3"
4
+ require_relative "../erb_check"
5
+
6
+ module ErbCheck
7
+ # erb_check snapshot boot the app and record its controllers, helpers and components
8
+ # erb_check compile generate the Ruby Sorbet checks
9
+ # erb_check check compile, run Sorbet, report template errors not in the baseline (exit 1 if any);
10
+ # --all prints the baselined ones too
11
+ # erb_check baseline compile, run Sorbet, write every template error to the baseline
12
+ # erb_check report what was checked: contexts, locals, callers erb_check couldn't follow
13
+ # erb_check lsp language server for editors: Sorbet's, with templates mapped in and out
14
+ class CLI
15
+ USAGE = <<~TEXT
16
+ Usage: erb_check <snapshot|compile|check|baseline|report|lsp> [--app PATH] [--all]
17
+ --all with check, print baselined template errors too
18
+ --version print erb_check's version
19
+ TEXT
20
+
21
+ # A file erb_check adds beside the generated programs for each Sorbet run, with a revealed type Sorbet must
22
+ # report. If it doesn't, Sorbet didn't check what erb_check generated, and a clean result would mean nothing.
23
+ CANARY = "erb_check_canary_must_be_reported"
24
+ CANARY_SOURCE = <<~RUBY
25
+ # typed: true
26
+ # Written by erb_check for one Sorbet run; Sorbet must report the revealed type below.
27
+ T.reveal_type(:#{CANARY})
28
+ RUBY
29
+
30
+ def initialize(argv, out: $stdout)
31
+ @argv = argv.dup
32
+ @out = out
33
+ app = @argv.index("--app") ? @argv.slice!(@argv.index("--app"), 2).last : Dir.pwd
34
+ @config = Config.load(File.expand_path(app))
35
+ end
36
+
37
+ def run
38
+ if @argv.include?("--help") || %w[-h help].include?(@argv.first)
39
+ @out.puts USAGE
40
+ return 0
41
+ end
42
+ if @argv.include?("--version") || @argv.first == "-v"
43
+ @out.puts "erb_check #{VERSION}"
44
+ return 0
45
+ end
46
+
47
+ case @argv.first
48
+ when "snapshot" then snapshot
49
+ when "compile" then compile && 0
50
+ when "check" then check
51
+ when "baseline" then write_baseline
52
+ when "report" then report
53
+ when "lsp" then LSP.new(@config).run
54
+ else
55
+ @out.puts USAGE
56
+ @argv.empty? ? 0 : 2
57
+ end
58
+ end
59
+
60
+ private
61
+
62
+ def snapshot
63
+ Dir.chdir(@config.app_root) do
64
+ require File.join(@config.app_root, "config/environment")
65
+ require_relative "rails_snapshot"
66
+ data = RailsSnapshot.capture(@config.app_root).merge("sources" => @config.snapshot_sources)
67
+ FileUtils.mkdir_p(@config.output_path)
68
+ File.write(@config.output_path("snapshot.json"), JSON.generate(data))
69
+ herb = data["herb_formats"].empty? ? "" : "; Herb compiles #{data['herb_formats'].join(', ')}"
70
+ @out.puts "Snapshot: #{count(data['controllers'].size, 'controller or mailer', 'controllers and mailers')}, " \
71
+ "#{count(data['components'].size, 'component')}#{herb}"
72
+ end
73
+ 0
74
+ end
75
+
76
+ def compile
77
+ unless File.exist?(@config.output_path("snapshot.json"))
78
+ @out.puts "No snapshot at #{@config.output}/snapshot.json; run `erb_check snapshot` first."
79
+ return false
80
+ end
81
+
82
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
83
+ @compiler = Compiler.new(@config).compile
84
+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
85
+ @out.puts "Compiled #{count(@compiler.units.map(&:template).uniq.size, 'template')} into " \
86
+ "#{count(@compiler.units.size, 'program')} in #{count(@compiler.registry.contexts.size, 'view context')} " \
87
+ "(#{elapsed.round(1)}s)"
88
+ if (changed = @compiler.changed_since_snapshot).any?
89
+ more = changed.size > 1 ? " and #{changed.size - 1} more" : ""
90
+ @out.puts "#{changed.first}#{more} changed since the snapshot; run `erb_check snapshot` to refresh it."
91
+ end
92
+ @compiler
93
+ end
94
+
95
+ def diagnostics
96
+ unless @config.sorbet.include?("--no-config") || File.exist?(@config.path("sorbet/config"))
97
+ @out.puts "No sorbet/config in #{@config.app_root}; run `bundle exec tapioca init` to set up Sorbet."
98
+ return
99
+ end
100
+ return unless compile
101
+
102
+ output, status = sorbet
103
+ parsed = Diagnostics.new(@config).parse(output).diagnostics
104
+ canary, parsed = parsed.partition { |d| Diagnostics.canary?(d.path) }
105
+ # Sorbet exits 1 when it reports errors. Failing with none it could parse means it didn't finish: fail
106
+ # rather than read the silence as a clean app.
107
+ if parsed.empty? && canary.empty? && !status.success?
108
+ @out.puts output, "Sorbet failed (#{status}) without reporting an error erb_check could read."
109
+ return
110
+ end
111
+ if canary.none? { |d| d.message.include?(CANARY) }
112
+ @out.puts output, "Sorbet didn't check the code erb_check generated: it never reported the type revealed in " \
113
+ "erb_check's canary file. erb_check passes the generated files as arguments to the `sorbet` " \
114
+ "command (#{@config.sorbet.join(' ')}); make sure it passes them on to `srb tc`, and that " \
115
+ "sorbet/config doesn't suppress error 7014 or lower the strictness of #{@config.output}/generated/."
116
+ return
117
+ end
118
+ findings = @compiler.findings.map do |f|
119
+ Diagnostics::Diagnostic.new(path: f.path, line: f.line, column: nil, code: f.code, message: f.message,
120
+ detail: "", contexts: [])
121
+ end
122
+ parsed + findings
123
+ end
124
+
125
+ # Sorbet over the app with the generated files named explicitly, so sorbet/config can ignore their directory
126
+ # (keeping them out of plain `srb tc` and the editor) without hiding them here. Naming them bypasses Sorbet's
127
+ # --ignore; ignoring the directory keeps a sorbet/config that includes it from checking each file twice.
128
+ # The error URL base is Sorbet's default, which Diagnostics reads codes from, whatever sorbet/config sets.
129
+ def sorbet
130
+ canary = @config.output_path("generated", "erb_check-canary-#{Process.pid}.rb")
131
+ args = @config.output_path("sorbet-#{Process.pid}.args")
132
+ File.write(canary, CANARY_SOURCE)
133
+ files = Dir.glob("**/*.{rb,rbi}", base: @config.output_path).sort.map { |f| File.join(@config.output, f) }
134
+ File.write(args, files.join("\n") + "\n")
135
+ Open3.capture2e(*@config.sorbet, "--ignore=/#{@config.output}/", "--error-url-base=https://srb.help/",
136
+ "@#{@config.output}/#{File.basename(args)}", chdir: @config.app_root)
137
+ ensure
138
+ FileUtils.rm_f([canary, args].compact)
139
+ end
140
+
141
+ def check
142
+ all = diagnostics or return 1
143
+ templates, ruby = all.partition(&:template?)
144
+ fresh, stale = Baseline.new(@config.path(@config.baseline)).compare(templates, method(:line_text))
145
+ shown = @argv.include?("--all") ? templates : fresh
146
+ (ruby + shown).each { |d| @out.puts d, "" }
147
+ @out.puts "#{templates.size} template errors, #{templates.size - fresh.size} in the baseline, #{fresh.size} new; " \
148
+ "#{ruby.size} errors in Ruby files"
149
+ @out.puts "#{stale.size} baseline entries no longer occur; run `erb_check baseline` to prune them." if stale.any?
150
+ ruby.empty? && fresh.empty? ? 0 : 1
151
+ end
152
+
153
+ def write_baseline
154
+ all = diagnostics or return 1
155
+ templates = all.select(&:template?)
156
+ failures = templates.count { |d| d.code == Diagnostics::COMPILER_FAILURE }
157
+ count = Baseline.new(@config.path(@config.baseline)).write(templates, method(:line_text))
158
+ @out.puts "Wrote #{count} template errors to #{@config.baseline}."
159
+ @out.puts "#{failures} compiler failures can't be baselined; fix or report them." if failures.positive?
160
+ 0
161
+ end
162
+
163
+ def report
164
+ compiler = compile or return 1
165
+ units = compiler.units.group_by(&:template)
166
+ strict = units.count { |_, u| u.first.locals.nil? && u.first.context }
167
+ legacy = units.count { |path, u| u.first.locals && compiler.graph.usages(path).any? { |x| x.locals&.any? } }
168
+ uncalled = units.count { |path, list| !u_component?(list) && compiler.graph.fallback?(path) }
169
+ @out.puts "Templates: #{units.size} checked, #{compiler.skipped.size} skipped"
170
+ compiler.skipped.each { |path, reason| @out.puts " skipped #{path}: #{reason.empty? ? '(no reason given)' : reason}" }
171
+ @out.puts "View contexts: #{compiler.registry.contexts.size} (from #{compiler.registry.controllers.size} controllers and mailers)"
172
+ @out.puts "Programs: #{compiler.units.size}; per template max #{units.values.map(&:size).max}"
173
+ @out.puts "Locals: #{strict} templates declare strict locals; #{legacy} take locals from their callers"
174
+ reads = compiler.ivar_coverage.values.sum { |v| v["reads"] }
175
+ typed = compiler.ivar_coverage.values.sum { |v| v["typed_reads"] }
176
+ @out.puts "Controller ivar reads: #{typed}/#{reads} typed (#{reads.zero? ? 0 : (100.0 * typed / reads).round(1)}%), counted per program"
177
+ @out.puts "No caller found, checked as their directory's controller: #{uncalled}"
178
+ unresolved = compiler.graph.unresolved.map { |u| [u.caller.delete_prefix("#{@config.app_root}/"), u.reason] }.uniq
179
+ unresolved = unresolved.sort_by { |caller, reason| [caller[/\A(.*):\d+\z/, 1].to_s, caller[/\d+\z/].to_i, reason] }
180
+ @out.puts "Render calls erb_check couldn't follow: #{unresolved.size}"
181
+ unresolved.each { |caller, reason| @out.puts " #{caller}: #{reason}" }
182
+ 0
183
+ end
184
+
185
+ def count(number, one, many = "#{one}s")
186
+ "#{number} #{number == 1 ? one : many}"
187
+ end
188
+
189
+ def u_component?(units)
190
+ units.all? { |u| u.context.nil? }
191
+ end
192
+
193
+ def line_text(diagnostic)
194
+ @lines ||= {}
195
+ lines = (@lines[diagnostic.path] ||= File.exist?(@config.path(diagnostic.path)) ? File.readlines(@config.path(diagnostic.path)) : [])
196
+ lines[diagnostic.line - 1]
197
+ end
198
+ end
199
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ErbCheck
4
+ # Finds a Ruby fragment in a larger text as a whole token: `end` is not the end of `safe_append` or
5
+ # `friend`. Both strings are binary, so offsets are bytes.
6
+ module CodeSearch
7
+ WORD = /[A-Za-z0-9_]/n
8
+
9
+ def self.find(text, code, from = 0)
10
+ while (found = text.index(code, from))
11
+ before = found.positive? ? text.byteslice(found - 1, 1) : ""
12
+ after = text.byteslice(found + code.bytesize, 1).to_s
13
+ open_ok = !code.match?(/\A#{WORD}/n) || !before.match?(WORD)
14
+ close_ok = !code.match?(/#{WORD}\z/n) || !after.match?(WORD)
15
+ return found if open_ok && close_ok
16
+
17
+ from = found + 1
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,349 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "fileutils"
5
+ require "json"
6
+ require "set"
7
+ require "active_support/core_ext/object/blank"
8
+
9
+ module ErbCheck
10
+ # Turns every template into Ruby Sorbet can check, under `<output>/generated`, with a source map beside each
11
+ # file, plus the view contexts and slot methods as RBI. A template is checked once for each distinct view
12
+ # context that renders it, and an undeclared partial once for each set of locals its callers pass.
13
+ class Compiler
14
+ # One generated program: a template checked in one context with one set of locals.
15
+ Unit = Data.define(:template, :context, :controllers, :locals, :generated)
16
+ # A finding erb_check makes itself, before Sorbet runs.
17
+ Finding = Data.define(:path, :line, :column, :code, :message)
18
+ # A generated program in memory: its unit, Ruby source (binary) and source map.
19
+ Program = Data.define(:unit, :source, :map)
20
+
21
+ LOCAL_NAME = /\A[a-z_][A-Za-z0-9_]*\z/
22
+ KEYWORDS = %w[alias and begin break case class def defined? do else elsif end ensure false for if in module next
23
+ nil not or redo rescue retry return self super then true undef unless until when while yield].freeze
24
+
25
+ attr_reader :units, :findings, :graph, :registry, :skipped, :programs_by_template, :local_type_programs, :ivar_coverage
26
+
27
+ def initialize(config)
28
+ @config = config
29
+ @snapshot = JSON.parse(File.read(config.output_path("snapshot.json")))
30
+ @inventory = Inventory.new(config.app_root, config.roots)
31
+ @templates = @inventory.templates
32
+ @sources = @templates.to_h { |t| [t.path, @inventory.source(t)] }
33
+ @registry = ContextRegistry.new(@snapshot, route_helper_modules: config.route_modules)
34
+ @components = @snapshot.fetch("components").each_with_object({}) do |c, map|
35
+ c["templates"].each { |path| map[path] = c["name"] }
36
+ end
37
+ @herb_formats = @snapshot.fetch("herb_formats")
38
+ @units = []
39
+ @findings = []
40
+ @skipped = {}
41
+ @programs_by_template = {}
42
+ @compiled = {}
43
+ @ivar_coverage = {}
44
+ end
45
+
46
+ def compile
47
+ build_graph
48
+ @ivar_flow = IvarFlow.new(@config, @snapshot, @graph)
49
+ out = @config.output_path("generated")
50
+ FileUtils.rm_rf(out)
51
+ @templates.each do |template|
52
+ (@programs_by_template[template.path] = programs(template)).each do |program|
53
+ write(program)
54
+ @units << program.unit
55
+ end
56
+ end
57
+ @local_type_programs = @templates.filter_map { |template| local_types(template) }
58
+ @local_type_programs.each { |program| write(program) }
59
+ File.write(@config.output_path("contexts.rbi"), @registry.rbi)
60
+ File.write(@config.output_path("slots.rbi"), slots_rbi)
61
+ File.write(@config.output_path("units.json"), JSON.pretty_generate(@units.map(&:to_h)))
62
+ File.write(@config.output_path("ivars.json"), JSON.pretty_generate(@ivar_coverage))
63
+ self
64
+ end
65
+
66
+ def build_graph
67
+ ruby_files = Dir.glob("app/**/*.rb", base: @config.app_root).map { |f| @config.path(f) }
68
+ pinned = @templates.filter_map { |t| (name = @config.context_override(t.path)) && [t.path, name] }.to_h
69
+ @graph = RenderGraph.new(templates: @templates, snapshot: @snapshot, ruby_files:, sources: @sources,
70
+ render_wrappers: @config.render_wrappers, default_controller: @config.default_context,
71
+ pinned:).build
72
+ self
73
+ end
74
+
75
+ # The snapshot's source files that have changed, appeared or gone since it was taken.
76
+ def changed_since_snapshot
77
+ recorded = @snapshot["sources"] or return []
78
+ current = @config.snapshot_sources
79
+ (recorded.keys | current.keys).reject { |file| recorded[file] == current[file] }.sort
80
+ end
81
+
82
+ def template(path)
83
+ @templates.find { |t| t.path == path }
84
+ end
85
+
86
+ # Ruby edits can change both callback execution and Sorbet's return types. The editor cannot boot
87
+ # a fresh snapshot of unsaved Ruby, so withdraw these facts until the next server start.
88
+ def forget_ivar_types
89
+ had_types = !@ivar_flow.nil?
90
+ @ivar_flow = nil
91
+ had_types
92
+ end
93
+
94
+ # The programs for one template, from `source` (an editor's unsaved text, or the file). Who renders it
95
+ # comes from the graph built from the files on disk.
96
+ def programs(template, source = @sources.fetch(template.path))
97
+ contracts = Contracts.new(source, external: @config.contract(template.path))
98
+ if (reason = contracts.ignore_reason)
99
+ @skipped[template.path] = reason
100
+ return []
101
+ end
102
+
103
+ if (component = @components[template.path])
104
+ return [program(template, source, contracts, context: nil, controllers: [], locals: nil, receiver: component)].compact
105
+ end
106
+
107
+ check_callers(template, contracts)
108
+ plans(template, contracts, source).filter_map do |(context, controllers, locals)|
109
+ program(template, source, contracts, context:, controllers:, locals:, receiver: nil)
110
+ end
111
+ end
112
+
113
+ # The class a caller's values are checked against: one identity method per local the template's
114
+ # locals_sig types, with that type copied from the template. Nil when nothing is typed.
115
+ def local_types(template)
116
+ source = @sources.fetch(template.path)
117
+ contracts = Contracts.new(source, external: @config.contract(template.path))
118
+ types = contracts.typed_params
119
+ return if types.empty? || contracts.ignore_reason || !contracts.strict_locals
120
+
121
+ generated = File.join(@config.output, "generated", "#{template.path}.locals.rb")
122
+ writer = MappedWriter.new(source)
123
+ writer.synthetic("# typed: true\n# Generated by erb_check from #{template.path}. Do not edit.\n")
124
+ writer.synthetic("class #{local_types_class(template.path)}\n extend T::Sig\n")
125
+ types.each do |name, type|
126
+ writer.synthetic(" sig { params(#{name}: ").contract(type).synthetic(").returns(T.untyped) }\n")
127
+ writer.synthetic(" def self.check_#{name}(#{name}) = #{name}\n")
128
+ end
129
+ writer.synthetic("end\n")
130
+ Program.new(unit: Unit.new(template: template.path, context: nil, controllers: [], locals: nil, generated:),
131
+ source: writer.source, map: writer.source_map(template_path: template.path, generated_path: generated))
132
+ end
133
+
134
+ private
135
+
136
+ def local_types_class(path)
137
+ "::ErbCheck::Generated::L#{Digest::SHA256.hexdigest(path)[0, 12]}"
138
+ end
139
+
140
+ def write(program)
141
+ path = @config.path(program.unit.generated)
142
+ FileUtils.mkdir_p(File.dirname(path))
143
+ File.binwrite(path, program.source)
144
+ File.write("#{path}.map.json", JSON.generate(program.map.to_h))
145
+ end
146
+
147
+ # Each value this template passes to a partial whose locals_sig types it, wrapped in that partial's check, as
148
+ # MappedWriter wraps. A value is checked only when every controller in the program renders the same partial.
149
+ def value_checks(template, source, controllers)
150
+ by_value = Hash.new { |h, k| h[k] = Set.new }
151
+ controllers.each do |controller|
152
+ @graph.arguments(template, source, controller).each do |callee, name, node|
153
+ by_value[[node.location.start_offset, node.location.length, name]] << callee
154
+ end
155
+ end
156
+ by_value.filter_map do |(offset, length, name), callees|
157
+ next unless callees.size == 1
158
+
159
+ callee = callees.first
160
+ next unless typed_locals(callee).include?(name)
161
+
162
+ [offset, length, "#{local_types_class(callee)}.check_#{name}("]
163
+ end
164
+ end
165
+
166
+ def typed_locals(path)
167
+ (@typed_locals ||= {})[path] ||= begin
168
+ contracts = Contracts.new(@sources.fetch(path), external: @config.contract(path))
169
+ contracts.strict_locals && !contracts.ignore_reason ? contracts.typed_names : []
170
+ end
171
+ end
172
+
173
+ # [context id, controllers, locals] for each program to generate. `locals` is nil for a template with
174
+ # strict locals, whose own declaration is the parameter list.
175
+ def plans(template, contracts, source)
176
+ usages = @graph.usages(template.path)
177
+ # Contexts guessed from a template nobody renders don't add to a template something real renders.
178
+ usages = usages.reject(&:guessed) if usages.any? { |u| !u.guessed }
179
+ pinned = @config.context_override(template.path)
180
+ usages = usages.select { |u| u.controller == pinned } if pinned
181
+ usages = [RenderGraph::Usage.new(controller: @config.default_context, locals: nil, caller: "none")] if usages.empty?
182
+ by_context = Hash.new { |h, k| h[k] = [] }
183
+ usages.each { |u| by_context[[context_for(u.controller), template_ivars(template.path, source, u.controller)]] << u }
184
+ # Literal callers say which locals a partial gets. Without one, an object or collection render may be what
185
+ # reaches it.
186
+ implicit = usages.none?(&:locals) ? object_locals(template) : []
187
+
188
+ by_context.flat_map do |(context, _ivars), context_usages|
189
+ controllers = context_usages.map(&:controller).uniq.sort
190
+ if contracts.strict_locals
191
+ [[context, controllers, nil]]
192
+ else
193
+ sets = context_usages.map(&:locals).compact.uniq
194
+ sets = [[]] if sets.empty?
195
+ sets.map { |set| (set + implicit).uniq.sort.grep(LOCAL_NAME) - KEYWORDS }.uniq
196
+ .map { |set| [context, controllers, set] }
197
+ end
198
+ end
199
+ end
200
+
201
+ # `render @post` and `render @posts` give `_post` the local `post`, and a collection its counter and iteration.
202
+ # erb_check can't follow those calls, so a partial no literal call reaches gets them, untyped.
203
+ def object_locals(template)
204
+ return [] unless template.partial?
205
+
206
+ name = File.basename(template.name).delete_prefix("_")
207
+ [name, "#{name}_counter", "#{name}_iteration"]
208
+ end
209
+
210
+ def context_for(controller)
211
+ (@registry.for_controller(controller) || @registry.for_controller(@config.default_context)).id
212
+ end
213
+
214
+ # Literal render calls against a strict-locals declaration: a required local not passed, or a local the
215
+ # template doesn't accept.
216
+ def check_callers(template, contracts)
217
+ return unless contracts.strict_locals
218
+
219
+ params = contracts.params
220
+ required = params.select { |p| p.kind == :required }.map(&:name)
221
+ accepted = params.map(&:name)
222
+ open = params.any? { |p| p.kind == :rest }
223
+ @graph.usages(template.path).filter_map { |u| [u.caller, u.locals] if u.locals }.uniq.each do |caller, locals|
224
+ path, line = caller.split(/:(\d+)\z/)
225
+ next unless line
226
+
227
+ missing = required - locals
228
+ # Rails passes a collection's `<as>_counter` and `<as>_iteration` only to a partial that declares them.
229
+ unknown = open ? [] : (locals - accepted).reject { |name| name.match?(/_(counter|iteration)\z/) }
230
+ if missing.any?
231
+ @findings << Finding.new(path: path.delete_prefix("#{@config.app_root}/"), line: line.to_i, column: 0, code: "ERB1001",
232
+ message: "Renders #{template.path} without required locals #{missing.join(', ')}")
233
+ end
234
+ next if unknown.empty?
235
+
236
+ @findings << Finding.new(path: path.delete_prefix("#{@config.app_root}/"), line: line.to_i, column: 0, code: "ERB1002",
237
+ message: "Renders #{template.path} with locals it doesn't declare: #{unknown.join(', ')}")
238
+ end
239
+ end
240
+
241
+ def program(template, source, contracts, context:, controllers:, locals:, receiver:)
242
+ ivars = receiver ? {} : template_ivars(template.path, source, controllers.first)
243
+ reads, = ivar_nodes(template.path, source)
244
+ digest = Digest::SHA256.hexdigest([template.path, context, locals, ivars].inspect)[0, 12]
245
+ generated = File.join(@config.output, "generated", "#{template.path}.#{digest}.rb")
246
+ # One template's engine output is the same in every context; only the header differs.
247
+ cached_source, result = @compiled[template.path]
248
+ unless cached_source == source
249
+ result = Backends.compile(source, format: template.format || ("html" if receiver), herb_formats: @herb_formats,
250
+ filename: template.path)
251
+ @compiled[template.path] = [source, result]
252
+ end
253
+ writer = MappedWriter.new(source)
254
+ writer.synthetic("# typed: #{contracts.typed}\n# Generated by erb_check from #{template.path}. Do not edit.\n")
255
+ if receiver
256
+ writer.synthetic("class ::#{receiver}\n def __erbcheck_template_#{digest}(__erbcheck_buffer)\n")
257
+ writer.synthetic(" @output_buffer = __erbcheck_buffer\n")
258
+ else
259
+ header(writer, contracts, digest:, context:, controllers:, locals:, ivars:)
260
+ end
261
+ @ivar_coverage[generated] = { "template" => template.path, "controllers" => controllers, "types" => ivars,
262
+ "read_names" => reads, "reads" => reads.size,
263
+ "typed_reads" => reads.count { |name| ivars.key?(name) } } unless receiver
264
+ wraps = receiver ? [] : value_checks(template, source, controllers)
265
+ writer.engine_output(result, wraps:).synthetic("\n end\nend\n")
266
+ Program.new(unit: Unit.new(template: template.path, context:, controllers: controllers.first(5), locals:, generated:),
267
+ source: writer.source, map: writer.source_map(template_path: template.path, generated_path: generated))
268
+ rescue CompileError => e
269
+ @findings << Finding.new(path: template.path, line: 1, column: 0, code: "ERB0001",
270
+ message: "erb_check couldn't compile this template: #{e.message}")
271
+ nil
272
+ end
273
+
274
+ def template_ivars(path, source, controller)
275
+ reads, writes = ivar_nodes(path, source)
276
+ (@ivar_flow&.types_for(path, controller) || {}).select do |name, _|
277
+ reads.include?(name) && !writes.include?(name) && name != "@output_buffer"
278
+ end
279
+ end
280
+
281
+ def ivar_nodes(path, source)
282
+ @ivar_nodes ||= {}
283
+ cached_source, result = @ivar_nodes[path]
284
+ return result if cached_source == source
285
+
286
+ reads = []
287
+ writes = []
288
+ visit = lambda do |node|
289
+ if node.is_a?(Prism::InstanceVariableReadNode)
290
+ reads << node.name.to_s
291
+ elsif node.class.name.start_with?("Prism::InstanceVariable") && node.respond_to?(:name)
292
+ writes << node.name.to_s
293
+ end
294
+ node.compact_child_nodes.each { |child| visit.call(child) }
295
+ end
296
+ visit.call(Prism.parse(::Herb.extract_ruby(source)).value)
297
+ @ivar_nodes[path] = [source, [reads, writes]]
298
+ [reads, writes]
299
+ end
300
+
301
+ def header(writer, contracts, digest:, context:, controllers:, locals:, ivars:)
302
+ shown = controllers.first(3).join(", ")
303
+ shown += " and #{controllers.size - 3} more" if controllers.size > 3
304
+ writer.synthetic("# Rendered by #{shown.empty? ? 'no known caller' : shown}.\n")
305
+ writer.synthetic("class ErbCheck::Generated::T#{digest} < ::ErbCheck::Contexts::#{context}\n")
306
+ unless ivars.empty?
307
+ writer.synthetic(" def initialize\n")
308
+ ivars.each { |name, type| writer.synthetic(" #{name} = T.let(T.unsafe(nil), #{type})\n") }
309
+ writer.synthetic(" end\n")
310
+ end
311
+ span = contracts.strict_locals
312
+ if (sig = contracts.locals_sig) && span
313
+ names = contracts.params.map(&:name)
314
+ writer.synthetic(" extend T::Sig\n sig { params(local_assigns: T::Hash[Symbol, T.untyped], output_buffer: T.untyped, ")
315
+ writer.contract(sig)
316
+ (names - contracts.typed_names).each { |name| writer.synthetic(", #{name}: T.untyped") }
317
+ writer.synthetic(", __erbcheck_block: T.untyped).returns(T.untyped) }\n")
318
+ end
319
+ writer.synthetic(" def __erbcheck_render(local_assigns, output_buffer")
320
+ if span
321
+ unless span.text.strip.empty?
322
+ writer.synthetic(", ")
323
+ writer.contract(span)
324
+ end
325
+ else
326
+ locals.each { |name| writer.synthetic(", #{name}:") }
327
+ end
328
+ writer.synthetic(", &__erbcheck_block)\n @output_buffer = output_buffer\n")
329
+ end
330
+
331
+ def slots_rbi
332
+ out = +"# typed: true\n# Generated by erb_check from the Rails snapshot. Do not edit.\n\n"
333
+ @snapshot.fetch("components").each do |component|
334
+ next if component["slot_methods"].empty?
335
+
336
+ out << "class ::#{component['name']}\n"
337
+ component["slot_methods"].each do |method|
338
+ if method["name"].end_with?("?")
339
+ out << " sig { returns(T::Boolean) }\n def #{method['name']}; end\n"
340
+ else
341
+ out << RbiMethod.new(method).lines(indent: " ").join("\n") << "\n"
342
+ end
343
+ end
344
+ out << "end\n\n"
345
+ end
346
+ out
347
+ end
348
+ end
349
+ end