workshop-rs 0.4.3

Canonical multi-locale Overwatch Workshop semantic core: catalog, parser, WIR, validation, emitter.
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
//! Executable witnesses for contextual Workshop literal semantics.

use workshop_rs::catalog::{Catalog, Locale};
use workshop_rs::parser;
use workshop_rs::roundtrip;
use workshop_rs::validate;
use workshop_rs::wir::{self, Action, Value};

fn catalog() -> Catalog {
    Catalog::builtin().expect("built-in catalog")
}

fn program_with(conditions: &str, actions: &str) -> wir::Program {
    let source = format!(
        r#"variables
{{
    global:
        0: probe
}}
rule ("contextual semantics")
{{
    event {{ Ongoing - Global; }}
    conditions {{
        {conditions}
    }}
    actions {{
        {actions}
    }}
}}"#
    );
    parser::parse_wir(&source, &catalog(), &Locale::new("en-US")).expect("contextual source parses")
}

fn program(actions: &str) -> wir::Program {
    program_with("", actions)
}

fn first_action_args(program: &wir::Program) -> &[wir::ValueId] {
    let rule = program.rules.iter().next().expect("rule");
    match program.actions.get(rule.actions[0]).expect("action") {
        Action::Call { args, .. } => args,
        other => panic!("expected a catalog action call, got {other:?}"),
    }
}

fn validate_program(program: &wir::Program) {
    validate::validate_canonical_ids_wir(program, &catalog()).expect("canonical validation");
}

fn first_value_call<'a>(program: &'a wir::Program, name: &str) -> &'a [wir::ValueId] {
    program
        .values
        .iter()
        .find_map(|node| match &node.value {
            Value::Call {
                name: value_name,
                args,
            } if value_name == name => Some(args.as_slice()),
            _ => None,
        })
        .unwrap_or_else(|| panic!("missing value call {name}"))
}

#[test]
fn numeric_boolean_aliases_share_canonical_wir_only_when_declared() {
    for (boolean, number, expected) in [("True", "1", 1.0), ("False", "0", 0.0)] {
        let boolean_program = program(&format!("Wait({boolean}, Ignore Condition);"));
        let number_program = program(&format!("Wait({number}, Ignore Condition);"));
        validate_program(&boolean_program);
        validate_program(&number_program);
        assert!(roundtrip::equivalent_wir(&boolean_program, &number_program));
        assert!(matches!(
            &boolean_program
                .values
                .get(first_action_args(&boolean_program)[0])
                .expect("wait duration")
                .value,
            Value::Number { value, .. } if *value == expected
        ));
    }
}

#[test]
fn one_sided_contextual_aliases_reject_the_other_boolean() {
    let accepted = program("Start Forcing Spawn Room(Team 1, False);");
    validate_program(&accepted);
    assert!(matches!(
        &accepted
            .values
            .get(first_action_args(&accepted)[1])
            .expect("spawn room")
            .value,
        Value::Number { value, .. } if *value == 0.0
    ));

    let rejected = program("Start Forcing Spawn Room(Team 1, True);");
    let error = validate::validate_canonical_ids_wir(&rejected, &catalog())
        .expect_err("True is not a documented alias for the spawn-room parameter");
    assert!(format!("{error:?}").contains("semantic type"));
}

#[test]
fn entity_ids_and_boolean_string_slice_counts_match_workshop_contract() {
    let setup = program(
        "Create Dummy Bot(All Heroes, Team 1, False, Null, Null); Start Forcing Dummy Bot Name(Last Created Entity, Custom String(\"x\"));",
    );
    validate_program(&setup);

    let derived = program(
        "Set Global Variable(probe, String Slice(String Replace(Custom String(\"x\"), String Split(Custom String(\"x\"), Empty Array), First Of(Last Created Entity)), 126, True)); Set Global Variable(parts, String Split(First Of(Last Created Entity), Empty Array));",
    );
    validate_program(&derived);
}

#[test]
fn wait_until_keeps_numeric_exception_without_global_truthiness() {
    let numeric = program("Wait Until(1, 2);");
    validate_program(&numeric);
    assert!(matches!(
        &numeric
            .values
            .get(first_action_args(&numeric)[0])
            .expect("continue condition")
            .value,
        Value::Number { value, .. } if *value == 1.0
    ));

    let vector = program("Wait Until(Vector(1, 2, 3), 2);");
    let error = validate::validate_canonical_ids_wir(&vector, &catalog())
        .expect_err("Wait Until must not accept arbitrary values as conditions");
    assert!(format!("{error:?}").contains("semantic type"));
}

