foch 0.0.2

EU4 mod analysis and merge toolkit
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
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};

use super::base::builtin::is_builtin_effect;
use super::content::ScriptFileKind;
use crate::game::schema::CwtSchema;
#[cfg(test)]
use crate::game::schema::query::CompiledAlias;
use crate::game::schema::query::{
	CompiledAliasCategory, CompiledRoot, CompiledRuleField, CompiledRuleValue, CwtQuery,
	RuleContext,
};
use crate::game::schema::rule_path::SchemaDirectory;
use crate::model::{GamePath, ScopeKind, ScopeType, base_scope};

pub mod merge;

/// The rule pack `build.rs` compiled from the package's `vendor/cwtools-eu4-config`
/// and, after it, the supplementary rules in `src/game/eu4/cwt_supplement`.
static EMBEDDED_RULE_PACK: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/cwt-rules.pack"));

/// `cwt_schema_id` of the rule pack compiled into this binary.
pub const EMBEDDED_CWT_SCHEMA_ID: &str = env!("FOCH_CWT_SCHEMA_ID");

/// Maintainer override: compile the schema from this directory instead of
/// using the embedded pack. The directory replaces both the vendored rules and
/// the supplement. It changes output bytes, so a directory that does
/// not load is a fatal error rather than a quiet fallback. It is compiled in
/// every process and never cached, so an edit to the compiler shows at once.
pub const CWT_SCHEMA_OVERRIDE_ENV: &str = "FOCH_CWTOOLS_SCHEMA_DIR";

/// The directory [`CWT_SCHEMA_OVERRIDE_ENV`] names; set but empty is unset.
pub fn cwt_schema_override() -> Option<PathBuf> {
	override_dir(std::env::var_os(CWT_SCHEMA_OVERRIDE_ENV))
}

fn override_dir(value: Option<OsString>) -> Option<PathBuf> {
	value.filter(|value| !value.is_empty()).map(PathBuf::from)
}

/// Loads the active EU4 schema without changing EU4's global base-scope state.
pub(crate) fn rule_engine() -> &'static CwtQuery {
	active_schema_slot().facts()
}

pub(crate) fn active_schema() -> Arc<CwtSchema> {
	Arc::clone(active_schema_slot())
}

/// `cwt_schema_id` of the schema this process uses: the embedded pack unless
/// [`CWT_SCHEMA_OVERRIDE_ENV`] names another directory.
pub fn active_cwt_schema_id() -> &'static str {
	static ID: OnceLock<String> = OnceLock::new();
	ID.get_or_init(|| active_schema_slot().source_id().to_hex())
}

fn active_schema_slot() -> &'static Arc<CwtSchema> {
	static EU4_SCHEMA: OnceLock<Arc<CwtSchema>> = OnceLock::new();
	EU4_SCHEMA.get_or_init(|| Arc::new(load_schema(cwt_schema_override())))
}

fn load_schema(override_root: Option<PathBuf>) -> CwtSchema {
	match override_root {
		None => CwtSchema::from_compiled_bytes(EMBEDDED_RULE_PACK)
			.expect("build.rs embeds a rule pack this binary's compiler wrote"),
		Some(root) => CwtSchema::load_with_cache(&root, None).unwrap_or_else(|error| {
			panic!(
				"{CWT_SCHEMA_OVERRIDE_ENV}=`{}` is not a loadable CWT schema: {error}",
				root.display()
			)
		}),
	}
}

pub fn iterator_scope_type(key: &str) -> Option<ScopeType> {
	match key {
		// Province iterators (every_/any_/all_/random_<...>_province)
		"all_core_province"
		| "all_neighbor_province"
		| "all_owned_province"
		| "all_owned_province_cumulative"
		| "all_province"
		| "all_province_in_state"
		| "all_state_province"
		| "all_trade_node_member_province"
		| "any_core_province"
		| "any_empty_neighbor_province"
		| "any_friendly_coast_border_province"
		| "any_heretic_province"
		| "any_owned_province"
		| "any_province"
		| "any_province_in_state"
		| "any_trade_node_member_province"
		| "every_claimed_province"
		| "every_core_province"
		| "every_empty_neighbor_province"
		| "every_heretic_province"
		| "every_neighbor_province"
		| "every_owned_province"
		| "every_province"
		| "every_province_in_state"
		| "every_trade_node_member_province"
		| "every_tribal_land_province"
		| "random_area_province"
		| "random_core_province"
		| "random_empty_neighbor_province"
		| "random_heretic_province"
		| "random_neighbor_province"
		| "random_owned_province"
		| "random_province"
		| "random_province_in_state"
		| "random_trade_node_member_province"
		// Sea zones are provinces in EU4
		| "every_neighbor_sea_zone"
		// Tribal land iterates over provinces
		| "any_tribal_land" => Some(base_scope::province()),
		// Country iterators
		"all_ally"
		| "all_countries_including_self"
		| "all_country"
		| "all_elector"
		| "all_federation_members"
		| "all_known_country"
		| "all_neighbor_country"
		| "all_rival_country"
		| "all_subject_country"
		| "all_trade_node_member_country"
		| "all_war_enemy_countries"
		| "any_ally"
		| "any_core_country"
		| "any_country"
		| "any_country_active_in_node"
		| "any_elector"
		| "any_enemy_country"
		| "any_great_power"
		| "any_hired_mercenary_company"
		| "any_known_country"
		| "any_neighbor_country"
		| "any_other_great_power"
		| "any_privateering_country"
		| "any_rival_country"
		| "any_trade_node_member_country"
		| "any_war_enemy_country"
		| "every_ally"
		| "every_core_country"
		| "every_country"
		| "every_country_including_inactive"
		| "every_elector"
		| "every_enemy_country"
		| "every_federation_member"
		| "every_known_country"
		| "every_neighbor_country"
		| "every_rival_country"
		| "every_subject_country"
		| "every_trade_node_member_country"
		| "every_war_enemy_country"
		| "random_ally"
		| "random_core_country"
		| "random_country"
		| "random_elector"
		| "random_enemy_country"
		| "random_hired_mercenary_company"
		| "random_known_country"
		| "random_neighbor_country"
		| "random_privateering_country"
		| "random_rival_country"
		| "random_subject_country"
		| "random_war_enemy_country" => Some(base_scope::country()),
		_ => None,
	}
}

