/
session.lua
1307 lines (1177 loc) · 37.8 KB
/
session.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local uv = vim.loop
local api = vim.api
local rpc = require('dap.rpc')
local utils = require('dap.utils')
local breakpoints = require('dap.breakpoints')
local progress = require('dap.progress')
local log = require('dap.log').create_logger('dap.log')
local repl = require('dap.repl')
local sec_to_ms = 1000
local non_empty = utils.non_empty
local index_of = utils.index_of
local mime_to_filetype = {
['text/javascript'] = 'javascript'
}
---@class Session
---@field capabilities Capabilities
---@field adapter Adapter
---@field dirty table<string, boolean>
---@field handlers table<string, fun(self: Session, payload: table)|fun()>
---@field client Client
---@field current_frame StackFrame|nil
---@field initialized boolean
---@field stopped_thread_id number|nil
---@class StackFrame
---@field id number
---@field source Source|nil
---@class Source
---@class Client
---@field close function
---@field write function
---@class Capabilities
---@field supportsConfigurationDoneRequest boolean|nil
---@field supportsFunctionBreakpoints boolean|nil
---@field supportsConditionalBreakpoints boolean|nil
---@field supportsHitConditionalBreakpoints boolean|nil
---@field supportsEvaluateForHovers boolean|nil
---@field exceptionBreakpointFilters ExceptionBreakpointsFilter[]|nil
---@field supportsStepBack boolean|nil
---@field supportsSetVariable boolean|nil
---@field supportsRestartFrame boolean|nil
---@field supportsGotoTargetsRequest boolean|nil
---@field supportsStepInTargetsRequest boolean|nil
---@field supportsCompletionsRequest boolean|nil
---@field completionTriggerCharacters string[]|nil
---@field supportsModulesRequest boolean|nil
---@field additionalModuleColumns ColumnDescriptor[]|nil
---@field supportedChecksumAlgorithms ChecksumAlgorithm[]|nil
---@field supportsRestartRequest boolean|nil
---@field supportsExceptionOptions boolean|nil
---@field supportsValueFormattingOptions boolean|nil
---@field supportsExceptionInfoRequest boolean|nil
---@field supportTerminateDebuggee boolean|nil
---@field supportSuspendDebuggee boolean|nil
---@field supportsDelayedStackTraceLoading boolean|nil
---@field supportsLoadedSourcesRequest boolean|nil
---@field supportsLogPoints boolean|nil
---@field supportsTerminateThreadsRequest boolean|nil
---@field supportsSetExpression boolean|nil
---@field supportsTerminateRequest boolean|nil
---@field supportsDataBreakpoints boolean|nil
---@field supportsReadMemoryRequest boolean|nil
---@field supportsWriteMemoryRequest boolean|nil
---@field supportsDisassembleRequest boolean|nil
---@field supportsCancelRequest boolean|nil
---@field supportsBreakpointLocationsRequest boolean|nil
---@field supportsClipboardContext boolean|nil
---@field supportsSteppingGranularity boolean|nil
---@field supportsInstructionBreakpoints boolean|nil
---@field supportsExceptionFilterOptions boolean|nil
---@field supportsSingleThreadExecutionRequests boolean|nil
---@class ExceptionBreakpointsFilter
---@field filter string
---@field label string
---@field description string|nil
---@field default boolean|nil
---@field supportsCondition boolean|nil
---@field conditionDescription string|nil
---@class ColumnDescriptor
---@field attributeName string
---@field label string
---@field format string|nil
---@field type nil|"string"|"number"|"number"|"unixTimestampUTC"
---@field width number|nil
---@class ChecksumAlgorithm
---@field algorithm "MD5"|"SHA1"|"SHA256"|"timestamp"
---@field checksum string
---@class Session
local Session = {}
local ns_pos = 'dap_pos'
local terminal_buf, terminal_width, terminal_height
local NIL = vim.NIL
local function convert_nil(v)
if v == NIL then
return nil
elseif type(v) == 'table' then
return vim.tbl_map(convert_nil, v)
else
return v
end
end
local json_decode
local json_encode = vim.fn.json_encode
local send_payload
if vim.json then
json_decode = function(payload)
return vim.json.decode(payload, { luanil = { object = true }})
end
json_encode = vim.json.encode
send_payload = function(client, payload)
local msg = rpc.msg_with_content_length(json_encode(payload))
client.write(msg)
end
else
json_decode = function(payload)
return assert(convert_nil(vim.fn.json_decode(payload)), "json_decode must return a value")
end
send_payload = function(client, payload)
vim.schedule(function()
local msg = rpc.msg_with_content_length(json_encode(payload))
client.write(msg)
end)
end
end
local function dap()
return require('dap')
end
local function ui()
return require('dap.ui')
end
local function defaults(session)
return dap().defaults[session.config.type]
end
local function signal_err(err, cb)
if err then
if cb then
cb(err)
else
error(vim.inspect(err))
end
return true
end
return false
end
local function launch_external_terminal(terminal, args)
local handle
local pid_or_err
local full_args = {}
vim.list_extend(full_args, terminal.args or {})
vim.list_extend(full_args, args)
local opts = {
args = full_args,
detached = true
}
handle, pid_or_err = uv.spawn(terminal.command, opts, function(code)
handle:close()
if code ~= 0 then
utils.notify(string.format('Terminal exited %d running %s %s', code, terminal.command, table.concat(full_args, ' ')), vim.log.levels.ERROR)
end
end)
return handle, pid_or_err
end
local function create_terminal_buf(terminal_win_cmd)
local cur_win = api.nvim_get_current_win()
if type(terminal_win_cmd) == "string" then
api.nvim_command(terminal_win_cmd)
local bufnr = api.nvim_get_current_buf()
local win = api.nvim_get_current_win()
api.nvim_set_current_win(cur_win)
return bufnr, win
else
assert(type(terminal_win_cmd) == "function", "terminal_win_cmd must be a string or a function")
return terminal_win_cmd()
end
end
local function run_in_terminal(self, request)
local body = request.arguments
log.debug('run_in_terminal', body)
local settings = dap().defaults[self.config.type]
if body.kind == 'external' or (settings.force_external_terminal and settings.external_terminal) then
local terminal = settings.external_terminal
if not terminal then
utils.notify('Requested external terminal, but none configured. Fallback to integratedTerminal', vim.log.levels.WARN)
else
local handle, pid = launch_external_terminal(terminal, body.args)
if not handle then
utils.notify('Could not launch terminal ' .. terminal.command, vim.log.levels.ERROR)
end
self:response(request, {
success = handle ~= nil;
body = { processId = pid; };
})
return
end
end
local cur_buf = api.nvim_get_current_buf()
if terminal_buf and api.nvim_buf_is_valid(terminal_buf) then
api.nvim_buf_set_option(terminal_buf, 'modified', false)
else
local terminal_win
terminal_buf, terminal_win = create_terminal_buf(settings.terminal_win_cmd)
if terminal_win then
vim.wo[terminal_win].number = false
vim.wo[terminal_win].relativenumber = false
vim.wo[terminal_win].signcolumn = "no"
end
terminal_width = terminal_win and api.nvim_win_get_width(terminal_win) or 80
terminal_height = terminal_win and api.nvim_win_get_height(terminal_win) or 40
api.nvim_buf_set_name(terminal_buf, '[dap-terminal] ' .. (self.config.name or body.args[1]))
end
local ok, path = pcall(api.nvim_buf_get_option, cur_buf, 'path')
if ok then
api.nvim_buf_set_option(terminal_buf, 'path', path)
end
local jobid
local chan = api.nvim_open_term(terminal_buf, {
on_input = function(_, _, _, data)
pcall(api.nvim_chan_send, jobid, data)
end,
})
local opts = {
env = next(body.env or {}) and body.env or vim.empty_dict(),
cwd = (body.cwd and body.cwd ~= '') and body.cwd or nil,
height = terminal_height,
width = terminal_width,
pty = true,
on_stdout = function(_, data)
api.nvim_chan_send(chan, table.concat(data, "\n"))
end,
on_exit = function(_, exit_code)
api.nvim_chan_send(chan, '\r\n[Process exited ' .. tostring(exit_code) .. ']')
api.nvim_buf_set_keymap(terminal_buf, "t", "<CR>", "<cmd>bd!<CR>", { noremap = true, silent = true})
end,
}
jobid = vim.fn.jobstart(body.args, opts)
if settings.focus_terminal then
for _, win in pairs(api.nvim_tabpage_list_wins(0)) do
if api.nvim_win_get_buf(win) == terminal_buf then
api.nvim_set_current_win(win)
break
end
end
end
if jobid == 0 or jobid == -1 then
log.error('Could not spawn terminal', jobid, request)
self:response(request, {
success = false;
message = 'Could not spawn terminal';
})
else
self:response(request, {
success = true;
body = {
processId = vim.fn.jobpid(jobid);
};
})
end
end
function Session:event_initialized()
local function on_done()
if self.capabilities.supportsConfigurationDoneRequest then
self:request('configurationDone', nil, function(err1, _)
if err1 then
utils.notify(err1.message, vim.log.levels.ERROR)
end
self.initialized = true
end)
else
self.initialized = true
end
end
local bps = breakpoints.get()
self:set_breakpoints(bps, function()
if self.capabilities.exceptionBreakpointFilters then
self:set_exception_breakpoints(dap().defaults[self.config.type].exception_breakpoints, nil, on_done)
else
on_done()
end
end)
end
function Session:_show_exception_info(thread_id)
if not self.capabilities.supportsExceptionInfoRequest then return end
self:request('exceptionInfo', {threadId = thread_id}, function(err, response)
if err then
utils.notify('Error getting exception info: ' .. err.message, vim.log.levels.ERROR)
end
if not response then return end
local exception_type = response.details and response.details.typeName
local of_type = exception_type and ' of type '..exception_type or ''
repl.append('Thread stopped due to exception'..of_type..' ('..response.breakMode..')')
if response.description then
repl.append('Description: '..response.description)
end
local details = response.details or {}
if details.stackTrace then
repl.append("Stack trace:")
repl.append(details.stackTrace)
end
if details.innerException then
repl.append("Inner Exceptions:")
for _, e in pairs(details.innerException) do
repl.append(vim.inspect(e))
end
end
end)
end
local function with_win(win, fn, ...)
local cur_win = api.nvim_get_current_win()
api.nvim_set_current_win(win)
local ok, err = pcall(fn, ...)
pcall(api.nvim_set_current_win, cur_win)
assert(ok, err)
end
local function set_cursor(win, line, column)
local ok, err = pcall(api.nvim_win_set_cursor, win, { line, column - 1 })
if ok then
with_win(win, api.nvim_command, 'normal! zv')
else
local msg = string.format(
"Debug adapter reported a frame at line %s column %s, but: %s. "
.. "Ensure executable is up2date and if using a source mapping ensure it is correct",
line,
column,
err
)
utils.notify(msg, vim.log.levels.WARN)
end
end
local function jump_to_location(bufnr, line, column)
local ok, failure = pcall(vim.fn.sign_place, 0, ns_pos, 'DapStopped', bufnr, { lnum = line; priority = 12 })
if not ok then
utils.notify(failure, vim.log.levels.ERROR)
end
progress.report('Stopped at line ' .. line)
-- vscode-go sends columns with 0
-- That would cause a "Column value outside range" error calling nvim_win_set_cursor
-- nvim-dap says "columnsStartAt1 = true" on initialize :/
if column == 0 then
column = 1
end
for _, win in pairs(api.nvim_tabpage_list_wins(0)) do
if api.nvim_win_get_buf(win) == bufnr then
set_cursor(win, line, column)
return
end
end
-- Buffer isn't active in any window; use the first window that is not special
-- (Don't want to move to code in the REPL...)
for _, win in pairs(api.nvim_tabpage_list_wins(0)) do
local winbuf = api.nvim_win_get_buf(win)
local buftype = api.nvim_buf_get_option(winbuf, 'buftype')
if buftype == '' or vim.b[winbuf].dap_source_buf == true then
local bufchanged, _ = pcall(api.nvim_win_set_buf, win, bufnr)
if bufchanged then
set_cursor(win, line, column)
return
end
end
end
utils.notify('Stopped at line ' .. line .. ' but could not jump to location', vim.log.levels.WARN)
end
local function jump_to_frame(cur_session, frame, preserve_focus_hint)
local source = frame.source
if not source then
utils.notify('Source not available, cannot jump to frame', vim.log.levels.INFO)
return
end
vim.fn.sign_unplace(ns_pos)
if preserve_focus_hint or frame.line < 0 then
return
end
if not source.sourceReference or source.sourceReference == 0 then
if not source.path then
utils.notify('Source path not available, cannot jump to frame', vim.log.levels.INFO)
return
end
local scheme = source.path:match('^([a-z]+)://.*')
local bufnr
if scheme then
bufnr = vim.uri_to_bufnr(source.path)
else
bufnr = vim.uri_to_bufnr(vim.uri_from_fname(source.path))
end
vim.fn.bufload(bufnr)
jump_to_location(bufnr, frame.line, frame.column)
else
cur_session:source(source, function(err, buf)
assert(not err, vim.inspect(err))
jump_to_location(buf, frame.line, frame.column)
end)
end
end
--- Request a source
-- @param source Source (https://microsoft.github.io/debug-adapter-protocol/specification#Types_Source)
-- @param cb (function(err, buf)) - the buffer will have the contents of the source
function Session:source(source, cb)
assert(source, 'source is required')
assert(source.sourceReference, 'sourceReference is required')
assert(source.sourceReference ~= 0, 'sourceReference must not be 0')
local params = {
source = source,
sourceReference = source.sourceReference
}
self:request('source', params, function(err, response)
if signal_err(err, cb) then return end
local buf = api.nvim_create_buf(false, true)
api.nvim_buf_set_var(buf, 'dap_source_buf', true)
local adapter_options = self.adapter.options or {}
local ft = mime_to_filetype[response.mimeType] or adapter_options.source_filetype
if ft then
api.nvim_buf_set_option(buf, 'filetype', ft)
end
api.nvim_buf_set_lines(buf, 0, -1, false, vim.split(response.content, '\n'))
if not ft and source.path and vim.filetype then
pcall(api.nvim_buf_set_name, buf, source.path)
pcall(vim.filetype.match, source.path, buf)
end
if cb then
cb(nil, buf)
end
end)
end
function Session:update_threads(cb)
self:request('threads', nil, function(err, response)
if signal_err(err, cb) then return end
local threads = {}
for _, thread in pairs(response.threads) do
threads[thread.id] = thread
end
self.threads = threads
self.dirty.threads = false
if cb then
cb(nil, threads)
end
end)
end
local function get_top_frame(frames)
for _, frame in pairs(frames) do
if frame.source and frame.source.path then
return frame
end
end
local _, first = next(frames)
return first
end
function Session:event_stopped(stopped)
if self.dirty.threads or (stopped.threadId and self.threads[stopped.threadId] == nil) then
self:update_threads(function(err)
if err then
utils.notify('Error retrieving threads: ' .. err.message, vim.log.levels.ERROR)
return
end
self:event_stopped(stopped)
end)
return
end
local should_jump = stopped.reason ~= 'pause' or stopped.allThreadsStopped
if self.stopped_thread_id and should_jump then
local thread = self.threads[self.stopped_thread_id]
if defaults(self).auto_continue_if_many_stopped then
log.debug(
'Received stopped event, but ' .. thread.name .. ' is already stopped. ' ..
'Resuming newly stopped thread. ' ..
'To disable this set the `auto_continue_if_many_stopped` option to false.')
self:request('continue', { threadId = stopped.threadId })
else
-- Allow thread to stop, but don't jump to it because stepping
-- interleaved between threads is confusing
should_jump = false
end
end
if should_jump then
self.stopped_thread_id = stopped.threadId
end
if stopped.allThreadsStopped then
progress.report('All threads stopped')
utils.notify(
'All threads stopped. ' .. stopped.reason and 'Reason: ' .. stopped.reason or '',
vim.log.levels.INFO
)
for _, thread in pairs(self.threads) do
thread.stopped = true
end
elseif stopped.threadId then
progress.report('Thread stopped: ' .. stopped.threadId)
self.threads[stopped.threadId].stopped = true
else
utils.notify('Stopped event received, but no threadId or allThreadsStopped', vim.log.levels.WARN)
end
if stopped.reason == 'exception' then
self:_show_exception_info(stopped.threadId)
end
if not stopped.threadId then
return
end
local thread = self.threads[stopped.threadId]
assert(thread, 'Thread not found: ' .. stopped.threadId)
self:request('stackTrace', { threadId = stopped.threadId; }, function(err, response)
if err then
utils.notify('Error retrieving stack traces: ' .. err.message, vim.log.levels.ERROR)
return
end
local frames = response.stackFrames
thread.frames = frames
local current_frame = get_top_frame(frames)
if not current_frame then
utils.notify('Debug adapter stopped at unavailable location', vim.log.levels.WARN)
return
end
if should_jump then
self.current_frame = current_frame
jump_to_frame(self, current_frame, stopped.preserveFocusHint)
self:_request_scopes(current_frame)
end
end)
end
function Session:event_terminated()
self:close()
dap().set_session(nil)
end
function Session.event_output(_, body)
if body.category == 'telemetry' then
log.info('Telemetry', body.output)
else
repl.append(body.output, '$')
end
end
function Session:_request_scopes(current_frame)
self:request('scopes', { frameId = current_frame.id }, function(_, scopes_resp)
if not scopes_resp or not scopes_resp.scopes then return end
current_frame.scopes = {}
for _, scope in pairs(scopes_resp.scopes) do
table.insert(current_frame.scopes, scope)
if not scope.expensive then
self:request('variables', { variablesReference = scope.variablesReference }, function(_, variables_resp)
if not variables_resp then return end
scope.variables = utils.to_dict(
variables_resp.variables,
function(v) return v.name end
)
end)
end
end
end)
end
--- Goto specified line (source and col are optional)
function Session:_goto(line, source, col)
local frame = self.current_frame
if not frame then
return
end
if not self.capabilities.supportsGotoTargetsRequest then
utils.notify("Debug Adapter doesn't support GotoTargetRequest", vim.log.levels.INFO)
return
end
self:request('gotoTargets', {source = source or frame.source, line = line, col = col}, function(err, response)
if err then
utils.notify('Error getting gotoTargets: ' .. err.message, vim.log.levels.ERROR)
return
end
if not response or not response.targets then
utils.notify("No goto targets available. Can't execute goto", vim.log.levels.INFO)
return
end
local params = {threadId = self.stopped_thread_id, targetId = response.targets[1].id }
self:request('goto', params, function(err1, _)
if err1 then
utils.notify('Error executing goto: ' .. err1.message, vim.log.levels.ERROR)
end
end)
end)
end
do
local function notify_if_missing_capability(bps, capabilities)
for _, bp in pairs(bps) do
if non_empty(bp.condition) and not capabilities.supportsConditionalBreakpoints then
utils.notify("Debug adapter doesn't support breakpoints with conditions", vim.log.levels.WARN)
end
if non_empty(bp.hitCondition) and not capabilities.supportsHitConditionalBreakpoints then
utils.notify("Debug adapter doesn't support breakpoints with hit conditions", vim.log.levels.WARN)
end
if non_empty(bp.logMessage) and not capabilities.supportsLogPoints then
utils.notify("Debug adapter doesn't support log points", vim.log.levels.WARN)
end
end
end
local detach_handlers = {}
function Session:set_breakpoints(bps, on_done)
local num_requests = vim.tbl_count(bps)
if num_requests == 0 then
if on_done then
on_done()
end
return
end
for bufnr, buf_bps in pairs(bps) do
notify_if_missing_capability(buf_bps, self.capabilities)
local on_detach = detach_handlers[bufnr]
if not on_detach and non_empty(buf_bps) then
on_detach = function()
self:set_breakpoints({[bufnr] = {}})
detach_handlers[bufnr] = nil
end
detach_handlers[bufnr] = on_detach
api.nvim_buf_attach(bufnr, false, { on_detach = on_detach })
end
local path = api.nvim_buf_get_name(bufnr)
local payload = {
source = {
path = path;
name = vim.fn.fnamemodify(path, ':t')
};
sourceModified = false;
breakpoints = vim.tbl_map(
function(bp)
-- trim extra information like the state
return {
line = bp.line,
column = bp.column,
condition = bp.condition,
hitCondition = bp.hitCondition,
logMessage = bp.logMessage,
}
end,
buf_bps
),
lines = vim.tbl_map(function(x) return x.line end, buf_bps);
}
self:request('setBreakpoints', payload, function(err1, resp)
if err1 then
utils.notify('Error setting breakpoints: ' .. err1.message, vim.log.levels.ERROR)
else
for _, bp in pairs(resp.breakpoints) do
breakpoints.set_state(bufnr, bp.line, bp)
if not bp.verified then
log.info('Server rejected breakpoint', bp)
if bp.message then
utils.notify(bp.message, vim.log.levels.ERROR)
end
end
end
end
num_requests = num_requests - 1
if num_requests == 0 and on_done then
on_done()
end
end)
end
end
end
function Session:set_exception_breakpoints(filters, exceptionOptions, on_done)
if not self.capabilities.exceptionBreakpointFilters then
utils.notify("Debug adapter doesn't support exception breakpoints", vim.log.levels.INFO)
return
end
if filters == 'default' then
local default_filters = {}
for _, f in pairs(self.capabilities.exceptionBreakpointFilters) do
if f.default then
table.insert(default_filters, f.filter)
end
end
filters = default_filters
end
if not filters then
local possible_filters = {}
for _, f in ipairs(self.capabilities.exceptionBreakpointFilters) do
table.insert(possible_filters, f.filter)
end
filters = vim.split(vim.fn.input("Exception breakpoint filters: ", table.concat(possible_filters, ' ')), ' ')
end
if exceptionOptions and not self.capabilities.supportsExceptionOptions then
utils.notify('Debug adapter does not support ExceptionOptions', vim.log.levels.INFO)
return
end
-- setExceptionBreakpoints (https://microsoft.github.io/debug-adapter-protocol/specification#Requests_SetExceptionBreakpoints)
--- filters: string[]
--- exceptionOptions: exceptionOptions?: ExceptionOptions[] (https://microsoft.github.io/debug-adapter-protocol/specification#Types_ExceptionOptions)
self:request(
'setExceptionBreakpoints',
{ filters = filters, exceptionOptions = exceptionOptions },
function(err, _)
if err then
utils.notify('Error setting exception breakpoints: ' .. err.message, vim.log.levels.ERROR)
end
if on_done then
on_done()
end
end)
end
function Session:handle_body(body)
local decoded = json_decode(body)
log.debug(decoded)
local listeners = dap().listeners
if decoded.request_seq then
local callback = self.message_callbacks[decoded.request_seq]
local request = self.message_requests[decoded.request_seq]
self.message_requests[decoded.request_seq] = nil
self.message_callbacks[decoded.request_seq] = nil
if not callback then
log.warn('No callback for ', decoded)
callback = function() end
end
if decoded.success then
vim.schedule(function()
for _, c in pairs(listeners.before[decoded.command]) do
c(self, nil, decoded.body, request)
end
callback(nil, decoded.body)
for _, c in pairs(listeners.after[decoded.command]) do
c(self, nil, decoded.body, request)
end
end)
else
vim.schedule(function()
local err = { message = decoded.message; body = decoded.body; }
for _, c in pairs(listeners.before[decoded.command]) do
c(self, err, nil, request)
end
callback(err, nil)
for _, c in pairs(listeners.after[decoded.command]) do
c(self, err, nil, request)
end
end)
end
elseif decoded.event then
local callback = self['event_' .. decoded.event]
vim.schedule(function()
local event_handled = false
for _, c in pairs(listeners.before['event_' .. decoded.event]) do
event_handled = true
c(self, decoded.body)
end
if callback then
event_handled = true
callback(self, decoded.body)
end
for _, c in pairs(listeners.after['event_' .. decoded.event]) do
event_handled = true
c(self, decoded.body)
end
if not event_handled then
log.warn('No event handler for ', decoded)
end
end)
elseif decoded.type == 'request' then
local handler = self.handlers.reverse_requests[decoded.command]
if handler then
handler(self, decoded)
else
log.warn('No handler for reverse request', decoded)
end
else
log.warn('Received unexpected message', decoded)
end
end
local default_reverse_request_handlers = {
runInTerminal = run_in_terminal
}
---@return Session
local function new_session(adapter, opts)
local handlers = {}
handlers.after = opts.after
handlers.reverse_requests = vim.tbl_extend(
'error',
default_reverse_request_handlers,
adapter.reverse_request_handlers or {}
)
local state = {
handlers = handlers;
message_callbacks = {};
message_requests = {};
initialized = false;
seq = 0;
stopped_thread_id = nil;
current_frame = nil;
threads = {};
adapter = adapter;
dirty = {};
}
return setmetatable(state, { __index = Session })
end
function Session.connect(_, adapter, opts, on_connect)
log.debug('Connecting to debug adapter', adapter)
local session = new_session(adapter, opts or {})
local closed = false
local client = uv.new_tcp()
session.client = {
write = function(line)
client:write(line)
end;
close = function()
if closed then
return
end
closed = true
client:shutdown()
client:close()
end;
}
local host = adapter.host or '127.0.0.1'
local on_addresses = function(err, addresses)
if err or #addresses == 0 then
err = err or ('Could not resolve ' .. host)
on_connect(err)
return
end
local address = addresses[1]
client:connect(address.addr, tonumber(adapter.port), function(conn_err)
if not conn_err then
local handle_body = vim.schedule_wrap(function(body)
session:handle_body(body)
end)
client:read_start(rpc.create_read_loop(handle_body, function()
if not closed then
closed = true
client:shutdown()
client:close()
end
local s = dap().session()
if s == session then
vim.schedule(function()
utils.notify('Debug adapter disconnected', vim.log.levels.INFO)
end)
dap().set_session(nil)
end
end))
end
on_connect(conn_err)
end)
end
-- getaddrinfo fails for some users with `bad argument #3 to 'getaddrinfo' (Invalid protocol hint)`
-- It should generally work with luv 1.42.0 but some still get errors
if vim.loop.version() >= 76288 then
local ok, err = pcall(uv.getaddrinfo, host, nil, { protocol = 'tcp' }, on_addresses)
if not ok then
log.warn(err)
on_addresses(nil, { { addr = host }, })
end
else
on_addresses(nil, { { addr = host }, })
end
return session
end
---@param adapter ExecutableAdapter
---@param opts table|nil
---@return Session
function Session.spawn(_, adapter, opts)
log.debug('Spawning debug adapter', adapter)
local session = new_session(adapter, opts or {})
local stdin = uv.new_pipe(false)
local stdout = uv.new_pipe(false)
local stderr = uv.new_pipe(false)
local handle
local pid_or_err
local closed = false
local function onexit()
if closed then
return
end
closed = true
stdin:shutdown(function()
stdout:close()
stderr:close()
log.info('Closed all handles')
if handle and not handle:is_closing() then
handle:close(function()
log.info('Process closed', pid_or_err, handle:is_active())
handle = nil
end)
end
end)
end
local options = adapter.options or {}
local spawn_opts = {
args = adapter.args;
stdio = {stdin, stdout, stderr};
cwd = options.cwd;
env = options.env;
detached = utils.if_nil(options.detached, true);
}
handle, pid_or_err = uv.spawn(adapter.command, spawn_opts, onexit)
if not handle then
onexit()
error('Error running ' .. adapter.command .. ': ' .. pid_or_err)
end
session.client = {
write = function(line) stdin:write(line) end;
close = onexit,
}
stdout:read_start(rpc.create_read_loop(vim.schedule_wrap(function(body)
session:handle_body(body)
end)))
stderr:read_start(function(err, chunk)
assert(not err, err)
if chunk then
log.error("stderr", adapter, chunk)
end
end)
return session
end
local function pause_thread(session, thread_id, cb)
assert(session, 'Cannot pause thread without active session')
assert(thread_id, 'thread_id is required to pause thread')
session:request('pause', { threadId = thread_id; }, function(err)
if err then
utils.notify('Error pausing: ' .. err.message, vim.log.levels.ERROR)
else
utils.notify('Thread paused ' .. thread_id, vim.log.levels.INFO)