forked from emacs-lsp/dap-mode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dap-mode.el
1891 lines (1678 loc) · 80.6 KB
/
dap-mode.el
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-mode.el --- Debug Adapter Protocol mode -*- lexical-binding: t; -*-
;; Copyright (C) 2019 Ivan Yonchovski
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
;; Author: Ivan Yonchovski <[email protected]>
;; Keywords: languages, debug
;; URL: https://github.com/emacs-lsp/dap-mode
;; Package-Requires: ((emacs "26.1") (dash "2.18.0") (lsp-mode "6.0") (bui "1.1.0") (f "0.20.0") (s "1.12.0") (lsp-treemacs "0.1") (posframe "0.7.0") (ht "2.3"))
;; Version: 0.6
;;; Commentary:
;; Debug Adapter Protocol client for Emacs.
;;; Code:
(require 'lsp-mode)
(require 'json)
(require 'f)
(require 'dash)
(require 'dap-overlays)
(require 'cl-lib)
(require 'ansi-color)
(require 'posframe)
(require 'ht)
(require 'dap-launch)
(defcustom dap-breakpoints-file (expand-file-name (locate-user-emacs-file ".dap-breakpoints"))
"Where to persist breakpoints"
:group 'dap-mode
:type 'file)
(defcustom dap-print-io nil
"If non-nil, print all messages to and from the DAP to messages."
:group 'dap-mode
:type 'boolean)
(defcustom dap-external-terminal '("xterm" "-T" "{title}"
"-hold" "-e" "sh" "-c" "exec {command}")
"Command to launch the external terminal for debugging.
When specifying that the program be run in an external terminal,
this command is used to launch it. It shall be a list of strings,
the first of which is the program to run and the rest of which
are arguments to pass to it. Special expansion is performed:
{command} will be replaced with the program to execute.
{display} will be replaced with window title.
See also `dap-default-terminal-kind'."
:group 'dap-mode
:type '(repeat string))
(defun dap--make-terminal-buffer (title debug-session)
"Generate an internal terminal buffer.
The name is derived from TITLE and DEBUG-SESSION. This function
should be used in `dap-internal-terminal-*'."
(generate-new-buffer
(format "*%s %s*"
(dap--debug-session-name debug-session)
(if title (concat "- " title) "console"))))
(declare-function vterm-mode "ext:vterm" (&optional arg))
(defvar vterm-shell)
(defvar vterm-kill-buffer-on-exit)
(defun dap-internal-terminal-vterm (command title debug-session)
(with-current-buffer (dap--make-terminal-buffer title debug-session)
(require 'vterm)
(let ((vterm-shell command)
(vterm-kill-buffer-on-exit nil))
(vterm-mode)
;; TODO: integrate into dap-ui
(display-buffer (current-buffer)))))
(defun dap-internal-terminal-shell (command title debug-session)
(let ((buf (dap--make-terminal-buffer title debug-session)))
(async-shell-command command buf buf)))
(defun dap-internal-terminal-auto (command title debug-session)
"Run COMMAND with an auto-detected terminal.
If `vterm' is loaded or auto-loaded, use vterm. Otherwise, use
`async-shell-command'."
;; NOTE: 'vterm is autoloaded. This means that (fboundp 'vterm) will yield t
;; even before vterm is loaded.
(if (fboundp 'vterm)
(dap-internal-terminal-vterm command title debug-session)
(dap-internal-terminal-shell command title debug-session)))
(defcustom dap-internal-terminal #'dap-internal-terminal-auto
"Terminal used with :console \"integratedTerminal\".
It is a function that shall take three arguments: the command to
run, as a string, the title from the debug adapter (may be nil)
and the debug session and it should execute COMMAND. Aside from
that, it can do anything and is itself responsible for displaying
any buffers, ....
If you are looking at implementing your own such function, see
also `dap--make-terminal-buffer'."
:group 'dap-mode
:type '(radio
(const :tag "auto-detect" :value dap-internal-terminal-auto)
(const :tag "vterm" :value dap-internal-terminal-vterm)
(const :tag "asnyc-shell" :value dap-internal-terminal-shell)
(function :tag "Custom function")))
(defcustom dap-output-buffer-filter '("stdout" "stderr")
"If non-nil, a list of output types to display in the debug output buffer."
:group 'dap-mode
:type 'list)
(defcustom dap-label-output-buffer-category nil
"If non-nil, content that is printed to the output buffer will be labelled
based on DAP protocol category."
:group 'dap-mode
:type 'boolean)
(defcustom dap-auto-show-output t
"If non-nil, the output buffer will be showed automatically."
:group 'dap-mode
:type 'boolean)
(defcustom dap-output-window-min-height 10
"The minimum height of the output window."
:group 'dap-mode
:type 'number)
(defcustom dap-output-window-max-height 20
"The maximum height of the output window."
:group 'dap-mode
:type 'number)
(defcustom dap-inhibit-io t
"If non-nil, the messages will be inhibited."
:group 'dap-mode
:type 'boolean)
(defcustom dap-terminated-hook nil
"List of functions to be called after a debug session has been terminated.
The functions will received the debug dession that
has been terminated."
:type 'hook
:group 'dap-mode)
(defcustom dap-stopped-hook nil
"List of functions to be called after a breakpoint has been hit."
:type 'hook
:group 'dap-mode)
(defcustom dap-session-changed-hook nil
"List of functions to be called after sessions have changed."
:type 'hook
:group 'dap-mode)
(defcustom dap-loaded-sources-changed-hook nil
"List of functions to be called after loaded sources have changed for
the session."
:type 'hook
:group 'dap-mode)
(defcustom dap-session-created-hook nil
"List of functions to be called after session have been created.
It will be called with one argument - the created session."
:type 'hook
:group 'dap-mode)
(defcustom dap-continue-hook nil
"List of functions to be called after application started.
The hook is called after application has been stopped/started(e.
g. after calling `dap-continue')"
:type 'hook
:group 'dap-mode)
(defcustom dap-executed-hook nil
"List of functions that will be called after execution and processing request."
:type 'hook
:group 'dap-mode)
(defcustom dap-breakpoints-changed-hook nil
"List of functions that will be called after breakpoints have changed.
The hook will be called with the session file and the new set of breakpoint
locations."
:type 'hook
:group 'dap-mode)
(defcustom dap-position-changed-hook nil
"List of functions that will be called after cursor position has changed."
:type 'hook
:group 'dap-mode)
(defcustom dap-stack-frame-changed-hook nil
"List of functions that will be called after active stack frame has changed."
:type 'hook
:group 'dap-mode)
(defvar dap--debug-providers (make-hash-table :test 'equal))
(defcustom dap-debug-template-configurations nil
"Plist Template configurations for DEBUG/RUN."
:safe #'listp
:group 'dap-mode
:type '(plist))
(defcustom dap-auto-configure-features '(sessions locals breakpoints expressions controls tooltip)
"Windows to auto show on debugging when in dap-ui-auto-configure-mode."
:group 'dap-mode
:type '(set (const :tag "Show sessions popup window when debugging" sessions)
(const :tag "Show locals popup window when debugging" locals)
(const :tag "Show breakpoints popup window when debugging" breakpoints)
(const :tag "Show expressions popup window when debugging" expressions)
(const :tag "Show REPL popup window when debugging" repl)
(const :tag "Enable `dap-ui-controls-mode` with controls to manage the debug session when debugging" controls)
(const :tag "Enable `dap-tooltip-mode` that enables mouse hover support when debugging" tooltip)))
(defconst dap-features->windows
'((sessions . (dap-ui-sessions . dap-ui--sessions-buffer))
(locals . (dap-ui-locals . dap-ui--locals-buffer))
(breakpoints . (dap-ui-breakpoints . dap-ui--breakpoints-buffer))
(expressions . (dap-ui-expressions . dap-ui--expressions-buffer))
(repl . (dap-ui-repl . dap-ui--repl-buffer))))
(defconst dap-features->modes
'((controls . (dap-ui-controls-mode . posframe))
(tooltip . dap-tooltip-mode)))
(defvar dap--debug-configuration nil
"List of the previous configuration that have been executed.")
(defvar dap-connect-retry-count 1000
"Retry count for dap connect.")
(defvar dap-connect-retry-interval 0.02
"Retry interval for dap connect.")
(eval-and-compile
(defun dash-expand:&dap-session (key source)
`(,(intern-soft (format "dap--debug-session-%s" (eval key))) ,source)))
(cl-defstruct dap--debug-session
(name nil)
;; ‘last-id’ is the last JSON-RPC identifier used.
(last-id 0)
(proc nil :read-only t)
;; ‘response-handlers’ is a hash table mapping integral JSON-RPC request
;; identifiers for pending asynchronous requests to functions handling the
;; respective responses. Upon receiving a response from the language server,
;; ‘dap-mode’ will call the associated response handler function with a
;; single argument, the deserialized response parameters.
(response-handlers (make-hash-table :test 'eql) :read-only t)
;; DAP parser.
(parser (make-dap--parser) :read-only t)
(output-buffer nil)
(thread-id nil)
;; reference to the workspace that holds the information about the lsp workspace.
(workspace nil)
(threads nil)
(thread-states (make-hash-table :test 'eql) :read-only t)
(active-frame-id nil)
(active-frame nil)
(cursor-marker nil)
;; one of 'pending 'running 'terminated 'failed
(state 'pending)
;; hash table containing mapping file -> active breakpoints.
(breakpoints (make-hash-table :test 'equal) :read-only t)
;; hash table tread-id -> stack frame
(thread-stack-frames (make-hash-table :test 'eql) :read-only t)
;; the arguments that were used to start the debug session.
(launch-args nil)
;; Currently-available server capabilities
(current-capabilities (make-hash-table :test 'equal))
(error-message nil)
(loaded-sources nil)
(program-proc)
;; Optional metadata to set and get it.
(metadata (make-hash-table :test 'eql))
;; when t the output already has been displayed for this buffer.
(output-displayed))
(cl-defstruct dap--parser
(waiting-for-response nil)
(response-result nil)
;; alist of headers
(headers '())
;; message body
(body nil)
;; If non-nil, reading body
(reading-body nil)
;; length of current message body
(body-length nil)
;; amount of current message body currently stored in 'body'
(body-received 0)
;; Leftover data from previous chunk; to be processed
(leftovers nil))
(defun dap--get-sessions ()
"Get sessions for WORKSPACE."
(lsp-workspace-get-metadata "debug-sessions"))
(defun dap--cur-session ()
"Get currently active `dap--debug-session'."
(lsp-workspace-get-metadata "default-session"))
(defun dap--resp-handler (&optional success-callback error-callback)
"Generate a response handler, for use in `dap--send-message'.
If the request is successful, call SUCCESS-CALLBACK with the
entire resulting messsage.
The handler will call ERROR-CALLBACK with the message or `error'
on failure."
(-lambda ((result &as &hash "success" "message"))
(if success
(when success-callback (funcall success-callback result))
(if error-callback (funcall error-callback message) (error message)))))
(defun dap--session-init-resp-handler (debug-session &optional success-callback)
"Returned handler will mark the DEBUG-SESSION as failed if call return error.
SUCCESS-CALLBACK will be called if it is provided and if the call
has succeeded."
(-lambda ((result &as &hash "success" "message"))
(if success
(when success-callback (funcall success-callback result))
(warn "Initialize request failed: %s" message)
(delete-process (dap--debug-session-proc debug-session))
(setf (dap--debug-session-state debug-session) 'failed
(dap--debug-session-error-message debug-session) message)
(dap--refresh-breakpoints)
(run-hook-with-args 'dap-terminated-hook debug-session)
(run-hooks 'dap-session-changed-hook))))
(defun dap--cur-session-or-die ()
"Get currently selection `dap--debug-session' or die."
(or (dap--cur-session) (error "No active current session")))
(defun dap--session-running (debug-session)
"Check whether DEBUG-SESSION still running."
(and debug-session
(not (memq (dap--debug-session-state debug-session) '(terminated failed)))))
(defun dap--cur-active-session-or-die ()
"Get currently non-terminated `dap--debug-session' or die."
(-let ((debug-session (dap--cur-session-or-die)))
(if (dap--session-running debug-session)
debug-session
(error "Session %s is terminated" (dap--debug-session-name debug-session)))))
(defun dap-breakpoint-get-point (breakpoint)
"Get position of BREAKPOINT."
(or (-some-> breakpoint (plist-get :marker) marker-position)
(plist-get breakpoint :point)))
(defun dap--set-cur-session (debug-session)
"Change the active debug session to DEBUG-SESSION."
(lsp-workspace-set-metadata "default-session" debug-session))
(defmacro dap--put-if-absent (config key form)
"Update KEY to FORM if KEY does not exist in plist CONFIG."
`(plist-put ,config ,key (or (plist-get ,config ,key) ,form)))
(defun dap--completing-read (prompt collection transform-fn &optional predicate
require-match initial-input
hist def inherit-input-method)
"Wrap `completing-read' to provide tranformation function.
TRANSFORM-FN will be used to transform each of the items before displaying.
PROMPT COLLECTION PREDICATE REQUIRE-MATCH INITIAL-INPUT HIST DEF
INHERIT-INPUT-METHOD will be proxied to `completing-read' without changes."
(let* ((result (--map (cons (funcall transform-fn it) it) collection))
(completion (completing-read prompt (-map 'cl-first result)
predicate require-match initial-input hist
def inherit-input-method)))
(cdr (assoc completion result))))
(defun dap--plist-delete (plist property)
"Delete PROPERTY from PLIST.
This is in contrast to merely setting it to 0."
(let (p)
(while plist
(if (not (eq property (cl-first plist)))
(setq p (plist-put p (cl-first plist) (nth 1 plist))))
(setq plist (cddr plist)))
p))
(defun dap--json-encode (params)
"Create a LSP message from PARAMS, after encoding it to a JSON string."
(let* ((json-encoding-pretty-print dap-print-io)
(json-false :json-false))
(json-encode params)))
(defun dap--make-message (params)
"Create a LSP message from PARAMS, after encoding it to a JSON string."
(let* ((body (dap--json-encode params)))
(format "Content-Length: %d\r\n\r\n%s" (string-bytes body) body)))
(defun dap--parse-header (s)
"Parse string S as a DAP (KEY . VAL) header."
(let ((pos (string-match "\:" s))
key val)
(unless pos
(signal 'lsp-invalid-header-name (list s)))
(setq key (substring s 0 pos)
val (substring s (+ 2 pos)))
(when (string-equal key "Content-Length")
(cl-assert (cl-loop for c being the elements of val
when (or (> c ?9) (< c ?0)) return nil
finally return t)
nil (format "Invalid Content-Length value: %s" val)))
(cons key val)))
(defun dap--get-breakpoints ()
"Get breakpoints in WORKSPACE."
(or (lsp-workspace-get-metadata "Breakpoints")
(let ((breakpoints (make-hash-table :test 'equal)))
(lsp-workspace-set-metadata "Breakpoints" breakpoints)
breakpoints)))
(defun dap--persist (file to-persist)
"Serialize TO-PERSIST to FILE."
(with-demoted-errors
"Failed to persist file: %S"
(make-directory (file-name-directory file) t)
(with-temp-file file
(erase-buffer)
(insert (prin1-to-string to-persist)))))
(defun dap--set-sessions (debug-sessions)
"Update list of debug sessions for WORKSPACE to DEBUG-SESSIONS."
(lsp-workspace-set-metadata "debug-sessions" debug-sessions)
(run-hook-with-args 'dap-session-changed-hook))
(defun dap--persist-breakpoints (breakpoints)
"Persist BREAKPOINTS."
;; filter markers before persisting the breakpoints (markers are not
;; writeable) and update the point based on the marker.
(let ((filtered-breakpoints (make-hash-table :test 'equal)))
(maphash (lambda (k v)
(puthash k (-map (-lambda ((bkp &as &plist :marker :point))
(-> bkp
(dap--plist-delete :point)
(dap--plist-delete :marker)
(plist-put :point (if marker
(marker-position marker)
point))))
v)
filtered-breakpoints))
breakpoints)
(dap--persist dap-breakpoints-file filtered-breakpoints)))
(defun dap--breakpoints-changed (updated-file-breakpoints &optional file-name)
"Common logic breakpoints related methods UPDATED-FILE-BREAKPOINTS.
FILE-NAME is the filename in which the breakpoints have been udpated."
(let* ((file-name (or file-name buffer-file-name (error "No file name")))
(breakpoints (dap--get-breakpoints)))
;; update the list
(if updated-file-breakpoints
(puthash file-name updated-file-breakpoints breakpoints)
(remhash file-name breakpoints))
;; do not update the breakpoints represenations if there is active session.
(when (not (and (dap--cur-session) (dap--session-running (dap--cur-session))))
(--when-let (find-buffer-visiting file-name)
(with-current-buffer it
(run-hooks 'dap-breakpoints-changed-hook))))
;; Update all of the active sessions with the list of breakpoints.
(let ((set-breakpoints-req (dap--set-breakpoints-request
file-name
updated-file-breakpoints)))
(-as-> (dap--get-sessions) $
(-filter 'dap--session-running $)
(--each $
(dap--send-message set-breakpoints-req
(dap--resp-handler
(lambda (resp)
(dap--update-breakpoints it
resp
file-name)))
it))))
(dap--persist-breakpoints breakpoints)))
(defun dap-breakpoint-toggle ()
"Toggle breakpoint on the current line."
(interactive)
(let ((file-breakpoints (gethash buffer-file-name (dap--get-breakpoints))))
(dap--breakpoints-changed
(if-let (existing-breakpoint (dap--get-breakpoint-at-point file-breakpoints))
;; delete if already exists
(progn
(-some-> existing-breakpoint
(plist-get :marker)
(set-marker nil))
(cl-remove existing-breakpoint file-breakpoints))
;; add if does not exist
(push (list :marker (point-marker)
:point (point))
file-breakpoints)))))
(defun dap--get-breakpoint-at-point (&optional file-breakpoints)
"Get breakpoint on the current point.
FILE-BREAKPOINTS is the list of breakpoints in the current file."
(let ((current-line (line-number-at-pos (point))))
(-first
(-lambda (bp)
(= current-line (line-number-at-pos (dap-breakpoint-get-point bp))))
(or file-breakpoints (gethash buffer-file-name (dap--get-breakpoints))))))
(defun dap-breakpoint-delete (breakpoint file-name)
"Delete breakpoint on the current line."
(interactive (list (-some->> (dap--get-breakpoints)
(gethash buffer-file-name)
dap--get-breakpoint-at-point)
buffer-file-name))
(when breakpoint
(-some-> breakpoint (plist-get :marker) (set-marker nil))
(dap--breakpoints-changed (-remove
(-lambda (bp)
(eq (dap-breakpoint-get-point bp)
(dap-breakpoint-get-point breakpoint)))
(gethash file-name (dap--get-breakpoints)))
file-name)))
(defun dap--breakpoint-update (property message file-name existing-breakpoint)
"Common code for updating breakpoint.
MESSAGE to be displayed to the user.
PROPERTY is the breakpoint property that will be udpated."
(let ((file-breakpoints (gethash file-name (dap--get-breakpoints))))
(if existing-breakpoint
(let ((value (read-string message
(plist-get existing-breakpoint property))))
(if (s-blank? value)
(setq file-breakpoints (cons (-> existing-breakpoint
(dap--plist-delete :hit-condition)
(dap--plist-delete :condition)
(dap--plist-delete :log-message))
(delete existing-breakpoint file-breakpoints)))
(plist-put existing-breakpoint property value))
(dap--breakpoints-changed file-breakpoints file-name))
(error "No breakpoint found."))))
(defun dap-breakpoint-condition (file-name breakpoint)
"Set breakpoint condition for the breakpoint at point."
(interactive (list buffer-file-name (dap--get-breakpoint-at-point)))
(dap--breakpoint-update :condition "Enter breakpoint condition: " file-name breakpoint))
(defun dap-breakpoint-hit-condition (file-name breakpoint)
"Set breakpoint hit condition for the breakpoint at point."
(interactive (list buffer-file-name (dap--get-breakpoint-at-point)))
(dap--breakpoint-update :hit-condition "Enter hit condition: " file-name breakpoint))
(defun dap-breakpoint-log-message (file-name breakpoint)
"Set breakpoint log message for the breakpoint at point.
If log message for the breakpoint is specified it won't stop
thread exection but the server will log message."
(interactive (list buffer-file-name (dap--get-breakpoint-at-point)))
(dap--breakpoint-update :log-message "Enter log message: " file-name breakpoint))
(defun dap-breakpoint-add ()
"Add breakpoint on the current line."
(interactive)
(let ((file-breakpoints (gethash buffer-file-name (dap--get-breakpoints))))
(unless (dap--get-breakpoint-at-point file-breakpoints)
(dap--breakpoints-changed (push (list :marker (point-marker)
:point (point))
file-breakpoints)))))
(defun dap--get-body-length (headers)
"Get body length from HEADERS."
(let ((content-length (cdr (assoc "Content-Length" headers))))
(if content-length
(string-to-number content-length)
;; This usually means either the server our our parser is
;; screwed up with a previous Content-Length
(error "No Content-Length header"))))
(defun dap--parser-reset (p)
"Reset `dap--parser' P."
(setf
(dap--parser-leftovers p) ""
(dap--parser-body-length p) nil
(dap--parser-body-received p) nil
(dap--parser-headers p) '()
(dap--parser-body p) nil
(dap--parser-reading-body p) nil))
(defun dap--parser-read (p output)
"Parser OUTPUT using parser P."
(let* ((messages '())
(output (encode-coding-string output 'utf-8 'nocopy))
(chunk (concat (dap--parser-leftovers p) output)))
(while (not (string-empty-p chunk))
(if (not (dap--parser-reading-body p))
;; Read headers
(let* ((body-sep-pos (string-match-p "\r\n\r\n" chunk)))
(if body-sep-pos
;; We've got all the headers, handle them all at once:
(let* ((header-raw (substring chunk 0 body-sep-pos))
(content (substring chunk (+ body-sep-pos 4)))
(headers
(mapcar 'dap--parse-header
(split-string header-raw "\r\n")))
(body-length (dap--get-body-length headers)))
(setf
(dap--parser-headers p) headers
(dap--parser-reading-body p) t
(dap--parser-body-length p) body-length
(dap--parser-body-received p) 0
(dap--parser-body p) (make-string body-length ?\0)
(dap--parser-leftovers p) nil)
(setq chunk content))
;; Haven't found the end of the headers yet. Save everything
;; for when the next chunk arrives and await further input.
(setf (dap--parser-leftovers p) chunk)
(setq chunk "")))
;; Read body
(let* ((total-body-length (dap--parser-body-length p))
(received-body-length (dap--parser-body-received p))
(chunk-length (string-bytes chunk))
(left-to-receive (- total-body-length received-body-length))
(this-body (substring chunk 0 (min left-to-receive chunk-length)))
(leftovers (substring chunk (string-bytes this-body))))
(store-substring (dap--parser-body p) received-body-length this-body)
(setf (dap--parser-body-received p) (+ (dap--parser-body-received p)
(string-bytes this-body)))
(when (>= chunk-length left-to-receive)
(push (decode-coding-string (dap--parser-body p) 'utf-8) messages)
(dap--parser-reset p))
(setq chunk leftovers))))
(nreverse messages)))
(defun dap--read-json (str)
"Read the JSON object contained in STR and return it."
(let* ((json-array-type 'list)
(json-object-type 'hash-table)
(json-false nil))
(json-read-from-string str)))
(defun dap--resume-application (debug-session)
"Resume DEBUG-SESSION."
(-let [thread-id (dap--debug-session-thread-id debug-session)]
(puthash thread-id "running" (dap--debug-session-thread-states debug-session))
(remhash thread-id (dap--debug-session-thread-stack-frames debug-session)))
(setf (dap--debug-session-active-frame debug-session) nil
(dap--debug-session-thread-id debug-session) nil)
(run-hook-with-args 'dap-continue-hook debug-session))
(defun dap-continue (debug-session thread-id)
"Call continue for the currently active session and thread."
(interactive (list (dap--cur-active-session-or-die)
(dap--debug-session-thread-id (dap--cur-active-session-or-die))))
(if thread-id
(progn
(dap--send-message (dap--make-request "continue"
(list :threadId thread-id))
(dap--resp-handler)
debug-session)
(dap--resume-application debug-session))
(lsp--error "Currently active thread is not stopped. Use `dap-switch-thread' or select stopped thread from sessions view.")))
(defun dap-disconnect (session)
"Disconnect from the currently active session."
(interactive (list (dap--cur-active-session-or-die)))
(dap--send-message (dap--make-request "disconnect"
(list :restart :json-false))
(lambda (_result)
(when-let (proc (dap--debug-session-program-proc session))
(lsp--info "Killing process %s" proc)
(kill-process proc)))
session)
(dap--resume-application session))
(defun dap--step (cmd debug-session)
"Send a request for CMD, a step command.
DEBUG-SESSION is the debug session in which the stepping is to be
executed."
(if-let (thread-id (dap--debug-session-thread-id debug-session))
(progn
(dap--send-message (dap--make-request
cmd
(list :threadId thread-id))
(dap--resp-handler)
debug-session)
(dap--resume-application debug-session))
(lsp--error "Currently active thread is not stopped. Use `dap-switch-thread' or select stopped thread from sessions view.")))
(defun dap-next (debug-session)
"Step over statements."
(interactive (list (dap--cur-session-or-die)))
(dap--step "next" debug-session))
(defun dap-step-in (debug-session)
"Like `dap-next', but step into function calls."
(interactive (list (dap--cur-session-or-die)))
(dap--step "stepIn" debug-session))
(defun dap-step-out (debug-session)
"Debug step out."
(interactive (list (dap--cur-session-or-die)))
(dap--step "stepOut" debug-session))
(defun dap-restart-frame (debug-session frame-id)
"Restarts current frame."
(interactive (let ((debug-session (dap--cur-active-session-or-die)))
(list debug-session
(-some->> debug-session dap--debug-session-active-frame (gethash "id")))))
(dap--send-message (dap--make-request "restartFrame"
(list :frameId frame-id))
(dap--resp-handler)
debug-session)
(dap--resume-application debug-session))
(defcustom dap-debug-restart-keep-session t
"Set if `dap-debug-restart' should use a new session.
When running `dap-debug-restart' with this variable set, the old
session will still be visible and accessible after restarting. If
not, the old session will be deleted, `dap-debug-restart'
behaving like an in-place restart instead. Note that you can
override this variable by calling `dap-debug-restart' with a
prefix argument (the effect will be reversed)."
:group 'dap-mode
:type 'boolean)
(defun dap-debug-restart (&optional toggle-keep-session)
"Restarts current frame.
If TOGGLE-KEEP-SESSION is set (in interactive mode this is the
prefix argument), the effect of `dap-debug-restart-keep-session'
will be reversed."
(interactive "P")
(if-let ((debug-session (dap--cur-session)))
(progn
(when (dap--session-running debug-session)
(message "Disconnecting from %s" (dap--debug-session-name debug-session))
(if (eq toggle-keep-session dap-debug-restart-keep-session)
(dap-delete-session debug-session)
(dap-disconnect debug-session)))
(dap-debug (dap--debug-session-launch-args debug-session)))
(user-error "There is session to restart")))
(defun dap--get-path-for-frame (stack-frame)
"Get file path for a STACK-FRAME."
(-when-let* ((source (gethash "source" stack-frame))
(path (gethash "path" source)))
(if (-> path url-unhex-string url-generic-parse-url url-type)
(lsp--uri-to-path path)
path)))
(defun dap--go-to-stack-frame (debug-session stack-frame)
"Make STACK-FRAME the active STACK-FRAME of DEBUG-SESSION."
(with-lsp-workspace (dap--debug-session-workspace debug-session)
(when stack-frame
(-let* (((&hash "line" line "column" column "name" name) stack-frame)
(path (dap--get-path-for-frame stack-frame)))
(setf (dap--debug-session-active-frame debug-session) stack-frame)
;; If we have a source file with path attached, open it and
;; position the point in the line/column referenced in the
;; stack trace.
(if (and path (file-exists-p path))
(progn
(select-window (get-mru-window (selected-frame) nil))
(find-file path)
(goto-char (point-min))
(forward-line (1- line))
(forward-char column))
(message "No source code for %s. Cursor at %s:%s." name line column))))
(run-hook-with-args 'dap-stack-frame-changed-hook debug-session)))
(defun dap--select-thread-id (debug-session thread-id &optional force)
"Make the thread with id=THREAD-ID the active thread for DEBUG-SESSION."
;; make the thread the active session only if there is no active debug
;; session.
(when (or force (not (dap--debug-session-thread-id debug-session)))
(setf (dap--debug-session-thread-id debug-session) thread-id)
(run-hook-with-args 'dap-stopped-hook debug-session))
(dap--send-message
(dap--make-request "stackTrace" (list :threadId thread-id))
(dap--resp-handler
(-lambda ((&hash "body" (&hash "stackFrames" stack-frames)))
(puthash thread-id
stack-frames
(dap--debug-session-thread-stack-frames debug-session))
;; select stackframe only when session matches the active session and when
;; thread-id is the same as the active one
(when (and (eq debug-session (dap--cur-session))
(eq thread-id (dap--debug-session-thread-id (dap--cur-session))))
(dap--go-to-stack-frame debug-session (cl-first stack-frames)))))
debug-session))
(defun dap--buffer-list ()
"Get all file backed buffers."
(-filter 'buffer-file-name (buffer-list)))
(defun dap--refresh-breakpoints ()
"Refresh breakpoints for DEBUG-SESSION."
(--each (dap--buffer-list)
(when (buffer-live-p it)
(with-current-buffer it
(dap--set-breakpoints-in-file
buffer-file-name
(gethash buffer-file-name (dap--get-breakpoints)))))))
(defun dap--mark-session-as-terminated (debug-session)
"Mark DEBUG-SESSION as terminated."
(setf (dap--debug-session-state debug-session) 'terminated
(dap--debug-session-active-frame debug-session) nil)
(with-demoted-errors "Process cleanup failed with %s"
(delete-process (dap--debug-session-proc debug-session)))
(clrhash (dap--debug-session-breakpoints debug-session))
(run-hook-with-args 'dap-stack-frame-changed-hook debug-session)
(run-hook-with-args 'dap-terminated-hook debug-session)
(dap--refresh-breakpoints)
(when-let ((cleanup-fn (plist-get
(dap--debug-session-launch-args debug-session)
:cleanup-function)))
(funcall cleanup-fn debug-session)))
(defun dap--output-buffer-format-with-category (category output)
"Formats a string suitable for printing to the output buffer using CATEGORY and OUTPUT."
(let ((message (format "%s: %s" category output)))
(if (string= (substring message -1) "\n")
message
(concat message "\n"))))
(defun dap--output-buffer-format (output-body)
"Formats a string suitable for printing to the output buffer using an OUTPUT-BODY."
(if dap-label-output-buffer-category
(dap--output-buffer-format-with-category (gethash "category" output-body)
(gethash "output" output-body))
(gethash "output" output-body)))
(defun dap--insert-at-point-max (str)
"Inserts STR at point-max of the buffer."
(goto-char (point-max))
(insert (ansi-color-apply str)))
(defun dap--print-to-output-buffer (debug-session str)
"Insert content from STR into the output buffer associated with DEBUG-SESSION."
(with-current-buffer (get-buffer-create (dap--debug-session-output-buffer debug-session))
(font-lock-mode t)
(setq-local buffer-read-only nil)
(if (and (eq (current-buffer) (window-buffer (selected-window)))
(not (= (point) (point-max))))
(save-excursion
(dap--insert-at-point-max str))
(dap--insert-at-point-max str))
(setq-local buffer-read-only t))
(when (and dap-auto-show-output
(not (dap--debug-session-output-displayed debug-session)))
(setf (dap--debug-session-output-displayed debug-session) t)
(save-excursion (dap-go-to-output-buffer t))))
(cl-defgeneric dap-handle-event (event-type session params)
"Extension point for handling custom events.
EVENT-TYPE is the event to handle.
SESSION is the session that has triggered the event.
PARAMS are the event params.")
(cl-defmethod dap-handle-event (event-type _session _params)
(message "No message handler for %s" event-type))
(defun dap--on-event (debug-session event)
"Dispatch EVENT for DEBUG-SESSION."
(-let [(&hash "body" "event" event-type) event]
(pcase event-type
("output" (-when-let* ((formatted-output (dap--output-buffer-format body))
(formatted-output (if-let ((output-filter-fn (-> debug-session
(dap--debug-session-launch-args)
(plist-get :output-filter-function))))
(funcall output-filter-fn formatted-output)
formatted-output)))
(when (or (not dap-output-buffer-filter) (member (gethash "category" body)
dap-output-buffer-filter))
(dap--print-to-output-buffer debug-session formatted-output))))
("breakpoint" (-when-let* (((breakpoint &as &hash "id") (when body
(gethash "breakpoint" body)))
(file-name (->> debug-session
(dap--debug-session-breakpoints)
(ht-find
(lambda (_ breakpoints)
(-first (-lambda ((bkp &as &hash "id" bkp-id))
(when (eq bkp-id id)
(ht-clear bkp)
(ht-aeach (ht-set bkp key value) breakpoint)
t))
breakpoints)))
(cl-first))))
(when (eq debug-session (dap--cur-session))
(with-current-buffer (find-file file-name)
(run-hooks 'dap-breakpoints-changed-hook)))))
("thread" (-let [(&hash "threadId" id "reason") body]
(puthash id reason (dap--debug-session-thread-states debug-session))
(run-hooks 'dap-session-changed-hook)
(dap--send-message
(dap--make-request "threads")
(-lambda ((&hash "body"))
(setf (dap--debug-session-threads debug-session)
(when body (gethash "threads" body)))
(run-hooks 'dap-session-changed-hook))
debug-session)))
("exited" (dap--mark-session-as-terminated debug-session))
("continued"
(-let [(&hash "threadId" thread-id) body]
(remhash thread-id (dap--debug-session-thread-states debug-session))
(if (and (equal thread-id (dap--debug-session-thread-id debug-session))
(equal debug-session (dap--cur-session)))
(dap--resume-application debug-session)
(run-hooks 'dap-session-changed-hook))))
("stopped"
(-let [(&hash "threadId" thread-id "type" "reason") body]
(puthash thread-id (or type reason)
(dap--debug-session-thread-states debug-session))
(dap--select-thread-id debug-session thread-id)
(when (string= "exception" reason)
(dap--send-message
(dap--make-request "exceptionInfo" (list :threadId thread-id))
(-lambda ((&hash "body" (&hash? "description" "exceptionId" exception-id)))
(lsp--error "Exception has occurred: %s\n%s"
exception-id description))
debug-session))
(run-hooks 'dap-session-changed-hook)))
("terminated"
(dap--mark-session-as-terminated debug-session))
("usernotification"
(-let [(&hash "notificationType" notification-type "message") body]
(warn (format "[%s] %s" notification-type message))))
("initialized"
(dap--configure-breakpoints
debug-session
(dap--get-breakpoints)
(apply-partially #'dap--send-configuration-done debug-session)))
("loadedSource"
(-let [(&hash "body" (&hash "source")) event]
(cl-pushnew source (dap--debug-session-loaded-sources debug-session))
(run-hook-with-args 'dap-loaded-sources-changed-hook debug-session)))
("capabilities"
(-let [(&hash "body" (&hash "capabilities")) event]
(ht-update! (dap--debug-session-current-capabilities debug-session) capabilities)))
(_ (dap-handle-event (intern event-type) debug-session body)))))
(defcustom dap-default-terminal-kind "integrated"
"Default terminal type used for :console."
:type '(radio
(const :tag "Terminal within Emacs" :value "integrated")
(const :tag "External terminal program (`dap-external-terminal')"
:value "external"))
:group 'dap-mode)
(defun dap--start-process (debug-session parsed-msg)
(-let* (((&hash "arguments" (&hash? "args" "cwd" "title" "kind") "seq")
parsed-msg)
(default-directory cwd)
(command-to-run (string-join args " "))
(kind (or kind dap-default-terminal-kind)))
(or
(when (string= kind "external")
(let* ((name (or title (concat (dap--debug-session-name debug-session)
"- terminal")))
(terminal-argv
(cl-loop for part in dap-external-terminal collect
(->> part (s-replace "{display}" name)
(s-replace "{command}" command-to-run)))))
(when
(condition-case-unless-debug err
(progn (apply #'start-process name name terminal-argv) t)
(error (lsp--warn
"dap-debug: failed to start external
terminal: %S (launch command was: \"%s\"). Set
`dap-external-terminal' to the correct value or install the
terminal configured (probably xterm)."
(error-message-string err)