#[cfg(test)]
pub(crate) fn schema_iterator_scope_type(engine: &CwtQuery, key: &str) -> Option<ScopeType> {
	cwt_alias_push_scope(engine, key)
		.and_then(scope_name_to_base_scope)
		.or_else(|| cwt_field_push_scope_type(engine, key))
}

#[cfg(test)]
pub(crate) fn schema_scope_changer_target_type(engine: &CwtQuery, key: &str) -> Option<ScopeType> {
	cwt_alias_push_scope(engine, key)
		.and_then(scope_name_to_base_scope)
		.or_else(|| cwt_direct_scope_marker_type(engine, key))
		.or_else(|| scope_changer_target_type_fallback(key))
}

#[cfg(test)]
pub(crate) fn schema_special_block_scope_kind(engine: &CwtQuery, key: &str) -> ScopeKind {
	let mut has_trigger = false;
	let mut has_effect = false;
	for alias in engine.aliases() {
		if alias.name != key {
			continue;
		}
		match alias_rules_scope_kind(alias) {
			Some(ScopeKind::Trigger) => has_trigger = true,
			Some(ScopeKind::Effect) => has_effect = true,
			_ => {}
		}
	}
	visit_rule_engine_fields(engine, &mut |field| {
		if field.key != key {
			return;
		}
		match rule_field_alias_scope_kind(field) {
			Some(ScopeKind::Trigger) => has_trigger = true,
			Some(ScopeKind::Effect) => has_effect = true,
			_ => {}
		}
	});
	if has_effect {
		ScopeKind::Effect
	} else if has_trigger {
		ScopeKind::Trigger
	} else {
		ScopeKind::Block
	}
}

#[cfg(test)]
fn cwt_alias_push_scope<'a>(engine: &'a CwtQuery, key: &str) -> Option<&'a str> {
	[
		CompiledAliasCategory::Effect,
		CompiledAliasCategory::Trigger,
	]
	.into_iter()
	.find_map(|category| engine.alias(category, key).and_then(alias_push_scope))
}

#[cfg(test)]
fn alias_push_scope(alias: &CompiledAlias) -> Option<&str> {
	alias.attributes.push_scope.as_deref().or_else(|| {
		alias
			.rules
			.first()
			.and_then(|field| field.attributes.push_scope.as_deref())
	})
}

#[cfg(test)]
fn scope_name_to_base_scope(scope_name: &str) -> Option<ScopeType> {
	if scope_name.eq_ignore_ascii_case("country") {
		Some(base_scope::country())
	} else if scope_name.eq_ignore_ascii_case("province") {
		Some(base_scope::province())
	} else {
		None
	}
}

#[cfg(test)]
fn cwt_field_push_scope_type(engine: &CwtQuery, key: &str) -> Option<ScopeType> {
	let mut matched = None;
	let mut ambiguous = false;
	visit_rule_engine_fields(engine, &mut |field| {
		if ambiguous || field.key != key {
			return;
		}
		let Some(scope_type) = field
			.attributes
			.push_scope
			.as_deref()
			.and_then(scope_name_to_base_scope)
		else {
			return;
		};
		match matched {
			Some(existing) if existing != scope_type => ambiguous = true,
			Some(_) => {}
			None => matched = Some(scope_type),
		}
	});
	if ambiguous { None } else { matched }
}

#[cfg(test)]
fn cwt_direct_scope_marker_type(engine: &CwtQuery, key: &str) -> Option<ScopeType> {
	let mut matched = None;
	let mut ambiguous = false;
	visit_rule_engine_fields(engine, &mut |field| {
		if ambiguous || field.key != key {
			return;
		}
		let Some(scope_type) = rule_field_scope_marker_type(field) else {
			return;
		};
		match matched {
			Some(existing) if existing != scope_type => ambiguous = true,
			Some(_) => {}
			None => matched = Some(scope_type),
		}
	});
	if ambiguous { None } else { matched }
}

#[cfg(test)]
fn rule_field_scope_marker_type(field: &CompiledRuleField) -> Option<ScopeType> {
	match &field.value {
		CompiledRuleValue::Marker(marker) | CompiledRuleValue::Scalar(marker) => {
			marker_scope_type(marker)
		}
		CompiledRuleValue::Block(_) => None,
	}
}

#[cfg(test)]
fn marker_scope_type(marker: &str) -> Option<ScopeType> {
	let (head, payload) = cwt_marker_parts(marker)?;
	(head == "scope")
		.then(|| scope_name_to_base_scope(payload))
		.flatten()
}

fn cwt_marker_parts(text: &str) -> Option<(&str, &str)> {
	let (head, rest) = text.split_once('[')?;
	Some((head, rest.strip_suffix(']')?))
}

