-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathmaster_server.cpp
More file actions
2884 lines (2471 loc) · 112 KB
/
master_server.cpp
File metadata and controls
2884 lines (2471 loc) · 112 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
#include "server/master_server.h"
#include <algorithm>
#include <chrono>
#include <format>
#include <optional>
#include <string>
#include <type_traits>
#include <variant>
#include <vector>
#include "command/search_config.h"
#include "eventide/ipc/json_codec.h"
#include "eventide/ipc/lsp/position.h"
#include "eventide/ipc/lsp/protocol.h"
#include "eventide/ipc/lsp/uri.h"
#include "eventide/reflection/enum.h"
#include "eventide/serde/json/json.h"
#include "eventide/serde/serde/raw_value.h"
#include "index/tu_index.h"
#include "semantic/symbol_kind.h"
#include "server/protocol.h"
#include "support/filesystem.h"
#include "support/logging.h"
#include "syntax/dependency_graph.h"
#include "syntax/include_resolver.h"
#include "syntax/scan.h"
#include "llvm/Support/Chrono.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/xxhash.h"
namespace clice {
namespace protocol = eventide::ipc::protocol;
namespace lsp = eventide::ipc::lsp;
namespace refl = eventide::refl;
using et::ipc::RequestResult;
using RequestContext = et::ipc::JsonPeer::RequestContext;
/// Hash a file's content using xxh3_64bits. Returns 0 on read failure.
static std::uint64_t hash_file(llvm::StringRef path) {
auto buf = llvm::MemoryBuffer::getFile(path);
if(!buf)
return 0;
return llvm::xxh3_64bits((*buf)->getBuffer());
}
/// Capture a two-layer staleness snapshot after a successful compilation.
/// Interns dependency paths into the PathPool and hashes each file's content.
static DepsSnapshot capture_deps_snapshot(PathPool& pool, llvm::ArrayRef<std::string> deps) {
DepsSnapshot snap;
// Capture timestamp BEFORE hashing to avoid TOCTOU: if a file is modified
// during hashing, its mtime will be > build_at, triggering Layer 2 re-hash.
snap.build_at = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
snap.path_ids.reserve(deps.size());
snap.hashes.reserve(deps.size());
for(const auto& file: deps) {
snap.path_ids.push_back(pool.intern(file));
snap.hashes.push_back(hash_file(file));
}
return snap;
}
/// Two-layer staleness check.
///
/// Layer 1 (fast): stat each dep file, compare mtime against build_at.
/// If all mtimes <= build_at → nothing changed, return false immediately.
///
/// Layer 2 (precise): for files with mtime > build_at, re-hash their content.
/// If the hash matches the stored hash → file was touched but not modified.
/// If any hash differs → truly changed, return true.
static bool deps_changed(const PathPool& pool, const DepsSnapshot& snap) {
for(std::size_t i = 0; i < snap.path_ids.size(); ++i) {
auto path = pool.resolve(snap.path_ids[i]);
llvm::sys::fs::file_status status;
if(auto ec = llvm::sys::fs::status(path, status)) {
// File disappeared — definitely changed.
if(snap.hashes[i] != 0)
return true;
continue;
}
// Layer 1: mtime check (cheap, stat only).
auto current_mtime = llvm::sys::toTimeT(status.getLastModificationTime());
if(current_mtime <= snap.build_at)
continue;
// Layer 2: mtime is newer — re-hash content to confirm actual change.
auto current_hash = hash_file(path);
if(current_hash != snap.hashes[i])
return true;
}
return false;
}
MasterServer::MasterServer(et::event_loop& loop, et::ipc::JsonPeer& peer, std::string self_path) :
loop(loop), peer(peer), pool(loop), self_path(std::move(self_path)) {}
MasterServer::~MasterServer() {
if(compile_graph) {
compile_graph->cancel_all();
}
}
std::string MasterServer::uri_to_path(const std::string& uri) {
auto parsed = lsp::URI::parse(uri);
if(parsed.has_value()) {
auto path = parsed->file_path();
if(path.has_value()) {
return std::move(*path);
}
}
return uri;
}
void MasterServer::publish_diagnostics(const std::string& uri,
int version,
const et::serde::RawValue& diagnostics_json) {
std::vector<protocol::Diagnostic> diagnostics;
if(!diagnostics_json.empty()) {
auto status = et::serde::json::from_json(diagnostics_json.data, diagnostics);
if(!status) {
LOG_WARN("Failed to deserialize diagnostics JSON for {}", uri);
}
}
protocol::PublishDiagnosticsParams params;
params.uri = uri;
params.version = version;
params.diagnostics = std::move(diagnostics);
peer.send_notification(params);
}
void MasterServer::clear_diagnostics(const std::string& uri) {
protocol::PublishDiagnosticsParams params;
params.uri = uri;
params.diagnostics = {};
peer.send_notification(params);
}
/// Serializable cache structures for cache.json persistence.
/// Paths are stored in a shared table and referenced by index to avoid
/// redundant storage (a single file can depend on thousands of headers,
/// many of which are shared across entries).
namespace {
struct CacheDepEntry {
std::uint32_t path; // index into CacheData::paths
std::uint64_t hash;
};
struct CachePCHEntry {
std::string filename;
std::uint32_t source_file; // index into CacheData::paths
std::uint64_t hash;
std::uint32_t bound;
std::int64_t build_at;
std::vector<CacheDepEntry> deps;
};
struct CachePCMEntry {
std::string filename;
std::uint32_t source_file; // index into CacheData::paths
std::string module_name;
std::int64_t build_at;
std::vector<CacheDepEntry> deps;
};
struct CacheData {
std::vector<std::string> paths;
std::vector<CachePCHEntry> pch;
std::vector<CachePCMEntry> pcm;
};
} // namespace
void MasterServer::load_cache() {
if(config.cache_dir.empty())
return;
auto cache_path = path::join(config.cache_dir, "cache", "cache.json");
auto content = fs::read(cache_path);
if(!content) {
LOG_DEBUG("No cache.json found at {}", cache_path);
return;
}
CacheData data;
auto status = et::serde::json::from_json(*content, data);
if(!status) {
LOG_WARN("Failed to parse cache.json");
return;
}
auto resolve = [&](std::uint32_t idx) -> llvm::StringRef {
return idx < data.paths.size() ? llvm::StringRef(data.paths[idx]) : "";
};
for(auto& entry: data.pch) {
auto pch_path = path::join(config.cache_dir, "cache", "pch", entry.filename);
auto source = resolve(entry.source_file);
if(!llvm::sys::fs::exists(pch_path) || source.empty())
continue;
DepsSnapshot deps;
deps.build_at = entry.build_at;
for(auto& dep: entry.deps) {
auto dep_path = resolve(dep.path);
if(dep_path.empty())
continue;
deps.path_ids.push_back(path_pool.intern(dep_path));
deps.hashes.push_back(dep.hash);
}
auto path_id = path_pool.intern(source);
auto& st = pch_states[path_id];
st.path = pch_path;
st.hash = entry.hash;
st.bound = entry.bound;
st.deps = std::move(deps);
LOG_DEBUG("Loaded cached PCH: {} -> {}", source, pch_path);
}
for(auto& entry: data.pcm) {
auto pcm_path = path::join(config.cache_dir, "cache", "pcm", entry.filename);
auto source = resolve(entry.source_file);
if(!llvm::sys::fs::exists(pcm_path) || source.empty())
continue;
DepsSnapshot deps;
deps.build_at = entry.build_at;
for(auto& dep: entry.deps) {
auto dep_path = resolve(dep.path);
if(dep_path.empty())
continue;
deps.path_ids.push_back(path_pool.intern(dep_path));
deps.hashes.push_back(dep.hash);
}
auto path_id = path_pool.intern(source);
pcm_states[path_id] = {pcm_path, std::move(deps)};
pcm_paths[path_id] = pcm_path;
LOG_DEBUG("Loaded cached PCM: {} (module {}) -> {}", source, entry.module_name, pcm_path);
}
LOG_INFO("Loaded cache.json: {} PCH entries, {} PCM entries",
pch_states.size(),
pcm_states.size());
}
void MasterServer::save_cache() {
if(config.cache_dir.empty())
return;
CacheData data;
std::unordered_map<std::string, std::uint32_t> index_map;
auto intern = [&](std::uint32_t runtime_path_id) -> std::uint32_t {
auto path = std::string(path_pool.resolve(runtime_path_id));
auto [it, inserted] =
index_map.try_emplace(path, static_cast<std::uint32_t>(data.paths.size()));
if(inserted) {
data.paths.push_back(path);
}
return it->second;
};
for(auto& [path_id, st]: pch_states) {
if(st.path.empty())
continue;
CachePCHEntry entry;
entry.filename = std::string(path::filename(st.path));
entry.source_file = intern(path_id);
entry.hash = st.hash;
entry.bound = st.bound;
entry.build_at = st.deps.build_at;
for(std::size_t i = 0; i < st.deps.path_ids.size(); ++i) {
entry.deps.push_back({intern(st.deps.path_ids[i]), st.deps.hashes[i]});
}
data.pch.push_back(std::move(entry));
}
for(auto& [path_id, st]: pcm_states) {
if(st.path.empty())
continue;
CachePCMEntry entry;
entry.filename = std::string(path::filename(st.path));
entry.source_file = intern(path_id);
auto mod_it = path_to_module.find(path_id);
entry.module_name = mod_it != path_to_module.end() ? mod_it->second : "";
entry.build_at = st.deps.build_at;
for(std::size_t i = 0; i < st.deps.path_ids.size(); ++i) {
entry.deps.push_back({intern(st.deps.path_ids[i]), st.deps.hashes[i]});
}
data.pcm.push_back(std::move(entry));
}
auto json_str = et::serde::json::to_json(data);
if(!json_str) {
LOG_WARN("Failed to serialize cache.json");
return;
}
auto cache_path = path::join(config.cache_dir, "cache", "cache.json");
auto tmp_path = cache_path + ".tmp";
auto write_result = fs::write(tmp_path, *json_str);
if(!write_result) {
LOG_WARN("Failed to write cache.json.tmp: {}", write_result.error().message());
return;
}
auto rename_result = fs::rename(tmp_path, cache_path);
if(!rename_result) {
LOG_WARN("Failed to rename cache.json.tmp to cache.json: {}",
rename_result.error().message());
}
}
void MasterServer::cleanup_cache(int max_age_days) {
if(config.cache_dir.empty())
return;
auto now = std::chrono::system_clock::now();
auto max_age = std::chrono::hours(max_age_days * 24);
for(auto* subdir: {"cache/pch", "cache/pcm"}) {
auto dir = path::join(config.cache_dir, subdir);
std::error_code ec;
for(auto it = llvm::sys::fs::directory_iterator(dir, ec);
!ec && it != llvm::sys::fs::directory_iterator();
it.increment(ec)) {
llvm::sys::fs::file_status status;
if(auto stat_ec = llvm::sys::fs::status(it->path(), status))
continue;
auto mtime = status.getLastModificationTime();
auto age = now - mtime;
if(age > max_age) {
llvm::sys::fs::remove(it->path());
LOG_DEBUG("Cleaned up stale cache file: {}", it->path());
}
}
}
}
et::task<> MasterServer::load_workspace() {
if(workspace_root.empty())
co_return;
// Create cache directory if configured
if(!config.cache_dir.empty()) {
auto ec = llvm::sys::fs::create_directories(config.cache_dir);
if(ec) {
LOG_WARN("Failed to create cache directory {}: {}", config.cache_dir, ec.message());
} else {
LOG_INFO("Cache directory: {}", config.cache_dir);
}
// Create cache/pch/ and cache/pcm/ subdirectories
for(auto* subdir: {"cache/pch", "cache/pcm"}) {
auto dir = path::join(config.cache_dir, subdir);
auto ec2 = llvm::sys::fs::create_directories(dir);
if(ec2) {
LOG_WARN("Failed to create {}: {}", dir, ec2.message());
}
}
// Clean up stale files first, then load — load_cache() only restores
// entries still listed in cache.json, so cleanup won't delete live files.
cleanup_cache();
load_cache();
}
// Search for compile_commands.json
std::string cdb_path;
// If the config specifies a CDB path, use it
if(!config.compile_commands_path.empty()) {
if(llvm::sys::fs::exists(config.compile_commands_path)) {
cdb_path = config.compile_commands_path;
} else {
LOG_WARN("Configured compile_commands_path not found: {}",
config.compile_commands_path);
}
}
// Otherwise auto-detect in common locations
if(cdb_path.empty()) {
for(auto* subdir: {"build", "cmake-build-debug", "cmake-build-release", "out", "."}) {
auto candidate = path::join(workspace_root, subdir, "compile_commands.json");
if(llvm::sys::fs::exists(candidate)) {
cdb_path = std::move(candidate);
break;
}
}
}
if(cdb_path.empty()) {
LOG_WARN("No compile_commands.json found in workspace {}", workspace_root);
co_return;
}
auto count = cdb.load(cdb_path);
LOG_INFO("Loaded CDB from {} with {} entries", cdb_path, count);
auto report = scan_dependency_graph(cdb, path_pool, dependency_graph);
// Build reverse include map so headers can find their host source files.
dependency_graph.build_reverse_map();
auto unresolved = report.includes_found - report.includes_resolved;
double accuracy =
report.includes_found > 0
? 100.0 * static_cast<double>(report.includes_resolved) / report.includes_found
: 100.0;
LOG_INFO(
"Dependency scan: {}ms, {} files ({} source + {} header), " "{} edges, {}/{} resolved ({:.1f}%), {} waves",
report.elapsed_ms,
report.total_files,
report.source_files,
report.header_files,
report.total_edges,
report.includes_resolved,
report.includes_found,
accuracy,
report.waves);
if(unresolved > 0) {
LOG_WARN("{} unresolved includes", unresolved);
}
// Build reverse mapping: path_id -> module name.
for(auto& [module_name, path_ids]: dependency_graph.modules()) {
for(auto path_id: path_ids) {
path_to_module[path_id] = module_name.str();
}
}
// Load persisted index from disk.
load_index();
// Build index queue from CDB entries (all source files).
// CDB entries use the CDB's internal path_ids; convert to server path_ids.
if(config.enable_indexing) {
for(auto& entry: cdb.get_entries()) {
auto file = cdb.resolve_path(entry.file);
auto server_id = path_pool.intern(file);
index_queue.push_back(server_id);
}
if(!index_queue.empty()) {
LOG_INFO("Queued {} files for background indexing", index_queue.size());
schedule_indexing();
}
}
if(path_to_module.empty()) {
LOG_INFO("No C++20 modules detected, skipping CompileGraph");
co_return;
}
// Lazy dependency resolver: scans a module file on demand to discover imports.
auto resolve = [this](std::uint32_t path_id) -> llvm::SmallVector<std::uint32_t> {
auto file_path = path_pool.resolve(path_id);
auto results = cdb.lookup(file_path, {.query_toolchain = true, .suppress_logging = true});
if(results.empty()) {
return {};
}
auto& ctx = results[0];
auto scan_result = scan_precise(ctx.arguments, ctx.directory);
llvm::SmallVector<std::uint32_t> deps;
for(auto& mod_name: scan_result.modules) {
auto mod_ids = dependency_graph.lookup_module(mod_name);
if(!mod_ids.empty()) {
deps.push_back(mod_ids[0]);
}
}
// Module implementation units implicitly depend on their interface unit.
if(!scan_result.module_name.empty() && !scan_result.is_interface_unit) {
auto mod_ids = dependency_graph.lookup_module(scan_result.module_name);
if(!mod_ids.empty()) {
deps.push_back(mod_ids[0]);
}
}
return deps;
};
// Dispatch: sends BuildPCM request to a stateless worker.
auto dispatch = [this](std::uint32_t path_id) -> et::task<bool> {
auto mod_it = path_to_module.find(path_id);
if(mod_it == path_to_module.end()) {
co_return false;
}
auto file_path = std::string(path_pool.resolve(path_id));
worker::BuildPCMParams pcm_params;
pcm_params.file = file_path;
if(!fill_compile_args(file_path, pcm_params.directory, pcm_params.arguments)) {
co_return false;
}
// Compute deterministic content-addressed PCM path.
// Replace ':' with '-' in module name for filesystem safety.
// Hash includes file path AND compile arguments so that argument
// changes (e.g. -DFOO) invalidate the cached PCM.
auto safe_module_name = mod_it->second;
std::ranges::replace(safe_module_name, ':', '-');
std::string hash_input = file_path;
for(auto& arg: pcm_params.arguments) {
hash_input += arg;
}
auto args_hash = llvm::xxh3_64bits(llvm::StringRef(hash_input));
auto pcm_filename = std::format("{}-{:016x}.pcm", safe_module_name, args_hash);
auto pcm_path = path::join(config.cache_dir, "cache", "pcm", pcm_filename);
// Check if cached PCM is still valid.
if(auto pcm_it = pcm_states.find(path_id); pcm_it != pcm_states.end()) {
if(!pcm_it->second.path.empty() && llvm::sys::fs::exists(pcm_it->second.path) &&
!deps_changed(path_pool, pcm_it->second.deps)) {
pcm_paths[path_id] = pcm_it->second.path;
co_return true;
}
}
pcm_params.module_name = mod_it->second;
pcm_params.output_path = pcm_path;
// Clang needs ALL transitive PCM deps, not just direct imports.
for(auto& [pid, existing_pcm_path]: pcm_paths) {
auto dep_mod_it = path_to_module.find(pid);
if(dep_mod_it != path_to_module.end()) {
pcm_params.pcms[dep_mod_it->second] = existing_pcm_path;
}
}
auto result = co_await pool.send_stateless(pcm_params);
if(!result.has_value() || !result.value().success) {
LOG_WARN("BuildPCM failed for module {}: {}",
mod_it->second,
result.has_value() ? result.value().error : result.error().message);
co_return false;
}
pcm_paths[path_id] = result.value().pcm_path;
pcm_states[path_id] = {result.value().pcm_path,
capture_deps_snapshot(path_pool, result.value().deps)};
LOG_INFO("Built PCM for module {}: {}", mod_it->second, result.value().pcm_path);
// Persist cache metadata after successful build.
save_cache();
co_return true;
};
compile_graph = std::make_unique<CompileGraph>(std::move(dispatch), std::move(resolve));
LOG_INFO("CompileGraph initialized with {} module(s)", path_to_module.size());
}
std::optional<HeaderFileContext>
MasterServer::resolve_header_context(std::uint32_t header_path_id) {
// Find source files that transitively include this header.
auto hosts = dependency_graph.find_host_sources(header_path_id);
if(hosts.empty()) {
LOG_DEBUG("resolve_header_context: no host sources for path_id={}", header_path_id);
return std::nullopt;
}
// If there's an active context override, prefer that host.
std::uint32_t host_path_id = 0;
std::vector<std::uint32_t> chain;
auto active_it = active_contexts.find(header_path_id);
if(active_it != active_contexts.end()) {
auto preferred = active_it->second;
auto preferred_path = path_pool.resolve(preferred);
auto results = cdb.lookup(preferred_path, {.suppress_logging = true});
if(!results.empty()) {
auto c = dependency_graph.find_include_chain(preferred, header_path_id);
if(!c.empty()) {
host_path_id = preferred;
chain = std::move(c);
}
}
}
// Fall back to the first available host that has a CDB entry.
if(chain.empty()) {
for(auto candidate: hosts) {
auto candidate_path = path_pool.resolve(candidate);
auto results = cdb.lookup(candidate_path, {.suppress_logging = true});
if(results.empty())
continue;
auto c = dependency_graph.find_include_chain(candidate, header_path_id);
if(c.empty())
continue;
host_path_id = candidate;
chain = std::move(c);
break;
}
}
if(chain.empty()) {
LOG_DEBUG("resolve_header_context: no usable host with include chain for path_id={}",
header_path_id);
return std::nullopt;
}
// Build preamble text: for each file in the chain except the last (target),
// append all content up to (but not including) the line that includes the
// next file in the chain.
std::string preamble;
for(std::size_t i = 0; i + 1 < chain.size(); ++i) {
auto cur_id = chain[i];
auto next_id = chain[i + 1];
auto cur_path = path_pool.resolve(cur_id);
auto next_path = path_pool.resolve(next_id);
auto next_filename = llvm::sys::path::filename(next_path);
// Prefer in-memory document text over disk content.
std::string content;
if(auto doc_it = documents.find(cur_id); doc_it != documents.end()) {
content = doc_it->second.text;
} else {
auto buf = llvm::MemoryBuffer::getFile(cur_path);
if(!buf) {
LOG_WARN("resolve_header_context: cannot read {}", cur_path);
return std::nullopt;
}
content = (*buf)->getBuffer().str();
}
// Scan line by line for the #include that brings in next_filename.
llvm::StringRef content_ref(content);
std::size_t line_start = 0;
std::size_t include_line_start = std::string::npos;
while(line_start <= content_ref.size()) {
auto newline_pos = content_ref.find('\n', line_start);
auto line_end =
(newline_pos == llvm::StringRef::npos) ? content_ref.size() : newline_pos;
auto line = content_ref.slice(line_start, line_end).trim();
if(line.starts_with("#include") || line.starts_with("# include")) {
// Check if this line references the next file in the chain.
if(line.contains(next_filename)) {
include_line_start = line_start;
break;
}
}
line_start =
(newline_pos == llvm::StringRef::npos) ? content_ref.size() + 1 : newline_pos + 1;
}
// Emit a #line marker then all content before the include line.
preamble += std::format("#line 1 \"{}\"\n", cur_path.str());
if(include_line_start != std::string::npos) {
preamble += content_ref.substr(0, include_line_start).str();
} else {
// No matching include line found — emit the whole file to be safe.
LOG_DEBUG("resolve_header_context: include line for {} not found in {}, emitting full",
next_filename,
cur_path);
preamble += content;
}
}
// Hash the preamble and write to cache directory.
auto preamble_hash = llvm::xxh3_64bits(llvm::StringRef(preamble));
auto preamble_filename = std::format("{:016x}.h", preamble_hash);
auto preamble_dir = path::join(config.cache_dir, "header_context");
auto preamble_path = path::join(preamble_dir, preamble_filename);
if(!llvm::sys::fs::exists(preamble_path)) {
auto ec = llvm::sys::fs::create_directories(preamble_dir);
if(ec) {
LOG_WARN("resolve_header_context: cannot create dir {}: {}",
preamble_dir,
ec.message());
return std::nullopt;
}
if(auto result = fs::write(preamble_path, preamble); !result) {
LOG_WARN("resolve_header_context: cannot write preamble {}: {}",
preamble_path,
result.error().message());
return std::nullopt;
}
LOG_INFO("resolve_header_context: wrote preamble {} for header path_id={}",
preamble_path,
header_path_id);
}
return HeaderFileContext{host_path_id, preamble_path, preamble_hash};
}
bool MasterServer::fill_compile_args(llvm::StringRef path,
std::string& directory,
std::vector<std::string>& arguments) {
if(cdb.has_entry(path)) {
auto results = cdb.lookup(path, {.query_toolchain = true});
if(!results.empty()) {
auto& ctx = results.front();
directory = ctx.directory.str();
arguments.clear();
for(auto* arg: ctx.arguments) {
arguments.emplace_back(arg);
}
return true;
}
}
// No direct CDB entry — try to compile the header in context of a host source.
auto path_id = path_pool.intern(path);
// Use cached context if available; otherwise resolve.
// If an active context override exists, invalidate cache if it points to
// a different host so we re-resolve with the correct one.
const HeaderFileContext* ctx_ptr = nullptr;
auto ctx_it = header_file_contexts.find(path_id);
auto active_it = active_contexts.find(path_id);
if(ctx_it != header_file_contexts.end()) {
// Check if the cached context matches the active context override.
if(active_it != active_contexts.end() && ctx_it->second.host_path_id != active_it->second) {
header_file_contexts.erase(ctx_it);
ctx_it = header_file_contexts.end();
} else {
ctx_ptr = &ctx_it->second;
}
}
if(!ctx_ptr) {
auto resolved = resolve_header_context(path_id);
if(!resolved) {
LOG_WARN("No CDB entry and no header context for {}", path);
return false;
}
header_file_contexts[path_id] = std::move(*resolved);
ctx_ptr = &header_file_contexts[path_id];
}
auto host_path = path_pool.resolve(ctx_ptr->host_path_id);
auto host_results = cdb.lookup(host_path, {.query_toolchain = true});
if(host_results.empty()) {
LOG_WARN("fill_compile_args: host {} has no CDB entry", host_path);
return false;
}
auto& host_ctx = host_results.front();
directory = host_ctx.directory.str();
arguments.clear();
// Copy host arguments, replacing the source file path (last non-flag arg)
// with the header file path, so the compiler processes the header in context.
auto num_args = host_ctx.arguments.size();
std::size_t copy_count = num_args;
if(copy_count > 0) {
llvm::StringRef last(host_ctx.arguments[copy_count - 1]);
if(!last.starts_with("-"))
copy_count -= 1;
}
for(std::size_t i = 0; i < copy_count; ++i) {
arguments.emplace_back(host_ctx.arguments[i]);
}
// Append the header file path as the source file.
arguments.emplace_back(path);
// Inject the preamble so the compiler sees all context code that normally
// precedes this header in the host translation unit.
// For cc1 args (["clang++", "-cc1", ...]), insert after "-cc1" at position 2.
// For driver args, insert after the driver binary at position 1.
std::size_t inject_pos = 1;
if(arguments.size() >= 2 && arguments[1] == "-cc1") {
inject_pos = 2;
}
arguments.insert(arguments.begin() + inject_pos, ctx_ptr->preamble_path);
arguments.insert(arguments.begin() + inject_pos, "-include");
LOG_INFO("fill_compile_args: using header context for {} (host={}, preamble={})",
path,
host_path,
ctx_ptr->preamble_path);
return true;
}
et::task<bool> MasterServer::ensure_pch(std::uint32_t path_id,
llvm::StringRef path,
const std::string& text,
const std::string& directory,
const std::vector<std::string>& arguments) {
auto bound = compute_preamble_bound(text);
if(bound == 0) {
// No preamble directives — PCH would be empty. Clear any stale entry.
pch_states.erase(path_id);
co_return true;
}
auto preamble_hash = llvm::xxh3_64bits(llvm::StringRef(text).substr(0, bound));
// Deterministic content-addressed PCH path.
auto pch_path =
path::join(config.cache_dir, "cache", "pch", std::format("{:016x}.pch", preamble_hash));
// Reuse existing PCH if preamble content and deps haven't changed.
if(auto it = pch_states.find(path_id); it != pch_states.end()) {
auto& st = it->second;
if(st.hash == preamble_hash && !st.path.empty() && !deps_changed(path_pool, st.deps)) {
st.bound = bound;
co_return true;
}
}
// Preamble incomplete (user still typing) — defer rebuild, reuse old PCH if available.
if(!is_preamble_complete(text, bound)) {
LOG_DEBUG("Preamble incomplete for {}, deferring PCH rebuild", path);
co_return pch_states.count(path_id) && !pch_states[path_id].path.empty();
}
// If another coroutine is already building PCH for this file, wait for it.
if(auto it = pch_states.find(path_id); it != pch_states.end() && it->second.building) {
co_await it->second.building->wait();
co_return !pch_states[path_id].path.empty();
}
// Register in-flight build so concurrent requests wait on us.
auto completion = std::make_shared<et::event>();
pch_states[path_id].building = completion;
// Build a new PCH via stateless worker.
worker::BuildPCHParams pch_params;
pch_params.file = std::string(path);
pch_params.directory = directory;
pch_params.arguments = arguments;
pch_params.content = text;
pch_params.preamble_bound = bound;
pch_params.output_path = pch_path;
LOG_DEBUG("Building PCH for {}, bound={}, output={}", path, bound, pch_path);
auto result = co_await pool.send_stateless(pch_params);
if(!result.has_value() || !result.value().success) {
LOG_WARN("PCH build failed for {}: {}",
path,
result.has_value() ? result.value().error : result.error().message);
pch_states[path_id].building.reset();
completion->set();
co_return false;
}
// Update state — no need to delete old file; content-addressed names differ
// when content differs, and the 7-day cleanup handles orphaned files.
auto& st = pch_states[path_id];
st.path = result.value().pch_path;
st.bound = bound;
st.hash = preamble_hash;
st.deps = capture_deps_snapshot(path_pool, result.value().deps);
st.building.reset();
LOG_INFO("PCH built for {}: {}", path, result.value().pch_path);
// Persist cache metadata after successful build.
save_cache();
completion->set();
co_return true;
}
/// Compile module dependencies, build/reuse PCH, and fill PCM paths.
/// Shared preparation step used by both ensure_compiled() (stateful path)
/// and forward_stateless() (completion/signatureHelp path).
et::task<bool> MasterServer::ensure_deps(std::uint32_t path_id,
llvm::StringRef path,
const std::string& text,
const std::string& directory,
const std::vector<std::string>& arguments,
std::pair<std::string, uint32_t>& pch,
std::unordered_map<std::string, std::string>& pcms) {
// Compile C++20 module dependencies (PCMs).
if(compile_graph && !co_await compile_graph->compile_deps(path_id)) {
co_return false;
}
// Scan buffer text for module imports that might not be in compile_graph yet.
// When a user adds `import std;` without saving, the compile_graph (disk-based)
// doesn't know about the new dependency. Scan the in-memory text to find them.
{
auto scan_result = scan(text);
for(auto& mod_name: scan_result.modules) {
if(mod_name.empty()) {
continue;
}
bool found = false;
for(auto& [pid, name]: path_to_module) {
if(name == mod_name) {
// If PCM not already built, try to build it.
if(pcm_paths.find(pid) == pcm_paths.end()) {
if(compile_graph && compile_graph->has_unit(pid)) {
co_await compile_graph->compile_deps(pid);
}
}
found = true;
break;
}
}
if(!found) {
LOG_DEBUG("Buffer imports unknown module '{}', skipping", mod_name);
}
}
}
// Build or reuse PCH.
auto pch_ok = co_await ensure_pch(path_id, path, text, directory, arguments);
if(pch_ok) {
if(auto pch_it = pch_states.find(path_id); pch_it != pch_states.end()) {
pch = {pch_it->second.path, pch_it->second.bound};
}
}
// Fill all available PCM paths so clang can resolve transitive imports.
// Exclude the file's own PCM to avoid "multiple module declarations".
for(auto& [pid, pcm_path]: pcm_paths) {
if(pid == path_id)
continue;
auto mod_it = path_to_module.find(pid);
if(mod_it != path_to_module.end()) {
pcms[mod_it->second] = pcm_path;
}
}
co_return true;
}
/// Pull-based compilation entry point for user-opened files.
///
/// Called lazily by forward_stateful() / forward_stateless() before every
/// feature request (hover, semantic tokens, etc.). Guarantees that when it
/// returns true the stateful worker assigned to `path_id` holds an up-to-date
/// AST and diagnostics have been published to the client.
///
/// Lifecycle overview (pull-based model):
///
/// didOpen / didChange – only update DocumentState, mark ast_dirty
/// didSave – mark dependents dirty, queue indexing
/// feature request arrives – calls ensure_compiled() first
/// 1. Fast-path exit if AST is already clean (!ast_dirty).
/// 2. Compile any C++20 module dependencies (PCMs) via CompileGraph.
/// 3. Build / reuse the precompiled header (PCH) via ensure_pch().
/// 4. Send CompileParams to the stateful worker, which builds the AST.
/// 5. On success: publish diagnostics, clear ast_dirty, schedule indexing.
/// 6. On generation mismatch (user edited during compile): keep dirty,
/// the next feature request will trigger another compile cycle.
///
/// Only the opened file itself is remapped (its in-memory text is sent to the
/// worker); every other file is read from disk by the compiler.
///
/// Concurrency: multiple concurrent feature requests for the same file will
/// each call ensure_compiled(). The first one launches a detached compile
/// task via loop.schedule(); subsequent ones wait on the shared event.
/// The detached task cannot be cancelled by LSP $/cancelRequest, preventing
/// the race where cancellation wakes all waiters and they all start compiles.
et::task<bool> MasterServer::ensure_compiled(std::uint32_t path_id) {
auto it = documents.find(path_id);
if(it == documents.end()) {
LOG_WARN("ensure_compiled: doc not found for path_id={} path={}",
path_id,
path_pool.resolve(path_id));
co_return false;
}
auto& doc = it->second;
LOG_DEBUG("ensure_compiled: path_id={} version={} gen={} ast_dirty={}",
path_id,
doc.version,
doc.generation,
doc.ast_dirty);
if(!doc.ast_dirty) {
bool changed = false;
auto ast_deps_it = ast_deps.find(path_id);
if(ast_deps_it != ast_deps.end() && deps_changed(path_pool, ast_deps_it->second)) {
changed = true;
}
if(!changed) {
auto pch_it = pch_states.find(path_id);
if(pch_it != pch_states.end() && deps_changed(path_pool, pch_it->second.deps)) {
changed = true;
}
}
if(!changed) {
co_return true;
}
doc.ast_dirty = true;
}