-
Notifications
You must be signed in to change notification settings - Fork 4
/
emacs-codeql.el
3337 lines (3061 loc) · 153 KB
/
emacs-codeql.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
;;; emacs-codeql.el --- codeql support for emacs -*- lexical-binding: t -*-
;; Author: Bas Alberts
;; Maintainer: Bas Alberts <bas@anti.computer>
;; Version: 0.2.1-pre
;; Package-Requires: ((emacs "27.1") (seq "2.23") (transient "0.3.7") (jsonrpc "1.0.14") (tree-sitter "0.18.0") (tree-sitter-langs "0.11.4") (tree-sitter-indent) (aggressive-indent) (eglot) (org))
;; Homepage: https://github.com/anticomputer/codeql.el
;; Keywords: dev
;; 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 <https://www.gnu.org/licenses/>.
;;; Commentary:
;; This package is a very early version of modern CodeQL support for emacs.
;;
;; It operates three major components:
;;
;; ql-tree-sitter.el || ql-tree-sitter-builtin.el
;;
;; A tree-sitter based QL highlighting and indentation mode. It requires
;; emacs-tree-sitter, tree-sitter-langs, tree-sitter-indent, tree-sitter-hl
;; and aggressive-indent to function for the non-native tree-sitter support.
;;
;; If you are on emacs 29 and have compiled with tree-sitter support you
;; can alternatively use ql-tree-sitter-builtin.el which provides a native
;; tree-sitter ql mode for emacs 29 and above.
;;
;; emacs-codeql.el
;;
;; A utility layer that enhances ql-tree-sitter-mode with modern codeql
;; ide extension functionality. It requires transient and json-pointer
;; to function in a basic capacity but eglot is highly recommended.
;;
;; While ql-tree-sitter.el does function without emacs-codeql.el, the two
;; are assumed to operate in tandem and considered part of the same package.
;; For `emacs-codeql' configuration examples and advice:
;;
;; https://github.com/anticomputer/emacs-codeql
;;; Disclaimers
;; This package has not been tested with lsp-mode and earlier experiments
;; with lsp-mode and QL language support suggest a less than ideal experience
;; when compared with eglot based lsp support for QL.
;;; Acknowledgements
;; This package was heavily inspired by, and in some cases directly ported
;; from, Alvaro Muñoz's codeql.nvim (https://github.com/pwntester/codeql.nvim)
;; I'd like to thank him for dragging me into a continuous, yet good natured,
;; editor arms race. He solved most of the hard problems in lua, and a lot of
;; this package stands on the shoulders of his prior art.
;; A lot of the fundamental ideas behind this package were both inspired and
;; outlined by Esben Sparre Andreasen (https://github.com/esbena). Esben is
;; a CodeQL engineer and his deep QL knowledge and early work on emacs codeql
;; support was a big inspiration to revive this effort. While this package
;; no longer contains Esben's original major mode and org rendering, the very
;; first iteration was heavily drafted on top of his work, and his early
;; design ideas are very much carried forward in this implementation.
;; While I was writing this code I found myself doing an inordinate amount
;; of destructuring binds to chew through the various json objects. In search
;; of a cleaner solution, I came across https://github.com/syohex/emacs-json-pointer
;; which I've found to be infinitely useful for clear json object access in elisp.
;; Since it is not available on MELPA, we bundle it as part of this package.
;; All original copyright and licensing as designated by Shohei YOSHIDA applies,
;; and I'd like to thank them for their continued contributions across the elisp
;; ecosystem.
;;; Support
;; There is none. This package is wholly unsupported and is focused solely on
;; my own workflows and requirements for codeql use. However, if you find it
;; useful and do run into problems, do please file an issue :)
;;; Code:
;; part of emacs
(require 'jsonrpc)
(require 'cl-lib)
(require 'url-util)
(require 'url-parse)
(require 'org)
(require 'ol)
(require 'files)
(require 'project)
;; bundled
(require 'json-pointer)
;; not part of emacs
(require 'transient)
;;; place our artifacts if they don't exist yet (very hacky!)
(cond
;; emacs 29+
((and (>= emacs-major-version 29)
(require 'treesit nil t)
(treesit-available-p))
(message "Attempting to use builtin tree-sitter support for emacs-codeql.")
(unless (treesit-ready-p 'ql)
(if (yes-or-no-p "tree-sitter ql support not found, install artifacts now?")
(let ((treesit-language-source-alist
'((ql . ("https://github.com/tree-sitter/tree-sitter-ql"
nil
nil
nil)))))
(treesit-install-language-grammar 'ql))
(error "emacs-codeql does not work without tree-sitter-langs support."))))
;; emacs 28-
((and (<= emacs-major-version 28)
(require 'tree-sitter-langs nil t))
(declare-function tree-sitter-langs--bin-dir "ext:tree-sitter-langs")
(unless
(member t
(cl-map 'list
(lambda (f)
(file-exists-p (concat (tree-sitter-langs--bin-dir) f)))
'("/ql.dylib" "/ql.so")))
(if (yes-or-no-p "tree-sitter-langs ql support not found, install artifacts now?")
(let* ((arch (string-trim-right (shell-command-to-string "uname -m")))
(sys (cond ((eq system-type 'gnu/linux) "linux")
((eq system-type 'darwin) "darwin")
(t (error "Your platform is currently not supported."))))
(cmd (format "cp %s/bin/%s/%s/ql.* %s"
(file-name-directory (or load-file-name (buffer-file-name)))
sys arch (tree-sitter-langs--bin-dir))))
(message "Placing tree-sitter artifacts with %s" cmd)
(cl-assert (eql 0 (shell-command cmd))))
(error "emacs-codeql does not work without tree-sitter-langs support."))))
;; bail out if we can't figure out tree-sitter support
(t (error "emacs-codeql is unable to determine tree-sitter support strategy ... aborting!")))
;; pick a tree-sitter
(if (and (fboundp 'treesit-ready-p) (treesit-ready-p 'ql))
;; use the built-in tree-sitter
(require 'ql-tree-sitter-builtin)
;; fall back to the external tree-sitter support
(require 'ql-tree-sitter))
;;; global user configuration options
(defgroup emacs-codeql nil
"Emacs CodeQL support configuration."
:prefix "emacs-codeql"
:group 'emacs-codeql)
(defcustom codeql-ast-sync-highlighting t
"Enable fancy AST viewer synchronized highlighting."
:type 'boolean
:group 'emacs-codeql)
(defcustom codeql-query-server-timeout most-positive-fixnum
"Query server compile/run timeout in seconds.
Normally we do not timeout, since queries can be long running.
Users may cancel queries instead through the transient UI."
:type 'integer
:group 'emacs-codeql)
(defcustom codeql-transient-binding "C-c C-d"
"The keybinding to start the emacs-codeql transient UI."
:type 'key-sequence
:group 'emacs-codeql)
(defcustom codeql-enable-xrefs t
"Enable CodeQL xref support for database source archives."
:type 'boolean
:group 'emacs-codeql)
(defcustom codeql-enable-remote-xrefs t
"Enable CodeQL xref support for database source archives in remote sessions."
:type 'boolean
:group 'emacs-codeql)
(defcustom codeql-configure-eglot-lsp t
"Use eglot for LSP support by default.
emacs-codeql requires eglot 20220326.2143 or newer from MELPA."
:type 'boolean
:group 'emacs-codeql)
(defcustom codeql-verbose-commands nil
"Be verbose about which commands we're running at any given time."
:type 'boolean
:group 'emacs-codeql)
(defcustom codeql-state-dir "~/.emacs-codeql"
"Base directory for codeql emacs state maintenance.
It is important to keep this as a ~/relative path so that it will resolve both
in local and remote contexts to something that readily exists."
:type 'directory
:group 'emacs-codeql)
(defcustom codeql-max-raw-results 2000
"The max amount of raw result tuples to render in an org-table."
:type 'integer
:group 'emacs-codeql)
(defcustom codeql-use-gh-codeql-extension-when-available t
"If emacs-codeql detects the presence of a codeql enabled gh cli, use it.
See https://github.com/github/gh-codeql for more information."
:type 'boolean
:group 'emacs-codeql)
(defcustom codeql-query-server-events-buffer-size 2000000
"The scrollback size for query server event buffers."
:type 'integer
:group 'emacs-codeql)
;; globals that the user normally shouldn't have to touch, but may
(defvar codeql-cli (executable-find "codeql")
"Path to codeql-cli")
(defvar codeql-search-paths '()
"codeql cli library search paths that require search precedence.
This provides you with search path precedence control and should not be used for
standard search path configurations.")
(defvar-local codeql-query-server nil
"Which query-server type to use.
This is automatically resolved for the buffer local context since we may be
operating multiple codeql environments, both local and remote, concurrently.
Don't confuse this for codeql--query-server, which represents the active
query server rpc connection.")
;; internal variables and configurations
(defvar codeql--run-query-always-save t
"Whether you always want to save prior to query evaluation.
Evaluation requires a synced position in the query file on disk, such that the
query server can grab the right contents.
This applies to both normal evaluation and quick evaluation.")
(defvar codeql--query-server-max-ram nil
"The max amount of RAM to use for query server evaluations.
Leave nil for default.")
;; we use buffer-local copies of these so we can play context dependent tricks
(defvar-local codeql--cli-buffer-local nil)
(defvar-local codeql--search-paths-buffer-local nil)
(defun codeql--gh-codeql-cli-available-p ()
(condition-case nil
(eql 0 (with-temp-buffer
(process-file "gh" nil `(,(current-buffer) nil) nil "codeql")))
(error nil)))
(defun codeql--cli-buffer-local-as-string ()
(mapconcat #'identity codeql--cli-buffer-local " "))
(defun codeql--search-paths-from-codeql-config ()
"Grab search paths from the codeql cli configuration file."
(let ((config-path "~/.config/codeql/config"))
(when-let* ((config-file
(and (codeql--file-exists-p config-path)
(with-temp-buffer
(insert-file-contents
(codeql--tramp-wrap config-path))
(buffer-string))))
(path-config
(when (string-match "^--search-path\\( +\\|=\\)\\(.*\\)" config-file)
(match-string 2 config-file))))
(cl-loop with search-paths = (split-string path-config ":")
for path in search-paths
unless (codeql--file-exists-p path) do
(error (format "Non-existing search path in configuration: %s" path))
collect
(let ((local-search-path
(codeql--tramp-unwrap
(expand-file-name (codeql--tramp-wrap path)))))
(message "Adding %s to search path from codeql cli config." local-search-path)
local-search-path)))))
(defun codeql--search-paths-from-emacs-config ()
"Grab search paths from our emacs configuration."
(cl-loop for path in codeql-search-paths
unless (and path (codeql--file-exists-p path)) do
(error (format "Non-existing search path in configuration: %s" path))
collect (let ((local-search-path
(codeql--tramp-unwrap
(expand-file-name (codeql--tramp-wrap path)))))
(message "Adding %s to search path from emacs config." local-search-path)
local-search-path)))
(defun codeql--search-path ()
"Return any currently configured codeql cli search paths."
(mapconcat #'identity codeql--search-paths-buffer-local ":"))
;; project.el integration for eglot
(defun codeql--find-project-root (path)
(or (locate-dominating-file path "qlpack.yml")
(locate-dominating-file path "codeql-pack.yml")))
(defun project-codeql (dir)
(let ((root (codeql--find-project-root dir)))
(when root
(list 'codeql root))))
(cl-defmethod project-root ((project (head codeql)))
(nth 1 project))
(cl-defmethod project-external-roots ((project (head codeql)))
codeql--search-paths-buffer-local)
(add-to-list 'project-find-functions #'project-codeql)
;; Eglot configuration
(when codeql-configure-eglot-lsp
(require 'eglot)
(defun codeql--lang-server-contact (_i)
"Return the currently configured LSP server parameters."
(cl-assert codeql--cli-buffer-local t)
(let ((lsp-server-cmd
(append codeql--cli-buffer-local
(list "execute" "language-server"
(format "--search-path=%s" (codeql--search-path))
"--check-errors" "ON_CHANGE"
"-q"))))
(message "Using LSP server cmd: %s" lsp-server-cmd)
lsp-server-cmd))
;; only configure eglot for codeql when we have the cli available in PATH
(add-to-list 'eglot-server-programs
`(ql-tree-sitter-mode . ,#'codeql--lang-server-contact))
;; hack to keep eglot project search spaces consistent on following xrefs
(defvar codeql--eglot-override nil)
(defun codeql-xref-location-marker (orig-fun &rest args)
(cond ((eq major-mode 'ql-tree-sitter-mode)
(let* ((codeql--eglot-override
(list default-directory
codeql--search-paths-buffer-local)))
(apply orig-fun args)))
(t (apply orig-fun args))))
;; this advice allows us to implement some special behavior when following
;; xrefs from the root of a codeql buffer
(advice-add 'xref-location-marker :around #'codeql-xref-location-marker))
(defun codeql--get-cli-version ()
;; used in setup for ql-tree-sitter-mode so we can not assert the mode here yet.
(let* ((cmd (format "%s version" (codeql--cli-buffer-local-as-string))))
(codeql--shell-command-to-string cmd)))
(defun codeql--buffer-local-init-hook ()
"Set up a codeql buffer context correctly."
;; use whatever the current config for codeql-cli and codeql-search-paths is
(setq codeql--cli-buffer-local (list codeql-cli))
;; decide whether we want to use the gh cli to run our codeql commands
(if (and codeql-use-gh-codeql-extension-when-available
(codeql--gh-codeql-cli-available-p))
(progn
(message "Enabling gh cli codeql extension use.")
(setq codeql--cli-buffer-local
(list (executable-find "gh" (file-remote-p default-directory)) "codeql")))
;; if we're in a remote context, make absolutely sure we know where the cli lives
(when (and (file-remote-p default-directory))
(let ((remote-path
(string-trim-right
(or (executable-find "codeql" t)
(read-file-name "Need remote path to codeql cli bin: "
nil default-directory t)))))
(message "Setting remote codeql cli path: %s" remote-path)
(setq codeql--cli-buffer-local (list (codeql--tramp-unwrap remote-path))))))
;; ensure we have somewhere to store result data in both local and remote contexts
(codeql--init-state-dirs)
;; ensure we were able to resolve _A_ path for the codeql cli local|remote execution
(cl-assert codeql--cli-buffer-local t)
;; now that default-directory points where it should, resolve our search paths
(if (and (boundp 'codeql--eglot-override) codeql--eglot-override)
;; this buffer is an xref follow from an already open project
;; so we just replicate the search path state of the existing project
;; which will prevent us from trying to start a bunch of different
;; language servers when navigating into xref'd qlpack roots
(progn
(message "Replicating search paths and project root from parent project.")
(setq default-directory (car codeql--eglot-override))
(setq codeql--search-paths-buffer-local (cadr codeql--eglot-override)))
;; this is the root of a new codeql project that we opened ourselves
(setq default-directory
(or (codeql--find-project-root (buffer-file-name))
;; if we can't find a project root, assume cwd is project root
(file-name-directory (buffer-file-name))))
(message "Resolving search paths from configuration.")
(setq codeql--search-paths-buffer-local
(append
;; emacs-codeql configs always have precedence
(codeql--search-paths-from-emacs-config)
;; only add new paths that weren't already configured to prevent double-hits, this can be nil
(cl-loop with config-paths = (codeql--search-paths-from-codeql-config)
for path in config-paths
unless (member path codeql-search-paths)
collect path)))
;; library paths should contain everything we need in terms of search paths
(let ((library-paths
(codeql--resolve-library-paths
(codeql--tramp-unwrap
(expand-file-name
(codeql--tramp-wrap (buffer-file-name)))))))
(setq codeql--search-paths-buffer-local
(append
codeql--search-paths-buffer-local
(cl-loop for library-path across library-paths
unless (member library-path codeql--search-paths-buffer-local)
collect library-path))))
;; dedupe and remove nil from search paths
(setq codeql--search-paths-buffer-local
(delq nil (delete-dups
codeql--search-paths-buffer-local))))
;; now that we have all our search paths, let's try and start up our LSP server
;; this will rely on our project.el integration to determine the workspace paths
(condition-case nil
(when (and codeql-configure-eglot-lsp
(or (and (file-remote-p (buffer-file-name))
(yes-or-no-p "[WARNING] Do you want to use LSP remotely? This can be very slow!"))
(not (file-remote-p (buffer-file-name)))))
;; turn eglot on if local or we really want it remote
(eglot-ensure))
;; no LSP for us due to error
(error (message "Ignoring failed LSP initialization and plowing ahead!"))))
;; add a hook that sets up all the things we need to be available in the buffer-local context
(add-hook 'ql-tree-sitter-mode-hook #'codeql--buffer-local-init-hook)
;; backup formatting utilities for when ql-tree-sitter is not available
(defun codeql-format (&optional min max)
"Format a QL region, use when ql-tree-sitter + agressive-indent is not available."
(interactive)
(shell-command-on-region
(or min (point-min))
(or max (point-max))
(format "%s query format --no-syntax-errors -- -"
(codeql--cli-buffer-local-as-string))
t t))
(defun codeql-format-region (min max)
"Format the current CodeQL region if active, or entire buffer if not."
(interactive "r")
(codeql-format min max))
;;; storage / persistence
(defvar codeql-results-dir (concat codeql-state-dir "/results"))
(defvar codeql-tmp-dir (concat codeql-state-dir "/tmp"))
;; Eglot lsp-to-point routines that deal with utf-16 code points
;;
;; START LICENSING: https://github.com/joaotavora/eglot/blob/master/LICENSE
;;; deal with utf-16 code points for column calculations, modified from eglot
(defun codeql--lsp-abiding-column ()
"Calculate current COLUMN as defined by the LSP spec."
;; codeql query server uses 1-based column values and utf-16 code points
(/ (length
(encode-coding-region
(line-beginning-position)
(min (point) (point-max)) 'utf-16 t))
2))
;; note: this isn't the same as codeql-lsp-abiding column which is 1-based
(defun codeql--eglot-lsp-abiding-column (&optional lbp)
"Calculate current COLUMN as defined by the LSP spec.
LBP defaults to `line-beginning-position'."
(/ (- (length
(encode-coding-region
(or lbp (line-beginning-position))
;; Fix github#860
(min (point) (point-max)) 'utf-16 t))
2)
2))
(cl-defmacro codeql--eglot--widening (&rest body)
"Save excursion and restriction. Widen. Then run BODY." (declare (debug t))
`(save-excursion (save-restriction (widen) ,@body)))
(defun codeql--eglot-move-to-lsp-abiding-column (column)
"Move to COLUMN abiding by the LSP spec."
(save-restriction
(cl-loop
with lbp = (line-beginning-position)
initially
(narrow-to-region lbp (line-end-position))
(move-to-column column)
for diff = (- column
(codeql--eglot-lsp-abiding-column lbp))
until (zerop diff)
do (condition-case eob-err
(forward-char (/ (if (> diff 0) (1+ diff) (1- diff)) 2))
(end-of-buffer (cl-return eob-err))))))
(defun codeql--eglot--lsp-position-to-point (pos-plist &optional marker)
"Convert LSP position POS-PLIST to Emacs point.
If optional MARKER, return a marker instead"
(save-excursion
(save-restriction
(widen)
(goto-char (point-min))
(forward-line (min most-positive-fixnum
(plist-get pos-plist :line)))
(unless (eobp) ;; if line was excessive leave point at eob
(let ((tab-width 1)
(col (plist-get pos-plist :character)))
(unless (wholenump col)
(message "Caution: LSP server sent invalid character position %s. Using 0 instead."
col)
(setq col 0))
(codeql--eglot-move-to-lsp-abiding-column col)))
(if marker (copy-marker (point-marker)) (point)))))
;; END LICENSING: https://github.com/joaotavora/eglot/blob/master/LICENSE
;; Helper functions to deal with tramp contexts
(defun codeql--tramp-wrap (file)
"Wrap a tramp prefix onto file if in a remote context (if needed)."
(cond ((file-remote-p file)
file)
((file-remote-p default-directory)
(let* ((v (tramp-dissect-file-name default-directory))
(method (tramp-file-name-method v))
(user (tramp-file-name-user v))
(host (tramp-file-name-host v)))
(format "/%s:%s%s:%s"
method
(if user (format "%s@" user) "")
host
file)))
(t
file)))
(defun codeql--tramp-unwrap (file)
"Strip the tramp prefix from a file if it's a remote file."
(cond
((file-remote-p file)
(file-local-name file))
(t
file)))
(defun codeql--file-truename (file)
(if (file-remote-p default-directory)
(codeql--tramp-unwrap file)
(file-truename file)))
(defun codeql--file-exists-p (file)
(if (file-remote-p default-directory)
(file-exists-p (codeql--tramp-wrap file))
(file-exists-p (codeql--tramp-unwrap file))))
(defun codeql--init-state-dirs ()
"Create our various storage directories if they do not exist yet."
(mapcar (lambda (path)
(unless (codeql--file-exists-p path)
(mkdir (codeql--tramp-wrap path) t)))
(list codeql-state-dir
codeql-results-dir
codeql-tmp-dir)))
(defun codeql-clear-state-dirs (clear-dirs)
"Clear out storage directories."
(interactive (list
(yes-or-no-p
(format "Clear out %s and %s?"
codeql-results-dir
codeql-tmp-dir))))
(when (and clear-dirs
(codeql--file-exists-p codeql-results-dir)
(codeql--file-exists-p codeql-tmp-dir))
(when (not (directory-empty-p codeql-results-dir))
(cl-assert (= 0 (shell-command (format "rm -v %s/*" codeql-results-dir))) t))
(when (not (directory-empty-p codeql-tmp-dir))
(cl-assert (= 0 (shell-command (format "rm -v %s/*" codeql-tmp-dir)))))))
;;; Request and notification handling
(cl-defgeneric codeql--query-server-handle-request (_server method &rest params)
"Handle SERVER's METHOD request with PARAMS."
(message "handle request: %s %s" method params))
(cl-defgeneric codeql--query-server-handle-notification (_server _method &rest _params)
"Handle SERVER's METHOD notification with PARAMS."
(message "handle notification"))
(cl-defmethod codeql--query-server-handle-notification
(_server (method (eql ql/progressUpdated)) &rest params)
"Handle SERVER's ql/progressUpdated notification with PARAMS."
;;(message "%s %s" method params)
(cl-destructuring-bind ((&key step maxStep message &allow-other-keys)) params
(unless (string= message "")
(message "[%s] step %s/%s -> %s" method step maxStep message))))
(cl-defmethod codeql--query-server-handle-request
(_server (method (eql evaluation/queryCompleted)) &rest params)
"Handle SERVER's evaluation/queryCompleted request with PARAMS."
;;(message "%s %s" method params)
(cl-destructuring-bind ((&key
resultType
queryId
evaluationTime
message
&allow-other-keys))
params
(message "[%s] resultType %s evaluationTime %s"
method resultType evaluationTime)
(cond ((eql resultType 0)
'())
((eql resultType 1)
;; oh the joys of function binding vs variable binding :P
(if message
(message message)
(message "ERROR: Other")))
((eql resultType 2)
(if message
(message message)
(message "ERROR: OOM")))
((eql resultType 3)
(if message
(message message)
(message "ERROR: Timeout")))
((eql resultType 4)
(if message
(message message)
(message "ERROR: Query was canceled"))))))
(defun codeql--query-server2-handle-message (&rest params)
"Handle SERVER's message from PARAMS."
(cl-destructuring-bind ((&key
resultType
queryId
evaluationTime
message
&allow-other-keys))
params
(cond ((eql resultType 0)
'())
((eql resultType 1)
;; oh the joys of function binding vs variable binding :P
(if message
(message message)
(message "ERROR: Other")))
((eql resultType 2)
(if message
(message message)
(message "ERROR: Compilation")))
((eql resultType 3)
(if message
(message message)
(message "ERROR: OOM")))
((eql resultType 4)
(if message
(message message)
(message "ERROR: Query Canceled")))
((eql resultType 5)
(if message
(message message)
(message "ERROR: DB Scheme mismatch")))
((eql resultType 6)
(if message
(message message)
(message "ERROR: DB Scheme no upgrade found"))))))
;;; emacs-wide state tracking variables and functions
(defvar codeql--registered-database-history nil)
;; global caches for database source archive files defs/refs/ast
(defvar codeql--definitions-cache (make-hash-table :test #'equal))
(defvar codeql--references-cache (make-hash-table :test #'equal))
(defvar codeql--ast-cache (make-hash-table :test #'equal))
(defvar codeql--ast-backwards-definitions (make-hash-table :test #'equal)
"A hash table of src-filename -> ast-table.
Provides backwards references into the AST buffer from the source file.")
(defun codeql-clear-refs-defs-ast-cache ()
"Clear global refs/defs/ast caches in case you need a clean slate."
(interactive)
(setq codeql--ast-backwards-definitions (make-hash-table :test #'equal))
(setq codeql--definitions-cache (make-hash-table :test #'equal))
(setq codeql--references-cache (make-hash-table :test #'equal))
(setq codeql--ast-cache (make-hash-table :test #'equal))
(message "Cleared refs/defs/ast caches."))
;; (defvar codeql--active-source-roots-with-buffers nil
;; "A hash table of currently active archive source roots and their query buffers.")
(defvar codeql--active-datasets nil
"A hash table of all registered databases across all sessions.")
(defun codeql--active-datasets-init ()
(setq codeql--active-datasets (make-hash-table :test #'equal)))
(defun codeql--active-datasets-add (database-dataset buffer)
(puthash database-dataset buffer codeql--active-datasets))
(defun codeql--active-datasets-del (database-dataset)
(remhash database-dataset codeql--active-datasets))
(defun codeql--active-datasets-get (database-dataset)
(gethash database-dataset codeql--active-datasets))
(codeql--active-datasets-init)
;;; buffer-local state tracking variables and functions
;; query server config state
(defvar-local codeql--path-problem-max-paths 10)
;; local connection state
(defvar-local codeql--query-server nil
"CodeQL query server rpc connection.")
;; local database state
(defvar-local codeql--active-database nil)
(defvar-local codeql--active-database-language nil)
(defvar-local codeql--database-dataset-folder nil)
(defvar-local codeql--database-source-location-prefix nil)
(defvar-local codeql--database-source-archive-zip nil)
(defvar-local codeql--database-source-archive-root nil)
(defvar-local codeql--library-path nil)
(defvar-local codeql--dbscheme nil)
;; this expects to run inside a query buffer-local context
(defun codeql--reset-database-state ()
"Clear out all the buffer-local database state."
(cl-assert (eq major-mode 'ql-tree-sitter-mode))
(setq codeql--active-database nil)
(setq codeql--active-database-language nil)
(setq codeql--database-dataset-folder nil)
(setq codeql--database-source-location-prefix nil)
(setq codeql--database-source-archive-root nil)
(setq codeql--database-source-archive-zip nil))
;; local query id state
(defvar-local codeql--query-server-client-id 0)
(defvar-local codeql--query-server-progress-id 0)
(defvar-local codeql--query-server-evaluate-id 0)
;; local query history
(defvar-local codeql--completed-query-history nil)
(defun codeql--query-server-on-shutdown (_obj buffer-context)
;; remove any active database from global database state
(when codeql--database-dataset-folder
(codeql--active-datasets-del codeql--database-dataset-folder))
;; clear out the buffer-local server and database state
(with-current-buffer buffer-context
(setq codeql--query-server nil)
(codeql--reset-database-state))
(message "Shut down query server and cleared active database."))
(defun codeql--query-server-next-client-id ()
(setq codeql--query-server-client-id
(1+ codeql--query-server-client-id))
codeql--query-server-client-id)
(defun codeql--query-server-next-progress-id ()
(setq codeql--query-server-progress-id
(1+ codeql--query-server-progress-id))
codeql--query-server-progress-id)
(defun codeql--query-server-next-evaluate-id ()
(setq codeql--query-server-evaluate-id
(1+ codeql--query-server-evaluate-id))
codeql--query-server-evaluate-id)
(defun codeql--query-server-current-or-error ()
"Check that we have an active CodeQL query server connection, or error."
(cl-assert (eq major-mode 'ql-tree-sitter-mode) t)
(or codeql--query-server
(jsonrpc-error "No active JSON-RPC connection.")))
;;; utility functions for running queries
(defun codeql--shell-command-to-string (cmd &optional verbose keep-stdout)
"A shell command to string that gives us explicit control over stdout and stderr."
(when (or verbose codeql-verbose-commands)
(message "Running %s cmd: %s"
(if (file-remote-p default-directory)
"remote" "local")
cmd))
(condition-case nil
(with-temp-buffer
(let* ((stdout-buffer (generate-new-buffer (format "* stdout: %s *" cmd)))
;; process-file will work in remote context pending default-directory
(exit-code
(apply 'process-file
;; rely on something that's ALWAYS there (hopefully)
"/bin/sh"
nil
;; redirect stderr here somewhere if we need to
`(,stdout-buffer nil)
nil
"-c"
(list cmd)))
(stdout-data
(when (eql exit-code 0)
(with-current-buffer stdout-buffer (buffer-string)))))
(unless keep-stdout
(kill-buffer stdout-buffer))
;; return stdout or signal error
(if stdout-data stdout-data (error "failed to execute cmd"))))
(error (progn (message "Error in codeql--shell-command-to-string: %s" cmd) nil))))
(defun codeql--resolve-query-server ()
"Resolve which query-server to use, legacy or query-server2."
(cl-assert (eq major-mode 'ql-tree-sitter-mode) t)
(let* ((cmd (format "%s execute --help" (codeql--cli-buffer-local-as-string)))
(help (codeql--shell-command-to-string cmd)))
(if (string-match-p (regexp-quote "query-server2") help)
"query-server2"
"query-server")))
(defun codeql--resolve-query-paths (query-path)
"Resolve and set buffer-local library-path and dbscheme for QUERY-PATH.
This version is used as part of actual query resolution and sets buffer local
context variables."
(cl-assert (eq major-mode 'ql-tree-sitter-mode) t)
;; only resolve once for current query buffer
(unless (and codeql--library-path codeql--dbscheme)
(message "Resolving query paths.")
(let* ((cmd (format "%s resolve library-path -v --log-to-stderr --format=json --additional-packs=%s --query=%s"
(codeql--cli-buffer-local-as-string) (codeql--search-path)
(codeql--tramp-unwrap query-path)))
(json (codeql--shell-command-to-string cmd)))
(when json
(condition-case nil
(cl-destructuring-bind (&key libraryPath dbscheme &allow-other-keys)
(json-parse-string json :object-type 'plist)
(setq codeql--library-path libraryPath)
(setq codeql--dbscheme dbscheme))
(error (progn (message "error parsing json: %s" json) nil))))))
;; nil indicates there was an error resolving these
(and codeql--library-path codeql--dbscheme))
(defun codeql--resolve-library-paths (query-path)
"Resolve library paths for QUERY-PATH.
This version is used in early buffer local init of search paths and has no
side effects."
(cl-assert (eq major-mode 'ql-tree-sitter-mode) t)
(let* ((cmd (format "%s resolve library-path -v --log-to-stderr --format=json --query=%s"
(codeql--cli-buffer-local-as-string) query-path))
(json (codeql--shell-command-to-string cmd)))
(when json
(condition-case nil
(cl-destructuring-bind (&key libraryPath &allow-other-keys)
(json-parse-string json :object-type 'plist)
;; this is a vector
libraryPath)
(error (progn (message "error parsing json: %s" json) nil))))))
(defun codeql--resolve-qlpack-paths (dir)
"Resolve qlpack paths from DIR."
(cl-assert (eq major-mode 'ql-tree-sitter-mode) t)
(let* ((cmd (format "%s resolve qlpacks -v --log-to-stderr --format=json --search-path=%s"
(codeql--cli-buffer-local-as-string) dir))
(json (codeql--shell-command-to-string cmd)))
(when json
(condition-case nil
(let* ((qlpacks (json-parse-string json :object-type 'alist)))
(cl-loop for qlpack in qlpacks collect
(mapcar #'identity (cdr qlpack))))
(error (progn (message "error parsing json: %s" json) nil))))))
(defun codeql--database-info (database-path)
"Resolve info for database at DATABASE-PATH."
(cl-assert (eq major-mode 'ql-tree-sitter-mode) t)
(let* ((cmd (format "%s resolve database -v --log-to-stderr --format=json -- %s"
(codeql--cli-buffer-local-as-string) (codeql--tramp-unwrap database-path)))
(json (codeql--shell-command-to-string cmd)))
(when json
(condition-case nil
(json-parse-string json :object-type 'alist)
(error (progn (message "error parsing json: %s" json) nil))))))
(defun codeql--database-upgrades (database-scheme)
"Resolve upgrades for DATABASE-SCHEME."
(cl-assert (eq major-mode 'ql-tree-sitter-mode) t)
(let* ((cmd (format "%s resolve upgrades -v --log-to-stderr --format=json -- %s"
(codeql--cli-buffer-local-as-string) (codeql--tramp-unwrap database-scheme)))
(json (codeql--shell-command-to-string cmd)))
(when json
(condition-case nil
(json-parse-string json :object-type 'alist)
(error (progn (message "error parsing json: %s" json) nil))))))
(defun codeql--query-info (query-path)
"Retrieve metadata for QUERY-PATH."
(cl-assert (eq major-mode 'ql-tree-sitter-mode) t)
(let* ((cmd (format "%s resolve metadata -v --log-to-stderr --format=json -- %s"
(codeql--cli-buffer-local-as-string) (codeql--tramp-unwrap query-path)))
(json (codeql--shell-command-to-string cmd)))
(when json
(condition-case nil
(json-parse-string json :object-type 'alist)
(error (progn (message "error parsing json: %s" json) nil))))))
(defun codeql--bqrs-info (bqrs-path)
"Retrieve info for BQRS-PATH."
(cl-assert (eq major-mode 'ql-tree-sitter-mode) t)
(let* ((cmd (format "%s bqrs info -v --log-to-stderr --format=json -- %s"
(codeql--cli-buffer-local-as-string) (codeql--tramp-unwrap bqrs-path)))
(json (codeql--shell-command-to-string cmd)))
(when json
(condition-case nil
(json-parse-string json :object-type 'alist)
(error (progn (message "error parsing json: %s" json) nil))))))
(defun codeql--bqrs-to-csv (bqrs-path entities)
(let* ((csv-file (concat bqrs-path ".csv"))
(cmd (format "%s bqrs decode --output=%s --format=csv --entities=%s -- %s"
(codeql--cli-buffer-local-as-string)
(codeql--tramp-unwrap csv-file) entities (codeql--tramp-unwrap bqrs-path))))
(when (codeql--shell-command-to-string cmd)
(with-temp-buffer (insert-file-contents csv-file) (buffer-string)))))
(defun codeql--bqrs-to-json (bqrs-path entities)
(let* ((json-file (concat bqrs-path ".json"))
(cmd (format "%s bqrs decode --output=%s --format=json --entities=%s -- %s"
(codeql--cli-buffer-local-as-string)
(codeql--tramp-unwrap json-file) entities (codeql--tramp-unwrap bqrs-path))))
(when (codeql--shell-command-to-string cmd)
(with-temp-buffer (insert-file-contents json-file) (buffer-string)))))
(defun codeql--bqrs-to-sarif (bqrs-path id kind &optional max-paths)
(cl-assert (and id kind) t)
(let* ((sarif-file (concat bqrs-path ".sarif"))
;; XXX: TODO check out --column-kind a bit deeper as well
;; it's important to enable --no-group-results, otherwise we get piled
;; on messages for a single result which complicates SARIF parsing
;; also note that our --max-paths is set to 10 by default, as to 4 in
;; the codeql extension, which is why we show more results
(cmd (format "%s bqrs interpret -v --log-to-stderr -t=id=%s -t=kind=%s --output=%s --format=sarif-latest --max-paths=%s --no-group-results -- %s"
(codeql--cli-buffer-local-as-string) id kind
(codeql--tramp-unwrap sarif-file) (or max-paths codeql--path-problem-max-paths)
(codeql--tramp-unwrap bqrs-path))))
(when (codeql--shell-command-to-string cmd)
(with-temp-buffer (insert-file-contents sarif-file) (buffer-string)))))
(defun codeql--database-archive-zipinfo ()
"Return extraction-relative file listing for source archive zip."
(cl-assert (eq major-mode 'ql-tree-sitter-mode) t)
(let ((zipinfo (codeql--shell-command-to-string
(format "%s -1 %s"
(executable-find "zipinfo" (file-remote-p default-directory))
codeql--database-source-archive-zip))))
(when zipinfo
(let ((zipinfo-relative-paths
(cl-map 'list (lambda (file) file) (split-string zipinfo "\n"))))
zipinfo-relative-paths))))
(defun codeql--database-extract-source-archive-zip (trusted-root)
"Mount or extract a database source zip archive, ensuring TRUSTED-ROOT."
(cl-assert (eq major-mode 'ql-tree-sitter-mode) t)
(message "archive-root: %s" (codeql--file-truename codeql--database-source-archive-root))
(message "trusted-root: %s" (codeql--file-truename trusted-root))
(cond
((and (>= emacs-major-version 27) (eq system-type 'gnu/linux))
;; >= emacs 27 we can just interact with the zip archive directly :)