tiger_lib/validator/
value_validator.rs

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
use std::borrow::Cow;
use std::fmt::{Debug, Display, Error, Formatter};
#[cfg(any(feature = "ck3", feature = "vic3"))]
use std::ops::{Bound, RangeBounds};
use std::str::FromStr;

use crate::context::ScopeContext;
use crate::date::Date;
use crate::everything::Everything;
use crate::item::Item;
use crate::report::{report, ErrorKey, Severity};
use crate::scopes::Scopes;
use crate::token::Token;
use crate::trigger::validate_target;
#[cfg(feature = "imperator")]
use crate::trigger::validate_target_ok_this;

/// A validator for one `Token`.
/// The intended usage is that the block-level [`Validator`](crate::validator::Validator) wraps the `Token`
/// in a `ValueValidator`, then you call one or more of the validation functions on it.
/// If the `ValueValidator` goes out of scope without having been validated, it will report an error.
///
/// Calling multiple validation functions is only supported when starting with the `maybe_`
/// variants. Calling one of the definite validation methods will either accept the value or warn
/// about it, and it's considered validated after that.
pub struct ValueValidator<'a> {
    /// The value being validated
    value: Cow<'a, Token>,
    /// A link to all the loaded and processed CK3 and mod files
    data: &'a Everything,
    /// Whether the value has been validated. If true, it means either the value was accepted as
    /// correct or it was warned about.
    validated: bool,
    /// Maximum severity of problems reported by this `ValueValidator`. Defaults to `Error`.
    /// This is intended to be set lower by validators for less-important items.
    /// As an exception, `Fatal` severity reports will still always be logged as `Fatal`.
    max_severity: Severity,
}

impl Debug for ValueValidator<'_> {
    /// Roll our own `Debug` implementation in order to leave out the `data` field.
    fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> {
        f.debug_struct("ValueValidator")
            .field("value", &self.value)
            .field("validated", &self.validated)
            .field("max_severity", &self.max_severity)
            .finish()
    }
}

impl<'a> ValueValidator<'a> {
    /// Construct a new `ValueValidator` for a `&Token`.
    pub fn new(value: &'a Token, data: &'a Everything) -> Self {
        Self { value: Cow::Borrowed(value), data, validated: false, max_severity: Severity::Error }
    }

    /// Construct a new `ValueValidator` for an owned `Token`.
    pub fn new_owned(value: Token, data: &'a Everything) -> Self {
        Self { value: Cow::Owned(value), data, validated: false, max_severity: Severity::Error }
    }

    /// Maximum severity of problems reported by this `ValueValidator`. Defaults to `Error`.
    /// This is intended to be set lower by validators for less-important items.
    /// As an exception, `Fatal` severity reports will still always be logged as `Fatal`.
    pub fn set_max_severity(&mut self, max_severity: Severity) {
        self.max_severity = max_severity;
    }

    /// Make a descendant validator from this one, usually for a sub-token.
    fn value_validator(&self, token: Token) -> Self {
        let mut vd = ValueValidator::new_owned(token, self.data);
        vd.set_max_severity(self.max_severity);
        vd
    }

    /// Access the value that this `ValueValidator` validates.
    pub fn value(&self) -> &Token {
        &self.value
    }

    /// Mark this value as valid, without placing any restrictions on it.
    pub fn accept(&mut self) {
        self.validated = true;
    }

    /// Expect the value to be the key of an `itype` item in the game database.
    /// The item is looked up and must exist.
    pub fn item(&mut self, itype: Item) {
        if self.validated {
            return;
        }
        self.validated = true;
        self.data.verify_exists_max_sev(itype, &self.value, self.max_severity);
    }

    // Expect the value to be the name of a file (possibly with suffix) in the defined path.
    #[cfg(feature = "ck3")]
    #[allow(dead_code)]
    pub fn icon(&mut self, define: &str, suffix: &str) {
        if self.validated {
            return;
        }
        self.validated = true;
        self.data.verify_icon(define, &self.value, suffix);
    }

    /// Add the given suffix to the value and mark that as a used item, without doing any validation.
    /// This is used for very weakly required localization, for example, where no warning is warranted.
    #[cfg(feature = "ck3")] // silence dead code warning
    pub fn item_used_with_suffix(&mut self, itype: Item, sfx: &str) {
        let implied = format!("{}{sfx}", self.value);
        self.data.mark_used(itype, &implied);
    }

    /// Validate a localization whose key is derived from the value, in the given [`ScopeContext`].
    #[allow(dead_code)]
    pub fn implied_localization_sc(&mut self, pfx: &str, sfx: &str, sc: &mut ScopeContext) {
        let implied = format!("{pfx}{}{sfx}", self.value);
        self.data.validate_localization_sc(&implied, sc);
    }

