code-moniker-workspace 0.5.0

Workspace model, ports, snapshots, linkage, and change analysis for code-moniker.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use super::records::RecordTable;

#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct ResourceGeneration(u64);

impl ResourceGeneration {
	pub fn new(value: u64) -> Self {
		Self(value)
	}

	pub fn value(self) -> u64 {
		self.0
	}
}

#[derive(Clone, Debug)]
pub struct WorkspaceRequest {
	pub label: String,
	pub catalog: CatalogRequest,
	cancellation: WorkspaceCancellation,
}

impl PartialEq for WorkspaceRequest {
	fn eq(&self, other: &Self) -> bool {
		self.label == other.label && self.catalog == other.catalog
	}
}

impl Eq for WorkspaceRequest {}

#[derive(Clone, Debug, Default)]
pub struct WorkspaceCancellation(Arc<AtomicBool>);

impl WorkspaceCancellation {
	pub fn cancel(&self) {
		self.0.store(true, Ordering::Release);
	}

	pub fn is_cancelled(&self) -> bool {
		self.0.load(Ordering::Acquire)
	}

	pub fn check(&self, resource: WorkspaceResource) -> WorkspaceResult<()> {
		if self.is_cancelled() {
			return Err(WorkspaceFailure::new(resource, "workspace build cancelled"));
		}
		Ok(())
	}
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CatalogRequest {
	Refresh,
	ReuseCurrent,
}

impl WorkspaceRequest {
	pub fn new(label: impl Into<String>) -> Self {
		Self {
			label: label.into(),
			catalog: CatalogRequest::Refresh,
			cancellation: WorkspaceCancellation::default(),
		}
	}

	pub fn with_cancellation(mut self, cancellation: WorkspaceCancellation) -> Self {
		self.cancellation = cancellation;
		self
	}

	pub fn cancellation(&self) -> &WorkspaceCancellation {
		&self.cancellation
	}

	pub fn reuse_current_catalog(mut self) -> Self {
		self.catalog = CatalogRequest::ReuseCurrent;
		self
	}

	pub fn should_reuse_current_catalog(&self) -> bool {
		self.catalog == CatalogRequest::ReuseCurrent
	}
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct SourceId {
	file: u32,
}

impl SourceId {
	pub fn at(file: usize) -> Self {
		Self { file: file as u32 }
	}

	pub fn parse(value: &str) -> Option<Self> {
		let rest = value.strip_prefix("source:")?;
		let file = rest.split(':').next()?;
		Some(Self {
			file: file.parse().ok()?,
		})
	}

	pub fn file(self) -> usize {
		self.file as usize
	}
}

impl std::fmt::Display for SourceId {
	fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(formatter, "source:{}", self.file)
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SourceUnit {
	pub id: SourceId,
	pub display_name: String,
	pub language: Option<String>,
}

impl SourceUnit {
	pub fn new(id: SourceId, display_name: impl Into<String>) -> Self {
		Self {
			id,
			display_name: display_name.into(),
			language: None,
		}
	}