#[cfg(test)]
fn scope_changer_target_type_fallback(key: &str) -> Option<ScopeType> {
	match key {
		// `scope_links.cwt:385-387` comments out `alias[effect:owner]`, and
		// `scope_links.cwt:1114-1116` comments out `alias[trigger:owner]`.
		"owner" => Some(base_scope::country()),
		// `scope_links.cwt:392-394` comments out `alias[effect:controller]`, and
		// `scope_links.cwt:1121-1123` comments out `alias[trigger:controller]`.
		"controller" => Some(base_scope::country()),
		_ => None,
	}
}

#[cfg(test)]
fn alias_rules_scope_kind(alias: &CompiledAlias) -> Option<ScopeKind> {
	rules_alias_scope_kind(&alias.rules)
}

#[cfg(test)]
fn rule_field_alias_scope_kind(field: &CompiledRuleField) -> Option<ScopeKind> {
	let CompiledRuleValue::Block(fields) = &field.value else {
		return None;
	};
	rules_alias_scope_kind(fields)
}

#[cfg(test)]
fn rules_alias_scope_kind(fields: &[CompiledRuleField]) -> Option<ScopeKind> {
	if fields.iter().any(|child| child.key == "alias_name[effect]") {
		Some(ScopeKind::Effect)
	} else if fields
		.iter()
		.any(|child| child.key == "alias_name[trigger]")
	{
		Some(ScopeKind::Trigger)
	} else {
		None
	}
}

#[cfg(test)]
fn visit_rule_engine_fields<F>(engine: &CwtQuery, visit: &mut F)
where
	F: FnMut(&CompiledRuleField),
{
	for definition in &engine.pack().roots {
		visit_rule_fields(&definition.rules, visit);
		for subtype in &definition.subtypes {
			visit_rule_fields(&subtype.rules, visit);
		}
	}
	for alias in engine.aliases() {
		visit_rule_fields(&alias.rules, visit);
	}
}

#[cfg(test)]
fn visit_rule_fields<F>(fields: &[CompiledRuleField], visit: &mut F)
where
	F: FnMut(&CompiledRuleField),
{
	for field in fields {
		visit(field);
		if let CompiledRuleValue::Block(children) = &field.value {
			visit_rule_fields(children, visit);
		}
	}
}

pub(crate) fn schema_file_kind_container_scope_kind(
	engine: &CwtQuery,
	file_kind: ScriptFileKind,
	key: &str,
) -> Option<ScopeKind> {
	if !is_legacy_container_scope_key(file_kind.as_str(), key) {
		return None;
	}
	if let Some(kind) = hand_container_scope_fallback(file_kind.clone(), key) {
		return Some(kind);
	}
	cwt_derived_container_scope_kind(engine, file_kind, key)
}

/// Resolve a block's script role from its concrete CWT path.
///
/// Unlike [`schema_file_kind_container_scope_kind`], this follows the active
/// schema branch and therefore handles dynamic keys such as age objective ids.
pub(crate) fn schema_path_container_scope_kind(
	engine: &CwtQuery,
	file_kind: ScriptFileKind,
	file_path: &GamePath,
	ast_path: &[&str],
) -> Option<ScopeKind> {
	let key = *ast_path.last()?;
	if let Some(kind) = hand_container_scope_fallback(file_kind, key) {
		return Some(kind);
	}

	for candidate_path in [
		ast_path,
		ast_path.get(1..).expect("non-empty AST path has a suffix"),
	] {
		if let Some(RuleContext::RuleField(field)) = engine.bind_context(file_path, candidate_path)
			&& let Some(kind) = cwt_container_field_scope_kind(engine, field)
		{
			return Some(kind);
		}
	}

	let parent_path = &ast_path[..ast_path.len() - 1];
	let parent = if parent_path.is_empty() {
		RuleContext::RootType(engine.bind_root(file_path)?)
	} else {
		engine.bind_context(file_path, parent_path).or_else(|| {
			engine.bind_context(
				file_path,
				parent_path
					.get(1..)
					.expect("non-empty parent path has a suffix"),
			)
		})?
	};
	if let Some(field_match) = engine.bind_field_match(parent, key) {
		if let Some(alias) = field_match.alias()
			&& let Some(kind) = cwt_alias_category_scope_kind(engine, &alias.category)
		{
			return Some(kind);
		}
		return cwt_container_field_scope_kind(engine, field_match.field());
	}
	cwt_dynamic_child_scope_kind(engine, parent)
}

fn cwt_dynamic_child_scope_kind(engine: &CwtQuery, parent: RuleContext<'_>) -> Option<ScopeKind> {
	let RuleContext::RuleField(parent) = parent else {
		return None;
	};
	let CompiledRuleValue::Block(fields) = &parent.value else {
		return None;
	};
	fields
		.iter()
		.find(|field| field.key == "localisation")
		.and_then(|field| cwt_container_field_scope_kind(engine, field))
}

