workshop-rs 0.6.4

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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//! Canonical Workshop artifact formats and the public [`SourceMap`].

use serde::{Deserialize, Serialize};

use super::{DeclarationProvenance, Program, ProgramProvenance, action_argument_count, fit};
use crate::source::{FileId, Position, SourceFile, Span};

/// Identifier of the canonical Workshop text artifact: the Workshop text alone.
pub const TEXT_V1: &str = "workshop-rs/text-v1";

/// Identifier of the canonical mapped Workshop artifact: Workshop text plus a
/// [`SourceMap`], serialized by [`MappedText::to_json`].
pub const MAPPED_TEXT_V1: &str = "workshop-rs/mapped-text-v1";

/// A source mapping detached from a [`Program`].
///
/// A source map records the file table, the program shape, and the
/// position-keyed spans of a span-bearing program. Extract it with
/// [`SourceMap::extract`], carry it beside the emitted Workshop text, and
/// [`apply`](Self::apply) it to a program parsed from that text. Spans use
/// [`Position`] units: 1-based lines and columns counted in Unicode scalar
/// values.
///
/// The mapping granularity is rule, condition, action, direct action argument,
/// and variable and subroutine declarations. Nodes without an authored origin
/// have no entry, so consumers report evidence on them as unmapped.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceMap {
    files: Vec<String>,
    shape: Shape,
    spans: Vec<MappedNode>,
}

/// Workshop text together with the [`SourceMap`] of its authored origin: the
/// `workshop-rs/mapped-text-v1` artifact.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MappedText {
    /// The Workshop text, itself a `workshop-rs/text-v1` artifact.
    pub text: String,
    /// The mapping from the program parsed from [`text`](Self::text) to the
    /// authored source.
    pub map: SourceMap,
}

/// A failure while decoding or applying a [`SourceMap`].
///
/// A failed [`SourceMap::apply`] leaves the program unchanged.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SourceMapError {
    GlobalVariableCount {
        expected: usize,
        found: usize,
    },
    PlayerVariableCount {
        expected: usize,
        found: usize,
    },
    SubroutineCount {
        expected: usize,
        found: usize,
    },
    RuleCount {
        expected: usize,
        found: usize,
    },
    ConditionCount {
        rule: usize,
        expected: usize,
        found: usize,
    },
    ActionCount {
        rule: usize,
        expected: usize,
        found: usize,
    },
    /// An entry addresses a node outside the program shape.
    InvalidPosition,
    /// Two entries map the same node.
    DuplicateEntry,
    /// A declaration entry carries neither a span nor a name span.
    EmptyEntry,
    /// A span references a file outside the file table.
    UnknownFile(usize),
    /// A span is not a valid 1-based interval.
    InvalidSpan(Span),
    /// The artifact declares a format other than `workshop-rs/mapped-text-v1`.
    UnsupportedFormat(String),
    /// The artifact is not well-formed JSON of the expected structure.
    Malformed(String),
}

impl std::fmt::Display for SourceMapError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mismatch = |formatter: &mut std::fmt::Formatter<'_>, what, expected, found| {
            write!(
                formatter,
                "source map shape mismatch: expected {expected} {what}, found {found}"
            )
        };
        match self {
            Self::GlobalVariableCount { expected, found } => {
                mismatch(formatter, "global variables", expected, found)
            }
            Self::PlayerVariableCount { expected, found } => {
                mismatch(formatter, "player variables", expected, found)
            }
            Self::SubroutineCount { expected, found } => {
                mismatch(formatter, "subroutines", expected, found)
            }
            Self::RuleCount { expected, found } => mismatch(formatter, "rules", expected, found),
            Self::ConditionCount {
                rule,
                expected,
                found,
            } => mismatch(
                formatter,
                &format!("conditions in rule {rule}"),
                expected,
                found,
            ),
            Self::ActionCount {
                rule,
                expected,
                found,
            } => mismatch(
                formatter,
                &format!("actions in rule {rule}"),
                expected,
                found,
            ),
            Self::InvalidPosition => {
                write!(formatter, "source map entry is outside the program shape")
            }
            Self::DuplicateEntry => write!(formatter, "source map maps a node twice"),
            Self::EmptyEntry => write!(formatter, "source map declaration entry has no span"),
            Self::UnknownFile(file) => {
                write!(formatter, "source map span references unknown file {file}")
            }
            Self::InvalidSpan(span) => write!(formatter, "invalid source map span {span:?}"),
            Self::UnsupportedFormat(format) => {
                write!(formatter, "unsupported mapped text format {format:?}")
            }
            Self::Malformed(message) => write!(formatter, "malformed mapped text: {message}"),
        }
    }
}

