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,231 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+ require "logger"
5
+
6
+ module RbLean
7
+ # A running Lean language server (`lean --server`, or `lake serve` in a Lake
8
+ # project). Safe to use from several threads: different documents are
9
+ # elaborated in parallel, operations on one document are serialized.
10
+ #
11
+ # Locks are always taken in the order Document -> Server -> Transport.
12
+ class Server
13
+ # Lean waits this long after an edit before reporting, to avoid flicker in
14
+ # editors. rblean has no use for it.
15
+ SERVER_ARGS = ["-Dserver.reportDelayMs=0"].freeze
16
+ STRICT_ARGS = ["-DwarningAsError=true"].freeze
17
+
18
+ attr_reader :toolchain, :root, :timeout
19
+
20
+ # @api private
21
+ attr_reader :protocol
22
+
23
+ @registry = []
24
+ @registry_lock = Mutex.new
25
+
26
+ class << self
27
+ # @api private
28
+ def register(server) = @registry_lock.synchronize { @registry << server }
29
+
30
+ # @api private
31
+ def unregister(server) = @registry_lock.synchronize { @registry.delete(server) }
32
+
33
+ # @api private
34
+ def close_all
35
+ servers = @registry_lock.synchronize { @registry.dup }
36
+ servers.each do |s|
37
+ s.close
38
+ rescue StandardError
39
+ nil
40
+ end
41
+ end
42
+ end
43
+
44
+ def initialize(project: nil, lean: nil, strict: false, timeout: 60, scratch: 1, logger: nil)
45
+ raise ArgumentError, "scratch must be at least 1" if scratch < 1
46
+
47
+ @toolchain = Toolchain.detect(project:, lean:)
48
+ @root = @toolchain.chdir
49
+ @timeout = timeout
50
+ @debug = ENV["RBLEAN_DEBUG"] == "1"
51
+ @logger = logger || (@debug ? Logger.new($stderr) : nil)
52
+ @lock = Mutex.new
53
+ @closed = false
54
+ @pid = Process.pid
55
+ @documents = {}
56
+ @scratch_seq = 0
57
+ @scratch_pool = Thread::Queue.new
58
+
59
+ args = SERVER_ARGS + (strict ? STRICT_ARGS : [])
60
+ command = if project
61
+ [@toolchain.lake!, "serve", "--", *args]
62
+ else
63
+ [@toolchain.lean, "--server", *args]
64
+ end
65
+ @process = Internal::ChildProcess.new(command, chdir: @root, logger: @logger)
66
+ Server.register(self)
67
+ transport = Internal::Transport.new(@process.stdout, @process.stdin, logger: @logger, debug: @debug)
68
+ @protocol = Internal::Protocol.new(
69
+ transport,
70
+ on_notification: method(:handle_notification),
71
+ on_eof: method(:crash_error),
72
+ logger: @logger
73
+ )
74
+ start
75
+ scratch.times { @scratch_pool.push(new_scratch_document) }
76
+ rescue StandardError
77
+ @process&.terminate(grace: 0, term_grace: 1)
78
+ Server.unregister(self)
79
+ raise
80
+ end
81
+
82
+ # Elaborates +source+ in an unnamed scratch document. May be called from
83
+ # several threads; at most scratch: elaborations run at once.
84
+ def elaborate(source, timeout: nil)
85
+ ensure_open!
86
+ doc = @scratch_pool.pop
87
+ begin
88
+ doc.update(source).elaborate(timeout:)
89
+ rescue TimeoutError
90
+ # Throw the runaway elaboration away together with its worker.
91
+ doc.close
92
+ doc = new_scratch_document
93
+ raise
94
+ ensure
95
+ @scratch_pool.push(doc) if doc
96
+ end
97
+ end
98
+
99
+ # Opens a named document (or returns it when already open). +name+ is
100
+ # relative to the project root.
101
+ def document(name, text = nil)
102
+ ensure_open!
103
+ uri = uri_for(name.to_s)
104
+ @lock.synchronize do
105
+ if (doc = @documents[uri])
106
+ return doc
107
+ end
108
+
109
+ @documents[uri] = Document.new(self, name.to_s, uri, text.to_s)
110
+ end.tap { |doc| doc.update(text.to_s) unless text.nil? }
111
+ end
112
+
113
+ # Reads a file from disk and opens it.
114
+ def open_file(path)
115
+ full = File.expand_path(path.to_s)
116
+ text = File.read(full, encoding: Encoding::UTF_8)
117
+ name = full.start_with?("#{@root}/") ? full.delete_prefix("#{@root}/") : full
118
+ document(name).update(text)
119
+ end
120
+
121
+ # Open named documents.
122
+ def documents = @lock.synchronize { @documents.values.reject(&:scratch?) }
123
+
124
+ # shutdown -> exit, then TERM and KILL if Lean does not stop. Idempotent.
125
+ def close
126
+ @lock.synchronize do
127
+ return if @closed
128
+
129
+ @closed = true
130
+ end
131
+ if Process.pid == @pid
132
+ begin
133
+ @protocol.request("shutdown", nil, timeout: 5) unless @protocol.failed?
134
+ @protocol.notify("exit", nil) unless @protocol.failed?
135
+ rescue Error, IOError, SystemCallError
136
+ nil
137
+ end
138
+ @process.terminate(grace: 5, term_grace: 2)
139
+ @protocol.join(1)
140
+ end
141
+ Server.unregister(self)
142
+ nil
143
+ end
144
+
145
+ def closed? = @closed
146
+
147
+ # The Lean version, e.g. "4.37.0-rc1". The initialize response only carries
148
+ # the protocol version ("0.3.0"), so this asks `lean --version` (once).
149
+ def version = @toolchain.version
150
+
151
+ def inspect = "#<RbLean::Server root=#{root} version=#{version.inspect}#{" closed" if closed?}>"
152
+
153
+ private
154
+
155
+ def start
156
+ result = @protocol.request("initialize", {
157
+ "processId" => Process.pid,
158
+ "rootUri" => file_uri(@root),
159
+ "clientInfo" => { "name" => "rblean", "version" => RbLean::VERSION },
160
+ "capabilities" => {
161
+ "textDocument" => {
162
+ "hover" => { "contentFormat" => %w[markdown plaintext] },
163
+ "publishDiagnostics" => { "versionSupport" => true }
164
+ }
165
+ },
166
+ "initializationOptions" => { "hasWidgets" => false }
167
+ }, timeout: @timeout)
168
+ @server_info = result&.fetch("serverInfo", nil)
169
+ @protocol.notify("initialized", {})
170
+ end
171
+
172
+ def ensure_open!
173
+ raise ClosedError, "server is closed" if @closed
174
+ raise ClosedError, "server was started in another process (fork is not supported)" if Process.pid != @pid
175
+
176
+ failure = @protocol.failure
177
+ raise failure if failure
178
+ end
179
+
180
+ def new_scratch_document
181
+ n = @lock.synchronize { @scratch_seq += 1 }
182
+ name = "RbLeanScratch_#{Process.pid}_#{n}.lean"
183
+ uri = uri_for(name)
184
+ doc = Document.new(self, name, uri, "", scratch: true)
185
+ @lock.synchronize { @documents[uri] = doc }
186
+ doc
187
+ end
188
+
189
+ def forget(doc)
190
+ @lock.synchronize { @documents.delete(doc.uri) if @documents[doc.uri].equal?(doc) }
191
+ end
192
+
193
+ def uri_for(name) = file_uri(File.expand_path(name, @root))
194
+
195
+ def file_uri(path)
196
+ encoded = path.split("/", -1).map do |segment|
197
+ URI.encode_www_form_component(segment).gsub("+", "%20")
198
+ end.join("/")
199
+ "file://#{encoded}"
200
+ end
201
+
202
+ def handle_notification(method, params)
203
+ case method
204
+ when "textDocument/publishDiagnostics"
205
+ doc = @lock.synchronize { @documents[params["uri"]] }
206
+ doc&.receive_diagnostics(params["version"], params["diagnostics"] || [])
207
+ when "window/logMessage", "window/showMessage"
208
+ log_message(params)
209
+ end
210
+ end
211
+
212
+ def log_message(params)
213
+ return unless @logger
214
+
215
+ text = "lean: #{params["message"]}"
216
+ case params["type"]
217
+ when 1 then @logger.error(text)
218
+ when 2 then @logger.warn(text)
219
+ when 3 then @logger.info(text)
220
+ else @logger.debug(text)
221
+ end
222
+ end
223
+
224
+ def crash_error
225
+ status = @process.status(timeout: 2)
226
+ ServerCrashed.new(status, @process.stderr_tail)
227
+ end
228
+ end
229
+
230
+ at_exit { Server.close_all }
231
+ end
@@ -0,0 +1,112 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "open3"
4
+
5
+ module RbLean
6
+ # The lean / lake executables in use and their version.
7
+ #
8
+ # Search order: the lean: argument, RBLEAN_LEAN / RBLEAN_LAKE, LEAN / LAKE,
9
+ # PATH, then elan's bin directory. elan's shims read lean-toolchain in the
10
+ # working directory, so everything is run with chdir: project.
11
+ class Toolchain
12
+ attr_reader :lean, :lake, :project
13
+
14
+ # @api private
15
+ def self.detect(project: nil, lean: nil, need_lake: !project.nil?, env: ENV)
16
+ searched = []
17
+ lean_path = nil
18
+ lake_path = nil
19
+
20
+ if lean
21
+ searched << lean.to_s
22
+ lean_path = executable(lean.to_s)
23
+ raise ToolchainNotFound.new(searched:) unless lean_path
24
+
25
+ candidate = File.join(File.dirname(lean_path), "lake")
26
+ searched << candidate
27
+ lake_path = executable(candidate)
28
+ else
29
+ lean_path = from_env(env, %w[RBLEAN_LEAN LEAN], searched)
30
+ lake_path = from_env(env, %w[RBLEAN_LAKE LAKE], searched)
31
+ dirs = path_dirs(env)
32
+ lean_path ||= from_dirs(dirs, "lean", searched)
33
+ lake_path ||= if lean_path && executable(File.join(File.dirname(lean_path), "lake"))
34
+ File.join(File.dirname(lean_path), "lake")
35
+ else
36
+ from_dirs(dirs, "lake", searched)
37
+ end
38
+ end
39
+
40
+ raise ToolchainNotFound.new(searched: searched.uniq) unless lean_path
41
+ if need_lake && !lake_path
42
+ raise ToolchainNotFound.new("lake not found (searched: #{searched.uniq.join(", ")})", searched: searched.uniq)
43
+ end
44
+
45
+ new(lean: lean_path, lake: lake_path, project: project && File.expand_path(project.to_s))
46
+ end
47
+
48
+ def self.executable(path)
49
+ path = File.expand_path(path)
50
+ File.file?(path) && File.executable?(path) ? path : nil
51
+ end
52
+
53
+ def self.from_env(env, names, searched)
54
+ names.each do |name|
55
+ value = env[name]
56
+ next if value.nil? || value.empty?
57
+
58
+ searched << "$#{name}=#{value}"
59
+ found = executable(value)
60
+ return found if found
61
+ end
62
+ nil
63
+ end
64
+
65
+ def self.path_dirs(env)
66
+ dirs = env.fetch("PATH", "").split(File::PATH_SEPARATOR).reject(&:empty?)
67
+ elan_home = env["ELAN_HOME"] || (env["HOME"] && File.join(env["HOME"], ".elan"))
68
+ dirs << File.join(elan_home, "bin") if elan_home
69
+ dirs.uniq
70
+ end
71
+
72
+ def self.from_dirs(dirs, name, searched)
73
+ dirs.each do |dir|
74
+ candidate = File.join(dir, name)
75
+ searched << candidate
76
+ found = executable(candidate)
77
+ return found if found
78
+ end
79
+ nil
80
+ end
81
+ private_class_method :executable, :from_env, :path_dirs, :from_dirs
82
+
83
+ def initialize(lean:, lake:, project: nil)
84
+ @lean = lean
85
+ @lake = lake
86
+ @project = project
87
+ @version = nil
88
+ @version_lock = Mutex.new
89
+ end
90
+
91
+ # Working directory for every command: the project root, or the current directory.
92
+ def chdir = project || Dir.pwd
93
+
94
+ # The version string Lean prints, e.g. "4.37.0-rc1".
95
+ def version
96
+ @version_lock.synchronize do
97
+ @version ||= begin
98
+ out, status = Open3.capture2e(lean, "--version", chdir:)
99
+ raise ToolchainNotFound.new("`#{lean} --version` failed: #{out.strip}", searched: [lean]) unless status.success?
100
+
101
+ out[/version (\S+?),?\s/, 1] || out.strip
102
+ end
103
+ end
104
+ end
105
+
106
+ def lake!
107
+ lake || raise(ToolchainNotFound.new("lake not found next to #{lean}", searched: [lean]))
108
+ end
109
+
110
+ def inspect = "#<RbLean::Toolchain lean=#{lean} lake=#{lake.inspect}>"
111
+ end
112
+ end
@@ -0,0 +1,126 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RbLean
4
+ # A position in a source. line is 1-based, column is 0-based and counted in
5
+ # characters (code points), the same as Lean's own "line:col" and String#[].
6
+ Position = Data.define(:line, :column) do
7
+ include Comparable
8
+
9
+ def <=>(other)
10
+ return nil unless other.is_a?(Position)
11
+
12
+ cmp = line <=> other.line
13
+ cmp.zero? ? column <=> other.column : cmp
14
+ end
15
+
16
+ def to_s = "#{line}:#{column}"
17
+ end
18
+
19
+ # A pair of positions. Not a ::Range.
20
+ Span = Data.define(:start, :stop) do
21
+ def to_s = "#{start}-#{stop}"
22
+ end
23
+
24
+ # One message Lean reported.
25
+ Message = Data.define(:severity, :text, :span) do
26
+ # severity: :error | :warning | :information | :hint
27
+
28
+ def line = span.start.line
29
+ def column = span.start.column
30
+
31
+ def error? = severity == :error
32
+ def warning? = severity == :warning
33
+ def info? = severity == :information
34
+
35
+ # gcc style, which editors can read as is: "3:26: error: ..."
36
+ def to_s
37
+ label = severity == :information ? "info" : severity.to_s
38
+ "#{line}:#{column}: #{label}: #{text}"
39
+ end
40
+ end
41
+
42
+ # The goal of a tactic, as Lean prints it.
43
+ Goal = Data.define(:text) do
44
+ # The part after the last "⊢ ". A rough guide only: nothing is parsed.
45
+ def target
46
+ idx = text.rindex("⊢ ")
47
+ idx ? text[(idx + 2)..] : text
48
+ end
49
+
50
+ def to_s = text
51
+ end
52
+
53
+ # The type and docstring at a position.
54
+ Hover = Data.define(:markdown, :span) do
55
+ def to_s = markdown
56
+ end
57
+
58
+ # The result of one elaboration. Immutable and Enumerable over its messages.
59
+ # == compares messages and source only.
60
+ class Result
61
+ include Enumerable
62
+
63
+ attr_reader :messages, :source
64
+
65
+ # @api private
66
+ def initialize(messages:, source:, document: nil, version: nil)
67
+ @messages = messages.dup.freeze
68
+ @source = source.dup.freeze
69
+ @document = document
70
+ @version = version
71
+ freeze
72
+ end
73
+
74
+ def each(&) = messages.each(&)
75
+
76
+ def errors = messages.select(&:error?)
77
+ def warnings = messages.select(&:warning?)
78
+ def infos = messages.select(&:info?)
79
+
80
+ # Lean reported no error (exit status 0 of `lean`). A `sorry` is a warning,
81
+ # so this can be true for an incomplete proof: use RbLean.check for that.
82
+ def success? = errors.empty?
83
+
84
+ # Goals at a position, asked of the very source this result was made from.
85
+ def goals(line:, column:)
86
+ document!.goals_at(@version, source, line:, column:)
87
+ end
88
+
89
+ def hover(line:, column:)
90
+ document!.hover_at(@version, source, line:, column:)
91
+ end
92
+
93
+ def ==(other)
94
+ other.is_a?(Result) && messages == other.messages && source == other.source
95
+ end
96
+ alias eql? ==
97
+
98
+ def hash = [self.class, messages, source].hash
99
+
100
+ def inspect
101
+ "#<RbLean::Result success=#{success?} errors=#{errors.size} warnings=#{warnings.size} infos=#{infos.size}>"
102
+ end
103
+
104
+ private
105
+
106
+ def document!
107
+ document = @document
108
+ raise NoServerError unless document
109
+
110
+ document
111
+ end
112
+ end
113
+
114
+ # The report of `lake check --json`, mirrored as is.
115
+ CheckReport = Data.define(:judgement, :sandboxed, :steps, :raw) do
116
+ # judgement is "accepted" (exit status 0 of `lake check`).
117
+ def success? = judgement == "accepted"
118
+ end
119
+
120
+ # One step of a CheckReport.
121
+ CheckReport::Step = Data.define(:judgement, :output) do
122
+ def success? = judgement == "success"
123
+ def skipped? = judgement == "skipped"
124
+ def failure? = judgement == "failure"
125
+ end
126
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RbLean
4
+ VERSION = "0.0.1"
5
+ end
data/lib/rblean.rb ADDED
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "rblean/version"
4
+ require_relative "rblean/errors"
5
+ require_relative "rblean/values"
6
+ require_relative "rblean/internal/positions"
7
+ require_relative "rblean/internal/transport"
8
+ require_relative "rblean/internal/protocol"
9
+ require_relative "rblean/toolchain"
10
+ require_relative "rblean/document"
11
+ require_relative "rblean/server"
12
+ require_relative "rblean/batch"
13
+ require_relative "rblean/checker"
14
+
15
+ # Drive Lean 4 from Ruby through the language server built into Lean.
16
+ module RbLean
17
+ module_function
18
+
19
+ # Starts a Lean server. With a block, yields it and always closes it
20
+ # afterwards, returning the block's value. Without one, returns the Server.
21
+ def open(project: nil, lean: nil, strict: false, timeout: 60, scratch: 1, logger: nil)
22
+ server = Server.new(project:, lean:, strict:, timeout:, scratch:, logger:)
23
+ return server unless block_given?
24
+
25
+ begin
26
+ yield server
27
+ ensure
28
+ server.close
29
+ end
30
+ end
31
+
32
+ # One-shot elaboration with `lean --json` (no server). The Result cannot
33
+ # answer goals / hover.
34
+ def elaborate(source, project: nil, lean: nil, strict: false, timeout: nil)
35
+ Batch.elaborate(source, project:, lean:, strict:, timeout:)
36
+ end
37
+
38
+ def elaborate_file(path, project: nil, lean: nil, strict: false, timeout: nil)
39
+ Batch.elaborate_file(path, project:, lean:, strict:, timeout:)
40
+ end
41
+
42
+ # Runs `lake check` on a Lake project and returns its report.
43
+ def check(project:, paranoid: false, lean: nil, timeout: nil)
44
+ Checker.check(project:, paranoid:, lean:, timeout:)
45
+ end
46
+
47
+ # The lean / lake that would be used, and the Lean version.
48
+ def toolchain(project: nil, lean: nil)
49
+ Toolchain.detect(project:, lean:, need_lake: false)
50
+ end
51
+ end