tiger_lib/data/
scripted_triggers.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
use std::path::PathBuf;

use crate::block::Block;
use crate::context::ScopeContext;
use crate::everything::Everything;
use crate::fileset::{FileEntry, FileHandler};
use crate::helpers::{dup_error, exact_dup_error, TigerHashMap, BANNED_NAMES};
use crate::lowercase::Lowercase;
use crate::macros::{MacroCache, MACRO_MAP};
use crate::parse::ParserMemory;
use crate::pdxfile::PdxFile;
use crate::report::{err, warn, ErrorKey, Severity};
use crate::scopes::Scopes;
use crate::token::Token;
use crate::tooltipped::Tooltipped;
use crate::trigger::validate_trigger_internal;

#[derive(Debug, Default)]
pub struct Triggers {
    scope_overrides: TigerHashMap<&'static str, Scopes>,
    triggers: TigerHashMap<&'static str, Trigger>,
}

impl Triggers {
    fn load_item(&mut self, key: Token, block: Block) {
        if let Some(other) = self.triggers.get(key.as_str()) {
            if other.key.loc.kind >= key.loc.kind {
                if other.block.equivalent(&block) {
                    exact_dup_error(&key, &other.key, "scripted trigger");
                } else {
                    dup_error(&key, &other.key, "scripted trigger");
                }
            }
        }
        if BANNED_NAMES.contains(&key.as_str()) {
            let msg = "scripted trigger has the same name as an important builtin";
            err(ErrorKey::NameConflict).strong().msg(msg).loc(key).push();
        } else {
            let scope_override = self
                .scope_overrides
                .get(key.as_str())
                .copied()
                .or_else(|| builtin_scope_overrides(&key));
            if block.source.is_some() {
                MACRO_MAP.insert_or_get_loc(key.loc);
            }
            self.triggers.insert(key.as_str(), Trigger::new(key, block, scope_override));
        }
    }

    pub fn exists(&self, key: &str) -> bool {
        self.triggers.contains_key(key)
    }

    pub fn iter_keys(&self) -> impl Iterator<Item = &Token> {
        self.triggers.values().map(|item| &item.key)
    }

    pub fn get(&self, key: &str) -> Option<&Trigger> {
        self.triggers.get(key)
    }

    pub fn validate(&self, data: &Everything) {
        for item in self.triggers.values() {
            item.validate(data);
        }
    }
}

impl FileHandler<Block> for Triggers {
    fn config(&mut self, config: &Block) {
        if let Some(block) = config.get_field_block("scope_override") {
            for (key, token) in block.iter_assignments() {
                let mut scopes = Scopes::empty();
                if token.lowercase_is("all") {
                    scopes = Scopes::all();
                } else {
                    for part in token.split('|') {
                        if let Some(scope) = Scopes::from_snake_case(part.as_str()) {
                            scopes |= scope;
                        } else {
                            let msg = format!("unknown scope type `{part}`");
                            warn(ErrorKey::Config).msg(msg).loc(part).push();
                        }
                    }
                }
                self.scope_overrides.insert(key.as_str(), scopes);
            }
        }
    }

    fn subpath(&self) -> PathBuf {
        PathBuf::from("common/scripted_triggers")
    }

    fn load_file(&self, entry: &FileEntry, parser: &ParserMemory) -> Option<Block> {
        if !entry.filename().to_string_lossy().ends_with(".txt") {
            return None;
        }

        PdxFile::read(entry, parser)
    }

    fn handle_file(&mut self, _entry: &FileEntry, mut block: Block) {
        for (key, block) in block.drain_definitions_warn() {
            self.load_item(key, block);
        }
    }
}

#[derive(Debug)]
pub struct Trigger {
    pub key: Token,
    block: Block,
    cache: MacroCache<ScopeContext>,
    scope_override: Option<Scopes>,
}

impl Trigger {
    pub fn new(key: Token, block: Block, scope_override: Option<Scopes>) -> Self {
        Self { key, block, cache: MacroCache::default(), scope_override }
    }