fn is_legacy_container_scope_key(file_kind: &str, key: &str) -> bool {
	match file_kind {
		"missions" => matches!(
			key,
			"potential_on_load"
				| "potential"
				| "trigger" | "provinces_to_highlight"
				| "completed_by"
				| "ai_weight"
				| "effect" | "on_completed"
				| "on_cancelled"
		),
		"new_diplomatic_actions" => {
			matches!(
				key,
				"is_visible"
					| "is_allowed" | "ai_will_do"
					| "on_accept" | "on_decline"
					| "add_entry"
			)
		}
		"events" => matches!(key, "mean_time_to_happen"),
		"ages" => matches!(
			key,
			"can_start" | "custom_trigger_tooltip" | "calc_true_if" | "ai_will_do" | "effect"
		),
		"buildings" => matches!(
			key,
			"ai_will_do"
				| "on_built" | "on_destroyed"
				| "on_construction_started"
				| "on_construction_canceled"
				| "on_obsolete"
		),
		"institutions" => matches!(
			key,
			"history"
				| "can_embrace"
				| "potential"
				| "custom_trigger_tooltip"
				| "on_start" | "embracement_speed"
				| "modifier"
		),
		"province_triggered_modifiers" => {
			matches!(
				key,
				"potential" | "trigger" | "on_activation" | "on_deactivation"
			)
		}
		"triggered_modifiers" => {
			matches!(
				key,
				"potential" | "trigger" | "on_activation" | "on_deactivation"
			)
		}
		"scripted_triggers" => matches!(key, "trigger" | "limit" | "custom_trigger_tooltip"),
		"ideas" => matches!(key, "start" | "bonus" | "trigger" | "ai_will_do"),
		"great_projects" => {
			matches!(
				key,
				"build_trigger"
					| "can_use_modifiers_trigger"
					| "can_upgrade_trigger"
					| "keep_trigger"
					| "on_built" | "on_destroyed"
					| "on_upgraded" | "on_downgraded"
					| "on_obtained" | "on_lost"
			)
		}
		"government_reforms" => {
			matches!(
				key,
				"on_enabled"
					| "on_disabled" | "on_enacted"
					| "on_removed" | "removed_effect"
					| "ai_will_do"
			)
		}
		"cb_types" => {
			matches!(
				key,
				"prerequisites_self" | "prerequisites" | "can_use" | "can_take_province"
			)
		}
		"government_names" => matches!(key, "trigger"),
		"customizable_localization" => matches!(key, "trigger"),
		"religions" => matches!(
			key,
			"potential" | "allow" | "ai_will_do" | "effect" | "on_convert"
		),
		"subject_types" => matches!(
			key,
			"is_potential_overlord"
				| "can_fight"
				| "can_rival"
				| "can_ally" | "can_marry"
				| "modifier_subject"
				| "modifier_overlord"
		),
		"rebel_types" => matches!(
			key,
			"spawn_chance"
				| "movement_evaluation"
				| "can_negotiate_trigger"
				| "can_enforce_trigger"
				| "siege_won_effect"
				| "demands_enforced_effect"
		),
		"disasters" => matches!(
			key,
			"potential"
				| "can_start"
				| "can_stop" | "can_end"
				| "on_start" | "on_end"
				| "on_monthly"
				| "progress" | "modifier"
		),
		"government_mechanics" => matches!(
			key,
			"available"
				| "trigger" | "on_max_reached"
				| "on_min_reached"
				| "powers" | "scaled_modifier"
				| "reverse_scaled_modifier"
				| "modifier"
		),
		"church_aspects" => matches!(
			key,
			"potential" | "trigger" | "ai_will_do" | "effect" | "modifier"
		),
		"factions" => matches!(key, "allow" | "modifier"),
		"hegemons" => matches!(key, "allow" | "base" | "scale" | "max"),
		"personal_deities" => matches!(
			key,
			"potential" | "trigger" | "ai_will_do" | "effect" | "removed_effect"
		),
		"fetishist_cults" => matches!(key, "allow" | "ai_will_do"),
		"peace_treaties" => matches!(
			key,
			"is_visible" | "is_allowed" | "ai_weight" | "effect" | "warscore_cost"
		),
		"policies" => matches!(
			key,
			"potential" | "allow" | "ai_will_do" | "effect" | "removed_effect"
		),
		"mercenary_companies" => matches!(key, "trigger" | "modifier"),
		"estate_agendas" => {
			matches!(
				key,
				"can_select"
					| "task_requirements"
					| "fail_if" | "invalid_trigger"
					| "provinces_to_highlight"
					| "selection_weight"
					| "pre_effect" | "immediate_effect"
					| "on_invalid" | "task_completed_effect"
			)
		}
		"estate_privileges" => {
			matches!(
				key,
				"is_valid"
					| "can_select" | "can_revoke"
					| "ai_will_do" | "on_granted"
					| "on_revoked" | "on_invalid"
					| "on_granted_province"
					| "on_revoked_province"
					| "on_invalid_province"
					| "on_cooldown_expires"
					| "benefits" | "penalties"
					| "modifier_by_land_ownership"
					| "mechanics" | "conditional_modifier"
					| "influence_scaled_conditional_modifier"
					| "loyalty_scaled_conditional_modifier"
			)
		}
		"estates" => matches!(
			key,
			"trigger"
				| "country_modifier_happy"
				| "country_modifier_neutral"
				| "country_modifier_angry"
				| "land_ownership_modifier"
				| "province_independence_weight"
				| "influence_modifier"
				| "loyalty_modifier"
				| "influence_from_dev_modifier"
		),
		"parliament_bribes" => matches!(key, "trigger" | "chance" | "ai_will_do" | "effect"),
		"parliament_issues" => matches!(
			key,
			"allow"
				| "chance" | "ai_will_do"
				| "effect" | "on_issue_taken"
				| "modifier" | "influence_scaled_modifier"
		),
		"state_edicts" => matches!(
			key,
			"potential" | "allow" | "notify_trigger" | "ai_will_do" | "modifier"
		),
		_ => false,
	}
}