    /// Check if the value is the key of an `itype` item the game database.
    /// The item is looked up, and if it exists then this validator is considered validated.
    /// Return whether the item exists.
    #[allow(dead_code)]
    pub fn maybe_item(&mut self, itype: Item) -> bool {
        if self.data.item_exists(itype, self.value.as_str()) {
            self.validated = true;
            true
        } else {
            false
        }
    }

    /// Check if the value is be the key of an `itype` item the game database, after removing the prefix `pfx`.
    /// The item is looked up, and if it exists then this validator is considered validated.
    /// Return whether the item exists.
    #[cfg(feature = "vic3")] // silence dead code warning
    pub fn maybe_prefix_item(&mut self, pfx: &str, itype: Item) -> bool {
        if let Some(value) = self.value.as_str().strip_prefix(pfx) {
            if self.data.item_exists(itype, value) {
                self.validated = true;
                return true;
            }
        }
        false
    }

    /// Expect the value to be the name of a file under the directory given here.
    #[cfg(feature = "ck3")] // silence dead code warning
    pub fn dir_file(&mut self, path: &str) {
        if self.validated {
            return;
        }
        self.validated = true;
        let pathname = format!("{path}/{}", self.value);
        // TODO: pass max_severity here
        self.data.verify_exists_implied(Item::File, &pathname, &self.value);
    }

    #[must_use]
    pub fn split(&mut self, c: char) -> Vec<ValueValidator> {
        self.validated = true;
        self.value.split(c).into_iter().map(|value| self.value_validator(value)).collect()
    }

    /// Expect the value to be a (possibly single-element) scope chain which evaluates to a scope type in `outscopes`.
    ///
    /// The value is evaluated in the scope context `sc`, so for example if the value does `scope:actor` but there is
    /// no named scope "actor" in the scope context, then a warning is emitted.
    ///
    /// Also emits a warning if the value is simply "`this`", because that is almost never correct.
    #[allow(dead_code)] // not used yet
    pub fn target(&mut self, sc: &mut ScopeContext, outscopes: Scopes) {
        if self.validated {
            return;
        }
        self.validated = true;
        // TODO: pass max_severity here
        validate_target(&self.value, self.data, sc, outscopes);
    }

    /// Just like [`ValueValidator::target`], but allows the value to be simply "`this`".
    /// It is expected to be used judiciously in cases where "`this`" can be correct.
    #[cfg(feature = "imperator")]
    pub fn target_ok_this(&mut self, sc: &mut ScopeContext, outscopes: Scopes) {
        if self.validated {
            return;
        }
        self.validated = true;
        // TODO: pass max_severity here
        validate_target_ok_this(&self.value, self.data, sc, outscopes);
    }

    /// This is a combination of [`ValueValidator::item`] and [`ValueValidator::target`]. If the field is present
    /// and is not a known `itype` item, then it is evaluated as a target.
    #[allow(dead_code)] // not used yet
    pub fn item_or_target(&mut self, sc: &mut ScopeContext, itype: Item, outscopes: Scopes) {
        if self.validated {
            return;
        }
        self.validated = true;
        if !self.data.item_exists(itype, self.value.as_str()) {
            // TODO: pass max_severity here
            validate_target(&self.value, self.data, sc, outscopes);
        }
    }

    /// Expect the value to be just `yes` or `no`.
    #[allow(dead_code)]
    pub fn bool(&mut self) {
        if self.validated {
            return;
        }
        let sev = Severity::Error.at_most(self.max_severity);
        self.validated = true;
        if !self.value.lowercase_is("yes") && !self.value.lowercase_is("no") {
            report(ErrorKey::Validation, sev).msg("expected yes or no").loc(self).push();
        }
    }

    /// Allow the value to be just `yes` or `no`, but don't mandate it.
    #[allow(dead_code)]
    pub fn maybe_bool(&mut self) {
        if self.validated {
            return;
        }
        if self.value.lowercase_is("yes") || self.value.lowercase_is("no") {
            self.validated = true;
        }
    }

    /// Expect the value to be an integer.
    pub fn integer(&mut self) {
        if self.validated {
            return;
        }
        self.validated = true;
        // TODO: pass max_severity here
        self.value.expect_integer();
    }

    /// Allow the value to be an integer, but don't mandate it.
    #[allow(dead_code)]
    pub fn maybe_integer(&mut self) {
        if self.validated {
            return;
        }
        if self.value.is_integer() {
            self.validated = true;
        }
    }