#[test]
fn null_and_empty_string_contexts_normalize_at_their_positions() {
    let teleport = program("Teleport(Event Player, 0);");
    validate_program(&teleport);
    assert!(matches!(
        &teleport
            .values
            .get(first_action_args(&teleport)[1])
            .expect("teleport position")
            .value,
        Value::Null
    ));

    let position = program("Start Forcing Player Position(Event Player, 0, False);");
    validate_program(&position);
    assert!(matches!(
        &position
            .values
            .get(first_action_args(&position)[1])
            .expect("forced position")
            .value,
        Value::Null
    ));

    let dummy =
        program("Create Dummy Bot(Hero(Bastion), Team 2, 0, Vector(0, 0, 0), Vector(0, 0, 0));");
    validate_program(&dummy);
    let dummy_args = first_action_args(&dummy);
    assert!(matches!(
        &dummy
            .values
            .get(dummy_args[3])
            .expect("dummy position")
            .value,
        Value::Null
    ));
    assert!(matches!(
        &dummy
            .values
            .get(dummy_args[4])
            .expect("dummy direction")
            .value,
        Value::Null
    ));

    let name = program("Start Forcing Dummy Bot Name(Event Player, Empty Array);");
    validate_program(&name);
    assert!(matches!(
        &name.values
            .get(first_action_args(&name)[1])
            .expect("forced name")
            .value,
        Value::String(value) if value.is_empty()
    ));

    let string_source = r#"variables
{
    global:
        0: probe
}
rule ("empty string")
{
    event { Ongoing - Global; }
    actions { Set Global Variable(probe, String Replace(Empty Array, Empty Array, Empty Array)); }
}"#;
    let reparsed = roundtrip::round_trip_with_context(
        string_source,
        &catalog(),
        &Locale::new("en-US"),
        &catalog(),
    );
    assert!(
        reparsed.equivalent,
        "empty string contextual alias must round-trip"
    );
}

#[test]
fn create_dummy_bot_accepts_hero_or_hero_array_only_for_hero_parameter() {
    let catalog = catalog();
    assert_eq!(
        catalog
            .entry(workshop_rs::catalog::Kind::Action, "createDummyBot")
            .expect("Create Dummy Bot")
            .param_type(0),
        Some("Hero|Array")
    );

    for hero in ["Hero(Bastion)", "All Heroes"] {
        let program = program(&format!(
            "Create Dummy Bot({hero}, Team 2, 0, Vector(0, 0, 0), Vector(0, 0, 0));"
        ));
        validate::validate_canonical_ids_wir(&program, &catalog)
            .expect("Create Dummy Bot accepts a single hero or hero array");
        assert!(matches!(
            program
                .actions
                .iter()
                .next()
                .expect("Create Dummy Bot action"),
            Action::Call { name, .. } if name == "createDummyBot"
        ));
    }

    let invalid =
        program("Create Dummy Bot(Color(White), Team 2, 0, Vector(0, 0, 0), Vector(0, 0, 0));");
    let error = validate::validate_canonical_ids_wir(&invalid, &catalog)
        .expect_err("Create Dummy Bot must reject an unrelated hero argument type");
    assert!(error.to_string().contains("createDummyBot"));
    assert!(error.to_string().contains("semantic type"));
}

#[test]
fn nested_numeric_boolean_aliases_normalize_inside_vector_components() {
    let program = program("Set Global Variable(probe, Vector(1, True, False));");
    validate_program(&program);
    let args = first_value_call(&program, "vector");
    assert_eq!(args.len(), 3);
    for (value_id, expected) in [(args[0], 1.0), (args[1], 1.0), (args[2], 0.0)] {
        assert!(matches!(
            &program.values.get(value_id).expect("vector component").value,
            Value::Number { value, .. } if *value == expected
        ));
    }
}

#[test]
fn comparisons_preserve_polymorphic_operand_types() {
    let program = program_with("1 == True;", "Wait(1, Ignore Condition);");
    validate_program(&program);
    let condition = program
        .values
        .get(program.rules.iter().next().expect("rule").conditions[0])
        .expect("comparison");
    let Value::Call { name, args } = &condition.value else {
        panic!("expected comparison call, got {:?}", condition.value);
    };
    assert_eq!(name, "==");
    assert!(matches!(
        &program.values.get(args[0]).expect("left operand").value,
        Value::Number { value, .. } if *value == 1.0
    ));
    assert!(matches!(
        &program.values.get(args[1]).expect("right operand").value,
        Value::Bool(true)
    ));
}

#[test]
fn arithmetic_operators_apply_contextual_aliases_but_comparisons_do_not() {
    let program = program("Set Global Variable(probe, True + 1);");
    validate_program(&program);
    let args = first_value_call(&program, "add");
    assert!(matches!(
        &program.values.get(args[0]).expect("left operand").value,
        Value::Number { value, .. } if *value == 1.0
    ));
}

