forked from svaante/dape
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdape.el
2889 lines (2629 loc) · 116 KB
/
dape.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
;;; dape.el --- Debug Adapter Protocol for Emacs -*- lexical-binding: t -*-
;; Author: Daniel Pettersson
;; Created: 2023
;; License: GPL-3.0-or-later
;; Version: 0.1
;; Homepage: https://github.com/svaante/dape
;; Package-Requires: ((emacs "29.1"))
;; This file is not part of GNU Emacs.
;; 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 <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This package is an debug adapter client for Emacs.
;; Use `dape-configs' to set up your debug adapter configurations.
;; To initiate debugging sessions, use the command `dape'.
;; Note:
;; For complete functionality, it's essential to activate `eldoc-mode'
;; in your source buffers and enable `repeat-mode' for ergonomics
;;; Code:
(require 'cl-lib)
(require 'subr-x)
(require 'seq)
(require 'font-lock)
(require 'pulse)
(require 'comint)
(require 'repeat)
(require 'compile)
(require 'tree-widget)
(require 'project)
;;; Custom
(defgroup dape nil
"Debug Adapter Protocol for Emacs."
:prefix "dape-"
:group 'applications)
(defcustom dape-configs nil
"This variable holds the Dape configurations as an alist.
In this alist, the car element serves as a symbol identifying each
configuration. Each configuration, in turn, is a property list (plist)
where keys can be symbols or keywords.
Symbol Keys (Used by Dape):
- command: Shell command to initiate the debug adapter.
- command-args: List of string arguments for the command.
- command-cwd: Working directory for the command.
- host: Host of the debug adapter.
- port: Port of the debug adapter.
- modes: List of modes where the configuration is active in `dape'
completions.
- compile: Executes a shell command with `dape-compile-fn'.
Debug adapter connection in configuration:
- If only command is specified (without host and port), Dape
will communicate with the debug adapter through stdin/stdout.
- If both host and port are specified, Dape will connect to the
debug adapter. If `command is specified, Dape will wait until the
command is initiated before it connects with host and port.
Keywords in configuration:
Keywords are transmitted to the adapter during the initialize and
launch/attach requests. Refer to `json-serialize' for detailed
information on how Dape serializes these keyword elements. Dape
uses nil as false.
Functions and symbols in configuration:
If a value in a key is a function, the function's return value will
replace the key's value before execution.
If a value in a key is a symbol, the symbol will recursively resolve
at runtime."
:type '(alist :key-type (symbol :tag "Name")
:value-type
(plist :options
(((const :tag "List of modes where config is active in `dape' completions" modes) (repeat function))
((const :tag "Shell command to initiate the debug adapter" command) (choice string symbol))
((const :tag "List of string arguments for command" command-args) (repeat string))
((const :tag "Working directory for command" command-cwd) (choice string symbol))
((const :tag "Host of debug adapter" host) string)
((const :tag "Port of debug adapter" port) natnum)
((const :tag "Compile cmd" compile) string)
((const :tag "Adapter type" :type) string)
((const :tag "Request type launch/attatch" :request) string)))))
(defcustom dape-key-prefix "\C-x\C-a"
"Prefix of all dape commands."
:type 'key)
(defcustom dape-display-source-buffer-action
'(display-buffer-reuse-window
display-buffer-same-window)
"`display-buffer' action used when displaying source buffer."
:type 'sexp)
(defcustom dape-on-start-hooks '(dape-info dape-repl)
"Hook to run on session start.
The hook is run with one argument, the compilation buffer."
:type 'hook)
(defcustom dape-main-functions nil
"Functions to set breakpoints at startup if no other breakpoints are set."
:type '(repeat string))
(defcustom dape-read-memory-default-count 1024
"The default count for `dape-read-memory'."
:type 'natnum)
(defcustom dape-info-buttons
'(("next" . dape-next)
("step" . dape-step-in)
("out" . dape-step-out)
("cont" . dape-continue)
("pause" . dape-pause)
("restart" . dape-restart)
("quit" . dape-quit))
"Actions to be displayed in `dape-info' buffer."
:type '(alist :key-type string
:value-type function))
(defcustom dape-info-buffer-variable-format 'line
"How variables are formatted in *dape-info* buffer."
:type '(choice (const :tag "Truncate string at new line" line)
(const :tag "No formatting" nil)))
(defcustom dape-info-display-buffer-action
'((display-buffer-in-side-window)
. ((side . left)))
"`display-buffer' action used when displaying *dape-info* buffer."
:type 'sexp)
(defcustom dape-repl-use-shorthand t
"Dape `dape-repl-commands' can be invokend with first char of command."
:type 'boolean)
(defcustom dape-repl-commands
'(("debug" . dape)
("next" . dape-next)
("continue" . dape-continue)
("pause" . dape-pause)
("step" . dape-step-in)
("out" . dape-step-out)
("restart" . dape-restart)
("kill" . dape-kill)
("disconnect" . dape-disconnect-quit)
("quit" . dape-quit))
"Dape commands available in REPL buffer."
:type '(alist :key-type string
:value-type function))
(defcustom dape-repl-display-buffer-action
'((display-buffer-reuse-window
display-buffer-in-side-window)
. ((side . bottom)
(slot . -1)))
"`display-buffer' action used when displaying *dape-repl* buffer."
:type 'sexp)
(defcustom dape-run-in-terminal-display-buffer-action
'((display-buffer-in-side-window) .
'((side . bottom)
(slot . 1)))
"`display-buffer' action used when displaying run in terminal buffer."
:type 'sexp)
(defcustom dape-inline-variables nil
"Show variable values inline."
:type 'boolean)
(defcustom dape-inline-variable-length 30
"Maximum length of inline variable overlays."
:type 'natnum)
(defcustom dape-compile-fn #'compile
"Function to run compile with."
:type 'function)
(defcustom dape-cwd-fn #'dape--default-cwd
"Function to get current working directory."
:type 'function)
(defcustom dape-compile-compile-hooks nil
"Hook run after dape compilation succeded.
The hook is run with one argument, the compilation buffer."
:type 'hook)
(defcustom dape--debug-on '(io info error std-server)
"Types of logs should be printed to *dape-debug*."
:type '(set (const :tag "dap IO" io)
(const :tag "info logging" info)
(const :tag "error logging" error)
(const :tag "dap tcp server stdout" std-server)))
;;; Face
(defface dape-log-face
'((t :inherit (font-lock-doc-face)
:height 0.85 :box (:line-width -1)))
"Face used to display log breakpoints.")
(defface dape-expression-face
'((t :inherit (font-lock-warning-face)
:height 0.85 :box (:line-width -1)))
"Face used to display conditional breakpoints.")
(defface dape-breakpoint-face
'((t :inherit (bold default)))
"Face used to display breakpoint overlays.")
(defface dape-stack-trace
'((t :inherit (highlight) :extend t))
"Face used to display stack trace overlays.")
(defface dape-stack-trace-pointer
'((t :inherit (bold default) :extend t))
"Face used to display stack trace overlays.")
(defface dape-repl-exit-code-exit
'((t :inherit compilation-mode-line-exit :extend t))
"Face used in repl for exit code 0.")
(defface dape-repl-exit-code-fail
'((t :inherit compilation-mode-line-fail :extend t))
"Face used in repl for non 0 exit codes.")
;;; Vars
(defvar dape--config nil
"Current session configuration plist.")
(defvar dape--timers nil
"List of running timers.")
(defvar dape--seq nil
"Session seq number.")
(defvar dape--seq-event nil
"Session event seq number.")
(defvar dape--cb nil
"Hash table of request callbacks.")
(defvar dape--state nil
"Session state string.")
(defvar dape--thread-id nil
"Selected thread id.")
(defvar dape--stack-id nil
"Selected stack id.")
(defvar dape--capabilities nil
"Session capabilities plist.")
(defvar dape--threads nil
"Session plist of thread data.")
(defvar dape--stack-pointers nil
"List of session stack pointer overlays.")
(defvar dape--breakpoints nil
"List of session breakpoint overlays.")
(defvar dape--variable-overlays nil
"List of variaiable overlays.")
(defvar dape--exceptions nil
"List of available exceptions as plists.")
(defvar dape--watched nil
"List of watched expressions.")
(defvar dape--server-process nil
"Debug adapter server process.")
(defvar dape--process nil
"Debug adapter communications process.")
(defvar dape--parent-process nil
"Debug adapter parent process. Used for by startDebugging adapters.")
(defvar dape--restart-in-progress nil
"Used for prevent adapter killing when restart request is in flight.")
(defvar dape--tree-widget-open-p (make-hash-table :test 'equal)
"Hash table of open `dape--tree-widget' widgets.")
(defvar dape--scopes-widget nil
"Scope widget in *dape-info* buffer.")
(defvar dape--watched-widget nil
"Watched widget in *dape-info* buffer.")
(defvar dape--stack-widget nil
"Stack widget in *dape-info* buffer.")
(defvar dape--threads-widget nil
"Threads widget in *dape-info* buffer.")
(defvar dape--breakpoints-widget nil
"Breakpoints widget in *dape-info* buffer.")
(defvar dape--exceptions-widget nil
"Exceptions widget in *dape-info* buffer.")
(defvar dape--widget-guard nil
"Guard var for *dape-info* buffer widget updates.")
(defvar dape--repl-insert-text-guard nil
"Guard var for *dape-repl* buffer text updates.")
;;; Utils
(defmacro dape--callback (&rest body)
"Create callback lambda for `dape-request' with BODY."
`(lambda (&optional process body success msg)
(ignore process body success msg)
,@body))
(defmacro dape--with (request-fn args &rest body)
"Call `dape-request' like REQUEST-FN with ARGS and BODY."
(declare (indent 2))
`(,request-fn ,@args (dape--callback ,@body)))
(defun dape--next-like-command (command &optional arg)
"Helper for interactive step like commands.
Run step like COMMAND. If ARG is set run COMMAND ARG times."
(if (dape--stopped-threads)
(dotimes (_ (or arg 1))
(dape-request (dape--live-process)
command
(dape--thread-id-object)
(dape--callback
(when success
(dape--update-state "running")
(dape--remove-stack-pointers)
(dolist (thread dape--threads)
(plist-put thread :status "running"))
(dape--info-update-threads-widget)))))
(user-error "No stopped threads")))
(defun dape--thread-id-object ()
"Helper to construct a thread id object."
(when dape--thread-id
(list :threadId dape--thread-id)))
(defun dape--stopped-threads ()
"List of stopped threads."
(mapcan (lambda (thread)
(when (equal (plist-get thread :status) "stopped")
(list thread)))
dape--threads))
(defun dape--current-thread ()
"Current thread plist."
(seq-find (lambda (thread)
(eq (plist-get thread :id) dape--thread-id))
dape--threads))
(defun dape--current-stack-frame ()
"Current stack frame plist."
(let* ((stack-frames (thread-first
(dape--current-thread)
(plist-get :stackFrames)))
(stack-frames-with-source
(seq-filter (lambda (stack-frame)
(thread-first stack-frame
(plist-get :source)
(plist-get :path)))
stack-frames)))
(or (seq-find (lambda (stack-frame)
(eq (plist-get stack-frame :id)
dape--stack-id))
stack-frames-with-source)
(car stack-frames-with-source)
(car stack-frames))))
(defun dape--object-to-marker (plist &optional buffer-open-fn)
"Create marker from dap PLIST containing file and line information.
If BUFFER-OPEN-FN is set, use that function to open a buffer from file path."
(and-let* ((path (thread-first plist
(plist-get :source)
(plist-get :path)))
((file-exists-p path))
(line (plist-get plist :line))
(buffer-open-fn (or buffer-open-fn 'find-file-noselect))
(buffer (funcall buffer-open-fn path)))
(with-current-buffer buffer
(save-excursion
(goto-char (point-min))
(forward-line (1- line))
(when-let ((column (plist-get plist :column)))
(when (> column 0)
(forward-char (1- column))))
(point-marker)))))
(defun dape--goto-source (plist &optional no-select pulse)
"Goto file and line of dap PLIST containing file and line information.
If NO-SELECT does not select buffer.
If PULSE pulse on after opening file."
(when-let ((marker (dape--object-to-marker plist)))
(let ((window
(display-buffer (marker-buffer marker)
dape-display-source-buffer-action)))
(unless no-select
(select-window window))
(with-current-buffer (marker-buffer marker)
(with-selected-window window
(goto-char (marker-position marker))
(when pulse
(pulse-momentary-highlight-region (line-beginning-position)
(line-beginning-position 2)
'next-error)))))))
(defun dape--default-cwd ()
"Try to guess current project absolute file path."
(expand-file-name
(or (when-let ((project (project-current)))
(project-root project))
default-directory)))
(defun dape-find-file (&optional default)
"Read filename without any ignored extensions at project root.
DEFAULT specifies which file to return on empty input."
(let ((completion-ignored-extensions nil)
(default-directory (funcall dape-cwd-fn)))
(expand-file-name
(read-file-name (if default
(format "Program (default %s): " default)
"Program : ")
default-directory
default t))))
(defun dape-find-file-buffer-default ()
"Read filename at project root, defaulting to current buffer."
(dape-find-file (buffer-file-name)))
(defun dape-read-pid ()
"Read pid of active processes if possible."
(if-let ((pids (list-system-processes)))
(let ((collection
(mapcar (lambda (pid)
(let ((args (alist-get 'args (process-attributes pid))))
(cons (concat
(format "%d" pid)
(when args
(format ": %s" args)))
pid)))
pids)))
(alist-get (completing-read "Pid: " collection)
collection nil nil 'equal))
(read-number "Pid: ")))
(defun dape--overlay-region (&optional extended)
"List of beg and end of current line.
If EXTENDED end of line is after newline."
(list (line-beginning-position)
(if extended
(line-beginning-position 2)
(1- (line-beginning-position 2)))))
(defun dape--variable-string (plist)
"Formats dap variable PLIST to string."
(let ((name (plist-get plist :name))
(value (or (plist-get plist :value)
(plist-get plist :result)))
(type (plist-get plist :type)))
(concat
(propertize name
'face 'font-lock-variable-name-face)
(unless (or (null value)
(string-empty-p value))
(format " = %s"
(propertize value
'face 'font-lock-number-face)))
(unless (or (null type)
(string-empty-p type))
(format ": %s"
(propertize type
'face 'font-lock-type-face))))))
(defun dape--format-file-line (file line)
"Formats FILE and LINE to string."
(concat (string-trim-left
file
(regexp-quote
(expand-file-name
(or (plist-get dape--config :cwd)
""))))
(when line
(format ":%d"
line))))
(defun dape--kill-processes ()
"Kill all Dape related process."
(when (hash-table-p dape--timers)
(dolist (timer (hash-table-values dape--timers))
(cancel-timer timer)))
(ignore-errors
(and dape--process
(delete-process dape--process))
(and dape--server-process
(delete-process dape--server-process))
(and dape--parent-process
(delete-process dape--parent-process))))
(defun dape--kill-buffers (&optional skip-process-buffers)
"Kill all Dape related buffers.
On SKIP-PROCESS-BUFFERS skip deletion of buffers which has processes."
(thread-last (buffer-list)
(seq-filter (lambda (buffer)
(unless (and skip-process-buffers
(get-buffer-process buffer))
(string-match-p "\\*dape-.+\\*" (buffer-name buffer)))))
(seq-do (lambda (buffer)
(when-let ((window (get-buffer-window buffer)))
(delete-window window))
(kill-buffer buffer)))))
;;; Process and parsing
;; HACK Issue #1 for some reason \r is not inserted into the parse
;; buffer by codelldb on windows. No trace in source code.
;; Some adapters can't help them self, sending headers not in spec..
(defconst dape--content-length-re
"Content-Length: \\([[:digit:]]+\\)\r?\n\
\\(?:.*: .*\r?\n\\)*\
\r?\n"
"Matches debug adapter protocol header.")
(defmacro dape--debug (type string &rest objects)
"Prints STRING of TYPE to *dape-debug*.
See `format' for STRING and OBJECTS usage.
See `dape-debug-on' for TYPE information."
`(when (memq ,type dape--debug-on)
(let ((objects (list ,@objects)))
(with-current-buffer (get-buffer-create "*dape-debug*")
(setq buffer-read-only t)
(goto-char (point-max))
(let ((inhibit-read-only t))
(insert (concat (propertize (format "[%s]" (symbol-name ,type)) 'face 'match)
" "
(apply 'format ,string objects))
"\n"))))))
(defun dape--live-process (&optional nowarn)
"Get current live process.
If NOWARN does not error on no active process."
(if (and dape--process
(processp dape--process)
(process-live-p dape--process))
dape--process
(unless nowarn
(user-error "No debug process live"))))
(defun dape--process-sentinel (process _msg)
"Sentinel for Dape processes."
(unless (process-live-p process)
(dape--remove-stack-pointers)
(dape--variable-remove-overlays)
;; Clean mode-line after 2 seconds
(run-with-timer 2 nil (lambda ()
(unless (dape--live-process t)
(setq dape--process nil)
(force-mode-line-update t))))
(dape--debug 'info "\nProcess %S exited with %d"
(process-command process)
(process-exit-status process))))
(defun dape--handle-object (process object)
"Handle a incoming parsed OBJECT from PROCESS."
(dape--debug 'io "Received:\n%S" object)
(when-let* ((type-string (plist-get object :type))
(type (intern type-string)))
(cl-case type
(response
(let ((seq (plist-get object :request_seq)))
(when-let ((timer (gethash seq dape--timers)))
(cancel-timer timer)
(remhash seq dape--timers))
(when-let ((cb (gethash seq dape--cb)))
(funcall cb
process
(plist-get object :body)
(plist-get object :success)
(plist-get object :message))
(remhash seq dape--cb))))
(request
(dape-handle-request process
(intern (plist-get object :command))
(plist-get object :seq)
(plist-get object :arguments)))
(event
(let ((seq (plist-get object :seq)))
(cond
;; FIXME This is only here for `godot' which keeps sending duplicate.
((or (> seq dape--seq-event)
(zerop seq))
(setq dape--seq-event seq)
(dape-handle-event process
(intern (plist-get object :event))
(plist-get object :body)))
(t (dape--debug 'error
"Event ignored due to request seq %d < last handled seq %d"
seq dape--seq-event)))))
(_ (dape--debug 'info "No handler for type %s" type)))))
(defun dape--process-filter (process string)
"Filter for Dape processes."
(when-let (((process-live-p process))
(input-buffer (process-buffer process))
(buffer (current-buffer)))
(with-current-buffer input-buffer
(goto-char (point-max))
(insert string)
(goto-char (point-min))
(let (expecting-more-bytes start)
(while (and (setq start (point))
(search-forward "Content-Length: " nil t)
(goto-char (match-beginning 0))
(search-forward-regexp dape--content-length-re
(+ (point) 1000) t))
;; Server non dap output?
(unless (equal start (match-beginning 0))
(dape--debug 'std-server "%s"
(buffer-substring start (match-beginning 0))))
(let ((content-length (string-to-number (match-string 1))))
(if-let* ((expected-end
(byte-to-position
(+ content-length (position-bytes (point)))))
(object
(condition-case nil
(json-parse-buffer :object-type 'plist
:null-object nil
:false-object nil)
(error
(and
(dape--debug 'error
"Failed to parse json from `%s`"
(buffer-substring (point) expected-end))
nil)))))
(with-current-buffer buffer
(setq expecting-more-bytes nil)
(dape--handle-object process object))
(dape--debug 'info "Need more bytes")
(setq expecting-more-bytes t))))
(when expecting-more-bytes
(goto-char (point-min))))
;; This seams like we are living a bit dangerous. If input buffer
;; is killed we are going to erase some random buffer
(when (buffer-live-p input-buffer)
(delete-region (point-min) (point))))))
;;; Outgoing requests
(defconst dape--timeout 5
"Time before dape starts to complain about missing responses.")
(defun dape--create-timer (process seq)
"Create SEQ request timeout timer for PROCESS."
(puthash seq
(run-with-timer dape--timeout
nil
(dape--callback
(dape--debug 'error
"Timeout for reached for seq %d"
seq)
(when (dape--live-process t)
(dape--update-state "timed out"))
(remhash seq dape--timers)
(when-let ((cb (gethash seq dape--cb)))
(clrhash dape--tree-widget-open-p)
(remhash seq dape--cb)
(funcall cb process nil nil nil)))
process)
dape--timers))
(defun dape-send-object (process &optional seq object)
"Helper for `dape-request' to send SEQ request with OBJECT to PROCESS."
(let* ((object (if seq (plist-put object :seq seq) object))
(json (json-serialize object :false-object nil))
(string (format "Content-Length: %d\r\n\r\n%s" (length json) json)))
(dape--debug 'io "Sending:\n%S" object)
(process-send-string process string)))
(defun dape-request (process command arguments &optional cb)
"Send request COMMAND to PROCESS with ARGUMENTS.
If CB set, invoke CB on response.
See `dape--callback' for expected function signature."
(let ((seq (setq dape--seq (1+ dape--seq)))
(object (and arguments (list :arguments arguments))))
(dape--create-timer process seq)
(when cb
(puthash seq cb dape--cb))
(dape-send-object process
seq
(thread-first object
(plist-put :type "request")
(plist-put :command command)))))
(defun dape--initialize (process)
"Send initialize request to PROCESS."
(dape-request process
"initialize"
(list :clientID "dape"
:adapterID (plist-get dape--config
:type)
:pathFormat "path"
:linesStartAt1 t
:columnsStartAt1 t
;;:locale "en-US"
;;:supportsVariableType t
;;:supportsVariablePaging t
:supportsRunInTerminalRequest t
;;:supportsMemoryReferences t
;;:supportsInvalidatedEvent t
;;:supportsMemoryEvent t
;;:supportsArgsCanBeInterpretedByShell t
:supportsProgressReporting t
:supportsStartDebuggingRequest t
;;:supportsVariableType t
)
(dape--callback
(setq dape--capabilities body)
(when success
(dape--launch-or-attach process)))))
(defun dape--launch-or-attach (process)
"Send launch or attach request to PROCESS.
Uses `dape--config' to derive type and to construct request."
(dape-request process
(or (plist-get dape--config :request) "launch")
(append
(cl-loop for (key value) on dape--config by 'cddr
when (keywordp key)
append (list key value))
(plist-get dape--config 'start-debugging))
(dape--callback
(when (plist-get dape--config 'start-debugging)
(plist-put dape--config 'start-debugging nil)))))
(defun dape--set-breakpoints (process buffer breakpoints &optional cb)
"Set BREAKPOINTS in BUFFER by send setBreakpoints request to PROCESS.
BREAKPOINTS is an list of breakpoint overlays.
See `dape--callback' for expected CB signature."
(let ((lines (mapcar (lambda (breakpoint)
(with-current-buffer (overlay-buffer breakpoint)
(line-number-at-pos (overlay-start breakpoint))))
breakpoints)))
(dape-request process
"setBreakpoints"
(list
:source
(list
:name (file-name-nondirectory
(buffer-file-name buffer))
:path (buffer-file-name buffer))
:breakpoints
(cl-map
'vector
(lambda (overlay line)
(let (plist it)
(setq plist (list :line line))
(cond
((setq it (overlay-get overlay 'dape-log-message))
(setq plist (plist-put plist :logMessage it)))
((setq it (overlay-get overlay 'dape-expr-message))
(setq plist (plist-put plist :condition it))))
plist))
breakpoints
lines)
:lines (apply 'vector lines))
cb)))
(defun dape--set-main-breakpoints (process cb)
"Set the main function breakpoints in adapter PROCESS.
The function names are derived from `dape-main-functions'.
See `dape--callback' for expected CB signature."
(if (plist-get dape--capabilities :supportsFunctionBreakpoints)
(dape-request process
"setFunctionBreakpoints"
(list
:breakpoints
(cl-map 'vector
(lambda (name)
(list :name name))
dape-main-functions))
cb)
(funcall cb process)))
(defun dape--set-exception-breakpoints (process cb)
"Set the exception breakpoints in adapter PROCESS.
The exceptions are derived from `dape--exceptions'.
See `dape--callback' for expected CB signature."
(if dape--exceptions
(dape-request process
"setExceptionBreakpoints"
(list
:filters
(cl-map 'vector
(lambda (exception)
(plist-get exception :filter))
(seq-filter (lambda (exception)
(plist-get exception :enabled))
dape--exceptions)))
cb)
(funcall cb process)))
(defun dape--configure-exceptions (process cb)
"Configure exception breakpoints in adapter PROCESS.
The exceptions are derived from `dape--exceptions'.
See `dape--callback' for expected CB signature."
(setq dape--exceptions
(cl-map 'list
(lambda (exception)
(let ((stored-exception
(seq-find (lambda (stored-exception)
(equal (plist-get exception :filter)
(plist-get stored-exception :filter)))
dape--exceptions)))
(cond
(stored-exception
(plist-put exception :enabled
(plist-get stored-exception :enabled)))
;; new exception
(t
(plist-put exception :enabled
(plist-get exception :default))))))
(plist-get dape--capabilities
:exceptionBreakpointFilters)))
(dape--set-exception-breakpoints process
(dape--callback
(dape--info-update-widget dape--exceptions-widget)
(funcall cb process))))
(defun dape--configure-breakpoints (process cb)
"Configure breakpoints in adapter PROCESS.
See `dape--callback' for expected CB signature."
(dape--clean-breakpoints)
(if-let ((counter 0)
(buffers-breakpoints (seq-group-by 'overlay-buffer
dape--breakpoints)))
(dolist (buffer-breakpoints buffers-breakpoints)
(pcase-let ((`(,buffer . ,breakpoints) buffer-breakpoints))
(dape--set-breakpoints process
buffer
breakpoints
(dape--callback
(setf counter (1+ counter))
(when (eq counter (length buffers-breakpoints))
(funcall cb process nil))))))
(dape--set-main-breakpoints process cb)))
(defun dape--configuration-done (process)
"End initialization of adapter PROCESS."
(dape-request process
"configurationDone"
nil
(dape--callback nil)))
(defun dape--get-threads (process stopped-id all-threads-stopped cb)
"Helper for the stopped event to update `dape--threads'."
(dape-request process
"threads"
nil
(dape--callback
(setq dape--threads
(cl-map
'list
(lambda (new-thread)
(let ((thread
(or (seq-find
(lambda (old-thread)
(eq (plist-get new-thread :id)
(plist-get old-thread :id)))
dape--threads)
new-thread)))
(plist-put thread :name
(plist-get new-thread :name))
(cond
(all-threads-stopped
(plist-put thread :status "stopped"))
((eq (plist-get thread :id) stopped-id)
(plist-put thread :status "stopped"))
(t thread))))
(plist-get body :threads)))
(funcall cb process))))
(defun dape--stack-trace (process thread cb)
"Update the stack trace in THREAD plist by adapter PROCESS.
See `dape--callback' for expected CB signature."
(cond
((or (plist-get (dape--current-thread) :stackFrames)
(not (integerp (plist-get thread :id))))
(funcall cb process))
(t
(dape-request process
"stackTrace"
(list :threadId (plist-get thread :id)
:levels 50)
(dape--callback
(plist-put thread :stackFrames
(cl-map 'list
'identity
(plist-get body :stackFrames)))
(funcall cb process))))))
(defun dape--variables (process object cb)
"Update OBJECTs variables by adapter PROCESS.
See `dape--callback' for expected CB signature."
(let ((variables-reference (plist-get object :variablesReference)))
(if (or (zerop variables-reference)
(plist-get object :variables))
(funcall cb process)
(dape-request process
"variables"
(list :variablesReference variables-reference)
(dape--callback
(plist-put object
:variables
(thread-last (plist-get body :variables)
(cl-map 'list 'identity)
(seq-filter 'identity)))
(funcall cb process))))))
(defun dape--variables-recursive (process object path pred cb)
"Update variables recursivly.
Get variable data from PROCESS and put result on OBJECT until PRED is nil.
PRED is called with PATH and OBJECT.
See `dape--callback' for expected CB signature."
(let ((objects
(seq-filter (apply-partially pred path)
(or (plist-get object :scopes)
(plist-get object :variables))))
(requests 0))
(if objects
(dolist (object objects)
(dape--with dape--variables (process object)
(dape--with dape--variables-recursive (process
object
(cons (plist-get object :name)
path)
pred)
(setq requests (1+ requests))
(when (length= objects requests)
(funcall cb process)))))
(funcall cb process))))
(defun dape--evaluate-expression (process frame-id expression context cb)
"Send evaluate request to PROCESS.
FRAME-ID specifies which frame the EXPRESSION is evaluated in and
CONTEXT which the result is going to be displayed in.
See `dape--callback' for expected CB signature."
(dape-request process
"evaluate"
(list :frameId frame-id
:expression expression
:context context)
cb))
(defun dape--scopes (process stack-frame cb)
"Send scopes request to PROCESS for STACK-FRAME plist.
See `dape--callback' for expected CB signature."
(if-let ((id (plist-get stack-frame :id))
((not (plist-get stack-frame :scopes))))
(dape-request process
"scopes"
(list :frameId id)
(dape--callback
(let ((scopes (cl-map 'list 'identity (plist-get body :scopes))))
(plist-put stack-frame :scopes scopes)
(funcall cb process))))
(funcall cb process)))
(defun dape--update (process &optional skip-clear-stack-frames)
"Update dape data and ui.
PROCESS specifies adapter process.
If SKIP-CLEAR-STACK-FRAMES not all stack frame data is cleared. This
is usefully if only to load data for another thread."
(let ((current-thread (dape--current-thread)))
(unless skip-clear-stack-frames
(dolist (thread dape--threads)
(plist-put thread :stackFrames nil)))
(dolist (watched dape--watched)
(plist-put watched :fetched nil))
(dape--with dape--stack-trace (process current-thread)
(dape--update-stack-pointers)
(dape--with dape--scopes (process
(dape--current-stack-frame))
(dape--with dape--variables-recursive (process
(dape--current-stack-frame)
nil
(lambda (path object)
(and (not (plist-get object :expensive))
(length< path 1))))
(when dape-inline-variables
(dape--update-inline-variables))
(dape--update-widgets))))))