    /// Expect the value to be an integer between `low` and `high` (inclusive).
    #[cfg(feature = "ck3")]
    pub fn integer_range<R: RangeBounds<i64>>(&mut self, range: R) {
        if self.validated {
            return;
        }
        let sev = Severity::Error.at_most(self.max_severity);
        self.validated = true;
        // TODO: pass max_severity here
        if let Some(i) = self.value.expect_integer() {
            if !range.contains(&i) {
                let low = match range.start_bound() {
                    Bound::Unbounded => None,
                    Bound::Included(&n) => Some(n),
                    Bound::Excluded(&n) => Some(n + 1),
                };
                let high = match range.end_bound() {
                    Bound::Unbounded => None,
                    Bound::Included(&n) => Some(n),
                    Bound::Excluded(&n) => Some(n - 1),
                };
                let msg;
                if low.is_some() && high.is_some() {
                    msg = format!(
                        "should be between {} and {} (inclusive)",
                        low.unwrap(),
                        high.unwrap()
                    );
                } else if low.is_some() {
                    msg = format!("should be at least {}", low.unwrap());
                } else if high.is_some() {
                    msg = format!("should be at most {}", high.unwrap());
                } else {
                    unreachable!(); // could not have failed the contains check
                }
                report(ErrorKey::Range, sev).msg(msg).loc(self).push();
            }
        }
    }

    /// Expect the value to be a number with up to 5 decimals.
    /// (5 decimals is the limit accepted by the game engine in most contexts).
    #[allow(dead_code)] // not used yet
    pub fn numeric(&mut self) {
        if self.validated {
            return;
        }
        self.validated = true;
        // TODO: pass max_severity here
        self.value.expect_number();
    }

    /// Expect the value to be a number with up to 5 decimals within the `range` provided.
    /// (5 decimals is the limit accepted by the game engine in most contexts).
    #[cfg(feature = "vic3")]
    pub fn numeric_range<R: RangeBounds<f64>>(&mut self, range: R) {
        if self.validated {
            return;
        }
        let sev = Severity::Error.at_most(self.max_severity);
        self.validated = true;
        // TODO: pass max_severity here
        if let Some(f) = self.value.expect_number() {
            if !range.contains(&f) {
                let low = match range.start_bound() {
                    Bound::Unbounded => None,
                    Bound::Included(&f) => Some(format!("{f} (inclusive)")),
                    Bound::Excluded(&f) => Some(format!("{f}")),
                };
                let high = match range.end_bound() {
                    Bound::Unbounded => None,
                    Bound::Included(&f) => Some(format!("{f} (inclusive)")),
                    Bound::Excluded(&f) => Some(format!("{f}")),
                };
                let msg;
                if low.is_some() && high.is_some() {
                    msg = format!("should be between {} and {}", low.unwrap(), high.unwrap());
                } else if low.is_some() {
                    msg = format!("should be at least {}", low.unwrap());
                } else if high.is_some() {
                    msg = format!("should be at most {}", high.unwrap());
                } else {
                    unreachable!(); // could not have failed the contains check
                }
                report(ErrorKey::Range, sev).msg(msg).loc(self).push();
            }
        }
    }

    /// Expect the value to be a number with any number of decimals.
    #[allow(dead_code)] // not used yet
    pub fn precise_numeric(&mut self) {
        if self.validated {
            return;
        }
        self.validated = true;
        // TODO: pass max_severity here
        self.value.expect_precise_number();
    }

    /// Expect the value to be a date.
    /// The format of dates is very flexible, from a single number (the year), to a year.month or year.month.day.
    /// No checking is done on the validity of the date as a date (so January 42nd is okay).
    #[allow(dead_code)] // not used yet
    pub fn date(&mut self) {
        if self.validated {
            return;
        }
        let sev = Severity::Error.at_most(self.max_severity);
        self.validated = true;
        if Date::from_str(self.value.as_str()).is_err() {
            let msg = "expected date value";
            report(ErrorKey::Validation, sev).msg(msg).loc(self).push();
        }
    }

    /// Expect the value to be one of the listed strings in `choices`.
    pub fn choice(&mut self, choices: &[&str]) {
        if self.validated {
            return;
        }
        self.validated = true;
        let sev = Severity::Error.at_most(self.max_severity);
        if !choices.contains(&self.value.as_str()) {
            let msg = format!("expected one of {}", choices.join(", "));
            report(ErrorKey::Choice, sev).msg(msg).loc(self).push();
        }
    }

    /// Check if the value is equal to the given string.
    /// If it is, mark this value as validated.
    /// Return whether the value matched the string.
    pub fn maybe_is(&mut self, s: &str) -> bool {
        if self.value.is(s) {
            self.validated = true;
            true
        } else {
            false
        }
    }

    /// Tells the `ValueValidator` to report a warning if the value is still unvalidated.
    pub fn warn_unvalidated(&mut self) {
        if !self.validated {
            let sev = Severity::Error.at_most(self.max_severity);
            let msg = format!("unknown value `{}`", self.value);
            report(ErrorKey::Validation, sev).msg(msg).loc(self).push();
        }
    }
}

impl Drop for ValueValidator<'_> {
    fn drop(&mut self) {
        self.warn_unvalidated();
    }
}

impl Display for ValueValidator<'_> {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        Display::fmt(&self.value, f)
    }
}