Skip to main content

forge_carddb/
parser.rs

1use std::collections::HashMap;
2
3use forge_card_script::{ParsedCardScript, ScriptLineKind};
4use forge_foundation::{CardSplitType, CardTypeLine, ColorSet, ManaCost};
5
6use crate::card_face::CardFace;
7use crate::card_rules::CardRules;
8
9/// Line-by-line parser for Forge card script files.
10/// Direct port of Java `CardRules.Reader.parseLine()`.
11pub struct CardScriptParser {
12    faces: Vec<Option<CardFace>>,
13    cur_face: usize,
14    alt_mode: CardSplitType,
15    meld_with: Option<String>,
16    partner_with: Option<String>,
17    normalized_name: String,
18    tokens: Vec<String>,
19}
20
21impl CardScriptParser {
22    pub fn new() -> Self {
23        CardScriptParser {
24            faces: vec![None, None, None, None, None, None, None],
25            cur_face: 0,
26            alt_mode: CardSplitType::None,
27            meld_with: None,
28            partner_with: None,
29            normalized_name: String::new(),
30            tokens: Vec::new(),
31        }
32    }
33
34    pub fn reset(&mut self) {
35        self.faces = vec![None, None, None, None, None, None, None];
36        self.cur_face = 0;
37        self.alt_mode = CardSplitType::None;
38        self.meld_with = None;
39        self.partner_with = None;
40        self.normalized_name.clear();
41        self.tokens.clear();
42    }
43
44    /// Parse all lines from a card script and produce a CardRules.
45    pub fn parse<'a, I: IntoIterator<Item = &'a str>>(
46        &mut self,
47        lines: I,
48        filename: Option<&str>,
49    ) -> Result<CardRules, String> {
50        self.reset();
51        let raw = lines.into_iter().collect::<Vec<_>>().join("\n");
52        let script = ParsedCardScript::parse(&raw);
53        for line in script.lines() {
54            match &line.kind {
55                ScriptLineKind::Blank | ScriptLineKind::Comment(_) => {}
56                _ => self.parse_line(line.raw),
57            }
58        }
59        if let Some(f) = filename {
60            self.normalized_name = f.to_string();
61        }
62        self.build()
63    }
64
65    /// Parse a single line of a card script.
66    pub fn parse_line(&mut self, line: &str) {
67        // Find the face to apply this line to
68        let face_idx = self.cur_face;
69        self.parse_line_for_face(line, face_idx);
70    }
71
72    fn parse_line_for_face(&mut self, line: &str, face_idx: usize) {
73        let colon_pos = line.find(':');
74        let (key, value) = match colon_pos {
75            Some(pos) if pos > 0 => (&line[..pos], Some(line[pos + 1..].trim())),
76            _ => (line, None),
77        };
78
79        let value_str = value.unwrap_or("");
80
81        if let Some(tok_idx) = value_str.find("TokenScript$").filter(|&idx| idx > 0) {
82            let token_param = value_str[tok_idx + 12..].trim();
83            let token_param = token_param
84                .find('|')
85                .map(|end_idx| token_param[..end_idx].trim())
86                .unwrap_or(token_param);
87            self.tokens
88                .extend(token_param.split(',').map(str::to_string));
89        }
90
91        match key.as_bytes().first() {
92            Some(b'A') => {
93                if key == "A" {
94                    self.ensure_face(face_idx);
95                    if let Some(face) = &mut self.faces[face_idx] {
96                        face.abilities.push(value_str.to_string());
97                    }
98                } else if key == "AlternateMode" {
99                    if let Some(mode) = CardSplitType::from_str_compat(value_str) {
100                        self.alt_mode = mode;
101                    }
102                } else if key == "ALTERNATE" {
103                    self.cur_face = 1;
104                }
105            }
106            Some(b'C') => {
107                if key == "Colors" {
108                    self.ensure_face(face_idx);
109                    if let Some(face) = &mut self.faces[face_idx] {
110                        let mut mask = 0u8;
111                        for part in value_str.split(',') {
112                            let cs = ColorSet::from_names(part.trim());
113                            mask |= cs.mask();
114                        }
115                        face.color = Some(ColorSet::from_mask(mask));
116                    }
117                }
118            }
119            Some(b'D') => {
120                if key == "Defense" {
121                    self.ensure_face(face_idx);
122                    if let Some(face) = &mut self.faces[face_idx] {
123                        face.defense = Some(value_str.to_string());
124                    }
125                } else if key == "Draft" {
126                    self.ensure_face(face_idx);
127                    if let Some(face) = &mut self.faces[face_idx] {
128                        face.draft_actions.push(value_str.to_string());
129                    }
130                }
131                // DeckHints, DeckNeeds, DeckHas — ignored for engine purposes
132            }
133            Some(b'F') => {
134                if key == "FlavorName" {
135                    self.ensure_face(face_idx);
136                    if let Some(face) = &mut self.faces[face_idx] {
137                        face.flavor_name = Some(value_str.to_string());
138                    }
139                }
140            }
141            Some(b'H') => {
142                // HandLifeModifier — vanguard, ignored for now
143            }
144            Some(b'K') => {
145                if key == "K" {
146                    self.ensure_face(face_idx);
147                    if let Some(face) = &mut self.faces[face_idx] {
148                        face.keywords.push(value_str.to_string());
149                    }
150                    // Track Partner with
151                    if value_str.starts_with("Partner with:") {
152                        if let Some(partner) = value_str.strip_prefix("Partner with:") {
153                            self.partner_with = Some(partner.to_string());
154                        }
155                    }
156                }
157            }
158            Some(b'L') => {
159                if key == "Loyalty" {
160                    self.ensure_face(face_idx);
161                    if let Some(face) = &mut self.faces[face_idx] {
162                        face.initial_loyalty = Some(value_str.to_string());
163                    }
164                } else if key == "Lights" {
165                    self.ensure_face(face_idx);
166                    if let Some(face) = &mut self.faces[face_idx] {
167                        face.attraction_lights = value_str
168                            .split_whitespace()
169                            .filter_map(|s| s.parse::<u32>().ok())
170                            .collect();
171                    }
172                }
173            }
174            Some(b'M') => {
175                if key == "ManaCost" {
176                    self.ensure_face(face_idx);
177                    if let Some(face) = &mut self.faces[face_idx] {
178                        face.mana_cost = if value_str == "no cost" {
179                            ManaCost::no_cost()
180                        } else {
181                            ManaCost::parse(value_str)
182                        };
183                    }
184                } else if key == "MeldPair" {
185                    self.meld_with = Some(value_str.to_string());
186                }
187            }
188            Some(b'N') => {
189                if key == "Name" {
190                    self.faces[self.cur_face] = Some(CardFace::new(value_str.to_string()));
191                }
192            }
193            Some(b'O') => {
194                if key == "Oracle" {
195                    self.ensure_face(face_idx);
196                    if let Some(face) = &mut self.faces[face_idx] {
197                        face.oracle_text = value_str.to_string();
198                    }
199                }
200            }
201            Some(b'P') => {
202                if key == "PT" {
203                    self.ensure_face(face_idx);
204                    if let Some(face) = &mut self.faces[face_idx] {
205                        face.set_pt(value_str);
206                    }
207                }
208            }
209            Some(b'R') => {
210                if key == "R" {
211                    self.ensure_face(face_idx);
212                    if let Some(face) = &mut self.faces[face_idx] {
213                        face.replacements.push(value_str.to_string());
214                    }
215                }
216            }
217            Some(b'S') => {
218                if key == "S" {
219                    self.ensure_face(face_idx);
220                    if let Some(face) = &mut self.faces[face_idx] {
221                        face.static_abilities.push(value_str.to_string());
222                    }
223                } else if key.starts_with("SPECIALIZE") {
224                    match value_str {
225                        "WHITE" => self.cur_face = 2,
226                        "BLUE" => self.cur_face = 3,
227                        "BLACK" => self.cur_face = 4,
228                        "RED" => self.cur_face = 5,
229                        "GREEN" => self.cur_face = 6,
230                        _ => {}
231                    }
232                } else if key == "SVar" {
233                    if let Some(val) = value {
234                        let svar_colon = val.find(':');
235                        let (var_name, var_value) = match svar_colon {
236                            Some(pos) => (&val[..pos], &val[pos + 1..]),
237                            None => (val, ""),
238                        };
239                        self.ensure_face(face_idx);
240                        if let Some(face) = &mut self.faces[face_idx] {
241                            face.svars
242                                .insert(var_name.to_string(), var_value.to_string());
243                        }
244                    }
245                } else if key.starts_with("SETCOLORID") {
246                    // Ignored for now
247                }
248            }
249            Some(b'T') => {
250                if key == "T" {
251                    self.ensure_face(face_idx);
252                    if let Some(face) = &mut self.faces[face_idx] {
253                        face.triggers.push(value_str.to_string());
254                    }
255                } else if key == "Types" {
256                    self.ensure_face(face_idx);
257                    if let Some(face) = &mut self.faces[face_idx] {
258                        face.type_line = CardTypeLine::parse(value_str);
259                    }
260                } else if key == "Text" && !value_str.is_empty() {
261                    self.ensure_face(face_idx);
262                    if let Some(face) = &mut self.faces[face_idx] {
263                        face.non_ability_text = Some(value_str.to_string());
264                    }
265                }
266            }
267            Some(b'V') if key == "Variant" => {
268                if let Some(val) = value {
269                    let variant_colon = val.find(':');
270                    if let Some(pos) = variant_colon {
271                        let _variant_name = &val[..pos];
272                        let _variant_line = &val[pos + 1..];
273                    }
274                }
275            }
276            _ => {
277                // AI:, other keys — ignored for engine
278            }
279        }
280    }
281
282    fn ensure_face(&mut self, idx: usize) {
283        if self.faces[idx].is_none() {
284            // This shouldn't happen in well-formed scripts (Name comes first),
285            // but handle gracefully
286            self.faces[idx] = Some(CardFace::new(format!("__unnamed_face_{idx}")));
287        }
288    }
289
290    /// Build the final CardRules from parsed data.
291    pub fn build(&mut self) -> Result<CardRules, String> {
292        let main = self.faces[0]
293            .take()
294            .ok_or_else(|| "Card has no main face (missing Name: line)".to_string())?;
295
296        let other = self.faces[1].take();
297
298        // Specialize faces
299        let mut specialized = HashMap::new();
300        let specialize_names = ["W", "U", "B", "R", "G"];
301        for (i, name) in specialize_names.iter().enumerate() {
302            if let Some(face) = self.faces[i + 2].take() {
303                specialized.insert(format!("Specialize{name}"), face);
304            }
305        }
306
307        let mut main = main;
308        main.assign_missing_fields();
309
310        let other = other.map(|mut f| {
311            f.assign_missing_fields();
312            f
313        });
314
315        for face in specialized.values_mut() {
316            face.assign_missing_fields();
317        }
318
319        // Calculate color identity
320        let mut ci_mask = CardRules::calculate_color_identity(&main);
321        if let Some(ref other_face) = other {
322            ci_mask |= CardRules::calculate_color_identity(other_face);
323        }
324
325        Ok(CardRules {
326            split_type: self.alt_mode,
327            main_part: main,
328            other_part: other,
329            specialized_parts: specialized,
330            color_identity: ColorSet::from_mask(ci_mask),
331            normalized_name: std::mem::take(&mut self.normalized_name),
332            meld_with: self.meld_with.take(),
333            partner_with: self.partner_with.take(),
334            tokens: std::mem::take(&mut self.tokens),
335        })
336    }
337}
338
339impl Default for CardScriptParser {
340    fn default() -> Self {
341        Self::new()
342    }
343}
344
345/// Convenience: parse a card from a single string (lines separated by newlines).
346pub fn parse_card_script(script: &str) -> Result<CardRules, String> {
347    let mut parser = CardScriptParser::new();
348    let lines: Vec<&str> = script.lines().collect();
349    parser.parse(lines, None)
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355
356    #[test]
357    fn parse_lightning_bolt() {
358        let script = "\
359Name:Lightning Bolt
360ManaCost:R
361Types:Instant
362A:SP$ DealDamage | ValidTgts$ Any | NumDmg$ 3 | SpellDescription$ CARDNAME deals 3 damage to any target.
363Oracle:Lightning Bolt deals 3 damage to any target.";
364
365        let card = parse_card_script(script).unwrap();
366        assert_eq!(card.main_part.name, "Lightning Bolt");
367        assert_eq!(card.main_part.mana_cost.cmc(), 1);
368        assert!(card.main_part.type_line.is_instant());
369        assert_eq!(card.main_part.abilities.len(), 1);
370        assert!(card.main_part.abilities[0].contains("DealDamage"));
371        assert!(card.main_part.resolved_color().has_red());
372    }
373
374    #[test]
375    fn parse_grizzly_bears() {
376        let script = "\
377Name:Grizzly Bears
378ManaCost:1 G
379Types:Creature Bear
380PT:2/2
381Oracle:";
382
383        let card = parse_card_script(script).unwrap();
384        assert_eq!(card.main_part.name, "Grizzly Bears");
385        assert_eq!(card.main_part.mana_cost.cmc(), 2);
386        assert!(card.main_part.type_line.is_creature());
387        assert_eq!(card.main_part.int_power, Some(2));
388        assert_eq!(card.main_part.int_toughness, Some(2));
389    }
390
391    #[test]
392    fn parse_transform_card() {
393        let script = "\
394Name:Lambholt Pacifist
395ManaCost:1 G
396Types:Creature Human Shaman Werewolf
397PT:3/3
398S:Mode$ CantAttack | ValidCard$ Card.Self
399T:Mode$ Phase | Phase$ Upkeep | Execute$ TrigTransform
400SVar:TrigTransform:DB$ SetState | Defined$ Self | Mode$ Transform
401AlternateMode:DoubleFaced
402Oracle:Test oracle text.
403
404ALTERNATE
405
406Name:Lambholt Butcher
407ManaCost:no cost
408Colors:green
409Types:Creature Werewolf
410PT:4/4
411Oracle:Back face oracle.";
412
413        let card = parse_card_script(script).unwrap();
414        assert_eq!(card.main_part.name, "Lambholt Pacifist");
415        assert_eq!(card.split_type, CardSplitType::Transform);
416        assert!(card.other_part.is_some());
417        let back = card.other_part.as_ref().unwrap();
418        assert_eq!(back.name, "Lambholt Butcher");
419        assert_eq!(back.int_power, Some(4));
420        assert!(back.resolved_color().has_green());
421    }
422
423    #[test]
424    fn parse_keywords_and_svars() {
425        let script = "\
426Name:Laelia, the Blade Reforged
427ManaCost:2 R
428Types:Legendary Creature Spirit Warrior
429PT:2/2
430K:Haste
431T:Mode$ Attacks | ValidCard$ Card.Self | Execute$ TrigExile
432SVar:TrigExile:DB$ Dig | Defined$ You
433Oracle:Haste";
434
435        let card = parse_card_script(script).unwrap();
436        assert_eq!(card.main_part.keywords, vec!["Haste"]);
437        assert_eq!(card.main_part.triggers.len(), 1);
438        assert!(card.main_part.svars.contains_key("TrigExile"));
439        assert!(card.main_part.type_line.is_legendary());
440    }
441}