Class: RstFilter::LSP

Inherits:
Object
  • Object
show all
Defined in:
lib/rstfilter/lsp/handler.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input: $stdin, output: $stdout, err: $stderr, indent: 50) ⇒ LSP

Returns a new instance of LSP.



11
12
13
14
15
16
17
18
19
20
# File 'lib/rstfilter/lsp/handler.rb', line 11

def initialize input: $stdin, output: $stdout, err: $stderr, indent: 50
  @input   = input
  @output  = output
  @err     = err
  @indent  = indent
  @records = {} # {filename => [record, line_record, src]}
  @server_request_id = 0
  @exit_status = 1
  @running = {} # {filename => Thread}
end

Class Method Details

.reloadObject



22
23
24
25
26
# File 'lib/rstfilter/lsp/handler.rb', line 22

def self.reload
  ::RstFilter.send(:remove_const, :LSP)
  $".delete_if{|e| /lsp\/handler\.rb$/ =~ e}
  require __FILE__
end

Instance Method Details

#clear_record(filename) ⇒ Object



268
269
270
271
272
273
274
# File 'lib/rstfilter/lsp/handler.rb', line 268

def clear_record filename
  @records[filename] = nil
  if th = @running[filename]
    @running[filename] = nil
    th.raise CancelRequest
  end
end

#cover?(line, char, bl, bc, el, ec) ⇒ Boolean

Returns:

  • (Boolean)


208
209
210
211
212
213
214
# File 'lib/rstfilter/lsp/handler.rb', line 208

def cover? line, char, bl, bc, el, ec
  return false if bl > line
  return false if bl == line && char < bc
  return false if el < line
  return false if el == line && char >= ec
  true
end

#event_loopObject



48
49
50
51
52
53
54
55
56
# File 'lib/rstfilter/lsp/handler.rb', line 48

def event_loop
  while req = recv_message
    if req[:id]
      handle_request req
    else
      handle_notification req
    end
  end
end

#handle_notification(req) ⇒ Object



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/rstfilter/lsp/handler.rb', line 285

def handle_notification req
  case req[:method]
  when 'initialized'
    send_notice 'rstfilter/version', {
      version: "#{::RstFilter::VERSION} on #{RUBY_DESCRIPTION}",
    }
  when 'textDocument/didOpen',
       'textDocument/didSave'
    #filename = uri2filename req.dig(:params, :textDocument, :uri)
    #take_record filename
    # do nothing
  when 'textDocument/didClose',
       'textDocument/didChange'
    filename = uri2filename req.dig(:params, :textDocument, :uri)
    clear_record filename
  when 'rstfilter/start'
    filename = req.dig(:params, :path)
    take_record filename
  when '$/cancelRequest'
    # ignore
  when 'exit'
    exit(@exit_code)
  else
    raise
  end
end

#handle_request(req) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/rstfilter/lsp/handler.rb', line 121

def handle_request req
  if req[:error]
    log "error: #{req.inspect}"
    return
  end

  case req[:method]
  when 'initialize'
    send_response req, {
      capabilities: {
        textDocumentSync: {
          openClose: true,
          change: 2, # Incremental
          # save: true,
        },

        inlineValueProvider: true,

        hoverProvider: true,

        inlayHintProvider: {
          resolveProvider: true,
        },

      },
      serverInfo: {
        name: "rstfilter-lsp-server",
        version: '0.0.1',
      }
    }
  when 'textDocument/hover'
    filename = uri2filename req.dig(:params, :textDocument, :uri)
    line = req.dig(:params, :position, :line)
    char = req.dig(:params, :position, :character)
    if (record, _line_record, src = @records[filename])
      line += 1
      rs = record.find_all{|(bl, bc, el, ec), _v| cover?(line, char, bl, bc, el, ec)}
      if rs.empty?
        send_response req, nil
        else
          r = rs.min_by{|(_bl, _bc, _el, ec), _v| ec}
          v = r[1][0].strip
          pos = r[0]
          send_response req, contents: {
            kind: 'markdown',
            value: "```\n#{v}```",
          }, range: {
            start: {line: pos[0]-1, character: pos[1],},
            end:   {line: pos[2]-1, character: pos[3],},
          }
        end
    else
      send_response req, nil
    end
  when 'textDocument/codeLens'
    filename = uri2filename req.dig(:params, :textDocument, :uri)
    send_response req, codelens(filename)
  when 'textDocument/inlayHint'
    filename = uri2filename req.dig(:params, :textDocument, :uri)
    send_response req, inlayhints(filename)
  when 'inlayHint/resolve'
    hint = req.dig(:params)
    send_response req, {
      position: hint[:position],

      label: [{
        tooltip: {
          kind: 'markdown',
          value: hint[:label] + "\n 1. *foo* `bar` _baz_",
          tooltip: hint[:label] + "\n 1. *foo* `bar` _baz_",
        }
      },
      {
        kind: 'markdown',
        value: hint[:label] + "\n# 2. FOO\n*foo* `bar` _baz_",
      }],
    }
  when 'shutdown'
    @exit_status = 0
    send_response req, nil
  when nil
    # reply
  else
    raise "unknown request: #{req.inspect}"
  end