fn cwt_derived_container_scope_kind(
	engine: &CwtQuery,
	file_kind: ScriptFileKind,
	key: &str,
) -> Option<ScopeKind> {
	let mut has_trigger = false;
	let mut has_effect = false;
	let mut has_block = false;
	for definition in file_kind_root_types(engine, &file_kind) {
		for field in file_kind_container_fields(engine, definition, key) {
			match cwt_container_field_scope_kind(engine, field) {
				Some(ScopeKind::Effect) => has_effect = true,
				Some(ScopeKind::Trigger) => has_trigger = true,
				Some(ScopeKind::Block) => has_block = true,
				_ => {}
			}
		}
	}
	if has_effect {
		Some(ScopeKind::Effect)
	} else if has_trigger {
		Some(ScopeKind::Trigger)
	} else if has_block {
		Some(ScopeKind::Block)
	} else {
		None
	}
}

fn file_kind_root_types<'e>(
	engine: &'e CwtQuery,
	file_kind: &ScriptFileKind,
) -> Vec<&'e CompiledRoot> {
	let kind = file_kind.as_str();
	let mut matches = engine
		.pack()
		.roots
		.iter()
		.filter(|definition| {
			definition.name.as_str() == kind
				|| definition
					.path
					.as_ref()
					.is_some_and(|path| schema_path_matches_file_kind(path, kind))
		})
		.collect::<Vec<_>>();
	matches.sort_by(|lhs, rhs| lhs.name.cmp(&rhs.name));
	matches
}

/// Whether a root type's directory is named for `file_kind`: its last
/// component, compared ignoring ASCII case as rule paths are.
pub(super) fn schema_path_matches_file_kind(path: &SchemaDirectory, file_kind: &str) -> bool {
	path.as_game_path()
		.is_some_and(|directory| directory.file_name().eq_ignore_ascii_case(file_kind))
}

fn file_kind_container_fields<'e>(
	engine: &'e CwtQuery,
	definition: &'e CompiledRoot,
	key: &str,
) -> Vec<&'e CompiledRuleField> {
	let mut matches = Vec::new();
	collect_rule_set_matches(
		engine,
		RuleContext::RootType(definition),
		definition.rules.as_slice(),
		key,
		&mut matches,
	);
	for subtype in &definition.subtypes {
		collect_rule_set_matches(
			engine,
			RuleContext::AliasRules(subtype.rules.as_slice()),
			subtype.rules.as_slice(),
			key,
			&mut matches,
		);
	}
	matches
}

fn collect_rule_set_matches<'e>(
	engine: &'e CwtQuery,
	parent: RuleContext<'e>,
	rules: &'e [CompiledRuleField],
	key: &str,
	matches: &mut Vec<&'e CompiledRuleField>,
) {
	matches.extend(engine.bind_fields(parent, key));
	for field in rules {
		let CompiledRuleValue::Block(children) = &field.value else {
			continue;
		};
		collect_rule_set_matches(
			engine,
			RuleContext::RuleField(field),
			children.as_slice(),
			key,
			matches,
		);
	}
}

fn cwt_container_field_scope_kind(
	engine: &CwtQuery,
	field: &CompiledRuleField,
) -> Option<ScopeKind> {
	match &field.value {
		CompiledRuleValue::Block(fields) => cwt_container_block_scope_kind(engine, fields),
		CompiledRuleValue::Scalar(value) | CompiledRuleValue::Marker(value) => {
			cwt_container_scalar_scope_kind(engine, value)
		}
	}
}

fn cwt_container_block_scope_kind(
	engine: &CwtQuery,
	fields: &[CompiledRuleField],
) -> Option<ScopeKind> {
	let mut has_trigger = false;
	let mut has_effect = false;
	let mut has_block = false;
	for child in fields {
		match cwt_direct_child_scope_kind(engine, child) {
			Some(ScopeKind::Effect) => has_effect = true,
			Some(ScopeKind::Trigger) => has_trigger = true,
			Some(ScopeKind::Block) => has_block = true,
			_ => {}
		}
		if is_effect_like_child_key(&child.key) {
			has_effect = true;
		}
	}
	if has_effect {
		Some(ScopeKind::Effect)
	} else if has_trigger {
		Some(ScopeKind::Trigger)
	} else if has_block || !fields.is_empty() {
		Some(ScopeKind::Block)
	} else {
		None
	}
}

fn cwt_direct_child_scope_kind(engine: &CwtQuery, field: &CompiledRuleField) -> Option<ScopeKind> {
	cwt_alias_marker_scope_kind(engine, &field.key)
}

fn cwt_container_scalar_scope_kind(engine: &CwtQuery, value: &str) -> Option<ScopeKind> {
	if is_event_like_reference(value) {
		return Some(ScopeKind::Effect);
	}
	if let Some(scope_kind) = cwt_alias_marker_scope_kind(engine, value) {
		return Some(scope_kind);
	}
	engine
		.root(value)
		.and_then(|definition| cwt_container_block_scope_kind(engine, &definition.rules))
}

fn cwt_alias_marker_scope_kind(engine: &CwtQuery, marker: &str) -> Option<ScopeKind> {
	let (head, payload) = cwt_marker_parts(marker)?;
	match head {
		"alias_name" | "alias" => {
			let category = payload
				.split_once(':')
				.map_or(payload, |(category, _)| category);
			cwt_alias_category_scope_kind(engine, &CompiledAliasCategory::from_name(category))
		}
		_ => None,
	}
}

