forked from mfussenegger/nvim-dap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dap.lua
1309 lines (1169 loc) · 35.8 KB
/
dap.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
dap = {} -- luacheck: ignore 111 - to support v:lua.dap... uses
local uv = vim.loop
local api = vim.api
local log = require('dap.log').create_logger('vim-dap.log')
local ui = require('dap.ui.share')
local repl = require('dap.repl')
local utils = require('dap.utils')
local non_empty_sequence = utils.non_empty_sequence
local index_of = utils.index_of
local M = {}
local ns_breakpoints = 'dap_breakpoints'
local ns_pos = 'dap_pos'
local Session = {}
local session = nil
local bp_info = {}
local last_run = nil
M.repl = repl
M.custom_event_handlers = setmetatable({}, {
__index = function(tbl, key)
rawset(tbl, key, {})
return rawget(tbl, key)
end
})
M.custom_response_handlers = setmetatable({}, {
__index = function(tbl, key)
rawset(tbl, key, {})
return rawget(tbl, key)
end
})
local DAP_QUICKFIX_TITLE = "DAP Breakpoints"
local DAP_QUICKFIX_CONTEXT = DAP_QUICKFIX_TITLE
--- For extension of language specific debug adapters.
--
-- `adapters.<type>` where <type> is specified in a configuration.
--
-- For example:
--
-- require('dap').adapters.python = {
-- type = 'executable';
-- command = '/path/to/python';
-- args = {'-m', 'debugpy.adapter' };
-- }
--
M.adapters = {}
--- Configurations for languages
--
-- Example:
--
-- require('dap').configurations.python = {
-- {
-- type = 'python';
-- request = 'launch';
-- name = "Launch file";
--
-- -- ${file} and ${workspaceFolder} variables are supported
-- program = "${file}";
--
-- -- values other than type, request and name can be functions, they'll be evaluated when the configuration is used
-- pythonPath = function()
-- local cwd = vim.fn.getcwd()
-- if vim.fn.executable(cwd .. '/venv/bin/python') then
-- return cwd .. '/venv/bin/python'
-- elseif vim.fn.executable(cwd .. '/.venv/bin/python') then
-- return cwd .. '/.venv/bin/python'
-- else
-- return '/usr/bin/python'
-- end
-- end;
-- }
-- }
--
M.configurations = {}
function M.session() return session end
vim.fn.sign_define('DapBreakpoint', {text='B', texthl='', linehl='', numhl=''})
vim.fn.sign_define('DapLogPoint', {text='L', texthl='', linehl='', numhl=''})
vim.fn.sign_define('DapStopped', {text='→', texthl='', linehl='debugPC', numhl=''})
local function expand_config_variables(option)
if type(option) == 'function' then
option = option()
end
if type(option) == "table" and vim.tbl_islist(option) then
return vim.tbl_map(expand_config_variables, option)
end
if type(option) ~= "string" then
return option
end
local variables = {
file = vim.fn.expand("%");
workspaceFolder = vim.fn.getcwd();
}
local ret = option
for key, val in pairs(variables) do
ret = ret:gsub('${' .. key .. '}', val)
end
return ret
end
local function run_adapter(adapter, configuration, opts)
if adapter.type == 'executable' then
M.launch(adapter, configuration, opts)
elseif adapter.type == 'server' then
M.attach(adapter.host, adapter.port, configuration, opts)
else
print(string.format('Invalid adapter type %s, expected `executable` or `server`', adapter.type))
end
end
local function maybe_enrich_config_and_run(adapter, configuration, opts)
assert(type(adapter) == 'table', 'adapter must be a table, not' .. vim.inspect(adapter))
assert(
adapter.type,
'Adapter for ' .. configuration.type .. ' must have the `type` property set to `executable` or `server`'
)
if adapter.enrich_config then
assert(
type(adapter.enrich_config) == 'function',
'`enrich_config` property of adapter must be a function: ' .. vim.inspect(adapter)
)
adapter.enrich_config(configuration, function(config)
run_adapter(adapter, config, opts)
end)
else
run_adapter(adapter, configuration, opts)
end
end
local function select_config_and_run()
local filetype = api.nvim_buf_get_option(0, 'filetype')
local configurations = M.configurations[filetype] or {}
local configuration = ui.pick_one(configurations, "Configuration: ", function(i) return i.name end)
if not configuration then
assert(
vim.tbl_islist(configurations),
'configurations for '
.. filetype
.. ' must be a list of config objects, not a table: '
.. vim.inspect(configurations)
)
print('No configuration found for ' .. filetype)
return
end
M.run(configuration)
end
function M.run(config, opts)
opts = opts or {}
last_run = {
config = config,
opts = opts,
}
if opts.before then
config = opts.before(config)
end
local adapter = M.adapters[config.type]
if type(adapter) == 'table' then
config = vim.tbl_map(expand_config_variables, config)
maybe_enrich_config_and_run(adapter, config, opts)
elseif type(adapter) == 'function' then
adapter(function(resolved_adapter)
config = vim.tbl_map(expand_config_variables, config)
maybe_enrich_config_and_run(resolved_adapter, config, opts)
end)
else
print(string.format('Invalid adapter: %q', adapter))
end
end
function M.run_last()
if last_run then
M.run(last_run.config, last_run.opts)
else
print('No configuration available to re-run')
end
end
function Session:run_in_terminal(request)
local body = request.arguments
-- env option is ignored without https://github.com/neovim/neovim/pull/11839
local opts = {
clear_env = false;
env = body.env;
}
local _ = log.debug() and log.debug('run_in_terminal', body.args, opts)
local win = api.nvim_get_current_win()
api.nvim_command('belowright new')
local jobid = vim.fn.termopen(body.args, opts)
api.nvim_set_current_win(win)
if jobid == 0 or jobid == -1 then
local _ = log.error() and 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
local function msg_with_content_length(msg)
return table.concat {
'Content-Length: ';
tostring(#msg);
'\r\n\r\n';
msg
}
end
-- Copied from neovim rpc.lua
local function parse_headers(header)
if type(header) ~= 'string' then
return nil
end
local headers = {}
for line in vim.gsplit(header, '\r\n', true) do
if line == '' then
break
end
local key, value = line:match('^%s*(%S+)%s*:%s*(.+)%s*$')
if key then
key = key:lower():gsub('%-', '_')
headers[key] = value
else
error(string.format("Invalid header line %q", line))
end
end
headers.content_length = tonumber(headers.content_length)
or error(string.format("Content-Length not found in headers. %q", header))
return headers
end
-- Mostly copied from neovim rpc.lua
local header_start_pattern = ("content"):gsub("%w", function(c) return "["..c..c:upper().."]" end)
local function parse_chunk_loop()
local buffer = ''
while true do
local start, finish = buffer:find('\r\n\r\n', 1, true)
if start then
local buffer_start = buffer:find(header_start_pattern)
local headers = parse_headers(buffer:sub(buffer_start, start - 1))
buffer = buffer:sub(finish + 1)
local content_length = headers.content_length
while #buffer < content_length do
buffer = buffer .. (coroutine.yield()
or error("Expected more data for the body. The server may have died."))
end
local body = buffer:sub(1, content_length)
buffer = buffer:sub(content_length + 1)
buffer = buffer .. (coroutine.yield(headers, body)
or error("Expected more data for the body. The server may have died."))
else
buffer = buffer .. (coroutine.yield()
or error("Expected more data for the header. The server may have died."))
end
end
end
function Session:event_initialized(_)
local function on_done()
if self.capabilities.supportsConfigurationDoneRequest then
self:request('configurationDone', nil, function(err1, _)
if err1 then
print(err1.message)
end
self.initialized = true
end)
else
self.initialized = true
end
end
self:set_breakpoints(nil, function()
if self.capabilities.exceptionBreakpointFilters then
self:set_exception_breakpoints('default', nil, on_done)
else
on_done()
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, ...)
api.nvim_set_current_win(cur_win)
assert(ok, err)
end
local function jump_to_frame(frame, preserve_focus_hint)
if not frame.source then
return
end
if not frame.source.path then
print('Source path not available, cannot jump to frame')
return
end
local scheme = frame.source.path:match('^([a-z]+)://.*')
local bufnr
if scheme then
bufnr = vim.uri_to_bufnr(frame.source.path)
else
bufnr = vim.uri_to_bufnr(vim.uri_from_fname(frame.source.path))
end
vim.fn.sign_unplace(ns_pos)
if preserve_focus_hint or frame.line < 0 then
return
end
vim.fn.bufload(bufnr)
local ok, failure = pcall(vim.fn.sign_place, 0, ns_pos, 'DapStopped', bufnr, { lnum = frame.line; priority = 12 })
if not ok then
print(failure)
end
-- 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 frame.column == 0 then
frame.column = 1
end
for _, win in pairs(api.nvim_list_wins()) do
if api.nvim_win_get_buf(win) == bufnr then
api.nvim_win_set_cursor(win, { frame.line, frame.column - 1 })
with_win(win, api.nvim_command, 'normal zv')
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_list_wins()) do
local winbuf = api.nvim_win_get_buf(win)
if api.nvim_buf_get_option(winbuf, 'buftype') == '' then
local bufchanged, _ = pcall(api.nvim_win_set_buf, win, bufnr)
if bufchanged then
api.nvim_win_set_cursor(win, { frame.line, frame.column - 1 })
with_win(win, api.nvim_command, 'normal zv')
return
end
end
end
end
function Session:_show_exception_info()
if not self.capabilities.supportsExceptionInfoRequest then return end
-- exceptionInfo (https://microsoft.github.io/debug-adapter-protocol/specification#Requests_ExceptionInfo)
--- threadId: number
self:request('exceptionInfo', {threadId = self.stopped_thread_id}, function(err, response)
if err then
print("Error getting exception info: "..err.message)
end
-- ExceptionInfoResponse
--- exceptionId: string
--- description?: string
--- breakMode: ExceptionBreakMode (https://microsoft.github.io/debug-adapter-protocol/specification#Types_ExceptionBreakMode)
--- details?: ExceptionDetails (https://microsoft.github.io/debug-adapter-protocol/specification#Types_ExceptionDetails)
if response then
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
-- ExceptionDetails (https://microsoft.github.io/debug-adapter-protocol/specification#Types_ExceptionDetails)
--- message?: string
--- typeName?: string
--- fullTypeName?: string
--- evaluateName?: string
--- stackTrace?: string
--- innerException?: ExceptionDetails[]
if response.details then
if response.details.stackTrace then
repl.append("Stack trace:")
repl.append(response.details.stackTrace)
end
if response.details.innerException then
repl.append("Inner Exceptions:")
for _, e in pairs(response.details.innerException) do
repl.append(vim.inspect(e))
end
end
end
end
end)
end
function Session:event_stopped(stopped)
if self.stopped_thread_id then
log.debug('Thread stopped, but another thread is already stopped, telling thread to continue')
session:request('continue', { threadId = stopped.threadId })
return
end
self.stopped_thread_id = stopped.threadId
self:request('threads', nil, function(err0, threads_resp)
if err0 then
print('Error retrieving threads: ' .. err0.message)
return
end
local threads = {}
self.threads = threads
for _, thread in pairs(threads_resp.threads) do
threads[thread.id] = thread
end
if stopped.reason == 'exception' then
self:_show_exception_info()
end
self:request('stackTrace', { threadId = stopped.threadId; }, function(err1, frames_resp)
if err1 then
print('Error retrieving stack traces: ' .. err1.message)
return
end
local frames = {}
local current_frame = nil
self.current_frame = nil
threads[stopped.threadId].frames = frames
for _, frame in pairs(frames_resp.stackFrames) do
if not current_frame and frame.source and frame.source.path then
current_frame = frame
self.current_frame = frame
end
table.insert(frames, frame)
end
if not current_frame then
current_frame = frames[1]
self.current_frame = current_frame
end
if not current_frame then
return
end
local preserve_focus
if stopped.reason ~= 'pause' then
preserve_focus = stopped.preserveFocusHint
end
jump_to_frame(current_frame, preserve_focus)
self:_request_scopes(current_frame)
end)
end)
end
function Session:event_terminated()
self:close()
if self.handlers.after then
self.handlers.after()
end
session = nil
end
function Session.event_exited()
end
function Session.event_module()
end
function Session.event_process()
end
function Session.event_thread()
end
function Session.event_continued()
end
function Session.event_output(_, body)
repl.append(body.output, '$')
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
-- Look up: name -> variable
scope.variables = utils.map_to_key(function(v) return v.name end, variables_resp.variables)
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
print("Debug Adapter doesn't support GotoTargetRequest")
return
end
self:request('gotoTargets', {source = source or frame.source, line = line, col = col}, function(err, response)
if err then
print('Error getting gotoTargets: ' .. err.message)
return
end
if not response or not response.targets then
print("No goto targets available. Can't execute goto")
return
end
local params = {threadId = session.stopped_thread_id, targetId = response.targets[1].id }
self:request('goto', params, function(err1, _)
if err1 then
print('Error executing goto: ' .. err1.message)
end
end)
end)
end
function Session:_frame_set(frame)
if not frame then
return
end
self.current_frame = frame
jump_to_frame(self.current_frame, false)
self:_request_scopes(self.current_frame)
end
function Session:_frame_delta(delta)
if not self.stopped_thread_id then
print('Cannot move frame if not stopped')
return
end
local frames = self.threads[self.stopped_thread_id].frames
assert(frames, 'Stopped thread must have frames')
local current_frame_index = index_of(frames, function(i) return i.id == self.current_frame.id end)
assert(current_frame_index, 'id of current frame must be present in frames')
current_frame_index = current_frame_index + delta
if current_frame_index < 1 then
current_frame_index = #frames
elseif current_frame_index > #frames then
current_frame_index = 1
end
self:_frame_set(frames[current_frame_index])
end
local function remove_breakpoint_signs(bufnr, lnum)
local signs = vim.fn.sign_getplaced(bufnr, { group = ns_breakpoints; lnum = lnum; })[1].signs
if signs and #signs > 0 then
for _, sign in pairs(signs) do
vim.fn.sign_unplace(ns_breakpoints, { buffer = bufnr; id = sign.id; })
bp_info[sign.id] = nil
end
return true
else
return false
end
end
local function get_breakpoint_signs(bufexpr)
if bufexpr then
return vim.fn.sign_getplaced(bufexpr, {group = ns_breakpoints})
end
local bufs_with_signs = vim.fn.sign_getplaced()
local result = {}
for _, buf_signs in ipairs(bufs_with_signs) do
buf_signs = vim.fn.sign_getplaced(buf_signs.bufnr, {group = ns_breakpoints})[1]
if #buf_signs.signs > 0 then
table.insert(result, buf_signs)
end
end
return result
end
function Session:set_breakpoints(bufexpr, on_done)
local bp_signs = get_breakpoint_signs(bufexpr)
local num_bufs = #bp_signs
if num_bufs == 0 then
on_done()
return
end
for _, buf_bp_signs in pairs(bp_signs) do
local breakpoints = {}
local bufnr = buf_bp_signs.bufnr
for _, bp in pairs(buf_bp_signs.signs) do
local bp_entry = bp_info[bp.id] or {}
table.insert(breakpoints, {
line = bp.lnum;
condition = bp_entry.condition;
hitCondition = bp_entry.hitCondition;
logMessage = bp_entry.logMessage;
})
end
if non_empty_sequence(bp_info.condition) and not self.capabilities.supportsConditionalBreakpoints then
print("Debug adapter doesn't support breakpoints with conditions")
end
if non_empty_sequence(bp_info.hitCondition) and not self.capabilities.supportsHitConditionalBreakpoints then
print("Debug adapter doesn't support breakpoints with hit conditions")
end
if non_empty_sequence(bp_info.logMessage) and not self.capabilities.supportsLogPoints then
print("Debug adapter doesn't support log points")
end
local path = api.nvim_buf_get_name(bufnr)
local payload = {
source = {
path = path;
name = vim.fn.fnamemodify(path, ':t')
};
breakpoints = breakpoints;
lines = vim.tbl_map(function(x) return x.line end, breakpoints);
}
self:request('setBreakpoints', payload, function(err1, resp)
if err1 then
print("Error setting breakpoints: " .. err1.message)
else
for _, bp in pairs(resp.breakpoints) do
if not bp.verified then
log.info('Server rejected breakpoint', bp)
remove_breakpoint_signs(bufnr, bp.line)
end
end
end
num_bufs = num_bufs - 1
if num_bufs == 0 and on_done then
on_done()
end
end
)
end
end
function Session:set_exception_breakpoints(filters, exceptionOptions, on_done)
if not self.capabilities.exceptionBreakpointFilters then
print("Debug adapter doesn't support exception breakpoints")
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
print("Debug adapter does not support ExceptionOptions")
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
print("Error setting exception breakpoints: "..err.message)
end
if on_done then
on_done()
end
end)
end
function Session:handle_body(body)
local decoded = vim.fn.json_decode(body)
self.seq = decoded.seq + 1
local _ = log.debug() and log.debug(decoded)
if decoded.request_seq then
local callback = self.message_callbacks[decoded.request_seq]
local request = self.message_requests[decoded.request_seq]
if not callback then
log.warn('No callback for ', decoded)
return
end
self.message_callbacks[decoded.request_seq] = nil
self.message_requests[decoded.request_seq] = nil
if decoded.success then
vim.schedule(function()
callback(nil, decoded.body)
for _, c in pairs(M.custom_response_handlers[decoded.command]) do
c(self, decoded.body, request)
end
end)
else
vim.schedule(function()
callback({ message = decoded.message; body = decoded.body; }, nil)
end)
end
elseif decoded.event then
local callback = self['event_' .. decoded.event]
if callback then
vim.schedule(function()
callback(self, decoded.body)
for _, c in pairs(M.custom_event_handlers['event_' .. decoded.event]) do
c(self, decoded.body)
end
end)
else
log.warn('No event handler for ', decoded)
end
elseif decoded.type == 'request' and decoded.command == 'runInTerminal' then
self:run_in_terminal(decoded)
else
local _ = log.warn() and log.warn('Received unexpected message', decoded)
end
end
local function session_defaults(opts)
local handlers = {}
handlers.after = opts.after
return {
handlers = handlers;
message_callbacks = {};
message_requests = {};
initialized = false;
seq = 0;
stopped_thread_id = nil;
current_frame = nil;
threads = {};
}
end
local function create_read_loop(handle_body)
local parse_chunk = coroutine.wrap(parse_chunk_loop)
parse_chunk()
return function (err, chunk)
if err then
print(err)
return
end
if not chunk then
return
end
while true do
local headers, body = parse_chunk(chunk)
if headers then
vim.schedule(function()
handle_body(body)
end)
chunk = ''
else
break
end
end
end
end
function Session:connect(host, port, opts)
local o = session_defaults(opts or {})
setmetatable(o, self)
self.__index = self
local client = uv.new_tcp()
o.client = {
write = function(line) client:write(line) end;
close = function()
client:shutdown()
client:close()
end;
}
client:connect(host or '127.0.0.1', tonumber(port), function(err)
if (err) then print(err) end
end)
client:read_start(create_read_loop(function(body) session:handle_body(body) end))
return o
end
function Session:spawn(adapter, opts)
local o = session_defaults(opts or {})
setmetatable(o, self)
self.__index = self
local stdin = uv.new_pipe(false)
local stdout = uv.new_pipe(false)
local stderr = uv.new_pipe(false)
local handle
local function onexit()
stdin:close()
stdout:close()
stderr:close()
handle:close()
end
local options = adapter.options or {}
local pid_or_err
handle, pid_or_err = uv.spawn(adapter.command, {
args = adapter.args;
stdio = {stdin, stdout, stderr};
cwd = options.cwd;
env = options.env;
}, onexit)
assert(handle, 'Error running ' .. adapter.command .. ': ' .. pid_or_err)
o.client = {
write = function(line) stdin:write(line) end;
close = function()
if handle then
pcall(handle.close, handle)
end
end;
}
stdout:read_start(create_read_loop(function(body)
if session then
session:handle_body(body)
end
end))
stderr:read_start(function(err, chunk)
assert(not err, err)
if chunk then
local _ = log.error() and log.error("stderr", adapter, chunk)
end
end)
return o
end
function Session:close()
vim.fn.sign_unplace(ns_pos)
self.threads = {}
self.message_callbacks = {}
self.message_requests = {}
self.client.close()
repl.set_session(nil)
end
function Session:request(command, arguments, callback)
local payload = {
seq = self.seq;
type = 'request';
command = command;
arguments = arguments
}
local _ = log.debug() and log.debug('request', payload)
local current_seq = self.seq
self.seq = self.seq + 1
vim.schedule(function()
local msg = msg_with_content_length(vim.fn.json_encode(payload))
self.client.write(msg)
if callback then
self.message_callbacks[current_seq] = callback
self.message_requests[current_seq] = arguments
end
end)
end
function Session:response(request, payload)
payload.seq = self.seq
self.seq = self.seq + 1
payload.type = 'response'
payload.request_seq = request.seq;
payload.command = request.command;
local _ = log.debug() and log.debug('response', payload)
vim.schedule(function()
local msg = msg_with_content_length(vim.fn.json_encode(payload))
self.client.write(msg)
end)
end
function Session:initialize(config)
self:request('initialize', {
clientId = 'neovim';
clientname = 'neovim';
adapterID = 'nvim-dap';
pathFormat = 'path';
columnsStartAt1 = true;
linesStartAt1 = true;
supportsRunInTerminalRequest = true;
locale = os.getenv('LANG') or 'en_US';
}, function(err0, result)
if err0 then
print("Could not initialize debug adapter: " .. err0.message)
return
end
session.capabilities = result
session:request(config.request, config, function(err)
if err then
print(string.format('Error on %s: %s', config.request, err.message))
session:close()
session = nil
return
end
repl.set_session(session)
end)
end)
end
function Session:evaluate(expression, fn)
self:request('evaluate', {
expression = expression;
context = 'repl';
frameId = (self.current_frame or {}).id;
}, fn)
end
function Session:disconnect()
self:request('disconnect', {
restart = false,
terminateDebuggee = true;
})
end
function Session:_pause(thread_id)
if self.stopped_thread_id then
print('One thread is already stopped. Cannot pause!')
return
end
self:request('threads', nil, function(err0, response)
if err0 then
print('Error requesting threads: ' .. err0.message)
end
if not thread_id then
local answer = ui.pick_one(response.threads, "Which thread?: ", function(t) return t.name end)
if not answer or not answer.id then
print('No thread to stop. Not pausing...')
return
end
thread_id = answer.id
end
session:request('pause', { threadId = thread_id; }, function(err1, _)
if err1 then
print('Error pausing: ' .. err1.message)
end
end)
end)
end
function Session:_step(step)
if vim.tbl_contains({"stepBack", "reverseContinue"}, step) and not session.capabilities.supportsStepBack then
print("Debug Adapter does not support "..step.."!")
return
end
if not self.stopped_thread_id then
print('No stopped thread. Cannot move')
return
end
local thread_id = self.stopped_thread_id
self.stopped_thread_id = nil
vim.fn.sign_unplace(ns_pos)
session:request(step, { threadId = thread_id; }, function(err0, _)
if err0 then
print('Error on '.. step .. ': ' .. err0.message)
end
end)
end
function M.step_over()