impl std::error::Error for SourceMapError {}

impl SourceMap {
    /// Extract the current mapping of a span-bearing program.
    ///
    /// Only spans that are still valid for the program's current shape are
    /// extracted; see [`Program::rule_span`].
    pub fn extract(program: &Program) -> Self {
        let mut spans = Vec::new();
        push_declarations(
            program,
            program.global_variables.len(),
            |provenance| &provenance.global_variables,
            |index, span, name_span| MappedNode::GlobalVariable {
                index,
                span,
                name_span,
            },
            &mut spans,
        );
        push_declarations(
            program,
            program.player_variables.len(),
            |provenance| &provenance.player_variables,
            |index, span, name_span| MappedNode::PlayerVariable {
                index,
                span,
                name_span,
            },
            &mut spans,
        );
        push_declarations(
            program,
            program.subroutines.len(),
            |provenance| &provenance.subroutines,
            |index, span, name_span| MappedNode::Subroutine {
                index,
                span,
                name_span,
            },
            &mut spans,
        );
        for (rule, public) in program.rules.iter().enumerate() {
            if let Some(span) = program.rule_span(rule) {
                spans.push(MappedNode::Rule {
                    rule,
                    span: span.into(),
                });
            }
            for condition in 0..public.conditions.len() {
                if let Some(span) = program.condition_span(rule, condition) {
                    spans.push(MappedNode::Condition {
                        rule,
                        condition,
                        span: span.into(),
                    });
                }
            }
            for (action, public_action) in public.actions.iter().enumerate() {
                if let Some(span) = program.action_span(rule, action) {
                    spans.push(MappedNode::Action {
                        rule,
                        action,
                        span: span.into(),
                    });
                }
                for argument in 0..action_argument_count(public_action) {
                    if let Some(span) = program.action_argument_span(rule, action, argument) {
                        spans.push(MappedNode::ActionArgument {
                            rule,
                            action,
                            argument,
                            span: span.into(),
                        });
                    }
                }
            }
        }
        Self {
            files: program.files.iter().map(|file| file.path.clone()).collect(),
            shape: Shape::of(program),
            spans,
        }
    }

    /// The paths of the file table that mapped spans refer to by file index.
    pub fn files(&self) -> &[String] {
        &self.files
    }

