rblean 0.0.1

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,243 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RbLean
4
+ # A named document kept open on the server (advanced API). Each document has
5
+ # its own Lean worker process, which reuses the unchanged prefix when the
6
+ # text is edited. The name only makes the URI: nothing is written to disk.
7
+ #
8
+ # Every operation that talks to Lean runs under the document's lock as
9
+ # "send text -> wait -> ask", so another thread cannot swap the text between
10
+ # the elaboration and the question.
11
+ class Document
12
+ attr_reader :name, :uri
13
+
14
+ # @api private
15
+ def initialize(server, name, uri, text, scratch: false)
16
+ @server = server
17
+ @name = name
18
+ @uri = uri
19
+ @scratch = scratch
20
+ @lock = Mutex.new
21
+ @diag_lock = Mutex.new
22
+ @text = text.to_s.dup.freeze
23
+ @version = 0 # version last sent to Lean (0: not opened)
24
+ @sent_text = nil
25
+ @resend = false # set after a timeout: bump the version next time
26
+ @opened = false
27
+ @closed = false
28
+ @diagnostics = {} # version => raw LSP diagnostics
29
+ end
30
+
31
+ def text = @lock.synchronize { @text }
32
+
33
+ # LSP version of the text last sent to Lean (0 before the first send).
34
+ def version = @lock.synchronize { @version }
35
+
36
+ def scratch? = @scratch
37
+
38
+ def closed? = @closed || @server.closed?
39
+
40
+ # Replaces the text and sends it to Lean. Does not wait for elaboration.
41
+ def update(text)
42
+ @lock.synchronize do
43
+ ensure_usable!
44
+ @text = text.to_s.dup.freeze
45
+ sync!
46
+ end
47
+ self
48
+ end
49
+
50
+ # Waits until the current text is elaborated and returns its Result.
51
+ def elaborate(timeout: nil)
52
+ @lock.synchronize do
53
+ ensure_usable!
54
+ sync!
55
+ wait!(timeout)
56
+ build_result
57
+ end
58
+ end
59
+
60
+ # Tactic goals at a position ([] when there are none). Waits for the
61
+ # current text to be elaborated first.
62
+ def goals(line:, column:, timeout: nil)
63
+ @lock.synchronize do
64
+ ensure_usable!
65
+ sync!
66
+ wait!(timeout)
67
+ query_goals(line, column, timeout)
68
+ end
69
+ end
70
+
71
+ # Type and docstring at a position, or nil.
72
+ def hover(line:, column:, timeout: nil)
73
+ @lock.synchronize do
74
+ ensure_usable!
75
+ sync!
76
+ wait!(timeout)
77
+ query_hover(line, column, timeout)
78
+ end
79
+ end
80
+
81
+ # Closes the document on the Lean side (its worker process ends too).
82
+ def close
83
+ @lock.synchronize do
84
+ return if @closed
85
+
86
+ @closed = true
87
+ begin
88
+ @server.protocol.notify("textDocument/didClose", { "textDocument" => { "uri" => uri } }) if @opened && !@server.closed?
89
+ rescue Error
90
+ nil
91
+ end
92
+ end
93
+ @server.__send__(:forget, self)
94
+ nil
95
+ end
96
+
97
+ def inspect = "#<RbLean::Document #{name} version=#{@version}>"
98
+
99
+ # --- used by Result -----------------------------------------------------
100
+
101
+ # @api private
102
+ def goals_at(version, source, line:, column:)
103
+ @lock.synchronize do
104
+ restore!(version, source)
105
+ query_goals(line, column, nil)
106
+ end
107
+ end
108
+
109
+ # @api private
110
+ def hover_at(version, source, line:, column:)
111
+ @lock.synchronize do
112
+ restore!(version, source)
113
+ query_hover(line, column, nil)
114
+ end
115
+ end
116
+
117
+ # --- used by Server's reader thread ---------------------------------------
118
+
119
+ # @api private
120
+ def receive_diagnostics(version, diagnostics)
121
+ @diag_lock.synchronize do
122
+ current = @version
123
+ # A notification without a version belongs to the newest text sent.
124
+ version ||= current
125
+ # Diagnostics of an older version are dropped.
126
+ next if version < current
127
+
128
+ @diagnostics.delete_if { |v, _| v < version }
129
+ @diagnostics[version] = diagnostics
130
+ end
131
+ end
132
+
133
+ # @api private
134
+ # Called by the server after a restart of the process (0.2) or by tests.
135
+ def mark_for_resend! = @lock.synchronize { @resend = true }
136
+
137
+ private
138
+
139
+ def ensure_usable!
140
+ raise ClosedError, "document #{name} is closed" if @closed
141
+
142
+ @server.__send__(:ensure_open!)
143
+ end
144
+
145
+ def timeout_for(timeout) = timeout || @server.timeout
146
+
147
+ # Sends the current text if Lean does not have it yet.
148
+ def sync!
149
+ return if @opened && !@resend && @sent_text.equal?(@text)
150
+
151
+ protocol = @server.protocol
152
+ @version += 1
153
+ @diag_lock.synchronize { @diagnostics.delete_if { |v, _| v < @version } }
154
+ if @opened
155
+ protocol.notify("textDocument/didChange", {
156
+ "textDocument" => { "uri" => uri, "version" => @version },
157
+ "contentChanges" => [{ "text" => @text }]
158
+ })
159
+ else
160
+ protocol.notify("textDocument/didOpen", {
161
+ "textDocument" => { "uri" => uri, "languageId" => "lean4", "version" => @version, "text" => @text }
162
+ })
163
+ @opened = true
164
+ end
165
+ @sent_text = @text
166
+ @resend = false
167
+ end
168
+
169
+ # Waits until every diagnostic of the current version has arrived. Lean
170
+ # sends them before answering, and the reader handles messages in order.
171
+ def wait!(timeout)
172
+ seconds = timeout_for(timeout)
173
+ @server.protocol.request("textDocument/waitForDiagnostics",
174
+ { "uri" => uri, "version" => @version }, timeout: seconds)
175
+ rescue TimeoutError
176
+ @resend = true
177
+ raise TimeoutError.new("elaborate", seconds)
178
+ end
179
+
180
+ # Makes Lean hold +source+ at +version+ again (for an older Result).
181
+ def restore!(version, source)
182
+ ensure_usable!
183
+ return if @opened && !@resend && @version == version && @sent_text == source
184
+
185
+ @text = source
186
+ sync!
187
+ wait!(nil)
188
+ end
189
+
190
+ def build_result
191
+ lines = Internal::Positions.lines(@text)
192
+ raw = @diag_lock.synchronize { @diagnostics[@version] } || []
193
+ messages = raw.map { |d| self.class.message_from_lsp(lines, d) }
194
+ messages.sort_by! { |m| [m.span.start.line, m.span.start.column] }
195
+ Result.new(messages:, source: @text, document: self, version: @version)
196
+ end
197
+
198
+ def query_goals(line, column, timeout)
199
+ lines = Internal::Positions.lines(@text)
200
+ result = @server.protocol.request("$/lean/plainGoal", {
201
+ "textDocument" => { "uri" => uri },
202
+ "position" => Internal::Positions.to_lsp(lines, line, column)
203
+ }, timeout: timeout_for(timeout))
204
+ return [] unless result
205
+
206
+ Array(result["goals"]).map { |g| Goal.new(text: g) }
207
+ rescue TimeoutError => e
208
+ raise TimeoutError.new("goals", e.seconds)
209
+ end
210
+
211
+ def query_hover(line, column, timeout)
212
+ lines = Internal::Positions.lines(@text)
213
+ result = @server.protocol.request("textDocument/hover", {
214
+ "textDocument" => { "uri" => uri },
215
+ "position" => Internal::Positions.to_lsp(lines, line, column)
216
+ }, timeout: timeout_for(timeout))
217
+ return nil unless result
218
+
219
+ contents = result["contents"]
220
+ markdown = case contents
221
+ when Hash then contents["value"].to_s
222
+ when Array then contents.map { |c| c.is_a?(Hash) ? c["value"] : c }.join("\n\n")
223
+ else contents.to_s
224
+ end
225
+ span = result["range"] && Internal::Positions.span_from_lsp(lines, result["range"])
226
+ Hover.new(markdown:, span:)
227
+ rescue TimeoutError => e
228
+ raise TimeoutError.new("hover", e.seconds)
229
+ end
230
+
231
+ SEVERITIES = { 1 => :error, 2 => :warning, 3 => :information, 4 => :hint }.freeze
232
+ private_constant :SEVERITIES
233
+
234
+ # @api private
235
+ def self.message_from_lsp(lines, diagnostic)
236
+ Message.new(
237
+ severity: SEVERITIES.fetch(diagnostic["severity"] || 1, :error),
238
+ text: diagnostic["message"].to_s,
239
+ span: Internal::Positions.span_from_lsp(lines, diagnostic.fetch("range"))
240
+ )
241
+ end
242
+ end
243
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RbLean
4
+ # Base class of every error rblean raises. Errors in the Lean code itself are
5
+ # never raised: they come back as messages of a Result.
6
+ class Error < StandardError; end
7
+
8
+ # lean / lake could not be found.
9
+ class ToolchainNotFound < Error
10
+ INSTALL_HINT = <<~HINT.chomp
11
+ rblean does not ship Lean. Install it with elan, which also picks the
12
+ version a project's lean-toolchain asks for:
13
+ curl https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh -sSf | sh
14
+ (see https://lean-lang.org/install/). Or pass lean: / set RBLEAN_LEAN.
15
+ HINT
16
+
17
+ attr_reader :searched
18
+
19
+ def initialize(message = nil, searched: [])
20
+ @searched = searched.freeze
21
+ super("#{message || "Lean toolchain not found (searched: #{searched.join(", ")})"}\n#{INSTALL_HINT}")
22
+ end
23
+ end
24
+
25
+ # A call took longer than its timeout. The request has already been cancelled.
26
+ class TimeoutError < Error
27
+ attr_reader :method_name, :seconds
28
+
29
+ def initialize(method_name, seconds)
30
+ @method_name = method_name
31
+ @seconds = seconds
32
+ super("#{method_name} timed out after #{seconds}s")
33
+ end
34
+ end
35
+
36
+ # The server answered a request with an error.
37
+ class ServerError < Error
38
+ attr_reader :code
39
+
40
+ def initialize(code, message)
41
+ @code = code
42
+ super(message)
43
+ end
44
+ end
45
+
46
+ # The Lean process exited.
47
+ class ServerCrashed < Error
48
+ attr_reader :status, :stderr
49
+
50
+ def initialize(status, stderr)
51
+ @status = status
52
+ @stderr = stderr
53
+ detail = stderr.to_s.strip
54
+ msg = "Lean server exited (#{status ? status.inspect : "unknown status"})"
55
+ msg += "\n#{detail}" unless detail.empty?
56
+ super(msg)
57
+ end
58
+ end
59
+
60
+ # A call on a server (or document) that has been closed, or from a forked child.
61
+ class ClosedError < Error; end
62
+
63
+ # goals / hover were asked of a Result made without a server (RbLean.elaborate).
64
+ class NoServerError < Error
65
+ def initialize(message = "this Result was made without a server; use RbLean.open to query goals or hover")
66
+ super
67
+ end
68
+ end
69
+
70
+ # lake check could not start (no bwrap, not Linux, not a Lake project, ...).
71
+ class CheckerUnavailable < Error; end
72
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RbLean
4
+ module Internal
5
+ # Converts between rblean positions (1-based lines, 0-based character
6
+ # columns) and LSP positions (0-based lines, 0-based UTF-16 columns).
7
+ module Positions
8
+ module_function
9
+
10
+ def lines(text) = text.split("\n", -1)
11
+
12
+ # Number of UTF-16 code units in the first +column+ characters of +line+.
13
+ def char_to_utf16(line, column)
14
+ return column if line.nil?
15
+
16
+ prefix = line[0, column] || line
17
+ units = prefix.encode("UTF-16LE").bytesize / 2
18
+ # Columns past the end of the line are kept as they are.
19
+ units + [column - prefix.length, 0].max
20
+ end
21
+
22
+ # Number of characters covering the first +units+ UTF-16 code units of +line+.
23
+ def utf16_to_char(line, units)
24
+ return units if line.nil?
25
+
26
+ count = 0
27
+ chars = 0
28
+ line.each_char do |c|
29
+ break if count >= units
30
+
31
+ count += c.ord > 0xFFFF ? 2 : 1
32
+ chars += 1
33
+ end
34
+ chars + [units - count, 0].max
35
+ end
36
+
37
+ # rblean (line, column) => LSP {"line", "character"}
38
+ def to_lsp(lines, line, column)
39
+ { "line" => line - 1, "character" => char_to_utf16(lines[line - 1], column) }
40
+ end
41
+
42
+ # LSP {"line", "character"} => Position
43
+ def from_lsp(lines, pos)
44
+ l = pos.fetch("line")
45
+ Position.new(line: l + 1, column: utf16_to_char(lines[l], pos.fetch("character")))
46
+ end
47
+
48
+ def span_from_lsp(lines, range)
49
+ Span.new(start: from_lsp(lines, range.fetch("start")), stop: from_lsp(lines, range.fetch("end")))
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RbLean
4
+ module Internal
5
+ # Matches responses to requests and routes notifications. One reader
6
+ # thread receives everything; each request waits on its own queue.
7
+ class Protocol
8
+ CRASHED = Object.new.freeze
9
+ private_constant :CRASHED
10
+
11
+ # +on_notification+ is called on the reader thread with (method, params).
12
+ # +on_eof+ is called once on the reader thread and must return the
13
+ # exception (ServerCrashed) that pending and later calls raise.
14
+ def initialize(transport, on_notification:, on_eof:, logger: nil)
15
+ @transport = transport
16
+ @on_notification = on_notification
17
+ @on_eof = on_eof
18
+ @logger = logger
19
+ @lock = Mutex.new
20
+ @next_id = 0
21
+ @pending = {}
22
+ @failure = nil
23
+ @reader = Thread.new { read_loop }
24
+ @reader.report_on_exception = false
25
+ end
26
+
27
+ # Sends a request and waits for its result. On timeout, sends
28
+ # $/cancelRequest and raises TimeoutError.
29
+ def request(method, params, timeout: nil)
30
+ queue = Thread::Queue.new
31
+ id = @lock.synchronize do
32
+ raise @failure if @failure
33
+
34
+ @next_id += 1
35
+ @pending[@next_id] = queue
36
+ @next_id
37
+ end
38
+ begin
39
+ @transport.write({ "jsonrpc" => "2.0", "id" => id, "method" => method, "params" => params })
40
+ rescue IOError, SystemCallError
41
+ @lock.synchronize { @pending.delete(id) }
42
+ raise broken_pipe_error
43
+ end
44
+
45
+ response = queue.pop(timeout:)
46
+ if response.nil?
47
+ @lock.synchronize { @pending.delete(id) }
48
+ cancel(id)
49
+ raise TimeoutError.new(method, timeout)
50
+ end
51
+ raise @lock.synchronize { @failure } if response.equal?(CRASHED)
52
+
53
+ if (error = response["error"])
54
+ raise ServerError.new(error["code"], error["message"].to_s)
55
+ end
56
+
57
+ response["result"]
58
+ end
59
+
60
+ def notify(method, params)
61
+ raise @lock.synchronize { @failure } if failed?
62
+
63
+ @transport.write({ "jsonrpc" => "2.0", "method" => method, "params" => params })
64
+ rescue IOError, SystemCallError
65
+ raise broken_pipe_error
66
+ end
67
+
68
+ def failed? = @lock.synchronize { !@failure.nil? }
69
+
70
+ def failure = @lock.synchronize { @failure }
71
+
72
+ # Waits for the reader thread to end (after the stream closes).
73
+ def join(timeout = nil) = @reader.join(timeout)
74
+
75
+ private
76
+
77
+ # The pipe broke: the process is gone, so wait for the reader to see EOF.
78
+ def broken_pipe_error
79
+ @reader.join(5)
80
+ @lock.synchronize { @failure } || ServerCrashed.new(nil, "")
81
+ end
82
+
83
+ def cancel(id)
84
+ notify("$/cancelRequest", { "id" => id })
85
+ rescue Error
86
+ nil
87
+ end
88
+
89
+ def read_loop
90
+ while (message = @transport.read)
91
+ dispatch(message)
92
+ end
93
+ rescue StandardError => e
94
+ @logger&.error("rblean: reader stopped: #{e.class}: #{e.message}")
95
+ ensure
96
+ fail_all
97
+ end
98
+
99
+ def dispatch(message)
100
+ if message.key?("id") && !message.key?("method")
101
+ queue = @lock.synchronize { @pending.delete(message["id"]) }
102
+ queue&.push(message)
103
+ elsif message.key?("id")
104
+ # A request from the server (client/registerCapability, ...).
105
+ @transport.write({ "jsonrpc" => "2.0", "id" => message["id"], "result" => nil })
106
+ else
107
+ @on_notification.call(message["method"], message["params"])
108
+ end
109
+ rescue StandardError => e
110
+ @logger&.error("rblean: error while handling #{message["method"] || "response"}: #{e.class}: #{e.message}")
111
+ end
112
+
113
+ def fail_all
114
+ failure = begin
115
+ @on_eof.call
116
+ rescue StandardError => e
117
+ ServerCrashed.new(nil, e.message)
118
+ end
119
+ pending = @lock.synchronize do
120
+ @failure ||= failure
121
+ @pending.values.tap { @pending.clear }
122
+ end
123
+ pending.each { |q| q.push(CRASHED) }
124
+ end
125
+ end
126
+ end
127
+ end
@@ -0,0 +1,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "open3"
5
+
6
+ module RbLean
7
+ module Internal
8
+ # JSON-RPC messages framed by Content-Length headers over a pair of IOs.
9
+ # Lengths are counted in bytes; bodies are UTF-8.
10
+ class Transport
11
+ def initialize(input, output, logger: nil, debug: false)
12
+ @input = input
13
+ @output = output
14
+ @input.binmode
15
+ @output.binmode
16
+ @write_lock = Mutex.new
17
+ @logger = logger
18
+ @debug = debug
19
+ end
20
+
21
+ # Writes one message. Safe to call from several threads.
22
+ def write(message)
23
+ body = JSON.generate(message).b
24
+ @logger&.debug("rblean --> #{body.dup.force_encoding(Encoding::UTF_8)}") if @debug
25
+ @write_lock.synchronize do
26
+ @output.write("Content-Length: #{body.bytesize}\r\n\r\n", body)
27
+ @output.flush
28
+ end
29
+ end
30
+
31
+ # Reads one message, or returns nil at the end of the stream.
32
+ def read
33
+ length = nil
34
+ loop do
35
+ line = @input.gets("\r\n")
36
+ return nil if line.nil?
37
+
38
+ line = line.chomp("\r\n")
39
+ break if line.empty?
40
+
41
+ name, value = line.split(":", 2)
42
+ length = Integer(value.strip) if name.strip.casecmp?("Content-Length")
43
+ end
44
+ raise Error, "missing Content-Length header" unless length
45
+
46
+ body = @input.read(length)
47
+ return nil if body.nil? || body.bytesize < length
48
+
49
+ body.force_encoding(Encoding::UTF_8)
50
+ @logger&.debug("rblean <-- #{body}") if @debug
51
+ JSON.parse(body)
52
+ end
53
+
54
+ def close_write
55
+ @write_lock.synchronize { @output.close unless @output.closed? }
56
+ rescue IOError
57
+ nil
58
+ end
59
+ end
60
+
61
+ # A child process with stdin/stdout for a Transport and stderr drained by a
62
+ # thread that keeps only the last 64 KiB.
63
+ class ChildProcess
64
+ STDERR_TAIL = 64 * 1024
65
+
66
+ attr_reader :pid, :stdin, :stdout
67
+
68
+ def initialize(command, chdir:, logger: nil)
69
+ @stdin, @stdout, @stderr, @wait = Open3.popen3(*command, chdir:)
70
+ @pid = @wait.pid
71
+ @tail = +""
72
+ @tail_lock = Mutex.new
73
+ @logger = logger
74
+ @stderr_thread = Thread.new { drain_stderr }
75
+ @stderr_thread.report_on_exception = false
76
+ end
77
+
78
+ def stderr_tail
79
+ @stderr_thread.join(0.5)
80
+ @tail_lock.synchronize { @tail.dup.force_encoding(Encoding::UTF_8).scrub }
81
+ end
82
+
83
+ def alive? = @wait.alive?
84
+
85
+ # Process::Status, waiting up to +timeout+ seconds (nil when still running).
86
+ def status(timeout: 0)
87
+ @wait.join(timeout) ? @wait.value : nil
88
+ end
89
+
90
+ def wait(timeout) = !@wait.join(timeout).nil?
91
+
92
+ def signal(sig)
93
+ Process.kill(sig, @pid)
94
+ rescue Errno::ESRCH, Errno::EPERM
95
+ nil
96
+ end
97
+
98
+ # Waits +grace+ seconds, then TERM, then KILL.
99
+ def terminate(grace: 5, term_grace: 2)
100
+ return if wait(grace)
101
+
102
+ signal("TERM")
103
+ return if wait(term_grace)
104
+
105
+ signal("KILL")
106
+ wait(5)
107
+ ensure
108
+ [@stdin, @stdout].each { |io| io.close unless io.closed? rescue nil } # rubocop:disable Style/RescueModifier
109
+ end
110
+
111
+ private
112
+
113
+ def drain_stderr
114
+ @stderr.binmode
115
+ while (chunk = @stderr.readpartial(8192))
116
+ @tail_lock.synchronize do
117
+ @tail << chunk
118
+ @tail = @tail.byteslice(-STDERR_TAIL, STDERR_TAIL) if @tail.bytesize > STDERR_TAIL
119
+ end
120
+ @logger&.info("lean stderr: #{chunk.dup.force_encoding(Encoding::UTF_8).scrub.chomp}")
121
+ end
122
+ rescue EOFError, IOError
123
+ nil
124
+ ensure
125
+ @stderr.close unless @stderr.closed?
126
+ end
127
+ end
128
+ end
129
+ end