Skip to main content

workshop_rs_cli/
census.rs

1//! Deterministic, sharded census of the canonical Workshop surface.
2//!
3//! The census is derived from this crate's catalog, settings table, and WIR
4//! capabilities. It is tooling that runs contract/regression probes and
5//! produces structured results, not a source-language inventory or a
6//! live-client oracle.
7
8use std::collections::{HashMap, HashSet};
9
10use serde::{Deserialize, Serialize};
11use sha2::{Digest, Sha256};
12
13use crate::conformance::{
14    CONFORMANCE_SCHEMA_VERSION, Comparison, ConformanceReason, ConformanceResult,
15    ConformanceStatus, Equivalence, FeatureId, FeatureKind, FeatureNamespace, ReasonCode,
16    TestArtifact, is_sha256_digest,
17};
18use workshop_rs::catalog::{Catalog, CatalogEntry, EnumDomain, Kind, Locale};
19use workshop_rs::gameplay::{self, HeroId};
20use workshop_rs::settings::{
21    self as settings_schema, SettingDefinition, SettingTarget, SettingTargetKind,
22    SettingValueDomain,
23};
24use workshop_rs::{WorkshopError, convert, emitter, parser, roundtrip};
25
26#[derive(Clone, Copy)]
27enum CensusCapabilityKind {
28    Variable,
29    PlayerVariable,
30    Subroutine,
31    ControlFlow,
32    String,
33}
34
35struct CensusCapability {
36    kind: CensusCapabilityKind,
37    name: &'static str,
38}
39
40const CENSUS_CAPABILITIES: &[CensusCapability] = &[
41    CensusCapability {
42        kind: CensusCapabilityKind::Variable,
43        name: "global",
44    },
45    CensusCapability {
46        kind: CensusCapabilityKind::PlayerVariable,
47        name: "player",
48    },
49    CensusCapability {
50        kind: CensusCapabilityKind::Subroutine,
51        name: "declaration-and-call",
52    },
53    CensusCapability {
54        kind: CensusCapabilityKind::ControlFlow,
55        name: "if",
56    },
57    CensusCapability {
58        kind: CensusCapabilityKind::ControlFlow,
59        name: "else-if",
60    },
61    CensusCapability {
62        kind: CensusCapabilityKind::ControlFlow,
63        name: "else",
64    },
65    CensusCapability {
66        kind: CensusCapabilityKind::ControlFlow,
67        name: "while",
68    },
69    CensusCapability {
70        kind: CensusCapabilityKind::ControlFlow,
71        name: "for-global-variable",
72    },
73    CensusCapability {
74        kind: CensusCapabilityKind::String,
75        name: "custom-string",
76    },
77];
78
79pub const CENSUS_SCHEMA_VERSION: u32 = 1;
80pub const CENSUS_IDENTITY_SCHEMA_VERSION: u32 = 1;
81const EN_US: &str = "en-US";
82const ZH_CN: &str = "zh-CN";
83const LOCALIZATION_EN_US_SOURCE: &str = r#"rule ("Localization") {
84    event {
85        Ongoing - Global;
86    }
87    actions {
88        Disable Inspector Recording;
89    }
90}
91"#;
92const LOCALIZATION_ZH_CN_SOURCE: &str = r#"rule ("Localization") {
93    event {
94        持续 - 全局;
95    }
96    actions {
97        禁用查看器录制;
98    }
99}
100"#;
101
102/// An explicit support classification for a census case.
103#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(tag = "kind", rename_all = "kebab-case")]
105pub enum CensusSupport {
106    Exercise,
107    Unsupported { detail: String },
108    KnownGap { detail: String },
109    Inconclusive { detail: String },
110}
111
112/// One deterministic case with explicit source-locale provenance.
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
114pub struct CensusCase {
115    pub case_id: String,
116    pub features: Vec<FeatureId>,
117    /// Locale of `source`; a zh-CN case is a real input, not an
118    /// implementation-generated conversion.
119    #[serde(default = "default_source_locale")]
120    pub source_locale: String,
121    pub source: String,
122    /// Independently recorded source text, when this case has an offline
123    /// expectation. None means the case remains inconclusive offline.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub reference_source: Option<String>,
126    pub support: CensusSupport,
127}
128
129/// A named collection of independently attributable cases.
130#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
131pub struct CensusShard {
132    pub shard_id: String,
133    pub cases: Vec<CensusCase>,
134}
135
136impl CensusShard {
137    pub fn new(
138        shard_id: impl Into<String>,
139        mut cases: Vec<CensusCase>,
140    ) -> Result<Self, CensusError> {
141        let shard_id = shard_id.into();
142        validate_name("shard_id", &shard_id)?;
143        cases.sort_by(|left, right| left.case_id.cmp(&right.case_id));
144        for case in &cases {
145            case.validate()?;
146        }
147        if cases
148            .windows(2)
149            .any(|pair| pair[0].case_id == pair[1].case_id)
150        {
151            return Err(CensusError::new(format!(
152                "shard '{shard_id}' contains duplicate case IDs"
153            )));
154        }
155        Ok(Self { shard_id, cases })
156    }
157}
158
159impl CensusCase {
160    fn probe(case_id: impl Into<String>, features: Vec<FeatureId>, source: String) -> Self {
161        Self {
162            case_id: case_id.into(),
163            features,
164            source_locale: EN_US.to_string(),
165            source,
166            reference_source: None,
167            support: generated_probe_support(),
168        }
169    }
170
171    fn exercise(mut self) -> Self {
172        self.support = CensusSupport::Exercise;
173        self
174    }
175
176    fn locale(mut self, locale: &str) -> Self {
177        self.source_locale = locale.to_string();
178        self
179    }
180
181    #[cfg(test)]
182    fn with_support(mut self, support: CensusSupport) -> Self {
183        self.support = support;
184        self
185    }
186
187    fn validate(&self) -> Result<(), CensusError> {
188        validate_name("case_id", &self.case_id)?;
189        if self.features.is_empty() {
190            return Err(CensusError::new(format!(
191                "case '{}' has no feature IDs",
192                self.case_id
193            )));
194        }
195        if self.source.trim().is_empty() {
196            return Err(CensusError::new(format!(
197                "case '{}' has no source",
198                self.case_id
199            )));
200        }
201        validate_name("source_locale", &self.source_locale)?;
202        if self
203            .reference_source
204            .as_deref()
205            .is_some_and(|source| source.trim().is_empty())
206        {
207            return Err(CensusError::new(format!(
208                "case '{}' has an empty reference source",
209                self.case_id
210            )));
211        }
212        let mut features = HashSet::new();
213        if self
214            .features
215            .iter()
216            .any(|feature| !features.insert(feature))
217        {
218            return Err(CensusError::new(format!(
219                "case '{}' contains duplicate feature IDs",
220                self.case_id
221            )));
222        }
223        Ok(())
224    }
225}
226
227/// The complete census assembled from deterministic shards.
228#[derive(Debug, Clone, PartialEq, Eq)]
229pub struct Census {
230    shards: Vec<CensusShard>,
231}
232
233/// The stable identity of a reviewed census definition.
234#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
235#[serde(rename_all = "camelCase")]
236pub struct CensusIdentity {
237    pub schema_version: u32,
238    pub digest: String,
239    pub shards: Vec<String>,
240}
241
242impl Census {
243    /// Assemble shards in stable shard and case order.
244    pub fn assemble(mut shards: Vec<CensusShard>) -> Result<Self, CensusError> {
245        shards.sort_by(|left, right| left.shard_id.cmp(&right.shard_id));
246        let mut shard_ids = HashSet::new();
247        let mut case_ids = HashSet::new();
248        for shard in &shards {
249            if !shard_ids.insert(shard.shard_id.clone()) {
250                return Err(CensusError::new(format!(
251                    "duplicate census shard '{}'",
252                    shard.shard_id
253                )));
254            }
255            for case in &shard.cases {
256                if !case_ids.insert(case.case_id.clone()) {
257                    return Err(CensusError::new(format!(
258                        "duplicate census case '{}'",
259                        case.case_id
260                    )));
261                }
262            }
263        }
264        Ok(Self { shards })
265    }
266
267    /// Derive the current surface from the canonical catalog, settings table,
268    /// and WIR capability names owned by this crate.
269    pub fn builtin(catalog: &Catalog) -> Result<Self, CensusError> {
270        Self::assemble(vec![
271            catalog_shard(catalog, Kind::Event, "catalog-events")?,
272            catalog_shard(catalog, Kind::Action, "catalog-actions")?,
273            catalog_shard(catalog, Kind::Value, "catalog-values")?,
274            catalog_shard(catalog, Kind::Operator, "catalog-operators")?,
275            catalog_shard(catalog, Kind::Structural, "catalog-structural")?,
276            enum_shard(catalog)?,
277            settings_shard(catalog)?,
278            wir_shard()?,
279            localization_shard(catalog)?,
280            content_id_shard(catalog)?,
281        ])
282    }
283
284    pub fn shards(&self) -> &[CensusShard] {
285        &self.shards
286    }
287
288    pub fn cases(&self) -> impl Iterator<Item = &CensusCase> {
289        self.shards.iter().flat_map(|shard| shard.cases.iter())
290    }
291
292    /// Execute all cases. No result state is dropped or converted to success.
293    /// Cases are independent and the report sorts results by case ID, so the
294    /// run parallelizes over available cores without changing the output.
295    pub fn run(&self, catalog: &Catalog) -> CensusReport {
296        let cases: Vec<(&str, &CensusCase)> = self
297            .shards
298            .iter()
299            .flat_map(|shard| {
300                shard
301                    .cases
302                    .iter()
303                    .map(move |case| (shard.shard_id.as_str(), case))
304            })
305            .collect();
306        let workers = std::thread::available_parallelism()
307            .map(std::num::NonZero::get)
308            .unwrap_or(1)
309            .min(cases.len().max(1));
310        let results: Vec<ConformanceResult> = if workers <= 1 {
311            cases
312                .iter()
313                .map(|(shard_id, case)| run_case(case, shard_id, catalog))
314                .collect()
315        } else {
316            let next = std::sync::atomic::AtomicUsize::new(0);
317            std::thread::scope(|scope| {
318                let handles: Vec<_> = (0..workers)
319                    .map(|_| {
320                        scope.spawn(|| {
321                            let mut worker_results = Vec::new();
322                            loop {
323                                let index = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
324                                let Some((shard_id, case)) = cases.get(index) else {
325                                    break;
326                                };
327                                worker_results.push(run_case(case, shard_id, catalog));
328                            }
329                            worker_results
330                        })
331                    })
332                    .collect();
333                handles
334                    .into_iter()
335                    .flat_map(|handle| handle.join().expect("census worker panicked"))
336                    .collect()
337            })
338        };
339        let mut results = results;
340        results.sort_by(|left, right| left.case_id.cmp(&right.case_id));
341        CensusReport {
342            schema_version: CENSUS_SCHEMA_VERSION,
343            conformance_schema_version: CONFORMANCE_SCHEMA_VERSION,
344            catalog: catalog.identity(),
345            census: self.identity(),
346            results,
347        }
348    }
349
350    /// Return the deterministic identity of this census definition.
351    pub fn identity(&self) -> CensusIdentity {
352        let definition = self
353            .export_json()
354            .expect("census definitions must remain serializable");
355        CensusIdentity {
356            schema_version: CENSUS_IDENTITY_SCHEMA_VERSION,
357            digest: sha256(&definition),
358            shards: self
359                .shards
360                .iter()
361                .map(|shard| shard.shard_id.clone())
362                .collect(),
363        }
364    }
365
366    /// Export shard definitions without executing them.
367    pub fn export_json(&self) -> Result<String, CensusError> {
368        serde_json::to_string_pretty(&self.shards)
369            .map_err(|error| CensusError::new(format!("cannot serialize census shards: {error}")))
370    }
371}
372
373/// Machine-readable output from a census run.
374#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
375#[serde(rename_all = "camelCase")]
376pub struct CensusReport {
377    pub schema_version: u32,
378    pub conformance_schema_version: u32,
379    pub catalog: workshop_rs::catalog::CatalogIdentity,
380    pub census: CensusIdentity,
381    pub results: Vec<ConformanceResult>,
382}
383
384impl CensusReport {
385    pub fn validate(&self) -> Result<(), CensusError> {
386        let catalog =
387            Catalog::builtin().map_err(|error| CensusError::new(format!("catalog: {error}")))?;
388        self.validate_against(&catalog)
389    }
390
391    pub fn validate_against(&self, catalog: &Catalog) -> Result<(), CensusError> {
392        if self.schema_version != CENSUS_SCHEMA_VERSION {
393            return Err(CensusError::new("unsupported census schema version"));
394        }
395        if self.conformance_schema_version != CONFORMANCE_SCHEMA_VERSION {
396            return Err(CensusError::new("unsupported conformance schema version"));
397        }
398        if self.catalog != catalog.identity() {
399            return Err(CensusError::new(
400                "report catalog identity does not match the loaded catalog",
401            ));
402        }
403        if self.census.schema_version != CENSUS_IDENTITY_SCHEMA_VERSION {
404            return Err(CensusError::new(
405                "unsupported census identity schema version",
406            ));
407        }
408        if !is_sha256_digest(&self.census.digest) {
409            return Err(CensusError::new(
410                "census identity digest must be a SHA-256 hex digest",
411            ));
412        }
413        if self.census.shards.is_empty()
414            || self.census.shards.windows(2).any(|pair| pair[0] >= pair[1])
415        {
416            return Err(CensusError::new(
417                "report shards must be non-empty and strictly sorted",
418            ));
419        }
420        for result in &self.results {
421            result
422                .validate_against(catalog)
423                .map_err(|error| CensusError::new(error.to_string()))?;
424            let matching_shards = self
425                .census
426                .shards
427                .iter()
428                .filter(|shard| {
429                    result
430                        .case_id
431                        .strip_prefix(shard.as_str())
432                        .is_some_and(|rest| rest.starts_with('/'))
433                })
434                .count();
435            if matching_shards != 1 {
436                return Err(CensusError::new(format!(
437                    "result '{}' does not map to exactly one census shard",
438                    result.case_id
439                )));
440            }
441        }
442        Ok(())
443    }
444
445    pub fn to_json(&self) -> Result<String, CensusError> {
446        self.validate()?;
447        serde_json::to_string_pretty(self)
448            .map_err(|error| CensusError::new(format!("cannot serialize census report: {error}")))
449    }
450}
451
452#[derive(Debug, Clone, PartialEq, Eq)]
453pub struct CensusError {
454    pub message: String,
455}
456
457impl CensusError {
458    fn new(message: impl Into<String>) -> Self {
459        Self {
460            message: message.into(),
461        }
462    }
463}
464
465impl std::fmt::Display for CensusError {
466    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
467        formatter.write_str(&self.message)
468    }
469}
470
471impl std::error::Error for CensusError {}
472
473fn validate_name(field: &str, value: &str) -> Result<(), CensusError> {
474    if value.trim().is_empty() || value.chars().any(char::is_control) {
475        Err(CensusError::new(format!(
476            "{field} must be non-empty and printable"
477        )))
478    } else {
479        Ok(())
480    }
481}
482
483fn default_source_locale() -> String {
484    EN_US.to_string()
485}
486
487fn feature(namespace: FeatureNamespace, kind: FeatureKind, name: impl Into<String>) -> FeatureId {
488    FeatureId::new(namespace, kind, name).expect("canonical census feature ID")
489}
490
491fn catalog_feature(kind: Kind, id: &str) -> FeatureId {
492    FeatureId::from_catalog(kind, id).expect("catalog IDs are validated by Catalog::load")
493}
494
495fn catalog_shard(
496    catalog: &Catalog,
497    kind: Kind,
498    shard_id: &str,
499) -> Result<CensusShard, CensusError> {
500    let cases = catalog
501        .entries_of(kind)
502        .map(|entry| {
503            let source = match kind {
504                Kind::Event => event_probe(catalog, entry),
505                Kind::Action => action_probe(catalog, entry),
506                Kind::Value => value_probe(catalog, entry),
507                Kind::Operator => operator_probe(catalog, entry),
508                Kind::Structural => structural_probe(catalog, entry),
509                Kind::Setting => unreachable!("settings use the settings table"),
510                Kind::Enum => unreachable!("enum domains use the enum shard"),
511            };
512            CensusCase::probe(
513                format!("{shard_id}/{}", entry.id),
514                vec![catalog_feature(kind, &entry.id)],
515                source,
516            )
517        })
518        .collect();
519    CensusShard::new(shard_id, cases)
520}
521
522fn enum_shard(catalog: &Catalog) -> Result<CensusShard, CensusError> {
523    enum_member_cases(catalog, "catalog-enums", false, true)
524}
525
526fn content_id_shard(catalog: &Catalog) -> Result<CensusShard, CensusError> {
527    enum_member_cases(catalog, "content-ids", true, false)
528}
529
530fn enum_member_cases(
531    catalog: &Catalog,
532    shard_id: &str,
533    content_only: bool,
534    domain_feature: bool,
535) -> Result<CensusShard, CensusError> {
536    let mut cases = Vec::new();
537    for domain in catalog.enum_domains() {
538        if content_only && !matches!(domain.domain.as_str(), "Hero" | "Map") {
539            continue;
540        }
541        for member in &domain.members {
542            let mut features = Vec::with_capacity(2);
543            if domain_feature {
544                features.push(catalog_feature(Kind::Enum, &domain.domain));
545            }
546            features.push(
547                FeatureId::from_enum_member(&domain.domain, &member.member)
548                    .expect("canonical enum member ID"),
549            );
550            cases.push(CensusCase::probe(
551                format!("{shard_id}/{}/{}", domain.domain, member.member),
552                features,
553                enum_probe(catalog, domain, &member.member),
554            ));
555        }
556    }
557    CensusShard::new(shard_id, cases)
558}
559fn settings_shard(catalog: &Catalog) -> Result<CensusShard, CensusError> {
560    let cases = settings_schema::definitions()
561        .map(|definition| {
562            let path = definition.path().to_string();
563            CensusCase::probe(
564                format!("settings/{path}"),
565                vec![feature(
566                    FeatureNamespace::Settings,
567                    FeatureKind::Setting,
568                    path,
569                )],
570                settings_probe(&definition, catalog),
571            )
572        })
573        .collect();
574    CensusShard::new("settings", cases)
575}
576
577fn wir_shard() -> Result<CensusShard, CensusError> {
578    let cases = CENSUS_CAPABILITIES
579        .iter()
580        .map(|capability| match capability.kind {
581            CensusCapabilityKind::Variable => wir_case(
582                "variables-global",
583                FeatureKind::Variable,
584                capability.name,
585                variables_source(),
586            ),
587            CensusCapabilityKind::PlayerVariable => CensusCase::probe(
588                "wir/variables-player".to_string(),
589                vec![feature(
590                    FeatureNamespace::Wir,
591                    FeatureKind::Variable,
592                    capability.name,
593                )],
594                player_variable_source(),
595            ),
596            CensusCapabilityKind::Subroutine => wir_case(
597                "subroutine",
598                FeatureKind::Subroutine,
599                capability.name,
600                subroutine_source(),
601            ),
602            CensusCapabilityKind::ControlFlow => {
603                let actions = match capability.name {
604                    "if" => "If(True);\n    Wait(0);\nEnd;",
605                    "else-if" => "If(True);\n    Wait(0);\nElse If(False);\n    Wait(0);\nEnd;",
606                    "else" => "If(True);\n    Wait(0);\nElse;\n    Wait(0);\nEnd;",
607                    "while" => "While(True);\n    Wait(0);\nEnd;",
608                    "for-global-variable" => {
609                        "For Global Variable(probe, 0, 1, 1);\n    Wait(0);\nEnd;"
610                    }
611                    _ => unreachable!("unknown WIR control-flow census capability"),
612                };
613                control_flow_case(capability.name, actions)
614            }
615            CensusCapabilityKind::String => CensusCase::probe(
616                "wir/string/custom-string".to_string(),
617                vec![feature(
618                    FeatureNamespace::Wir,
619                    FeatureKind::String,
620                    capability.name,
621                )],
622                rule_source(
623                    "String",
624                    "Set Global Variable(probe, Custom String(\"census\"));",
625                ),
626            )
627            .exercise(),
628        })
629        .collect();
630    CensusShard::new("wir", cases)
631}
632
633fn localization_shard(catalog: &Catalog) -> Result<CensusShard, CensusError> {
634    let mut cases = vec![
635        CensusCase::probe(
636            "localization/en-us-to-zh-cn".to_string(),
637            vec![feature(
638                FeatureNamespace::Localization,
639                FeatureKind::Localization,
640                "en-us-to-zh-cn",
641            )],
642            LOCALIZATION_EN_US_SOURCE.to_string(),
643        ),
644        CensusCase::probe(
645            "localization/zh-cn-to-en-us".to_string(),
646            vec![feature(
647                FeatureNamespace::Localization,
648                FeatureKind::Localization,
649                "zh-cn-to-en-us",
650            )],
651            LOCALIZATION_ZH_CN_SOURCE.to_string(),
652        )
653        .locale(ZH_CN),
654    ];
655    let settings_index = SettingsSpellings::build();
656    for locale in catalog.locales() {
657        for kind in [
658            Kind::Event,
659            Kind::Action,
660            Kind::Value,
661            Kind::Operator,
662            Kind::Structural,
663        ] {
664            for entry in catalog.entries_of(kind) {
665                for (index, spelling) in entry.spellings(locale).iter().enumerate() {
666                    cases.push(
667                        CensusCase::probe(
668                            format!(
669                                "localization/{}/{}/{}/{}",
670                                locale.as_str(),
671                                kind.as_str(),
672                                entry.id,
673                                index
674                            ),
675                            vec![catalog_feature(kind, &entry.id)],
676                            localized_probe(catalog, locale, kind, entry, spelling),
677                        )
678                        .locale(locale.as_str()),
679                    );
680                }
681            }
682        }
683        for domain in catalog.enum_domains() {
684            let domain_spelling = CONSTRUCTOR_DOMAINS
685                .contains(&domain.domain.as_str())
686                .then(|| domain.spelling(locale))
687                .flatten();
688            if let Some(spelling) = domain_spelling {
689                let Some(member) = domain.members.first() else {
690                    continue;
691                };
692                let member_spelling =
693                    localized_member(catalog, &domain.domain, &member.member, locale);
694                cases.push(
695                    CensusCase::probe(
696                        format!(
697                            "localization/{}/enum-domain/{}",
698                            locale.as_str(),
699                            domain.domain
700                        ),
701                        vec![catalog_feature(Kind::Enum, &domain.domain)],
702                        global_probe(catalog, locale, &format!("{spelling}({member_spelling})")),
703                    )
704                    .locale(locale.as_str()),
705                );
706            }
707            for member in &domain.members {
708                for (index, spelling) in member.spellings(locale).iter().enumerate() {
709                    cases.push(
710                        CensusCase::probe(
711                            format!(
712                                "localization/{}/enum/{}/{}/{}",
713                                locale.as_str(),
714                                domain.domain,
715                                member.member,
716                                index
717                            ),
718                            vec![
719                                FeatureId::from_enum_member(&domain.domain, &member.member)
720                                    .expect("canonical enum member ID"),
721                            ],
722                            member_probe(catalog, locale, domain, spelling),
723                        )
724                        .locale(locale.as_str()),
725                    );
726                }
727            }
728        }
729        for entry in catalog.localized_strings() {
730            for (index, spelling) in entry.spellings(locale).iter().enumerate() {
731                let string_call = catalog
732                    .spelling(Kind::Value, locale, "string")
733                    .or_else(|| catalog.spelling(Kind::Value, &Locale::new(EN_US), "string"))
734                    .unwrap_or("string");
735                cases.push(
736                    CensusCase::probe(
737                        format!(
738                            "localization/{}/localized-string/{}/{}",
739                            locale.as_str(),
740                            entry.id,
741                            index
742                        ),
743                        vec![feature(
744                            FeatureNamespace::Localization,
745                            FeatureKind::String,
746                            entry.id.clone(),
747                        )],
748                        global_probe(catalog, locale, &format!("{string_call}({spelling})")),
749                    )
750                    .locale(locale.as_str()),
751                );
752            }
753        }
754        for (row, name) in settings_schema::localized_setting_names()
755            .iter()
756            .enumerate()
757        {
758            if !name.locale.eq_ignore_ascii_case(locale.as_str()) {
759                continue;
760            }
761            let case_id = format!(
762                "localization/{}/settings/{}/{}",
763                locale.as_str(),
764                name.section,
765                row
766            );
767            let feature_id = feature(
768                FeatureNamespace::Settings,
769                FeatureKind::Setting,
770                format!("{}/{}", name.section, slug(name.english)),
771            );
772            match localized_settings_probe(catalog, &settings_index, name, locale) {
773                Ok(source) => cases.push(
774                    CensusCase::probe(case_id, vec![feature_id], source).locale(locale.as_str()),
775                ),
776                Err(detail) => cases.push(
777                    CensusCase {
778                        case_id,
779                        features: vec![feature_id],
780                        source_locale: locale.as_str().to_string(),
781                        source: "settings {\n}".to_string(),
782                        reference_source: None,
783                        support: CensusSupport::KnownGap {
784                            detail: format!(
785                                "settings {} {:?} for {}: {detail}",
786                                name.section, name.spelling, name.english
787                            ),
788                        },
789                    }
790                    .locale(locale.as_str()),
791                ),
792            }
793        }
794    }
795    CensusShard::new("localization", cases)
796}
797
798const CONSTRUCTOR_DOMAINS: &[&str] = &["Hero", "Button", "Color", "Map"];
799
800fn slug(name: &str) -> String {
801    name.chars()
802        .map(|character| {
803            if character.is_whitespace() || character == '/' {
804                '-'
805            } else {
806                character
807            }
808        })
809        .collect()
810}
811
812fn localized_spelling(catalog: &Catalog, kind: Kind, locale: &Locale, id: &str) -> String {
813    catalog
814        .spelling(kind, locale, id)
815        .or_else(|| catalog.spelling(kind, &Locale::new(EN_US), id))
816        .unwrap_or(id)
817        .to_string()
818}
819
820fn localized_member(catalog: &Catalog, domain: &str, member: &str, locale: &Locale) -> String {
821    catalog
822        .enum_spelling(domain, locale, member)
823        .or_else(|| catalog.enum_spelling(domain, &Locale::new(EN_US), member))
824        .unwrap_or(member)
825        .to_string()
826}
827
828fn probe_filler(catalog: &Catalog, locale: &Locale, entry: &CatalogEntry, index: usize) -> String {
829    if let Some(operation) = entry
830        .param_content(index)
831        .and_then(|content| content.operations.first())
832    {
833        return localized_spelling(catalog, Kind::Operator, locale, operation).to_string();
834    }
835    if let Some(domain) = entry.param_domain(index) {
836        let member = catalog
837            .enum_domain(domain)
838            .and_then(|domain| domain.members.first())
839            .map(|member| member.member.as_str())
840            .unwrap_or("ALL");
841        let spelling = localized_member(catalog, domain, member, locale);
842        if CONSTRUCTOR_DOMAINS.contains(&domain) {
843            let domain_spelling = catalog
844                .enum_domain(domain)
845                .and_then(|domain| domain.spelling(locale))
846                .unwrap_or(domain);
847            return format!("{domain_spelling}({spelling})");
848        }
849        return spelling;
850    }
851    if let Some(default) = entry.param_default(index) {
852        return param_default_filler(catalog, locale, default);
853    }
854    match entry.param_type(index) {
855        Some("Variable") => "probe".to_string(),
856        Some("Subroutine") | Some("Subroutines") => "probe".to_string(),
857        Some("Bool") => localized_spelling(catalog, Kind::Value, locale, "true"),
858        Some("Hero") => {
859            let member = catalog
860                .enum_domain("Hero")
861                .and_then(|domain| domain.members.first())
862                .map(|member| member.member.as_str())
863                .unwrap_or("ANA");
864            localized_member(catalog, "Hero", member, locale)
865        }
866        Some("String") => {
867            let custom_string = localized_spelling(catalog, Kind::Value, locale, "customString");
868            format!("{custom_string}(\"x\")")
869        }
870        Some(kind) if kind.contains("Player") || kind.contains("EntityId") => {
871            localized_spelling(catalog, Kind::Value, locale, "eventPlayer")
872        }
873        _ => "0".to_string(),
874    }
875}
876
877fn param_default_filler(catalog: &Catalog, locale: &Locale, default: &str) -> String {
878    if let Some((domain, member)) = default.split_once('.') {
879        let spelling = localized_member(catalog, domain, member, locale);
880        if CONSTRUCTOR_DOMAINS.contains(&domain) {
881            let domain_spelling = catalog
882                .enum_domain(domain)
883                .and_then(|domain| domain.spelling(locale))
884                .unwrap_or(domain);
885            return format!("{domain_spelling}({spelling})");
886        }
887        return spelling;
888    }
889    if catalog.entry(Kind::Value, default).is_some() {
890        return localized_spelling(catalog, Kind::Value, locale, default);
891    }
892    if let Some(spelling) = catalog.localized_string_spelling(locale, default) {
893        return spelling.to_string();
894    }
895    default.to_string()
896}
897
898fn probe_args(catalog: &Catalog, locale: &Locale, entry: &CatalogEntry) -> String {
899    (0..entry.param_count())
900        .map(|index| probe_filler(catalog, locale, entry, index))
901        .collect::<Vec<_>>()
902        .join(", ")
903}
904
905fn probe_rule(catalog: &Catalog, locale: &Locale, actions: &str) -> String {
906    let variables = localized_spelling(catalog, Kind::Structural, locale, "variables");
907    let global = localized_spelling(catalog, Kind::Structural, locale, "global");
908    let player = localized_spelling(catalog, Kind::Structural, locale, "player");
909    let subroutines = localized_spelling(catalog, Kind::Structural, locale, "subroutines");
910    let rule = localized_spelling(catalog, Kind::Structural, locale, "rule");
911    let event = localized_spelling(catalog, Kind::Structural, locale, "event");
912    let ongoing_global = localized_spelling(catalog, Kind::Event, locale, "global");
913    let actions_section = localized_spelling(catalog, Kind::Structural, locale, "actions");
914    format!(
915        "{variables} {{\n    {global}:\n        0: probe\n    {player}:\n        0: probe\n}}\n\n{subroutines} {{\n    0: probe\n}}\n\n{rule} (\"probe\") {{\n    {event} {{\n        {ongoing_global};\n    }}\n    {actions_section} {{\n        {actions}\n    }}\n}}\n"
916    )
917}
918
919fn global_probe(catalog: &Catalog, locale: &Locale, operand: &str) -> String {
920    let set_global = localized_spelling(catalog, Kind::Structural, locale, "setGlobalVariable");
921    probe_rule(catalog, locale, &format!("{set_global}(probe, {operand});"))
922}
923
924fn localized_probe(
925    catalog: &Catalog,
926    locale: &Locale,
927    kind: Kind,
928    entry: &CatalogEntry,
929    spelling: &str,
930) -> String {
931    match kind {
932        Kind::Event => {
933            let extra = match entry.id.as_str() {
934                "global" => String::new(),
935                "subroutine" => "        probe;\n".to_string(),
936                _ => format!(
937                    "        {};\n        {};\n",
938                    localized_member(catalog, "EventTeam", "ALL", locale),
939                    localized_member(catalog, "EventPlayer", "ALL", locale),
940                ),
941            };
942            let subroutines = localized_spelling(catalog, Kind::Structural, locale, "subroutines");
943            let rule = localized_spelling(catalog, Kind::Structural, locale, "rule");
944            let event = localized_spelling(catalog, Kind::Structural, locale, "event");
945            let actions = localized_spelling(catalog, Kind::Structural, locale, "actions");
946            let wait = localized_spelling(catalog, Kind::Action, locale, "wait");
947            format!(
948                "{subroutines} {{\n    0: probe\n}}\n\n{rule} (\"e\") {{\n    {event} {{\n        {spelling};\n{extra}    }}\n    {actions} {{\n        {wait};\n    }}\n}}\n"
949            )
950        }
951        Kind::Action => {
952            let call = if entry.param_count() == 0 {
953                format!("{spelling};")
954            } else {
955                format!("{spelling}({});", probe_args(catalog, locale, entry))
956            };
957            let call = if entry.id.starts_with("__for") {
958                let wait = localized_spelling(catalog, Kind::Action, locale, "wait");
959                let end = localized_spelling(catalog, Kind::Structural, locale, "end");
960                format!("{call}\n        {wait}(0);\n    {end};")
961            } else {
962                call
963            };
964            probe_rule(catalog, locale, &call)
965        }
966        Kind::Value => {
967            let operand = match entry.id.as_str() {
968                "string" => {
969                    let hello = catalog
970                        .localized_string_spelling(locale, "hello")
971                        .or_else(|| catalog.localized_string_spelling(&Locale::new(EN_US), "hello"))
972                        .unwrap_or("Hello");
973                    format!("{spelling}({hello})")
974                }
975                "compare" => {
976                    let eq = localized_spelling(catalog, Kind::Operator, locale, "==");
977                    format!("{spelling}(1, {eq}, 1)")
978                }
979                _ if entry.param_count() == 0 => spelling.to_string(),
980                _ => format!("{spelling}({})", probe_args(catalog, locale, entry)),
981            };
982            global_probe(catalog, locale, &operand)
983        }
984        Kind::Operator => {
985            if matches!(entry.id.as_str(), "==" | "!=" | "<" | "<=" | ">" | ">=") {
986                let if_ = localized_spelling(catalog, Kind::Structural, locale, "if");
987                let wait = localized_spelling(catalog, Kind::Action, locale, "wait");
988                let end = localized_spelling(catalog, Kind::Structural, locale, "end");
989                probe_rule(
990                    catalog,
991                    locale,
992                    &format!("{if_}(1 {spelling} 1);\n        {wait}(0);\n    {end};"),
993                )
994            } else {
995                let modify =
996                    localized_spelling(catalog, Kind::Structural, locale, "modifyGlobalVariable");
997                probe_rule(catalog, locale, &format!("{modify}(probe, {spelling}, 1);"))
998            }
999        }
1000        Kind::Structural => structural_spelling_probe(catalog, locale, &entry.id, spelling),
1001        _ => unreachable!("settings and enum spellings use their own probes"),
1002    }
1003}
1004
1005fn structural_spelling_probe(
1006    catalog: &Catalog,
1007    locale: &Locale,
1008    id: &str,
1009    spelling: &str,
1010) -> String {
1011    let kw = |name: &str| localized_spelling(catalog, Kind::Structural, locale, name);
1012    let wait = localized_spelling(catalog, Kind::Action, locale, "wait");
1013    let true_ = localized_spelling(catalog, Kind::Value, locale, "true");
1014    let ongoing_global = localized_spelling(catalog, Kind::Event, locale, "global");
1015    let event_player = localized_spelling(catalog, Kind::Value, locale, "eventPlayer");
1016    let end = kw("end");
1017    let block = |head: &str| format!("{head}\n        {wait}(0);\n    {end};");
1018    match id {
1019        "settings" => format!("{spelling} {{\n}}\n"),
1020        "workshop" => format!("{} {{\n    {spelling} {{\n    }}\n}}\n", kw("settings")),
1021        "variables" => format!(
1022            "{spelling} {{\n    {}:\n        0: probe\n}}\n",
1023            kw("global")
1024        ),
1025        "global" | "player" => {
1026            format!(
1027                "{} {{\n    {spelling}:\n        0: probe\n}}\n",
1028                kw("variables")
1029            )
1030        }
1031        "subroutines" => format!("{spelling} {{\n    0: probe\n}}\n"),
1032        "rule" => format!(
1033            "{spelling} (\"r\") {{\n    {} {{\n        {ongoing_global};\n    }}\n    {} {{\n        {wait};\n    }}\n}}\n",
1034            kw("event"),
1035            kw("actions"),
1036        ),
1037        "event" => format!(
1038            "{} (\"r\") {{\n    {spelling} {{\n        {ongoing_global};\n    }}\n    {} {{\n        {wait};\n    }}\n}}\n",
1039            kw("rule"),
1040            kw("actions"),
1041        ),
1042        "conditions" => {
1043            let equals = localized_spelling(catalog, Kind::Operator, locale, "==");
1044            format!(
1045                "{} (\"c\") {{\n    {} {{\n        {ongoing_global};\n    }}\n    {spelling} {{\n        {true_} {equals} {true_};\n    }}\n    {} {{\n        {wait};\n    }}\n}}\n",
1046                kw("rule"),
1047                kw("event"),
1048                kw("actions"),
1049            )
1050        }
1051        "actions" => format!(
1052            "{} (\"r\") {{\n    {} {{\n        {ongoing_global};\n    }}\n    {spelling} {{\n        {wait};\n    }}\n}}\n",
1053            kw("rule"),
1054            kw("event"),
1055        ),
1056        "disabled" => probe_rule(catalog, locale, &format!("{spelling} {wait}(0);")),
1057        "if" => probe_rule(catalog, locale, &block(&format!("{spelling}({true_});"))),
1058        "elseIf" => {
1059            let if_ = kw("if");
1060            probe_rule(
1061                catalog,
1062                locale,
1063                &format!(
1064                    "{if_}({true_});\n        {wait}(0);\n    {spelling}({true_});\n        {wait}(0);\n    {end};"
1065                ),
1066            )
1067        }
1068        "else" => {
1069            let if_ = kw("if");
1070            probe_rule(
1071                catalog,
1072                locale,
1073                &format!(
1074                    "{if_}({true_});\n        {wait}(0);\n    {spelling};\n        {wait}(0);\n    {end};"
1075                ),
1076            )
1077        }
1078        "end" => {
1079            let if_ = kw("if");
1080            probe_rule(
1081                catalog,
1082                locale,
1083                &format!("{if_}({true_});\n        {wait}(0);\n    {spelling};"),
1084            )
1085        }
1086        "while" => probe_rule(catalog, locale, &block(&format!("{spelling}({true_});"))),
1087        "forGlobalVariable" => probe_rule(
1088            catalog,
1089            locale,
1090            &block(&format!("{spelling}(probe, 0, 1, 1);")),
1091        ),
1092        "forPlayerVariable" => probe_rule(
1093            catalog,
1094            locale,
1095            &block(&format!("{spelling}({event_player}, probe, 0, 1, 1);")),
1096        ),
1097        "setGlobalVariable" => probe_rule(catalog, locale, &format!("{spelling}(probe, 1);")),
1098        "modifyGlobalVariable" => {
1099            let add = localized_spelling(catalog, Kind::Operator, locale, "add");
1100            probe_rule(catalog, locale, &format!("{spelling}(probe, {add}, 1);"))
1101        }
1102        "setPlayerVariable" => probe_rule(
1103            catalog,
1104            locale,
1105            &format!("{spelling}({event_player}, probe, 1);"),
1106        ),
1107        "modifyPlayerVariable" => {
1108            let add = localized_spelling(catalog, Kind::Operator, locale, "add");
1109            probe_rule(
1110                catalog,
1111                locale,
1112                &format!("{spelling}({event_player}, probe, {add}, 1);"),
1113            )
1114        }
1115        "callSubroutine" => probe_rule(catalog, locale, &format!("{spelling}(probe);")),
1116        _ => probe_rule(catalog, locale, &format!("{spelling};")),
1117    }
1118}
1119
1120fn member_probe(catalog: &Catalog, locale: &Locale, domain: &EnumDomain, spelling: &str) -> String {
1121    if CONSTRUCTOR_DOMAINS.contains(&domain.domain.as_str()) {
1122        let domain_spelling = domain.spelling(locale).unwrap_or(&domain.domain);
1123        return global_probe(catalog, locale, &format!("{domain_spelling}({spelling})"));
1124    }
1125    if domain.domain == "EventTeam" || domain.domain == "EventPlayer" {
1126        let event = localized_spelling(catalog, Kind::Event, locale, "eachPlayer");
1127        let other = if domain.domain == "EventTeam" {
1128            localized_member(catalog, "EventPlayer", "ALL", locale)
1129        } else {
1130            localized_member(catalog, "EventTeam", "ALL", locale)
1131        };
1132        let (team, player) = if domain.domain == "EventTeam" {
1133            (spelling.to_string(), other)
1134        } else {
1135            (other, spelling.to_string())
1136        };
1137        let rule = localized_spelling(catalog, Kind::Structural, locale, "rule");
1138        let event_kw = localized_spelling(catalog, Kind::Structural, locale, "event");
1139        let actions = localized_spelling(catalog, Kind::Structural, locale, "actions");
1140        let wait = localized_spelling(catalog, Kind::Action, locale, "wait");
1141        return format!(
1142            "{rule} (\"e\") {{\n    {event_kw} {{\n        {event};\n        {team};\n        {player};\n    }}\n    {actions} {{\n        {wait};\n    }}\n}}\n"
1143        );
1144    }
1145    let host = [Kind::Value, Kind::Action]
1146        .into_iter()
1147        .flat_map(|kind| catalog.entries_of(kind))
1148        .filter(|entry| {
1149            (0..entry.param_count()).any(|index| entry.param_domain(index) == Some(&domain.domain))
1150        })
1151        .min_by_key(|entry| entry.required_param_count());
1152    let Some(host) = host else {
1153        return global_probe(catalog, locale, spelling);
1154    };
1155    let target = (0..host.param_count())
1156        .find(|index| host.param_domain(*index) == Some(&domain.domain))
1157        .expect("host was selected for carrying this domain");
1158    let mut call_args: Vec<String> = (0..host.param_count())
1159        .map(|index| probe_filler(catalog, locale, host, index))
1160        .collect();
1161    call_args[target] = spelling.to_string();
1162    let host_spelling = localized_spelling(catalog, host.kind, locale, &host.id);
1163    let call = format!("{host_spelling}({})", call_args.join(", "));
1164    match host.kind {
1165        Kind::Value => global_probe(catalog, locale, &call),
1166        _ => probe_rule(catalog, locale, &format!("{call};")),
1167    }
1168}
1169
1170struct SettingsSpellings {
1171    by_label: HashMap<String, Vec<SettingDefinition>>,
1172    by_member: HashMap<String, Vec<SettingDefinition>>,
1173    names: HashMap<(String, String, String), String>,
1174}
1175
1176impl SettingsSpellings {
1177    fn build() -> Self {
1178        let mut by_label: HashMap<String, Vec<SettingDefinition>> = HashMap::new();
1179        let mut by_member: HashMap<String, Vec<SettingDefinition>> = HashMap::new();
1180        for definition in settings_schema::definitions() {
1181            by_label
1182                .entry(definition.presentation().english_name.to_string())
1183                .or_default()
1184                .push(definition.clone());
1185            for member in definition.enum_members() {
1186                by_member
1187                    .entry(member.english_name().to_string())
1188                    .or_default()
1189                    .push(definition.clone());
1190            }
1191        }
1192        let mut names = HashMap::new();
1193        for row in settings_schema::localized_setting_names() {
1194            names.insert(
1195                (
1196                    row.locale.to_string(),
1197                    row.section.to_string(),
1198                    row.english.to_string(),
1199                ),
1200                row.spelling.to_string(),
1201            );
1202        }
1203        Self {
1204            by_label,
1205            by_member,
1206            names,
1207        }
1208    }
1209
1210    fn name(&self, locale: &str, section: &str, english: &str) -> String {
1211        self.lookup(locale, section, english)
1212            .or_else(|| self.lookup(EN_US, section, english))
1213            .unwrap_or(english)
1214            .to_string()
1215    }
1216
1217    fn lookup(&self, locale: &str, section: &str, english: &str) -> Option<&str> {
1218        self.names
1219            .get(&(locale.to_string(), section.to_string(), english.to_string()))
1220            .map(String::as_str)
1221    }
1222}
1223
1224fn settings_probe_hero(definition: &SettingDefinition, english: &str) -> Option<Option<String>> {
1225    if !definition.path().contains(".<hero>.") && !definition.path().ends_with(".<hero>") {
1226        return Some(None);
1227    }
1228    let data = gameplay::data::builtin_ref().ok()?;
1229    let heroes = data.query().heroes().to_vec();
1230    let hero_ids: Vec<String> = match definition.target_kind() {
1231        SettingTargetKind::HeroAbility { slot, variant } => heroes
1232            .iter()
1233            .filter(|hero| {
1234                data.query()
1235                    .ability_name(hero.id().as_str(), slot.as_str(), variant.as_ref(), EN_US)
1236                    .is_ok()
1237            })
1238            .map(|hero| hero.id().as_str().to_string())
1239            .collect(),
1240        _ => heroes
1241            .iter()
1242            .map(|hero| hero.id().as_str().to_string())
1243            .collect(),
1244    };
1245    let mut matching = Vec::new();
1246    let mut any = Vec::new();
1247    for id in hero_ids {
1248        let target = match definition.target_kind() {
1249            SettingTargetKind::HeroAbility { slot, variant } => SettingTarget::HeroAbility {
1250                team: None,
1251                hero: HeroId::new(id.as_str()),
1252                slot,
1253                variant,
1254            },
1255            _ => SettingTarget::Hero {
1256                team: None,
1257                hero: HeroId::new(id.as_str()),
1258            },
1259        };
1260        let emitted = definition
1261            .localized_name(EN_US, &target)
1262            .ok()
1263            .flatten()
1264            .map(str::to_string);
1265        any.push(id.clone());
1266        if emitted.as_deref() == Some(english) {
1267            matching.push(id);
1268        }
1269    }
1270    matching.into_iter().chain(any).next().map(Some)
1271}
1272
1273fn substitute_template(
1274    definition: &SettingDefinition,
1275    spelling: &str,
1276    hero: Option<&str>,
1277    locale: &str,
1278) -> Option<String> {
1279    if !spelling.contains("%1$s") {
1280        return Some(spelling.to_string());
1281    }
1282    let SettingTargetKind::HeroAbility { slot, variant } = definition.target_kind() else {
1283        return None;
1284    };
1285    let ability = gameplay::data::builtin_ref()
1286        .ok()?
1287        .query()
1288        .ability_name(hero?, slot.as_str(), variant.as_ref(), locale)
1289        .ok()?
1290        .to_string();
1291    Some(spelling.replace("%1$s", &ability))
1292}
1293
1294fn localized_settings_context(
1295    catalog: &Catalog,
1296    index: &SettingsSpellings,
1297    locale: &Locale,
1298    definition: &SettingDefinition,
1299    leaf: &str,
1300    hero: Option<&str>,
1301) -> String {
1302    let hero_name = hero
1303        .and_then(|id| {
1304            gameplay::data::builtin_ref()
1305                .ok()?
1306                .query()
1307                .heroes()
1308                .iter()
1309                .find(|hero| hero.id().as_str() == id)
1310                .and_then(|hero| hero.name().value().get(EN_US).map(str::to_string))
1311        })
1312        .map(|english| index.name(locale.as_str(), "heroes", &english))
1313        .unwrap_or_else(|| index.name(locale.as_str(), "heroes", "Ana"));
1314    let settings = localized_spelling(catalog, Kind::Structural, locale, "settings");
1315    let mut lines = vec![format!("{settings} {{")];
1316    let mut depth = 1;
1317    let parts: Vec<_> = definition.path().split('.').collect();
1318    for (part_index, part) in parts.iter().take(parts.len() - 1).enumerate() {
1319        let name = match *part {
1320            "gamemodes" => index.name(locale.as_str(), "namespaces", "modes"),
1321            "heroes" => index.name(locale.as_str(), "namespaces", "heroes"),
1322            "<team>" | "general" => index.name(locale.as_str(), "teams", "General"),
1323            "<hero>" => hero_name.clone(),
1324            value if part_index == 1 && parts.first() == Some(&"gamemodes") => {
1325                let english = catalog_enum_spelling(catalog, "Gamemode", value)
1326                    .unwrap_or_else(|| value.to_string());
1327                index.name(locale.as_str(), "modes", &english)
1328            }
1329            value => index.name(locale.as_str(), "labels", value),
1330        };
1331        lines.push(format!("{}{} {{", "    ".repeat(depth), name));
1332        depth += 1;
1333    }
1334    lines.push(format!("{}{leaf}", "    ".repeat(depth)));
1335    while depth > 1 {
1336        depth -= 1;
1337        lines.push(format!("{}{}", "    ".repeat(depth), "}"));
1338    }
1339    lines.push("}".to_string());
1340    lines.join("\n")
1341}
1342
1343fn leaf_value(
1344    index: &SettingsSpellings,
1345    locale: &Locale,
1346    definition: &SettingDefinition,
1347) -> String {
1348    match definition.domain() {
1349        SettingValueDomain::PresenceOnly => String::new(),
1350        SettingValueDomain::String => ": \"x\"".to_string(),
1351        SettingValueDomain::Boolean | SettingValueDomain::Enum { .. } => {
1352            let member = definition
1353                .enum_members()
1354                .next()
1355                .map(|member| {
1356                    index
1357                        .lookup(locale.as_str(), "enums", member.english_name())
1358                        .or_else(|| index.lookup(locale.as_str(), "tokens", member.english_name()))
1359                        .unwrap_or(member.english_name())
1360                        .to_string()
1361                })
1362                .unwrap_or_else(|| index.name(locale.as_str(), "tokens", "On"));
1363            format!(": {member}")
1364        }
1365        SettingValueDomain::Number(_) => ": 1".to_string(),
1366        SettingValueDomain::Percent(_) => ": 100%".to_string(),
1367        SettingValueDomain::HeroList | SettingValueDomain::MapList => " {\n}".to_string(),
1368        _ => ": 0".to_string(),
1369    }
1370}
1371
1372fn localized_settings_probe(
1373    catalog: &Catalog,
1374    index: &SettingsSpellings,
1375    name: &settings_schema::LocalizedSettingName,
1376    locale: &Locale,
1377) -> Result<String, String> {
1378    let english = name.english;
1379    let spelling = name.spelling;
1380    let loc = locale.as_str();
1381    let settings = localized_spelling(catalog, Kind::Structural, locale, "settings");
1382    let modes = index.name(loc, "namespaces", "modes");
1383    let heroes = index.name(loc, "namespaces", "heroes");
1384    let general = index.name(loc, "teams", "General");
1385    let assault = index.name(loc, "modes", "Assault");
1386    match name.section {
1387        "namespaces" => Ok(format!("{settings} {{\n    {spelling} {{\n    }}\n}}")),
1388        "modes" => Ok(format!(
1389            "{settings} {{\n    {modes} {{\n        {spelling} {{\n        }}\n    }}\n}}"
1390        )),
1391        "teams" => Ok(format!(
1392            "{settings} {{\n    {heroes} {{\n        {spelling} {{\n            {} {{\n            }}\n        }}\n    }}\n}}",
1393            index.name(loc, "heroes", "Ana")
1394        )),
1395        "heroes" => Ok(format!(
1396            "{settings} {{\n    {heroes} {{\n        {general} {{\n            {spelling} {{\n            }}\n        }}\n    }}\n}}"
1397        )),
1398        "maps" => Ok(format!(
1399            "{settings} {{\n    {modes} {{\n        {assault} {{\n            {} {{\n                {spelling}\n            }}\n        }}\n    }}\n}}",
1400            index.name(loc, "labels", "enabled maps")
1401        )),
1402        "tokens" => match english {
1403            "disabled" => Ok(format!(
1404                "{settings} {{\n    {modes} {{\n        {spelling} {assault} {{\n        }}\n    }}\n}}"
1405            )),
1406            _ => Ok(format!(
1407                "{settings} {{\n    {modes} {{\n        {assault} {{\n            {}: {spelling}\n        }}\n    }}\n}}",
1408                index.name(loc, "labels", "Competitive Rules")
1409            )),
1410        },
1411        "labels" => {
1412            let Some(defs) = index.by_label.get(english) else {
1413                return Err(format!("no settings definition named {english:?}"));
1414            };
1415            let mut reasons = Vec::new();
1416            for definition in defs {
1417                let hero = settings_probe_hero(definition, english);
1418                let leaf = match substitute_template(
1419                    definition,
1420                    spelling,
1421                    hero.as_ref().and_then(|hero| hero.as_deref()),
1422                    loc,
1423                ) {
1424                    Some(leaf) => leaf,
1425                    None => {
1426                        reasons.push("template needs a hero-ability context".to_string());
1427                        continue;
1428                    }
1429                };
1430                return Ok(localized_settings_context(
1431                    catalog,
1432                    index,
1433                    locale,
1434                    definition,
1435                    &format!("{leaf}{}", leaf_value(index, locale, definition)),
1436                    hero.as_ref().and_then(|hero| hero.as_deref()),
1437                ));
1438            }
1439            Err(reasons
1440                .into_iter()
1441                .next()
1442                .unwrap_or_else(|| "no probe context".to_string()))
1443        }
1444        "enums" => {
1445            let Some(defs) = index.by_member.get(english) else {
1446                return Err(format!("no settings definition takes member {english:?}"));
1447            };
1448            let definition = &defs[0];
1449            let hero = settings_probe_hero(definition, definition.presentation().english_name);
1450            let label = index.name(loc, "labels", definition.presentation().english_name);
1451            Ok(localized_settings_context(
1452                catalog,
1453                index,
1454                locale,
1455                definition,
1456                &format!("{label}: {spelling}"),
1457                hero.as_ref().and_then(|hero| hero.as_deref()),
1458            ))
1459        }
1460        other => Err(format!("unhandled settings section {other:?}")),
1461    }
1462}
1463
1464fn wir_case(case_id: &str, kind: FeatureKind, name: &str, source: String) -> CensusCase {
1465    CensusCase::probe(
1466        format!("wir/{case_id}"),
1467        vec![feature(FeatureNamespace::Wir, kind, name)],
1468        source,
1469    )
1470    .exercise()
1471}
1472
1473fn control_flow_case(name: &str, actions: &str) -> CensusCase {
1474    CensusCase::probe(
1475        format!("wir/control-flow/{name}"),
1476        vec![feature(
1477            FeatureNamespace::Wir,
1478            FeatureKind::ControlFlow,
1479            name,
1480        )],
1481        rule_source(name, actions),
1482    )
1483}
1484
1485fn generated_probe_support() -> CensusSupport {
1486    CensusSupport::Inconclusive {
1487        detail: "generated probe has no independently recorded expected result".to_string(),
1488    }
1489}
1490
1491fn rule_source(name: &str, actions: &str) -> String {
1492    format!(
1493        "variables {{\n    global:\n        0: probe\n}}\n\nrule (\"{name}\") {{\n    event {{\n        Ongoing - Global;\n    }}\n    actions {{\n        {actions}\n    }}\n}}\n"
1494    )
1495}
1496
1497fn variables_source() -> String {
1498    "variables {\n    global:\n        0: probe\n}\n\nrule (\"Global variable\") {\n    event {\n        Ongoing - Global;\n    }\n    actions {\n        Set Global Variable(probe, 1);\n    }\n}\n"
1499        .to_string()
1500}
1501
1502fn player_variable_source() -> String {
1503    "variables {\n    player:\n        0: probe\n}\n\nrule (\"Player variable\") {\n    event {\n        Ongoing - Each Player;\n        All;\n        All;\n    }\n    actions {\n        Set Player Variable(Event Player, probe, 1);\n    }\n}\n"
1504        .to_string()
1505}
1506
1507fn subroutine_source() -> String {
1508    "subroutines {\n    0: probe\n}\n\nrule (\"Subroutine\") {\n    event {\n        Subroutine;\n        probe;\n    }\n    actions {\n        Call Subroutine(probe);\n    }\n}\n"
1509        .to_string()
1510}
1511
1512fn event_probe(catalog: &Catalog, entry: &CatalogEntry) -> String {
1513    let spelling = catalog
1514        .spelling(Kind::Event, &Locale::new(EN_US), &entry.id)
1515        .unwrap_or(&entry.id);
1516    let filters = if matches!(entry.id.as_str(), "global" | "subroutine") {
1517        String::new()
1518    } else {
1519        "        All;\n        All;\n".to_string()
1520    };
1521    let subroutine = if entry.id == "subroutine" {
1522        "        probe;\n"
1523    } else {
1524        ""
1525    };
1526    format!(
1527        "subroutines {{\n    0: probe\n}}\n\nrule (\"Event\") {{\n    event {{\n        {spelling};\n{filters}{subroutine}    }}\n    actions {{\n        Wait;\n    }}\n}}\n"
1528    )
1529}
1530
1531fn action_probe(catalog: &Catalog, entry: &CatalogEntry) -> String {
1532    let spelling = catalog
1533        .spelling(Kind::Action, &Locale::new(EN_US), &entry.id)
1534        .unwrap_or(&entry.id);
1535    let call = if matches!(
1536        entry.id.as_str(),
1537        "chasePlayerVariableAtRate" | "chasePlayerVariableOverTime"
1538    ) {
1539        format!("{spelling}(Event Player, probe, 0, 1, 0);")
1540    } else {
1541        format!("{spelling};")
1542    };
1543    rule_source("Action", &call)
1544}
1545
1546fn value_probe(catalog: &Catalog, entry: &CatalogEntry) -> String {
1547    let spelling = catalog
1548        .spelling(Kind::Value, &Locale::new(EN_US), &entry.id)
1549        .unwrap_or(&entry.id);
1550    rule_source("Value", &format!("Set Global Variable(probe, {spelling});"))
1551}
1552
1553fn operator_probe(catalog: &Catalog, entry: &CatalogEntry) -> String {
1554    let spelling = catalog
1555        .spelling(Kind::Operator, &Locale::new(EN_US), &entry.id)
1556        .unwrap_or(&entry.id);
1557    rule_source(
1558        "Operator",
1559        &format!("If(1 {spelling} 1);\n    Wait(0);\nEnd;"),
1560    )
1561}
1562
1563fn structural_probe(catalog: &Catalog, entry: &CatalogEntry) -> String {
1564    let spelling = catalog
1565        .spelling(Kind::Structural, &Locale::new(EN_US), &entry.id)
1566        .unwrap_or(&entry.id);
1567    let actions = match entry.id.as_str() {
1568        "if" => format!("{spelling}(True);\n    Wait(0);\nEnd;"),
1569        "elseIf" => format!("If(True);\n    Wait(0);\n{spelling}(False);\n    Wait(0);\nEnd;"),
1570        "else" => format!("If(True);\n    Wait(0);\n{spelling};\n    Wait(0);\nEnd;"),
1571        "end" => format!("If(True);\n    Wait(0);\n{spelling};"),
1572        "while" => format!("{spelling}(True);\n    Wait(0);\nEnd;"),
1573        "forGlobalVariable" => format!("{spelling}(probe, 0, 1, 1);\n    Wait(0);\nEnd;"),
1574        "setGlobalVariable" => format!("{spelling}(probe, 1);"),
1575        "modifyGlobalVariable" => format!("{spelling}(probe, Add, 1);"),
1576        "setPlayerVariable" => format!("{spelling}(Event Player, probe, 1);"),
1577        "modifyPlayerVariable" => format!("{spelling}(Event Player, probe, Add, 1);"),
1578        "callSubroutine" => format!("{spelling}(probe);"),
1579        _ => format!("{spelling};"),
1580    };
1581    let prefix = match entry.id.as_str() {
1582        "setPlayerVariable" | "modifyPlayerVariable" => {
1583            "variables {\n    player:\n        0: probe\n}\n\n"
1584        }
1585        "callSubroutine" => "subroutines {\n    0: probe\n}\n\n",
1586        _ => "",
1587    };
1588    format!("{prefix}{}", rule_source("Structural", &actions))
1589}
1590
1591fn enum_probe(catalog: &Catalog, domain: &EnumDomain, member: &str) -> String {
1592    let locale = Locale::new(EN_US);
1593    let domain_spelling = catalog
1594        .spelling(Kind::Value, &locale, &domain.domain)
1595        .unwrap_or(&domain.domain);
1596    let member_spelling = catalog
1597        .enum_spelling(&domain.domain, &locale, member)
1598        .unwrap_or(member);
1599    let operand = if CONSTRUCTOR_DOMAINS.contains(&domain.domain.as_str()) {
1600        format!("{domain_spelling}({member_spelling})")
1601    } else {
1602        member_spelling.to_string()
1603    };
1604    rule_source("Enum", &format!("Set Global Variable(probe, {operand});"))
1605}
1606
1607fn settings_probe(definition: &SettingDefinition, catalog: &Catalog) -> String {
1608    let mut lines = vec!["settings {".to_string()];
1609    let mut depth = 1;
1610    let parts: Vec<_> = definition.path().split('.').collect();
1611    for (index, part) in parts.iter().enumerate() {
1612        let name = match *part {
1613            "gamemodes" => "modes".to_string(),
1614            "heroes" => "heroes".to_string(),
1615            "<team>" => "General".to_string(),
1616            "<hero>" => {
1617                catalog_enum_spelling(catalog, "Hero", "mei").unwrap_or_else(|| "Mei".to_string())
1618            }
1619            "general" => "General".to_string(),
1620            value if index == 1 && parts.first() == Some(&"gamemodes") => {
1621                mode_spelling(catalog, value)
1622            }
1623            value => value.to_string(),
1624        };
1625        lines.push(format!("{}{} {{", "    ".repeat(depth), name));
1626        depth += 1;
1627    }
1628    let indent = "    ".repeat(depth);
1629    let name = definition.presentation().english_name;
1630    match definition.domain() {
1631        SettingValueDomain::PresenceOnly => lines.push(format!("{indent}{name}")),
1632        SettingValueDomain::String => lines.push(format!("{indent}{name}: \"census\"")),
1633        SettingValueDomain::Boolean => {
1634            let value = definition
1635                .enum_members()
1636                .next()
1637                .map(|member| member.english_name().to_string())
1638                .unwrap_or_else(|| "On".to_string());
1639            lines.push(format!("{indent}{name}: {value}"));
1640        }
1641        SettingValueDomain::Number(_) => lines.push(format!("{indent}{name}: 1")),
1642        SettingValueDomain::Percent(_) => lines.push(format!("{indent}{name}: 100%")),
1643        SettingValueDomain::Enum { .. } => {
1644            let value = definition
1645                .enum_members()
1646                .next()
1647                .map(|member| member.english_name().to_string())
1648                .unwrap_or_else(|| "Off".to_string());
1649            lines.push(format!("{indent}{name}: {value}"));
1650        }
1651        SettingValueDomain::HeroList | SettingValueDomain::MapList => {
1652            lines.push(format!("{indent}{name} {{"));
1653            lines.push(format!("{indent}}}"));
1654        }
1655        other => unreachable!("census has no probe for settings value domain {other:?}"),
1656    }
1657    while depth > 1 {
1658        depth -= 1;
1659        lines.push(format!("{}{}", "    ".repeat(depth), "}"));
1660    }
1661    lines.push("}".to_string());
1662    lines.join("\n")
1663}
1664
1665fn mode_spelling(catalog: &Catalog, key: &str) -> String {
1666    catalog_enum_spelling(catalog, "Gamemode", key).unwrap_or_else(|| key.to_string())
1667}
1668
1669fn catalog_enum_spelling(catalog: &Catalog, domain: &str, key: &str) -> Option<String> {
1670    let normalize = |value: &str| {
1671        value
1672            .chars()
1673            .filter(|character| character.is_ascii_alphanumeric())
1674            .flat_map(char::to_lowercase)
1675            .collect::<String>()
1676    };
1677    let normalized = normalize(key);
1678    let member = catalog
1679        .enum_domains()
1680        .find(|candidate| candidate.domain == domain)?
1681        .members
1682        .iter()
1683        .find(|candidate| normalize(&candidate.member) == normalized)?;
1684    catalog
1685        .enum_spelling(domain, &Locale::new(EN_US), &member.member)
1686        .map(str::to_string)
1687}
1688
1689fn run_case(case: &CensusCase, shard_id: &str, catalog: &Catalog) -> ConformanceResult {
1690    let source = artifact(
1691        format!("census/{shard_id}/{}.ws", case.case_id),
1692        &case.source,
1693    );
1694    let base = |status, comparison, reason, locale| ConformanceResult {
1695        schema_version: CONFORMANCE_SCHEMA_VERSION,
1696        case_id: case.case_id.clone(),
1697        features: case.features.clone(),
1698        status,
1699        comparison,
1700        source: source.clone(),
1701        catalog: catalog.identity(),
1702        locale,
1703        reason,
1704    };
1705    match &case.support {
1706        CensusSupport::Unsupported { detail } => base(
1707            ConformanceStatus::Unsupported,
1708            not_comparable(),
1709            Some(reason(ReasonCode::Unsupported, detail)),
1710            None,
1711        ),
1712        CensusSupport::KnownGap { detail } => base(
1713            ConformanceStatus::KnownGap,
1714            not_comparable(),
1715            Some(reason(ReasonCode::KnownGap, detail)),
1716            None,
1717        ),
1718        CensusSupport::Inconclusive { detail } => execute_case(case, base, catalog, Some(detail)),
1719        CensusSupport::Exercise => execute_case(case, base, catalog, None),
1720    }
1721}
1722
1723struct Fail {
1724    code: ReasonCode,
1725    detail: String,
1726    locale: Locale,
1727}
1728
1729impl Fail {
1730    fn workshop(error: &WorkshopError, locale: &Locale) -> Self {
1731        let code = match error {
1732            WorkshopError::Unsupported { .. } => ReasonCode::Unsupported,
1733            WorkshopError::MissingMapping { .. } => ReasonCode::KnownGap,
1734            _ => ReasonCode::UnexpectedRegression,
1735        };
1736        Self {
1737            code,
1738            detail: error.to_string(),
1739            locale: locale.clone(),
1740        }
1741    }
1742
1743    fn regression(detail: impl Into<String>, locale: &Locale) -> Self {
1744        Self {
1745            code: ReasonCode::UnexpectedRegression,
1746            detail: detail.into(),
1747            locale: locale.clone(),
1748        }
1749    }
1750}
1751
1752fn execute_case(
1753    case: &CensusCase,
1754    base: impl Fn(
1755        ConformanceStatus,
1756        Comparison,
1757        Option<ConformanceReason>,
1758        Option<Locale>,
1759    ) -> ConformanceResult,
1760    catalog: &Catalog,
1761    inconclusive_detail: Option<&str>,
1762) -> ConformanceResult {
1763    match run_pipeline(case, catalog, inconclusive_detail) {
1764        Ok((comparison, locale)) => {
1765            base(ConformanceStatus::Matched, comparison, None, Some(locale))
1766        }
1767        Err(fail) => failed_text(base, fail.code, fail.detail, Some(fail.locale)),
1768    }
1769}
1770
1771fn run_pipeline(
1772    case: &CensusCase,
1773    catalog: &Catalog,
1774    inconclusive_detail: Option<&str>,
1775) -> Result<(Comparison, Locale), Fail> {
1776    let source_locale = Locale::new(&case.source_locale);
1777    let target_locale = if source_locale.as_str() == ZH_CN {
1778        Locale::new(EN_US)
1779    } else {
1780        Locale::new(ZH_CN)
1781    };
1782
1783    let parse = |source: &str, locale: &Locale| {
1784        parser::parse_with_context(source, catalog, locale, catalog)
1785            .map_err(|error| Fail::workshop(&error, locale))
1786    };
1787    let validate = |program: &workshop_rs::Program, locale: &Locale| {
1788        program
1789            .validate()
1790            .map_err(|error| Fail::regression(error.to_string(), locale))
1791    };
1792    let emit = |program: &workshop_rs::Program, locale: &Locale| {
1793        emitter::emit(program, catalog, locale).map_err(|error| Fail::workshop(&error, locale))
1794    };
1795    let convert_or =
1796        |source: &str, from: &Locale, to: &Locale| -> Result<convert::Conversion, Fail> {
1797            convert::convert(source, catalog, from, to, &Default::default())
1798                .map_err(|error| Fail::workshop(&error, to))
1799        };
1800
1801    let surface_equivalent =
1802        |a: &workshop_rs::Program, b: &workshop_rs::Program, locale: &Locale| {
1803            let (Ok(x), Ok(y)) = (emit(a, locale), emit(b, locale)) else {
1804                return false;
1805            };
1806            normalize_workshop(&x) == normalize_workshop(&y)
1807        };
1808
1809    let program = parse(&case.source, &source_locale)?;
1810    validate(&program, &source_locale)?;
1811    let emitted = emit(&program, &source_locale)?;
1812    let reparsed = parse(&emitted, &source_locale)?;
1813    validate(&reparsed, &source_locale)?;
1814    let reemitted = emit(&reparsed, &source_locale)?;
1815    if !roundtrip::equivalent(&program, &reparsed)
1816        || normalize_workshop(&emitted) != normalize_workshop(&reemitted)
1817    {
1818        return Err(Fail::regression(
1819            "en-US semantic or normalized gate diverged",
1820            &source_locale,
1821        ));
1822    }
1823
1824    let converted = convert_or(&case.source, &source_locale, &target_locale)?;
1825    let target_program = parse(&converted.text, &target_locale)?;
1826    validate(&target_program, &target_locale)?;
1827    if !roundtrip::equivalent(&program, &target_program) {
1828        if surface_equivalent(&program, &target_program, &target_locale) {
1829            return Err(Fail {
1830                code: ReasonCode::Inconclusive,
1831                detail: "converted text matches the canonical emission, but the \
1832                         target-locale spelling is ambiguous across enum domains; \
1833                         resolved semantics cannot be independently verified"
1834                    .to_string(),
1835                locale: target_locale,
1836            });
1837        }
1838        return Err(Fail::regression(
1839            "zh-CN conversion changed canonical WIR semantics",
1840            &target_locale,
1841        ));
1842    }
1843    let back = convert_or(&converted.text, &target_locale, &source_locale)?;
1844    let back_program = parse(&back.text, &source_locale)?;
1845    if !roundtrip::equivalent(&program, &back_program)
1846        || normalize_workshop(&back.text) != normalize_workshop(&emitted)
1847    {
1848        if surface_equivalent(&program, &back_program, &source_locale) {
1849            return Err(Fail {
1850                code: ReasonCode::Inconclusive,
1851                detail: "round-trip text matches the canonical emission, but the \
1852                         source-locale spelling is ambiguous across enum domains; \
1853                         resolved semantics cannot be independently verified"
1854                    .to_string(),
1855                locale: source_locale,
1856            });
1857        }
1858        return Err(Fail::regression(
1859            "cross-locale semantic or normalized gate diverged",
1860            &source_locale,
1861        ));
1862    }
1863
1864    let Some(reference_source) = case.reference_source.as_ref() else {
1865        return Err(Fail {
1866            code: ReasonCode::Inconclusive,
1867            detail: inconclusive_detail
1868                .unwrap_or(
1869                    "offline semantic and locale gates passed, but no independent expectation artifact is recorded",
1870                )
1871                .to_string(),
1872            locale: source_locale,
1873        });
1874    };
1875    let expected_program = parse(reference_source, &target_locale)?;
1876    if !roundtrip::equivalent(&program, &expected_program)
1877        || normalize_workshop(&converted.text) != normalize_workshop(reference_source)
1878    {
1879        return Err(Fail::regression(
1880            "conversion differed from the independent reference source",
1881            &target_locale,
1882        ));
1883    }
1884    Ok((
1885        Comparison {
1886            mode: Equivalence::Semantic,
1887            expected: Some(reference_artifact(case, reference_source)),
1888            observed: Some(artifact(
1889                format!("census/{}/converted-output.ws", case.case_id),
1890                &converted.text,
1891            )),
1892            normalizer: Some("canonical-wir;normalized-workshop-text".to_string()),
1893        },
1894        source_locale,
1895    ))
1896}
1897
1898fn failed_text(
1899    base: impl Fn(
1900        ConformanceStatus,
1901        Comparison,
1902        Option<ConformanceReason>,
1903        Option<Locale>,
1904    ) -> ConformanceResult,
1905    code: ReasonCode,
1906    detail: String,
1907    locale: Option<Locale>,
1908) -> ConformanceResult {
1909    let status = match code {
1910        ReasonCode::Unsupported => ConformanceStatus::Unsupported,
1911        ReasonCode::KnownGap => ConformanceStatus::KnownGap,
1912        ReasonCode::UnexpectedRegression => ConformanceStatus::UnexpectedRegression,
1913        ReasonCode::Inconclusive => ConformanceStatus::Inconclusive,
1914    };
1915    let comparison = if code == ReasonCode::UnexpectedRegression {
1916        Comparison {
1917            mode: Equivalence::Normalized,
1918            expected: None,
1919            observed: None,
1920            normalizer: Some("census-stage".to_string()),
1921        }
1922    } else {
1923        not_comparable()
1924    };
1925    base(status, comparison, Some(reason(code, &detail)), locale)
1926}
1927
1928fn reason(code: ReasonCode, detail: &str) -> ConformanceReason {
1929    ConformanceReason {
1930        code,
1931        detail: detail.to_string(),
1932    }
1933}
1934
1935fn not_comparable() -> Comparison {
1936    Comparison {
1937        mode: Equivalence::NotComparable,
1938        expected: None,
1939        observed: None,
1940        normalizer: None,
1941    }
1942}
1943
1944fn artifact(name: impl Into<String>, content: &str) -> TestArtifact {
1945    TestArtifact {
1946        name: name.into(),
1947        revision: None,
1948        path: None,
1949        sha256: Some(sha256(content)),
1950        license: Some("MIT".to_string()),
1951    }
1952}
1953
1954fn reference_artifact(case: &CensusCase, content: &str) -> TestArtifact {
1955    TestArtifact {
1956        name: format!("census reference for {}", case.case_id),
1957        revision: Some("census-v1".to_string()),
1958        path: Some("tests/fixtures/census/reference.ws".to_string()),
1959        sha256: Some(sha256(content)),
1960        license: Some("MIT".to_string()),
1961    }
1962}
1963
1964fn sha256(content: &str) -> String {
1965    let mut hasher = Sha256::new();
1966    hasher.update(content.as_bytes());
1967    format!("{:x}", hasher.finalize())
1968}
1969
1970fn normalize_workshop(text: &str) -> String {
1971    text.split_whitespace().collect::<Vec<_>>().join(" ")
1972}
1973
1974#[cfg(test)]
1975mod tests {
1976    use super::*;
1977
1978    #[test]
1979    fn builtin_census_is_derived_and_deterministic() {
1980        let catalog = Catalog::builtin().expect("builtin catalog");
1981        let first = Census::builtin(&catalog).expect("census");
1982        let second = Census::builtin(&catalog).expect("census");
1983        assert_eq!(first, second);
1984        assert_eq!(first.shards().first().unwrap().shard_id, "catalog-actions");
1985        assert!(
1986            first
1987                .cases()
1988                .any(|case| case.features.iter().any(|feature| feature.name == "wait"))
1989        );
1990        assert!(first.cases().any(|case| {
1991            case.features
1992                .iter()
1993                .any(|feature| feature.kind == FeatureKind::Setting)
1994        }));
1995        assert!(first.cases().any(|case| {
1996            case.features
1997                .iter()
1998                .any(|feature| feature.kind == FeatureKind::ControlFlow)
1999        }));
2000        assert_eq!(first.export_json().unwrap(), second.export_json().unwrap());
2001        assert_eq!(first.identity(), second.identity());
2002        assert_eq!(first.identity().digest.len(), 64);
2003    }
2004
2005    #[test]
2006    fn settings_probes_use_catalog_gamemode_spellings() {
2007        let catalog = Catalog::builtin().expect("builtin catalog");
2008
2009        for (mode, expected) in [
2010            ("ffa", "Deathmatch"),
2011            ("tdm", "Team Deathmatch"),
2012            ("ctf", "Capture The Flag"),
2013        ] {
2014            let prefix = format!("gamemodes.{mode}.");
2015            let definition = settings_schema::definitions()
2016                .find(|definition| definition.path().starts_with(&prefix))
2017                .unwrap_or_else(|| panic!("missing settings definition for {mode}"));
2018            let probe = settings_probe(&definition, &catalog);
2019            assert!(
2020                probe.contains(&format!("{expected} {{")),
2021                "{mode} probe used the wrong mode spelling:\n{probe}"
2022            );
2023        }
2024    }
2025
2026    #[test]
2027    fn explicit_non_matching_states_remain_machine_readable() {
2028        let feature_case = |id: &str, support| {
2029            CensusCase::probe(
2030                format!("state-tests/{id}"),
2031                vec![feature(FeatureNamespace::Wir, FeatureKind::Structural, id)],
2032                format!("rule (\"{id}\") {{}}"),
2033            )
2034            .with_support(support)
2035        };
2036        let shard = CensusShard::new(
2037            "state-tests",
2038            vec![
2039                feature_case(
2040                    "unsupported",
2041                    CensusSupport::Unsupported {
2042                        detail: "not declared".to_string(),
2043                    },
2044                ),
2045                feature_case(
2046                    "known-gap",
2047                    CensusSupport::KnownGap {
2048                        detail: "missing mapping".to_string(),
2049                    },
2050                ),
2051                feature_case(
2052                    "inconclusive",
2053                    CensusSupport::Inconclusive {
2054                        detail: "no oracle".to_string(),
2055                    },
2056                ),
2057            ],
2058        )
2059        .unwrap();
2060        let report = Census::assemble(vec![shard])
2061            .unwrap()
2062            .run(&Catalog::builtin().unwrap());
2063        report
2064            .validate()
2065            .expect("states use the current conformance adapter");
2066        let json = report.to_json().unwrap();
2067        assert!(json.contains("unsupported"));
2068        assert!(json.contains("known-gap"));
2069        assert!(json.contains("inconclusive"));
2070    }
2071
2072    #[test]
2073    fn builtin_census_report_validates_against_the_catalog() {
2074        let catalog = Catalog::builtin().expect("builtin catalog");
2075        let census = Census::builtin(&catalog).expect("census");
2076        let report = census.run(&catalog);
2077        report
2078            .validate_against(&catalog)
2079            .expect("census results use canonical catalog identities");
2080        assert_eq!(report.census, census.identity());
2081        assert_eq!(
2082            report.results.len(),
2083            census.cases().count(),
2084            "census drops or duplicates cases"
2085        );
2086        let localization_cases = census
2087            .cases()
2088            .filter(|case| case.case_id.starts_with("localization/"))
2089            .count();
2090        assert_eq!(
2091            report
2092                .results
2093                .iter()
2094                .filter(|result| result.case_id.starts_with("localization/"))
2095                .count(),
2096            localization_cases
2097        );
2098        assert!(
2099            localization_cases > 2,
2100            "localization shard must enumerate per-spelling cases"
2101        );
2102        assert!(
2103            report.results.iter().any(|result| {
2104                result.case_id.starts_with("localization/")
2105                    && result.status == ConformanceStatus::KnownGap
2106            }),
2107            "unwritable localized settings spellings must report as known gaps"
2108        );
2109    }
2110
2111    #[test]
2112    fn census_report_rejects_a_malformed_identity_digest() {
2113        let catalog = Catalog::builtin().expect("builtin catalog");
2114        let census = Census::assemble(vec![
2115            CensusShard::new(
2116                "state-tests",
2117                vec![CensusCase::probe(
2118                    "state-tests/probe".to_string(),
2119                    vec![feature(
2120                        FeatureNamespace::Wir,
2121                        FeatureKind::Structural,
2122                        "probe",
2123                    )],
2124                    "rule (\"probe\") {}".to_string(),
2125                )],
2126            )
2127            .unwrap(),
2128        ])
2129        .unwrap();
2130        let mut report = census.run(&catalog);
2131        report.census.digest = "not-a-digest".to_string();
2132
2133        let error = report
2134            .validate_against(&catalog)
2135            .expect_err("report identity must carry a SHA-256 digest");
2136        assert!(error.to_string().contains("SHA-256"));
2137    }
2138}
2139
2140#[cfg(test)]
2141mod probe_debug {
2142    use super::*;
2143
2144    #[test]
2145    fn dump_failing_localization_probes() {
2146        let catalog = Catalog::builtin().unwrap();
2147        let census = Census::builtin(&catalog).unwrap();
2148        let wanted = [
2149            "localization/es-mx/value/hero/0",
2150            "localization/fr-fr/value/hero/0",
2151        ];
2152        for case in census.cases() {
2153            if !wanted.contains(&case.case_id.as_str()) {
2154                continue;
2155            }
2156            println!("==== {} ====", case.case_id);
2157            println!("{}", case.source);
2158            let result = run_case(case, "localization", &catalog);
2159            println!(
2160                "-> {:?} {:?}",
2161                result.status,
2162                result.reason.map(|r| r.detail)
2163            );
2164        }
2165    }
2166}