    /// Replace the source mapping of `program` with this map.
    ///
    /// The program's file table becomes this map's file table, and nodes
    /// without an entry carry no span. The program must have exactly the shape
    /// the map was extracted from; otherwise the whole mapping is rejected and
    /// `program` is unchanged.
    pub fn apply(&self, program: &mut Program) -> Result<(), SourceMapError> {
        self.shape.check(program)?;

        let mut provenance = ProgramProvenance::default();
        fit(
            &mut provenance.global_variables,
            self.shape.global_variables,
        );
        fit(
            &mut provenance.player_variables,
            self.shape.player_variables,
        );
        fit(&mut provenance.subroutines, self.shape.subroutines);
        fit(&mut provenance.rules, self.shape.rules.len());
        for (rule, shape) in provenance.rules.iter_mut().zip(&self.shape.rules) {
            fit(&mut rule.conditions, shape.conditions);
            fit(&mut rule.actions, shape.actions);
        }

        for node in &self.spans {
            match node {
                MappedNode::GlobalVariable {
                    index,
                    span,
                    name_span,
                } => {
                    let declaration = provenance
                        .global_variables
                        .get_mut(*index)
                        .ok_or(SourceMapError::InvalidPosition)?;
                    let mapped = self.declaration(*span, *name_span)?;
                    if declaration.span.is_some() || declaration.name_span.is_some() {
                        return Err(SourceMapError::DuplicateEntry);
                    }
                    *declaration = mapped;
                }
                MappedNode::PlayerVariable {
                    index,
                    span,
                    name_span,
                } => {
                    let declaration = provenance
                        .player_variables
                        .get_mut(*index)
                        .ok_or(SourceMapError::InvalidPosition)?;
                    let mapped = self.declaration(*span, *name_span)?;
                    if declaration.span.is_some() || declaration.name_span.is_some() {
                        return Err(SourceMapError::DuplicateEntry);
                    }
                    *declaration = mapped;
                }
                MappedNode::Subroutine {
                    index,
                    span,
                    name_span,
                } => {
                    let declaration = provenance
                        .subroutines
                        .get_mut(*index)
                        .ok_or(SourceMapError::InvalidPosition)?;
                    let mapped = self.declaration(*span, *name_span)?;
                    if declaration.span.is_some() || declaration.name_span.is_some() {
                        return Err(SourceMapError::DuplicateEntry);
                    }
                    *declaration = mapped;
                }
                MappedNode::Rule { rule, span } => {
                    let span = self.span(*span)?;
                    let slot = &mut provenance
                        .rules
                        .get_mut(*rule)
                        .ok_or(SourceMapError::InvalidPosition)?
                        .span;
                    if slot.replace(span).is_some() {
                        return Err(SourceMapError::DuplicateEntry);
                    }
                }
                MappedNode::Condition {
                    rule,
                    condition,
                    span,
                } => {
                    let span = self.span(*span)?;
                    let slot = provenance
                        .rules
                        .get_mut(*rule)
                        .and_then(|rule| rule.conditions.get_mut(*condition))
                        .ok_or(SourceMapError::InvalidPosition)?;
                    if slot.replace(span).is_some() {
                        return Err(SourceMapError::DuplicateEntry);
                    }
                }
                MappedNode::Action { rule, action, span } => {
                    let span = self.span(*span)?;
                    let slot = &mut provenance
                        .rules
                        .get_mut(*rule)
                        .and_then(|rule| rule.actions.get_mut(*action))
                        .ok_or(SourceMapError::InvalidPosition)?
                        .span;
                    if slot.replace(span).is_some() {
                        return Err(SourceMapError::DuplicateEntry);
                    }
                }
                MappedNode::ActionArgument {
                    rule,
                    action,
                    argument,
                    span,
                } => {
                    let span = self.span(*span)?;
                    let count = program
                        .rules
                        .get(*rule)
                        .and_then(|rule| rule.actions.get(*action))
                        .map(action_argument_count)
                        .ok_or(SourceMapError::InvalidPosition)?;
                    if *argument >= count {
                        return Err(SourceMapError::InvalidPosition);
                    }
                    let arguments = &mut provenance
                        .rules
                        .get_mut(*rule)
                        .and_then(|rule| rule.actions.get_mut(*action))
                        .ok_or(SourceMapError::InvalidPosition)?
                        .arguments;
                    fit(arguments, count);
                    if arguments[*argument].replace(span).is_some() {
                        return Err(SourceMapError::DuplicateEntry);
                    }
                }
            }
        }

        program.files.clear();
        for path in &self.files {
            program.add_file(SourceFile::new(path.clone()));
        }
        program.provenance = Some(Box::new(provenance));
        Ok(())
    }

    fn span(&self, wire: WireSpan) -> Result<Span, SourceMapError> {
        if wire.file >= self.files.len() {
            return Err(SourceMapError::UnknownFile(wire.file));
        }
        let span = Span::from(wire);
        if !span.is_valid() {
            return Err(SourceMapError::InvalidSpan(span));
        }
        Ok(span)
    }

    fn declaration(
        &self,
        span: Option<WireSpan>,
        name_span: Option<WireSpan>,
    ) -> Result<DeclarationProvenance, SourceMapError> {
        if span.is_none() && name_span.is_none() {
            return Err(SourceMapError::EmptyEntry);
        }
        Ok(DeclarationProvenance {
            span: span.map(|span| self.span(span)).transpose()?,
            name_span: name_span.map(|span| self.span(span)).transpose()?,
        })
    }
}

impl MappedText {
    /// Serialize as a `workshop-rs/mapped-text-v1` JSON document.
    pub fn to_json(&self) -> String {
        let artifact = Artifact {
            format: MAPPED_TEXT_V1.to_string(),
            text: self.text.clone(),
            files: self
                .map
                .files
                .iter()
                .map(|path| WireFile { path: path.clone() })
                .collect(),
            shape: self.map.shape.clone(),
            spans: self.map.spans.clone(),
        };
        serde_json::to_string(&artifact).expect("mapped text serializes to JSON")
    }

    /// Decode a `workshop-rs/mapped-text-v1` JSON document.
    ///
    /// Decoding checks the format and structure only; [`SourceMap::apply`]
    /// validates the mapping against the program it is applied to.
    pub fn from_json(json: &str) -> Result<Self, SourceMapError> {
        let value: serde_json::Value = serde_json::from_str(json)
            .map_err(|error| SourceMapError::Malformed(error.to_string()))?;
        match value.get("format").and_then(serde_json::Value::as_str) {
            Some(MAPPED_TEXT_V1) => {}
            Some(other) => return Err(SourceMapError::UnsupportedFormat(other.to_string())),
            None => return Err(SourceMapError::Malformed("missing format".to_string())),
        }
        let artifact: Artifact = serde_json::from_value(value)
            .map_err(|error| SourceMapError::Malformed(error.to_string()))?;
        Ok(Self {
            text: artifact.text,
            map: SourceMap {
                files: artifact.files.into_iter().map(|file| file.path).collect(),
                shape: artifact.shape,
                spans: artifact.spans,
            },
        })
    }
}

