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,393 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "monitor"
5
+ require "open3"
6
+ require "set"
7
+ require "uri"
8
+
9
+ module ErbCheck
10
+ # `erb_check lsp`: a language server for templates. It runs Sorbet's own (`srb tc --lsp`) and stands between
11
+ # it and the editor. Ruby files pass through untouched. When the editor opens or edits a template, the proxy
12
+ # compiles the unsaved text into the template's programs and hands those to Sorbet as open documents; Sorbet's
13
+ # diagnostics, hovers, definitions and completions on them come back at the template's own positions.
14
+ #
15
+ # Editors count columns in UTF-16 units and Sorbet counts bytes (`script/lsp_probe.rb`), so positions convert
16
+ # on the template side; generated positions stay in bytes, Sorbet's unit.
17
+ class LSP
18
+ POSITION_REQUESTS = %w[textDocument/hover textDocument/definition textDocument/typeDefinition textDocument/implementation
19
+ textDocument/references textDocument/documentHighlight textDocument/completion
20
+ textDocument/signatureHelp].freeze
21
+ DROP = Object.new.freeze
22
+
23
+ # Content-Length framed JSON-RPC over a pair of IOs.
24
+ class Transport
25
+ def initialize(input, output)
26
+ @input = input.binmode
27
+ @output = output.binmode
28
+ @lock = Mutex.new
29
+ end
30
+
31
+ def read
32
+ length = nil
33
+ while (line = @input.gets("\r\n"))
34
+ break if line == "\r\n"
35
+
36
+ length = line[/\AContent-Length:\s*(\d+)/i, 1]&.to_i || length
37
+ end
38
+ return unless length
39
+
40
+ JSON.parse(@input.read(length).force_encoding(Encoding::UTF_8))
41
+ end
42
+
43
+ def write(message)
44
+ json = JSON.generate(message.merge("jsonrpc" => "2.0"))
45
+ @lock.synchronize do
46
+ @output.write("Content-Length: #{json.bytesize}\r\n\r\n#{json}")
47
+ @output.flush
48
+ end
49
+ rescue IOError, Errno::EPIPE
50
+ nil
51
+ end
52
+ end
53
+
54
+ # A template's editor text, for converting between UTF-16 and byte columns.
55
+ class Text
56
+ attr_reader :source
57
+
58
+ def initialize(source)
59
+ @source = source.dup.force_encoding(Encoding::UTF_8)
60
+ @lines = @source.lines
61
+ end
62
+
63
+ def to_bytes(line, units)
64
+ count = bytes = 0
65
+ (@lines[line] || "").each_char do |char|
66
+ break if count >= units
67
+
68
+ count += char.ord > 0xFFFF ? 2 : 1
69
+ bytes += char.bytesize
70
+ end
71
+ bytes
72
+ end
73
+
74
+ def to_units(line, bytes)
75
+ (@lines[line] || "").byteslice(0, bytes).scrub.each_char.sum { |char| char.ord > 0xFFFF ? 2 : 1 }
76
+ end
77
+
78
+ def line_bytes(line)
79
+ (@lines[line] || "").chomp.bytesize
80
+ end
81
+ end
82
+
83
+ class ServerExited < StandardError; end
84
+
85
+ def initialize(config, input: $stdin, output: $stdout, log: $stderr)
86
+ @config = config
87
+ @client = Transport.new(input, output)
88
+ @log = log
89
+ @lock = Monitor.new
90
+ @texts = {} # template path => Text the programs were compiled from
91
+ @current = {} # template path => generated paths of its programs
92
+ @programs = {} # generated path => Program
93
+ @sent = {} # generated path => version sent to Sorbet
94
+ @found = Hash.new { |h, k| h[k] = {} } # template path => { generated path => diagnostics }
95
+ @own = Hash.new { |h, k| h[k] = [] } # template path => erb_check's own diagnostics
96
+ @pending = {} # request id => Program the request was moved into
97
+ end
98
+
99
+ def run
100
+ unless File.exist?(@config.output_path("snapshot.json"))
101
+ @log.puts "erb_check lsp: no snapshot at #{@config.output}/snapshot.json; run `erb_check snapshot` first."
102
+ return 1
103
+ end
104
+
105
+ @compiler = Compiler.new(@config).compile
106
+ @templates = @compiler.programs_by_template.keys.to_set
107
+ @compiler.programs_by_template.each do |path, programs|
108
+ @texts[path] = Text.new(File.binread(@config.path(path)))
109
+ @current[path] = programs.map { |p| p.unit.generated }
110
+ programs.each { |p| @programs[p.unit.generated] = p }
111
+ end
112
+ # A value checked against another template's locals_sig points at that template.
113
+ @compiler.local_type_programs.each { |p| @programs[p.unit.generated] = p }
114
+ @compiler.findings.clear
115
+ @log.puts "erb_check lsp: #{@programs.size} programs from #{@templates.size} templates"
116
+ if (changed = @compiler.changed_since_snapshot).any?
117
+ @log.puts "erb_check lsp: #{changed.first}#{' and others' if changed.size > 1} changed since the snapshot; run `erb_check snapshot` and restart."
118
+ end
119
+
120
+ config_args, dropped = @config.sorbet_config_seeing_output
121
+ if dropped.any?
122
+ @log.puts "erb_check lsp: Sorbet runs without sorbet/config's --ignore=#{dropped.join(',')} so it sees #{@config.output}/."
123
+ end
124
+ args = [*@config.sorbet, *config_args]
125
+ if (hiding = ignore_patterns(args).select { |p| @config.ignores_output?(p) }).any?
126
+ @log.puts "erb_check lsp: --ignore=#{hiding.join(',')} hides #{@config.output}/ from Sorbet, so templates won't be checked."
127
+ end
128
+ stdin, stdout, stderr, wait = Open3.popen3(*args, "--lsp", "--disable-watchman", chdir: @config.app_root)
129
+ Thread.new { stderr.each_line { |line| @log.write(line) } }
130
+ @server = Transport.new(stdout, stdin)
131
+ main = Thread.current
132
+ reader = Thread.new do
133
+ while (message = @server.read)
134
+ @lock.synchronize { from_server(message) }
135
+ end
136
+ main.raise(ServerExited) unless @exiting
137
+ end
138
+
139
+ while (message = @client.read)
140
+ @exiting = true if message["method"] == "exit"
141
+ @lock.synchronize { from_client(message) }
142
+ break if @exiting
143
+ end
144
+ stdin.close
145
+ wait.join(10) || Process.kill("TERM", wait.pid)
146
+ reader.kill
147
+ @exiting && wait.value.success? ? 0 : 1
148
+ rescue ServerExited
149
+ @log.puts "erb_check lsp: Sorbet exited"
150
+ 1
151
+ end
152
+
153
+ private
154
+
155
+ def ignore_patterns(args)
156
+ args.each_with_index.flat_map do |arg, i|
157
+ value = arg.start_with?("--ignore=") ? arg.delete_prefix("--ignore=") : (args[i + 1] if arg == "--ignore")
158
+ value.to_s.split(",")
159
+ end
160
+ end
161
+
162
+ # -- editor to Sorbet
163
+
164
+ def from_client(message)
165
+ uri = message.dig("params", "textDocument", "uri")
166
+ path = uri && template_path(uri)
167
+ if ruby_changed?(message, uri) && @compiler.forget_ivar_types
168
+ @texts.each { |template, text| sync(template, text.source) }
169
+ end
170
+ return @server.write(message) unless path || uri&.end_with?(".erb")
171
+
172
+ case message["method"]
173
+ when "textDocument/didOpen" then sync(path, message.dig("params", "textDocument", "text")) if path
174
+ when "textDocument/didChange"
175
+ sync(path, apply(@texts[path], message.dig("params", "contentChanges"))) if path
176
+ when "textDocument/didClose" then sync(path, File.binread(@config.path(path))) if path
177
+ when *POSITION_REQUESTS then forward_position(path, message)
178
+ else @client.write("id" => message["id"], "result" => nil) if message.key?("id")
179
+ end
180
+ end
181
+
182
+ def ruby_changed?(message, uri)
183
+ if message["method"] == "workspace/didChangeWatchedFiles"
184
+ return message.dig("params", "changes").to_a.any? { |change| change["uri"].match?(/\.(?:rb|rbi)\z/) }
185
+ end
186
+ return false unless uri&.match?(/\.(?:rb|rbi)\z/)
187
+ return true if message["method"] == "textDocument/didChange"
188
+ return false unless message["method"] == "textDocument/didOpen"
189
+
190
+ file = relative(uri)
191
+ file.nil? || !File.file?(@config.path(file)) ||
192
+ File.binread(@config.path(file)) != message.dig("params", "textDocument", "text").to_s.b
193
+ end
194
+
195
+ # Recompiles a template from `text` and puts its programs in front of Sorbet. A program that no longer exists
196
+ # (the template now opts out) is replaced by an empty file.
197
+ def sync(path, text)
198
+ text = Text.new(text)
199
+ @texts[path] = text
200
+ before = @compiler.findings.size
201
+ programs = @compiler.programs(@compiler.template(path), text.source)
202
+ failures = @compiler.findings.slice!(before..).select { |f| f.code == "ERB0001" && f.path == path }
203
+ generated = programs.map { |p| p.unit.generated }
204
+
205
+ removed = @current.fetch(path, []) - generated
206
+ removed.each do |gone|
207
+ send_document(gone, "# typed: ignore\n")
208
+ @found[path].delete(gone)
209
+ end
210
+ programs.each do |program|
211
+ @programs[program.unit.generated] = program
212
+ send_document(program.unit.generated, program.source)
213
+ end
214
+ @current[path] = generated
215
+ publish(path) unless removed.empty?
216
+
217
+ own = failures.map { |f| own_diagnostic(f.message, f.code) }
218
+ return if own == @own[path]
219
+
220
+ @own[path] = own
221
+ publish(path)
222
+ end
223
+
224
+ def send_document(generated, source)
225
+ text = source.dup.force_encoding(Encoding::UTF_8).scrub
226
+ uri = uri_for(generated)
227
+ if (version = @sent[generated])
228
+ @sent[generated] = version + 1
229
+ @server.write("method" => "textDocument/didChange",
230
+ "params" => { "textDocument" => { "uri" => uri, "version" => version + 1 }, "contentChanges" => [{ "text" => text }] })
231
+ else
232
+ @sent[generated] = 1
233
+ @server.write("method" => "textDocument/didOpen",
234
+ "params" => { "textDocument" => { "uri" => uri, "languageId" => "ruby", "version" => 1, "text" => text } })
235
+ end
236
+ end
237
+
238
+ # Applies the editor's changes: whole-text (what Sorbet asks for) or ranged.
239
+ def apply(text, changes)
240
+ changes.reduce(text.source) do |source, change|
241
+ next change["text"] unless change["range"]
242
+
243
+ current = Text.new(source)
244
+ start, finish = change["range"].values_at("start", "end").map do |pos|
245
+ offset = source.lines.first(pos["line"]).sum(&:bytesize)
246
+ offset + current.to_bytes(pos["line"], pos["character"])
247
+ end
248
+ source.byteslice(0, start) + change["text"] + source.byteslice(finish..)
249
+ end
250
+ end
251
+
252
+ # Moves a request at a template position into the first program whose copied code covers it. A position
253
+ # in the template's HTML has no Ruby to ask about.
254
+ def forward_position(path, message)
255
+ position = message.dig("params", "position")
256
+ text = @texts.fetch(path)
257
+ target = SourceMap::Position.new(line: position["line"] + 1, column: text.to_bytes(position["line"], position["character"]))
258
+ program, generated = @current.fetch(path, []).lazy.filter_map do |g|
259
+ (at = @programs[g].map.to_generated(target)) && [@programs[g], at]
260
+ end.first
261
+ return @client.write("id" => message["id"], "result" => nil) unless program
262
+
263
+ params = message["params"].merge("textDocument" => { "uri" => uri_for(program.unit.generated) },
264
+ "position" => { "line" => generated.line - 1, "character" => generated.column })
265
+ @pending[message["id"]] = program
266
+ @server.write(message.merge("params" => params))
267
+ end
268
+
269
+ # -- Sorbet to editor
270
+
271
+ def from_server(message)
272
+ if message["method"] == "textDocument/publishDiagnostics" && (program = program_for(message.dig("params", "uri")))
273
+ found(program, message.dig("params", "diagnostics"))
274
+ elsif message.key?("result") && !message.key?("method")
275
+ result = map_value(message["result"], @pending.delete(message["id"]))
276
+ @client.write(message.merge("result" => result.equal?(DROP) ? nil : result))
277
+ else
278
+ @client.write(message)
279
+ end
280
+ end
281
+
282
+ def found(program, diagnostics)
283
+ path = program.unit.template
284
+ return unless @current.fetch(path, []).include?(program.unit.generated)
285
+
286
+ @found[path][program.unit.generated] = diagnostics.map { |d| map_diagnostic(program, d) }
287
+ publish(path)
288
+ end
289
+
290
+ def publish(path)
291
+ diagnostics = (@own[path] + @found[path].values.flatten).uniq { |d| [d["range"], d["message"]] }
292
+ @client.write("method" => "textDocument/publishDiagnostics",
293
+ "params" => { "uri" => uri_for(path), "diagnostics" => diagnostics })
294
+ end
295
+
296
+ def map_diagnostic(program, diagnostic)
297
+ from, to = diagnostic["range"].values_at("start", "end")
298
+ line = from["line"] + 1
299
+ last = to["line"] == from["line"] ? [to["character"] - 1, from["character"]].max : from["character"]
300
+ start = program.map.locate(line, from["character"], last)
301
+ start ||= program.map.next_code(line) if diagnostic["code"].to_s == Diagnostics::UNREACHABLE
302
+ # Sorbet's quick fixes edit generated code, so the proxy doesn't offer them.
303
+ message = Diagnostics.normalize(diagnostic["message"]).delete_suffix(" (fix available)")
304
+ unless start
305
+ return own_diagnostic("erb_check generated code Sorbet rejected (#{program.unit.generated}:#{line}): #{message}",
306
+ Diagnostics::COMPILER_FAILURE)
307
+ end
308
+
309
+ finish = to["line"] == from["line"] && program.map.to_template(SourceMap::Position.new(line:, column: to["character"]), end_of_range: true)
310
+ text = @texts.fetch(program.unit.template)
311
+ unless finish && finish.line == start.line && finish.column > start.column
312
+ width = [last - from["character"] + 1, 1].max
313
+ finish = SourceMap::Position.new(line: start.line, column: [start.column + width, text.line_bytes(start.line - 1)].min)
314
+ end
315
+ related = diagnostic["relatedInformation"] && map_value(diagnostic["relatedInformation"], nil)
316
+ diagnostic.merge("range" => lsp_range(text, start, finish), "message" => message,
317
+ "relatedInformation" => related.equal?(DROP) ? nil : related).compact
318
+ end
319
+
320
+ # Moves every location in a response that points into a generated program to its template. `doc` is the
321
+ # program a bare range belongs to (the request's document). A location that lands in synthetic code is
322
+ # dropped; an optional range (a hover's) is left out.
323
+ def map_value(value, doc)
324
+ case value
325
+ when Array then value.map { |v| map_value(v, doc) }.reject { |v| v.equal?(DROP) }
326
+ when Hash
327
+ uri_key = %w[uri targetUri].find { |k| value[k].is_a?(String) }
328
+ here = uri_key ? program_for(value[uri_key]) : doc
329
+ value.each_with_object({}) do |(key, v), out|
330
+ scope = key == "originSelectionRange" ? doc : here
331
+ if range?(v) && scope
332
+ mapped = template_range(scope, v)
333
+ return DROP if mapped.nil? && %w[range targetRange].include?(key) && !value.key?("contents")
334
+
335
+ out[key] = mapped if mapped
336
+ elsif key == uri_key && here
337
+ out[key] = uri_for(here.unit.template)
338
+ else
339
+ mapped = map_value(v, here)
340
+ out[key] = mapped unless mapped.equal?(DROP)
341
+ end
342
+ end
343
+ else value
344
+ end
345
+ end
346
+
347
+ def template_range(program, range)
348
+ from, to = range.values_at("start", "end")
349
+ start = program.map.to_template(SourceMap::Position.new(line: from["line"] + 1, column: from["character"]))
350
+ return unless start
351
+
352
+ finish = program.map.to_template(SourceMap::Position.new(line: to["line"] + 1, column: to["character"]), end_of_range: true)
353
+ finish = start unless finish && (finish.line > start.line || finish.column >= start.column)
354
+ lsp_range(@texts.fetch(program.unit.template), start, finish)
355
+ end
356
+
357
+ def lsp_range(text, start, finish)
358
+ { "start" => { "line" => start.line - 1, "character" => text.to_units(start.line - 1, start.column) },
359
+ "end" => { "line" => finish.line - 1, "character" => text.to_units(finish.line - 1, finish.column) } }
360
+ end
361
+
362
+ # erb_check's own error, on the template's first line.
363
+ def own_diagnostic(message, code)
364
+ { "range" => { "start" => { "line" => 0, "character" => 0 }, "end" => { "line" => 0, "character" => 0 } },
365
+ "severity" => 1, "source" => "erb_check", "code" => code.to_s, "message" => message }
366
+ end
367
+
368
+ def range?(value)
369
+ value.is_a?(Hash) && value["start"].is_a?(Hash) && value["end"].is_a?(Hash) && value.size == 2
370
+ end
371
+
372
+ # -- paths
373
+
374
+ def relative(uri)
375
+ return unless uri.start_with?("file://")
376
+
377
+ path = URI.decode_uri_component(uri.delete_prefix("file://"))
378
+ path.delete_prefix("#{@config.app_root}/") if path.start_with?("#{@config.app_root}/")
379
+ end
380
+
381
+ def template_path(uri)
382
+ (path = relative(uri)) && @templates.include?(path) ? path : nil
383
+ end
384
+
385
+ def program_for(uri)
386
+ (path = relative(uri)) && @programs[path]
387
+ end
388
+
389
+ def uri_for(path)
390
+ "file://" + @config.path(path).split("/").map { |part| URI.encode_uri_component(part) }.join("/")
391
+ end
392
+ end
393
+ end
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ErbCheck
4
+ class CompileError < StandardError; end
5
+
6
+ # Builds a generated program from synthetic text and Ruby copied from a template, recording where each
7
+ # copied byte came from.
8
+ class MappedWriter
9
+ attr_reader :source
10
+
11
+ def initialize(template_source)
12
+ @template = template_source.b
13
+ @source = +"".b
14
+ @segments = []
15
+ end
16
+
17
+ def synthetic(text)
18
+ @source << text.b
19
+ self
20
+ end
21
+
22
+ # Writes a contract's text: copied from the template at its offset, or synthetic when it came from config.
23
+ def contract(span)
24
+ span.offset ? copy(span.offset, span.text.bytesize) : synthetic(span.text)
25
+ end
26
+
27
+ # Copies the template's bytes at `offset`.
28
+ def copy(offset, length)
29
+ @segments << SourceMap::Segment.new(generated: @source.bytesize, template: offset, length:)
30
+ @source << @template.byteslice(offset, length)
31
+ self
32
+ end
33
+
34
+ # Appends an engine's output, mapping each recorded fragment to where it sits in the template. The engines
35
+ # emit fragments in template order, so each is looked for after the previous one, in the template's Ruby.
36
+ # `wraps` are [template offset, length, prefix]: that copied code is written as `prefix<code>)`, still mapped
37
+ # to its own bytes. Wraps that overlap an earlier one, or straddle a fragment's edge, are skipped.
38
+ def engine_output(result, wraps: [])
39
+ src = result.src.b
40
+ emitted = 0
41
+ cursor = 0
42
+ wraps = non_overlapping(wraps)
43
+ result.fragments.each do |fragment|
44
+ code = fragment.code.b
45
+ found = CodeSearch.find(result.ruby, code, cursor)
46
+ raise CompileError, "couldn't find #{fragment.code.inspect} in the template after byte #{cursor}" unless found
47
+
48
+ synthetic(src.byteslice(emitted, fragment.offset - emitted))
49
+ finish = found + code.bytesize
50
+ inside = wraps.select { |offset, length, _| offset >= found && offset + length <= finish }
51
+ if inside.empty? || @template.byteslice(found, code.bytesize) != code
52
+ @segments << SourceMap::Segment.new(generated: @source.bytesize, template: found, length: code.bytesize)
53
+ @source << code
54
+ else
55
+ position = found
56
+ inside.each do |offset, length, prefix|
57
+ copy(position, offset - position) if offset > position
58
+ synthetic(prefix).copy(offset, length).synthetic(")")
59
+ position = offset + length
60
+ end
61
+ copy(position, finish - position) if finish > position
62
+ end
63
+ emitted = fragment.offset + code.bytesize
64
+ cursor = finish
65
+ end
66
+ synthetic(src.byteslice(emitted..))
67
+ end
68
+
69
+ def source_map(template_path:, generated_path:)
70
+ SourceMap.new(template_path:, generated_path:, segments: @segments,
71
+ template_source: @template, generated_source: @source)
72
+ end
73
+
74
+ private
75
+
76
+ def non_overlapping(wraps)
77
+ wraps.sort_by(&:first).each_with_object([]) do |wrap, kept|
78
+ kept << wrap if kept.empty? || wrap[0] >= kept.last[0] + kept.last[1]
79
+ end
80
+ end
81
+ end
82
+ end