	pub fn with_language(
		id: SourceId,
		display_name: impl Into<String>,
		language: impl Into<String>,
	) -> Self {
		Self {
			id,
			display_name: display_name.into(),
			language: Some(language.into()),
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SourceCatalog {
	pub generation: ResourceGeneration,
	pub sources: Vec<SourceUnit>,
}

impl SourceCatalog {
	pub fn new(generation: ResourceGeneration, mut sources: Vec<SourceUnit>) -> Self {
		sources.shrink_to_fit();
		Self {
			generation,
			sources,
		}
	}
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct SymbolId {
	file: u32,
	def: u32,
}

impl SymbolId {
	pub fn at(file: usize, def: usize) -> Self {
		Self {
			file: file as u32,
			def: def as u32,
		}
	}

	pub fn parse(value: &str) -> Option<Self> {
		let rest = value.strip_prefix("symbol:")?;
		let (file, def) = rest.split_once(':')?;
		Some(Self {
			file: file.parse().ok()?,
			def: def.parse().ok()?,
		})
	}

	pub fn file(self) -> usize {
		self.file as usize
	}

	pub fn def(self) -> usize {
		self.def as usize
	}
}

impl std::fmt::Display for SymbolId {
	fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(formatter, "symbol:{}:{}", self.file, self.def)
	}
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct SymbolLocation {
	pub file: usize,
	pub symbol: usize,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SymbolRecord {
	pub id: SymbolId,
	pub source: SourceId,
	pub identity: Arc<str>,
	pub name: String,
	pub kind: String,
	pub visibility: String,
	pub signature: String,
	pub call_name: Option<String>,
	pub call_arity: Option<usize>,
	pub navigable: bool,
	pub line_range: Option<(u32, u32)>,
	pub parent: Option<SymbolId>,
}

impl SymbolRecord {
	pub fn new(
		id: SymbolId,
		source: SourceId,
		name: impl Into<String>,
		kind: impl Into<String>,
	) -> Self {
		Self {
			identity: Arc::from(id.to_string()),
			id,
			source,
			name: name.into(),
			kind: kind.into(),
			visibility: String::new(),
			signature: String::new(),
			call_name: None,
			call_arity: None,
			navigable: true,
			line_range: None,
			parent: None,
		}
	}
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct ReferenceId {
	file: u32,
	reference: u32,
}

impl ReferenceId {
	pub fn at(file: usize, reference: usize) -> Self {
		Self {
			file: file as u32,
			reference: reference as u32,
		}
	}

	pub fn parse(value: &str) -> Option<Self> {
		let rest = value.strip_prefix("reference:")?;
		let (file, reference) = rest.split_once(':')?;
		Some(Self {
			file: file.parse().ok()?,
			reference: reference.parse().ok()?,
		})
	}

	pub fn file(self) -> usize {
		self.file as usize
	}

	pub fn reference(self) -> usize {
		self.reference as usize
	}
}

impl std::fmt::Display for ReferenceId {
	fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(formatter, "reference:{}:{}", self.file, self.reference)
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ReferenceRecord {
	pub id: ReferenceId,
	pub source: SourceId,
	pub source_symbol: SymbolId,
	pub target_identity: Arc<str>,
	pub kind: String,
	pub call_name: Option<String>,
	pub call_arity: Option<usize>,
	pub confidence: Option<String>,
	pub receiver: Option<String>,
	pub alias: Option<String>,
	pub line_range: Option<(u32, u32)>,
}

impl ReferenceRecord {
	pub fn new(
		id: ReferenceId,
		source: SourceId,
		source_symbol: SymbolId,
		target_identity: impl Into<Arc<str>>,
		kind: impl Into<String>,
		line_range: Option<(u32, u32)>,
	) -> Self {
		Self {
			id,
			source,
			source_symbol,
			target_identity: target_identity.into(),
			kind: kind.into(),
			call_name: None,
			call_arity: None,
			confidence: None,
			receiver: None,
			alias: None,
			line_range,
		}
	}

	pub fn with_call_metadata(
		mut self,
		call_name: Option<String>,
		call_arity: Option<usize>,
	) -> Self {
		self.call_name = call_name;
		self.call_arity = call_arity;
		self
	}

	pub fn with_metadata(
		mut self,
		confidence: Option<String>,
		receiver: Option<String>,
		alias: Option<String>,
	) -> Self {
		self.confidence = confidence;
		self.receiver = receiver;
		self.alias = alias;
		self
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SourceFileRecord {
	pub id: SourceId,
	pub uri: String,
	pub source_root: usize,
	pub path: String,
	pub rel_path: String,
	pub anchor: String,
	pub language: String,
	pub text: String,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CodeIndex {
	pub generation: ResourceGeneration,
	pub catalog_generation: ResourceGeneration,
	pub identity_scheme: String,
	pub sources: Vec<SourceFileRecord>,
	pub symbols: RecordTable<SymbolRecord>,
	pub references: RecordTable<ReferenceRecord>,
	pub timings: CodeIndexTimings,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct CodeIndexTimings {
	pub extract_sources: Duration,
	pub semantic_index: Duration,
	pub total: Duration,
}

impl CodeIndex {
	pub fn new(
		generation: ResourceGeneration,
		catalog_generation: ResourceGeneration,
		symbols: Vec<SymbolRecord>,
	) -> Self {
		Self::with_references(generation, catalog_generation, symbols, Vec::new())
	}

	pub fn with_references(
		generation: ResourceGeneration,
		catalog_generation: ResourceGeneration,
		symbols: Vec<SymbolRecord>,
		references: Vec<ReferenceRecord>,
	) -> Self {
		Self {
			generation,
			catalog_generation,
			identity_scheme: crate::DEFAULT_IDENTITY_SCHEME.to_string(),
			sources: Vec::new(),
			symbols: RecordTable::from_records(symbols),
			references: RecordTable::from_records(references),
			timings: CodeIndexTimings::default(),
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LinkageEdge {
	pub reference: ReferenceId,
	pub target: SymbolId,
	pub evidence: ResolutionEvidence,
}

impl LinkageEdge {
	pub fn new(reference: ReferenceId, target: SymbolId) -> Self {
		Self::with_evidence(reference, target, ResolutionEvidence::ExactBinding)
	}

	pub fn with_evidence(
		reference: ReferenceId,
		target: SymbolId,
		evidence: ResolutionEvidence,
	) -> Self {
		Self {
			reference,
			target,
			evidence,
		}
	}
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ResolutionEvidence {
	ExactBinding,
	LocalBinding,
	GlobalBinding,
	TypeConstraint,
	Mro,
	Injected,
	NameMatch,
}

impl ResolutionEvidence {
	pub fn as_str(self) -> &'static str {
		match self {
			Self::ExactBinding => "exact_binding",
			Self::LocalBinding => "local_binding",
			Self::GlobalBinding => "global_binding",
			Self::TypeConstraint => "type_constraint",
			Self::Mro => "mro",
			Self::Injected => "injected",
			Self::NameMatch => "name_match",
		}
	}

	pub fn rank(self) -> u8 {
		match self {
			Self::ExactBinding => 100,
			Self::LocalBinding | Self::TypeConstraint => 90,
			Self::Mro => 85,
			Self::GlobalBinding | Self::Injected => 80,
			Self::NameMatch => 10,
		}
	}
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CandidateReason {
	WeakNameMatch,
	MultipleTargets,
	AmbiguousLookup,
}

impl CandidateReason {
	pub fn as_str(self) -> &'static str {
		match self {
			Self::WeakNameMatch => "weak_name_match",
			Self::MultipleTargets => "multiple_targets",
			Self::AmbiguousLookup => "ambiguous_lookup",
		}
	}
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CandidateScope {
	Local,
	Global,
	Builtin,
	Injected,
	Unknown,
}

impl CandidateScope {
	pub fn as_str(self) -> &'static str {
		match self {
			Self::Local => "local",
			Self::Global => "global",
			Self::Builtin => "builtin",
			Self::Injected => "injected",
			Self::Unknown => "unknown",
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CandidateReference {
	pub reference: ReferenceId,
	pub targets: Vec<SymbolId>,
	pub reason: CandidateReason,
	pub scope: CandidateScope,
	pub evidence: ResolutionEvidence,
}

impl CandidateReference {
	pub fn new(
		reference: ReferenceId,
		targets: Vec<SymbolId>,
		reason: CandidateReason,
		scope: CandidateScope,
		evidence: ResolutionEvidence,
	) -> Self {
		Self {
			reference,
			targets,
			reason,
			scope,
			evidence,
		}
	}
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DynamicReason {
	DynamicAttribute,
	DescriptorOrFrameworkInjected,
	DuckTypedCandidateSet,
	MixinContract,
	ExternalDependencyUnindexed,
	RuntimeImport,
	RuntimeMutation,
	PreprocessorExpansion,
	InsufficientLocalFacts,
}

impl DynamicReason {
	pub fn as_str(self) -> &'static str {
		match self {
			Self::DynamicAttribute => "dynamic_attribute",
			Self::DescriptorOrFrameworkInjected => "descriptor_or_framework_injected",
			Self::DuckTypedCandidateSet => "duck_typed_candidate_set",
			Self::MixinContract => "mixin_contract",
			Self::ExternalDependencyUnindexed => "external_dependency_unindexed",
			Self::RuntimeImport => "runtime_import",
			Self::RuntimeMutation => "runtime_mutation",
			Self::PreprocessorExpansion => "preprocessor_expansion",
			Self::InsufficientLocalFacts => "insufficient_local_facts",
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DynamicReference {
	pub reference: ReferenceId,
	pub target_identity: Arc<str>,
	pub reason: DynamicReason,
	pub candidates: Vec<SymbolId>,
}

impl DynamicReference {
	pub fn new(
		reference: ReferenceId,
		target_identity: impl Into<Arc<str>>,
		reason: DynamicReason,
		candidates: Vec<SymbolId>,
	) -> Self {
		Self {
			reference,
			target_identity: target_identity.into(),
			reason,
			candidates,
		}
	}
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ExternalReferenceOrigin {
	Sdk,
	Dependency,
	Injected,
	UnknownExternal,
}

impl ExternalReferenceOrigin {
	pub fn label(self) -> &'static str {
		match self {
			Self::Sdk => "sdk",
			Self::Dependency => "dependency",
			Self::Injected => "injected",
			Self::UnknownExternal => "unknown_external",
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ExternalReference {
	pub reference: ReferenceId,
	pub target_identity: Arc<str>,
	pub origin: ExternalReferenceOrigin,
}

impl ExternalReference {
	pub fn new(
		reference: ReferenceId,
		target_identity: impl Into<Arc<str>>,
		origin: ExternalReferenceOrigin,
	) -> Self {
		Self {
			reference,
			target_identity: target_identity.into(),
			origin,
		}
	}
}

/// Why linkage could not bind a reference. The taxonomy is part of the
/// resolution contract: consumers can split external-by-design from real
/// resolution gaps instead of reading one opaque count.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum UnresolvedReason {
	ManifestBlocked,
	Visibility,
	LanguageBoundary,
	MissingQuery,
	NoCandidate,
	Ambiguous,
	UnsupportedLanguageRule,
	IncompleteExtractorMetadata,
}

impl UnresolvedReason {
	pub fn as_str(&self) -> &'static str {
		match self {
			Self::ManifestBlocked => "manifest_blocked",
			Self::Visibility => "visibility",
			Self::LanguageBoundary => "language_boundary",
			Self::MissingQuery => "missing_query",
			Self::NoCandidate => "no_candidate",
			Self::Ambiguous => "ambiguous",
			Self::UnsupportedLanguageRule => "unsupported_language_rule",
			Self::IncompleteExtractorMetadata => "incomplete_extractor_metadata",
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UnresolvedReference {
	pub reference: ReferenceId,
	pub target_identity: Arc<str>,
	pub reason: UnresolvedReason,
}

impl UnresolvedReference {
	pub fn new(
		reference: ReferenceId,
		target_identity: impl Into<Arc<str>>,
		reason: UnresolvedReason,
	) -> Self {
		Self {
			reference,
			target_identity: target_identity.into(),
			reason,
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LinkageSnapshot {
	pub generation: ResourceGeneration,
	pub index_generation: ResourceGeneration,
	pub resolved_refs: usize,
	pub candidate_refs: usize,
	pub external_refs: usize,
	pub dynamic_refs: usize,
	pub blocked_refs: usize,
	/// Compatibility counter for manifest-policy blocks.
	pub manifest_blocked_refs: usize,
	pub unresolved_refs: usize,
	/// Compatibility counter for existing consumers. Candidate references are
	/// now stored separately and never projected as graph edges.
	pub ambiguous_refs: usize,
	pub resolved: Vec<LinkageEdge>,
	pub candidates: Vec<CandidateReference>,
	pub external: Vec<ExternalReference>,
	pub dynamic: Vec<DynamicReference>,
	pub blocked: Vec<UnresolvedReference>,
	/// Compatibility view containing only `ManifestBlocked` entries.
	pub manifest_blocked: Vec<UnresolvedReference>,
	pub unresolved: Vec<UnresolvedReference>,
	pub read_index: LinkageReadIndexHandle,
}

#[derive(Debug)]
pub struct LinkageReadIndex {
	pub(crate) incoming: rustc_hash::FxHashMap<SymbolId, Vec<ReferenceId>>,
	pub(crate) targets: rustc_hash::FxHashMap<ReferenceId, SymbolId>,
}

impl LinkageReadIndex {
	pub fn from_edges(edges: &[LinkageEdge]) -> Self {
		let mut incoming = rustc_hash::FxHashMap::<SymbolId, Vec<ReferenceId>>::default();
		let mut targets = rustc_hash::FxHashMap::<ReferenceId, SymbolId>::default();
		for edge in edges {
			let LinkageEdge {
				reference, target, ..
			} = edge.clone();
			targets.entry(reference).or_insert(target);
			incoming.entry(target).or_default().push(reference);
		}
		Self { incoming, targets }
	}

	pub fn incoming(&self, symbol: &SymbolId) -> &[ReferenceId] {
		self.incoming.get(symbol).map(Vec::as_slice).unwrap_or(&[])
	}

	pub fn resolved_target(&self, reference: &ReferenceId) -> Option<&SymbolId> {
		self.targets.get(reference)
	}
}

#[derive(Clone, Debug, Default)]
pub struct LinkageReadIndexHandle(Option<Arc<LinkageReadIndex>>);

impl LinkageReadIndexHandle {
	pub fn from_edges(edges: &[LinkageEdge]) -> Self {
		Self(Some(Arc::new(LinkageReadIndex::from_edges(edges))))
	}

	pub fn get(&self) -> Option<&LinkageReadIndex> {
		self.0.as_deref()
	}
}

impl PartialEq for LinkageReadIndexHandle {
	fn eq(&self, _other: &Self) -> bool {
		true
	}
}

impl Eq for LinkageReadIndexHandle {}

impl LinkageSnapshot {
	pub fn new(
		generation: ResourceGeneration,
		index_generation: ResourceGeneration,
		resolved_refs: usize,
		unresolved_refs: usize,
	) -> Self {
		Self {
			generation,
			index_generation,
			resolved_refs,
			candidate_refs: 0,
			external_refs: 0,
			dynamic_refs: 0,
			blocked_refs: 0,
			manifest_blocked_refs: 0,
			unresolved_refs,
			ambiguous_refs: 0,
			resolved: Vec::new(),
			candidates: Vec::new(),
			external: Vec::new(),
			dynamic: Vec::new(),
			blocked: Vec::new(),
			manifest_blocked: Vec::new(),
			unresolved: Vec::new(),
			read_index: LinkageReadIndexHandle::default(),
		}
	}

	pub fn with_refs(
		generation: ResourceGeneration,
		index_generation: ResourceGeneration,
		mut resolved: Vec<LinkageEdge>,
		mut unresolved: Vec<UnresolvedReference>,
	) -> Self {
		resolved.shrink_to_fit();
		unresolved.shrink_to_fit();
		let read_index = LinkageReadIndexHandle::from_edges(&resolved);
		Self {
			generation,
			index_generation,
			resolved_refs: resolved.len(),
			candidate_refs: 0,
			external_refs: 0,
			dynamic_refs: 0,
			blocked_refs: 0,
			manifest_blocked_refs: 0,
			unresolved_refs: unresolved.len(),
			ambiguous_refs: 0,
			resolved,
			candidates: Vec::new(),
			external: Vec::new(),
			dynamic: Vec::new(),
			blocked: Vec::new(),
			manifest_blocked: Vec::new(),
			unresolved,
			read_index,
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ChangeOverlay {
	pub generation: ResourceGeneration,
	pub catalog_generation: ResourceGeneration,
	pub index_generation: ResourceGeneration,
	pub scope: String,
	pub resources: Vec<ChangeResource>,
	pub diagnostics: Vec<String>,
	pub changed_symbols: Vec<SymbolId>,
	pub changes: Vec<ChangeRecord>,
	pub semantic: Option<std::sync::Arc<crate::changes::semantic::review::SemanticReview>>,
}

pub struct ChangeOverlayReport {
	pub generation: ResourceGeneration,
	pub catalog_generation: ResourceGeneration,
	pub index_generation: ResourceGeneration,
	pub scope: String,
	pub resources: Vec<ChangeResource>,
	pub diagnostics: Vec<String>,
	pub changes: Vec<ChangeRecord>,
}

impl ChangeOverlay {
	pub fn new(
		generation: ResourceGeneration,
		catalog_generation: ResourceGeneration,
		index_generation: ResourceGeneration,
		mut changed_symbols: Vec<SymbolId>,
	) -> Self {
		changed_symbols.shrink_to_fit();
		Self {
			generation,
			catalog_generation,
			index_generation,
			scope: "HEAD..worktree".to_string(),
			resources: Vec::new(),
			diagnostics: Vec::new(),
			changed_symbols,
			changes: Vec::new(),
			semantic: None,
		}
	}

	pub fn with_records(
		generation: ResourceGeneration,
		catalog_generation: ResourceGeneration,
		index_generation: ResourceGeneration,
		mut changes: Vec<ChangeRecord>,
	) -> Self {
		changes.shrink_to_fit();
		let changed_symbols = changes.iter().filter_map(|change| change.symbol).fold(
			Vec::new(),
			|mut out, symbol| {
				if !out.contains(&symbol) {
					out.push(symbol);
				}
				out
			},
		);
		let mut changed_symbols = changed_symbols;
		changed_symbols.shrink_to_fit();
		Self {
			generation,
			catalog_generation,
			index_generation,
			scope: "HEAD..worktree".to_string(),
			resources: Vec::new(),
			diagnostics: Vec::new(),
			changed_symbols,
			changes,
			semantic: None,
		}
	}

	pub fn from_report(report: ChangeOverlayReport) -> Self {
		let mut resources = report.resources;
		let mut diagnostics = report.diagnostics;
		resources.shrink_to_fit();
		diagnostics.shrink_to_fit();
		let mut overlay = Self::with_records(
			report.generation,
			report.catalog_generation,
			report.index_generation,
			report.changes,
		);
		overlay.scope = report.scope;
		overlay.resources = resources;
		overlay.diagnostics = diagnostics;
		overlay
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ChangeResource {
	pub available: bool,
	pub label: String,
	pub message: String,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ChangeStatus {
	Added,
	Modified,
	Removed,
}

impl ChangeStatus {
	pub fn label(self) -> &'static str {
		match self {
			Self::Added => "added",
			Self::Modified => "modified",
			Self::Removed => "removed",
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct ChangeId(String);

impl ChangeId {
	pub fn new(value: impl Into<String>) -> Self {
		Self(value.into())
	}

	pub fn as_str(&self) -> &str {
		&self.0
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ChangeRecord {
	pub id: ChangeId,
	pub status: ChangeStatus,
	pub source: Option<SourceId>,
	pub source_uri: Option<String>,
	pub symbol: Option<SymbolId>,
	pub identity: String,
	pub language: String,
	pub file_path: String,
	pub name: String,
	pub kind: String,
	pub line_range: Option<(u32, u32)>,
	pub hunk_count: usize,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ChangeRecordCoreFields {
	pub id: ChangeId,
	pub status: ChangeStatus,
	pub identity: String,
	pub language: String,
	pub file_path: String,
	pub name: String,
	pub kind: String,
	pub line_range: Option<(u32, u32)>,
	pub hunk_count: usize,
}

impl ChangeRecord {
	pub fn new(fields: ChangeRecordCoreFields) -> Self {
		Self {
			id: fields.id,
			status: fields.status,
			source: None,
			source_uri: None,
			symbol: None,
			identity: fields.identity,
			language: fields.language,
			file_path: fields.file_path,
			name: fields.name,
			kind: fields.kind,
			line_range: fields.line_range,
			hunk_count: fields.hunk_count,
		}
	}

	pub fn with_source(mut self, source: SourceId, source_uri: impl Into<String>) -> Self {
		self.source = Some(source);
		self.source_uri = Some(source_uri.into());
		self
	}

	pub fn with_symbol(mut self, symbol: SymbolId) -> Self {
		self.symbol = Some(symbol);
		self
	}
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkspaceSnapshot {
	pub generation: ResourceGeneration,
	pub catalog: SourceCatalog,
	pub index: CodeIndex,
	pub linkage: LinkageSnapshot,
	pub changes: ChangeOverlay,
	pub timings: WorkspaceTimings,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct WorkspaceTimings {
	pub source_catalog: Duration,
	pub extract_sources: Duration,
	pub semantic_index: Duration,
	pub code_index: Duration,
	pub linkage: Duration,
	pub change_overlay: Duration,
	pub total: Duration,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WorkspaceResource {
	SourceCatalog,
	CodeIndex,
	LinkageSnapshot,
	ChangeOverlay,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WorkspaceFailure {
	pub resource: WorkspaceResource,
	pub message: String,
}

impl WorkspaceFailure {
	pub fn new(resource: WorkspaceResource, message: impl Into<String>) -> Self {
		Self {
			resource,
			message: message.into(),
		}
	}
}

pub type WorkspaceResult<T> = Result<T, WorkspaceFailure>;

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum WorkspaceTransition {
	Ready {
		generation: ResourceGeneration,
	},
	Failed {
		failure: WorkspaceFailure,
		preserved_generation: Option<ResourceGeneration>,
	},
}