    pub fn validate(&self, data: &Everything) {
        // We could let triggers get "naturally" validated by being called from other places,
        // but we want to also validate triggers that aren't called from anywhere yet.
        if self.block.source.is_none() {
            let mut sc = ScopeContext::new_unrooted(Scopes::all(), &self.key);
            sc.set_strict_scopes(false);
            if self.scope_override.is_some() {
                sc.set_no_warn(true);
            }
            self.validate_call(&self.key, data, &mut sc, Tooltipped::No, false);
        }
    }

    pub fn validate_call(
        &self,
        key: &Token,
        data: &Everything,
        sc: &mut ScopeContext,
        tooltipped: Tooltipped,
        negated: bool,
    ) {
        if !self.cached_compat(key, &[], tooltipped, negated, sc) {
            let mut our_sc = ScopeContext::new_unrooted(Scopes::all(), &self.key);
            our_sc.set_strict_scopes(false);
            if self.scope_override.is_some() {
                our_sc.set_no_warn(true);
            }
            self.cache.insert(key, &[], tooltipped, negated, our_sc.clone());
            validate_trigger_internal(
                Lowercase::empty(),
                false,
                &self.block,
                data,
                &mut our_sc,
                tooltipped,
                negated,
                Severity::Error,
            );
            if let Some(scopes) = self.scope_override {
                our_sc = ScopeContext::new_unrooted(scopes, key);
                our_sc.set_strict_scopes(false);
            }
            sc.expect_compatibility(&our_sc, key);
            self.cache.insert(key, &[], tooltipped, negated, our_sc);
        }
    }

    pub fn macro_parms(&self) -> Vec<&'static str> {
        self.block.macro_parms()
    }

    pub fn cached_compat(
        &self,
        key: &Token,
        args: &[(&'static str, Token)],
        tooltipped: Tooltipped,
        negated: bool,
        sc: &mut ScopeContext,
    ) -> bool {
        self.cache.perform(key, args, tooltipped, negated, |our_sc| {
            sc.expect_compatibility(our_sc, key);
        })
    }

    pub fn validate_macro_expansion(
        &self,
        key: &Token,
        args: &[(&'static str, Token)],
        data: &Everything,
        sc: &mut ScopeContext,
        tooltipped: Tooltipped,
        negated: bool,
    ) {
        // Every invocation is treated as different even if the args are the same,
        // because we want to point to the correct one when reporting errors.
        if !self.cached_compat(key, args, tooltipped, negated, sc) {
            if let Some(block) = self.block.expand_macro(args, key.loc, &data.parser.pdxfile) {
                let mut our_sc = ScopeContext::new_unrooted(Scopes::all(), &self.key);
                our_sc.set_strict_scopes(false);
                if self.scope_override.is_some() {
                    our_sc.set_no_warn(true);
                }
                // Insert the dummy sc before continuing. That way, if we recurse, we'll hit
                // that dummy context instead of macro-expanding again.
                self.cache.insert(key, args, tooltipped, negated, our_sc.clone());
                validate_trigger_internal(
                    Lowercase::empty(),
                    false,
                    &block,
                    data,
                    &mut our_sc,
                    tooltipped,
                    negated,
                    Severity::Error,
                );
                if let Some(scopes) = self.scope_override {
                    our_sc = ScopeContext::new_unrooted(scopes, key);
                    our_sc.set_strict_scopes(false);
                }
                sc.expect_compatibility(&our_sc, key);
                self.cache.insert(key, args, tooltipped, negated, our_sc);
            }
        }
    }
}

const BUILTIN_OVERRIDE_TRIGGERS: &[&str] = &[
    #[cfg(feature = "ck3")]
    "artifact_low_rarity_trigger",
    #[cfg(feature = "ck3")]
    "artifact_medium_rarity_trigger",
    #[cfg(feature = "ck3")]
    "artifact_high_rarity_trigger",
    #[cfg(feature = "ck3")]
    "artifact_region_trigger",
];

/// There are vanilla triggers that are known to confuse tiger's scope checking.
/// Rather than wait for the user to update their config files, just program them in as defaults,
/// but only if the key is from vanilla. If it's from the mod, they may have implemented the
/// trigger differently.
fn builtin_scope_overrides(key: &Token) -> Option<Scopes> {
    (key.loc.kind.counts_as_vanilla() && BUILTIN_OVERRIDE_TRIGGERS.contains(&key.as_str()))
        .then_some(Scopes::all())
}