fn cwt_alias_category_scope_kind(
	engine: &CwtQuery,
	category: &CompiledAliasCategory,
) -> Option<ScopeKind> {
	match category {
		CompiledAliasCategory::Effect => Some(ScopeKind::Effect),
		CompiledAliasCategory::Trigger => Some(ScopeKind::Trigger),
		CompiledAliasCategory::Modifier => Some(ScopeKind::Block),
		CompiledAliasCategory::Link => None,
		CompiledAliasCategory::Other(_) => {
			let mut has_trigger = false;
			let mut has_effect = false;
			let mut has_block = false;
			for alias in engine
				.aliases()
				.iter()
				.filter(|alias| &alias.category == category)
			{
				match cwt_container_block_scope_kind(engine, &alias.rules) {
					Some(ScopeKind::Effect) => has_effect = true,
					Some(ScopeKind::Trigger) => has_trigger = true,
					Some(ScopeKind::Block) => has_block = true,
					_ => {}
				}
			}
			if has_effect {
				Some(ScopeKind::Effect)
			} else if has_trigger {
				Some(ScopeKind::Trigger)
			} else if has_block {
				Some(ScopeKind::Block)
			} else {
				None
			}
		}
	}
}

fn is_event_like_reference(value: &str) -> bool {
	value.starts_with("<event.") && value.ends_with('>')
}

fn is_effect_like_child_key(key: &str) -> bool {
	matches!(
		key,
		"effect"
			| "removed_effect"
			| "hidden_effect"
			| "immediate"
			| "after" | "on_add"
			| "on_remove"
			| "on_start"
			| "on_end"
			| "on_monthly"
	) || key.starts_with("on_")
		|| key.ends_with("_effect")
		|| is_builtin_effect(key)
}

/// Hand-maintained fallbacks for cwtools-eu4-config schema gaps.
///
/// These entries are the exact cases where the hybrid diff test found that
/// cwtools-eu4-config either lacks the relevant rule entirely or projects it in
/// a way that changes the legacy scope kind. To remove an entry from this list,
/// contribute the corresponding rule to cwtools-eu4-config upstream and bump the
/// vendored schema.
pub(super) fn hand_container_scope_fallback(
	file_kind: ScriptFileKind,
	key: &str,
) -> Option<ScopeKind> {
	match (file_kind.as_str(), key) {
		// cwtools-eu4-config gap: missions/missions.cwt declares `completed_by = date_field`
		// without enough schema signal to preserve the legacy trigger classification.
		("missions", "completed_by") => Some(ScopeKind::Trigger),
		// cwtools-eu4-config gap: missions/missions.cwt models `ai_weight` through
		// score/helper structure, but legacy behavior treats its children as trigger
		// conditions rather than scripted effect calls.
		("missions", "ai_weight") => Some(ScopeKind::Trigger),
		// cwtools-eu4-config gap: missions/missions.cwt does not declare these mission
		// lifecycle effect containers.
		("missions", "on_completed" | "on_cancelled") => Some(ScopeKind::Effect),
		// cwtools-eu4-config gap: events/events.cwt models MTTH as score/helper
		// structure, but legacy behavior treats its children as trigger conditions.
		("events", "mean_time_to_happen") => Some(ScopeKind::Trigger),
		// cwtools-eu4-config gap: common/ages.cwt does not expose explicit fields for
		// these trigger containers.
		("ages", "custom_trigger_tooltip" | "calc_true_if") => Some(ScopeKind::Trigger),
		// cwtools-eu4-config gap: common/institutions.cwt only exposes nested trigger-like
		// content under `embracement_speed.modifier`, but legacy behavior treats the
		// outer `modifier` container as a plain block.
		("institutions", "modifier") => Some(ScopeKind::Block),
		// cwtools-eu4-config gap: common/00_small_types_consolidated.cwt does not declare
		// these top-level triggered modifier lifecycle effects for the `triggered_modifiers`
		// root family.
		("triggered_modifiers", "on_activation" | "on_deactivation") => Some(ScopeKind::Effect),
		// cwtools-eu4-config gap: common/scripted_triggers_and_effects.cwt does not model
		// these legacy scripted trigger containers directly.
		("scripted_triggers", "trigger" | "limit" | "custom_trigger_tooltip") => {
			Some(ScopeKind::Trigger)
		}
		// cwtools-eu4-config gap: common/ideas_and_native_advancements.cwt models `start`
		// as a modifier/ability block, but legacy semantics treat it as an effect container.
		("ideas", "start") => Some(ScopeKind::Effect),
		// cwtools-eu4-config gap: common/greatprojects.cwt does not declare these optional
		// lifecycle effect hooks.
		("great_projects", "on_downgraded" | "on_obtained" | "on_lost") => Some(ScopeKind::Effect),
		// cwtools-eu4-config gap: common/governments_and_reforms.cwt is missing these
		// reform lifecycle hooks and the legacy ai_will_do trigger container.
		("government_reforms", "on_enabled" | "on_disabled" | "on_enacted" | "on_removed") => {
			Some(ScopeKind::Effect)
		}
		("government_reforms", "ai_will_do") => Some(ScopeKind::Trigger),
		// cwtools-eu4-config gap: common/casus_belli_and_war_goals.cwt does not expose
		// these casus belli trigger containers.
		("cb_types", "can_use" | "can_take_province") => Some(ScopeKind::Trigger),
		// cwtools-eu4-config gap: common/subject_types.cwt models these relation checks as
		// structural blocks, but legacy semantics treat them as trigger containers.
		("subject_types", "can_fight" | "can_rival" | "can_ally" | "can_marry") => {
			Some(ScopeKind::Trigger)
		}
		// cwtools-eu4-config gap: common/disasters.cwt only surfaces a modifier_rule-style
		// block for `progress`, but legacy behavior keeps it as a plain block container.
		("disasters", "progress") => Some(ScopeKind::Block),
		// cwtools-eu4-config gap: common/peace_treaties.cwt models `ai_weight` as an AI
		// score block, but legacy behavior classifies it as a trigger container.
		("peace_treaties", "ai_weight") => Some(ScopeKind::Trigger),
		// cwtools-eu4-config gap: common/estates.cwt leaves `mechanics` empty, so schema
		// traversal cannot distinguish it from an untyped block without this fallback.
		("estate_privileges", "mechanics") => Some(ScopeKind::Block),
		// cwtools-eu4-config gap: common/estates.cwt projects these estate modifiers as a
		// modifier_rule block or scalar, but legacy behavior keeps them as plain blocks.
		("estates", "province_independence_weight" | "influence_from_dev_modifier") => {
			Some(ScopeKind::Block)
		}
		_ => None,
	}
}

