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