fn push_declarations(
    program: &Program,
    count: usize,
    recorded: impl Fn(&ProgramProvenance) -> &[DeclarationProvenance],
    node: impl Fn(usize, Option<WireSpan>, Option<WireSpan>) -> MappedNode,
    output: &mut Vec<MappedNode>,
) {
    for index in 0..count {
        let declaration = program.declaration_provenance(&recorded, count, index);
        if declaration.span.is_some() || declaration.name_span.is_some() {
            output.push(node(
                index,
                declaration.span.map(WireSpan::from),
                declaration.name_span.map(WireSpan::from),
            ));
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Artifact {
    format: String,
    text: String,
    files: Vec<WireFile>,
    shape: Shape,
    spans: Vec<MappedNode>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct WireFile {
    path: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Shape {
    global_variables: usize,
    player_variables: usize,
    subroutines: usize,
    rules: Vec<RuleShape>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct RuleShape {
    conditions: usize,
    actions: usize,
}

impl Shape {
    fn of(program: &Program) -> Self {
        Self {
            global_variables: program.global_variables.len(),
            player_variables: program.player_variables.len(),
            subroutines: program.subroutines.len(),
            rules: program
                .rules
                .iter()
                .map(|rule| RuleShape {
                    conditions: rule.conditions.len(),
                    actions: rule.actions.len(),
                })
                .collect(),
        }
    }

    fn check(&self, program: &Program) -> Result<(), SourceMapError> {
        let found = Self::of(program);
        if self.global_variables != found.global_variables {
            return Err(SourceMapError::GlobalVariableCount {
                expected: self.global_variables,
                found: found.global_variables,
            });
        }
        if self.player_variables != found.player_variables {
            return Err(SourceMapError::PlayerVariableCount {
                expected: self.player_variables,
                found: found.player_variables,
            });
        }
        if self.subroutines != found.subroutines {
            return Err(SourceMapError::SubroutineCount {
                expected: self.subroutines,
                found: found.subroutines,
            });
        }
        if self.rules.len() != found.rules.len() {
            return Err(SourceMapError::RuleCount {
                expected: self.rules.len(),
                found: found.rules.len(),
            });
        }
        for (rule, (expected, found)) in self.rules.iter().zip(&found.rules).enumerate() {
            if expected.conditions != found.conditions {
                return Err(SourceMapError::ConditionCount {
                    rule,
                    expected: expected.conditions,
                    found: found.conditions,
                });
            }
            if expected.actions != found.actions {
                return Err(SourceMapError::ActionCount {
                    rule,
                    expected: expected.actions,
                    found: found.actions,
                });
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "node", rename_all = "snake_case")]
enum MappedNode {
    Rule {
        rule: usize,
        span: WireSpan,
    },
    Condition {
        rule: usize,
        condition: usize,
        span: WireSpan,
    },
    Action {
        rule: usize,
        action: usize,
        span: WireSpan,
    },
    ActionArgument {
        rule: usize,
        action: usize,
        argument: usize,
        span: WireSpan,
    },
    GlobalVariable {
        index: usize,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        span: Option<WireSpan>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        name_span: Option<WireSpan>,
    },
    PlayerVariable {
        index: usize,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        span: Option<WireSpan>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        name_span: Option<WireSpan>,
    },
    Subroutine {
        index: usize,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        span: Option<WireSpan>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        name_span: Option<WireSpan>,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
struct WireSpan {
    file: usize,
    start: WirePosition,
    end: WirePosition,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
struct WirePosition {
    line: u32,
    column: u32,
}

impl From<Span> for WireSpan {
    fn from(span: Span) -> Self {
        Self {
            file: span.file.index(),
            start: span.start.into(),
            end: span.end.into(),
        }
    }
}

impl From<WireSpan> for Span {
    fn from(wire: WireSpan) -> Self {
        Span::new(
            FileId::from_index(wire.file),
            wire.start.into(),
            wire.end.into(),
        )
    }
}

impl From<Position> for WirePosition {
    fn from(position: Position) -> Self {
        Self {
            line: position.line,
            column: position.col,
        }
    }
}

impl From<WirePosition> for Position {
    fn from(position: WirePosition) -> Self {
        Position::new(position.line, position.column)
    }
}