-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcc.lua
More file actions
1602 lines (1509 loc) Β· 56.3 KB
/
Copy pathcc.lua
File metadata and controls
1602 lines (1509 loc) Β· 56.3 KB
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
-- ============================================================================
-- C / C++ integration. Single source of truth for "how do I build, run and
-- debug this code" β what config/python.lua is for uv, this is for the C family.
--
-- Every C/C++ tool in the config resolves through here: clangd's argv
-- (lua/plugins/lsp.lua), clang-format's path (conform.lua), the lldb-dap
-- adapter (dap.lua), and the <leader>r build/run keymaps at the bottom.
--
-- Two modes, chosen per buffer, no configuration:
-- β’ project β the file sits under a CMakeLists.txt or a Makefile: build with
-- cmake/make, run a *target* (targets come from CMake's File API).
-- β’ single β a lone .c/.cpp (exercises, scratch code, competitive
-- programming): compiled straight to the cache dir and run.
-- <leader>rr does the right one; <leader>rs always forces single-file.
--
-- macOS: the Xcode Command Line Tools already ship clangd, clang-format AND
-- lldb-dap, but only put some of them on $PATH β `xcrun -f <tool>` finds the
-- rest, so a stock Mac needs nothing installed. See M.tool().
-- ============================================================================
local M = {}
local uv = vim.uv or vim.loop
-- ---------------------------------------------------------------------------
-- Settings. Override from your own config *before* anything builds, e.g.
-- require("config.cc").settings.std.cpp = "c++20"
-- ---------------------------------------------------------------------------
M.settings = {
std = { c = "c17", cpp = "c++23" }, -- Apple clang 21 accepts up to c++26 / c23
build_type = "Debug", -- "Debug" (-O0 -g) | "Release" (-O2 -DNDEBUG)
sanitize = false, -- -fsanitize=address,undefined
warnings = { "-Wall", "-Wextra", "-Wpedantic" },
build_dir = "build", -- CMake binary dir, relative to the project root
height = 15, -- height of the run split
indent = 4, -- shiftwidth for C/C++ buffers (matches the clang-format fallback)
column = 100, -- colorcolumn (matches the clang-format fallback ColumnLimit)
jobs = (uv.available_parallelism and uv.available_parallelism()) or 4,
}
-- Per-project CMake/make target choice, keyed by project root.
local chosen_target = {}
-- ---------------------------------------------------------------------------
-- 1. Tool discovery
-- ---------------------------------------------------------------------------
local tool_cache = {}
--- Absolute path to a toolchain binary, or nil. Falls back to `xcrun -f` so the
--- Command Line Tools' clang-format / lldb-dap are found without $PATH surgery.
---@param name string
---@return string|nil
function M.tool(name)
local hit = tool_cache[name]
if hit ~= nil then
return hit or nil
end
local path = vim.fn.exepath(name)
if path == "" and vim.fn.executable("xcrun") == 1 then
local res = vim.system({ "xcrun", "-f", name }, { text = true }):wait()
if res.code == 0 then
path = vim.trim(res.stdout or "")
end
end
if path ~= "" and vim.fn.executable(path) == 1 then
tool_cache[name] = path
else
tool_cache[name] = false
end
return tool_cache[name] or nil
end
--- argv for clangd β flags chosen so a bare file and a full CMake project both
--- behave. Consumed by lua/plugins/lsp.lua.
---@return string[]
function M.clangd_cmd()
return {
M.tool("clangd") or "clangd",
"--background-index", -- index the project on idle, persist to disk
"--clang-tidy", -- lint in-process (no clang-tidy binary needed)
"--completion-style=detailed",
"--header-insertion=iwyu", -- add the owning #include when completing
"--function-arg-placeholders=1",
"--all-scopes-completion",
"--enable-config", -- read .clangd / clangd/config.yaml
"--fallback-style=LLVM",
"--pch-storage=memory",
"-j=" .. M.settings.jobs,
}
end
--- Resolved clang-format path (CLT ships it off-PATH). Consumed by conform.lua.
---@return string|nil
function M.clang_format()
return M.tool("clang-format")
end
--- Resolved lldb-dap path (CLT ships it off-PATH). Consumed by dap.lua.
---@return string|nil
function M.lldb_dap()
return M.tool("lldb-dap")
end
-- ---------------------------------------------------------------------------
-- 2. Project detection
-- ---------------------------------------------------------------------------
local SOURCE_FT = { c = true, cpp = true, cuda = true, objc = true, objcpp = true }
-- The last C-family buffer that was current. Running a program moves the cursor
-- into the run terminal, and the quickfix window isn't a file either β so every
-- "which project is this?" question has to be answered from the source buffer,
-- not from whatever window happens to be focused.
local last_source = nil
--- The buffer the build commands should act on.
---@return integer
local function source_buf()
local cur = vim.api.nvim_get_current_buf()
if not SOURCE_FT[vim.bo[cur].filetype] and last_source and vim.api.nvim_buf_is_valid(last_source) then
return last_source
end
return cur
end
--- A path to start searching from β guaranteed non-empty, because vim.fs.root
--- asserts on "" and getcwd() *is* empty when the cwd has been deleted under us
--- (a checkout, a cleaned build dir).
local function bufpath(buf)
local name = vim.api.nvim_buf_get_name(buf or source_buf())
if name ~= "" then
return name
end
local cwd = vim.fn.getcwd()
if cwd ~= "" then
return cwd
end
local ok, real = pcall(uv.cwd)
if ok and real and real ~= "" then
return real
end
return vim.env.HOME or vim.fn.stdpath("cache")
end
--- The directory to act in: the buffer's own directory, or bufpath() itself when
--- that is already a directory (which it is for a buffer with no file name).
---@return string
local function bufdir(buf)
local path = bufpath(buf)
local stat = uv.fs_stat(path)
if stat and stat.type == "directory" then
return path
end
return vim.fs.dirname(path)
end
--- Directory of the build system that owns this file.
--- vim.fs.root() stops at the *nearest* marker, which is wrong for CMake: a
--- project with `add_subdirectory(src)` has a CMakeLists.txt in src/ too, and
--- configuring that one builds a fragment of the project. So for CMakeLists.txt
--- keep climbing while the parent has one as well.
---@return string
function M.root(buf)
local start = bufpath(buf)
local cmake = vim.fs.root(start, { "CMakeLists.txt" })
if cmake then
local parent = vim.fs.dirname(cmake)
while parent and parent ~= cmake and uv.fs_stat(parent .. "/CMakeLists.txt") do
cmake = parent
parent = vim.fs.dirname(cmake)
end
return cmake
end
return vim.fs.root(start, {
"Makefile",
"makefile",
"GNUmakefile",
"compile_commands.json",
"compile_flags.txt",
".clangd",
}) or bufdir(buf)
end
--- "cmake" | "make" | "single" β which build path <leader>rr takes.
---@return string
function M.kind(buf)
local start = bufpath(buf)
if vim.fs.root(start, { "CMakeLists.txt" }) then
return "cmake"
end
if vim.fs.root(start, { "Makefile", "makefile", "GNUmakefile" }) then
return "make"
end
return "single"
end
--- The CMake binary dir for this buffer's project.
---@return string
function M.build_dir(buf)
return M.root(buf) .. "/" .. M.settings.build_dir
end
-- ---------------------------------------------------------------------------
-- 3. Diagnostics β quickfix
-- ---------------------------------------------------------------------------
-- Neovim's default 'errorformat' is not usable for clang: it types nothing
-- (" error: " gets swallowed into %m, so nothing can tell errors from notes) and
-- it turns every include-chain breadcrumb into a junk entry. Patterns are
-- END-ANCHORED, which is the whole reason the built-in
-- "In file included from %f:%l" never matches clang's "foo.cpp:1:".
-- Compilers are called with -fno-color-diagnostics (an ANSI escape ends up
-- *inside* %f, making the entry unopenable) and -fdiagnostics-absolute-paths.
M.errorformat = table.concat({
-- the snippet / caret art and the trailing tally clang wraps around each one
"%-G%*[ 0-9]|%.%#",
"%-G%*[0-9] warning%.%#",
"%-G%*[0-9] error%.%#",
-- include + instantiation breadcrumbs (clang's form carries no column)
"%-GIn file included from %f:%l:%c:",
"%-GIn file included from %f:%l:",
"%-G%*[ ]from %f:%l:%c:",
"%-G%*[ ]from %f:%l:",
-- build-tool chatter. The ": " is load-bearing: a bare "%-Gmake%.%#" would
-- silently swallow real diagnostics from a file named make_helpers.cpp.
"%-G[%*[ 0-9]%%] %.%#",
"%-Gmake: %.%#",
"%-Gmake[%*[0-9]]: %.%#",
"%-Gninja: %.%#",
-- diagnostics. The %t single-char trick is what types them: e/w/n render as
-- error/warning/note, so :cnext, Trouble and the statusline can discriminate.
"%f:%l:%c: %tarning: %m",
"%f:%l:%c: fatal %trror: %m",
"%f:%l:%c: %trror: %m",
"%f:%l:%c: %tote: %m",
"%f:%l:%c: %m",
"%f:%l: %tarning: %m",
"%f:%l: fatal %trror: %m",
"%f:%l: %trror: %m",
"%f:%l: %tote: %m",
"%f:%l: %m",
-- driver-level failures, which carry no location
"%Efatal error: %m",
"%Eclang%.%#: error: %m",
"%Wclang%.%#: warning: %m",
-- ld's undefined-symbol block: worth showing, but genuinely not jumpable β
-- it names an object file (`_main in foo.o`), never a source line.
"%-GUndefined symbols for architecture%.%#",
'%E "%m"\\, referenced from:',
"%C%*[ ]%m",
"%Eld: error: %m",
"%Wld: warning: %m",
"%Eld: %m",
}, ",")
local QF_PREFIX = "cc: "
--- A hand-written Makefile usually compiles with paths relative to the project
--- root, and quickfix resolves those against *Neovim's* cwd. Re-anchor entries
--- whose file only exists under `root`, otherwise <CR> opens an empty buffer.
---@param root string
local function anchor_quickfix(root)
if not root or root == vim.fn.getcwd() then
return
end
local items, fixed = vim.fn.getqflist(), false
for _, item in ipairs(items) do
if item.valid == 1 and item.bufnr and item.bufnr > 0 then
local name = vim.api.nvim_buf_get_name(item.bufnr)
if name ~= "" and vim.fn.filereadable(name) == 0 then
local candidate = root .. "/" .. vim.fs.normalize(name):gsub("^" .. vim.pesc(vim.fn.getcwd()) .. "/", "")
if vim.fn.filereadable(candidate) == 1 then
item.filename, item.bufnr, fixed = candidate, nil, true
end
end
end
end
if fixed then
local title = vim.fn.getqflist({ title = 1 }).title
vim.fn.setqflist({}, "r", { title = title, items = items })
end
end
--- Put compiler output in the quickfix list. Returns #errors, #warnings.
---@param lines string[]
---@param title string
---@param root? string re-anchor relative paths against this directory
local function to_quickfix(lines, title, root)
vim.fn.setqflist({}, " ", { title = QF_PREFIX .. title, lines = lines, efm = M.errorformat })
if root then
anchor_quickfix(root)
end
local errors, warnings = 0, 0
for _, item in ipairs(vim.fn.getqflist()) do
-- `%trror`/`%tarning` yield lowercase e/w; only the %E/%W-prefixed linker
-- and driver patterns yield uppercase. Normalise, or warnings never count.
local kind = (item.type or ""):upper()
if item.valid == 1 then
if kind == "E" then
errors = errors + 1
elseif kind == "W" then
warnings = warnings + 1
end
end
end
return errors, warnings
end
--- Compilers put diagnostics on stderr and progress chatter on stdout; prefer
--- stderr so `[ 50%] Building β¦` lines never reach the quickfix parser.
local function split_output(res)
local text = res.stderr or ""
if vim.trim(text) == "" then
text = res.stdout or ""
end
return vim.split(text, "\n", { trimempty = true })
end
--- vim.system() reports a signal death (a sanitizer abort is SIGABRT) as
--- code = 0, signal = 6 β so a bare `code ~= 0` check would call it a success.
local function failed(res)
return res.code ~= 0 or (res.signal or 0) ~= 0
end
--- Transient one-line status (no message history, unlike vim.notify).
local function echo(msg, hl)
vim.api.nvim_echo({ { msg, hl or "MoreMsg" } }, false, {})
end
--- Open the quickfix list at the first error.
function M.quickfix()
vim.cmd("botright copen 10")
pcall(vim.cmd.cfirst)
end
--- Close the quickfix window, but only when it's showing *our* build output β
--- never yank away a list the user opened for grep/diagnostics.
local function close_quickfix()
local title = vim.fn.getqflist({ title = 1 }).title or ""
if vim.startswith(title, QF_PREFIX) then
vim.cmd("cclose")
end
end
--- Shared tail of every build: parse the output into the quickfix list, report,
--- and continue with `done` only when the build actually succeeded.
---@param res table the vim.system() result
---@param title string
---@param done? fun()
---@param root? string directory to re-anchor relative diagnostic paths against
local function finish_build(res, title, done, root)
local errors, warnings = to_quickfix(split_output(res), title, root)
if failed(res) then
vim.notify(("%s failed β %d error(s)"):format(title, math.max(errors, 1)), vim.log.levels.ERROR)
M.quickfix()
return
end
if warnings > 0 then
echo((" %s β %d warning(s), <leader>rq"):format(title, warnings), "WarningMsg")
else
close_quickfix()
echo(" " .. title .. " ok")
end
if done then
done()
end
end
-- ---------------------------------------------------------------------------
-- 4. The run window β one reusable bottom split, exit code + wall time in its
-- winbar. jobstart{term=true} needs a fresh (unmodified) buffer each run,
-- since a terminal buffer is bound to exactly one job.
-- ---------------------------------------------------------------------------
local runner = { win = nil, buf = nil, job = nil, last = nil }
local function job_alive(job)
return job and job > 0 and vim.fn.jobwait({ job }, 0)[1] == -1
end
---@param cmd string[]|string argv, or a shell line when redirection is needed
---@param opts { cwd?:string, title?:string }
local function terminal(cmd, opts)
opts = opts or {}
runner.last = { cmd = cmd, opts = opts }
if job_alive(runner.job) then
pcall(vim.fn.jobstop, runner.job)
end
-- Reuse the run window only while it is still showing the run output. Once
-- something else has been opened there it is the user's window, and taking it
-- over would replace the file they're editing.
local reusable = runner.win
and vim.api.nvim_win_is_valid(runner.win)
and runner.buf
and vim.api.nvim_win_get_buf(runner.win) == runner.buf
if reusable then
vim.api.nvim_set_current_win(runner.win)
else
vim.cmd("botright " .. M.settings.height .. "split")
runner.win = vim.api.nvim_get_current_win()
end
local buf = vim.api.nvim_create_buf(false, true)
vim.api.nvim_win_set_buf(runner.win, buf)
if runner.buf and vim.api.nvim_buf_is_valid(runner.buf) and runner.buf ~= buf then
pcall(vim.api.nvim_buf_delete, runner.buf, { force = true })
end
runner.buf = buf
-- Die with the window rather than lingering as an unlisted dead terminal.
vim.bo[buf].bufhidden = "wipe"
-- 'winbar' is a statusline-format option: a stray "%" (a file called 50%.cpp,
-- or args like `--rate 50%`) raises E539 and would abort the run entirely.
local win, title = runner.win, ((opts.title or "run"):gsub("%%", "%%%%"))
vim.wo[win].winbar = " " .. title
vim.wo[win].number = false
vim.wo[win].relativenumber = false
vim.wo[win].signcolumn = "no"
local started = uv.hrtime()
local job = vim.fn.jobstart(cmd, {
term = true,
cwd = opts.cwd,
env = opts.env,
on_exit = function(_, code)
local ms = math.floor((uv.hrtime() - started) / 1e6)
if vim.api.nvim_win_is_valid(win) then
local mark = code == 0 and " " or " "
vim.wo[win].winbar = ("%s%s Β· exit %d Β· %dms"):format(mark, title, code, ms)
end
end,
})
runner.job = job
if job <= 0 then
vim.notify("could not start: " .. vim.inspect(cmd), vim.log.levels.ERROR)
return
end
-- Closing the split stops the program too. A still-running process with no
-- window is worse than a lost log β and it would hold its pty until the next
-- build reused the slot.
vim.api.nvim_create_autocmd("BufWinLeave", {
buffer = buf,
once = true,
callback = function()
if job_alive(job) then
pcall(vim.fn.jobstop, job)
end
end,
})
-- q closes the window (and stops the program with it); the source window is
-- one <C-k> away, and <Esc><Esc> leaves terminal mode as everywhere else.
vim.keymap.set("n", "q", function()
if job_alive(runner.job) then
pcall(vim.fn.jobstop, runner.job)
end
if vim.api.nvim_win_is_valid(win) then
vim.api.nvim_win_close(win, true)
end
end, { buffer = buf, nowait = true, silent = true, desc = "Close run window" })
vim.cmd.startinsert()
end
--- The shell line that actually launches a program. Everything goes through
--- `sh -c 'β¦; exit $?'` on purpose: without the trailing `exit`, sh
--- exec-optimizes the child and a death by signal (a sanitizer abort, a
--- segfault) is reported as exit 0. Run args are intentionally *not* escaped β
--- the prompt behaves like a shell, so quotes and globs work.
---@param bin string
---@param args? string
---@param stdin? string
---@return string[]
local function launch_cmd(bin, args, stdin)
local script = vim.fn.shellescape(bin)
if args and args ~= "" then
script = script .. " " .. args
end
if stdin and stdin ~= "" then
script = script .. " < " .. vim.fn.shellescape(stdin)
end
return { "/bin/sh", "-c", script .. "; exit $?" }
end
--- Re-run the last command (same argv, same cwd).
function M.rerun()
if not runner.last then
vim.notify("Nothing has been run yet", vim.log.levels.WARN)
return
end
terminal(runner.last.cmd, runner.last.opts)
end
-- ---------------------------------------------------------------------------
-- 5. Single-file mode
-- ---------------------------------------------------------------------------
--- Where a single file's binary goes: the cache dir, keyed by the source's
--- directory, so the source tree stays clean and two same-named files in
--- different folders never collide.
---@return string
local function cache_bin(file, create)
local dir = ("%s/cute-cc/%s"):format(vim.fn.stdpath("cache"), vim.fn.sha256(vim.fs.dirname(file)):sub(1, 12))
if create then
vim.fn.mkdir(dir, "p")
end
return dir .. "/" .. vim.fn.fnamemodify(file, ":t:r")
end
--- Compiler argv for one translation unit straight to an executable.
local function compile_argv(file, ft, out)
local is_c = ft == "c"
local cc = M.tool(is_c and "clang" or "clang++") or (is_c and "cc" or "c++")
local argv = { cc, "-std=" .. (is_c and M.settings.std.c or M.settings.std.cpp) }
vim.list_extend(argv, M.settings.warnings)
if M.settings.build_type == "Release" then
vim.list_extend(argv, { "-O2", "-DNDEBUG" })
else
vim.list_extend(argv, { "-O0", "-g" })
end
if M.settings.sanitize then
-- -fno-sanitize-recover is not optional: UBSan otherwise prints the
-- diagnostic, keeps going and exits 0, so a run would look successful.
vim.list_extend(argv, {
"-fsanitize=address,undefined",
"-fno-sanitize-recover=undefined",
"-fno-omit-frame-pointer",
"-g",
})
end
-- Both are load-bearing for the quickfix list: an ANSI escape would be
-- captured *into* the filename, and relative paths resolve against Neovim's
-- cwd rather than the compiler's.
vim.list_extend(argv, { "-fno-color-diagnostics", "-fdiagnostics-absolute-paths" })
vim.list_extend(argv, { file, "-o", out })
return argv
end
--- Sanitizer runtime knobs for the *run* step. detect_leaks is deliberately
--- absent: it is unsupported on macOS arm64 and aborts even correct programs.
local function run_env()
if not M.settings.sanitize then
return nil
end
return {
UBSAN_OPTIONS = "print_stacktrace=1:halt_on_error=1",
ASAN_OPTIONS = "abort_on_error=1",
}
end
--- Compile the current buffer's file. Calls `done(binary)` only on success;
--- errors land in the quickfix list.
---@param done fun(binary: string)
function M.compile_single(done)
local buf = source_buf()
local ft = vim.bo[buf].filetype
if not SOURCE_FT[ft] then
vim.notify("Not a C/C++ buffer", vim.log.levels.WARN)
return
end
local file = vim.api.nvim_buf_get_name(buf)
if file == "" then
vim.notify("Save the buffer first", vim.log.levels.WARN)
return
end
local HEADER = { h = true, hpp = true, hh = true, hxx = true, ipp = true, tpp = true, inl = true }
if HEADER[vim.fn.fnamemodify(file, ":e")] then
vim.notify("Headers aren't compiled on their own β switch to the source (β₯o)", vim.log.levels.WARN)
return
end
if vim.bo[buf].modified then
vim.api.nvim_buf_call(buf, function()
vim.cmd.write()
end)
end
local out = cache_bin(file, true)
local argv = compile_argv(file, ft, out)
local name = vim.fs.basename(file)
echo(" compiling " .. name .. " β¦")
vim.system(argv, { text = true, cwd = vim.fs.dirname(file) }, function(res)
vim.schedule(function()
finish_build(res, name, function()
done(out)
end)
end)
end)
end
--- An input file to feed the program on stdin: `<stem>.in`, then `input.txt`.
---@return string|nil
local function default_stdin(file)
local dir = vim.fs.dirname(file)
for _, candidate in ipairs({ vim.fn.fnamemodify(file, ":r") .. ".in", dir .. "/input.txt" }) do
if uv.fs_stat(candidate) then
return candidate
end
end
return nil
end
--- Compile + run the current file on its own.
---@param opts? { args?: string, stdin?: string }
function M.run_single(opts)
opts = opts or {}
local file = vim.api.nvim_buf_get_name(source_buf())
local stdin = opts.stdin or default_stdin(file)
M.compile_single(function(bin)
local title = vim.fs.basename(bin)
if opts.args and opts.args ~= "" then
title = title .. " " .. opts.args
end
if stdin then
title = title .. " < " .. vim.fs.basename(stdin)
end
terminal(launch_cmd(bin, opts.args, stdin), {
cwd = vim.fs.dirname(file),
title = title,
env = run_env(),
})
end)
end
-- ---------------------------------------------------------------------------
-- 6. CMake β configure, discover targets via the File API, build, run
-- ---------------------------------------------------------------------------
local function read_json(path)
local fd = io.open(path, "r")
if not fd then
return nil
end
local data = fd:read("*a")
fd:close()
local ok, decoded = pcall(vim.json.decode, data)
return ok and decoded or nil
end
--- Ask CMake to emit a codemodel on the next *generate* (the query is an empty
--- file whose name is the request; it must exist before cmake runs).
--- https://cmake.org/cmake/help/latest/manual/cmake-file-api.7.html
local function write_query(build)
local dir = build .. "/.cmake/api/v1/query/client-nvim"
vim.fn.mkdir(dir, "p")
local path = dir .. "/codemodel-v2"
if not uv.fs_stat(path) then
local f = io.open(path, "w")
if f then
f:close()
end
end
end
--- A build dir is only usable once the generator has written its build file β
--- a *failed* generate still leaves CMakeCache.txt behind.
local function is_configured(build)
return uv.fs_stat(build .. "/CMakeCache.txt") ~= nil
and (uv.fs_stat(build .. "/Makefile") ~= nil or uv.fs_stat(build .. "/build.ninja") ~= nil)
end
--- Read one CMake cache entry, e.g. cache_value(build, "CMAKE_BUILD_TYPE").
---@return string|nil
local function cache_value(build, key)
local fd = io.open(build .. "/CMakeCache.txt", "r")
if not fd then
return nil
end
local pattern = "^" .. key .. ":[%w_]+=(.*)$"
for line in fd:lines() do
local value = line:match(pattern)
if value then
fd:close()
return value
end
end
fd:close()
return nil
end
--- Does the configured build dir still match the current settings? Toggling
--- Debug/Release or sanitizers has to re-run the generate step, otherwise
--- `cmake --build` happily rebuilds with the flags baked in last time.
--- Sanitizer state is tracked through our *own* cache variable rather than by
--- sniffing CMAKE_CXX_FLAGS, so we only ever undo a change we made ourselves.
local function needs_reconfigure(build)
if (cache_value(build, "CMAKE_BUILD_TYPE") or "") ~= M.settings.build_type then
return true
end
return (cache_value(build, "CUTE_CC_SANITIZE") == "ON") ~= M.settings.sanitize
end
--- Every executable CMake knows how to build: { { name, path } β¦ }.
---@return table[]
function M.targets(buf)
local build = M.build_dir(buf)
local reply = build .. "/.cmake/api/v1/reply"
local indices = {}
if uv.fs_stat(reply) then
for name, kind in vim.fs.dir(reply) do
if kind == "file" and name:match("^index%-.*%.json$") then
indices[#indices + 1] = name
end
end
end
-- index-<date>-<hash>.json β the newest sorts last (CMake guarantees this).
table.sort(indices)
local index = indices[#indices] and (reply .. "/" .. indices[#indices]) or nil
local out = {}
local idx = index and read_json(index)
local codemodel
for _, obj in ipairs(idx and idx.objects or {}) do
if obj.kind == "codemodel" then
codemodel = read_json(reply .. "/" .. obj.jsonFile)
end
end
-- Every config is accepted: with no CMAKE_BUILD_TYPE, CMake names it "".
local top = (codemodel and codemodel.paths and codemodel.paths.build) or build
for _, config in ipairs(codemodel and codemodel.configurations or {}) do
for _, target in ipairs(config.targets or {}) do
-- The codemodel's target stubs carry no `type`, so each has to be opened.
local detail = read_json(reply .. "/" .. target.jsonFile)
if detail and detail.type == "EXECUTABLE" then
local artifact = detail.artifacts and detail.artifacts[1] and detail.artifacts[1].path
if artifact then
-- artifacts[].path is relative to the *top-level* build dir (and
-- already honours RUNTIME_OUTPUT_DIRECTORY) β never to target.paths.
out[#out + 1] = {
name = detail.name,
path = artifact:sub(1, 1) == "/" and artifact or (top .. "/" .. artifact),
}
end
end
end
end
table.sort(out, function(a, b)
return a.name < b.name
end)
return out
end
--- Configure (or re-configure) the CMake project. `done` runs on success.
---@param done? fun()
function M.configure(done)
local root, build = M.root(), M.build_dir()
if not uv.fs_stat(root .. "/CMakeLists.txt") then
vim.notify("No CMakeLists.txt above " .. vim.fs.basename(bufpath()), vim.log.levels.WARN)
return
end
write_query(build)
local argv = {
"cmake",
"-S",
root,
"-B",
build,
"-DCMAKE_BUILD_TYPE=" .. M.settings.build_type,
"-DCMAKE_EXPORT_COMPILE_COMMANDS=ON",
-- forced color would put ANSI escapes inside the quickfix filenames
"-DCMAKE_COLOR_DIAGNOSTICS=OFF",
}
-- Sanitizers have to reach both the compile and the link step. CUTE_CC_SANITIZE
-- is our own marker: turning them back off only clears the flag variables when
-- *we* were the ones who set them, so a project's own flags are never wiped.
local was_sanitized = cache_value(build, "CUTE_CC_SANITIZE") == "ON"
if M.settings.sanitize then
local san = "-fsanitize=address,undefined -fno-sanitize-recover=undefined -fno-omit-frame-pointer -g"
vim.list_extend(argv, {
"-DCUTE_CC_SANITIZE=ON",
"-DCMAKE_CXX_FLAGS=" .. san,
"-DCMAKE_C_FLAGS=" .. san,
"-DCMAKE_EXE_LINKER_FLAGS=-fsanitize=address,undefined",
})
else
argv[#argv + 1] = "-DCUTE_CC_SANITIZE=OFF"
if was_sanitized then
vim.list_extend(argv, { "-UCMAKE_CXX_FLAGS", "-UCMAKE_C_FLAGS", "-UCMAKE_EXE_LINKER_FLAGS" })
end
end
if vim.fn.executable("ninja") == 1 then
vim.list_extend(argv, { "-G", "Ninja" })
end
echo(" cmake configure (" .. M.settings.build_type .. ") β¦")
vim.system(argv, { text = true, cwd = root }, function(res)
vim.schedule(function()
if failed(res) then
to_quickfix(split_output(res), "cmake configure")
vim.notify("cmake configure failed", vim.log.levels.ERROR)
M.quickfix()
return
end
-- clangd probes each ancestor dir and its `build/` subdir, so the default
-- layout needs nothing. For any other build dir name, link the compilation
-- database into the root so clangd can still find it.
if M.settings.build_dir ~= "build" then
local link, generated = root .. "/compile_commands.json", build .. "/compile_commands.json"
if uv.fs_stat(generated) and not uv.fs_stat(link) then
uv.fs_symlink(generated, link)
end
end
vim.notify("cmake: configured " .. vim.fs.basename(build), vim.log.levels.INFO)
if done then
done()
end
end)
end)
end
--- Build the project (configuring first if needed). `done` runs on success.
--- `target` narrows the build β that's what the run/debug path does, so the inner
--- loop only rebuilds what it is about to launch. <leader>rb passes nothing and
--- builds everything, so errors anywhere in the project still surface.
---@param done? fun()
---@param target? string
---@param reconfigured? boolean internal: guards against a configure/build loop
function M.build_cmake(done, target, reconfigured)
local build = M.build_dir()
if not reconfigured and (not is_configured(build) or needs_reconfigure(build)) then
M.configure(function()
M.build_cmake(done, target, true)
end)
return
end
local argv = { "cmake", "--build", build, "-j", tostring(M.settings.jobs) }
if target then
vim.list_extend(argv, { "--target", target })
end
echo(vim.trim(" cmake --build " .. (target and ("--target " .. target) or "")) .. " β¦")
vim.system(argv, { text = true, cwd = M.root() }, function(res)
vim.schedule(function()
finish_build(res, "cmake build", done, M.root())
end)
end)
end
--- Ask, unless there's only one answer or the project already has a choice.
--- `force` re-asks even when a target is remembered (that's <leader>rp).
local function choose(root, targets, cb, force)
if #targets == 1 then
chosen_target[root] = targets[1].name
return cb(targets[1])
end
if not force then
for _, t in ipairs(targets) do
if t.name == chosen_target[root] then
return cb(t)
end
end
end
vim.ui.select(targets, {
prompt = "CMake target to run:",
format_item = function(t)
return t.name
end,
}, function(pick)
if pick then
chosen_target[root] = pick.name
cb(pick)
end
end)
end
--- Resolve which executable to run, asking only when it's ambiguous. A build dir
--- configured without our File API query (by hand, by an IDE) has no target
--- reply β a bare `cmake -B <build>` regenerates one, so recover instead of
--- making the user re-configure.
---@param cb fun(target: table)
---@param force? boolean re-ask even when a target is already remembered
local function pick_target(cb, force)
local root, build = M.root(), M.build_dir()
local targets = M.targets()
if #targets > 0 then
return choose(root, targets, cb, force)
end
if not is_configured(build) then
vim.notify("Project isn't configured yet β <leader>rg", vim.log.levels.WARN)
return
end
write_query(build)
echo(" cmake: reading targets β¦")
vim.system({ "cmake", "-B", build }, { text = true, cwd = root }, function(res)
vim.schedule(function()
local retry = M.targets()
if #retry == 0 then
to_quickfix(split_output(res), "cmake targets")
vim.notify("No executable targets in this project", vim.log.levels.WARN)
return
end
choose(root, retry, cb, force)
end)
end)
end
--- Let the user (re)choose the target this project runs.
function M.select_target()
pick_target(function(target)
vim.notify("target: " .. target.name, vim.log.levels.INFO)
end, true)
end
---@param opts? { args?: string, stdin?: string }
function M.run_cmake(opts)
opts = opts or {}
M.build_cmake(function()
pick_target(function(target)
terminal(launch_cmd(target.path, opts.args, opts.stdin), {
cwd = M.root(),
title = vim.trim(target.name .. " " .. (opts.args or "")) .. (opts.stdin and (" < " .. vim.fs.basename(opts.stdin)) or ""),
env = run_env(),
})
end)
end, chosen_target[M.root()])
end
-- ---------------------------------------------------------------------------
-- 7. Makefile projects
-- ---------------------------------------------------------------------------
local function makefile(root)
for _, name in ipairs({ "Makefile", "makefile", "GNUmakefile" }) do
if uv.fs_stat(root .. "/" .. name) then
return root .. "/" .. name
end
end
end
--- Does the Makefile declare this target?
local function has_target(path, target)
local fd = io.open(path, "r")
if not fd then
return false
end
for line in fd:lines() do
if line:match("^" .. target .. "%s*:") then
fd:close()
return true
end
end
fd:close()
return false
end
---@param done? fun()
function M.build_make(done)
local root = M.root()
local target = chosen_target[root]
local argv = { "make", "-C", root, "-j", tostring(M.settings.jobs) }
if target then
argv[#argv + 1] = target
end
echo(vim.trim(" make " .. (target or "")) .. " β¦")
vim.system(argv, { text = true, cwd = root }, function(res)
vim.schedule(function()
finish_build(res, "make", done, root)
end)
end)
end
-- Extensions that are never the thing you want to run, even when the exec bit
-- happens to be set (build scripts, sources, libraries, notes).
local NOT_A_BINARY = {
c = true, cc = true, cpp = true, cxx = true, h = true, hpp = true, hh = true, hxx = true,
o = true, a = true, so = true, dylib = true, d = true, mk = true, cmake = true,
sh = true, bash = true, zsh = true, py = true, pl = true, txt = true, md = true,
json = true, yml = true, yaml = true, toml = true, log = true, ["in"] = true,
}
--- Executable files sitting in the project root β where a Makefile usually
--- drops its binary.
local function root_executables(root)
local out = {}
for name, kind in vim.fs.dir(root) do
local path = root .. "/" .. name
local ext = name:match("%.([%w+]+)$")
if kind == "file" and not NOT_A_BINARY[ext] and vim.fn.executable(path) == 1 then
out[#out + 1] = { name = name, path = path }
end
end
table.sort(out, function(a, b)
return a.name < b.name
end)
return out
end
---@param opts? { args?: string, stdin?: string }
function M.run_make(opts)
opts = opts or {}
local root = M.root()
local mk = makefile(root)
-- A `run:` rule is the project's own opinion about how to run β prefer it.
-- It owns the argv, so args/stdin can't be threaded through it.
if mk and has_target(mk, "run") then
if (opts.args and opts.args ~= "") or opts.stdin then
vim.notify("`make run` owns the command line β args/stdin ignored", vim.log.levels.WARN)
end
terminal({ "make", "-C", root, "run" }, { cwd = root, title = "make run" })
return
end
M.build_make(function()
local bins = root_executables(root)
if #bins == 0 then
vim.notify("Built, but no executable found in " .. root, vim.log.levels.WARN)
return
end
local function launch(bin)
terminal(launch_cmd(bin.path, opts.args, opts.stdin), {