end

#inlayhints(filename) ⇒ Object



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/rstfilter/lsp/handler.rb', line 216

def inlayhints filename
  if (_record, line_record, src = @records[filename])
    src_lines = src.lines.to_a

    line_record.sort_by{|k, v| k}.map do |lineno, r|
      line = src_lines[lineno - 1]
      next unless line

      {
        position: {
          line: lineno - 1, # 0 origin
          character: line.length,
        },
        label: ' ' * [@indent - line.size, 3].max + "#=> #{r.first.strip}",
        # tooltip: "tooltip of #{lineno}",
        paddingLeft: true,
        kind: 1,
      }
    end.compact
  else
    nil
  end
end

#log(msg) ⇒ Object



58
59
60
# File 'lib/rstfilter/lsp/handler.rb', line 58

def log msg
  @err.puts msg
end

#recv_messageObject



62
63
64
65
66
67
68
69
70
# File 'lib/rstfilter/lsp/handler.rb', line 62

def recv_message
  log "wait from #{@input.inspect}"
  line = @input.gets 
  line.match(/Content-Length: (\d+)/) || raise("irregular json-rpc: #{line}")
  @input.gets
  msg = JSON.parse(@input.read($1.to_i), symbolize_names: true)
  log "[recv] #{msg.inspect}"
  msg
end

#send_message(type, msg_text) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/rstfilter/lsp/handler.rb', line 72

def send_message type, msg_text
  log "[#{type}] #{msg_text}"

  text = "Content-Length: #{msg_text.size}\r\n" \
      "\r\n" \
      "#{msg_text}"
  @output.write text
  @output.flush
  if true
    log '----'
    log text
    log '----'
  end
end

#send_notice(method, kw = {}) ⇒ Object



110
111
112
113
114
115
116
117
118
119
# File 'lib/rstfilter/lsp/handler.rb', line 110

def send_notice method, kw = {}
  msg_text = JSON.dump({
    jsonrpc: "2.0",
    method: method,
    params: {
      **kw
    }
  })
  send_message "notice", msg_text
end

#send_request(method, kw = {}) ⇒ Object



97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/rstfilter/lsp/handler.rb', line 97

def send_request method, kw = {}
  msg_text = JSON.dump({
    jsonrpc: "2.0",
    method: method,
    id: (@server_request_id+=1),
    params: {
      **kw
    }
  })

  send_message 'request', msg_text
end

#send_response(req, kw) ⇒ Object



87
88
89
90
91
92
93
94
95
# File 'lib/rstfilter/lsp/handler.rb', line 87

def send_response req, kw
  res_text = JSON.dump({
    jsonrpc: "2.0",
    id: req[:id],
    result: kw,
  })

  send_message 'response', res_text
end

#startObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rstfilter/lsp/handler.rb', line 28

def start
  # for reload
  trap(:USR1){
    Thread.main.raise "reload"
  }

  lsp = self
  begin
    lsp.event_loop
  rescue Exception => e
    log e
    log e.backtrace

    # reload
    lsp.class.reload
    lsp = RstFilter::LSP.new
    retry
  end
end

#take_record(filename) ⇒ Object



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/rstfilter/lsp/handler.rb', line 240

def take_record filename
  send_notice 'rstfilter/started', {
    uri: filename,
  }
  @running[filename] = Thread.new do
    filter = RstFilter::Exec.new
    filter.optparse! ['--pp', '-eruby']
    records, src, _comments = filter.record_records(filename)
    records = records.first # only 1 process results
    @records[filename] = [records, filter.make_line_records(records), src]
    send_notice 'rstfilter/done'
    unless filter.output.empty?
      send_notice 'rstfilter/output', output: "# Output for #{filename}\n\n#{filter.output}"
    end
    send_request 'workspace/inlayHint/refresh'
  rescue CancelRequest
    # canceled
  rescue SyntaxError => e
    send_notice 'rstfilter/output', output: "SyntaxError on #{filename}:\n#{e.inspect}"
    send_notice 'rstfilter/done'
  rescue Exception => e
    send_notice 'rstfilter/output', output: "Error on #{filename}:\n#{e.inspect}\n#{e.backtrace.join("\n")}#{filter.output}"
    send_notice 'rstfilter/done'
  ensure
    @running[filename] = nil
  end
end

#uri2filename(uri) ⇒ Object



276
277
278
279
280
281
282
283
# File 'lib/rstfilter/lsp/handler.rb', line 276

def uri2filename uri
  case uri
  when /^file:\/\/(.+)/
    $1
  else
    raise "unknown uri: #{uri}"
  end
end