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,268 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "prism"
4
+ require "digest"
5
+
6
+ module ErbCheck
7
+ # A deliberately small interpreter for controller writes, not a Ruby type inferencer. A missing
8
+ # value means unknown, including on a branch that never assigns it. Only Sorbet supplies types.
9
+ # States are recorded at render calls, not at the end of methods that may already have rendered.
10
+ class IvarFlow
11
+ State = Data.define(:values, :rendered, :returned)
12
+
13
+ def initialize(config, snapshot, graph)
14
+ @config, @graph = config, graph
15
+ @controllers = snapshot.fetch("controllers").to_h { |c| [c["name"], c] }
16
+ @trees = {}
17
+ @digests = {}
18
+ @records = Hash.new { |h, k| h[k] = [] }
19
+ @valid = @graph.rendering_controllers.filter_map { |name| @controllers[name] }.select { |c| fresh?(c["ivar_flow"]) }
20
+ files = @valid.flat_map { |c| c["ivar_flow"]["sources"].keys }.uniq
21
+ @types = IvarTypes.new(config, files).types
22
+ @valid.each { |controller| analyze(controller) }
23
+ end
24
+
25
+ # A graph edge without a modeled execution is unknown, even if another action sets the ivar.
26
+ # Template-to-template edges and layouts currently stay untyped: a view/helper may mutate state.
27
+ def types_for(path, controller)
28
+ usages = @graph.usages(path).select { |u| u.controller == controller && !u.guessed }
29
+ return {} if usages.empty?
30
+
31
+ incoming = usages.flat_map do |usage|
32
+ key = [controller, usage.caller]
33
+ return {} unless @records.key?(key)
34
+
35
+ @records[key]
36
+ end
37
+ join_values(incoming)
38
+ end
39
+
40
+ private
41
+
42
+ def fresh?(metadata)
43
+ metadata && metadata["sources"].all? do |path, digest|
44
+ file = @config.path(path)
45
+ File.file?(file) && (@digests[file] ||= Digest::SHA256.file(file).hexdigest) == digest
46
+ end
47
+ end
48
+
49
+ def analyze(controller)
50
+ @controller = controller
51
+ @metadata = controller.fetch("ivar_flow")
52
+ @memo = {}
53
+ controller["actions"].each do |action|
54
+ @stack = []
55
+ implicit = [controller["name"], "#{controller['name']}##{action}"]
56
+ @records[implicit] # An empty list is a proven unreachable implicit render.
57
+ callbacks = @metadata["callbacks"]
58
+ states = [state]
59
+ callbacks.reject { |c| c["kind"] == "after" }.each do |callback|
60
+ applies = applicability(callback, action)
61
+ next if applies == false
62
+
63
+ if callback["kind"] == "around"
64
+ # Nothing before an unknown around callback survives its pre-yield code. If it yields,
65
+ # subsequent callbacks/actions execute from unknown state; Rails performs even implicit
66
+ # rendering inside that yield, before the wrapper resumes. The wrapper's own renders are
67
+ # unmodeled edges, so they cannot borrow these action facts.
68
+ states = states.map { |s| state({}, s.rendered, s.returned) }
69
+ next
70
+ end
71
+
72
+ # Arbitrary predicate execution can write ivars. Model symbol predicates for their effects;
73
+ # unknown blocks clear facts. Both the skipped and taken paths remain possible.
74
+ %w[if unless].each do |kind|
75
+ callback.fetch(kind).reject { |c| c.key?("actions") }.each do |condition|
76
+ states = invoke(condition["method"], states)
77
+ end
78
+ end
79
+ taken = invoke(callback["method"], states)
80
+ states = merge(applies.nil? ? states + taken : taken)
81
+ states = states.reject(&:rendered).map { |s| state(s.values) }
82
+ end
83
+ invoke(action, states).each do |s|
84
+ @records[implicit] << s.values unless s.rendered
85
+ end
86
+ end
87
+ end
88
+
89
+ def applicability(callback, action)
90
+ unknown = false
91
+ %w[if unless].each do |kind|
92
+ callback.fetch(kind).each do |condition|
93
+ if condition.key?("actions")
94
+ matches = condition["actions"].include?(action)
95
+ return false if kind == "if" ? !matches : matches
96
+ else
97
+ unknown = true
98
+ end
99
+ end
100
+ end
101
+ unknown ? nil : true
102
+ end
103
+
104
+ def definition(name)
105
+ location = @metadata["methods"][name]
106
+ return unless location
107
+
108
+ file, line = location
109
+ definitions = (@trees[file] ||= begin
110
+ found = {}
111
+ walk(Prism.parse_file(@config.path(file)).value) do |node|
112
+ next unless node.is_a?(Prism::DefNode) && node.receiver.nil?
113
+
114
+ key = [node.name.to_s, node.location.start_line]
115
+ found[key] = found.key?(key) ? nil : node
116
+ end
117
+ found
118
+ end)
119
+ node = definitions[[name, line]]
120
+ [file, node] if node
121
+ end
122
+
123
+ def invoke(name, states)
124
+ key = [name, states]
125
+ return @memo[key] if @memo.key?(key)
126
+
127
+ found = name && definition(name)
128
+ return states.map { |s| state({}, s.rendered, s.returned) } unless found && !@stack.include?(name)
129
+
130
+ file, node = found
131
+ @stack << name
132
+ previous = @file
133
+ @file = file
134
+ result = execute(node.body, states.map { |s| state(s.values, s.rendered) })
135
+ @file = previous
136
+ @stack.pop
137
+ @memo[key] = result.map { |s| state(s.values, s.rendered) }
138
+ end
139
+
140
+ def execute(node, states)
141
+ return states unless node
142
+
143
+ stopped, active = states.partition(&:returned)
144
+ return states if active.empty?
145
+
146
+ result = case node
147
+ when Prism::StatementsNode
148
+ node.body.reduce(active) { |list, child| execute(child, list) }
149
+ when Prism::InstanceVariableWriteNode
150
+ execute(node.value, active).map do |s|
151
+ next s if s.returned
152
+
153
+ value = @types[[@file, node.location.start_offset]]
154
+ state(s.values.merge(node.name.to_s => value), s.rendered, s.returned)
155
+ end
156
+ when Prism::IfNode, Prism::UnlessNode
157
+ tested = execute(node.predicate, active)
158
+ other = node.is_a?(Prism::IfNode) ? node.subsequent : node.else_clause
159
+ truthy, falsey = branches(node.predicate, tested)
160
+ truthy, falsey = falsey, truthy if node.is_a?(Prism::UnlessNode)
161
+ merge(execute(node.statements, truthy) + execute(other, falsey))
162
+ when Prism::ElseNode
163
+ execute(node.statements, active)
164
+ when Prism::AndNode, Prism::OrNode
165
+ left = execute(node.left, active)
166
+ merge(left + execute(node.right, left))
167
+ when Prism::ReturnNode
168
+ execute(node.arguments, active).map { |s| state(s.values, s.rendered, true) }
169
+ when Prism::CallNode
170
+ call(node, active)
171
+ when Prism::BeginNode, Prism::WhileNode, Prism::UntilNode, Prism::ForNode, Prism::CaseNode,
172
+ Prism::CaseMatchNode, Prism::MultiWriteNode, Prism::InstanceVariableOrWriteNode,
173
+ Prism::InstanceVariableAndWriteNode, Prism::InstanceVariableOperatorWriteNode,
174
+ Prism::YieldNode, Prism::SuperNode, Prism::ForwardingSuperNode,
175
+ Prism::DefNode, Prism::ClassNode, Prism::ModuleNode, Prism::LambdaNode, Prism::DefinedNode
176
+ unknown(node, active)
177
+ else
178
+ node.compact_child_nodes.reduce(active) { |list, child| execute(child, list) }
179
+ end
180
+ merge(stopped + result)
181
+ end
182
+
183
+ def call(node, states)
184
+ return unknown(node, states) if node.block
185
+
186
+ states = execute(node.receiver, states)
187
+ states = execute(node.arguments, states)
188
+ stopped, states = states.partition(&:returned)
189
+ merge(stopped + dispatch(node, states))
190
+ end
191
+
192
+ def dispatch(node, states)
193
+ return unknown(node, states) if node.receiver.is_a?(Prism::LocalVariableReadNode) ||
194
+ contains?(node.arguments, Prism::SelfNode)
195
+ return states unless node.receiver.nil? || node.receiver.is_a?(Prism::SelfNode)
196
+
197
+ case node.name
198
+ when :render, :render_to_string
199
+ states = states.reject(&:rendered) if node.name == :render
200
+ key = [@controller["name"], "#{@config.path(@file)}:#{node.location.start_line}"]
201
+ @records[key].concat(states.map(&:values))
202
+ states.map { |s| state(s.values, s.rendered || node.name == :render, s.returned) }
203
+ when :redirect_to, :redirect_back, :head
204
+ states.map { |s| state(s.values, true, s.returned) }
205
+ when :raise, :fail
206
+ []
207
+ else
208
+ invoke(node.name.to_s, states)
209
+ end
210
+ end
211
+
212
+ def unknown(node, states)
213
+ # A render inside unsupported control flow contributes an unknown path. Preserve that fact even
214
+ # when a later supported assignment recovers useful facts for the action's implicit render.
215
+ walk(node) do |child|
216
+ next unless child.is_a?(Prism::CallNode) && %i[render render_to_string].include?(child.name)
217
+
218
+ @records[[@controller["name"], "#{@config.path(@file)}:#{child.location.start_line}"]] << {}
219
+ end
220
+ result = states.map { |s| state({}, s.rendered, s.returned) }
221
+ result += states.map { |s| state({}, s.rendered, true) } if contains?(node, Prism::ReturnNode)
222
+ result
223
+ end
224
+
225
+ def branches(predicate, states)
226
+ return [states, []] if predicate.is_a?(Prism::TrueNode)
227
+ return [[], states] if predicate.is_a?(Prism::FalseNode) || predicate.is_a?(Prism::NilNode)
228
+
229
+ # Don't carry a nullable type past a guard we haven't proved. In particular, missing guard
230
+ # analysis must not create a nil error after `return unless @order` or `@order.present?`.
231
+ reads = []
232
+ walk(predicate) { |n| reads << n.name.to_s if n.is_a?(Prism::InstanceVariableReadNode) }
233
+ widened = states.map { |s| state(s.values.reject { |name, _| reads.include?(name) }, s.rendered, s.returned) }
234
+ [widened, widened]
235
+ end
236
+
237
+ def contains?(node, klass)
238
+ node && (node.is_a?(klass) || node.compact_child_nodes.any? { |child| contains?(child, klass) })
239
+ end
240
+
241
+ def state(values = {}, rendered = false, returned = false)
242
+ State.new(values:, rendered:, returned:)
243
+ end
244
+
245
+ def merge(states)
246
+ states.group_by { |s| [s.rendered, s.returned] }.map do |(rendered, returned), group|
247
+ state(join_values(group.map(&:values)), rendered, returned)
248
+ end
249
+ end
250
+
251
+ def join_values(values)
252
+ return {} if values.empty?
253
+
254
+ values.first.keys.each_with_object({}) do |name, result|
255
+ types = values.map { |v| v[name] }
256
+ next if types.any?(&:nil?)
257
+
258
+ types = types.uniq.sort
259
+ result[name] = types.size == 1 ? types.first : "T.any(#{types.join(', ')})"
260
+ end
261
+ end
262
+
263
+ def walk(node, &block)
264
+ yield node
265
+ node.compact_child_nodes.each { |child| walk(child, &block) }
266
+ end
267
+ end
268
+ end
@@ -0,0 +1,144 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "fileutils"
5
+ require "open3"
6
+ require "prism"
7
+
8
+ module ErbCheck
9
+ # Ask Sorbet about assignment values in their original lexical and local-variable scope. The probe
10
+ # run replaces each original file with one temporary copy; it never changes application files or
11
+ # feeds duplicate method definitions to Sorbet. Only ordinary, reusable type expressions escape it.
12
+ class IvarTypes
13
+ def initialize(config, files)
14
+ @config = config
15
+ @files = files
16
+ end
17
+
18
+ def types
19
+ return {} if @files.empty?
20
+
21
+ dir = @config.output_path("ivar_probes")
22
+ FileUtils.rm_rf(dir)
23
+ FileUtils.mkdir_p(dir)
24
+ sites = {}
25
+ originals = []
26
+ @files.each do |path|
27
+ source = File.binread(@config.path(path))
28
+ next if source.match?(/^# typed: ignore\b/)
29
+
30
+ parsed = Prism.parse(source)
31
+ next unless parsed.success?
32
+
33
+ nodes = assignments(parsed.value)
34
+ next if nodes.empty?
35
+
36
+ originals << path
37
+ generated = File.join(dir, "#{Digest::SHA256.hexdigest(path)[0, 16]}.rb")
38
+ out = +"# typed: true\n".b
39
+ cursor = 0
40
+ nodes.each do |node|
41
+ value = node.value
42
+ out << source.byteslice(cursor...value.location.start_offset)
43
+ out << "T.reveal_type(\n"
44
+ sites[[generated, out.count("\n")]] = [path, node.location.start_offset]
45
+ out << value.slice.b << "\n)"
46
+ cursor = value.location.end_offset
47
+ end
48
+ out << source.byteslice(cursor..)
49
+ # The first sigil wins; remove the source's old sigil, retaining line counts.
50
+ out = out.sub(/(?<=\n)# typed: (?:ignore|false|true|strict|strong)/, "# original typed sigil")
51
+ File.binwrite(generated, out)
52
+ end
53
+ return {} if sites.empty?
54
+
55
+ ignores = originals.map { |path| "--ignore=/#{path}" }
56
+ output, = Open3.capture2e(*@config.sorbet, *ignores, *sites.keys.map(&:first).uniq,
57
+ "--no-error-count", chdir: @config.app_root)
58
+ found = {}
59
+ output.each_line do |line|
60
+ next unless (match = line.match(/\A(.+\.rb):(\d+): Revealed type: `([^`]+)`/))
61
+
62
+ site = sites[[File.expand_path(match[1], @config.app_root), match[2].to_i]]
63
+ type = self.class.type_expression(match[3])
64
+ found[site] = type if site && type
65
+ end
66
+ # A valid display type may still name a private constant or omit generic arguments. Ask Sorbet
67
+ # which expressions are legal outside the controller before putting them in a template header.
68
+ usable = validate(found.values.uniq, dir, ignores, sites.keys.map(&:first).uniq)
69
+ found.select { |_, type| usable.include?(type) }
70
+ ensure
71
+ FileUtils.rm_rf(dir) if dir
72
+ end
73
+
74
+ # Widen literal types, and reject Sorbet's display-only syntax (shapes, tuples, attached classes,
75
+ # type members, etc.). Unknowns, even inside a container or union, stay unknown.
76
+ def self.type_expression(text)
77
+ text = text.gsub(/\b(?:String|Integer|Float|Symbol)\([^()]*\)/) { |s| s.split("(").first }
78
+ text = text.gsub(/\b(?:TrueClass|FalseClass)\b/, "T::Boolean")
79
+ return if text.include?("T.untyped")
80
+
81
+ parsed = Prism.parse(text)
82
+ return unless parsed.success?
83
+
84
+ qualify(parsed.value.statements.body.first)
85
+ end
86
+
87
+ def self.qualify(node)
88
+ case node
89
+ when Prism::ConstantReadNode, Prism::ConstantPathNode
90
+ name = node.full_name.delete_prefix("::")
91
+ return if %w[T.attached_class T.self_type].include?(name)
92
+
93
+ "::#{name}"
94
+ when Prism::CallNode
95
+ args = node.arguments&.arguments || []
96
+ if node.receiver&.slice == "T" && %i[any nilable].include?(node.name)
97
+ types = args.map { |arg| qualify(arg) }
98
+ "T.#{node.name}(#{types.join(', ')})" if types.all?
99
+ elsif node.name == :[] && node.receiver&.slice&.match?(/\AT::(?:Array|Hash|Set|Enumerable|Enumerator|Range|Class)\z/)
100
+ types = args.map { |arg| qualify(arg) }
101
+ "#{node.receiver.slice}[#{types.join(', ')}]" if types.all?
102
+ end
103
+ end
104
+ end
105
+
106
+ private
107
+
108
+ def validate(types, dir, ignores, probes)
109
+ return [] if types.empty?
110
+
111
+ file = File.join(dir, "types.rb")
112
+ File.write(file, "# typed: true\n" + types.map { |type| "T.let(T.unsafe(nil), #{type})\n" }.join)
113
+ output, = Open3.capture2e(*@config.sorbet, *ignores, *probes, file,
114
+ "--no-error-count", chdir: @config.app_root)
115
+ rejected = output.each_line.filter_map do |line|
116
+ match = line.match(/\A(.+\.rb):(\d+): /)
117
+ match[2].to_i - 2 if match && File.expand_path(match[1], @config.app_root) == file
118
+ end
119
+ types.each_with_index.filter_map { |type, index| type unless rejected.include?(index) }
120
+ end
121
+
122
+ def assignments(node)
123
+ if node.is_a?(Prism::InstanceVariableWriteNode)
124
+ # No nested probes; ivar/local receivers may depend on state that Sorbet doesn't know at the
125
+ # actual action/callback invocation. Leave those for a future flow-sensitive probe adapter.
126
+ return safe_value?(node.value) ? [node] : []
127
+ end
128
+
129
+ node.compact_child_nodes.flat_map { |child| assignments(child) }
130
+ end
131
+
132
+ def safe_value?(node)
133
+ return false if node.is_a?(Prism::InstanceVariableReadNode) || node.is_a?(Prism::LocalVariableReadNode) ||
134
+ node.is_a?(Prism::InstanceVariableWriteNode) || node.is_a?(Prism::BlockNode) ||
135
+ node.is_a?(Prism::IfNode) || node.is_a?(Prism::UnlessNode) || node.is_a?(Prism::CaseNode) ||
136
+ node.is_a?(Prism::BeginNode) || node.is_a?(Prism::AndNode) || node.is_a?(Prism::OrNode) ||
137
+ node.is_a?(Prism::ReturnNode)
138
+ # Projected ActiveRecord rows can expose columns absent from the model's nominal RBI type.
139
+ return false if node.is_a?(Prism::CallNode) && %i[select reselect find_by_sql].include?(node.name)
140
+
141
+ node.compact_child_nodes.all? { |child| safe_value?(child) }
142
+ end
143
+ end
144
+ end