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') => {
268                if key == "Variant" {
269                    // Functional variants (Attractions, Un-cards) — store raw for now
270                    // We parse the variant line recursively like Java does
271                    if let Some(val) = value {
272                        let variant_colon = val.find(':');
273                        if let Some(pos) = variant_colon {
274                            let _variant_name = &val[..pos];
275                            let _variant_line = &val[pos + 1..];
276                            // For now, we skip functional variants — they're rare
277                            // and can be added later without architecture changes
278                        }
279                    }
280                }
281            }
282            _ => {
283                // AI:, other keys — ignored for engine
284            }
285        }
286    }
287
288    fn ensure_face(&mut self, idx: usize) {
289        if self.faces[idx].is_none() {
290            // This shouldn't happen in well-formed scripts (Name comes first),
291            // but handle gracefully
292            self.faces[idx] = Some(CardFace::new(format!("__unnamed_face_{idx}")));
293        }
294    }
295
296    /// Build the final CardRules from parsed data.
297    pub fn build(&mut self) -> Result<CardRules, String> {
298        let main = self.faces[0]
299            .take()
300            .ok_or_else(|| "Card has no main face (missing Name: line)".to_string())?;
301
302        let other = self.faces[1].take();
303
304        // Specialize faces
305        let mut specialized = HashMap::new();
306        let specialize_names = ["W", "U", "B", "R", "G"];
307        for (i, name) in specialize_names.iter().enumerate() {
308            if let Some(face) = self.faces[i + 2].take() {
309                specialized.insert(format!("Specialize{name}"), face);
310            }
311        }
312
313        let mut main = main;
314        main.assign_missing_fields();
315
316        let other = other.map(|mut f| {
317            f.assign_missing_fields();
318            f
319        });
320
321        for face in specialized.values_mut() {
322            face.assign_missing_fields();
323        }
324
325        // Calculate color identity
326        let mut ci_mask = CardRules::calculate_color_identity(&main);
327        if let Some(ref other_face) = other {
328            ci_mask |= CardRules::calculate_color_identity(other_face);
329        }
330
331        Ok(CardRules {
332            split_type: self.alt_mode,
333            main_part: main,
334            other_part: other,
335            specialized_parts: specialized,
336            color_identity: ColorSet::from_mask(ci_mask),
337            normalized_name: std::mem::take(&mut self.normalized_name),
338            meld_with: self.meld_with.take(),
339            partner_with: self.partner_with.take(),
340            tokens: std::mem::take(&mut self.tokens),
341        })
342    }
343}
344
345impl Default for CardScriptParser {
346    fn default() -> Self {
347        Self::new()
348    }
349}
350
351/// Convenience: parse a card from a single string (lines separated by newlines).
352pub fn parse_card_script(script: &str) -> Result<CardRules, String> {
353    let mut parser = CardScriptParser::new();
354    let lines: Vec<&str> = script.lines().collect();
355    parser.parse(lines, None)
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361
362    #[test]
363    fn parse_lightning_bolt() {
364        let script = "\
365Name:Lightning Bolt
366ManaCost:R
367Types:Instant
368A:SP$ DealDamage | ValidTgts$ Any | NumDmg$ 3 | SpellDescription$ CARDNAME deals 3 damage to any target.
369Oracle:Lightning Bolt deals 3 damage to any target.";
370
371        let card = parse_card_script(script).unwrap();
372        assert_eq!(card.main_part.name, "Lightning Bolt");
373        assert_eq!(card.main_part.mana_cost.cmc(), 1);
374        assert!(card.main_part.type_line.is_instant());
375        assert_eq!(card.main_part.abilities.len(), 1);
376        assert!(card.main_part.abilities[0].contains("DealDamage"));
377        assert!(card.main_part.resolved_color().has_red());
378    }
379
380    #[test]
381    fn parse_grizzly_bears() {
382        let script = "\
383Name:Grizzly Bears
384ManaCost:1 G
385Types:Creature Bear
386PT:2/2
387Oracle:";
388
389        let card = parse_card_script(script).unwrap();
390        assert_eq!(card.main_part.name, "Grizzly Bears");
391        assert_eq!(card.main_part.mana_cost.cmc(), 2);
392        assert!(card.main_part.type_line.is_creature());
393        assert_eq!(card.main_part.int_power, Some(2));
394        assert_eq!(card.main_part.int_toughness, Some(2));
395    }
396
397    #[test]
398    fn parse_transform_card() {
399        let script = "\
400Name:Lambholt Pacifist
401ManaCost:1 G
402Types:Creature Human Shaman Werewolf
403PT:3/3
404S:Mode$ CantAttack | ValidCard$ Card.Self
405T:Mode$ Phase | Phase$ Upkeep | Execute$ TrigTransform
406SVar:TrigTransform:DB$ SetState | Defined$ Self | Mode$ Transform
407AlternateMode:DoubleFaced
408Oracle:Test oracle text.
409
410ALTERNATE
411
412Name:Lambholt Butcher
413ManaCost:no cost
414Colors:green
415Types:Creature Werewolf
416PT:4/4
417Oracle:Back face oracle.";
418
419        let card = parse_card_script(script).unwrap();
420        assert_eq!(card.main_part.name, "Lambholt Pacifist");
421        assert_eq!(card.split_type, CardSplitType::Transform);
422        assert!(card.other_part.is_some());
423        let back = card.other_part.as_ref().unwrap();
424        assert_eq!(back.name, "Lambholt Butcher");
425        assert_eq!(back.int_power, Some(4));
426        assert!(back.resolved_color().has_green());
427    }
428
429    #[test]
430    fn parse_keywords_and_svars() {
431        let script = "\
432Name:Laelia, the Blade Reforged
433ManaCost:2 R
434Types:Legendary Creature Spirit Warrior
435PT:2/2
436K:Haste
437T:Mode$ Attacks | ValidCard$ Card.Self | Execute$ TrigExile
438SVar:TrigExile:DB$ Dig | Defined$ You
439Oracle:Haste";
440
441        let card = parse_card_script(script).unwrap();
442        assert_eq!(card.main_part.keywords, vec!["Haste"]);
443        assert_eq!(card.main_part.triggers.len(), 1);
444        assert!(card.main_part.svars.contains_key("TrigExile"));
445        assert!(card.main_part.type_line.is_legendary());
446    }
447}