pub fn scope_changer_target_type(key: &str) -> Option<ScopeType> {
	match key {
		"capital_scope" | "sea_zone" | "area_for_scope_province" | "region_for_scope_province" => {
			Some(base_scope::province())
		}
		"owner"
		| "controller"
		| "attacker_leader"
		| "defender_leader"
		| "emperor"
		| "colonial_parent"
		| "other_overlord"
		| "same_overlord"
		| "strongest_trade_power"
		| "unit_owner" => Some(base_scope::country()),
		_ => None,
	}
}

pub fn special_block_scope_kind(key: &str) -> ScopeKind {
	match key {
		"possible"
		| "visible"
		| "happened"
		| "provinces_to_highlight"
		| "exclude_from_progress" => ScopeKind::Trigger,
		_ => ScopeKind::Block,
	}
}

pub fn is_country_file_reference(value: &str) -> bool {
	value.starts_with("countries/") && value.ends_with(".txt")
}

pub fn is_country_tag_text(value: &str) -> bool {
	is_country_tag_token(value)
}

pub fn is_country_tag_selector(key: &str) -> bool {
	is_country_tag_token(key)
}

/// EU4 country tags are exactly three ASCII characters: the first is an
/// uppercase letter and the remaining characters are uppercase letters or
/// ASCII digits. This matches both vanilla tags (FRA, ENG, KOR) and the
/// digit-bearing tags commonly used by mods (X3E, Y1D, K01).
fn is_country_tag_token(token: &str) -> bool {
	if token.len() != 3 {
		return false;
	}
	let mut chars = token.chars();
	let first = chars.next().unwrap();
	if !first.is_ascii_uppercase() {
		return false;
	}
	chars.all(|ch| ch.is_ascii_uppercase() || ch.is_ascii_digit())
}

pub fn is_province_id_text(value: &str) -> bool {
	value.parse::<u32>().is_ok_and(|id| id > 0)
}

pub fn is_province_id_selector(key: &str) -> bool {
	key.parse::<u32>().map(|value| value > 100).unwrap_or(false)
}

pub fn is_dynamic_scope_reference_key(key: &str) -> bool {
	key.starts_with("event_target:")
}

pub fn looks_like_map_group_key(key: &str) -> bool {
	key.ends_with("_area")
		|| key.ends_with("_region")
		|| key.ends_with("_superregion")
		|| key.ends_with("_provincegroup")
		|| key.starts_with("trade_company_")
}

#[cfg(test)]
mod tests {
	use std::path::{Path, PathBuf};

	use std::ffi::OsString;

	use super::{
		CwtSchema, EMBEDDED_CWT_SCHEMA_ID, EMBEDDED_RULE_PACK, iterator_scope_type, load_schema,
		override_dir, schema_path_container_scope_kind,
	};
	use crate::game::eu4::content::ScriptFileKind;
	use crate::game::schema::CwtLoadStatus;
	use crate::game::schema::query::CompiledRulePack;
	use crate::game::schema::source::cwt_files;
	use crate::game::schema::source::{
		SchemaPack, cwt_schema_id_from_dir, cwt_schema_id_from_dirs, normalize_line_endings,
	};
	use crate::model::{GamePath, ScopeKind, ScopeRegistry, base_scope};

	/// The directories `build.rs` compiles, in its order.
	fn embedded_schema_dirs() -> [PathBuf; 2] {
		let package = Path::new(env!("CARGO_MANIFEST_DIR"));
		[
			package.join("vendor/cwtools-eu4-config"),
			package.join("src/game/eu4/cwt_supplement"),
		]
	}

	#[test]
	fn default_schema_is_the_embedded_pack_of_the_vendored_config_and_supplement() {
		let schema = load_schema(None);
		let [vendor, supplement] = embedded_schema_dirs();
		let embedded_id =
			cwt_schema_id_from_dirs(&[&vendor, &supplement]).expect("hash embedded CWT");

		assert_eq!(schema.cache_status(), CwtLoadStatus::Embedded);
		assert_eq!(schema.source_id(), &embedded_id);
		assert_eq!(schema.source_id().to_hex(), EMBEDDED_CWT_SCHEMA_ID);
		assert!(schema.facts().root_count() > 0);
		assert!(schema.facts().alias_count() > 0);
	}

	#[test]
	fn compiling_the_vendored_config_and_supplement_reproduces_the_embedded_bytes() {
		// build.rs compiled the embedded pack in another process, so equality
		// also proves the encoding does not depend on per-process hash seeds.
		let [vendor, supplement] = embedded_schema_dirs();
		let pack =
			SchemaPack::load_from_dirs(&[&vendor, &supplement]).expect("compile embedded CWT");
		let bytes = CompiledRulePack::from_schema_pack(&pack)
			.to_bytes()
			.expect("encode compiled CWT");

		assert!(bytes == EMBEDDED_RULE_PACK);
	}