#[test]
fn indexed_player_variable_sugar_uses_canonical_parameter_positions() {
    let source = r#"variables
{
    global:
        0: probe
    player:
        0: indexed
}

rule ("indexed contextual semantics")
{
    event { Ongoing - Global; }
    actions { Set Player Variable At Index(Event Player, indexed, True, Null); }
}"#;
    let parsed = parser::parse_wir(source, &catalog(), &Locale::new("en-US"))
        .expect("indexed source parses");
    validate::validate_canonical_ids_wir(&parsed, &catalog()).expect("canonical validation");
    let action = parsed
        .actions
        .get(parsed.rules.iter().next().expect("rule").actions[0])
        .expect("indexed action");
    let Action::Call { args, .. } = action else {
        panic!("expected indexed action call, got {action:?}");
    };
    assert!(matches!(
        &parsed.values.get(args[1]).expect("index").value,
        Value::Number { value, .. } if *value == 1.0
    ));
}

#[test]
fn conditional_operator_applies_branch_contextual_aliases() {
    let parsed = program("Set Global Variable(probe, True ? 0 : 1);");
    validate_program(&parsed);
    let args = first_value_call(&parsed, "ifThenElse");
    assert!(matches!(
        &parsed.values.get(args[1]).expect("true branch").value,
        Value::Null
    ));
}

#[test]
fn audited_catalog_parameters_cover_boolean_numeric_aliases() {
    for (source, expected) in [
        ("Set Gravity(Event Player, True);", 1.0),
        ("Set Ultimate Charge(Event Player, False);", 0.0),
        ("Set Team Score(Team 1, True);", 1.0),
    ] {
        let parsed = program(source);
        validate_program(&parsed);
        assert!(matches!(
            &parsed
                .values
                .get(first_action_args(&parsed)[1])
                .expect("numeric parameter")
                .value,
            Value::Number { value, .. } if *value == expected
        ));
    }

    let parsed = program("Set Global Variable(probe, Is Objective Complete(True));");
    validate_program(&parsed);
    let args = first_value_call(&parsed, "isObjectiveComplete");
    assert!(matches!(
        &parsed.values.get(args[0]).expect("objective index").value,
        Value::Number { value, .. } if *value == 1.0
    ));
}

#[test]
fn array_index_sugar_applies_value_in_array_context() {
    let parsed = program("Set Global Variable(probe, Array(1)[True]);");
    validate_program(&parsed);
    let args = first_value_call(&parsed, "valueInArray");
    assert!(matches!(
        &parsed.values.get(args[1]).expect("array index").value,
        Value::Number { value, .. } if *value == 1.0
    ));
}

#[test]
fn modify_contexts_apply_operation_specific_replacements() {
    let source = r#"variables
{
    global:
        0: g
    player:
        0: p
}
rule ("modify contextual semantics")
{
    event { Ongoing - Global; }
    actions {
        Modify Global Variable(g, Add, False);
        Modify Global Variable(g, Append To Array, 0);
        Modify Player Variable(Event Player, p, Subtract, True);
        Modify Global Variable At Index(g, 0, Append To Array, 0);
        Global.g[False] += 1;
    }
}"#;
    let parsed =
        parser::parse_wir(source, &catalog(), &Locale::new("en-US")).expect("modify source parses");
    validate_program(&parsed);

    let direct_values: Vec<_> = parsed
        .actions
        .iter()
        .filter_map(|action| match action {
            Action::ModifyGlobalVariable { value, .. }
            | Action::ModifyPlayerVariable { value, .. } => Some(value),
            _ => None,
        })
        .collect();
    assert!(matches!(
        &parsed.values.get(*direct_values[0]).expect("add value").value,
        Value::Number { value, .. } if *value == 0.0
    ));
    assert!(matches!(
        &parsed
            .values
            .get(*direct_values[1])
            .expect("append value")
            .value,
        Value::Null
    ));
    assert!(matches!(
        &parsed.values.get(*direct_values[2]).expect("subtract value").value,
        Value::Number { value, .. } if *value == 1.0
    ));

    let indexed: Vec<_> = parsed
        .actions
        .iter()
        .filter_map(|action| match action {
            Action::Call { name, args, .. } if name == "modifyGlobalVariableAtIndex" => Some(args),
            _ => None,
        })
        .collect();
    assert_eq!(indexed.len(), 2);
    assert!(matches!(
        &parsed
            .values
            .get(indexed[0][3])
            .expect("indexed modify value")
            .value,
        Value::Null
    ));
    assert!(matches!(
        &parsed
            .values
            .get(indexed[1][1])
            .expect("indexed assignment index")
            .value,
        Value::Number { value, .. } if *value == 0.0
    ));
}