	#[test]
	fn a_crlf_checkout_compiles_to_the_embedded_bytes() {
		// Windows checkouts convert the rules' line endings; their binaries
		// must embed the same pack the same `cwt_schema_id` names elsewhere.
		let copies = embedded_schema_dirs().map(|source_root| {
			let crlf = tempfile::tempdir().expect("create CRLF schema copy");
			for source in cwt_files(&source_root).expect("list embedded CWT") {
				let target = crlf
					.path()
					.join(source.strip_prefix(&source_root).expect("embedded path"));
				let text = std::fs::read(&source).expect("read embedded CWT");
				let lf = normalize_line_endings(&text);
				let mut converted = Vec::with_capacity(lf.len() * 11 / 10);
				for &byte in lf.iter() {
					if byte == b'\n' {
						converted.push(b'\r');
					}
					converted.push(byte);
				}
				std::fs::create_dir_all(target.parent().expect("CWT parent"))
					.expect("create CWT parent");
				std::fs::write(target, converted).expect("write CRLF CWT");
			}
			crlf
		});

		let pack = SchemaPack::load_from_dirs(&[copies[0].path(), copies[1].path()])
			.expect("compile CRLF CWT");
		let bytes = CompiledRulePack::from_schema_pack(&pack)
			.to_bytes()
			.expect("encode compiled CWT");

		assert!(bytes == EMBEDDED_RULE_PACK);
	}

	#[test]
	fn an_override_compiles_its_own_directory() {
		let root =
			Path::new(env!("CARGO_MANIFEST_DIR")).join("src/game/schema/tests/fixtures/binding");
		let schema = load_schema(Some(root.clone()));

		assert_eq!(schema.cache_status(), CwtLoadStatus::CompiledFromSource);
		assert!(schema.cache_path().is_none());
		assert_eq!(
			schema.source_id(),
			&cwt_schema_id_from_dir(&root).expect("hash fixture CWT")
		);
		assert_ne!(schema.source_id().to_hex(), EMBEDDED_CWT_SCHEMA_ID);
	}

	#[test]
	#[should_panic(expected = "FOCH_CWTOOLS_SCHEMA_DIR")]
	fn an_override_without_rule_files_is_fatal() {
		let empty = tempfile::tempdir().expect("create empty schema directory");
		load_schema(Some(empty.path().to_path_buf()));
	}

	#[test]
	fn an_empty_override_variable_is_unset() {
		assert_eq!(override_dir(None), None);
		assert_eq!(override_dir(Some(OsString::new())), None);
		assert_eq!(
			override_dir(Some(OsString::from("/maintainer/cwt"))),
			Some(PathBuf::from("/maintainer/cwt"))
		);
	}

	#[test]
	fn iterator_scope_type_classifies_known_iterators() {
		ScopeRegistry::install_test_defaults();
		for key in [
			"all_core_province",
			"any_owned_province",
			"every_neighbor_province",
			"random_province",
			"every_neighbor_sea_zone",
			"any_tribal_land",
		] {
			assert_eq!(
				iterator_scope_type(key),
				Some(base_scope::province()),
				"{key}"
			);
		}
		for key in [
			"all_ally",
			"any_country",
			"every_subject_country",
			"random_war_enemy_country",
			"any_hired_mercenary_company",
		] {
			assert_eq!(
				iterator_scope_type(key),
				Some(base_scope::country()),
				"{key}"
			);
		}
		for key in ["", "not_an_iterator", "owner", "any_known_country_xyz"] {
			assert_eq!(iterator_scope_type(key), None, "{key}");
		}
	}

	#[test]
	fn schema_path_classifies_dynamic_age_objectives_as_triggers() {
		let engine = super::rule_engine();
		let file = GamePath::new("common/ages/00_default.txt").expect("valid game path");
		let file_kind = ScriptFileKind::new("ages");

		assert_eq!(
			schema_path_container_scope_kind(
				engine,
				file_kind.clone(),
				file,
				&["age_of_reformation", "objectives"],
			),
			Some(ScopeKind::Block),
		);
		assert_eq!(
			schema_path_container_scope_kind(
				engine,
				file_kind,
				file,
				&["age_of_reformation", "objectives", "obj_colonial_empire",],
			),
			Some(ScopeKind::Trigger),
		);
	}

	/// A user schema can declare a rule path that is not a game path. It no
	/// longer loads, and the report says which schema, which file and which
	/// declaration instead of switching schema features off silently.
	#[test]
	#[should_panic(expected = "FOCH_CWTOOLS_SCHEMA_DIR")]
	fn a_user_schema_that_fails_to_load_is_reported_with_its_cause() {
		let root = tempfile::tempdir().expect("create schema dir");
		let file = root.path().join("ideas.cwt");
		std::fs::write(
			&file,
			"types = { type[idea_group] = { path = \"game/common/ideas/\" } }\n",
		)
		.expect("write schema");
		let error = CwtSchema::load_with_cache(root.path(), None)
			.err()
			.expect("a trailing `/` is not a game path");
		let report: String = error.to_string();

		for expected in [
			root.path().display().to_string(),
			file.display().to_string(),
			"`idea_group` declares an invalid path".to_string(),
		] {
			assert!(report.contains(&expected), "{expected} not in {report}");
		}
		load_schema(Some(root.path().to_path_buf()));
	}
}